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

如何让Discord Bot访问在线电子表格?开发入门求教

让Discord Bot访问在线电子表格的实现思路

一、针对Google Sheets的实现

  • 开启API并获取凭据
    登录Google Cloud控制台创建项目,启用Sheets API,创建服务账号密钥(JSON格式),将密钥文件放到Bot项目目录中。
  • 安装依赖库
    执行pip install gspread oauth2client(Python环境),gspread用于操作表格,oauth2client处理身份验证。
  • 编写核心代码
    import gspread
    from oauth2client.service_account import ServiceAccountCredentials
    
    # 配置权限范围
    scope = ["https://spreadsheets.google.com/feeds", "https://www.googleapis.com/auth/drive"]
    # 加载凭据
    creds = ServiceAccountCredentials.from_json_keyfile_name('你的密钥文件.json', scope)
    client = gspread.authorize(creds)
    
    # 打开目标表格(支持表格名称或URL中的ID)
    sheet = client.open("你的表格名称").sheet1
    
    # 读取数据示例:获取第一行内容
    row_data = sheet.row_values(1)
    # 写入数据示例:在第一行第一列写入内容
    sheet.update_cell(1, 1, "Discord Bot 测试内容")
    
  • 授权表格访问权限
    打开你的Google Sheets,点击分享按钮,输入服务账号的邮箱(密钥文件中client_email字段),赋予编辑或查看权限。

二、针对腾讯文档/在线Excel的实现

  • 申请开放平台权限
    腾讯文档开放平台创建应用,获取AppID和AppSecret;微软Excel在线则注册Microsoft Azure应用,获取对应凭据,通过官方API接口读写表格。
  • 安装依赖或直接请求
    腾讯文档可使用官方SDK,或用requests库发送HTTP请求;微软场景可安装msgraph-core库简化操作。
  • 代码示例(腾讯文档)
    import requests
    
    # 获取访问令牌
    def get_access_token():
        url = "https://openapi.qq.com/v3/token"
        params = {
            "grant_type": "client_credentials",
            "client_id": "你的AppID",
            "client_secret": "你的AppSecret"
        }
        response = requests.get(url, params=params)
        return response.json().get("access_token")
    
    # 读取表格数据
    def read_sheet(access_token, sheet_id):
        url = f"https://openapi.qq.com/v3/doc/sheets/{sheet_id}/values"
        headers = {"Authorization": f"Bearer {access_token}"}
        response = requests.get(url, headers=headers)
        return response.json()
    
    # 调用示例
    token = get_access_token()
    sheet_data = read_sheet(token, "你的表格ID")
    

三、通用注意事项

  • 确保Bot运行环境能访问对应API域名(如Google API需网络支持,国内平台无需额外配置)。
  • 敏感信息(密钥、AppSecret)不要硬编码,用环境变量或加密配置文件管理。
  • 处理API请求异常(网络错误、权限不足等),避免Bot崩溃。

内容的提问来源于stack exchange,提问作者Mr. Duck

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 16:55:20