Educational telegram bot. Example of a math problem book

The telegram bot technology won me over with its versatility. You can use it in telegram, or just in the browser, you can create any logic of work… Today we will consider the version of the telegram bot, which is a fragment of a math problem book for the 4th grade. Why is everything so complicated, the child is simply in the 4th grade and actively uses telegram.

Let's get started. In the telegram, we launch the BotFether bot, register a new bot name. The bot name and token will always be available to us in BotFether.

Then we install Python and PyCharm on the computer. We check that they see each other and install the telebot module. I will give these steps in chronological order, more detailed information can be found on the Internet.

We choose a classic problem from the textbook.

Two cars left the city in opposite directions. The speed of the first car is 57.8 km/h. The speed of the second car is 63.5 km/h. In how many hours will the distance between them be 363.9 km?

Excellent. From this problem, we can formulate 4 problems with the definition of various parameters: the speed of the first car, the speed of the second car, time and distance.

In this case, we make some of the numerical values ​​random, and always calculate the path. Let's reformulate the problem a little and get the following source code in Python.

    users[message.from_user.id]['v1'] = random.randint(50, 90)
    users[message.from_user.id]['v2'] = random.randint(50, 90)
    users[message.from_user.id]['t'] = random.randint(2, 7)
    users[message.from_user.id]['S'] = (users[message.from_user.id]['v1'] + users[message.from_user.id]['v2']) * users[message.from_user.id]['t']
    users[message.from_user.id]['mode'] = random.randint(1, 4)
    if users[message.from_user.id]['mode'] == 1:
        a = "Из города в противоположных направлениях выехали два автомобиля. Скорость первого автомобиля " + str(users[message.from_user.id]['v1']) + " км/ч. Скорость второго " + str(users[message.from_user.id]['v2']) + " км/ч. Через сколько часов расстояние между ними будет составлять " + str(users[message.from_user.id]['S']) + " км?"
    elif users[message.from_user.id]['mode'] == 2:
        a = "Из города в противоположных направлениях выехали два автомобиля. Скорость первого автомобиля " + str(users[message.from_user.id]['v1']) + " км/ч. Скорость второго " + str(users[message.from_user.id]['v2']) + " км/ч. Какое расстояние будет между ними через " + str(users[message.from_user.id]['t']) + " ч?"
    elif users[message.from_user.id]['mode'] == 3:
        a = "Из города в противоположных направлениях выехали два автомобиля. Скорость первого автомобиля " + str(users[message.from_user.id]['v1']) + " км/ч. Через " + str(users[message.from_user.id]['t']) + " ч расстояние между ними было " + str(users[message.from_user.id]['S']) + " км. Определите скорость второго автомобиля."
    else:
        a = "Из города в противоположных направлениях выехали два автомобиля. Скорость второго автомобиля " + str(users[message.from_user.id]['v2']) + " км/ч. Через " + str(users[message.from_user.id]['t']) + " ч расстояние между ними было " + str(users[message.from_user.id]['S']) + " км. Определите скорость первого автомобиля."
    bot.send_message(message.chat.id, a)
    bot.send_message(message.chat.id, "Введите ответ")

In line 5, we select the question option.

Let's process the answer entered by the student.

    if users[message.from_user.id]['mode'] > 0:
        if is_number(message.text)==True:
            if users[message.from_user.id]['mode']==1:
                if users[message.from_user.id]['t'] == int(message.text):
                    zapis(True,message.from_user.id,users[message.from_user.id]['mode'])
                else:
                    zapis(False,message.from_user.id,users[message.from_user.id]['mode'])
            elif users[message.from_user.id]['mode']==2:
                if users[message.from_user.id]['S'] == int(message.text):
                    zapis(True,message.from_user.id,users[message.from_user.id]['mode'])
                else:
                    zapis(False, message.from_user.id, users[message.from_user.id]['mode'])
            elif users[message.from_user.id]['mode']==3:
                if users[message.from_user.id]['v2'] == int(message.text):
                    zapis(True, message.from_user.id, users[message.from_user.id]['mode'])
                else:
                    zapis(False,message.from_user.id,users[message.from_user.id]['mode'])
            else:
                if users[message.from_user.id]['v1'] == int(message.text):
                    zapis(True, message.from_user.id, users[message.from_user.id]['mode'])
                else:
                    zapis(False, message.from_user.id, users[message.from_user.id]['mode'])

At the same time, do not forget to check that the entered answer is a number.

def is_number(s):
    """ Функция проверки ввода на число """
    try:
        float(s)
        return True
    except ValueError:
        return False

The previously mentioned zapis function outputs a message about the correctness of the answer and writes it to a file for the teacher.

def zapis(r,id,md):
    if r==True:
        stroka="Правильно"
        bot.send_message(id, "Правильно.")
    else:
        stroka = "Неправильно"
        bot.send_message(id, "Неправильно.")
    f = open('result.txt', 'a', encoding='utf-8')
    f.write(users[id]['name'] + "  "+str(md)+"  "+stroka+'\n')
    f.close()

To determine who owns which result, we ask the student to enter a name and match it with a numeric identifier when the bot starts.

@bot.message_handler(commands=['start'])
def start_message(message):
    global chet
    users.setdefault(message.from_user.id, {'v1': 0,
                                            'v2': 0,
                                            't': 0,
                                            'name': "",
                                            'mode': 0,
                                            'S': 0})
    # Создание reply кнопки 'Меню'
    markup = types.ReplyKeyboardMarkup(resize_keyboard=True)
    btn = types.KeyboardButton("Новая задача")
    markup.add(btn)
    bot.send_message(message.chat.id, "Введите имя",
                     reply_markup=markup)
    chet = 1
 if message.text!="password" and is_number(message.text)==False and chet==1:
        users[message.from_user.id]['name']=message.text
        chet=0
        bot.send_message(message.chat.id, "Нажмите 'Новая задача'")

Launch the bot. Enter the name, click the New task button. Enter the wrong answer, enter the correct answer.

Everything works. Let's try generating new tasks.

That's right. New tasks every time. We're adding the ability for the teacher to upload a file with results and clear it.

    if message.text =="password":
        file = open("./result.txt", "rb")
        bot.send_document(message.chat.id, file)

    if message.text =="pass_del":
        f = open('result.txt', 'w', encoding='utf-8')
        f.write("Результаты решения задач:"+'\n')
        f.close()
        bot.send_message(message.chat.id, "Данные удалены")

Let's try.

The file with the results is downloaded using our password.

Now we have a working bot with a variable task for the whole class. At the same time, this technology will allow the whole class to work with the telegram bot at the same time. There is a mechanism for uploading results. In a similar way, you can process almost any educational material. The variability of tasks will not allow copying from each other, and the correctness check is already automated. Below is the entire source code of the main file.

import telebot  # Импортируем telebot
from secrets import secrets  # Словарь с токеном из файла secrets.py
from users import users  # Импортируем словарь для работы нескольких пользователей одновременно
from telebot import types  # для указания типов
from inline import del_inline  # для работы функции удаления предыдущего сообщения inline
import time
import random

# передаём значение переменной с кодом экземпляру бота
token = secrets.get('BOT_API_TOKEN')
bot = telebot.TeleBot(token)


def is_number(s):
    """ Функция проверки ввода на число """
    try:
        float(s)
        return True
    except ValueError:
        return False


# хендлер и функция для обработки команды /start
@bot.message_handler(commands=['start'])
def start_message(message):
    global chet
    users.setdefault(message.from_user.id, {'v1': 0,
                                            'v2': 0,
                                            't': 0,
                                            'name': "",
                                            'mode': 0,
                                            'S': 0})
    # Создание reply кнопки 'Меню'
    markup = types.ReplyKeyboardMarkup(resize_keyboard=True)
    btn = types.KeyboardButton("Новая задача")
    markup.add(btn)
    bot.send_message(message.chat.id, "Введите имя",
                     reply_markup=markup)
    chet = 1

def zapis(r,id,md):
    if r==True:
        stroka="Правильно"
        bot.send_message(id, "Правильно.")
    else:
        stroka = "Неправильно"
        bot.send_message(id, "Неправильно.")
    f = open('result.txt', 'a', encoding='utf-8')
    f.write(users[id]['name'] + "  "+str(md)+"  "+stroka+'\n')
    f.close()

@bot.message_handler(content_types=["text"])
def text(message):
    global chet     # Для работы возможности выбора только одной операции в один момент времени (Калькулятор или список продуктов)
    if message.text == "Новая задача":  # При поступлении сообщения 'Меню' в чат
        menu(message)   # Вызов функции меню

    if message.text!="password" and is_number(message.text)==False and chet==1:
        users[message.from_user.id]['name']=message.text
        chet=0
        bot.send_message(message.chat.id, "Нажмите 'Новая задача'")

    if message.text =="password":
        file = open("./result.txt", "rb")
        bot.send_document(message.chat.id, file)

    if message.text =="pass_del":
        f = open('result.txt', 'w', encoding='utf-8')
        f.write("Результаты решения задач:"+'\n')
        f.close()
        bot.send_message(message.chat.id, "Данные удалены")

    if users[message.from_user.id]['mode'] > 0:
        if is_number(message.text)==True:
            if users[message.from_user.id]['mode']==1:
                if users[message.from_user.id]['t'] == int(message.text):
                    zapis(True,message.from_user.id,users[message.from_user.id]['mode'])
                else:
                    zapis(False,message.from_user.id,users[message.from_user.id]['mode'])
            elif users[message.from_user.id]['mode']==2:
                if users[message.from_user.id]['S'] == int(message.text):
                    zapis(True,message.from_user.id,users[message.from_user.id]['mode'])
                else:
                    zapis(False, message.from_user.id, users[message.from_user.id]['mode'])
            elif users[message.from_user.id]['mode']==3:
                if users[message.from_user.id]['v2'] == int(message.text):
                    zapis(True, message.from_user.id, users[message.from_user.id]['mode'])
                else:
                    zapis(False,message.from_user.id,users[message.from_user.id]['mode'])
            else:
                if users[message.from_user.id]['v1'] == int(message.text):
                    zapis(True, message.from_user.id, users[message.from_user.id]['mode'])
                else:
                    zapis(False, message.from_user.id, users[message.from_user.id]['mode'])
@bot.message_handler(content_types=["text"])
def menu(message):
    """
    Функция вызова меню с выбором inline кнопок
    """
    users[message.from_user.id]['v1'] = random.randint(50, 90)
    users[message.from_user.id]['v2'] = random.randint(50, 90)
    users[message.from_user.id]['t'] = random.randint(2, 7)
    users[message.from_user.id]['S'] = (users[message.from_user.id]['v1'] + users[message.from_user.id]['v2']) * users[message.from_user.id]['t']
    users[message.from_user.id]['mode'] = random.randint(1, 4)
    if users[message.from_user.id]['mode'] == 1:
        a = "Из города в противоположных направлениях выехали два автомобиля. Скорость первого автомобиля " + str(users[message.from_user.id]['v1']) + " км/ч. Скорость второго " + str(users[message.from_user.id]['v2']) + " км/ч. Через сколько часов расстояние между ними будет составлять " + str(users[message.from_user.id]['S']) + " км?"
    elif users[message.from_user.id]['mode'] == 2:
        a = "Из города в противоположных направлениях выехали два автомобиля. Скорость первого автомобиля " + str(users[message.from_user.id]['v1']) + " км/ч. Скорость второго " + str(users[message.from_user.id]['v2']) + " км/ч. Какое расстояние будет между ними через " + str(users[message.from_user.id]['t']) + " ч?"
    elif users[message.from_user.id]['mode'] == 3:
        a = "Из города в противоположных направлениях выехали два автомобиля. Скорость первого автомобиля " + str(users[message.from_user.id]['v1']) + " км/ч. Через " + str(users[message.from_user.id]['t']) + " ч расстояние между ними было " + str(users[message.from_user.id]['S']) + " км. Определите скорость второго автомобиля."
    else:
        a = "Из города в противоположных направлениях выехали два автомобиля. Скорость второго автомобиля " + str(users[message.from_user.id]['v2']) + " км/ч. Через " + str(users[message.from_user.id]['t']) + " ч расстояние между ними было " + str(users[message.from_user.id]['S']) + " км. Определите скорость первого автомобиля."
    bot.send_message(message.chat.id, a)
    bot.send_message(message.chat.id, "Введите ответ")

# бесконечное выполнение кода
while True:
    try:
      bot.polling(none_stop=True, interval=0)
    except:
      continue
#bot.polling(none_stop=True, interval=0)

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *