everyonebot/main.py
2024-12-20 17:42:23 -05:00

81 lines
2.4 KiB
Python

import json
import time
from pathlib import Path
import flask
import requests
from secret import token
REVERSE_PROXY = False # if True: uses X-Real-IP header instead of remote addr
BASE_DIR = Path(__file__).parent
TIMEOUT = 15 * 60
CONTENT_WARNING = "test post ignore" # "Post from a random person - trinkey is not responsible for the content!!"
POST_URL = "https://is.trinkey.com/api/iceshrimp/notes"
RUN_CONF = {
"debug": True,
"host": "127.0.0.1",
"port": "8000"
}
app = flask.Flask(__file__)
data: dict[str, int] = {}
try:
data = json.load(open(BASE_DIR / "blocked.json", "r"))
except FileNotFoundError:
...
except json.JSONDecodeError:
...
def save():
with open(BASE_DIR / "blocked.json", "w") as f:
json.dump(data, f)
def get_ip() -> str:
return (flask.request.headers.get("X-Real-IP") if REVERSE_PROXY else flask.request.remote_addr) or "0.0.0.0"
app.route("/about/")(lambda: open(BASE_DIR / "public/about.html", "rb").read())
@app.route("/", methods=["POST", "GET"])
def index() -> bytes:
ip = get_ip()
cant_post = ip in data and data[ip] > time.time()
message = ""
if flask.request.method == "POST":
if not cant_post:
content = (flask.request.form.get("text") or "").strip()
if content:
resp = requests.post(POST_URL, json={
"text": content,
"cw": CONTENT_WARNING,
"replyId": None,
"renoteId": None,
"mediaIds": None,
"visibility": "home",
"idempotencyKey": None
}, headers={
"Authorization": f"Bearer {token}"
})
if resp.status_code == 200:
data[ip] = int(time.time() + TIMEOUT)
save()
message = "Success!"
else:
message = f"Got non-200 status code ({resp})"
else:
message = "Enter some text!"
else:
message = "You can't post yet!"
return open(BASE_DIR / "public/index.html", "rb").read() \
.replace(b"{{ IP }}", str.encode(ip)) \
.replace(b"{{ EXPIRE }}", str.encode(str(data[ip] if cant_post else 0))) \
.replace(b"{{ ERROR }}", str.encode(message))
if __name__ == "__main__":
app.run(**RUN_CONF)