Discord机器人无法将所有文本放入同一Embed的问题求助
解决Discord机器人循环发送多个Embed的问题
你的问题出在循环内部每次创建新Embed并发送,导致每条数据对应一个独立的消息。要把所有内容放到同一个Embed里,只需要把Embed的创建和发送逻辑移到循环外,在循环里只填充内容即可。
修正方案1:拼接描述文本
如果希望所有名称直接展示在Embed的描述中,可以这样修改:
import requests import discord from discord.ext import commands bot = commands.Bot(command_prefix='!', description="ayuda bot") bot.remove_command("help") @bot.command() async def habbo(ctx): response = requests.get("https://images.habbo.com/habbo-web-leaderboards/hhes/visited-rooms/daily/latest.json") data = response.json() # 先创建一个空的Embed,设置标题和颜色 embed = discord.Embed(title="每日热门房间", color=discord.Colour.random()) # 初始化描述文本 description_text = "" # 循环遍历数据,拼接每个名称 for index, habbo in enumerate(data, start=1): description_text += f"{index}. {habbo['name']}\n" # 将拼接好的文本设置为Embed的描述 embed.description = description_text # 最后统一发送这个Embed await ctx.send(embed=embed) @bot.event async def on_ready(): print("BOT listo!") bot.run('你的机器人Token')
修正方案2:使用Embed字段(更整洁)
如果希望每条数据用独立的字段展示,可读性更好,可以用add_field方法:
import requests import discord from discord.ext import commands bot = commands.Bot(command_prefix='!', description="ayuda bot") bot.remove_command("help") @bot.command() async def habbo(ctx): response = requests.get("https://images.habbo.com/habbo-web-leaderboards/hhes/visited-rooms/daily/latest.json") data = response.json() embed = discord.Embed(title="每日热门房间", color=discord.Colour.random()) for index, habbo in enumerate(data, start=1): # 添加字段,name是序号,value是房间名称,inline=False让每个字段占一行 embed.add_field(name=f"第{index}名", value=habbo['name'], inline=False) await ctx.send(embed=embed) @bot.event async def on_ready(): print("BOT listo!") bot.run('你的机器人Token')
注意事项
- Discord的Embed有长度限制:描述最多2048字符,单个字段value最多1024字符,总字段数最多25个。如果你的数据量超过这些限制,需要考虑分页或者截断内容。
- 尽量给Embed设置一个清晰的标题,方便用户理解内容。
内容的提问来源于stack exchange,提问作者aidinha
相关产品推荐
相关产品推荐

