Created
October 22, 2018 02:55
-
-
Save lawulu/6b0e1d8f1dd5334f6306adc3d1828e31 to your computer and use it in GitHub Desktop.
wechat bot Api
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from flask import Flask, request | |
from flask_restful import Resource, Api, abort | |
from flask_pymongo import PyMongo | |
import itchat | |
import logging | |
from logging.handlers import RotatingFileHandler | |
EMPTY="_EMPTY_" | |
app = Flask(__name__) | |
app.config["MONGO_URI"] = "mongodb://localhost:27017/test" | |
#@see http://api.mongodb.com/python/current/ | |
mongo = PyMongo(app) | |
alerts = mongo.db.wechat_bot_alert | |
api = Api(app) | |
wx_groups={} | |
class Alert(Resource): | |
def post(self): | |
app.logger.info('got Info',request.json) | |
body = request.json | |
body["isSent"] =0 | |
group=body.get("group",EMPTY) | |
msg=body.get("message",EMPTY) | |
if group == EMPTY: | |
abort(400, error_message='empty group') | |
group_id = wx_groups.get(group,EMPTY) | |
if group_id == EMPTY: | |
alerts.insert_one(body) | |
abort(400, error_message='no group named ' + group + " founded") | |
wx_response = itchat.send_msg(msg,group_id) | |
response_code = wx_response["BaseResponse"]["Ret"]; | |
body["isSent"] =1 | |
res = alerts.insert_one(body) | |
app.logger.ino | |
if response_code != 0: | |
abort(400, error_message="can not send msgs please contact the admin ") | |
return {'message': "send message successfully"} | |
api.add_resource(Alert, '/alert') | |
def update_chatrooms(): | |
chatrooms = itchat.get_chatrooms() | |
for chatroom in chatrooms: | |
wx_groups[chatroom["NickName"]]=chatroom["UserName"] | |
if __name__ == '__main__': | |
itchat.auto_login(hotReload=True, enableCmdQR=2, loginCallback=update_chatrooms) | |
#https://gist.github.com/ibeex/3257877 | |
handler = RotatingFileHandler('api.log', maxBytes=10000, backupCount=30) | |
handler.setLevel(logging.INFO) | |
app.logger.addHandler(handler) | |
app.run(debug=True) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment