Лайфхаки

Маленькие, полезные хитрости

Создание Python Telegram бота и его deploy на.. Часть 1: Создание бота на Python для Telegram

23.08.2023 в 02:40

Создание Python Telegram бота и его deploy на.. Часть 1: Создание бота на Python для Telegram

Первым шагом для создания бота на Python для Telegram является регистрация бота и получение токена доступа. Для этого следуйте инструкциям Telegram и создайте нового бота, получив уникальный токен доступа.

Шаг 2: Установка необходимых библиотек

Далее необходимо установить библиотеку python-telegram-bot, которая предоставляет удобный интерфейс для взаимодействия с Telegram API. Вы можете установить ее с помощью pip, выполнив команду:

Шаг 3: Написание кода бота

Теперь, когда у вас есть токен доступа и установлены необходимые библиотеки, можно приступить к написанию кода бота на Python. Вот простой пример кода, который реагирует на приветствие пользователя и отправляет ответное сообщение:

from telegram.ext import Updater, MessageHandler, Filters def handle_message(update, context): message = update.message.text if message.lower() == 'привет': context.bot.send_message(chat_id=update.effective_chat.id, text='Привет, как дела?') updater = Updater(token='YOUR_TOKEN_HERE', use_context=True) dispatcher = updater.dispatcher dispatcher.add_handler(MessageHandler(Filters.text, handle_message)) updater.start_polling()

Вышеуказанный код создает экземплярUpdater, который устанавливает соединение с Telegram API с использованием вашего токена доступа. Затем мы создаем обработчик сообщенийMessageHandler, который реагирует на текстовые сообщения. В нашем примере он проверяет, содержит ли сообщение текст «привет» и отправляет ответное сообщение.

Deploy Telegram bot for free. Create and deploy your Telegram bot HERE entirely free!

In this tutorial, I will be showing you how you can deploy your telegram bot and keep it running 24/7 entirely for free.

For telegram bot development, there are generally 2 methods used: polling and webhooks. Many tutorials out there make use of polling using a NodeJS or Python server, that listens to any messages received by the bot. This means that in order to deploy it, we would need a server running 24/7 that keeps polling for updates. There aren’t many free options available to keep a server running (the most common one would be Heroku, but once the server sleeps, there isn’t a good way to get it up again to continue responding to messages)

Today, we will explore the options of webhooks. Setting a webhook for your telegram bot means that whenever your bot receives a new message, telegram will send that update to your pre-defined webhook endpoint. From our custom endpoint, we are then free to do whatever we want with this knowledge that our bot has received a message, and we can respond to it.

For example, when our bot receives a message from a user, telegram will send a POST request with a payload containing information about that message (the user, message text, time, etc) to our pre-defined endpoint. Our endpoint will receive that POST request with the payload, and with that, we can respond to the user.

But does this mean we will also need a server to accept these POST requests? Yes, but we do not need the server to be running 24/7. Instead, we will use serverless functions. There are many free serverless function options available: Cloudflare Workers, Vercel Serverless functions, etc.

In this tutorial, we will utilise Cloudflare Workers to create a POST endpoint which we will set up as our webhook for our Telegram bot.

Table of Contents:

  1. Creating a new Cloudflare Worker
  2. 1. Creating a new Cloudflare Worker

  • Navigate to dash.cloudflare.com and login (or sign up)
  • On the sidebar, click on ‘Workers’
  • Click on ‘Create a service’ to create your new worker
  • Enter a name for your new worker and select the ‘HTTP handler’ as the starter, and click on ‘Create service’
  • Once your service has been created, click on ‘Quick Edit’ to edit your worker directly in the browser
  • Now, in your editor, you should be seeing the default code for a new Cloudflare worker.

The logic of how we are going to handle the incoming request will be done in thehandleRequestfunction.

At this point, it is good to know what is the payload that Telegram will be sending to us.

