一个用于通过 Telegram 控制服务器部署命令的小型 Rust Bot。Bot 只执行 TOML 配置中明确声明的白名单命令,不提供任意 Shell 入口,也不接受 Telegram 命令参数。
- 使用 Telegram 长轮询,无需开放服务器入站端口。
- 支持用户 ID 和聊天 ID 白名单;两者都配置时必须同时匹配。
- 支持全局工作目录和单命令工作目录,避免脚本依赖相对路径时执行失败。
- 支持补充
PATH、执行超时和 Telegram 输出长度限制。 - 服务器命令全局串行;已有命令运行时,新请求会立即被拒绝而不会排队。
- 忽略 Bot 停机期间积压的旧命令,避免恢复服务后意外执行。
- 在 Telegram 中联系 @BotFather,发送
/newbot创建 Bot 并保存 Token。 - 向新 Bot 发送一条消息。如果要在群聊中使用,请先把 Bot 加入群聊并在群里发送消息。
- 将 Token 替换到下面的地址,通过 Telegram Bot API 查看更新:
curl --silent "https://api.telegram.org/bot123456:replace-me/getUpdates"返回结果中的 message.from.id 是用户 ID,message.chat.id 是聊天 ID。群聊 ID 通常是负数。获取后将它们填入 TOML 白名单,并注意不要把 Token 提交到版本库或粘贴到不可信环境。
复制并编辑示例配置:
sudo install -Dm600 config.example.toml /opt/telegram-command-bot/config.toml
sudo editor /opt/telegram-command-bot/config.tomlToken 直接配置在 [telegram] 中:
[telegram]
token = "123456:replace-me"每条 Telegram 命令使用独立配置表:
[commands.restart_llm]
command = "./scripts/restart-llm.sh"
description = "重启 LLM 服务"
working_directory = "/opt/server-control"
timeout_seconds = 180commands.<名称>.working_directory 优先于 execution.working_directory。所有配置的工作目录都必须是 Bot 启动时已经存在的绝对路径,否则配置加载会失败。
execution.executable_directories 会添加到进程继承的 PATH 前面。这可以解决命令在 SSH 交互终端中能运行,但由 systemd 启动后找不到 docker、node、uv 或自定义工具的问题。对于需要 sudo 的高权限操作,仍建议在脚本和 sudoers 中使用可执行文件绝对路径。
cargo build --release二进制文件位于 target/release/telegram-command-bot。
静态链接交叉编译示例:
rustup target add x86_64-unknown-linux-musl
cargo build --release --target x86_64-unknown-linux-musl
rustup target add aarch64-unknown-linux-musl
cargo build --release --target aarch64-unknown-linux-musl确保配置中的工作目录已经创建,然后执行:
./target/release/telegram-command-bot --config ./config.example.toml不传 --config 时默认读取当前目录下的 config.toml。可通过 RUST_LOG 调整日志级别,例如 RUST_LOG=telegram_command_bot=debug。
将软件和配置统一放在同一个目录,并确认下面两个文件已经就位:
/opt/telegram-command-bot/telegram-command-bot/opt/telegram-command-bot/config.toml
创建 /etc/systemd/system/telegram-command-bot.service:
[Unit]
Description=Telegram Command Bot
After=network-online.target
Wants=network-online.target
[Service]
ExecStart=/opt/telegram-command-bot/telegram-command-bot --config /opt/telegram-command-bot/config.toml
Environment=RUST_LOG=telegram_command_bot=info
Restart=on-failure
RestartSec=5
[Install]
WantedBy=multi-user.target启动:
sudo systemctl daemon-reload
sudo systemctl enable --now telegram-command-bot查看日志:
sudo journalctl -u telegram-command-bot -f以后修改 config.toml 后执行 sudo systemctl restart telegram-command-bot 即可。这个最小配置默认以 root 运行;如果希望改用已有普通用户,只需在 [Service] 中增加 User=用户名。
/help:显示配置的帮助信息。/commands:列出所有白名单命令及其描述。/命令名:执行对应的固定命令;不接受/命令名 参数形式。
群聊中的 /命令名@Bot用户名 形式同样受支持。执行结果会返回退出码以及 stdout、stderr;过长输出会被截断。
config.toml包含 Bot Token,应限制为 root 所有、权限600,并避免提交到 Git。- 同时配置精确的用户 ID 和聊天 ID,避免只依赖群成员身份。
- 默认 systemd 服务以 root 执行所有白名单命令,请严格保护 Token 和白名单。
- 不要在白名单命令字符串中拼接任何不可信变量。
MIT