Skip to content

Commit

Permalink
Update: v0.5.0 #minor
Browse files Browse the repository at this point in the history
This update is designed to be a QOL update, and changes some internal parts in order to improve them. For more info, please see the changelog ~ Noelle
  • Loading branch information
No767 authored Nov 10, 2023
2 parents 9e7c3e6 + 5182976 commit 6748970
Show file tree
Hide file tree
Showing 32 changed files with 1,194 additions and 1,443 deletions.
7 changes: 7 additions & 0 deletions .dockerignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
# ENV files
**/.env

# Cache files
**/__pycache__
**/*.py[cod]
**/*$py.class
15 changes: 3 additions & 12 deletions bot/catherinebot.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,33 +9,23 @@
from dotenv import load_dotenv
from libs.utils import CatherineLogger, read_env

# Only used for Windows development
if os.name == "nt":
asyncio.set_event_loop_policy(asyncio.WindowsProactorEventLoopPolicy())
from winloop import install
else:
try:
import uvloop

asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())
except ImportError:
pass
from uvloop import install

load_dotenv()

ENV_PATH = Path(__file__).parent / ".env"

TOKEN = os.environ["TOKEN"]
DEV_MODE = os.getenv("DEV_MODE") in ("True", "TRUE")
ENABLE_MESSAGE_CONTENT = os.getenv("ENABLE_MESSAGE_CONTENT") in ("True", "TRUE")
IPC_SECRET_KEY = os.environ["IPC_SECRET_KEY"]
IPC_HOST = os.environ["IPC_HOST"]
POSTGRES_URI = os.environ["POSTGRES_URI"]


intents = discord.Intents.default()
intents.members = True
if DEV_MODE is True or ENABLE_MESSAGE_CONTENT is True:
intents.message_content = True


async def main() -> None:
Expand All @@ -56,6 +46,7 @@ async def main() -> None:

def launch() -> None:
with CatherineLogger():
install()
asyncio.run(main())


