Skip to content

Instantly share code, notes, and snippets.

@unnikked
Last active February 19, 2024 02:58
Show Gist options
  • Save unnikked/828e45e52e217adc09478321225ec3de to your computer and use it in GitHub Desktop.
Save unnikked/828e45e52e217adc09478321225ec3de to your computer and use it in GitHub Desktop.
How to host your Telegram bot on Google App Script

Telegram Bot on Google App Script

This is the source code of one of my blog post. To read the full blog post please click here.

var token = 'xxx';
function doPost(e) {
// Make sure to only reply to json requests
if(e.postData.type == "application/json") {
// Parse the update sent from Telegram
var update = JSON.parse(e.postData.contents);
// Instantiate our bot passing the update
var bot = new Bot(token, update);
// Building commands
var bus = new CommandBus();
bus.on(/\/start/, function () {
this.replyToSender("Congratulations! It works!");
});
bus.on(/\/joke\s*([A-Za-z0-9_]+)?\s*([A-Za-z0-9_]+)?/, randomJoke);
// Register the command bus
bot.register(bus);
// If the update is valid, process it
if (update) {
bot.process();
}
}
}
function setWebhook() {
var bot = new Bot(token, {});
var result = bot.request('setWebhook', {
url: // publish your app and put your /excec URL here
});
Logger.log(result);
}
function randomJoke(name, surname) {
var firstName = name || null;
var lastName = surname || null;
var url = 'http://api.icndb.com/jokes/random?escape=javascript';
if (firstName) url += '&firstName=' + firstName;
if (lastName) url += '&lastName=' + lastName;
var data = JSON.parse(UrlFetchApp.fetch(url).getContentText());
this.replyToSender(data.value.joke);
}
function Bot (token, update) {
this.token = token;
this.update = update;
this.handlers = [];
}
Bot.prototype.register = function ( handler) {
this.handlers.push(handler);
}
Bot.prototype.process = function () {
for (var i in this.handlers) {
var event = this.handlers[i];
var result = event.condition(this);
if (result) {
return event.handle(this);
}
}
}
Bot.prototype.request = function (method, data) {
var options = {
'method' : 'post',
'contentType': 'application/json',
'payload' : JSON.stringify(data)
};
var response = UrlFetchApp.fetch('https://api.telegram.org/bot' + this.token + '/' + method, options);
if (response.getResponseCode() == 200) {
return JSON.parse(response.getContentText());
}
return false;
}
Bot.prototype.replyToSender = function (text) {
return this.request('sendMessage', {
'chat_id': this.update.message.from.id,
'text': text
});
}
function CommandBus() {
this.commands = [];
}
CommandBus.prototype.on = function (regexp, callback) {
this.commands.push({'regexp': regexp, 'callback': callback});
}
CommandBus.prototype.condition = function (bot) {
return bot.update.message.text.charAt(0) === '/';
}
CommandBus.prototype.handle = function (bot) {
for (var i in this.commands) {
var cmd = this.commands[i];
var tokens = cmd.regexp.exec(bot.update.message.text);
if (tokens != null) {
return cmd.callback.apply(bot, tokens.splice(1));
}
}
return bot.replyToSender("Invalid command");
}
@Darth41
Copy link

Darth41 commented Sep 18, 2020

Hi,
I get this error when trying to run this script. Any help?

Exception: Request failed for https://api.telegram.org returned code 404. Truncated server response: {"ok":false,"error_code":404,"description":"Not Found"} (use muteHttpExceptions option to examine full response) (line 81, file "Code")

Thank you!

@alexwer76
Copy link

Привет,
я получаю эту ошибку при попытке запустить этот скрипт. Любая помощь?

Исключение: сбой запроса для https://api.telegram.org вернул код 404. Усеченный ответ сервера: {"ok": false, "error_code": 404, "description": "Not Found"} (используйте параметр muteHttpExceptions для проверки полный ответ) (строка 81, файл «Код»)

Спасибо!

Надо отправить команду боту Ошибка говорит что нет сообщения

@KellsonM
Copy link

Changing the function name to "function doPost(e)" works for me.
Also setWebhook https://gist.github.com/unnikked/828e45e52e217adc09478321225ec3de#gistcomment-3226679

Thanks @unnikked 👍

@unnikked
Copy link
Author

Thank you guys for your contributions! I did not know that this blew up over these years! Feel free to share your ideas!

You can join my community on Telegram.

@alii2212
Copy link

alii2212 commented Dec 4, 2020

Thank you guys for your contributions! I did not know that this blew up over these years! Feel free to share your ideas!

You can join my community on Telegram.

hi unnikked thank you for share this
i have a little problem i can write code just in one page https://ibb.co/pnS6CNr
i want write code just Return the user message and i that massage input var x ="massage"

@alexwer76
Copy link

alexwer76 commented Jan 18, 2021 via email

@baublys
Copy link

baublys commented Nov 2, 2021

@fuzmorel
Copy link

Add keyboard to replytosender:

replyToSender(text,keys) { return this.request('sendMessage',{ 'chat_id': this.update.message.from.id, 'text': text, 'parse_mode': "HTML", 'reply_markup': JSON.stringify(keys) }); }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment