您好,我希望我的机器人在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())
答案 0 :(得分:1)
此解决方案已经过测试:
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,因为它非常有用。