Monday, February 17, 2020


1.Overview




2.Setup
2.1 Create Telegram bot
Chat with BotFater to create Telegram bot and get TOKEN (red frame)

2.2 Create Apps Script
Step1: Go to  https://script.google.com/ and create new script.
Select "Publish > Deploy as web app" to get web app url


Fill your token and webAppUrl to below script.
Code.gs
var token = "23947923427:kahsdkajsdgsakjdaksjdbkhyjhhd"; // FILL IN YOUR OWN TOKEN
var telegramUrl = "https://api.telegram.org/bot" + token;
var webAppUrl = "https://script.google.com/macros/s/AKfycbxasdhhwuihuip17OHRD7gcajsdhkjasjpSMtKjh2tue40MSHY74/exec"; // FILL IN YOUR GOOGLE WEB APP ADDRESS

function doGet(e) {
  return HtmlService.createHtmlOutput("Hi there");
}


function getMe() {
  var url = telegramUrl + "/getMe";
  var response = UrlFetchApp.fetch(url);
  Logger.log(response.getContentText());
}

function setWebhook() {
  var url = telegramUrl + "/setWebhook?url=" + webAppUrl;
  var response = UrlFetchApp.fetch(url);
  Logger.log(response.getContentText());
}

function sendText(id,text) {
  var url = telegramUrl + "/sendMessage?chat_id=" + id + "&text=" + text;
  var response = UrlFetchApp.fetch(url);
  Logger.log(response.getContentText());
}

function doPost(e) {
  // this is where telegram works
  //console.log(e)
  
  var data = JSON.parse(e.postData.contents);
  var text = data.message.text;
  var id = data.message.chat.id;
  var name = data.message.chat.first_name;
  var answer = "Hi " + name + ", thank you for your comment " + text;
  sendText(id,answer);
}

Update code by run "Publish > Deploy as web app" again.
Note: select "New" in project version.

Step2: Run setWebhook to set webhook (webAppUrl) to telegram server.


Okey, try to use.


Leave a Reply

Subscribe to Posts | Subscribe to Comments

- Copyright © Lập trình hệ thống nhúng Linux . Powered by Luong Duy Ninh -