chore: 添加参考文件

This commit is contained in:
sealday 2024-04-05 17:04:09 +08:00
parent 105f23d8a2
commit b35c692998
5 changed files with 281 additions and 0 deletions

View File

@ -0,0 +1,80 @@
import asyncio
import requests
import websockets
import time
import json
from datetime import datetime
# 构建API请求链接
room_id = "17066184578990"
timestamp = int(time.time() * 1000)
api_url = f"https://live-api.immomo.com/open/m/room/profile?roomid={room_id}&momoid=&src=m50011&web_uid=11126216061Xazx3TgC&_= {timestamp}"
# 发起API请求
response = requests.get(api_url)
data = response.json()
ws_token = data["data"].get("ws_token", "")
umomoid = data["data"]["momoid"]
async def connect():
uri = "wss://live-ws.immomo.com/ws/im"
async with websockets.connect(uri) as websocket:
print(f"链接websocket:[{uri}] 完成")
momoid = umomoid
roomid = room_id
token = f"{ws_token}"
data = '{{"msg_id":1,"client_time":{0},"type":"Sauth","data":{{"momoid":"{1}","roomid":"{2}","token":"{3}","barType":"NORMAL"}}}}'.format(
timestamp, momoid, roomid, token)
print(data)
await websocket.send(data)
print("Send Hello")
while True:
try:
response = await websocket.recv()
current_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
#print(f"[{current_time}] 收到原始消息 => " + response)
try:
json_data = json.loads(response)
#print(f"[{current_time}] 收到JSON消息 => ", json_data)
message_type = json_data['groups'][0]['units'][0]['type']
if message_type == "Message":
nick = json_data['groups'][0]['nick']
text = json_data['groups'][0]['units'][0]['Msg.Message.data']['text']
print(f"[{current_time}] {nick} : {text}")
elif message_type == "EnterRoom":
text = json_data['groups'][0]['units'][0]['Set.EnterRoom.data']['text']
print(f"[{current_time}] 有新人: {text}")
elif message_type == "BiliBili":
nick = json_data['groups'][0]['nick']
text = json_data['groups'][0]['units'][0]['Pay.BiliBili.data']['text']
print(f"[{current_time}] {nick} : {text}")
elif message_type == "GiftV3":
nick = json_data['groups'][0]['nick']
text = json_data['groups'][0]['units'][0]['GiftV3.giftV3']['text']
product_id = json_data['groups'][0]['units'][0]['GiftV3.giftV3']['productId']
print(f"[{current_time}] 用户: {nick} 送出礼物,内容为: {text}产品ID为: {product_id}")
#else:
# 其他消息类型的处理
#print(f"[{current_time}] 收到未处理的消息类型: {message_type}")
except KeyError as e:
print(f"[{current_time}] JSON数据中缺少必要的键:", e)
except json.JSONDecodeError as e:
print(f"[{current_time}] 无法解析为JSON格式: ", e)
except websockets.exceptions.ConnectionClosedError:
print(f"[{current_time}] 与服务器断开链接")
break
async def main():
await connect()
asyncio.run(main())

View File

@ -0,0 +1,44 @@
import requests
import time
# API请求链接
room_id = "17079648294690"
timestamp = int(time.time() * 1000)
print(timestamp)
api_url = f"https://live-api.immomo.com/open/m/room/profile?roomid={room_id}&momoid=&src=m50011&web_uid=11126216061Xazx3TgC&_= {timestamp}"
# 发起API请求
response = requests.get(api_url)
data = response.json()
# 提取信息
title = data["data"]["title"]
#anchor_info = data["data"]["anchor_info"]
avatar_url = data["data"]["cover"]
cover_url = data["data"]["cover"]
m3u8 = data["data"]["url"]
m3u81 = data["data"]["revertStream"]
online_users = data["data"]["online"]
nickname = data["data"]["stars"][0]["nickname"]
momoid = data["data"]["momoid"]
# 获取ws_token及其他可显示信息
ws_token = data["data"].get("ws_token", "")
socketUrl = data["data"]["socketUrl"]
#live_url = data["data"]["push_stream"]
# 输出信息
print("直播间信息:")
print(f"标题:{title}")
print("主播:", nickname)
#print("主播信息:", anchor_info)
print(f"主播头像链接:{avatar_url}")
#print(f"直播间封面链接:{cover_url}")
print(f"在线人数:{online_users}")
print("媒体流:", m3u8)
print("媒体流1", m3u81)
print("wss", socketUrl)
print(f"ws_token{ws_token}")
print(f"momoid{momoid}")

View File

@ -0,0 +1,34 @@
import asyncio
import websockets
async def connect():
uri = "wss://live-ws.immomo.com/ws/im"
async with websockets.connect(uri) as websocket:
print(f"链接websocket:[{uri}] 完成")
client_time = "1711123627734"
momoid = "1062302597"
roomid = "15925755150740"
token = "b458d6fd04ee38a9e5330e76a3802df9"
data = '{{"msg_id":1,"client_time":{0},"type":"Sauth","data":{{"momoid":"{1}","roomid":"{2}","role":6,"isVisitor":false,"token":"{3}","ua":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/106.0.0.0 Safari/537.36"}}}}'.format(
client_time, momoid, roomid, token)
await websocket.send(data)
print("Send Hello")
while True:
try:
response = await websocket.recv()
print("收到消息=>" + response)
except websockets.exceptions.ConnectionClosedError:
print("与服务器断开链接")
break
async def main():
await connect()
asyncio.run(main())

