如何实现Git仓库更新时自动拉取代码并重启Ubuntu上的Discord Bot?
自动拉取GitHub代码并重启Discord Bot(Ubuntu环境)
针对你的需求,这里提供两种实用方案,从易到难,适合新手操作:
方案一:定时拉取(简单易上手)
适合不想折腾内网穿透的场景,定期检查仓库更新并执行操作。
- 编写更新脚本
创建一个update_bot.sh脚本,放在Bot代码目录下:
#!/bin/bash # 进入Bot代码目录 cd /path/to/your/discord-bot # 拉取最新代码 git pull origin main # 重启Bot(假设用systemd管理,后面会讲配置方法) sudo systemctl restart discord-bot.service
给脚本添加执行权限:
chmod +x update_bot.sh
- 设置定时任务
用crontab实现定时执行,比如每5分钟检查一次:
crontab -e
在打开的编辑器里添加一行:
*/5 * * * * /path/to/your/discord-bot/update_bot.sh >> /var/log/bot_update.log 2>&1
执行日志会存在/var/log/bot_update.log,方便后续排查问题。
方案二:GitHub Webhook(实时触发)
当仓库有push操作时立刻触发更新,需要解决个人笔记本的公网访问问题(用ngrok做内网穿透)。
第一步:用systemd管理Bot
先把Bot做成系统服务,方便重启和后台运行:
创建服务文件/etc/systemd/system/discord-bot.service:
[Unit] Description=My Discord Bot After=network.target [Service] User=your-ubuntu-username WorkingDirectory=/path/to/your/discord-bot ExecStart=/usr/bin/python3 bot.py # 替换成你的Bot启动命令 Restart=always # 意外崩溃自动重启 [Install] WantedBy=multi-user.target
然后启用并启动服务:
sudo systemctl daemon-reload sudo systemctl enable discord-bot.service sudo systemctl start discord-bot.service
第二步:搭建Webhook接收服务
用Python Flask快速搭建一个简单的服务:
- 安装Flask:
pip install flask
- 创建
webhook_server.py:
from flask import Flask, request import subprocess import hmac import hashlib app = Flask(__name__) SECRET = "your-custom-secret" # 后面GitHub配置要用到相同内容 BOT_UPDATE_SCRIPT = "/path/to/your/discord-bot/update_bot.sh" @app.route('/webhook', methods=['POST']) def handle_webhook(): # 验证GitHub签名(可选但提升安全性) signature = request.headers.get('X-Hub-Signature-256') if not signature: return "Unauthorized", 401 sha_name, signature_hash = signature.split('=') if sha_name != 'sha256': return "Unsupported signing method", 400 mac = hmac.new(SECRET.encode('utf-8'), msg=request.data, digestmod=hashlib.sha256) if not hmac.compare_digest(mac.hexdigest(), signature_hash): return "Unauthorized", 401 # 执行更新脚本 subprocess.run(BOT_UPDATE_SCRIPT, shell=True) return "OK", 200 if __name__ == '__main__': app.run(host='0.0.0.0', port=5000)
第三步:内网穿透(ngrok)
因为个人笔记本没有公网IP,用ngrok把本地5000端口暴露到公网:
安装ngrok后执行:
ngrok http 5000
会得到一个类似https://xxxx-xx-xx-xx-xx.ngrok.io的公网地址。
第四步:配置GitHub Webhook
在你的GitHub仓库页面,进入Settings > Webhooks > Add webhook:
- Payload URL:填写
https://xxxx-xx-xx-xx-xx.ngrok.io/webhook(替换成你的ngrok地址) - Content type:选择
application/json - Secret:填写刚才脚本里的
your-custom-secret - Which events would you like to trigger this webhook?:选择
Just the push event - 勾选
Active,点击Add webhook
前置准备注意事项
Git凭证配置:避免拉取代码时输入密码,建议用SSH密钥:
ssh-keygen -t ed25519 -C "your-github-email@example.com"把生成的
~/.ssh/id_ed25519.pub内容复制到GitHub账户的Settings > SSH and GPG keys中。权限问题:确保执行脚本的用户有sudo重启服务的权限,编辑
/etc/sudoers(用visudo命令),添加一行:your-ubuntu-username ALL=(ALL) NOPASSWD: /usr/bin/systemctl restart discord-bot.service
内容的提问来源于stack exchange,提问作者Nostalgic
相关产品推荐
相关产品推荐

