IISHKO: Telegram bot, Mini App and gateway
Initial public release. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,187 @@
|
||||
from contextlib import closing
|
||||
import os
|
||||
import sqlite3
|
||||
import time
|
||||
import unicodedata
|
||||
|
||||
BOT_DB = os.environ.get("IISHKO_BOT_DB", os.environ.get("GROK_BOT_DB", "/opt/grok-bot/bot.db"))
|
||||
WINDOW = 86400
|
||||
TAG_MAX = 48
|
||||
TAG_LIMIT = 12
|
||||
|
||||
|
||||
def _connect():
|
||||
con = sqlite3.connect(BOT_DB, timeout=10)
|
||||
con.row_factory = sqlite3.Row
|
||||
con.execute("PRAGMA busy_timeout=8000")
|
||||
return con
|
||||
|
||||
|
||||
def init_db():
|
||||
with closing(_connect()) as con:
|
||||
con.executescript("""
|
||||
CREATE TABLE IF NOT EXISTS wa_entry_tags (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
ip_hmac TEXT NOT NULL,
|
||||
tag TEXT NOT NULL,
|
||||
created_at INTEGER NOT NULL,
|
||||
by_uid INTEGER NOT NULL DEFAULT 0,
|
||||
UNIQUE(ip_hmac, tag)
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS wa_entry_tag_net ON wa_entry_tags(ip_hmac);
|
||||
CREATE TABLE IF NOT EXISTS wa_entry_tag_prompts (
|
||||
message_id INTEGER PRIMARY KEY,
|
||||
chat_id INTEGER NOT NULL,
|
||||
alert_id INTEGER NOT NULL,
|
||||
ip_hmac TEXT NOT NULL,
|
||||
alert_message_id INTEGER NOT NULL DEFAULT 0,
|
||||
admin_id INTEGER NOT NULL,
|
||||
created_at INTEGER NOT NULL
|
||||
);
|
||||
""")
|
||||
con.commit()
|
||||
return True
|
||||
|
||||
|
||||
def clean_tag(value):
|
||||
if not isinstance(value, str):
|
||||
return ""
|
||||
text = "".join(ch for ch in value[:TAG_MAX * 4]
|
||||
if not unicodedata.category(ch).startswith("C"))
|
||||
return " ".join(text.split())[:TAG_MAX]
|
||||
|
||||
|
||||
def alert(alert_id):
|
||||
try:
|
||||
alert_id = int(alert_id)
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
with closing(_connect()) as con:
|
||||
row = con.execute("SELECT id,ip_hmac,created_at,accounts,country,city,geo_source "
|
||||
"FROM wa_entry_alerts WHERE id=?", (alert_id,)).fetchone()
|
||||
if row is None:
|
||||
return None
|
||||
data = dict(row)
|
||||
try:
|
||||
import json
|
||||
data["accounts"] = json.loads(data.get("accounts") or "[]")
|
||||
except ValueError:
|
||||
data["accounts"] = []
|
||||
data["uids"] = [int(item["uid"]) for item in data["accounts"]
|
||||
if isinstance(item, dict) and isinstance(item.get("uid"), int)]
|
||||
return data
|
||||
|
||||
|
||||
def recent_alerts(limit=5):
|
||||
limit = max(1, min(int(limit or 5), 20))
|
||||
with closing(_connect()) as con:
|
||||
rows = con.execute("SELECT id,ip_hmac,created_at,accounts,country,city "
|
||||
"FROM wa_entry_alerts ORDER BY id DESC LIMIT ?", (limit,)).fetchall()
|
||||
out = []
|
||||
for row in rows:
|
||||
item = dict(row)
|
||||
try:
|
||||
import json
|
||||
item["accounts"] = json.loads(item.get("accounts") or "[]")
|
||||
except ValueError:
|
||||
item["accounts"] = []
|
||||
out.append(item)
|
||||
return out
|
||||
|
||||
|
||||
def net_accounts(ip_hmac, window=WINDOW, limit=40):
|
||||
"""Every account that entered through this network inside the window."""
|
||||
now = int(time.time())
|
||||
with closing(_connect()) as con:
|
||||
rows = con.execute(
|
||||
"SELECT v.uid, u.username, COALESCE(u.banned,0) AS banned, COALESCE(u.admin,0) AS admin, "
|
||||
"v.last_visit, v.country, v.city FROM wa_entry_visits v "
|
||||
"LEFT JOIN users u ON u.tg_id=v.uid WHERE v.ip_hmac=? AND v.last_visit>? "
|
||||
"ORDER BY v.last_visit DESC LIMIT ?", (str(ip_hmac), now - int(window), limit)).fetchall()
|
||||
return [dict(row) for row in rows]
|
||||
|
||||
|
||||
def tags(ip_hmac):
|
||||
if not ip_hmac:
|
||||
return []
|
||||
with closing(_connect()) as con:
|
||||
rows = con.execute("SELECT tag FROM wa_entry_tags WHERE ip_hmac=? "
|
||||
"ORDER BY id LIMIT ?", (str(ip_hmac), TAG_LIMIT)).fetchall()
|
||||
return [row["tag"] for row in rows]
|
||||
|
||||
|
||||
def add_tag(ip_hmac, tag, by_uid=0):
|
||||
tag = clean_tag(tag)
|
||||
if not tag or not ip_hmac:
|
||||
return False
|
||||
with closing(_connect()) as con:
|
||||
count = con.execute("SELECT COUNT(*) FROM wa_entry_tags WHERE ip_hmac=?", (str(ip_hmac),)).fetchone()[0]
|
||||
exists = con.execute("SELECT 1 FROM wa_entry_tags WHERE ip_hmac=? AND tag=?",
|
||||
(str(ip_hmac), tag)).fetchone()
|
||||
if exists is None and count >= TAG_LIMIT:
|
||||
return False
|
||||
con.execute("INSERT OR IGNORE INTO wa_entry_tags(ip_hmac,tag,created_at,by_uid) VALUES(?,?,?,?)",
|
||||
(str(ip_hmac), tag, int(time.time()), int(by_uid or 0)))
|
||||
con.commit()
|
||||
return True
|
||||
|
||||
|
||||
def del_tag(ip_hmac, tag):
|
||||
tag = clean_tag(tag)
|
||||
if not tag or not ip_hmac:
|
||||
return False
|
||||
with closing(_connect()) as con:
|
||||
cur = con.execute("DELETE FROM wa_entry_tags WHERE ip_hmac=? AND tag=?",
|
||||
(str(ip_hmac), tag))
|
||||
con.commit()
|
||||
return cur.rowcount > 0
|
||||
|
||||
|
||||
def apply_tags(ip_hmac, raw, by_uid=0):
|
||||
"""Accepts 'a, b, c' or '-a' to drop a tag. Returns (added, removed, all_tags)."""
|
||||
added, removed = [], []
|
||||
for chunk in str(raw or "").replace(";", ",").split(",")[:8]:
|
||||
chunk = chunk.strip()
|
||||
if not chunk:
|
||||
continue
|
||||
if chunk.startswith("-"):
|
||||
if del_tag(ip_hmac, chunk[1:]):
|
||||
removed.append(clean_tag(chunk[1:]))
|
||||
elif add_tag(ip_hmac, chunk, by_uid):
|
||||
added.append(clean_tag(chunk))
|
||||
return added, removed, tags(ip_hmac)
|
||||
|
||||
|
||||
def save_prompt(message_id, chat_id, alert_id, ip_hmac, alert_message_id, admin_id):
|
||||
with closing(_connect()) as con:
|
||||
con.execute("DELETE FROM wa_entry_tag_prompts WHERE created_at<?",
|
||||
(int(time.time()) - 3 * WINDOW,))
|
||||
con.execute("INSERT OR REPLACE INTO wa_entry_tag_prompts"
|
||||
"(message_id,chat_id,alert_id,ip_hmac,alert_message_id,admin_id,created_at) "
|
||||
"VALUES(?,?,?,?,?,?,?)",
|
||||
(int(message_id), int(chat_id), int(alert_id), str(ip_hmac),
|
||||
int(alert_message_id or 0), int(admin_id), int(time.time())))
|
||||
con.commit()
|
||||
return True
|
||||
|
||||
|
||||
def has_prompt(message_id, admin_id):
|
||||
with closing(_connect()) as con:
|
||||
row = con.execute("SELECT 1 FROM wa_entry_tag_prompts WHERE message_id=? AND admin_id=?",
|
||||
(int(message_id), int(admin_id))).fetchone()
|
||||
return row is not None
|
||||
|
||||
|
||||
def take_prompt(message_id):
|
||||
with closing(_connect()) as con:
|
||||
row = con.execute("SELECT * FROM wa_entry_tag_prompts WHERE message_id=?",
|
||||
(int(message_id),)).fetchone()
|
||||
if row is None:
|
||||
return None
|
||||
con.execute("DELETE FROM wa_entry_tag_prompts WHERE message_id=?", (int(message_id),))
|
||||
con.commit()
|
||||
return dict(row)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
print("init_db:", init_db())
|
||||
Reference in New Issue
Block a user