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:
Fam Zheng
2026-04-05 06:56:46 +01:00
commit db8ff94f7c
9 changed files with 2651 additions and 0 deletions

260
src/main.rs Normal file
View 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
}