portail/scripts/generate_chat_info.py

90 lines
2.7 KiB
Python

from rocketchat_API.rocketchat import RocketChat
import os, time
import json
from datetime import datetime
from monthdelta import monthdelta
from common.rocketchathelper import getAllChannels, getAllMessages, Connection
from common.savehelper import save
def main():
print("Start chat info generation")
crapauds_total = 0
crapauds_recent = 0
channels_total = 0
channels_recent = 0
channels_list = []
messages_total = 0
messages_recent = 0
cohortes = []
recent_date = datetime.now() - monthdelta()
rocket = Connection()
print("Check users")
crapauds_total = getNbUsers(rocket)
print("Check channels")
channels = getAllChannels(rocket)
channels_total = len(channels)
users = []
for channel in channels:
if "lm" not in channel:
continue
messages_total += int(channel["msgs"])
date = channel["lm"]
channel_date = datetime.strptime(date, "%Y-%m-%dT%H:%M:%S.%fZ")
if channel["name"].startswith("cohorte-"):
cohortes.append(channel["name"][8:])
if channel_date > recent_date:
channels_recent += 1
messages = getAllMessages(rocket, channel["_id"], begindate= recent_date)
if messages is not None:
nbMessages = len(messages)
print("Check messages for channels {} ({})".format(channel['name'], nbMessages))
messages_recent += nbMessages
if (channel["name"] != "general") and (channel["name"] != "accueil"):
channels_list.append((channel["name"], nbMessages))
users.extend(map(lambda message: message["u"]["_id"], messages))
else:
print("ERROR : couldn't get message")
time.sleep(20)
# Get the channels with the most number of message
channels_list.sort(key=lambda channel: channel[1], reverse= True)
channels_recentlist = list(map(lambda channel: channel[0], channels_list))
crapauds_recent = len(set(users))
info = {
"crapauds": {
"total": crapauds_total,
"recent": crapauds_recent
},
"canaux": {
"total": channels_total,
"recent": channels_recent,
# Get only the 10 first channels
"liste": channels_recentlist[0:10]
},
"messages": {
"total": messages_total,
"recent": messages_recent
},
"cohortes": cohortes
}
save(info, "chat")
print("End chat info generation")
def getNbUsers(rocket):
users = rocket.users_list().json()
return users["total"]
if __name__ == "__main__":
main()