Skip to content

Commit

Permalink
Add hyperlinks in admin commands
Browse files Browse the repository at this point in the history
  • Loading branch information
laggron42 committed Jan 20, 2025
1 parent 9318715 commit 038665f
Show file tree
Hide file tree
Showing 7 changed files with 121 additions and 37 deletions.
14 changes: 12 additions & 2 deletions ballsdex/packages/admin/balls.py
Original file line number Diff line number Diff line change
Expand Up @@ -255,6 +255,11 @@ async def balls_info(self, interaction: discord.Interaction[BallsDexBot], countr
if ball.catch_date and ball.spawned_time
else "N/A"
)
admin_url = (
f"[View online](<{settings.admin_url}/bd_models/ballinstance/{ball.pk}/change/>)"
if settings.admin_url
else ""
)
await interaction.response.send_message(
f"**{settings.collectible_name.title()} ID:** {ball.pk}\n"
f"**Player:** {ball.player}\n"
Expand All @@ -268,7 +273,7 @@ async def balls_info(self, interaction: discord.Interaction[BallsDexBot], countr
f"**Spawned at:** {spawned_time}\n"
f"**Catch time:** {catch_time} seconds\n"
f"**Caught in:** {ball.server_id if ball.server_id else 'N/A'}\n"
f"**Traded:** {ball.trade_player}\n",
f"**Traded:** {ball.trade_player}\n{admin_url}",
ephemeral=True,
)
await log_action(f"{interaction.user} got info for {ball}({ball.pk}).", interaction.client)
Expand Down Expand Up @@ -589,9 +594,14 @@ async def balls_create(
if wild_card:
files.append(await wild_card.to_file())
await interaction.client.load_cache()
admin_url = (
f"[View online](<{settings.admin_url}/bd_models/ball/{ball.pk}/change/>)\n"
if settings.admin_url
else ""
)
await interaction.followup.send(
f"Successfully created a {settings.collectible_name} with ID {ball.pk}! "
"The internal cache was reloaded.\n"
f"The internal cache was reloaded.\n{admin_url}"
f"{missing_default}\n"
f"{name=} regime={regime.name} economy={economy.name if economy else None} "
f"{health=} {attack=} {rarity=} {enabled=} {tradeable=} emoji={emoji}",
Expand Down
30 changes: 25 additions & 5 deletions ballsdex/packages/admin/blacklist.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,13 @@
from tortoise.exceptions import DoesNotExist, IntegrityError

from ballsdex.core.bot import BallsDexBot
from ballsdex.core.models import BlacklistedGuild, BlacklistedID, BlacklistHistory
from ballsdex.core.models import (
BlacklistedGuild,
BlacklistedID,
BlacklistHistory,
GuildConfig,
Player,
)
from ballsdex.core.utils.logging import log_action
from ballsdex.core.utils.paginator import Pages
from ballsdex.packages.admin.menu import BlacklistViewFormat
Expand Down Expand Up @@ -123,18 +129,25 @@ async def blacklist_info(
)
else:
moderator_msg = "Moderator: Unknown"
if settings.admin_url and (player := await Player.get_or_none(discord_id=user.id)):
admin_url = (
"\n[View history online]"
f"(<{settings.admin_url}/bd_models/player/{player.pk}/change/>)"
)
else:
admin_url = ""
if blacklisted.date:
await interaction.response.send_message(
f"`{user}` (`{user.id}`) was blacklisted on {format_dt(blacklisted.date)}"
f"({format_dt(blacklisted.date, style='R')}) for the following reason:\n"
f"{blacklisted.reason}\n{moderator_msg}",
f"{blacklisted.reason}\n{moderator_msg}{admin_url}",
ephemeral=True,
)
else:
await interaction.response.send_message(
f"`{user}` (`{user.id}`) is currently blacklisted (date unknown)"
" for the following reason:\n"
f"{blacklisted.reason}\n{moderator_msg}",
f"{blacklisted.reason}\n{moderator_msg}{admin_url}",
ephemeral=True,
)

Expand Down Expand Up @@ -330,17 +343,24 @@ async def blacklist_info_guild(
)
else:
moderator_msg = "Moderator: Unknown"
if settings.admin_url and (gconf := await GuildConfig.get_or_none(guild_id=guild.id)):
admin_url = (
"\n[View history online]"
f"(<{settings.admin_url}/bd_models/guildconfig/{gconf.pk}/change/>)"
)
else:
admin_url = ""
if blacklisted.date:
await interaction.response.send_message(
f"`{guild}` (`{guild.id}`) was blacklisted on {format_dt(blacklisted.date)}"
f"({format_dt(blacklisted.date, style='R')}) for the following reason:\n"
f"{blacklisted.reason}\n{moderator_msg}",
f"{blacklisted.reason}\n{moderator_msg}{admin_url}",
ephemeral=True,
)
else:
await interaction.response.send_message(
f"`{guild}` (`{guild.id}`) is currently blacklisted (date unknown)"
" for the following reason:\n"
f"{blacklisted.reason}\n{moderator_msg}",
f"{blacklisted.reason}\n{moderator_msg}{admin_url}",
ephemeral=True,
)
42 changes: 30 additions & 12 deletions ballsdex/packages/admin/history.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,11 @@

import discord
from discord import app_commands
from tortoise.exceptions import DoesNotExist
from tortoise.expressions import Q

from ballsdex.core.bot import BallsDexBot
from ballsdex.core.models import BallInstance, Trade
from ballsdex.core.models import BallInstance, Player, Trade
from ballsdex.core.utils.paginator import Pages
from ballsdex.packages.trade.display import TradeViewFormat, fill_trade_embed_fields
from ballsdex.packages.trade.trade_user import TradingUser
Expand Down Expand Up @@ -55,15 +56,21 @@ async def history_user(
return

queryset = Trade.all()
if user2:
queryset = queryset.filter(
(Q(player1__discord_id=user.id) & Q(player2__discord_id=user2.id))
| (Q(player1__discord_id=user2.id) & Q(player2__discord_id=user.id))
)
else:
queryset = queryset.filter(
Q(player1__discord_id=user.id) | Q(player2__discord_id=user.id)
)
try:
player1 = await Player.get(discord_id=user.id)
if user2:
player2 = await Player.get(discord_id=user2.id)
query = f"?q={user.id}+{user2.id}"
queryset = queryset.filter(
(Q(player1=player1) & Q(player2=player2))
| (Q(player1=player2) & Q(player2=player1))
)
else:
query = f"?q={user.id}"
queryset = queryset.filter(Q(player1=player1) | Q(player2=player1))
except DoesNotExist:
await interaction.followup.send("One or more players are not registered by the bot.")
return

if days is not None and days > 0:
end_date = datetime.datetime.now()
Expand All @@ -82,7 +89,8 @@ async def history_user(
f"History of {user.display_name} and {user2.display_name}:"
)

source = TradeViewFormat(history, user.display_name, interaction.client, True)
url = f"{settings.admin_url}/bd_models/trade/{query}" if settings.admin_url else None
source = TradeViewFormat(history, user.display_name, interaction.client, True, url)
pages = Pages(source=source, interaction=interaction)
await pages.start(ephemeral=True)

Expand Down Expand Up @@ -152,8 +160,13 @@ async def history_ball(
await interaction.followup.send("No history found.", ephemeral=True)
return

url = (
f"{settings.admin_url}/bd_models/ballinstance/{ball.pk}/change/"
if settings.admin_url
else None
)
source = TradeViewFormat(
trades, f"{settings.collectible_name} {ball}", interaction.client, True
trades, f"{settings.collectible_name} {ball}", interaction.client, True, url
)
pages = Pages(source=source, interaction=interaction)
await pages.start(ephemeral=True)
Expand Down Expand Up @@ -188,6 +201,11 @@ async def trade_info(
return
embed = discord.Embed(
title=f"Trade {trade.pk:0X}",
url=(
f"{settings.admin_url}/bd_models/trade/{trade.pk}/change/"
if settings.admin_url
else None
),
description=f"Trade ID: {trade.pk:0X}",
timestamp=trade.date,
)
Expand Down
11 changes: 11 additions & 0 deletions ballsdex/packages/admin/info.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,8 +56,11 @@ async def guild(
)
return

url = None
if config := await GuildConfig.get_or_none(guild_id=guild.id):
spawn_enabled = config.enabled and config.guild_id
if settings.admin_url:
url = f"{settings.admin_url}/bd_models/guildconfig/{config.pk}/change/"
else:
spawn_enabled = False

Expand All @@ -69,12 +72,14 @@ async def guild(
owner = await interaction.client.fetch_user(guild.owner_id)
embed = discord.Embed(
title=f"{guild.name} ({guild.id})",
url=url,
description=f"**Owner:** {owner} ({guild.owner_id})",
color=discord.Color.blurple(),
)
else:
embed = discord.Embed(
title=f"{guild.name} ({guild.id})",
url=url,
color=discord.Color.blurple(),
)
embed.add_field(name="Members:", value=guild.member_count)
Expand Down Expand Up @@ -115,12 +120,18 @@ async def user(
if not player:
await interaction.followup.send("The user you gave does not exist.", ephemeral=True)
return
url = (
f"{settings.admin_url}/bd_models/player/{player.pk}/change/"
if settings.admin_url
else None
)
total_user_balls = await BallInstance.filter(
catch_date__gte=datetime.datetime.now() - datetime.timedelta(days=days),
player=player,
)
embed = discord.Embed(
title=f"{user} ({user.id})",
url=url,
description=(
f"**Privacy Policy:** {PRIVATE_POLICY_MAP[player.privacy_policy]}\n"
f"**Donation Policy:** {DONATION_POLICY_MAP[player.donation_policy]}\n"
Expand Down
10 changes: 9 additions & 1 deletion ballsdex/packages/admin/menu.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,10 @@
import discord
from discord.utils import format_dt

from ballsdex.core.models import BlacklistHistory
from ballsdex.core.models import BlacklistHistory, Player
from ballsdex.core.utils import menus
from ballsdex.core.utils.paginator import Pages
from ballsdex.settings import settings

if TYPE_CHECKING:
from ballsdex.core.bot import BallsDexBot
Expand Down Expand Up @@ -35,6 +36,13 @@ async def format_page(self, menu: Pages, blacklist: BlacklistHistory) -> discord
inline=True,
)
embed.add_field(name="Action Time", value=format_dt(blacklist.date, "R"), inline=True)
if settings.admin_url and (player := await Player.get_or_none(discord_id=self.header)):
embed.add_field(
name="\u200B",
value="[View history online]"
f"(<{settings.admin_url}/bd_models/player/{player.pk}/change/>)",
inline=False,
)
embed.set_footer(
text=(
f"Blacklist History {menu.current_page + 1}/{menu.source.get_max_pages()}"
Expand Down
3 changes: 3 additions & 0 deletions ballsdex/packages/trade/display.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,10 @@ def __init__(
header: str,
bot: "BallsDexBot",
is_admin: bool = False,
url: str | None = None,
):
self.header = header
self.url = url
self.bot = bot
self.is_admin = is_admin
super().__init__(entries, per_page=1)
Expand All @@ -28,6 +30,7 @@ async def format_page(self, menu: Pages, trade: TradeModel) -> discord.Embed:
embed = discord.Embed(
title=f"Trade history for {self.header}",
description=f"Trade ID: {trade.pk:0X}",
url=self.url if self.is_admin else None,
timestamp=trade.date,
)
embed.set_footer(
Expand Down
48 changes: 31 additions & 17 deletions ballsdex/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,7 @@ class Settings:

# django admin panel
webhook_url: str | None = None
admin_url: str | None = None
client_id: str = ""
client_secret: str = ""

Expand Down Expand Up @@ -168,9 +169,11 @@ def read_settings(path: "Path"):
"spawn-manager", "ballsdex.packages.countryballs.spawn.SpawnManager"
)

settings.webhook_url = content.get("webhook-url")
settings.client_id = content.get("client-id")
settings.client_secret = content.get("client-secret")
if admin := content.get("admin-panel"):
settings.webhook_url = admin.get("webhook-url")
settings.client_id = admin.get("client-id")
settings.client_secret = admin.get("client-secret")
settings.admin_url = admin.get("url")

log.info("Settings loaded.")

Expand Down Expand Up @@ -259,15 +262,20 @@ def write_default_settings(path: "Path"):
# Admin panel related settings
admin-panel:
# to enable Discord login, fill this
# the client ID of the Discord application
client-id:
# the client secret of the Discord application (this is not the bot token)
client-secret:
# to enable Discord OAuth2 login, fill this
# client ID of the Discord application (not the bot's user ID)
client-id:
# client secret of the Discord application (this is not the bot token)
client-secret:
# to get admin notifications from the admin panel, create a Discord webhook and paste the url
webhook-url:
# to get admin notifications from the admin panel, create a Discord webhook and paste the url
webhook-url:
# this will provide some hyperlinks to the admin panel when using /admin commands
# set to an empty string to disable those links entirely
url: http://localhost:8000
# list of packages that will be loaded
packages:
Expand Down Expand Up @@ -372,15 +380,21 @@ def update_settings(path: "Path"):
if add_django:
content += """
# Admin panel related settings
admin-panel:
# to enable Discord OAuth2 login, fill this
# client ID of the Discord application (not the bot's user ID)
client-id:
# client secret of the Discord application (this is not the bot token)
client-secret:
# to get admin notifications from the admin panel, create a Discord webhook and paste the url
webhook-url:
# to enable Discord login, fill this
# the client ID of the Discord application
client-id:
# the client secret of the Discord application (this is not the bot token)
client-secret:
# this will provide some hyperlinks to the admin panel when using /admin commands
# set to an empty string to disable those links entirely
url: http://localhost:8000
# to get admin notifications from the admin panel, create a Discord webhook and paste the url
webhook-url:
"""

if any(
Expand Down

0 comments on commit 038665f

Please sign in to comment.