🤖

Developing a Simple Python Telegram Bot

Jul 16, 2024

Developing a Simple Python Telegram Bot

Overview

  • Presenter: Federico Tartarini
  • Objective: Create a basic Python bot that echoes user messages
  • Tool: Python Telegram Bot Library, Google Cloud Functions

Why Google Cloud Functions?

  • Avoids continuous running costs associated with using a server
  • Automatically triggered by a webhook
  • No server maintenance, patching, or updates required

Prerequisites

  • Google Cloud Platform (GCP) account
    • Must enable billing, provide credit card details (likely won't be charged for light use)
  • Python installed on your computer
  • Google Cloud SDK installed on your computer
    • Follow installation instructions based on your OS
  • Telegram account
    • BotFather interaction to create a new bot

Creating a Telegram Bot

  1. In Telegram: Search for BotFather
    • Use command /newbot
    • Name your bot and set a username (unique)
    • Save the API key generated (keep it secret)
    • Example: example_youtube_video_bot
  2. Find or create your bot and save its username

Setting Up Your Python Environment

  1. Open PyCharm
    • Create a new project
    • Name it (e.g., telegram_example)
    • Set base interpreter to Python 3.8
    • Create virtual environment (no global site packages)
  2. Add files:
    • main.py: import os from telegram import Bot def telegram_bot(request): bot = Bot(token=os.environ['TELEGRAM_TOKEN']) if request.method == 'POST': update = request.get_json() chat_id = update['message']['chat']['id'] text = update['message']['text'] bot.send_message(chat_id=chat_id, text=text) return 'OK'
    • .gitignore: Standard Python and PyCharm exclusion
    • .gcloudignore: Exclude .gitignore, README.md, and other unnecessary files for deployment
    • requirements.txt: Should include python-telegram-bot

Deploying on Google Cloud Functions

  1. Using the GCP Console:
    • Create a new project if not already existing
    • Note the project ID
  2. Deploy the function via terminal with gcloud: gcloud functions deploy telegram_bot \ --runtime python38 \ --trigger-http \ --set-env-vars TELEGRAM_TOKEN=<your-api-key> \ --project=<your-project-id>
    • Authenticate if prompted
    • Allow unauthenticated invocation
  3. Set the Telegram Webhook: curl -F "url=https://<your-cloud-function-url>" https://api.telegram.org/bot<your-api-key>/setWebhook

Testing the Bot

  • Send a message to your new bot, it should reply with the same message
  • Example: Send "Ciao", receive "Ciao" back

Modification Example

  • Inside main.py, modify the content returned by the bot: def telegram_bot(request): bot = Bot(token=os.environ['TELEGRAM_TOKEN']) if request.method == 'POST': update = request.get_json() chat_id = update['message']['chat']['id'] text = update['message']['text'] + ' from the bot' bot.send_message(chat_id=chat_id, text=text) return 'test'
  • Deploy changes and test again

Conclusion

  • Ensure proper setup and deployment as guided
  • Check the response to confirm the bot's functionality
  • Refer to the Python Telegram Bot library and Google Cloud documentation for more advanced features and configurations

Resources

Troubleshooting

  • Ensure proper API key usage and secrecy
  • Verify GCP billing is enabled and account is active
  • Follow logs and error messages when deploying to debug issues