Step 1: Install Required Libraries First, you need to install the python-telegram-bot
library, which provides a convenient interface for interacting with the Telegram Bot API. Open your terminal or command prompt and run the following command:
1 |
pip install python-telegram-bot |
Step 2: Create a Telegram Bot
To create a Telegram bot, you need to interact with the BotFather bot on Telegram. Here are the steps:
Open Telegram and search for “BotFather.”
Start a chat with BotFather.
Type “/newbot” to create a new bot.
Follow the instructions and provide a name and username for your bot.
Once the bot is created, you will receive an API token. Make sure to save this token for later use.
Step 3: Set Up the Python Script
Create a new Python script (e.g., auto_reply_bot.py) and open it in a text editor. Add the following code to the script:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
import logging from telegram.ext import Updater, MessageHandler, Filters # Enable logging logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO) # Telegram bot API token (replace 'YOUR_API_TOKEN' with your actual token) TOKEN = 'YOUR_API_TOKEN' # Define the auto-reply function def auto_reply(update, context): message = update.message # Retrieve the text from the incoming message text = message.text.lower() # Define the auto-reply message reply_text = "Thank you for your message. We will get back to you soon!" # Send the auto-reply message context.bot.send_message(chat_id=message.chat_id, text=reply_text) def main(): # Create an updater object updater = Updater(token=TOKEN, use_context=True) # Get the dispatcher to register handlers dispatcher = updater.dispatcher # Register the auto_reply function as a message handler dispatcher.add_handler(MessageHandler(Filters.text & ~Filters.command, auto_reply)) # Start the bot updater.start_polling() # Run the bot until you press Ctrl-C updater.idle() if __name__ == '__main__': main() |
In the code above, make sure to replace 'YOUR_API_TOKEN'
with the API token you received from BotFather.
Step 4: Run the Script Save the Python script, open your terminal or command prompt, navigate to the directory where the script is located, and run the following command:
1 |
python auto_reply_bot.py |