本文详解如何用 discord.py 实现机器人编辑自身历史消息,通过 embed 字段动态追加用户信息到指定国家条目后,避免纯文本拼接的复杂性与易错性。
本文详解如何用 discord.py 实现机器人编辑自身历史消息,通过 embed 字段动态追加用户信息到指定国家条目后,避免纯文本拼接的复杂性与易错性。
在 Discord 机器人开发中,直接编辑原始文本消息并精准插入内容(如在“USA”行后添加 @user)极易引发格式错乱、换行丢失或定位错误——尤其当名单动态变化时。更稳健、可维护且视觉友好的方案是:改用 Embed 消息 + 字段(fields)管理国家列表。每个国家作为独立字段,其 value 可安全追加用户提及,无需解析整段文本。
首先精简 host-template.txt,仅保留国家名(每行一个),移除标题行:
USAJapanUKUSSRGermanyFranceItaly
在 !host 命令中读取文件并构建 Embed:
@client.command()async def host(ctx): with open('host-template.txt', 'r') as f: countries = [line.strip() for line in f if line.strip()] # 过滤空行 embed = discord.Embed(title="✅ Available Nations", color=0x3498db) for country in countries: embed.add_field(name=country, value="N/A", inline=False) # N/A 表示暂无预约 message = await ctx.send(embed=embed) # 保存消息 ID(用于后续编辑) with open('message.txt', 'w') as f: f.write(str(message.id))
关键逻辑:根据用户输入的国家名匹配 Embed 字段索引,安全追加用户提及:
@client.command()async def reserve(ctx, nation: str): # 规范化输入(忽略大小写和空格) nation = nation.strip().title() # 读取消息 ID 并获取原消息 try: with open("message.txt", "r") as f: message_id = int(f.read()) channel = ctx.channel message = await channel.fetch_message(message_id) except (FileNotFoundError, ValueError, discord.NotFound): await ctx.send("❌ 预约列表未初始化,请先执行 `!host`。") return # 确保消息含 Embed if not message.embeds: await ctx.send("❌ 预约列表格式异常,请重新执行 `!host`。") return embed = message.embeds[0].copy() # 避免修改原引用 field_index = None # 查找匹配的国家字段(不区分大小写) for i, field in enumerate(embed.fields): if field.name.strip().lower() == nation.lower(): field_index = i break if field_index is None: await ctx.send(f"❌ 国家 '{nation}' 不在列表中,请检查拼写。") return # 更新字段值:N/A → @user,或追加新用户 current_value = embed.fields[field_index].value new_value = f"{ctx.author.mention}" if current_value != "N/A": new_value = f"{current_value}n{ctx.author.mention}" # 替换字段(保持顺序) embed.set_field_at( index=field_index, name=embed.fields[field_index].name, value=new_value, inline=False ) await message.edit(embed=embed) await ctx.send(f"✅ 已为 `{nation}` 预约:{ctx.author.mention}")
此方案彻底规避了字符串正则匹配与行定位的脆弱性,利用 Discord 原生 Embed 字段的语义化结构,实现清晰、可靠、可扩展的预约状态管理。