Skip to content

Commit 3833521

Browse files
authored
Counting channel messages
1 parent dd595b8 commit 3833521

File tree

1 file changed

+45
-42
lines changed

1 file changed

+45
-42
lines changed

active_threads_command.py

Lines changed: 45 additions & 42 deletions
Original file line numberDiff line numberDiff line change
@@ -13,8 +13,8 @@ def get_db_connection():
1313
user=DB_username,
1414
password=DB_password,
1515
database=DB_name,
16-
charset= 'utf8mb4', # Specify the charset
17-
collation= 'utf8mb4_general_ci', # Specify a compatible collation
16+
charset='utf8mb4', # Specify the charset
17+
collation='utf8mb4_general_ci', # Specify a compatible collation
1818
connection_timeout=10 # Set a reasonable timeout value
1919
)
2020
return connection
@@ -40,8 +40,7 @@ def __init__(self, bot):
4040
def read_settings():
4141
return read_yaml('config/active_threads.yml')
4242

43-
44-
##### LEVEL 0
43+
##### LEVEL 0
4544
@tasks.loop(hours=1)
4645
async def refresh_open_threads_list(self):
4746
self.initialize_run()
@@ -51,7 +50,7 @@ async def refresh_open_threads_list(self):
5150

5251
print(f"API Calls made: {self.api_call_count}")
5352
self.api_call_count = 0
54-
53+
5554
@tasks.loop(hours=168) # Run once a week
5655
async def delete_old_messages_from_db(self):
5756
db = get_db_connection()
@@ -73,7 +72,7 @@ async def delete_old_messages_from_db(self):
7372
cursor.close()
7473
db.close()
7574

76-
##### LEVEL 1
75+
##### LEVEL 1
7776
def initialize_run(self):
7877
self.date = datetime.now(tz=timezone.utc)
7978
self.settings = self.read_settings()
@@ -96,7 +95,7 @@ async def update_active_threads_channel(self):
9695
await self.delete_old_messages()
9796
await self.send_new_messages()
9897

99-
##### LEVEL 2
98+
##### LEVEL 2
10099
async def get_threads_info(self):
101100
self.threads = []
102101
threads_raw = await self.guild.active_threads()
@@ -115,6 +114,7 @@ async def get_threads_info(self):
115114
self.threads.append(thread_dict)
116115

117116
async def count_messages_last_6_hours(self):
117+
self.channels_and_threads_dictionaries = []
118118
db = get_db_connection()
119119
if not db:
120120
print("Failed to connect to the database.")
@@ -141,20 +141,11 @@ async def count_messages_last_6_hours(self):
141141
# Update message counts for threads
142142
for thread in self.threads:
143143
thread_id = thread["id"]
144-
thread["message_count"] = message_counts.get(thread_id, 0)
145-
146-
# Get channels and their message counts
147-
for channel in self.guild.text_channels:
148-
channel_id = channel.id
149-
if channel_id not in message_counts:
150-
continue
151-
channel_dict = {
152-
"channel": channel,
153-
"mention": channel.mention,
154-
"id": channel_id,
155-
"message_count": message_counts[channel_id]
156-
}
157-
self.channels_and_threads_dictionaries.append(channel_dict)
144+
parent_channel_id = thread["channel"].id
145+
# Add thread message count
146+
thread["thread_message_count"] = message_counts.get(thread_id, 0)
147+
# Add parent channel message count
148+
thread["channel_message_count"] = message_counts.get(parent_channel_id, 0)
158149

159150
except mysql.connector.Error as err:
160151
print(f"Database error: {err}")
@@ -164,44 +155,63 @@ async def count_messages_last_6_hours(self):
164155

165156
def build_channels_and_threads_list(self):
166157
self.channels_and_threads_dictionaries = []
158+
# Store channels without active threads separately
159+
channels_without_active_threads = {}
160+
167161
while self.threads:
168162
channel = self.threads[0]["channel"]
169163
threads_channel = [thread for thread in self.threads if thread["channel"] == channel]
170164
channel_dictionary = {
171165
"channel": channel,
172-
"threads": [thread for thread in threads_channel if not thread["is_dead"] and not thread["excluded"]]
166+
"threads": [thread for thread in threads_channel if not thread["is_dead"] and not thread["excluded"]],
167+
"message_count": threads_channel[0].get("channel_message_count", 0) # Get channel message count
173168
}
174169

