我似乎无法弄清楚如何激活后台任务运行时。如果我让代码在事件后运行,则应该更改角色的颜色,该角色将成功完成。但是将其设置为在后台工作仍然会失败。也没有错误,我猜是任务永远不会加载。
#Login and bot initializer
@client.event
async def on_ready():
print('Logged in as')
print(f"Username: {client.user.name}")
print(f"User ID: {client.user.id}")
print('---------------------------------')
#Runtime Background Tasks
async def runtime_background_task():
id=client.get_guild(564683412699480094)
colours = [discord.Colour(0xe91e63),discord.Colour(0x0000FF0),discord.Colour(0x00FF00),discord.Colour(0xFF0000)]
print("BACKGROUND TASK>> Functional")
await client.wait_until_ready()
while not client.is_closed:
i = random.randint(0, len(colours))
await asyncio.sleep(1)
print(i)
for role in id.roles:
if role.name == 'bot':
await role.edit(server=id, role=role, colour=colours[i])
break
答案 0 :(得分:0)
您可以使用discord.ext.tasks
扩展名来简化此操作。在这里,我们有一个任务,它每秒运行一次以更改角色的颜色。
我没有看到您在id
处定义的位置,因此我正在使用before_loop
从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")