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