oldl

oldl

Tutorial: Building an Automated Personal Blog in the Cloud with Hexo + Yuque + Tencent Cloud Functions.

The original text was published on the public account: Music and Beer
Due to the possibility of incomplete display of reprinted images, please refer to the original text.
https://mp.weixin.qq.com/s?__biz=MzI1NTg2NzQyOA==&mid=2247489178&idx=1&sn=a41a6400af3703ace1df85d34acf42fa&chksm=ea2e39d1dd59b0c76a9f4e38e8ce1345416515c8691fce04bd6e4790a6ee102faebf584bee42&mpshare=1&scene=1&srcid=1222PiZqOCbXJzVXNvqxSogq&sharer_sharetime=1640131461472&sharer_shareid=b206f2fa812b6ca26b027c2ef010574f#rd

How to use hexo + Yuque + serverless cloud functions to achieve automatic blog publishing 

After spending a few days searching through all relevant materials online, I finally summarized it into this tutorial, which is also a record for myself. Through this tutorial, you can store your articles in the cloud, achieving cloud writing (not limited to MAC systems, Windows systems, mobile WeChat mini-programs), freeing yourself from the limitations of local machines. In addition, an excellent and simple rich text editor can greatly enhance your writing efficiency, allowing you to focus more on writing text. By combining GitHub Actions (GitHub automatic deployment), serverless cloud functions (Tencent Cloud API, used for triggering deployment events), Yuque (document publishing), and Hexo (blog system), you can automatically implement the process of publishing articles to the blog.

