Creating a Basic Telegram Bot using Python and Telebot

Creating a Basic Telegram Bot using Python and Telebot

Play this article

In this tutorial, we'll walk you through the process of creating a basic Telegram bot using Python and the Telebot library. The bot will respond to user messages and provide a welcome message upon the /start command. Let's get started!

Prerequisites

  • Telegram Account: You'll need a Telegram account to create a bot and obtain its token.

  • Python Installed: Ensure that Python is installed on your system.

Step 1: Getting Your Bot Token

  1. Open the Telegram app and search for BotFather.

  2. Start a chat with BotFather by sending the /start command.

  3. Use the /newbot command to create a new bot. Set a name and username for your bot.

  4. Copy the token provided by BotFather.

  5. Full Guide On Getting A Token From BotFahter

Step 2: Writing the Python Code

import telebot

bot = telebot.TeleBot("your_bot_token_here")  # Replace with your bot token

# /start command for your bot
@bot.message_handler(commands=['start'])
def handle_start(message):
    start_message = "<b>Hello, welcome to the bot!</b>"
    bot.reply_to(message, start_message, parse_mode='HTML')

# A text message handler
@bot.message_handler(func=lambda message: True)
def handle_text(message):
    reply_text = message.text
    bot.reply_to(message, reply_text)

# Start the bot
bot.polling()

Running the Bot

  1. Save the Python code in a .py file.

  2. Open your terminal or command prompt and navigate to the directory containing the .py file.

  3. Replace your_bot_token_here with the actual bot token.

  4. Run the bot script by executing the command: python filename.py.

Interacting with Your Bot

  1. Open your Telegram app and search for your bot's username.

  2. Start a chat with your bot.

  3. Send the /start command to receive a welcome message.

  4. Send any text message to the bot, and it will respond with the same message.

Conclusion

Congratulations! You've successfully created a basic Telegram bot using Python and the Telebot library. This bot responds to the /start command with a welcome message and echoes back any text messages you send. This is just a starting point, and you can build more advanced interactions and features using the Telebot library.

Did you find this article valuable?

Support Karan Coder by becoming a sponsor. Any amount is appreciated!