Python via Telegram! Writing five simple Telegram bots in Python

Date: 02/06/2025

In this article, we are implementing a simple but extremely useful project in Python — a bot for Telegram. Bots are small scripts that can interact with the API to receive messages from the user and send information to different chats and channels.

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 /start), BotFather will send us a list of available commands in response:

  • /newbot — create a new bot;
  • /mybots — edit your bots;
  • /setname — change the name of the bot;
  • /setdescription — change the bot description;
  • /setabouttext — edit bot information;
  • /setuserpic — change the photo of the bot avatar;
  • /setcommands — change the list of bot commands;
  • /deletebot — delete the bot.

Let’s send a command to the bate-bot /newbot 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 instance
bot = 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 bot
bot.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 /start and we can verify that it works and returns messages.

Echo-bot example
Echo-bot example

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 instance
bot = telebot.TeleBot('Enter the token you received from @botfather here')
# Install the Russian language in Wikipedia
wikipedia.set_lang("ru")
# Clean the text of an article in Wikipedia and limit it to a thousand characters
def 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 bot
bot.polling(none_stop=True, interval=0)
Example of a Wikipedia bot
Example of a Wikipedia bot

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.txt and thinks.txt, 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 /start.

import telebot
import random
from telebot import types
# Upload a list of interesting facts
f = open('data/facts.txt', 'r', encoding='UTF-8')
facts = f.read().split('\n')
f.close()
# Uploading a list of sayings
f = open('data/thinks.txt', 'r', encoding='UTF-8')
thinks = f.read().split('\n')
f.close()
# Creating a bot
bot = 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 bot
bot.polling(none_stop=True, interval=0)
An example of a bot that knows facts and sayings
An example of a bot that knows facts and sayings

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 telebot
import time
# Token that issues @botfather
bot = telebot.TeleBot('Here is your token received from @botfather')
# Telegram channel address, starts with @
CHANNEL_NAME = '@channel_address'
# Loading the list of jokes
f = open('data/fun.txt', 'r', encoding='UTF-8')
jokes = f.read().split('\n')
f.close()
# Until the jokes run out, send them to the channel
for 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 :-(")
An example of a bot running a channel with jokes
An example of a bot running a channel with jokes

Chatbot “Masha”

Now let’s make the simplest chatbot that will chat with the user. To do this, we will prepare the boltun.txt 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 name
My name is Masha!
u: How old are you
I've already 18, honestly-honestly!

File boltun.txt 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 fuzzywuzzy
pip 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.txt.

import telebot
import os
from fuzzywuzzy import fuzz
# Create a bot, write your own token
bot = telebot.TeleBot('Here is your token received from @botfather')
# Loading the list of phrases and answers into the
mas=[]
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 answer
def 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 bot
bot.polling(none_stop=True, interval=0)
Example of a chatbot
Example of a chatbot

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.

Sign up for a course

Related posts:
2022.06.02 — Blindfold game. Manage your Android smartphone via ABD

One day I encountered a technical issue: I had to put a phone connected to a single-board Raspberry Pi computer into the USB-tethering mode on boot. To do this,…

Full article →
2022.02.15 — First contact: How hackers steal money from bank cards

Network fraudsters and carders continuously invent new ways to steal money from cardholders and card accounts. This article discusses techniques used by criminals to bypass security…

Full article →
2022.02.09 — F#ck da Antivirus! How to bypass antiviruses during pentest

Antiviruses are extremely useful tools - but not in situations when you need to remain unnoticed on an attacked network. Today, I will explain how…

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 →
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.07.20 — Evil modem. Establishing a foothold in the attacked system with a USB modem

If you have direct access to the target PC, you can create a permanent and continuous communication channel with it. All you need for this…

Full article →
2022.01.11 — Pentest in your own way. How to create a new testing methodology using OSCP and Hack The Box machines

Each aspiring pentester or information security enthusiast wants to advance at some point from reading exciting write-ups to practical tasks. How to do this in the best way…

Full article →
2022.06.03 — Challenge the Keemaker! How to bypass antiviruses and inject shellcode into KeePass memory

Recently, I was involved with a challenging pentesting project. Using the KeeThief utility from GhostPack, I tried to extract the master password for the open-source KeePass database…

Full article →
2022.06.01 — Routing nightmare. How to pentest OSPF and EIGRP dynamic routing protocols

The magic and charm of dynamic routing protocols can be deceptive: admins trust them implicitly and often forget to properly configure security systems embedded in these protocols. In this…

Full article →
2023.03.26 — Poisonous spuds. Privilege escalation in AD with RemotePotato0

This article discusses different variations of the NTLM Relay cross-protocol attack delivered using the RemotePotato0 exploit. In addition, you will learn how to hide the signature of an…

Full article →