From the payload, we are able to tell who the user is, what is the chat that the user is sending (important for group chats) and what is the message text. As a start, lets make our bot echo the user’s message, but add an ‘over’ at the end of the message.

In this code snippet, we check if the incoming request is a POST, and whether the payload contains the important information from Telegram. We get the chatId and text from the payload, and we generate a unique URL which we will call GET to, which will send a message via our bot programatically. One thing is still missing, which is the${API_KEY}. This is where the bot API token will be substituted into, and we can set this value via the Cloudflare Workers settings.

  • Under the settings panel, click on variables. Here you can set the environment variable for the worker.
  • Click on ‘Add variable’ and input the variable name as API_KEY and the value as the bot’s API token and save your settings.

Now, with our endpoint ready, all that is left to do is to set the webhook of our bot to our custom endpoint.

With our bot API token, and the URL of our new worker (which should be ending with workers.dev), substitute the values into this URL and simply copy and paste it into your browser and enter

If you see this as a response, you’re all set!

Wasn’t that easy?

So now you have set up your telegram bot which is able to run 24/7 entirely for free! You can customise this code to make your bot do anything you want. In a future tutorial, I will be showing you how to use Cloudflare KV to setup a simple database for your bot, to retain user data and enhance the capabilites of your bot! It’s really simple too, so like this tutorial if you want to see more!

Хостинг для телеграм бота Python. Пошаговая инструкция, как запустить бота на хостинге

Сделать универсальное руководство по загрузке телеграм-бота на хостинг нельзя, поскольку для создания ботов используются разные технологии и языки программирования. Чаще всего виртуальных ассистентов для Телеграма пишут на Python или NodeJS. Наша инструкция основана на первом варианте: мы опишем, как выбрать хостинг для чат-бота на Python, установить нужные модули на сервер, залить, запустить, а также поставить бота на автоисполнение. Однако общая схема действий по установке, размещению и запуску может быть применима к любому телеграм-боту.

Создание Python Telegram бота и его deploy на.. Часть 1: Создание бота на Python для Telegram

Изображение от redgreystock на Freepik.

Выбор хостинга для телеграм-бота

Выбирая, где разместить своего чат-бота, следует обращать внимание на возможности и ресурсы, которые поставляет хостинг-провайдер. Установить и запустить телеграм-бота можно и бесплатно: например, через облачный сервис Heroku. Но бесплатный хостинг крайне ограничен и часто небезопасен. Если у вас простой бот, который отвечает на триггеры заготовленными репликами, его можно залить на обычный shared hosting. Главное, найти тариф с поддержкой Python и Telegram API.

Если же ваш помощник основан на нейросети и ожидается большой поток клиентов, лучше остановиться на аренде VPS (Virtual Private Server). На виртуальном сервере подключение будет стабильнее за счет изолированности вычислительных мощностей, а кроме того, VPS легче масштабировать. Вам не понадобится сайт и домен, чтобы его арендовать: подключиться можно будет по выделенному IP-адресу.

Допустим, вы заказали подходящий сервер и удаленно подключились к нему по SSH. Прежде чем размещать на нем файлы нашего бота, нужно установить зависимости, которые потребуются для его работы. В частности, это язык Python и библиотека РуTelegramBotAPI. Мы покажем, как поставить эти компоненты на примере ОС Ubuntu. Введите в терминал:

sudo apt install python3
sudo apt install python3-pip

Мы взяли третью версию «Питона», но если ваш бот написан на другой, то загрузите нужную. Теперь можно заливать файл на сервер.

Размещение чат-бота

Сначала создадим папку, в которой будем размещать телеграм-бота:

cd /home
mkdir имя_папки
cd имя_папки

