Compare commits

...
24 Commits
Author SHA1 Message Date
HibiKier 3c8983e753 Update task_hook.py 2022-02-26 00:11:26 +08:00
HibiKier 1fe41dd823 Update __version__ 2022-02-25 23:21:03 +08:00
HibiKier e8df59203c Update README.md 2022-02-25 23:17:42 +08:00
HibiKier 0f6690606b Update README.md 2022-02-25 22:50:24 +08:00
HibiKier a0115309dd Merge pull request #124 from Nova-Noir/main
Fixed error in custom_welcome_msg and message_builder
2022-02-24 16:12:39 +08:00
HibiKier ca18d45786 Update message_builder.py 2022-02-24 16:12:25 +08:00
NovaNo1r 76df21036a Fixed error in custom_welcome_msg and message_builder 2022-02-23 21:45:53 -08:00
HibiKier c674d581b7 Update README.md 2022-02-23 13:52:10 +08:00
HibiKier fc53c3c487 Update _data_source.py 2022-02-23 13:51:19 +08:00
HibiKier 7a4e31df80 Update __init__.py 2022-02-23 13:49:57 +08:00
HibiKier f1d308d559 Update __init__.py 2022-02-23 13:49:21 +08:00
HibiKier b7914bac05 Update README.md 2022-02-21 19:05:42 +08:00
HibiKier 8c40d88cc4 Update .gitignore 2022-02-21 18:20:43 +08:00
HibiKier b4ed6dcb5d Delete server_ip.py 2022-02-21 18:18:30 +08:00
HibiKier 0d3bd8a89c fix bug 2022-02-21 15:59:17 +08:00
HibiKier 87f0189abd Update README.md 2022-02-20 11:39:00 +08:00
HibiKier 1c17ac1f9d Update __init__.py 2022-02-20 11:06:32 +08:00
HibiKier f038763041 fix bug 2022-02-20 11:06:04 +08:00
HibiKier eaf6d54757 Update README.md 2022-02-19 23:24:21 +08:00
HibiKier d7368c83bc Update query_resource.py 2022-02-19 20:12:51 +08:00
HibiKier 4011620da1 Update README.md 2022-02-19 20:06:53 +08:00
HibiKier 6e0b91531e Update __version__ 2022-02-19 20:05:36 +08:00
HibiKier b8ca1d68aa Update update_info.json 2022-02-19 20:04:19 +08:00
HibiKier 2b9cda40a0 Update query_resource.py 2022-02-19 20:03:40 +08:00
28 changed files with 372 additions and 334 deletions
+1 -1
View File
@@ -139,7 +139,7 @@ dmypy.json
cython_debug/
test.py
server.py
server_ip.py
member_activity_handle.py
Yu-Gi-Oh/
search_image/
+45 -2
View File
@@ -191,7 +191,7 @@
# 配置gocq
在 https://github.com/Mrs4s/go-cqhttp 下载Releases最新版本,运行后选择反向代理,
后将gocq的配置文件config.yml中的universal改为universal: ws://127.0.0.1:8080/cqhttp/ws
后将gocq的配置文件config.yml中的universal改为universal: ws://127.0.0.1:8080/onebot/v11/ws
# 获取代码
git clone https://github.com/HibiKier/zhenxun_bot.git
@@ -236,13 +236,56 @@ __Docker 最新版本由 [Sakuracio](https://github.com/Sakuracio) 提供__
## 更新
### 2022/2/19 \[v0.1.2] (nonebot beta2!)
### 2022/2/25 \[v0.1.4]
* PIX提供配置MAX_ONCE_NUM2FORWARD:当单次发送图片超过指定张数且在群聊时,将转为合并消息
* 优化抽卡
* 修复点歌无法正确发送
* 修复我有一个朋友有时文本会包含CQ码
* 修复群欢消息被动控制文本未删除 [@pull/124](https://github.com/HibiKier/zhenxun_bot/pull/124)
* message_builder.image不再提供参数:abspath
### 2022/2/23
* 插件状态将从已加载插件模块中读取
* 修复b站订阅插件订阅失败问题
* 修复重启命令无法使用
### 2022/2/21 \[v0.1.3.2]
* 群权限为-1时,超级用户发送的命令依旧生效
* 当群权限为-1时,被动技能也将不会发送
* 修复功能开关,b站转发解析,复读 ignore无法使用
* 修复色图下载文件名与路径错误
* 修复被动技能提醒有时无法删除控制文本
### 2022/2/20 \[v0.1.3.1]
* 修复pix下载临时文件目录错误
* 修复AI,天气,发送图片ignore导致无法使用
* 修复纯文本被动技能提醒有时无法删除控制文本
### 2022/2/19 \[v0.1.3] (nonebot beta2!)
* 由于nonebot升级版本,提供更新建议(__该次升级将会导致nonebot.beta1以下的插件无法使用__
* 保证services,utils,configs,plugins,basic_plugins,文件夹均为最新
* 根目录有pyproject.toml与poetry.lock
* 执行命令:
* pip3 install poetry
* poetry install
* poetry shell
* playwright install chromium
* python3 bot.py
* 适配nonebot.beta2
* 删除图片搜索 nonebot_plugin_picsearcher
* 新增图片搜索 search_image
* 替换cos api
* 原神签到树脂提醒新增绑定群里,在某群绑定uid就会在某群发送提醒信息(有好友则私聊,需要重新绑定uid
* 修改update_info.json
* 修复原神资源查询下载数据失败时导致报错
* 优化BuildImage.circle()锯齿问题 [@pull/109](https://github.com/HibiKier/zhenxun_bot/pull/109)
* epic restful 替换 [@pull/119](https://github.com/HibiKier/zhenxun_bot/pull/119)
* fix: 修复远古时期残留的epic推送问题 [@pull/122](https://github.com/HibiKier/zhenxun_bot/pull/122)
+1 -1
View File
@@ -1 +1 @@
__version__: v0.1.2
__version__: v0.1.4
+24 -20
View File
@@ -3,7 +3,7 @@ from nonebot.adapters.onebot.v11.message import MessageSegment
from services.log import logger
from configs.path_config import DATA_PATH
from utils.message_builder import image
from utils.utils import get_bot
from utils.utils import get_bot, get_matchers
from pathlib import Path
from models.group_member_info import GroupInfoUser
from datetime import datetime
@@ -75,7 +75,7 @@ async def custom_group_welcome(
await AsyncHttpx.download_file(
img, DATA_PATH / "custom_welcome_msg" / f"{group_id}.jpg"
)
img_result = image(abspath=DATA_PATH / "custom_welcome_msg" / f"{group_id}.jpg")
img_result = image(DATA_PATH / "custom_welcome_msg" / f"{group_id}.jpg")
logger.info(f"USER {user_id} GROUP {group_id} 更换群欢迎消息图片")
except Exception as e:
logger.error(f"GROUP {group_id} 替换群消息失败 e:{e}")
@@ -187,24 +187,28 @@ def _get_plugin_status() -> MessageSegment:
"""
rst = "\t功能\n"
flag_str = "状态".rjust(4) + "\n"
for module in plugins_manager.get_data():
flag = plugins_manager.get_plugin_block_type(module)
flag = flag.upper() + " CLOSE" if flag else "OPEN"
try:
plugin_name = plugins_manager.get(module)["plugin_name"]
if (
"[Hidden]" in plugin_name
or "[Admin]" in plugin_name
or "[Superuser]" in plugin_name
):
continue
rst += f"{plugin_name}"
except KeyError:
rst += f"{module}"
if plugins_manager.get(module)["error"]:
rst += "[ERROR]"
rst += "\n"
flag_str += f"{flag}\n"
tmp_name = []
for matcher in get_matchers():
if matcher.plugin_name not in tmp_name:
tmp_name.append(matcher.plugin_name)
module = matcher.plugin_name
flag = plugins_manager.get_plugin_block_type(module)
flag = flag.upper() + " CLOSE" if flag else "OPEN"
try:
plugin_name = plugins_manager.get(module)["plugin_name"]
if (
"[Hidden]" in plugin_name
or "[Admin]" in plugin_name
or "[Superuser]" in plugin_name
):
continue
rst += f"{plugin_name}"
except KeyError:
rst += f"{module}"
if plugins_manager.get(module)["error"]:
rst += "[ERROR]"
rst += "\n"
flag_str += f"{flag}\n"
height = len(rst.split("\n")) * 24
a = BuildImage(250, height, font_size=20)
a.text((10, 10), rst)
+1 -1
View File
@@ -31,7 +31,7 @@ def switch_rule(event: Event) -> bool:
cmd.append(f"关闭 {x}")
except KeyError:
pass
msg = get_message_text(event.json())
msg = get_message_text(event.json()).split()
msg = msg[0] if msg else ""
return msg in cmd
except Exception as e:
@@ -1,7 +1,6 @@
from nonebot.adapters.onebot.v11 import Bot, GroupMessageEvent, MessageEvent, GROUP, Message
from nonebot.adapters.onebot.v11 import Bot, GroupMessageEvent, MessageEvent, GROUP
from nonebot import on_command, on_message, on_regex
from nonebot.typing import T_State
from nonebot.params import CommandArg
from nonebot.params import RegexGroup
from ._data_source import (
change_group_switch,
set_plugin_status,
@@ -13,6 +12,7 @@ from services.log import logger
from configs.config import NICKNAME, Config
from utils.utils import get_message_text, is_number
from nonebot.permission import SUPERUSER
from typing import Tuple, Any
from .rule import switch_rule
@@ -65,14 +65,14 @@ group_status = on_regex("^(休息吧|醒来)$", permission=GROUP, priority=5, bl
@switch_rule_matcher.handle()
async def _(bot: Bot, event: MessageEvent, arg: Message = CommandArg()):
_cmd = arg.extract_plain_text().strip().split()[0]
async def _(bot: Bot, event: MessageEvent):
_cmd = get_message_text(event.json()).split()[0]
if isinstance(event, GroupMessageEvent):
await switch_rule_matcher.send(await change_group_switch(_cmd, event.group_id))
logger.info(f"USER {event.user_id} GROUP {event.group_id} 使用群功能管理命令 {_cmd}")
else:
if str(event.user_id) in bot.config.superusers:
block_type = " ".join(arg.extract_plain_text().strip().split()[1:])
block_type = " ".join(get_message_text(event.json()).split()[1:])
block_type = block_type if block_type else "a"
if is_number(block_type):
if not int(block_type) in [
@@ -114,8 +114,8 @@ async def _(event: GroupMessageEvent):
@group_status.handle()
async def _(event: GroupMessageEvent, state: T_State):
cmd = state["_matched_groups"][0]
async def _(event: GroupMessageEvent, reg_group: Tuple[Any, ...] = RegexGroup()):
cmd = reg_group[0]
if cmd == "休息吧":
msg = set_group_bot_status(event.group_id, False)
else:
+1 -1
View File
@@ -129,7 +129,7 @@ async def _(bot: Bot, event: GroupIncreaseNoticeEvent):
at_flag = True
if (DATA_PATH / "custom_welcome_msg" / f"{event.group_id}.jpg").exists():
img = image(
abspath=DATA_PATH / "custom_welcome_msg" / f"{event.group_id}.jpg"
DATA_PATH / "custom_welcome_msg" / f"{event.group_id}.jpg"
)
if msg or img:
msg = msg.strip() + img
+48 -41
View File
@@ -11,7 +11,7 @@ from utils.manager import (
plugins_manager,
plugins2cd_manager,
plugins2block_manager,
plugins2count_manager
plugins2count_manager,
)
from ._utils import set_block_limit_false, status_message_manager
from nonebot.typing import T_State
@@ -23,7 +23,7 @@ from nonebot.adapters.onebot.v11 import (
PokeNotifyEvent,
PrivateMessageEvent,
Message,
Event
Event,
)
from configs.config import Config
from models.ban_user import BanUser
@@ -49,23 +49,28 @@ async def _(matcher: Matcher, bot: Bot, event: MessageEvent, state: T_State):
# 功能的金币检测 #######################################
# 功能的金币检测 #######################################
cost_gold = 0
if isinstance(event, GroupMessageEvent) and plugins2settings_manager.get_plugin_data(module).get('cost_gold'):
cost_gold = plugins2settings_manager.get_plugin_data(module).get('cost_gold')
if isinstance(
event, GroupMessageEvent
) and plugins2settings_manager.get_plugin_data(module).get("cost_gold"):
cost_gold = plugins2settings_manager.get_plugin_data(module).get("cost_gold")
if await BagUser.get_gold(event.user_id, event.group_id) < cost_gold:
await send_msg(f"金币不足..该功能需要{cost_gold}金币..", bot, event)
raise IgnoredException(f"{module} 金币限制...")
# 当插件不阻塞超级用户时,超级用户提前扣除金币
if str(event.user_id) in bot.config.superusers and not plugins2info_dict[module]["limit_superuser"]:
if (
str(event.user_id) in bot.config.superusers
and not plugins2info_dict[module]["limit_superuser"]
):
await BagUser.spend_gold(event.user_id, event.group_id, cost_gold)
try:
if (
(not isinstance(event, MessageEvent) and module != "poke")
or await BanUser.is_ban(event.user_id)
and str(event.user_id) not in bot.config.superusers
(not isinstance(event, MessageEvent) and module != "poke")
or await BanUser.is_ban(event.user_id)
and str(event.user_id) not in bot.config.superusers
) or (
str(event.user_id) in bot.config.superusers
and plugins2info_dict.get(module)
and not plugins2info_dict[module]["limit_superuser"]
str(event.user_id) in bot.config.superusers
and plugins2info_dict.get(module)
and not plugins2info_dict[module]["limit_superuser"]
):
return
except AttributeError:
@@ -76,8 +81,8 @@ async def _(matcher: Matcher, bot: Bot, event: MessageEvent, state: T_State):
_module = _plugin.module
plugin_name = _module.__getattribute__("__zx_plugin_name__")
if (
"[superuser]" in plugin_name.lower()
and str(event.user_id) in bot.config.superusers
"[superuser]" in plugin_name.lower()
and str(event.user_id) in bot.config.superusers
):
return
except AttributeError:
@@ -85,7 +90,10 @@ async def _(matcher: Matcher, bot: Bot, event: MessageEvent, state: T_State):
# 群黑名单检测 群总开关检测
if isinstance(event, GroupMessageEvent) or matcher.plugin_name == "poke":
try:
if group_manager.get_group_level(event.group_id) < 0:
if (
group_manager.get_group_level(event.group_id) < 0
and str(event.user_id) not in bot.config.superusers
):
raise IgnoredException("群黑名单")
if not group_manager.check_group_bot_status(event.group_id):
try:
@@ -99,12 +107,12 @@ async def _(matcher: Matcher, bot: Bot, event: MessageEvent, state: T_State):
if isinstance(event, GroupMessageEvent):
# 个人权限
if (
not await LevelUser.check_level(
event.user_id,
event.group_id,
admin_manager.get_plugin_level(module),
)
and admin_manager.get_plugin_level(module) > 0
not await LevelUser.check_level(
event.user_id,
event.group_id,
admin_manager.get_plugin_level(module),
)
and admin_manager.get_plugin_level(module) > 0
):
try:
if _flmt.check(event.user_id):
@@ -112,7 +120,7 @@ async def _(matcher: Matcher, bot: Bot, event: MessageEvent, state: T_State):
await bot.send_group_msg(
group_id=event.group_id,
message=f"{at(event.user_id)}你的权限不足喔,该功能需要的权限等级:"
f"{admin_manager.get_plugin_level(module)}",
f"{admin_manager.get_plugin_level(module)}",
)
except ActionFailed:
pass
@@ -122,7 +130,7 @@ async def _(matcher: Matcher, bot: Bot, event: MessageEvent, state: T_State):
raise IgnoredException("权限不足")
else:
if not await LevelUser.check_level(
event.user_id, 0, admin_manager.get_plugin_level(module)
event.user_id, 0, admin_manager.get_plugin_level(module)
):
try:
await bot.send_private_msg(
@@ -138,12 +146,12 @@ async def _(matcher: Matcher, bot: Bot, event: MessageEvent, state: T_State):
if module in plugins2info_dict.keys() and matcher.priority not in [1, 9]:
# 戳一戳单独判断
if isinstance(event, GroupMessageEvent) or (
isinstance(event, PokeNotifyEvent) and event.group_id
isinstance(event, PokeNotifyEvent) and event.group_id
):
if status_message_manager.get(event.group_id) is None:
status_message_manager.delete(event.group_id)
if plugins2info_dict[module]["level"] > group_manager.get_group_level(
event.group_id
event.group_id
):
try:
if _flmt_g.check(event.user_id) and module not in ignore_rst_module:
@@ -161,7 +169,7 @@ async def _(matcher: Matcher, bot: Bot, event: MessageEvent, state: T_State):
if not group_manager.get_plugin_status(module, event.group_id):
try:
if module not in ignore_rst_module and _flmt_s.check(
event.group_id
event.group_id
):
_flmt_s.start_cd(event.group_id)
await bot.send_group_msg(
@@ -177,8 +185,8 @@ async def _(matcher: Matcher, bot: Bot, event: MessageEvent, state: T_State):
if not group_manager.get_plugin_status(f"{module}:super", event.group_id):
try:
if (
_flmt_s.check(event.group_id)
and module not in ignore_rst_module
_flmt_s.check(event.group_id)
and module not in ignore_rst_module
):
_flmt_s.start_cd(event.group_id)
await bot.send_group_msg(
@@ -194,8 +202,8 @@ async def _(matcher: Matcher, bot: Bot, event: MessageEvent, state: T_State):
if not plugins_manager.get_plugin_status(module, block_type="group"):
try:
if (
_flmt_c.check(event.group_id)
and module not in ignore_rst_module
_flmt_c.check(event.group_id)
and module not in ignore_rst_module
):
_flmt_c.start_cd(event.group_id)
await bot.send_group_msg(
@@ -225,14 +233,14 @@ async def _(matcher: Matcher, bot: Bot, event: MessageEvent, state: T_State):
# 维护
if not plugins_manager.get_plugin_status(module, block_type="all"):
if isinstance(
event, GroupMessageEvent
event, GroupMessageEvent
) and group_manager.check_group_is_white(event.group_id):
return
try:
if isinstance(event, GroupMessageEvent):
if (
_flmt_c.check(event.group_id)
and module not in ignore_rst_module
_flmt_c.check(event.group_id)
and module not in ignore_rst_module
):
_flmt_c.start_cd(event.group_id)
await bot.send_group_msg(
@@ -267,9 +275,9 @@ async def _(matcher: Matcher, bot: Bot, event: MessageEvent, state: T_State):
limit_type = plugin_cd_data["limit_type"]
rst = plugin_cd_data["rst"]
if (
(isinstance(event, PrivateMessageEvent) and check_type == "private")
or (isinstance(event, GroupMessageEvent) and check_type == "group")
or plugins2cd_manager.get_plugin_data(module).get("check_type") == "all"
(isinstance(event, PrivateMessageEvent) and check_type == "private")
or (isinstance(event, GroupMessageEvent) and check_type == "group")
or plugins2cd_manager.get_plugin_data(module).get("check_type") == "all"
):
cd_type_ = event.user_id
if limit_type == "group" and isinstance(event, GroupMessageEvent):
@@ -288,9 +296,9 @@ async def _(matcher: Matcher, bot: Bot, event: MessageEvent, state: T_State):
limit_type = plugin_block_data["limit_type"]
rst = plugin_block_data["rst"]
if (
(isinstance(event, PrivateMessageEvent) and check_type == "private")
or (isinstance(event, GroupMessageEvent) and check_type == "group")
or check_type == "all"
(isinstance(event, PrivateMessageEvent) and check_type == "private")
or (isinstance(event, GroupMessageEvent) and check_type == "group")
or check_type == "all"
):
block_type_ = event.user_id
if limit_type == "group" and isinstance(event, GroupMessageEvent):
@@ -304,8 +312,8 @@ async def _(matcher: Matcher, bot: Bot, event: MessageEvent, state: T_State):
plugins2block_manager.set_true(block_type_, module)
# Count
if (
plugins2count_manager.check_plugin_count_status(module)
and event.user_id not in bot.config.superusers
plugins2count_manager.check_plugin_count_status(module)
and event.user_id not in bot.config.superusers
):
plugin_count_data = plugins2count_manager.get_plugin_count_data(module)
limit_type = plugin_count_data["limit_type"]
@@ -375,4 +383,3 @@ async def init_rst(rst: str, event: MessageEvent):
if "[at]" in rst and isinstance(event, GroupMessageEvent):
rst = rst.replace("[at]", str(at(event.user_id)))
return rst
+31 -8
View File
@@ -1,7 +1,6 @@
from nonebot.exception import MockApiException
from nonebot.adapters.onebot.v11 import Bot, MessageSegment
from nonebot.adapters.onebot.v11 import Bot, Message
from utils.manager import group_manager
from utils.utils import get_message_text
from typing import Dict, Any
import re
@@ -10,15 +9,39 @@ import re
async def handle_api_call(bot: Bot, api: str, data: Dict[str, Any]):
r = None
if (
(api == "send_msg" and data["message"] == "group_id" or api == "send_group_msg")
and (r := re.search("^\[\[_task\|(.*)]]", get_message_text(data["message"])))
(
(api == "send_msg" and data["message_type"] == "group")
or api == "send_group_msg"
)
and (
(
r := re.search(
"^\[\[_task\|(.*)]]",
data["message"].strip()
if isinstance(data["message"], str)
else str(data["message"]["text"]).strip(),
)
)
or (
r := re.search(
"^&#91;&#91;_task\|(.*)&#93;&#93;",
data["message"].strip()
if isinstance(data["message"], str)
else str(data["message"]["text"]).strip(),
)
)
)
and r.group(1) in group_manager.get_task_data().keys()
):
task = r.group(1)
group_id = data["group_id"]
if not await group_manager.check_group_task_status(group_id, task):
if group_manager.get_group_level(
group_id
) < 0 or not await group_manager.check_group_task_status(group_id, task):
raise MockApiException(f"被动技能 {task} 处于关闭状态...")
else:
msg = str(data["message"][0])
msg = msg.replace(f"&#91;&#91;_task|{task}&#93;&#93;", "")
data["message"][0] = MessageSegment.text(msg)
msg = str(data["message"]).strip()
msg = msg.replace(f"&#91;&#91;_task|{task}&#93;&#93;", "").replace(
f"[[_task|{task}]]", ""
)
data["message"] = Message(msg)
+3 -4
View File
@@ -6,11 +6,10 @@ from nonebot.adapters.onebot.v11 import (
MessageEvent,
)
from nonebot.rule import to_me
from nonebot.params import CommandArg
from models.friend_user import FriendUser
from models.group_member_info import GroupInfoUser
from services.log import logger
from utils.utils import get_message_img
from utils.utils import get_message_img, get_message_text
from .data_source import get_chat_result, hello, no_result
from configs.config import NICKNAME, Config
@@ -42,8 +41,8 @@ ai = on_message(rule=to_me(), priority=8)
@ai.handle()
async def _(bot: Bot, event: MessageEvent, arg: Message = CommandArg()):
msg = arg.extract_plain_text().strip()
async def _(bot: Bot, event: MessageEvent):
msg = get_message_text(event.json())
img = get_message_img(event.json())
if "CQ:xml" in str(event.get_message()):
return
+16 -8
View File
@@ -17,7 +17,7 @@ from utils.utils import is_number, scheduler, get_bot
from typing import Optional
from services.log import logger
from nonebot import Driver
from nonebot.params import CommandArg, ArgPlainText
from nonebot.params import CommandArg, ArgStr
import nonebot
__zx_plugin_name__ = "B站订阅"
@@ -112,14 +112,22 @@ async def _(event: MessageEvent, state: T_State, arg: Message = CommandArg()):
state["id"] = int(id_)
@add_sub.got("sub_type")
@add_sub.got("sub_user")
@add_sub.got("id")
async def _(event: MessageEvent, state: T_State, id_: str = ArgPlainText("id")):
season_data = state["season_data"]
if not is_number(id_) or int(id_) < 1 or int(id_) > len(season_data):
await add_sub.reject_arg("id", "Id必须为数字且在范围内!请重新输入...")
id_ = season_data[int(id_) - 1]["media_id"]
sub_type = state["sub_type"]
sub_user = state["sub_user"]
async def _(
event: MessageEvent,
state: T_State,
id_: str = ArgStr("id"),
sub_type: str = ArgStr("sub_type"),
sub_user: str = ArgStr("sub_user"),
):
if sub_type in ["season", "动漫", "番剧"] and state.get("season_data"):
season_data = state["season_data"]
if not is_number(id_) or int(id_) < 1 or int(id_) > len(season_data):
await add_sub.reject_arg("id", "Id必须为数字且在范围内!请重新输入...")
id_ = season_data[int(id_) - 1]["media_id"]
id_ = int(id_)
if sub_type in ["主播", "直播"]:
await add_sub.send(await add_live_sub(id_, sub_user))
elif sub_type.lower() in ["up", "用户"]:
+2 -3
View File
@@ -1,5 +1,4 @@
from nonebot.adapters.onebot.v11 import Bot
from nonebot.typing import T_State
from nonebot.permission import SUPERUSER
from nonebot import on_command
from .data_source import check_update, get_latest_version_data
@@ -8,6 +7,7 @@ from utils.utils import scheduler, get_bot
from pathlib import Path
from configs.config import Config
from nonebot.rule import to_me
from nonebot.params import ArgStr
import platform
import os
@@ -73,8 +73,7 @@ async def _():
@restart.got("flag", prompt="确定是否重启真寻?(重启失败咱们将失去联系,请谨慎!)")
async def _(state: T_State):
flag = state["flag"]
async def _(flag: str = ArgStr("flag")):
if flag.lower() in ["true", "是", "好", "确定", "确定是"]:
await restart.send("开始重启真寻..请稍等...")
open("is_restart", "w")
-1
View File
@@ -122,7 +122,6 @@ onmyoji_update = on_keyword({'更新阴阳师信息'}, permission=SUPERUSER, pri
@prts.handle()
async def _(bot: Bot, event: MessageEvent, state: T_State, reg: Tuple[Any, ...] = RegexGroup()):
msg = str(event.get_message()).strip()
print(reg)
if msg in ['方舟一井', '方舟1井']:
num = 300
else:
-1
View File
@@ -182,7 +182,6 @@ def init_rst(
rst += f"第 {index} 抽获取UP {name}\n"
else:
rst += f"第 {index} 抽获取 {name}\n"
print(rst)
return rst[:-1] if rst else ""
+1 -1
View File
@@ -72,6 +72,6 @@ async def _():
if msg_list and code == 200:
await bot.send_group_forward_msg(group_id=g, messages=msg_list)
else:
bot.send_group_msg(group_id=g, messages=msg_list)
await bot.send_group_msg(group_id=g)
except Exception as e:
logger.error(f"GROUP {g} epic免费游戏推送错误 {type(e)}: {e}")
+1 -1
View File
@@ -1,7 +1,7 @@
from httpx import AsyncClient
from datetime import datetime
from nonebot.log import logger
from nonebot.adapters.cqhttp import Bot
from nonebot.adapters.onebot.v11 import Bot
from configs.config import NICKNAME
+9 -16
View File
@@ -4,14 +4,11 @@ from utils.image_utils import get_img_hash
import random
from utils.message_builder import image
from nonebot import on_message
from utils.utils import get_message_img
from nonebot.params import CommandArg, Command
from nonebot.adapters.onebot.v11 import GroupMessageEvent, Message
from utils.utils import get_message_img, get_message_text
from nonebot.adapters.onebot.v11 import GroupMessageEvent
from configs.config import Config
from utils.http_utils import AsyncHttpx
from utils.manager import group_manager
from services.log import logger
from typing import Tuple
__zx_plugin_name__ = "复读"
@@ -81,18 +78,14 @@ fudu = on_message(permission=GROUP, priority=9)
@fudu.handle()
async def _(event: GroupMessageEvent, cmd: Tuple[str, ...] = Command(), arg: Message = CommandArg()):
if (
event.is_tome()
or cmd
or not await group_manager.check_group_task_status(event.group_id, "fudu")
):
async def _(event: GroupMessageEvent):
if event.is_tome():
return
if arg.extract_plain_text().strip():
if arg.extract_plain_text().strip().find("@可爱的小真寻") != -1:
if get_message_text(event.json()):
if get_message_text(event.json()).find("@可爱的小真寻") != -1:
await fudu.finish("复制粘贴的虚空艾特?", at_sender=True)
img = get_message_img(event.json())
msg = arg.extract_plain_text().strip()
msg = get_message_text(event.json())
if not img and not msg:
return
if img:
@@ -112,7 +105,7 @@ async def _(event: GroupMessageEvent, cmd: Tuple[str, ...] = Command(), arg: Mes
"fudu", "FUDU_PROBABILITY"
) and not _fudu_list.is_repeater(event.group_id):
if random.random() < 0.2:
await fudu.finish("打断施法!")
await fudu.finish("[[_task|fudu]]打断施法!")
_fudu_list.set_repeater(event.group_id)
if img and msg:
rst = msg + image(f"compare_{event.group_id}_img.jpg", "temp")
@@ -125,7 +118,7 @@ async def _(event: GroupMessageEvent, cmd: Tuple[str, ...] = Command(), arg: Mes
if rst:
if rst.endswith("打断施法!"):
rst = "打断" + rst
await fudu.send(rst)
await fudu.send("[[_task|fudu]]" + rst)
async def get_fudu_img_hash(url, group_id):
@@ -48,7 +48,7 @@ async def query_resource(resource_name: str) -> str:
planning_route = True
if not resource_name or resource_name not in resource_name_list:
# return f"未查找到 {resource_name} 资源,可通过 “原神资源列表” 获取全部资源名称.."
return ''
return ""
map_ = Map(
resource_name, CENTER_POINT, planning_route=planning_route, ratio=MAP_RATIO
)
@@ -84,7 +84,7 @@ def check_resource_exists(resource: str) -> bool:
检查资源是否存在
:param resource: 资源名称
"""
resource = resource.replace('路径', '').replace('路线', '')
resource = resource.replace("路径", "").replace("路线", "")
return resource in resource_name_list
@@ -97,16 +97,18 @@ async def init(flag: bool = False):
await download_resource_data(semaphore)
await download_resource_type()
if not CENTER_POINT:
CENTER_POINT = json.load(open(resource_label_file, "r", encoding="utf8"))[
"CENTER_POINT"
]
with open(resource_type_file, "r", encoding="utf8") as f:
data = json.load(f)
for id_ in data:
for x in data[id_]["children"]:
resource_name_list.append(x["name"])
if resource_label_file.exists():
CENTER_POINT = json.load(
open(resource_label_file, "r", encoding="utf8")
)["CENTER_POINT"]
if resource_label_file.exists():
with open(resource_type_file, "r", encoding="utf8") as f:
data = json.load(f)
for id_ in data:
for x in data[id_]["children"]:
resource_name_list.append(x["name"])
except TimeoutError:
logger.warning('原神资源查询信息初始化超时....')
logger.warning("原神资源查询信息初始化超时....")
# 图标及位置资源
@@ -114,7 +116,7 @@ async def download_resource_data(semaphore: Semaphore):
icon_path.mkdir(parents=True, exist_ok=True)
resource_label_file.parent.mkdir(parents=True, exist_ok=True)
try:
response = await AsyncHttpx.get(POINT_LIST_URL, timeout=5)
response = await AsyncHttpx.get(POINT_LIST_URL, timeout=10)
if response.status_code == 200:
data = response.json()
if data["message"] == "OK":
@@ -157,16 +159,14 @@ async def download_resource_data(semaphore: Semaphore):
# 下载原神地图并拼图
async def download_map_init(
semaphore: Semaphore, flag: bool = False
):
async def download_map_init(semaphore: Semaphore, flag: bool = False):
global CENTER_POINT, MAP_RATIO
map_path.mkdir(exist_ok=True, parents=True)
_map = map_path / "map.png"
if _map.exists() and os.path.getsize(_map) > 1024 * 1024 * 30:
_map.unlink()
try:
response = await AsyncHttpx.get(MAP_URL, timeout=5)
response = await AsyncHttpx.get(MAP_URL, timeout=10)
if response.status_code == 200:
data = response.json()
if data["message"] == "OK":
@@ -176,20 +176,24 @@ async def download_map_init(
data = data["slices"]
idx = 0
for _map_data in data[0]:
map_url = _map_data['url']
map_url = _map_data["url"]
await download_image(
map_url,
f"{map_path}/{idx}.png",
semaphore,
force_flag=flag,
)
BuildImage(0, 0, background=f"{map_path}/{idx}.png", ratio=MAP_RATIO).save()
BuildImage(
0, 0, background=f"{map_path}/{idx}.png", ratio=MAP_RATIO
).save()
idx += 1
_w, h = BuildImage(0, 0, background=f"{map_path}/0.png").size
w = _w * len(os.listdir(map_path))
map_file = BuildImage(w, h, _w, h, ratio=MAP_RATIO)
for i in range(idx):
map_file.paste(BuildImage(0, 0, background=f"{map_path}/{i}.png"))
map_file.paste(
BuildImage(0, 0, background=f"{map_path}/{i}.png")
)
map_file.save(f"{map_path}/map.png")
else:
logger.warning(f'获取原神地图失败 msg: {data["message"]}')
@@ -205,7 +209,7 @@ async def download_map_init(
async def download_resource_type():
resource_type_file.parent.mkdir(parents=True, exist_ok=True)
try:
response = await AsyncHttpx.get(LABEL_URL, timeout=5)
response = await AsyncHttpx.get(LABEL_URL, timeout=10)
if response.status_code == 200:
data = response.json()
if data["message"] == "OK":
@@ -251,7 +255,7 @@ async def download_image(
async with semaphore:
try:
if not os.path.exists(path) or not is_valid or force_flag:
if await AsyncHttpx.download_file(img_url, path, timeout=5):
if await AsyncHttpx.download_file(img_url, path, timeout=10):
logger.info(f"下载原神资源图标:{img_url}")
if gen_flag:
gen_icon(path)
@@ -1,13 +1,12 @@
from nonebot import on_message, on_regex
from configs.path_config import IMAGE_PATH
from utils.message_builder import image
from utils.utils import is_number
from utils.utils import is_number, get_message_text
from services.log import logger
from nonebot.adapters.onebot.v11 import MessageEvent, GroupMessageEvent, Message
from nonebot.adapters.onebot.v11 import MessageEvent, GroupMessageEvent
from utils.utils import FreqLimiter, cn2py
from configs.config import Config
from utils.manager import withdraw_message_manager
from nonebot.params import CommandArg
from .rule import rule
import random
import os
@@ -58,8 +57,8 @@ _path = IMAGE_PATH / "image_management"
@send_img.handle()
async def _(event: MessageEvent, arg: Message = CommandArg()):
msg = arg.extract_plain_text().strip().split()
async def _(event: MessageEvent):
msg = get_message_text(event.json()).split()
gallery = msg[0]
if gallery not in Config.get_config("image_management", "IMAGE_DIR_LIST"):
return
+115 -105
View File
@@ -1,7 +1,7 @@
from nonebot import on_message
from services.log import logger
from nonebot.adapters.onebot.v11 import GroupMessageEvent, Message
from utils.utils import get_message_json, get_local_proxy, is_number
from nonebot.adapters.onebot.v11 import GroupMessageEvent
from utils.utils import get_message_json, get_local_proxy, is_number, get_message_text
from nonebot.adapters.onebot.v11.permission import GROUP
from bilibili_api import video
from utils.message_builder import image
@@ -11,11 +11,11 @@ from utils.browser import get_browser
from configs.path_config import IMAGE_PATH
from utils.http_utils import AsyncHttpx
from configs.config import Config
from nonebot.params import CommandArg
from utils.user_agent import get_user_agent
import aiohttp
import asyncio
import time
from bilibili_api import settings
from utils.manager import group_manager
import ujson as json
@@ -47,113 +47,123 @@ _tmp = {}
@parse_bilibili_json.handle()
async def _(event: GroupMessageEvent, arg: Message = CommandArg()):
if await group_manager.check_group_task_status(event.group_id, "bilibili_parse"):
vd_info = None
url = None
if get_message_json(event.json()):
try:
data = json.loads(get_message_json(event.json())[0]["data"])
except (IndexError, KeyError):
data = None
if data:
# 转发视频
if data.get("desc") == "哔哩哔哩":
response = await AsyncHttpx.get(
data["meta"]["detail_1"]["qqdocurl"], timeout=7
)
url = str(response.url).split("?")[0]
bvid = url.split("/")[-1]
vd_info = await video.Video(bvid=bvid).get_info()
# 转发专栏
if (
data.get("meta")
and data["meta"].get("news")
and data["meta"]["news"].get("desc") == "哔哩哔哩专栏"
):
url = data["meta"]["news"]["jumpUrl"]
page = None
try:
browser = await get_browser()
if not browser:
return
page = await browser.new_page(
user_agent="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"
" (KHTML, like Gecko) Chrome/93.0.4530.0 Safari/537.36"
)
await page.goto(url, wait_until="networkidle", timeout=10000)
await page.set_viewport_size({"width": 2560, "height": 1080})
await page.click("#app > div")
div = await page.query_selector("#app > div")
await div.screenshot(
path=f"{IMAGE_PATH}/temp/cv_{event.user_id}.png",
timeout=100000,
)
await asyncio.get_event_loop().run_in_executor(
None, resize, f"{IMAGE_PATH}/temp/cv_{event.user_id}.png"
)
await parse_bilibili_json.send(
image(f"cv_{event.user_id}.png", "temp")
)
await page.close()
logger.info(
f"USER {event.user_id} GROUP {event.group_id} 解析bilibili转发 {url}"
)
except Exception as e:
logger.error(f"尝试解析bilibili专栏 {url} 失败 {type(e)}:{e}")
if page:
await page.close()
return
# BV
if arg.extract_plain_text().strip():
msg = arg.extract_plain_text().strip()
if "BV" in msg:
index = msg.find("BV")
if len(msg[index + 2 :]) >= 10:
msg = msg[index : index + 12]
url = f"https://www.bilibili.com/video/{msg}"
vd_info = await video.Video(bvid=msg).get_info()
elif "av" in msg:
index = msg.find("av")
if len(msg[index + 2 :]) >= 9:
msg = msg[index + 2 : index + 11]
if is_number(msg):
url = f"https://www.bilibili.com/video/{msg}"
vd_info = await video.Video(aid=int(msg)).get_info()
elif "https://b23.tv" in msg:
url = "https://" + msg[msg.find("b23.tv") : msg.find("b23.tv") + 13]
res = await AsyncHttpx.get(url, timeout=7)
url = str(res.url).split("?")[0]
bvid = url.split("/")[-1]
vd_info = await video.Video(bvid=bvid).get_info()
if vd_info:
async def _(event: GroupMessageEvent):
vd_info = None
url = None
if get_message_json(event.json()):
try:
data = json.loads(get_message_json(event.json())[0]["data"])
except (IndexError, KeyError):
data = None
if data:
# 转发视频
if data.get("desc") == "哔哩哔哩":
async with aiohttp.ClientSession(
headers=get_user_agent()
) as session:
async with session.get(
data["meta"]["detail_1"]["qqdocurl"],
proxy=get_local_proxy(),
timeout=7,
) as response:
url = str(response.url).split("?")[0]
bvid = url.split("/")[-1]
vd_info = await video.Video(bvid=bvid).get_info()
# response = await AsyncHttpx.get(
# data["meta"]["detail_1"]["qqdocurl"], timeout=7
# )
# url = str(response.url).split("?")[0]
# bvid = url.split("/")[-1]
# vd_info = await video.Video(bvid=bvid).get_info()
# 转发专栏
if (
url in _tmp.keys() and time.time() - _tmp[url] > 30
) or url not in _tmp.keys():
_tmp[url] = time.time()
aid = vd_info["aid"]
title = vd_info["title"]
author = vd_info["owner"]["name"]
reply = vd_info["stat"]["reply"] # 回复
favorite = vd_info["stat"]["favorite"] # 收藏
coin = vd_info["stat"]["coin"] # 投币
# like = vd_info['stat']['like'] # 点赞
# danmu = vd_info['stat']['danmaku'] # 弹幕
date = time.strftime("%Y-%m-%d", time.localtime(vd_info["ctime"]))
data.get("meta")
and data["meta"].get("news")
and data["meta"]["news"].get("desc") == "哔哩哔哩专栏"
):
url = data["meta"]["news"]["jumpUrl"]
page = None
try:
await parse_bilibili_json.send(
image(vd_info["pic"]) + f"\nav{aid}\n标题:{title}\n"
f"UP:{author}\n"
f"上传日期:{date}\n"
f"回复:{reply},收藏:{favorite},投币:{coin}\n"
f"{url}"
browser = await get_browser()
if not browser:
return
page = await browser.new_page(
user_agent="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"
" (KHTML, like Gecko) Chrome/93.0.4530.0 Safari/537.36"
)
except ActionFailed:
logger.warning(f"{event.group_id} 发送bilibili解析失败")
else:
await page.goto(url, wait_until="networkidle", timeout=10000)
await page.set_viewport_size({"width": 2560, "height": 1080})
await page.click("#app > div")
div = await page.query_selector("#app > div")
await div.screenshot(
path=f"{IMAGE_PATH}/temp/cv_{event.user_id}.png",
timeout=100000,
)
await asyncio.get_event_loop().run_in_executor(
None, resize, f"{IMAGE_PATH}/temp/cv_{event.user_id}.png"
)
await parse_bilibili_json.send(
"[[_task|bilibili_parse]]" + image(f"cv_{event.user_id}.png", "temp")
)
await page.close()
logger.info(
f"USER {event.user_id} GROUP {event.group_id} 解析bilibili转发 {url}"
)
except Exception as e:
logger.error(f"尝试解析bilibili专栏 {url} 失败 {type(e)}:{e}")
if page:
await page.close()
return
# BV
if msg := get_message_text(event.json()):
if "BV" in msg:
index = msg.find("BV")
if len(msg[index + 2 :]) >= 10:
msg = msg[index : index + 12]
url = f"https://www.bilibili.com/video/{msg}"
vd_info = await video.Video(bvid=msg).get_info()
elif "av" in msg:
index = msg.find("av")
if len(msg[index + 2 :]) >= 9:
msg = msg[index + 2 : index + 11]
if is_number(msg):
url = f"https://www.bilibili.com/video/{msg}"
vd_info = await video.Video(aid=int(msg)).get_info()
elif "https://b23.tv" in msg:
url = "https://" + msg[msg.find("b23.tv") : msg.find("b23.tv") + 13]
res = await AsyncHttpx.get(url, timeout=7)
url = str(res.url).split("?")[0]
bvid = url.split("/")[-1]
vd_info = await video.Video(bvid=bvid).get_info()
if vd_info:
if (
url in _tmp.keys() and time.time() - _tmp[url] > 30
) or url not in _tmp.keys():
_tmp[url] = time.time()
aid = vd_info["aid"]
title = vd_info["title"]
author = vd_info["owner"]["name"]
reply = vd_info["stat"]["reply"] # 回复
favorite = vd_info["stat"]["favorite"] # 收藏
coin = vd_info["stat"]["coin"] # 投币
# like = vd_info['stat']['like'] # 点赞
# danmu = vd_info['stat']['danmaku'] # 弹幕
date = time.strftime("%Y-%m-%d", time.localtime(vd_info["ctime"]))
try:
await parse_bilibili_json.send(
"[[_task|bilibili_parse]]" +
image(vd_info["pic"]) + f"\nav{aid}\n标题:{title}\n"
f"UP:{author}\n"
f"上传日期:{date}\n"
f"回复:{reply},收藏:{favorite},投币:{coin}\n"
f"{url}"
)
except ActionFailed:
logger.warning(f"{event.group_id} 发送bilibili解析失败")
else:
logger.info(
f"USER {event.user_id} GROUP {event.group_id} 解析bilibili转发 {url}"
)
def resize(path: str):
+1 -1
View File
@@ -238,7 +238,7 @@ async def get_image(img_url: str, user_id: int) -> Optional[str]:
TEMP_PATH / f"pix_{user_id}_{img_url[-10:-4]}.jpg", "wb"
) as f:
await f.write(response.content)
return f"pix_{user_id}_{img_url[-10:-4]}.jpg"
return TEMP_PATH / f"pix_{user_id}_{img_url[-10:-4]}.jpg"
except TimeoutError:
logger.warning(f"PIX:{img_url} 图片下载超时...")
pass
+2 -2
View File
@@ -149,11 +149,11 @@ async def _(bot: Bot, event: MessageEvent, arg: Message = CommandArg()):
f"title:{title}\n"
f"author:{author}\n"
f"PID:{pid}\nUID:{uid}\n"
f"{image(_img, 'temp')}"
f"{image(_img)}"
)
)
else:
msg_id = await pix.send(image(_img, 'temp'))
msg_id = await pix.send(image(_img))
logger.info(
f"(USER {event.user_id}, GROUP {event.group_id if isinstance(event, GroupMessageEvent) else 'private'})"
f" 查看PIX图库PID: {pid}"
+7 -7
View File
@@ -89,13 +89,13 @@ async def search_online_setu(
ws_url = Config.get_config("pixiv", "PIXIV_NGINX_URL")
if ws_url:
url_ = url_.replace("i.pximg.net", ws_url).replace("i.pixiv.cat", ws_url)
index = random.randint(1, 100000) if id_ is None else id_
path_ = IMAGE_PATH / path_ if path_ else TEMP_PATH
file_name = f"{index}_temp_setu.jpg" if path_ == TEMP_PATH else f"{index}.jpg"
path_.mkdir(parents=True, exist_ok=True)
for i in range(3):
logger.info(f"search_online_setu --> {i}")
try:
index = random.randint(1, 100000) if id_ is None else id_
path_ = IMAGE_PATH / path_ if path_ else TEMP_PATH
file_name = f"{index}_temp_setu.jpg" if not path_ == TEMP_PATH else f"{index}.jpg"
path_.mkdir(parents=True, exist_ok=True)
if not await AsyncHttpx.download_file(
url_,
path_ / file_name,
@@ -104,14 +104,14 @@ async def search_online_setu(
continue
if id_ is not None:
if (
os.path.getsize(f"{IMAGE_PATH}/{path_}/{index}.jpg")
os.path.getsize(path_ / f"{index}.jpg")
> 1024 * 1024 * 1.5
):
compressed_image(
f"{IMAGE_PATH}/{path_}/{index}.jpg",
path_ / f"{index}.jpg",
)
logger.info(f"下载 lolicon 图片 {url_} 成功, id:{index}")
return image(abspath=path_ / file_name), index
return image(path_ / file_name), index
except TimeoutError:
pass
except Exception as e:
-36
View File
@@ -1,36 +0,0 @@
from nonebot import on_command
from nonebot.adapters.onebot.v11 import Bot, PrivateMessageEvent, GroupMessageEvent
from nonebot.typing import T_State
from nonebot.rule import to_me
__zx_plugin_name__ = "服务器 [Hidden]"
__plugin_version__ = 0.1
__plugin_author__ = "HibiKier"
server_ip = on_command("服务器", aliases={"ip"}, rule=to_me(), priority=5, block=True)
@server_ip.handle()
async def _(bot: Bot, event: PrivateMessageEvent, state: T_State):
await server_ip.finish(
"|* 请不要发给其他人! *|\n"
"\t121.40.195.22\n"
"|* 请不要发给其他人! *|\n"
"csgo ~号键控制台输入 connect 121.40.195.22 进入服务器\n"
"然后再公屏输入 !diy 来使用皮肤(英文感叹号,注意)\n"
"【说不定可以凑到内战噢,欢迎~{娱乐为主}】",
at_sender=True,
)
@server_ip.handle()
async def _(bot: Bot, event: GroupMessageEvent, state: T_State):
if event.group_id == 698279647:
await server_ip.finish(
"嗨呀!当前服务器地址是:" "\n\tay: 121.40.195.22" "\n\t夜之北枭: 101.132.170.254"
)
elif event.group_id == 1046451860:
await server_ip.finish("嗨呀!当前服务器地址是:\n121.40.195.22\n !diy")
else:
await server_ip.finish("不好意思呀,小真寻不能为你使用此功能,因为服务器IP是真寻的小秘密呀!", at_sender=True)
+6 -13
View File
@@ -1,10 +1,10 @@
from nonebot import on_regex
from .data_source import get_weather_of_city, get_city_list
from nonebot.adapters.onebot.v11 import MessageEvent, GroupMessageEvent, Message
from nonebot.adapters.onebot.v11 import MessageEvent, GroupMessageEvent
from jieba import posseg
from services.log import logger
from nonebot.params import CommandArg
import re
from nonebot.params import RegexGroup
from typing import Tuple, Any
__zx_plugin_name__ = "天气查询"
@@ -27,19 +27,12 @@ __plugin_settings__ = {
}
weather = on_regex(r".{0,10}市?的?天气.{0,10}", priority=5, block=True)
weather = on_regex(r".{0,10}?(.*)的?天气.*?.{0,10}", priority=5, block=True)
@weather.handle()
async def _(event: MessageEvent, arg: Message = CommandArg()):
msg = arg.extract_plain_text().strip()
msg1 = re.search(r".*?(.*)市?的?天气.*?", msg)
msg2 = re.search(r".*?天气(.*).*?", msg)
msg1 = msg1.group(1)
msg2 = msg2.group(1)
msg = msg1 if msg1 else msg2
if msg[-1] == "的":
msg = msg[:-1]
async def _(event: MessageEvent, reg_group: Tuple[Any, ...] = RegexGroup()):
msg = reg_group[0]
if msg[-1] != "市":
msg += "市"
city = ""
+4 -2
View File
@@ -7,8 +7,10 @@
"basic_plugins",
"configs/path_config.py",
"configs/utils",
"bot.py"
"bot.py",
"poetry.lock",
"pyproject.toml"
],
"add_file": [],
"delete_file": []
}
}
+13 -8
View File
@@ -261,15 +261,20 @@ class GroupManager(StaticData):
初始化群聊 被动技能 状态
"""
if not self._task:
_m = []
for matcher in get_matchers():
_plugin = nonebot.plugin.get_plugin(matcher.plugin_name)
try:
_module = _plugin.module
plugin_task = _module.__getattribute__("__plugin_task__")
for key in plugin_task.keys():
self._task[key] = plugin_task[key]
except AttributeError:
pass
if matcher.plugin_name not in _m:
_m.append(matcher.plugin_name)
_plugin = nonebot.plugin.get_plugin(matcher.plugin_name)
try:
_module = _plugin.module
plugin_task = _module.__getattribute__("__plugin_task__")
for key in plugin_task.keys():
if key in self._task.keys():
raise ValueError(f"plugin_task:{key} 已存在!")
self._task[key] = plugin_task[key]
except AttributeError:
pass
bot = get_bot()
if bot or group_id:
if group_id:
+3 -16
View File
@@ -10,7 +10,6 @@ import os
def image(
file: Union[str, Path, bytes] = None,
path: str = None,
abspath: Union[str, Path] = None,
b64: str = None,
) -> Union[MessageSegment, str]:
"""
@@ -20,18 +19,9 @@ def image(
参数:
:param file: 图片文件名称,默认在 resource/img 目录下
:param path: 图片所在路径,默认在 resource/img 目录下
:param abspath: 图片绝对路径
:param b64: 图片base64
"""
if abspath:
if isinstance(abspath, Path):
return MessageSegment.image(file)
return (
MessageSegment.image("file:///" + abspath)
if os.path.exists(abspath)
else ""
)
elif isinstance(file, Path):
if isinstance(file, Path):
if file.exists():
return MessageSegment.image(file)
logger.warning(f"图片 {file.absolute()}缺失...")
@@ -41,14 +31,11 @@ def image(
elif b64:
return MessageSegment.image(b64 if "base64://" in b64 else "base64://" + b64)
else:
if "http" in file:
if file.startswith("http"):
return MessageSegment.image(file)
if len(file.split(".")) == 1:
file += ".jpg"
file = (
IMAGE_PATH / path / file if path else IMAGE_PATH / file
)
if file.exists():
if (file := IMAGE_PATH / path / file if path else IMAGE_PATH / file).exists():
return MessageSegment.image(file)
else:
logger.warning(f"图片 {file} 缺失...")