Improved the API

This commit is contained in:
Darks 2020-11-11 13:46:05 +01:00
parent 8ca3e79327
commit b1eaa4ecd7
Signed by: Darks
GPG Key ID: 7515644268BE1433
3 changed files with 50 additions and 13 deletions

15
bot.py
View File

@ -2,6 +2,7 @@ import socket
from threading import Thread
from irc import IRC
from v5 import V5
from secrets import USER, PASSWORD
@ -9,9 +10,7 @@ class Bot(object):
def __init__(self, irc, v5, channels):
self.irc = IRC(*irc)
self.channels = channels
self._sock = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
self._v5_handler = Thread(target=self._handle_v5)
self._sock.bind(v5)
self.v5 = V5(v5, self.irc)
def start(self):
# Start IRC
@ -22,15 +21,7 @@ class Bot(object):
self.irc.join(c)
# Start v5 handler
self._v5_handler.start()
self.v5.start()
# Run IRC
self.irc.run()
def _handle_v5(self):
while True:
data, addr = self._sock.recvfrom(4096)
data = data.decode()
print(f"v5: Received <{data}>")
self.irc.send("#glados", data)

View File

@ -5,7 +5,6 @@ import time
from threading import Thread
from bot import Bot
from secrets import USER, PASSWORD
glados = Bot(
('irc.planet-casio.com', 6697),
@ -17,5 +16,9 @@ glados = Bot(
def say_hello(msg):
glados.irc.send(msg.to, f"Nice to see you, {msg.author}")
@glados.v5.on(lambda c, m: True)
def announce(channels, message):
for c in channels:
glados.irc.send(c, message)
glados.start()

43
v5.py Normal file
View File

@ -0,0 +1,43 @@
import socket
from threading import Thread
from functools import wraps
class V5(object):
def __init__(self, v5, irc):
""" Initialize v5 handle
:irc <IRC>: an initialized IRC object """
self.irc = irc
self._sock = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
self._sock.bind(v5)
self._handler = Thread(target=self._handle)
self._callbacks = []
def start(self):
# Start v5 handler
self._handler.start()
def on(self, event):
""" Adds a callback to the v5 handler
Event is a function taking in parameter a list of channels and a
string, and return True if the callback should be executed """
def callback(func):
@wraps(func)
def wrapper(channels, message):
func(channels, message)
self._callbacks.append((event, wrapper))
return wrapper
return callback
def _handle(self):
while True:
data, addr = self._sock.recvfrom(4096)
data = data.decode()
channels, message = data.split(":", 1)
channels = channels.split(" ")
for event, callback in self._callbacks:
if event(channels, message):
callback(channels, message)