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

Discord机器人报错AttributeError: 'str'对象无send属性如何解决

问题原因

你从config.json读取到的statusChannel是字符串格式的频道ID,不是Discord.py的TextChannel对象,只有频道对象才有send()方法,直接调用字符串的send属性自然会触发AttributeError。

修复方案

需要先把存储的字符串ID转换为整数,再通过机器人实例的get_channel()方法获取对应的频道对象,修改后核心代码如下:

@bot.event
async def on_ready():
  print(f'{bot.user} has connected to Discord!')
  # 字符串ID转整数后获取频道对象
  channel_id = int(config['statusChannel'])
  channel = bot.get_channel(channel_id)
  if channel:
    print(f" {channel.name} is set as the server status channel.")
    await channel.send('This is the status channel.')
  else:
    print("配置的频道ID无效,请检查config.json")
更简洁的频道ID存储&设置方案
  • 直接用discord.ext.commands的参数类型标注自动解析频道对象,不需要手动过滤用户输入字符,避免把有效ID处理成无效值
  • 存储时直接写入整数类型的频道ID,读取后不需要额外格式处理即可使用
  • 如果机器人仅在单个服务器运行,也可以直接把频道ID存入.env环境变量,省去单独维护json配置文件的步骤

优化后的setstatus命令代码:

@bot.command()
async def setstatus(ctx, channel: discord.TextChannel):
  # 参数类型标注会自动把用户@的频道解析为频道对象
  config['statusChannel'] = channel.id
  # 直接更新配置后写入文件,不需要单独定义data变量
  with open('config.json', 'w') as f:
    json.dump(config, f)
  await ctx.send(f'服务状态频道已设置为 {channel.mention}')

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.21 08:54:04