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

使用gspread的Discord Bot对接Google Sheets报AttributeError求助

Discord Bot对接Google Sheets时的AttributeError错误

错误信息

Traceback (most recent call last):
  File "/home/runner/Bundeswehr-Bot/venv/lib/python3.8/site-packages/discord/ui/modal.py", line 186, in _scheduled_task
    await self.on_submit(interaction)
  File "/home/runner/Bundeswehr-Bot/modals.py", line 45, in on_submit
    if sheet.find(self.host.value) == None:
  File "/home/runner/Bundeswehr-Bot/venv/lib/python3.8/site-packages/gspread/cell.py", line 44, in __eq__
    same_row = self.row == other.row
AttributeError: 'NoneType' object has no attribute 'row'

问题代码

class bct_modal(discord.ui.Modal, title="BCT Logging"):
  host = discord.ui.TextInput(
        label='Host ID',
        placeholder='The hosts discord ID here...',
        required=True
    )

  async def on_submit(self, interaction: discord.Interaction):
      ids = []
      ids.append(self.host.value)

      print(ids)
      if sheet.find(self.host.value) == None:
        sheet.append_row([self.host.value, 0, 0, 0, 0, 0, 0, 0, 0])
        for id in ids:
          bct_host_col = sheet.find("Hosted BCT").col
          cell_row = sheet.find(id).row
          sheet.update_cell(cell_row, bct_host_col, int(sheet.cell(cell_row, bct_host_col).value) + 1)
      elif sheet.find(self.host.value) != None:
        print("This ID is already in the sheet.")

问题分析

  1. 比较逻辑触发对象方法报错:gspread的find()方法返回Cell对象,用== None比较时,会触发Cell类的__eq__方法,该方法会尝试访问None的row属性,但None没有这个属性,直接抛出错误。
  2. 重复查询浪费资源:代码多次调用sheet.find(),每次都发起API请求,既低效又增加出错概率。

修复方案

  • 单次查询结果存为变量,避免重复调用API
  • 用is None替代== None做判断,is是身份比较,不会触发对象的__eq__方法,能直接判断是否为None

修复后的代码

class bct_modal(discord.ui.Modal, title="BCT Logging"):
  host = discord.ui.TextInput(
        label='Host ID',
        placeholder='The hosts discord ID here...',
        required=True
    )

  async def on_submit(self, interaction: discord.Interaction):
      host_id = self.host.value
      ids = [host_id]
      print(ids)
      
      # 仅查询一次并保存结果
      found_cell = sheet.find(host_id)
      
      if found_cell is None:
        sheet.append_row([host_id, 0, 0, 0, 0, 0, 0, 0, 0])
        # 追加后重新获取行号
        found_cell = sheet.find(host_id)
        bct_host_col = sheet.find("Hosted BCT").col
        current_value = int(sheet.cell(found_cell.row, bct_host_col).value)
        sheet.update_cell(found_cell.row, bct_host_col, current_value + 1)
      else:
        print("This ID is already in the sheet.")

注:原代码中for id in ids循环无实际意义(列表仅一个元素),修复后直接用变量简化操作。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 21:20:28