From 4b35dba729865f512afb0012b3785561aa3f83f9 Mon Sep 17 00:00:00 2001 From: trevor Date: Fri, 6 Dec 2024 11:29:10 +0900 Subject: [PATCH] main commit. bot added, admin is functional --- bot/bot.py | 39 ----------------------------- bot/handlers.py | 29 +++++++++++++++++++++ bot/management/commands/__init__.py | 0 bot/management/commands/run_bot.py | 28 +++++++++++++++++++++ 4 files changed, 57 insertions(+), 39 deletions(-) delete mode 100644 bot/bot.py create mode 100644 bot/handlers.py create mode 100644 bot/management/commands/__init__.py create mode 100644 bot/management/commands/run_bot.py diff --git a/bot/bot.py b/bot/bot.py deleted file mode 100644 index e50bfaf1..00000000 --- a/bot/bot.py +++ /dev/null @@ -1,39 +0,0 @@ -from telegram import Update -from telegram.ext import Updater, CommandHandler, CallbackContext -from users.models import User, UserConfirmation -import uuid - -def start(update: Update, context: CallbackContext): - user_id = update.message.from_user.id - chat_id = update.message.chat_id - - user, created = User.objects.get_or_create(telegram_id=user_id, defaults={'chat_id': chat_id}) - if not user.confirmed: - confirmation_code = str(uuid.uuid4()) - UserConfirmation.objects.create(user=user, confirmation_code=confirmation_code) - update.message.reply_text(f"Ваш код подтверждения: {confirmation_code}") - else: - update.message.reply_text("Вы уже зарегистрированы!") - -def confirm(update: Update, context: CallbackContext): - user_id = update.message.from_user.id - code = ' '.join(context.args) - - try: - confirmation = UserConfirmation.objects.get(user__telegram_id=user_id, confirmation_code=code) - confirmation.user.confirmed = True - confirmation.user.save() - confirmation.delete() - update.message.reply_text("Регистрация подтверждена!") - except UserConfirmation.DoesNotExist: - update.message.reply_text("Неверный код подтверждения!") - -def main(): - updater = Updater("YOUR_TELEGRAM_BOT_TOKEN") - dispatcher = updater.dispatcher - - dispatcher.add_handler(CommandHandler("start", start)) - dispatcher.add_handler(CommandHandler("confirm", confirm)) - - updater.start_polling() - updater.idle() diff --git a/bot/handlers.py b/bot/handlers.py new file mode 100644 index 00000000..02de6963 --- /dev/null +++ b/bot/handlers.py @@ -0,0 +1,29 @@ +from telegram import Update +from telegram.ext import ContextTypes +from users.models import User +from hotels.models import Hotel +from asgiref.sync import sync_to_async # Импортируем sync_to_async + +async def start(update: Update, context: ContextTypes.DEFAULT_TYPE): + """Обработчик команды /start""" + await update.message.reply_text("Привет! Я бот, работающий с Django. Используй /users или /hotels для проверки базы данных.") + +async def list_users(update: Update, context: ContextTypes.DEFAULT_TYPE): + """Обработчик команды /users""" + # Выполняем запрос к базе данных через sync_to_async + users = await sync_to_async(list)(User.objects.all()) # Преобразуем QuerySet в список + if users: + user_list = "\n".join([f"{user.id}: {user.username}" for user in users]) + await update.message.reply_text(f"Список пользователей:\n{user_list}") + else: + await update.message.reply_text("В базе данных нет пользователей.") + +async def list_hotels(update: Update, context: ContextTypes.DEFAULT_TYPE): + """Обработчик команды /hotels""" + # Выполняем запрос к базе данных через sync_to_async + hotels = await sync_to_async(list)(Hotel.objects.all()) # Преобразуем QuerySet в список + if hotels: + hotel_list = "\n".join([f"{hotel.id}: {hotel.name}" for hotel in hotels]) + await update.message.reply_text(f"Список отелей:\n{hotel_list}") + else: + await update.message.reply_text("В базе данных нет отелей.") diff --git a/bot/management/commands/__init__.py b/bot/management/commands/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/bot/management/commands/run_bot.py b/bot/management/commands/run_bot.py new file mode 100644 index 00000000..cfd191bc --- /dev/null +++ b/bot/management/commands/run_bot.py @@ -0,0 +1,28 @@ +import os +import django +from django.core.management.base import BaseCommand +from telegram.ext import Application, CommandHandler +from bot.handlers import start, list_users, list_hotels # Импорт обработчиков + +# Настройка Django окружения +os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'touchh.settings') +django.setup() + +def main(): + # Создаём приложение Telegram + application = Application.builder().token("8125171867:AAGxDcSpQxJy3_pmq3TDBWtqaAVCj7b-F5k").build() + + # Регистрируем обработчики команд + application.add_handler(CommandHandler("start", start)) + application.add_handler(CommandHandler("users", list_users)) + application.add_handler(CommandHandler("hotels", list_hotels)) + + # Запускаем бота + application.run_polling() + +class Command(BaseCommand): + help = "Запуск Telegram бота" + + def handle(self, *args, **options): + self.stdout.write("Запуск Telegram бота...") + main()