使用Webhook更新Hexo博客

本文最后更新于:2023年5月17日 晚上

这里提到的 Webhook 不是单纯意义上的 Webhook,而是一个 Webhook 的开源实现库

Webhook

Github:

到 Release 页面下载一份二进制程序,放到服务器的一个文件夹下,然后在同文件夹根目录下新建一个 hooks.yml 文件,文件结构如下:

1
2
3
. /path/to/webhook
├── ./hooks.yml
└── ./webhook

配置你需要的 Hooks

编辑配置文件 nano hooks.yml,相关配置说明参考 Hook-Definition.md

1
2
3
4
5
6
7
8
9
10
11
12
13
- id: "webhook-demo"
command-working-directory: "/www/demo"
execute-command: "update.sh"
success-http-response-code: 200
response-message: "Hook is checked."
include-command-output-in-response: true

- id: "my-hexo"
command-working-directory: "/www/my-hexo"
execute-command: "update.sh"
success-http-response-code: 200
response-message: "Hook is checked."
include-command-output-in-response: true
  • execute-command 参数说明:
    脚本为相对路径时,最终执行的命令为 ${command-working-directory}/${execute-command},如 /www/my-hexo/update.sh
    脚本为绝对路径时,command-working-directory 将作为工作路径参数传入到执行脚本中

一切都配置完成后,运行启动命令,相关参数参考 Webhook-Parameters.md

1
./webhook -verbose -ip "127.0.0.1" -port 9000 --hooks hooks.yml -hotreload -pidfile ./webhook.pid

以如上配置做举例说明:当 webhook 程序运行后,它将运行一个服务并监听两个接口:

  • http://yourserver:9000/hooks/my-hexo
  • http://yourserver:9000/hooks/webhook-demo

调用相应的 Hooks 会执行配置的脚本,例如:

1
2
3
curl -X "POST" -H "Content-Type: application/json" -d "{}" -i http://yourserver:9000/hooks/my-hexo
# 会执行配置文件中 'command-working-directory/execute-command' 配置的脚本
/www/my-hexo/update.sh

配置 Hooks 触发

以上就是你所拥有的 Webhooks 了,接下来只要把这两个接口配置到你所需要调用的地方就可以了,比如 Github 或 Gitlab 仓库的Webhooks配置中:

img name
img name

配置执行脚本

update.sh 脚本中写入你所需要进行的操作即可,例如我是打算根据 git 仓库的推送事件,进行博客的更新操作:

1
2
3
4
5
6
7
8
#!/bin/bash
cd `dirname $0`

git pull

hexo clean && hexo g --silent

chown www:www -R ./public

update.sh 放入 hexo 博客的文件夹内随 git 仓库一同保存,这样以后本地编辑文章并推送到仓库后,Github 或 Gitlab 就会调用服务端的 Webhooks,然后去执行所配置路径下的 update.sh 脚本,这样就达到了自动更新博客的目的。

注:如果你的服务器执行 git pull 每次都要输入用户名密码进行验证,可提前在服务器端执行以下命令:

1
2
# 执行一次即可
git config --global credential.helper store

这样以后就不需要每次都进行验证了,参考:部署Hexogit-credential-cache


使用Webhook更新Hexo博客
https://blog.doracoin.cc/posts/days/34223.html
作者
Doracoin
发布于
2023年5月17日
更新于
2023年5月17日
许可协议