【问题标题】:Background Tasks not working in discord.py后台任务在 discord.py 中不起作用
【发布时间】:2021-06-07 02:42:11
【问题描述】:

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

我尝试了许多非常基本的后台任务示例,但没有任何效果,除了 discord.py 工作得很好,我可以做很多可以很好地工作的事情。 甚至 while 循环中的 print 语句也没有显示出来,这很奇怪。

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 后面少了一对括号,虽然我找到的所有在线示例都没有使用。

【问题讨论】:

  • 您使用的是哪个版本的discord.py?您的代码在过去的版本中有一些不推荐使用的方法,但如果您的版本不匹配,我希望您会看到错误。
  • 我的discord.py 版本是1.2.3,我的python 版本是3.6.7。哪些方法已弃用?因为我没有一个警告。
  • send_message 等方法来自 1.0 版本之前。请参阅迁移指南:discordpy.readthedocs.io/en/latest/migrating.html

标签: python discord discord.py


【解决方案1】:

"@tasks.loop(seconds = 1)" 表示循环每 X 秒重复一次。
您可以使用“@tasks.loop()”定义循环,使用“(seconds = 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)

【讨论】:

  • 真的很抱歉,我修好了 =)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-03-29
  • 1970-01-01
  • 2019-08-24
  • 2021-03-19
  • 2015-10-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多