Discord.py 从后台线程关闭机器人
Discord.py close Bot from background thread
我对此并没有很好的理由,但坚持我的头脑,我现在真的很想这样做。我的 discord 服务器有一个 discord bot,主要在晚上使用。所以我想制作一个线程,在其“非活动”时间关闭机器人。但是,我真的很难做到。我目前拥有的:
async def wait():
print('In thread')
time.sleep(5)
await bot.close()
print('Bot should now be stopped')
def threat():
asyncio.run(wait())
p1 = Process(target=threat)
p1.start()
bot.run(TOKEN)
这不是全部代码,但这些是重要的内容。一般来说,我真的不明白 asyncio 有什么大惊小怪的,因为无论哪种方式,你都必须等待一个协程完成才能进入下一个协程,而它一直在阻止你的执行。这不是吗那么简单的线性执行呢?
无论如何,我们将不胜感激! :)
你可以尝试做task
...
from discord.ext import tasks
...
@task.loop(seconds=3600) # this will execute the func. every 1 hour
async def Do_Something():
# your code
...
更多内容可以阅读官方文档。
https://discordpy.readthedocs.io/en/latest/ext/tasks/index.html
您基本上可以使用时间模块并制作一个函数,例如每 30 分钟检查一次小时,或者在执行命令时(如果您的机器人有命令)。
然后,如果返回的时间在您的“非活动”时间戳中,只需关闭机器人即可。
我对此并没有很好的理由,但坚持我的头脑,我现在真的很想这样做。我的 discord 服务器有一个 discord bot,主要在晚上使用。所以我想制作一个线程,在其“非活动”时间关闭机器人。但是,我真的很难做到。我目前拥有的:
async def wait():
print('In thread')
time.sleep(5)
await bot.close()
print('Bot should now be stopped')
def threat():
asyncio.run(wait())
p1 = Process(target=threat)
p1.start()
bot.run(TOKEN)
这不是全部代码,但这些是重要的内容。一般来说,我真的不明白 asyncio 有什么大惊小怪的,因为无论哪种方式,你都必须等待一个协程完成才能进入下一个协程,而它一直在阻止你的执行。这不是吗那么简单的线性执行呢?
无论如何,我们将不胜感激! :)
你可以尝试做task
...
from discord.ext import tasks
...
@task.loop(seconds=3600) # this will execute the func. every 1 hour
async def Do_Something():
# your code
...
更多内容可以阅读官方文档。 https://discordpy.readthedocs.io/en/latest/ext/tasks/index.html
您基本上可以使用时间模块并制作一个函数,例如每 30 分钟检查一次小时,或者在执行命令时(如果您的机器人有命令)。 然后,如果返回的时间在您的“非活动”时间戳中,只需关闭机器人即可。