后台任务在 discord.py 中不起作用



我正在Linux Mint上使用 Discord.py,我想使用后台任务,但我似乎无法使它们工作。由于某种原因,while循环(见下文(显然从未进入过。

我尝试了许多非常基本的后台任务示例,但没有任何工作,除此之外,discord.py 工作得很好,我可以做很多完全可以正常工作的事情。甚至 while 循环中的打印语句也没有显示,这很奇怪。

import discord
import asyncio
TOKEN = '<my-token>'
client = discord.Client()
async def my_background_task():
    await client.wait_until_ready()
    print("I am showing up!")
    while not client.is_closed:
        print("I am not showing up!")
        servers = client.get_all_servers()
        for server in servers:
            for channel in server.channels:
                await client.send_message(channel, "Some message")
        await asyncio.sleep(1) # task runs every second
@client.event
async def on_ready():
    print('Logged in as')
    print(client.user.name)
    print(client.user.id)
    print('------')
client.loop.create_task(my_background_task())
client.run(TOKEN)

所以机器人可以正确启动,如果我有一个on_message方法,它会起作用(我没有添加它,因为它无关紧要(。但是由于某种原因,后台任务从未完成。甚至没有显示任何错误消息。好像后台任务被忽略了。我在谷歌上搜索过,但似乎没有人遇到过这个问题。

编辑:已解决。client.is_closed后缺少一对括号,尽管我找到的所有在线示例都没有使用任何括号。

"@tasks.loop(seconds = 1("表示循环每X秒重复一次。
您可以使用"@tasks.loop(("来定义循环,并使用"(秒= 1("来定义循环重复的秒数。
要启动循环,您需要添加"my_background_task.start((",这意味着后台任务是已启动的。

您可以将 my_background_task.start(( 添加为命令:

@bot.command()
async def mybgtask(ctx):
    my_background_task.start()
    await ctx.send("my_background_task loop has started")

这是代码:

import discord
import asyncio
from discord.ext import tasks
TOKEN = '<my-token>'
client = discord.Client()

@tasks.loop(seconds = 1) #The loop repeats every 1 seconds
async def my_background_task():
    await client.wait_until_ready()
    print("I am showing up!")
    if not client.is_closed:
        print("I am not showing up!")
        servers = client.get_all_servers()
        for server in servers:
            for channel in server.channels:
                await client.send_message(channel, "Some message")
@client.event
async def on_ready():
    print('Logged in as')
    print(client.user.name)
    print(client.user.id)
    print('------')
my_background_task.start()
client.run(TOKEN)

最新更新