function checkAndUpdateRoundStatus() {
let allCirclesApproved = true;
users.forEach((user) => {
user.circles.forEach((circle) => {
if (
circle.status === "active" &&
circle.playerGame.approveState !== 4 &&
circle.playerGame.name !== "Empty"
) {
allCirclesApproved = false;
}
});
});
if (allCirclesApproved) {
users.forEach((user, userIndex) => {
const activeCircleIndex = user.circles.findIndex(
(c) => c.status === "active"
);
if (activeCircleIndex !== -1) {
let newRoundPoints = 0;
const playerFish =
user.circles[activeCircleIndex].playerGame.fishCount;
const opponentFish =
user.circles[activeCircleIndex].opponentGame.fishCount;
if (playerFish === 0 && opponentFish === 0) {
newRoundPoints = 1;
} else if (playerFish === opponentFish && playerFish > 0) {
newRoundPoints = 2;
} else if (playerFish > opponentFish) {
newRoundPoints = 4;
} else if (playerFish < opponentFish && playerFish > 0) {
newRoundPoints = 1;
} else if (playerFish < opponentFish && playerFish === 0) {
newRoundPoints = 0;
}
users[userIndex].total_user_points =
users[userIndex].total_user_points + newRoundPoints;
users[userIndex].total_user_fish =
users[userIndex].total_user_fish + playerFish;
users[userIndex].circles[activeCircleIndex].playerGame.points =
newRoundPoints;
users[userIndex].circles[
activeCircleIndex
].playerGame.total_points = users[userIndex].total_user_points;
users.forEach((userOpponent, userIndexOpponent) => {
userOpponent.circles.forEach(
(circleOpponent, circleIndexOpponent) => {
if (
circleOpponent.opponentGame.number ===
user.player_id
) {
if (circleOpponent.status === "active") {
users[userIndexOpponent].circles[
circleIndexOpponent
].opponentGame.points =
users[userIndex].circles[
activeCircleIndex
].playerGame.points;
}
users[userIndexOpponent].circles[
circleIndexOpponent
].opponentGame.total_points =
users[userIndex].circles[
activeCircleIndex
].playerGame.total_points;
} else if (
circleOpponent.playerGame.number ===
user.player_id
) {
users[userIndexOpponent].circles[
circleIndexOpponent
].playerGame.total_points =
users[userIndex].circles[
activeCircleIndex
].playerGame.total_points;
}
}
);
});
}
});
/*
Выше я для каждого пользователя сначала обновил его очки и рыбы глобально, затем всем его оппонентам в кругах обновил его данные об общих очках
И если мы встретили текущего оппонента, ему обновляем наши points текущие для этого раунда
Таким образом мы каждому игроку обновили его глобальные данные, данные в его кругах, данные о нем в кругах всех его оппонентов
И после прохода по всем игрокам будет обновлена информация у всех про всех
Ниже происходит обновление статуса кругов и emit в socket.
*/
users.forEach((user, userIndex) => {
const activeCircles = user.circles.filter(
(c) => c.status === "active"
);
server.listen(PORT, () => {
console.log(Server is running on http://localhost:${PORT});
});
Это мой сервер
import asyncio
import requests
import pandas as pd
from aiogram import F
from aiogram import Bot, Dispatcher, types
from aiogram.filters import Command
from aiogram.types import InlineKeyboardButton, InlineKeyboardMarkup
from aiogram.utils.keyboard import InlineKeyboardBuilder
from aiogram.types import FSInputFile
from datetime import datetime
import numpy as np
import random
import string
import aiohttp
import os
import json
from dotenv import load_dotenv
from aiohttp import FormData
load_dotenv()
server = os.getenv("WEB_APP_URL")
bot_token = os.getenv("BOT_TOKEN")
web_url = os.getenv("WEB_URL")
def load_config():
with open("config.json", "r") as file:
return json.load(file)
def save_config(config):
with open("config.json", "w") as file:
json.dump(config, file, indent=4)
async def update_stats():
previous_stats = None
while True:
await asyncio.sleep(90)
try:
async with aiohttp.ClientSession() as session:
async with session.get(server + "/api/stats") as response:
if response.status == 200:
result_array = await response.json()
if result_array != previous_stats and any(result_array):
previous_stats = result_array
columns = ["№ участника", "Участник", "Баллы", "Рыбы"] + [
f"Баллы" for _ in range(len(result_array[0]) - 4)
]
df = pd.DataFrame(result_array, columns=columns)
df.loc[-1] = columns
df.index = df.index + 1
df = df.sort_index()
# Сохранение в Excel файл
file_path = "./statistics.xlsx"
df.to_excel(file_path, index=False, header=False)
document = FSInputFile("./statistics.xlsx")
for admin_id in admin_ids:
await bot.send_document(
chat_id=admin_id, document=document
)
os.remove(file_path)
except aiohttp.ClientError as e:
print(f"Ошибка: {e}")
await asyncio.sleep(1)
except Exception as e:
print(f"Ошибка: {e}")
await asyncio.sleep(1)
async def check_registered_users():
previous_user_count = len(user_props)
while True:
await asyncio.sleep(60)
current_user_count = len(user_props)
if current_user_count != previous_user_count and current_user_count > 0:
previous_user_count = current_user_count
# Создать эксель-файл
df = pd.DataFrame()
df["User"] = [user_props[i]["name"] for i in range(len(user_props))]
df["Code"] = [user_props[i]["code"] for i in range(len(user_props))]
df["Index"] = [i + 1 for i in range(len(user_props))]
df["Time"] = [user_props[i]["timestamp"] for i in range(len(user_props))]
file_path = "./registration.xlsx"
df.to_excel(file_path, index=False, header=False)
document = FSInputFile(file_path)
for admin_id in admin_ids:
await bot.send_document(chat_id=admin_id, document=document)
# Удалить файл
os.remove(file_path)
@dp.message(lambda message: message.photo)
async def handle_photo(message: types.Message):
user_id = message.from_user.id
if user_state.get(user_id) == "awaiting_background_image":
photo = message.photo[-1]
file_id = photo.file_id
file_path = await bot.get_file(file_id)
file_url = f"https://api.telegram.org/file/bot{TOKEN}/{file_path.file_path}"
async with aiohttp.ClientSession() as session:
async with session.get(file_url) as response:
file_data = await response.read()
async with aiohttp.ClientSession() as session:
form_data = FormData()
form_data.add_field("photo", file_data, filename="photo.png")
async with session.post(
server + "/api/upload_photo",
data=form_data,
) as response:
if response.status == 200:
print("Фото отправлено на сервер")
await message.answer("Фото отправлено на сервер!")
chat_id = message.chat.id
message_id = messages_to_delete[chat_id][0]
await bot.delete_message(chat_id=chat_id, message_id=message_id)
user_state[user_id] = None
@dp.message(lambda message: message.text and message.from_user.id not in admin_ids)
async def handle_user_info(message: types.Message):
global registration_open
if registration_open:
async with user_props_lock:
# Проверка, существует ли уже пользователь с таким именем
if not any(user["name"] == message.text for user in user_props):
user_info = {
"id": message.from_user.id,
"code": (
str(len(user_props) + 1)
+ "".join(
random.choices(string.ascii_letters + string.digits, k=3)
)
),
"name": message.text,
"timestamp": str(datetime.now().strftime("%Y-%m-%d %H:%M:%S")),
}
user_props.append(user_info)
update_user_props(user_props)
await message.answer("Спасибо, ваши данные сохранены. Ниже ваш код")
await message.answer(f"{user_info['code']}")
else:
await message.answer("Пользователь с таким именем уже зарегистрирован.")
else:
await message.answer("Регистрация в данный момент закрыта.")
@dp.callback_query(F.data == "get_unready_players")
async def get_unready_players(callback_query: types.CallbackQuery):
response = requests.get(server + "/api/unready_players")
if response.status_code == 200:
unready_players = response.json()
result_string = "\n".join([str(player) for player in unready_players])
if len(unready_players) == 0 and result_string != "message":
await callback_query.message.answer("Все игроки готовы")
elif result_string != "message":
await callback_query.message.answer(f"Неготовые игроки:\n{result_string}")
else:
await callback_query.message.answer(f"Проверьте, начался ли турнир")
else:
await callback_query.message.answer(
f"Не удалось получить данные с сервера.\n Проверьте, идет ли турнир"
)
await callback_query.answer()
Это мой бот
В бота я хочу в админ панель добавить пару кнопок - первая кнопка "обновить счет игрока", при нажатии на эту кнопку бот должен присылать пользователю сообщение "присылайте 3 числа через пробел, где первое число - номер этапа, второе - номер игрока, третье - новый счет" с кнопкой назад и должно быть новое состояние у пользователя - ожидание отправки сообщения об изменении счета. Если пользователь нажал кнопку назад после этого - сообщение просто удаляется и ничего не происходит, если же пользователь прислал сообщение и оно содержит 3 числа, то нужно отправлять эти 3 числа на сервер, на сервере нужно принять эти 3 числа, найти в users user с номером, соответствующим номеру игрока из бота, у него найти все круги circle в user.circles[], у которых .index_circle равен отправленному из бота номеру этапа, таких кругов может быть не более 2, у одного .second_circle true, у другого круга false, мне нужно сначала запомнить в обоих кругах или в одном points (записать в 2 или 3 переменные circle.playerGame.points из одного из 2 кругов и в 2 остальные переменные записать 2 значения circle.opponentGame.points для 2 кругов), далее нужно для моего user в обоих или в одном circle обновить circle.playergame.fishcount на значение "новый счет" из бота, затем для одного или двух кругов перерасчитать .playerGame.points и opponentGame.points, рассчитываются очки по правилу: если circle.playerGame.fishcount === circle.playerGame.fishcount === 0, то у обоих .points = 1, если их fishcount равны и больше 0, то у обоих points = 2, если же один fishcount больше другого, то points = 4 у того, у кого fishcount больше, а у кого fishcount меньше есть всего одно условие: если fishcount меньше и не равен 0, то points = 1, иначе 0, после того как мы рассчитали новые points для одного или двух кругов нужно найти одного или двух user в users, у которых user.circles[i].opponentGame.number === номеру игрока из бота и обновить им opponentGame.fishcount на присланное значение из бота и аналогично перерасчитать points
В процессе нужно обновить .playerGame.total_points и .opponentGame.total_points путем вычитания предыдущих значений points и прибавления нового, но это при условии, что круг у нашего оппонента, в котором изменяемый нами игрок является оппонентом, не имеет .second_circle === true, в таком случае нам нужно .total_points поменять только у нашего user.circles]
И вот после всего этого нам нужно наши новые рассчитанные total_points записать 2-3 нашим игрокам - измененному
To accomplish your request, we need to make changes both in the bot code and the server code.
Here's how you can implement the "Update Player Score" feature:
Bot Code Modifications
1. Add a New Button in the Admin Panel
In your bot code, find the cmd_start function where you build the admin panel. Add a new button for updating the player's score.
Modified cmd_start Function:
@dp.message(Command("start"))
async def cmd_start(message: types.Message):
if message.from_user.id in admin_ids:
builder = InlineKeyboardBuilder()
builder.row(
InlineKeyboardButton(text="Прислать жеребьевку", callback_data="send_draw")
)
builder.row(InlineKeyboardButton(text="Узнать ID", callback_data="get_id"))
builder.row(
InlineKeyboardButton(text="Добавить админа", callback_data="add_admin")
)
builder.row(
InlineKeyboardButton(
text="Начать регистрацию", callback_data="start_registration"
)
)
builder.row(
InlineKeyboardButton(
text="Закрыть регистрацию", callback_data="close_registration"
)
)
builder.row(
InlineKeyboardButton(
text="Получить ссылку для зрителей", callback_data="get_email"
)
)
builder.row(
InlineKeyboardButton(
text="Неготовые игроки", callback_data="get_unready_players"
)
)
builder.row(
InlineKeyboardButton(
text="Очистить регистрацию", callback_data="clear_registration"
)
)
builder.row(
InlineKeyboardButton(text="Новый фон сайта", callback_data="new_background")
)
# Add the new button here
builder.row(
InlineKeyboardButton(
text="Обновить счет игрока", callback_data="update_player_score"
)
)
await message.answer("Панель управления", reply_markup=builder.as_markup())
else:
await message.answer("Пожалуйста, отправьте свою Фамилию и имя.")
2. Handle the Callback for "Update Player Score"
Add a new callback query handler to process the update_player_score callback data.
Add the Following Handler:
@dp.callback_query(F.data == "update_player_score")
async def update_player_score(callback_query: types.CallbackQuery):
user_id = callback_query.from_user.id
user_state[user_id] = "awaiting_score_update"
request_message = await callback_query.message.answer(
"Пожалуйста, присылайте 3 числа через пробел, где первое число - номер этапа, второе - номер игрока, третье - новый счет.",
reply_markup=InlineKeyboardMarkup(
inline_keyboard=[[InlineKeyboardButton(text="Назад", callback_data="back")]]
),
)
messages_to_delete[callback_query.message.chat.id] = [request_message.message_id]
await callback_query.answer()
3. Handle the State When the User Sends the Three Numbers
Add a message handler to process the three numbers sent by the admin.
Add the Following Handler:
@dp.message(lambda message: user_state.get(message.from_user.id) == "awaiting_score_update")
async def handle_score_update(message: types.Message):
user_id = message.from_user.id
if user_state.get(user_id) == "awaiting_score_update":
try:
numbers = list(map(int, message.text.strip().split()))
if len(numbers) != 3:
await message.answer("Пожалуйста, отправьте ровно 3 числа через пробел.")
return
stage_number, player_number, new_score = numbers
# Send these numbers to the server
data = {
"stage_number": stage_number,
"player_number": player_number,
"new_score": new_score
}
async with aiohttp.ClientSession() as session:
async with session.post(server + "/api/update_player_score", json=data) as response:
if response.status == 200:
# Optionally fetch updated stats and send the new table
async with session.get(server + "/api/stats") as stats_response:
if stats_response.status == 200:
result_array = await stats_response.json()
columns = ["№ участника", "Участник", "Баллы", "Рыбы"] + [
f"Баллы" for _ in range(len(result_array[0]) - 4)
]
df = pd.DataFrame(result_array, columns=columns)
df.loc[-1] = columns
df.index = df.index + 1
df = df.sort_index()
# Save to Excel file
file_path = "./updated_statistics.xlsx"
df.to_excel(file_path, index=False, header=False)
document = FSInputFile(file_path)
await message.answer("Счет игрока обновлен. Новая таблица позиций:")
await message.answer_document(document=document)
os.remove(file_path)
else:
await message.answer("Счет игрока обновлен, но не удалось получить новую таблицу.")
else:
await message.answer("Ошибка при обновлении счета игрока.")
except ValueError:
await message.answer("Пожалуйста, отправьте 3 числа через пробел.")
finally:
user_state[user_id] = None
4. Ensure the "Назад" Button Works Properly
You already have a handler for the "Назад" button, so no changes are needed here.
Server Code Modifications
1. Add a New Endpoint to Handle the Score Update
In your server code, add a new route to handle the POST request from the bot.
Your server code already has a mechanism to emit updates to connected clients using Socket.IO. The io.emit("allUsersUpdated", users); line ensures that all clients receive the updated user data.
Additional Notes
Error Handling: Ensure that your code properly handles cases where users or stages are not found.
Data Consistency: Be cautious with concurrent modifications to the users array. If your application is concurrent, consider adding locks or using a database.
Testing: Thoroughly test the new feature to ensure it works correctly in all scenarios.
Optimization: If the users' data becomes large, consider optimizing the way you handle and emit data to clients.
By following these steps, you'll be able to add the "Update Player Score" feature to your bot and server, fulfilling your requirements.