feat: Refactored all cogs implementation
Some checks failed
CI / Run tests (pull_request) Has been cancelled
Some checks failed
CI / Run tests (pull_request) Has been cancelled
This commit is contained in:
42
cogs/__init__.py
Normal file
42
cogs/__init__.py
Normal file
@@ -0,0 +1,42 @@
|
||||
import discord, json, csv
|
||||
from discord.ext import commands
|
||||
from typing import Union, Any, Optional, Callable
|
||||
from setup.config import Config
|
||||
|
||||
class BaseCog(commands.Cog):
|
||||
def __init__(self,bot:discord.Bot):
|
||||
self.bot = bot
|
||||
|
||||
class ConfigurableCog(BaseCog):
|
||||
def __init__(self, bot: discord.Bot):
|
||||
super().__init__(bot)
|
||||
|
||||
|
||||
class FeatureCog(BaseCog):
|
||||
"""Base Cog that provides per-guild feature flag checks.
|
||||
|
||||
Subclasses should set `feature_name` or pass it to the constructor.
|
||||
This class reads the feature flags from `Config.GUILD_CONFIGS[guild_id]["features"]`.
|
||||
"""
|
||||
|
||||
def __init__(self, bot: discord.Bot, feature_name: Optional[str] = None):
|
||||
super().__init__(bot)
|
||||
self.feature_name = feature_name
|
||||
|
||||
def is_enabled(self, guild_id: int) -> bool:
|
||||
if not self.feature_name:
|
||||
return False
|
||||
guild_cfg = Config.GUILD_CONFIGS.get(guild_id)
|
||||
if not guild_cfg:
|
||||
return False
|
||||
features = guild_cfg.get("features", {})
|
||||
return bool(features.get(self.feature_name, False))
|
||||
|
||||
def require_enabled_check(self) -> Callable[[commands.Context], bool]:
|
||||
def predicate(ctx: commands.Context) -> bool:
|
||||
if not ctx.guild:
|
||||
return False
|
||||
return self.is_enabled(ctx.guild.id)
|
||||
|
||||
return commands.check(predicate)
|
||||
|
||||
19
cogs/cs.py
19
cogs/cs.py
@@ -7,6 +7,7 @@ from discord.ext import commands, tasks, bridge
|
||||
from setup.logger import LOGGER
|
||||
from setup.config import Config
|
||||
from models.cs_models import *
|
||||
from cogs import FeatureCog
|
||||
|
||||
BASE_URL = "https://www.hltv.org"
|
||||
|
||||
@@ -24,12 +25,20 @@ OLD_MATCH_DURATION = 3600 * 24 * 2
|
||||
EMOJI_CREATE_EVENT = "✅" # Create guild event for the match
|
||||
EMOJI_REMOVE_EVENT = "❌" # Remove guild event for the match
|
||||
|
||||
class CSCog(commands.Cog):
|
||||
def __init__(self, bot:discord.Bot):
|
||||
self.bot = bot
|
||||
self.matches:list[Match] = []
|
||||
class CSCog(FeatureCog):
|
||||
def __init__(self, bot: discord.Bot):
|
||||
super().__init__(bot, feature_name="cs")
|
||||
self.matches: list[Match] = []
|
||||
self.message_match_map = {} # Maps message IDs to Match objects
|
||||
self.get_matches.start()
|
||||
|
||||
# Start scraping loop only if at least one guild enabled CS feature
|
||||
try:
|
||||
enabled_any = any(cfg.get("features", {}).get("cs") for cfg in Config.GUILD_CONFIGS.values())
|
||||
except Exception:
|
||||
enabled_any = False
|
||||
|
||||
if enabled_any:
|
||||
self.get_matches.start()
|
||||
|
||||
def is_up_to_date(self) -> bool:
|
||||
"""Check if PAGE_FILE and MATCHES_FILE are up to date."""
|
||||
|
||||
@@ -1,32 +1,76 @@
|
||||
import discord, json, os, random, re
|
||||
import collections
|
||||
import discord, random, re
|
||||
from discord.ext import commands
|
||||
from setup.logger import LOGGER
|
||||
from setup.config import Config
|
||||
from cogs import FeatureCog
|
||||
|
||||
class InsultsCog(commands.Cog):
|
||||
def __init__(self, bot:discord.Bot):
|
||||
self.bot = bot
|
||||
class InsultsCog(FeatureCog):
|
||||
def __init__(self, bot: discord.Bot):
|
||||
super().__init__(bot, feature_name="insults")
|
||||
LOGGER.debug("InsultsCog initialized")
|
||||
|
||||
with open(os.path.join(Config.CONFIG_PATH, "insults.txt")) as f:
|
||||
self.insults = [l.strip() for l in f.readlines()]
|
||||
def reload_men_list(self):
|
||||
self.men: list[discord.Member] = []
|
||||
for guild in self.bot.guilds:
|
||||
for role in guild.roles:
|
||||
if role.name and re.match(r'^([hH]im|[hH]e).*$', role.name):
|
||||
self.men.extend(role.members)
|
||||
# dedupe by id
|
||||
self.men = list({m.id: m for m in self.men}.values())
|
||||
|
||||
@commands.Cog.listener()
|
||||
async def on_message(self, message:discord.Message):
|
||||
if len(message.content.split()) > 3:
|
||||
author = message.author
|
||||
if any(author.id == u.id for u in self.men):
|
||||
r = int(random.random()*100)
|
||||
print(r)
|
||||
if r < 5:
|
||||
insult = random.choice(self.insults)
|
||||
async def on_message(self, message: discord.Message):
|
||||
if not message.guild or message.author.bot:
|
||||
return
|
||||
|
||||
# only run if feature enabled for this guild
|
||||
if not self.is_enabled(message.guild.id):
|
||||
return
|
||||
|
||||
if len(message.content.split()) <= 3:
|
||||
return
|
||||
|
||||
author = message.author
|
||||
if not hasattr(self, 'men') or not self.men:
|
||||
self.reload_men_list()
|
||||
|
||||
if any(author.id == u.id for u in self.men):
|
||||
guild_cfg = Config.GUILD_CONFIGS.get(message.guild.id, {})
|
||||
insults_cfg = guild_cfg.get("configs", {}).get("insults", {})
|
||||
safeguard_patterns = insults_cfg.get("safeguard_patterns", [])
|
||||
safeguard_match = any(re.match(pattern, message.content) for pattern in safeguard_patterns)
|
||||
if safeguard_match:
|
||||
return
|
||||
|
||||
r = random.random() * 100
|
||||
exceptions = insults_cfg.get("exceptions", [])
|
||||
filtered = [ex for ex in exceptions if ex.get("user_id") == author.id]
|
||||
if filtered:
|
||||
try:
|
||||
r *= float(filtered[0].get("factor", 1))
|
||||
except Exception:
|
||||
pass
|
||||
if r < 5:
|
||||
insults = insults_cfg.get("insults", [])
|
||||
if insults:
|
||||
insult = random.choice(insults)
|
||||
await message.reply(insult)
|
||||
|
||||
@commands.Cog.listener()
|
||||
async def on_ready(self):
|
||||
self.men:list[discord.Member] = []
|
||||
for guild in self.bot.guilds:
|
||||
for role in guild.roles:
|
||||
if re.match(r'^([hH]im|[hH]e).*$',role.name):
|
||||
self.men.extend(role.members)
|
||||
self.men = list(set(self.men))
|
||||
self.reload_men_list()
|
||||
|
||||
@commands.Cog.listener()
|
||||
async def on_member_update(self, before: discord.Member, after: discord.Member):
|
||||
before_roles = set(before.roles)
|
||||
after_roles = set(after.roles)
|
||||
removed = before_roles.difference(after_roles)
|
||||
added = after_roles.difference(before_roles)
|
||||
role = None
|
||||
if removed:
|
||||
role = list(removed).pop()
|
||||
elif added:
|
||||
role = list(added).pop()
|
||||
|
||||
if role and re.match(r'^([hH]im|[hH]e).*$', role.name):
|
||||
self.reload_men_list()
|
||||
55
cogs/intern.py
Normal file
55
cogs/intern.py
Normal file
@@ -0,0 +1,55 @@
|
||||
import random
|
||||
from discord.ext import commands
|
||||
|
||||
|
||||
class InternCog(commands.Cog):
|
||||
def __init__(self, bot=None):
|
||||
self.bot = bot
|
||||
# `data` expected to be a list of dicts with 'guild_id' and 'mentor_id'
|
||||
self.data = []
|
||||
self.connected_guild_ids = set()
|
||||
self.in_voice_channel = False
|
||||
|
||||
async def on_voice_state_update(self, member, before, after):
|
||||
# determine guild context
|
||||
guild = None
|
||||
if after and getattr(after, 'channel', None):
|
||||
guild = after.channel.guild
|
||||
elif before and getattr(before, 'channel', None):
|
||||
guild = before.channel.guild
|
||||
if not guild:
|
||||
return
|
||||
|
||||
# find matching mentor entry for this guild
|
||||
entry = None
|
||||
for e in getattr(self, 'data', []):
|
||||
if e.get('guild_id') == getattr(guild, 'id', None) and e.get('mentor_id') == getattr(member, 'id', None):
|
||||
entry = e
|
||||
break
|
||||
if not entry:
|
||||
return
|
||||
|
||||
# find existing voice client for this guild (if any)
|
||||
voice_client = None
|
||||
for vc in getattr(self.bot, 'voice_clients', []):
|
||||
if getattr(vc, 'guild', None) and getattr(vc.guild, 'id', None) == getattr(guild, 'id', None):
|
||||
voice_client = vc
|
||||
break
|
||||
|
||||
# mentor joined a channel (initial join)
|
||||
if (not before or not getattr(before, 'channel', None)) and after and getattr(after, 'channel', None):
|
||||
# if bot is not connected, connect with 25% chance
|
||||
if not voice_client:
|
||||
if random.random() < 0.25:
|
||||
await after.channel.connect()
|
||||
return
|
||||
|
||||
# mentor moved channels while bot is connected -> move bot
|
||||
if voice_client and after and getattr(after, 'channel', None):
|
||||
await voice_client.move_to(after.channel)
|
||||
return
|
||||
|
||||
# mentor left channel -> disconnect bot if connected
|
||||
if voice_client and (not after or not getattr(after, 'channel', None)):
|
||||
await voice_client.disconnect(force=True)
|
||||
return
|
||||
201
cogs/roles.py
201
cogs/roles.py
@@ -1,95 +1,146 @@
|
||||
import discord, os, json
|
||||
import discord
|
||||
from cogs import FeatureCog
|
||||
from discord import option
|
||||
from discord.ext import commands, bridge
|
||||
from setup.config import Config
|
||||
from setup.logger import LOGGER
|
||||
|
||||
CONFIG_FILE = os.path.join(Config.CONFIG_PATH,"roles.json")
|
||||
|
||||
class RolesCog(commands.Cog):
|
||||
def __init__(self,bot:discord.Bot):
|
||||
self.bot = bot
|
||||
self.load_config()
|
||||
|
||||
def load_config(self):
|
||||
with open(CONFIG_FILE) as file:
|
||||
self.config = json.load(file)
|
||||
|
||||
def save_config(self):
|
||||
with open(CONFIG_FILE,"w") as file:
|
||||
json.dump(self.config,file)
|
||||
class RolesCog(FeatureCog):
|
||||
def __init__(self, bot: discord.Bot):
|
||||
super().__init__(bot, feature_name="roles")
|
||||
|
||||
@bridge.bridge_command()
|
||||
async def roles(self,ctx: discord.ApplicationContext, category:bridge.BridgeOption(name="category",description="The category to manipulate", input_type=str,required=True)):
|
||||
filtered = [config_category for config_category in self.config if config_category["category_id"] == category]
|
||||
if len(filtered):
|
||||
await ctx.defer()
|
||||
config_category = filtered.pop()
|
||||
embed = discord.Embed(
|
||||
title=config_category["category_name"],
|
||||
description=config_category["message_header"],
|
||||
color=discord.Color.blue()
|
||||
)
|
||||
roles = [
|
||||
self.bot.get_guild(897157935006900254).get_role(role_config["role_id"])
|
||||
for role_config in config_category["roles"]
|
||||
]
|
||||
for role_instance,role_config in zip(roles,config_category["roles"]):
|
||||
embed.add_field(name=role_config["reaction"],value=role_instance.mention)
|
||||
message = await ctx.send(embed=embed)
|
||||
if message:
|
||||
config_category["message_id"] = message.id
|
||||
for config_role in config_category["roles"]:
|
||||
await message.add_reaction(config_role["reaction"])
|
||||
self.save_config()
|
||||
await ctx.followup.send("Role message generated",ephemeral=True)
|
||||
async def roles(self, ctx: discord.ApplicationContext, category: bridge.BridgeOption(name="category", description="The category to manipulate", input_type=str, required=True)):
|
||||
if not ctx.guild:
|
||||
await ctx.respond("This command must be used in a guild.", ephemeral=True)
|
||||
return
|
||||
|
||||
guild_id = ctx.guild.id
|
||||
if not self.is_enabled(guild_id):
|
||||
await ctx.respond("Roles feature is disabled for this guild.", ephemeral=True)
|
||||
return
|
||||
|
||||
guild_cfg = Config.GUILD_CONFIGS.get(guild_id)
|
||||
if not guild_cfg:
|
||||
await ctx.respond("No configuration for this guild.", ephemeral=True)
|
||||
return
|
||||
|
||||
categories = guild_cfg.get("configs", {}).get("roles", {}).get("categories", [])
|
||||
filtered = [c for c in categories if c.get("category_id") == category]
|
||||
if not filtered:
|
||||
await ctx.respond("Category not found.", ephemeral=True)
|
||||
return
|
||||
|
||||
await ctx.defer()
|
||||
config_category = filtered.pop()
|
||||
embed = discord.Embed(
|
||||
title=config_category.get("category_name", ""),
|
||||
description=config_category.get("message_header", ""),
|
||||
color=discord.Color.blue()
|
||||
)
|
||||
|
||||
roles_list = [
|
||||
ctx.guild.get_role(role_config.get("role_id"))
|
||||
for role_config in config_category.get("roles", [])
|
||||
]
|
||||
for role_instance, role_config in zip(roles_list, config_category.get("roles", [])):
|
||||
mention = role_instance.mention if role_instance else "(role missing)"
|
||||
embed.add_field(name=role_config.get("reaction", ""), value=mention)
|
||||
|
||||
message = await ctx.send(embed=embed)
|
||||
if message:
|
||||
config_category["message_id"] = message.id
|
||||
# persist the updated guild config
|
||||
Config.save_guild_config(guild_id)
|
||||
|
||||
for config_role in config_category.get("roles", []):
|
||||
reaction = config_role.get("reaction")
|
||||
if reaction:
|
||||
await message.add_reaction(reaction)
|
||||
|
||||
await ctx.followup.send("Role message generated", ephemeral=True)
|
||||
|
||||
@commands.Cog.listener()
|
||||
async def on_raw_reaction_add(self, payload:discord.RawReactionActionEvent):
|
||||
async def on_raw_reaction_add(self, payload: discord.RawReactionActionEvent):
|
||||
if payload.user_id == self.bot.user.id:
|
||||
return
|
||||
|
||||
message_id = payload.message_id
|
||||
filtered = [config_category for config_category in self.config if config_category["message_id"] == message_id]
|
||||
if len(filtered):
|
||||
config_category = filtered.pop()
|
||||
role_ids = [config_role["role_id"] for config_role in config_category["roles"] if config_role["reaction"] == payload.emoji.name]
|
||||
if len(role_ids):
|
||||
role_id = role_ids.pop()
|
||||
guild_id = payload.guild_id
|
||||
guild_cfg = Config.GUILD_CONFIGS.get(guild_id)
|
||||
if not guild_cfg:
|
||||
return
|
||||
if not self.is_enabled(guild_id):
|
||||
return
|
||||
|
||||
guild = self.bot.get_guild(payload.guild_id)
|
||||
if guild:
|
||||
role = guild.get_role(role_id)
|
||||
if role:
|
||||
user = guild.get_member(payload.user_id)
|
||||
if user:
|
||||
if "parent_role_id" in config_category.keys():
|
||||
parent_role = guild.get_role(config_category["parent_role_id"])
|
||||
await user.add_roles(parent_role,role)
|
||||
else:
|
||||
await user.add_roles(role)
|
||||
categories = guild_cfg.get("configs", {}).get("roles", {}).get("categories", [])
|
||||
filtered = [c for c in categories if c.get("message_id") == payload.message_id]
|
||||
if not filtered:
|
||||
return
|
||||
|
||||
config_category = filtered.pop()
|
||||
role_ids = [config_role.get("role_id") for config_role in config_category.get("roles", []) if config_role.get("reaction") == payload.emoji.name]
|
||||
if not role_ids:
|
||||
return
|
||||
|
||||
role_id = role_ids.pop()
|
||||
guild = self.bot.get_guild(guild_id)
|
||||
if not guild:
|
||||
return
|
||||
role = guild.get_role(role_id)
|
||||
if not role:
|
||||
return
|
||||
|
||||
user = guild.get_member(payload.user_id)
|
||||
if not user:
|
||||
return
|
||||
|
||||
if "parent_role_id" in config_category:
|
||||
parent_role = guild.get_role(config_category.get("parent_role_id"))
|
||||
if parent_role:
|
||||
await user.add_roles(parent_role, role)
|
||||
return
|
||||
|
||||
await user.add_roles(role)
|
||||
|
||||
@commands.Cog.listener()
|
||||
async def on_raw_reaction_remove(self, payload:discord.RawReactionActionEvent):
|
||||
async def on_raw_reaction_remove(self, payload: discord.RawReactionActionEvent):
|
||||
if payload.user_id == self.bot.user.id:
|
||||
return
|
||||
|
||||
message_id = payload.message_id
|
||||
filtered = [config_category for config_category in self.config if config_category["message_id"] == message_id]
|
||||
if len(filtered):
|
||||
config_category = filtered.pop()
|
||||
role_ids = [config_role["role_id"] for config_role in config_category["roles"] if config_role["reaction"] == payload.emoji.name]
|
||||
if len(role_ids):
|
||||
role_id = role_ids.pop()
|
||||
guild_id = payload.guild_id
|
||||
guild_cfg = Config.GUILD_CONFIGS.get(guild_id)
|
||||
if not guild_cfg:
|
||||
return
|
||||
if not self.is_enabled(guild_id):
|
||||
return
|
||||
|
||||
guild = self.bot.get_guild(payload.guild_id)
|
||||
if guild:
|
||||
role = guild.get_role(role_id)
|
||||
if role:
|
||||
user = guild.get_member(payload.user_id)
|
||||
if user:
|
||||
if "parent_role_id" in config_category.keys():
|
||||
parent_role = guild.get_role(config_category["parent_role_id"])
|
||||
await user.remove_roles(parent_role,role)
|
||||
else:
|
||||
await user.remove_roles(role)
|
||||
categories = guild_cfg.get("configs", {}).get("roles", {}).get("categories", [])
|
||||
filtered = [c for c in categories if c.get("message_id") == payload.message_id]
|
||||
if not filtered:
|
||||
return
|
||||
|
||||
config_category = filtered.pop()
|
||||
role_ids = [config_role.get("role_id") for config_role in config_category.get("roles", []) if config_role.get("reaction") == payload.emoji.name]
|
||||
if not role_ids:
|
||||
return
|
||||
|
||||
role_id = role_ids.pop()
|
||||
guild = self.bot.get_guild(guild_id)
|
||||
if not guild:
|
||||
return
|
||||
role = guild.get_role(role_id)
|
||||
if not role:
|
||||
return
|
||||
|
||||
user = guild.get_member(payload.user_id)
|
||||
if not user:
|
||||
return
|
||||
|
||||
if "parent_role_id" in config_category:
|
||||
parent_role = guild.get_role(config_category.get("parent_role_id"))
|
||||
if parent_role:
|
||||
await user.remove_roles(parent_role, role)
|
||||
return
|
||||
|
||||
await user.remove_roles(role)
|
||||
@@ -5,11 +5,12 @@ import random
|
||||
import discord
|
||||
from discord import option
|
||||
from discord.ext import commands
|
||||
from cogs import FeatureCog
|
||||
|
||||
|
||||
class RouletteCog(commands.Cog):
|
||||
class RouletteCog(FeatureCog):
|
||||
def __init__(self, bot: discord.Bot):
|
||||
self.bot = bot
|
||||
super().__init__(bot, feature_name="roulette")
|
||||
self.cooldown = 60 * 3
|
||||
self.active_games = {}
|
||||
|
||||
@@ -155,6 +156,10 @@ class RouletteCog(commands.Cog):
|
||||
ctx: discord.ApplicationContext,
|
||||
target: discord.Member,
|
||||
):
|
||||
# ensure feature enabled for this guild
|
||||
if not ctx.guild or not self.is_enabled(ctx.guild.id):
|
||||
await ctx.respond("Roulette feature is disabled for this guild.", ephemeral=True)
|
||||
return
|
||||
author = ctx.author
|
||||
self_test = author.id == target.id
|
||||
|
||||
|
||||
Reference in New Issue
Block a user