Managing Azure Instances With Telegram Bot Using Python-Part 2
Just send a command to your Telegram Bot to control your Azure Instance
Welcome to Part 2 of Managing Azure Instances with Telegram Bot using Python. If you haven’t read the previous article, you may read it here.
In the Part 1, as Rishabh Rathod has described us how the Azure VM Instance can easily be controlled by just making a API call. In this part we will focus on how we can call those API via telegram bot to turn on /off Azure’s VM instance.
For entire code you can also check my Git Repository from here.
▹ Azure account (Covered in Part 1)
▹ Basic knowledge of Python (Functions, Decorators, Basic if-else).
★ Here we have targeted Azure VM as the resource to be managed. Similar approach can then be used to manage other Azure Resources. Here our main objective is to show you how can this Integration be achieved in Azure.
★ Also, Telegram bot can be configured in many programming languages and you can make it work accordingly for your task. Here we have selected Python because of it’s simplicity and global reach.
Step 1. Creating Telegram Bot
The steps to make a bot on telegram using BotFather is showed in the image
After creating the bot, you will receive the bot token which will be used by us further in configuring it’s commands.
Firstly we will create commands for our bot and then configure those commands using Python to achieve what we want. To make commands go to botfather and select your bot first and then click on Edit Bot
Here you will have to select Edit Commands and then give your list of all the commands you want. The command name should entirely be in lowercase and the description separated with a hyphen(-). You can also edit other things of the bot according to your need. Now we’ll move to the next part.
Step 2. Configuring Bot Commands using Python
For Python coding we’ll be using pyTelegramBotAPI for handling telegram and hence the 1st step is to install the library
pip install pyTelegramBotAPI
After installing pyTelegramBotAPI we will make and instance of the bot by passing in the bot token which was received to us by BotFather after successfully creating the Bot in a file named Bot.py .
import telebotbot = telebot.TeleBot(token="your_bot_token_here")
You can simply pass your bot token here but if you are planning to upload your code on Github or share with anyone it is not advisable to publicly put your Bot token there. Hence we will save it in .env file. For that we will first install it’s library named python-dotenv.
pip install python-dotenv
Next, create an .env file in the same directory of your Bot.py file and in it define your Bot Token there.
BOT_TOKEN = "your_bot_token_here"
And now in your Bot.py file, we have to import the
Dot-Env library Then we use getenv() function present in
os by passing the name used by us above in .env file as the parameter . After accessing the bot token from .env file we will pass it to the Telebot so that it understands to which Telegram bot’s commands it has to listen to.
from dotenv import load_dotenvload_dotenv()
bot_token = os.getenv('BOT_TOKEN')
bot = telebot.TeleBot(token=bot_token)
Now we are ready to configure our commands which can be done by using a decorator with a function and write the piece of code what we want to execute inside the function like this. This decorator tells that on giving the command /start or /help to our telegram, it will reply to the user the following message which is passed as the parameter.
bot.reply_to(message, "How you doinnn?")
A function which is decorated by a message handler can have an arbitrary name. However, it must have only one parameter (the message). Now after that the final step to start our bot is to call polling(). The entire code looks like this.
from dotenv import load_dotenvload_dotenv()
bot_token = os.getenv('BOT_TOKEN')
bot = telebot.TeleBot(token=bot_token)@bot.message_handler(commands=['start', 'help'])
bot.reply_to(message, "How you doinnn?")bot.polling()
To start the bot, simply open up a terminal and enter
python Bot.py to run the bot! And then test it by sending commands ('/start' and '/help') in to your telegram bot and the bot should return a message like this.
Now as we have got an idea of how we can configure our bot commands we will achieve our main goal which is to turn on/off our Azure VM Instance by calling the API which was created in Part-1.
Firstly we will store the url which we created in the .env file as by accessing those url anyone can access your VM which can lead to a big security breach. Your .env file will look like this now.
BOT_TOKEN = "your_bot_token_received_by_botfather"
START_URL = "your_url_here"
STOP_URL = "your_url_here"
STATUS_URL = "your_url_here"
Now we can call this url in our function decorated with the command we want. Before we want to start the server we check the status of it and if it’s off we will turn it on. So we write the code to check the status and also we can call it by sending a command. To call the API we need to import requests and the response returned is shown here to capture the status for us.
import email@example.com_handler(commands=['checkstatus']) # check status of VM
STATUS_URL = os.getenv('STATUS_URL')
s = requests.get(STATUS_URL).json()
status = s['statuses']['displayStatus']
chatid = message.chat.id
bot.send_message(chatid, 'Current status of is ' + status)
We are first fetching the STATUS_URL from the .env file and then using the requests library we are making a get request on that url. The data we are receiving we are parsing it to JSON for better accessibility. Also we are getting the chat ID of the message sent from the message parameter which is used as a parameter to send back the message and the bot understands to whom he has to send the message by calling the send_message function. At last we will return the status as we will be calling this method from other methods.
After checking the status we can decide if we want to turn on/off the VM instance or not. After that we let the user know that we are trying to turn on/off the server by sending a simple message. Next, we call the URL to turn on/off by making a get request.
We can do this exact same thing for turning off the server by using the STOP_URL we had saved in the .env file and modifying the messages accordingly.
Now, in telegram anyone can find this bot with the username of the bot and turn on or off our VM Instance. And in Azure, we all know once we start the VM Instance we are started getting billed for it. Hence this can cause us huge cost for someone’s mistake. Hence we will only allow particular users to access our startServer and stopServer commands. We will first make a list of users authorized to perform those actions and depending upon your code share-ability, you can make that list in your code or save it in .env file. We will pursue with storing it in .env file for more security and loading it in our code.
AUTHORISED_USERS = os.getenv('AUTHORISED_USERS')
authorized_users = AUTHORISED_USERS.split(",")
for index,element in enumerate(authorized_users):
authorized_users[index] = element.strip()
And then before turning on or off the VM Instance we will check if the command is coming from an authorized user or not. If yes will continue with the task or otherwise will send them a message that they are not authorized for that action.
Now we are nearing up to finishing up our bot. The last step is to polling the Bot. Upon calling this function, TeleBot starts polling the Telegram servers for new messages. We will put inside
While True: loop wrapped with enter
Try and Catch
You can also clone this code from my Git Repository from here.
By running this entire code on your local machine, you can try to send a command on your bot and check if your are getting the required reply. But you can not always keep on running this code on your machine. Hence you can host this on a free hosting site like PythonAnywhere or Heroku.
Step 3. Deploying your code to make your bot available 24*7
For this example we cannot use PythonAnywhere as it only has a particular set of websites which are whitelisted which you can check here for the free account. Except for this list it doesn’t allow our code to go to any other sites. But if you are planning not to make any get request or your site is whitelisted then you can use PythonAnywhere(check this video for detailed instruction) and install you dependencies with
pip install by opening up a new bash window and then upload your file on it and finally run that file on the bash.
pip install flask
Now we have to remove the while loop we had previously added as we will be no longer running it on our local machine and instead will be suing web hooks for the same. We will be running it as website which will be hosted 24*7 so that anytime we send a command to our Telegram Bot, we will always get a reply and we will be available to turn on/off our VM Instance accordingly.
After making this changes in your Bot.py file we also have to add a
Procfile(without any extension) which will contain the following so that it understands which file to execute when someone hits our site
web: python3 Bot.py
Also we have to make a Requirements.txt file where we have to specify all the dependencies we need, so that Heroku can install it for you. You can get this list by running
pip freeze and copy the result entirely in your Requirements.txt file. At last we will upload 4 files on Heroku namely .env, Bot.py, Procfile, requirements.txt. and finally deploy it.
— — — — — — — — Thanks for reading..😀😉 — — — — — — —