Python Discord.py—使用后台任务在状态间循环重写 我的目标
您好,我想让我的机器人通过3个前缀循环,机器人的前缀,服务器的数量,以及我选择的另一条消息。我使用的是Python Discord.py—使用后台任务在状态间循环重写 我的目标,python,python-3.x,discord,discord.py,discord.py-rewrite,Python,Python 3.x,Discord,Discord.py,Discord.py Rewrite,您好,我想让我的机器人通过3个前缀循环,机器人的前缀,服务器的数量,以及我选择的另一条消息。我使用的是@bot.command/@bot这个东西,所以readthedocs网站常见问题解答中的示例对我没有帮助。我尝试的方法不起作用,我也不知道如何获取bot所在的服务器数量 我试过的 该解决方案已经过测试: prefixes = [lambda: 'prefix1', lambda: 'prefix2', lambda: str(len(bot.guilds))] bot = commands.
@bot.command
/@bot
这个东西,所以readthedocs网站常见问题解答中的示例对我没有帮助。我尝试的方法不起作用,我也不知道如何获取bot所在的服务器数量
我试过的
该解决方案已经过测试:
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函数,因为它允许将bot添加到其他服务器,并在发生这种情况时调整前缀。当需要更改前缀时,将调用其中一个函数,返回一个字符串
我还建议您查看,因为它非常有用
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())