Python新手求助:Discord Bot使用command装饰器触发AttributeError
问题分析与解决
错误原因
你的代码存在两个关键问题:
- 混用了f-string和
.format()语法:f-string本身支持直接在字符串中嵌入变量,不需要额外调用.format(),且你的写法里f-string未预留runnum的位置,.format()传参无法生效。 - 未导入
random模块:代码中使用了random.randint()但未导入该模块,这会触发AttributeError。
修正后的代码
import random from discord.ext import commands client = commands.Bot(command_prefix='!') # 假设你的命令前缀为! @client.command() async def roll(ctx, arg=7): author = ctx.message.author runnum = random.randint(0, arg) await ctx.send(f"{author.mention}, ваш бросок равен {runnum}")
说明
- 开头添加
import random导入随机数模块,解决random未定义的问题。 - 调整字符串写法,将
runnum直接嵌入f-string的{}中,移除多余的.format(runnum)。
内容的提问来源于stack exchange,提问作者Vlad
相关产品推荐
相关产品推荐

