Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
582 views
in Technique[技术] by (71.8m points)

python - Making a discord bot change playing status every 10 seconds

I'm trying to make the status for a test discord bot change between two messages every ten seconds. I need the rest of the script to execute while the status message changes, but an error keeps popping up whenever I try to make it work. There's threading in my script, but I'm not entirely sure how to use it in this circumstance.

@test_bot.event
async def on_ready():
    print('Logged in as')
    print(test_bot.user.name)
    print(test_bot.user.id)
    print('------')
    await change_playing()


@test_bot.event
async def change_playing():
    threading.Timer(10, change_playing).start()
    await test_bot.change_presence(game=discord.Game(name='Currently on ' + str(len(test_bot.servers)) +
                                                          ' servers'))
    threading.Timer(10, change_playing).start()
    await test_bot.change_presence(game=discord.Game(name='Say test.help'))

The error message reads:

C:PythonPython36-32libhreading.py:1182: RuntimeWarning: coroutine 'change_playing' was never awaited
  self.function(*self.args, **self.kwargs)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Threading and asyncio don't play nice together unfortunately. You need to jump through extra hoops to await coroutines inside threads. The simplest solution is to just not use threading.

What you are trying to do is wait a duration and then run a coroutine. This can be done with a background task (example)

async def status_task():
    while True:
        await test_bot.change_presence(...)
        await asyncio.sleep(10)
        await test_bot.change_presence(...)
        await asyncio.sleep(10)

@test_bot.event
async def on_ready():
    ...
    bot.loop.create_task(status_task())

You cannot use time.sleep() as this will block the execution of the bot. asyncio.sleep() though is a coroutine like everything else and as such is non-blocking.

Lastly, the @client.event decorator should only be used on functions the bot recognises as events. Such as on_ready and on_message.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...