微信发博客

193 阅读2分钟

kevin-bhagat-343433-unsplash.jpg

Photo by Kevin Bhagat on Unsplash

在小武 2 岁的时候我创建了 《小武成长记》 网站: jiaxianhua.com

今年还没有更新一次博文。

jiaxianhua.com/jekyll/upda…

记录了网站的创建过程。

当时是用 jekyll 创建的,发 post 的话运行 rake 命令,交互式的创建标题,子标题,分类等,最后生成 post 模板,再写内容。

如果当天没有打开电脑,就发不了文章。

后来发现官方提供 github.com/jekyll/jeky…,可以网页发文章。

微信发博客

如果有人想要添加小武成长的故事,通过微信把内容发给我,我还要自己更新 github 仓库。

微信收到内容后可以自动发博文就太好了。

如何实现呢?

简单的三步:

  1. 收到微信通知
  2. 生成博文
  3. 更新博文

搞定!

1. 收到信息通知

这个可以能过 github 上面开源的聊天机器人实现。

我之前用过 WeixinBot,这里使用 ItChat。

首先创建一个后台运行的环境。

$ screen -S growth15

安装 itchat

$ pip3 install itchat

测试一下

有了 itchat,如果你想要给文件传输助手发一条信息,只需要这样:

import itchat

itchat.auto_login(True, enableCmdQR=2)

itchat.send('Hello, filehelper', toUserName='filehelper')

文本消息

如果你想要回复发给自己的文本消息,只需要这样:

import itchat

@itchat.msg_register(itchat.content.TEXT)
def text_reply(msg):
    return msg.text

itchat.auto_login(enableCmdQR=2)
itchat.run()

客服

import itchat
import re

@itchat.msg_register(itchat.content.TEXT)
def text_reply(msg):
    reply = {
            "发货|包装": "已经包装好,正在发货!",
            "功效|使用方法": "你应该这么使用。。。有这些作用。。。"
            }
    text = msg.text
    print(text)
    for key, value in reply.items():
        if (re.search(key, text)):
            return value

itchat.auto_login(enableCmdQR=2)
itchat.run()

2. 生成博文

import itchat
import re
import time
import os

def post(text):
    post_head = """---
layout: post
title: {title}
subtitle:
author: 小武
date: {date}
categories:
tag:
---
"""
    now = time.localtime()
    title = time.strftime("%Y 年 %m 月 %d 日")
    date = time.strftime("%Y-%m-%d %H:%M:%S +0800")

    content = post_head.format(title=title, date=date)
    content += text
    filename = time.strftime("_posts/%Y-%m-%d-%H-%M-%S-growth15.md")
    with open(filename, 'w') as f:
        f.write(content)

3. 更新博文

主要是 git push

    commit = "git commit -m '{}'".format(title)
    os.system("git add -A")
    os.system(commit)
    os.system("git push")
    return '发送成功'

测试一下

growth15.png

jiaxianhua.com/2019/04/18/…

growth15.com.png

完美!

PS. 这里只是举了一个简单的例子,我并没有处理图片,视频等内容,有需要的赶紧行动起来。