半夜无法实时监控服务器后台跑的任务,从而造成时间浪费

笔者想要从0开始开发一个telegram bot,作为与以claude code为大脑的本地linux服务器的通信转发桥梁,以实现在手机上达到对服务器的操控。

获取Bot Token与User ID

首先,找到用户@BotFather运行

/newbot

创建一个新bot

然后,为之命名(对话框里bot显示的名字,可任意取)

myserverbot

接着,为之命制一个独一无二的名字(用于指代)

qy_server_bot

于是,bot创建成功!它会返回一串bot token。

同样地,为了服务于特定用户,我们需要找到用户@userinfobot运行

/start

获得一串用户ID

v0.1版本:连通bot链路

serverbot/
├── bot.py             # 主程序入口
├── requirements.txt   # 依赖声明
└── .env               # 环境变量(BOT_TOKEN 等)
#bot.py
import os
from dotenv import load_dotenv
from telegram import Update
from telegram.ext import Application,CommandHandler,ContextTypes

load_dotenv()

BOT_TOKEN=os.environ["BOT_TOKEN"]
ALLOWED_USERS_ID=int(os.environ["ALLOWED_USERS_ID"])

#是否是指定用户
def is_authorized(update:Update)->bool:
    user=update.effective_user
    return user is not None and user.id==ALLOWED_USERS_ID

#start命令处理
async def start(update:Update,context: ContextTypes.DEFAULT_TYPE):
    if not is_authorized(update):
        await update.effective_message.reply_text("你没有权限使用此机器人。")
    await update.effective_message.reply_text(
        "欢迎使用服务器管理机器人!\n\n"
        "可用命令:\n"
        "/start - 显示此消息\n"
        "/status - 获取服务器状态\n"
        "/restart - 重启服务器\n"
        "/shutdown - 关闭服务器\n"
        "/update - 更新服务器\n"
    )

#ping命令处理
async def ping(update:Update,context: ContextTypes.DEFAULT_TYPE):
    if not is_authorized(update):
        await update.effective_message.reply_text("你没有权限使用此机器人。")
    await update.effective_message.reply_text("Pong!")

#main函数
def main():
    app=Application.builder().token(BOT_TOKEN).build()
    #注册命令处理器
    app.add_handler(CommandHandler("start",start))
    app.add_handler(CommandHandler("ping",ping))
    #启动机器人
    app.run_polling()

if __name__=="__main__":
    main()
#requirements.txt
python-telegram-bot==21.*
python-dotenv
#.env
BOT_TOKEN=xxx
ALLOWED_USERS_ID=xxx

Updated: