Skip to content

Телеграм боты

Как сделать тг-бота с помощью Yandex Cloud Functions?

  1. Создаем бота в @botfather, получаем токен

  2. Ставим либу

    pip install python-telegram-bot
    
  3. Пишем функцию

    import json
    import os
    
    import telegram
    
    
    def handler(event, context):
        bot = telegram.Bot(token=os.environ['TG_TOKEN'])
        update = telegram.Update.de_json(json.loads(event['body']), bot)
    
        chat = update.message.chat_id
        msg = update.message.text
    
        bot.send_message(chat, msg)
    
        return {'statusCode': 200, 'body': '', }
    
  4. Заливаем ее, напр. с помощью плагина

  5. Дружим бота и функцию

    POST https://api.telegram.org/bot{{ TG_BOT_TOKEN }}/setWebhook
    Content-Type: application/json
    
    {
      "url": "https://functions.yandexcloud.net/{{YA_CLOUD_FUNCTION_ID}}"
    }
    

Источник: https://cloud.yandex.ru/docs/api-gateway/tutorials/telegram-bot-serverless