message-handler/http-handler

Description

  • Incorporate an HTTP message handler, necessitating the implementation of your own HTTP Server.
  • The delivery method is through POST.

Request URL

  • http://127.0.0.1:8888/api/

Request Method

  • POST

Parameters

Parameter NameRequiredParameter TypeDescription
typeYesintAPI ID
protocolYesintProtocol Type
urlYesstringServer Address

Request Example

 {
  "type": 1001,
  "protocol": 2,
  "url": "http://127.0.0.1:18000/"
 } 

推送示例

{
  "pushType": 1,
  "pushTime": 1685179951,
  "data": 
      {
          "from": "wxid_xxx",
          "to": "wxid_xxx",
		  "type": 1,
		  "content": "123",
		  "msgSvrID": 1111111111111111111111,
		  "reversed1": "xxx",
		  "createTime": 1685179951
      }
} 

示例代码

import re

import requests
from flask import Flask, request, jsonify

app = Flask(__name__)
WECHAT_API_URL = 'http://127.0.0.1:8888/api/'


# Method for Receiving Messages
@app.route('/wechatSDK', methods=['POST'])
def chat():
    data = request.json
    print(data)
    pushType = data["pushType"]  #
    # We only process text messages sent by groups or friends; other message formats will be disregarded.
    # For details on message types, please refer to: https://www.wechatsdk.com/en/docs/Message-Handler/Message-Type.md
    if pushType != 1 or data["data"]['type'] != 1:
        return jsonify({"success": "true"})
    msg_obj = data["data"]
    # Was it a message from a friend, or was it sent by a group?
    sendChannel = msg_obj["from"]
    # What is the content of the message sent?
    msgContent = msg_obj["content"]

    # When the message channel contains the keyword '@chatroom', it signifies a group message in the description. At this point, it becomes essential to parse the message content as it contains the sender's ID and '@' mentions.
    ifGroupMessage = "@chatroom" in sendChannel

    group_mes_send_user = None
    if ifGroupMessage:
        send_content = msgContent.split(":\n")
        # Determine which member of the group sent the message and the exact content of the message.
        group_mes_send_user, msgContent = send_content[0], send_content[1]
        msgContent = re.sub(r'@[^\u2005]+( |   $)', '', msgContent).strip()

    # # Employ an API for random quotes. Naturally, you have the flexibility to utilize any API of your choice, like ChatGPT.
    # replayMsg = requests.get("https://api.7585.net.cn/yan/api.php?lx=mj").text

    # # Send the API results to the specified friend. To explore additional WeChat API functionalities, please check: https://www.wechatsdk.com/en/docs
    # requests.post(WECHAT_API_URL, json={
    #     "type": 10009,
    #     "userName": sendChannel,  # Reply to messages from individual friends to the sender, and reply to messages from groups to the respective groups.
    #     "msgContent": replayMsg  # Reply content
    # })

    # # What should I do if I want to monitor group messages and respond whenever someone speaks?
    # if ifGroupMessage:
    #     # Employ an API for random quotes. Naturally, you have the flexibility to utilize any API of your choice, like ChatGPT.
    #     replayMsg = requests.get("https://api.7585.net.cn/yan/api.php?lx=mj").text
    #     requests.post(WECHAT_API_URL, json={
    #         "type": 10009,
    #         "userName": sendChannel,  # Reply to messages from individual friends to the sender, and reply to messages from groups to the respective groups.
    #         "msgContent": replayMsg  # Reply content
    #     })

    # "What should I do if I want to respond only when someone @mentions me in a group chat, and when I reply, I @mention them back?
    # The @ function is available exclusively for group messages.
    if ifGroupMessage:
        # First, acquire your wxid.
        login_wxid = data['robot']['userName']
        # I won't respond unless it's a message that mentions me.
        if login_wxid not in data['data']["reversed1"]:
            return jsonify({"success": "true"})
        # Employ an API for random quotes. Naturally, you have the flexibility to utilize any API of your choice, like ChatGPT.
        replayMsg = requests.get("https://api.7585.net.cn/yan/api.php?lx=mj").text

        # Obtain the sender's WeChat username.
        group_mes_send_user_Name = msg_obj["chatroomMemberInfo"]["nickName"]
        # Integrate the @mention into the reply message.
        replayMsg = f"@{group_mes_send_user_Name} {replayMsg}"
        requests.post(
            WECHAT_API_URL,
            json={
                "type": 10009,
                "userName": sendChannel,  # Reply to messages from individual friends to the sender, and reply to messages from groups to the respective groups.
                "msgContent": replayMsg,  # Reply content
                "atUserList": [group_mes_send_user]
            })

    print(f"{sendChannel} Send Message:{msgContent}")
    return jsonify({"success": "true"})


def addCallBackUrl(callBackUrl):
    """
    Configure a callback address so that whenever a message is sent, WeChat forwards the information to this designated endpoint.
    :return:
    """
    # Retrieve all callback URLs.
    resdatalist = requests.post(WECHAT_API_URL, json={
        "type": 1003
    }).json()["data"]["data"]
    # Delete the previously set callback URLs.
    for item in resdatalist:
        requests.post(WECHAT_API_URL,
                      json={
                          "type": 1002,
                          "cookie": item["cookie"]
                      })
    # Set a new callback URL.
    requests.post(WECHAT_API_URL,
                  json={
                      "type": 1001,
                      "protocol": 2,
                      "url": callBackUrl
                  })


if __name__ == '__main__':
    # Configure the WeChat callback URL to match the address of this service.
    try:
        # Set up a callback URL on WeChat so that when someone sends a message, WeChat will send the information to this interface.
        addCallBackUrl("http://127.0.0.1:18000/wechatSDK")
        print("Connection to WeChat established successfully.")
    except Exception as e:
        print("Failed to connect to WeChat.", e)
    app.run(host='0.0.0.0', port=18000)

Return Parameter Description

Parameter NameParameter TypeDescription
error_codeintError code
descriptionstringError Description
datajsonBusiness data

Remark