telegram机器人bot自动更换VPS IP
安装必要的安装包
pip install python-telegram-bot requests
创建bot.py,并更改配置变量
import os import subprocess import logging from telegram import Update from telegram.ext import Application, CommandHandler, ContextTypes # 配置日志 logging.basicConfig( format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO ) # 配置变量 TELEGRAM_TOKEN = '8195299999:AAHXN99999wPciJTG-0k8leg99999Lhdwqcis' API_URL = 'https://api.coldshrink.cc/ipch/cawr99999a' ALLOWED_USER_IDS = [1208199999] async def change_ip(update: Update, context: ContextTypes.DEFAULT_TYPE): logger = logging.getLogger(__name__) if update.effective_user.id not in ALLOWED_USER_IDS: logger.warning(f"未授权用户 {update.effective_user.id} 尝试访问") await update.message.reply_text("您没有权限使用此命令。") return try: status_message = await update.message.reply_text("T叔,正在更换 IP...") # 添加超时控制的 curl 命令 process = subprocess.run( ['curl', '-m', '30', API_URL], capture_output=True, text=True, timeout=35 ) if process.returncode == 0: result = process.stdout.strip() success_message = f"T叔,IP 更换操作完成!\n返回结果: {result}" await status_message.edit_text(success_message) logger.info(f"IP 更换成功: {result}") else: error_msg = f"T叔,IP 更换失败。\n错误信息: {process.stderr}" await status_message.edit_text(error_msg) logger.error(f"curl 命令执行失败: {process.stderr}") except subprocess.TimeoutExpired: await status_message.edit_text("T叔,请求超时,请稍后重试。") logger.error("API 请求超时") except Exception as e: error_msg = f"发生错误: {str(e)}" await update.message.reply_text(error_msg) logger.error(f"未预期的错误: {str(e)}", exc_info=True) async def start(update: Update, context: ContextTypes.DEFAULT_TYPE): await update.message.reply_text( "T叔,欢迎使用 IP 管理机器人!\n" "使用 /change_ip 命令来更换 IP 地址。" ) def main(): # 创建应用 application = Application.builder().token(TELEGRAM_TOKEN).build() # 添加命令处理器 application.add_handler(CommandHandler("start", start)) application.add_handler(CommandHandler("change_ip", change_ip)) # 启动机器人 print("机器人已启动...") application.run_polling() if __name__ == '__main__': main()
用python3来运行机器人
python3 bot.py
创建系统服务来实现开机自动启动
nano /etc/systemd/system/telegram-bot.service
[Unit] Description=Telegram IP Change Bot After=network.target [Service] Type=simple User=root WorkingDirectory=/root ExecStart=/usr/bin/python3 /root/bot.py Restart=always RestartSec=10 [Install] WantedBy=multi-user.target
重新加载systemd配置
systemctl daemon-reload
启动服务,并设置开机自启
systemctl start telegram-bot systemctl enable telegram-bot
检查服务状态,或者查看日志
systemctl status telegram-bot journalctl -u telegram-bot -f