本视频是Telegram Bot 机器人编程系列的第二集。 本集介绍如何用简单不到60行的代码实现一个汤姆猫机器人, 就是你说什么, 它就说什么。 支持文字, 表情还有图片。谷歌 script.google.com
相关的代码请翻到下面
本视频中使用的代码:
Set Webhook 的链接:
https://api.telegram.org/bot这里放机器人的token/setWebhook?url=这里放urlEncode过的谷歌的发布链接
代码如下:
function doGet(e){
return HtmlService.createHtmlOutput("Hello World!! No, this link should be hidden!!!");
}
function doPost(e){
var dataFromTelegram = {
"method": "post",
"payload": e.postData.contents
}
var body = JSON.parse(e.postData.contents);
body.message.chat.id = body.message.chat.id + '';
var payload = preparePayload(body);
var data = {
"method": "post",
"payload": payload
}
var dataToTelegram = {
"method": "post",
"payload": payload
}
UrlFetchApp.fetch("https://api.telegram.org/bot这里放机器人的token/", data);
}
function preparePayload(body){
var payload;
if (body.message.text){
payload = {
"method": "sendMessage",
"chat_id": body.message.chat.id,
"text": body.message.text,
}
}
else if (body.message.sticker){
payload = {
"method": "sendSticker",
"chat_id": body.message.chat.id,
"sticker": body.message.sticker.file_id
}
}
else if (body.message.photo){
array = body.message.photo;
text = array[1];
payload = {
"method": "sendPhoto",
"chat_id": body.message.chat.id,
"photo": text.file_id
}
}
else {
payload = {
"method": "sendMessage",
"chat_id": body.message.chat.id,
"text": "Try other stuff"
}
}
return payload
}