【问题标题】:Loop "for" pause bug循环“for”暂停错误
【发布时间】:2021-11-06 21:40:25
【问题描述】:

我正在用 python 制作一个不和谐的机器人,我遇到了一个问题。我想做一个命令,列出所有拥有我的机器人的服务器。一切都很顺利,但是一旦超过 5 台服务器,5 台服务器之间就会出现 2-3 秒的停顿。我的代码如下所示:

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)

我可以让它在没有暂停的情况下显示公会列表吗?

【问题讨论】:

  • 我建议你阅读这篇关于 ratelimit 的不和谐文章:discord.com/developers/docs/topics/rate-limits#rate-limits 你无法在短时间内向 api 发送尽可能多的请求。
  • 先加入名字,然后一起发送(考虑到 4000 个字符的限制)。您当前发送的请求过多,并且您的速率受到限制。

标签: python discord discord.py


【解决方案1】:

每个公会发送一条消息这不是一个好主意,因为您可能会收到rate-limited 并在短时间内发送许多消息,通常效果不佳。我建议先循环,获取所有行会,然后发送消息:

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

或使用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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-04-15
    • 2014-04-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-23
    相关资源
    最近更新 更多