This commit is contained in:
Auric Vente 2024-02-22 20:22:16 -06:00
parent 6b2010fa16
commit 96df5b5b7a
1 changed files with 271 additions and 235 deletions

86
main.py
View File

@ -1,5 +1,14 @@
import requests, websockets, asyncio, json, re, httpx
import traceback, subprocess, os, aiohttp, sys, random
import requests
import websockets
import asyncio
import json
import re
import httpx
import traceback
import subprocess
import os
import aiohttp
import random
from bs4 import BeautifulSoup
from datetime import datetime
from pathlib import Path
@ -9,9 +18,11 @@ HERE = Path(__file__).parent
username = os.environ.get("GLUEBOT_USERNAME")
password = os.environ.get("GLUEBOT_PASSWORD")
def get_time():
return datetime.now().timestamp()
def remove_file(path):
try:
path.unlink()
@ -19,45 +30,52 @@ def remove_file(path):
print(f"(Remove) Error: {e}")
traceback.print_exc()
def get_extension(path):
return Path(path).suffix.lower().lstrip(".")
def clean_lines(s):
cleaned = s
cleaned = re.sub(r" *(\n+|\\n+) *", "\n", cleaned)
cleaned = re.sub(r" +", " ", cleaned)
return cleaned.strip()
def random_int(min_val, max_val):
return random.randint(min_val, max_val)
def get_path(name):
return str(Path(HERE, name))
def extract_range(string):
pattern = re.compile(r"\s*(\d+)\s*(\d+)?\s*")
match = pattern.search(string)
pattern = r"(?:(?P<number1>-?\d+)(?:\s*(.+?)\s*(?P<number2>-?\d+))?)?"
match = re.search(pattern, string)
num1 = None
num2 = None
if not match:
return [0]
if match["number1"]:
num1 = int(match["number1"])
start = match.group(1)
end = match.group(2)
if match["number2"]:
num2 = int(match["number2"])
return [num1, num2]
if end is None:
return [int(start)]
else:
return [int(start), int(end)]
def clean_list(lst):
return list(filter(lambda x: x != "", lst))
def string_to_number(input_string):
hash_value = hash(input_string)
absolute_hash = abs(hash_value)
scaled_number = absolute_hash % 1000
return scaled_number
headers = {
"User-Agent": "gluebot",
"Origin": "https://deek.chat",
@ -76,13 +94,16 @@ gm_common = "--width 350 --nogrow --output /tmp/gifmaker"
cmd_date = get_time()
def update_time():
global cmd_date
cmd_date = get_time()
def blocked():
return (get_time() - cmd_date) < delay
def auth():
global token, session, headers
@ -91,11 +112,15 @@ def auth():
exit(1)
data = {"name": username, "password": password, "submit": "log+in"}
res = requests.post(url + "/login/submit", headers=headers, data=data, allow_redirects=False)
token = re.search("(?:api_token)=[^;]+", res.headers.get("Set-Cookie")).group(0)
session = re.search("(?:session_id)=[^;]+", res.headers.get("Set-Cookie")).group(0)
res = requests.post(url + "/login/submit", headers=headers,
data=data, allow_redirects=False)
token = re.search("(?:api_token)=[^;]+",
res.headers.get("Set-Cookie")).group(0)
session = re.search(
"(?:session_id)=[^;]+", res.headers.get("Set-Cookie")).group(0)
headers["Cookie"] = token + "; " + session
async def run():
async with websockets.connect(ws_url, extra_headers=headers) as ws:
try:
@ -110,8 +135,10 @@ async def run():
print("(WebSocket) Error:", e)
traceback.print_exc()
async def on_message(ws, message):
if blocked(): return
if blocked():
return
try:
data = json.loads(message)
@ -171,6 +198,7 @@ async def on_message(ws, message):
update_time()
await random_post(ws, room_id)
async def random_bird(ws, room_id):
birdfile = get_path("data/aves.txt")
@ -179,6 +207,7 @@ async def random_bird(ws, room_id):
bird = random.choice(birds).strip()
await send_message(ws, f".i \"{bird}\" bird", room_id)
async def gif_describe(who, room_id):
input_path = get_path("describe.jpg")
@ -193,6 +222,7 @@ async def gif_describe(who, room_id):
await run_gifmaker(command, room_id)
async def gif_wins(who, room_id):
input_path = get_path("wins.gif")
@ -206,18 +236,18 @@ async def gif_wins(who, room_id):
await run_gifmaker(command, room_id)
async def gif_numbers(arg, room_id):
num = -1
if arg:
numbers = extract_range(arg)
nums = extract_range(arg)
if len(numbers) == 1:
if numbers[0] > 0:
num = random_int(0, numbers[0])
elif len(numbers) == 2:
if numbers[0] < numbers[1]:
num = random_int(numbers[0], numbers[1])
if nums[0] is not None:
if nums[1] is not None:
num = random_int(nums[0], nums[1])
else:
num = random_int(0, nums[0])
if num == -1:
num = string_to_number(arg)
@ -237,6 +267,7 @@ async def gif_numbers(arg, room_id):
await run_gifmaker(command, room_id)
async def gif_date(who, room_id):
input_path = get_path("time.jpg")
@ -250,6 +281,7 @@ async def gif_date(who, room_id):
await run_gifmaker(command, room_id)
async def random_post(ws, room_id):
boards = ["g", "an", "ck", "lit", "x", "tv", "v", "fit", "k", "o"]
board = random.choice(boards)
@ -275,7 +307,8 @@ async def random_post(ws, room_id):
# Select a random post
post = posts[random_int(0, len(posts) - 1)]
html = post.get("com", "")
if not html: return
if not html:
return
# Parse HTML using BeautifulSoup
soup = BeautifulSoup(html, "html.parser")
@ -298,6 +331,7 @@ async def random_post(ws, room_id):
except Exception as err:
print(f"Error: {err}")
async def run_gifmaker(command, room_id):
process = await asyncio.create_subprocess_shell(
" ".join(command),
@ -314,6 +348,7 @@ async def run_gifmaker(command, room_id):
await upload(Path(stdout.decode().strip()), room_id)
async def upload(path, room_id):
if (not path.exists()) or (not path.is_file()):
return
@ -330,7 +365,7 @@ async def upload(path, room_id):
url = "https://deek.chat/message/send/" + str(room_id)
data = aiohttp.FormData()
data.add_field(name="files[]", value=open(path, "rb"), \
data.add_field(name="files[]", value=open(path, "rb"),
filename=path.name, content_type=f"image/{ext}")
try:
@ -343,6 +378,7 @@ async def upload(path, room_id):
remove_file(path)
async def send_message(ws, text, room_id):
await ws.send(json.dumps({"type": "message", "data": text, "roomId": room_id}))