Skip to content

Commit

Permalink
fix bug
Browse files Browse the repository at this point in the history
- 修复订阅B站动态及直播间时不能添加数据库中没有的订阅的错误
- 调整直播间提醒,不发送网页链接
- 修正表情包制作文字为正确位置
  • Loading branch information
Ailitonia committed Jan 10, 2021
1 parent baac5d6 commit 6dc3fd3
Show file tree
Hide file tree
Showing 6 changed files with 86 additions and 13 deletions.
10 changes: 8 additions & 2 deletions omega_miya/plugins/bilibili_dynamic_monitor/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,7 @@ async def handle_uid(bot: Bot, event: Event, state: T_State):
logger.error(f'获取用户信息失败, uid: {uid}, error: {_res.info}')
await bilibili_dynamic.finish('获取用户信息失败了QAQ, 请稍后再试~')
up_name = _res.result.get('name')
state['up_name'] = up_name
msg = f'即将{sub_command}{up_name}】的动态!'
await bilibili_dynamic.send(msg)

Expand All @@ -115,7 +116,8 @@ async def handle_check(bot: Bot, event: Event, state: T_State):
logger.info(f"{sub_command}动态成功, group_id: {event.dict().get('group_id')}, uid: {uid}")
await bilibili_dynamic.finish(f'{sub_command}成功!')
else:
logger.error(f"{sub_command}动态失败, group_id: {event.dict().get('group_id')}, uid: {uid}")
logger.error(f"{sub_command}动态失败, group_id: {event.dict().get('group_id')}, uid: {uid},"
f"info: {_res.info}")
await bilibili_dynamic.finish(f'{sub_command}失败了QAQ, 可能并未订阅该用户, 或请稍后再试~')


Expand All @@ -137,7 +139,11 @@ async def sub_add(bot: Bot, event: Event, state: T_State) -> Result:
group_id = event.dict().get('group_id')
group = DBGroup(group_id=group_id)
uid = state['uid']
_res = group.subscription_add(sub=DBSubscription(sub_type=2, sub_id=uid))
sub = DBSubscription(sub_type=2, sub_id=uid)
_res = sub.add(up_name=state.get('up_name'), live_info='动态')
if not _res.success():
return _res
_res = group.subscription_add(sub=sub)
if not _res.success():
return _res
result = Result(error=False, info='Success', result=0)
Expand Down
10 changes: 7 additions & 3 deletions omega_miya/plugins/bilibili_dynamic_monitor/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,9 +36,13 @@ async def fetch_json(url: str, paras: dict = None) -> Result:
try:
timeout = aiohttp.ClientTimeout(total=10)
async with aiohttp.ClientSession(timeout=timeout) as session:
headers = {'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) '
headers = {'accept': 'application/json, text/plain, */*',
'accept-encoding': 'gzip, deflate, br',
'accept-language:': 'zh-CN,zh;q=0.9',
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) '
'AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36',
'referer': 'https://www.bilibili.com/'}
'origin': 'https://space.bilibili.com',
'referer': 'https://space.bilibili.com/'}
async with session.get(url=url, params=paras, headers=headers, cookies=cookies, timeout=timeout) as rp:
_json = await rp.json()
result = Result(error=False, info='Success', result=_json)
Expand Down Expand Up @@ -362,9 +366,9 @@ async def get_dynamic_info(dy_uid) -> Result:
'get_dynamic_info'
]


if __name__ == '__main__':
import asyncio

loop = asyncio.get_event_loop()
res = loop.run_until_complete(get_dynamic_info(dy_uid=846180))
print(res)
10 changes: 8 additions & 2 deletions omega_miya/plugins/bilibili_live_monitor/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,7 @@ async def handle_room_id(bot: Bot, event: Event, state: T_State):
logger.error(f'获取直播间信息失败, room_id: {room_id}, error: {_res.info}')
await bilibili_live.finish('获取直播间信息失败了QAQ, 请稍后再试~')
up_name = _res.result.get('name')
state['up_name'] = up_name
msg = f'即将{sub_command}{up_name}】的直播间!'
await bilibili_live.send(msg)

