Browse Source

stats / last

master
nemesis 2 years ago
parent
commit
7b40d6dd65
  1. 185
      asmodee.py

185
asmodee.py

@ -34,6 +34,7 @@ salons = {} # liste de salons recommandés
welcome = {} # Messages d'accueil des salons
clock = {} # horloges pbta
paquets = {} # paquets de cartes des salons
stats = {} # Statistiques sur les messages
cartes_base = ["As de carreau", "2 de carreau", "3 de carreau", "4 de carreau", "5 de carreau", "6 de carreau", \
"7 de carreau", "8 de carreau", "9 de carreau", "10 de carreau", "Valet de carreau", "Dame de carreau", \
@ -147,6 +148,15 @@ def paquets_read():
paquets = loader.load()
except:
paquets = {}
def stats_read():
global stats
try:
with open("stats", "rb") as fichier:
loader = pickle.Unpickler(fichier)
stats = loader.load()
except:
stats = {}
def save_obj(room=None, message=None):
with open("moderateurs", "wb") as fichier:
@ -185,10 +195,23 @@ def save_obj(room=None, message=None):
with open("paquets", "wb") as fichier:
saver = pickle.Pickler(fichier)
saver.dump(paquets)
if ('stats' in liste_mod):
with open("stats", "wb") as fichier:
saver = pickle.Pickler(fichier)
saver.dump(stats)
def signal_handler(signal, frame): # Sauvegarder les données persistantes avant sortie
save_obj(None,None)
sys.exit(0)
class Userstats: #Pour garder des stats sur les users
def __init__(self,room,user,nick):
self.room = room
self.user = user
self.nick = nick.strip()
self.date = 0
self.mess = 0
self.char = 0
class Parser: #Pour parser la ligne de commande
def __init__(self, str, nick, room):
@ -872,18 +895,19 @@ async def verifPMRoom(room, message): # Pour obtenir ou créer un salon pour les
nick = getNick(room, message)
client_id = bot.creds.username.split(':')[0].split('@')[1]
client_host = bot.creds.username.split(':')[1]
room_nick = client_id + "_" + nick + "_b"
room_nick = client_id + "_" + nick
bot_nick = getNick(room, message)
salon = None
room_id = prive.get(sender)
if (room_id):
await bot.async_client.room_invite(room_id=room_id, user_id=sender)
new_salon = nio.rooms.MatrixRoom(room_id, client_id)
new_salon.name="Asmodee"
new_salon.name=bot_nick
new_salon.topic="Informations d'Asmodee"
new_salon.is_direct=True
return(new_salon)
else:
salon = await bot.async_client.room_create(alias=room_nick, name="Asmodee", topic="Informations d'Asmodee",is_direct=True,invite=[sender])
salon = await bot.async_client.room_create(alias=room_nick, name=bot_nick, topic="Informations d'Asmodee",is_direct=True,invite=[sender])
if isinstance(salon, nio.responses.RoomCreateError):
print("Impossible de creer : " + room_nick + " pour " + sender)
return(room)
@ -1364,6 +1388,149 @@ async def carte(room, message): # Tirer une carte du paquet en la retirant ensui
await msg(room,cartes[i],sender)
cartes.pop(i)
paquets[room.room_id]=cartes
#async def last(room, message): # dernière connexion d'un utilisateur
# global modules
# try:
# rmod = modules[room.room_id, 'stats']
# except:
# modules[room.room_id, 'stats'] = False
# if (modules[room.room_id, 'stats']):
# args = getMessage(message).split()
# sender = getUser(message)
# args.pop(0)
# print("analyse args " + str(args))
# if (len(args) == 1):
# try:
# print("into try")
# target = room.users.get(args[0])
# print("get target")
# if (target):
# ago = target.last_active_ago
# await msg(room,"d" + str(ago),sender)
# else:
# await msg(room,args[0] + " non trouvé.",sender)
# except:
# print(args[0])
# else:
# await msg(room,"!last <mxid>",sender)
async def last(room,message): # Regarde la dernière fois que quelqu'un a écrit un message
global modules
try:
rmod = modules[room.room_id, 'stats']
except:
modules[room.room_id, 'stats'] = False
if (modules[room.room_id, 'stats']):
global stats
args = getMessage(message).split()
sender = getUser(message)
usrstats = None
args.pop(0)
pers = ""
if (len(args) >= 1 and args[0] == "all"):
max_sign = "+"
max_duree = 0
if (len(args) > 1):
max_sign = args[1][0]
max_duree = int(args[1][1:])
ref_duree = datetime.now() - timedelta(days=max_duree)
salon = await verifPMRoom(room,message)
all_usr = {}
reponse = "Les gens ayant posté à " + max_sign + " de " + str(max_duree) + " jours :\n"
for cle,valeur in stats.items():
if (cle[0] == room.room_id):
usrstats = stats[room.room_id,cle[1]]
if ((usrstats.user in all_usr and all_usr[usrstats.user].date < usrstats.date) or not usrstats.user in all_usr):
all_usr[usrstats.user] = usrstats
for user,usrstats in all_usr.items():
if ((max_sign == "+" and usrstats.date < ref_duree) or ((max_sign == "-" and usrstats.date > ref_duree))):
reponse += "- " + usrstats.nick + "(" + user + ")" + " le " + usrstats.date.strftime("%Y-%m-%d %H:%M:%S") + ")\n"
await msg(salon, reponse,sender)
elif (len(args) >= 1 and args[0] == "inactifs"):
max_sign = "+"
max_duree = 0
max_mess = 0
if (len(args) > 2):
max_sign = args[1][0]
max_duree = int(args[1][1:])
max_mess = int(args[2])
ref_duree = datetime.now() - timedelta(days=max_duree)
salon = await verifPMRoom(room,message)
all_usr = {}
reponse = "Les gens ayant posté à " + max_sign + " de " + str(max_duree) + " jours et n'ayant pas plus de " + str(max_mess) + " messages :\n"
for cle,valeur in stats.items():
if (cle[0] == room.room_id):
usrstats = stats[room.room_id,cle[1]]
if ((usrstats.user in all_usr and all_usr[usrstats.user].date < usrstats.date) or not usrstats.user in all_usr):
all_usr[usrstats.user] = usrstats
for user,usrstats in all_usr.items():
if (((max_sign == "+" and usrstats.date < ref_duree) or ((max_sign == "-" and usrstats.date > ref_duree))) and usrstats.mess <= max_mess):
reponse += "- " + usrstats.nick + "(" + user + ")" + " le " + usrstats.date.strftime("%Y-%m-%d %H:%M:%S") + ")\n"
await msg(salon, reponse, sender)
else:
if (len(args) == 0):
await msg(room,"!last <mxid>",sender)
else:
pers=" ".join(args)
try:
print(pers)
usrstats = stats[room.room_id,pers]
print(usrstats.nick)
except:
try:
for cle,valeur in room.users.items():
if (valeur.display_name == pers):
usrstats = stats[room.room_id, cle]
break
except:
print(pers + " non reconnu")
if (usrstats is not None):
target = room.users.get(usrstats.user)
if (target and target.last_active_ago is not None):
ago = datetime.fromtimestamp(datetime.now().timestamp() - target.last_active_ago/1000)
await msg(room,"J'ai vu " + usrstats.nick + " pour la dernière fois le : " + ago.strftime("%Y-%m-%d %H:%M:%S") + ". Et il a posté pour la dernière fois le : " + usrstats.date.strftime("%Y-%m-%d %H:%M:%S"),sender)
else:
await msg(room,"J'ai vu " + usrstats.nick + " poster pour la dernière fois le " + usrstats.date.strftime("%Y-%m-%d %H:%M:%S"),sender)
else:
target = room.users.get(pers)
if (target and target.last_active_ago is not None):
ago = datetime.fromtimestamp(datetime.now().timestamp() - target.last_active_ago/1000)
await msg(room,"Dernière présence de " + pers + " : " + ago.strftime("%Y-%m-%d %H:%M:%S"),sender)
else:
await msg(room,pers + " : Personne non reconnue",sender)
def statistiques(room,message): # Enregistrement des statistiques
global modules
try:
rmod = modules[room.room_id, 'stats']
except:
modules[room.room_id, 'stats'] = False
if (modules[room.room_id, 'stats']):
global stats
nick = getNick(room, message)
user = getUser(message)
mess = getMessage(message)
usrstats = None
try:
usrstats = stats[room.room_id,user]
except:
usrstats = Userstats(room.room_id,user,nick)
# date de la phrase
date = datetime.now()
usrstats.date = date
# recup nb phrases +1, 1 sinon
usrstats.mess = usrstats.mess + 1
# recup nb lettres +lettres phrase, lettres phrases sinon
usrstats.char = usrstats.char + len(mess)
# insertion des objets
stats[room.room_id,user] = usrstats
async def help(room, message): # Aide en message privé
await help_center(room,message,"help",True)
@ -1459,6 +1626,18 @@ async def help_center(room,message,name,private): # Aide sur les commandes dispo
message += "\n- !modo : Gère les modérateurs du salon\n- !module : Gère les modules actifs sur le salon\n\n- Pour plus de details, tapez !" + name + " <commande>\n\nRetrouvez Asmodee sur https://git.ombreport.info/nemesis/asmodee_matrix"
await msg(salon,message,sender, False)
@bot.listener.on_message_event
async def callLast(room, message):
match = botlib.MessageMatch(room, message, bot, PREFIX)
if match.is_not_from_this_bot() and match.prefix() and match.command("last"):
await last(room, message)
@bot.listener.on_message_event
async def callStats(room, message):
match = botlib.MessageMatch(room, message, bot)
if match.is_not_from_this_bot():
statistiques(room, message)
@bot.listener.on_message_event
async def callSave(room, message):
match = botlib.MessageMatch(room, message, bot, PREFIX)

Loading…
Cancel
Save