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

开发带数据库的Discord Bot时遇TypeError: 'NoneType'不可下标错误

解决Discord机器人的'NoneType' object is not subscriptable错误

错误原因

报错行channel = self.client.get_channel(int(result[0]))触发TypeError,是因为cursor.fetchone()返回了None——你的main数据库表中,没有匹配当前服务器guild_id的channel_id记录。对None执行下标操作[0]是不允许的。

修复方案

在使用查询结果前添加非空判断,同时优化SQL查询避免注入风险,完善数据库连接管理:

@commands.Cog.listener()
async def on_message(self, message):
    if message.author == self.client.user:
        return
    
    db = sqlite3.connect('main.sqlite')
    cursor = db.cursor()
    # 使用参数化查询避免SQL注入
    cursor.execute("SELECT channel_id FROM main WHERE guild_id = ?", (message.guild.id,))
    result = cursor.fetchone()
    
    # 检查查询结果是否存在
    if result is None:
        await message.channel.send("当前服务器未配置目标转发频道!")
        db.close()
        return
    
    target_channel_id = int(result[0])
    channel = self.client.get_channel(target_channel_id)
    
    # 检查频道是否存在
    if channel is None:
        await message.channel.send(f"配置的目标频道(ID: {target_channel_id})不存在!")
        db.close()
        return
    
    await channel.send(message.content)
    db.close()  # 关闭数据库连接

额外注意事项

  • 参数化查询:原代码用format拼接SQL存在注入风险,改用?占位符传入参数是更安全的做法。
  • 数据库连接管理:每次操作完成后必须调用db.close(),防止连接资源泄露。
  • 频道存在性校验:即使数据库中有记录,目标频道也可能被删除,因此需要额外判断channel是否有效。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 10:10:39