import json import requests as r import logging import time from functools import wraps from threading import Thread class Shoutbox(object): def __init__(self, cookies): self.channels = {'annonces': 0, 'projets': 0, 'hs': 0} self.cookies = cookies self._callbacks = [] for channel, last_id in self.channels.items(): messages = json.loads(r.get(f"https://www.planet-casio.com/Fr/shoutbox/api/read?since={last_id}&channel={channel}&format=text").text)['messages'] for m in messages: self.channels[channel] = m['id'] def run(self): def handler(): while True: for channel, last_id in self.channels.items(): messages = json.loads(r.get(f"https://www.planet-casio.com/Fr/shoutbox/api/read?since={last_id}&channel={channel}&format=text").text)['messages'] for m in messages: logging.debug(m) self.channels[channel] = m['id'] message = SBMessage(m, channel) for event, callback in self._callbacks: if event(message): logging.info(f"matched {event.__name__}") callback(message) time.sleep(1) Thread(target=handler).start() def on(self, event): """ Adds a callback to the IRC handler Event is a function taking in parameter a SBMessage and returning True if the callback should be executed on the message """ def callback(func): @wraps(func) def wrapper(message): func(message) self._callbacks.append((event, wrapper)) logging.info(f"added callback {func.__name__}") return wrapper return callback def post(self, user, msg, channel, users): if any(user in t for t in users): for i in users: if i[1] == user: r.post("https://www.planet-casio.com/Fr/shoutbox/api/post-as", data={"user": i[0], "message": msg, "channel": channel}, cookies=self.cookies) else: r.post("https://www.planet-casio.com/Fr/shoutbox/api/post-as", data={"user": "IRC", "message": f"{user} : {msg}", "channel": channel}, cookies=self.cookies) class SBMessage(object): def __init__(self, raw, channel): self.author = raw['author'] self.channel = channel self.text = raw['content']