Telegram bots - To lend a helping hand

I’m a massive believer in anything automated. I look back on my career, and I’m starting to think it is ingrained in me. I’ve been tinkering with Excel macros, when I was writing reports in my early career, then getting into SysAdmin I wrote simple monitoring scripts to check the output of commands on remote systems and send me an email with the results. Script patching updates, and automate the roll-out of applications. And now moving more to a cloud architecture focus, I’m writing tools to audit customers' environments and, streamlining my own cloud environment. It’s such a helpful skill to have.

The benefits of automating tasks in the workplace

So let’s just talk about the gains that automation itself provides. Automation in the workplace doesn’t only streamline your mundane tasks and frees up your time to perform more important tasks, but it also prevents mistakes. Human-error becomes quite a problem when we look at performing repetitive tasks. In a support desk environment, where we implemented automation mechanisms, we found that support staff that has to perform a series of tasks based on customers' requests, often rush through the steps and make mistakes, and then spend a lot of time troubleshooting the issue. Time wasted in my opinion, and if we can guarantee that the steps are performed accurately, every time, we save.

To elaborate on the automation mechanisms mentioned above, this is a series of Ansible playbooks that deploy network device policies to a number of customer devices throughout their network. These playbooks not only copies the files from a central repository to the end device, but it also makes the necessary changes and applies it to the current running configuration. The only action the staff member needs to perform is to run the playbook with one or maximum of two parameters (depending on the play). This is done from Ansible Tower/AWX, and the user doesn’t even have access to the end devices, they’re only allowed to execute the playbook.

Removing the number of steps needed to be taken by staff members, speed things along, and improves accuracy. Imagine you have a new member joining the support desk, and instead of teaching them how to perform all those tasks from before (the ones that are no longer needed), we only have to teach them how to execute the playbooks, which playbooks to execute when, and which values to pass to each. The ramp-up time for a new staff member improves drastically, and they can start contributing to the team, a lot sooner.

Recently I’ve been playing around with chatbots - specifically using Telegram - and I have found how super helpful they can be, at triggering scripts at your will, collecting info from a bunch of systems and returning the results. And this is all from my mobile device.

For those not sure what Telegram chatbots are. Telegram is an instant messaging app, for mobile and desktop, but with a whole bunch of APIs and webhooks that you can make use of programmatically. So the chatbot is basically a little python program, and to the user, it looks like just another contact in your contact list that you can chat with.

This concept of getting the info you need, securely - wherever you are - is an amazing leap forward, at least in my mind, from the little bash scripts that I added to cron, and emailed the output to myself, not too long ago.

My little chatbot that runs at home can provide all kinds of information to me, or perform actions, and all I have to do is ask.

It runs in a little CentOS container at home, and by executing a simple command from the Telegram app, I can get my home router’s public IP (I had some trouble with DynDNS recently, and why not, it’s cool). I can see who’s at home, by listing the devices that are connected to the WIFI. I also have a few workloads running in a personal AWS account, and even though I have billing alarms configured, I’m still scared of my bill running away with me. I have integrated my bot with my AWS account, and the bot gets my current AWS bill for me (and converts it to my local currency). Pretty awesome, I must say. I’m also planning on integrating it into my home automation system so that I can turn things on and off with the bot, and sure most home automation apps allow this anyway - but I want to see if I can do it this way.

So wait, how does this bot stuff work?

Telegram makes it pretty simple for you, actually… Here’s a little call flow diagram.

Call Flow Diagram

Your code, on the far right in the diagram, runs from basically anywhere - with an internet connection. The connection to the Telegram servers is outbound from where your code runs. This means that the Telegram server doesn’t need access to your server that’s running the code. As I mentioned, I run mine in a little CentOS container. It needs to run the whole time, in order to poll the server for updates.

Once the user sends a message, this message also becomes available via the Telegram API, once your bot, polls the server again, finds the update, it processes it, and sends the relevant response.

The message is then delivered to the user via the same route.

What about security? Can anyone start a chat with my chatbot? Which means they can get all the info that my bot can provide!!?

Well, no… What I have found is that anyone can search for your bot in the ‘search contacts’ option, within Telegram. And you can send it messages, but, you can limit the users that the bot is allowed to respond to.

Meaning, my bot will only respond to me. Or the users that I allow him to respond to.

If you want to look at the code, it would look something like this:

I have a config file with my allowed users and bot token defined.

[SECURITY]

TGRAM_ALLOWED_USERS = myusername
BOT_TOKEN = 123456789:AABBCCDDEEFFGGHHIIJJKKLLMMNNOOPP

Then in our bot’s code, we import the necessary modules and save the configuration parameters to variables.

import telegram, json, configparser, calendar, boto3, time
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters

config = configparser.ConfigParser()
config.read('/fullPathToBotConfig/bot.conf')

bot_token = config['SECURITY']['BOT_TOKEN']

tgram_allowed_users = list(config['SECURITY']['TGRAM_ALLOWED_USERS'].split(sep=','))

When any commands are processed by the bot, it filters it by the usernames defined in the tgram_allowed_users variable. So this means, that if a user is not defined as an allowed user, the bot won’t even process the message sent by the user.

def main():
  dispatcher.add_handler(CommandHandler('start', start, filters=Filters.user(username=tgram_allowed_users)))
  dispatcher.add_handler(CommandHandler('help', cmdhelp, filters=Filters.user(username=tgram_allowed_users)))

I’ll create a full how-to post on the code behind my bot. But for now, this should cover the basics.

In the end, interaction with my bot looks similar to this:

Chatbot-scheenshot

Pretty cool, right?

With that covered, let’s think back at the business use-case described earlier in this article. Again, in a way, the Telegram bot replaces the user’s GUI, but what gets executed in the background, is basically up to you. In the support desk use-case when these commands are executed via the bot, they simply call an API endpoint exposed by the Ansible Tower/AWX, and it then, in turn, executes the playbooks as needed.

It’s really that simple.

In the ever-changing tech field of today, automation is a key requirement for any successful team.