gsd 2 years ago
parent
commit
19d18b72e1
  1. 9
      bot.py
  2. 9
      other_ext/stats_presence.py
  3. 73
      player.py
  4. 2
      user_ext/profile.py

9
bot.py

@ -6,6 +6,7 @@ import aiohttp
from datetime import datetime
from discord.ext import tasks
from player import *
import traceback
#Скрыть сообщение если надо ephemeral=True
@ -29,6 +30,8 @@ class DiscordClient(discord.Client):
super().__init__(intents=discord.Intents.default())
self.tree = app_commands.CommandTree(self)
self.load_extensions(['user_ext', 'admin_ext', 'other_ext'])
###################################################
self.setup_events()
def load_extensions(self, extensions_path):
if type(extensions_path) == str:
@ -56,6 +59,12 @@ class DiscordClient(discord.Client):
async def on_ready():
print(f'Logged in as {self.user} (ID: {self.user.id})')
@self.tree.error
async def on_app_command_error(interaction, error):
if isinstance(error.original, CannotCastToSteamID):
return await interaction.response.send_message(f'Не возможно найти такой профиль, попробуй написать иные данные!', ephemeral=True)
traceback.print_exc()
async def GetSteam64OfDiscord(self, user, no_cache = False):
if user.id in self.discord2steam_cache and not no_cache:
return self.discord2steam_cache[user.id]

9
other_ext/stats_presence.py

@ -1,18 +1,19 @@
from discord.ext import tasks
import discord
class Extension:
show_stats_prev = 0
def __init__(self, core):
show_stats_prev = 0
@tasks.loop(seconds=3)
async def show_stats(core):
if not core.stats['servers'].items():
print("Stats not be loaded")
return
try:
server = core.stats['servers'].items()[core.show_stats_prev]
server = core.stats['servers'].items()[self.show_stats_prev]
self.show_stats_prev += 1
except:
show_stats_prev = 0
server = core.stats['servers'].items()[core.show_stats_prev]
self.show_stats_prev = 0
server = core.stats['servers'].items()[self.show_stats_prev]
addr = server['address'].split(":")
act = discord.Streaming(name = f"{server['name']} - {server['player_count']}", url=f"https://{addr[0]}/connect/{addr[1]}")

73
player.py

@ -1,9 +1,14 @@
from email import message
import aiohttp, os
from datetime import datetime
from discord import Embed
class CannotCastToSteamID(Exception):
pass
class NotLoadProfile(Exception):
pass
class Player:
original_request = ""
requester_steam64 = ""
@ -24,9 +29,70 @@ class Player:
async def LoadProfile(self):
self.current = await self.GetProfile(self.steamid.get("steam64"))
@property
def embed(self) -> Embed:
if not self.current:
raise NotLoadProfile
# build header
prepare_description = ""
if self.current.get("play_on", {}):
prepare_description = f"Сейчас играет на {self.stats['servers'][self.current['play_on']['server_id']]['name']}\n"
elif self.current.get("lastplay", {}):
selected_srv = "srv1"
selected_timestamp = 0
for srv, maps in self.current["lastplay"].items():
for last_play in maps.values():
if last_play > selected_timestamp:
selected_srv = srv
selected_timestamp = last_play
prepare_description = f"Последняя игра на {self.stats['servers'][selected_srv]['name']}\nв {utime2human(selected_timestamp)}"
else:
prepare_description = "Не играл на фактах13"
embed = Embed(
title=self.current["steam_data"]["nickname"],
description=prepare_description,
url=self.current["steamids"]["community_url"])
# set image
embed.set_thumbnail(url = self.current["steam_data"]["avatar"])
# Последняя игра на сервере
if self.current.get("lastplay", {}):
message = ""
for maps in self.current["lastplay"].values():
for map_name, last_play in maps.items():
message += f"{workshopmap2bsp(map_name)} - {utime2human(last_play)}\n"
embed.add_field(name="Последняя игра на серверах", value=message, inline=False)
# Игрокое время
if self.current.get("gametime", {}):
message = ""
for maps in self.current["gametime"].values():
for map_name, play_time in maps.items():
message += f"{workshopmap2bsp(map_name)} - {human_TIME(play_time)}\n"
embed.add_field(name="Статистика по картам", value=message, inline=False)
# Права
if self.current.get("permition", {}):
message = f"{self.current['permition']['status']} назначен {utime2human(self.current['permition']['u_timestamp']) if self.current['permition']['u_timestamp'] != 0 else 'с момента создания'}\n"
if self.current['permition'].get('amount', 0) and self.current['permition'].get("u_timestamp", 0):
message += f"окончание после {utime2human(self.current['permition']['u_timestamp'] + self.current['permition']['amount'])}\n"
embed.add_field(name="Права на серверах", value=message, inline=False)
# Бан
if self.current.get("ban", {}):
message = f"Ник: {self.current['ban']['player_name']}\n"
message += f"Причина: {self.current['ban']['ban_reason']}\n"
message += f"Время: {utime2human(self.current['ban']['ban_utime'])}\n"
message += f"Кто забанил: {self.current['ban']['banned_by']} | <@{self.current['ban']['admin_info']['discord_id']}>\n"
if self.current['ban']['active'] == True:
if self.current['ban']['ban_length'] == 0:
message += "Данный бан навсегда!\n"
else:
message += f"Дата разбана: {utime2human(self.current['ban']['ban_utime'] + self.current['ban']['ban_length_seconds'])}\n"
embed.add_field(name="Имеется бан на сервере", value=message, inline=False)
return embed
def __str__(self):
if not self.current:
return "profile not load from backend, use GetProfile"
raise NotLoadProfile
message = self.current["steamids"]["community_url"] + "\n"
if "play_on" in self.current and self.current["play_on"]:
@ -74,7 +140,10 @@ class Player:
async def GetSteamIDOfProfile(self, any:str):
async with aiohttp.ClientSession(cookies={"secretkey":os.getenv("BACKEND_SECRETKEY")}) as session:
async with session.get(f"{os.getenv('BACKEND_URL')}/api/profile/steam?any={any}", ssl=False) as response:
response = await response.json()
try:
response = await response.json()
except:
response = None
if response == None:
raise CannotCastToSteamID
return response

2
user_ext/profile.py

@ -10,4 +10,4 @@ class Extension:
):
steam64 = await core.GetSteam64OfDiscord(interaction.user)
player = await core.GetPlayer(profile, steam64) if profile else await core.GetPlayer(steam64, steam64)
return await interaction.response.send_message(f'{player}', ephemeral=False)
return await interaction.response.send_message(embed=player.embed, ephemeral=False)
Loading…
Cancel
Save