GLaDOS/irc_api/api.py

132 lines
3.3 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import logging
from irc_api.irc import IRC
PREFIX = ""
def command(name, desc=""):
def decorator(func):
return Command(
name=name,
func=func,
events=[lambda m: m.text.startswith(PREFIX + name)],
desc=desc
)
return decorator
def on(event, desc=""):
def decorator(func):
return Command(
name=func.__name__,
func=func,
events=[event],
desc=desc
)
return decorator
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.bot, msg)
class Bot:
"""Run the connexion between IRC's server and V5 one.
Attributes
----------
irc : IRC, public
IRC wrapper which handle communication with IRC server.
v5 : V5, public
V5 wrapper which handle communication with V5 server.
channels : list, public
The channels the bot will listen.
Methods
-------
start : NoneType, public
Runs the bot and connects it to IRC and V5 servers.
"""
def __init__(self, auth: tuple, irc_params: tuple, channels: list, prefix: str=""):
"""Initialize the Bot instance.
Parameters
----------
irc_params : tuple
Contains the IRC server informations (host, port)
channels : list
Contains the names of the channels on which the bot will connect.
prefix : str, optionnal
The prefix on which the bot will react.
"""
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(self.auth[0], self.auth[1])
# Join channels
for channel in self.channels:
self.irc.join(channel)
# Run IRC
self.irc.run()
def add_commands(self, commands):
"""Add a package of commands to the bot.
Parameters
----------
commands_pack : CommandsPack
A commands pack which contains command's instances.
"""
for cmnd in commands:
cmnd.bot = self
self.irc.callbacks.append(cmnd)
@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}")