Telegram Bot集成Google Sheets遇Webhook 302错误求助
问题排查与解决
核心原因:Web App部署设置导致302重定向
Telegram Webhook要求接收端返回200响应,而Google Apps Script的Web App若部署时权限设置错误,会触发重定向(302),导致Telegram无法正确接收响应。
排查步骤与修复方案
修正Web App部署权限
重新部署Web App时,严格设置:- 「执行权限」选「我(当前Google账号)」
- 「访问权限」选「任何人,甚至匿名」
若选「仅限组织」或「特定人员」,Telegram的请求会被Google重定向到登录页面,直接返回302错误。
规范
doPost函数的返回值
确保函数明确返回Telegram认可的响应,不能返回空或未处理内容。示例代码:function doPost(e) { // 处理消息同步逻辑 const sheet = SpreadsheetApp.openById('你的表格ID').getActiveSheet(); const update = JSON.parse(e.postData.contents); if (update.message) { const text = update.message.text; const date = new Date(update.message.date * 1000); sheet.appendRow([date, text]); } // 必须返回标准JSON响应,告知Telegram请求成功 return ContentService.createTextOutput(JSON.stringify({status: "ok"})).setMimeType(ContentService.MimeType.JSON); }要点:不能省略返回语句或返回
null,否则GAS会默认返回HTML页面,触发重定向。验证Webhook URL有效性
- 确保使用Web App部署后的正式URL:
https://script.google.com/macros/s/部署ID/exec - 禁止用带
/dev的预览URL,仅生产环境的/exec地址可用于Webhook。
- 确保使用Web App部署后的正式URL:
重置Webhook
调用Telegram API重置Webhook(替换<你的BotToken>和<你的WebAppURL>):https://api.telegram.org/bot<你的BotToken>/setWebhook?url=<你的WebAppURL>检查返回结果,确认
ok和result均为true。确认频道权限
- 将Bot添加到目标频道,并开启「查看消息」权限
- 若为超级频道,需将Bot设为管理员(至少保留读取消息权限)
内容的提问来源于stack exchange,提问作者Governor Bets
相关产品推荐
相关产品推荐

