Tech

A step by step information to development your first Telegram bot

Chatbots are often touted as a revolution in the way users interact with technology and businesses. They have a fairly simple interface compared with traditional apps, as they only require users to chat, and the chatbots are supposed to understand and do whatever the user demands from them, at least in theory.

Many industries are shifting their customer service to chatbot systems. That’s because of the huge drop in the cost compared to actual humans, and also because of the robustness and constant availability. Chatbots deliver a degree of user support without substantial additional cost.

Today, chatbots are used in many scenarios, ranging from menial tasks such as displaying time and weather data to more complex operations such as rudimentary medical diagnosis and customer communication/support. You can devise a chatbot that will help your customers when they ask certain questions about your product, or you can make a personal assistant chatbot that can handle basic tasks and remind you when it’s time to head to a meeting or the gym.

There are a lot of options when it comes to where you can deploy your chatbot, and one of the most common uses are social media platforms, as most people use them on a regular basis. The same can be said of instant messaging apps, though with some caveats.

Telegram is one of the more popular IM platforms today, as it allows you to store messages on the cloud instead of just your device and it boasts good multi-platform support, as you can have Telegram on Android, iOS, Windows, and just about any other platform that can support the web version. Building a chatbot on Telegram is fairly simple and requires few steps that take very little time to complete. The chatbot can be integrated into Telegram groups and channels, and it also works on its own.

[Read: A developer’s guide to building a WhatsApp chatbot]

In this tutorial, we will be creating a Telegram bot that gives you an avatar image from Adorable Avatars. Our example will involve building a bot using Flask and deploying it on a free Heroku server.

To complete this tutorial, you will need Python 3 installed on your system as well as Python coding skills. Also, a good understanding of how apps work would be a good addition, but not a must, as we will be going through most of the stuff we present in detail. You also need Git installed on your system.

Of course, the tutorial also requires a Telegram account, which is free. You can sign up here. A Heroku account is required, too, and you can get it for free here.

Bringing your telegram bot to life

To create a chatbot on Telegram, you need to contact the BotFather, which is essentially a bot used to create other bots.

READ  20 Ultimate-Minute Father's Day Present Concepts and Offers (2020)

The command you need is /newbot which leads to the following steps to create your bot:

Telegram bot tutorial - screenshot example

Your bot should have two attributes: a name and a username. The name will show up for your bot, while the username will be used for mentions and sharing.

After choosing your bot name and username—which must end with “bot”—you will get a message containing your access token, and you’ll obviously need to save your access token and username for later, as you will be needing them.

Code the chatbot logic

We will be using Ubuntu in this tutorial. For Windows users, most of the commands here will work without any problems, but should you face any issues with the virtual environment setup, please consult this link. As for Mac users, this tutorial should work just fine.

First, let’s create a virtual environment. It helps isolate your project’s requirements from your global Python environment.

 

$ python -m venv botenv/

 

Now we will have a botenv/ directory which will contain all the Python libraries we will be using. Go ahead and activate virtualenv using the following command:

 

$ source botenv/bin/activate

 

The libraries we need for our bot are:

You can install them in the virtual environment using pip command as follows:

 

(telebot) $ pip install flask
(telebot) $ pip install python-telegram-bot
(telebot) $ pip install requests

 

Now let’s browse our project directory.

 

.
├── app.py
├── telebot
│   ├── credentials.py
│   |   .
│   |   you can build your engine here
│   |   .
│   └── __init__.py
└── botenv

In the credentials.py file we will need three variables:

bot_token = "here goes your access token from BotFather"
bot_user_name = "the username you entered"
URL = "the heroku app link that we will create later"

 

Now let’s go back to our app.py and go through the code step by step:

 


from flask import Flask, request
import telegram
from telebot.credentials import bot_token, bot_user_name,URL
global bot
global TOKEN
TOKEN = bot_token
bot = telegram.Bot(token=TOKEN)

 

Now we have the bot object which will be used for any action we require the bot to perform.

 


app = Flask(__name__)

 

We also need to bind functions to specific routes. In other words, we need to tell Flask what to do when a specific address is called. More detailed info about Flask and routes can be found here.

In our example, the route function responds to a URL which is basically /{token}, and this is the URL Telegram will call to get responses for messages sent to the bot.

 

@app.route('/{}'.format(TOKEN), methods=['POST'])
def respond():
   
   update = telegram.Update.de_json(request.get_json(force=True), bot)

   chat_id = update.message.chat.id
   msg_id = update.message.message_id

   
   text = update.message.text.encode('utf-8').decode()
   
   print("got text message :", text)
   
   if text == "/start":
       
       bot_welcome = """
       Welcome to coolAvatar bot, the bot is using the service from http://avatars.adorable.io/ to generate cool looking avatars based on the name you enter so please enter a name and the bot will reply with an avatar for your name.
       """
       
       bot.sendMessage(chat_id=chat_id, text=bot_welcome, reply_to_message_id=msg_id)


   else:
       try:
           
           text = re.sub(r"W", "_", text)
           
           url = "https://api.adorable.io/avatars/285/{}.png".format(text.strip())
           
           
           bot.sendPhoto(chat_id=chat_id, photo=url, reply_to_message_id=msg_id)
       except Exception:
           
           bot.sendMessage(chat_id=chat_id, text="There was a problem in the name you used, please enter different name", reply_to_message_id=msg_id)

   return 'ok'

 

