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

如何编写Google App Script实现Telegram Bot延迟回复Google Sheet生成码

实现Telegram Bot延迟回复Google Sheet追踪码的方案

核心逻辑

  1. 收到Telegram指令后,先将数据写入Google Sheet,获取生成追踪码的行号
  2. 通过时间驱动触发器实现3秒延迟(避免阻塞Webhook响应)
  3. 延迟后从Sheet对应行读取A列追踪码,调用Telegram API发送回复

完整脚本

// 处理Telegram Webhook请求
function doPost(e) {
  const data = JSON.parse(e.postData.contents);
  const chatId = data.message.chat.id;
  const command = data.message.text;

  // 替换为你的触发命令,比如 /submitData
  if (command.startsWith('/submitData')) {
    // 1. 执行你已有的添加数据到Sheet的逻辑
    const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('你的工作表名称');
    // 替换为你实际的新增数据逻辑,示例中A列留空由Sheet公式生成追踪码
    const newRow = ['', '用户提交的数据1', '用户提交的数据2'];
    const rowIndex = sheet.appendRow(newRow) + 1; // 获取新行行号(appendRow返回索引从0开始,需+1)

    // 2. 存储延迟回复所需的临时参数
    const props = PropertiesService.getScriptProperties();
    const tempKey = `delay_${chatId}_${Date.now()}`;
    props.setProperty(tempKey, JSON.stringify({ chatId, rowIndex }));

    // 3. 创建3秒延迟的触发器
    ScriptApp.newTrigger('sendTrackingCode')
      .timeBased()
      .after(3000) // 3000毫秒=3秒
      .withArgs(tempKey)
      .create();

    // 可选:先发送提交确认消息
    sendTelegramMessage(chatId, '数据已提交,正在生成追踪码...');
  }

  return ContentService.createTextOutput(JSON.stringify({ ok: true })).setMimeType(ContentService.MimeType.JSON);
}

// 延迟执行的追踪码回复函数
function sendTrackingCode(tempKey) {
  const props = PropertiesService.getScriptProperties();
  const params = JSON.parse(props.getProperty(tempKey));
  const { chatId, rowIndex } = params;

  // 1. 读取Sheet中对应行的A列追踪码
  const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('你的工作表名称');
  const trackingCode = sheet.getRange(rowIndex, 1).getValue(); // 第rowIndex行,第1列(A列)

  // 2. 发送追踪码到Telegram
  if (trackingCode) {
    sendTelegramMessage(chatId, `你的追踪码:${trackingCode}`);
  } else {
    sendTelegramMessage(chatId, '追踪码生成失败,请稍后重试');
  }

  // 清理临时存储的参数
  props.deleteProperty(tempKey);
}

// 封装Telegram消息发送工具函数
function sendTelegramMessage(chatId, text) {
  const botToken = '你的Telegram Bot Token'; // 替换为你的Bot Token
  const url = `https://api.telegram.org/bot${botToken}/sendMessage`;
  const payload = {
    chat_id: chatId,
    text: text
  };

  UrlFetchApp.fetch(url, {
    method: 'post',
    contentType: 'application/json',
    payload: JSON.stringify(payload)
  });
}

关键注意事项

  • 避免直接使用Utilities.sleep(3000):Telegram Webhook要求服务器在5秒内响应,直接sleep会触发超时重试,导致重复处理问题。时间驱动触发器是异步执行,不会阻塞Webhook响应。
  • 追踪码生成逻辑:假设你的Sheet A列通过公式自动生成追踪码(比如="FPB"&TEXT(TODAY(),"DDMMYY")&"-"&ROW()-1),如果是脚本生成,直接在appendRow时填入A列值即可。
  • 权限配置:首次运行脚本时需要授权,确保脚本拥有Google Sheet编辑权限和Telegram API调用权限。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 10:35:18