Почему такая сортировка?
Сортирую по полю last_battle_time
(timestamp - Время последнего боя).
Простой код метода:
async def send_session_embed(self, ctx, session):
try:
start_time = session["start_time"].strftime('%d.%m.%Y %H:%M:%S')
account_id = session["account_id"]
nickname = session["nickname"]
main_embed = disnake.Embed(
title=f"От: {start_time}\nСессия для: `{nickname} | {account_id}`",
)
max_tanks_to_show = 10
if "tanks_stats" in session:
stats = session["tanks_stats"]
player_data = self.api.get_player_technique_stats(session["account_id"])
total_battles = 0
total_wins = 0
total_damage = 0
tank_info_list = []
for tank_id, saved_stats in stats.items():
tank_data = next((tank_info["all"] for tank_info in player_data if str(tank_info["tank_id"]) == tank_id), None)
if tank_data:
current_battles = tank_data.get('battles', 0)
current_wins = tank_data.get('wins', 0)
current_damage_dealt = tank_data.get('damage_dealt', 0)
last_battle_time = datetime.fromtimestamp(tank_data.get('last_battle_time', 0), tz=timezone.utc)
saved_battles = saved_stats["battles"]
saved_wins = saved_stats["wins"]
saved_damage_dealt = saved_stats["damage_dealt"]
saved_last_battle_time = datetime.fromtimestamp(
saved_stats.get("last_battle_time", 0), tz=timezone.utc)
if (current_battles > saved_battles or
current_wins > saved_wins or
current_damage_dealt > saved_damage_dealt or
last_battle_time > saved_last_battle_time):
delta_battles = current_battles - saved_battles
delta_wins = current_wins - saved_wins
delta_damage = current_damage_dealt - saved_damage_dealt
win_rate = (delta_wins / delta_battles) * 100 if delta_battles != 0 else 0
avg_damage = round(delta_damage / delta_battles) if delta_battles > 0 else 0
total_battles += delta_battles
total_wins += delta_wins
total_damage += delta_damage
try:
tank_info = await self.get_tank_info_embed(tank_id)
tank_name = tank_info['name']
print(f"Информация о танке {tank_id} из get_tank_info_embed: {tank_info}")
except Exception as e:
tank_name = "Неизвестный танк"
print(f"Ошибка при получении информации о танке {tank_id}: {e}")
tank_info_list.append({
"name": tank_name,
"win_rate": win_rate,
"avg_damage": avg_damage,
"battles": delta_battles,
"last_battle_time": last_battle_time
})
win_rate = (total_wins / total_battles) * 100 if total_battles != 0 else 0
avg_damage = total_damage // total_battles if total_battles > 0 else 0
main_embed.add_field(
name="",
value=f"```css\nБоев: {total_battles}\nПП: {win_rate:.2f}%\nСр. урон: {avg_damage}```",
inline=False
)
if tank_info_list:
sorted_tank_info_list = sorted(
tank_info_list, key=lambda x: x["last_battle_time"], reverse=True)
for tank_info in sorted_tank_info_list[:max_tanks_to_show]:
tank_name = tank_info["name"]
win_rate = tank_info["win_rate"]
avg_damage = tank_info["avg_damage"]
battles = tank_info["battles"]
tank_info_str = f"**{tank_name}**\n```css\nПП: {win_rate:.2f}% Урон: {avg_damage} Бои: {battles}```"
main_embed.add_field(
name="", value=tank_info_str, inline=False)
total_tanks = len(tank_info_list)
if total_tanks > max_tanks_to_show:
main_embed.set_footer(text=f"Показано {max_tanks_to_show} из {total_tanks} танков")
await ctx.send(embed=main_embed)
else:
await ctx.send(embed=disnake.Embed(description="Сыграйте хотя бы один бой, чтобы посмотреть сессию!"))
except Exception as e:
await ctx.send(f"Произошла ошибка при отправке сессии: {e}")
Выводит информацию в ембед так:
Но как правильно: