-
Notifications
You must be signed in to change notification settings - Fork 2
/
mk
executable file
·425 lines (358 loc) · 9.22 KB
/
mk
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
#!/bin/bash
#
# Synopsis
# This is a small collection of tools to help manage and
# test `now` deployments
# Author
# Erick Calder <[email protected]>
# Notes
# For information on usage please refer to the Medium article:
# https://medium.com/@ekkis/building-a-telegram-bot-in-node-js-now-6daea82ca425
#
help() {
cat <<- "EOF"
mk [-d] [command]
where <command> may be:
logs - shows deployment logs for your project
msg [-] <command> <chat_id> <from> - sends a message to your server
bind - binds your server to the Telegram bot using web hooks
bind info - shows binding information
bind rm - removes the existing binding
clearqueue - useful to wipe out messages stuck in the queue
secret <key> <value> - installs a secret (appends to the .env)
secrets - install all secrets in your .env file
scaffold - creates a skeleton bot in your project directory
kill - kills running local servers
To see the actual statements issued by this script when running
a command prefix the command with -d:
$ mk -d bind
To build a deployment just run this script without arguments:
$ mk
For your first deployment, supply the bot key:
$mk --bot-key 743460589:AAFNkaZ0X3_51dZTuctsK0RrM9fKCRS22Ds
-- messaging --
For development you can run your bot using `npm start`. You can send
messages to it from the command line as shown below. If you want the bot
to actually send messages to a Telegram chat, set the TELEGRAM_BOT_CHATID
with a valid value in your environment. You can also optionally set the
TELEGRAM_BOT_USERNAME variable if you want to send a specific username in
the messages.
To ping the local server:
$ mk msg -l "/ping" # local
After deployment (hosted on Now) you can message the bot with `-b`:
$ mk msg -b "/ping" # deployed
You can also message Telegram directly. Hers's how:
$ mk msg -t "/ping" # Telegram
and for sending test messages with images to the bot, supply a valid file id
to the -p parameter:
$ mk msg -b "/ping" -p "AgADAQADaqgxGyX5yETF2DyyOFrdN_9sDDAABO6I-45utcxCSBoEAAEC"
Contact info can also be sent like this:
$ mk msg -t "#" -c "+1 (800) 555-1212"
-- environment --
To be compatible with the VSCode debugger, environment files cannot include the EXPORT
statement, without which subshells cannot see the values. The command below thus allows
you to initialise your environment from one of these files:
$ eval `mk env`
You can also create all the secrets needed for your deployment from the environment
file by running the following command:
$ mk secrets
The script will also indicate any secrets required by your deployment that are missing
from your environment file
-- examples --
To show current bindings:
$ mk bind info
To set a secret with credentials for your database:
$ mk secret "DATABASE_AUTH" "JohnDoe:SomePassword"
You can then check that the secret was also added to the environment file:
$ cat .env
EOF
exit 0
}
msg() {
[ -z "$TELEGRAM_BOT_CHATID" ] && {
warn="WARNING: Environment variable TELEGRAM_BOT_CHATID not set!"
warn="$warn No messages will be sent to Telegram"
echo -e "\033[33m$warn\033[0m"
}
srv=$1; cmd=$2; type=$3; args=$4
chat_id=$TELEGRAM_BOT_CHATID
bot_nm=$TELEGRAM_BOT_USERNAME
d=$(msg_data $srv "$cmd" "$chat_id" "$bot_nm" "$type" "$args")
method="?bot=$TELEGRAM_BOT_KEY"
if [ "$srv" == "-t" ]; then
case $type in
"-p") method="sendPhoto" ;;
"-d") method="sendDocument" ;;
*) method="sendMessage" ;;
esac
fi
fetch $method $srv -d "'$d'" $(hdr -j)
}
bind() {
[ "$1" == "rm" ] && {
fetch "/deleteWebhook" -t; return
}
[ "$1" == "info" ] && {
fetch "/getWebhookInfo" -t; return
}
#d='{"url": "%s", "allowed_updates": ["message", "channel_post"]}'
d=$(printf '{"url": "%s"}' "$(cat .url)/server.js?bot=$TELEGRAM_BOT_KEY")
fetch "/setWebhook" -t -d "'$d'" $(hdr -j)
}
clearqueue() {
bind rm
id=$(fetch "/getUpdates" -t 2>/dev/null |jq .result[-1].update_id)
id=$(echo "$id+1" |bc)
fetch "/getUpdates" -t "-F 'offset=$id'"
bind
}
secret() {
key=$1; val=$2
now secret add "$key" "$val"
[ $? -eq 0 ] && {
key=$(echo $key| sed 's/-/_/g' |awk '{print toupper($0)}')
echo "$key=$val" >> .env
}
}
secrets() {
script=$(cat <<- EOF
const fs = require('fs')
const jsp = require('js-prototype-lib')
jsp.install('string', 'object')
const now = require('./now.json').env;
const env = fs.readFileSync('./.env', 'utf8')
.replace(/^export\s+/gm, '')
.keyval()
var val = env.map((self, k, acc) => {
if (now[k] && env[k]) {
acc[now[k].replace(/^@/, '')] = env[k].q('')
}
})
var rm = val.keys().map(k => 'echo Y | now secret rm ' + k)
.join('\n')
var add = val.keyval(' ')
.replace(/^/gm, 'now secret add ')
var missing = now.notIn(env);
console.log(rm)
console.log(add)
console.log("echo -e '\n* Environment set up (" + val.keys().length + " keys installed)'")
if (missing.length > 0) {
console.log("echo '\nThe following keys are missing from your environment'")
console.log("echo 'file for your deployment to work:'")
console.log("echo '\n * " + missing.join('\n * ') + "\n'")
}
EOF
)
script=$(node -e "$script")
[ -z "$NOEXEC" ] && eval "$script" || echo "$script"
}
scaffold() {
d=node_modules/telegram-bot-now/scaffold
cp -r $d/* . > /dev/null
echo "The following files have been created in your project root:"
echo " - server.js"
echo " - now.json"
}
env() {
cat .env |grep -ve '^\s*$' |sed 's/^/export /' |sed 's/$/;/'
}
logs() {
msg="Cannot show logs. No deployment has been made"
[ ! -f .url ] && {
echo $msg; exit 0
}
url=$(cat .url)
[ -z "$url" ] && {
echo $msg; exit 0
}
now logs -n ${1:-200} -f $url
}
kill() {
/bin/kill -9 $(ps aux |grep "[m]icro" |awk '{print $2}')
}
# --- support functionatlity --------------------------------------------------
fetch() {
srv=$1; cmd=""; shift
# server is optional
[[ "$srv" != -* ]] && {
cmd=$srv; srv=$1; shift
}
url="curl --silent $@ $(url $srv)"
[ ! -z "$cmd" ] && url="$url$cmd"
[ ! -z "$DEBUG" ] && echo $url > /dev/stderr
[ -z "$NOEXEC" ] && {
eval $url
echo ""
}
}
url() {
[ "$1" == "-b" ] && {
echo "$(cat .url)/server.js"
}
[ "$1" == "-l" ] && {
echo "http://localhost:3000/server.js"
}
[ "$1" == "-t" ] && {
echo "https://api.telegram.org/bot${TELEGRAM_BOT_KEY}"
}
}
hdr() {
[[ "$1" == "-j" ]] && {
echo -H "Content-Type:application/json"
}
}
msg_data() {
srv=$1; cmd=$2; chat_id=${3:-0}; from=${4:-testuser}; type=$5; args=$6
if [ "$type" == "-p" ]; then
if [ "$srv" == "-t" ]; then
printf "$(msg_photoToTel)" $chat_id $args
else
printf "$(msg_photoToBot)" $chat_id $from $args
fi
elif [ "$type" == "-k" ]; then
printf "$(msg_keyboardToTel)" $chat_id "$args"
elif [ "$type" == "-c" ]; then
printf "$(msg_contactToBot)" $chat_id $from "$args"
elif [ "$type" == "-d" ]; then
printf "$(msg_documentToBot)" $chat_id $from "$args"
else
f=$([ "$srv" == "-t" ] && msg_textToTel || msg_textToBot)
printf "$f" $chat_id $from "$cmd"
fi
}
msg_textToTel() {
cat <<- EOF
{
"chat_id": "%s",
"chat_type": "private",
"username": "%s",
"parse_mode": "Markdown",
"text": "%s"
}
EOF
}
msg_textToBot() {
cat <<- EOF
{ "message": {
"chat": {"id": "%s", "type": "private"},
"from": {"username": "%s"},
"text": "%s"
}}
EOF
}
msg_photoToTel() {
cat <<- EOF
{
"chat_id": "%s",
"photo": "%s"
}
EOF
}
msg_photoToBot() {
cat <<- EOF
{ "message": {
"chat": {
"id": "%s",
"type": "private"
},
"from": {"username": "%s"},
"photo": [{
"file_id": "%s",
"file_size": "857",
"width": "90",
"height": "15"
}]
}}
EOF
}
msg_keyboardToTel() {
cat <<- EOF
{
"chat_id": "%s",
"text": "xx",
"reply_markup": {
"keyboard": [%s],
"one_time_keyboard": true,
"resize_keyboard": true,
"selective": false
}
}
EOF
}
msg_contactToBot() {
cat <<- EOF
{ "message": {
"chat": {
"id": "%s",
"type": "private"
},
"from": {"username": "%s"},
"contact": {
"phone_number": "%s",
"first_name": "testuser",
"user_id": "0"
}
}}
EOF
}
msg_documentToBot() {
cat <<- EOF
{ "message": {
"chat": {
"id": "%s",
"type": "private"
},
"from": {"username": "%s"},
"document": {
file_name: 'tst.pdf',
mime_type: 'application/pdf',
thumb: {
file_id: 'AAQBABMSLBEwAATNIk5Rfkv4jMNhAAIC',
file_size: 5895,
width: 247,
height: 320
},
file_id: 'BQADAQADUwADYWIBRwfwuzfSbsn_Ag',
file_size: 4191
}
}}
EOF
}
err() {
echo "$@" > /dev/stderr
}
die() {
echo -e $1; exit 1
}
mkenv() {
[ -z "$TELEGRAM_BOT_KEY" ] && {
echo -e "\nNo environment file available. Please supply your Telegram bot key."
read -p "Enter key: " TELEGRAM_BOT_KEY
}
echo "TELEGRAM_BOT_KEY=$TELEGRAM_BOT_KEY" > .env
}
# --- main() ------------------------------------------------------------------
[ "$1" == "--help" ] && {
help
}
[ "$1" == "-d" ] && {
shift; NOWDEBUG=--debug; set -x
}
[ ! -f .env ] && mkenv
eval `env`
[ "$1" == "--bot-key" ] && {
TELEGRAM_BOT_KEY=$2
shift; shift
}
[[ ! -z "$1" && ! "$1" =~ "-" ]] && {
type "$1" &>/dev/null || die "Command [$1] not supported!"
[ ! -z "$DEBUG" ] && echo "CMD=$@"
"$@"; exit
}
[ -f .url ] && url=$(cat .url)
[ ! -z "$url" ] && now rm --yes $url
now $NOWDEBUG $1 > .url
[ $? == 0 ] && {
echo -e "\nBinding deployment to Telegram webhook..."
bind
}