How To Clone Any Telegram Bot

Chatbots are often touted as a revolution in the fashion users collaborate with technology and businesses. They have a fairly elementary interface compared with traditional apps, as they merely crave 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 drib in the price compared to bodily humans, and also considering 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 condition data to more complex operations such as rudimentary medical diagnosis and client communication/support. Y’all can devise a chatbot that volition help your customers when they enquire sure questions about your product, or you can brand a personal banana chatbot that tin 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 tin can deploy your chatbot, and one of the about common uses are social media platforms, as most people use them on a regular ground. The same can be said of instant messaging apps, though with some caveats.

Telegram is one of the more pop IM platforms today, as it allows you to store messages on the cloud instead of simply your device and it boasts good multi-platform support, as you tin have Telegram on Android, iOS, Windows, and just about any other platform that can back up the web version. Edifice a chatbot on Telegram is fairly simple and requires few steps that take very lilliputian time to complete. The chatbot can exist integrated in Telegram groups and channels, and information technology also works on its ain.

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

To complete this tutorial, yous will need Python three installed on your system also every bit Python coding skills. Also, a good agreement of how apps work would exist a proficient addition, but not a must, as we will be going through nearly of the stuff we nowadays in detail. Yous also need Git installed on your system.

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

Bringing Your Telegram Bot to Life

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

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

Telegram bot tutorial - screenshot example

Your bot should take ii attributes: a name and a username. The name will show upward for your bot, while the username volition be used for mentions and sharing.

After choosing your bot name and username—which must end with “bot”—y’all volition become a message containing your access token, and you’ll plainly need to salve your access token and username for later, as you will be needing them.

Code the Chatbot Logic

Nosotros will exist using Ubuntu in this tutorial. For Windows users, well-nigh of the commands here will work without whatsoever problems, but should y’all face whatsoever issues with the virtual surround setup, please consult this link. Equally for Mac users, this tutorial should work merely fine.

First, allow’s create a virtual environment. Information technology helps isolate your project’s requirements from your global Python environment.

        $ python -m venv botenv/
        
      

At present we will have a
botenv/
directory which volition contain all the Python libraries we will be using. Become ahead and activate
virtualenv
using the following command:

        $ source botenv/bin/actuate
        
      

The libraries we need for our bot are:

  • Flask: A micro web framework built in Python.
  • Python-telegram-bot: A Telegram wrapper in Python.
  • Requests: A popular Python http library.

Y’all 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’due south scan our project directory.

        . ├── app.py ├── telebot │   ├── credentials.py │   |   . │   |   yous can build your engine hither │   |   . │   └── __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 nosotros will create later"
        
      

Now let’s become dorsum to our app.py and get through the lawmaking stride by step:

        # import everything 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.

        # start the flask app app = Flask(__name__)
        
      

Nosotros also need to bind functions to specific routes. In other words, we demand to tell Flask what to do when a specific accost is chosen. More than detailed info about Flask and routes can be found here.

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

        @app.route('/{}'.format(TOKEN), methods=['Postal service']) def respond():    # retrieve the message in JSON and and so transform it to Telegram object    update = telegram.Update.de_json(request.get_json(force=Truthful), bot)     chat_id = update.bulletin.chat.id    msg_id = update.message.message_id     # Telegram understands UTF-eight, so encode text for unicode compatibility    text = update.message.text.encode('utf-8').decode()    # for debugging purposes only    print("got text message :", text)    # the first time you chat with the bot AKA the welcoming message    if text == "/kickoff":        # print the welcoming message        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 y'all enter so please enter a proper noun and the bot will reply with an avatar for your proper noun.        """        # send the welcoming message        bot.sendMessage(chat_id=chat_id, text=bot_welcome, reply_to_message_id=msg_id)      else:        attempt:            # articulate the message nosotros got from any not alphabets            text = re.sub(r"\W", "_", text)            # create the api link for the avatar based on http://avatars.adorable.io/            url = "https://api.adorable.io/avatars/285/{}.png".format(text.strip())            # reply with a photo to the name the user sent,            # note that you tin can send photos by url and telegram will fetch information technology for you            bot.sendPhoto(chat_id=chat_id, photo=url, reply_to_message_id=msg_id)        except Exception:            # if things went incorrect            bot.sendMessage(chat_id=chat_id, text="There was a problem in the name you used, please enter unlike proper name", reply_to_message_id=msg_id)     return 'ok'
        
      

