-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.py
69 lines (59 loc) · 2 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
66
67
68
69
import json
import discord
import tldextract
# Utility Function to Format Recipe Responses
def format_recipe_list(recipes) -> str:
"""
Formats a list of Recipe objects into a user-friendly string.
"""
if not recipes:
return "No recipes found."
return "\n".join(
f"{i+1}. {recipe.title} ({recipe.extra.get('time', 'N/A')}) - [Link]({recipe.source_url})"
for i, recipe in enumerate(recipes)
)
def fallback_title_for(recipe) -> str:
"""
If recipe.title is empty, fallback to domain name of recipe.source_url.
Otherwise, use the stored title.
"""
if recipe.title and recipe.title.strip():
return recipe.title
return extract_domain(recipe.source_url)
def save_seen_users(seen_users):
with open("seen_users.json", "w") as f:
json.dump(list(seen_users), f)
def load_seen_users():
try:
with open("seen_users.json", "r") as f:
data = json.load(f)
seen_users = set(data)
except FileNotFoundError:
seen_users = set()
return seen_users
def extract_domain(url: str) -> str:
"""
Returns something like "pinterest.com"
given a full URL.
If the domain is not found, returns "untitled".
"""
parsed = tldextract.extract(url)
domain_part = f"{parsed.domain}.{parsed.suffix}" if parsed.suffix else parsed.domain
return domain_part if domain_part else "untitled"
async def check_for_new_users(ctx, rules: str):
"""
Checks if the user has already received the DM with the rules.
If not, sends the DM and marks the user as seen.
"""
seen_users = load_seen_users()
if ctx.author.id not in seen_users:
try:
await ctx.author.send(rules)
except discord.Forbidden:
# If the user has DMs disabled, skip
pass
except Exception as e:
print(f"Error sending DM to user {ctx.author.id}: {e}")
# Mark the user as seen
seen_users.add(ctx.author.id)
save_seen_users(seen_users)