shoutbridge/shoutbox.py

71 lines
2.7 KiB
Python
Raw Normal View History

2021-09-10 14:23:43 +02:00
import json
import requests as r
import logging
import time
from functools import wraps
from threading import Thread
2022-03-10 10:38:43 +01:00
2021-09-10 14:23:43 +02:00
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
2022-03-09 14:14:58 +01:00
def post(self, user, msg, channel, users):
2022-03-11 19:18:36 +01:00
if msg.startswith("ACTION"):
msg = msg.replace("ACTION", "/me")
2022-03-09 14:14:58 +01:00
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)
2021-09-10 14:23:43 +02:00
class SBMessage(object):
def __init__(self, raw, channel):
self.author = raw['author']
self.channel = channel
self.text = raw['content']