如何将Telegram bot通过telegraf获取的数据保存到Google Sheets
报错原因
ctx是Telegraf事件回调的局部参数,仅在接收到Telegram消息触发的回调作用域内可用。你原本在全局谷歌授权完成后直接调用gsrun,该作用域下不存在ctx变量,因此触发未定义报错。
修改步骤
- 存储谷歌授权客户端为全局变量,避免每次收到消息重复授权
- 改写
gsrun函数,支持接收动态传入的行数据作为写入内容 - 在
text事件回调中,从ctx提取所需字段,调用gsrun写入表格
修改后完整代码
const { Telegraf } = require('telegraf'); // 替换为自己的Telegram Bot Token const bot = new Telegraf("xyz") const { google } = require("googleapis"); const keys = require("./Keys.json") // 全局存储谷歌API授权客户端 let gsClient = null; bot.on('text', async (ctx, next) => { // 提取需要写入的字段,兼容空值避免报错 const chatId = ctx.message.chat.id; const username = ctx.from.username || ''; const fullName = `${ctx.message.chat.first_name || ''} ${ctx.message.chat.last_name || ''}`.trim(); const text = ctx.message.text; // 保留原有日志逻辑 console.log(`[text] ${chatId} ${username} ${fullName} ${text}`); // 谷歌授权完成后再执行写入操作 if(gsClient) { try { // 按列顺序传入需要写入的字段 await gsrun(gsClient, [chatId, username, fullName, text]); } catch (e) { console.error('写入表格失败:', e) } } return next(); }); bot.start((ctx) => ctx.reply('Welcome')) bot.help((ctx) => ctx.reply('Send me a sticker')) bot.on('sticker', (ctx) => ctx.reply('👍')) bot.hears('hi', (ctx) => ctx.reply('Hey there')) const client = new google.auth.JWT( keys.client_email, null, keys.private_key, ["https://www.googleapis.com/auth/spreadsheets"] ); client.authorize(function(err){ if(err){ console.log(err); return; } else { console.log("谷歌API连接成功"); // 授权成功后将客户端实例赋值给全局变量 gsClient = client; } }); // 新增rowData参数接收动态数据 async function gsrun(cl, rowData){ const gsapi = google.sheets({version:"v4", auth: cl}); const updateOptions = { // 替换为自己的Google Sheets ID spreadsheetId: "xyz", range: "Sheet1", valueInputOption: "RAW", insertDataOption: "INSERT_ROWS", resource: { values: [rowData] } }; let res = await gsapi.spreadsheets.values.append(updateOptions); console.log('写入成功:', res.data); } bot.launch()
注意事项
- 代码中标注
xyz的位置需要替换为你自己的Telegram bot token和Google Sheets ID - 已增加空值兼容逻辑,避免部分用户未设置用户名/姓氏时触发报错
- 已增加异常捕获,写入失败时只会打印错误日志,不会中断bot正常运行
内容的提问来源于stack exchange,提问作者Mohammad Abbas
相关产品推荐
相关产品推荐

