Forging Your Telegram Bot

Aarnav Jindal
5 min readApr 17, 2019

--

From playing games with us like chess to understanding and executing complex tasks like Siri, from managing humongous warehouses to studying and influencing our opinions via social media websites, bots are omnipresent and affect our lives more than we can imagine.

These bots offer several advantages over manual labor which include but are not limited to being available 24/7, triggering when certain events happen, serving multiple customers at once and giving uniform controlled results.

Several platforms like Facebook messenger, Telegram and Slack provide you facility to deploy bots offering quick and efficient services, and growing your customer base.

Bot Stack

This post will help you create and deploy a bot on Telegram offering services such as getting Memes, News, Searching lyrics and Downloading Songs on client devices.

Tech Stack

  • Python, since it offers abundant easy to use libraries to perform our backend tasks easily with minimal code
  • Flask, it is a lightweight web application framework for quick and easy development

Service Platforms

  • Herokuapp.com, a freemium model based website with great dashboard to track app activity and direct deploy feature for Github repositories
  • Telegram, we’ll use telegram’s Bot Father to create and deploy our bot

Getting Bot Token

Install the Telegram app beforehand since it’ll help register the bot using bot father and later test the bot

  • Search for Bot Father using search button in Telegram app
  • Type and send “/newbot”
  • Enter a name for your bot
  • You’ll be given your token now

Forging the Bot

  • Start a new Flask project
  • You can set up the project and run the app to see if it’s working properly
  • Install and import the required dependencies like below
  • We will initialise our bot as follows
  • We create a queue to store all incoming requests since there may be more than one request that needs processing, so we store and later process them one by one
  • Now we need the url endpoint at which we will set a webhook for incoming requests from our bot redirected by the Telegram server. I used the endpoint “/work” for it.
  • We need the endpoint to accept incoming POST requests
  • Now we define the handle function which gets msg object as input
  • You can print msg to see the structure of the object for better clarity of the structure of msg dictionary
  • The text from user resides in msg[‘text’]
  • We check the first word to see which type of query it is and respond accordingly
  • Finally we ask the bot to reply via sendMessage to the user

Making Modules

Since we want to be able to send more than just static responses, we create modules for getting jokes, news, lyrics etc and then import and use them in our main file

Joke Module

  • Beautiful soup is an amazing library to parse and filter content from webpage html via tags
  • You can go to the actual website and see their html structure
  • The result object has an array of jokes from which we return a random joke

Meme Module

  • Just like with the joke module, we select a random meme from the webpage and get it’s src url
  • We then use the url to read the image data and write the bytes in meme.jpg file
  • In the main file when we get response “done” from our module, we use the bot to send the image as follows

News Module

  • We use an API to fetch news urls and send them to the user
  • You can register for your own API key and start making requests like below

You can now import these modules into your project and then make calls to fetch and serve data to customers. Other modules like getting lyrics, songs, videos etc can be made similarly with little tweaks.

Final Touches to Code

  • You need to freeze requirements for your project as given here
  • Then you need to add a Procfile file to your project

Now you can push your project to Github

Uploading on HerokuApp

  • Now go to deploy tab
  • Select deployment method as Github
  • Search for your repository in the search bar below and connect to it
  • Now click on Deploy Branch

You will see that your project will now be deployed. If you face issues simple fixes can be found on stack overflow or just mention in the comments below.

Setting Webhook

The last step is telling Telegram servers where to redirect the messages we get from our users. Our webhook url will be of the form : https://________.herokuapp.com/work

Replace the bot token and actual herokuapp url in the below url. Now put the url in your web browser search bar and hit enter. This will return a message saying your webhook was set successfully.

https://api.telegram.org/bot{your_bot_token}/setWebhook?url=https://________.herokuapp.com/work

Test the Bot

Now you can search for your bot in the telegram app and start conversing with it. You can send a message to your bot and view logs in the herokuapp to check for errors and other logs.

If your app crashes, you can see the logs and fix the error. Then select restart all dynos to restart the server and see if errors have been successfully fixed.

Bot Prettifying

You can add bot image, description etc to make it look prettier using Bot Father. You can also add commands and corresponding descriptions. The commands then pop up in chat as suggestions which is a pretty cool feature.

My bot is on Telegram with the name Oshawott if you want to check it out. The complete source code is available here at the link below. The structure maybe a little different from the tutorial but it’ll be simple to understand. Implementation of songs, videos, lyrics and wikipedia API are also present. Feel free to leave your queries, comments below or if you want a tutorial on something else. Don’t forget to clap if you liked my project. Until next time, keep geeking it out 🤓

--

--

Aarnav Jindal

Avid programmer chasing developments in the dynamic and invigorating world of technology 🤓