⬆️ ⬇️

A simple telegram bot in python in 30 minutes

On Habré, and not only, so much has already been said about bots that even too much. But, having become interested in this topic a couple of weeks ago, it didn’t work for me to find normal material: all articles were either for dummies at all and were limited to sending a message in response to a user's message, or were irrelevant. This prompted me to write an article that would explain to the same novice as I, how to write and run a more or less meaningful bot (with the possibility of expanding functionality).



Part 1: Register your bot



The most simple and described part. Very briefly: you need to find the @BotFather bot, write him / start , or / newbot , fill in the fields that he asks (bot name and short name), and get a message with the bot token and a link to the documentation. The token must be saved, preferably securely, as this is the only key for authorizing and interacting with the bot.



Part 2: Preparing to write code



As already mentioned in the title, we will write a bot on Python. This article will describe how to work with the PyTelegramBotAPI (Telebot) library. If you do not have Python installed, you first need to do this: in the Linux terminal you need to enter

')

sudo apt-get install python python-pip 


If you are using Windows, then you need to download Python from the official site.



After that, in the Linux terminal, or the Windows command line, enter



 pip install pytelegrambotapi 


Now everything is ready for writing code.



Part 3: Receive messages and say "Hello"



A small digression. A telegram can tell the bot about the user's actions in two ways: via a response to a server request (Long Poll), and via Webhook, when the Telegram server itself sends a message that someone wrote to the bot. The second method clearly looks better, but requires a dedicated IP address, and established SSL on the server. In this article I want to talk about writing a bot, and not setting up a server, so we will use Long Poll.



Open your favorite text editor and write bot code!



The first thing to do is import our library and connect the bot token:



 import telebot; bot = telebot.TeleBot('% %'); 


Now we will declare a method for receiving text messages:



 @bot.message_handler(content_types=['text']) def get_text_messages(message): 


In this section of code, we declared a listener for text messages and a method for processing them. The content_types field can take on different values, and not just one, for example



 @bot.message_handler(content_types=['text', 'document', 'audio']) 


Will respond to text messages, documents and audio. More details can be read in the official documentation.



Now we’ll add some functionality to our method: if the user writes “Hello” to us, then we’ll say “Hello, how can I help?”



 if message.text == "": bot.send_message(message.from_user.id, ",     ?") elif message.text == "/help": bot.send_message(message.from_user.id, " ") else: bot.send_message(message.from_user.id, "   .  /help.") 


This piece of code does not require comments, I think. Now we need to add only one line to our code (outside of all methods).



 bot.polling(none_stop=True, interval=0) 


Now our bot will constantly ask the server for the Telegram “Has anyone written to me?”, And if we write to our bot, the Telegram will send him our message. Save the entire file and write to the console.



 python bot.py 


Where bot.py is the name of our file.



Now you can write a bot and look at the result:



image


Part 4: Buttons and Message Branches



Sending messages is undoubtedly fun, but it is even more fun to carry on a dialogue with the user: asking him questions and getting answers to them. Suppose now our bot will ask the user in turn his name, surname and age. To do this, we will use the register_next_step_handler bot method:



 name = ''; surname = ''; age = 0; @bot.message_handler(content_types=['text']) def start(message): if message.text == '/reg': bot.send_message(message.from_user.id, "  ?"); bot.register_next_step_handler(message, get_name); #  –  get_name else: bot.send_message(message.from_user.id, ' /reg'); def get_name(message): #  global name; name = message.text; bot.send_message(message.from_user.id, '   ?'); bot.register_next_step_handler(message, get_surnme); def get_surname(message): global surname; surname = message.text; bot.send_message('  ?'); bot.register_next_step_handler(message, get_age); def get_age(message): global age; while age == 0: #    try: age = int(message.text) #,     except Exception: bot.send_message(message.from_user.id, ', '); bot.send_message(message.from_user.id, ' '+str(age)+' ,   '+name+' '+surname+'?') 


And so, we recorded user data. This example shows a very simplified example, for good, you need to store intermediate data and user states in the database, but today we are working with a bot, not with databases. The final touch is to ask the users for confirmation that everything has been entered correctly, and not just like that, but with buttons! To do this, edit the get_age method code a little.



 def get_age(message): global age; while age == 0: #    try: age = int(message.text) #,     except Exception: bot.send_message(message.from_user.id, ', '); keyboard = types.InlineKeyboardMarkup(); #  key_yes = types.InlineKeyboardButton(text='', callback_data='yes'); # «» keyboard.add(key_yes); #    key_no= types.InlineKeyboardButton(text='', callback_data='no'); keyboard.add(key_no); question = ' '+str(age)+' ,   '+name+' '+surname+'?'; bot.send_message(message.from_user.id, text=question, reply_markup=keyboard) 


And now our bot sends the keyboard, but if you click on it, nothing will happen. Because we did not write a handler method. Let's write:



 @bot.callback_query_handler(func=lambda call: True) def callback_worker(call): if call.data == "yes": #call.data  callback_data,       .... #  ,    bot.send_message(call.message.chat.id, ' : )'); elif call.data == "no": ... # 


It remains only to add one line to the beginning of the file:



 from telebot import types 


That's it, save and run our bot:



image

Source: https://habr.com/ru/post/442800/



All Articles