在discord.py库中,当您在主函数(on_message)中执行后台任务时,可能会发现您的命令不再响应。这是因为discord.py运行在一个事件循环中,如果您阻塞了此循环,则无法响应其他事件。
解决此问题有两种方法:
import asyncio
def my_background_task():
await asyncio.sleep(5)
print('Background task completed')
@client.event
async def on_message(message):
if message.content == "!start_task":
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
loop.create_task(my_background_task())
await message.channel.send('Background task started')
在此示例中,当用户发送“!start_task”消息时,将创建一个新的事件循环并启动后台任务。这不会影响discord.py的主事件循环,因此您的命令可以继续响应。
from discord.ext import tasks
@tasks.loop(seconds=5)
async def my_background_task():
print('Background task completed')
@client.event
async def on_message(message):
if message.content == "!start_task":
my_background_task.start()
await message.channel.send('Background task started')
在此示例中,我们使用了discord.py提供的后台任务装饰器来运行后台任务。当用户发送“!start_task”消息时,将启动任务并在后台每5秒执行一次。此方法也不会阻塞discord.py的主事件循环。
无论您选择哪种方法,都需要记住确保您的后台任务不会阻塞主事件循环。通过使用asyncio.sleep()或在后台任务中使用异步代码,可以确保此目标的实现。
上一篇:BackgroundTask Framework 有哪些限制吗?
下一篇:BackgroundThreadmessagestoUIThreadcacheandnotpushedtoUItillbackgroundprocesscomplete”改写为中文。