How to Create Your Own Telegram Bot

Jerry
Spider R&D
Published in
7 min readFeb 3, 2021

Missing Natasha from Hike-chat? What if I tell you we can create our own service in Telegram which communicates with us! In this article, we are going to do just that with simple open-source code using Python and Telegram for free!

Source: SAP Conversational AI

Introduction

Telegram Bots are simply Telegram accounts operated by software — not people — and they often have specific features and functionalities. They can do a range of stuff such as teach, play, search, broadcast, remind, connect, integrate with other services, or even pass commands to the Internet of Things.

Now, let us create a Telegram-bot which can chat with you like an AI application anywhere, anytime, and for anyone.
How cool is that? Let’s get started.

Steps to build it:

  1. Create a Telegram-bot.
  2. Create a Chatbot.
  3. Create a service that can link the Chat-bot with the Telegram-bot.

Creating a Telegram bot

How do we create a bot?
Its very simple, Telegram offers a bot that does this for you with simple commands. Search for Botfather in the Telegram application search bar, you will find the bot with the official verified tick mark. Next, we click on start to use the bot.

Source: Telegram

We will use the /newbot command to create a bot.
Let’s call the bot Deadpool, adding a little spice to give savage replies.

Using Telegram Botfather service to create a new bot. The first highlight is the shareable link and the next is the API token for the newly created bot (this token is currently deactivated).

We give a name and a unique username (the shareable link) for the bot, that’s it, Hurrah! our bot is created.

We can copy the link and share it with anyone on the internet or search the Telegram-bot in the search bar to get the bot. Open up the bot and start using it.

We send messages, but why isn’t the Deadpool bot replying? In the next section, we will make it to reply to our messages.

Creating a Chatbot

We need an AI application that can reply to our messages. We will be coding that in this section. We can code our own chatbot and train with our data from scratch or use open source libraries to build with some libraries. Here we will be using chatterbot — a python library that does all work for you, we just need to input the message and it gives a response back, that’s the power of open-source.

Next, we install the required python3 libraries

pip install ChatterBot
Sample code for using Chatterbot module

This is just as easy as it can get creating a chatbot, whatever input we give inside the get_response method we get a response from the trained AI bot we just made.

We just made the chatbot, But how can we integrate the chatbot with the Telegram-bot? The next section does exactly that.

Integrating the service

We created the telegram-bot for the users, We got the chatbot to respond to messages, here we need to integrate them such that the chatbot receives the message from the telegram bot and responds to it back again.

How do we perform that?

Before that, we will be required to know about the Telegram API which allows the Python3 code to communicate with the telegram bot.

When a user sends a message, our server(code) needs to collect the message. There are two ways in which Telegram offers for our servers to receive messages(from the user).

1. Polling in an API endpoint — Telegram API offers /getUpdate endpoint in the API to receive updates for the user input.

2. Webhooks — Telegram offers /setWebhook and /deleteWebhook endpoint to set and delete a webhook for message updates from the user.

More about the definitions and differences between Polling and Web-hooks.

We will be using the 1st option polling an API request in this article since this option does not require a server hosted on the internet with an endpoint(URL) and also this is easy to run and test. If you are new to Web API, click here to learn about them.

Using Polling

Getting user messages: We can use the /getUpdates endpoint with the secure API token obtained while creating the bot to receive messages sent by all the users of the Deadpool bot using the below URL.

https://api.telegram.org/bot1635894026:AAHiGLTmIfLYd8IIqYBvu2vlO1Fy0JHOj3E/getUpdates

Since it is a GET request endpoint, we can run it in the browser. eplace the above API Token with your API token and use the URL in your browser, type some messages to your bot and you will receive the messages in JSON format on reload.

Replying user messages: Now we can use the /sendMessage endpoint to send messages to the user with their user chat id (obtained from the /getUpdates endpoint) and the reply message using this format in the URL.

https://api.telegram.org/bot1635894026:AAHiGLTmIfLYd8IIqYBvu2vlO1Fy0JHOj3E/sendMessage?text="reply to users message"&chat_id=654923404

Replace with your token and the chat id for the message from the previous endpoint to reply with the reply message in the text field in the URL.

Hurrah! we can send and receive messages from the API endpoints, Let us implement it in python3 code.

We install the required libraries from pip. Next, we have created:

  1. Telegram bot API access which has methods for getting updates using timeout waiting for a message-id which is a number and increments itself by one for each message and sending messages, see the documentation here.
  2. Config file to use our own token.
  3. Server file to run the server which has the chatbot (the one which we made in the previous section) and to reply to the users chat id using the telegram bot send_message method from the imported bot class.

Output

We run the file using the following command

python server.py

which gives output in the console as shown below.

Server running and ready to respond to messages for the Deadpool bot

The output comes from the chatbot trainer which trains the chatbot to respond to input, it trains the bot using the pre-collected dataset in multiple sections of the English language so that it can respond to various aspects impersonating a human being on the server.

Now while the server is running, we head over to Telegram to check out our bot, we can send messages and see its response and have a conversation.

Cool right? Accomplishment Yay! We have successfully created a Telegram chatbot. Share it with your friends using the shareable link and they can try it out. If they provoke the bot it would give savage replies like these…

He never used the bot again.

You can search for messages using the API secretly what your friend has messaged the Telegram-bot even if they don’t share the embarrassment with you and laugh with your friends.

Conclusion

The bot responds as well as the user input is meaningful and understandable. Not to mention the chatbot is an AI application, training data is required for a bot to understand human behaviour and emotions from the input text, you can use your own chatbots or you can make one by yourself using some well maintained open-source libraries and apply it here.

Instead of a chatbot, we can create our own application with as many services as we can integrate. For example with databases, third-party services many more. Telegram bots can do any automated services such as event registration with a payment portal, giving sports updates, and even more.

In the development environment, we run the python file locally which makes sure that the telegram bot works. Practically for long-term use of the telegram bot, we need a computer(server) to run the python script full time to access the bot anytime anyone wants. A personal computer is not good in this case. Hence we can use any computer-server such as your own server or a free online service server which removes the worry for you such as Heroku or pythonanywhere etc.

Thanks to the open-source community for making it easy to create a great project in a short time.

A more clean version of the code is available on GitHub, here. Feel free to star and fork the repo to test and modify it as per your needs. That’s it for today, folks!

You can try out the bot at t.me/deadpool_chatbot.

This article is published under Spider Research and Development Club, NIT Trichy on a Web Wednesday!

--

--