接入Websocket,自动接收CSDN短消息

最近在研究Websocket功能,本来想接入抖音和快手的弹幕功能,以及短消息功能。

在了解的过程中,也开发了一些测试项目。

这不是,就把CSDN的短消息项目给弄出来了。

直接上代码:

python 复制代码
# !/usr/bin python3
# -*- encoding=utf-8 -*-
# Description : 
# Author  : 
# @Email : 
# @File : csdn.py
# @Time : 2023-09-05 15:18:58
# @Project : live_core

import requests
import websocket
import threading
import time
import json
import logging
import re


class CSDN(object):

    user_name = ''
    device_id = ''
    cookie = ''

    def init_wws(self, cookie):
        try:
            self.cookie = cookie
            self.user_name = re.search('UserName=(.*?);', cookie).group(1)
            self.device_id = re.search('uuid_tt_dd=(.*?);', cookie).group(1)
        except Exception as e:
            logging.error('错误'.format(e.args))

    def _connect_data(self):
        _url = 'https://bizapi.csdn.net/im-manage/v1.0/dispatch/do'
        _h = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/115.0.0.0 Safari/537.36',
            'Cookie': self.cookie
        }

        _d = {
            'appId': "CSDN-PC",
            'channelType': "privateMsg",
            'deviceId': self.device_id,
            'groupId': "CSDN-private-MSG",
            'linkType': 1,
            'token': "",
            'userId': self.user_name
        }

        _req = requests.post(_url, headers=_h, json=_d)
        return _req.json()

    def _on_open(self, ws):
        _body = self._connect_data()
        # print(_body.get('data'))
        _body_data = _body.get('data')
        _data = {
            'body': {
                'userId': self.user_name,
                'appId': 'CSDN-PC',
                'imToken': _body_data.get('imToken'),
                'groupId': 'CSDN-private-MSG'
            },
            'cmdId': 2,
            'isZip': 0,
            'ver': '1.0'
        }
        ws.send(json.dumps(_data))
        threading.Thread(target=self._keep_heart_beat, args=(ws,), daemon=True).start()

    def _keep_heart_beat(self, ws: websocket.WebSocketApp):
        while True:
            time.sleep(5)
            _payload = {
                'cmdId': 1
            }
            ws.send(json.dumps(_payload))

    def _on_message(self, ws: websocket.WebSocketApp, message):
        logging.info(message)

    def _on_error(self, ws: websocket.WebSocketApp, error):
        logging.error(error)

    def _on_close(self, ws):
        logging.info('close')

    def wss_start(self):
        websocket.enableTrace(False)
        ws = websocket.WebSocketApp(
            'wss://im-linkserver-66.csdn.net/', on_message=self._on_message, on_error=self._on_error, on_close=self._on_close,
            on_open=self._on_open
        )
        ws.run_forever()


if __name__ == '__main__':
    LOG_FORMAT = "%(asctime)s - %(levelname)s - %(message)s"
    logging.basicConfig(level=logging.DEBUG, format=LOG_FORMAT)

    # cookies 这里填CSDN的Cookies
    _c = ''

    _csdn = CSDN()
    _csdn.init_wws(_c)
    _csdn.wss_start()

运行结果如下:

相关推荐
LabVIEW开发11 分钟前
LabVIEW气体污染无线监测
网络·labview·labview知识·labview功能·labview程序
error:(15 分钟前
【从零到公网】本地电脑部署服务并实现公网访问(IPv4/IPv6/DDNS 全攻略)
网络·智能路由器
酷飞飞41 分钟前
Python网络与多任务编程:TCP/UDP实战指南
网络·python·tcp/ip
风中的微尘2 小时前
39.网络流入门
开发语言·网络·c++·算法
hsjkdhs2 小时前
网络编程之UDP广播与粘包问题
网络·网络协议·udp
学生信的大叔3 小时前
【Python自动化】Ubuntu24.04配置Selenium并测试
python·selenium·自动化
GAOJ_K4 小时前
弧形导轨如何提升新能源汽车的能效和续航里程?
科技·自动化·汽车·制造
全栈工程师修炼指南4 小时前
告别手动构建!Jenkins 与 Gitlab 完美协作,根据参数自动化触发CI/CD流水线实践
运维·ci/cd·自动化·gitlab·jenkins
AD钙奶-lalala4 小时前
SpringBoot实现WebSocket服务端
spring boot·后端·websocket
yzx9910134 小时前
接口协议全解析:从HTTP到gRPC,如何选择适合你的通信方案?
网络·人工智能·网络协议·flask·pygame