main commit. bot added, admin is functional
This commit is contained in:
39
bot/bot.py
39
bot/bot.py
@@ -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()
|
|
||||||
29
bot/handlers.py
Normal file
29
bot/handlers.py
Normal file
@@ -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("В базе данных нет отелей.")
|
||||||
0
bot/management/commands/__init__.py
Normal file
0
bot/management/commands/__init__.py
Normal file
28
bot/management/commands/run_bot.py
Normal file
28
bot/management/commands/run_bot.py
Normal file
@@ -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()
|
||||||
Reference in New Issue
Block a user