The intuitive way to make this part to work is that nosotros will call it every second, and so that it checks whether a new message has arrived, just 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, and 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 role that we ourself need to telephone call to activate the Webhook of Telegram, basically telling Telegram to call a specific link when a new message arrives. We volition call this part in one case only, when we beginning create the bot. If y’all change the app link, then you will need to run this function over again with the new link yous take.

The route hither can exist anything; you’re the one who will call it:

        @app.route('/setwebhook', methods=['GET', 'POST']) def set_webhook():     # we utilise the bot object to link the bot to our app which live     # in the link provided by URL     south = bot.setWebhook('{URL}{HOOK}'.format(URL=URL, Hook=TOKEN))     # something to permit united states know things work     if s:         return "webhook setup ok"     else:         return "webhook setup failed"
        
      

Now that everything is set, allow’s just make a fancy homepage and then that we know the engine is up.

        @app.route('/') def alphabetize():     return '.' if __name__ == '__main__':     # note the threaded arg which allow     # your app to have more than one thread     app.run(threaded=Truthful)
        
      

Allow’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=['Mail']) def respond():    # retrieve the message in JSON and then transform it to Telegram object    update = telegram.Update.de_json(request.get_json(force=True), bot)     chat_id = update.message.chat.id    msg_id = update.message.message_id     # Telegram understands UTF-8, so encode text for unicode compatibility    text = update.message.text.encode('utf-eight').decode()    # for debugging purposes only    impress("got text message :", text)    # the start time you chat with the bot AKA the welcoming bulletin    if text == "/outset":        # print the welcoming bulletin        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 proper noun yous enter so please enter a name and the bot volition reply with an avatar for your name.        """        # ship the welcoming message        bot.sendMessage(chat_id=chat_id, text=bot_welcome, reply_to_message_id=msg_id)      else:        try:            # articulate the message we got from any non alphabets            text = re.sub(r"\W", "_", text)            # create the api link for the avatar based on http://avatars.ambrosial.io/            url = "https://api.adorable.io/avatars/285/{}.png".format(text.strip())            # reply with a photograph to the name the user sent,            # notation that you can ship photos by url and telegram will fetch it for yous            bot.sendPhoto(chat_id=chat_id, photo=url, reply_to_message_id=msg_id)        except Exception:            # if things went wrong            bot.sendMessage(chat_id=chat_id, text="At that place was a trouble in the proper noun you used, please enter different proper name", reply_to_message_id=msg_id)     return 'ok'  @app.route('/set_webhook', methods=['GET', 'POST']) def set_webhook():    due south = bot.setWebhook('{URL}{Claw}'.format(URL=URL, HOOK=TOKEN))    if s:        return "webhook setup ok"    else:        return "webhook setup failed"  @app.route('/') def alphabetize():    return '.'   if __name__ == '__main__':    app.run(threaded=True)
        
      

That’s the last bit of code you will write in our tutorial. Now we can progress to the terminal 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 projection uses, and so we accept to tell it using the
requirements.txt
file—a common problem is that you misspell requirements, then exist careful—to generate the requirements file using pip:

        pip freeze > requirements.txt
        
      

Now you take your requirements file gear up to go.

At present yous need the
Procfile
which tells Heroku where our app starts, so create a
Procfile
file and add the following:

        web: gunicorn app:app
        
      

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

