feat(shard): Lots of code.

This commit is contained in:
Nyeki.py
2024-11-15 23:24:11 -03:00
parent d9d752c730
commit 6377cb66c2
35 changed files with 2546 additions and 105 deletions
+73 -6
View File
@@ -5,11 +5,16 @@ from discord.ext import commands
from payphone.db import models
from payphone.bot import Payphone
from payphone.cogs import base
from payphone.cogs.admin import embeds, views
from payphone.core import checks
class Admin(commands.Cog):
class Admin(base.Cog):
"""Administration in Payphone."""
show_in_help = False
def __init__(self, bot: Payphone) -> None:
"""Initializes the Calls cog.
@@ -22,26 +27,69 @@ class Admin(commands.Cog):
@commands.command(aliases=["mod"])
@commands.is_owner()
async def moderator(
self, ctx: commands.Context, user: discord.User, toggle: bool
self, ctx: commands.Context, user: discord.User, toggle: bool = True
) -> None:
"""Gives the user the Moderator role."""
"""Gives the user the Moderator role.
Options:
- `<user>`: The user to give the role.
- `[toggle]`: Whether to give or remove the role.
await models.User.update_or_create(
Permissions:
- Bot Owner
"""
instance, _ = await models.User.update_or_create(
id=user.id, defaults={"is_moderator": toggle}
)
await instance.set_cache(self.bot.redis)
await ctx.send(
f"Toggled the moderator role {'on' if toggle else 'off'} for {user.mention}."
)
@commands.command(aliases=["ub"])
@checks.is_moderator()
async def unban(
self, ctx: commands.Context, user: discord.User | None = None
) -> None:
"""Unbans the user from the bot.
Options:
- `[user]`: The user to unban. If none is provided, the author will be unbanned.
Permissions:
- Bot Moderator
"""
user = user or ctx.author
await self.bot.unban(user.id)
await ctx.send(f"{user.mention} was unbanned from Payphone.")
try:
await user.send("🔔 You were unbanned from Payphone!")
except discord.Forbidden:
pass
@commands.command(aliases=["sup"])
@commands.is_owner()
async def supporter(
self, ctx: commands.Context, user: discord.User, toggle: bool = True
) -> None:
"""Gives the user the Supporter role."""
"""Gives the user the Supporter role.
Options:
- `<user>`: The user to give the role.
- `[toggle]`: Whether to give or remove the role.
await models.User.update_or_create(
Permissions:
- Bot Owner
"""
instance, _ = await models.User.update_or_create(
id=user.id,
defaults={
"is_supporter_until": (
@@ -49,11 +97,30 @@ class Admin(commands.Cog):
)
},
)
await instance.set_cache(self.bot.redis)
await ctx.send(
f"Gave the Supporter role to {ctx.author.mention} until in one month."
)
@commands.command()
@checks.is_moderator()
async def reports(self, ctx: commands.Context) -> None:
"""Shows the reports.
Permissions:
- Bot Moderator
"""
report = await models.Report.filter(resolved=False).first()
if report is None:
return await ctx.send("✅ No reports left, have this cookie 🍪 !!")
await ctx.send(
embed=embeds.report_embed(report), view=views.ReportView(self.bot, report)
)
def setup(bot: Payphone) -> None:
"""Loads the Admin cog into the bot.
+33
View File
@@ -0,0 +1,33 @@
import discord
from payphone.db import models
from payphone.core import constants
def report_embed(report: models.Report) -> discord.Embed:
"""Creates an embed for a report.
Args:
report (models.Report): The report to create an embed for.
Returns:
(discord.Embed): The embed.
"""
return discord.Embed(
color=constants.PRIMARY_COLOR,
title="Message Report",
description=(
f"**ID:** {report.id}\n"
f"**User ID**: {report.user_id}\n"
f"**User Name**: {report.user_name}\n"
f"**Channel ID**: {report.channel_id}\n"
f"**Created At**: <t:{int(report.created_at.timestamp())}>\n"
),
fields=[
discord.EmbedField(
name="Message Content", value=report.message_content, inline=False
)
],
thumbnail=report.user_avatar_url,
)
+197
View File
@@ -0,0 +1,197 @@
from datetime import datetime, timedelta, timezone
import discord
from payphone.db import models
from payphone.bot import Payphone
from payphone.core import constants
from payphone.cogs.admin import embeds
class ReportView(discord.ui.View):
"""The report view."""
def __init__(self, bot: Payphone, report: models.Report) -> None:
"""Initializes the ReportView.
Args:
bot (Payphone): The bot.
report (models.Report): The report.
"""
super().__init__(disable_on_timeout=True)
self.bot = bot
self.report = report
@discord.ui.select(
placeholder="Select an action",
options=[
discord.SelectOption(
value="warn",
label="Warn",
description="Send a warning to the user. This is done automatically.",
),
discord.SelectOption(
value="ban",
label="Ban",
description="Ban the user. The duration of the ban will be applied automatically.",
),
discord.SelectOption(
value="ban_permanently",
label="Permanent Ban",
description="Ban the user permanently. Use this when the user must not be allowed back.",
),
],
)
async def action_callback(
self, select: discord.SelectMenu, interaction: discord.Interaction
) -> None:
"""Handles the action select."""
user = await models.User.get_cache_or_db(self.bot.redis, self.report.user_id)
if select.values[0] == "warn":
user.warns_count += 1
await user.save(force_update=True)
await user.set_cache(self.bot.redis)
embed = discord.Embed(
color=constants.MASK_COLOR,
title="Warned",
description=f"You've been warned. You've received `{user.warns_count}` warnings in total.",
fields=[
discord.EmbedField(
name="Message Content",
value=f"You sent the following message in a call:\n> {self.report.message_content}",
),
discord.EmbedField(
name="User Name",
value=self.report.user_name,
),
discord.EmbedField(
name="User Avatar",
value=f"[Click to open your avatar URL](<{self.report.user_avatar_url}>)",
),
],
footer=discord.EmbedFooter(
text="⚠️ Repeating this action will result in a ban."
),
)
try:
await (await self.bot.get_or_fetch_user(self.report.user_id)).send(
embed=embed
)
except discord.Forbidden:
pass
else:
user.bans_count += 1
await user.save(force_update=True)
await user.set_cache(self.bot.redis)
expires_at = None
if select.values[0] == "ban":
expiry_times = {
1: datetime.now(timezone.utc) + timedelta(days=1),
2: datetime.now(timezone.utc) + timedelta(days=7),
3: datetime.now(timezone.utc) + timedelta(days=30),
}
expires_at = expiry_times.get(user.bans_count, None)
await self.bot.ban(
self.report.user_id,
self.report,
expires_at=expires_at,
created_by_id=interaction.user.id,
)
embed = discord.Embed(
color=constants.MODERATOR_COLOR,
title="Banned",
description=f"You've been banned. You've been banned `{user.bans_count}` times.",
fields=[
discord.EmbedField(
name="Message Content",
value=f"You sent the following message in a call:\n> {self.report.message_content}",
),
discord.EmbedField(
name="User Name",
value=self.report.user_name,
),
discord.EmbedField(
name="User Avatar",
value=f"[Click to open your avatar URL](<{self.report.user_avatar_url}>)",
),
discord.EmbedField(
name="Expires At",
value=(
expires_at.strftime("%Y-%m-%d %H:%M:%S")
+ f" <t:{int(expires_at.timestamp())}:R>"
if expires_at
else "Never"
),
),
],
footer=discord.EmbedFooter(
text=(
"⚠️ In case you get banned again, your ban will last longer. Multiple bans will result in a permanent ban."
if expires_at is not None
else "⚠️ You've been permanently banned."
)
),
)
try:
await (await self.bot.get_or_fetch_user(self.report.user_id)).send(
embed=embed
)
except discord.Forbidden:
pass
self.report.resolved = True
await self.report.save()
report = await models.Report.filter(resolved=False).first()
if report is None:
self.stop()
return await interaction.response.edit_message(
content="✅ No reports left, have this cookie 🍪 !!",
embeds=[],
view=None,
)
await interaction.response.edit_message(
embed=embeds.report_embed(report), view=ReportView(self.bot, report)
)
@discord.ui.button(label="Skip", style=discord.ButtonStyle.gray)
async def skip_callback(
self, _button: discord.ui.Button, interaction: discord.Interaction
) -> None:
"""Skips the report."""
self.report.resolved = True
await self.report.save()
report = await models.Report.filter(resolved=False).first()
if report is None:
self.stop()
return await interaction.response.edit_message(
content="✅ No reports left, have this cookie 🍪 !!",
embeds=[],
view=None,
)
await interaction.response.edit_message(
embed=embeds.report_embed(report), view=ReportView(self.bot, report)
)