python Flask 编写一个简单的机器人通知

1、wechat.py

#!/usr/bin/env python
# -*- coding:utf-8 -*-
from urllib import parse, requestimport 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": [
                "号码"  # 如果需要@某人,这里写他的手机号
            ],
            "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="web_hook地址[",message](https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=df23f060-d6ac-403f-8c5a-672ece9bf24c",message) ='吃饭了', on_off=True).run())



2、flask 运行代码manage.py

from flask import Flask,request
from api.wechat import WeChatAPI
import json
app = Flask(__name__)


@app.route('/robot/api/v1')
def send_message():
    webhook_url = request.args.get('webhook_url')
    message = request.args.get('message')
    on_off = True if request.args.get('on_off').lower() == 'true' else False
    print (type(webhook_url), type(message), type(on_off))    result = WeChatAPI(http_url=webhook_url, message=message, on_off=on_off).run()

    msg = {
        'webhook_url': webhook_url,
        'message': message,
        'on_off': on_off,
        'result': result.get('errmsg')    }

    return json.dumps(msg,ensure_ascii=False)


if __name__ == '__main__':
    app.run(host='0.0.0.0')
暂无评论