Skip to content

Commit

Permalink
yeah I changed some stuff
Browse files Browse the repository at this point in the history
  • Loading branch information
pacnpal authored Sep 29, 2024
1 parent a5333a1 commit c319fde
Show file tree
Hide file tree
Showing 2 changed files with 74 additions and 34 deletions.
18 changes: 16 additions & 2 deletions birthday/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,14 +8,19 @@ To install this cog, follow these steps:

1. Ensure you have Red-DiscordBot V3 installed.
2. Add the repository to your bot:

```
[p]repo add Pac-cogs https://github.com/pacnpal/Pac-cogs
```

3. Install the Birthday cog:

```
[p]cog install Pac-cogs birthday
```

4. Load the cog:

```
[p]load birthday
```
Expand All @@ -27,28 +32,37 @@ Replace `[p]` with your bot's prefix.
Before using the cog, you need to set it up:

1. Set the birthday role:

```
[p]birthdayset role @Birthday
```

**Note:** The bot's role must be above the birthday role in the server's role hierarchy, but users assigning the birthday role do not need to have a role above it.

2. Add roles that can use the birthday command:

```
[p]birthdayset addrole @Moderator
```

3. (Optional) Set the timezone for role expiration:

```
[p]birthdayset timezone America/New_York
```

4. (Optional) Set a specific channel for birthday announcements:

```
[p]birthdayset channel #birthdays
```

If not set, the birthday message will be sent in the channel where the command is used.

## Usage

To assign the birthday role to a user:

```
[p]birthday @User
```
Expand All @@ -59,7 +73,7 @@ This will assign the birthday role to the user and send a celebratory message wi

- Assigns a special birthday role to users
- Sends a celebratory message with random cake (or pie) emojis
- Automatically removes the birthday role at midnight
- Automatically removes the birthday role at midnight, temporarily stores so tasks will complete even if cog is reloaded
- Configurable timezone for role expiration
- Option to set a specific channel for birthday announcements (defaults to the channel where the command is used)
- Restricts usage of the birthday command to specified roles
Expand All @@ -76,4 +90,4 @@ This will assign the birthday role to the user and send a celebratory message wi

## Support

If you encounter any issues or have questions, please open an issue on the [GitHub repository](https://github.com/pacnpal/Pac-cogs).
If you encounter any issues or have questions, please open an issue on the [GitHub repository](https://github.com/pacnpal/Pac-cogs).
90 changes: 58 additions & 32 deletions birthday/birthday.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,8 @@ def __init__(self, bot: Red):
"birthday_role": None,
"allowed_roles": [],
"timezone": "UTC",
"birthday_channel": None
"birthday_channel": None,
"scheduled_tasks": {}
}
self.config.register_guild(**default_guild)
self.birthday_tasks = {}
Expand All @@ -28,27 +29,12 @@ async def birthdayset(self, ctx):
pass

@birthdayset.command()
@checks.is_owner()
async def role(self, ctx, role: discord.Role):
"""Set the birthday role."""
await self.config.guild(ctx.guild).birthday_role.set(role.id)
await ctx.send(f"Birthday role set to {role.name}")

@birthdayset.command()
async def addrole(self, ctx, role: discord.Role):
"""Add a role that can use the birthday command."""
async with self.config.guild(ctx.guild).allowed_roles() as allowed_roles:
if role.id not in allowed_roles:
allowed_roles.append(role.id)
await ctx.send(f"Added {role.name} to the list of roles that can use the birthday command.")

@birthdayset.command()
async def removerole(self, ctx, role: discord.Role):
"""Remove a role from using the birthday command."""
async with self.config.guild(ctx.guild).allowed_roles() as allowed_roles:
if role.id in allowed_roles:
allowed_roles.remove(role.id)
await ctx.send(f"Removed {role.name} from the list of roles that can use the birthday command.")

@birthdayset.command()
@checks.is_owner()
async def timezone(self, ctx, tz: str):
Expand All @@ -67,6 +53,22 @@ async def channel(self, ctx, channel: discord.TextChannel):
await self.config.guild(ctx.guild).birthday_channel.set(channel.id)
await ctx.send(f"Birthday announcement channel set to {channel.mention}")

@birthdayset.command()
async def addrole(self, ctx, role: discord.Role):
"""Add a role that can use the birthday command."""
async with self.config.guild(ctx.guild).allowed_roles() as allowed_roles:
if role.id not in allowed_roles:
allowed_roles.append(role.id)
await ctx.send(f"Added {role.name} to the list of roles that can use the birthday command.")

@birthdayset.command()
async def removerole(self, ctx, role: discord.Role):
"""Remove a role from using the birthday command."""
async with self.config.guild(ctx.guild).allowed_roles() as allowed_roles:
if role.id in allowed_roles:
allowed_roles.remove(role.id)
await ctx.send(f"Removed {role.name} from the list of roles that can use the birthday command.")

@commands.command()
async def birthday(self, ctx, member: discord.Member):
"""Assign the birthday role to a user until midnight in the set timezone."""
Expand All @@ -78,7 +80,7 @@ async def birthday(self, ctx, member: discord.Member):
birthday_role_id = await self.config.guild(ctx.guild).birthday_role()
if not birthday_role_id:
return await ctx.send("The birthday role hasn't been set. An admin needs to set it using `[p]birthdayset role`.")

birthday_role = ctx.guild.get_role(birthday_role_id)
if not birthday_role:
return await ctx.send("The birthday role doesn't exist anymore. Please ask an admin to set it again.")
Expand All @@ -89,8 +91,13 @@ async def birthday(self, ctx, member: discord.Member):
except discord.Forbidden:
return await ctx.send("I don't have permission to assign that role.")

timezone = await self.config.guild(ctx.guild).timezone()

# Generate birthday message with random cakes (or pie)
cakes = random.randint(0, 5)
if cakes == 0:
message = f"🎉 Happy Birthday, {member.mention}! Sorry, out of cake today! Here's pie instead: 🥧"
else:
message = f"🎉 Happy Birthday, {member.mention}! Here's your cake{'s' if cakes > 1 else ''}: " + "🎂" * cakes

# Get the birthday announcement channel
birthday_channel_id = await self.config.guild(ctx.guild).birthday_channel()
if birthday_channel_id:
Expand All @@ -100,16 +107,10 @@ async def birthday(self, ctx, member: discord.Member):
else:
channel = ctx.channel

# Generate birthday message with random cakes (or pie)
cakes = random.randint(0, 5)
if cakes == 0:
message = f"🎉 Happy Birthday, {member.mention}! Sorry, out of cake today! Here's pie instead: 🥧"
else:
message = f"🎉 Happy Birthday, {member.mention}! Here's your cake{'s' if cakes > 1 else ''}: " + "🎂" * cakes

await channel.send(message)

# Schedule role removal
timezone = await self.config.guild(ctx.guild).timezone()
try:
tz = ZoneInfo(timezone)
except ZoneInfoNotFoundError:
Expand All @@ -119,10 +120,15 @@ async def birthday(self, ctx, member: discord.Member):
now = datetime.now(tz)
midnight = datetime.combine(now.date() + timedelta(days=1), time.min).replace(tzinfo=tz)

if ctx.guild.id in self.birthday_tasks:
self.birthday_tasks[ctx.guild.id].cancel()

self.birthday_tasks[ctx.guild.id] = self.bot.loop.create_task(self.remove_birthday_role(ctx.guild, member, birthday_role, midnight))
await self.schedule_birthday_role_removal(ctx.guild, member, birthday_role, midnight)

async def schedule_birthday_role_removal(self, guild, member, role, when):
"""Schedule the removal of the birthday role."""
await self.config.guild(guild).scheduled_tasks.set_raw(str(member.id), value={
"role_id": role.id,
"remove_at": when.isoformat()
})
self.birthday_tasks[guild.id] = self.bot.loop.create_task(self.remove_birthday_role(guild, member, role, when))

async def remove_birthday_role(self, guild, member, role, when):
"""Remove the birthday role at the specified time."""
Expand All @@ -132,4 +138,24 @@ async def remove_birthday_role(self, guild, member, role, when):
except (discord.Forbidden, discord.HTTPException):
pass # If we can't remove the role, we'll just let it be
finally:
del self.birthday_tasks[guild.id]
del self.birthday_tasks[guild.id]
await self.config.guild(guild).scheduled_tasks.clear_raw(str(member.id))

async def reload_scheduled_tasks(self):
"""Reload and reschedule tasks from the configuration."""
for guild in self.bot.guilds:
scheduled_tasks = await self.config.guild(guild).scheduled_tasks()
for member_id, task_info in scheduled_tasks.items():
member = guild.get_member(int(member_id))
if not member:
continue
role = guild.get_role(task_info["role_id"])
if not role:
continue
remove_at = datetime.fromisoformat(task_info["remove_at"]).replace(tzinfo=ZoneInfo(await self.config.guild(guild).timezone()))
self.birthday_tasks[guild.id] = self.bot.loop.create_task(self.remove_birthday_role(guild, member, role, remove_at))

async def setup(bot):
cog = Birthday(bot)
await bot.add_cog(cog)
await cog.reload_scheduled_tasks()

0 comments on commit c319fde

Please sign in to comment.