186 lines
7.3 KiB
Python
186 lines
7.3 KiB
Python
import logging
|
||
import sqlite3
|
||
import asyncio
|
||
from aiogram import Bot, Dispatcher, types
|
||
from aiogram.contrib.middlewares.logging import LoggingMiddleware
|
||
from aiogram.types import 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())
|
||
|
||
# Словарь для хранения вопросов и ответов
|
||
questions = {
|
||
1: "Как вас зовут?",
|
||
2: "Укажите номер телефона для связи",
|
||
3: "Укажите район, улицу, дом",
|
||
4: "Какая уборка нужна, влажная или сухая?",
|
||
5: "На какое время?",
|
||
6: "Оплата наличными или картой?"
|
||
}
|
||
|
||
answer_map = {
|
||
'wet_cleaning': 'Влажная уборка',
|
||
'dry_cleaning': 'Сухая уборка',
|
||
'morning_time': 'Утро',
|
||
'day_time': 'День',
|
||
'evening_time': 'Вечер',
|
||
'cash_payment': 'Наличные',
|
||
'card_payment': 'Карта'
|
||
}
|
||
|
||
# Обработчик команды /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):
|
||
if question_id in [4, 5, 6]:
|
||
if question_id == 4:
|
||
keyboard = InlineKeyboardMarkup(inline_keyboard=[
|
||
[InlineKeyboardButton(text="Влажная", callback_data="wet_cleaning")],
|
||
[InlineKeyboardButton(text="Сухая", callback_data="dry_cleaning")]
|
||
])
|
||
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")]
|
||
])
|
||
elif question_id == 6:
|
||
keyboard = InlineKeyboardMarkup(inline_keyboard=[
|
||
[InlineKeyboardButton(text="Наличные", callback_data="cash_payment")],
|
||
[InlineKeyboardButton(text="Карта", callback_data="card_payment")]
|
||
])
|
||
await bot.send_message(user_id, text=questions[question_id], reply_markup=keyboard)
|
||
else:
|
||
await bot.send_message(user_id, text=questions[question_id])
|
||
|
||
# Обработчик текстовых ответов на первые три вопроса
|
||
@dp.message_handler(lambda message: message.text not in ["Переписать", "Отправить"])
|
||
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
|
||
|
||
await save_answer(user_id, question_id, answer)
|
||
|
||
if question_id < 6:
|
||
await ask_question(user_id, question_id + 1)
|
||
else:
|
||
await show_confirmation_options(user_id)
|
||
|
||
# Обработчик inline-кнопок
|
||
@dp.callback_query_handler(lambda query: query.data in answer_map.keys())
|
||
async def handle_callback_answer(query: types.CallbackQuery):
|
||
user_id = query.from_user.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
|
||
|
||
await save_answer(user_id, question_id, answer_map[query.data])
|
||
await query.answer()
|
||
|
||
if question_id < 6:
|
||
await ask_question(user_id, question_id + 1)
|
||
else:
|
||
await show_confirmation_options(user_id)
|
||
|
||
# Функция для сохранения ответа в базе данных
|
||
async def save_answer(user_id, question_id, answer):
|
||
cursor.execute("INSERT INTO answers (user_id, question_id, answer) VALUES (?, ?, ?)", (user_id, question_id, answer))
|
||
conn.commit()
|
||
|
||
# Функция для отображения опций подтверждения
|
||
async def show_confirmation_options(user_id):
|
||
cursor.execute("SELECT answer FROM answers WHERE user_id=? ORDER BY question_id", (user_id,))
|
||
answers = cursor.fetchall()
|
||
answer_text = "\n".join([f"{questions[i+1]}: {answers[i][0]}" for i in range(6)])
|
||
await bot.send_message(user_id, text=f"Ваши ответы:\n\n{answer_text}")
|
||
|
||
keyboard = InlineKeyboardMarkup(inline_keyboard=[
|
||
[InlineKeyboardButton(text="Отправить", callback_data="send_answers")],
|
||
[InlineKeyboardButton(text="Переписать", callback_data="rewrite_answers")]
|
||
])
|
||
await bot.send_message(user_id, "Проверьте свои ответы. Выберите действие:", reply_markup=keyboard)
|
||
|
||
# Обработчик выбора действия подтверждения
|
||
@dp.callback_query_handler(lambda query: query.data in ['send_answers', 'rewrite_answers'])
|
||
async def handle_confirmation(query: types.CallbackQuery):
|
||
user_id = query.from_user.id
|
||
if query.data == "send_answers":
|
||
await send_answers_to_group(user_id)
|
||
elif query.data == "rewrite_answers":
|
||
await rewrite_answers(user_id)
|
||
|
||
# Функция для отправки ответов в группу
|
||
async def send_answers_to_group(user_id):
|
||
cursor.execute("SELECT * FROM answers WHERE user_id=?", (user_id,))
|
||
answers = cursor.fetchall()
|
||
|
||
if answers:
|
||
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()
|
||
|
||
# Отправляем ответы в группу
|
||
await bot.send_message(GROUP_ID, answer_text)
|
||
await bot.send_message(user_id, "Ваши ответы отправлены.")
|
||
else:
|
||
await bot.send_message(user_id, "Ответов нет")
|
||
|
||
# Функция для переписывания ответов
|
||
async def rewrite_answers(user_id):
|
||
# Очищаем таблицу с ответами
|
||
cursor.execute("DELETE FROM answers WHERE user_id=?", (user_id,))
|
||
conn.commit()
|
||
|
||
await bot.send_message(user_id, "Ваши ответы удалены. Начнем сначала.")
|
||
await ask_question(user_id, 1)
|
||
|
||
if __name__ == '__main__':
|
||
loop = asyncio.get_event_loop()
|
||
try:
|
||
loop.create_task(dp.start_polling())
|
||
loop.run_forever()
|
||
except KeyboardInterrupt:
|
||
pass
|
||
finally:
|
||
conn.close()
|