-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.py
65 lines (50 loc) · 1.89 KB
/
utils.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
from datetime import datetime, timedelta
from typing import TypeVar
T = TypeVar("T")
def join_grammatically(words: list[str]) -> str:
"""
Joins words with commas and, when grammatically correct, the word "and."
Args:
1. words: A list of words to be joined.
Returns:
A string, containing all the inputted words grammatically joined.
"""
if len(words) == 0:
return ""
elif len(words) == 1:
return words[0]
else:
return ", ".join(words[:-1]) + " and " + words[-1]
def group(array: list[T], size: int) -> list[list[T]]:
"""
Groups the elements of an array into sublists of a specified size.
Args:
1. array: A list of elements to be grouped.
2. size: The desired size of each sublist.
Returns:
A list of sublists, where each sublist contains at most `size` elements.
"""
return [array[i : i + size] for i in range(0, len(array), size)]
def split_conversations(
messages: list[dict], conversation_duration: timedelta
) -> list[list[dict]]:
"""
Splits a message download into individual conversations of certain time durations.
Args:
1. messages: A list of messages obtained from Save DMs.
2. conversation_duration: The maximum time between messages before a new conversation begins.
Returns:
A list of sublists, where each sublist is a single conversation.
"""
conversations: list[list[dict]] = []
last_timestamp: datetime = datetime(
2000, 1, 1
) # No Discord messages can exist before this, so it's a good starting date.
for message in messages:
timestamp = datetime.fromisoformat(message["timestamp"])
if timestamp.timestamp() < (last_timestamp + conversation_duration).timestamp():
conversations[-1].append(message)
else:
conversations.append([message])
last_timestamp = timestamp
return conversations