blivedm/open_live_sample.py

77 lines
2.5 KiB
Python
Raw Normal View History

# -*- coding: utf-8 -*-
import asyncio
2023-09-03 10:46:01 +08:00
import blivedm
2023-09-03 16:53:08 +08:00
import blivedm.models.open_live as open_models
import blivedm.models.web as web_models
2023-09-03 16:53:08 +08:00
# 在开放平台申请的开发者密钥
2023-09-04 19:15:22 +08:00
ACCESS_KEY_ID = ''
ACCESS_KEY_SECRET = ''
2023-09-03 16:53:08 +08:00
# 在开放平台创建的项目ID
2023-09-03 10:46:01 +08:00
APP_ID = 0
2023-09-03 16:53:08 +08:00
# 主播身份码
2023-09-03 10:46:01 +08:00
ROOM_OWNER_AUTH_CODE = ''
async def main():
2023-09-03 10:46:01 +08:00
await run_single_client()
2023-09-03 10:46:01 +08:00
async def run_single_client():
"""
演示监听一个直播间
"""
2023-09-03 12:22:01 +08:00
client = blivedm.OpenLiveClient(
2023-09-04 19:15:22 +08:00
access_key_id=ACCESS_KEY_ID,
access_key_secret=ACCESS_KEY_SECRET,
2023-09-03 10:46:01 +08:00
app_id=APP_ID,
room_owner_auth_code=ROOM_OWNER_AUTH_CODE,
)
handler = MyHandler()
client.set_handler(handler)
client.start()
try:
2023-09-03 10:46:01 +08:00
# 演示70秒后停止
2023-09-03 16:53:08 +08:00
# await asyncio.sleep(70)
# client.stop()
await client.join()
finally:
await client.stop_and_close()
2023-09-03 10:46:01 +08:00
2023-09-03 16:53:08 +08:00
class MyHandler(blivedm.BaseHandler):
def _on_heartbeat(self, client: blivedm.BLiveClient, message: web_models.HeartbeatMessage):
2023-09-03 16:53:08 +08:00
print(f'[{client.room_id}] 心跳')
def _on_open_live_danmaku(self, client: blivedm.OpenLiveClient, message: open_models.DanmakuMessage):
2023-09-03 16:53:08 +08:00
print(f'[{message.room_id}] {message.uname}{message.msg}')
def _on_open_live_gift(self, client: blivedm.OpenLiveClient, message: open_models.GiftMessage):
2023-09-03 16:53:08 +08:00
coin_type = '金瓜子' if message.paid else '银瓜子'
total_coin = message.price * message.gift_num
2023-09-03 16:53:08 +08:00
print(f'[{message.room_id}] {message.uname} 赠送{message.gift_name}x{message.gift_num}'
f' {coin_type}x{total_coin}')
2023-09-03 16:53:08 +08:00
def _on_open_live_buy_guard(self, client: blivedm.OpenLiveClient, message: open_models.GuardBuyMessage):
2023-09-03 16:53:08 +08:00
print(f'[{message.room_id}] {message.user_info.uname} 购买 大航海等级={message.guard_level}')
def _on_open_live_super_chat(
2023-09-03 16:53:08 +08:00
self, client: blivedm.OpenLiveClient, message: open_models.SuperChatMessage
):
print(f'[{message.room_id}] 醒目留言 ¥{message.rmb} {message.uname}{message.message}')
def _on_open_live_super_chat_delete(
2023-09-03 16:53:08 +08:00
self, client: blivedm.OpenLiveClient, message: open_models.SuperChatDeleteMessage
):
print(f'[{message.room_id}] 删除醒目留言 message_ids={message.message_ids}')
def _on_open_live_like(self, client: blivedm.OpenLiveClient, message: open_models.LikeMessage):
2023-09-03 16:53:08 +08:00
print(f'[{message.room_id}] {message.uname} 点赞')
2023-09-03 10:46:01 +08:00
if __name__ == '__main__':
2023-09-03 10:46:01 +08:00
asyncio.run(main())