python Flask 开发一个机器人的HTTP服务

##1、创建一个Flask 项目,一下是目录结构
.
├── api
│   ├── init.py
│   ├── pycache
│   │   ├── init.cpython-36.pyc
│   │   └── wechat.cpython-36.pyc
│   └── wechat.py
├── manage.py
└── requirements.txt

2、查看代码文件

2.1、查看wechat.py

#!/usr/bin/env python
# -*- coding:utf-8 -*-
from urllib import parse, request
import json


class WeChatAPI(object):
    def __init__(self, http_url, message, on_off=False):
        self.http_url = http_url
        self.message = message
        self.on_off = on_off

    def run(self):
        HEADERS = {
            "Content-Type": "application/json ;charset=utf-8 ",
            "Charset": "UTF-8"
        }
        String_textMsg = {
            "msgtype": "text",
            "text": {"content": self.message},
            "atMobiles": [
                "18877672325"  # 如果需要@某人,这里写他的手机号
            ],
            "at": {
                "isAtAll": self.on_off
            }
        }

        # 对请求的数据进行json封装
        sendData = json.dumps(String_textMsg)
        sendData = sendData.encode("utf-8")

        # 发送请求
        req = request.Request(url=self.http_url, data=sendData, headers=HEADERS)
        # 将请求发回的数据构建成为文件格式
        opener = request.urlopen(req)
        result = opener.read().decode(encoding="utf-8")
        return eval(result)
        
if __name__ == "__main__":
    print (WeChatAPI(http_url="webhook地址",message ='吃饭了', on_off=True).run())
暂无评论