You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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}")

说明

  1. 开头添加import random导入随机数模块,解决random未定义的问题。
  2. 调整字符串写法,将runnum直接嵌入f-string的{}中,移除多余的.format(runnum)。

内容的提问来源于stack exchange,提问作者Vlad

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.24 17:37:00