mirror of
https://github.com/allthingslinux/tux.git
synced 2024-10-03 00:53:12 +00:00
Merge branch 'EventBranch' of github.com:allthingslinux/tux into EventBranch
This commit is contained in:
commit
a54bb228a3
10 changed files with 325 additions and 42 deletions
2
.gitignore
vendored
2
.gitignore
vendored
|
@ -8,7 +8,6 @@ __pycache__/
|
|||
|
||||
# Distribution / packaging
|
||||
.Python
|
||||
build/
|
||||
develop-eggs/
|
||||
dist/
|
||||
downloads/
|
||||
|
@ -24,6 +23,7 @@ share/python-wheels/
|
|||
*.egg-info/
|
||||
.installed.cfg
|
||||
*.egg
|
||||
*.pyc
|
||||
MANIFEST
|
||||
|
||||
# PyInstaller
|
||||
|
|
36
tux/main.py
36
tux/main.py
|
@ -0,0 +1,36 @@
|
|||
import discord
|
||||
from discord.ext import commands
|
||||
from tux_events.event_handler import EventHandler
|
||||
import asyncio
|
||||
import logging
|
||||
from tux_utils.tux_logger import setup, TuxLogger
|
||||
|
||||
logger = TuxLogger(__name__)
|
||||
|
||||
bot_prefix = '!'
|
||||
intents = discord.Intents.all()
|
||||
bot = commands.Bot(command_prefix=bot_prefix, intents=intents)
|
||||
|
||||
asyncio.run(setup(bot, project_logging_level=logging.DEBUG, discord_logging_level=logging.WARNING))
|
||||
event_handler = EventHandler(bot, True)
|
||||
|
||||
|
||||
async def main():
|
||||
async with bot:
|
||||
logger.debug("Setting up event handler...")
|
||||
await event_handler.setup(bot, True)
|
||||
logger.debug("Event handler setup completed.")
|
||||
|
||||
await bot.start(
|
||||
'MTE4MjE5NDU4NTY5OTYzMTEzNA.GUaYP5.qbUQSLvBYzZ6TsXP_P3Qx1RZiobPrCDgF3NWpQ',
|
||||
reconnect=True
|
||||
)
|
||||
|
||||
@commands.Cog.listener()
|
||||
async def on_ready(self):
|
||||
"""
|
||||
This function is called when the bot successfully connects to Discord.
|
||||
"""
|
||||
logger.info(f'{self.bot.user} has connected to Discord!', __name__)
|
||||
|
||||
asyncio.run(main())
|
0
tux/tux_events/__init__.py
Normal file
0
tux/tux_events/__init__.py
Normal file
|
@ -1,33 +1,28 @@
|
|||
from discord.ext import commands
|
||||
import os
|
||||
from tux_utils.tux_logger import TuxLogger
|
||||
import logging
|
||||
|
||||
|
||||
logger = TuxLogger(__name__)
|
||||
|
||||
|
||||
class EventHandler(commands.Cog):
|
||||
def __init__(self, bot, debug=False):
|
||||
"""
|
||||
Constructor for the EventHandler Cog.
|
||||
|
||||
:param bot: The instance of the Discord bot.
|
||||
:param debug: A flag indicating whether debug mode is enabled.
|
||||
Parameters:
|
||||
bot (commands.Bot): The instance of the Discord bot.
|
||||
debug (bool): A flag indicating whether debug mode is enabled.
|
||||
"""
|
||||
self.bot = bot
|
||||
self.debug = debug
|
||||
self._setup_logging()
|
||||
self._load_events()
|
||||
self.ignore_cogs = []
|
||||
if debug:
|
||||
logger.setLevel(logging.DEBUG)
|
||||
|
||||
def _setup_logging(self):
|
||||
"""
|
||||
Configures logging settings based on the debug flag.
|
||||
"""
|
||||
logging_level = logging.DEBUG if self.debug else logging.INFO
|
||||
logging.basicConfig(
|
||||
level=logging_level,
|
||||
format='%(asctime)s [%(levelname)s] %(message)s',
|
||||
datefmt='%Y-%m-%d %H:%M:%S'
|
||||
)
|
||||
|
||||
def _load_events(self):
|
||||
async def _load_events(self):
|
||||
"""
|
||||
Dynamically loads event modules from the 'events' directory.
|
||||
|
||||
|
@ -37,31 +32,29 @@ class EventHandler(commands.Cog):
|
|||
events_dir = os.path.join(os.path.dirname(__file__), 'events')
|
||||
|
||||
for filename in os.listdir(events_dir):
|
||||
if filename.endswith('.py') and not filename.startswith('__'):
|
||||
event_name = filename[:-3]
|
||||
module = f'src.events.{event_name}'
|
||||
event_name = filename[:-3]
|
||||
module = f'tux_events.events.{event_name}'
|
||||
|
||||
try:
|
||||
self.bot.load_extension(module)
|
||||
logging.debug(f'Successfully loaded event: {module}')
|
||||
except Exception as e:
|
||||
logging.error(f'Failed to load event {module}. Error: {e}')
|
||||
if not filename.endswith('.py') or event_name in self.ignore_cogs \
|
||||
or filename.startswith('__'):
|
||||
logger.info(f"Skipping {module}.", __name__)
|
||||
continue
|
||||
|
||||
@commands.Cog.listener()
|
||||
async def on_ready(self):
|
||||
try:
|
||||
await self.bot.load_extension(module)
|
||||
logger.debug(f'Successfully loaded event: {module}', __name__)
|
||||
except Exception as e:
|
||||
logger.error(f'Failed to load event {module}. Error: {e}', __name__)
|
||||
|
||||
@classmethod
|
||||
async def setup(cls, bot, debug=False):
|
||||
"""
|
||||
Event handler for the bot being ready.
|
||||
Sets up the EventHandler Cog and adds it to the bot.
|
||||
|
||||
This function is called when the bot successfully connects to Discord.
|
||||
Parameters:
|
||||
bot (commands.Bot): The instance of the Discord bot.
|
||||
debug (bool): A flag indicating whether debug mode is enabled.
|
||||
"""
|
||||
logging.info(f'{self.bot.user} has connected to Discord!')
|
||||
|
||||
|
||||
def setup(bot, debug=False):
|
||||
"""
|
||||
Sets up the EventHandler Cog and adds it to the bot.
|
||||
|
||||
:param bot: The instance of the Discord bot.
|
||||
:param debug: A flag indicating whether debug mode is enabled.
|
||||
"""
|
||||
bot.add_cog(EventHandler(bot, debug))
|
||||
cog = cls(bot, debug)
|
||||
await cog._load_events()
|
||||
await bot.add_cog(cog)
|
||||
|
|
46
tux/tux_events/events/__event_template__.py
Normal file
46
tux/tux_events/events/__event_template__.py
Normal file
|
@ -0,0 +1,46 @@
|
|||
from discord.ext import commands
|
||||
|
||||
|
||||
class CogTemplate(commands.Cog):
|
||||
def __init__(self, bot):
|
||||
self.bot = bot
|
||||
|
||||
@commands.command(name='hello', help='Responds with a greeting.')
|
||||
async def hello(self, ctx):
|
||||
"""
|
||||
An example hello world command.
|
||||
|
||||
Parameters:
|
||||
- ctx (commands.Context): The context of the command.
|
||||
|
||||
Example usage:
|
||||
!hello
|
||||
"""
|
||||
await ctx.send('world!')
|
||||
|
||||
@commands.Cog.listener()
|
||||
async def on_message(self, message):
|
||||
"""
|
||||
An event listener that triggers when a message is sent. You can find a
|
||||
list of these at
|
||||
https://discordpy.readthedocs.io/en/latest/api.html#event-reference
|
||||
|
||||
Parameters:
|
||||
- message (discord.Message): The message object.
|
||||
|
||||
Notes:
|
||||
- This example function will be called every time a message is sent in
|
||||
any channel.
|
||||
"""
|
||||
# Avoid responding to your own messages
|
||||
if message.author == self.bot.user:
|
||||
return
|
||||
|
||||
# Respond to a specific message content
|
||||
if message.content.lower() == 'ping':
|
||||
await message.channel.send('Pong!')
|
||||
|
||||
|
||||
# Define the setup function that will be called when loading the cog
|
||||
def setup(bot):
|
||||
bot.add_cog(CogTemplate(bot))
|
0
tux/tux_events/events/__init__.py
Normal file
0
tux/tux_events/events/__init__.py
Normal file
56
tux/tux_events/events/bans.py
Normal file
56
tux/tux_events/events/bans.py
Normal file
|
@ -0,0 +1,56 @@
|
|||
import logging
|
||||
from discord.ext import commands
|
||||
from tux_utils.tux_logger import TuxLogger
|
||||
|
||||
logger = TuxLogger(__name__)
|
||||
|
||||
|
||||
class BanCog(commands.Cog):
|
||||
def __init__(self, bot):
|
||||
self.bot = bot
|
||||
|
||||
@commands.command(name='tban')
|
||||
async def temp_ban(self,
|
||||
ctx,
|
||||
user: commands.MemberConverter,
|
||||
duration: int,
|
||||
reason: str):
|
||||
"""
|
||||
Temporarily ban a user.
|
||||
Example: !tban @user 7 Violating rules
|
||||
"""
|
||||
await ctx.guild.ban(user, reason=reason)
|
||||
logger.info(f"Temporarily banned {user} for {duration} days. Reason: {reason}")
|
||||
|
||||
@commands.command(name='qban')
|
||||
async def quick_ban(self,
|
||||
ctx,
|
||||
user: commands.MemberConverter):
|
||||
"""
|
||||
Quickly ban a user.
|
||||
Example: !qban @user
|
||||
"""
|
||||
await ctx.guild.ban(user)
|
||||
logger.info(f"Quickly banned {user}")
|
||||
|
||||
@commands.command(name='ban')
|
||||
async def perm_ban(self,
|
||||
ctx,
|
||||
user: commands.MemberConverter,
|
||||
reason: str):
|
||||
"""
|
||||
Permanently ban a user.
|
||||
Example: !ban @user Violating rules
|
||||
"""
|
||||
await ctx.guild.ban(
|
||||
user,
|
||||
reason=reason,
|
||||
delete_message_days=0
|
||||
)
|
||||
logger.info(f"Permanently banned {user}. Reason: {reason}")
|
||||
|
||||
|
||||
async def setup(bot, debug=False):
|
||||
if debug:
|
||||
logger.setLevel(logging.DEBUG)
|
||||
await bot.add_cog(BanCog(bot))
|
15
tux/tux_events/events/on_join.py
Normal file
15
tux/tux_events/events/on_join.py
Normal file
|
@ -0,0 +1,15 @@
|
|||
from discord.ext import commands
|
||||
|
||||
|
||||
class OnJoin(commands.Cog):
|
||||
def __init__(self, bot):
|
||||
self.bot = bot
|
||||
|
||||
@commands.Cog.listener()
|
||||
async def on_member_join(self, member):
|
||||
# Your on_join logic goes here
|
||||
print(f'{member} has joined the server.')
|
||||
|
||||
|
||||
async def setup(bot):
|
||||
await bot.add_cog(OnJoin(bot))
|
|
@ -14,5 +14,5 @@ class OnMessage(commands.Cog):
|
|||
await message.channel.send('Hello!')
|
||||
|
||||
|
||||
def setup(bot):
|
||||
bot.add_cog(OnMessage(bot))
|
||||
async def setup(bot):
|
||||
await bot.add_cog(OnMessage(bot))
|
||||
|
|
137
tux/tux_utils/tux_logger.py
Normal file
137
tux/tux_utils/tux_logger.py
Normal file
|
@ -0,0 +1,137 @@
|
|||
import os
|
||||
import logging
|
||||
import colorlog
|
||||
from discord.ext import commands
|
||||
|
||||
# ==================
|
||||
# Usage Instructions
|
||||
# ==================
|
||||
# Hey contributor, Ty here! To use the logger in your cog files, please follow these steps:
|
||||
|
||||
# 1. Import the logger by adding the following line at the top of your main bot file:
|
||||
# from your_module_name import logger
|
||||
|
||||
# 2. Once imported, you can use the logger to log messages in your code. For example:
|
||||
# logger.info("This is an information message.")
|
||||
# logger.warning("This is a warning message.")
|
||||
# logger.error("This is an error message.")
|
||||
# logger.debug("This is a debug message.")
|
||||
|
||||
# I love you all and thank you for contributing <3
|
||||
# =========================
|
||||
# End of Usage Instructions
|
||||
# =========================
|
||||
|
||||
|
||||
class TuxLogger(logging.Logger):
|
||||
def __init__(self,
|
||||
name,
|
||||
project_logging_level=logging.INFO):
|
||||
"""
|
||||
Constructor for the custom logger class.
|
||||
|
||||
Parameters:
|
||||
- name: The name of the logger.
|
||||
- project_logging_level: The logging level for the project (default is INFO).
|
||||
"""
|
||||
super().__init__(name, level=project_logging_level)
|
||||
self._setup_logging()
|
||||
|
||||
def _setup_logging(self):
|
||||
"""
|
||||
Set up the logging configuration for the custom logger.
|
||||
"""
|
||||
log_format = '%(asctime)s [%(log_color)s%(levelname)s%(reset)s] [%(name)s]: %(message)s'
|
||||
log_dir = 'logs'
|
||||
os.makedirs(log_dir, exist_ok=True)
|
||||
|
||||
handler = colorlog.StreamHandler()
|
||||
handler.setFormatter(colorlog.ColoredFormatter(log_format))
|
||||
self.addHandler(handler)
|
||||
|
||||
file_handler = logging.FileHandler(
|
||||
os.path.join(log_dir, 'bot.log'),
|
||||
mode='a'
|
||||
)
|
||||
file_handler.setFormatter(logging.Formatter(
|
||||
'%(asctime)s [%(levelname)s] [%(name)s]: %(message)s'))
|
||||
self.addHandler(file_handler)
|
||||
|
||||
def _log_to_file(self, level, message, caller_module):
|
||||
"""
|
||||
Log a message to a specific file.
|
||||
|
||||
Parameters:
|
||||
- level: The logging level (e.g., logging.DEBUG, logging.INFO, etc.).
|
||||
- message: The log message.
|
||||
- filename: The name of the file to log to.
|
||||
"""
|
||||
|
||||
file_handler = logging.FileHandler(
|
||||
os.path.join('logs', f"{caller_module}.log"),
|
||||
mode='a'
|
||||
)
|
||||
file_handler.setFormatter(
|
||||
logging.Formatter(
|
||||
f'%(asctime)s [%(levelname)s] [{caller_module}]: %(message)s'
|
||||
)
|
||||
)
|
||||
self.addHandler(file_handler)
|
||||
self.log(level, message)
|
||||
self.removeHandler(file_handler)
|
||||
|
||||
def debug(self, message, filename="unknown"):
|
||||
self._log_to_file(logging.DEBUG, message, filename)
|
||||
|
||||
def info(self, message, filename="unknown"):
|
||||
self._log_to_file(logging.INFO, message, filename)
|
||||
|
||||
def warning(self, message, filename="unknown"):
|
||||
self._log_to_file(logging.WARNING, message, filename)
|
||||
|
||||
def error(self, message, filename="unknown"):
|
||||
self._log_to_file(logging.ERROR, message, filename)
|
||||
|
||||
def critical(self, message, filename="unknown"):
|
||||
self._log_to_file(logging.CRITICAL, message, filename)
|
||||
|
||||
|
||||
class LoggingCog(commands.Cog):
|
||||
def __init__(self,
|
||||
bot,
|
||||
discord_logging_level=logging.WARNING):
|
||||
"""
|
||||
Constructor for the LoggingCog class.
|
||||
|
||||
Parameters:
|
||||
- bot: The Discord bot instance.
|
||||
- discord_logging_level: The logging level for the Discord library (default is WARNING).
|
||||
"""
|
||||
self.bot = bot
|
||||
self.discord_logging_level = discord_logging_level
|
||||
|
||||
discord_logger = logging.getLogger('discord')
|
||||
discord_logger.setLevel(self.discord_logging_level)
|
||||
|
||||
|
||||
logger = TuxLogger(__name__)
|
||||
|
||||
|
||||
async def setup(bot,
|
||||
project_logging_level=logging.DEBUG,
|
||||
discord_logging_level=logging.WARNING):
|
||||
"""
|
||||
Asynchronous function to set up the LoggingCog and add it to the Discord bot.
|
||||
|
||||
Parameters:
|
||||
- bot: The Discord bot instance.
|
||||
- project_logging_level: The logging level for the project (default is DEBUG).
|
||||
- discord_logging_level: The logging level for the Discord library (default is WARNING).
|
||||
"""
|
||||
global logger
|
||||
log_cog = LoggingCog(
|
||||
bot,
|
||||
discord_logging_level
|
||||
)
|
||||
logger.setLevel(project_logging_level)
|
||||
await bot.add_cog(log_cog)
|
Loading…
Reference in a new issue