# Developing a Telegram Bot in Python


<!--more-->

## Developing a Telegram Bot Using the Python-telegram-bot Library

Telegram bots are becoming increasingly popular due to their functionality and ease of use.
In this article, we will go through how to create a simple Telegram bot using the **python-telegram-bot** library.

First, you need to create a virtual environment:

```bash
python3 -m venv .venv

.venv\Scripts\activate # for Windows.
.venv/bin/activate   # for Linux systems.
```

Then install the python-telegram-bot library using pip:

```bash
pip install python-telegram-bot
```

To create a bot in Telegram:

Open Telegram and search for the bot `@BotFather`. Send the command `/newbot` and follow the instructions to create a
new bot. After creating your bot, you will receive a token that will be used to interact with the Telegram API.

## Handlers

### Commands

Now that we have a token, we can start writing the code. Create a file named bot.py and add the following code:

```python
from telegram import Update
from telegram.ext import Application, CommandHandler, ContextTypes


# Function to be called when the /start command is issued
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
    await update.message.reply_text("Hello! I'm your Telegram bot.")


# Main function to run the bot
def main() -> None:
    # Insert your token here
    app = Application.builder().token("YOUR_TOKEN_HERE").build()

    # Register the handler
    app.add_handler(CommandHandler("start", start))

    # Start the bot
    app.run_polling()


if __name__ == "__main__":
    main()
```

Replace **YOUR_TOKEN_HERE** with the token provided by BotFather. Then, run your bot:

```bash
python3 bot.py
```

Now your bot will be up and running and will respond to the `/start` command.

### Adding New Commands

You can easily extend your bot's functionality by adding new commands. For example, let's add a `/help` command that
displays a list of available commands:

```python
from telegram import Update
from telegram.ext import Application, CommandHandler, ContextTypes


# Function to be called when the /start command is issued
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
    await update.message.reply_text("Hello! I'm your Telegram bot.")


# New function for the /help command
async def help(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
    await update.message.reply_text(
        """
        List of commands:
        /start - Greeting message.
        /help - Help.
        """
    )


def main() -> None:
    app = Application.builder().token("YOUR_TOKEN_HERE").build()

    app.add_handler(CommandHandler("start", start))

    # Register the new handler
    app.add_handler(CommandHandler("help", help))

    # Start the bot
    app.run_polling()


if __name__ == "__main__":
    main()
```

### Text Messages

You can also handle text messages sent by users. To do this, add the following handler:

```python
from telegram import Update
from telegram.ext import Application, MessageHandler, ContextTypes, filters


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


def main() -> None:
    app = Application.builder().token("YOUR_TOKEN_HERE").build()

    # Register the handler
    app.add_handler(MessageHandler(filters.TEXT, echo))

    # Start the bot
    app.run_polling()


if __name__ == "__main__":
    main()
```

This code will duplicate any text messages received from the user.

There are many handlers available, but the most commonly used ones are **MessageHandler** and **CommandHandler**, as
demonstrated above.

Also, the **filters** object allows you to handle all sorts of messages in the chat, whether text, photos, videos, etc.
For a better understanding, I recommend checking out the [documentation](https://docs.python-telegram-bot.org).

