This commit is contained in:
2024-06-15 00:42:43 +03:00
parent 1fcedf2cdb
commit c50fc58257
9 changed files with 228 additions and 0 deletions

3
.idea/.gitignore generated vendored Normal file
View File

@@ -0,0 +1,3 @@
# Default ignored files
/shelf/
/workspace.xml

10
.idea/BOTKlining.iml generated Normal file
View File

@@ -0,0 +1,10 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="PYTHON_MODULE" version="4">
<component name="NewModuleRootManager">
<content url="file://$MODULE_DIR$">
<excludeFolder url="file://$MODULE_DIR$/.venv" />
</content>
<orderEntry type="jdk" jdkName="Python 3.11 (BOTKlining)" jdkType="Python SDK" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>

View File

@@ -0,0 +1,6 @@
<component name="InspectionProjectProfileManager">
<settings>
<option name="USE_PROJECT_PROFILE" value="false" />
<version value="1.0" />
</settings>
</component>

7
.idea/misc.xml generated Normal file
View File

@@ -0,0 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="Black">
<option name="sdkName" value="Python 3.11 (BOTklining)" />
</component>
<component name="ProjectRootManager" version="2" project-jdk-name="Python 3.11 (BOTKlining)" project-jdk-type="Python SDK" />
</project>

8
.idea/modules.xml generated Normal file
View File

@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/BOTKlining.iml" filepath="$PROJECT_DIR$/.idea/BOTKlining.iml" />
</modules>
</component>
</project>

6
.idea/vcs.xml generated Normal file
View File

@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="" vcs="Git" />
</component>
</project>

BIN
answers.db Normal file

Binary file not shown.

BIN
bot.db Normal file

Binary file not shown.

188
main.py Normal file
View File

@@ -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()