From c50fc582571ceb2641d104d5446e77913e7d00cc Mon Sep 17 00:00:00 2001 From: krasi Date: Sat, 15 Jun 2024 00:42:43 +0300 Subject: [PATCH] 140600 --- .idea/.gitignore | 3 + .idea/BOTKlining.iml | 10 + .../inspectionProfiles/profiles_settings.xml | 6 + .idea/misc.xml | 7 + .idea/modules.xml | 8 + .idea/vcs.xml | 6 + answers.db | Bin 0 -> 8192 bytes bot.db | Bin 0 -> 8192 bytes main.py | 188 ++++++++++++++++++ 9 files changed, 228 insertions(+) create mode 100644 .idea/.gitignore create mode 100644 .idea/BOTKlining.iml create mode 100644 .idea/inspectionProfiles/profiles_settings.xml create mode 100644 .idea/misc.xml create mode 100644 .idea/modules.xml create mode 100644 .idea/vcs.xml create mode 100644 answers.db create mode 100644 bot.db create mode 100644 main.py diff --git a/.idea/.gitignore b/.idea/.gitignore new file mode 100644 index 0000000..26d3352 --- /dev/null +++ b/.idea/.gitignore @@ -0,0 +1,3 @@ +# Default ignored files +/shelf/ +/workspace.xml diff --git a/.idea/BOTKlining.iml b/.idea/BOTKlining.iml new file mode 100644 index 0000000..d69e8e4 --- /dev/null +++ b/.idea/BOTKlining.iml @@ -0,0 +1,10 @@ + + + + + + + + + + \ No newline at end of file diff --git a/.idea/inspectionProfiles/profiles_settings.xml b/.idea/inspectionProfiles/profiles_settings.xml new file mode 100644 index 0000000..105ce2d --- /dev/null +++ b/.idea/inspectionProfiles/profiles_settings.xml @@ -0,0 +1,6 @@ + + + + \ No newline at end of file diff --git a/.idea/misc.xml b/.idea/misc.xml new file mode 100644 index 0000000..d92aab6 --- /dev/null +++ b/.idea/misc.xml @@ -0,0 +1,7 @@ + + + + + + \ No newline at end of file diff --git a/.idea/modules.xml b/.idea/modules.xml new file mode 100644 index 0000000..3956f52 --- /dev/null +++ b/.idea/modules.xml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/.idea/vcs.xml b/.idea/vcs.xml new file mode 100644 index 0000000..35eb1dd --- /dev/null +++ b/.idea/vcs.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/answers.db b/answers.db new file mode 100644 index 0000000000000000000000000000000000000000..771431feaf389fd6b0568260d5647ba030590647 GIT binary patch literal 8192 zcmeI1OG^S#6oBuwG0}XqNec;Xi(d5DsEcS(CPM@gWV3J=MiU67>5R11B3$$kqE%48 z!3@P7+CPXpe?t5hb!M(YyY3IJawUxeiTd5nDDxVQdQnC4{21Gan7H3 z+bHr^tHi3PJH%_?V~%&oHbVneXeb;Gg<+&1={5fr2GusVTzE?4 zPZTx;1Rwwb2tWV=5P$##AOHafK;T~m4kA-DO>t~!Z?^LHfxnvu+S7iJD2=u&EhSl5 zEk|-ySsq_7MDW!;>=bbTd literal 0 HcmV?d00001 diff --git a/main.py b/main.py new file mode 100644 index 0000000..2c54d5f --- /dev/null +++ b/main.py @@ -0,0 +1,188 @@ +import logging +import sqlite3 +import asyncio +from aiogram import Bot, Dispatcher, types +from aiogram.contrib.middlewares.logging import LoggingMiddleware +from aiogram.types import ReplyKeyboardMarkup, KeyboardButton, InlineKeyboardMarkup, InlineKeyboardButton + +# Устанавливаем уровень логов +logging.basicConfig(level=logging.INFO) + +# Подключаемся к базе данных SQLite +conn = sqlite3.connect("answers.db") +cursor = conn.cursor() + +# Создание таблицы для хранения ответов +cursor.execute(""" +CREATE TABLE IF NOT EXISTS answers ( + user_id INTEGER, + question_id INTEGER, + answer TEXT +) +""") +conn.commit() + +# Заменить на свой токен +API_TOKEN = '7472030348:AAGI53nX-ON-WBmEhd_qBC6EnZsHOqp_2kE' +GROUP_ID = '-1001961537659' + +# Инициализация бота и диспетчера +bot = Bot(token=API_TOKEN) +dp = Dispatcher(bot) +dp.middleware.setup(LoggingMiddleware()) + +# Клавиатура для подтверждения ответов +confirm_keyboard = ReplyKeyboardMarkup(resize_keyboard=True).add(KeyboardButton('Подтвердить')) + +# Словарь для хранения вопросов и ответов +questions = { + 1: "Как вас зовут?", + 2: "Укажите номер телефона дл связи", + 3: "Укажите район, улицу дом", + 4: "Какая уборка нужна, влажная ли сухая?", + 5: "На какое время?", + 6: "Оплата наличными или картой?" +} + +# Обработчик команды /start +@dp.message_handler(commands=['start']) +async def start(message: types.Message): + await message.answer("Привет! Я задам тебе 6 вопросов. Давай начнем.") + await ask_question(message.chat.id, 1) + + +# Функция для задания вопроса +async def ask_question(user_id, question_id): + #question_text = questions[question_id] + #await bot.send_message(user_id, text=question_text, reply_markup=confirm_keyboard) + if question_id == 4: + keyboard = InlineKeyboardMarkup(inline_keyboard=[ + [ + InlineKeyboardButton(text="Влажная", callback_data="wet_cleaning"), + InlineKeyboardButton(text="Сухая", callback_data="dry_cleaning") + ] + ]) + question_text = questions[question_id] + await bot.send_message(user_id, text=question_text, reply_markup=keyboard) + elif question_id == 5: + keyboard = InlineKeyboardMarkup(inline_keyboard=[ + [ + InlineKeyboardButton(text="Утро", callback_data="morning_time"), + InlineKeyboardButton(text="День", callback_data="day_time"), + InlineKeyboardButton(text="Вечер", callback_data="evening_time") + ] + ]) + question_text = questions[question_id] + await bot.send_message(user_id, text=question_text, reply_markup=keyboard) + elif question_id == 6: + keyboard = InlineKeyboardMarkup(inline_keyboard=[ + [ + InlineKeyboardButton(text="Наличные", callback_data="cash_payment"), + InlineKeyboardButton(text="Карта", callback_data="card_payment") + ] + ]) + question_text = questions[question_id] + await bot.send_message(user_id, text=question_text, reply_markup=keyboard) + else: + question_text = questions[question_id] + await bot.send_message(user_id, text=question_text, reply_markup=confirm_keyboard) + + +# Обработчик callback-кнопок +@dp.callback_query_handler(lambda query: query.data in ['wet_cleaning', 'dry_cleaning', 'morning_time', 'day_time', 'evening_time', 'cash_payment', 'card_payment']) +async def handle_callback_answer(query: types.CallbackQuery): + answer = { + 'wet_cleaning': 'Влажная уборка', + 'dry_cleaning': 'Сухая уборка', + 'morning_time': 'Утро', + 'day_time': 'День', + 'evening_time': 'Вечер', + 'cash_payment': 'Наличные', + 'card_payment': 'Карта' + } + await save_answer(query.from_user.id, answer[query.data]) + await ask_question(query.from_user.id, query.message.message_id + 1) + +# Функция для сохранения ответа в базе данных +async def save_answer(user_id, answer): + cursor.execute("INSERT INTO answers (user_id, question_id, answer) VALUES (?, ?, ?)", (user_id, cursor.rowcount + 1, answer)) + conn.commit() + +# Обработчик ответов с текстовым полем +@dp.message_handler(lambda message: message.text != 'Подтвердить') +async def handle_text_answer(message: types.Message): + user_id = message.chat.id + cursor.execute("SELECT MAX(question_id) FROM answers WHERE user_id=?", (user_id,)) + prev_question_id = cursor.fetchone()[0] + + if prev_question_id is None: + question_id = 1 + else: + question_id = prev_question_id + 1 + answer = message.text + + cursor.execute("INSERT INTO answers (user_id, question_id, answer) VALUES (?, ?, ?)", + (user_id, question_id, answer)) + conn.commit() + + if question_id < 6: + await ask_question(user_id, question_id + 1) + else: + await bot.send_message(user_id, "Ответы записаны. Подтверди перед отправкой.", reply_markup=confirm_keyboard) + + +# Обработчик ответов с inline кнопкой +@dp.callback_query_handler() +async def handle_callback_answer(query: types.CallbackQuery): + user_id = query.from_user.id + answer = query.data + + cursor.execute("SELECT MAX(question_id) FROM answers WHERE user_id=?", (user_id,)) + prev_question_id = cursor.fetchone()[0] + + if prev_question_id is None: + question_id = 1 + else: + question_id = prev_question_id + 1 + + cursor.execute("INSERT INTO answers (user_id, question_id, answer) VALUES (?, ?, ?)", + (user_id, question_id, answer)) + conn.commit() + + if question_id < 6: + await ask_question(user_id, question_id + 1) + else: + await bot.send_message(user_id, "Ответы записаны. Подтверди перед отправкой.", reply_markup=confirm_keyboard) +# Функция для подтверждения ответов и отправки в группу +@dp.message_handler(lambda message: message.text == 'Подтвердить') +async def confirm_answers(message: types.Message): + user_id = message.chat.id + cursor.execute("SELECT * FROM answers WHERE user_id=?", (user_id,)) + answers = cursor.fetchall() + + if answers: + group_id = GROUP_ID # Заменить на ID вашей группы + answer_text = '\n'.join([f"{questions[ans[1]]}: {ans[2]}" for ans in answers]) + + # Очищаем таблицу с ответами + cursor.execute("DELETE FROM answers WHERE user_id=?", (user_id,)) + conn.commit() + + # Отправляем ответы в группу с помощью реплая + sent_message = await bot.send_message(group_id, answer_text) + await bot.send_message(user_id, + f"Ответы отправлены в группу. Можете посмотреть их [здесь](https://t.me/{sent_message.chat.username}/{sent_message.message_id})", + parse_mode='Markdown') + else: + await bot.send_message(user_id, "Ответов нет") + + +if __name__ == '__main__': + loop = asyncio.get_event_loop() + try: + loop.create_task(dp.start_polling()) + loop.run_forever() + except KeyboardInterrupt: + pass + finally: + conn.close()