Skip to content

Instantly share code, notes, and snippets.

@Pitasi
Last active November 6, 2017 10:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Pitasi/8da6c0d11eb1ff6fc8a64e594f5c4f64 to your computer and use it in GitHub Desktop.
Save Pitasi/8da6c0d11eb1ff6fc8a64e594f5c4f64 to your computer and use it in GitHub Desktop.
https://anto.pt/2017/11/05/Telegram-bots-with-Node-js/ - A simple Telegram bot built with Telegraf.js
// Include Telegraf module
const Telegraf = require('telegraf');
// Create a bot using TOKEN provided as environment variable
const bot = new Telegraf(process.env.TOKEN);
// Import replies file
const replies = require('./replies')
// Extract reply_to_message.message_id field from Telegraf ctx
// If not present, return null
const getReplyToMessageId = ctx => (
ctx.message.reply_to_message ? ctx.message.reply_to_message.message_id : null
)
// This method will send the reply, based on the answer type
// (text / gif / sticker). See replies.js for objects structure.
const sendReply = (ctx, reply) => {
// reply method will be the Telegraf method for sending the reply
let replyMethod = {
text: ctx.reply,
gif: ctx.replyWithDocument,
sticker: ctx.replyWithSticker
}[reply.type]
replyMethod(reply.value, {
// this will make the bot reply to the original message instead of just sending it
reply_to_message_id: getReplyToMessageId(ctx)
})
}
// /list command - will send all the triggers defined in replies.js.
bot.command('list', ctx => {
ctx.reply(
'Available triggers:\n\n' +
Object.keys(replies).join('\n')
)
})
// Listen on every text message, if message.text is one of the trigger,
// send the reply
bot.on('text', ctx => {
let cmd = ctx.message.text.toLowerCase()
if (cmd in replies)
sendReply(ctx, replies[cmd])
})
bot.startPolling();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment