
Python for beginners
If you’re not familiar with Python at all, it’s a great place to start by reading the three introductory articles I published in Hacker this summer, or by attending the «Python for beginners», which I will start publishing for the readers of “Hacker” very soon – on 30 November.
To create a bot, we need to give it a name, an address, and get a token — a string that will uniquely identify our bot for Telegram servers. Let’s go to Telegram under your account and open the “father of all bots”, BotFather.
Click the “Start” button (or send /
), BotFather will send us a list of available commands in response:
-
/
— create a new bot;newbot -
/
— edit your bots;mybots -
/
— change the name of the bot;setname -
/
— change the bot description;setdescription -
/
— edit bot information;setabouttext -
/
— change the photo of the bot avatar;setuserpic -
/
— change the list of bot commands;setcommands -
/
— delete the bot.deletebot
Let’s send a command to the bate-bot /
to create a new bot. In response, it will ask you to enter the name of the future bot, it can be written in Russian. After entering the name, you will need to send the bot’s address, and it must end with the word bot. For example xakepbot
or xakep_bot
. If the address is already who then busy, BotFather will start apologizing and asking for something else.
When we finally find a free and beautiful address for our bot, we will receive a message in which after the phrase “Use this token to access the HTTP API”, a string of letters and numbers will be written — this is the token we need. Save it somewhere on your computer to use it in the bot script later.
There are several ready-made modules for interacting with the Telegram API. The simplest of them is Telebot. To install it, dial
pip install pytelegrambotapi
On Linux, you may need to write pip3
Instead of pip
to indicate that we want to work with a third version of Python.
Echo Bot
To begin with, let’s implement the so-called echo bot. It will receive a text message from the user and return it.
import telebot# Create a bot instancebot = telebot.TeleBot('Enter the token you received from @botfather here')# Function that handles the /start command@bot.message_handler(commands=["start"])def start(m, res=False): bot.send_message(m.chat.id, 'I'm in touch. Write me something )')# Receiving messages from the user@bot.message_handler(content_types=["text"])def handle_text(message): bot.send_message(message.chat.id, 'You wrote: ' + message.text)# Launch the botbot.polling(none_stop=True, interval=0)
Run the script and search for your bot in the Telegram search at the address you came up with earlier. Start the bot with the “Start” button or the /
and we can verify that it works and returns messages.

Wikipedia bot
Let’s teach our bot not just to send messages back, but to do something more interesting. For example, by the entered word, give an article on Wikipedia. This is where the Wikipedia module can help us:
pip install wikipedia
Preparing the code.
import telebot, wikipedia, re# Create a bot instancebot = telebot.TeleBot('Enter the token you received from @botfather here')# Install the Russian language in Wikipediawikipedia.set_lang("ru")# Clean the text of an article in Wikipedia and limit it to a thousand charactersdef getwiki(s): try: ny = wikipedia.page(s) # Get the first thousand characters wikitext=ny.content[:1000] # Split by points wikimas=wikitext.split('.') # Discard everything after the last point wikimas = wikimas[:-1] # Create an empty variable for the text wikitext2 = '' # Go through the string where there are no "equals" signs (that is, everything except the headings) for x in wikimas: if not('==' in x): # If there are more than three characters left in the string, add it to our variable and return the dots lost when splitting the strings to their place if(len((x.strip()))>3): wikitext2=wikitext2+x+'.' else: break # Now use regular expressions to remove the markup wikitext2=re.sub('\([^()]*\)', '', wikitext2) wikitext2=re.sub('\([^()]*\)', '', wikitext2) wikitext2=re.sub('\{[^\{\}]*\}', '', wikitext2) # Return a text string return wikitext2 # Handling an exception that could return a wikipedia module when requested except Exception as e: return 'There is no information about this in the encyclopedia'# Function that handles the /start command@bot.message_handler(commands=["start"])def start(m, res=False): bot.send_message(m.chat.id, 'Send me any word and I'll find its meaning on Wikipedia')# Receiving messages from the user@bot.message_handler(content_types=["text"])def handle_text(message): bot.send_message(message.chat.id, getwiki(message.text))# Launch the botbot.polling(none_stop=True, interval=0)

www
When creating the following bots, we will use several text files with content. You can download them from my website.
Bot with two virtual buttons
Many Telegram bots use so-called virtual buttons to select some actions. Let’s try to make ourselves the same!
Suppose we have two files facts.
and thinks.
, which contain a list of interesting facts and sayings. On each string of files, there is one fact or saying.
Let’s make a bot with two buttons: “Facts” and “Sayings”. If you click any, the bot will send a corresponding message to the user.
info
If you use the same token for this bot as for the previous one, then to see the buttons, restart the bot with the command /
.
import telebotimport randomfrom telebot import types# Upload a list of interesting factsf = open('data/facts.txt', 'r', encoding='UTF-8')facts = f.read().split('\n')f.close()# Uploading a list of sayingsf = open('data/thinks.txt', 'r', encoding='UTF-8')thinks = f.read().split('\n')f.close()# Creating a botbot = telebot.TeleBot('Here is your token received from @botfather')# Start command@bot.message_handler(commands=["start"])def start(m, res=False): # Add two buttons markup=types.ReplyKeyboardMarkup(resize_keyboard=True) item1=types.KeyboardButton("Fact") item2=types.KeyboardButton("Proverb") markup.add(item1) markup.add(item2) bot.send_message(m.chat.id, 'Click: \nFact to get an interesting fac\nProverb – to get a wise quote ', reply_markup=markup)# Receiving messages from the user@bot.message_handler(content_types=["text"])def handle_text(message): # If the user sent 1, give a random fact if message.text.strip() == 'Fact' : answer = random.choice(facts) # If the user sent 2, give a smart thought elif message.text.strip() == 'Proverb': answer = random.choice(thinks) # Send a message to the user in their chat bot.send_message(message.chat.id, answer)# Launch the botbot.polling(none_stop=True, interval=0)

Bot, leading a Telegram channel with jokes
Previous bots sent messages to the user when they received commands or phrases from them. But what if we need a bot that will periodically and automatically post something to our channel?
Let’s make a bot that gets a list of jokes from a file and posts one of these jokes to the channel every hour. To do this, we need to create our own channel in Telegram, add our bot to the channel subscribers and appoint it as the channel administrator with the right to publish messages.
The file with anecdotes should be in the folder data
next to the bot script.
import telebotimport time# Token that issues @botfatherbot = telebot.TeleBot('Here is your token received from @botfather')# Telegram channel address, starts with @CHANNEL_NAME = '@channel_address'# Loading the list of jokesf = open('data/fun.txt', 'r', encoding='UTF-8')jokes = f.read().split('\n')f.close()# Until the jokes run out, send them to the channelfor joke in jokes: bot.send_message(CHANNEL_NAME, joke) # Pausing for one hour time.sleep(3600)bot.send_message(CHANNEL_NAME, "The jokes are over :-(")

Chatbot “Masha”
Now let’s make the simplest chatbot that will chat with the user. To do this, we will prepare the boltun.
that contains strings with questions (at the beginning of such string, put a u:
) and the answers in the next strin.
u: What is your nameMy name is Masha!u: How old are youI've already 18, honestly-honestly!
File boltun.
Put it in the data
next to the bot script. To find similar questions, use the fuzzywuzzy, which allows to compare how similar two strings are to each other. Of course, first you need to install this module:
pip install fuzzywuzzypip install python-Levenshtein
Below, there is the source code of the bot. After launching it, write to the bot “Hello” and try to communicate with it. Naturally, this is not artificial intelligence and the set of its answers is limited to phrases from the file boltun.
.
import telebotimport osfrom fuzzywuzzy import fuzz# Create a bot, write your own tokenbot = telebot.TeleBot('Here is your token received from @botfather')# Loading the list of phrases and answers into themas=[]if os.path.exists('data/boltun.txt'): f=open('data/boltun.txt', 'r', encoding='UTF-8') for x in f: if(len(x.strip()) > 2): mas.append(x.strip().lower()) f.close()# Using fuzzywuzzy, calculate the most similar phrase and give the next list item as an answerdef answer(text): try: text=text.lower().strip() if os.path.exists('data/boltun.txt'): a = 0 n = 0 nn = 0 for q in mas: if('u: ' in q): # Using fuzzywuzzy, get how similar the two strings are aa=(fuzz.token_sort_ratio(q.replace('u: ',''), text)) if(aa > a and aa!= a): a = aa nn = n n = n + 1 s = mas[nn + 1] return s else: return 'Error' except: return 'Error'# Command "Start"@bot.message_handler(commands=["start"])def start(m, res=False): bot.send_message(m.chat.id, 'I'm in touch. Write me Hello )')# Receiving messages from the user@bot.message_handler(content_types=["text"])def handle_text(message): # Logging f=open('data/' + str(message.chat.id) + '_log.txt', 'a', encoding='UTF-8') s=answer(message.text) f.write('u: ' + message.text + '\n' + s +'\n') f.close() # Reply bot.send_message(message.chat.id, s)# Launch the botbot.polling(none_stop=True, interval=0)

Conclusions
We wrote five simple bots, using the example of which we learned how to receive and send messages, make buttons, and understand inaccurate requests.
In the next article, we will look at working with Telegram bots in more detail: we will learn how to make bots that work through webhooks, accept payments from users, and interact with the SQLite database.
I also urge you not to delay and sign up for the course “Python for beginners”, where we will move from the simplest concepts to creating the first interesting projects. We start very soon!
Python course
The course “Python from scratch” is aimed at learning the basics and basic concepts of programming. After that, you can easily delve into any of the IT areas: web development, data analysis, application security, and so on. The course duration is two calendar months. Lessons will be held twice a week (Tuesday and Thursday, approximately at 17:00 Moscow time), each for one academic hour. Homework will be given out periodically.

2022.01.13 — Bug in Laravel. Disassembling an exploit that allows RCE in a popular PHP framework
Bad news: the Ignition library shipped with the Laravel PHP web framework contains a vulnerability. The bug enables unauthorized users to execute arbitrary code. This article examines…
Full article →
2023.01.22 — Top 5 Ways to Use a VPN for Enhanced Online Privacy and Security
This is an external third-party advertising publication. In this period when technology is at its highest level, the importance of privacy and security has grown like never…
Full article →
2022.04.04 — Elephants and their vulnerabilities. Most epic CVEs in PostgreSQL
Once a quarter, PostgreSQL publishes minor releases containing vulnerabilities. Sometimes, such bugs make it possible to make an unprivileged user a local king superuser. To fix them,…
Full article →
2022.01.11 — Persistence cheatsheet. How to establish persistence on the target host and detect a compromise of your own system
Once you have got a shell on the target host, the first thing you have to do is make your presence in the system 'persistent'. In many real-life situations,…
Full article →
2023.02.13 — First Contact: Attacks on Google Pay, Samsung Pay, and Apple Pay
Electronic wallets, such as Google Pay, Samsung Pay, and Apple Pay, are considered the most advanced and secure payment tools. However, these systems are also…
Full article →
2022.06.02 — Climb the heap! Exploiting heap allocation problems
Some vulnerabilities originate from errors in the management of memory allocated on a heap. Exploitation of such weak spots is more complicated compared to 'regular' stack overflow; so,…
Full article →
2023.07.07 — Evil Ethernet. BadUSB-ETH attack in detail
If you have a chance to plug a specially crafted device to a USB port of the target computer, you can completely intercept its traffic, collect cookies…
Full article →
2023.02.21 — Herpaderping and Ghosting. Two new ways to hide processes from antiviruses
The primary objective of virus writers (as well as pentesters and Red Team members) is to hide their payloads from antiviruses and avoid their detection. Various…
Full article →
2022.06.01 — F#ck AMSI! How to bypass Antimalware Scan Interface and infect Windows
Is the phrase "This script contains malicious content and has been blocked by your antivirus software" familiar to you? It's generated by Antimalware Scan Interface…
Full article →
2023.03.03 — Nightmare Spoofing. Evil Twin attack over dynamic routing
Attacks on dynamic routing domains can wreak havoc on the network since they disrupt the routing process. In this article, I am going to present my own…
Full article →