Expand All @@ -121,7 +122,8 @@ async def handle_check(bot: Bot, event: Event, state: T_State):
logger.info(f"{sub_command}直播间成功, group_id: {event.dict().get('group_id')}, room_id: {room_id}")
await bilibili_live.finish(f'{sub_command}成功!')
else:
logger.error(f"{sub_command}直播间失败, group_id: {event.dict().get('group_id')}, room_id: {room_id}")
logger.error(f"{sub_command}直播间失败, group_id: {event.dict().get('group_id')}, room_id: {room_id},"
f"info: {_res.info}")
await bilibili_live.finish(f'{sub_command}失败了QAQ, 可能并未订阅该用户, 或请稍后再试~')


Expand All @@ -143,7 +145,11 @@ async def sub_add(bot: Bot, event: Event, state: T_State) -> Result:
group_id = event.dict().get('group_id')
group = DBGroup(group_id=group_id)
room_id = state['room_id']
_res = group.subscription_add(sub=DBSubscription(sub_type=1, sub_id=room_id))
sub = DBSubscription(sub_type=1, sub_id=room_id)
_res = sub.add(up_name=state.get('up_name'), live_info='直播间')
if not _res.success():
return _res
_res = group.subscription_add(sub=sub)
if not _res.success():
return _res
# 添加直播间时需要刷新全局监控列表
Expand Down
18 changes: 15 additions & 3 deletions omega_miya/plugins/bilibili_live_monitor/monitor.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import asyncio
from nonebot import logger, require, get_driver, get_bots
from nonebot.adapters.cqhttp import MessageSegment
from omega_miya.utils.Omega_Base import DBSubscription, DBTable
from .utils import get_live_info, get_user_info, verify_cookies
from .utils import get_live_info, get_user_info, pic_2_base64, verify_cookies


# 初始化直播间标题, 状态
Expand Down Expand Up @@ -170,7 +171,12 @@ async def check_live(room_id: int):
logger.info(f"直播间: {room_id}/{up_name} 标题变更为: {live_info['title']}")
elif live_info['status'] == 1 and live_info['title'] != live_title[room_id]:
# 通知有通知权限且订阅了该直播间的群
msg = f"{up_name}的直播间换标题啦!\n\n{live_info['title']}\n{live_info['url']}"
cover_pic = await pic_2_base64(url=live_info.get('cover_img'))
if cover_pic.success():
msg = f"{up_name}的直播间换标题啦!\n\n{live_info['title']}\n{MessageSegment.image(cover_pic.result)}"
else:
# msg = f"{up_name}的直播间换标题啦!\n\n【{live_info['title']}】\n{live_info['url']}"
msg = f"{up_name}的直播间换标题啦!\n\n{live_info['title']}】"
for group_id in notice_group:
for _bot in bots:
try:
Expand Down Expand Up @@ -207,7 +213,13 @@ async def check_live(room_id: int):
logger.info(f"开播记录: LiveStart! Room: {room_id}/{up_name}, Title: {live_info['title']}, "
f"TrueTime: {live_info['time']}")

msg = f"{live_info['time']}\n{up_name}开播啦!\n\n{live_info['title']}\n{live_info['url']}"
cover_pic = await pic_2_base64(url=live_info.get('cover_img'))
if cover_pic.success():
msg = f"{live_info['time']}\n{up_name}开播啦!\n\n{live_info['title']}】" \
f"\n{MessageSegment.image(cover_pic.result)}"
else:
# msg = f"{live_info['time']}\n{up_name}开播啦!\n\n【{live_info['title']}】\n{live_info['url']}"
msg = f"{live_info['time']}\n{up_name}开播啦!\n\n{live_info['title']}】"
for group_id in notice_group:
for _bot in bots:
try:
Expand Down
49 changes: 47 additions & 2 deletions omega_miya/plugins/bilibili_live_monitor/utils.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import aiohttp
import nonebot
import base64
from io import BytesIO
from omega_miya.utils.Omega_Base import Result

