Delete classes and add decorators

This commit is contained in:
Shadow15510 2023-06-11 18:25:08 +02:00
parent b0d6fbac85
commit a5f20b3113
4 changed files with 103 additions and 68 deletions

View File

@ -1,20 +1,46 @@
from irc_api import api
from random import choice
class GladosV4(api.CommandsPack):
@api.command(name="bye", event=lambda m: "au revoir glados" in m.text.lower())
def greetings_bye(self, msg):
"""Répond "au revoir"."""
self.bot.irc.send(msg.to, f"Au revoir {msg.author}")
@api.command(name="hello", event=lambda m: "bonjour glados" in m.text.lower())
def greetings_hello(self, msg):
"""Dit bonjour lorsque l'on salue le GLaDOS."""
self.bot.irc.send(msg.to, f"Bonjour {msg.author}")
@api.on(lambda m: "au revoir glados" in m.text.lower())
def greetings_bye(bot, msg):
bot.irc.send(msg.to, f"Au revoir {msg.author}")
class GladosV5(api.CommandsPack):
@api.command(name="test")
def test(self, msg):
"""Test de module de fonction."""
self.bot.irc.send(msg.to, "Ceci est un test")
@api.channel("#glados")
@api.on(
event=lambda m: "bonjour glados" in m.text.lower(),
desc="Réagis au 'bonjour glados' uniquement si le message est envoyé depuis le channel"\
"#glados."
)
def greetings_hello(bot, msg):
bot.irc.send(msg.to, f"Oh un utilisateur sur #glados :o")
@api.command("test")
def test(bot, msg):
"""Test de module de fonction."""
bot.irc.send(msg.to, "Ceci est un test")
@api.channel("#glados")
def react_on_glados(bot, msg):
"""Répond de manière random à tout les messages posté sur #glados."""
answers = (
f"Yo {msg.author} o/",
"Alors, de quoi on parle ?",
"Ça va ?",
"Bon, tu as fini de spammer ou bien ?",
"Ça roule ?",
"Hey you! Ah, you finally awake…",
)
bot.irc.send(msg.to, choice(answers))
commands = [
api.auto_help,
greetings_bye,
greetings_hello,
test,
react_on_glados
]

View File

@ -1,45 +1,65 @@
from functools import wraps
import logging
from secrets import USER, PASSWORD
from irc_api.irc import IRC
PREFIX = ""
def command(name, event=None):
"""Decorate a function and return a Command instance."""
def command(name, desc=""):
def decorator(func):
desc = name
if func.__doc__:
desc = func.__doc__
return Command(
name=name,
desc=desc,
func=func,
event=event
events=[lambda m: m.text.startswith(PREFIX + name)],
desc=desc
)
return decorator
class Command:
def __init__(self, name, desc, func, event=None):
self.name = name
self.desc = desc
self.func = func
if not event:
self.event = lambda m: m.text.startswith(PREFIX + name)
else:
self.event = event
def on(event, desc=""):
def decorator(func):
return Command(
name=func.__name__,
func=func,
events=[event],
desc=desc
)
return decorator
self.cmnd_pack = None
def channel(channel_name, desc=""):
def decorator(func_or_cmnd):
if isinstance(func_or_cmnd, Command):
func_or_cmnd.events.append(lambda m: m.to == channel_name)
return func_or_cmnd
else:
return Command(
name=func_or_cmnd.__name__,
func=func_or_cmnd,
events=[lambda m: m.to == channel_name],
desc=desc
)
return decorator
class Command:
def __init__(self, name, func, events, desc):
self.name = name
self.func = func
self.events = events
if desc:
self.desc = desc
else:
self.desc = "..."
if func.__doc__:
self.desc = func.__doc__
self.bot = None
def __call__(self, msg):
return self.func(self.cmnd_pack, msg)
class CommandsPack:
def __init__(self, bot):
self.bot = bot
return self.func(self.bot, msg)
class Bot:
@ -59,7 +79,7 @@ class Bot:
start : NoneType, public
Runs the bot and connects it to IRC and V5 servers.
"""
def __init__(self, irc_params: tuple, channels: list, prefix: str=""):
def __init__(self, auth: tuple, irc_params: tuple, channels: list, prefix: str=""):
"""Initialize the Bot instance.
Parameters
@ -74,13 +94,14 @@ class Bot:
global PREFIX
PREFIX = prefix
self.auth = auth
self.irc = IRC(*irc_params)
self.channels = channels
def start(self):
"""Starts the bot and connect it to the given IRC and V5 servers."""
# Start IRC
self.irc.start(USER, PASSWORD)
self.irc.start(self.auth[0], self.auth[1])
# Join channels
for channel in self.channels:
@ -89,16 +110,7 @@ class Bot:
# Run IRC
self.irc.run()
def add_help(self):
help_callback = Command(
"aide",
"Affiche la liste des commandes disponibles.",
help_cmnd
)
help_callback.cmnd_pack = self
self.irc.callbacks.append(help_callback)
def add_commands_pack(self, commands_pack):
def add_commands(self, commands):
"""Add a package of commands to the bot.
Parameters
@ -106,18 +118,14 @@ class Bot:
commands_pack : CommandsPack
A commands pack which contains command's instances.
"""
cmnd_pack = commands_pack(self)
for cmnd_name in dir(commands_pack):
if not cmnd_name.startswith("__") and not cmnd_name.endswith("__"):
cmnd = getattr(commands_pack, cmnd_name)
cmnd.cmnd_pack = cmnd_pack
self.irc.callbacks.append(cmnd)
for cmnd in commands:
cmnd.bot = self
self.irc.callbacks.append(cmnd)
def help_cmnd(bot, msg):
"""Documentation des fonctions disponibles."""
@command("aide")
def auto_help(bot, msg):
"""Aide des commandes disponibles."""
bot.irc.send(msg.to, f"Aide des commandes")
for cmnd in bot.irc.callbacks:
bot.irc.send(msg.to, f" {cmnd.name} : {cmnd.desc}")

View File

@ -109,7 +109,7 @@ class IRC:
logging.info("received %s", message)
if message is not None:
for callback in self.callbacks:
if callback.event(message):
if not False in [event(message) for event in callback.events]:
logging.info("matched %s", callback.name)
callback(message)

11
main.py
View File

@ -11,7 +11,10 @@ Create a bot's instance and manages it.
import logging
import re
from irc_api import api
from glados_cmnds import GladosV4, GladosV5
from glados_cmnds import commands
from secrets import USER, PASSWORD
LOG_FORMAT = "%(asctime)s [%(levelname)s] <%(filename)s> %(funcName)s: %(message)s"
@ -19,15 +22,13 @@ logging.basicConfig(format=LOG_FORMAT, level=logging.DEBUG)
glados = api.Bot(
(USER, PASSWORD),
('irc.planet-casio.com', 6697),
["#general", "#glados"],
"!"
)
glados.add_commands_pack(GladosV4)
glados.add_commands_pack(GladosV5)
glados.add_help()
glados.add_commands(commands)
glados.start()