Pip install pytelegrambotapi как установить

от admin

Name already in use

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

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.5!

This API is tested with Python 3.7-3.11 and Pypy 3. There are two ways to install the library:

  • Installation using pip (a Python package manager):
  • Installation from source (requires git):

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

It is presumed that you have obtained an API token with @BotFather. We will call this token TOKEN . Furthermore, you have basic knowledge of the Python programming language and more importantly the Telegram Bot API.

A simple echo bot

The TeleBot class (defined in _init_.py) encapsulates all API calls in a single class. It provides functions such as send_xyz ( send_message , send_document etc.) and several ways to listen for incoming messages.

Create a file called echo_bot.py . Then, open the file and create an instance of the TeleBot class.

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

All types are defined in types.py. They are all completely in line with the Telegram API’s definition of the types, except for the Message’s from field, which is renamed to from_user (because from is a Python reserved token). Thus, attributes such as message_id can be accessed directly with message.message_id . Note that message.chat can be either an instance of User or GroupChat (see How can I distinguish a User and a GroupChat in message.chat?).

The Message object also has a content_type attribute, which defines the type of the Message. content_type can be one of the following strings: text , audio , document , photo , sticker , video , video_note , voice , location , contact , new_chat_members , left_chat_member , new_chat_title , new_chat_photo , delete_chat_photo , group_chat_created , supergroup_chat_created , channel_chat_created , migrate_to_chat_id , migrate_from_chat_id , pinned_message , web_app_data .

You can use some types in one function. Example:

content_types=[«text», «sticker», «pinned_message», «photo», «audio»]

All API methods are located in the TeleBot class. They are renamed to follow common Python naming conventions. E.g. getMe is renamed to get_me and sendMessage to send_message .

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):

function_name is not bound to any restrictions. Any function name is permitted with message handlers. The function must accept at most one argument, which will be the message that the function must handle. filters is a list of keyword arguments. A filter is declared in the following manner: name=argument . One handler may have multiple filters. TeleBot supports the following filters:

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) # <- passes a Message type object to your function

Channel Post handler

Handle channel post messages @bot.channel_post_handler(filters) # <- passes a Message type object to your function

Edited Channel Post handler

Handle edited channel post messages @bot.edited_channel_post_handler(filters) # <- passes a Message type object to your function

Callback Query Handler

Handle callback queries

Shipping Query Handler

Handle shipping queries @bot.shipping_query_handler() # <- passes a ShippingQuery type object to your function

Pre Checkout Query Handler

Handle pre checkoupt queries @bot.pre_checkout_query_handler() # <- passes a PreCheckoutQuery type object to your function

Handle poll updates @bot.poll_handler() # <- passes a Poll type object to your function

Poll Answer Handler

Handle poll answers @bot.poll_answer_handler() # <- passes a PollAnswer type object to your function

My Chat Member Handler

Handle updates of a the bot’s member status in a chat @bot.my_chat_member_handler() # <- passes a ChatMemberUpdated type object to your function

Chat Member Handler

Handle updates of a chat member’s status in a chat @bot.chat_member_handler() # <- passes a ChatMemberUpdated type object to your function 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() # <- passes ChatInviteLink type object to your function

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

A middleware handler is a function that allows you to modify requests or the bot context as they pass through the Telegram to the bot. You can imagine middleware as a chain of logic connection handled before any other handlers are executed. Middleware processing is disabled by default, enable it by setting apihelper.ENABLE_MIDDLEWARE = True .

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:

All send_xyz functions of TeleBot take an optional reply_markup argument. This argument must be an instance of ReplyKeyboardMarkup , ReplyKeyboardRemove or ForceReply , which are defined in types.py.

The last example yields this result:

ForceReply

Working with entities

This object represents one special entity in a text message. For example, hashtags, usernames, URLs, etc. Attributes:

  • type
  • url
  • offset
  • length
  • user

Here’s an Example: message.entities[num].<attribute>
Here num is the entity number or order of entity in a reply, for if incase there are multiple entities in the reply/message.
message.entities returns a list of entities object.
message.entities[0].type would give the type of the first entity
Refer Bot Api for extra details

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:

  • threaded: True/False (default True). A flag to indicate whether TeleBot should execute message handlers on it’s polling Thread.

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.

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.

