Skip to content

Instantly share code, notes, and snippets.

@oshliaer
Last active July 16, 2019 10:46
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save oshliaer/77ccc68599e7b0fea39f to your computer and use it in GitHub Desktop.
Save oshliaer/77ccc68599e7b0fea39f to your computer and use it in GitHub Desktop.
oshlibot

oshlibot

  • Как вызвать бота? В Telegram ник @oshlibot

  • Как запустить своего бота? Скопировать код. Получить apikey. Добавить apikey в свойства скрипта. Опубликовать скрипт как веб-приложение для всех. Запустить вручную setWebhook() из модуля ScriptService.gs

  • Важно. В настройках необходимо в свойства скрипта добавить apikey

  • Как получить apikey? Необходимо спросить у @BotFather

  • Какие бывают способы доступа для бота? Два метода API определяют будущее поведение приложения: getUpdates или setWebhook

  • @oshlibot использует подписку на Webhooks

function doPost(e) {
var contents = JSON.parse(e.postData.contents);
try {
//log([JSON.stringify(e), JSON.stringify(contents)]);
actions(contents);
} catch (err) {
var params = {
chat_id: contents.message.chat.id,
text: err.message
};
sendMessage(params);
}
}
function actions(contents) {
var cmd = contents.message.text.split(' ')[0];
var text = '';
var params = {};
params.chat_id = contents.message.chat.id;
switch (cmd) {
case '/new':
if (contents.message.text.length <= 5) {
text = 'Отправьте команду /new с параметрами. Например, /new тестовая строка'
} else {
recordDoc('@' + contents.message.from.username + ': ' + contents.message.text.substring(5));
text = 'Сообщение добавлено';
}
break;
case '/l10':
text = getL10();
break;
case '/doc':
text = 'https://goo.gl/hMWMrN';
break;
case '/start':
text = getInstructions();
break;
case '/help':
text = getInstructions();
break;
default:
params.reply_to_message_id = contents.message.message_id;
if (cmd.charAt(0) === '/') text = 'Неизвестная команда ' + cmd;
}
if (text == '') return;
params.text = text;
sendMessage(params);
}
function api(METHOD_NAME) {
log(['https://api.telegram.org/bot' + getApiKey() + '/' + METHOD_NAME]);
return 'https://api.telegram.org/bot' + getApiKey() + '/' + METHOD_NAME
}
function sendMessage(params) {
var uf = UrlFetchApp.fetch(api('sendMessage') + '?' + params.serialize(), {
muteHttpExceptions: true
});
}
Object.prototype.serialize = function() {
var str = [];
for (var p in this)
if (this.hasOwnProperty(p)) {
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(this[p]));
}
return str.join("&");
}
function getInstructions() {
var text = '';
text += 'Этот бот предназначен для записи сообщений в его файл https://goo.gl/hMWMrN' + '\n';
text += 'Введите команду /new [текст сообщения]';
return text;
}
function recordDoc(text){
var doc = DocumentApp.openByUrl('https://docs.google.com/document/d/1xySCgcpAUvtHxcEEvjimVjFxPFtHI_VJnUFKS3RVwiw/edit?usp=sharing');
doc.getBody().insertParagraph(0, text);
return 1;
}
function getL10(){
var doc = DocumentApp.openByUrl('https://docs.google.com/document/d/1xySCgcpAUvtHxcEEvjimVjFxPFtHI_VJnUFKS3RVwiw/edit?usp=sharing');
var ps = doc.getBody().getParagraphs();
var text = '';
var j = 0;
while(j < 10 && j < ps.length){
text += ps[j].getText() + '\n';
j++;
}
return text;
}
function getScriptURL(){
return ScriptApp.getService().getUrl();
}
function setWebhook(){
var uf = UrlFetchApp.fetch(api('setWebhook') + '?url=' + getScriptURL());
}
function disableWebhook(){
var uf = UrlFetchApp.fetch(api('setWebhook') + '?url=');
}
function getApiKey(){
return PropertiesService.getScriptProperties().getProperty('apikey');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment