@Ryuk3000
Noob в питоне

Как сделать в телеграмм боте что б он в mongodb отображал имя, фамилию и группу?

Здравствуйте всем. Помогите пожалуйста. Есть телеграмм бот для студентов вопрос ответ.
Когда заходит студент в телеграмм ему нужно ввести команду /go
после выходит сообщение что б он ввел (Ф.И.Группу).
Как он вводит (Ф.И.Группу) сразу появляются вопросы. Но в mongodb мне нужно сделать что б он отображал введенный (Ф.И.Группу).
Как можно это сделать?
Код прикреплю. Помогите пожалуйста
63b2142bc23d1999709822.png
63b2157ea58af278756353.png

import telebot
from pymongo import MongoClient
from datetime import datetime


bot = telebot.TeleBot("")



class DataBase:
    def __init__(self):
        cluster = MongoClient("")

        self.db = cluster["QuizBot"]
        self.users = self.db["Users"]
        self.questions = self.db["Questions"]

        self.questions_count = len(list(self.questions.find({})))

    def get_user(self, chat_id):
        user = self.users.find_one({"chat_id": chat_id})
        date = datetime.now().date()
        time = datetime.now().time()



        if user is not None:
            return user

        user = {
            "chat_id": chat_id,
            "is_passing": False,
            "is_passed": False,
            'date': str(date),
            'time': str(time),
            "question_index": None,
            "answers": []
        }
        self.users.insert_one(user)



        return user

    def set_user(self, chat_id, update):
        self.users.update_one({"chat_id": chat_id }, {"$set": update})

    def get_question(self, index):
        return self.questions.find_one({"id": index})


db = DataBase()

@bot.message_handler(commands=['go'])
def send_welcome(message):
    message = bot.reply_to(message, """\
Привет, начинаем экзамен
напишите свою Группу, Фамилию и Имя
""")
    bot.register_next_step_handler(message, process_name_step)
@bot.message_handler(commands=["process_name_step"])
def process_name_step (message):
    user = db.get_user(message.chat.id)

    


    if user['is_passed']:
        bot.send_message(message.from_user.id, "Ты уже проходил экзамен ")
        return

    if user["is_passing"]:
        return

    db.set_user(message.chat.id, {"question_index": 0, "is_passing": True})

    user = db.get_user(message.chat.id)
    post = get_question_message(user)
    if post is not None:
        bot.send_message(message.from_user.id, post["text"], reply_markup=post["keyboard"])

@bot.callback_query_handler(func=lambda query: query.data.startswith("?ans"))
def answered(query):
    user = db.get_user(query.message.chat.id)

    if user["is_passed"] or not user["is_passing"]:
        return

    user["answers"].append(int(query.data.split("&")[1]))
    db.set_user(query.message.chat.id, {"answers": user["answers"]})

    post = get_answered_message(user)
    if post is not None:
        bot.edit_message_text(post["text"], query.message.chat.id, query.message.id,
                              reply_markup=post["keyboard"])

@bot.callback_query_handler(func=lambda query: query.data == "?next")
def next(query):
    user = db.get_user(query.message.chat.id)

    if user["is_passed"] or not user["is_passing"]:
        return

    user["question_index"] += 1
    db.set_user(query.message.chat.id, {"question_index": user["question_index"]})

    post = get_question_message(user)
    if post is not None:
        bot.edit_message_text(post["text"], query.message.chat.id, query.message.id,
                              reply_markup=post["keyboard"])


def get_question_message(user):
    if user["question_index"] == db.questions_count:
        count = 0
        for question_index, question in enumerate(db.questions.find({})):
            if question["correct"] == user["answers"][question_index]:
                count += 1
        points = round(40 * count / db.questions_count)

        if points < 10:
            smile = ""
        elif points < 20:
            points = ""
        elif points < 30:
            smile = ""
        elif points < 40:
            smile = ""
        else:
            smile = ""

        text = f"Вы ответили правильно на {points} points вопросов {smile}"

        db.set_user(user["chat_id"], {"is_passed": True, "is_passing": False})

        return {
            "text": text,
            "keyboard": None
        }

    question = db.get_question(user["question_index"])

    if question is None:
        return

    keyboard = telebot.types.InlineKeyboardMarkup()
    for answer_index, answer in enumerate(question["answers"]):
        keyboard.row(telebot.types.InlineKeyboardButton(f"{chr(answer_index + 97)}) {answer}",
                                                        callback_data=f"?ans&{answer_index}"))

    text = f"Вопрос №{user['question_index'] + 1}\n\n{question['text']}"

    return {
        "text": text,
        "keyboard": keyboard
    }

def get_answered_message(user):
    question = db.get_question(user["question_index"])

    text = f"Вопрос №{user['question_index'] + 1}\n\n{question['text']}\n"

    for answer_index, answer in enumerate(question["answers"]):
        text += f"{chr(answer_index + 97)}) {answer}"

        if answer_index == question["correct"]:
            text += " "
        elif answer_index == user["answers"][-1]:
            text += " ❌"

        text += "\n"

    keyboard = telebot.types.InlineKeyboardMarkup()
    keyboard.row(telebot.types.InlineKeyboardButton("Далее", callback_data="?next"))

    return {
        "text": text,
        "keyboard": keyboard
    }


bot.polling()
  • Вопрос задан
  • 159 просмотров
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы