forked from telegraf/telegraf
-
Notifications
You must be signed in to change notification settings - Fork 0
/
example-bot.js
66 lines (51 loc) · 1.82 KB
/
example-bot.js
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
const Telegraf = require('telegraf')
const Extra = require('telegraf/extra')
const session = require('telegraf/session')
const { reply, fork } = Telegraf
const randomPhoto = 'https://picsum.photos/200/300/?random'
const sayYoMiddleware = fork((ctx) => ctx.reply('yo'))
const bot = new Telegraf(process.env.BOT_TOKEN)
// // Register session middleware
bot.use(session())
// Register logger middleware
bot.use((ctx, next) => {
const start = new Date()
return next().then(() => {
const ms = new Date() - start
console.log('response time %sms', ms)
})
})
// Login widget events
bot.on('connected_website', ({ reply }) => reply('Website connected'))
// Telegram passport events
bot.on('passport_data', ({ reply }) => reply('Telegram password connected'))
// Random location on some text messages
bot.on('text', ({ replyWithLocation }, next) => {
if (Math.random() > 0.2) {
return next()
}
return Promise.all([
replyWithLocation((Math.random() * 180) - 90, (Math.random() * 180) - 90),
next()
])
})
// Text messages handling
bot.hears('Hey', sayYoMiddleware, (ctx) => {
ctx.session.heyCounter = ctx.session.heyCounter || 0
ctx.session.heyCounter++
return ctx.replyWithMarkdown(`_Hey counter:_ ${ctx.session.heyCounter}`)
})
// Command handling
bot.command('answer', sayYoMiddleware, (ctx) => {
console.log(ctx.message)
return ctx.reply('*42*', Extra.markdown())
})
bot.command('cat', ({ replyWithPhoto }) => replyWithPhoto(randomPhoto))
// Streaming photo, in case Telegram doesn't accept direct URL
bot.command('cat2', ({ replyWithPhoto }) => replyWithPhoto({ url: randomPhoto }))
// Look ma, reply middleware factory
bot.command('foo', reply('http://coub.com/view/9cjmt'))
// Wow! RegEx
bot.hears(/reverse (.+)/, ({ match, reply }) => reply(match[1].split('').reverse().join('')))
// Launch bot
bot.launch()