-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbot.js
64 lines (50 loc) · 1.32 KB
/
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
const TelegramBot = require('node-telegram-bot-api'),
mjAPI = require('mathjax-node'),
svg2png = require('svg2png')
const token = 'YOUR-BOT-TOKEN',
scale = 30,
minWidth = 400
mjAPI.start()
const bot = new TelegramBot(token, {polling: true})
const sendError = (chatId, errStr, reply) => {
var options = {}
if(reply) {
options['reply_to_message_id'] = reply
}
bot.sendMessage(chatId, 'Uh-oh! I couldn\'t render your formula! ' +
errStr, options)
}
bot.onText(/\/start/, (msg, match) => {
bot.sendMessage(msg.chat.id, 'Hello! Send me your equations, ' +
'I\'ll typeset them for you')
})
bot.onText(/\/help/, (msg, match) => {
bot.sendMessage(msg.chat.id, 'Just send me the equation, I\'ll do the rest')
})
bot.on('message', msg => {
if(msg.entities) {
// Ignore non text messages, including bot commands
return
}
const chatId = msg.chat.id,
msgId = msg.message_id
mjAPI.typeset({
math: msg.text,
format: "TeX",
svg: true,
}, data => {
if (data.errors) {
sendError(chatId, data.errors.join('\n'), msgId)
return
}
var width = (data.width.substring(0, data.width.length - 2)) * scale
if(width < minWidth) {
width = minWidth
}
svg2png(data.svg, {width}).then(png => {
bot.sendPhoto(chatId, png, {reply_to_message_id: msgId})
}).catch(e => {
sendError(chatId, e, msgId)
})
})
})