-
Notifications
You must be signed in to change notification settings - Fork 0
/
birthday_cog.py
155 lines (127 loc) · 5.31 KB
/
birthday_cog.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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
import discord
from discord.ext import commands, tasks
import datetime
import pymongo
import os
import certifi
ca = certifi.where()
from pymongo.mongo_client import MongoClient
from pymongo.server_api import ServerApi
import json
with open("credentials.json", "r") as f:
credentials = json.load(f)
TOKEN = credentials["mongo_uri"]
class birthday_cog(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.mongo_client = None
self.db = None
self.collection = None
self.connect_to_mongodb() # Establish the MongoDB connection
self.check_birthdays.start() # Start the background task
@commands.command(name="set_birthday", aliases=["bday", "cumple"], help="Set your birthday.")
async def set_birthday(self, ctx, date):
"""Set your birthday."""
try:
# Parse the provided date string into a datetime object
birthday = datetime.datetime.strptime(date, "%Y-%m-%d").date()
# Save the birthday date for the user
self.save_birthday(ctx.author.id, birthday)
await ctx.send("Cumpleaños agregado exitosamente!")
except ValueError:
await ctx.send("Formato de fecha incorrecto. Por favor usa YYYY-MM-DD.")
@commands.Cog.listener()
async def on_ready(self):
print("BirthdayCog is ready.")
self.connect_to_mongodb()
self.check_birthdays.start()
def connect_to_mongodb(self):
# Set up MongoDB connection
mongo_uri = TOKEN # Replace with your MongoDB URI
self.mongo_client = pymongo.MongoClient(mongo_uri, tlsCAFile=ca)
self.db = self.mongo_client["BalboaBot"]
self.collection = self.db["Birthdays"]
def save_birthday(self, user_id, birthday):
# Check if the user already exists in the collection
user_data = self.collection.find_one({"user_id": user_id})
if user_data:
# Update the existing user's birthday
self.collection.update_one(
{"user_id": user_id},
{"$set": {"birthday": birthday.strftime("%Y-%m-%d")}},
)
else:
# Add a new user and their birthday
user_data = {"user_id": user_id, "birthday": birthday.strftime("%Y-%m-%d")}
self.collection.insert_one(user_data)
@tasks.loop(hours=24)
async def check_birthdays(self):
# Get the current date without the year
current_date = datetime.datetime.now().date().replace(year=1900)
channel = self.bot.get_channel(852779059234340894)
# Find all users with a birthday today
birthday_users = list(
self.collection.find(
{
"birthday": {
"$regex": f"{current_date.month:02d}-{current_date.day:02d}"
}
}
)
)
birthday_count = len(birthday_users) # Get the count of documents
if birthday_count == 0:
await channel.send("Nadie está de cumpleaños hoy")
else:
message = ""
for user_data in birthday_users:
user = self.bot.get_user(user_data["user_id"])
if user:
message += f"¡Feliz Cumpleaños {user.mention}!\n"
await channel.send(message)
@commands.command(name="check", help="Check for birthdays today.")
async def check(self, ctx):
# Get the current date without the year
current_date = datetime.datetime.now().date().replace(year=1900)
# Find all users with a birthday today
try:
birthday_users = list(
self.collection.find(
{
"birthday": {
"$regex": f"{current_date.month:02d}-{current_date.day:02d}"
}
}
)
)
except ServerApi.ServerSelectionTimeoutError:
await ctx.send("Error connecting to MongoDB.")
return
birthday_count = len(birthday_users) # Get the count of documents
if birthday_count == 0:
await ctx.send("No hay cumpleaños hoy :(")
else:
message = "Cumpleaños Hoy:\n"
for user_data in birthday_users:
user = self.bot.get_user(user_data["user_id"])
if user:
message += f"- {user.mention}\n"
await ctx.send(message)
@commands.command(name="display", aliases=['mostrar'], help="Display all registered birthdays.")
async def display_birthdays(self, ctx):
# Get all registered birthdays
birthday_users = list(self.collection.find())
if len(birthday_users) == 0:
await ctx.send("No existen cumpleaños registrados.")
else:
message = "Cumpleaños Registrados:\n"
for user_data in birthday_users:
user_id = user_data.get("user_id")
if user_id:
user = self.bot.get_user(user_id)
if user:
birthday = datetime.datetime.strptime(
user_data["birthday"], "%Y-%m-%d"
).date()
message += f"- {user.name} ~ {birthday.strftime('%B %d')}\n"
await ctx.send(message)