Python 3.x Discord.py重写,设置后台任务,未加载后台任务

Python 3.x Discord.py重写,设置后台任务,未加载后台任务,python-3.x,background-task,discord.py-rewrite,Python 3.x,Background Task,Discord.py Rewrite,我似乎不知道如何在运行时激活我的后台任务。如果我让代码在事件后运行,它应该会更改角色的颜色,而这是成功的。但是,将其设置为在后台工作一直是失败的。也没有错误,我猜任务从未加载 登录和bot初始值设定项 @客户端事件 _就绪时的异步定义: 打印“登录为” printfUsername:{client.user.name} printfUser ID:{client.user.ID} 打印'--------------' 运行时后台任务 异步def运行时\u后台\u任务: id=client.get

我似乎不知道如何在运行时激活我的后台任务。如果我让代码在事件后运行,它应该会更改角色的颜色,而这是成功的。但是,将其设置为在后台工作一直是失败的。也没有错误,我猜任务从未加载

登录和bot初始值设定项 @客户端事件 _就绪时的异步定义: 打印“登录为” printfUsername:{client.user.name} printfUser ID:{client.user.ID} 打印'--------------' 运行时后台任务 异步def运行时\u后台\u任务: id=client.get_guild564683412699480094 颜色=[discord.color0xE91E63,discord.color0x0000FF0,discord.color0x00FF00,discord.color0xFF0000] 打印后台任务>>功能 等待客户。等待,直到准备就绪 而不是client.u关闭时: i=random.randint0,Lencolors 等待asyncio.sleep1 普林蒂 对于id.roles中的角色: 如果role.name==“bot”: 等待角色。editserver=id,角色=role,颜色=colors[i] 打破 您可以使用扩展来简化这一过程。在这里,我们有一个每秒运行一次的任务来更改角色的颜色

我没有看到您在哪里定义了id,因此我使用before\u循环从id初始化服务器:

import discord
from discord.utils import get
from discord.ext.tasks import loop
from discord.ext.commands import Bot
from random import choice

bot = Bot("!")

colours = [discord.Colour(0xe91e63), discord.Colour(0x0000FF0), discord.Colour(0x00FF00), discord.Colour(0xFF0000)]

guild_id = 12345
role_name = "bot"
role_to_change = None

@loop(seconds=1)
async def colour_change():
    await role_to_change.edit(colour=choice(colours))
    print("Task")

@colour_change.before_loop
async def colour_change_before():
    global role_to_change
    await bot.wait_until_ready()
    guild = bot.get_guild(guild_id)
    role_to_change = get(guild.roles, name=role_name)

colour_change.start()
bot.run("token")
您可以使用扩展来简化这一过程。在这里,我们有一个每秒运行一次的任务来更改角色的颜色

我没有看到您在哪里定义了id,因此我使用before\u循环从id初始化服务器:

import discord
from discord.utils import get
from discord.ext.tasks import loop
from discord.ext.commands import Bot
from random import choice

bot = Bot("!")

colours = [discord.Colour(0xe91e63), discord.Colour(0x0000FF0), discord.Colour(0x00FF00), discord.Colour(0xFF0000)]

guild_id = 12345
role_name = "bot"
role_to_change = None

@loop(seconds=1)
async def colour_change():
    await role_to_change.edit(colour=choice(colours))
    print("Task")

@colour_change.before_loop
async def colour_change_before():
    global role_to_change
    await bot.wait_until_ready()
    guild = bot.get_guild(guild_id)
    role_to_change = get(guild.roles, name=role_name)

colour_change.start()
bot.run("token")

ModuleNotFoundError:没有名为'discord.ext.tasks'的模块。我还将ID添加到代码中,以便更容易理解;您可能需要更新discord.py版本:pip install-U discord.py更新修复了这个问题,但代码似乎也无法完成此任务。没有错误,但实际上也没有做任何事情。@KA我丢失了颜色_change.start line我这样添加了代码,但直到无法工作ModuleNotFoundError:没有名为“discord.ext.tasks”的模块。我还将ID添加到代码中,以便更容易理解;您可能需要更新discord.py版本:pip install-U discord.py更新修复了这个问题,但代码似乎也无法完成此任务。没有错误,但实际上也没有做任何事情。@KA我丢失了颜色更改。开始行我这样添加了代码,但直到不起作用为止颜色更改机器人被禁止,以避免淹没API,以防你不知道。颜色更改机器人被禁止,以避免淹没API,以防你不知道。