如何设置bot作为状态的服务器数量(discord.py重写)?



我尝试使用这段代码:

status = cycle(['.apuva', f'{str(len(client.guilds))} palvelimella!']
@client.event
async def on_ready():
change_status.start()
print('Botti on käynnissä.')
async def change_status():
await client.change_presence(activity=discord.Game(next(status)))

然而,这显示状态为"0台服务器",即使我的机器人在3台服务器上。如何在重写版本的discord.py中修复此问题?

之所以说0个服务器,是因为f字符串是在声明它们的同一行求值的。由于bot尚未运行,len(client.guilds)在字符串中的计算值为0,因此它将与分配status = cycle(['.apuva', '0 palvelimella!'])相同。

不使用f-string,你可以在字符串中留下占位符,然后在循环中对它们进行格式化。

status = itertools.cycle(['In {n} servers', ...])
... 
@tasks.loop(minutes=5)
async def change_status():
name = next(status)
name = name.format(n=len(client.guilds))
# Note that if the placeholder '{n}' does not exist in the string,
# no error will occur and the string remains the same
await client.change_presence(...)
import asyncio
@client.event
async def on_ready():
print("Bot is ready!")
while not client.is_closed():
await client.change_presence(activity=discord.Game(name=f"{len(client.guilds)} servers!")
await asyncio.sleep(10)
await client.change_presence(activity=discord.Game(name="Status 2")
await asyncio.sleep(10)

最新更新