How to create telegram bot using python

In this blog post, you will learn How to create telegram bot using Python. By the end of this post, you can create a telegram bot that can do things for you.

1. Setting up the Environment

  • Python Installation: If you haven’t already, install Python on your machine. You can download the latest version from the official website: https://www.python.org/
  • Telegram Bot API: Create a new bot on Telegram. Here’s how:
    • Find the BotFather on Telegram (@BotFather)
      telegram botfather
    • Send /newbot command.
    • Choose a name for your bot.
    • Create a username for your bot (must end with bot).
    • BotFather will provide you with an API token – keep this safe!
      telegram api
  • Python Libraries: Install the python-telegram-bot library:

2. The Bot’s Code

Let’s write a simple “Hello World” bot:

  • Import the library: import telebot
  • Set your token: Store your API token in the BOT_TOKEN variable.
  • Create a bot instance: bot = telebot.TeleBot(BOT_TOKEN)
  • Define a handler: The @bot.message_handler decorator tells the bot what to do when it receives a message. We’re using func=lambda message: True to handle all incoming messages.
  • Respond to messages: The echo_all function sends a “Hello” message back to the user.
  • Start the bot: bot.polling() keeps the bot listening for messages.

3. Run the Bot

Save the code as a .py file (e.g., my_bot.py) and run it from your terminal:

Now, open Telegram and search for your bot using its username. Send a message to your bot, and it should respond with “Hello, [your name]!”.

Now that you have created a bot, you might have realized that it needs to run continuously in the background to work properly. If your computer shuts down, your bot stops responding—definitely not ideal if you want it to be available at all times.

One solution is to host your bot on a server, but instead of paying for expensive servers or setting up complicated configurations, there are free services you can use. You can use PythonAnywhere, a free online hosting platform that’s easy to use and perfect for small to medium-sized bot projects.

Leave a Comment