制作不和谐机器人每10秒更改播放状态

lui*_*eny 7 python python-3.x python-3.6 discord.py

我试图让每10秒钟两次消息之间的测试不和谐机器人的状态发生变化.我需要在状态消息更改时执行脚本的其余部分,但每当我尝试使其工作时,错误就会一直弹出.我的脚本中有线程,但我不完全确定在这种情况下如何使用它.

@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'))
Run Code Online (Sandbox Code Playgroud)

错误消息显示:

C:\Python\Python36-32\lib\threading.py:1182: RuntimeWarning: coroutine 'change_playing' was never awaited
  self.function(*self.args, **self.kwargs)
Run Code Online (Sandbox Code Playgroud)

Sam*_*ett 8

不幸的是,线程和asyncio并不能很好地结合在一起.你需要跳过额外的箍来等待线程内的协同程序.最简单的解决方案是不使用线程.

你要做的是等待一段时间,然后运行一个协程.这可以通过后台任务完成(示例)

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())
Run Code Online (Sandbox Code Playgroud)

你不能使用time.sleep(),因为这会阻止僵尸程序的执行.asyncio.sleep()虽然是一个像其他所有的协程,因此是非阻塞的.

最后,@client.event装饰器应仅用于机器人识别为事件的功能.例如on_ready和on_message.