使不和谐的机器人每10秒更改播放状态 [英] Making a discord bot change playing status every 10 seconds

查看:54
本文介绍了使不和谐的机器人每10秒更改播放状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使测试不一致机器人的状态每10秒在两条消息之间切换一次。当状态消息更改时,我需要执行脚本的其余部分,但是每当我尝试使其正常工作时,都会弹出错误。我的脚本中有线程,但是我不确定在这种情况下如何使用它。

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

错误消息为:

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


推荐答案

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

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

您不能使用time.sleep(),因为这会阻止机器人的执行。

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.

最后, @ client.event code>装饰器仅应在机器人识别为事件的函数上使用。例如on_ready和on_message。

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

这篇关于使不和谐的机器人每10秒更改播放状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