首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使不一致机器人每10秒改变一次播放状态

使不一致机器人每10秒改变一次播放状态
EN

Stack Overflow用户
提问于 2017-09-18 02:51:03
回答 3查看 35.7K关注 0票数 9

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

代码语言:javascript
复制
@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'))

错误消息为:

代码语言:javascript
复制
C:\Python\Python36-32\lib\threading.py:1182: RuntimeWarning: coroutine 'change_playing' was never awaited
  self.function(*self.args, **self.kwargs)
EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2017-09-18 03:19:47

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

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

代码语言:javascript
复制
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()和其他所有东西一样都是一个协程,因此是非阻塞的。

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

票数 17
EN

Stack Overflow用户

发布于 2019-04-30 08:58:57

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

以下是使用tasks执行任务的示例

代码语言:javascript
复制
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")
票数 3
EN

Stack Overflow用户

发布于 2017-09-18 03:15:46

请看以下内容:

https://github.com/Rapptz/discord.py/blob/master/examples/background_task.py

导入不一致导入asyncio client = discord.Client() async def my_background_task():await client.wait_until_ready() counter =0 channel =discord.Object(id=‘client.is_closed_id_here’) while not channel:计数器+= 1等待client.send_message(channel,计数器)等待asyncio.sleep( 60 ) #任务每隔60秒运行一次@client.event异步定义on_ready():打印(‘登录身份’)打印(client.user.name)打印(client.user.id)打印(‘-’) client.loop.create_task(my_background_task()) client.run('token')

Discord.py有一个内置的后台任务功能,

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/46267705

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档