一. Telegram 机器人的申请和设置图文教程

Telegram 是一个社交聊天软件。 里面有一个很有特色的功能就是机器人。 机器人是由程序控制 的用户。 我们可以写程序来控制这个机器人。 而且写起来也不难哦。

https://core.telegram.org/bots/api#updating-messages

首先在Telegram 里搜索 @botfather

找到后点进去

image001

第一次和机器人对话会有个开始按钮,点一下

img

这时候机器人会弹出一些说明, 英文好的小伙伴其实就可以直接跳过本教程了。

img

现在我们输入 /newbot

img

这时我们要给机器人起个名字, 我这边就随便起啦, 就叫 我的小机器人

然后你要给机器人一个标识, 这个名字是不能改的, 所以要想好, 只能用英文, 而且必须用 bot 结尾, 我这里就叫他 fenggebot

img

输入用户名后, 机器人就申请成功了。 如果你只是要一个可以用的机器人, 到这步就够了。 其中的 bot token: 1287833603:AAGmx9hQq6ViT3km0_77z8psBGqUKfdpSHY 是最重要的部分, 不要让人看到, 否则别人可以控制你的机器人。

然后, 我们还可以给机器人设置其它东西, 这些东西不是必须的,有兴趣的小伙伴请继续往下看吧。

输入 /mybots 列出我的所有机器人

img

点击我刚刚创建的 @fenggebot , 当然,你需要用另一个名字, 因为这个名字已经被我占用了。

然后点击 Edit Bot

img

你会发现除了名字以外, 其它都没有设置

img

如果你想改变名字, 可以点 Edit Name

现在我们先来点 Edit Description, 点完后会提示输入描述,我这里就随便输了

img

点 Back to Bot, 再点 Edit Bot 回到刚才的选单, 这次点机器人的名字

img

我们去看看机器人吧, 发现没有, 你点进机器人的时候, 你就看到你刚设置的那行描述

img

现在点图中的左箭头回到设置, 再点 Edit Bot, 这回看到 Description 已经有了, 再来点 Edit About

img

然后跟据提示输入关于机器人的一些信息

再点 back to bot, 再点 edit bot, 现在 about 也有了, 这次来设置机器人的头像, 点 edit botpic

img

根据提示,发一张图片
img

再点 back to bot, 再点 edit bot, 再点机器人的名字看看
img

机器人有头像啦, 也有资料啦, 回到设置, 这回点 edit commands, 跟据提示输入命令和命令的简介

img

点 back to bot 再点 机器人的名字, 这回我们点开始

在文字输入栏打 /
img

这时就会弹出命令提示, 当然, 现在这些命令是没用的, 只是个提示的作用, 因为机器人还没有写代码

二.汤姆猫机器人, 支持文字, 表情还有图片以及Webhook使用。

SetWebhook 的链接:

https://api.telegram.org/bot这里放机器人的token/setWebhook?url=这里放urlEncode过的谷歌的发布链接

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
// 真是对不起呀, 发布代码的时候我把doGet 给删除了,导致和视频里不一样, 现在加回去。。。
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/bot682267360:AAHmjSil8oylavD2pENLLpcMU1svaD7mVeA/", 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
}

三. Telegram Bot 处理特定的命令

如何根据不同的命令回复不回的内容, 还会介绍怎么把机器人加的群中, 如何在群中使用机器人。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
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/bot682267360:AAHmjSil8oylavD2pENLLpcMU1svaD7mVeA/", 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
}

四. Telegram Bot 处理带参数的命令

如何在一个主命令后增强参数来增强主命令的功能, 我们可以把一个主命令下再加二级命令,甚至三级命令。 这样,我们可以把一些相关的功能都放在同一个主命令底下处理。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
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/bot682267360:AAHmjSil8oylavD2pENLLpcMU1svaD7mVeA/", data);
}
function preparePayload(body){
var payload;

body.message.text = body.message.text.toLowerCase();
body.message.text = body.message.text.replace(/@temptestbot2/g, '');

var paras = body.message.text.trim().split(" ");
// remove empty strings
paras = paras.filter(function(para){
if (para){
return true;
}
});

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;
}

