summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorKyomotoi <[email protected]>2021-08-26 01:22:34 +0800
committerKyomotoi <[email protected]>2021-08-26 01:22:34 +0800
commitc177a4d279b159a76d737e6b4ae547ccdd979a4e (patch)
treebd5001f02e92a5bff38286a4251aa2781cae4683
parentf17b264ad6470ba1308deacb25b9ead59461c895 (diff)
downloadATRI-c177a4d279b159a76d737e6b4ae547ccdd979a4e.tar.gz
ATRI-c177a4d279b159a76d737e6b4ae547ccdd979a4e.tar.bz2
ATRI-c177a4d279b159a76d737e6b4ae547ccdd979a4e.zip
🐛🔥 更改一些内容
修复: - 好友/群邀请 写入文件失败 - 同意 好友/群邀请、查看申请列表 获取arg失败 删除: - 移除 Ubuntu paste 更改: - saucenao 最大显示数量为3 - anime search 最大显示数量为3
-rw-r--r--ATRI/exceptions.py4
-rw-r--r--ATRI/plugins/anime_search.py30
-rw-r--r--ATRI/plugins/essential.py75
-rw-r--r--ATRI/plugins/manage/__init__.py126
-rw-r--r--ATRI/plugins/manage/data_source.py25
-rw-r--r--ATRI/plugins/saucenao/__init__.py7
-rw-r--r--ATRI/plugins/saucenao/data_source.py53
-rw-r--r--ATRI/utils/__init__.py55
8 files changed, 168 insertions, 207 deletions
diff --git a/ATRI/exceptions.py b/ATRI/exceptions.py
index b8d4764..b49d3a0 100644
--- a/ATRI/exceptions.py
+++ b/ATRI/exceptions.py
@@ -34,7 +34,7 @@ def _save_error(prompt: str, content: str) -> str:
track_id=track_id,
prompt=prompt,
time=time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()),
- content=content,
+ content=content
)
path = ERROR_DIR / f"{track_id}.json"
with open(path, "w", encoding="utf-8") as r:
@@ -110,7 +110,7 @@ async def _track_error(
logger.debug(f"A bug has been cumming!!! Track ID: {track_id}")
msg = f"呜——出错了...追踪: {track_id}"
-
+
for superusers in BotSelfConfig.superusers:
try:
await bot.send_private_msg(user_id=superusers, message=msg)
diff --git a/ATRI/plugins/anime_search.py b/ATRI/plugins/anime_search.py
index b9a068b..6132d27 100644
--- a/ATRI/plugins/anime_search.py
+++ b/ATRI/plugins/anime_search.py
@@ -7,16 +7,14 @@ from nonebot.adapters.cqhttp.message import Message, MessageSegment
from ATRI.service import Service
from ATRI.rule import is_in_service
-from ATRI.utils import request, UbuntuPaste, Translate
+from ATRI.utils import request, Translate
from ATRI.utils.limit import FreqLimiter
from ATRI.exceptions import RequestError
-
URL = "https://api.trace.moe/search?anilistInfo=true&url="
_anime_flmt = FreqLimiter(10)
_anime_flmt_notice = choice(["慢...慢一..点❤", "冷静1下", "歇会歇会~~"])
-
__doc__ = """
通过一张图片搜索你需要的番!据说里*也可以
"""
@@ -42,9 +40,10 @@ class Anime(Service):
data = data["result"]
d = dict()
- for i in range(len(data)):
+ for i in range(3):
if data[i]["anilist"]["title"]["native"] in d.keys():
- d[data[i]["anilist"]["title"]["native"]][0] += data[i]["similarity"]
+ d[data[i]["anilist"]["title"]
+ ["native"]][0] += data[i]["similarity"]
else:
from_m = data[i]["from"] / 60
from_s = data[i]["from"] % 60
@@ -57,7 +56,8 @@ class Anime(Service):
else:
n = data[i]["episode"]
- d[Translate(data[i]["anilist"]["title"]["native"]).to_simple()] = [
+ d[Translate(data[i]["anilist"]["title"]["native"]).to_simple(
+ )] = [
data[i]["similarity"],
f"第{n}集",
f"约{int(from_m)}min{int(from_s)}s至{int(to_m)}min{int(to_s)}s处",
@@ -69,18 +69,12 @@ class Anime(Service):
for i in result:
t += 1
s = "%.2f%%" % (i[1][0] * 100)
- msg0 = msg0 + (
- "\n——————————\n"
- f"({t}) Similarity: {s}\n"
- f"Name: {i[0]}\n"
- f"Time: {i[1][1]} {i[1][2]}"
- )
-
- if len(result) == 2:
- return msg0
- else:
- repo = f"详细请移步此处~\n{await UbuntuPaste(content=msg0).paste()}"
- return repo
+ msg0 = msg0 + ("\n——————————\n"
+ f"({t}) Similarity: {s}\n"
+ f"Name: {i[0]}\n"
+ f"Time: {i[1][1]} {i[1][2]}")
+
+ return msg0
anime_search = Anime().on_command("以图搜番", "发送一张图以搜索可能的番剧")
diff --git a/ATRI/plugins/essential.py b/ATRI/plugins/essential.py
index ddf96fc..98a0e9e 100644
--- a/ATRI/plugins/essential.py
+++ b/ATRI/plugins/essential.py
@@ -28,11 +28,9 @@ from nonebot.adapters.cqhttp import (
import ATRI
from ATRI.service import Service
from ATRI.log import logger as log
-from ATRI.rule import is_in_service
from ATRI.config import BotSelfConfig
from ATRI.utils import CoolqCodeChecker
-
driver = ATRI.driver()
bots = nonebot.get_bots()
@@ -53,9 +51,8 @@ async def shutdown():
@run_preprocessor # type: ignore
-async def _check_block(
- matcher: Matcher, bot: Bot, event: MessageEvent, state: T_State
-) -> None:
+async def _check_block(matcher: Matcher, bot: Bot, event: MessageEvent,
+ state: T_State) -> None:
user_file = "block_user.json"
path = MANEGE_DIR / user_file
if not path.is_file():
@@ -138,22 +135,21 @@ async def _friend_add(bot: Bot, event: FriendRequestEvent):
apply_code = event.flag
apply_comment = event.comment
user_id = event.get_user_id()
- now_time = datetime.now()
+ now_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
data = json.loads(path.read_bytes())
- data[apply_code] = FriendRequestInfo(
- user_id=user_id, comment=apply_comment, time=now_time, is_approve=False
- )
+ data[apply_code] = FriendRequestInfo(user_id=user_id,
+ comment=apply_comment,
+ time=now_time,
+ is_approve=False).dict()
with open(path, "w", encoding="utf-8") as w:
- w.write(json.dumps(data.dict(), indent=4))
-
- repo = (
- "咱收到一条好友请求...\n"
- f"请求人:{user_id}\n"
- f"申请信息:{apply_comment}\n"
- f"申请码:{apply_code}\n"
- "Tip:好友申请 帮助"
- )
+ w.write(json.dumps(data, indent=4))
+
+ repo = ("咱收到一条好友请求...\n"
+ f"请求人:{user_id}\n"
+ f"申请信息:{apply_comment}\n"
+ f"申请码:{apply_code}\n"
+ "Tip:好友申请 帮助")
for superuser in BotSelfConfig.superusers:
await bot.send_private_msg(user_id=superuser, message=repo)
@@ -184,22 +180,21 @@ async def _group_invite(bot: Bot, event: GroupRequestEvent):
apply_code = event.flag
apply_comment = event.comment
user_id = event.get_user_id()
- now_time = datetime.now()
+ now_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
data = json.loads(path.read_bytes())
- data[apply_code] = GroupRequestInfo(
- user_id=user_id, comment=apply_comment, time=now_time, is_approve=False
- )
+ data[apply_code] = GroupRequestInfo(user_id=user_id,
+ comment=apply_comment,
+ time=now_time,
+ is_approve=False).dict()
with open(path, "w", encoding="utf-8") as w:
- w.write(json.dumps(data.dict(), indent=4))
-
- repo = (
- "咱收到一条群聊邀请请求...\n"
- f"请求人:{user_id}\n"
- f"申请信息:{apply_comment}\n"
- f"申请码:{apply_code}\n"
- "Tip:群聊邀请 帮助"
- )
+ w.write(json.dumps(data, indent=4))
+
+ repo = ("咱收到一条群聊邀请请求...\n"
+ f"请求人:{user_id}\n"
+ f"申请信息:{apply_comment}\n"
+ f"申请码:{apply_code}\n"
+ "Tip:群聊邀请 帮助")
for superuser in BotSelfConfig.superusers:
await bot.send_private_msg(user_id=superuser, message=repo)
@@ -210,7 +205,7 @@ group_member_event = Essential().on_notice("群成员变动")
@group_member_event.handle()
async def _group_member_join(bot: Bot, event: GroupIncreaseNoticeEvent):
await asyncio.sleep(randint(1, 6))
- msg = "好欸!事新人!\n" f"在下 {choice(list(BotSelfConfig.nickname))} 哒!w!"
+ msg = ("好欸!事新人!\n" f"在下 {choice(list(BotSelfConfig.nickname))} 哒!w!")
await group_member_event.finish(msg)
@@ -230,8 +225,8 @@ async def _group_admin_event(bot: Bot, event: GroupAdminNoticeEvent):
for superuser in BotSelfConfig.superusers:
await bot.send_private_msg(
- user_id=int(superuser), message=f"好欸!主人!我在群 {event.group_id} 成为了管理!!"
- )
+ user_id=int(superuser),
+ message=f"好欸!主人!我在群 {event.group_id} 成为了管理!!")
group_ban_event = Essential().on_notice("群禁言变动")
@@ -243,11 +238,9 @@ async def _group_ban_event(bot: Bot, event: GroupBanNoticeEvent):
return
if event.duration:
- msg = (
- "那个..。,主人\n"
- f"咱在群 {event.group_id} 被 {event.operator_id} 塞上了口球...\n"
- f"时长...是 {event.duration} 秒"
- )
+ msg = ("那个..。,主人\n"
+ f"咱在群 {event.group_id} 被 {event.operator_id} 塞上了口球...\n"
+ f"时长...是 {event.duration} 秒")
for superuser in BotSelfConfig.superusers:
await bot.send_private_msg(user_id=int(superuser), message=msg)
else:
@@ -276,7 +269,7 @@ async def _recall_group_event(bot: Bot, event: GroupRecallNoticeEvent):
if not check:
repo = repo.replace("CQ", "QC")
- msg = "主人,咱拿到了一条撤回信息!\n" f"{user}@[群:{group}]\n" "撤回了\n" f"{repo}"
+ msg = ("主人,咱拿到了一条撤回信息!\n" f"{user}@[群:{group}]\n" "撤回了\n" f"{repo}")
for superuser in BotSelfConfig.superusers:
await bot.send_private_msg(user_id=int(superuser), message=msg)
@@ -297,6 +290,6 @@ async def _recall_private_event(bot: Bot, event: FriendRecallNoticeEvent):
if not check:
repo = repo.replace("CQ", "QC")
- msg = "主人,咱拿到了一条撤回信息!\n" f"{user}@[私聊]" "撤回了\n" f"{repo}"
+ msg = ("主人,咱拿到了一条撤回信息!\n" f"{user}@[私聊]" "撤回了\n" f"{repo}")
for superuser in BotSelfConfig.superusers:
await bot.send_private_msg(user_id=int(superuser), message=msg)
diff --git a/ATRI/plugins/manage/__init__.py b/ATRI/plugins/manage/__init__.py
index 0be7b83..a841dfb 100644
--- a/ATRI/plugins/manage/__init__.py
+++ b/ATRI/plugins/manage/__init__.py
@@ -7,7 +7,6 @@ from nonebot.adapters.cqhttp.permission import GROUP_OWNER, GROUP_ADMIN
from .data_source import Manage
-
block_user = Manage().on_command("封禁用户", "对目标用户进行封禁", permission=SUPERUSER)
@@ -104,7 +103,9 @@ async def _deal_unblock_group(bot: Bot, event: MessageEvent, state: T_State):
await unblock_group.finish(f"好欸!群 {group_id} 重获新生!")
-global_block_service = Manage().on_command("全局禁用", "全局禁用某服务", permission=SUPERUSER)
+global_block_service = Manage().on_command("全局禁用",
+ "全局禁用某服务",
+ permission=SUPERUSER)
@global_block_service.handle()
@@ -115,7 +116,8 @@ async def _ready_block_service(bot: Bot, event: MessageEvent, state: T_State):
@global_block_service.got("global_block_service", "阿...是哪个服务呢")
-async def _deal_global_block_service(bot: Bot, event: MessageEvent, state: T_State):
+async def _deal_global_block_service(bot: Bot, event: MessageEvent,
+ state: T_State):
block_service = state["global_block_service"]
quit_list = ["算了", "罢了"]
if block_service in quit_list:
@@ -128,18 +130,22 @@ async def _deal_global_block_service(bot: Bot, event: MessageEvent, state: T_Sta
await global_block_service.finish(f"服务 {block_service} 已被禁用")
-global_unblock_service = Manage().on_command("全局启用", "全局启用某服务", permission=SUPERUSER)
+global_unblock_service = Manage().on_command("全局启用",
+ "全局启用某服务",
+ permission=SUPERUSER)
@global_unblock_service.handle()
-async def _ready_unblock_service(bot: Bot, event: MessageEvent, state: T_State):
+async def _ready_unblock_service(bot: Bot, event: MessageEvent,
+ state: T_State):
msg = str(event.message).strip()
if msg:
state["global_unblock_service"] = msg
@global_unblock_service.got("global_unblock_service", "阿...是哪个服务呢")
-async def _deal_global_unblock_service(bot: Bot, event: MessageEvent, state: T_State):
+async def _deal_global_unblock_service(bot: Bot, event: MessageEvent,
+ state: T_State):
unblock_service = state["global_unblock_service"]
quit_list = ["算了", "罢了"]
if unblock_service in quit_list:
@@ -152,9 +158,9 @@ async def _deal_global_unblock_service(bot: Bot, event: MessageEvent, state: T_S
await global_unblock_service.finish(f"服务 {unblock_service} 已启用")
-user_block_service = Manage().on_regex(
- r"对用户(.*?)禁用(.*)", "针对某一用户禁用服务", permission=SUPERUSER
-)
+user_block_service = Manage().on_regex(r"对用户(.*?)禁用(.*)",
+ "针对某一用户禁用服务",
+ permission=SUPERUSER)
@user_block_service.handle()
@@ -171,9 +177,9 @@ async def _user_block_service(bot: Bot, event: MessageEvent):
await user_block_service.finish(f"完成~已禁止用户 {aim_user} 使用 {aim_service}")
-user_unblock_service = Manage().on_regex(
- r"对用户(.*?)启用(.*)", "针对某一用户启用服务", permission=SUPERUSER
-)
+user_unblock_service = Manage().on_regex(r"对用户(.*?)启用(.*)",
+ "针对某一用户启用服务",
+ permission=SUPERUSER)
@user_unblock_service.handle()
@@ -190,22 +196,23 @@ async def _user_unblock_service(bot: Bot, event: MessageEvent):
await user_unblock_service.finish(f"完成~已允许用户 {aim_user} 使用 {aim_service}")
-group_block_service = Manage().on_command(
- "禁用", "针对所在群禁用某服务", permission=SUPERUSER | GROUP_OWNER | GROUP_ADMIN
-)
+group_block_service = Manage().on_command("禁用",
+ "针对所在群禁用某服务",
+ permission=SUPERUSER | GROUP_OWNER
+ | GROUP_ADMIN)
@group_block_service.handle()
-async def _ready_group_block_service(
- bot: Bot, event: GroupMessageEvent, state: T_State
-):
+async def _ready_group_block_service(bot: Bot, event: GroupMessageEvent,
+ state: T_State):
msg = str(event.message).strip()
if msg:
state["group_block_service"] = msg
@group_block_service.got("group_block_service", "阿...是哪个服务呢")
-async def _deal_group_block_service(bot: Bot, event: GroupMessageEvent, state: T_State):
+async def _deal_group_block_service(bot: Bot, event: GroupMessageEvent,
+ state: T_State):
aim_service = state["group_block_service"]
group_id = str(event.group_id)
quit_list = ["算了", "罢了"]
@@ -218,24 +225,23 @@ async def _deal_group_block_service(bot: Bot, event: GroupMessageEvent, state: T
await group_block_service.finish(f"完成!~已禁止本群使用服务:{aim_service}")
-group_unblock_service = Manage().on_command(
- "启用", "针对所在群启用某服务", permission=SUPERUSER | GROUP_OWNER | GROUP_ADMIN
-)
+group_unblock_service = Manage().on_command("启用",
+ "针对所在群启用某服务",
+ permission=SUPERUSER | GROUP_OWNER
+ | GROUP_ADMIN)
@group_unblock_service.handle()
-async def _ready_group_unblock_service(
- bot: Bot, event: GroupMessageEvent, state: T_State
-):
+async def _ready_group_unblock_service(bot: Bot, event: GroupMessageEvent,
+ state: T_State):
msg = str(event.message).strip()
if msg:
state["group_unblock_service"] = msg
@group_unblock_service.got("group_unblock_service", "阿...是哪个服务呢")
-async def _deal_group_unblock_service(
- bot: Bot, event: GroupMessageEvent, state: T_State
-):
+async def _deal_group_unblock_service(bot: Bot, event: GroupMessageEvent,
+ state: T_State):
aim_service = state["group_unblock_service"]
group_id = str(event.group_id)
quit_list = ["算了", "罢了"]
@@ -248,7 +254,9 @@ async def _deal_group_unblock_service(
await group_unblock_service.finish(f"完成!~已允许本群使用服务:{aim_service}")
-get_friend_add_list = Manage().on_command("获取好友申请", "获取好友申请列表", permission=SUPERUSER)
+get_friend_add_list = Manage().on_command("获取好友申请",
+ "获取好友申请列表",
+ permission=SUPERUSER)
@get_friend_add_list.handle()
@@ -267,18 +275,22 @@ async def _get_friend_add_list(bot: Bot, event: MessageEvent):
await get_friend_add_list.finish(msg1)
-approve_friend_add = Manage().on_command("同意好友", "同意好友申请", permission=SUPERUSER)
+approve_friend_add = Manage().on_command("同意好友",
+ "同意好友申请",
+ permission=SUPERUSER)
@approve_friend_add.handle()
-async def _ready_approve_friend_add(bot: Bot, event: MessageEvent, state: T_State):
+async def _ready_approve_friend_add(bot: Bot, event: MessageEvent,
+ state: T_State):
msg = str(event.message).strip()
if msg:
- state["approve_friend_add"]
+ state["approve_friend_add"] = msg
@approve_friend_add.got("approve_friend_add", "申请码GKD!")
-async def _deal_approve_friend_add(bot: Bot, event: MessageEvent, state: T_State):
+async def _deal_approve_friend_add(bot: Bot, event: MessageEvent,
+ state: T_State):
apply_code = state["approve_friend_add"]
quit_list = ["算了", "罢了"]
if apply_code in quit_list:
@@ -298,14 +310,16 @@ refuse_friend_add = Manage().on_command("拒绝好友", "拒绝好友申请", pe
@refuse_friend_add.handle()
-async def _ready_refuse_friend_add(bot: Bot, event: MessageEvent, state: T_State):
+async def _ready_refuse_friend_add(bot: Bot, event: MessageEvent,
+ state: T_State):
msg = str(event.message).strip()
if msg:
- state["refuse_friend_add"]
+ state["refuse_friend_add"] = msg
@refuse_friend_add.got("refuse_friend_add", "申请码GKD!")
-async def _deal_refuse_friend_add(bot: Bot, event: MessageEvent, state: T_State):
+async def _deal_refuse_friend_add(bot: Bot, event: MessageEvent,
+ state: T_State):
apply_code = state["refuse_friend_add"]
quit_list = ["算了", "罢了"]
if apply_code in quit_list:
@@ -321,7 +335,9 @@ async def _deal_refuse_friend_add(bot: Bot, event: MessageEvent, state: T_State)
await refuse_friend_add.finish("已拒绝!")
-get_group_invite_list = Manage().on_command("获取邀请列表", "获取群邀请列表", permission=SUPERUSER)
+get_group_invite_list = Manage().on_command("获取邀请列表",
+ "获取群邀请列表",
+ permission=SUPERUSER)
@get_group_invite_list.handle()
@@ -340,27 +356,31 @@ async def _get_group_invite_list(bot: Bot, event: MessageEvent):
await get_friend_add_list.finish(msg1)
-approve_group_invite = Manage().on_command("同意邀请", "同意群聊邀请", permission=SUPERUSER)
+approve_group_invite = Manage().on_command("同意邀请",
+ "同意群聊邀请",
+ permission=SUPERUSER)
@approve_group_invite.handle()
-async def _ready_approve_group_invite(bot: Bot, event: MessageEvent, state: T_State):
+async def _ready_approve_group_invite(bot: Bot, event: MessageEvent,
+ state: T_State):
msg = str(event.message).strip()
if msg:
- state["approve_group_invite"]
+ state["approve_group_invite"] = msg
@approve_group_invite.got("approve_group_invite", "申请码GKD!")
-async def _deal_approve_group_invite(bot: Bot, event: MessageEvent, state: T_State):
+async def _deal_approve_group_invite(bot: Bot, event: MessageEvent,
+ state: T_State):
apply_code = state["approve_group_invite"]
quit_list = ["算了", "罢了"]
if apply_code in quit_list:
await approve_group_invite.finish("好吧...")
try:
- await bot.set_group_add_request(
- flag=apply_code, sub_type="invite", approve=True
- )
+ await bot.set_group_add_request(flag=apply_code,
+ sub_type="invite",
+ approve=True)
except BaseException:
await approve_group_invite.finish("同意失败...尝试下手动?")
data = Manage().load_invite_apply_list()
@@ -369,27 +389,31 @@ async def _deal_approve_group_invite(bot: Bot, event: MessageEvent, state: T_Sta
await approve_group_invite.finish("好欸!申请已通过!")
-refuse_group_invite = Manage().on_command("拒绝邀请", "拒绝群聊邀请", permission=SUPERUSER)
+refuse_group_invite = Manage().on_command("拒绝邀请",
+ "拒绝群聊邀请",
+ permission=SUPERUSER)
@refuse_group_invite.handle()
-async def _ready_refuse_group_invite(bot: Bot, event: MessageEvent, state: T_State):
+async def _ready_refuse_group_invite(bot: Bot, event: MessageEvent,
+ state: T_State):
msg = str(event.message).strip()
if msg:
- state["refuse_group_invite"]
+ state["refuse_group_invite"] = msg
@refuse_group_invite.got("refuse_group_invite", "申请码GKD!")
-async def _deal_refuse_group_invite(bot: Bot, event: MessageEvent, state: T_State):
+async def _deal_refuse_group_invite(bot: Bot, event: MessageEvent,
+ state: T_State):
apply_code = state["refuse_group_invite"]
quit_list = ["算了", "罢了"]
if apply_code in quit_list:
await refuse_group_invite.finish("好吧...")
try:
- await bot.set_group_add_request(
- flag=apply_code, sub_type="invite", approve=False
- )
+ await bot.set_group_add_request(flag=apply_code,
+ sub_type="invite",
+ approve=False)
except BaseException:
await refuse_group_invite.finish("拒绝失败...尝试下手动?")
data = Manage().load_invite_apply_list()
diff --git a/ATRI/plugins/manage/data_source.py b/ATRI/plugins/manage/data_source.py
index 1897d03..0ecc9ae 100644
--- a/ATRI/plugins/manage/data_source.py
+++ b/ATRI/plugins/manage/data_source.py
@@ -4,27 +4,20 @@ from pathlib import Path
from datetime import datetime
from ATRI.service import Service, ServiceTools
-from ATRI.utils import UbuntuPaste
from ATRI.exceptions import ReadFileError, load_error
-
MANAGE_DIR = Path(".") / "data" / "database" / "manege"
ESSENTIAL_DIR = Path(".") / "data" / "database" / "essential"
os.makedirs(MANAGE_DIR, exist_ok=True)
os.makedirs(ESSENTIAL_DIR, exist_ok=True)
-
-TRACK_BACK_FORMAT = """
-Track ID:{track_id}
+TRACK_BACK_FORMAT = """Track ID:{track_id}
Prompt: {prompt}
Time: {time}
{content}
""".strip()
-
-__doc__ = """
-控制bot的各项服务
-"""
+__doc__ = """控制bot的各项服务"""
class Manage(Service):
@@ -160,7 +153,8 @@ class Manage(Service):
return True
@staticmethod
- def control_user_service(service: str, user_id: str, is_enabled: bool) -> bool:
+ def control_user_service(service: str, user_id: str,
+ is_enabled: bool) -> bool:
"""
Only SUPERUSER.
"""
@@ -182,7 +176,8 @@ class Manage(Service):
return True
@staticmethod
- def control_group_service(service: str, group_id: str, is_enabled: bool) -> bool:
+ def control_group_service(service: str, group_id: str,
+ is_enabled: bool) -> bool:
"""
SUPERUSER and GROUPADMIN or GROUPOWNER.
Only current group.
@@ -267,8 +262,8 @@ class Manage(Service):
time = data.get("time", "ignore")
content = data.get("content", "ignore")
- msg0 = TRACK_BACK_FORMAT.format(
- track_id=track_id, prompt=prompt, time=time, content=content
- )
- repo = f"详细请移步此处~\n{await UbuntuPaste(content=msg0).paste()}"
+ repo = TRACK_BACK_FORMAT.format(track_id=track_id,
+ prompt=prompt,
+ time=time,
+ content=content)
return repo
diff --git a/ATRI/plugins/saucenao/__init__.py b/ATRI/plugins/saucenao/__init__.py
index b55f18c..468b001 100644
--- a/ATRI/plugins/saucenao/__init__.py
+++ b/ATRI/plugins/saucenao/__init__.py
@@ -16,7 +16,6 @@ _search_flmt_notice = choice(["慢...慢一..点❤", "冷静1下", "歇会歇�
saucenao = SaouceNao().on_command("以图搜图", "透过一张图搜索可能的来源")
-
@saucenao.args_parser # type: ignore
async def _get_img(bot: Bot, event: MessageEvent, state: T_State):
msg = str(event.message).strip()
@@ -28,18 +27,16 @@ async def _get_img(bot: Bot, event: MessageEvent, state: T_State):
else:
state["img"] = msg
-
@saucenao.handle()
async def _ready_search(bot: Bot, event: MessageEvent, state: T_State):
user_id = event.get_user_id()
if not _search_flmt.check(user_id):
await saucenao.finish(_search_flmt_notice)
-
+
msg = str(event.message).strip()
if msg:
state["img"] = msg
-
@saucenao.got("img", "图呢?")
async def _deal_search(bot: Bot, event: MessageEvent, state: T_State):
user_id = event.get_user_id()
@@ -47,7 +44,7 @@ async def _deal_search(bot: Bot, event: MessageEvent, state: T_State):
img = findall(r"url=(.*?)]", msg)
if not img:
await saucenao.reject("请发送图片而不是其他东西!!")
-
+
a = SaouceNao(SauceNAO.key)
result = f"> {MessageSegment.at(user_id)}" + await a.search(img[0])
_search_flmt.start_cd(user_id)
diff --git a/ATRI/plugins/saucenao/data_source.py b/ATRI/plugins/saucenao/data_source.py
index 3f77118..4f38f2c 100644
--- a/ATRI/plugins/saucenao/data_source.py
+++ b/ATRI/plugins/saucenao/data_source.py
@@ -3,27 +3,23 @@ from random import choice
from ATRI.service import Service
from ATRI.rule import is_in_service
from ATRI.exceptions import RequestError
-from ATRI.utils import request, UbuntuPaste
-
+from ATRI.utils import request
URL = "https://saucenao.com/search.php"
-
__doc__ = """
以图搜图,仅限二刺螈
"""
class SaouceNao(Service):
- def __init__(
- self,
- api_key: str = None,
- output_type=2,
- testmode=1,
- dbmaski=32768,
- db=5,
- numres=5,
- ):
+ def __init__(self,
+ api_key: str = None,
+ output_type=2,
+ testmode=1,
+ dbmaski=32768,
+ db=5,
+ numres=5):
Service.__init__(self, "以图搜图", __doc__, rule=is_in_service("以图搜图"))
params = dict()
@@ -50,26 +46,25 @@ class SaouceNao(Service):
res = data["results"]
result = list()
- for i in range(len(res)):
- data = res[i]
+ for i in range(3):
+ sim = res[i]["header"]["similarity"]
+ if float(sim) >= 80:
+ data = res[i]
- _result = dict()
- _result["similarity"] = data["header"]["similarity"]
- _result["index_name"] = data["header"]["index_name"]
- _result["url"] = choice(data["data"].get("ext_urls", ["None"]))
- result.append(_result)
+ _result = dict()
+ _result["similarity"] = sim
+ _result["index_name"] = data[i]["header"]["index_name"]
+ _result["url"] = choice(data["data"].get("ext_urls", ["None"]))
+ result.append(_result)
msg0 = str()
for i in result:
- msg0 += (
- "\n——————————\n"
- f"Similarity: {i['similarity']}\n"
- f"Name: {i['index_name']}\n"
- f"URL: {i['url'].replace('https://', '')}"
- )
+ msg0 += ("\n——————————\n"
+ f"Similarity: {i['similarity']}\n"
+ f"Name: {i['index_name']}\n"
+ f"URL: {i['url'].replace('https://', '')}")
- if len(res) <= 3:
- return msg0
+ if not result:
+ return "没有相似的结果呢..."
else:
- repo = f"\n详细请移步此处~\n{await UbuntuPaste(content=msg0).paste()}"
- return repo
+ return msg0
diff --git a/ATRI/utils/__init__.py b/ATRI/utils/__init__.py
index 6cccc7f..d4298f5 100644
--- a/ATRI/utils/__init__.py
+++ b/ATRI/utils/__init__.py
@@ -37,7 +37,6 @@ class ListDealer:
"""
对列表进行处理
"""
-
def __init__(self, lst: list, aim):
self.lst = lst
self.aim = aim
@@ -59,7 +58,6 @@ class CoolqCodeChecker:
"""
检查所传回的cq码是否存在被注入可能
"""
-
tenc_gchat_url: str = "gchat.qpic.cn"
may_inject_keys: list = ["record", "video", "music", "xml", "json"]
@@ -89,14 +87,14 @@ class FileDealer:
"""
打开文件
"""
-
def __init__(self, path: Path, encoding: str = "utf-8"):
self.path = path
self.encoding = encoding
async def write(self, path: Path, content):
try:
- async with aiofiles.open(path, "w", encoding=self.encoding) as target:
+ async with aiofiles.open(path, "w",
+ encoding=self.encoding) as target:
await target.write(content)
except Exception:
raise Exception(f"Writing file({path}) failed!")
@@ -129,8 +127,11 @@ class ImageDealer:
"""
对图片进行压缩处理
"""
-
- def __init__(self, out_path, kb: int = 300, quality: int = 85, k: float = 0.9):
+ def __init__(self,
+ out_path,
+ kb: int = 300,
+ quality: int = 85,
+ k: float = 0.9):
self.out_path = out_path
self.kb = kb
self.quality = quality
@@ -145,7 +146,8 @@ class ImageDealer:
while o_size > self.kb:
img = Image.open(self.out_path)
x, y = img.size
- out = img.resize((int(x * self.k), int(y * self.k)), Image.ANTIALIAS)
+ out = img.resize((int(x * self.k), int(y * self.k)),
+ Image.ANTIALIAS)
try:
out.save(self.out_path, quality=self.quality)
except Exception:
@@ -192,42 +194,3 @@ class Translate:
output_str_list.append(self.text[i])
return "".join(output_str_list)
-
-
-class UbuntuPaste:
- """
- 将信息粘贴至 ubuntu pastebin
- """
-
- URL = "https://paste.ubuntu.com/"
-
- def __init__(
- self,
- poster: str = "ATRI running log",
- syntax: str = "text",
- expiration: str = "day",
- content: str = "0w0",
- ):
- self.poster = poster
- self.syntax = syntax
- self.expiration = expiration
- self.content = content
-
- def _gen_form_data(self) -> FormData:
- data = FormData()
- data.add_field("poster", self.poster)
- data.add_field("syntax", self.syntax)
- data.add_field("expiration", self.expiration)
- data.add_field("content", self.content)
- return data
-
- async def paste(self) -> str:
- try:
- res = await request.post(self.URL, self._gen_form_data())
- except BaseException:
- raise BaseException("Request failed!")
- result = str(res.url)
- if result == self.URL:
- result = self.content
-
- return result