Listen, Telegram bots are a hot topic for several years now. They're used for everything from weather notifications to full-fledged payment systems. I started with a simple echo bot, and now I have several services that generate a steady income and save a ton of time. In this article, I'll show you how to go from zero to your first "smart" bot.
If you're completely new to Python, don't worry. I once didn't know which way to approach this snake either. At the end of the article, I'll provide links to introductory materials that will help you understand the basics.
---
What you need to get started
We'll need:
Python 3 (preferably 3.6 or higher)
The pyTelegramBotApi library installed
A Telegram account
A little patience and a willingness to tinker
To install the library, open a terminal and enter:
pip install pytelegrambotapi
If you're on Linux, you may need pip3 instead of pip.
--
Creating a Telegram bot: instructions for those who don't know where to start
First, you need to get acquainted with BotFather—the "father of all bots." Find it in Telegram, click "Run," or type /start. It will display a list of commands:
/newbot — create a new bot
/mybots — view your bots
/setname — change name
/setdescription — change description
/setabouttext — change "about me"
/setuserpic — change avatar
/setcommands — customize the command list
/deletebot — delete bot
Click /newbot. BotFather will ask you to enter the bot's name (as it will be displayed in the interface; you can enter it in Russian). Then enter the address (username). The address must end in "bot." For example, xakep_bot. If the address is already taken, try another one.
After successful creation, you will receive a message with a token—this is the API access key. It looks like a string of letters and numbers. Save it in a safe place; you'll need it for all our scripts.
---
Echo Bot: Our First Application
Let's start with the simplest thing—a bot that returns the same message to the user. This is the foundation upon which everything else is built.
Import telebot
Insert your token here
bot = telebot.TeleBot('YOUR_TOKEN')
/start command handler
@bot.message_handler(commands=["start"]) def start(message): bot.send_message(message.chat.id, 'I'm online. Text me something')
Any text message handler
@bot.message_handler(content_types=["text"]) def handle_text(message): bot.send_message(message.chat.id, 'You wrote: ' + message.text)
Start the bot
bot.polling(none_stop=True, interval=0)
Run the script, find your bot in Telegram, press /start, and write any message. The bot should repeat it.
---
Wikipedia Bot: Adding Useful Functionality
Now let's create a bot that searches for Wikipedia articles. For this, we'll need the Wikipedia module.
pip install wikipedia
import telebot import wikipedia import re
bot = telebot.TeleBot('YOUR_TOKEN')
Set the Russian language
wikipedia.set_lang("ru")
Function for getting an article
def getwiki(search): try: page = wikipedia.page(search) # Get the first 1000 characters wikitext = page.content[:1000] # Split by periods wikimas = wikitext.split('.') # Discard everything after the last period wikimas = wikimas[:-1] wikitext2 = '' # Collect the text without headings for x in wikimas: if not('==' in x): if len(x.strip()) > 3: wikitext2 = wikitext2 + x + '.' else: break # Cleaning up the markup with regular expressions wikitext2 = re.sub('[^()]*', '', wikitext2) wikitext2 = re.sub('\{[^\{\}]*\}', '', wikitext2) return wikitext2 except: return 'The encyclopedia doesn't have any information about this'
@bot.message_handler(commands=["start"]) def start(message): bot.send_message(message.chat.id, 'Send me any word, and I'll look it up on Wikipedia')
@bot.message_handler(content_types=["text"]) def handle_text(message): bot.send_message(message.chat.id, getwiki(message.text))
bot.polling(none_stop=True, interval=0)
The bot can now search for information. Try sending it the word "Python" or "hacker"—it should give you a quick summary.
---
Бот с двумя виртуальными кнопками
Виртуальные кнопки — это удобный способ управления. Сделаем бота, который выдает случайный факт или поговорку.
Сначала создадим два текстовых файла в папке data/:
· facts.txt — с фактами (каждая строка — один факт)
· thinks.txt — с поговорками (каждая строка — одна поговорка)
import telebot import random from telebot import types
Загружаем файлы
with open('data/facts.txt', 'r', encoding='UTF-8') as f: facts = f.read().split('\n') with open('data/thinks.txt','r', encoding='UTF-8') as f: thinks = f.read().split('\n')
bot = telebot.TeleBot('ТВОЙ_ТОКЕН')
@bot.message_handler(commands=["start"]) def start(message): # Создаем кнопки markup = types.ReplyKeyboardMarkup(resize_keyboard=True) item1 = types.KeyboardButton("Факт") item2 = types.KeyboardButton("Поговорка") markup.add(item1, item2) bot.send_message(message.chat.id, 'Нажми кнопку', reply_markup=markup)
@bot.message_handler(content_types=["text"]) def handle_text(message): if message.text == "Факт": answer = random.choice(facts) elif message.text == "Поговорка": answer = random.choice(thinks) else: answer = "Я тебя не понял. Нажми кнопку." bot.send_message(message.chat.id, answer)
bot.polling(none_stop=True, interval=0)
Теперь бот не просто слушает текст, но и реагирует на нажатия кнопок.
---
Чат-бот «Маша»: простейший ИИ на fuzzywuzzy
Финальный этап — сделаем бота, который умеет поддерживать простой диалог. Для этого нам понадобится файл boltun.txt в папке data/. Формат простой: строки с u: — это вопросы или фразы пользователя, следующая строка — ответ бота.
Пример содержимого boltun.txt:
u:как зовут Маша меня зовут! u:сколько тебе лет Мне уже 18,честно-честно! u:привет Привет!Как дела?
Установим библиотеку fuzzywuzzy для сравнения строк:
pip install fuzzywuzzy pip install python-Levenshtein
Теперь код:
import telebot import os from fuzzywuzzy import fuzz
bot = telebot.TeleBot('ТВОЙ_ТОКЕН')
Загружаем фразы и ответы в массив
phrases = [] if os.path.exists('data/boltun.txt'): with open('data/boltun.txt', 'r', encoding='UTF-8') as f: for line in f: if len(line.strip()) > 2: phrases.append(line.strip().lower())
Функция поиска ответа
def get_answer(text): try: text = text.lower().strip() if not os.path.exists('data/boltun.txt'): return 'Ошибка: нет базы фраз'
@bot.message_handler(commands=["start"]) def start(message): bot.send_message(message.chat.id, 'Я на связи. Напиши мне "Привет" )')
@bot.message_handler(content_types=["text"]) def handle_text(message): # Сохраняем лог диалога (опционально) with open(f'data/{message.chat.id}_log.txt', 'a', encoding='UTF-8') as f: f.write(f'u: {message.text}\n') answer = get_answer(message.text) f.write(f'{answer}\n') bot.send_message(message.chat.id, answer)
bot.polling(none_stop=True, interval=0)
---
A bot with two virtual buttons
Virtual buttons are a convenient control method. Let's create a bot that produces a random fact or proverb.
First, let's create two text files in the data/ folder:
· facts.txt — with facts (each line is one fact)
· thinks.txt — with proverbs (each line is one proverb)
import telebot import random from telebot import types
Loading files
with open('data/facts.txt', 'r', encoding='UTF-8') as f: facts = f.read().split('\n') with open('data/thinks.txt','r', encoding='UTF-8') as f: thinks = f.read().split('\n')
bot = telebot.TeleBot('YOUR_TOKEN')
@bot.message_handler(commands=["start"]) def start(message): # Create buttons markup = types.ReplyKeyboardMarkup(resize_keyboard=True) item1 = types.KeyboardButton("Fact") item2 = types.KeyboardButton("Proverb") markup.add(item1, item2) bot.send_message(message.chat.id, 'Press the button', reply_markup=markup)
@bot.message_handler(content_types=["text"]) def handle_text(message): if message.text == "Fact": answer = random.choice(facts) elif message.text == "Proverb": answer = random.choice(thinks) else: answer = "I didn't understand you. Press the button." bot.send_message(message.chat.id, answer)
bot.polling(none_stop=True, interval=0)
Now the bot not only listens to text but also responds to button presses.
---
Chatbot "Masha": Basic AI on fuzzywuzzy
The final step is to create a bot that can maintain a simple dialogue. For this, we'll need the boltun.txt file in the data/ folder. The format is simple: lines with u: are the user's questions or phrases, the next line is the bot's response.
Example of boltun.txt contents:
u: What's your name? Masha? My name is! u: How old are you? I'm already 18, honestly! u: Hello! How are you?
Let's install the fuzzywuzzy library for string comparison:
pip install fuzzywuzzy pip install python-Levenshtein
Now the code:
import telebot import os from fuzzywuzzy import fuzz
bot = telebot.TeleBot('YOUR_TOKEN')
Loading phrases and answers into an array
phrases = [] if os.path.exists('data/boltun.txt'): with open('data/boltun.txt', 'r', encoding='UTF-8') as f: for line in f: if len(line.strip()) > 2: phrases.append(line.strip().lower())
Answer search function
def get_answer(text): try: text = text.lower().strip() if not os.path.exists('data/boltun.txt'): return 'Error: no phrase database'
@bot.message_handler(commands=["start"]) def start(message): bot.send_message(message.chat.id, 'I'm online. Text me "Hi"')')
@bot.message_handler(content_types=["text"]) def handle_text(message): # Save the conversation log (optional) with open(f'data/{message.chat.id}_log.txt', 'a', encoding='UTF-8') as f: f.write(f'u: {message.text}\n') answer = get_answer(message.text) f.write(f'{answer}\n') bot.send_message(message.chat.id, answer)
bot.polling(none_stop=True, interval=0)
Now the bot can answer similar questions. It's not true AI, of course, but it's more than enough for simple chatbots.
---
Conclusions and What's Next
We've gone from a simple echo bot to a chatbot that supports dialogue. During this time, we've learned how to:
Work with the Telegram API via the pyTelegramBotApi library
Process commands and text messages
Add virtual buttons
Integrate external data (Wikipedia, files)
Use fuzzywuzzy to search for similar strings
In future articles, we'll cover more complex topics:
Webhooks instead of long polling
Accepting payments from users
Integration with SQLite databases
Multithreading and processing large numbers of messages
For now, experiment, fine-tune the code to suit your needs, and add new features. And don't forget to backup your scripts.
А пока — экспериментируй, допиливай код под свои нужды, добавляй новые фичи. И не забывай делать резервные копии своих скриптов.
If you're completely new to Python, don't worry. I once didn't know which way to approach this snake either. At the end of the article, I'll provide links to introductory materials that will help you understand the basics.
---
What you need to get started
We'll need:
Python 3 (preferably 3.6 or higher)
The pyTelegramBotApi library installed
A Telegram account
A little patience and a willingness to tinker
To install the library, open a terminal and enter:
pip install pytelegrambotapi
If you're on Linux, you may need pip3 instead of pip.
--
Creating a Telegram bot: instructions for those who don't know where to start
First, you need to get acquainted with BotFather—the "father of all bots." Find it in Telegram, click "Run," or type /start. It will display a list of commands:
/newbot — create a new bot
/mybots — view your bots
/setname — change name
/setdescription — change description
/setabouttext — change "about me"
/setuserpic — change avatar
/setcommands — customize the command list
/deletebot — delete bot
Click /newbot. BotFather will ask you to enter the bot's name (as it will be displayed in the interface; you can enter it in Russian). Then enter the address (username). The address must end in "bot." For example, xakep_bot. If the address is already taken, try another one.
After successful creation, you will receive a message with a token—this is the API access key. It looks like a string of letters and numbers. Save it in a safe place; you'll need it for all our scripts.
---
Echo Bot: Our First Application
Let's start with the simplest thing—a bot that returns the same message to the user. This is the foundation upon which everything else is built.
Import telebot
Insert your token here
bot = telebot.TeleBot('YOUR_TOKEN')
/start command handler
@bot.message_handler(commands=["start"]) def start(message): bot.send_message(message.chat.id, 'I'm online. Text me something')
Any text message handler
@bot.message_handler(content_types=["text"]) def handle_text(message): bot.send_message(message.chat.id, 'You wrote: ' + message.text)
Start the bot
bot.polling(none_stop=True, interval=0)
Run the script, find your bot in Telegram, press /start, and write any message. The bot should repeat it.
---
Wikipedia Bot: Adding Useful Functionality
Now let's create a bot that searches for Wikipedia articles. For this, we'll need the Wikipedia module.
pip install wikipedia
import telebot import wikipedia import re
bot = telebot.TeleBot('YOUR_TOKEN')
Set the Russian language
wikipedia.set_lang("ru")
Function for getting an article
def getwiki(search): try: page = wikipedia.page(search) # Get the first 1000 characters wikitext = page.content[:1000] # Split by periods wikimas = wikitext.split('.') # Discard everything after the last period wikimas = wikimas[:-1] wikitext2 = '' # Collect the text without headings for x in wikimas: if not('==' in x): if len(x.strip()) > 3: wikitext2 = wikitext2 + x + '.' else: break # Cleaning up the markup with regular expressions wikitext2 = re.sub('[^()]*', '', wikitext2) wikitext2 = re.sub('\{[^\{\}]*\}', '', wikitext2) return wikitext2 except: return 'The encyclopedia doesn't have any information about this'
@bot.message_handler(commands=["start"]) def start(message): bot.send_message(message.chat.id, 'Send me any word, and I'll look it up on Wikipedia')
@bot.message_handler(content_types=["text"]) def handle_text(message): bot.send_message(message.chat.id, getwiki(message.text))
bot.polling(none_stop=True, interval=0)
The bot can now search for information. Try sending it the word "Python" or "hacker"—it should give you a quick summary.
---
Бот с двумя виртуальными кнопками
Виртуальные кнопки — это удобный способ управления. Сделаем бота, который выдает случайный факт или поговорку.
Сначала создадим два текстовых файла в папке data/:
· facts.txt — с фактами (каждая строка — один факт)
· thinks.txt — с поговорками (каждая строка — одна поговорка)
import telebot import random from telebot import types
Загружаем файлы
with open('data/facts.txt', 'r', encoding='UTF-8') as f: facts = f.read().split('\n') with open('data/thinks.txt','r', encoding='UTF-8') as f: thinks = f.read().split('\n')
bot = telebot.TeleBot('ТВОЙ_ТОКЕН')
@bot.message_handler(commands=["start"]) def start(message): # Создаем кнопки markup = types.ReplyKeyboardMarkup(resize_keyboard=True) item1 = types.KeyboardButton("Факт") item2 = types.KeyboardButton("Поговорка") markup.add(item1, item2) bot.send_message(message.chat.id, 'Нажми кнопку', reply_markup=markup)
@bot.message_handler(content_types=["text"]) def handle_text(message): if message.text == "Факт": answer = random.choice(facts) elif message.text == "Поговорка": answer = random.choice(thinks) else: answer = "Я тебя не понял. Нажми кнопку." bot.send_message(message.chat.id, answer)
bot.polling(none_stop=True, interval=0)
Теперь бот не просто слушает текст, но и реагирует на нажатия кнопок.
---
Чат-бот «Маша»: простейший ИИ на fuzzywuzzy
Финальный этап — сделаем бота, который умеет поддерживать простой диалог. Для этого нам понадобится файл boltun.txt в папке data/. Формат простой: строки с u: — это вопросы или фразы пользователя, следующая строка — ответ бота.
Пример содержимого boltun.txt:
u:как зовут Маша меня зовут! u:сколько тебе лет Мне уже 18,честно-честно! u:привет Привет!Как дела?
Установим библиотеку fuzzywuzzy для сравнения строк:
pip install fuzzywuzzy pip install python-Levenshtein
Теперь код:
import telebot import os from fuzzywuzzy import fuzz
bot = telebot.TeleBot('ТВОЙ_ТОКЕН')
Загружаем фразы и ответы в массив
phrases = [] if os.path.exists('data/boltun.txt'): with open('data/boltun.txt', 'r', encoding='UTF-8') as f: for line in f: if len(line.strip()) > 2: phrases.append(line.strip().lower())
Функция поиска ответа
def get_answer(text): try: text = text.lower().strip() if not os.path.exists('data/boltun.txt'): return 'Ошибка: нет базы фраз'
@bot.message_handler(commands=["start"]) def start(message): bot.send_message(message.chat.id, 'Я на связи. Напиши мне "Привет" )')
@bot.message_handler(content_types=["text"]) def handle_text(message): # Сохраняем лог диалога (опционально) with open(f'data/{message.chat.id}_log.txt', 'a', encoding='UTF-8') as f: f.write(f'u: {message.text}\n') answer = get_answer(message.text) f.write(f'{answer}\n') bot.send_message(message.chat.id, answer)
bot.polling(none_stop=True, interval=0)
---
A bot with two virtual buttons
Virtual buttons are a convenient control method. Let's create a bot that produces a random fact or proverb.
First, let's create two text files in the data/ folder:
· facts.txt — with facts (each line is one fact)
· thinks.txt — with proverbs (each line is one proverb)
import telebot import random from telebot import types
Loading files
with open('data/facts.txt', 'r', encoding='UTF-8') as f: facts = f.read().split('\n') with open('data/thinks.txt','r', encoding='UTF-8') as f: thinks = f.read().split('\n')
bot = telebot.TeleBot('YOUR_TOKEN')
@bot.message_handler(commands=["start"]) def start(message): # Create buttons markup = types.ReplyKeyboardMarkup(resize_keyboard=True) item1 = types.KeyboardButton("Fact") item2 = types.KeyboardButton("Proverb") markup.add(item1, item2) bot.send_message(message.chat.id, 'Press the button', reply_markup=markup)
@bot.message_handler(content_types=["text"]) def handle_text(message): if message.text == "Fact": answer = random.choice(facts) elif message.text == "Proverb": answer = random.choice(thinks) else: answer = "I didn't understand you. Press the button." bot.send_message(message.chat.id, answer)
bot.polling(none_stop=True, interval=0)
Now the bot not only listens to text but also responds to button presses.
---
Chatbot "Masha": Basic AI on fuzzywuzzy
The final step is to create a bot that can maintain a simple dialogue. For this, we'll need the boltun.txt file in the data/ folder. The format is simple: lines with u: are the user's questions or phrases, the next line is the bot's response.
Example of boltun.txt contents:
u: What's your name? Masha? My name is! u: How old are you? I'm already 18, honestly! u: Hello! How are you?
Let's install the fuzzywuzzy library for string comparison:
pip install fuzzywuzzy pip install python-Levenshtein
Now the code:
import telebot import os from fuzzywuzzy import fuzz
bot = telebot.TeleBot('YOUR_TOKEN')
Loading phrases and answers into an array
phrases = [] if os.path.exists('data/boltun.txt'): with open('data/boltun.txt', 'r', encoding='UTF-8') as f: for line in f: if len(line.strip()) > 2: phrases.append(line.strip().lower())
Answer search function
def get_answer(text): try: text = text.lower().strip() if not os.path.exists('data/boltun.txt'): return 'Error: no phrase database'
@bot.message_handler(commands=["start"]) def start(message): bot.send_message(message.chat.id, 'I'm online. Text me "Hi"')')
@bot.message_handler(content_types=["text"]) def handle_text(message): # Save the conversation log (optional) with open(f'data/{message.chat.id}_log.txt', 'a', encoding='UTF-8') as f: f.write(f'u: {message.text}\n') answer = get_answer(message.text) f.write(f'{answer}\n') bot.send_message(message.chat.id, answer)
bot.polling(none_stop=True, interval=0)
Now the bot can answer similar questions. It's not true AI, of course, but it's more than enough for simple chatbots.
---
Conclusions and What's Next
We've gone from a simple echo bot to a chatbot that supports dialogue. During this time, we've learned how to:
Work with the Telegram API via the pyTelegramBotApi library
Process commands and text messages
Add virtual buttons
Integrate external data (Wikipedia, files)
Use fuzzywuzzy to search for similar strings
In future articles, we'll cover more complex topics:
Webhooks instead of long polling
Accepting payments from users
Integration with SQLite databases
Multithreading and processing large numbers of messages
For now, experiment, fine-tune the code to suit your needs, and add new features. And don't forget to backup your scripts.
А пока — экспериментируй, допиливай код под свои нужды, добавляй новые фичи. И не забывай делать резервные копии своих скриптов.