1
Fork 0
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:
Scott 2023-12-26 14:39:12 -05:00
commit a54bb228a3
10 changed files with 325 additions and 42 deletions

2
.gitignore vendored
View file

@ -8,7 +8,6 @@ __pycache__/
# Distribution / packaging # Distribution / packaging
.Python .Python
build/
develop-eggs/ develop-eggs/
dist/ dist/
downloads/ downloads/
@ -24,6 +23,7 @@ share/python-wheels/
*.egg-info/ *.egg-info/
.installed.cfg .installed.cfg
*.egg *.egg
*.pyc
MANIFEST MANIFEST
# PyInstaller # PyInstaller

View file

@ -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())

View file

View file

@ -1,33 +1,28 @@
from discord.ext import commands from discord.ext import commands
import os import os
from tux_utils.tux_logger import TuxLogger
import logging import logging
logger = TuxLogger(__name__)
class EventHandler(commands.Cog): class EventHandler(commands.Cog):
def __init__(self, bot, debug=False): def __init__(self, bot, debug=False):
""" """
Constructor for the EventHandler Cog. Constructor for the EventHandler Cog.
:param bot: The instance of the Discord bot. Parameters:
:param debug: A flag indicating whether debug mode is enabled. bot (commands.Bot): The instance of the Discord bot.
debug (bool): A flag indicating whether debug mode is enabled.
""" """
self.bot = bot self.bot = bot
self.debug = debug self.debug = debug
self._setup_logging() self.ignore_cogs = []
self._load_events() if debug:
logger.setLevel(logging.DEBUG)
def _setup_logging(self): async def _load_events(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):
""" """
Dynamically loads event modules from the 'events' directory. 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') events_dir = os.path.join(os.path.dirname(__file__), 'events')
for filename in os.listdir(events_dir): for filename in os.listdir(events_dir):
if filename.endswith('.py') and not filename.startswith('__'): event_name = filename[:-3]
event_name = filename[:-3] module = f'tux_events.events.{event_name}'
module = f'src.events.{event_name}'
try: if not filename.endswith('.py') or event_name in self.ignore_cogs \
self.bot.load_extension(module) or filename.startswith('__'):
logging.debug(f'Successfully loaded event: {module}') logger.info(f"Skipping {module}.", __name__)
except Exception as e: continue
logging.error(f'Failed to load event {module}. Error: {e}')
@commands.Cog.listener() try:
async def on_ready(self): 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!') cog = cls(bot, debug)
await cog._load_events()
await bot.add_cog(cog)
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))

View 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))

View file

View 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))

View 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))

View file

@ -14,5 +14,5 @@ class OnMessage(commands.Cog):
await message.channel.send('Hello!') await message.channel.send('Hello!')
def setup(bot): async def setup(bot):
bot.add_cog(OnMessage(bot)) await bot.add_cog(OnMessage(bot))

137
tux/tux_utils/tux_logger.py Normal file
View 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)