How I built my Telegram Bot [Part 3]
Find out more about Telegram-Python-Bot Library
Introduction
Welcome back! This is our 3rd and final part of how I built my own telegram bot. If you have yet to read the previous article on forming the foundation of the telegram bot, do check it out to keep up with the contents of this article. I hope to share more about how to improve our telebot and some tips about hosting it.
Content Page
Improvements to Bot
Continuing on from the previous post, our telegram bot is not as functional as we would like it to be. The first problem is that everytime get_updates() function is being called, the entire json with all past messages (even messages that have been “read”) are being processed and this is not an efficient way to retrieve the latest message. As such, we can make changes to the following function:
def get_updates(offset=None):
url = URL + "getUpdates"
if offset:
url += "?offset={}".format(offset)
response = requests.get(url)
decode_response = response.content.decode("utf8")
updates = json.loads(decode_response)
return updates
The 'offset' parameter allows you to retrieve the message after a certain number which is indicated by the offset. For example, you would like to process text messages after the 5th result, the offset in this case would be 5.
‘offset=None’ in the get_updates() function ensures that if there is no offset argument being passed, the default value is None (which is Python’s nil value). If the value of offset is left completely blank, the url formed will not work.
If you are also curious about the ‘?’ found before the “offset={}” in the url variable, it is actually how we pass query parameters in a HTTP Get request. The key-value pairs following the ? are the params and if there are 2 or more params, they are connected with a ‘&’. For example, www.codingcucumbers.com?language=python&version=3 is a url with 2 query params -- language and version.
For clarification, the result that I am referring to is the result list from the return json body after the HTTP request is made, check out the second blog posts in the series if you are still unsure.
Following, we need to write a new function to get the index of the latest message, which will help figure out what the value of offset in get_updates function would be.
def get_last_update_id(updates):
return updates["result"][-1]["update_id"]
It simply traverses the dictionary to locate the latest update_id.
Finally, bringing it all together again. Change your main function to the one below.
def main():
last_update_id = None
while True:
updates = get_updates(last_update_id)
if len(updates["result"]) > 0:
last_update_id = get_last_update_id(updates) + 1
time.sleep(0.5)
time.sleep(0.5) allows the script to receive the most recent messages from every 0.5 second. Don’t forget to import the time package! Finally, our bot is able to sieve out past messages and duplicated messages being processed is not a worry.
Exploring Telegram Bot Library
Despite being able to create our own telebot with our very own functions, I am sure you can start to see that it is a little repetitive and time consuming to be starting from scratch every time. Therefore, I highly recommend using functions that were built previously by professional developers to make our lives much easier.
On top of that, the code written in the 3rd party package is optimised hence the bot replies will be much faster than that of the custom function we built. I get that it might seem like a waste to throw away all the functions we have built above, but the way I see it, creating those functions forms a strong understanding of how telegram bots work!
Check out the documentation of the package here! It contains all the features that you can implement on your bot. This github contains examples to learn from which is super helpful considering that the documentation can be quite dry. If you scroll down to the readme section of the github page, there is an installation guide as well. I am sure that with your existing knowledge of the inner workings of a telegram bots, you will be able to navigate this package well and readily develop the bot of your choice.
How to use Python Telegram Bot Package
For my own personal bot, I used the Python Telegram Bot Package. Here is a snippet of my code and I’ll walk through the code.
from telegram.ext import Updater, CommandHandler
def start(update, context):
context.bot.send_message(chat_id=update.effective_chat.id, text=“hello!”)
def help(update, context):
context.bot.send_message(chat_id=update.effective_chat.id, text= “please contact me at codingcucmbers@gmail.com”)
def main():
updater = Updater(token='yout_token', use_context=True)
dispatcher = updater.dispatcher
start_handler = CommandHandler('start', start)
help_handler = CommandHandler('help', help)
dispatcher.add_handler(start_handler)
dispatcher.add_handler(help_handler)
updater.start_polling()
updater.idle()
if __name__ == "__main__":
main()
After importing the necessary packages, I start defining my command handlers. There are only 2 for now, “/start” and “/help”. Upon receiving the “/start” message from the user, send a message to that chat_id of the user with the text “hello!”. This is what the function is essentially doing. Similarly, upon receiving “/help” from the user, reply to that specific user with the text predefined in the help function.
Next, in the main function, we declare our “updater” and “dispatcher” objects. The Updater class continuously fetches new updates from telegram and passes them on to the Dispatcher class. Following, we register our start and help handlers, with the user of the CommandHandler function. We also need to add the handlers to the dispatcher object.
Lastly, we start polling the bot, which means that the bot is constantly asking if there are new messages. We let the bot idle so as not to waste too much resources when there are no new updates. Now test out the bot! You will be amazed at how fast this bot is compared to the previous bot we built from scratch.
Of course, this is just the foundation of how to use the package, there are many more features such as inlinekeyboard which creates those buttons to select options from. You can even create games with telegram bot like Werewolf!
The next step after building the telebot is to actually host it so that the bot will function without you needing to run the code from your local. Some platforms to host your code include Google Cloud Functions, Google Cloud Run or Heroku. You can check those platforms out to host your code for free. I think it would be a bit intimidating to figure out those platforms on your own. I wrote a comprehensive guide to host your telebot on Heroku for free, so do check it out.
Conclusion
I hope you have enjoyed this short 3 part series on building your own telegram bot. Writing a telegram bot program is definitely lots of fun and we would love to hear more about the telegram bot you have built. Feel free to share it with us coding.cucumbers@gmail.com. Stay cool Cucumbers!.