READ  Videoconferencing Must Climb Out of the Uncanny Valley

The intuitive way to make this function to work is that we will call it every second, so that it checks whether a new message has arrived, but we won’t be doing that. Instead, we will be using Webhook which provides us a way of letting the bot call our server whenever a message is called, so that we don’t need to make our server suffer in a while loop waiting for a message to come.

So, we will make a function that we ourself need to call to activate the Webhook of Telegram, basically telling Telegram to call a specific link when a new message arrives. We will call this function one time only, when we first create the bot. If you change the app link, then you will need to run this function again with the new link you have.

The route here can be anything; you’re the one who will call it:

 

@app.route('/setwebhook', methods=['GET', 'POST'])
def set_webhook():
    
    
    s = bot.setWebhook('{URL}{HOOK}'.format(URL=URL, HOOK=TOKEN))
    
    if s:
        return "webhook setup ok"
    else:
        return "webhook setup failed"

 

Now that everything is set, let’s just make a fancy homepage so that we know the engine is up.

 

@app.route("https://thenextweb.com/")
def index():
    return '.'
if __name__ == '__main__':
    
    
    app.run(threaded=True)

 

Let’s take a look at the full version of app.py:

 

import re
from flask import Flask, request
import telegram
from telebot.credentials import bot_token, bot_user_name,URL


global bot
global TOKEN
TOKEN = bot_token
bot = telegram.Bot(token=TOKEN)

app = Flask(__name__)

@app.route('/{}'.format(TOKEN), methods=['POST'])
def respond():
   
   update = telegram.Update.de_json(request.get_json(force=True), bot)

   chat_id = update.message.chat.id
   msg_id = update.message.message_id

   
   text = update.message.text.encode('utf-8').decode()
   
   print("got text message :", text)
   
   if text == "/start":
       
       bot_welcome = """
       Welcome to coolAvatar bot, the bot is using the service from http://avatars.adorable.io/ to generate cool looking avatars based on the name you enter so please enter a name and the bot will reply with an avatar for your name.
       """
       
       bot.sendMessage(chat_id=chat_id, text=bot_welcome, reply_to_message_id=msg_id)


   else:
       try:
           
           text = re.sub(r"W", "_", text)
           
           url = "https://api.adorable.io/avatars/285/{}.png".format(text.strip())
           
           
           bot.sendPhoto(chat_id=chat_id, photo=url, reply_to_message_id=msg_id)
       except Exception:
           
           bot.sendMessage(chat_id=chat_id, text="There was a problem in the name you used, please enter different name", reply_to_message_id=msg_id)

   return 'ok'

@app.route('/set_webhook', methods=['GET', 'POST'])
def set_webhook():
   s = bot.setWebhook('{URL}{HOOK}'.format(URL=URL, HOOK=TOKEN))
   if s:
       return "webhook setup ok"
   else:
       return "webhook setup failed"

@app.route("https://thenextweb.com/")
def index():
   return '.'


if __name__ == '__main__':
   app.run(threaded=True)

 

READ  Coronavirus: Fb and Intel ditch MWC tech display

That’s the last bit of code you will write in our tutorial. Now we can progress to the last step, launching our app on Heroku.

Launch our app on Heroku

We need a couple of things before we make our app.

Heroku can’t know what libraries your project uses, so we have to tell it using the requirements.txt file—a common problem is that you misspell requirements, so be careful—to generate the requirements file using pip:

 

pip freeze > requirements.txt

 

Now you have your requirements file ready to go.

Now you need the Procfile which tells Heroku where our app starts, so create a Procfile file and add the following:

 

web: gunicorn app:app

 

A bounce step: You can add a .gitignore file to your project so that no-use files don’t get uploaded to the repository.

From your Heroku dashboard, create a new app. Once you do, it will direct you to the Deploy page. Then, open the Settings tab in a new window and copy the domain of the app which will be something like https://appname.herokuapp.com/ and paste it in the URL variable inside credentials.py.

Heroku dashboard screenshot

Now, go back to the Deploy tab and proceed with the steps:

Note: Windows and macOS users can follow the steps described here.

Log in to Heroku:

 

$ heroku login

 

Please note that this method sometimes gets stuck in waiting for login, if this happens to you, try to log in using:

 

$ heroku login -i

 

Initialize a Git repository in our directory:

 

$ git init
$ heroku git:remote -a {heroku-project-name}

 

Deploy the app:

 

$ git add .
$ git commit -m "first commit"
$ git push heroku master

 

At this point, you will see the building progress in your terminal. If everything went okay, you will see something like this:

 

remote: -----> Launching...
remote:        Released v6
remote:        https://project-name.herokuapp.com/ deployed to Heroku
remote:
remote: Verifying deploy... done.

 

Now go to the app page (the link of the domain you copied before) and add to the end of the link /setwebhook so that the address will be something like https://appname.herokuapp.com/setwebhook. If you see webhook setup ok, that means you are ready to go!

Now go talk to your bot

Live version of Telegram chatbot
Close
Close

Adblock Detected

Please consider supporting us by disabling your ad blocker