让不和谐的机器人每 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'))

错误消息如下:

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

原文由 luigiisgreeny 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 749
2 个回答

不幸的是,线程和异步不能很好地结合在一起。您需要跳过额外的环节才能等待线程内的协程。最简单的解决方案就是不使用线程。

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

 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())

您不能使用 time.sleep(),因为这会阻止机器人的执行。 asyncio.sleep() 虽然是一个像其他一切一样的协程,因此是非阻塞的。

最后, @client.event 装饰器应该只用在机器人识别为 事件 的函数上。比如on_ready和on_message。

原文由 Sam Rockett 发布,翻译遵循 CC BY-SA 3.0 许可协议

discord.py 版本 1.1.0 引入了 discord.ext.tasks ,它旨在使您描述的后台任务更容易,并在出现连接问题时处理重新连接到 discord 的潜在复杂逻辑。

这是使用 tasks 的任务示例:

 from discord.ext import commands, tasks
from commands import Bot
from tasks import loop
from asyncio import sleep

bot = Bot("!")

@loop(seconds=10)
async def name_change():
    await bot.change_presence(...)
    await sleep(10)
    await bot.change_presence(...)

name_change.before_loop(bot.wait_until_ready())
name_change.start()
bot.run("TOKEN")

原文由 Patrick Haugh 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题