Preparation before use
To better and more conveniently complete the deployment of hexo × Yuque, you need a certain foundation before starting the process setup. If you encounter problems, you can search for them on Baidu and follow the steps below step by step.
Account application and authorization

 Yuque account -- Apply 
 Serverless option one (I use): Tencent Cloud account login authorization ( https://console.cloud.tencent.com/scf/), after authorizing the cloud function, proceed to API authorization ( https://console.cloud.tencent.com/apigateway/index) to use the cloud function normally.

 Serverless option two: Baidu Cloud authorization ( https://console.bce.baidu.com/cfc/#/cfc/functions), method guide for opening 
 Option three: Use the API built with Vercel.

 Obtain GitHub private key, go to GitHub's token settings ( https://github.com/settings/tokens), click the generate key button, fill in the key name, and check the repo option. Save the generated key in a newly created txt file on your desktop for backup.

Repository preparation
To achieve automatic deployment of hexo, you need to hand over the local source code files to GitHub for hosting. You can create a private repository (recommended) or a public repository. First, create a private repository on GitHub.

Step one:
Create a Yuque repository
Log in to Yuque, click Knowledge Base 👉 New Knowledge Base. Change the visibility of the knowledge base to "Visible on the Internet."

Import old articles or create new ones (at least one article must exist)
Click the management button of the knowledge base, select Import under New, and batch import the _post articles from the blog.

Create a template (can be created later)
To facilitate future document writing, you can create a template. Note that image links need to be prefixed with '' to prevent them from being rendered as links.

Step two: Install the Yuque plugin for local debugging
To ensure that the blog can be generated normally in the cloud, first debug locally.
Installation of the Yuque plugin
First, open the terminal in the root directory and install yuque-hexo.
POWERSHELL

   1 
   npm i -g yuque-hexo 
  
 

Modify package.json
Add the "yuqueConfig" code block after the first object code block.
JSON

   {  "name": "hexo-site",  "version": "0.0.0",  "private": true,  "scripts": {    "build": "hexo generate",    "clean": "hexo clean",    "deploy": "hexo deploy",    "server": "hexo server"},  "yuqueConfig": {    "postPath": "source/_posts/yuque",    "cachePath": "yuque.json",    "mdNameFormat": "slug",    "adapter": "markdown",    "concurrency": 5,    "baseUrl": "https://www.yuque.com/api/v2",    "login": "Your Yuque username",    "repo": "Your Yuque knowledge base name",    "token": "******Change this to your Yuque TOKEN*******",    "onlyPublished": true,    "onlyPublic": true  }, 
  
 

You need to modify the "login", "repo", and "token" fields.

 Click to enter the blog's knowledge base, and copy and paste the username and repository name into the "login" and "repo" fields in the browser address bar. 
 
 The Yuque token is added in the upper right corner avatar -> Account Settings -> Token, and the permission can be set to read only. Copy and paste the obtained "token" field. 
 

Modify "scripts" to add "sync": "yuque-hexo sync" and "clean": "yuque-hexo clean".
JSON

   {  "name": "hexo-site",  "version": "0.0.0",  "private": true,  "scripts": {    "build": "hexo generate",    "clean": "hexo clean",    "deploy": "hexo deploy",    "server": "hexo server",    "sync": "yuque-hexo sync",    "clean:yuque": "yuque-hexo clean"  },  "yuqueConfig": {    "postPath": "source/_posts",    "cachePath": "yuque.json",    "mdNameFormat": "slug",    "adapter": "markdown",    "concurrency": 5,    "baseUrl": "https://www.yuque.com/api/v2",    "login": "Username",    "repo": "Knowledge base name",    "token": "********TOKEN***************",    "onlyPublished": true,    "onlyPublic": true  },  "hexo": {    "version": "5.2.0"  },  "dependencies": {    "yuque-hexo": "^1.6.0",    "gulp": "^4.0.2",    "gulp-base64": "^0.1.3",    "gulp-htmlmin": "^5.0.1",    "gulp-tobase64": "^1.1.2",    "hexo": "^5.0.0",    "hexo-abbrlink": "^2.2.1",    "hexo-deployer-git": "^2.1.0",    "hexo-generator-archive": "^1.0.0",    "hexo-generator-baidu-sitemap": "^0.1.9",    "hexo-generator-category": "^1.0.0",    "hexo-generator-feed": "^3.0.0",    "hexo-generator-index-pin-top": "^0.2.2",    "hexo-generator-sitemap": "^2.1.0",    "hexo-generator-tag": "^1.0.0",    "hexo-helper-live2d": "^3.1.1",    "hexo-offline-popup": "^1.0.3",    "hexo-renderer-ejs": "^1.0.0",    "hexo-renderer-marked": "^3.0.0",    "hexo-renderer-pug": "^1.0.0",    "hexo-renderer-stylus": "^1.1.0",    "hexo-server": "^1.0.0",    "hexo-tag-aplayer": "^3.0.4",    "hexo-wordcount": "^6.0.1",    "live2d-widget-model-unitychan": "^1.0.5",    "workbox-build": "^5.1.4"  },  "devDependencies": {    "@babel/core": "^7.12.3",    "@babel/preset-env": "^7.12.1",    "del": "^6.0.0",    "gulp": "^4.0.2",    "gulp-babel": "^8.0.0",    "gulp-clean-css": "^4.3.0",    "gulp-cli": "^2.3.0",    "gulp-html-css-js-base64": "^0.0.4",    "gulp-htmlclean": "^2.7.22",    "gulp-htmlmin": "^5.0.1",    "gulp-imagemin": "^7.1.0",    "gulp-imgs-base64": "^1.0.2",    "gulp-minify-inline-json": "^1.3.4",    "gulp-uglify": "^3.0.2",    "gulp-uglify-es": "^2.0.0"  }} 
  
 

Perform local debugging
After adding, save it. Before executing the command, please back up your _post folder because the download operation from Yuque will overwrite the original _post folder. Enter 'yuque-hexo sync' in the terminal to download the articles from Yuque. Then debug using 'hexo g & hexo s'. ps: Entering 'yuque-hexo clean' will clear all articles under _post. If there are external tags, please ensure that the format of the external tag is written correctly, otherwise, errors may occur.

Step three: Configure GitHub Actions
Delete the version control files of the theme
Since you cannot push a repository inside another repository to GitHub, it will only upload an empty folder, which will cause the blog to become a blank page later. You need to delete the .git folder in the hexo theme that was cloned.
Here, only the simplest method is listed; you can also fork to create your own theme, which will not be introduced here for now.

  • Modify the meta in the hexo theme files
    Taking the butterfly theme as an example, open the theme file at /themes/butterfly/layout/includes/head.pug. Add meta (name="referrer" content="no-referrer") after meta (name="theme-color" content=themeColor). This step ensures that images in Yuque can load normally.
    YAML

    1
    meta(name="theme-color" content=themeColor)meta(name="referrer" content="no-referrer")

Modify hexo's _config.yml
Go to the root directory of the blog and modify the develop configuration in hexo's _config.yml.
POWERSHELL

   1 
   # Deployment## Docs: https://hexo.io/docs/deployment.htmldeploy:  type: git  repository:   github: https://username:the key saved in [email protected]/username/repository.git  branch: masterNote this pit, the repository name is .Github.io 
  
 

Here, only one simple solution is listed; others will be introduced when there is time.
Create GitHub Actions script
Create a new .github folder in the root directory of the blog (don't forget this), and create a workflows folder under this folder.

Create autodeploy.yml in the workflows folder and fill in the following code. Modify the user.name and user.email information after [Update Yuque pull cache and articles] and [Deploy] to your own information, paying attention to alignment.
YAML

   1 
   name: Automatic Deployment# Trigger Action when there are changes pushed and Yuque is publishedon: [push, repository_dispatch]jobs:  deploy:    runs-on: ubuntu-latest    steps:      - name: Check branch        uses: actions/checkout@v2        with:          ref: master      # After October 2020, the default branch for new GitHub repositories changed to main, be sure to change      # But private repositories seem to still be master and have not changed      - name: Install Node        uses: actions/setup-node@v1        with:          node-version: "12.x"      - name: Install Hexo        run: |          export TZ='Asia/Shanghai'          npm install hexo-cli -g          #npm install gulp-cli -g          # If you are using gulp, uncomment the above line          npm install yuque-hexo -g          yuque-hexo clean          yuque-hexo sync      - name: Update Yuque pull cache and articles # Update the articles pulled from Yuque to the GitHub repository        run: |          echo `date +"%Y-%m-%d %H:%M:%S"` begin > time.log          git config --global user.email "¥@.com"          git config --global user.name "¥¥¥"          git add .          git commit -m "Refresh yuque json" -a      - name: Push Yuque pull cache and articles # Push the modified yuque json        uses: ad-m/github-push-action@master        with:          github_token: ${{ secrets.GITHUB_TOKEN }}      - name: Cache Hexo        uses: actions/cache@v1        id: cache        with:          path: node_modules          key: ${{runner.OS}}-${{hashFiles('**/package-lock.json')}}      - name: Install dependencies        if: steps.cache.outputs.cache-hit != 'true'        run: |          npm install --save      - name: Generate static files        run: |          hexo clean          hexo g          #gulp          # If you are using gulp, uncomment the above line      - name: Deploy        run: |          git config --global user.name "¥¥"          git config --global user.email "¥¥¥@.com"          hexo deploy 
  
 

Upload blog source code
Open the terminal and enter the following commands to upload your blog source code to the private source repository.
POWERSHELL

   git initgit add .git commit -m "first commit"git remote add origin https://github.com/your_username/your_private_blog_source_repository.gitgit push -u origin master 
  
 

Perform cloud debugging
After uploading, you will find that GitHub Actions is effective. Wait a few minutes, and if it is checked, it means the deployment was successful. If not checked, please check the steps that went wrong.

The time.log file seems to not be generated automatically recently, so if the action is unsuccessful, please manually create time.log in the repository.
Step four: Configure cloud functions
Vercel option (recommended)
To facilitate everyone's calls, I wrote an API in Python. The annoying thing is that when filling in the GitHub private key in the repository, GitHub automatically deletes the key. So I tried for a long time without success. Therefore, I directly set the API as a parameter-passing type for everyone to call. API address: https://yuque-vercel-webhook-api.vercel.app/api?. Of course, you can also fork the project and set it up in Vercel yourself, replacing 'https://yuque-vercel-webhook-api.vercel.app' with your app application link. The parameters you need to pass are token, user, source.
CODE

   https://yuque-vercel-webhook-api.vercel.app/api?token='{Fill in your GitHub private key}'&user='{Fill in your GitHub username}'&source='{Fill in your GitHub repository address}'Example: https://yuque-vercel-webhook-api.vercel.app/api?token='8888888888'&user='Zfour'&source='my-blog-source-file'Use this URL path as the trigger link and configure it in Yuque. 
  
 

Modify the parameter items in the trigger link, access this link, and if 'This’s OK!' appears, it means the configuration is successful. Copy the URL path as the trigger link and configure it in Yuque.
Baidu Cloud option (recommended)
Create a new cloud function
After logging in, click to create a function.

Choose a blank function, set the timeout to 10s, and select Python 2.7 as the runtime. Click next.
Choose HTTP trigger, fill in the URL path as '/', and set the HTTP method to POST and GET, then click submit.
Click the function, select the function list, paste the following code and save it, changing the username and repository address to your own information. Replace the saved private key with ****, and keep the token field. Test the code, and when it returns "This’s OK!" and the GitHub action starts running, it means success.

PYTHON

   # -*- coding: utf8 -*-import requestsdef handler(event, context):    r = requests.post("https://api.github.com/repos/username/source_repository/dispatches",    json = {"event_type": "run-it"},    headers = {"User-Agent":'curl/7.52.1',              'Content-Type': 'application/json',              'Accept': 'application/vnd.github.everest-preview+json',              'Authorization': 'token ****GITHUB's*******'})    if r.status_code == 204:        return "This's OK!"    else:        return r.status_code 
  
 

Copy the URL path as the trigger link and configure it in Yuque.
Tencent Cloud option (with usage period)
Create a new cloud function
The Tencent Cloud option currently has a 1-year usage period, and I am currently trying the Alibaba Cloud option and Vercel option.
After logging in, click the new button. There are two cloud functions, one is serverless and the other is in static hosting. Do not choose the one in static hosting.

Fill in the basic information. Choose the runtime environment as Python 2.7, and create it in a blank way.

Fill in the following script. Change the username and repository address to your own information. Replace the saved private key with ****, and keep the token field.

PYTHON

   # -*- coding: utf8 -*-import requestsdef main_handler(event, context):    r = requests.post("https://api.github.com/repos/%%/%%/dispatches",    json = {"event_type": "run-it"},    headers = {"User-Agent":'curl/7.52.1',              'Content-Type': 'application/json',              'Accept': 'application/vnd.github.everest-preview+json',              'Authorization': 'token ******See the image above********'})    if r.status_code == 204:        return "This's OK!"    else:        return r.status_code 
  
 

Click save and test, and if it returns "This’s OK!" and the GitHub action starts running, it means success.
Create a new trigger condition
Click trigger management, create a new trigger. After clicking submit, copy the access path.

Record this access path.

Step five: Configure Yuque's webhook
Set trigger rules
In the knowledge base, select settings.

Set the trigger rules, name it whatever you like. The URL is the cloud function address you noted above. Paste the access path obtained from the cloud function (Tencent Cloud) or the URL link (Baidu Cloud).

After setting up, you can try publishing an article for testing. If the GitHub action starts executing, it means the configuration is successful.
Although it is now very convenient to use Yuque for synchronization and automatic deployment of articles, the entire process is indeed too complicated, cumbersome, and has too many pitfalls. It is recommended that those lacking hands-on ability should not attempt it. Just be honest.
The content draws on many predecessors' experiences, but there are still many unsatisfactory places. If you have any questions, you can leave a message here. Since the article was not edited in the public account, if there are any formatting errors, you can refer to the original text on my website. For reference only.

Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.