🤖

Creating a Telegram Bot in Python (2023)

Jul 14, 2024

Creating a Telegram Bot in Python (2023)

Introduction

  • The video demonstrates how to create a Telegram bot in Python compatible with both groups and private chats.
  • Updates to the 2022 version are necessary due to changes in the API.
  • Development environment: PyCharm using Python 3.11.

Setting Up the Bot on Telegram

  1. Open Telegram on phone/computer.
  2. Search for BotFather and click on "Start".
  3. Use the /newbot command to create a new bot.
  4. Name and Username:
    • Example: "Banana Bot" and "banana_bot".
    • Note: Username must be unique and end with 'bot'.
  5. Receive access token:
    • Copy this token for use in the Python script.

Initializing Python Script

  1. Define constants in the script:
    TOKEN: Final = 'your-token-here'
    BOT_USERNAME: Final = '@your_bot_username'
    
  2. Install necessary packages:
    pip install python-telegram-bot
    
  3. Import required modules: python from telegram import Update from telegram.ext import Application, CommandHandler, MessageHandler, Filters, ContextTypes from typing import Final

Creating Bot Commands

  • Define async command functions:
    • Example: Start command
      async def start_command(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
            await update.message.reply_text('Hello, thanks for chatting with me. I am a banana.')
      
    • Create other commands such as help and custom commands similarly.

Handling Responses

  • Define a handler function for processing text:

    def handle_response(text: str) -> str:
          text = text.lower()
          if 'hello' in text:
               return 'Hey there!'
          elif 'how are you' in text:
               return 'I am good!'
          elif 'i love python' in text:
               return 'Remember to subscribe!'
          else:
               return 'I do not understand what you wrote.'
    
  • Define the message handler:

    async def handle_message(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
          message_type = update.message.chat.type
          text = update.message.text.lower()
    
          if message_type == 'group' and BOT_USERNAME in text:
               text = text.replace(BOT_USERNAME, '').strip()
               response = handle_response(text)
          else:
               response = handle_response(text)
    
          await update.message.reply_text(response)
    

Logging Errors

  • Define an error logging function:
    async def error(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
          print(f'Update {update} caused error {context.error}')
    

Putting It All Together

  1. Create and configure the application:
    if __name__ == '__main__':
        app = Application.builder().token(TOKEN).build()
    
        app.add_handler(CommandHandler('start', start_command))
        app.add_handler(CommandHandler('help', help_command))
        app.add_handler(CommandHandler('custom', custom_command))
        app.add_handler(MessageHandler(Filters.text & (~Filters.command), handle_message))
    
        app.add_error_handler(error)
    
        print('Starting bot...')
        app.run_polling(poll_interval=3)
    

Setting Commands in BotFather

  • Use /setcommands to define bot commands:
    start - Starts the bot
    help - Provides help for the bot
    custom - This is a custom command
    

Running and Testing the Bot

  1. Run the script in PyCharm.
  2. Check for "Starting bot..." and "Polling..." messages in the console.
  3. Interact with the bot in Telegram:
    • Private chat: send messages and test responses.
    • Group chat: mention the bot for it to respond (requires admin rights).

Conclusion

  • The bot can now handle basic commands and respond to messages in both private and group chats.
  • Future work: Add more features and AI to improve responses.

Additional Remarks

  • Keep the bot's token secure.
  • Use proper error handling for a more robust bot.
  • Regular updates might be required as the Telegram API evolves.

Enjoy coding your Telegram bot! 🚀


Note: The project is updated for 2023 as APIs change frequently; regular updates might be needed.

Keywords: Telegram, Bot, Python, API, Async Programming, Chatbot, 2023

For More: Follow and subscribe for more Python and programming-related content! 😉


Resources:


Author's Note: Thanks for watching! See you in the next video.

Emoji Summary

Create interactive Telegram bots with Python! 🤖✨