Лайфхаки

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

Telegram Bot proxy in Python. Telegram Bot on Python 3

29.06.2023 в 13:43

Telegram Bot proxy in Python. Telegram Bot on Python 3

Today we will create a simple telegram bot on python that can respond to our messages, interact with us, offering answer options in the form of buttons and process the result we selected by executing commands on the server. Work with Telegram Bot Api we will using the pyTelegramBotAPI ( telebot ) library written in Python .

    To register a new bot, you need to write the BotFather bot. To do this, type BotFather in the search bar and in the results find it:

    Attention! Check bot name, image and a check mark, indicating that he is really the father of all bots.

    Click it and write the command /start and the bot in the response message will send a list of all available commands:

    We need to creating a new bot, so we select the /newbot command. You can either type the command yourself or select the mouse in the message and it will automatically be sent:

    The first step we are offered to give a name to the new bot, it can be arbitrary. We will call it PocketAdmin :

    Now you need to specify the bot identifier ( username ), it must end with _bot and be unique in the system. We will indicate PocketAdminTech_bot :

    In the last message, we received a link to our new bot t.me/PocketAdminTech_bot and the token (shaded) needed to interact with the API.

    Attention! Be sure to keep the token and keep it secret!

    Install Python and library pyTelegramBotAPI

    Download Python you can from the official site (how to install the package on Centos 8 can be found in this article ) and we will not focus on this issue.

    To install the pyTelegramBotAPI package, use pip :

    On this, the preparatory work is completed, we proceed directly to writing our bot.

Edit_message_text Python telegram Bot. Специальные кнопки

Некоторым ботам жизненно необходим ваш номер телефона или местоположение, например, для привязки к учётным записям на других сайтах или же поиска близлежащих объектов на карте. Разработчики Telegram прислушались к мнению ботоводов и добавили особые свойства обычным (не инлайновым) кнопкам. Итак, чтобы запросить номер телефона, нужно помимо аргументаtextпередать аргументrequest_contact=True, а для геолокации, соответственно,request_location=True. Обратите внимание, что одновременно у кнопки может быть не больше одного особого свойства (можно не указывать никакой), а также что специальные кнопки могут быть отправлены только в диалоги (бот-человек). Напишем код, который на команду /geophone отправит нам клавиатуру с этими кнопками.

Edit_message_text Python telegram Bot. Специальные кнопки
Нажатие на кнопку запроса телефона

# не забудьте про from telebot import types @bot.message_handler(commands=) def geophone(message): # Эти параметры для клавиатуры необязательны, просто для удобства keyboard = types.ReplyKeyboardMarkup(row_width=1, resize_keyboard=True) button_phone = types.KeyboardButton(text= "Отправить номер телефона" , request_contact=True) button_geo = types.KeyboardButton(text= "Отправить местоположение" , request_location=True) keyboard.add(button_phone, button_geo) bot.send_message(message.chat.id, "Отправь мне свой номер телефона или поделись местоположением, жалкий человечишка!" , reply_markup=keyboard)

При нажатии на кнопку отправки номера телефона сервер вернёт объект Message с непустым типом, а при нажатии на кнопку отправки геолокации – с непустым типом.

Важно : если вы используете конечные автоматы или любой другой механизм состояний, который будет ждать от пользователя его телефон в объекте Contact, помните, что ушлый юзер может попробовать обмануть бота и скинуть любой другой контакт из записной книжки. Чтобы убедиться, что номер телефона принадлежит именно этому конкретному пользователю, сравнитеuser_idв объектеfromсuser_idв объектеContact, они должны совпадать.