Last active
October 15, 2022 10:05
-
-
Save Max-Makhrov/f65070308415b54d20a91dcb438a5956 to your computer and use it in GitHub Desktop.
send a message to Telegram with Bot from WebApp. Google Apps Script
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var token = "1234697707:AAHGyL2PE..."; // CHANGE1 | |
function doPost(e) { | |
var chat_id = -0123456789; // CHANGE1 | |
var msg = e.parameter.msg; | |
if (!msg || msg === '') { | |
return returnXml_('no message'); | |
} | |
// uncomment to prevent same messages | |
// if (inMemory_(msg)) { | |
// return returnXml_('sent'); | |
// } | |
sendMessage2Bot_(msg, chat_id); | |
var d = new Date(); | |
var dd = Utilities.formatDate( | |
d, | |
Session.getTimeZone(), | |
"yyyy-MM-dd HH:mm:ss" | |
); | |
return returnXml_(dd); | |
} | |
function doGet(e) { | |
return doPost(e); | |
} | |
function returnXml_(text) { | |
return ContentService.createTextOutput('<res>'+ text +'</res>').setMimeType( | |
ContentService.MimeType.XML | |
); | |
} | |
var telegramUrl = "https://api.telegram.org/bot" + token; | |
function testSend() { | |
// Telegram Bot API | |
// supports only these tags: | |
// b, i, a, code, pre | |
sendMessage2Bot_( | |
'Hello,\n' + | |
'<b>bold</b>\n' + | |
'<strong>strong💪🏼</strong>\n' + | |
'<a href = "https://twitter.com/max__makhrov">url</a>\n' + | |
'<i>italic</i>\n' + | |
'<em>emphasized</em>\n\n' + | |
'<code>code\nis multiline</code>\n\n' + | |
'<pre>pre\nis multiline</pre>', | |
-0123456789); // CHANGE1 | |
} | |
function sendMessage2Bot_(msg, chat_id) { | |
var text = | |
encodeURIComponent(msg). | |
replace(/(?:\r\n|\r|\n)/g, '\\n'); | |
text = msg; | |
chat_id = chat_id || GROUP0_CHAT_ID; | |
var data = { | |
"text" : text, | |
"parse_mode": 'html' | |
}; | |
var payload = JSON.stringify(data); | |
var options = { | |
"method" : "POST", | |
"contentType" : "application/json", | |
"payload" : payload, | |
"muteHttpExceptions": true | |
}; | |
var url = telegramUrl + "/sendMessage?chat_id=" + chat_id; | |
var response = UrlFetchApp.fetch(url, options); | |
// var url = telegramUrl + "/sendMessage?chat_id=" + chat_id + "&text="+ text; | |
console.log(response.getContentText()); | |
} | |
// prevent dupes | |
function inMemory_(msg) { | |
var key = 'telebeep1'; | |
var c = CacheService.getScriptCache(); | |
var mem = c.get(key); | |
var o; | |
if (mem) { | |
o = JSON.parse(mem); | |
} else { | |
o = {}; | |
} | |
var res = false; | |
if (o[msg]) { | |
res = true; | |
} | |
o[msg] = 1; | |
c.put(key, JSON.stringify(o), 21600); | |
return res; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment