This commit is contained in:
Zikil 2024-12-18 00:19:45 +07:00
parent d9b9716432
commit 8b48220f36
4 changed files with 4 additions and 141 deletions

View File

@ -1,4 +1,4 @@
FROM python:3.11-slim
FROM python:3.10-slim
# Установка рабочей директории
WORKDIR /app

View File

@ -1,133 +0,0 @@
from telegram import Update, WebAppInfo, KeyboardButton, ReplyKeyboardMarkup
from telegram.ext import ContextTypes
from database import Database
import json
db = Database()
async def start_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
keyboard = [
[
KeyboardButton(
"Открыть счётчик 🎲",
web_app=WebAppInfo(url=context.bot_data['webapp_url'])
)
],
[KeyboardButton("Новая игра 🎮"), KeyboardButton("Статистика 📊")],
[KeyboardButton("Завершить игру 🏁")]
]
reply_markup = ReplyKeyboardMarkup(keyboard, resize_keyboard=True)
await update.message.reply_text(
"🎲 Добро пожаловать в счётчик кубиков для нард!\n\n"
"Выберите действие:",
reply_markup=reply_markup
)
async def new_game_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
user = update.effective_user
# Проверяем, нет ли уже активной игры
active_game = db.get_active_game(user.id)
if active_game:
await update.message.reply_text(
"❗️ У вас уже есть активная игра. "
"Сначала завершите её командой /end_game"
)
return
game_id = db.create_game(user.id, user.username)
context.user_data['current_game'] = game_id
await update.message.reply_text(
"🎮 Новая игра начата!\n"
"Используйте кнопку «Открыть счётчик» для записи бросков."
)
async def handle_webapp_data(update, context):
try:
data = json.loads(update.effective_message.web_app_data.data)
if data['type'] == 'game_session':
# Получаем активную игру пользователя
game = db.get_active_game(update.effective_user.id)
if game:
# Записываем все броски
for throw in data['throws']:
db.add_throw(
game['id'],
throw['dice'][0],
throw['dice'][1]
)
# Завершаем игру
db.end_game(game['id'])
# Отправляем сообщение об успешном завершении
await update.message.reply_text(
f"Игра завершена! Записано {len(data['throws'])} бросков.\n"
f"Используйте /statistics для просмотра статистики."
)
else:
await update.message.reply_text(
"Ошибка: активная игра не найдена.\n"
"Используйте /new_game для начала новой игры."
)
except Exception as e:
print(f"Error handling webapp data: {e}")
await update.message.reply_text("Произошла ошибка при обработке данных.")
async def statistics_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
user_id = update.effective_user.id
stats = db.get_statistics(user_id)
# Получаем активную игру
active_game = db.get_active_game(user_id)
response = "📊 Ваша статистика:\n\n"
if stats['total_throws']:
response += (
f"Всего игр: {stats['total_games']}\n"
f"Всего бросков: {stats['total_throws']}\n"
f"Средняя сумма: {stats['avg_sum']:.2f}\n"
)
if active_game:
game_throws = db.get_game_throws(active_game['id'])
response += f"\nТекущая игра:\n"
response += f"Количество бросков: {len(game_throws)}\n"
if game_throws:
last_throw = game_throws[0]
response += f"Последний бросок: {last_throw['dice1']}-{last_throw['dice2']}"
else:
response += "У вас пока нет записанных бросков."
await update.message.reply_text(response)
async def end_game_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
game_id = context.user_data.get('current_game')
if not game_id:
await update.message.reply_text("У вас нет активной игры!")
return
game_throws = db.get_game_throws(game_id)
db.end_game(game_id)
del context.user_data['current_game']
response = "🏁 Игра завершена!\n\n"
if game_throws:
total_throws = len(game_throws)
avg_sum = sum(t['dice1'] + t['dice2'] for t in game_throws) / total_throws
response += (
f"Статистика игры:\n"
f"Всего бросков: {total_throws}\n"
f"Средняя сумма: {avg_sum:.2f}"
)
else:
response += "В игре не было записано ни одного броска."
await update.message.reply_text(response)

View File

@ -1,10 +1,10 @@
from aiogram import Bot, Dispatcher, types, F
from aiogram.filters import Command
from aiogram.types import WebAppInfo, KeyboardButton, ReplyKeyboardMarkup
from database import Database
from bot.database import Database
import json
import asyncio
from config import BOT_TOKEN, WEBAPP_URL
from bot.config import BOT_TOKEN, WEBAPP_URL
import logging
# Настройка логирования

View File

@ -1,6 +1,2 @@
python-telegram-bot==20.7
pymongo==4.6.1
python-dotenv==1.0.0
fastapi==0.109.0
uvicorn==0.27.0
aiogram==3.0.0
aiogram==3.4.1