Pip install pytelegrambotapi как установить
Pip install pytelegrambotapi как установить
Telegram Bot на Python 3
В данной статье мы напишем telegram bot на python, который сможет отвечать на наши сообщения, взаимодействовать с нами, предлагая варианты ответов в виде кнопок и обрабатывать выбранный нами результат, выполняя команды на сервере. Взаимодействовать с Telegram Bot Api мы будем с помощью библиотеки pyTelegramBotAPI (telebot) написанной на Python.
Создание бота
Для регистрации нового бота необходимо обратиться к боту BotFather. Для этого в строке поиска наберите BotFather и в показанных результатах найдите интересующего нас бота:
Обратите внимание на его имя, изображение и знак в виде галочки, говорящий о том, что это действительно отец всех ботов.
Выберите его и в диалоговом окне напишите команду /start и бот в ответном сообщение пришлет список всех доступных команд:
Нас интересует создание нового бота, поэтому выбираем команду /newbot. Команду можно как напечатать самостоятельно, так и выбрать мышью в сообщении и она автоматически отправится:
Первым шагом нам предлагают дать имя новому боту, оно может быть произвольным. Мы назовем его PocketAdmin:
Теперь требуется указать идентификатор бота (username), он должен заканчиваться на _bot и быть уникальным в системе. Мы укажем PocketAdminTech_bot:
На этом создание бота завершено. В последнем сообщении нам пришла ссылка на нашего нового бота t.me/PocketAdminTech_bot и токен (закрашен), необходимый для взаимодействия с API.
Обязательно сохраните токен и храните его в тайне!
Установка Python и библиотеки pyTelegramBotAPI
Скачать Python можно с официального сайта (как установить пакет на Centos 8 можно ознакомиться в данной заметке) и мы не будем заострять внимание на данном вопросе.
Чтобы установить пакет pyTelegramBotAPI воспользуемся pip:
На этом подготовительная работа завершена, приступаем непосредственно к написанию нашего бота.
Пишем Telegram Bot на Python
Так как наш бот создается в ознакомительных целях и не будет содержать много кода, то писать я его буду сразу на сервере с установленной Centos 8 используя обычный редактор nano. Создадим файл bot.py, открыв его nano:
Для начала импортируем библиотеку pyTelegramBotAPI:
Затем зададим переменную token равную нашему токену, который мы получили от BotFather для взаимодействия с Telegram Bot Api:
Далее задается декоратор. Пока наш бот будет обрабатывать только команду start:
и в ответ писать нам “Привет!”:
Чтобы бот постоянно ожидал запрос от пользователя в конце пропишем:
В итоге мы получим код:
Затем откроем нашего бота (можно найти по имени) и напишем ему команду /start:
Поздравлю с первыми словами нашего бота PocketAdmin!
Использование прокси в telebot
При запуске скрипта может появиться ошибка следующего вида:
Чтобы исправить её, можно попробовать подключиться через прокси:
где login:password@ip:port – соответствующие данные для подключения к прокси.
Если при использовании прокси возникают ошибки, подобные: Not supported proxy scheme socks5 или Missing dependencies for SOCKS support, то необходимо установить модули:
Ответы бота на сообщения пользователя
Аналогично хэндлерам для команд, в telegram bot api есть возможность обрабатывать сообщения от пользователя. Для этого используется тип text. Например, мы можем запрограммировать бота отвечать на определенные фразы или слова пользователя:
Думаю тут все понятно. На слово “Привет” бот будет отвечать “Ещё раз привет!”, а на “Пока” – “Пока!”. Весь код нашего telegram bot на python теперь будет выглядеть следующим образом:
Перезапустим скрипт и пообщаемся с ботом:
Таким образом мы можем описывать различные диалоги с ботом.
Клавиатура в Telegram Bot на Python
Апи телеграма позволяет использовать свою клавиатуру, а точнее быстрые кнопки, позволяющие пользователю отправлять текст по их нажатию.
Добавим в обработчик команды /start клавиатуру с кнопками “Привет “и “Пока”:
И запустим измененный скрипт. Как только мы отправим боту команду /start у нас внизу появится наша клавиатура:
Теперь для отправки сообщений достаточно лишь нажать на соответствующую кнопку. Это очень удобно в мобильной версии телеграма.
InLine клавиатура
На мой взгляд, наиболее интересной является InLine клавиатура. Она позволяет вместе с сообщением отправлять пользователю интерактивные кнопки, например с вариантами ответов, а после их нажатия обрабатывать результат.
Давайте добавим простой вопрос от бота на команду /test:
Переменная markup объявляет новую переменную с inline keyboard, а markup.add – создает отдельную кнопку. Основные параметры при создании кнопки – text и callback_data: первый отвечает за текст на кнопке, второй – данные, которые будут переданы боту при выборе пользователем определенного варианта ответа.
Запустим скрипт и напишем /test:
Отлично, бот прислал нам варианты ответов. Но при нажатии на кнопку ничего не произойдет, т.к. мы не описали обработку результатов. Исправим это:
bot.answer_callback_quer – это всплывающее окно, которое будет показано пользователю после нажатия кнопки. А в call.data будет передано значение, которое мы указывали при создании клавиатуры в параметре callback_data. Ответим боту, выбрав один из ответов:
Отлично, все работает. Но будет лучше, если после ответа, клавиатура будет исчезать из чата. Это можно сделать добавив в конец функции query_handler следующую строку:
Это функция редактирования клавиатуры, вызванная без указания объекта клавиатуры. Теперь после ответа пользователя клавиатура будет убрана ботом:
Конечный листинг телеграм бот на питоне
Мы рассмотрели лишь малую часть возможностей telegram bot api, однако, это очень полезные инструменты по работе с ним. В конце приведем полный листинг получившегося у нас telegram bot на python:
telebot быстро и понятно. Телеграмм-бот
telebot (pyTelegramBotAPI) хорошая и лёгкая библиотека для создания бота на python для телеграмма.
Установка
Если у вас windows, тогда вам надо найти cmd на своём пк, а если у вас macOS, тогда вам надо открыть терминал.
Для установки telebot (pyTelegramBotAPI) на windows вам надо написать в cmd
Для установки на macOS нам надо написать в терминале
Написание кода
Сначала надо получить токен. Для этого зайдём к боту botfather,чтобы получить токен (botfather)
Теперь можно начать писать код.Сначала мы импортируем библиотеку.
Теперь создаём переменную под названием token, в ней мы будем хранить наш токен.
Теперь мы можем создать приветствие бота:
Нам надо создать переменную bot, в ней мы пишем telebot.Telebot (наша переменная с токеном).
Создаём функцию под названием «start_message»
В скобках указываем «message».
Пишем внутри функции bot.send_message(message.chat.id,»Привет»)
и вне функции пишем bot.infinity_poling()
и запускаем программу.
Теперь наш бот может приветствовать
Приветствие мы сделали, теперь давайте сделаем кнопку.
Надо написать from telebot import types там же, где мы импортировали библиотеку telebot
Теперь пишем @bot.message_handler(commands=[‘button’]). Дальше мы создаём функцию под названием button_message, в скобках указываем message.
Дальше надо создать клавиатуру в переменной под названием markup, в переменной пишем types.ReplyKeyboardMarkup(resize_keyboard=True).
Потом создаём переменную item1, в ней будет хранится сама кнопка и пишем что item1=types.KeyboardButton(«текст на кнопке»).
Дальше к клавиатуре добавим нашу кнопку
Далее надо отправить сообщение «Выберите что вам надо» и после текста написать reply_markup=markup и закрываем скобки.
Теперь у нас есть кнопка. Вот пример:
Но если мы на неё нажмём, то ничего не произойдёт. Сейчас мы сделаем так, чтобы при нажатии на кнопку выдавало ссылку на мою страницу в Хабре.
Для начала мы напишем @bot.message_handler(content_types=’text’)
Дальше нам надо создать функцию по названием message_reply, а в скобках указать message.
Внутри функции надо указать условие «if message.text==»Кнопка:», а внутри условия отправить нам нужное сообщение.
Смена кнопок
Это последняя часть статьи.В следующей статье мы разберём с вами добавление в группу или канал.
Это можно считать самая лёгкая часть статьи.
Мы разберём сейчас с вами замену кнопок.
Теперь нам просто надо создать клавиатуру с кнопками и добавить к клавиатуре кнопку как в прошлой части в тоже самое условие.Дальше в той же функции написать:
Теперь при нажатии на Кнопку 1 она у нас сменяется на кнопку 2 и при нажатии на кнопку 2 у нас присылает сообщение «Спасибо за прочтение статьи!».
Подготовка рабочего места в Windows и Linux. Virtual Environment (venv). Ответы на вопросы
Предисловие
Весь текст ниже появился как попытка дать универсальный ответ на те вопросы, которые дорогие читатели присылали и продолжают присылать раз за разом. Здесь не будет кода, связанного с ботами напрямую, а лишь советы по организации процесса написания. И, конечно же, не нужно воспринимать это как истину в последней инстанции, напротив, выбирайте те инструменты и подходы к разработке, которые лично вам кажутся удобными. Важная деталь: текст написан в конце 2019 года. Достаточно вступительных слов, поехали!
Предположим, вы уже немного знаете язык Python 3 (забудьте про Python 2.7, он мёртв), умеете писать простенькие программы и хотите взяться за разработку ботов. Где это делать? В чём писать код? Как правило, у большинства начинающих программистов основной операционкой используется Microsoft Windows. С неё и начнём, но сперва…
Virtual environment
Вы когда-нибудь пользовались VirtualBox? Например, чтобы «пощупать» другие операционные системы или просто установить какой-нибудь подозрительный софт. Python Virtual environment (далее — venv) чем-то напоминает «виртуалку». При его использовании создаётся копия выбранного интерпретатора Питон, а все устанавливаемые модули хранятся изолированно от общесистемных, тем самым, упрощается их обновление, удаление или изменение. Часто venv позволяет избежать ошибок, связанных с обратной совместимостью некоторых библиотек, а также обойтись без конфликтов с системными модулями. Работа с venv будет подробнее описана ниже в разделе Linux, но использовать его мы будем везде.
Windows
Создание нового проекта в PyCharm
Установка библиотеки через терминал в PyCharm
Прекрасно, теперь начинайте творить! Создайте первый файл с исходником, нажав правой кнопкой мышки по имени проекта в списке файлов, затем New и Python File.
Создание нового файла кода в PyCharm
Запустить код можно, выбрав сверху пункт Run, затем снова Run…, но с многоточием, и затем выбрав созданный ранее файл.
Как залить файлы на сервер?
Для копирования файлов на удалённый сервер (обычно там стоит Linux), я использую замечательную бесплатную программу WinSCP, причём в ней присутствует режим автоматической синхронизации файлов, чтобы при любом изменении в локальном каталоге обновлялось содержимое на удалённой машине, избавляя вас от необходимости копировать всё вручную.
Скриншот программы WinSCP
При помощи WinSCP можно даже просто подключиться к серверу и подправить файл «на лету», не забудьте только потом перезапустить бота!
Linux
Хорошим правилом будет иметь на сервере ровно ту же версию Python, что и на своей локальной машине, во избежание различных неприятностей. Если версия на сервере ниже 3.7 и/или ниже той, что установлена локально, лучше всего будет установить её отдельно. Очень рекомендую вот эту статью, по которой я для себя написал простой скрипт для автоматизации рутинных действий. Итак, интерпретатор установлен, теперь пора создать каталог, куда положим файлы бота. Выполните по очереди следующие команды:
В результате должно получиться примерно то же самое, что на скриншоте ниже, с той лишь разницей, что я прервал процесс установки библиотеки для читабельности. Обратите внимание, что после подгрузки файла venv/bin/activate, перед названием пользователя и текущего каталога появится приписка (venv), означающая, что мы «вошли» в виртуальное окружение и устанавливаем библиотеки именно в него.
Создание venv в Linux-терминале
Что произошло выше? Во-первых, мы создали каталог с названием mybot и перешли в него. Во-вторых, мы использовали Python версии 3.7 (в вашем случае это может быть не так), чтобы создать виртуальное окружение в подкаталоге venv. В-третьих, мы «активировали» venv и выполнили в нём нужную нам команду. Внутри venv команды pip и python точно знают, к какому именно интерпретатору они относятся, поэтому путаницы вроде «я установил библиотеку для Python 3.5, а запускаю из-под Python 3.7» попросту не будет. Наконец, в-четвёртых, мы деактивировали venv, поскольку он напрямую нам больше не нужен. Чтобы сделать жизнь ещё приятнее, давайте настроим автозагрузку бота, чтобы при возникновении ошибок или при перезапуске сервера он вновь запускался, избавляя нас от необходимости постоянно проверять всё вручную. Для этого мы воспользуемся подсистемой инициализации systemd, которая всё больше распространена в современных Linux-дистрибутивах. Прежде, чем описать службу systemd, откройте главный файл с ботом, в котором прописан его запуск и добавьте в качестве первой строки следующий код: #!venv/bin/python
Проверка статуса бота через systemd
Как редактировать файлы на сервере?
Если что-то нужно подправить небольшое, то неплохим вариантом остаётся старое доброе подключение по SSH и использование редакторов вроде micro, nano или даже vim с emacs. Но если вдруг у вас в качестве локальной машины применяется Linux, то крайне рекомендую редактор Visual Studio Code (https://code.visualstudio.com) с дополнением Remote-SSH. В этом случае, вы сможете прямо в VS Code открывать каталоги на сервере и редактировать файлы в удобном окружении и с подсветкой синтаксиса. К сожалению, насколько мне известно, расширение Remote-SSH не работает в Windows, но впоследствии этот недочёт будет устранён.
Ответы на часто задаваемые вопросы (FAQ)
Хочу научиться писать ботов. С чего мне начать?
Прежде всего, пожалуйста, изучите хотя бы немного сам язык Python. Он довольно простой, но перед созданием ботов стоит понять азы. Конкретнее: переменные, циклы, функции, классы, обработка исключений, работа с файлами и файловой системой.
Можно ли писать ботов на телефоне?
Да кто ж вам запретит-то? Но лучше от этого никому не будет, поверьте. Будет трудно, неудобно и контрпродуктивно. Используйте нормальный компьютер.
[pyTelegramBotAPI] Ошибка AttributeError: module ‘telebot’ has no attribute ‘TeleBot’!
На 99% уверен, что вы установили библиотеку telebot вместо pytelegrambotapi. С учётом всего вышесказанного проще создать новое окружение venv, перенести туда нужные файлы и установить именно pytelegrambotapi, при этом в исходниках должно остаться import telebot.
Как мне держать бота запущеным в Windows?
Запустите бота в PyCharm, не закрывайте приложение и не выключайте комп. Почти шутка. По-моему, Windows — не самая лучшая операционка для подобных вещей, проще арендовать сервер у европейских провайдеров, заодно не будет геморроя с варварами из Российского Консорциума Неадекватов.
Библиотека pyTelegramBotAPI не поддерживает новые фичи Bot API!
К сожалению, упомянутая библиотека в 2019 году развивалась гораздо медленнее, чем хотелось. Если вы уже чувствуете себя уверенным ботописателем, подумайте о переходе на альтернативы вроде aiogram.
В завершение хочется напомнить, что если у вас возникли замечания, предложения или вопросы, вы всегда можете открыть issue на Github или прийти к нам в чатик.
Телеграм-бот на Python
15 минут — и можете запускать своего первого бота.
В первой части мы сделали гороскоп на Python, который выдаёт нам прогноз на день по знаку зодиака. Сегодня пойдём дальше: теперь этот же генератор гороскопов будет встроен в Телеграм в виде бота.
Да. То, что обычно на курсах продают за 50 тысяч рублей, мы вам сейчас расскажем за 15 минут бесплатно.
Как всё будет работать
В этом проекте три звена: наш компьютер с Python, сервер Телеграма и Телеграм-клиент.
На компьютере работает интерпретатор Python, а внутри интерпретатора крутится наша программа на Python. Она отвечает за весь контент: в неё заложены все шаблоны текста, вся логика, всё поведение.
Внутри программы на Python работает библиотека, которая отвечает за общение с сервером Телеграма. В библиотеку мы вшили секретный ключ, чтобы сервер Телеграма понимал, что наша программа связана с определённым ботом.
Когда клиент с Телеграмом запрашивает у бота гороскоп, запрос приходит на сервер, а сервер отправляет его на наш компьютер. Запрос обрабатывается программой на Python, ответ идёт на сервер Телеграма, сервер отдаёт ответ клиенту. Изи:
Обратите внимание, что работать наш бот будет только тогда, когда включён компьютер и на нём запущена программа на Python. Если компьютер выключится, пропадёт интернет или вы отключите интерпретатор, то бот работать перестанет: запросы будут приходить, но никто на них не ответит. В одной из следующих частей мы сделаем так, чтобы это всё работало на удалённом сервере и было всегда доступно.
Что будем делать
Если записать пошагово наш план, то он будет выглядеть так:
Теперь по очереди разберём каждый пункт.
1. Регистрация нового бота
В Телеграме находим канал @BotFather — он отвечает за регистрацию новых ботов:
Первый в списке со специальным значком подтверждения — это он.
Нажимаем Start и пишем команду /newbot. Нас по очереди спросят про название бота и его никнейм (мы придумали только с третьей попытки, потому что остальные были заняты):
С третьей попытки нам дали нового бота и токен для управления. Токен нужен для управления ботом, поэтому на экране его нет.
2. Установка библиотеки
Есть два основных способа работать с телеграмом в Python: через библиотеку telebot и с помощью Webhook. Мы будем использовать библиотеку — так проще и быстрее.
Чтобы её установить, запускаем командную строку от имени администратора (если у вас Windows) и пишем команду pip install pytelegrambotapi
В конце видим сообщение об успешной установке, значит всё сделали правильно.
Подключаем библиотеку и получаем сообщения
Чтобы программа на Python умела управлять Телеграм-ботами, нужно в самое начало кода добавить строки:
Единственное, о чём нужно не забыть — заменить слово «токен» на настоящий токен, который дал нам @BotFather. Открываем программу гороскопа и добавляем.
Теперь научим бота реагировать на слово «Привет». Для этого добавим после строчек с импортом новый метод и сразу пропишем в нём реакцию на нужное слово. Если не знаете, что такое метод и зачем он нужен, — читайте статью про ООП.
И последнее, что нам осталось сделать до запуска, — добавить после метода такую строчку:
Она скажет программе, чтобы она непрерывно спрашивала у бота, не пришли ли ему какие-то новые сообщения. Запускаем программу и проверяем, как работает наш бот.
Бот отвечает именно так, как мы запрограммировали. Класс.
Такая ошибка во время запуска программы означает, что компьютер не может соединиться с сервером telegram.org, потому что его блокирует Роскомнадзор. Что делать? Сложно сказать. Если бы вы жили в другой стране, этой проблемы бы не было. Ещё можно использовать какие-то средства, которые направляют ваш трафик через другую страну, но рассказ об этих средствах является в России преступлением, поэтому тут мы вам ничего не можем подсказать.
Добавляем кнопки
Чтобы пользователям нашего бота было удобно, покажем им сразу все знаки зодиака в виде кнопок. А потом сделаем так, что когда на них нажимаешь — появляется гороскоп для этого знака на сегодня.
Добавляем код с кнопками в раздел, который реагирует на «Привет»:
Кнопки есть, но пока не работают. Сейчас исправим.
Добавляем обработчик кнопок
Давайте сделаем обработчик кнопок, который будет реагировать на ‘zodiac’ и выдавать случайный текст, как в исходной программе. Для этого добавим новый метод в программу:
Нажимаем на кнопку — получаем текст гороскопа.
Убираем лишнее
Теперь у нас есть готовый бот, и нам осталось только убрать лишний код, который раньше отвечал за вывод знаков зодиака в консоли. После чистки получаем готовую программу:
Как видно, большую часть кода занимает тупое перечисление всех знаков зодиака. Мы могли бы автоматизировать это через циклы, но на улице такая хорошая погода, что мы это отложим.
Что дальше
Впереди — безграничные возможности:
Напишите в комментариях, что бы вы хотели от такого бота? Что должен уметь идеальный бот с гороскопом?
pyTelegramBotAPI 4.6.0
pip install pyTelegramBotAPI Copy PIP instructions
Released: Jun 23, 2022
Python Telegram bot api.
Navigation
Project links
Statistics
View statistics for this project via Libraries.io, or by using our public dataset on Google BigQuery
License: GNU General Public License v2 (GPLv2) (GPL2)
Author: eternnoir
Tags telegram, bot, api, tools
Maintainers
Classifiers
Project description
A simple, but extensible Python implementation for the Telegram Bot API.
Both synchronous and asynchronous.
Supported Bot API version: 6.1!
Official documentation
Contents
Getting started
This API is tested with Python 3.6-3.10 and Pypy 3. There are two ways to install the library:
It is generally recommended to use the first option.
While the API is production-ready, it is still under development and it has regular updates, do not forget to update it regularly by calling
Writing your first bot
Prerequisites
A simple echo bot
Note: Make sure to actually replace TOKEN with your own API token.
After that declaration, we need to register some so-called message handlers. Message handlers define filters which a message must pass. If a message passes the filter, the decorated function is called and the incoming message is passed as an argument.
Let’s define a message handler which handles incoming /start and /help commands.
A function which is decorated by a message handler can have an arbitrary name, however, it must have only one parameter (the message).
Let’s add another handler:
This one echoes all incoming text messages back to the sender. It uses a lambda function to test a message. If the lambda returns True, the message is handled by the decorated function. Since we want all messages to be handled by this function, we simply always return True.
Note: all handlers are tested in the order in which they were declared
We now have a basic bot which replies a static message to «/start» and «/help» commands and which echoes the rest of the sent messages. To start the bot, add the following to our source file:
Alright, that’s it! Our source file now looks like this:
To start the bot, simply open up a terminal and enter python echo_bot.py to run the bot! Test it by sending commands (‘/start’ and ‘/help’) and arbitrary text messages.
General API Documentation
Types
You can use some types in one function. Example:
content_types=[«text», «sticker», «pinned_message», «photo», «audio»]
Methods
General use of the API
Outlined below are some general use cases of the API.
Message handlers
A message handler is a function that is decorated with the message_handler decorator of a TeleBot instance. Message handlers consist of one or multiple filters. Each filter must return True for a certain message in order for a message handler to become eligible to handle that message. A message handler is declared in the following way (provided bot is an instance of TeleBot):
name | argument(s) | Condition |
---|---|---|
content_types | list of strings (default [‘text’] ) | True if message.content_type is in the list of strings. |
regexp | a regular expression as a string | True if re.search(regexp_arg) returns True and message.content_type == ‘text’ (See Python Regular Expressions) |
commands | list of strings | True if message.content_type == ‘text’ and message.text starts with a command that is in the list of strings. |
chat_types | list of chat types | True if message.chat.type in your filter |
func | a function (lambda or function reference) | True if the lambda or function reference returns True |
Here are some examples of using the filters and message handlers:
Important: all handlers are tested in the order in which they were declared
Edited Message handler
Handle edited messages @bot.edited_message_handler(filters) #
Channel Post handler
Handle channel post messages @bot.channel_post_handler(filters) #
Edited Channel Post handler
Handle edited channel post messages @bot.edited_channel_post_handler(filters) #
Callback Query Handler
Handle callback queries
Shipping Query Handler
Handle shipping queries @bot.shipping_query_handeler() #
Pre Checkout Query Handler
Handle pre checkoupt queries @bot.pre_checkout_query_handler() #
Poll Handler
Handle poll updates @bot.poll_handler() #
Poll Answer Handler
Handle poll answers @bot.poll_answer_handler() #
My Chat Member Handler
Handle updates of a the bot’s member status in a chat @bot.my_chat_member_handler() #
Chat Member Handler
Handle updates of a chat member’s status in a chat @bot.chat_member_handler() # Note: «chat_member» updates are not requested by default. If you want to allow all update types, set allowed_updates in bot.polling() / bot.infinity_polling() to util.update_types
Chat Join Request Handler
Handle chat join requests using: @bot.chat_join_request_handler() #
Inline Mode
More information about Inline mode.
Inline handler
Now, you can use inline_handler to get inline queries in telebot.
Chosen Inline handler
Use chosen_inline_handler to get chosen_inline_result in telebot. Don’t forgot add the /setinlinefeedback command for @Botfather.
Answer Inline Query
Additional API features
Middleware Handlers
There are other examples using middleware handler in the examples/middleware directory.
Class-based middlewares
There are class-based middlewares. Basic class-based middleware looks like this:
Class-based middleware should have to functions: post and pre process. So, as you can see, class-based middlewares work before and after handler execution. For more, check out in examples
Custom filters
Also, you can use built-in custom filters. Or, you can create your own filter.
Also, we have examples on them. Check this links:
You can check some built-in filters in source code
If you want to add some built-in filter, you are welcome to add it in custom_filters.py file.
Here is example of creating filter-class:
TeleBot
Reply markup
The last example yields this result:
Working with entities
This object represents one special entity in a text message. For example, hashtags, usernames, URLs, etc. Attributes:
Advanced use of the API
Using local Bot API Sever
Since version 5.0 of the Bot API, you have the possibility to run your own Local Bot API Server. pyTelegramBotAPI also supports this feature.
Important: Like described here, you have to log out your bot from the Telegram server before switching to your local API server. in pyTelegramBotAPI use bot.log_out()
Note: 4200 is an example port
Asynchronous TeleBot
New: There is an asynchronous implementation of telebot. To enable this behaviour, create an instance of AsyncTeleBot instead of TeleBot.
Now, every function that calls the Telegram API is executed in a separate asynchronous task. Using AsyncTeleBot allows you to do the following:
Sending large text messages
Sometimes you must send messages that exceed 5000 characters. The Telegram API can not handle that many characters in one request, so we need to split the message in multiples. Here is how to do that using the API:
Or you can use the new smart_split function to get more meaningful substrings:
Controlling the amount of Threads used by TeleBot
The TeleBot constructor takes the following optional arguments:
The listener mechanism
As an alternative to the message handlers, one can also register a function as a listener to TeleBot.
NOTICE: handlers won’t disappear! Your message will be processed both by handlers and listeners. Also, it’s impossible to predict which will work at first because of threading. If you use threaded=False, custom listeners will work earlier, after them handlers will be called. Example:
Using web hooks
When using webhooks telegram sends one Update per call, for processing it you should call process_new_messages([update.message]) when you recieve it.
There are some examples using webhooks in the examples/webhook_examples directory.
Logging
You can use the Telebot module logger to log debug info about Telebot. Use telebot.logger to get the logger of the TeleBot module. It is possible to add custom logging Handlers to the logger. Refer to the Python logging module page for more info.
Proxy
You can use proxy for request. apihelper.proxy object will use by call requests proxies argument.
Testing
You can disable or change the interaction with real Telegram server by using
parameter. You can pass there your own function that will be called instead of requests.request.
Then you can use API and proceed requests in your handler code.
custom_sender. method: post, url: https://api.telegram.org/botololo/sendMessage, params:
API conformance
AsyncTeleBot
Asynchronous version of telebot
We have a fully asynchronous version of TeleBot. This class is not controlled by threads. Asyncio tasks are created to execute all the stuff.
EchoBot
Echo Bot example on AsyncTeleBot:
As you can see here, keywords are await and async.
Why should I use async?
Asynchronous tasks depend on processor performance. Many asynchronous tasks can run parallelly, while thread tasks will block each other.
Differences in AsyncTeleBot
AsyncTeleBot is asynchronous. It uses aiohttp instead of requests module.
Examples
See more examples in our examples folder
How can I distinguish a User and a GroupChat in message.chat?
Telegram Bot API support new type Chat for message.chat.
How can I handle reocurring ConnectionResetErrors?
Bot instances that were idle for a long time might be rejected by the server when sending a message due to a timeout of the last used session. Add apihelper.SESSION_TIME_TO_LIVE = 5 * 60 to your initialisation to force recreation after 5 minutes without any activity.
The Telegram Chat Group
Get help. Discuss. Chat.
Telegram Channel
Join the News channel. Here we will post releases and updates.
More examples
Code Template
Template is a ready folder that contains architecture of basic project. Here are some examples of template:
Bots using this library
Want to have your bot listed here? Just make a pull request. Only bots with public source code are accepted.
Наш первый бот
admin · May 20, 2018 в 6:21 pm
Регистрация бота
Откройте клиент телеграмма, найдите @BotFather и начните беседу. Отправьте команду /newbot и следуйте инструкциям. После выполнения первых шагов вы получите:
Собственно, вот и всё. На данном этапе ваш бот полностью пассивен.
Установка программ для разработки ботов
Мы, в компании Momentum bots разрабатываем ботов на языке Python 3, и обучаем новеньких тоже на этом языке программирования. Он один из самых легких и имеет очень много готовых качественных библиотек для самых разнообразных задач. Идеальный инструмент для разработки ботов).
Если вы пользуетесь ос Windows:
Заходим на https://python.org/downloads/windows/, выбираем “latest python release” и python 3. Скачиваем и устанавливаем, важно – при установке поставить галочку в поле Add to PATH.
Если вы пользуетесь ос Linux:
У вас скорее всего уже установлен пайтон. Откройте консоль (обычно ctrl+alt+t). Введите в консоли:
Скорее всего, вас любезно поприветствует python 3:
Если это так, то можно вас поздравить: у вас уже стоит python 3. В противном случае нужно установить пакет python3 с помощью пакетного менеджера вашего дистрибутива (apt/yum/etc)
Если вы используете MacOS:
В пункте меню Downloads под Download for Mac OS X выбрать и загрузить нужную версию python
Кликнуть на файл два раза (или раз правой клавишей и выбрать Открыть в программе – Установщик программ)
Пройти процесс инсталляции (помните, что устанавливать python нужно только на тот диск, с которого у вас грузится сама система Mac OS X — обычно он выбран по умолчанию)
Открыть консоль и проверить версию python запустив команду python3
Установка библиотеки для работы с Telegram:
Если вы корректно установили Python 3, то установить библиотеку для работы с телеграммом не составит труда:
В открытой консоли вводим pip install pyTelegramBotApi
Linux/MacOS: Открываем терминал, вводим
sudo pip3 install pyTelegramBotApi
Наконец-то код!
Поскольку это только тестовый проект – создадим исполняемый файл бота в корневой папке (в той, которая открывается при открытии терминала(простите за тавтологию)).
Открываем папку, создаем файл bot.py
Для удобного написания кода бота можно использовать редакторы кода, как Sublime text, Atom, или IDE, лучший выбор – Pycharm.
Если у Вас пока что нет этих программ, откроем файл с помощью блокнота и вставим этот код:
Pip install pytelegrambotapi как установить
A simple, but extensible Python implementation for the Telegram Bot API.
Both synchronous and asynchronous.
Supported Bot API version: 6.1!
This API is tested with Python 3.6-3.10 and Pypy 3. There are two ways to install the library:
It is generally recommended to use the first option.
While the API is production-ready, it is still under development and it has regular updates, do not forget to update it regularly by calling
Writing your first bot
Note: Make sure to actually replace TOKEN with your own API token.
After that declaration, we need to register some so-called message handlers. Message handlers define filters which a message must pass. If a message passes the filter, the decorated function is called and the incoming message is passed as an argument.
Let’s define a message handler which handles incoming /start and /help commands.
A function which is decorated by a message handler can have an arbitrary name, however, it must have only one parameter (the message).
Let’s add another handler:
This one echoes all incoming text messages back to the sender. It uses a lambda function to test a message. If the lambda returns True, the message is handled by the decorated function. Since we want all messages to be handled by this function, we simply always return True.
Note: all handlers are tested in the order in which they were declared
We now have a basic bot which replies a static message to «/start» and «/help» commands and which echoes the rest of the sent messages. To start the bot, add the following to our source file:
Alright, that’s it! Our source file now looks like this:
To start the bot, simply open up a terminal and enter python echo_bot.py to run the bot! Test it by sending commands (‘/start’ and ‘/help’) and arbitrary text messages.
General API Documentation
You can use some types in one function. Example:
content_types=[«text», «sticker», «pinned_message», «photo», «audio»]
General use of the API
Outlined below are some general use cases of the API.
A message handler is a function that is decorated with the message_handler decorator of a TeleBot instance. Message handlers consist of one or multiple filters. Each filter must return True for a certain message in order for a message handler to become eligible to handle that message. A message handler is declared in the following way (provided bot is an instance of TeleBot):
name | argument(s) | Condition |
---|---|---|
content_types | list of strings (default [‘text’] ) | True if message.content_type is in the list of strings. |
regexp | a regular expression as a string | True if re.search(regexp_arg) returns True and message.content_type == ‘text’ (See Python Regular Expressions) |
commands | list of strings | True if message.content_type == ‘text’ and message.text starts with a command that is in the list of strings. |
chat_types | list of chat types | True if message.chat.type in your filter |
func | a function (lambda or function reference) | True if the lambda or function reference returns True |
Here are some examples of using the filters and message handlers:
Important: all handlers are tested in the order in which they were declared
Edited Message handler
Handle edited messages @bot.edited_message_handler(filters) #
Channel Post handler
Handle channel post messages @bot.channel_post_handler(filters) #
Edited Channel Post handler
Handle edited channel post messages @bot.edited_channel_post_handler(filters) #
Callback Query Handler
Handle callback queries
Shipping Query Handler
Handle shipping queries @bot.shipping_query_handeler() #
Pre Checkout Query Handler
Handle pre checkoupt queries @bot.pre_checkout_query_handler() #
Handle poll updates @bot.poll_handler() #
Poll Answer Handler
Handle poll answers @bot.poll_answer_handler() #
My Chat Member Handler
Handle updates of a the bot’s member status in a chat @bot.my_chat_member_handler() #
Chat Member Handler
Handle updates of a chat member’s status in a chat @bot.chat_member_handler() # Note: «chat_member» updates are not requested by default. If you want to allow all update types, set allowed_updates in bot.polling() / bot.infinity_polling() to util.update_types
Chat Join Request Handler
Handle chat join requests using: @bot.chat_join_request_handler() #
More information about Inline mode.
Now, you can use inline_handler to get inline queries in telebot.
Chosen Inline handler
Use chosen_inline_handler to get chosen_inline_result in telebot. Don’t forgot add the /setinlinefeedback command for @Botfather.
Answer Inline Query
Additional API features
There are other examples using middleware handler in the examples/middleware directory.
There are class-based middlewares. Basic class-based middleware looks like this:
Class-based middleware should have to functions: post and pre process. So, as you can see, class-based middlewares work before and after handler execution. For more, check out in examples
Also, you can use built-in custom filters. Or, you can create your own filter.
Also, we have examples on them. Check this links:
You can check some built-in filters in source code
If you want to add some built-in filter, you are welcome to add it in custom_filters.py file.
Here is example of creating filter-class:
The last example yields this result:
Working with entities
This object represents one special entity in a text message. For example, hashtags, usernames, URLs, etc. Attributes:
Advanced use of the API
Using local Bot API Sever
Since version 5.0 of the Bot API, you have the possibility to run your own Local Bot API Server. pyTelegramBotAPI also supports this feature.
Important: Like described here, you have to log out your bot from the Telegram server before switching to your local API server. in pyTelegramBotAPI use bot.log_out()
Note: 4200 is an example port
New: There is an asynchronous implementation of telebot. To enable this behaviour, create an instance of AsyncTeleBot instead of TeleBot.
Now, every function that calls the Telegram API is executed in a separate asynchronous task. Using AsyncTeleBot allows you to do the following:
Sending large text messages
Sometimes you must send messages that exceed 5000 characters. The Telegram API can not handle that many characters in one request, so we need to split the message in multiples. Here is how to do that using the API:
Or you can use the new smart_split function to get more meaningful substrings:
Controlling the amount of Threads used by TeleBot
The TeleBot constructor takes the following optional arguments:
The listener mechanism
As an alternative to the message handlers, one can also register a function as a listener to TeleBot.
NOTICE: handlers won’t disappear! Your message will be processed both by handlers and listeners. Also, it’s impossible to predict which will work at first because of threading. If you use threaded=False, custom listeners will work earlier, after them handlers will be called. Example:
When using webhooks telegram sends one Update per call, for processing it you should call process_new_messages([update.message]) when you recieve it.
There are some examples using webhooks in the examples/webhook_examples directory.
You can use the Telebot module logger to log debug info about Telebot. Use telebot.logger to get the logger of the TeleBot module. It is possible to add custom logging Handlers to the logger. Refer to the Python logging module page for more info.
You can use proxy for request. apihelper.proxy object will use by call requests proxies argument.
You can disable or change the interaction with real Telegram server by using
parameter. You can pass there your own function that will be called instead of requests.request.
Then you can use API and proceed requests in your handler code.
custom_sender. method: post, url: https://api.telegram.org/botololo/sendMessage, params:
Asynchronous version of telebot
We have a fully asynchronous version of TeleBot. This class is not controlled by threads. Asyncio tasks are created to execute all the stuff.
Echo Bot example on AsyncTeleBot:
As you can see here, keywords are await and async.
Why should I use async?
Asynchronous tasks depend on processor performance. Many asynchronous tasks can run parallelly, while thread tasks will block each other.
Differences in AsyncTeleBot
AsyncTeleBot is asynchronous. It uses aiohttp instead of requests module.
See more examples in our examples folder
How can I distinguish a User and a GroupChat in message.chat?
Telegram Bot API support new type Chat for message.chat.
How can I handle reocurring ConnectionResetErrors?
Bot instances that were idle for a long time might be rejected by the server when sending a message due to a timeout of the last used session. Add apihelper.SESSION_TIME_TO_LIVE = 5 * 60 to your initialisation to force recreation after 5 minutes without any activity.
The Telegram Chat Group
Get help. Discuss. Chat.
Join the News channel. Here we will post releases and updates.
Template is a ready folder that contains architecture of basic project. Here are some examples of template:
Bots using this library
Want to have your bot listed here? Just make a pull request. Only bots with public source code are accepted.
eternnoir/pyTelegramBotAPI
Latest commit
Git stats
Files
Failed to load latest commit information.
README.md
A simple, but extensible Python implementation for the Telegram Bot API.
Both synchronous and asynchronous.
Supported Bot API version: 6.1!
This API is tested with Python 3.6-3.10 and Pypy 3. There are two ways to install the library:
It is generally recommended to use the first option.
While the API is production-ready, it is still under development and it has regular updates, do not forget to update it regularly by calling
Writing your first bot
Note: Make sure to actually replace TOKEN with your own API token.
After that declaration, we need to register some so-called message handlers. Message handlers define filters which a message must pass. If a message passes the filter, the decorated function is called and the incoming message is passed as an argument.
Let’s define a message handler which handles incoming /start and /help commands.
A function which is decorated by a message handler can have an arbitrary name, however, it must have only one parameter (the message).
Let’s add another handler:
This one echoes all incoming text messages back to the sender. It uses a lambda function to test a message. If the lambda returns True, the message is handled by the decorated function. Since we want all messages to be handled by this function, we simply always return True.
Note: all handlers are tested in the order in which they were declared
We now have a basic bot which replies a static message to «/start» and «/help» commands and which echoes the rest of the sent messages. To start the bot, add the following to our source file:
Alright, that’s it! Our source file now looks like this:
To start the bot, simply open up a terminal and enter python echo_bot.py to run the bot! Test it by sending commands (‘/start’ and ‘/help’) and arbitrary text messages.
General API Documentation
You can use some types in one function. Example:
content_types=[«text», «sticker», «pinned_message», «photo», «audio»]
General use of the API
Outlined below are some general use cases of the API.
A message handler is a function that is decorated with the message_handler decorator of a TeleBot instance. Message handlers consist of one or multiple filters. Each filter must return True for a certain message in order for a message handler to become eligible to handle that message. A message handler is declared in the following way (provided bot is an instance of TeleBot):
name | argument(s) | Condition |
---|---|---|
content_types | list of strings (default [‘text’] ) | True if message.content_type is in the list of strings. |
regexp | a regular expression as a string | True if re.search(regexp_arg) returns True and message.content_type == ‘text’ (See Python Regular Expressions) |
commands | list of strings | True if message.content_type == ‘text’ and message.text starts with a command that is in the list of strings. |
chat_types | list of chat types | True if message.chat.type in your filter |
func | a function (lambda or function reference) | True if the lambda or function reference returns True |
Here are some examples of using the filters and message handlers:
Important: all handlers are tested in the order in which they were declared
Edited Message handler
Handle edited messages @bot.edited_message_handler(filters) #
Channel Post handler
Handle channel post messages @bot.channel_post_handler(filters) #
Edited Channel Post handler
Handle edited channel post messages @bot.edited_channel_post_handler(filters) #
Callback Query Handler
Handle callback queries
Shipping Query Handler
Handle shipping queries @bot.shipping_query_handeler() #
Pre Checkout Query Handler
Handle pre checkoupt queries @bot.pre_checkout_query_handler() #
Handle poll updates @bot.poll_handler() #
Poll Answer Handler
Handle poll answers @bot.poll_answer_handler() #
My Chat Member Handler
Handle updates of a the bot’s member status in a chat @bot.my_chat_member_handler() #
Chat Member Handler
Handle updates of a chat member’s status in a chat @bot.chat_member_handler() # Note: «chat_member» updates are not requested by default. If you want to allow all update types, set allowed_updates in bot.polling() / bot.infinity_polling() to util.update_types
Chat Join Request Handler
Handle chat join requests using: @bot.chat_join_request_handler() #
More information about Inline mode.
Now, you can use inline_handler to get inline queries in telebot.
Chosen Inline handler
Use chosen_inline_handler to get chosen_inline_result in telebot. Don’t forgot add the /setinlinefeedback command for @Botfather.
Answer Inline Query
Additional API features
There are other examples using middleware handler in the examples/middleware directory.
There are class-based middlewares. Basic class-based middleware looks like this:
Class-based middleware should have to functions: post and pre process. So, as you can see, class-based middlewares work before and after handler execution. For more, check out in examples
Also, you can use built-in custom filters. Or, you can create your own filter.
Also, we have examples on them. Check this links:
You can check some built-in filters in source code
If you want to add some built-in filter, you are welcome to add it in custom_filters.py file.
Here is example of creating filter-class:
The last example yields this result:
Working with entities
This object represents one special entity in a text message. For example, hashtags, usernames, URLs, etc. Attributes:
Advanced use of the API
Using local Bot API Sever
Since version 5.0 of the Bot API, you have the possibility to run your own Local Bot API Server. pyTelegramBotAPI also supports this feature.
Important: Like described here, you have to log out your bot from the Telegram server before switching to your local API server. in pyTelegramBotAPI use bot.log_out()
Note: 4200 is an example port
New: There is an asynchronous implementation of telebot. To enable this behaviour, create an instance of AsyncTeleBot instead of TeleBot.
Now, every function that calls the Telegram API is executed in a separate asynchronous task. Using AsyncTeleBot allows you to do the following:
Sending large text messages
Sometimes you must send messages that exceed 5000 characters. The Telegram API can not handle that many characters in one request, so we need to split the message in multiples. Here is how to do that using the API:
Or you can use the new smart_split function to get more meaningful substrings:
Controlling the amount of Threads used by TeleBot
The TeleBot constructor takes the following optional arguments:
The listener mechanism
As an alternative to the message handlers, one can also register a function as a listener to TeleBot.
NOTICE: handlers won’t disappear! Your message will be processed both by handlers and listeners. Also, it’s impossible to predict which will work at first because of threading. If you use threaded=False, custom listeners will work earlier, after them handlers will be called. Example:
When using webhooks telegram sends one Update per call, for processing it you should call process_new_messages([update.message]) when you recieve it.
There are some examples using webhooks in the examples/webhook_examples directory.
You can use the Telebot module logger to log debug info about Telebot. Use telebot.logger to get the logger of the TeleBot module. It is possible to add custom logging Handlers to the logger. Refer to the Python logging module page for more info.
You can use proxy for request. apihelper.proxy object will use by call requests proxies argument.
You can disable or change the interaction with real Telegram server by using
parameter. You can pass there your own function that will be called instead of requests.request.
Then you can use API and proceed requests in your handler code.
custom_sender. method: post, url: https://api.telegram.org/botololo/sendMessage, params:
Asynchronous version of telebot
We have a fully asynchronous version of TeleBot. This class is not controlled by threads. Asyncio tasks are created to execute all the stuff.
Echo Bot example on AsyncTeleBot:
As you can see here, keywords are await and async.
Why should I use async?
Asynchronous tasks depend on processor performance. Many asynchronous tasks can run parallelly, while thread tasks will block each other.
Differences in AsyncTeleBot
AsyncTeleBot is asynchronous. It uses aiohttp instead of requests module.
See more examples in our examples folder
How can I distinguish a User and a GroupChat in message.chat?
Telegram Bot API support new type Chat for message.chat.
How can I handle reocurring ConnectionResetErrors?
Bot instances that were idle for a long time might be rejected by the server when sending a message due to a timeout of the last used session. Add apihelper.SESSION_TIME_TO_LIVE = 5 * 60 to your initialisation to force recreation after 5 minutes without any activity.
The Telegram Chat Group
Get help. Discuss. Chat.
Join the News channel. Here we will post releases and updates.
Template is a ready folder that contains architecture of basic project. Here are some examples of template:
Bots using this library
Want to have your bot listed here? Just make a pull request. Only bots with public source code are accepted.
Боты для Telegram
В настоящее время существует достаточно много разных популярных мессенджеров. Достоинством мессенджера Telegram является наличие богатого API, позволяющего взаимодействовать с мессенжером не людям, а программам, то есть писать боты.
Краткое введение в Telegram Bot API
Можете изучить полную документацию на Telegram Bot API, но непосредственно этим API мы пользоваться не будем. Но нужно понять, как это устроено внутри.
На самом простом уровне это API, использующее HTTP с JSON-ответом. Вы можете промоделировать работу бота, просто используя GET-запросы в браузере, то есть загружая страницы с определённым адресом используя браузер.
Самый простой пример тестовой страницы, которую можно загрузить при помощи API:
В ответ вы получите от @BotFather токен.
Дальнейшее описание Telegram Bot API не нужно для выполнения заданий (т.к. мы будем использовать упрощающую разработку ботов библиотеку), но полезно для понимания.
Пример простого запроса getMe для проверки токена, который можно просто ввести в адресную строку браузера, заменив на токен вашего бота:
В ответ вы должны получить небольшой JSON с информацией о вашем боте.
Если написать боту сообщение (например, с телефона или используя web.telegram.org), то это сообщение будет храниться на серверах Telegram. Чтобы получить сообщения, адресованные боту, необходимо выполнить запрос getUpdates:
Для того, чтобы отправить сообщение, вам необходимо сделать запрос sendMessage с двумя обязательными параметрами в адресной строке: chat_id —идентификатор чата для отправки сообщения и text — сообщение, отправляемое пользователю. Например:
Таким образом, простейшая схема реализации бота следующая. Бот — это постоянно запущенное приложение, которое регулярно опрашивает сервер, посылая запросы getUpdates и “засыпая” на некоторое время после этого. Если ответ сервера содержит какие-то новые сообщения, то их нужно обработать и отправить запросы sendMessage для отправки ответных сообщений.
Библиотека pytelegrambotapi (telebot)
Установка библиотеки
Её необходимо установить при помощи pip, в pip она называется pytelegrambotapi. Соответствующая консольная команда может выглядеть, например, так:
Сразу же установите библиотеку requests, она пригодится для выполнения ряда заданий.
Простой обработчик сообщений
Пример простого бота, который на любое сообщение всегда отвечает одним словом “Привет!”:
Эта функция регистрируется в качестве обработчика для сообщений типа “text”, что делается при помощи так называемых “декораторов” — это строчка, начинающаяся со значка “@” перед нашей функцией.
Теперь при поступлении сообщений объект bot будет вызывать функцию get_text_messages для каждого сообщения отдельно, тем самым принимая на себя работу по получению и парсингу полученных сообщений. Вам нужно всего лишь определить, что делает бот для ответа на полученное сообщение. Вы можете отправлять сообщения, вызывая метод send_message с параметрами: идентификатор чата и текст отправляемого сообщения.
Реализация клавиатуры
Команды, набираемые пользователем, сложно декодировать, да и пользователь может ошибиться в их написании. Поэтому в Телеграме у ботов есть возможность использования клавиатуры для выбора стандартных действий пользователя. Есть два типа клавиатуры: ReplyKeyboardMarkup (более древняя) и InlineKeyboardMarkup (более современная и богатая возможностями), на второй и остановимся.
Используем это для того, чтобы сделать разные обработчики для разных кнопок.
Telegram bot для начинающих с выгрузкой на сервер ubuntu
Привет всем, хочу поделится опытом создания своего первого чат бота в телеграм. Меня вдохновила идея автоматизированного бизнеса с использованием чат ботов и голосовых ассистентов, потому что я считаю, что за этими технологиями будущее торговли товарами или продажа услуг в интернете.
Юный падаван
Так как опыта в программировании у меня не было, пришлось идти путем проб и ошибок. Я перечитал огромное количество материалов, посвященных созданию телеграм ботов и у меня сложилось впечатление, что авторы чего-то не договаривают, либо я еще совсем юный подаван. Первое с чем я столкнулся, был вопрос: на каком ПО заняться разработкой бота — Windows или Linux? Windows был мне знаком с детства, но слишком частые обновления и монопольный консерватизм Windows подтолкнули меня к Linux, к тому же, при установке Ubuntu рядом с Windows, я допустил грубую ошибку в связи со своей неопытностью, установив Ubuntu на весь жесткий диск)
Через тернии к звездам
Еще одна проблема, с которой я столкнулся, это блокировка телеграм в России, то есть запросы не отправлялись на сервер telegram bot api.
Для начала работы нужно установить vpn на Ubuntu, я решил использовать vpn windscribe — хороший и бесплатный vpn, ссылка для установки rus.windscribe.com/guides/linux#how-to
Далее нужно установить Python
С ним уже в комплекте идет менеджер пакетов pip3.
Затем переходим в директорию bots
Устанавливаем виртуальную среду в каталог bots
Далее в каталоге bots создаем виртуальную среду
Следующий шаг — активируем ее
Итак, виртуальная среда готова, теперь установим пакет pyTelegramBotAPI в каталог bots
Теперь приступим к написанию кода, я использовал код из рипозитория gihub pyTelegramBotAPI.
Переходим в каталог бот и создаем файл с расширением в конце .py Я использую редактор NANO, вы можете использовать любой другой редактор, на ваше усмотрение)
Этот код возвращает то слово или команду, которую вы отправили боту. Где TOKEN нужно вставить «TOKEN» вашего бота.
Теперь нужно включить ваш vpn, лучше включить vpn в каталоге bots
Затем запустите бота с помощью команды
После этого бот должен заработать.
Для того, чтобы бот работал автономно и вам не приходилось все время сидеть с включенным пк, его надо загрузить на удаленный сервер. Для этого я использовал Ubuntu Server, главное чтобы он был расположен в другой стране, опять же из-за блокировки телеграм в РФ, я нашел vps стоимостью 3$, его достаточно для создания обыкновенного бота.
Как развернуть удаленный сервер я расскажу в следующей статье.
Источники информации:
- http://habr.com/ru/post/580408/
- http://mastergroosha.github.io/telegram-tutorial/docs/pyTelegramBotAPI/lesson_00/
- http://thecode.media/python-bot/
- http://pypi.org/project/pyTelegramBotAPI/
- http://momentum-bots.top/blog/2018/05/20/firstbot/
- http://github.com/eternnoir/pyTelegramBotAPI/blob/master/README.md
- http://github.com/eternnoir/pyTelegramBotAPI
- http://server.179.ru/tasks/python/theory/24-telegram.html
- http://habr.com/ru/sandbox/130094/