Skip to content

Commit

Permalink
合并最近的開發進度 (#4)
Browse files Browse the repository at this point in the history
* 内置禮物圖片

*添加禮物圖片顯示

* 修復bug
  • Loading branch information
northgreen authored Feb 2, 2024
1 parent a2525b7 commit 92bb30a
Show file tree
Hide file tree
Showing 483 changed files with 7,803 additions and 17 deletions.
4 changes: 3 additions & 1 deletion .idea/bdm-plugin.iml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Empty file added bilibili_dm_plugin/.gitignore
Empty file.
46 changes: 30 additions & 16 deletions bilibili_dm_plugin/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,6 @@
from . import blivedm
from depends import plugin_main, msgs, connects
import shutil


import aiohttp
from aiohttp import web
from typing import *
Expand All @@ -31,8 +29,6 @@
from .blivedm.models import web as web_models
import logging

session: Optional[aiohttp.ClientSession] = None
SESSDATA = ''
logger = logging.getLogger(__name__)
local_path = __path__[0]

Expand Down Expand Up @@ -97,7 +93,10 @@ def _on_gift(self, client: ws_base.WebSocketClientBase, message: web_models.Gift
name=message.uname,
face="/cgi/b_dm_plugin/face?url=" + message.face
).to_dict(),
pic=self.user_face[message.uname] if message.uname in self.user_face else "null"
pic=msgs.pic(
border=False,
pic_url="/cgi/b_dm_plugin/gift?item=" + message.gift_name + ".png"
).to_dict()
).to_dict(),
msg_type="info"
).to_dict()
Expand All @@ -113,20 +112,32 @@ def plugin_init(self):
os.mkdir(os.path.join(local_path, "tmp"))
else:
os.mkdir(os.path.join(local_path, "tmp"))
self.runners = []

self.plugin_name = "b_dm_plugin"

self.sprit_cgi_support = True
self.sprit_cgi_lists["face"] = self.sprit_cgi
self.sprit_cgi_lists["face"] = self.cgi_face
self.sprit_cgi_lists["gift"] = self.cgi_gift
self.read_config()

# print(self.config)
if "session" in self.config:
self.SESSDATA = self.config["session"]
else:
self.config["session"] = ""
self.update_config(self.config)


return "message"

async def sprit_cgi(self, request: web.Request):
async def cgi_face(self, request: web.Request):
ret = web.Response(status=404, text="no such file")
ret = await return_for_face(request.rel_url.query.get("url"))
return ret

async def cgi_gift(self, request: web.Request):
return web.FileResponse(os.path.join(local_path, "resource", request.rel_url.query.get("item")))

async def plugin_main(self):
self.config = {"test": "test"}
self.update_config()
Expand All @@ -138,17 +149,18 @@ def plugin_callback(self):

def dm_iter(self, params: dict, connect_waper: connects.connect_wrapper) -> object:
class dm_iter_back:
def __init__(self, params, connect_waper):
def __init__(self, params, connect_waper, session):
self.messages = []
if "broom" in params:
cookies = http.cookies.SimpleCookie()
cookies['SESSDATA'] = SESSDATA
cookies['SESSDATA'] = session
cookies['SESSDATA']['domain'] = 'bilibili.com'

session = aiohttp.ClientSession()
session.cookie_jar.update_cookies(cookies)
self.session: Optional[aiohttp.ClientSession]
self.session = aiohttp.ClientSession()
self.session.cookie_jar.update_cookies(cookies)

self.client = blivedm.BLiveClient(params["broom"], session=session)
self.client = blivedm.BLiveClient(params["broom"], session=self.session)

handler = Handler(self.messages)
self.client.set_handler(handler)
Expand All @@ -162,8 +174,10 @@ async def __aiter__(self):
except IndexError:
return

def __del__(self):
async def callback(self):
logger.info("blivedm closing")
if hasattr(self, "client"):
asyncio.get_event_loop().create_task(self.client.stop_and_close())
await self.session.close()
await self.client.stop_and_close()

return dm_iter_back(params, connect_waper)
return dm_iter_back(params, connect_waper, self.SESSDATA)
32 changes: 32 additions & 0 deletions bilibili_dm_plugin/depends/configs.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import yaml


def config() -> dict:
with open("./config/system/config.yaml", "r", encoding="utf-8") as f:
configs = yaml.load(f.read(), Loader=yaml.FullLoader)
if configs["debug"] == 1:
print(f"log:already reading config file: {configs}\n")
return configs


def set_config(config_family: str, config: dict) -> bool:
"""
设置插件的配置
"""
try:
with open(f"./config/plugin/{config_family}/config.yaml", "w", encoding="utf_8") as f:
yaml.dump(data=config, stream=f, allow_unicode=True)
except Exception as e:
print(str(e))
return False
finally:
return True

