企业微信-会话内容存档-python3对接Linux_C_SDK-libWeWorkFinanceSdk_C.so

东郭鹤龄
2023-12-01
import base64
import ctypes
import json

import Crypto
from Crypto.Cipher import PKCS1_v1_5
from Crypto.PublicKey import RSA


class WxWork:
    CORP_ID = ''
    PRI_KEY = ''
    CHAT_SECRET = ''

    @classmethod
    def sync_msg(cls):
        dll = ctypes.cdll.LoadLibrary(os.getcwd() + "/libWeWorkFinanceSdk_C.so")  # 真实libWeWorkFinanceSdk_C位置
        new_sdk = dll.NewSdk()
        result = dll.Init(new_sdk, cls.CORP_ID.encode(), cls.CHAT_SECRET.encode())
        if result != 0:
            return
        private_key = RSA.import_key(cls.PRI_KEY)
        cipher = Crypto.Cipher.PKCS1_v1_5.new(private_key)
        seq = 0
        while True:
            s = dll.NewSlice()
            dll.GetChatData(new_sdk, seq, 1000, '', '', 5, ctypes.c_long(s))
            data = dll.GetContentFromSlice(s)
            data = ctypes.string_at(data, -1).decode("utf-8")
            dll.FreeSlice(s)
            data = json.loads(data).get('chatdata')
            if not data:
                break
            seq = data[-1].get('seq')
            for msg in data:
                encrypt_key = cipher.decrypt(base64.b64decode(msg.get('encrypt_random_key')), "ERROR")
                ss = dll.NewSlice()
                dll.DecryptData(encrypt_key, msg.get('encrypt_chat_msg').encode(), ctypes.c_long(ss))
                result = dll.GetContentFromSlice(ss)
                result = ctypes.string_at(result, -1).decode("utf-8")
                result = json.loads(result)
                dll.FreeSlice(ss)
                print(result)
        dll.DestroySdk(new_sdk)


if __name__ == '__main__':
    WxWork.sync_msg()

 类似资料: