Step by step telegram notification bot
Creating notification bot in Telegram can be frustrating especially if you’re familiar with FB Messenger Bot or Slack Bot because the concept is different, not to mention there are tons of documentation before you could send a simple message. You need approval from Facebook or Slack if you planning to publish your bot. The benefit of develop Telegram bot is you can publish bots as many as you want as long as your bot is publicly accessible.
The code example is using NodeJS and you can find the repo in the references below.
Step 1
Download and register a telegram account (duh)
https://telegram.org/
Step 2
Search for botfather
and click start
With BotFather, type /newbot
to setup a bot and give it a name
Once a bot name and username has been created. You will receive a bot token for example123456:xxxxxxx-xxxxxxxxxx
.Hurray! you just created a new bot
Step 3
Create a public channel and give it name. You can convert it to private channel later. We will use the channel name to make our API first call
Add your bot into the channel by clicking the triple dots icon at top right corner -> info -> Admins -> Add Admin -> enter your bot username
Step 4
Create a directory and initialise a NodeJS project
npm initnpm i request request-promise -S
Create a file to store our credential. Let’s name it config.js
module.exports = {
bot_token: '123456:xxxxx-xxxxxxxxxxx',
peer: '@testnotification' // your bot username start with @ sign
}
Next, create an index.js
const request = require('request-promise')
const config = require('./config')request({
method: 'POST',
baseUrl: 'https://api.telegram.org',
uri: `/bot${config.bot_token}/sendMessage`,
json: true,
body: {
chat_id: config.peer,
text: '<b>Hello World</b>',
parse_mode: 'HTML'
}
})
.then(res => {
console.log(res)
})
.catch(err => console.error(err.message))
Finally, lets run our app node index.js
You should see a message in your telegram app
That’s it ! So simple isn’t it ? Moving on there’re a lot of improvement here for example you can use third party library to encapsulate Telegram API https://core.telegram.org/bots/samples