if(body.message.text.indexOf("/list") === 0){
if (paras[1]){
switch (paras[1].toLowerCase()){
case "people":
if (paras[2]){
if ("JS神技能".toLowerCase().indexOf(paras[2]) >= 0){
payload.text = "JS神技能 - https://www.youtube.com/channel/UC6tPP3jOTKgjqfDgqMsaG4g";
}
if ("悟空的日常".toLowerCase().indexOf(paras[2]) >= 0){
payload.text = "悟空的日常 - https://www.youtube.com/channel/UCii04BCvYIdQvshrdNDAcww";
}
if ("YuFeng Deng".toLowerCase().indexOf(paras[2]) >= 0){
payload.text = "YuFeng Deng - https://www.youtube.com/channel/UCG6xoef2xU86hnrCsS5m5Cw";
}
} else {
payload.text = "JS神技能\n"
+ "悟空的日常\n"
+ "YuFeng Deng\n";
return payload;
}
break;
default:
payload.text = "红\n黄\n蓝";
break;
}

return payload;
} else {
payload.text = "JS神技能\n"
+ "悟空的日常\n"
+ "YuFeng Deng\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
}

五. Telegram Bot 发送漂亮的消息,粗体,斜体, 表格,按钮

如何使用Telegram机器人发送漂亮的消息,包据粗体,斜体,链接,按钮,代码,表格等。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
function doGet(e){
return HtmlService.createHtmlOutput("Hello World!! No, this link should be hidden!!!");

// return HtmlService.createHtmlOutputFromFile('Index');
}


function doPost(e){
var body = JSON.parse(e.postData.contents);

body.message.chat.id = body.message.chat.id + '';

var payload = preparePayload(body);
var data = {
"method": "post",
"contentType": 'application/json',
"payload": JSON.stringify(payload),
}

UrlFetchApp.fetch("https://api.telegram.org/bot682267360:AAHmjSil8oylavD2pENLLpcMU1svaD7mVeA/", data);
}
function preparePayload(body){
var payload;

body.message.text = body.message.text.toLowerCase();
body.message.text = body.message.text.replace(/@temptestbot2/g, '');

var paras = body.message.text.trim().split(" ");
// remove empty strings
paras = paras.filter(function(para){
if (para){
return true;
}
});

if (body.message.text){

payload = {
"method": "sendMessage",
"chat_id": body.message.chat.id,
"text": "你好, 欢迎使用本机器人, 本机器人现在只认识颜色。",
"parse_mode": "Markdown",
"disable_web_page_preview": true,
}

if(body.message.text.indexOf("/help") === 0){
payload.text = "你好, 欢迎使用本机器人, 本机器人现在只认识颜色。";
return payload;
}

if(body.message.text.indexOf("/colors") === 0){
payload.text = "红\n黄\n蓝";
return payload;
}

if(body.message.text.indexOf("/list") === 0){
if (paras[1]){
switch (paras[1].toLowerCase()){
case "people":
if (paras[2]){
if ("JS神技能".toLowerCase().indexOf(paras[2]) >= 0){
payload.text = "JS神技能 - https://www.youtube.com/channel/UC6tPP3jOTKgjqfDgqMsaG4g";
}
if ("悟空的日常".toLowerCase().indexOf(paras[2]) >= 0){
payload.text = "悟空的日常 - https://www.youtube.com/channel/UCii04BCvYIdQvshrdNDAcww";
}
if ("YuFeng Deng".toLowerCase().indexOf(paras[2]) >= 0){
payload.text = "YuFeng Deng - https://www.youtube.com/channel/UCG6xoef2xU86hnrCsS5m5Cw";
}
} else {
payload.text = "JS神技能\n"
+ "悟空的日常\n"
+ "YuFeng Deng\n";
return payload;
}
break;
default:
payload.text = "红\n黄\n蓝";
break;
}

return payload;
} else {
payload.text = "*JS神技能*\n"
+ "[悟空的日常](https://www.youtube.com/channel/UCii04BCvYIdQvshrdNDAcww)\n"
+ "[*YuFeng Deng*](https://www.youtube.com/channel/UCG6xoef2xU86hnrCsS5m5Cw)\n"
+ "_YuFeng Deng_\n"
+ "`01|" + "UCii04BCvYIdQvshrdNDAcww" + " | `\n"
+ "`02|" + "UCG6xoef2xU86hnrCsS5m5Cw" + " | `\n"
+ "```javascript\n"
+ 'payload = {\n'
+ ' "method": "sendMessage",\n'
+ ' "chat_id": body.message.chat.id,\n'
+ ' "text": body.message.text,\n'
+ '}'
+ "```"
;

var inlineKeyboardMarkup = {};
inlineKeyboardMarkup.inline_keyboard = [];
var keyboardRow = [];
var keyboardButton1 = {
text: "按钮1",
url: "https://www.google.com"
};

var keyboardButton2 = {
text: "按钮2",
url: "https://www.google.com"
};

var keyboardRow2 = [];
var keyboardButton3 = {
text: "按钮3",
url: "https://www.google.com"
};

var keyboardButton4 = {
text: "按钮4",
url: "https://www.google.com"
};

keyboardRow.push(keyboardButton1);
keyboardRow.push(keyboardButton2);

keyboardRow2.push(keyboardButton3);
keyboardRow2.push(keyboardButton4);
inlineKeyboardMarkup.inline_keyboard.push(keyboardRow);
inlineKeyboardMarkup.inline_keyboard.push(keyboardRow2);
payload.reply_markup = inlineKeyboardMarkup;


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
}

六. Telegram Bot 使用Cloudflare CF worker 制作回声机器人

怎么样在Cloudflare 上用worker 来创建一个Telegram bot 的聊天机器人.当然是最简单的机器人, 只能简单的回复文字, 而且还是同样的汤姆猫机器人, 就是你说什么, 它就说什么.

首先, 我们需要创建一个机器人, 这个就直接看我的TG教程系列的第一集就可以了.

机器人申请好了, 我们来加一下 cf worker 的代码

还没有cloudflare 帐号的小伙伴自己注册一下, 这个很简单,我就不多介绍了.

自己到以下网址注册

https://dash.cloudflare.com/sign-up

然后登录

新建一个 worker 脚本

新建完脚本以后, 是一个简单的hello world 网页, 直接就是工作的.

通过 save and deploy 发布这个网站

到以下这个网址去抄网方的示例POST代码
https://developers.cloudflare.com/workers/templates/snippets/post_data/

抄来的代码最后那段HTML不要, 然后 save and deploy 就可以开作了

只是简单的显示了 The request was a GET

现在我来加入机器人的代码, 只有简单的几行, 非常容易!

粘贴完这段代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
let bodyString = await readRequestBody(request)

try {

let body = JSON.parse(bodyString);

const init = {
headers: { ‘content-type’: ‘application/json’ },
}

if (body.message) {
let payload = {
“method”: “sendMessage”,
“chat_id”: body.message.chat.id,
“text”: “Only echo back text”,
“parse_mode”: “markdown”,
“disable_web_page_preview”: true,
};
if (body.message.text) {
payload.text = body.message.text;
const myInit = {
method: ‘POST’,
headers: {
Content-Type’: ‘application/json’
},
body: JSON.stringify(payload)
};

let myRequest = new
Request(“https://api.telegram.org/bot682267360:AAHmjSil8oylavD2pENLLpcMU1svaD7mVeA/”,
myInit)

//let myRequest = new Request(“https://eaa874bb.ngrok.io”, myInit)
fetch(myRequest).then(x=> {
console.log(x);

});

return new Response(“OK”)
} else {
return new Response(“OK”)
}

} else {
return new Response(JSON.stringify(body), init)
}

}catch(e){
return new Response(e)
}

注册刚才高亮的那段代码, 其中的网址是以下这段, 这里面从bot 开始, 就是机器人的token
https://api.telegram.org/bot682267360:AAHmjSil8oylavD2pENLLpcMU1svaD7mVeA/

注意后面那个 / 非常重要, 不能省略

好了, 现在发布改过的代码

发布完成后, 我们需要绑定机器人, 机器人的网址在这里

https://raspy-sun-ed74.fennng.workers.dev/

为了预防成一, 我们把这个网址做一下 urlencode

网上随便找一个在线的 url encoder , encoder 完是以下的样子

https%3A%2F%2Fraspy-sun-ed74.fennng.workers.dev%2F

现在找到绑定机器人的链接,以下这段是设置机器人的链接, 前面 https://api.telegram.org/bot 这段是固定的,

中间这段 682267360:AAHmjSil8oylavD2pENLLpcMU1svaD7mVeA 是机器人的 token

后面这段是设置机器人链接的方法 /setWebhook?url=

所以我们要把机器人后台链接放在这个链接的最后面

https://api.telegram.org/bot682267360:AAHmjSil8oylavD2pENLLpcMU1svaD7mVeA/setWebhook?url=https%3A%2F%2Fraspy-sun-ed74.fennng.workers.dev%2F

粘贴完后是上面这个样子

现在把这个链接放在浏览器的地址栏打开, 看到以下这个就是绑定成功

{“ok”:true,”result”:true,”description”:”Webhook was set”}

现在我们去试下机器人

工作, 发布成功.

现在来随便改点东西, 简单的加了个签名, 现在再去看看

成功的改了….

很简单吧, 机器人的创建看第一集. 然后, 其它机器人的功能看我关于 谷歌app script 的教程就行了, 差不了多少.

注意的是, cf worker 的 fetch 是 promise, 这点和gas 有很大不同…做简单的机器人可以先不理会. 跟着我的代码写就行了.

七. Telegram Bot 判断群消息的来源和处理有人入群, 有人被踢等

群消息的格式, 原来机器人收到的消息是长这个样子呀。 还有如何处理群通知,比如说有人入群,有人被移出群, 有消息被置顶等

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
function doGet(e){
return HtmlService.createHtmlOutput("Hello World!! No, this link should be hidden!!!");

// return HtmlService.createHtmlOutputFromFile('Index');
}


function doPost(e){
var body = JSON.parse(e.postData.contents);

body.message.chat.id = body.message.chat.id + '';

var payload = preparePayload(body);
var data = {
"method": "post",
"contentType": 'application/json',
"payload": JSON.stringify(payload),
}

UrlFetchApp.fetch("https://api.telegram.org/bot682267360:AAHmjSil8oylavD2pENLLpcMU1svaD7mVeA/", data);
}

function getName(user) {
var name = user.first_name;
if (user.last_name) {
name += " " + user.last_name;
}

return name;
}

function escapeMarkDown(toEscapeMsg) {
var escapedMsg = toEscapeMsg
.replace(/_/g, "\\_")
.replace(/\*/g, "\\*")
.replace(/\[/g, "\\[")
.replace(/`/g, "\\`");
return escapedMsg;

}


function getMentionName(user) {
var username = user.username;
var mentionName = "";

var name = getName(user);
if (!name) {
name = "神秘人";
}

// if (!username) {
mentionName = getMarkDownUserUrl(escapeMarkDown(name), user.id);
// } else {
// mentionName = "[" + escapeMarkDown(name) + "](@" + escapeMarkDown(username) + ")";
// }

return mentionName;
}

function getMarkDownUserUrl(userName, userId) {
return "[" + userName + "](tg://user?id=" + userId + ")";
}


function preparePayload(body){
var payload;

if (body.message.new_chat_member) {
payload = {
"method": "sendMessage",
"chat_id": body.message.chat.id,
"text": "你好, 欢迎加入本群",
"parse_mode": "Markdown",
"disable_web_page_preview": true,
}

payload.text = "你好!" + getMentionName(body.message.new_chat_member) + ", 欢迎加入本群";
return payload;
}

if (body.message.left_chat_member) {
payload = {
"method": "sendMessage",
"chat_id": body.message.chat.id,
"text": "你好, 欢迎加入本群",
"parse_mode": "Markdown",
"disable_web_page_preview": true,
}

payload.text = getMentionName(body.message.left_chat_member) + "君, 一路走好!";
return payload;
}

if (body.message.pinned_message) {
payload = {
"method": "sendMessage",
"chat_id": body.message.chat.id,
"text": "你好, 欢迎加入本群",
"parse_mode": "Markdown",
"disable_web_page_preview": true,
}
var whoPinned = getName(body.message.from);
var whoOwned = getName(body.message.pinned_message.from);

payload.text = whoPinned + "置顶了消息:\n\n" + body.message.pinned_message.text
+ "\n\n"
+ "本BOT代表" + whoOwned + "感谢您"
;
return payload;
}


body.message.text = body.message.text.toLowerCase();
body.message.text = body.message.text.replace(/@temptestbot2/g, '');

var paras = body.message.text.trim().split(" ");
// remove empty strings
paras = paras.filter(function(para){
if (para){
return true;
}
});



if (body.message.text){

payload = {
"method": "sendMessage",
"chat_id": body.message.chat.id,
"text": "你好, 欢迎使用本机器人, 本机器人现在只认识颜色。",
"parse_mode": "Markdown",
"disable_web_page_preview": true,
}

if(body.message.text.indexOf("/help") === 0){
payload.text = "你好, 欢迎使用本机器人, 本机器人现在只认识颜色。";
return payload;
}

if(body.message.text.indexOf("/colors") === 0){
payload.text = "红\n黄\n蓝";
return payload;
}

if(body.message.text.indexOf("/list") === 0){
if (paras[1]){
switch (paras[1].toLowerCase()){
case "people":
if (paras[2]){
if ("JS神技能".toLowerCase().indexOf(paras[2]) >= 0){
payload.text = "JS神技能 - https://www.youtube.com/channel/UC6tPP3jOTKgjqfDgqMsaG4g";
}
if ("悟空的日常".toLowerCase().indexOf(paras[2]) >= 0){
payload.text = "悟空的日常 - https://www.youtube.com/channel/UCii04BCvYIdQvshrdNDAcww";
}
if ("YuFeng Deng".toLowerCase().indexOf(paras[2]) >= 0){
payload.text = "YuFeng Deng - https://www.youtube.com/channel/UCG6xoef2xU86hnrCsS5m5Cw";
}
} else {
payload.text = "JS神技能\n"
+ "悟空的日常\n"
+ "YuFeng Deng\n";
return payload;
}
break;
default:
payload.text = "红\n黄\n蓝";
break;
}

return payload;
} else {
payload.text = "*JS神技能*\n"
+ "[悟空的日常](https://www.youtube.com/channel/UCii04BCvYIdQvshrdNDAcww)\n"
+ "[*YuFeng Deng*](https://www.youtube.com/channel/UCG6xoef2xU86hnrCsS5m5Cw)\n"
+ "_YuFeng Deng_\n"
+ "`01|" + "UCii04BCvYIdQvshrdNDAcww" + " | `\n"
+ "`02|" + "UCG6xoef2xU86hnrCsS5m5Cw" + " | `\n"
+ "```javascript\n"
+ 'payload = {\n'
+ ' "method": "sendMessage",\n'
+ ' "chat_id": body.message.chat.id,\n'
+ ' "text": body.message.text,\n'
+ '}'
+ "```"
;

var inlineKeyboardMarkup = {};
inlineKeyboardMarkup.inline_keyboard = [];
var keyboardRow = [];
var keyboardButton1 = {
text: "按钮1",
url: "https://www.google.com"
};

var keyboardButton2 = {
text: "按钮2",
url: "https://www.google.com"
};

var keyboardRow2 = [];
var keyboardButton3 = {
text: "按钮3",
url: "https://www.google.com"
};

var keyboardButton4 = {
text: "按钮4",
url: "https://www.google.com"
};

keyboardRow.push(keyboardButton1);
keyboardRow.push(keyboardButton2);

keyboardRow2.push(keyboardButton3);
keyboardRow2.push(keyboardButton4);
inlineKeyboardMarkup.inline_keyboard.push(keyboardRow);
inlineKeyboardMarkup.inline_keyboard.push(keyboardRow2);
payload.reply_markup = inlineKeyboardMarkup;


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
}

八.Telegram Bot 连接Mongo DB 数据库, 超酷超好用的JSON数据库, 不需要学SQL啦

如何在谷歌 Google App Scripts 中使用Mongo Db 数据库。 Mongo DB做为文档数据库, 数据的格式为JSON, 也就是和我们机器人处理的消息是同样的格式, 非常的方便, 而且大家也不用学SQL啦。

mongo express 建站代码(可选)

1
2
3
4
5
6
7
8
9
10
docker run -it --rm  ^
--name mongo-express ^
-p 8082:8081 ^
-e ME_CONFIG_MONGODB_PORT="端口" ^
-e ME_CONFIG_MONGODB_SERVER="服务器链接" ^
-e ME_CONFIG_MONGODB_AUTH_DATABASE="mongo" ^
-e ME_CONFIG_MONGODB_AUTH_USERNAME="用户名" ^
-e ME_CONFIG_MONGODB_AUTH_PASSWORD="密码" ^
-e ME_CONFIG_MONGODB_ENABLE_ADMIN="false" ^
mongo-express

代码.gs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
function doGet(e){
return HtmlService.createHtmlOutput("Hello World!! No, this link should be hidden!!!");

// return HtmlService.createHtmlOutputFromFile('Index');
}


function doPost(e){
var body = JSON.parse(e.postData.contents);

body.message.chat.id = body.message.chat.id + '';
mongo.insert(logColl, body);

var payload = preparePayload(body);
var data = {
"method": "post",
"contentType": 'application/json',
"payload": JSON.stringify(payload),
}

mongo.insert("to-telegram", payload);

UrlFetchApp.fetch("https://api.telegram.org/bot682267360:AAHmjSil8oylavD2pENLLpcMU1svaD7mVeA/", data);
}

function getName(user) {
var name = user.first_name;
if (user.last_name) {
name += " " + user.last_name;
}

return name;
}

function escapeMarkDown(toEscapeMsg) {
var escapedMsg = toEscapeMsg
.replace(/_/g, "\\_")
.replace(/\*/g, "\\*")
.replace(/\[/g, "\\[")
.replace(/`/g, "\\`");
return escapedMsg;

}


function getMentionName(user) {
var username = user.username;
var mentionName = "";

var name = getName(user);
if (!name) {
name = "神秘人";
}

// if (!username) {
mentionName = getMarkDownUserUrl(escapeMarkDown(name), user.id);
// } else {
// mentionName = "[" + escapeMarkDown(name) + "](@" + escapeMarkDown(username) + ")";
// }

return mentionName;
}

function getMarkDownUserUrl(userName, userId) {
return "[" + userName + "](tg://user?id=" + userId + ")";
}


function preparePayload(body){
var payload;

if (body.message.new_chat_member) {
payload = {
"method": "sendMessage",
"chat_id": body.message.chat.id,
"text": "你好, 欢迎加入本群",
"parse_mode": "Markdown",
"disable_web_page_preview": true,
}

payload.text = "你好!" + getMentionName(body.message.new_chat_member) + ", 欢迎加入本群";
return payload;
}

if (body.message.left_chat_member) {
payload = {
"method": "sendMessage",
"chat_id": body.message.chat.id,
"text": "你好, 欢迎加入本群",
"parse_mode": "Markdown",
"disable_web_page_preview": true,
}

payload.text = getMentionName(body.message.left_chat_member) + "君, 一路走好!";
return payload;
}

if (body.message.pinned_message) {
payload = {
"method": "sendMessage",
"chat_id": body.message.chat.id,
"text": "你好, 欢迎加入本群",
"parse_mode": "Markdown",
"disable_web_page_preview": true,
}
var whoPinned = getName(body.message.from);
var whoOwned = getName(body.message.pinned_message.from);

payload.text = whoPinned + "置顶了消息:\n\n" + body.message.pinned_message.text
+ "\n\n"
+ "本BOT代表" + whoOwned + "感谢您"
;
return payload;
}


body.message.text = body.message.text.toLowerCase();
body.message.text = body.message.text.replace(/@temptestbot2/g, '');

var paras = body.message.text.trim().split(" ");
// remove empty strings
paras = paras.filter(function(para){
if (para){
return true;
}
});



if (body.message.text){

payload = {
"method": "sendMessage",
"chat_id": body.message.chat.id,
"text": "你好, 欢迎使用本机器人, 本机器人现在只认识颜色。",
"parse_mode": "Markdown",
"disable_web_page_preview": true,
}

if(body.message.text.indexOf("/help") === 0){
payload.text = "你好, 欢迎使用本机器人, 本机器人现在只认识颜色。";
return payload;
}

if(body.message.text.indexOf("/colors") === 0){
payload.text = "红\n黄\n蓝";
return payload;
}

if(body.message.text.indexOf("/list") === 0){
if (paras[1]){
switch (paras[1].toLowerCase()){
case "people":
if (paras[2]){
if ("JS神技能".toLowerCase().indexOf(paras[2]) >= 0){
payload.text = "JS神技能 - https://www.youtube.com/channel/UC6tPP3jOTKgjqfDgqMsaG4g";
}
if ("悟空的日常".toLowerCase().indexOf(paras[2]) >= 0){
payload.text = "悟空的日常 - https://www.youtube.com/channel/UCii04BCvYIdQvshrdNDAcww";
}
if ("YuFeng Deng".toLowerCase().indexOf(paras[2]) >= 0){
payload.text = "YuFeng Deng - https://www.youtube.com/channel/UCG6xoef2xU86hnrCsS5m5Cw";
}
} else {
payload.text = "JS神技能\n"
+ "悟空的日常\n"
+ "YuFeng Deng\n";
return payload;
}
break;
default:
payload.text = "红\n黄\n蓝";
break;
}

return payload;
} else {
payload.text = "*JS神技能*\n"
+ "[悟空的日常](https://www.youtube.com/channel/UCii04BCvYIdQvshrdNDAcww)\n"
+ "[*YuFeng Deng*](https://www.youtube.com/channel/UCG6xoef2xU86hnrCsS5m5Cw)\n"
+ "_YuFeng Deng_\n"
+ "`01|" + "UCii04BCvYIdQvshrdNDAcww" + " | `\n"
+ "`02|" + "UCG6xoef2xU86hnrCsS5m5Cw" + " | `\n"
+ "```javascript\n"
+ 'payload = {\n'
+ ' "method": "sendMessage",\n'
+ ' "chat_id": body.message.chat.id,\n'
+ ' "text": body.message.text,\n'
+ '}'
+ "```"
;

var inlineKeyboardMarkup = {};
inlineKeyboardMarkup.inline_keyboard = [];
var keyboardRow = [];
var keyboardButton1 = {
text: "按钮1",
url: "https://www.google.com"
};

var keyboardButton2 = {
text: "按钮2",
url: "https://www.google.com"
};

var keyboardRow2 = [];
var keyboardButton3 = {
text: "按钮3",
url: "https://www.google.com"
};

var keyboardButton4 = {
text: "按钮4",
url: "https://www.google.com"
};

keyboardRow.push(keyboardButton1);
keyboardRow.push(keyboardButton2);

keyboardRow2.push(keyboardButton3);
keyboardRow2.push(keyboardButton4);
inlineKeyboardMarkup.inline_keyboard.push(keyboardRow);
inlineKeyboardMarkup.inline_keyboard.push(keyboardRow2);
payload.reply_markup = inlineKeyboardMarkup;


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
}

Test.gs

1
2
3
4
5
6
7
8
9
10
var testList = '{"update_id":427274836,"message":{"message_id":173,"from":{"id":539065210,"is_bot":false,"first_name":"Yufeng Deng","last_name":"峰哥","username":"fennng","language_code":"en-US"},"chat":{"id":539065210,"first_name":"Yufeng Deng","last_name":"峰哥","username":"fennng","type":"private"},"date":1538193751,"text":"/list","entities":[{"offset":0,"length":5,"type":"bot_command"}]}}';
var testList2 = '{"update_id":427275035,"message":{"message_id":211,"from":{"id":539065210,"is_bot":false,"first_name":"Yufeng Deng","last_name":"峰哥","username":"fennng","language_code":"en-US"},"chat":{"id":"539065210","first_name":"Yufeng Deng","last_name":"峰哥","username":"fennng","type":"private"},"date":1540807486,"text":"/list","entities":[{"offset":0,"length":5,"type":"bot_command"}]}}';
var isDebug = false;

function debug() {
e = {};
e.postData = {};
e.postData.contents = testList2;
doPost(e);
}

MLab.gs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
var baseUrl = "https://api.mlab.com/api/1/";
var dbUrl = baseUrl + "databases/mongo/";
var collectionUrl = dbUrl + "collections/";

var logColl = "logs";

var mongo = {};

function debugMLab(){
debug();
}

function testMLab(){

var testObject = {"name": "峰哥"};
mongo.insert(logColl, testObject);

}

function testMLab2() {
var query = {"message.from.id": 539065210};
var q = JSON.stringify(query);
var a = mongo.get(logColl, "q=" + q);
var b = a[0];
Logger.log(a);
}


function testMLab3() {
mongo.put(logColl, null, []);
}

mongo.insert = function(collection, data) {
var db = apendAPI(collectionUrl + collection);
var option = getInsertOption(data);
Logger.log(data);
var response = UrlFetchApp.fetch(db, option);
// Logger.log(response);
Logger.log(data);
}

mongo.update = function(collection, query, set) {
var db = apendAPI(collectionUrl + collection);
db += "&" + query + "&m=true&u=true";
var option = getPutOption(set);
UrlFetchApp.fetch(db, option);
}

// Warning, put will override the whole collectoin, put empty array data will clear the whole collection
mongo.put = function(collection, query, data) {
var db = apendAPI(collectionUrl + collection);
if (query){
db += "&" + query;
}
var option = getPutOption(data);
var url = encodeURI(db);
UrlFetchApp.fetch(url, option);
}
mongo.get = function(collection, query) {
var db = apendAPI(collectionUrl + collection);

if (query){
db += "&" + query;
}

var option = getGetOption();
var response = UrlFetchApp.fetch(encodeURI(db), option);

return JSON.parse(response);
}

function apendAPI(url){
return url + "?apiKey=WULdZqaqxqikzrGePcLC5uWBeyvGZqBp";
}


function getInsertOption(data){
var option = {
"method": "post",
'contentType': 'application/json',
// "muteHttpExceptions": true,
"payload": JSON.stringify(data)
}
return option;
}
function getPutOption(data){
var option = {
"method": "put",
'contentType': 'application/json',
"payload": JSON.stringify(data)
}
return option;
}
function getGetOption(){
var option = {
"method": "get",
}
return option;
}

九. Telegram Bot 使用快捷按钮Inline Button, Reply Button和用户交互

如何使用 Reply button 按钮和 Inline button 按钮来跟用户交互。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
function doGet(e){
return HtmlService.createHtmlOutput("Hello World!! No, this link should be hidden!!!");

// return HtmlService.createHtmlOutputFromFile('Index');
}


function doPost(e){
var body = JSON.parse(e.postData.contents);
mongo.insert(logColl, body);




var payload = preparePayload(body);
var data = {
"method": "post",
"contentType": 'application/json',
"payload": JSON.stringify(payload),
}

mongo.insert("to-telegram", payload);

UrlFetchApp.fetch("https://api.telegram.org/bot682267360:AAHmjSil8oylavD2pENLLpcMU1svaD7mVeA/", data);
}

function getName(user) {
var name = user.first_name;
if (user.last_name) {
name += " " + user.last_name;
}

return name;
}

function escapeMarkDown(toEscapeMsg) {
var escapedMsg = toEscapeMsg
.replace(/_/g, "\\_")
.replace(/\*/g, "\\*")
.replace(/\[/g, "\\[")
.replace(/`/g, "\\`");
return escapedMsg;

}


function getMentionName(user) {
var username = user.username;
var mentionName = "";

var name = getName(user);
if (!name) {
name = "神秘人";
}

// if (!username) {
mentionName = getMarkDownUserUrl(escapeMarkDown(name), user.id);
// } else {
// mentionName = "[" + escapeMarkDown(name) + "](@" + escapeMarkDown(username) + ")";
// }

return mentionName;
}

function getMarkDownUserUrl(userName, userId) {
return "[" + userName + "](tg://user?id=" + userId + ")";
}


function preparePayload(body){
var payload;

if (body.message) {
body.message.chat.id = body.message.chat.id + '';
}

if (body.callback_query) {
payload = {
"method": "sendMessage",
"chat_id": body.callback_query.message.chat.id,
"text": "这是一个 callback",
"parse_mode": "Markdown",
"disable_web_page_preview": true,
};



if(body.callback_query.data.indexOf("/help") === 0){
payload.text += ": " + body.callback_query.data;
}

if(body.callback_query.data.indexOf("nihao") === 0){
payload.text = "你好";
}

if(body.callback_query.data.indexOf("update") === 0){

payload = {
"method": "editMessageText",
"chat_id": body.callback_query.message.chat.id,
"message_id": body.callback_query.message.message_id,
"text": "",
"parse_mode": "markdown",
"disable_web_page_preview": false,
};
payload.text = "原消息被更新了";
}

return payload;

}

if (body.message.new_chat_member) {
payload = {
"method": "sendMessage",
"chat_id": body.message.chat.id,
"text": "你好, 欢迎加入本群",
"parse_mode": "Markdown",
"disable_web_page_preview": true,
}

payload.text = "你好!" + getMentionName(body.message.new_chat_member) + ", 欢迎加入本群";
return payload;
}

if (body.message.left_chat_member) {
payload = {
"method": "sendMessage",
"chat_id": body.message.chat.id,
"text": "你好, 欢迎加入本群",
"parse_mode": "Markdown",
"disable_web_page_preview": true,
}

payload.text = getMentionName(body.message.left_chat_member) + "君, 一路走好!";
return payload;
}

if (body.message.pinned_message) {
payload = {
"method": "sendMessage",
"chat_id": body.message.chat.id,
"text": "你好, 欢迎加入本群",
"parse_mode": "Markdown",
"disable_web_page_preview": true,
}
var whoPinned = getName(body.message.from);
var whoOwned = getName(body.message.pinned_message.from);

payload.text = whoPinned + "置顶了消息:\n\n" + body.message.pinned_message.text
+ "\n\n"
+ "本BOT代表" + whoOwned + "感谢您"
;
return payload;
}




if (body.message.text){

//谢谢 kba977 指出这个错误

body.message.text = body.message.text.toLowerCase();
body.message.text = body.message.text.replace(/@temptestbot2/g, '');

var paras = body.message.text.trim().split(" ");
// remove empty strings
paras = paras.filter(function(para){
if (para){
return true;
}
});


payload = {
"method": "sendMessage",
"chat_id": body.message.chat.id,
"text": "你好, 欢迎使用本机器人, 本机器人现在只认识颜色。",
"parse_mode": "Markdown",
"disable_web_page_preview": true,
}

if(body.message.text.indexOf("/removekeyboard") === 0){
var replyKeyboardRemove = {
remove_keyboard: true,
selective: false
};
payload.reply_markup = replyKeyboardRemove;
return payload;
}

if(body.message.text.indexOf("/help") === 0){
var mentionName = getMentionName(body.message.from);
payload.text = "您好!" + mentionName + "! ";
payload.text += "欢迎使用本机器人, 本机器人现在只认识颜色。";

var command9 = [
"/colors",
"/list",
];

var replyKeyboardMarkup = {};
replyKeyboardMarkup.keyboard = [];
replyKeyboardMarkup.resize_keyboard = false;
replyKeyboardMarkup.one_time_keyboard = true;
replyKeyboardMarkup.selective = true;

var count = 0;
for (var i = 0; i < command9.length / 3; i++) {
var keyboardRow = [];
for (var j = 0; j < 3; j++) {
var keyboardButton = {
text: command9[i * 3 + j],
};
count++;
keyboardRow.push(keyboardButton);
if (count >= command9.length) {
break;
}

}
replyKeyboardMarkup.keyboard.push(keyboardRow);
}
payload.reply_markup = replyKeyboardMarkup;


return payload;
}

if(body.message.text.indexOf("/colors") === 0){
payload.text = "红\n黄\n蓝";
return payload;
}

if(body.message.text.indexOf("/list") === 0){
if (paras[1]){
switch (paras[1].toLowerCase()){
case "people":
if (paras[2]){
if ("JS神技能".toLowerCase().indexOf(paras[2]) >= 0){
payload.text = "JS神技能 - https://www.youtube.com/channel/UC6tPP3jOTKgjqfDgqMsaG4g";
}
if ("悟空的日常".toLowerCase().indexOf(paras[2]) >= 0){
payload.text = "悟空的日常 - https://www.youtube.com/channel/UCii04BCvYIdQvshrdNDAcww";
}
if ("YuFeng Deng".toLowerCase().indexOf(paras[2]) >= 0){
payload.text = "YuFeng Deng - https://www.youtube.com/channel/UCG6xoef2xU86hnrCsS5m5Cw";
}
} else {
payload.text = "JS神技能\n"
+ "悟空的日常\n"
+ "YuFeng Deng\n";
return payload;
}
break;
default:
payload.text = "红\n黄\n蓝";
break;
}

return payload;
} else {
payload.text = "*JS神技能*\n"
+ "[悟空的日常](https://www.youtube.com/channel/UCii04BCvYIdQvshrdNDAcww)\n"
+ "[*YuFeng Deng*](https://www.youtube.com/channel/UCG6xoef2xU86hnrCsS5m5Cw)\n"
+ "_YuFeng Deng_\n"
+ "`01|" + "UCii04BCvYIdQvshrdNDAcww" + " | `\n"
+ "`02|" + "UCG6xoef2xU86hnrCsS5m5Cw" + " | `\n"
+ "```javascript\n"
+ 'payload = {\n'
+ ' "method": "sendMessage",\n'
+ ' "chat_id": body.message.chat.id,\n'
+ ' "text": body.message.text,\n'
+ '}'
+ "```"
;

var inlineKeyboardMarkup = {};
inlineKeyboardMarkup.inline_keyboard = [];
var keyboardRow = [];
var keyboardButton1 = {
text: "Help",
callback_data: "/help"
};

var keyboardButton2 = {
text: "按钮2",
callback_data: "nihao"
};

var keyboardRow2 = [];
var keyboardButton3 = {
text: "升级原消息",
callback_data: "update"
};

var keyboardButton4 = {
text: "按钮4",
url: "https://www.google.com"
};

keyboardRow.push(keyboardButton1);
keyboardRow.push(keyboardButton2);

keyboardRow2.push(keyboardButton3);
keyboardRow2.push(keyboardButton4);
inlineKeyboardMarkup.inline_keyboard.push(keyboardRow);
inlineKeyboardMarkup.inline_keyboard.push(keyboardRow2);
payload.reply_markup = inlineKeyboardMarkup;


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
}

Test.gs

1
2
3
4
5
6
7
8
9
10
var testList = '{"update_id":427274836,"message":{"message_id":173,"from":{"id":539065210,"is_bot":false,"first_name":"Yufeng Deng","last_name":"峰哥","username":"fennng","language_code":"en-US"},"chat":{"id":539065210,"first_name":"Yufeng Deng","last_name":"峰哥","username":"fennng","type":"private"},"date":1538193751,"text":"/list","entities":[{"offset":0,"length":5,"type":"bot_command"}]}}';
var testList2 = '{"update_id":427275035,"message":{"message_id":211,"from":{"id":539065210,"is_bot":false,"first_name":"Yufeng Deng","last_name":"峰哥","username":"fennng","language_code":"en-US"},"chat":{"id":"539065210","first_name":"Yufeng Deng","last_name":"峰哥","username":"fennng","type":"private"},"date":1540807486,"text":"/help","entities":[{"offset":0,"length":5,"type":"bot_command"}]}}';
var isDebug = false;

function debug() {
e = {};
e.postData = {};
e.postData.contents = testList2;
doPost(e);
}

MLab.gs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
var baseUrl = "https://api.mlab.com/api/1/";
var dbUrl = baseUrl + "databases/mongo/";
var collectionUrl = dbUrl + "collections/";

var logColl = "logs";

var mongo = {};

function debugMLab(){
debug();
}

function testMLab(){

var testObject = {"name": "峰哥"};
mongo.insert(logColl, testObject);

}

function testMLab2() {
var query = {"message.from.id": 539065210};
var q = JSON.stringify(query);
var a = mongo.get(logColl, "q=" + q);
var b = a[0];
Logger.log(a);
}


function testMLab3() {
mongo.put(logColl, null, []);
}

mongo.insert = function(collection, data) {
var db = apendAPI(collectionUrl + collection);
var option = getInsertOption(data);
Logger.log(data);
var response = UrlFetchApp.fetch(db, option);
// Logger.log(response);
Logger.log(data);
}

mongo.update = function(collection, query, set) {
var db = apendAPI(collectionUrl + collection);
db += "&" + query + "&m=true&u=true";
var option = getPutOption(set);
UrlFetchApp.fetch(db, option);
}

// Warning, put will override the whole collectoin, put empty array data will clear the whole collection
mongo.put = function(collection, query, data) {
var db = apendAPI(collectionUrl + collection);
if (query){
db += "&" + query;
}
var option = getPutOption(data);
var url = encodeURI(db);
UrlFetchApp.fetch(url, option);
}
mongo.get = function(collection, query) {
var db = apendAPI(collectionUrl + collection);

if (query){
db += "&" + query;
}

var option = getGetOption();
var response = UrlFetchApp.fetch(encodeURI(db), option);

return JSON.parse(response);
}

function apendAPI(url){
return url + "?apiKey=WULdZqaqxqikzrGePcLC5uWBeyvGZqBp";
}


function getInsertOption(data){
var option = {
"method": "post",
'contentType': 'application/json',
// "muteHttpExceptions": true,
"payload": JSON.stringify(data)
}
return option;
}
function getPutOption(data){
var option = {
"method": "put",
'contentType': 'application/json',
"payload": JSON.stringify(data)
}
return option;
}
function getGetOption(){
var option = {
"method": "get",
}
return option;
}

十. Telegram Bot 从代码给机器人发送多条指令,发送欢迎消息后,删除前一条欢迎消息示例 | 数据库查询 | 调试进阶

如何使用在发送一条欢迎消息的同时,删除前一条欢迎消息。 同时视频中有对数据库查询,调试等进阶操作。

代码.gs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
function doGet(e){
return HtmlService.createHtmlOutput("Hello World!! No, this link should be hidden!!!");

// return HtmlService.createHtmlOutputFromFile('Index');
}


function doPost(e){
var body = JSON.parse(e.postData.contents);
mongo.insert(logColl, body);

var payload = preparePayload(body);

var payloads;

if (Array.isArray(payload)){
payloads = payload;
} else {
payloads = [payload]
}

for (var i = 0; i < payloads.length; i++){
payload = payloads[i];
if (payload){
var res = postTelegram(payload);
}
}


}

function postTelegram(payload) {
var data = {
'contentType': 'application/json',
"method": "post",
"payload": JSON.stringify(payload)
}

mongo.insert("to-telegram", payload);
var response = UrlFetchApp.fetch("https://api.telegram.org/bot682267360:AAHmjSil8oylavD2pENLLpcMU1svaD7mVeA/", data);
var res = JSON.parse(response);
mongo.insert("telegram-response", res);
return res;
}

function getName(user) {
var name = user.first_name;
if (user.last_name) {
name += " " + user.last_name;
}

return name;
}

function escapeMarkDown(toEscapeMsg) {
var escapedMsg = toEscapeMsg
.replace(/_/g, "\\_")
.replace(/\*/g, "\\*")
.replace(/\[/g, "\\[")
.replace(/`/g, "\\`");
return escapedMsg;

}


function getMentionName(user) {
var username = user.username;
var mentionName = "";

var name = getName(user);
if (!name) {
name = "神秘人";
}

// if (!username) {
mentionName = getMarkDownUserUrl(escapeMarkDown(name), user.id);
// } else {
// mentionName = "[" + escapeMarkDown(name) + "](@" + escapeMarkDown(username) + ")";
// }

return mentionName;
}

function getMarkDownUserUrl(userName, userId) {
return "[" + userName + "](tg://user?id=" + userId + ")";
}

function getLastWelcomeMessage(){
var regex = "欢迎加入本群";
var regexSearch = { "$regex": regex, "$options": 'i' };
var searchString = {"result.text": regexSearch};

var q = JSON.stringify(searchString);

var sortObject = {
"result.date": -1
};

var s = JSON.stringify(sortObject);

var httpQuery = "q=" + q + "&s=" + s + "&l=1";

var lastWelcomeMessage = mongo.get("telegram-response", httpQuery);
return lastWelcomeMessage;
}


function preparePayload(body){
var payload;

if (body.message) {
body.message.chat.id = body.message.chat.id + '';
}

if (body.callback_query) {
payload = {
"method": "sendMessage",
"chat_id": body.callback_query.message.chat.id,
"text": "这是一个 callback",
"parse_mode": "Markdown",
"disable_web_page_preview": true,
};



if(body.callback_query.data.indexOf("/help") === 0){
payload.text += ": " + body.callback_query.data;
}

if(body.callback_query.data.indexOf("nihao") === 0){
payload.text = "你好";
}

if(body.callback_query.data.indexOf("update") === 0){

payload = {
"method": "editMessageText",
"chat_id": body.callback_query.message.chat.id,
"message_id": body.callback_query.message.message_id,
"text": "",
"parse_mode": "markdown",
"disable_web_page_preview": false,
};
payload.text = "原消息被更新了";
}

return payload;

}

if (body.message.new_chat_member) {
payload = {
"method": "sendMessage",
"chat_id": body.message.chat.id,
"text": "你好, 欢迎加入本群",
"parse_mode": "Markdown",
"disable_web_page_preview": true,
}

payload.text = "你好!" + getMentionName(body.message.new_chat_member) + ", 欢迎加入本群";



var payloads = [];
payloads.push(payload);

var lastWelcomeMessage = getLastWelcomeMessage();
if (lastWelcomeMessage.length == 1){
var messageId = lastWelcomeMessage[0].result.message_id;
var payload2 = {
"method": "deleteMessage",
"message_id": messageId,
"chat_id": body.message.chat.id
};

payloads.push(payload2);
}


return payloads;
}

if (body.message.left_chat_member) {
payload = {
"method": "sendMessage",
"chat_id": body.message.chat.id,
"text": "你好, 欢迎加入本群",
"parse_mode": "Markdown",
"disable_web_page_preview": true,
}

payload.text = getMentionName(body.message.left_chat_member) + "君, 一路走好!";
return payload;
}

if (body.message.pinned_message) {
payload = {
"method": "sendMessage",
"chat_id": body.message.chat.id,
"text": "你好, 欢迎加入本群",
"parse_mode": "Markdown",
"disable_web_page_preview": true,
}
var whoPinned = getName(body.message.from);
var whoOwned = getName(body.message.pinned_message.from);

payload.text = whoPinned + "置顶了消息:\n\n" + body.message.pinned_message.text
+ "\n\n"
+ "本BOT代表" + whoOwned + "感谢您"
;
return payload;
}




if (body.message.text){

//谢谢 kba977 指出这个错误

body.message.text = body.message.text.toLowerCase();
body.message.text = body.message.text.replace(/@temptestbot2/g, '');

var paras = body.message.text.trim().split(" ");
// remove empty strings
paras = paras.filter(function(para){
if (para){
return true;
}
});


payload = {
"method": "sendMessage",
"chat_id": body.message.chat.id,
"text": "你好, 欢迎使用本机器人, 本机器人现在只认识颜色。",
"parse_mode": "Markdown",
"disable_web_page_preview": true,
}

if(body.message.text.indexOf("/removekeyboard") === 0){
var replyKeyboardRemove = {
remove_keyboard: true,
selective: false
};
payload.reply_markup = replyKeyboardRemove;
return payload;
}

if(body.message.text.indexOf("/help") === 0){
var mentionName = getMentionName(body.message.from);
payload.text = "您好!" + mentionName + "! ";
payload.text += "欢迎使用本机器人, 本机器人现在只认识颜色。";

var command9 = [
"/colors",
"/list",
];

var replyKeyboardMarkup = {};
replyKeyboardMarkup.keyboard = [];
replyKeyboardMarkup.resize_keyboard = false;
replyKeyboardMarkup.one_time_keyboard = true;
replyKeyboardMarkup.selective = true;

var count = 0;
for (var i = 0; i < command9.length / 3; i++) {
var keyboardRow = [];
for (var j = 0; j < 3; j++) {
var keyboardButton = {
text: command9[i * 3 + j],
};
count++;
keyboardRow.push(keyboardButton);
if (count >= command9.length) {
break;
}

}
replyKeyboardMarkup.keyboard.push(keyboardRow);
}
payload.reply_markup = replyKeyboardMarkup;


return payload;
}

if(body.message.text.indexOf("/colors") === 0){
payload.text = "红\n黄\n蓝";
return payload;
}

if(body.message.text.indexOf("/list") === 0){
if (paras[1]){
switch (paras[1].toLowerCase()){
case "people":
if (paras[2]){
if ("JS神技能".toLowerCase().indexOf(paras[2]) >= 0){
payload.text = "JS神技能 - https://www.youtube.com/channel/UC6tPP3jOTKgjqfDgqMsaG4g";
}
if ("悟空的日常".toLowerCase().indexOf(paras[2]) >= 0){
payload.text = "悟空的日常 - https://www.youtube.com/channel/UCii04BCvYIdQvshrdNDAcww";
}
if ("YuFeng Deng".toLowerCase().indexOf(paras[2]) >= 0){
payload.text = "YuFeng Deng - https://www.youtube.com/channel/UCG6xoef2xU86hnrCsS5m5Cw";
}
} else {
payload.text = "JS神技能\n"
+ "悟空的日常\n"
+ "YuFeng Deng\n";
return payload;
}
break;
default:
payload.text = "红\n黄\n蓝";
break;
}

return payload;
} else {
payload.text = "*JS神技能*\n"
+ "[悟空的日常](https://www.youtube.com/channel/UCii04BCvYIdQvshrdNDAcww)\n"
+ "[*YuFeng Deng*](https://www.youtube.com/channel/UCG6xoef2xU86hnrCsS5m5Cw)\n"
+ "_YuFeng Deng_\n"
+ "`01|" + "UCii04BCvYIdQvshrdNDAcww" + " | `\n"
+ "`02|" + "UCG6xoef2xU86hnrCsS5m5Cw" + " | `\n"
+ "```javascript\n"
+ 'payload = {\n'
+ ' "method": "sendMessage",\n'
+ ' "chat_id": body.message.chat.id,\n'
+ ' "text": body.message.text,\n'
+ '}'
+ "```"
;

var inlineKeyboardMarkup = {};
inlineKeyboardMarkup.inline_keyboard = [];
var keyboardRow = [];
var keyboardButton1 = {
text: "Help",
callback_data: "/help"
};

var keyboardButton2 = {
text: "按钮2",
callback_data: "nihao"
};

var keyboardRow2 = [];
var keyboardButton3 = {
text: "升级原消息",
callback_data: "update"
};

var keyboardButton4 = {
text: "按钮4",
url: "https://www.google.com"
};

keyboardRow.push(keyboardButton1);
keyboardRow.push(keyboardButton2);

keyboardRow2.push(keyboardButton3);
keyboardRow2.push(keyboardButton4);
inlineKeyboardMarkup.inline_keyboard.push(keyboardRow);
inlineKeyboardMarkup.inline_keyboard.push(keyboardRow2);
payload.reply_markup = inlineKeyboardMarkup;


var payloads = [];

var payload2 = {};

var payloadStr = JSON.stringify(payload);
payload2 = JSON.parse(payloadStr);

payloads.push(payload);
// payloads.push(payload2);

return payloads;
}
}



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
}

Mlab.gs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
var baseUrl = "https://api.mlab.com/api/1/";
var dbUrl = baseUrl + "databases/mongo/";
var collectionUrl = dbUrl + "collections/";

var logColl = "logs";

var mongo = {};

function debugMLab(){
debug();
}

function testMLab(){

var testObject = {"name": "峰哥"};
mongo.insert(logColl, testObject);

}

function testMLab2() {
var query = {"message.from.id": 539065210};
var q = JSON.stringify(query);
var a = mongo.get(logColl, "q=" + q);
var b = a[0];
Logger.log(a);
}


function testMLab3() {
mongo.put(logColl, null, []);
}

mongo.insert = function(collection, data) {
var db = apendAPI(collectionUrl + collection);
var option = getInsertOption(data);
Logger.log(data);
var response = UrlFetchApp.fetch(db, option);
// Logger.log(response);
Logger.log(data);
}

mongo.update = function(collection, query, set) {
var db = apendAPI(collectionUrl + collection);
db += "&" + query + "&m=true&u=true";
var option = getPutOption(set);
UrlFetchApp.fetch(db, option);
}

// Warning, put will override the whole collectoin, put empty array data will clear the whole collection
mongo.put = function(collection, query, data) {
var db = apendAPI(collectionUrl + collection);
if (query){
db += "&" + query;
}
var option = getPutOption(data);
var url = encodeURI(db);
UrlFetchApp.fetch(url, option);
}
mongo.get = function(collection, query) {
var db = apendAPI(collectionUrl + collection);

if (query){
db += "&" + query;
}

var option = getGetOption();
var response = UrlFetchApp.fetch(encodeURI(db), option);

return JSON.parse(response);
}

function apendAPI(url){
return url + "?apiKey=WULdZqaqxqikzrGePcLC5uWBeyvGZqBp";
}


function getInsertOption(data){
var option = {
"method": "post",
'contentType': 'application/json',
// "muteHttpExceptions": true,
"payload": JSON.stringify(data)
}
return option;
}
function getPutOption(data){
var option = {
"method": "put",
'contentType': 'application/json',
"payload": JSON.stringify(data)
}
return option;
}
function getGetOption(){
var option = {
"method": "get",
}
return option;
}

Test.gs

1
2
3
4
5
6
7
8
9
10
var testList = '{"update_id":427274836,"message":{"message_id":173,"from":{"id":539065210,"is_bot":false,"first_name":"Yufeng Deng","last_name":"峰哥","username":"fennng","language_code":"en-US"},"chat":{"id":539065210,"first_name":"Yufeng Deng","last_name":"峰哥","username":"fennng","type":"private"},"date":1538193751,"text":"/list","entities":[{"offset":0,"length":5,"type":"bot_command"}]}}';
var testList2 = '{"update_id":427275035,"message":{"message_id":211,"from":{"id":539065210,"is_bot":false,"first_name":"Yufeng Deng","last_name":"峰哥","username":"fennng","language_code":"en-US"},"chat":{"id":"539065210","first_name":"Yufeng Deng","last_name":"峰哥","username":"fennng","type":"private"},"date":1540807486,"text":"/help","entities":[{"offset":0,"length":5,"type":"bot_command"}]}}';
var isDebug = false;

function debug() {
e = {};
e.postData = {};
e.postData.contents = testList2;
doPost(e);
}

十一.Telegram Bot 高级应用 -集成其它服务 – 谷歌Youtube Data API 示例

如何将Telegram 机器人和其它的服务集成, 本集用Youtube Data API 作为示例

代码.gs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
function debugCode(){
debug();
}

function doGet(e){
return HtmlService.createHtmlOutput("Hello World!! No, this link should be hidden!!!");

// return HtmlService.createHtmlOutputFromFile('Index');
}


function doPost(e){
var body = JSON.parse(e.postData.contents);
// 没有数据库的小伙伴可以删除以下这行
mongo.insert(logColl, body);

var payload = preparePayload(body);

var payloads;

if (Array.isArray(payload)){
payloads = payload;
} else {
payloads = [payload]
}

for (var i = 0; i < payloads.length; i++){
payload = payloads[i];
if (payload){
var res = postTelegram(payload);
}
}


}

function postTelegram(payload) {
var data = {
'contentType': 'application/json',
"method": "post",
"payload": JSON.stringify(payload)
}

// 没有数据库的小伙伴可以删除以下这行
mongo.insert("to-telegram", payload);
var response = UrlFetchApp.fetch("https://api.telegram.org/bot682267360:AAHmjSil8oylavD2pENLLpcMU1svaD7mVeA/", data);
var res = JSON.parse(response);
// 没有数据库的小伙伴可以删除以下这行
mongo.insert("telegram-response", res);
return res;
}

function getName(user) {
var name = user.first_name;
if (user.last_name) {
name += " " + user.last_name;
}

return name;
}

function escapeMarkDown(toEscapeMsg) {
var escapedMsg = toEscapeMsg
.replace(/_/g, "\\_")
.replace(/\*/g, "\\*")
.replace(/\[/g, "\\[")
.replace(/`/g, "\\`");
return escapedMsg;

}


function getMentionName(user) {
var username = user.username;
var mentionName = "";

var name = getName(user);
if (!name) {
name = "神秘人";
}

// if (!username) {
mentionName = getMarkDownUserUrl(escapeMarkDown(name), user.id);
// } else {
// mentionName = "[" + escapeMarkDown(name) + "](@" + escapeMarkDown(username) + ")";
// }

return mentionName;
}

function getMarkDownUserUrl(userName, userId) {
return "[" + userName + "](tg://user?id=" + userId + ")";
}

function getLastWelcomeMessage(){
var regex = "欢迎加入本群";
var regexSearch = { "$regex": regex, "$options": 'i' };
var searchString = {"result.text": regexSearch};

var q = JSON.stringify(searchString);

var sortObject = {
"result.date": -1
};

var s = JSON.stringify(sortObject);

var httpQuery = "q=" + q + "&s=" + s + "&l=1";

var lastWelcomeMessage = mongo.get("telegram-response", httpQuery);
return lastWelcomeMessage;
}


function preparePayload(body){
var payload;

if (body.message) {
body.message.chat.id = body.message.chat.id + '';
}

if (body.callback_query) {
payload = {
"method": "sendMessage",
"chat_id": body.callback_query.message.chat.id,
"text": "这是一个 callback",
"parse_mode": "Markdown",
"disable_web_page_preview": true,
};



if(body.callback_query.data.indexOf("/help") === 0){
payload.text += ": " + body.callback_query.data;
}

if(body.callback_query.data.indexOf("nihao") === 0){
payload.text = "你好";
}

if(body.callback_query.data.indexOf("update") === 0){

payload = {
"method": "editMessageText",
"chat_id": body.callback_query.message.chat.id,
"message_id": body.callback_query.message.message_id,
"text": "",
"parse_mode": "markdown",
"disable_web_page_preview": false,
};
payload.text = "原消息被更新了";
}

return payload;

}

if (body.message.new_chat_member) {
payload = {
"method": "sendMessage",
"chat_id": body.message.chat.id,
"text": "你好, 欢迎加入本群",
"parse_mode": "Markdown",
"disable_web_page_preview": true,
}

payload.text = "你好!" + getMentionName(body.message.new_chat_member) + ", 欢迎加入本群";



var payloads = [];
payloads.push(payload);

var lastWelcomeMessage = getLastWelcomeMessage();
if (lastWelcomeMessage.length == 1){
var messageId = lastWelcomeMessage[0].result.message_id;
var payload2 = {
"method": "deleteMessage",
"message_id": messageId,
"chat_id": body.message.chat.id
};

payloads.push(payload2);
}


return payloads;
}

if (body.message.left_chat_member) {
payload = {
"method": "sendMessage",
"chat_id": body.message.chat.id,
"text": "你好, 欢迎加入本群",
"parse_mode": "Markdown",
"disable_web_page_preview": true,
}

payload.text = getMentionName(body.message.left_chat_member) + "君, 一路走好!";
return payload;
}

if (body.message.pinned_message) {
payload = {
"method": "sendMessage",
"chat_id": body.message.chat.id,
"text": "你好, 欢迎加入本群",
"parse_mode": "Markdown",
"disable_web_page_preview": true,
}
var whoPinned = getName(body.message.from);
var whoOwned = getName(body.message.pinned_message.from);

payload.text = whoPinned + "置顶了消息:\n\n" + body.message.pinned_message.text
+ "\n\n"
+ "本BOT代表" + whoOwned + "感谢您"
;
return payload;
}




if (body.message.text){

//谢谢 kba977 指出这个错误

var origParas = body.message.text.trim().split(" ");
origParas = origParas.filter(function(origPara){
if (origPara){
return true;
}
});

body.message.text = body.message.text.toLowerCase();
body.message.text = body.message.text.replace(/@temptestbot2/g, '');

var paras = body.message.text.trim().split(" ");
// remove empty strings
paras = paras.filter(function(para){
if (para){
return true;
}
});


payload = {
"method": "sendMessage",
"chat_id": body.message.chat.id,
"text": "你好, 欢迎使用本机器人, 本机器人现在只认识颜色。",
"parse_mode": "Markdown",
"disable_web_page_preview": true,
}

if(body.message.text.indexOf("/removekeyboard") === 0){
var replyKeyboardRemove = {
remove_keyboard: true,
selective: false
};
payload.reply_markup = replyKeyboardRemove;
return payload;
}

if(body.message.text.indexOf("/help") === 0){
var mentionName = getMentionName(body.message.from);
payload.text = "您好!" + mentionName + "! ";
payload.text += "欢迎使用本机器人, 本机器人现在只认识颜色。";

var command9 = [
"/colors",
"/list",
];

var replyKeyboardMarkup = {};
replyKeyboardMarkup.keyboard = [];
replyKeyboardMarkup.resize_keyboard = false;
replyKeyboardMarkup.one_time_keyboard = true;
replyKeyboardMarkup.selective = true;

var count = 0;
for (var i = 0; i < command9.length / 3; i++) {
var keyboardRow = [];
for (var j = 0; j < 3; j++) {
var keyboardButton = {
text: command9[i * 3 + j],
};
count++;
keyboardRow.push(keyboardButton);
if (count >= command9.length) {
break;
}

}
replyKeyboardMarkup.keyboard.push(keyboardRow);
}
payload.reply_markup = replyKeyboardMarkup;


return payload;
}

if(body.message.text.indexOf("/colors") === 0){
payload.text = "红\n黄\n蓝";
return payload;
}

if(body.message.text.indexOf("/searchvideo") === 0){
if (paras[1]){
var videoId = origParas[1];
var videos = videosListById('snippet,contentDetails,statistics', {'id': videoId});
var video = videos.items[0];
payload.text = "标题: " + video.snippet.title + "\n";
return payload;
}
payload.text = "请提供视频ID";
return payload;
}

if(body.message.text.indexOf("/list") === 0){
if (paras[1]){
switch (paras[1].toLowerCase()){
case "people":
if (paras[2]){
if ("JS神技能".toLowerCase().indexOf(paras[2]) >= 0){
payload.text = "JS神技能 - https://www.youtube.com/channel/UC6tPP3jOTKgjqfDgqMsaG4g";
}
if ("悟空的日常".toLowerCase().indexOf(paras[2]) >= 0){
payload.text = "悟空的日常 - https://www.youtube.com/channel/UCii04BCvYIdQvshrdNDAcww";
}
if ("YuFeng Deng".toLowerCase().indexOf(paras[2]) >= 0){
payload.text = "YuFeng Deng - https://www.youtube.com/channel/UCG6xoef2xU86hnrCsS5m5Cw";
}
} else {
payload.text = "JS神技能\n"
+ "悟空的日常\n"
+ "YuFeng Deng\n";
return payload;
}
break;
default:
payload.text = "红\n黄\n蓝";
break;
}

return payload;
} else {
payload.text = "*JS神技能*\n"
+ "[悟空的日常](https://www.youtube.com/channel/UCii04BCvYIdQvshrdNDAcww)\n"
+ "[*YuFeng Deng*](https://www.youtube.com/channel/UCG6xoef2xU86hnrCsS5m5Cw)\n"
+ "_YuFeng Deng_\n"
+ "`01|" + "UCii04BCvYIdQvshrdNDAcww" + " | `\n"
+ "`02|" + "UCG6xoef2xU86hnrCsS5m5Cw" + " | `\n"
+ "```javascript\n"
+ 'payload = {\n'
+ ' "method": "sendMessage",\n'
+ ' "chat_id": body.message.chat.id,\n'
+ ' "text": body.message.text,\n'
+ '}'
+ "```"
;

var inlineKeyboardMarkup = {};
inlineKeyboardMarkup.inline_keyboard = [];
var keyboardRow = [];
var keyboardButton1 = {
text: "Help",
callback_data: "/help"
};

var keyboardButton2 = {
text: "按钮2",
callback_data: "nihao"
};

var keyboardRow2 = [];
var keyboardButton3 = {
text: "升级原消息",
callback_data: "update"
};

var keyboardButton4 = {
text: "按钮4",
url: "https://www.google.com"
};

keyboardRow.push(keyboardButton1);
keyboardRow.push(keyboardButton2);

keyboardRow2.push(keyboardButton3);
keyboardRow2.push(keyboardButton4);
inlineKeyboardMarkup.inline_keyboard.push(keyboardRow);
inlineKeyboardMarkup.inline_keyboard.push(keyboardRow2);
payload.reply_markup = inlineKeyboardMarkup;


var payloads = [];

var payload2 = {};

var payloadStr = JSON.stringify(payload);
payload2 = JSON.parse(payloadStr);

payloads.push(payload);
// payloads.push(payload2);

return payloads;
}
}



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
}

Mlab.gs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
var baseUrl = "https://api.mlab.com/api/1/";
var dbUrl = baseUrl + "databases/mongo/";
var collectionUrl = dbUrl + "collections/";

var logColl = "logs";

var mongo = {};

function debugMLab(){
debug();
}

function testMLab(){

var testObject = {"name": "峰哥"};
mongo.insert(logColl, testObject);

}

function testMLab2() {
var query = {"message.from.id": 539065210};
var q = JSON.stringify(query);
var a = mongo.get(logColl, "q=" + q);
var b = a[0];
Logger.log(a);
}


function testMLab3() {
mongo.put(logColl, null, []);
}

mongo.insert = function(collection, data) {
var db = apendAPI(collectionUrl + collection);
var option = getInsertOption(data);
Logger.log(data);
var response = UrlFetchApp.fetch(db, option);
// Logger.log(response);
Logger.log(data);
}

mongo.update = function(collection, query, set) {
var db = apendAPI(collectionUrl + collection);
db += "&" + query + "&m=true&u=true";
var option = getPutOption(set);
UrlFetchApp.fetch(db, option);
}

// Warning, put will override the whole collectoin, put empty array data will clear the whole collection
mongo.put = function(collection, query, data) {
var db = apendAPI(collectionUrl + collection);
if (query){
db += "&" + query;
}
var option = getPutOption(data);
var url = encodeURI(db);
UrlFetchApp.fetch(url, option);
}
mongo.get = function(collection, query) {
var db = apendAPI(collectionUrl + collection);

if (query){
db += "&" + query;
}

var option = getGetOption();
var response = UrlFetchApp.fetch(encodeURI(db), option);

return JSON.parse(response);
}

function apendAPI(url){
return url + "?apiKey=WULdZqaqxqikzrGePcLC5uWBeyvGZqBp";
}


function getInsertOption(data){
var option = {
"method": "post",
'contentType': 'application/json',
// "muteHttpExceptions": true,
"payload": JSON.stringify(data)
}
return option;
}
function getPutOption(data){
var option = {
"method": "put",
'contentType': 'application/json',
"payload": JSON.stringify(data)
}
return option;
}
function getGetOption(){
var option = {
"method": "get",
}
return option;
}

Youtube.gs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
/****** START BOILERPLATE CODE ******/

// <b>Note:</b> Apps Script automatically requests authorization
// based on the API's used in the code.

// Build an object from an object containing properties as key-value pairs
function createResource(properties) {
var res = {};
var normalizedProps = {};
for (var p in properties) {
var value = properties[p];
if (p.substr(-2, 2) == '[]' && value) {
var adjustedName = p.replace('[]', '');
normalizedProps[adjustedName] = value.split(',');
} else {
normalizedProps[p] = value;
}
}
for (var p in normalizedProps) {
if (normalizedProps.hasOwnProperty(p) && normalizedProps[p]) {
var propArray = p.split('.');
var ref = res;
for (var pa = 0; pa < propArray.length; pa++) {
var key = propArray[pa];
if (pa == propArray.length - 1) {
ref[key] = normalizedProps[p];
} else {
ref = ref[key] = ref[key] || {};
}
}
};
}
return res;
}

// Remove parameters that don't have values before sending API request
function removeEmptyParams(params) {
for (var p in params) {
if (!params[p] || params[p] == 'undefined') {
delete params[p];
}
}
return params;
}

// Sample Apps Script code for printing API response data

function printResults(response) {
Logger.log(response);
}
/***** END BOILERPLATE CODE *****/

// Sample appsscript code for videos.list

function videosListById(part, params) {
params = removeEmptyParams(params); // See full sample for function

var response = YouTube.Videos.list(part,
params);
printResults(response);
return response;
}

function TestYoutube() {
videosListById('snippet,contentDetails,statistics', {'id': 'Ks-_Mh1QhMc'});
}

Test.gs

1
2
3
4
5
6
7
8
9
10
11
12
var testList = '{"update_id":427274836,"message":{"message_id":173,"from":{"id":539065210,"is_bot":false,"first_name":"Yufeng Deng","last_name":"峰哥","username":"fennng","language_code":"en-US"},"chat":{"id":539065210,"first_name":"Yufeng Deng","last_name":"峰哥","username":"fennng","type":"private"},"date":1538193751,"text":"/list","entities":[{"offset":0,"length":5,"type":"bot_command"}]}}';
var testList2 = '{"update_id":427275035,"message":{"message_id":211,"from":{"id":539065210,"is_bot":false,"first_name":"Yufeng Deng","last_name":"峰哥","username":"fennng","language_code":"en-US"},"chat":{"id":"539065210","first_name":"Yufeng Deng","last_name":"峰哥","username":"fennng","type":"private"},"date":1540807486,"text":"/help","entities":[{"offset":0,"length":5,"type":"bot_command"}]}}';
var testSearchVideo = '{"update_id":427275035,"message":{"message_id":211,"from":{"id":539065210,"is_bot":false,"first_name":"Yufeng Deng","last_name":"峰哥","username":"fennng","language_code":"en-US"},"chat":{"id":"539065210","first_name":"Yufeng Deng","last_name":"峰哥","username":"fennng","type":"private"},"date":1540807486,"text":"/searchVideo Ri938AvTOGc","entities":[{"offset":0,"length":5,"type":"bot_command"}]}}';

var isDebug = false;

function debug() {
e = {};
e.postData = {};
e.postData.contents = testSearchVideo;
doPost(e);
}

十二.Telegram Bot 使用机器人管理群,限制用户,踢出用户

如何使用机器人来管理群, 本集演示了机器人限制用户和踢出用户的方法

这次只改动了 代码.gs 文件, 其它的文件请到上集的贴子里找

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
function debugCode(){
debug();
}

function doGet(e){
return HtmlService.createHtmlOutput("Hello World!! No, this link should be hidden!!!");

// return HtmlService.createHtmlOutputFromFile('Index');
}


function doPost(e){
var body = JSON.parse(e.postData.contents);
mongo.insert(logColl, body);

var payload = preparePayload(body);

var payloads;

if (Array.isArray(payload)){
payloads = payload;
} else {
payloads = [payload]
}

for (var i = 0; i < payloads.length; i++){
payload = payloads[i];
if (payload){
var res = postTelegram(payload);
}
}


}

function postTelegram(payload) {
var data = {
'contentType': 'application/json',
"method": "post",
"payload": JSON.stringify(payload)
}

mongo.insert("to-telegram", payload);
var response = UrlFetchApp.fetch("https://api.telegram.org/bot682267360:AAHmjSil8oylavD2pENLLpcMU1svaD7mVeA/", data);
var res = JSON.parse(response);
mongo.insert("telegram-response", res);
return res;
}

function getName(user) {
var name = user.first_name;
if (user.last_name) {
name += " " + user.last_name;
}

return name;
}

function escapeMarkDown(toEscapeMsg) {
var escapedMsg = toEscapeMsg
.replace(/_/g, "\\_")
.replace(/\*/g, "\\*")
.replace(/\[/g, "\\[")
.replace(/`/g, "\\`");
return escapedMsg;

}


function getMentionName(user) {
var username = user.username;
var mentionName = "";

var name = getName(user);
if (!name) {
name = "神秘人";
}

// if (!username) {
mentionName = getMarkDownUserUrl(escapeMarkDown(name), user.id);
// } else {
// mentionName = "[" + escapeMarkDown(name) + "](@" + escapeMarkDown(username) + ")";
// }

return mentionName;
}

function getMarkDownUserUrl(userName, userId) {
return "[" + userName + "](tg://user?id=" + userId + ")";
}

function getLastWelcomeMessage(){
var regex = "欢迎加入本群";
var regexSearch = { "$regex": regex, "$options": 'i' };
var searchString = {"result.text": regexSearch};

var q = JSON.stringify(searchString);

var sortObject = {
"result.date": -1
};

var s = JSON.stringify(sortObject);

var httpQuery = "q=" + q + "&s=" + s + "&l=1";

var lastWelcomeMessage = mongo.get("telegram-response", httpQuery);
return lastWelcomeMessage;
}


function preparePayload(body){
var payload;

if (body.message) {
body.message.chat.id = body.message.chat.id + '';
}

if (body.callback_query) {
payload = {
"method": "sendMessage",
"chat_id": body.callback_query.message.chat.id,
"text": "这是一个 callback",
"parse_mode": "Markdown",
"disable_web_page_preview": true,
};



if(body.callback_query.data.indexOf("/help") === 0){
payload.text += ": " + body.callback_query.data;
}

if(body.callback_query.data.indexOf("nihao") === 0){
payload.text = "你好";
}

if(body.callback_query.data.indexOf("update") === 0){

payload = {
"method": "editMessageText",
"chat_id": body.callback_query.message.chat.id,
"message_id": body.callback_query.message.message_id,
"text": "",
"parse_mode": "markdown",
"disable_web_page_preview": false,
};
payload.text = "原消息被更新了";
}

return payload;

}

if (body.message.new_chat_member) {
var payload2 = {
"method": "restrictChatMember",
"chat_id": body.message.chat.id,
"user_id": body.message.new_chat_member.id,
"can_send_messages": false,
"can_send_media_messages": false,
"can_send_other_messages": false,
"can_add_web_page_previews": false,
};

var payload4 = {
"method": "kickChatMember",
"chat_id": body.message.chat.id,
"user_id": body.message.new_chat_member.id,
};


var payloads = [];

if (getName(body.message.new_chat_member).indexOf("广告") >= 0) {
payloads.push(payload4);
}



return payloads;
}

if (body.message.left_chat_member) {
payload = {
"method": "sendMessage",
"chat_id": body.message.chat.id,
"text": "你好, 欢迎加入本群",
"parse_mode": "Markdown",
"disable_web_page_preview": true,
}

payload.text = getMentionName(body.message.left_chat_member) + "君, 一路走好!";
return payload;
}

if (body.message.pinned_message) {
payload = {
"method": "sendMessage",
"chat_id": body.message.chat.id,
"text": "你好, 欢迎加入本群",
"parse_mode": "Markdown",
"disable_web_page_preview": true,
}
var whoPinned = getName(body.message.from);
var whoOwned = getName(body.message.pinned_message.from);

payload.text = whoPinned + "置顶了消息:\n\n" + body.message.pinned_message.text
+ "\n\n"
+ "本BOT代表" + whoOwned + "感谢您"
;
return payload;
}




if (body.message.text){

//谢谢 kba977 指出这个错误

var origParas = body.message.text.trim().split(" ");
origParas = origParas.filter(function(origPara){
if (origPara){
return true;
}
});

body.message.text = body.message.text.toLowerCase();
body.message.text = body.message.text.replace(/@temptestbot2/g, '');

var paras = body.message.text.trim().split(" ");
// remove empty strings
paras = paras.filter(function(para){
if (para){
return true;
}
});


payload = {
"method": "sendMessage",
"chat_id": body.message.chat.id,
"text": "你好, 欢迎使用本机器人, 本机器人现在只认识颜色。",
"parse_mode": "Markdown",
"disable_web_page_preview": true,
}

if(body.message.text.indexOf("/removekeyboard") === 0){
var replyKeyboardRemove = {
remove_keyboard: true,
selective: false
};
payload.reply_markup = replyKeyboardRemove;
return payload;
}

if(body.message.text.indexOf("/help") === 0){
var mentionName = getMentionName(body.message.from);
payload.text = "您好!" + mentionName + "! ";
payload.text += "欢迎使用本机器人, 本机器人现在只认识颜色。";

var command9 = [
"/colors",
"/list",
];

var replyKeyboardMarkup = {};
replyKeyboardMarkup.keyboard = [];
replyKeyboardMarkup.resize_keyboard = false;
replyKeyboardMarkup.one_time_keyboard = true;
replyKeyboardMarkup.selective = true;

var count = 0;
for (var i = 0; i < command9.length / 3; i++) {
var keyboardRow = [];
for (var j = 0; j < 3; j++) {
var keyboardButton = {
text: command9[i * 3 + j],
};
count++;
keyboardRow.push(keyboardButton);
if (count >= command9.length) {
break;
}

}
replyKeyboardMarkup.keyboard.push(keyboardRow);
}
payload.reply_markup = replyKeyboardMarkup;


return payload;
}

if(body.message.text.indexOf("/colors") === 0){
payload.text = "红\n黄\n蓝";
return payload;
}

if(body.message.text.indexOf("/searchvideo") === 0){
if (paras[1]){
var videoId = origParas[1];
var videos = videosListById('snippet,contentDetails,statistics', {'id': videoId});
var video = videos.items[0];
payload.text = "标题: " + video.snippet.title + "\n";
return payload;
}
payload.text = "请提供视频ID";
return payload;
}

if(body.message.text.indexOf("/list") === 0){
if (paras[1]){
switch (paras[1].toLowerCase()){
case "people":
if (paras[2]){
if ("JS神技能".toLowerCase().indexOf(paras[2]) >= 0){
payload.text = "JS神技能 - https://www.youtube.com/channel/UC6tPP3jOTKgjqfDgqMsaG4g";
}
if ("悟空的日常".toLowerCase().indexOf(paras[2]) >= 0){
payload.text = "悟空的日常 - https://www.youtube.com/channel/UCii04BCvYIdQvshrdNDAcww";
}
if ("YuFeng Deng".toLowerCase().indexOf(paras[2]) >= 0){
payload.text = "YuFeng Deng - https://www.youtube.com/channel/UCG6xoef2xU86hnrCsS5m5Cw";
}
} else {
payload.text = "JS神技能\n"
+ "悟空的日常\n"
+ "YuFeng Deng\n";
return payload;
}
break;
default:
payload.text = "红\n黄\n蓝";
break;
}

return payload;
} else {
payload.text = "*JS神技能*\n"
+ "[悟空的日常](https://www.youtube.com/channel/UCii04BCvYIdQvshrdNDAcww)\n"
+ "[*YuFeng Deng*](https://www.youtube.com/channel/UCG6xoef2xU86hnrCsS5m5Cw)\n"
+ "_YuFeng Deng_\n"
+ "`01|" + "UCii04BCvYIdQvshrdNDAcww" + " | `\n"
+ "`02|" + "UCG6xoef2xU86hnrCsS5m5Cw" + " | `\n"
+ "```javascript\n"
+ 'payload = {\n'
+ ' "method": "sendMessage",\n'
+ ' "chat_id": body.message.chat.id,\n'
+ ' "text": body.message.text,\n'
+ '}'
+ "```"
;

var inlineKeyboardMarkup = {};
inlineKeyboardMarkup.inline_keyboard = [];
var keyboardRow = [];
var keyboardButton1 = {
text: "Help",
callback_data: "/help"
};

var keyboardButton2 = {
text: "按钮2",
callback_data: "nihao"
};

var keyboardRow2 = [];
var keyboardButton3 = {
text: "升级原消息",
callback_data: "update"
};

var keyboardButton4 = {
text: "按钮4",
url: "https://www.google.com"
};

keyboardRow.push(keyboardButton1);
keyboardRow.push(keyboardButton2);

keyboardRow2.push(keyboardButton3);
keyboardRow2.push(keyboardButton4);
inlineKeyboardMarkup.inline_keyboard.push(keyboardRow);
inlineKeyboardMarkup.inline_keyboard.push(keyboardRow2);
payload.reply_markup = inlineKeyboardMarkup;


var payloads = [];

var payload2 = {};

var payloadStr = JSON.stringify(payload);
payload2 = JSON.parse(payloadStr);

payloads.push(payload);
// payloads.push(payload2);

return payloads;
}
}



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
}

十三.Telegram Bot 使用机器人定时发送消息与图片

如何让Telegram 机器人定时的发送消息和图片, 因为我教大家写的机器人是用谷歌app script 写的, 所以这件事变得非常的容易 。 今天这个视频就来讲讲怎么样做到定时发送。

没有动的代码请到上节课的贴子找

手动触发代码

1
2
3
4
if (e.parameter.runAutoTask){
AutoTask();
return HtmlService.createHtmlOutput(e.parameter.runAutoTask);
}

定时任务

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
function AutoSendMessage() {
var payload = {
"method": "sendMessage",
"chat_id": 539065210,
"text": "这是一条定时发送的文字消息",
"parse_mode": "Markdown",
"disable_web_page_preview": true,
};
postTelegram(payload);
}

function postTelegram(payload) {
var data = {
'contentType': 'application/json',
"method": "post",
"payload": JSON.stringify(payload)
}

// 没有数据库的小伙伴可以删除以下这行
mongo.insert("to-telegram", payload);
var response = UrlFetchApp.fetch("https://api.telegram.org/bot682267360:AAHmjSil8oylavD2pENLLpcMU1svaD7mVeA/", data);
var res = JSON.parse(response);
// 没有数据库的小伙伴可以删除以下这行
mongo.insert("telegram-response", res);
return res;
}
function AutoSendPhoto() {
var payload = {
"method": "sendPhoto",
"chat_id": 539065210,
"photo": "AgADAQAD_qcxGziKyEdxR2ejIuaEQshmDDAABAdOS7wVW7MAAR7LAwABAg"
};

postTelegram(payload);
}


function AutoTask() {
AutoSendMessage();
AutoSendPhoto();
}

十四.Telegram Bot 电报聊天机器人连接 RestHeart MongoDB 数据库

如何使用机器人来连接 RestHeart Mongo DB.

只提供新的 Restheart.gs 文件, 其它文件请看之前的视频, 跳着看是不行地

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
var mongo;
var restheart = {};
var restheartUrl = "https://restheart.dengnz.com/user2/";

restheart.insert = function(collection, data) {
var db = restheartUrl + collection;
var option = getInsertOption(data);
var response = UrlFetchApp.fetch(db, option);
};

function testRestHeart(){
// restheart.replace("to-telegram", null, {desc: "record all message send
to telegram chat"});
// restheart.replace("telegram-response", null, {desc: "record all message
return from telegram"});
// restheart.replace("logs", null, {desc: "record some other logs"});
var data = {test: 'test2'};
restheart.insert("logs", data);

// var data = {test: 'test replace'};
// restheart.replace("testColl/5c75be5e294610d3cbaa39f9", null, data);

// var data = {test: 'test get'};
// restheart.get("testColl/5c75be5e294610d3cbaa39f9", null, data);
//
// var data = {test: 'test set'};
// restheart.set("testColl/5c75be5e294610d3cbaa39f9", null, data);


// var data = {"$addToSet":{"array" : "bar2"}};
// restheart.setOne("testColl/5c75be5e294610d3cbaa39f9", data);
}

restheart.replace = function(collection, query, data) {
var db = restheartUrl + collection;
if (query){
db += "?" + query;
}
var option = getPutOption(data);
var url = encodeURI(db);
UrlFetchApp.fetch(url, option);
};

restheart.setOne = function(urlWithId, data) {
var db = restheartUrl + urlWithId;
var option = getPatchOption(data);
option.muteHttpExceptions = true;
var url = encodeURI(db);
var response = UrlFetchApp.fetch(encodeURI(db), option);
}

restheart.setMany = function(collection, query, data) {
var db = restheartUrl + collection;
if (query){
db += "/*?" + query;
}
var option = getPatchOption(data);
var url = encodeURI(db);
UrlFetchApp.fetch(url, option);
}

restheart.set = restheart.setMany;
restheart.remove = function(collection, query) {
var db = restheartUrl + collection;
if (query){
db += "/*?" + query;
}
var option = getDeleteOption();
var url = encodeURI(db);
UrlFetchApp.fetch(url, option);
}

restheart.get = function(collection, query) {
var db = restheartUrl + collection;

if (query){
db += "?" + query;
}

var option = getGetOption();
var response = UrlFetchApp.fetch(encodeURI(db), option);

var contentText = response.getContentText();
var responseString = JSON.stringify(response);

var object = JSON.parse(response);
return object;
}

mongo = restheart;



function getInsertOption(data){
var option = {
"method": "post",
'contentType': 'application/json',
'headers': {"Authorization": "Basic " + Utilities.base64Encode('user2'
+ ":" + 'changeit')},
"muteHttpExceptions": true,
"payload": JSON.stringify(data)
};
return option;
}
function getDeleteOption(){
var option = {
"method": "delete",
'contentType': 'application/json',
'headers': {"Authorization": "Basic " + Utilities.base64Encode('user2'
+ ":" + 'changeit')},
};
return option;
}
function getPutOption(data){
var option = {
"method": "put",
'contentType': 'application/json',
'headers': {"Authorization": "Basic " + Utilities.base64Encode('user2'
+ ":" + 'changeit')},
"payload": JSON.stringify(data)
};
return option;
}
function getPatchOption(data){
var option = {
"method": "patch",
'contentType': 'application/json',
'headers': {"Authorization": "Basic " + Utilities.base64Encode('user2'
+ ":" + 'changeit')},
"payload": JSON.stringify(data)
};
return option;
}
function getGetOption(){
var option = {
"method": "get",
'headers': {"Authorization": "Basic " + Utilities.base64Encode('user2'
+ ":" + 'changeit')},
};
return option;
}

十五.Telegram聊天软件 如何用机器人自动回复,回答常见问题, 删除脏话,踢人,禁言,警告用户等 (支持图片和动图)