Discord.py-使用后台任务重写状态循环
Discord.py-Rewrite Cycle through statuses using background tasks
我的目标
你好,我想让我的机器人循环显示 3 个前缀,机器人的前缀,它所在的服务器数量,以及我选择的另一条消息。我使用 @bot.command
/@bot
东西,所以 readthedocs 网站常见问题解答中的示例对我没有帮助。我试过没有用,我也不知道如何获取机器人所在的服务器数量。
我试过的
async def my_background_task(self):
await bot.change_presence(activity=discord.Game(name="message"))
await asyncio.sleep(7)
await bot.change_presence(activity=discord.Game(name="PREFIX: CF>"))
await asyncio.sleep(7)
@bot.event
async def on_ready(self):
print('Bot is online and ready.')
self.bg_task = self.loop.create_task(self.my_background_task())
此解决方案已经过测试:
prefixes = [lambda: 'prefix1', lambda: 'prefix2', lambda: str(len(bot.guilds))]
bot = commands.Bot(command_prefix=prefixes[0]())
async def my_background_task():
prefix_num = 0
while True:
prefix = prefixes[prefix_num]()
await bot.change_presence(activity=discord.Game(name=prefix))
bot.command_prefix = prefix
# increase the current prefix - if it's reached the length of the prefix list, set it back to 0
prefix_num = (prefix_num + 1) % len(prefixes)
await asyncio.sleep(7)
@bot.event
async def on_ready():
bot.loop.create_task(my_background_task())
首先,您的后台任务和 on_ready 函数中不应包含任何 self
。此外,您的后台任务必须在其中有一个 while 循环,否则,它只会 运行 一次。
此代码使用匿名 lambda 函数,因为它允许将机器人添加到不同的服务器并在发生这种情况时调整前缀。当需要更改前缀时,将调用其中一个函数,返回一个字符串。
我还建议您查看 API reference,因为它非常有用。
我的目标
你好,我想让我的机器人循环显示 3 个前缀,机器人的前缀,它所在的服务器数量,以及我选择的另一条消息。我使用 @bot.command
/@bot
东西,所以 readthedocs 网站常见问题解答中的示例对我没有帮助。我试过没有用,我也不知道如何获取机器人所在的服务器数量。
我试过的
async def my_background_task(self):
await bot.change_presence(activity=discord.Game(name="message"))
await asyncio.sleep(7)
await bot.change_presence(activity=discord.Game(name="PREFIX: CF>"))
await asyncio.sleep(7)
@bot.event
async def on_ready(self):
print('Bot is online and ready.')
self.bg_task = self.loop.create_task(self.my_background_task())
此解决方案已经过测试:
prefixes = [lambda: 'prefix1', lambda: 'prefix2', lambda: str(len(bot.guilds))]
bot = commands.Bot(command_prefix=prefixes[0]())
async def my_background_task():
prefix_num = 0
while True:
prefix = prefixes[prefix_num]()
await bot.change_presence(activity=discord.Game(name=prefix))
bot.command_prefix = prefix
# increase the current prefix - if it's reached the length of the prefix list, set it back to 0
prefix_num = (prefix_num + 1) % len(prefixes)
await asyncio.sleep(7)
@bot.event
async def on_ready():
bot.loop.create_task(my_background_task())
首先,您的后台任务和 on_ready 函数中不应包含任何 self
。此外,您的后台任务必须在其中有一个 while 循环,否则,它只会 运行 一次。
此代码使用匿名 lambda 函数,因为它允许将机器人添加到不同的服务器并在发生这种情况时调整前缀。当需要更改前缀时,将调用其中一个函数,返回一个字符串。
我还建议您查看 API reference,因为它非常有用。