LIVE_API_URL = 'https://api.live.bilibili.com/room/v1/Room/get_info'
Expand Down Expand Up @@ -32,8 +34,12 @@ async def fetch_json(url: str, paras: dict = None) -> Result:
try:
timeout = aiohttp.ClientTimeout(total=10)
async with aiohttp.ClientSession(timeout=timeout) as session:
headers = {'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) '
headers = {'accept': 'application/json, text/plain, */*',
'accept-encoding': 'gzip, deflate, br',
'accept-language:': 'zh-CN,zh;q=0.9',
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) '
'AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36',
'origin': 'https://www.bilibili.com',
'referer': 'https://www.bilibili.com/'}
async with session.get(url=url, params=paras, headers=headers, cookies=cookies, timeout=timeout) as rp:
_json = await rp.json()
Expand All @@ -49,6 +55,43 @@ async def fetch_json(url: str, paras: dict = None) -> Result:
return result


# 图片转base64
async def pic_2_base64(url: str) -> Result:
async def get_image(pic_url: str):
timeout_count = 0
error_info = ''
while timeout_count < 3:
try:
timeout = aiohttp.ClientTimeout(total=10)
async with aiohttp.ClientSession(timeout=timeout) as session:
headers = {'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) '
'AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36',
'referer': 'https://www.bilibili.com/'}
async with session.get(url=pic_url, headers=headers, timeout=timeout) as resp:
_res = await resp.read()
return _res
except Exception as _e:
error_info += f'{repr(_e)} Occurred in pic_2_base64 trying {timeout_count + 1} using paras: {pic_url}\n'
finally:
timeout_count += 1
else:
error_info += f'Failed too many times in pic_2_base64 using paras: {pic_url}'
return None

origin_image_f = BytesIO()
try:
origin_image_f.write(await get_image(pic_url=url))
except Exception as e:
result = Result(error=True, info=f'pic_2_base64 error: {repr(e)}', result='')
return result
b64 = base64.b64encode(origin_image_f.getvalue())
b64 = str(b64, encoding='utf-8')
b64 = 'base64://' + b64
origin_image_f.close()
result = Result(error=False, info='Success', result=b64)
return result


# 获取直播间信息
async def get_live_info(room_id) -> Result:
url = LIVE_API_URL
Expand All @@ -64,7 +107,8 @@ async def get_live_info(room_id) -> Result:
'url': LIVE_URL + str(room_id),
'title': live_info['data']['title'],
'time': live_info['data']['live_time'],
'uid': live_info['data']['uid']
'uid': live_info['data']['uid'],
'cover_img': live_info['data']['user_cover']
}
result = Result(error=False, info='Success', result=_res)
except Exception as e:
Expand Down Expand Up @@ -111,6 +155,7 @@ async def verify_cookies() -> Result:
__all__ = [
'get_live_info',
'get_user_info',
'pic_2_base64',
'verify_cookies'
]

Expand Down
2 changes: 1 addition & 1 deletion omega_miya/plugins/sticker_maker/utils/default_render.py
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ def stick_maker_temp_whitebg(text: str, image_file: bytes, font_path: str, image
font = ImageFont.truetype(font_path, font_size)
text_w, text_h = font.getsize_multiline(text)
# 计算居中文字位置
text_coordinate = (((background_w - text_w) // 2), background_h - 100)
text_coordinate = (((background_w - text_w) // 2), image_height + ((100 - text_h) // 2))

draw.multiline_text(text_coordinate, text, font=font, fill=(0, 0, 0))

Expand Down

0 comments on commit 6dc3fd3

Please sign in to comment.