Skip to content

Instantly share code, notes, and snippets.

@unnikked
Last active February 19, 2024 02:58
Show Gist options
  • Star 45 You must be signed in to star a gist
  • Fork 9 You must be signed in to fork a gist
  • 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");
}
@linglung
Copy link

linglung commented Jun 16, 2018

Script function not found: doGet

anyway, you forgot to put your URL blog
To read the full blog post please click here.

@destaa
Copy link

destaa commented Sep 20, 2018

hi.. i'm totally newbie in this and github as well..
but i want to ask, how if i simply put command: /balance
and inside that command i want to add function to check dogecoin balance from api in dogechain.info

what i want to ask, how we listen to message input from user, and integrate it in the command?
the step that i want:

  • if user type command /balance, they will recieve message from us "please insert address:"
  • user replying with valid dogecoin address
  • we listen to that reply, integrate to dogechain api
  • user get dogecoin balance based on address they input

to integrate command /balance and the function, i use this code..is it right?
bus.on(//balance/, input);

and i create function
function input(address) {
this.replyToSender("please insert address:");

var address = function (bot) {
return this.update.message.text;
};

var url = 'https://dogechain.info/api/v1/address/balance/';

if (address) url += address;

var data = JSON.parse(UrlFetchApp.fetch(url).getContentText());
this.replyToSender(data.balance);
}

is this function correct? i tried it with declare var address as fixed address, as shows:
var address = ("A5i4GW7muSLhmAbYvZ2ycHEQMsA4AHHg1c");
it's working, with user typing command /balance,
it shows dogecoin balance from address A5i4GW7muSLhmAbYvZ2ycHEQMsA4AHHg1c

but how if we want to use user's input as var = address?

@arashsoftco
Copy link

Script function not found: doGet

???

@samjia12
Copy link

hello, thanks for the sharing.
i am complete new of coding, if i want to build my own code, except change "token=XXX", what else do I need to change in order to make it run?

@aasoloviov
Copy link

Мне необходимо сделать интеграцию, а точнее написать код для телеграмм бота.

Задача следующая:
Чтобы после введения пользователем команды, например /name, бот выдавал сообщение "Введите Ваше имя" и добавлял текст следующего сообщения пользователя в ячейку гугл таблицы, например в столбец "А".
Также и со следующей командой, например /mail, бот выдавал сообщение "Введите вашу эл. почту". Пользователь вводил бы сообщение, а бот добавлял ее в другую ячейку гугл таблицы, например в столбец B.

Вроде легко должно быть, но у меня не получается.

С помощью следующего кода, бот каждое сообщение вводит в гугл таблицу в столбец "А". И выводит после него сообщение "Привет, Вася (пример), спасибо за сообщение".

А мне нужно, чтобы вводил в разные столбцы в зависимости от предыдущей команды.

function doPost(e) {
var update = JSON.parse(e.postData.contents);
// проверяем тип полученного, нам нужен только тип "сообщение"
if (update.hasOwnProperty('message')) {
var msg = update.message;
var chatId = msg.chat.id;
// this is where telegram works
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 + " " + data.message.chat.last_name;
var answer = "Привет " + name + ", спасибо за сообщение " + text;
sendText(id,answer);
SpreadsheetApp.openById(ssId).getSheets()[0].appendRow([text,new Date(),id,name,answer]);
}
}

Как мне это сделать? Что для этого нужно? Заранее благодарю за ответ.

@e-labInnovations
Copy link

Awesome idea

Please add more features like sendPhotos, inlineKeyboard, buttons and actions etc

@titoprab2511
Copy link

hallo, is thats possible send data to my website database? i try but always stuck and error ,,
but i run it by specify function its work
i test also my script on my server to catch it its work

can u explain whats wrong is this? thanks you so much

@sunuazizrahayu
Copy link

setWebhook() was invalid, you must use labeled URL Current web app URL and ends in /exec
the log of ScriptApp.getService().getUrl() is ......../dev

@joshhamon
Copy link

I get no responses from the bot. Beyond changing the token and setting the webhook, are their additional steps?

@Venya-sudo
Copy link

Я должен сделать интеграцию, чтобы написать код для телеграмм бота.

Задача следующая: чтобы
после того, как были представлены команды, например / имя, бот выдавал сообщение "введите ваше имя" и добавили текстовые сообщения пользователя в ячейку таблицы, например в столбец "А".
Например, бот отправил сообщение "Введите вашу эл. Почту". Пользователь вводит сообщение, например, в столбец Б.

Вроде легко должно быть, но у меня не получается.

С помощью следующего кода, каждое сообщение вводится в таблицу в столбце "А". Привет, Вася (пример), спасибо за сообщение.

Команда должна быть в зависимости от предыдущей команды.

function doPost (e) {
var update = JSON.parse (e.postData.contents);
// проверяем тип полученного, нам нужен только тип "сообщения"
if (update.hasOwnProperty ('message')) {
var msg = update.message;
var chatId = msg.chat.id;
// здесь работает телеграмма
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 + "" + data.message.chat.last_name;
var answer = "Привет" + name + ", спасибо за сообщение" + text;
SendText (идентификатор, ответ);
SpreadsheetApp.openById (ssId) .getSheets () [0] .appendRow ([текст, новая дата (), идентификатор, имя, ответ]);
}
}

Как мне это сделать? Что для этого нужно? Заранее благодарю за ответ.

У вас получилось это сделать? мне тоже такое необходимо, ломаю голову)

@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