Где имя_папки — это придуманное вами название директории (на латинице). Команда cd позволит нам перейти в эту директорию. Далее необходимо загрузить сами файлы. Это можно сделать через сторонний FTP-клиент (например, FileZilla) или панель управления VPS/VDS, если она имеется. В любом случае вам понадобятся данные для входа на сервер: логин, пароль и IP-адрес (вы должны были использовать их, когда устанавливали SSH-подключение). Откройте выбранную программу, найдите папку с указанным именем и залейте в нее файлы телеграм-бота.

Запуск бота

Чтобы запустить бота, примените команду следующего вида, подставив свое значение:

python3 имя_файла.ру

Обычно проект телеграм-бота хранится в файле с названием main.py или bot.py. У вас он может иметь другое имя, главное, чтобы расширение было «ру».

После этой команды ваш бот будет запущен. Вы можете убедиться в этом, зайдя в Телеграм и обратившись к нему в чате. Но есть одно но: сейчас ассистент работает, как приложение. Если вы закроете консоль, куда ввели команду для запуска, чат-бот отключится. Исправим это на следующем шаге.

Настройка автозапуска телеграм-бота

Ставить нашего бота на автовыполнение мы будем с помощью менеджера systemd. Чтобы создать службу, введите команду вида:

sudo nano /lib/systemd/system/example_bot.service

Замените example_bot на собственное значение. Теперь нужно прописать конфигурацию юнита. Она может выглядеть следующим образом:

Description=Example - Telegram Bot \\В переменной «Description» вы можете указать название своего бота, это просто описание, чтобы при открытии файла вы сразу поняли, к чему относятся нижеследующие параметры.

After=syslog.target
After=network.target

Type=simple
WorkingDirectory=/home/имя_папки/

ExecStart=/usr/bin/python3 /home/имя_папки/имя_файла.py \\Здесь и выше укажите названия, которые установили для директории и файла с ботом.

RestartSec=60
Restart=always

WantedBy=multi-user.target

Чтобы сохранить изменения и выйти, нажмите CTRL+S и CTRL+X. Теперь остается только запустить саму службу:

sudo systemctl enable example_bot
sudo systemctl start example_bot

Где example_bot — это название службы, которое вы указали в начале данного шага. Готово! Ваш телеграм-бот будет работать в фоновом режиме, даже когда вы отключитесь от сервера.

Python-telegram bot docker. Вступление


В связи с обстановкой тотальной паники и дезинформации которая льется к нам из абсолютно всех каналов таких как мессенджеры, новостные сайты, радио, телевидение было принято решение показать как можно победить коронавирус с помощью бота на python и других интересных ингредиентов для Telegram (шутка)!

Для приготовления вакцина-бота в домашних условиях требуется эвм, python, docker , heroku CLI , telegram мессенджер как платформа и mongoDB в качестве базы данных. Всем остальным можно пренебречь в начале нашего рассказа, в конце будет предоставлен полный список и дозировка для критического анализа и дальнейшего развития.

Что мы хотим сделать

Начнем с того, что определимся, что мы хотим сделать, это телеграмм бот который будет уметь показывать:

  • Статистику случаев заражения COVID-19 на текущую дату по любой стране
  • Статистику случаев заражения COVID-19 по геолокации
  • Статистику запросов стран пользователями
  • Статистику действий пользователей
  • Информацию о контактах
  • Справку, о том, как пользоваться ботом

Что мы будем с этого иметь

Чему мы научимся во время приготовления вакцина-бота:

  • Работой с базой данных mongodb(подключение, получение данных, сохранение)
  • Работа с внешними API
  • Упаковка приложения в Docker контейнер
  • Бесплатная публикация бота на PAAS платформу Heroku
  • CI приложения с помощью Github и Heroku

Затем необходимо зарегистрировать нашего бота в Telegram и получить токен для работы с ним из нашего кода. Процедура тривиальная, но все же для тех кто не знаком с платформой опишу пошагово:

  • Найти бота в Telegram по имени “ BotFather ”
  • Выполнить команду /start
  • Выполнить команду /newbot
  • Выбрать ник бота и адрес по которому он будет доступен в Telegram
  • Сохраняем token который бот вернул нам в ответе в блокнот

