forked from telegraf/telegraf
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexample-bot.js
60 lines (48 loc) · 1.61 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
const Telegraf = require('telegraf')
const Extra = require('telegraf/extra')
const session = require('telegraf/session')
const { reply } = Telegraf
const bot = new Telegraf(process.env.BOT_TOKEN)
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)
})
})
const sayYoMiddleware = ({ reply }, next) => reply('yo').then(() => next())
// 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())
})
const catPhoto = 'http://lorempixel.com/400/200/cats/'
bot.command('cat', ({ replyWithPhoto }) => replyWithPhoto(catPhoto))
// Streaming photo, in case Telegram doesn't accept direct URL
bot.command('cat2', ({ replyWithPhoto }) => replyWithPhoto({ url: catPhoto }))
// Look ma, reply middleware factory
bot.command('foo', reply('http://coub.com/view/9cjmt'))
// Wow! RegEx
bot.hears(/reverse (.+)/, ({ match, reply }) => {
return reply(match[1].split('').reverse().join(''))
})
// Start polling
bot.startPolling()