View File

@ -0,0 +1,35 @@
import asyncio
import websockets
import json
import time
async def connect_and_send_messages():
uri = "wss://live-ws.immomo.com/ws/im"
async with websockets.connect(uri) as websocket:
print(f"连接websocket:[{uri}] 完成")
client_time = "1711123627734"
momoid = "1062302597"
roomid = "17066184578990"
token = "b458d6fd04ee38a9e5330e76a3802df9"
data = '{{"msg_id":1,"client_time":{0},"type":"Sauth","data":{{"momoid":"{1}","roomid":"{2}","role":6,"isVisitor":false,"token":"{3}","ua":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/106.0.0.0 Safari/537.36"}}}}'.format(
client_time, momoid, roomid, token)
await websocket.send(data)
print("直播间通讯成功")
msg_id = 3 # 初始化消息的 msg_id
while True:
client_time = str(int(time.time() * 1000))
message_data = '{{"msg_id":{0},"client_time":{1},"type":"Bili","data":{{"text":"666"}}}}'.format(msg_id, client_time)
await websocket.send(message_data)
print("Send Message:", message_data)
msg_id += 1 # 递增消息的 msg_id
await asyncio.sleep(10) # 每隔10秒发送一次消息
async def main():
connect_task = asyncio.create_task(connect_and_send_messages())
await connect_task
asyncio.run(main())

View File

@ -0,0 +1,88 @@
import asyncio
import websockets
import time
import json
import datetime
async def connect():
uri = "wss://live-ws.immomo.com/ws/im"
async with websockets.connect(uri) as websocket:
print(f"链接websocket:[{uri}] 完成")
momoid = "1062302597"
roomid = "17066184578990"
token = "b458d6fd04ee38a9e5330e76a3802df9"
ping_msg_id = 2 # 心跳包的id2
client_time = str(int(time.time() * 1000))
data = '{{"msg_id":1,"client_time":{0},"type":"Sauth","data":{{"momoid":"{1}","roomid":"{2}","role":6,"isVisitor":false,"token":"{3}","ua":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36 Edg/122.0.0.0"}}}}'.format(
client_time, momoid, roomid, token)
await websocket.send(data)
print("Send Sauth")
while True:
try:
response = await websocket.recv()
current_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
#print(f"[{current_time}] 收到原始消息 => " + response)
# print("收到原始消息 => " + response)
try:
json_data = json.loads(response)
# print("收到JSON消息 => ", json_data)
message_type = json_data['groups'][0]['units'][0]['type']
if message_type == "Message":
nick = json_data['groups'][0]['nick']
text = json_data['groups'][0]['units'][0]['Msg.Message.data']['text']
print(f"[{current_time}] {nick} : {text}")
elif message_type == "EnterRoom":
text = json_data['groups'][0]['units'][0]['Set.EnterRoom.data']['text']
print(f"[{current_time}] 有新人: {text}")
elif message_type == "BiliBili":
nick = json_data['groups'][0]['nick']
text = json_data['groups'][0]['units'][0]['Pay.BiliBili.data']['text']
print(f"[{current_time}] {nick} : {text}")
elif message_type == "GiftV3":
nick = json_data['groups'][0]['nick']
text = json_data['groups'][0]['units'][0]['GiftV3.giftV3']['text']
product_id = json_data['groups'][0]['units'][0]['GiftV3.giftV3']['productId']
print(f"[{current_time}] 用户: {nick} 送出礼物,内容为: {text}产品ID为: {product_id}")
except KeyError as e:
print("JSON数据缺少:", e)
except json.JSONDecodeError as e:
print("无法解析JSON格式: ", e)
except websockets.exceptions.ConnectionClosedError:
print(f"[{current_time}] 与服务器断开链接")
break
async def send_ping(websocket):
ping_msg_id = 2
await asyncio.sleep(30) # 延迟30秒后开始发送心跳包
while True:
client_time = str(int(time.time() * 1000))
ping_data = '{{"msg_id":{0},"client_time":{1},"type":"Ping","data":{{}}}}'.format(ping_msg_id, client_time)
try:
await websocket.send(ping_data)
print("Send Ping", ping_data)
ping_msg_id += 1
await asyncio.sleep(30) # 每隔30秒发送一次
except websockets.exceptions.ConnectionClosedError:
print("与服务器断开链接")
break
async def main():
websocket = await websockets.connect("wss://live-ws.immomo.com/ws/im")
connect_task = asyncio.create_task(connect())
ping_task = asyncio.create_task(send_ping(websocket))
await connect_task
await ping_task
asyncio.run(main())