Skip to content

Commit 3f048b7

Browse files
authored
Update active_threads_command.py
1 parent d6647e3 commit 3f048b7

File tree

1 file changed

+188
-2
lines changed

1 file changed

+188
-2
lines changed

active_threads_command.py

Lines changed: 188 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,8 @@
33
from disnake import Guild
44
from disnake.ext import commands, tasks
55
from tools.text_managers import read_yaml
6+
import os
7+
import json
68

79
class ActiveThreadsManager:
810
def __init__(self, bot):
@@ -16,6 +18,8 @@ def __init__(self, bot):
1618
self.instructions = ''
1719
self.messages = ['']
1820
self.refresh_open_threads_list.start()
21+
#self.last_message_file = "last_message_dates.json"
22+
#self.last_message_dates = self.load_last_message_dates()
1923

2024
@staticmethod
2125
def read_settings():
@@ -33,15 +37,70 @@ async def refresh_open_threads_list(self):
3337
self.build_message_list()
3438
await self.update_active_threads_channel()
3539
##############################################################
40+
# def load_last_message_dates(self):
41+
# if os.path.exists(self.last_message_file):
42+
# with open(self.last_message_file, "r") as f:
43+
# try:
44+
# last_message_dates = json.load(f)
45+
# # Convert datetime strings back to datetime objects
46+
# return {thread_id: datetime.fromisoformat(date_string) for thread_id, date_string in last_message_dates.items()}
47+
# except (json.decoder.JSONDecodeError, ValueError):
48+
# # Handle empty or malformed JSON file
49+
# print("Handle empty or malformed JSON file")
50+
#
51+
# return {}
52+
# else:
53+
# return {}
54+
55+
"""
56+
def load_last_message_dates(self):
57+
if os.path.exists(self.last_message_file):
58+
try:
59+
with open(self.last_message_file, "r") as f:
60+
last_message_dates = json.load(f)
61+
# Convert datetime strings back to datetime objects
62+
return {thread_id: datetime.fromisoformat(date_string) for thread_id, date_string in last_message_dates.items()}
63+
except (json.decoder.JSONDecodeError, ValueError) as e:
64+
# Handle empty or malformed JSON file
65+
print(f"Error loading JSON data from file: {e}")
66+
return {}
67+
except (FileNotFoundError, PermissionError) as e:
68+
# Handle file-related errors
69+
print(f"Error accessing or reading file: {e}")
70+
return {}
71+
else:
72+
return {}
73+
"""
74+
75+
"""
76+
def save_last_message_date(self, thread_id, last_message_date):
77+
self.last_message_dates[int(thread_id)] = last_message_date.isoformat() # Convert to ISO 8601 format
78+
with open(self.last_message_file, "w") as f:
79+
json.dump(self.last_message_dates, f, default=str) # Use default=str to serialize datetimes as strings
80+
"""
81+
3682

