Telegram bot 101: How to start with the Telegram API
Find out how to create and deploy a simple telegram bot with long polling on PythonAnywhere.
In the ever-evolving world of messaging platforms, Telegram has been my constant companion since 2013, cherished for its commitment to security, independence, and an excellent user experience. Its significance goes beyond borders, especially in my home country — Ukraine, where it serves as a lifeline for information, memes, videos, music, learning materials, and communication. Unfortunately, in the harsh reality of today, Telegram is also used to spread urgent information about incoming rockets or drone attacks from russian forces.
What You’ll Learn
In this series, we’ll kick off with “Telegram Bot 101,” guiding you through creating, updating, and deploying a simple Telegram bot using long polling and PythonAnywhere. Stay tuned for more insights and advanced topics in upcoming articles, including working with databases to store bot interactions and engagements. Plus, discover how to visualize results with interactive dashboards and graphs using Streamlit.
Getting Started: Telegram Bot Development Essentials
1. Acquiring a Token from BotFather
To integrate your bot with the Telegram Bot API, you need a unique token. Obtain this token by interacting with BotFather, Telegram’s official bot for creating and managing bots. Follow the provided documentation for a step-by-step guide.
Watch Out for Username: During the interaction with BotFather, be cautious not to make mistakes with the username. At the beginning of the process, you’ll be prompted to input the username (which is not editable once set). After this step, you’ll be asked to input the name, which could be changed later. This ensures that your bot’s username is chosen carefully as it’s a permanent identifier.
2. Setting Up Your Development Environment
Prepare your development environment by importing the necessary libraries into your preferred IDE(for me it is PyCharm). This lays the groundwork for your bot’s functionality.
For details on setting up PyCharm for Python development, refer to PyCharm’s official documentation.
3. Writing Basic Commands
Now that you have your Telegram bot token, let’s explore writing basic commands and understanding the structure of a simple bot. Below is a basic example using the popular python-telegram-bot
library:
from telegram import Update
from telegram.ext import Updater, CommandHandler, CallbackContext
import os
from dotenv import load_dotenv
# Load your environment variables
load_dotenv()
tg_token = os.getenv("TOKEN")
# Define the start command
def start_command(update: Update, context: CallbackContext) -> None:
update.message.reply_text('Hello! I am your Telegram Bot.')
# Define the help command
def help_command(update: Update, context: CallbackContext) -> None:
update.message.reply_text('You can use /start to begin.')
# Run the main block when the script is executed
if __name__ == '__main__':
print("Starting the bot...")
app = Application.builder().token(tg_token).build()
# Commands handlers
app.add_handler(CommandHandler("start", start_command))
app.add_handler(CommandHandler("help", help_command))
print("Looking for new messages...")
app.run_polling(poll_interval=5)
Loading Environment Variables
The load_dotenv()
function is used to load environment variables from a .env file. This file contains sensitive information, such as API tokens, and is not shared or exposed publicly. We will also need it later for deploying on PythonAnywhere. To install the library run the following command:
pip install python-dotenv
Ater this create a file called .env in the same directory as your bot code and create a variable for the token you have received from botfather.
Start Command Handle
The start_command
function is a command handler that defines the behavior when users send the /start command to the bot. In this case, it sends a welcome message to the user.
Help Command Handler
The help_command
function is a command handler that defines the behavior when users send the /help command to the bot. It responds with information about how to use the bot.
Main Execution Block
The if __name__ == '__main__':
block ensures that the code inside it is executed only when the script is run directly, not when it's imported as a module. Further, we initialized the Telegram bot application using Application.builder().token(tg_token).build()
. This prepares the bot for interaction with the Telegram API.
-Add Command Handlers: It adds the command handlers (start_command
and help_command
) to the bot application using app.add_handler()
. This associates the defined functions with specific commands.
-Start the Bot: When starting the bot, we use the app.run_polling(poll_interval=5)
method, which employs a technique known as "long polling." In long polling, the bot makes periodic requests to the Telegram server, checking for new updates or messages every 5 seconds in this case. This ensures that the bot remains responsive to user interactions, handling incoming messages and commands.
Additionally, for deployment in a production environment, an alternative method called “webhooks” can be used. Webhooks involve the Telegram server sending updates directly to your server whenever there is new activity. Ensure to refer to the official documentation for more details on setting up webhooks using the python-telegram-bot
library: WebhookHandler Documentation.
The choice between long polling and webhooks depends on your deployment requirements and infrastructure. Long polling is a simpler approach suitable for most use cases, while webhooks are more efficient for production environments where constant polling might be less ideal.
Error Handling
Ensuring that your bot properly handles errors is crucial for providing a seamless user experience. The python-telegram-bot
library allows you to define error handlers using the add_error_handler
method. For example:
# Error handler for all errors
def handle_errors(update: Update, context: CallbackContext) -> None:
error_message = f"An error occurred: {context.error}"
update.message.reply_text(error_message)
Also, we need to addhandle_errors
function to the error handler in the main function. This ensures that users receive informative error messages and that you can log or handle errors appropriately.
app.add_error_handler(handle_errors)
Deploying on PythonAnywhere
1. Create an Account:
- Go to the PythonAnywhere website.
- Sign up for a new account. If you already have an account, log in.
2. Upload Your Code and .env File:
- After logging in, you’ll be directed to your dashboard. Go to the “Files” tab.
- Click on “Upload a file” and upload your Python script (the one containing your bot code) and the
.env
file.
3. Run Your Bot:
- Open your bot file and click “Run” on the right side of the navigation bar
- If you’re using the free version of PythonAnywhere, your bot will stop working after 48–72 hours. To restart it, simply go to the “Files” tab, find your bot script, and click “Run”
What’s next?
Congratulations! You’ve successfully launched your Telegram bot on PythonAnywhere. Your journey into Telegram bot development has just begun, and there’s so much more to explore. In the next article, we’ll continue with the basics and will cover some features like integrating keyboards with buttons and inline keyboards to enhance user interaction. Additionally, we’ll outline the callback queries and filters, executing commands with external API calls, and integrating databases to store your bot’s interactions.
If you have any questions or suggestions, please leave a comment below.
Thank you so much for reading!
Oleksandr Pypenko
Let’s connect!🔗
GitHub • LinkedIn
Tags — #python #telegram #programming #blog #tutorial