From 9c60068122bfac2c1deb305c04172fcc859cdbbb Mon Sep 17 00:00:00 2001 From: Mohammed Sohail Date: Wed, 15 Feb 2017 08:17:55 +0300 Subject: [PATCH] examples: Express webhook (#287) Feature: A webhook integration with an express app. References: * Feature request: https://github.com/yagop/node-telegram-bot-api/issues/282 * PR: https://github.com/yagop/node-telegram-bot-api/pull/287 * Requested-by: @kamikazechaser * PR-by: @kamikazechaser --- examples/expressWebhook.js | 39 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 examples/expressWebhook.js diff --git a/examples/expressWebhook.js b/examples/expressWebhook.js new file mode 100644 index 0000000..e564e65 --- /dev/null +++ b/examples/expressWebhook.js @@ -0,0 +1,39 @@ +/** + * This example demonstrates setting up a webook, and receiving + * updates in your express app + */ + +const TOKEN = process.env.TELEGRAM_TOKEN || 'YOUR_TELEGRAM_BOT_TOKEN'; +const url = 'https://'; +const port = process.env.PORT; + +const TelegramBot = require('..'); +const express = require('express'); +const bodyParser = require('body-parser'); + +// No need to pass any parameters as we will handle the updates with Express +const bot = new TelegramBot(TOKEN); + +// This informs the Telegram servers of the new webhook. +bot.setWebHook(`${url}/bot${TOKEN}`); + +const app = express(); + +// parse the updates to JSON +app.use(bodyParser.json()); + +// We are receiving updates at the route below! +app.post(`/bot${TOKEN}`, (req, res) => { + bot.processUpdate(req.body); + res.sendStatus(200); +}); + +// Start Express Server +app.listen(port, () => { + console.log(`Express server is listening on ${port}`); +}); + +// Just to ping! +bot.on('message', msg => { + bot.sendMessage(msg.chat.id, 'I am alive!'); +});