I am making a discord bot in python, and I ran into a problem. I wanted to make a command that lists all the servers that have my bot. Everything went well, but as soon as there were more than 5 servers, there was a pause of 2-3 seconds between 5 servers. My code looked like this:
import discord
from discord.ext import commands
from discord.ext.commands import bot
bot = commands.Bot(command_prefix = ";", intents=discord.Intents.all(),help_command=None,case_insensitive=True)
@bot.command()
async def listguilds(ctx):
servers = bot.guilds
for guild in servers:
await ctx.send(guild.name)
bot.run(TOKEN)
Can I make it display the guild list without pauses?
You send one message per guild which is not a really great idea as you might get rate-limited and sending many messages in a short period of time, usually doesn't work well. I would suggest looping first, getting all guilds and after that sending a message:
@bot.command()
async def listguilds(ctx):
servers = bot.guilds
all_guilds = "" #empty string which will store all guilds
for guild in servers:
all_guilds += guild.name + "\n"
await ctx.send(all_guilds)
or by using embeds:
@bot.command()
async def listguilds(ctx):
servers = bot.guilds
embed = discord.Embed(color=discord.Color.blurple(), title="Guild list")
for guild in servers:
embed.add_field(name=guild.name, value=len(guild.members), inline=False) #also shows how many members are on server (requires intents.members!!!)
await ctx.send(embed=embed)