Expand Down
16 changes: 3 additions & 13 deletions bot/catherinecore.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ def __init__(
activity=discord.Activity(
type=discord.ActivityType.watching, name="for some eggs to hatch!"
),
command_prefix="uwu-oneechan",
command_prefix=commands.when_mentioned,
help_command=None,
intents=intents,
owner_id=454357482102587393,
Expand All @@ -66,7 +66,8 @@ def __init__(
def blacklist_cache(self) -> Dict[int, bool]:
"""Global blacklist cache
The main blacklist is stored on PostgreSQL, and is always a 1:1 mapping of the cache. R. Danny loads it from a JSON file, but I call that json as a db.
The main blacklist is stored on PostgreSQL, and is always a 1:1 mapping of the cache.
R. Danny loads it from a JSON file, but I call that json as a db.
Returns:
Dict[int, bool]: Cached version of all globally blacklisted users.
Expand Down Expand Up @@ -131,17 +132,6 @@ def remove_from_blacklist_cache(self, id: int) -> None:
def replace_blacklist_cache(self, new_cache: Dict[int, bool]) -> None:
self._blacklist_cache = new_cache

async def get_or_fetch_member(
self, guild: discord.Guild, member_id: int
) -> Optional[discord.Member]:
member = guild.get_member(member_id)
if member is not None:
return member
members = await guild.query_members(limit=1, user_ids=[member_id], cache=True)
if not members:
return None
return members[0]

async def fs_watcher(self) -> None:
cogs_path = Path(__file__).parent.joinpath("cogs")
async for changes in awatch(cogs_path):
Expand Down
2 changes: 1 addition & 1 deletion bot/cogs/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,4 +13,4 @@ def __str__(self) -> str:


EXTENSIONS = [module.name for module in iter_modules(__path__, f"{__package__}.")]
VERSION: VersionInfo = VersionInfo(major=0, minor=4, micro=1, releaselevel="final")
VERSION: VersionInfo = VersionInfo(major=0, minor=5, micro=0, releaselevel="final")
54 changes: 20 additions & 34 deletions bot/cogs/blacklist.py
Original file line number Diff line number Diff line change
@@ -1,75 +1,61 @@
import discord
from catherinecore import Catherine
from discord import app_commands
from discord.ext import commands
from libs.cog_utils.blacklist import is_owner
from libs.ui.blacklist import BlacklistPages
from libs.utils import get_or_fetch_full_blacklist

HANGOUT_GUILD_ID = 1145897416160194590
ID_DESCRIPTION = "User or Guild ID to add"
DONE_MSG = "Done."


class Blacklist(commands.Cog):
class Blacklist(commands.Cog, command_attrs=dict(hidden=True)):
"""Global blacklist management cog"""

def __init__(self, bot: Catherine) -> None:
self.bot = bot
self.pool = self.bot.pool

blacklist = app_commands.Group(
name="blacklist",
description="Blacklisting module",
guild_ids=[HANGOUT_GUILD_ID],
)

@is_owner()
@blacklist.command(name="view")
async def view(self, interaction: discord.Interaction):
"""View the global blacklist"""
@commands.group(name="blacklist", invoke_without_command=True)
@commands.is_owner()
@commands.guild_only()
async def blacklist(self, ctx: commands.Context) -> None:
"""Global blacklisting system - Without subcommand you are viewing the blacklist"""
blacklist = await get_or_fetch_full_blacklist(self.bot, self.pool)
if blacklist is None:
await interaction.response.send_message("No blacklist entries found")
await ctx.send("No blacklist entries found")
return

cache_to_list = [{k: v} for k, v in blacklist.items()]

pages = BlacklistPages(entries=cache_to_list, interaction=interaction)
pages = BlacklistPages(entries=cache_to_list, ctx=ctx)
await pages.start()

@is_owner()
@blacklist.command(name="add")
@app_commands.describe(id=ID_DESCRIPTION)
async def add(self, interaction: discord.Interaction, id: str):
async def add(self, ctx: commands.Context, id: discord.Object):
"""Adds an ID to the global blacklist"""
obj = discord.Object(id=int(id))
given_id = id.id
query = """
INSERT INTO blacklist (id, blacklist_status)
VALUES ($1, $2) ON CONFLICT (id) DO NOTHING;
"""
await self.pool.execute(query, obj.id, True)
if obj.id not in self.bot.blacklist_cache:
self.bot.add_to_blacklist_cache(obj.id)
await self.pool.execute(query, given_id, True)
if id not in self.bot.blacklist_cache:
self.bot.add_to_blacklist_cache(given_id)
self.bot.metrics.blacklisted_users.inc()
await interaction.response.send_message(DONE_MSG, ephemeral=True)
await ctx.send(DONE_MSG)

@is_owner()
@blacklist.command(name="remove")
@app_commands.describe(id=ID_DESCRIPTION)
async def remove(self, interaction: discord.Interaction, id: str):
async def remove(self, ctx: commands.Context, id: discord.Object):
"""Removes an ID from the global blacklist"""
obj = discord.Object(id=int(id))
given_id = id.id
query = """
DELETE FROM blacklist
WHERE id = $1;
"""
await self.pool.execute(query, obj.id)
if obj.id in self.bot.blacklist_cache:
self.bot.remove_from_blacklist_cache(obj.id)
await self.pool.execute(query, given_id)
if given_id in self.bot.blacklist_cache:
self.bot.remove_from_blacklist_cache(given_id)
self.bot.metrics.blacklisted_users.dec()

await interaction.response.send_message(DONE_MSG, ephemeral=True)
await ctx.send(DONE_MSG)


async def setup(bot: Catherine) -> None:
Expand Down
10 changes: 6 additions & 4 deletions bot/cogs/dev_tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,6 @@ class DevTools(commands.Cog, command_attrs=dict(hidden=True)):
def __init__(self, bot: Catherine):
self.bot = bot

@property
def display_emoji(self) -> discord.PartialEmoji:
return discord.PartialEmoji(name="\U0001f6e0")

@commands.guild_only()
@commands.is_owner()
@commands.command(name="sync", hidden=True)
Expand Down Expand Up @@ -68,6 +64,12 @@ async def sync(
@commands.command(name="reload-all", hidden=True)
async def reload_all(self, ctx: commands.Context) -> None:
"""Reloads all cogs. Used in production to not produce any downtime"""
if not hasattr(self.bot, "uptime"):
await ctx.send(
"Catherine-Chan needs to be fully loaded before anything can happen"
)
return

for extension in EXTENSIONS:
await self.bot.reload_extension(extension)
await ctx.send("Successfully reloaded all extensions live")
Expand Down
2 changes: 1 addition & 1 deletion bot/cogs/meta.py
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@ async def support(self, interaction: discord.Interaction):
"""Ways you can support Catherine-Chan!"""
invite_url = oauth_url(client_id=self.bot.application.id) # type: ignore # By the time the bot is ready, the app id is already there
desc = f"""
**Upvoting on Top.gg**: [Insert coming top.gg link]
**Upvoting on Top.gg**: https://top.gg/bot/1142620675517984808
**Joining the support server**: https://discord.gg/ns3e74frqn
**Inviting Catherine-Chan to you server**: {invite_url}
Expand Down
22 changes: 3 additions & 19 deletions bot/cogs/pride_support.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,25 +13,6 @@ class PrideSupport(commands.Cog):
def __init__(self, bot: Catherine):
self.bot = bot

@app_commands.command(name="pride-server")
async def pride_servers(self, interaction: discord.Interaction) -> None:
"""Get a list of LGBTQ oriented discord servers"""
embed = Embed()
embed.title = "Servers for LGBTQ+"
embed.description = """
***This bot is not affiliated or associated with these servers at all!***
LGTBTQ+ Hangout - https://www.discord.gg/Pride
Transcord - https://discord.gg/trans
The LGBTQ+ Community - https://discord.gg/pridemonth
Enby_eautiful - https://discord.gg/j8MCnEC64S
"""
embed.set_footer(
text="If you are enjoying Catherine-Chan, please consider to tell your friends about this bot! If you can't, then you can still show your support by upvoting on Top.gg!",
icon_url="https://cdn.discordapp.com/emojis/1096897624432443392.webp?size=128&quality=lossless",
)
await interaction.response.send_message(embed=embed)

@app_commands.command(name="pride-support")
@app_commands.describe(type="The type of support your are looking for")
async def pride_support(
Expand All @@ -42,6 +23,7 @@ async def pride_support(
"""Get support as a person of the LGBTQ+ community"""
title = f"Support for {type}"
description = ""
footer = "Keep in mind to conduct your own research from reputable sources!"
if type == "HRT":
description = """
Keep in mind that if you're a minor (-17) you will need a parental consent for Hormone Replacement Therapy (HRT)
Expand All @@ -52,6 +34,7 @@ async def pride_support(
Cleveland Clinic - [Link](https://my.clevelandclinic.org/health/treatments/21653-feminizing-hormone-therapy)
Mayo Clinic - [Link](https://www.mayoclinic.org/tests-procedures/masculinizing-hormone-therapy/about/pac-20385099)
NCBI - [Link](https://www.ncbi.nlm.nih.gov/pmc/articles/PMC5182227/)
UCSF Transgender Care - [Link](https://transcare.ucsf.edu/hormone-therapy)
"""
elif type == "Therapy":
description = """
Expand Down Expand Up @@ -87,6 +70,7 @@ async def pride_support(
embed = Embed()
embed.title = title
embed.description = description
embed.set_footer(text=footer)
await interaction.response.send_message(embed=embed)


Expand Down
1 change: 0 additions & 1 deletion bot/libs/cog_utils/blacklist/__init__.py

This file was deleted.

13 changes: 0 additions & 13 deletions bot/libs/cog_utils/blacklist/utils.py

This file was deleted.

17 changes: 7 additions & 10 deletions bot/libs/ui/blacklist/pages.py
Original file line number Diff line number Diff line change
@@ -1,18 +1,15 @@
from typing import Dict, List

import discord
from libs.utils.pages import CatherinePages, SimplePageSource
from discord.ext import commands
from libs.utils.pages import CatherineContextPages, SimplePageSource

from .page_entries import BlacklistPageEntry


class BaseBlacklistPages(CatherinePages):
def __init__(
self, entries, *, interaction: discord.Interaction, per_page: int = 10
):
super().__init__(
SimplePageSource(entries, per_page=per_page), interaction=interaction
)
class BaseBlacklistPages(CatherineContextPages):
def __init__(self, entries, *, ctx: commands.Context, per_page: int = 10):
super().__init__(SimplePageSource(entries, per_page=per_page), ctx=ctx)
self.embed = discord.Embed(
title="Blacklist List", colour=discord.Colour.from_rgb(255, 176, 241)
)
Expand All @@ -23,8 +20,8 @@ def __init__(
self,
entries: List[Dict[int, bool]],
*,
interaction: discord.Interaction,
ctx: commands.Context,
per_page: int = 10
):
converted = [BlacklistPageEntry(entry) for entry in entries]
super().__init__(converted, per_page=per_page, interaction=interaction)
super().__init__(converted, per_page=per_page, ctx=ctx)
1 change: 1 addition & 0 deletions bot/libs/utils/pages/__init__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
from .base_pages import SimplePages as SimplePages
from .context_paginator import CatherineContextPages as CatherineContextPages
from .paginator import CatherinePages as CatherinePages
from .sources import (
EmbedListSource as EmbedListSource,
Expand Down
Loading

0 comments on commit 6748970

Please sign in to comment.