tontsa28
tontsa28

Reputation: 83

How to set number of servers that the bot is on as status (discord.py rewrite)?

I tried using this piece of code:

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)))

However, this shows the status to be on "0 servers", even though my bot is on 3 servers. How to fix this in the rewrite version of discord.py?

Upvotes: 0

Views: 488

Answers (2)

thegamecracks
thegamecracks

Reputation: 584

The reason it says 0 servers is because f-strings are evaluated on the same line you declare them. Since the bot hasn't yet been run, len(client.guilds) evaluates to 0 in your string, so it would be the same as assigning status = cycle(['.apuva', '0 palvelimella!']).

Instead of using f-strings, you can leave placeholders in your strings and then format them when you're inside the loop.

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(...)

Upvotes: 1

Ali Hakan Kurt
Ali Hakan Kurt

Reputation: 1037

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)

Upvotes: 0

Related Questions