Introduction
Are you a newcomer to Python, uncertain about what to do for your first project? Or perhaps you are a seasoned developer seeking a new endeavor? If so, then welcome to the world of Telegram bot development!
In this beginner-friendly guide, we'll embark on a journey to create our very own Telegram bot using the Python programming language. Whether you're a coding enthusiast taking initial steps or an experienced developer exploring new avenues, this article will provide you with a hands-on experience to help you bring up your very own Telegram bot.
Prerequisites
Before we dive into the exciting contents, do note that this guide assumes knowledge of the following:
- Familiarity with Python
- Familiarity with pip
- Familiarity with Telegram
Basic Python knowledge will suffice, and we will not be covering the above prerequisites as they are not the focus of this guide - there are plenty of Python & pip guides out there while Telegram is a messaging platform that needs little elaboration. All that said, if you need help with any of the above, you are more than welcome to reach out for assistance.
Setup
Since we are working with a simple Telegram bot, the setup is relatively straightforward. Create and head into the folder where we will house our project (e.g. my_telegram_bot).
We will also be using python-telegram-bot, which is a wrapper around the Telegram API. Install the library with the following command:
pip install python-telegram-bot --upgrade
Next, create a main.py file and paste the following short snippet within it.
from telegram.ext import Application
def main():
"""
Handles the initial launch of the program (entry point).
"""
token = ""
application = Application.builder().token(token).concurrent_updates(True).read_timeout(30).write_timeout(30).build()
print("Telegram Bot started!", flush=True)
application.run_polling()
if __name__ == '__main__':
main()
Let's breakdown the above code. We first define a main
function that serves as an entry point for the program. Within the function, a variable named token
is initialized with an empty string (not to worry, we'll revisit this soon). We then proceed to initialize the Application
class, providing configurations via a builder pattern. Finally, we print a message to notify us that the instance has been started before calling the run_polling
method to listen for updates.
If you save this file and try running it with python main.py
now, you will be faced with an invalid token error. This is not much surprise, since our token hasn't even been set, which brings us on to the next section on obtaining bot tokens.
Bot Token
For our program to startup successfully, the missing ingredient is the bot token that uniquely identifies our Telegram bot! Thankfully, Telegram provides a bot for us to easily obtain bot tokens:
Head over to BotFather and type /newbot
. You will be prompted with a series of questions such as the bot name and handle. Follow through with the creation process and you'll be greeted with a bot token at the end of the steps. This token can be used to control your Telegram bot so keep it safe and do not share it with others!
With the bot token obtained above, return to main.py and replace it where your token is currently an empty string. Try running the file again and this time, you'll see your console printing "Telegram Bot started!".
Great! We've now got a bot running. Go ahead and send a message to your Telegram bot. Is it responding? Something feels amiss, we have not defined what the bot should respond to!
The First Message
For the bot to respond to user actions, we need to provide it with handlers. Since we would like our bot to respond to our text messages, let us start with a simple MessageHandler
. Within main.py define a short function as outlined below:
def reply(update, context):
update.message.reply_text("Hello there!")
Next, we add our MessageHandler
and have it filter for text messages by applying filters.TEXT
. Your new main.py should now look like this (remember to update the imports at the top as well):
from telegram.ext import Application, MessageHandler, filters
async def reply(update, context):
await update.message.reply_text("Hello there!")
def main():
"""
Handles the initial launch of the program (entry point).
"""
token = YOUR_BOT_TOKEN_HERE
application = Application.builder().token(token).concurrent_updates(True).read_timeout(30).write_timeout(30).build()
application.add_handler(MessageHandler(filters.TEXT, reply)) # new text handler here
print("Telegram Bot started!", flush=True)
application.run_polling()
if __name__ == '__main__':
main()
Re-run your bot and try sending in a hello message again. Your bot should reply with "Hello there!". Pretty nice, but what if we want it to run commands?
The First Command
You got your bot to utter its first word, now let's try having it greet us when we say hello via a command instead! Similar to how we added messages, we will add another line but instead of a MessageHandler
, we will be using a CommandHandler
(again, remember to update your imports):
from telegram.ext import Application, CommandHandler, MessageHandler, filters
async def reply(update, context):
await update.message.reply_text("Hello there!")
def main():
"""
Handles the initial launch of the program (entry point).
"""
token = YOUR_BOT_TOKEN_HERE
application = Application.builder().token(token).concurrent_updates(True).read_timeout(30).write_timeout(30).build()
application.add_handler(MessageHandler(filters.TEXT, reply))
application.add_handler(CommandHandler("hello", reply)) # new command handler here
print("Telegram Bot started!", flush=True)
application.run_polling()
if __name__ == '__main__':
main()
Now, go ahead and type /hello
to your chatbot. If you've been following this guide diligently, the bot would have responded with "Hello there!" again.
The First Upload
Getting the hang of things? Let's try with a slightly more advanced option, sending an image to your bot! This time round, we will be using MessageHandler
again but unlike the first example, the PHOTO
filter will be applied instead of the TEXT
filter. Go ahead and add the new line as shown below:
from telegram.ext import Application, CommandHandler, MessageHandler, filters
async def reply(update, context):
await update.message.reply_text("Hello there!")
def main():
"""
Handles the initial launch of the program (entry point).
"""
token = YOUR_BOT_TOKEN_HERE
application = Application.builder().token(token).concurrent_updates(True).read_timeout(30).write_timeout(30).build()
application.add_handler(MessageHandler(filters.TEXT, reply))
application.add_handler(CommandHandler("hello", reply))
application.add_handler(MessageHandler(filters.PHOTO, reply)) # new photo handler here
print("Telegram Bot started!", flush=True)
application.run_polling()
if __name__ == '__main__':
main()
Now, if you send your bot a photo, it will once again greet you enthusiastically with a "Hello there!" - not the most intuitive for a photo upload but you get the point.
Unleash Your Creativity
We've just gone through some basic examples but I hope you're convinced that creating your own Telegram bot is no tough work! From here on out, you may be interested to check out the documentation for python-telegram-bot to find out more of what you can do with the bot.
For those who are interested to take things further, you may also wish to extend the functionalities of the bot into a project. In case you need some inspirations, I've open-sourced a handful of Telegram bots such as TeleQR, Simple Media Converter and Simple Transcriptions.
As a stretch goal, consider hosting your Telegram bot and including liveness checks once you've completed your project!
Conclusion
In this short walkthrough, we've explored how to create a basic Telegram bot. I hope you found this journey useful for your learning and that you're motivated to explore beyond just this guide. If you've got ideas or suggestions, feel free to leave them in the comments below or bounce ideas with me here. Thank you for reading!
Top comments (0)