dkcht2innanetrlycht/main.py

111 lines
5.2 KiB
Python
Raw Normal View History

2022-06-20 23:36:22 +00:00
import requests, websockets, asyncio, json, re, threading, time
from ircked.bot import irc_bot
from ircked.message import *
2022-07-05 04:02:57 +00:00
import traceback
2022-08-03 02:35:52 +00:00
import html
2022-08-03 03:42:45 +00:00
import ratelimiter
2022-06-20 23:36:22 +00:00
class bird_inst():
def __init__(self, endpoint, httpendpoint, config):
self.endpoint = endpoint
self.httpendpoint = httpendpoint
self.config = config
self.ws = None
self.headers = None
self.irc = irc_bot(nick=self.config["irc_nick"])
self.irc.connect_register(self.config["irc_serb"], self.config["irc_port"])
2022-07-05 04:02:57 +00:00
self.send_queue = []
2022-06-20 23:36:22 +00:00
2023-10-29 05:52:37 +00:00
self.limiter = ratelimiter.ratelimit(.5)
2022-08-03 03:42:45 +00:00
2022-06-20 23:36:22 +00:00
def irc_handler(msg, ctx):
#print("<><><><>", str(msg))
if msg.command == "PING":
message.manual("", "PONG", msg.parameters).send(ctx.socket)
elif msg.command == "001":
message.manual("", "JOIN", [self.config["irc_chan"]]).send(ctx.socket)
elif msg.command == "PRIVMSG" and "\x01VERSION\x01" in msg.parameters:
message.manual(":"+msg.parameters[0], "PRIVMSG", [msg.prefix[1:].split("!")[0], ":\x01dorfl bot\x01"]).send(ctx.socket)
if msg.command == "PRIVMSG" and ("py-ctcp" not in msg.prefix):
pm = privmsg.parse(msg)
2024-07-12 04:40:55 +00:00
post = pm.bod
if pm.fr.split("!")[0] != self.config["passthru_nick"]: post = "<"+pm.fr.split("!")[0]+"> " + post
self.send_post(post)
2022-06-20 23:36:22 +00:00
threading.Thread(target=self.irc.run, kwargs={"event_handler": irc_handler}, daemon=True).start()
def auth(self, name, passwd):
h = {
"User-Agent": "renabot",
2023-10-29 05:52:37 +00:00
"Origin": "https://deek.chat",
2022-06-20 23:36:22 +00:00
"DNT": "1",
}
res = requests.post(self.httpendpoint+"/login/submit", headers=h, data={"name": name, "password": passwd, "submit": "log+in"}, allow_redirects=False)
2023-10-29 05:52:37 +00:00
print(res.headers)
2022-06-20 23:36:22 +00:00
token = re.search("(?:api_token)=[^;]+", res.headers.get("Set-Cookie")).group(0)
sessid = re.search("(?:session_id)=[^;]+", res.headers.get("Set-Cookie")).group(0)
h["Cookie"] = token+"; "+sessid
self.headers = h
async def run(self):
print("running main loop")
async with websockets.connect(self.endpoint, extra_headers=self.headers) as self.ws:
print(self.ws)
2022-07-05 04:02:57 +00:00
asyncio.get_event_loop().create_task(self._send_post())
2022-08-03 03:42:45 +00:00
asyncio.get_event_loop().create_task(self.ship_queued_messages())
2022-06-20 23:36:22 +00:00
while True:
data = json.loads(await self.ws.recv())
print(">>>", data)
2023-10-29 05:52:37 +00:00
#getattr(self, "handle_"+data["type"], None)(data)
2022-08-03 03:53:55 +00:00
try: getattr(self, "handle_"+data["type"], None)(data)
except Exception as e: print("hey buddy your shits fucked thought you might want to know", e)
2022-06-20 23:36:22 +00:00
def handle_message(self, ctx):
2024-07-12 04:28:37 +00:00
room = int(ctx["roomId"])
if room != self.config["deek_roomid"]: return
2023-10-29 05:52:37 +00:00
print("btw i just got this", ctx["data"]["text"])
ctx["data"]["text"] = html.unescape(ctx["data"]["text"])
if ctx["data"]["name"] == self.config["deek_user"]: return
mesg = ctx["data"]["text"].replace("\n", " ")
2022-07-05 04:57:27 +00:00
chunks = list(mesg[0+i:400+i] for i in range(0, len(mesg), 400))
2024-07-12 04:28:37 +00:00
chunks = ["<"+ctx["data"]["name"]+"> "+m for m in chunks]
chunks[0] = f"(#{ctx['data']['id']}) " + chunks[0]
2022-07-05 04:57:08 +00:00
for m in chunks:
2024-07-12 04:28:37 +00:00
self.limiter.action(True, self.irc.sendraw, (privmsg.build(self.config["irc_nick"], self.config["irc_chan"], m).msg,))
2023-10-29 05:52:37 +00:00
def handle_messageStart(self, ctx): pass
def handle_messageChange(self, ctx): pass
def handle_messageEnd(self, ctx): self.handle_message(ctx)
2022-06-20 23:36:22 +00:00
def handle_avatar(self, ctx): pass
2023-10-29 05:52:37 +00:00
def handle_loadUsers(self, ctx): pass
2022-06-20 23:36:22 +00:00
def handle_files(self, ctx):
2023-10-29 05:52:37 +00:00
ctx["data"]["text"] = html.unescape(ctx["data"]["text"])
2023-10-29 20:28:27 +00:00
self.irc.sendraw(privmsg.build(self.config["irc_nick"], self.config["irc_chan"], "<"+ctx["data"]["name"]+"> "+ctx["data"]["text"]).msg)
2023-10-29 05:52:37 +00:00
for f in ctx["data"]["files"]:
self.limiter.action(True, self.irc.sendraw, (privmsg.build(self.config["irc_nick"], self.config["irc_chan"], f"({ctx['data']['name']} uploaded file: {self.httpendpoint}/storage/files/{f['name']} )").msg,))
2022-06-20 23:36:22 +00:00
def handle_exit(self, ctx): pass
def handle_enter(self, ctx): pass
def handle_userLoaded(self, ctx): pass
def send_post(self, msg):
if self.ws is None: return
print(msg)
2022-07-05 04:02:57 +00:00
self.send_queue.append(msg)
async def _send_post(self):
while True:
for msg in self.send_queue:
2023-10-29 05:52:37 +00:00
await self.ws.send(json.dumps({"type": "message", "data": msg, "roomId": 1}))
2022-07-05 04:02:57 +00:00
self.send_queue.remove(msg)
print("shipped", msg)
2022-07-05 05:01:41 +00:00
await asyncio.sleep(.1)
2022-08-03 03:42:45 +00:00
async def ship_queued_messages(self):
while True:
self.limiter.lazyrun()
await asyncio.sleep(.1)
2022-06-20 23:36:22 +00:00
cfg = json.loads(open("config.json", "r").read())
2023-10-29 05:52:37 +00:00
bi = bird_inst("wss://deek.chat/ws", "https://deek.chat", cfg)
2022-06-20 23:36:22 +00:00
print("yes hello birdchat here")
bi.auth(cfg["deek_user"], cfg["deek_passwd"])
while True:
try: asyncio.run(bi.run())
except KeyboardInterrupt:
break
except Exception as e:
2022-07-05 04:02:57 +00:00
print("yo ur shits broken", e)
print(traceback.format_exc())
2022-07-13 03:40:26 +00:00
continue