175170
if len(channel_dictionary["threads"]) > 0:
176171
self.channels_and_threads_dictionaries.append(channel_dictionary)
177-
172+
else:
173+
# Only add channels without active threads if message count > 0
174+
message_count = channel_dictionary["message_count"]
175+
if message_count > 0:
176+
channels_without_active_threads[channel.id] = {
177+
"channel": channel,
178+
"message_count": message_count
179+
}
178180
for thread in threads_channel:
179181
self.threads.remove(thread)
182+
183+
# Add channels without active threads to the final list if message count > 0
184+
for channel_info in channels_without_active_threads.values():
185+
self.channels_and_threads_dictionaries.append({
186+
"channel": channel_info["channel"],
187+
"threads": [], # No threads
188+
"message_count": channel_info["message_count"]
189+
})
180190

181191
def add_channel_and_threads_to_messages(self, channel_and_threads):
182-
self.complete_last_message('\n\n\n')
192+
self.complete_last_message('\n')
183193
self.complete_last_message(channel_and_threads["channel"].mention)
194+
message_count = channel_and_threads.get("message_count", 0)
195+
if message_count > 0:
196+
self.complete_last_message(f" ({message_count})")
184197

185198
# If there are threads, handle them
186-
if "threads" in channel_and_threads:
199+
if "threads" in channel_and_threads and channel_and_threads["threads"]:
187200
for thread in channel_and_threads["threads"]:
188201
self.add_thread_to_messages(thread)
189-
else:
190-
# Handle channel message count
191-
message_count = channel_and_threads.get("message_count", 0) #NOT WORKING!!
192-
if message_count > 0:
193-
self.complete_last_message(f" ({message_count})")
202+
self.complete_last_message('\n\n\n')
194203

195204
async def delete_old_messages(self):
196205
async for message in self.channel_to_update.history(limit=None):
197-
self.api_call_count += 1
206+
self.api_call_count += 1 # Increment for fetching each batch of messages
198207
await message.delete()
208+
self.api_call_count += 1 # Increment for deleting each message
199209

200210
async def send_new_messages(self):
201211
for message in self.messages:
202212
await self.channel_to_update.send(message)
203213

204-
##### LEVEL 3
214+
##### LEVEL 3
205215
async def get_thread_archive_date(self, thread):
206216
up_timestamp = thread.archive_timestamp
207217
self.api_call_count += 1
@@ -212,7 +222,6 @@ async def get_thread_archive_date(self, thread):
212222
last_activity = max(last_message, up_timestamp)
213223
return last_activity + timedelta(minutes=thread.auto_archive_duration)
214224

215-
216225
def complete_last_message(self, string_to_add):
217226
last_message_length = len(self.messages[-1])
218227
string_to_add_length = len(string_to_add)
@@ -230,8 +239,7 @@ def add_thread_to_messages(self, thread):
230239
thread_string += self.add_message_count_if_required(thread)
231240
self.complete_last_message(thread_string)
232241

233-
234-
##### LEVEL 4
242+
##### LEVEL 4
235243
async def get_thread_last_message_date(self, thread):
236244
message_list = []
237245
async for item in thread.history(limit=1):
@@ -260,17 +268,12 @@ def add_dying_emoji_if_required(self, thread):
260268
return f" :{parameters['emoji']}:" if hours_until_archive < hours_for_emoji else ""
261269

262270
def add_message_count_if_required(self, thread):
263-
message_count = thread.get("message_count", 0)
264-
if message_count > 30:
265-
return " :fire: (30+)"
266-
elif message_count > 0:
267-
return f" ({message_count})"
268-
return ""
271+
return f" ({thread['thread_message_count']})" if thread["thread_message_count"] > 0 else ""
269272

270273
##### LEVEL 2
271274
def update_instructions_string(self):
272275
self.instructions = f"""
273-
Au {self.date.astimezone(tz=tz.gettz('Europe/Paris')).strftime("%d/%m/%Y, %H:%M:%S")} (heure de Paris), voici la liste des fils actifs sur ce serveur Discord.
276+
Au {self.date.astimezone(tz=tz.gettz('Europe/Paris')).strftime("%d/%m/%Y, %H:%M:%S")} (heure de Paris), voici la liste des discussions en cours.
274277
275278
**__Légende :__**
276279
> :{self.settings["new"]["emoji"]}: = {self.settings["new"]["description"]}

0 commit comments

Comments
 (0)