If you want to use socket5 proxy you need install dependency pip install requests[socks] and make sure, that you have the latest version of gunicorn , PySocks , pyTelegramBotAPI , requests and urllib3 .

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 limitations

  • ➕ Bot API 4.5 — No nested MessageEntities and Markdown2 support
  • ➕ Bot API 4.1 — No Passport support
  • ➕ Bot API 4.0 — No Passport support

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.

  • Check the type attribute in Chat object:

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 pyTelegramBotAPI Telegram Chat Group

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

    (source) by ilteoood — Monitors websites and sends a notification on changes by aRandomStranger by GabrielRF — Let me Google that for you. by mrgigabyte by Tronikart — Multifunctional Telegram Bot RadRetroRobot. (source) by i32ropie by @NeoRanger (source) — Share code snippets as beautifully syntax-highlighted HTML and/or images. (source) by alejandrocq — Telegram bot to check the menu of Universidad de Granada dining hall. — Simple Proxy Bot for Telegram. by p-hash — DonantesMalagaBot facilitates information to Malaga blood donors about the places where they can donate today or in the incoming days. It also records the date of the last donation so that it helps the donors to know when they can donate again. — by vfranch by Dmytryi Striletskyi — Timetable for one university in Kiev. by rmed — Send and receive messages to/from WhatsApp through Telegram (source) by jcolladosp — Telegram bot using the Python API that gets films rating from IMDb and metacritic (source) by GabrielRF — Send to Kindle service. (source) by GabrielRF — Bot used to track packages on the Brazilian Mail Service. (link) by EeOneDown — Bot with timetables for SPbU students. (link) by 0xVK — Telegram timetable bot, for Zhytomyr Ivan Franko State University students. (link) — A Telegram Bot created to help people to memorize other languages’ vocabulary. by rubenleon (GitHub) — Bot that provides buses coming to a certain stop and their remaining time for the city of Vigo (Galicia — Spain) (source) by airatk — bot which shows all the necessary information to KNTRU-KAI students. (source) by @FacuM — Support Telegram bot for developers and maintainers. (source) by @DesExcile — Сatalog of poems by Eduard Asadov. (source) by @LeoSvalov — words and synonyms from dictionary.com and thesaurus.com in the telegram. (source) by @irevenko — An all-round bot that displays some statistics (weather, time, crypto etc. ) (source) by @Fliego — a simple bot for food ordering (source) by @0xnu — Telegram bot for displaying the latest news, sports schedules and injury updates. (source) by @zeph1997 — A Telegram Bot to remove «join group» and «removed from group» notifications. (source) by @Pablo-Davila — A (tasks) lists manager bot for Telegram. (source) by @Pablo-Davila — An implementation of the famous Eliza psychologist chatbot. (source) by Mrsqd. A Telegram bot that will always be happy to show you the weather forecast. by ModischFabrications. This bot can start, stop and monitor a minecraft server. by dexpiper. This bot can roll multiple dices for RPG-like games, add positive and negative modifiers and show short descriptions to the rolls. by Anvaari. This Bot make «Add to google calendar» link for your events. It give information about event and return link. It work for Jalali calendar and in Tehran Time. Source code by Areeg Fahad. This bot can be used to translate texts. by Areeg Fahad. With this bot, you can now monitor the prices of more than 12 digital Cryptocurrency. by Leon Heess (source). Send any link, and the bot tries its best to remove all tracking from the link you sent. by Vishal Singh(source code) This telegram bot can do tasks like GitHub search & clone,provide c++ learning resources ,Stackoverflow search, Codeforces(profile visualizer,random problems) by Aadithya & Amol Soans This Telegram bot provides live updates , data and documents on current and upcoming IPOs(Initial Public Offerings) (source) by TrevorWinstral — Gets live COVID Country data, plots it, and briefs the user (source) by TrevorWinstral — Notifies ETH students when their lectures have been uploaded by Resinprotein2333. This bot can help you to find The information of CVE vulnerabilities. (Source by DevAdvik — Get Live Ethereum Gas Fees in GWEI by JoachimStanislaus. This bot can help you to track your expenses by uploading your bot entries to your google sheet. by Carlosma7. This bot is a trivia game that allows you to play with people from different ages. This project addresses the use of a system through chatbots to carry out a social and intergenerational game as an alternative to traditional game development. (source) This bot lets you find difinitions of words in Spanish using RAE’s dictionary. It features direct message and inline search. by EnriqueMoran. Control your LinuxOS computer through Telegram. . Make purchases of items in a store with an Admin panel for data control and notifications. Query wolframalpha.com and make use of its API through Telegram. This Bot can understand spoken text in videos and translate it to English (source) Zyprexa can solve, help you solve any mathematical problem you encounter and convert your regular mathematical expressions into beautiful imagery using LaTeX. by tusharhero — Makes bincodes from text provides and also converts them back to text. Toolset for Hydrophilia tabletop game (game cards, rules, structure. ). (source) by 咕谷酱 GuXiaoJiang is a multi-functional robot, such as OSU game information query, IP test, animation screenshot search and other functions. A feedback bot for user-admin communication. Made on AsyncTeleBot, using template. by ablakely This is a Telegram to IRC bridge which links as an IRC server and makes Telegram users appear as native IRC users. by Anton Glyzin This is a simple telegram-store with an admin panel. Designed according to a template. (source)by CommanderCRM. This bot aggregates media (movies, TV series, etc.) ratings from IMDb, Rotten Tomatoes, Metacritic, TheMovieDB, FilmAffinity and also provides number of votes of said media on IMDb.

Want to have your bot listed here? Just make a pull request. Only bots with public source code are accepted.

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 у нас присылает сообщение «Спасибо за прочтение статьи!».

Build your first Telegram Bot using Python

Let me start by introducing the things that you are gonna need for a while:

  1. Creating a bot token using botfather (of course assuming that you are having a telegram account)
  2. A wrapper of telegram API in python (pyTelegramBotAPI)
  3. Your enthusiasm (definitely yes)

Yes, that’s all the recipe you need to do your first Telegram bot.

Creating our bot

Step 1: Search @BotFather in telegram and press start.

Step 2: Type in /newbot, then type in your desired name for the bot and username for the bot (make sure to create a unique username, also it must end with `Bot`).

Step 3: Congratulations, now you have your own bot in Telegram that can automate your stuff. Copy the API Token and get started to code your bot.

Don’t share or make your API Token publicly visible. It’s just like giving your account password.

Installing package and dependencies

Always ensure to create a virtual environment so that dependencies don’t mess up your whole environment.To create the virtual environment, open the command prompt or if you use anaconda prompt it will be much easier.

After creating this virtual environment, switch from base to virtual environment.

Now, let us install the packages that does the magic,

$ pip install pyTelegramBotAPI

that pretty much covered everything that is required, there are a lot other Telegram API’s available, but we choose pyTelegramBotAPI because of its simplicity and elegance.

Follow up this directory structure

Create a new file named ‘config.json’ containing the obtained API_KEY as key-value pair in the same directory.

Now, let’s get our hand into coding by firing up IDE.

Telebot is part of pyTelegramBotAPI that handles the interaction with Telegram bot. Run the snippet and Voilaa.

If you get an output like this:

Then, you’ve now successfully connected your Telegram bot with Python.

Let us add more commands that the bot can use to interact with its user. Add the following functions before the `pooling` step. (Link to an example repository given at end of this article)

Using `@bot.message_handler` decorator, you’ve now triggered a piece of code to run when the mentioned command is called. This welcomes a user or sends a help message when /start or /help command is provided.

Now, let’s connect a simple API to demonstrate how Bots can be used to automate and simplify your daily task .

This replies with a random quote from `quotable.io` to the user whenever /motivate is sent.

So, I’ve demonstrated a way to automate simple tasks using this bot, you can create a bot that provides daily stats of your company or price of products to customers or as a gateway to your Machine Learning models !!

Подготовка рабочего места в Windows и Linux. Virtual Environment (venv). Ответы на вопросы

Весь текст ниже появился как попытка дать универсальный ответ на те вопросы, которые дорогие читатели присылали и продолжают присылать раз за разом. Здесь не будет кода, связанного с ботами напрямую, а лишь советы по организации процесса написания. И, конечно же, не нужно воспринимать это как истину в последней инстанции, напротив, выбирайте те инструменты и подходы к разработке, которые лично вам кажутся удобными. Важная деталь: текст написан в конце 2019 года. Достаточно вступительных слов, поехали!

Предположим, вы уже немного знаете язык Python 3 (забудьте про Python 2.7, он мёртв), умеете писать простенькие программы и хотите взяться за разработку ботов. Где это делать? В чём писать код? Как правило, у большинства начинающих программистов основной операционкой используется Microsoft Windows. С неё и начнём, но сперва…

Virtual environment

Вы когда-нибудь пользовались VirtualBox? Например, чтобы «пощупать» другие операционные системы или просто установить какой-нибудь подозрительный софт. Python Virtual environment (далее — venv) чем-то напоминает «виртуалку». При его использовании создаётся копия выбранного интерпретатора Питон, а все устанавливаемые модули хранятся изолированно от общесистемных, тем самым, упрощается их обновление, удаление или изменение. Часто venv позволяет избежать ошибок, связанных с обратной совместимостью некоторых библиотек, а также обойтись без конфликтов с системными модулями. Работа с venv будет подробнее описана ниже в разделе Linux, но использовать его мы будем везде.

Windows

Первым делом, разумеется, нужно скачать сам интерпретатор Python. На момент написания этого текста актуальной версией является Python 3.8.1. В качестве каталога установки я рекомендую использовать что-то простое, вроде C:\Python38. Где писать код — личное дело каждого, конечно, но я всё же рекомендую использовать специальную среду разработки под названием PyCharm Community Edition. Бесплатной версии (та самая Community) более чем достаточно. После установки и первичной настройки выберите пункт File -> New Project. Укажите имя вашего первого проекта, а ниже укажите «New environment using virtualenv», ниже в качестве интерпретатора путь к python.exe каталога с Питоном (например, C:\Python38\python.exe).

Создание нового проекта в PyCharm

После запуска откройте вкладку Terminal в левом нижнем углу и установите библиотеку pytelegrambotapi (не telebot!). Для любителей тыкать мышкой есть более запутанный вариант: File -> Settings -> Project <имя проекта>-> Project Interpreter -> кнопка «+» в правой части экрана.

Установка библиотеки через терминал в PyCharm

Прекрасно, теперь начинайте творить! Создайте первый файл с исходником, нажав правой кнопкой мышки по имени проекта в списке файлов, затем New и Python File.

Создание нового файла кода в PyCharm

Запустить код можно, выбрав сверху пункт Run, затем снова Run…, но с многоточием, и затем выбрав созданный ранее файл.

Как залить файлы на сервер?

Для копирования файлов на удалённый сервер (обычно там стоит Linux), я использую замечательную бесплатную программу WinSCP, причём в ней присутствует режим автоматической синхронизации файлов, чтобы при любом изменении в локальном каталоге обновлялось содержимое на удалённой машине, избавляя вас от необходимости копировать всё вручную.

Скриншот программы WinSCP

При помощи WinSCP можно даже просто подключиться к серверу и подправить файл «на лету», не забудьте только потом перезапустить бота!

Linux

Если Linux у вас используется вместо Windows, то работа с PyCharm будет точно такой же, поэтому второй раз писать не имеет смысла. Далее рассмотрен процесс запуска в терминале на удалённом сервере. Прекрасно, вы написали бота и хотите где-то его запустить. Например, арендовали сервер у Scaleway/DigitalOcean/AWS/etc. Запустили сервер, подключились к нему по SSH, а там чёрный экран и терминальная Linux-сессия. Во-первых, давайте посмотрим, какой интерпретатор у нас выбран по умолчанию, введя команду python3 .

Хорошим правилом будет иметь на сервере ровно ту же версию 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

Сохраните файл, закройте его и выполните команду chmod +x имяфайласботом.py , чтобы сделать его исполняемым. Теперь создайте файл mybot.service, и скопируйте туда следующий текст:

Отредактируйте поля Description , WorkingDirectory и ExecStart , сохраните и закройте файл. Далее скопируйте его в каталог /etc/systemd/system , введя свой пароль при необходимости (если сидите не из-под рута, что правильно, то ваш юзер должен иметь возможность выполнять команды от имени sudo). Затем выполните следующие команды для включения автозагрузки и запуска бота (опять-таки, требуются права суперпользователя):

Наконец, проверьте состояние вашего бота командой systemctl status mybot . Его статус должен быть Active (running) зелёного цвета (если поддерживается разноцветный режим).

Проверка статуса бота через 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 или прийти к нам в чатик.

Читать:
Как расписать синус в квадрате

Похожие статьи