The background,

At present, some members of the project group want to forward specific messages according to the group, including text, pictures and language, when there are many replies from wechat group messages among the team members. In this is only their own implementation for reference only, you can modify more functions according to their own needs.

Second, the code

2.1 Enterprise wechat related information

  • Corporate ID: corpid

  • Self-built application AppID
  • Self-built application Secret

  • Get access_token API
  • Sending message API

2.2 Server Deployment Environment: Python 2.7

git clone https://github.com/redhatxl/wechatmsg.git
nohup python2.7 wechatmsg/wx_msg_server.py &
Copy the code

2.3 Refer to RUL:

Gets the access_token send message

2.4 code

  • Core code Github address
Flask framework backend
  def server_run(self):
        app = Flask(__name__)
        @app.route('/index', methods=['GET'.'POST'])
        def index():

            wxcpt = WXBizMsgCrypt(self.sToken, self.sEncodingAESKey, self.sCorpID)
            Get parameters related to url authentication sent by wechat
            sVerifyMsgSig = request.args.get('msg_signature')
            sVerifyTimeStamp = request.args.get('timestamp')
            sVerifyNonce = request.args.get('nonce')
            sVerifyEchoStr = request.args.get('echostr')

            # verification url
            if request.method == 'GET':
                ret, sEchoStr = wxcpt.VerifyURL(sVerifyMsgSig, sVerifyTimeStamp, sVerifyNonce, sVerifyEchoStr)
                print type(ret)
                print type(sEchoStr)

                if(ret ! = 0) :print "ERR: VerifyURL ret:" + str(ret)
                    sys.exit(1)
                return sEchoStr

            Receive client messages
            if request.method == 'POST':
                sReqMsgSig = sVerifyMsgSig
                sReqTimeStamp = sVerifyTimeStamp
                sReqNonce = sVerifyNonce
                sReqData = request.data
                print(sReqData)

                ret, sMsg = wxcpt.DecryptMsg(sReqData, sReqMsgSig, sReqTimeStamp, sReqNonce)
                print ret, sMsg
                if(ret ! = 0) :print "ERR: DecryptMsg ret: " + str(ret)
                    sys.exit(1)
                Parse the sent content and print it

                xml_tree = ET.fromstring(sMsg)
                print('xml_tree is ', xml_tree)

Copy the code
  • Sending message content
 def _send_text_msg(self, content):
        data = {
            "touser": ('|').join(self.userid.split(', ')),
            "toparty": ('|').join(self.partid.split(', ')),
            # "toparty":int(self.partid),
            "msgtype": "text"."agentid": self.agent_id,
            "text": {
                "content": content
            },
            "safe": 0
        }
        try:
            response = requests.post(self.send_msg_url.format(self.access_token), json.dumps(data))
            self.logoper.info(response.text)
            print(response.text)
            result_msg = json.loads(response.content)['errmsg']
            return result_msg
        except Exception as e:
            self.logoper.info(e)

Copy the code
  • The log
   def create_dir(self):
        """Create directory :return: file name"""
        _LOGDIR = os.path.join(os.path.dirname(__file__), self.logdir_name)
        _TIME = time.strftime('%Y-%m-%d', time.gmtime()) + The '-'
        _LOGNAME = _TIME + self.logfile_name
        LOGFILENAME = os.path.join(_LOGDIR, _LOGNAME)
        if not os.path.exists(_LOGDIR):
            os.mkdir(_LOGDIR)
        return LOGFILENAME

    def create_logger(self, logfilename):
        """Create logger object :param logfilename: :return: Logger object"""
        logger = logging.getLogger()
        logger.setLevel(logging.INFO)
        handler = logging.FileHandler(logfilename)
        handler.setLevel(logging.INFO)
        formater = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
        handler.setFormatter(formater)
        logger.addHandler(handler)
        return logger

Copy the code

The configuration file

# Define wechat public account information
[common]
# Enterprise wechat enterprise ID
corpid = wxe23xxxxxxxxxxx


Receive message server configuration
[recmsg]

Token = mVNAAw3xxxxxxxxxxxxxxxxx
EncodingAESKey = vwbKImxc3WPeE073xxxxxxxxxxxxxxxxxx


# Self-build app information
[appconfig]
# Build your own app Agentid
agentid = 1000002
# Self-built app Secret
secret = 6HAGX7Muw36pv5anxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

# Message receive message
User ID if multiple users are separated by ','
userid = xuel|yaoy

Id of the receiving department, if multiple departments are separated by ','
partid = 11


[urlconfig]
Get the APPLICATION token API interface
get_access_token_url = https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={}&corpsecret={}
Send message API
send_msg_url = https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token={}
# Upload media API to get mediaid
upload_media_url = https://qyapi.weixin.qq.com/cgi-bin/media/upload?access_token={}&type=image
Upload hd voice interface
upload_video_url = https://qyapi.weixin.qq.com/cgi-bin/media/get/jssdk?access_token={}&media_id={}

[loginfo]
# log directory
logdir_name = logdir
# Log file name
logfile_name = wechat_server.log

Copy the code

Three, test,

When sending messages on enterprise wechat, you can modify the configuration file to forward the messages to specific groups, thus avoiding message diversion. Enable the application API and set the callback address

Four, optimization

  • The access_token obtained each time can be saved to the database together with the database. After the access_token expires in 2 hours, the access_token can be obtained again.
  • More content forwarding