How to build a simple Telegram Bot using Python

David Melashych
5 min readFeb 19, 2024

--

Introduction

Imagine a little helper that interacts with your customers 24/7, answers their questions, and even brings in sales. That’s the power of a Telegram bot!

Telegram, a popular messaging app, lets you create these automated assistants. Think of them as mini-apps within the app, programmed to do various tasks — from sending out personalized messages to sharing updates and information.

For businesses and entrepreneurs, Telegram bots offer a unique way to connect directly with their target audience. And the best part? Done right, they can even help you generate revenue!

The Father of All Bots

So before writing Python code, we need a bot token. It is required to authorize the bot and to send requests to the Bot API. For mature developers here is detailed documentation

So let’s get started. We need to open our Telegram app and type @BotFather

Tap or click on it to start a conversation.

So after pressing START, we can see so many commands and options which we can use to customize our future bot. But for now, we need to choose /newbot

Upon receiving instructions, you’ll be asked to provide a title for your bot, along with a distinct username concluding with the term ‘bot.’ For instance, you have the option to label your bot as ‘MyNewBot’ and assign the username as ‘@MyNewBot.’ It’s crucial to verify the uniqueness of the chosen username, as it will be the means by which your bot is identified.

Once you’ve supplied a name and username, BotFather will generate a bot token. This token serves as a vital piece of information, enabling your application to authenticate and engage with the Telegram API on behalf of your bot. It’s important to maintain the security and confidentiality of this token since it grants access to your bot’s functionalities.

Create a Telegram Bot

To simplify the process of setting up our environment for the development. We will use PythonAnywhere

PythonAnywhere is a feature-rich and user-friendly online Python development environment, accessible from any device with a web browser. It operates in a cloud-based environment, ensuring your bot remains online 24/7, making it a “serverless” application. This is ideal for our Telegram bot, enabling it to respond to user interactions at any given moment.

1. Create your account:

Head over to PythonAnywhere and register for a new account. It’s quick and easy!

2. Dive into your “Files” tab:

Once logged in, navigate to the “Files” tab on the dashboard. This is where you’ll store your bot’s code and settings.

3. Create your bot’s files:

  • Click “New file” and name it main.py. This will be your bot's main code file.
  • Do the same again, but name this one requirements.txt. This file lists the packages your bot needs.

4. Install python-telegram-bot:

Open the requirements.txt file and type in python-telegram-bot. Save the file. This tells PythonAnywhere to install the necessary library for interacting with Telegram.

5. Enter your bot’s code:

Go back to the main.py file and copy-paste the provided code. Remember to replace YOUR_TOKEN with the actual token you received from BotFather.


import logging

from telegram import ForceReply, Update
from telegram.ext import Application, CommandHandler, ContextTypes, MessageHandler, filters

# Enable logging
logging.basicConfig(
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", level=logging.INFO
)
# set higher logging level for httpx to avoid all GET and POST requests being logged
logging.getLogger("httpx").setLevel(logging.WARNING)

logger = logging.getLogger(__name__)


# Define a few command handlers. These usually take the two arguments update and
# context.
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
"""Send a message when the command /start is issued."""
user = update.effective_user
await update.message.reply_html(
rf"Hi {user.mention_html()}!",
reply_markup=ForceReply(selective=True),
)


async def help_command(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
"""Send a message when the command /help is issued."""
await update.message.reply_text("Help!")


async def echo(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
"""Echo the user message."""
await update.message.reply_text(update.message.text)


def main() -> None:
"""Start the bot."""
# Create the Application and pass it your bot's token.
application = Application.builder().token("YOUR_TOKEN").build()

# on different commands - answer in Telegram
application.add_handler(CommandHandler("start", start))
application.add_handler(CommandHandler("help", help_command))

# on non command i.e message - echo the message on Telegram
application.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, echo))

# Run the bot until the user presses Ctrl-C
application.run_polling(allowed_updates=Update.ALL_TYPES)


if __name__ == "__main__":
main()

6. Run your bot and watch it come alive!

Navigate to the editor for the “main.py” file and locate the “Bash Console” button beneath it. Click on it to launch a new console. Within the console, input the following commands to install the required libraries and execute your bot:

pip install -r requirements.txt
python main.py

Congratulations!

Congratulations on crafting your first Telegram bot! In this tutorial, we’ve implemented two operational commands: /start and /help. Typically, newcomers initiate interaction with your bot by using the /start command, which serves as the default entry point. On the other hand, /help, as its name suggests, offers guidance by displaying a list of available bot commands and other relevant instructions.

This marks just the initial phase of the countless possibilities that Telegram bots offer. The range of potential applications is vast, including but not limited to. Reminder bots, Online shopping bots, Automation services bots, ChatGPT interactions, Trading bots.

And the list goes on — your imagination is the only limit!

You can find more cool examples of creating a Telegram Bot here.

--

--