本视频是Telegram Bot 机器人编程系列的第三集。 本集介绍如何根据不同的命令回复不回的内容, 还会介绍怎么把机器人加的群中, 如何在群中使用机器人。
本视频中使用的代码:
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": "你好, 欢迎使用本机器人, 本机器人现在只认识颜色。",
}
if(body.message.text.indexOf("/help") === 0){
payload.text = "你好, 欢迎使用本机器人, 本机器人现在只认识颜色。";
return payload;
}
if(body.message.text.indexOf("/colors") === 0){
payload.text = "红\n黄\n蓝";
return payload;
}
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
}