init: telegram bot bridging messages to claude sessions
Async Rust bot (teloxide + tokio) that: - Authenticates users per chat with a passphrase (resets daily at 5am) - Generates deterministic UUID v5 session IDs from chat_id + date - Pipes messages to `claude -p --session-id/--resume <uuid>` - Persists auth and session state to disk across restarts - Deploys as systemd --user service via `make deploy`
This commit is contained in:
4
.gitignore
vendored
Normal file
4
.gitignore
vendored
Normal file
@@ -0,0 +1,4 @@
|
||||
/target
|
||||
config.yaml
|
||||
state.json
|
||||
noc.service
|
||||
2280
Cargo.lock
generated
Normal file
2280
Cargo.lock
generated
Normal file
File diff suppressed because it is too large
Load Diff
17
Cargo.toml
Normal file
17
Cargo.toml
Normal file
@@ -0,0 +1,17 @@
|
||||
[package]
|
||||
name = "noc"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
|
||||
[dependencies]
|
||||
anyhow = "1"
|
||||
chrono = { version = "0.4", features = ["serde"] }
|
||||
dptree = "0.3"
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
serde_json = "1"
|
||||
serde_yaml = "0.9"
|
||||
teloxide = { version = "0.12", features = ["macros"] }
|
||||
tokio = { version = "1", features = ["full"] }
|
||||
uuid = { version = "1", features = ["v5"] }
|
||||
tracing = "0.1"
|
||||
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
|
||||
16
Makefile
Normal file
16
Makefile
Normal file
@@ -0,0 +1,16 @@
|
||||
REPO := $(shell pwd)
|
||||
|
||||
.PHONY: build deploy
|
||||
|
||||
build:
|
||||
cargo build --release
|
||||
|
||||
noc.service: noc.service.in
|
||||
sed -e 's|@REPO@|$(REPO)|g' -e 's|@PATH@|$(PATH)|g' $< > $@
|
||||
|
||||
deploy: build noc.service
|
||||
mkdir -p ~/.config/systemd/user
|
||||
cp noc.service ~/.config/systemd/user/
|
||||
systemctl --user daemon-reload
|
||||
systemctl --user enable --now noc
|
||||
systemctl --user restart noc
|
||||
40
README.md
Normal file
40
README.md
Normal file
@@ -0,0 +1,40 @@
|
||||
# NOC
|
||||
|
||||
Telegram bot that bridges messages to `claude` sessions.
|
||||
|
||||
## How it works
|
||||
|
||||
1. User sends a message to the bot
|
||||
2. First message must be the auth passphrase, otherwise the bot replies "not authenticated"
|
||||
3. Once authenticated, messages are piped to `ms --resume <session_id>` via stdin
|
||||
4. `claude` stdout is sent back as the reply
|
||||
5. Sessions are scoped per chat and refresh daily at 5am local time
|
||||
|
||||
## Setup
|
||||
|
||||
```bash
|
||||
cp config.example.yaml config.yaml
|
||||
# edit config.yaml with your values
|
||||
```
|
||||
|
||||
## Config
|
||||
|
||||
| Key | Description |
|
||||
|-----|-------------|
|
||||
| `tg.key` | Telegram bot token |
|
||||
| `auth.passphrase` | Passphrase required to authenticate each session |
|
||||
| `session.refresh_hour` | Hour (local time, 24h) when sessions reset |
|
||||
|
||||
## Deploy
|
||||
|
||||
```bash
|
||||
make deploy
|
||||
```
|
||||
|
||||
This builds the release binary and installs a `systemd --user` service.
|
||||
|
||||
## Logs
|
||||
|
||||
```bash
|
||||
journalctl --user -u noc -f
|
||||
```
|
||||
8
config.example.yaml
Normal file
8
config.example.yaml
Normal file
@@ -0,0 +1,8 @@
|
||||
tg:
|
||||
key: "YOUR_TELEGRAM_BOT_TOKEN"
|
||||
|
||||
auth:
|
||||
passphrase: "YOUR_AUTH_PASSPHRASE"
|
||||
|
||||
session:
|
||||
refresh_hour: 5
|
||||
8
doc/todo.md
Normal file
8
doc/todo.md
Normal file
@@ -0,0 +1,8 @@
|
||||
# TODO
|
||||
|
||||
- [ ] Streaming responses — edit message as `ms` output arrives instead of waiting for full completion
|
||||
- [ ] Markdown formatting — parse `ms` output and send with TG MarkdownV2
|
||||
- [ ] Timeout handling — kill `ms` if it hangs beyond a threshold
|
||||
- [ ] Graceful shutdown on SIGTERM
|
||||
- [ ] `/reset` command to force new session without waiting for 5am
|
||||
- [ ] Rate limiting per chat
|
||||
18
noc.service.in
Normal file
18
noc.service.in
Normal file
@@ -0,0 +1,18 @@
|
||||
[Unit]
|
||||
Description=NOC Telegram Bot
|
||||
After=network-online.target
|
||||
Wants=network-online.target
|
||||
|
||||
[Service]
|
||||
Type=simple
|
||||
WorkingDirectory=%h
|
||||
ExecStart=@REPO@/target/release/noc
|
||||
Restart=on-failure
|
||||
RestartSec=5
|
||||
Environment=RUST_LOG=noc=info
|
||||
Environment=NOC_CONFIG=@REPO@/config.yaml
|
||||
Environment=NOC_STATE=@REPO@/state.json
|
||||
Environment=PATH=@PATH@
|
||||
|
||||
[Install]
|
||||
WantedBy=default.target
|
||||
260
src/main.rs
Normal file
260
src/main.rs
Normal file
@@ -0,0 +1,260 @@
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::path::PathBuf;
|
||||
use std::process::Stdio;
|
||||
use std::sync::Arc;
|
||||
|
||||
use anyhow::Result;
|
||||
use chrono::{Local, NaiveDate, NaiveTime};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use teloxide::dispatching::UpdateFilterExt;
|
||||
use teloxide::prelude::*;
|
||||
use teloxide::types::ChatAction;
|
||||
use tokio::process::Command;
|
||||
use tokio::sync::RwLock;
|
||||
use tracing::{error, info, warn};
|
||||
use uuid::Uuid;
|
||||
|
||||
// ── config ──────────────────────────────────────────────────────────
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct Config {
|
||||
tg: TgConfig,
|
||||
auth: AuthConfig,
|
||||
session: SessionConfig,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct TgConfig {
|
||||
key: String,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct AuthConfig {
|
||||
passphrase: String,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct SessionConfig {
|
||||
refresh_hour: u32,
|
||||
}
|
||||
|
||||
// ── persistent state ────────────────────────────────────────────────
|
||||
|
||||
#[derive(Serialize, Deserialize, Default)]
|
||||
struct Persistent {
|
||||
authed: HashMap<i64, NaiveDate>,
|
||||
known_sessions: HashSet<String>,
|
||||
}
|
||||
|
||||
struct AppState {
|
||||
persist: RwLock<Persistent>,
|
||||
state_path: PathBuf,
|
||||
}
|
||||
|
||||
impl AppState {
|
||||
fn load(path: PathBuf) -> Self {
|
||||
let persist = std::fs::read_to_string(&path)
|
||||
.ok()
|
||||
.and_then(|s| serde_json::from_str(&s).ok())
|
||||
.unwrap_or_default();
|
||||
info!("loaded state from {}", path.display());
|
||||
Self {
|
||||
persist: RwLock::new(persist),
|
||||
state_path: path,
|
||||
}
|
||||
}
|
||||
|
||||
async fn save(&self) {
|
||||
let data = self.persist.read().await;
|
||||
if let Ok(json) = serde_json::to_string_pretty(&*data) {
|
||||
if let Err(e) = std::fs::write(&self.state_path, json) {
|
||||
error!("save state: {e}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ── helpers ─────────────────────────────────────────────────────────
|
||||
|
||||
fn session_date(refresh_hour: u32) -> NaiveDate {
|
||||
let now = Local::now();
|
||||
let refresh = NaiveTime::from_hms_opt(refresh_hour, 0, 0).unwrap();
|
||||
if now.time() < refresh {
|
||||
now.date_naive() - chrono::Duration::days(1)
|
||||
} else {
|
||||
now.date_naive()
|
||||
}
|
||||
}
|
||||
|
||||
fn session_uuid(chat_id: i64, refresh_hour: u32) -> String {
|
||||
let date = session_date(refresh_hour);
|
||||
let name = format!("noc-{}-{}", chat_id, date.format("%Y%m%d"));
|
||||
Uuid::new_v5(&Uuid::NAMESPACE_OID, name.as_bytes()).to_string()
|
||||
}
|
||||
|
||||
// ── main ────────────────────────────────────────────────────────────
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() {
|
||||
tracing_subscriber::fmt()
|
||||
.with_env_filter(
|
||||
tracing_subscriber::EnvFilter::from_default_env()
|
||||
.add_directive("noc=info".parse().unwrap()),
|
||||
)
|
||||
.init();
|
||||
|
||||
let config_path = std::env::var("NOC_CONFIG").unwrap_or_else(|_| "config.yaml".into());
|
||||
let raw = std::fs::read_to_string(&config_path)
|
||||
.unwrap_or_else(|e| panic!("read {config_path}: {e}"));
|
||||
let config: Config =
|
||||
serde_yaml::from_str(&raw).unwrap_or_else(|e| panic!("parse config: {e}"));
|
||||
|
||||
let state_path = std::env::var("NOC_STATE")
|
||||
.map(PathBuf::from)
|
||||
.unwrap_or_else(|_| PathBuf::from("state.json"));
|
||||
let state = Arc::new(AppState::load(state_path));
|
||||
|
||||
info!("noc bot starting");
|
||||
|
||||
let bot = Bot::new(&config.tg.key);
|
||||
let handler = Update::filter_message().endpoint(handle);
|
||||
|
||||
Dispatcher::builder(bot, handler)
|
||||
.dependencies(dptree::deps![state, Arc::new(config)])
|
||||
.default_handler(|_| async {})
|
||||
.build()
|
||||
.dispatch()
|
||||
.await;
|
||||
}
|
||||
|
||||
// ── handler ─────────────────────────────────────────────────────────
|
||||
|
||||
async fn handle(
|
||||
bot: Bot,
|
||||
msg: Message,
|
||||
state: Arc<AppState>,
|
||||
config: Arc<Config>,
|
||||
) -> ResponseResult<()> {
|
||||
let text = match msg.text() {
|
||||
Some(t) => t,
|
||||
None => return Ok(()),
|
||||
};
|
||||
|
||||
let chat_id = msg.chat.id;
|
||||
let raw_id = chat_id.0;
|
||||
let date = session_date(config.session.refresh_hour);
|
||||
|
||||
// auth gate
|
||||
let is_authed = {
|
||||
let p = state.persist.read().await;
|
||||
p.authed.get(&raw_id) == Some(&date)
|
||||
};
|
||||
|
||||
if !is_authed {
|
||||
if text.trim() == config.auth.passphrase {
|
||||
{
|
||||
let mut p = state.persist.write().await;
|
||||
p.authed.insert(raw_id, date);
|
||||
}
|
||||
state.save().await;
|
||||
bot.send_message(chat_id, "authenticated").await?;
|
||||
info!(chat = raw_id, "authed");
|
||||
} else {
|
||||
bot.send_message(chat_id, "not authenticated").await?;
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let sid = session_uuid(raw_id, config.session.refresh_hour);
|
||||
info!(%sid, "recv");
|
||||
|
||||
let _ = bot.send_chat_action(chat_id, ChatAction::Typing).await;
|
||||
|
||||
let known = state.persist.read().await.known_sessions.contains(&sid);
|
||||
|
||||
let reply = match invoke_claude(&sid, text, known).await {
|
||||
Ok(out) => {
|
||||
if !known {
|
||||
state.persist.write().await.known_sessions.insert(sid.clone());
|
||||
state.save().await;
|
||||
}
|
||||
out
|
||||
}
|
||||
Err(e) => {
|
||||
error!(%sid, "claude: {e:#}");
|
||||
format!("[error] {e:#}")
|
||||
}
|
||||
};
|
||||
|
||||
if reply.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
for chunk in split_msg(&reply, 4096) {
|
||||
bot.send_message(chat_id, chunk).await?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// ── claude bridge ───────────────────────────────────────────────────
|
||||
|
||||
async fn invoke_claude(sid: &str, prompt: &str, known: bool) -> Result<String> {
|
||||
if known {
|
||||
return run_claude(&["--resume", sid], prompt).await;
|
||||
}
|
||||
|
||||
// session might exist from before restart — try resume first
|
||||
match run_claude(&["--resume", sid], prompt).await {
|
||||
Ok(out) => {
|
||||
info!(%sid, "resumed existing session");
|
||||
Ok(out)
|
||||
}
|
||||
Err(e) => {
|
||||
warn!(%sid, "resume failed ({e:#}), creating new session");
|
||||
run_claude(&["--session-id", sid], prompt).await
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn run_claude(extra_args: &[&str], prompt: &str) -> Result<String> {
|
||||
let mut args: Vec<&str> = vec!["--dangerously-skip-permissions", "-p"];
|
||||
args.extend(extra_args);
|
||||
args.push(prompt);
|
||||
|
||||
let out = Command::new("claude")
|
||||
.args(&args)
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::piped())
|
||||
.spawn()?
|
||||
.wait_with_output()
|
||||
.await?;
|
||||
|
||||
if out.status.success() {
|
||||
Ok(String::from_utf8_lossy(&out.stdout).to_string())
|
||||
} else {
|
||||
let err = String::from_utf8_lossy(&out.stderr);
|
||||
anyhow::bail!("exit {}: {err}", out.status)
|
||||
}
|
||||
}
|
||||
|
||||
fn split_msg(s: &str, max: usize) -> Vec<&str> {
|
||||
if s.len() <= max {
|
||||
return vec![s];
|
||||
}
|
||||
let mut parts = Vec::new();
|
||||
let mut rest = s;
|
||||
while !rest.is_empty() {
|
||||
if rest.len() <= max {
|
||||
parts.push(rest);
|
||||
break;
|
||||
}
|
||||
let mut end = max;
|
||||
while !rest.is_char_boundary(end) {
|
||||
end -= 1;
|
||||
}
|
||||
let (chunk, tail) = rest.split_at(end);
|
||||
parts.push(chunk);
|
||||
rest = tail;
|
||||
}
|
||||
parts
|
||||
}
|
||||
Reference in New Issue
Block a user