File size: 1,438 Bytes
d82c270
f77d1e4
 
 
 
 
 
5e8aaea
f77d1e4
 
 
 
d82c270
f77d1e4
d82c270
 
 
 
 
 
5e8aaea
d82c270
 
f77d1e4
d82c270
 
 
 
f77d1e4
d82c270
5e8aaea
d82c270
 
 
 
 
f77d1e4
d82c270
f77d1e4
d82c270
 
f77d1e4
 
d82c270
f77d1e4
 
d82c270
 
 
 
5e8aaea
d82c270
 
 
 
f77d1e4
d82c270
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
from fastapi import FastAPI, Request, Form
import threading
import time

app = FastAPI()
lock = threading.Lock()

# -------- STORAGE --------
channels = {}
update_ids = {}


# -------- SEND MESSAGE --------
@app.post("/sendMessage/{channel}")
async def send_message(channel: str, text: str = Form(None), req: Request = None):
    try:
        # support both form-data & raw body
        if not text:
            data = await req.body()
            text = data.decode("utf-8", errors="ignore").strip()

        if not text:
            return {"ok": False, "error": "Empty message"}

        with lock:
            if channel not in channels:
                channels[channel] = []
                update_ids[channel] = 0

            update_ids[channel] += 1

            channels[channel].append({
                "update_id": update_ids[channel],
                "text": text,
                "time": int(time.time())
            })

        return {"ok": True}

    except Exception as e:
        return {"ok": False, "error": str(e)}


# -------- GET UPDATES (consume-on-read) --------
@app.get("/getUpdates/{channel}")
def get_updates(channel: str):
    try:
        with lock:
            msgs = channels.get(channel, []).copy()
            channels[channel] = []

        return {
            "ok": True,
            "result": msgs if msgs else []
        }

    except Exception as e:
        return {"ok": False, "error": str(e)}