首页 > 解决方案 > python discord.py 后台任务停止主函数

问题描述

使用:discord.py 我试图运行后台任务。但是在它启动后,像 on_message 这样的主函数停止工作。

代码

async def on_ready():
        print('x')
        x = "true"
        client.loop.create_task(my_background_task(x))
async def my_background_task(x):
        while True:
                #do stuff
                await asyncio.sleep(3)

标签: pythondiscord.pypython-asyncio

解决方案


import discord 
client = discord.Client()

@client.event
async def on_ready():
   #your on_ready code here

@client.event
async def on_message(message):
   #your on_message code here

async def my_background_task(x):
    await client.wait_until_ready()
    while not client.is_closed():
        #do stuff
        await asyncio.sleep(3)

client.loop.create_task(my_background_task(True))
client.run('token')

推荐阅读