Skip to content

Repository files navigation

🔮 42space-tg-bot — Prediction-Market Alert Bot (Telegram + Discord)

English | 中文

A self-hosted alert bot for 42.space prediction markets, powered by the Clawby aggregated API (ft42_* family). Single FastAPI process + SQLite, one scan cycle every 60 s — pushes to a Telegram chat/topic and a Discord webhook simultaneously, in English or Chinese (switchable at runtime).

✨ What it does

# Feature Logic
1 Ending soon Market closes for betting within ≤16 min (configurable) and MCap ≥ threshold → full odds ladder + resolution criteria + live win-odds check (DexScreener FDV/MCap/price matched against outcome buckets, real SMA when the market resolves on one; X + LLM fallback for non-crypto markets)
2 🆕 New market First seen in the snapshot & freshly opened → market info (first boot seeds silently, no spam)
3 🐋 Whale trades Volume-delta gated: only markets whose volume moved get an activity lookup; collateral ≥ $X triggers
4 🔧 Admin panel /admin (Basic Auth): every threshold, message language (EN/中文), TG chat/topic targets, chat whitelist, Discord webhook, AI model + editable AI prompt — all hot-reload, no restart

Channel controls: chat whitelist supports chat_id (whole chat) and chat_id:topic_id (a single forum topic) — the bot stays completely silent anywhere else (commands from non-whitelisted chats are ignored, not even rejected). Alerts land in the exact topic you configure.

🗂 Project Structure

42space_tg_bot/
├── run: uvicorn app.main:app          # single process, port 8642
├── requirements.txt                   # fastapi / httpx / uvicorn / zhconv
├── .env.example                       # secrets template — copy to .env
├── get_chat_id.py                     # helper: discover chat/topic ids
├── deploy.sh                          # rsync + venv + systemd deploy (set DEPLOY_HOST)
├── ft42bot.service                    # systemd unit
└── app/
    ├── main.py        # FastAPI app: admin page, settings API, loops boot
    ├── scanner.py     # 60s cycle: one snapshot feeds the three detectors
    ├── analysis.py    # win-odds engine: bucket parsing, DexScreener, SMA, X+LLM
    ├── responder.py   # /start /stop /help self-service subscription (whitelisted)
    ├── tg.py          # Telegram sender: HTML, 4096 chunking, topic targeting
    ├── discord.py     # Discord webhook mirror: HTML→markdown, 2000 chunking
    ├── i18n.py        # EN/中文 message catalog (admin-switchable)
    ├── translate.py   # zh criteria translation chain (LLM → Google → none)
    ├── llm.py         # OpenRouter chat wrapper
    ├── clawby.py      # Clawby relay client (throttled for the free plan)
    ├── config.py      # env secrets + DEFAULT_SETTINGS (seeded into DB)
    ├── db.py          # SQLite: settings, dedup state, subscribers, alert log
    └── admin.html     # the admin single-page UI

Call budget: one cycle = 1 × ft42_markets + ≤8 × ft42_activity (volume-changed markets only), globally throttled 3.2 s/call — safely inside the Clawby free plan's 20 req/min.

🚀 Install & Run (local)

Prerequisites: Python ≥ 3.10 · a Telegram bot token from @BotFather · a Clawby API key. Optional: a Discord webhook URL, an OpenRouter key for AI analysis.

# 1. Install
python3 -m venv .venv && ./.venv/bin/pip install -r requirements.txt

# 2. Configure secrets
cp .env.example .env
#    fill in: CLAWBY_API_KEY / TG_BOT_TOKEN / TG_CHAT_ID / ADMIN_PASSWORD

# 3. Find your chat / topic id (message the bot or add it to the group first)
TG_BOT_TOKEN=xxx python3 get_chat_id.py
#    forum supergroups: use  -100xxxxxxxxxx:TOPIC_ID  to target one topic

# 4. Run
set -a; source .env; set +a
./.venv/bin/uvicorn app.main:app --port 8642
#    admin panel: http://127.0.0.1:8642/admin   (user: admin)

First boot seeds all runtime settings into SQLite — from then on the admin panel is the source of truth (env vars are only first-boot seeds for those).

⚙️ Configuration

Where What
.env secrets & deploy constants: Clawby key, TG token, initial chat id, admin password, port, scan interval
/admin → thresholds ending window/MCap min, new-market window, whale trade $X, mute keywords
/admin → 📣 channels message language (EN/中文) · TG targets chat[:topic] · chat whitelist · Discord on/off + webhook
/admin → 🤖 AI OpenRouter key + model picker + editable win-odds prompt ({question} {outcomes} {posts} {reason_lang})

Behavior notes:

  • Whitelist empty = open self-subscription (anyone can /start); set it to lock the bot to your channels only.
  • Language zh also switches market titles to the official localized ones and translates resolution criteria (cached per market); en uses source text directly (zero translation cost).
  • Every outgoing message is mirrored to Discord when a webhook is set.

📦 Deploy to a server (systemd)

DEPLOY_HOST=ubuntu@your-server ./deploy.sh ~/.ssh/your-key.pem
# first deploy: ssh in, edit /home/ubuntu/ft42-tg-bot/.env, then
#   sudo systemctl restart ft42bot
# logs:  journalctl -u ft42bot -f

🔒 Security notes

  • .env is never rsynced by deploy.sh; keep it chmod 600.
  • The Discord webhook URL is a credential — anyone holding it can post to your channel. Store it via the admin panel; regenerate it if it ever leaks.
  • httpx logging is kept at WARNING so the TG bot token never lands in journals.


🔮 42space-tg-bot — 预测市场告警机器人(Telegram + Discord)

English | 中文

自托管的 42.space 预测市场告警机器人,基于 Clawby 聚合 API(ft42_* 接口族)。FastAPI 单进程 + SQLite,每 60 秒一轮扫描——同时推送 Telegram 指定群/话题 Discord webhook,消息语言中英可切(后台热切换)。

✨ 功能

# 功能 逻辑
1 尾盘预警 距最后下注 ≤16 分钟(可调)且 MCap ≥ 阈值 → 完整赔率 + 判定标准 + 实测胜率分析(DexScreener FDV/MCap/价格对照选项区间,判定口径为均价时实算 SMA;非加密盘走 X + LLM 兜底)
2 🆕 新盘提醒 快照首现且刚开盘 → 推送市场信息(首轮启动静默入库,不刷屏)
3 🐋 大额交易 成交量差分门控:只对 volume 变化的市场查 activity,collateral ≥ $X 触发
4 🔧 管理台 /admin(Basic Auth):全部阈值、消息语言(EN/中文)、TG 目标与白名单、Discord webhook、AI 模型与可编辑提示词——全部热生效

频道管控:白名单支持 chat_id(整群)与 chat_id:topic_id(单个话题), 白名单之外机器人完全静默(不响应、不拒绝);告警精确投递到你配置的话题。

🗂 项目结构

见上方英文部分的结构树——app/ 内:scanner 扫描循环、analysis 胜率引擎、 responder 订阅命令、tg/discord 双通道发送、i18n 中英文案、 translate 中文判定标准翻译链、db 设置与去重存储、admin.html 管理台。

🚀 安装与运行(本地)

环境要求:Python ≥ 3.10 · @BotFather 创建的 bot token · Clawby API key。可选:Discord webhook、OpenRouter key(AI 分析)。

# 1. 安装依赖
python3 -m venv .venv && ./.venv/bin/pip install -r requirements.txt

# 2. 配置密钥
cp .env.example .env
#    填入 CLAWBY_API_KEY / TG_BOT_TOKEN / TG_CHAT_ID / ADMIN_PASSWORD

# 3. 获取群/话题 ID(先给 bot 发消息或拉进群)
TG_BOT_TOKEN=xxx python3 get_chat_id.py
#    带话题的超级群用  -100xxxxxxxxxx:话题ID  精确指定话题

# 4. 启动
set -a; source .env; set +a
./.venv/bin/uvicorn app.main:app --port 8642
#    管理台 http://127.0.0.1:8642/admin(用户名 admin)

首次启动会把运行时设置种入 SQLite——此后管理台是唯一事实源(环境变量仅作首次种子)。

⚙️ 配置说明

位置 内容
.env 密钥与部署常量:Clawby key、TG token、初始 chat id、管理密码、端口、扫描间隔
/admin → 阈值 尾盘窗口/MCap 下限、新盘窗口、大额交易 $X、静音关键词
/admin → 📣 消息通道 消息语言(EN/中文) · TG 目标 chat[:topic] · 白名单 · Discord 开关 + webhook
/admin → 🤖 AI OpenRouter key + 模型选择 + 可编辑胜率提示词({question} {outcomes} {posts} {reason_lang})

行为说明:白名单留空 = 开放订阅(任何人可 /start);中文模式下市场标题用官方 本地化标题、判定标准走翻译链(按市场缓存),英文模式直接用原文(零翻译成本); 配置了 webhook 后每条消息同步镜像到 Discord。

📦 部署到服务器(systemd)

DEPLOY_HOST=ubuntu@你的服务器 ./deploy.sh ~/.ssh/你的密钥.pem
# 首次部署后:ssh 上去编辑 /home/ubuntu/ft42-tg-bot/.env,然后
#   sudo systemctl restart ft42bot
# 看日志:journalctl -u ft42bot -f

🔒 安全说明

  • deploy.sh 永不同步 .env;请保持 chmod 600。
  • Discord webhook 地址即凭据——持有者可向你的频道发消息;请通过管理台配置, 泄露即在 Discord 里重新生成。
  • httpx 日志压到 WARNING,TG token 不会出现在系统日志里。

Built with FastAPI · SQLite · Clawby API

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

Packages

Contributors

Languages