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

discord.py报Converting to "int" failed for parameter "num"错误

问题根因

你在Cog类中定义命令方法时漏写了第一个强制位置参数self,直接导致所有参数位置错位:

  • 在继承自commands.Cog的类中定义实例命令方法时,discord.py会自动传入的第一个参数是Cog实例本身(对应self),第二个参数才是命令上下文ctx,之后才是用户输入的命令参数
  • 你当前的命令方法参数写为async def crafting(ctx, name: str, num: int),参数错位后,你输入的第一个参数gbs被直接传给了标注为int类型的num参数,自然触发int类型转换失败的报错,和你做不做整数转换没有任何关系。
修复要点
  1. 给crafting命令方法补上self作为第一个位置参数
  2. 修正类型标注的拼写错误:commands.bot改为commands.Bot(首字母大写,是discord.py定义的官方类名)
  3. (可选优化)打开素材图后创建副本再绘制,避免多次调用命令时文字反复叠加在同一张原图对象上;处理完图片后及时释放资源,避免文件被占用无法读写。
修复后可运行代码
from PIL import Image, ImageDraw, ImageFont
import discord
from discord.ext import commands

class crafting(commands.Cog):
    "制作材料计算相关命令"
    def __init__(self, bot: commands.Bot):
        self.bot = bot

    @commands.command()
    async def crafting(self, ctx: commands.Context, name: str, num: int):
        if name == "gbs":
            # 打开素材后创建副本,避免修改原图导致多次调用叠字
            with Image.open("gearboxcrafting.png") as base_img:
                img = base_img.copy()
            font = ImageFont.truetype("ARIAL.TTF", 30)
            numfont = ImageFont.truetype("Bold-X3RG.ttf", 40)
            
            copper_rod = num * 10
            steel_bolt = num * 50
            steel_plate = num * 25
            
            draw = ImageDraw.Draw(img)
            draw.text((368,565), str(copper_rod), (37, 35, 32), font=font)
            draw.text((368,656), str(steel_bolt), (37, 35, 32), font=font)
            draw.text((368,747), str(steel_plate), (37, 35, 32), font=font)
            draw.text((109,926), str(num), (37, 35, 32), font=numfont)

            img.save("text.png")
            # 释放资源避免文件占用
            del draw
            img.close()
            
            await ctx.send(file=discord.File("text.png"))

# discord.py 2.0+版本需要添加setup函数用于加载Cog
async def setup(bot: commands.Bot):
    await bot.add_cog(crafting(bot))
注意事项
  • 调用命令时格式要和参数顺序匹配,例如你的命令前缀是!的话,正确调用格式为!crafting gbs 10,第一个参数传物品名,第二个传整数制作数量
  • 确保字体文件ARIAL.TTF、Bold-X3RG.ttf和素材图gearboxcrafting.png都放在机器人运行的工作目录下,否则会触发文件找不到的错误

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.28 05:15:42