Discord.py骰子命令Embed显示原始值而非目标整数问题
解决Discord机器人Embed显示原始代码表达式而非计算结果的问题
问题核心:你的Embed字段值使用了普通字符串包裹占位符,Python未解析这些表达式导致直接显示原始文本;而下方普通消息用了f-string,能正确完成变量替换和计算。
修复步骤
- 预计算骰子结果:避免两次调用
random.randint得到不同结果,先把结果存入变量。 - 使用字符串格式化语法:对Embed的标题、字段值使用f-string(和你普通消息里的写法一致),让Python解析占位符。
- 修复异步睡眠问题:
asyncio.sleep(1)需要加await,否则会阻塞事件循环。
修改后的完整代码
import asyncio import random import discord from discord.ext import commands @bot.command() async def rolldice(ctx): messagetwo = await ctx.send("Choose a number:\n**4**, **6**, **8**, **10**, **12**, **20** ") user = ctx.message.author.display_name def check(m): return m.author == ctx.author try: messageone = await bot.wait_for("message", check=check, timeout=30.0) m = messageone.content valid_choices = {"4", "6", "8", "10", "12", "20"} if m not in valid_choices: await ctx.send("Sorry, invalid choice.") return coming = await ctx.send("Here it comes...") await asyncio.sleep(1) # 补上await关键字 await coming.delete() await messagetwo.delete() await ctx.channel.purge(limit=2) # 预计算骰子结果,统一Embed和普通消息的输出值 roll_result = random.randint(1, int(m)) # 用f-string格式化Embed内容 embedVar = discord.Embed(title=f"{user}'s Dice", color=0x00ffff) embedVar.add_field(name="rolled", value=f"D{m}", inline=True) embedVar.add_field(name="landed", value=f"{roll_result}", inline=True) embedVar.set_footer(text='Booty Police | Dungeon Dice', icon_url="http://canvaswrite.com/PI/pybot/attachments/server-icon-full.png") await ctx.send(embed=embedVar) await ctx.send(f"{user} rolled a **D{m}** and got a **{roll_result}**") except asyncio.TimeoutError: await messageone.delete() await ctx.send("Process has been canceled because you didn't respond in **30** seconds.")
关键修改点说明
- 标题从
"{user}'s Dice"改为f"{user}'s Dice",确保用户名被正确替换。 - 字段值
"D{m}"改为f"D{m}"、"{random.randint(1, int(m))}"改为f"{roll_result}",让表达式被解析计算。 - 新增
roll_result变量,避免Embed和普通消息显示不同的骰子结果。 - 修正
asyncio.sleep(1)为await asyncio.sleep(1),保证异步流程正常执行。
内容的提问来源于stack exchange,提问作者newtboot
相关产品推荐
相关产品推荐