3783
async def collect_channels_and_threads(self):
3884
await self.get_threads_info()
3985
self.build_channels_and_threads_list()
40-
86+
"""
4187
async def get_threads_info(self):
4288
self.threads = []
4389
threads_raw = await self.guild.active_threads()
90+
4491
for thread in threads_raw:
92+
thread_id = str(thread.id)
93+
94+
last_message_date = self.last_message_dates.get(thread_id)
95+
96+
if not last_message_date:
97+
last_message_date = await self.get_thread_last_message_date(thread)
98+
self.save_last_message_date(thread_id, last_message_date)
99+
else:
100+
messages_last_hour = await self.count_messages_last_hour(thread, last_message_date)
101+
# Add message count to thread dictionary
102+
thread_dict["messages_last_hour"] = messages_last_hour
103+
45104
thread_dict = {
46105
"channel": thread.parent,
47106
#"channel_id": thread.parent_id,
@@ -55,6 +114,126 @@ async def get_threads_info(self):
55114
thread_dict["excluded"] = thread.parent_id == 1218292569209831514 #Excluding threads of channel early-access-sojfest
56115
57116
self.threads.append(thread_dict)
117+
"""
118+
async def get_threads_info(self):
119+
self.threads = []
120+
threads_raw = await self.guild.active_threads()
121+
for thread in threads_raw:
122+
thread_dict = {} # Define thread_dict here
123+
thread_id = str(thread.id) # Convert thread ID to string
124+
125+
"""
126+
if thread_id in self.last_message_dates:
127+
last_message_date = self.last_message_dates[thread_id]
128+
messages_last_hour = await self.count_messages_last_hour(thread, last_message_date)
129+
130+
# Define the thread dictionary
131+
thread_dict = {
132+
"channel": thread.parent,
133+
"mention": thread.mention,
134+
"creation_date": thread.created_at,
135+
"up_date": thread.archive_timestamp,
136+
"archive_date": await self.get_thread_archive_date(thread),
137+
"messages_last_hour": messages_last_hour
138+
}
139+
thread_dict["is_dead"] = thread_dict["archive_date"] < datetime.now(tz=timezone.utc)
140+
thread_dict["excluded"] = thread.parent_id == 1218292569209831514 #Excluding threads of channel early-access-sojfest
141+
142+
self.threads.append(thread_dict)
143+
else:
144+
print("Thread ID does not exist in last_message_dates dictionary")
145+
messages_last_hour = 0
146+
last_message_date = await self.get_thread_last_message_date(thread)
147+
self.save_last_message_date(thread_id, last_message_date)
148+
# Define the thread dictionary
149+
thread_dict = {
150+
"channel": thread.parent,
151+
"mention": thread.mention,
152+
"creation_date": thread.created_at,
153+
"up_date": thread.archive_timestamp,
154+
"archive_date": await self.get_thread_archive_date(thread),
155+
"messages_last_hour": messages_last_hour
156+
}
157+
thread_dict["is_dead"] = thread_dict["archive_date"] < datetime.now(tz=timezone.utc)
158+
thread_dict["excluded"] = thread.parent_id == 1218292569209831514 #Excluding threads of channel early-access-sojfest
159+
160+
self.threads.append(thread_dict)
161+
"""
162+
messages_last_hour = await self.count_messages_last_hour(thread)
163+
# Define the thread dictionary
164+
thread_dict = {
165+
"channel": thread.parent,
166+
"mention": thread.mention,
167+
"creation_date": thread.created_at,
168+
"up_date": thread.archive_timestamp,
169+
"archive_date": await self.get_thread_archive_date(thread),
170+
"messages_last_hour": messages_last_hour
171+
}
172+
thread_dict["is_dead"] = thread_dict["archive_date"] < datetime.now(tz=timezone.utc)
173+
thread_dict["excluded"] = thread.parent_id == 1218292569209831514 #Excluding threads of channel early-access-sojfest
174+
self.threads.append(thread_dict)
175+
176+
"""
177+
async def count_messages_last_hour(self, thread, last_message_date):
178+
# Count messages in the last hour
179+
messages_last_hour = int(0)
180+
previous_message_date = None
181+
previous_message_author = None
182+
# async for message in thread.history(after=last_message_date, limit=100):
183+
async for message in thread.history(limit=51):
184+
# Make the message's creation time timezone-aware (assuming it's in UTC)
185+
message_created_at = message.created_at.replace(tzinfo=timezone.utc)
186+
if message_created_at > (datetime.now(tz=timezone.utc) - timedelta(hours=6)): # Messages des SIX (6) dernières heures
187+
current_message_date = message.created_at.replace(second=0, microsecond=0) # Round down to the nearest minute
188+
current_message_author = message.author
189+
if previous_message_author:
190+
if previous_message_author != current_message_author:
191+
pass
192+
else:
193+
if previous_message_date:
194+
if current_message_date > previous_message_date:
195+
pass
196+
else:
197+
continue
198+
else:
199+
previous_message_date = current_message_date
200+
else:
201+
previous_message_author = current_message_author
202+
messages_last_hour += 1
203+
204+
if messages_last_hour > 49:
205+
messages_last_hour = str("50+")
206+
return messages_last_hour
207+
"""
208+
async def count_messages_last_hour(self, thread):
209+
# Count messages in the last hour
210+
messages_last_hour = int(0)
211+
previous_message_date = None
212+
previous_message_author = None
213+
async for message in thread.history(limit=51):
214+
# Make the message's creation time timezone-aware (assuming it's in UTC)
215+
message_created_at = message.created_at.replace(tzinfo=timezone.utc)
216+
if message_created_at > (datetime.now(tz=timezone.utc) - timedelta(hours=6)): # Messages des SIX (6) dernières heures
217+
current_message_date = message.created_at.replace(second=0, microsecond=0) # Round down to the nearest minute
218+
current_message_author = message.author
219+
if previous_message_author:
220+
if previous_message_author != current_message_author:
221+
pass
222+
else:
223+
if previous_message_date:
224+
if current_message_date > previous_message_date:
225+
pass
226+
else:
227+
continue
228+
else:
229+
previous_message_date = current_message_date
230+
else:
231+
previous_message_author = current_message_author
232+
messages_last_hour += 1
233+
234+
#if messages_last_hour > 49:
235+
# messages_last_hour = str("50+")
236+
return messages_last_hour
58237

59238
async def get_thread_archive_date(self, thread):
60239
up_timestamp = thread.archive_timestamp
@@ -103,6 +282,7 @@ def update_instructions_string(self):
103282
> :{self.settings["new"]["emoji"]}: = {self.settings["new"]["description"]}
104283
> :{self.settings["up"]["emoji"]}: = {self.settings["up"]["description"]}
105284
> :{self.settings["dying"]["emoji"]}: = {self.settings["dying"]["description"]}
285+
> (nombre de messages écrits dans les 6 dernières heures)
106286
"""
107287

108288
def add_channel_and_threads_to_messages(self, channel_and_threads):
@@ -115,17 +295,23 @@ def add_channel_and_threads_to_messages(self, channel_and_threads):
115295
def complete_last_message(self, string_to_add):
116296
last_message_length = len(self.messages[-1])
117297
string_to_add_length = len(string_to_add)
118-
119298
if last_message_length + string_to_add_length <= self.settings["max_message_length"]:
120299
self.messages[-1] += string_to_add
121300
else:
122301
self.messages.append(string_to_add)
123302

303+
124304
def add_thread_to_messages(self, thread):
125305
thread_string = f"\n> {thread['mention']}"
126306
thread_string += self.add_new_emoji_if_required(thread)
127307
thread_string += self.add_up_emoji_if_required(thread)
128308
thread_string += self.add_dying_emoji_if_required(thread)
309+
if "messages_last_hour" in thread:
310+
if thread['messages_last_hour'] > 0:
311+
if thread['messages_last_hour'] == 51:
312+
thread_string += f" **(50+)** :fire:"
313+
else:
314+
thread_string += f" **({thread['messages_last_hour']})**"
129315
self.complete_last_message(thread_string)
130316

131317
def add_new_emoji_if_required(self, thread):

0 commit comments

Comments
 (0)