首页 > 解决方案 > 使用 Google Web 应用 JavaScript 将 JSON 对象发送到 Telegram 机器人

问题描述

0stone0:修复问题;谢谢,谢谢+谢谢;

ADW:感谢您对键盘对象进行说明,采纳;

基于 JavaScript 的 Google Web 应用程序将 JSON 对象发送到 Telegram 机器人;使用按钮实现基于 Telegram 的菜单,以便用户按下选定的按钮并执行相应的操作;

用户类型:菜单

电报组屏幕上显示按钮列表

解决方案如下:

function menu( chat_id ) {
    let url = vUrlTelegram + "/sendMessage";

    var keyboard = {
        'inline_keyboard' : 
        [
            [{'text' : 'admin',      'callback_data' : 'admin'}], // Row 1 
            [{'text' : 'squad',      'callback_data' : 'squad'}], // Row 2

            [{'text' : 'carioca',    'callback_data' : 'carioca'}], // Row 3
            [{'text' : 'brasileiro', 'callback_data' : 'brasileiro'}], // Row 4

            [{'text' : 'sponsors',   'callback_data' : 'sponsors'}], // Row 5       
            [{'text' : 'test',       'callback_data' : 'test'}] // Row 6       
        ]
    };  

    var data = {
        'chat_id': chat_id,
        'text': "main menu",
        'reply_markup': keyboard
    };   

    var options = {
        'method' : 'post',
        'contentType': 'application/json',
        'payload' : JSON.stringify(data)
    };
    var response = UrlFetchApp.fetch(url, options);  
    Logger.log(response);
}

标签: javascriptjsongoogle-apps-scripttelegram-bot

解决方案


这假设您尝试使用 Google Apps 脚本向 Telegram 发送内联键盘。

我编写了这个示例脚本,可能会有所帮助:

function sample_inlineKeyboard() {
  var chat_id = '123456789';
  var text = 'Please pick a button:';
  var keyboard = {
    'inline_keyboard' : 
    [
      [{'text' : 'blue',   'callback_data' : 'blue'}, 
       {'text' : 'green',  'callback_data' : 'green'}, 
       {'text' : 'red',    'callback_data' : 'red'}], // Row 1
      [{'text' : 'yellow', 'callback_data' : 'yellow'},
       {'text' : 'brown',  'callback_data' : 'brown'}, 
       {'text' : 'black',  'callback_data' : 'black'}] // Row 2
    ]
  }
  var data = {
    'chat_id': chat_id,
    'text': text,
    'reply_markup': keyboard
  };        
  var options = {
    'method' : 'post',
    'contentType': 'application/json',
    'payload' : JSON.stringify(data)
  };
  var token = "0123456789:AABBCC....."; // Bot token
  var vUrlTelegram = 'https://api.telegram.org/bot' + token + '/sendMessage';
  var response = UrlFetchApp.fetch(vUrlTelegram, options);    
  Logger.log(response);
}

推荐阅读