From your Heroku dashboard, create a new app. Once you practise, information technology will direct yous to the
Deploy
folio. So, 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 information technology 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
        
      

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

        $ heroku login -i
        
      

Initialize a Git repository in our directory:

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

Deploy the app:

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

At this point, you will encounter the edifice progress in your concluding. If everything went okay, you lot will see something like this:

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

Now go to the app folio (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 y’all see
webhook setup ok, that means you lot are ready to become!

Now Go Talk to Your Bot

A live version of the bot

Finishing Touches, Tips, and Tricks

Now you accept your Telegram bot up and running, 24/7, without whatsoever need for your intervention. You tin can add whatever logic you lot want to the bot, so, for example, you lot tin can brand your bot more realistic by adding a “typing” status and sending a photo condition as follows:

The adjacent code snippet from the
respond()
function:

        
          if text == "/beginning":        # print the welcoming message        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 y'all enter so please enter a name and the bot will reply with an avatar for your name.        """        # send the welcoming message        bot.sendChatAction(chat_id=chat_id, action="typing")        sleep(ane.5)        bot.sendMessage(chat_id=chat_id, text=bot_welcome, reply_to_message_id=msg_id)      else:        attempt:            # clear the message we got from whatsoever non alphabets            text = re.sub(r"\West", "_", text)            # create the api link for the avatar based on http://avatars.ambrosial.io/            url = "https://api.adorable.io/avatars/285/{}.png".format(text.strip())            # reply with a photo to the proper noun the user sent,            # annotation that y'all can send photos by url and telegram will fetch it for yous            bot.sendChatAction(chat_id=chat_id, action="upload_photo")            sleep(2)            bot.sendPhoto(chat_id=chat_id, photo=url, reply_to_message_id=msg_id)        except Exception:            # if things went incorrect            bot.sendMessage(chat_id=chat_id, text="At that place was a trouble in the name y'all used, please enter different proper name", reply_to_message_id=msg_id)
        
      

Every bit you can see in the snippet, we added a typing action when we are about to transport the information about the bot which is in text format, and added an upload photo activeness when we are about to send a photo to make the bot more realistic. More actions can be establish here.

Yous tin also change the bot image and clarification from the BotFather channel to make it more friendly.

Many more simple examples of telegram bots can exist establish on the python-telegram-bot page on GitHub.

You can build upon our bot and go far the next super AI bot—all you need to do is to integrate your logic in the
respond()
function. For example, your logic tin can be in a divide module and can be called inside of the
reply()
function like then:

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

And inside of
ai.py :

        def generate_smart_reply(text):     # hither we tin can practice all our work     return "this is a smart respond from the ai!"
        
      

Import information technology now in the
app.py :

        import re from time import slumber from flask import Flask, asking import telegram From telebot.ai import generate_smart_reply from telebot.credentials import bot_token, bot_user_name,URL
        
      

Then just call it inside of the
answer()
code.

        def answer():    # recollect the message in JSON and then transform it to Telegram object    update = telegram.Update.de_json(request.get_json(force=True), bot)     chat_id = update.message.chat.id    msg_id = update.bulletin.message_id     # Telegram understands UTF-viii, and so encode text for unicode compatibility    text = update.bulletin.text.encode('utf-8').decode()    # for debugging purposes only    print("got text message :", text)    # here call your smart reply message    reply = generate_smart_reply(text)    bot.sendMessage(chat_id=chat_id, text=reply, reply_to_message_id=msg_id)
        
      

Now you tin can have your bot work the manner you desire—go alee and create the adjacent big matter!

I hope you had fun building your first Telegram bot.

Boosted Resources

  • Building a Chatbot using Telegram and Python
  • Setting your Telegram Bot WebHook the easy fashion
  • Python-telegram-bot Repository
  • Deploying with Git on Heroku
  • Python Telegram Bot documentation

Source: https://www.toptal.com/python/telegram-bot-tutorial-python