Patrick Frischmann
May 2 · 6 min read

In this article I want to show you how you can communicate with your app users through a Telegram bot. Pretty cool idea, right?

Based on a NodeJS application, I will provide code snippets and tips to help you get started. I will also introduce useful features that might come in handy in the future.

Introduction

Ever wondered how you can communicate with your app users through a Telegram bot? Let me start with establishing a base by briefly introducing the functionality of the application. A client needed a web crawler that would log in to an admittedly old school forms-based website and traverse a calendar for information (there is more to it, but let’s stick to that for now). The application would then monitor a date range for certain events and notify users about any changes or newly added data. In fact, the whole parsing was an interesting problem to solve on its own, but today I’m concentrating on user interface design.

Due to login and specific user data requirements, support for configuration options was needed. Naturally, the first thought that came to my mind was providing a minimalistic web frontend for users to log in and manage their configuration settings. However, while brainstorming over the most efficient way to deliver notifications to users, I thought why not use the same channel for user interaction.

The overall constraints I had to work with were

  • “non-tech” users who
  • access the app mainly from their mobiles and
  • need an easy-to-use interface.

As you may guess I ended up with Telegram messenger, which is available for all platforms (mobile, desktop and as web app) — even for Windows Phone ;-). People are comfortable using messengers nowadays and the main advantage that came with it was having a single endpoint to the application. Besides, Telegram is free, lightning fast and provides encryption for your messages.

So let’s get started and first talk to the father of all bots — “Hello BotFather”.

Image source: https://core.telegram.org/bots/

A bot is born

In order for my application to communicate to the user I need to set up a Telegram bot. This bot will later be able to send messages to specific users (and groups) as well as receive commands. BotFather will guide you through the few steps necessary to create a new bot. If you want to get a good overview on bots in general there is also a great introduction available here.

By the time you finished setting up your bot you should have received your authorization token. It looks something like 123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11. You can already query the Telegram Bot via HTTPS using the following syntax: https://api.telegram.org/bot<token>/METHOD_NAME
For more info on available methods please see the Bot API manual.

Connect Telegram Bot with NodeJS Backend

Now it is time to switch to your favourite editor and get coding. While you may use the official API directly, I personally like to use the Telegraf framework. It provides a useful wrapper and middleware with full Telegram Bot API support. It will get you started faster and make life easier. However, this time I went with the tgfancy wrapper because it offers ordered sending of messages out of the box. Install via

$ npm install tgfancy --save

The whole setup to send a message looks like this:

const Tgfancy = require("tgfancy"); 
const bot = new Tgfancy(CREDENTIALS.BOT_TOKEN, {
tgfancy: {
orderedSending: true
}
});
bot.sendMessage(chatId, "text message");

So that’s basically how you would send your notifications. Pretty quick setup, right? Parsers for HTML and Markdown are readily available to format your messages if needed. There is also support for Emoticons . In order to obtain the correct chatId, you can use the /getMe method with your bot's auth token like this: https://api.telegram.org/bot<token>/getMe

Talk to your bot

Now to the hard(er) part — implementing commands. First you want to implement suggested basic commands /start, /help and /settings (if applicable). Next are your individual commands that provide your bot functionality. For me, those are commands the users may execute to configure the application. In my case there is a very limited set of configuration values so I can make use of the inline keyboard to display pre-defined options to the user.

Let’s look at it in code. Here for example, the /set-user command would provide three options upon execution. The user may simply tap on one of them which would result in a callback_query event on the server side. Depending on the callback_data provided, you can again display further options and thus guide the user through the setup process.

Here is an example:

bot.onText(/\/set_user/, (msg) => {
bot.sendMessage(msg.chat.id, 'Got it, please select an option below:', {
reply_markup: {
inline_keyboard: [[
{
text: 'Id Number',
callback_data: 'USER_ID_NUMBER'
}, {
text: 'Id Type',
callback_data: 'USER_ID_TYPE'
}, {
text: 'Date Of Birth',
callback_data: 'USER_DOB'
}
]]
}
});
});
bot.on("callback_query", (callbackQuery) => {
const message = callbackQuery.message;
switch (callbackQuery.data) {
case 'USER_DOB':
bot.sendMessage(message.chat.id, 'Got it, please type DATE OF BIRTH in the following format: DD/MM/YYYY');
break;
default:
bot.sendMessage(message.chat.id, 'I am sorry, this action is not implemented!');
break;
}
});

In my opinion this setup process is very comprehensible and my clients felt really comfortable using it. This way, they feel a close interaction with the software and I gotta say response times are incredibly fast.

Security and usability

Obviously, for security reasons, you should consider access control by username (or chat id), and Turn groups off in the bot settings to forbid users to add your bot to other groups. You can also use the /setjoingroups command for that as shown in the image below.

Once you are done, don’t forget to actually provide a list of your commands to the BotFather. You can do that using /setcommands in your conversation with BotFather. This is very helpful for the end user, because he will then get a list of supported commands when he enters a '/' in the chat and can simply tap on one of them.

I know there really is no rocket science about this, but I hope I was able to communicate my general idea. It is just something to keep in mind when designing your next application. I really felt that communication with the software using the bot felt natural to the users. There are multiple integration options besides notifications, e.g. website login through Telegram and even accepting payments.

Please leave a comment if you have any further questions or suggestions. Leave a like if you found this article helpful.

Bonus section — Telegram Payment API

To enable even more advanced use-cases, Telegram bots can now also accept payments for goods and services (details see here). They are then called Merchant bots. I played around with the Payment API using the Stripe test server. I admit, it really is a seamless integration for the user, and I believe it will be huge in the future. Unfortunately, none of the currently integrated payment providers offer their services in Cyprus so it is still waiting time for me.


Originally published at https://thehooraymedia.com on April 13, 2019.

The Hooray Media

Stories and insights from creators and thinkers.

Patrick Frischmann

Written by

Entrepreneur | Blockchain Enthusiast | Software Engineer | Full Stack Developer

The Hooray Media

Stories and insights from creators and thinkers.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade