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

Python Discord机器人createkey命令报错:'int'对象无split属性

问题根源与修复方案

错误原因

  1. 类型不匹配:你把duration参数定义为int类型,但代码里调用了split()方法——这是字符串专属方法,整数(int)没有这个属性,直接触发AttributeError。你实际想要接收的是类似"345 day(s) 12 hour(s) 34 minute(s)"的带单位字符串,所以参数类型应该是str。
  2. 判断逻辑错误:part[-1] == 'day(s)'是错误的,part[-1]取的是字符串最后一个字符,永远不可能等于"day(s)"这种多字符后缀,应该用str.endswith()方法来检查后缀。
  3. 变量名冲突:你用duration += ...来累加时长,但duration是传入的参数,应该用初始化的变量存储计算结果,否则会覆盖原始输入,导致逻辑混乱。

修正后的代码

@tree.command(name='createkey', description='创建兑换码')
async def createkey(interaction: discord.Interaction, duration: str):
    # 将时长字符串解析为总分钟数
    total_minutes = 0
    duration_parts = duration.split(" ")
    
    # 遍历拆分后的部分,跳过空字符串(如果有)
    for part in duration_parts:
        part = part.strip()
        if not part:
            continue
        
        if part.endswith('day(s)'):
            # 提取数字部分并转换为分钟
            days = int(part.replace('day(s)', ''))
            total_minutes += days * 24 * 60
        elif part.endswith('hour(s)'):
            hours = int(part.replace('hour(s)', ''))
            total_minutes += hours * 60
        elif part.endswith('minute(s)'):
            minutes = int(part.replace('minute(s)', ''))
            total_minutes += minutes
    
    # 此处可添加生成兑换码的逻辑,比如生成Discord-xxxx格式的随机码
    # 同时将total_minutes作为有效期存储
    await interaction.response.send_message(f"已生成兑换码,有效期总时长:{total_minutes} 分钟")

额外说明

  • 调用命令时,需传入符合格式的字符串,比如/createkey duration:"345 day(s) 12 hour(s) 34 minute(s)"
  • 若需要更严谨的格式校验,可添加异常捕获(如无法转换为整数的情况),避免程序崩溃

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 03:35:31