1
Fork 0
mirror of https://github.com/allthingslinux/tux.git synced 2024-10-03 00:53:12 +00:00

[Fix/Add] Events directory, examples directory, event template

This commit is contained in:
kaizen 2023-12-30 02:20:20 -05:00
parent 2b47382862
commit 8d1ca05c42
9 changed files with 75 additions and 159 deletions

View file

@ -0,0 +1,65 @@
"""
Discord Bot Event Handler Template
This example contains a template for creating new event handlers for Tux. It is designed to be have a
familiar and straightforward command structure, with each event being able to have its own function.
Link to discord.py event reference:
https://discordpy.readthedocs.io/en/latest/api.html#event-reference
To use this template, replace `EventName` with the name of your event handler class.
Replace `@commands.command` sections and their respective functions with the commands you
wish to create. Refer to the given 'hello' command as an example.
For each command, ensure that you have:
1. A name parameter that defines the command's call sign (i.e., the string that must be typed
out to call the command).
2. A help parameter that succinctly but clearly describes what the command does. This
description will be displayed in the bot's help command.
3. Refer to the given 'on_message' listener as an example for creating event listeners.
4. Remember to properly use the TuxLogger for outputting events to console and files. 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.")
After defining the event handler functions in the EventName class and the setup function,
replace this block comment with a description of what your particular event is meant to do.
Happy Coding!
"""
import logging
from discord.ext import commands
from utils._tux_logger import TuxLogger
logger = TuxLogger(__name__)
class EventName(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.Cog.listener()
async def on_message(self, message):
"""
An event listener that triggers when a message is sent.
Parameters:
- message (discord.Message): The message object.
Notes:
- This 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
if message.content.lower() == 'ping':
logger.debug("Ping message detected.")
await message.channel.send('Pong!')
logger.info("Pong message sent.")
# The setup function that'll be called when loading the cog
async def setup(bot):
logger.debug("Setting up...")
await bot.add_cog(EventName(bot))
logger.info("Setup completed successfully.")

View file

@ -57,7 +57,7 @@ class CogLoader(commands.Cog):
debug (bool): A flag indicating whether debug mode is enabled.
"""
cog = cls(bot, debug)
# await cog.load_cogs_from_folder('events')
await cog.load_cogs_from_folder('events')
await cog.load_cogs_from_folder("utils")
await cog.load_cogs_from_folder("commands")
await bot.add_cog(cog)

View file

@ -1,62 +0,0 @@
import logging
import os
from discord.ext import commands
from tux_utils.tux_logger import TuxLogger
logger = TuxLogger(__name__)
class EventHandler(commands.Cog):
def __init__(self, bot, debug=False):
"""Constructor for the EventHandler Cog.
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.ignore_cogs = []
if debug:
logger.setLevel(logging.DEBUG)
async def _load_events(self):
"""Dynamically loads event modules from the 'events' directory.
Each event module should be a Python file in the 'events' directory.
The file name (excluding extension) is considered the event name.
"""
events_dir = os.path.join(os.path.dirname(__file__), "events")
for filename in os.listdir(events_dir):
event_name = filename[:-3]
module = f"tux_events.events.{event_name}"
if (
not filename.endswith(".py")
or event_name in self.ignore_cogs
or filename.startswith("__")
):
logger.info(f"Skipping {module}.", __name__)
continue
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):
"""Sets up the EventHandler Cog and adds it to the bot.
Parameters
----------
bot (commands.Bot): The instance of the Discord bot.
debug (bool): A flag indicating whether debug mode is enabled.
"""
cog = cls(bot, debug)
await cog._load_events()
await bot.add_cog(cog)

View file

@ -1,47 +0,0 @@
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

@ -1,47 +0,0 @@
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

@ -1,5 +1,10 @@
from discord.ext import commands
# from discord.ext import commands
import logging
from discord.ext import commands
from utils._tux_logger import TuxLogger
logger = TuxLogger(__name__)
class OnMessage(commands.Cog):
def __init__(self, bot):
@ -15,4 +20,6 @@ class OnMessage(commands.Cog):
async def setup(bot):
await bot.add_cog(OnMessage(bot))
# cog = OnMessage(bot)
# logger.info(f"Setting up {cog.__class__.__name__}...")
await bot.add_cog(OnMessage(bot))