def read_config(config_family: str) -> dict:
"""
读取插件的配置
"""
with open(f"./config/plugin/{config_family}/config.yaml", "r", encoding="utf_8") as f:
configs = yaml.load(f.read(), Loader=yaml.FullLoader)
return configs

32 changes: 32 additions & 0 deletions bilibili_dm_plugin/depends/connects.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
# Copyright (c) 2023 楚天寻箫(ictye)
#
# 此软件基于楚天寻箫非商业开源软件许可协议 1.0发布.
# 您可以根据该协议的规定,在非商业或商业环境中使用、分发和引用此软件.
# 惟分发此软件副本时,您不得以商业方式获利,并且不得限制用户获取该应用副本的体验.
# 如果您修改或者引用了此软件,请按协议规定发布您的修改源码.
#
# 此软件由版权所有者提供,没有明确的技术支持承诺,使用此软件和源码造成的任何损失,
# 版权所有者概不负责。如需技术支持,请联系版权所有者或社区获取最新版本。
#
# 更多详情请参阅许可协议文档
from websockets.server import WebSocketServerProtocol


class connect_wrapper:

"""
连接包装类
"""

def __init__(self, connect: WebSocketServerProtocol):
self.__connect__ = connect
self.id = connect.id # 连接id
self.open = connect.open # 连接状态

def refresh(self):
"""
刷新状态
"""
self.id = self.__connect__.id
self.open = self.__connect__.open

15 changes: 15 additions & 0 deletions bilibili_dm_plugin/depends/logger.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import logging


def setup_logging(config: dict):
"""
Setup logging configuration
"""

level_dic: dict = {"DEBUG": logging.DEBUG,
"INFO": logging.INFO,
"WARNING": logging.WARNING,
"ERROR": logging.ERROR,
"CRITICAL": logging.CRITICAL,
"FATAL": logging.FATAL}
logging.basicConfig(level=level_dic[config["loglevel"]], format="[%(asctime)s,%(name)s] %(levelname)s : %(message)s")
111 changes: 111 additions & 0 deletions bilibili_dm_plugin/depends/msgs.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
"""
这个文件内定义全部的标准消息模板
所有的函数都应该又to_dict方法来将其转为字典,相反的这个函数能输出打包好的字典
别问我为啥,问就是不知道
"""


class datas:
def to_dict(self, cls: object):
return dict(cls)


class connect_ok:
"""
连接认证消息
"""
code = 200
msg = "connect ok"

def to_dict(self):
return {"code": self.code,
"msg": self.msg}


class dm:
def __init__(self, msg: str, who: dict):
"""
params:
msg:str 消息主体
who:dict 消息发出者对象(其实是一个字典)
成员方法:
to_dict: 输出为字典
"""
self.msg = msg
self.who = who

def to_dict(self):
return {"msg": self.msg,
"who": self.who}


class info:
def __init__(self,
msg: str,
who: str,
pic: dict):
self.msg = msg
self.who = who
self.pic = pic

def to_dict(self):
return {"msg": self.msg,
"who": self.who,
"pic": self.pic}


class socket_responce:
def __init__(self, config: dict):
self.code = 200
self.local = "ws://{}:{}".format(config["host"], config["websocket"]["port"])

def to_dict(self):
return {"code": self.code,
"local": self.local}


class msg_who:
def __init__(self, type: int,
name: str,
face: str):
self.type = type
self.name = name
self.face = face

def to_dict(self):
return {"name": self.name,
"type": self.type,
"face": self.face}


class pic:
def __init__(self,
border: bool,
pic_url: str):
self.border = border
self.pic_url = pic_url

def to_dict(self):
return {"border": self.border,
"pic_url": self.pic_url}


class msg_box:
"""
消息标准封装所用的类
"""

def __init__(self,
message_class: str,
msg_type: str,
message_body: dict):
self.message_class = message_class
self.msg_type = msg_type
self.message_body = message_body

def to_dict(self):
return {"message_class": self.message_class,
"msg_type": self.msg_type,
"message_body": self.message_body}
19 changes: 19 additions & 0 deletions bilibili_dm_plugin/depends/plugin_errors.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
class PluginTypeError(Exception):
def __init__(self, message):
self.message = message
super().__init__(self.message)


class UnexpectedPluginMessage(Exception):
def __init__(self, message):
super(UnexpectedPluginMessage, self).__init__(message)


class UnexpectedPluginMather(Exception):
def __init__(self, message):
super(UnexpectedPluginMather, self).__init__(message)


class NoMainMather(Exception):
def __init__(self, message):
super(NoMainMather, self).__init__(message)
Loading

0 comments on commit 92bb30a

Please sign in to comment.