Подготовка машины для программирования бота

Для того чтобы подготовить машину к программированию бота для Telegram необходимо поставить на нее следующее программное обеспечение:

  • Интерпретатор языка программирования Python
  • Консольное приложение git CLI
  • Систему управления контейнерами Docker
  • Сервер баз данных MongoDb
  • IDE или редактор для разработки ПО на Python, я пользуюсь Pycharm от JetBrains

Структура приложения

Структура приложения может быть выбрана вами в зависимости от ваших потребностей, целей и опыта. Но перед этим предлагаю вам создать репозиторий на github с названием вашего бота и склонировать его к себе на машину, это необходимо для использования системы контроля версий и настройки CI в перспективе.

Готовый скрипт бота телеграм Python. python-telegram-bot-template

This repository serves as a template to create newapplications, their python wrapper over the Telegram API is amazing and enables very smooth programming for bots. It doesn't however provide defaults for persistence, state management and other shortcuts that are necessary for a maintainable and growable software architecture.

This template is mostly meant for projects that start with quite a bit of complexity and whose requirements are going to evolve as time passes.

Please read!

The documentation from this point forward may be incorrect, I did some refactoring for a few wrapper and edited a few typings as my new LSP gave me a lot of errors (went from Pycharm to Pyright). I will update this documentation in the future.

Foreword

I made this template to provide an implementation for a few things that I always ended up implementing in my telegram bot projects, customApplicationContextforcontext.bot_data, context.chat_data, context.user_datatyping, decorators/wrappers for handlers to cut down on a bit of boilerplate and implement common behaviours. This will take the mind off technicalities and instead help put your focus where it belongs, on the project.

On a sidenote: the code inside ofencoders.pyforjsonable_encoderis from

Run the Bot

To run the bot you just have to executemain.pywith the following environment variables set:

    MONGODB_CONNECTION_URLneeded to conntect to your database, feel free to swap out the persistence layer with anything you prefer or to remove it entirely, MongoDB together with their atlas-cloud database is a nice way to get started prototyping your small projects. In hindsight I should have just used SQLite with SQLAlchemy, this would allow anyone that pulls the template to just start it up with a bot token. MONGODB_DATABASEname of your database BOT_TOKENyou can get one from Botfather

Devops and Dependency management

name : CI on : push : branches : jobs : docker-build : runs-on : ubuntu-latest steps : - uses : actions/checkout@v3 - name : Install Poetry uses : snok/install-poetry@v1 - name : create requirements run : poetry export --without-hashes --format=requirements.txt > requirements.txt - name : Login to Docker Hub uses : docker/login-action@v2 with : username : ${{ secrets.DOCKERHUB_USERNAME }} password : - : : : : : :

This simple CI script will get your pipeline started, it uses poetry to export yourpyproject.tomldependencies as arequirements.txtfile that is needed for the Docker build, then proceeds to push the built image to your docker repository, afterwards any Continuous Deployment solution may take over from there. Once you have started implementing some business logic you can add apoetry run pyteststep to the pipeline (remember to poetry install first) .

The template ships with, if you don't want to use this just deletepyproject.toml, poetry.lockand keep arequirements.txtfile in your project for the docker build.

Configuration

The app gets its configuration from environment variables that are defined in the classes extendingpydantic.BaseSettingsinsettings.py

from pydantic import BaseSettings class DBSettings ( BaseSettings ): MONGODB_CONNECTION_URL : str MONGODB_DB : str class TelegramSettings ( BaseSettings ): BOT_TOKEN : str class Settings ( TelegramSettings , DBSettings ): pass settings = Settings ()

How to persist entities

For the persistence layer of the project I created two main template classes to extend,MongoEntityandBaseDao, both live indb.core.

Источник: https://lajfhak.ru-land.com/novosti/sozdanie-i-hosting-telegram-bota-hosting-ili-server