summaryrefslogtreecommitdiff
path: root/ATRI/plugins
diff options
context:
space:
mode:
Diffstat (limited to 'ATRI/plugins')
19 files changed, 634 insertions, 549 deletions
diff --git a/ATRI/plugins/plugin_admin/__init__.py b/ATRI/plugins/plugin_admin/__init__.py
index b83da69..7dd18e7 100644
--- a/ATRI/plugins/plugin_admin/__init__.py
+++ b/ATRI/plugins/plugin_admin/__init__.py
@@ -1,6 +1,5 @@
#!/usr/bin/env python3
# -*- encoding: utf-8 -*-
-
'''
@File : __init__.py
@Time : 2020/10/11 14:37:53
@@ -18,13 +17,14 @@ from pathlib import Path
from random import randint
from nonebot.plugin import on_command
-from nonebot.adapters.cqhttp import Bot, Event
+from nonebot.typing import Bot, Event
from nonebot.permission import GROUP_ADMIN, GROUP_OWNER, SUPERUSER
-from utils.utils_yml import load_yaml
-from utils.utils_error import errorRepo
-from utils.utils_rule import check_banlist
-from utils.utils_switch import controlSwitch
+from ATRI.utils.utils_yml import load_yaml
+from ATRI.utils.utils_error import errorRepo
+from ATRI.utils.utils_rule import check_banlist
+from ATRI.utils.utils_textcheck import PUBLIC_OPINION_PATH, Textcheck
+from ATRI.utils.utils_switch import controlSwitch
CONFIG_PATH = Path('.') / 'config.yml'
master = load_yaml(CONFIG_PATH)['bot']['superusers']
@@ -34,26 +34,25 @@ switch = on_command('switch',
permission=(SUPERUSER | GROUP_OWNER | GROUP_ADMIN))
-@switch.handle() # type: ignore
+@switch.handle()
async def _(bot: Bot, event: Event, state: dict) -> None:
user = str(event.user_id)
group = str(event.group_id)
-
func = str(event.message).strip()
+ SWITCH_PATH = Path('.') / 'ATRI' / 'utils' / 'utils_rule' / 'switch.json'
+ with open(SWITCH_PATH, 'r') as f:
+ data = json.load(f)
+
if not func:
msg0 = "-==ATRI Switch Control System==-\n"
- msg0 += "┌Usage: switch on/off-{service}\n"
- msg0 += "├For SUPERUSER:\n"
- msg0 += "│ └Usage: switch all-on/off-{service}\n"
- msg0 += "└Service:\n"
- msg0 += " ├anime-setu\n"
- msg0 += " ├anime-pic-search\n"
- msg0 += " ├anime-vid-search\n"
- msg0 += " ├ai-face\n"
- msg0 += " ├pixiv-pic-search\n"
- msg0 += " ├pixiv-author-search\n"
- msg0 += " └pixiv-rank"
+ msg0 += "Usage: switch on/off-{service}\n"
+ msg0 += "* For SUPERUSER:\n"
+ msg0 += " - Usage: switch all-on/off-{service}\n"
+ msg0 += "Service:\n"
+
+ for i in data.keys():
+ msg0 += f" {i}\n"
await switch.finish(msg0)
@@ -84,128 +83,105 @@ async def _(bot: Bot, event: Event, state: dict) -> None:
# 舆情监控系统
-publicOpinion = on_command("舆情",
- rule=check_banlist(),
- permission=SUPERUSER | GROUP_ADMIN | GROUP_OWNER)
-data_PO = Path(
- '.') / 'ATRI' / 'plugins' / 'plugin_chat' / 'public_opinion.json'
+publicOpinion = on_command("舆情", rule=check_banlist(), permission=SUPERUSER)
-@publicOpinion.handle() # type: ignore
+@publicOpinion.handle()
async def _(bot: Bot, event: Event, state: dict) -> None:
msg = str(event.message).strip().split(' ')
+ with open(PUBLIC_OPINION_PATH, 'r') as f:
+ data = json.load(f)
+
if msg[0] == '':
msg0 = "---=====ATRI POM System=====---\n"
msg0 += "Usage:\n"
- msg0 += " - 舆情 [key] [times] [ban time(bot)] [repo]\n"
+ msg0 += " - 舆情 [key] [repo] [times] [ban time(bot)]\n"
+ msg0 += " - 舆情 del [key]\n"
+ msg0 += " - 舆情 list\n"
msg0 += "Tips:\n"
msg0 += " - 非 SUPERU 只能设置本群\n"
msg0 += " - SUPERU 需在后跟随 -a 以启用全局效果\n"
msg0 += " - 参数类型:\n"
msg0 += " * key: 关键词(将使用正则匹配)\n"
+ msg0 += " * repo: 触发后的关键词(可选),如为图片,键入 img\n"
msg0 += " * times: 容忍次数(n>0, int)\n"
- msg0 += " * ban time: bot对其失效时间(min, int)\n"
- msg0 += " * repo: 触发后的关键词(可选),如为图片,键入 img"
+ msg0 += " * ban time: bot对其失效时间(min, int)"
await publicOpinion.finish(msg0)
+ if msg[0] == 'del':
+ await publicOpinion.finish(Textcheck().del_word(msg[1]))
+
+ if msg[0] == 'list':
+ msg0 = "舆情检测列表如下:\n"
+ for w in data.keys():
+ msg0 += f' {w}\n'
+
if msg[0] and msg[1] and msg[2] and msg[3]:
pass
else:
msg0 = "请检查格式奥~!\n"
- msg0 += "舆情 [key] [times] [ban time(bot)] [repo]\n"
+ msg0 += "舆情 [key] [repo] [times] [ban time(bot)]\n"
msg0 += " * key: 关键词(将使用正则匹配)\n"
+ msg0 += " * repo: 触发后的关键词(可选),如为图片,键入 img\n"
msg0 += " * times: 容忍次数(n>0, int)\n"
- msg0 += " * ban time: bot对其失效时间(min, int)\n"
- msg0 += " * repo: 触发后的关键词(可选),如为图片,键入 img"
+ msg0 += " * ban time: bot对其失效时间(min, int)"
await publicOpinion.finish(msg0)
- key_word = msg[0]
- remind = msg[1]
- punish = msg[2]
- repo = msg[3]
+ key = msg[0]
+ repo = msg[1]
+ max_times = msg[2]
+ ban_time = msg[3]
- if key_word and remind and punish and repo:
- if re.findall(r"/^\d{1,}$/", remind) and re.findall(
- r"/^\d{1,}$/", punish):
- pass
-
- else:
+ if key and repo and max_times and ban_time:
+ if not re.findall(r"/^\d{1,}$/", max_times) and re.findall(
+ r"/^\d{1,}$/", ban_time):
await publicOpinion.finish("非法字符!请注意(times, ban time)类型为int(阿拉伯数字)"
)
else:
- await publicOpinion.finish("请键入完整信息!\n如需帮助,请键入 舆情")
+ await publicOpinion.finish("请键入完整信息!\n如需帮助,请键入:舆情")
if repo == "img":
- state["key_word"] = key_word
- state["remind"] = remind
- state["punish"] = punish
+ state["key"] = key
+ state["max_times"] = max_times
+ state["ban_time"] = ban_time
else:
- try:
- with open(data_PO, "r") as f:
- data = json.load(f)
- except FileNotFoundError:
- data = {}
-
- data[key_word] = [remind, punish, repo]
-
- with open(data_PO, "w") as f:
- f.write(json.dumps(data))
- f.close()
-
- msg0 = "舆情信息记录完成~!\n"
- msg0 += f"Keyword: {key_word}\n"
- msg0 += f"Times: {remind}\n"
- msg0 += f"Ban time: {punish}\n"
- msg0 += f"Repo: {repo}"
-
- await publicOpinion.finish(msg0)
+ await publicOpinion.finish(Textcheck().add_word(
+ key, repo, int(max_times), int(ban_time)))
-@publicOpinion.got("repo", prompt="检测到 repo 类型为 img,请发送一张图片") # type: ignore
+@publicOpinion.got("repo", prompt="检测到 repo 类型为 img,请发送一张图片")
async def _(bot: Bot, event: Event, state: dict) -> None:
- key_word = state["key_word"]
- remind = state["remind"]
- punish = state["punish"]
+ key = state["key"]
repo = state["repo"]
+ max_times = state["max_times"]
+ ban_time = state["ban_time"]
if "[CQ:image" not in repo:
await publicOpinion.reject("请发送一张图片而不是图片以外的东西~!(")
- try:
- with open(data_PO, "r") as f:
- data = json.load(f)
- except FileNotFoundError:
- data = {}
-
- data[key_word] = [remind, punish, repo]
-
- with open(data_PO, "w") as f:
- f.write(json.dumps(data))
- f.close()
-
- msg0 = "舆情信息记录完成~!\n"
- msg0 += f"Keyword: {key_word}\n"
- msg0 += f"Times: {remind}\n"
- msg0 += f"Ban time: {punish}\n"
- msg0 += f"Repo: {repo}"
-
- await publicOpinion.finish(msg0)
+ await publicOpinion.finish(Textcheck().add_word(key, repo, int(max_times),
+ int(ban_time)))
trackError = on_command("track", permission=SUPERUSER)
file_error = Path('.') / 'ATRI' / 'data' / 'data_Error' / 'error.json'
-@trackError.handle() # type: ignore
+@trackError.handle()
async def _(bot: Bot, event: Event, state: dict) -> None:
- track_id = str(event.message).strip()
+ args = str(event.message).strip()
+
+ if args:
+ state['track_id'] = args
+
- if not track_id:
- await trackError.finish("请告诉咱追踪ID嗷~!不然无法获取错误堆栈呢!!")
+@trackError.got('track_id', prompt='请告诉咱追踪ID嗷~!不然无法获取错误堆栈呢!!')
+async def _(bot: Bot, event: Event, state: dict) -> None:
+ track_id = state['track_id']
data = {}
@@ -230,7 +206,7 @@ async def _(bot: Bot, event: Event, state: dict) -> None:
groupSendMessage = on_command("群发", permission=SUPERUSER)
-@groupSendMessage.handle() # type: ignore
+@groupSendMessage.handle()
async def _(bot: Bot, event: Event, state: dict) -> None:
args = str(event.message).strip()
@@ -238,7 +214,7 @@ async def _(bot: Bot, event: Event, state: dict) -> None:
state['msg'] = args
-@groupSendMessage.got('msg', prompt='请告诉咱需要群发的内容~!') # type: ignore
+@groupSendMessage.got('msg', prompt='请告诉咱需要群发的内容~!')
async def _(bot: Bot, event: Event, state: dict) -> None:
msg = state['msg']
group_list = await bot.get_group_list()
@@ -251,7 +227,7 @@ async def _(bot: Bot, event: Event, state: dict) -> None:
for group in group_list:
if group['group_id'] not in ban_group_list:
- asyncio.sleep(randint(1,5))
+ asyncio.sleep(randint(1, 5))
try:
await bot.send_group_msg(group_id=group['group_id'],
message=msg)
diff --git a/ATRI/plugins/plugin_anime/__init__.py b/ATRI/plugins/plugin_anime/__init__.py
index 6fde78c..c51e73f 100644
--- a/ATRI/plugins/plugin_anime/__init__.py
+++ b/ATRI/plugins/plugin_anime/__init__.py
@@ -15,21 +15,25 @@ import json
import sqlite3
from pathlib import Path
from random import randint
+from datetime import datetime, timedelta
+from apscheduler.triggers.date import DateTrigger
from nonebot.log import logger
+from nonebot.sched import scheduler
+from nonebot.typing import Bot, Event
from nonebot.permission import SUPERUSER
-from nonebot.adapters.cqhttp import Bot, Event
from nonebot.plugin import on_message, on_command, on_regex
-from utils.utils_yml import load_yaml
-from utils.utils_error import errorRepo
-from utils.utils_history import getMessage
-from utils.utils_translate import toSimpleString
-from utils.utils_rule import check_banlist, check_switch
-from utils.utils_request import aio_get_bytes, request_get
-from utils.utils_img import compress_image, aio_download_pics
+from ATRI.utils.utils_times import countX
+from ATRI.utils.utils_yml import load_yaml
+from ATRI.utils.utils_error import errorRepo
+from ATRI.utils.utils_history import getMessage
+from ATRI.utils.utils_translate import toSimpleString
+from ATRI.utils.utils_rule import check_banlist, check_switch
+from ATRI.utils.utils_request import aio_get_bytes, request_get
+from ATRI.utils.utils_img import compress_image, aio_download_pics
-from .body import resultRepo
+from .data_source import resultRepo
CONFIG_PATH = Path('.') / 'config.yml'
config = load_yaml(CONFIG_PATH)
@@ -38,10 +42,11 @@ plugin_name_0 = "anime-pic-search"
key_SauceNAO = config['api']['SauceNaoKEY']
SaucenaoSearch = on_command('以图搜图',
- rule=check_banlist() & check_switch(plugin_name_0))
+ rule=check_banlist()
+ & check_switch(plugin_name_0, True))
-@SaucenaoSearch.handle() # type: ignore
+@SaucenaoSearch.handle()
async def _(bot: Bot, event: Event, state: dict) -> None:
user = str(event.user_id)
group = str(event.group_id)
@@ -55,7 +60,7 @@ async def _(bot: Bot, event: Event, state: dict) -> None:
state["img_url"] = img
-@SaucenaoSearch.got("img_url", prompt="请发送一张目标图片") # type: ignore
+@SaucenaoSearch.got("img_url", prompt="请发送一张目标图片")
async def _(bot: Bot, event: Event, state: dict) -> None:
img = state["img_url"]
img = re.findall(r"(http://.*?)]", img)
@@ -72,10 +77,10 @@ async def _(bot: Bot, event: Event, state: dict) -> None:
SaucenaoSearch_repo = on_message(rule=check_banlist()
- & check_switch(plugin_name_0))
+ & check_switch(plugin_name_0, True))
-@SaucenaoSearch_repo.handle() # type: ignore
+@SaucenaoSearch_repo.handle()
async def _(bot: Bot, event: Event, state: dict) -> None:
group = str(event.group_id)
msg = str(event.message)
@@ -109,10 +114,11 @@ async def _(bot: Bot, event: Event, state: dict) -> None:
plugin_name_1 = "anime-vid-search"
AnimeSearch = on_command('以图搜番',
- rule=check_banlist() & check_switch(plugin_name_1))
+ rule=check_banlist()
+ & check_switch(plugin_name_1, True))
-@AnimeSearch.handle() # type: ignore
+@AnimeSearch.handle()
async def _(bot: Bot, event: Event, state: dict) -> None:
user = str(event.user_id)
group = str(event.group_id)
@@ -126,7 +132,7 @@ async def _(bot: Bot, event: Event, state: dict) -> None:
state["img_url"] = img
-@AnimeSearch.got("img_url", prompt="请发送一张目标图片") # type: ignore
+@AnimeSearch.got("img_url", prompt="请发送一张目标图片")
async def _(bot: Bot, event: Event, state: dict) -> None:
img = state["img_url"]
img = re.findall(r"(http://.*?)]", img)
@@ -194,18 +200,53 @@ async def _(bot: Bot, event: Event, state: dict) -> None:
plugin_name_2 = "anime-setu"
key_LoliconAPI = config['api']['LoliconAPI']
setu_type = 1 # setu-type: 1(local), 2(url: https://api.lolicon.app/#/setu) default: 1(local)
+SP_temp_list = []
+SP_list = []
+SEPI_PATH = Path('.') / 'ATRI' / 'plugins' / 'plugin_anime' / 'sepi_list.json'
-setus = on_regex(
- r"来[点丶张份副个幅][涩色瑟][图圖]|[涩色瑟][图圖]来|[涩色瑟][图圖][gkd|GKD|搞快点]|[gkd|GKD|搞快点][涩色瑟][图圖]",
- rule=check_banlist() & check_switch(plugin_name_2))
+async def check_sepi(bot: Bot, event: Event, state: dict) -> bool:
+ """检查目标是否是涩批"""
+ if event.user_id in SP_list:
+ await bot.send(event, "你可少冲点吧!涩批!哼唧")
+ return False
+ else:
+ return True
+
+def add_sepi(user: int) -> None:
+ """将目标移入涩批名单"""
+ global SP_list
+ SP_list.append(user)
+
+def del_sepi(user: int) -> None:
+ """将目标移出涩批名单"""
+ global SP_list
+ SP_list.remove(user)
+
+
+setu = on_regex(
+ r"来[点丶张份副个幅][涩色瑟][图圖]|[涩色瑟][图圖]来|[涩色瑟][图圖][gkd|GKD|搞快点]|[gkd|GKD|搞快点][涩色瑟][图圖]",
+ rule=check_banlist() & check_switch(plugin_name_2, False) & check_sepi)
-@setus.handle() # type: ignore
-async def _setu(bot: Bot, event: Event, state: dict) -> None:
- group = str(event.group_id)
+@setu.handle()
+async def _(bot: Bot, event: Event, state: dict) -> None:
+ global SP_temp_list
+ user = event.user_id
+ group = event.group_id
res = randint(1, 5)
+ if countX(SP_temp_list, user) == 5:
+ add_sepi(user) # type: ignore
+ SP_temp_list = list(set(SP_temp_list))
+ delta = timedelta(hours=1)
+ trigger = DateTrigger(run_date=datetime.now() + delta)
+ scheduler.add_job(func=del_sepi,
+ trigger=trigger,
+ args=(user, ),
+ misfire_grace_time=60)
+ return
+
if setu_type == 1:
con = sqlite3.connect(
@@ -225,7 +266,8 @@ async def _setu(bot: Bot, event: Event, state: dict) -> None:
msg0 += f"[CQ:image,file=file:///{compress_image(await aio_download_pics(img))}]"
if 1 <= res < 5:
- await setus.finish(msg0)
+ SP_temp_list.append(user)
+ await setu.finish(msg0)
elif res == 5:
await bot.send(event, "我找到涩图了!但我发给主人了\nο(=•ω<=)ρ⌒☆")
@@ -246,7 +288,7 @@ async def _setu(bot: Bot, event: Event, state: dict) -> None:
data = json.loads(
request_get('https://api.lolicon.app/setu/', params))
except Exception:
- await setus.finish(errorRepo("请求数据失败,也可能为接口调用次数达上限"))
+ await setu.finish(errorRepo("请求数据失败,也可能为接口调用次数达上限"))
msg0 = "setu info:\n"
msg0 += f'Title: {data["data"][0]["title"]}\n'
@@ -254,7 +296,8 @@ async def _setu(bot: Bot, event: Event, state: dict) -> None:
msg0 += f'[CQ:image,file=file:///{compress_image(await aio_download_pics(data["data"][0]["url"]))}]'
if 1 <= res < 5:
- await setus.finish(msg0)
+ SP_temp_list.append(user)
+ await setu.finish(msg0)
elif res == 5:
await bot.send(event, "我找到涩图了!但我发给主人了\nο(=•ω<=)ρ⌒☆")
@@ -297,59 +340,3 @@ async def _(bot: Bot, event: Event, state: dict) -> None:
await setuType.finish("请检查类型是否输入正确嗷!")
await setuType.finish("Type conversion completed!")
-
-
-# @scheduler.scheduled_job(
-# "cron",
-# minute=45,
-# bot=Bot,
-# event=Event,
-# state=dict
-# )
-# async def _(bot: Bot, event: Event, state: dict) -> None:
-# group = str(event.group_id)
-
-# if banList(group=group):
-# if checkSwitch(plugin_name_2, group):
-# # group_list = await bot.get_group_list()
-# # group = sample(group_list, 1)
-# # group = group['group_id']
-
-# if setu_type == 1:
-
-# con = sqlite3.connect(Path('.') / 'ATRI' / 'data' / 'data_Sqlite' / 'setu' / 'nearR18.db')
-# cur = con.cursor()
-# msg = cur.execute('SELECT * FROM nearR18 ORDER BY RANDOM() limit 1;')
-
-# for i in msg:
-# pid = i[0]
-# title = i[1]
-# img = i[7]
-
-# msg0 = f"setu info:\n"
-# msg0 += f"Title: {title}\n"
-# msg0 += f"Pid: {pid}\n"
-# msg0 += f"[CQ:image,file=file:///{compress_image(await aio_download_pics(img))}]"
-
-# await setu.finish(msg0)
-
-# else:
-# params = {
-# "apikey": key_LoliconAPI,
-# "r18": "0",
-# "num": "1"
-# }
-
-# data = {}
-
-# try:
-# data = json.loads(request_get('https://api.lolicon.app/setu/', params))
-# except Exception:
-# await setu.finish(errorRepo("请求数据失败,也可能为接口调用次数达上限"))
-
-# msg0 = f"setu info:\n"
-# msg0 += f'Title: {data["data"][0]["title"]}\n'
-# msg0 += f'Pid: {data["data"][0]["pid"]}\n'
-# msg0 += f'[CQ:image,file=file:///{compress_image(await aio_download_pics(data["data"][0]["url"]))}]'
-
-# await setu.finish(msg0)
diff --git a/ATRI/plugins/plugin_anime/body.py b/ATRI/plugins/plugin_anime/data_source.py
index d7dae84..21f7d74 100644
--- a/ATRI/plugins/plugin_anime/body.py
+++ b/ATRI/plugins/plugin_anime/data_source.py
@@ -12,8 +12,8 @@ __author__ = 'kyomotoi'
import json
-from utils.utils_error import errorRepo
-from utils.utils_request import request_get
+from ATRI.utils.utils_error import errorRepo
+from ATRI.utils.utils_request import request_get
class SauceNAO:
diff --git a/ATRI/plugins/plugin_anime/sepi_list.json b/ATRI/plugins/plugin_anime/sepi_list.json
new file mode 100644
index 0000000..9e26dfe
--- /dev/null
+++ b/ATRI/plugins/plugin_anime/sepi_list.json
@@ -0,0 +1 @@
+{} \ No newline at end of file
diff --git a/ATRI/plugins/plugin_chat/__init__.py b/ATRI/plugins/plugin_chat/__init__.py
index ec6738f..13c6348 100644
--- a/ATRI/plugins/plugin_chat/__init__.py
+++ b/ATRI/plugins/plugin_chat/__init__.py
@@ -10,23 +10,28 @@
'''
__author__ = 'kyomotoi'
+import os
import json
from pathlib import Path
from random import choice
-from nonebot.permission import SUPERUSER
+from random import randint
from requests import exceptions
from nonebot.log import logger
from nonebot.rule import to_me
-from nonebot.adapters.cqhttp import Bot, Event
+from nonebot.typing import Bot, Event
+from nonebot.permission import SUPERUSER
from nonebot.plugin import on_command, on_message, on_notice, on_request
-from utils.utils_times import countX
-from utils.utils_yml import load_yaml
-from utils.utils_error import errorRepo
-from utils.utils_rule import check_banlist
-from utils.utils_history import saveMessage
-from utils.utils_request import request_api_text
+from ATRI.utils.utils_ban import ban
+from ATRI.utils.utils_times import countX
+from ATRI.utils.utils_yml import load_yaml
+from ATRI.utils.utils_error import errorRepo
+from ATRI.utils.utils_textcheck import Textcheck
+from ATRI.utils.utils_history import saveMessage
+from ATRI.utils.utils_request import request_api_text
+from ATRI.utils.utils_rule import check_banlist, check_switch
+
CONFIG_PATH = Path('.') / 'config.yml'
config = load_yaml(CONFIG_PATH)['bot']
@@ -37,7 +42,7 @@ master = config['superusers']
MessageSave = on_message()
-@MessageSave.handle() # type: ignore
+@MessageSave.handle()
async def _(bot: Bot, event: Event, state: dict) -> None:
user = str(event.user_id)
group = str(event.group_id)
@@ -50,7 +55,7 @@ async def _(bot: Bot, event: Event, state: dict) -> None:
saveMessage(message_id, message, user, group)
logger.opt(colors=True).info(
- f"[<yellow>{group}</yellow>]-U: (<blue>{user}</blue>) | Message: (<green>{message}</green>) Saved successfully"
+ f"GROUP[<yellow>{group}</yellow>]: USER(<blue>{user}</blue>) > Message: (<green>{message}</green>) Saved successfully"
)
@@ -58,7 +63,7 @@ async def _(bot: Bot, event: Event, state: dict) -> None:
callMe = on_message(rule=check_banlist())
-@callMe.handle() # type: ignore
+@callMe.handle()
async def _(bot: Bot, event: Event, state: dict) -> None:
msg = str(event.raw_event['raw_message']).strip()
@@ -73,7 +78,7 @@ async def _(bot: Bot, event: Event, state: dict) -> None:
pokehah = on_command("戳一戳", rule=to_me() & check_banlist())
-@pokehah.handle() # type: ignore
+@pokehah.handle()
async def _poke(bot: Bot, event: Event, state: dict) -> None:
msg = choice([
"你再戳!", "?再戳试试?", "别戳了别戳了再戳就坏了555", "我爪巴爪巴,球球别再戳了", "你戳你🐎呢?!",
@@ -100,7 +105,7 @@ poke.handle()(_poke)
groupEvent = on_notice()
-@groupEvent.handle() # type: ignore
+@groupEvent.handle()
async def _(bot: Bot, event: Event, state: dict) -> None:
if event.raw_event['notice_type'] == 'group_increase':
if event.user_id != int(event.self_id):
@@ -125,7 +130,7 @@ FRIEND_ADD = 0
GROUP_INVITE = 0
-@selfEvent.handle() # type: ignore
+@selfEvent.handle()
async def _(bot: Bot, event: Event, state: dict) -> None:
print(event.raw_event)
flag = event.raw_event['flag']
@@ -175,7 +180,7 @@ async def _(bot: Bot, event: Event, state: dict) -> None:
controlSelfEvent = on_command('selfevent', permission=SUPERUSER)
-@controlSelfEvent.handle() # type: ignore
+@controlSelfEvent.handle()
async def _(bot: Bot, event: Event, state: dict) -> None:
args = str(event.message).strip()
msg0 = ''
@@ -204,16 +209,6 @@ async def _(bot: Bot, event: Event, state: dict) -> None:
await controlSelfEvent.finish('DONE!')
-# # 舆情监听系统
-# listenPublicOpinion = on_message()
-# file_PO = Path(
-# '.') / 'ATRI' / 'plugins' / 'plugin_chat' / 'public_opinion.json'
-
-# @groupEvent.handle() # type: ignore
-# async def _(bot: Bot, event: Event, state: dict) -> None:
-# with open(file_PO, 'r') as f:
-# data = json.load(f)
-
# 口臭一下
fxxkMe = on_command('口臭一下',
aliases={'口臭', '骂我'},
@@ -221,13 +216,14 @@ fxxkMe = on_command('口臭一下',
list_M = []
-@fxxkMe.handle() # type: ignore
+@fxxkMe.handle()
async def _(bot: Bot, event: Event, state: dict) -> None:
user = str(event.user_id)
global list_M
if countX(list_M, user) >= 3:
await fxxkMe.finish("不是??你这么想被咱骂的嘛??被咱骂就这么舒服的吗?!该......你该不会是.....M吧!")
+ list_M = list(set(list_M))
elif countX(list_M, user) >= 6:
await fxxkMe.finish("给我适可而止阿!?")
@@ -253,7 +249,7 @@ hitokoto = on_command('一言',
list_Y = []
-@hitokoto.handle() # type: ignore
+@hitokoto.handle()
async def _(bot: Bot, event: Event, state: dict) -> None:
user = str(event.user_id)
global list_Y
@@ -292,4 +288,148 @@ async def _(bot: Bot, event: Event, state: dict) -> None:
# result.append(line.strip('\n'))
# resu = choice(result)
-# print(resu%name) \ No newline at end of file
+# print(resu%name)
+
+# 扔漂流瓶
+plugin_name = 'drifting-bottle'
+DRIFTING_BOTTLE_PATH = Path(
+ '.') / 'ATRI' / 'plugins' / 'plugin_chat' / 'drifting_bottle.json'
+driftingBottle = on_command('扔漂流瓶',
+ rule=to_me() & check_banlist()
+ & check_switch(plugin_name, True))
+
+
+@driftingBottle.handle()
+async def _(bot: Bot, event: Event, state: dict) -> None:
+ args = str(event.message).strip()
+
+ if args:
+ state['args'] = args
+
+
+@driftingBottle.got('args', prompt='请告诉咱瓶中内容~!')
+async def _(bot: Bot, event: Event, state: dict) -> None:
+ args = state['args']
+ user = event.user_id
+ group = event.group_id
+
+ if not DRIFTING_BOTTLE_PATH.is_file():
+ with open(DRIFTING_BOTTLE_PATH, 'w') as f:
+ f.write(json.dumps({}))
+
+ with open(DRIFTING_BOTTLE_PATH, 'r') as f:
+ data = json.load(f)
+
+ num = len(data)
+ data[num + 1] = [user, group, args]
+
+ with open(DRIFTING_BOTTLE_PATH, 'w') as f:
+ f.write(json.dumps(data))
+
+ await driftingBottle.finish('漂流瓶已飘向远方...')
+
+
+# 捡漂流瓶
+getDriftingBottle = on_command('捞漂流瓶',
+ rule=to_me() & check_banlist()
+ & check_switch(plugin_name, True))
+
+
+@getDriftingBottle.handle()
+async def _(bot: Bot, event: Event, state: dict) -> None:
+ if not DRIFTING_BOTTLE_PATH.is_file():
+ with open(DRIFTING_BOTTLE_PATH, 'w') as f:
+ f.write(json.dumps({}))
+
+ with open(DRIFTING_BOTTLE_PATH, 'r') as f:
+ data = json.load(f)
+
+ num = len(data)
+ if not num:
+ await getDriftingBottle.finish('暂无漂流瓶可供打捞呢~(')
+
+ num = randint(1, num)
+ bottle = data[str(num)]
+ user = bottle[0]
+ group = bottle[1]
+ msg = bottle[2]
+
+ msg0 = f'[CQ:at,qq={event.user_id}]\n'
+ msg0 += f'漂流瓶[{num}]来自群[{group}][{user}],内容如下\n'
+ msg0 += msg
+
+ await getDriftingBottle.finish(msg0)
+
+
+# 清除漂流瓶
+delDriftingBottle = on_command('清除漂流瓶',
+ rule=check_banlist(),
+ permission=SUPERUSER)
+
+
+@delDriftingBottle.handle()
+async def _(bot: Bot, event: Event, state: dict) -> None:
+ args = str(event.message).strip()
+
+ if not args:
+ msg0 = 'Drifting Bottle:\n'
+ msg0 += '*For SUPERUSERS'
+ msg0 += '- delall\n'
+ msg0 += '- del [num]\n'
+ msg0 += 'eg: 清除漂流瓶 del 123'
+
+ await delDriftingBottle.finish(msg0)
+
+ if not DRIFTING_BOTTLE_PATH.is_file():
+ with open(DRIFTING_BOTTLE_PATH, 'w') as f:
+ f.write(json.dumps({}))
+
+ await delDriftingBottle.finish('清除了个寂寞...')
+
+ with open(DRIFTING_BOTTLE_PATH, 'r') as f:
+ data = json.load(f)
+
+ if args[0] == 'delall':
+ os.remove(os.path.abspath(DRIFTING_BOTTLE_PATH))
+
+ elif args[0] == 'del':
+ try:
+ del data[args[1]]
+ except:
+ await delDriftingBottle.finish(errorRepo('清除失败了...'))
+
+ with open(DRIFTING_BOTTLE_PATH, 'w') as f:
+ f.write(json.dumps(data))
+ f.close()
+
+ result = args[1] if args[0] == 'del' else "ALL"
+ await delDriftingBottle.finish(
+ f'完成啦!成功清除漂流瓶[{result}],目前还剩余[{len(data)}]个~')
+
+
+# 舆情监听
+publicOpinion = on_message(rule=check_banlist(True))
+ban_temp_list = []
+
+
+@publicOpinion.handle()
+async def _(bot: Bot, event: Event, state: dict) -> None:
+ global ban_temp_list
+ msg = str(event.message)
+ user = str(event.user_id)
+
+ # 检查是否满足条件
+ if countX(ban_temp_list, user) == Textcheck().get_times(str(Textcheck().check(msg))):
+ ban_temp_list = list(set(ban_temp_list))
+ ban(user)
+
+ if Textcheck().check(msg) == "False":
+ return
+
+ if Textcheck().check(msg):
+ if user in master:
+ await publicOpinion.finish("主人你给我注意点阿?!你这可是在死亡边缘试探呢!!")
+
+ ban_temp_list.append(int(user))
+
+ await publicOpinion.finish(Textcheck().check(msg))
diff --git a/ATRI/plugins/plugin_chat/drifting_bottle.json b/ATRI/plugins/plugin_chat/drifting_bottle.json
new file mode 100644
index 0000000..9e26dfe
--- /dev/null
+++ b/ATRI/plugins/plugin_chat/drifting_bottle.json
@@ -0,0 +1 @@
+{} \ No newline at end of file
diff --git a/ATRI/plugins/plugin_chat/public_opinion.json b/ATRI/plugins/plugin_chat/public_opinion.json
deleted file mode 100644
index e69de29..0000000
--- a/ATRI/plugins/plugin_chat/public_opinion.json
+++ /dev/null
diff --git a/ATRI/plugins/plugin_pixiv/__init__.py b/ATRI/plugins/plugin_pixiv/__init__.py
index 3c5b849..c7687ed 100644
--- a/ATRI/plugins/plugin_pixiv/__init__.py
+++ b/ATRI/plugins/plugin_pixiv/__init__.py
@@ -15,18 +15,18 @@ import json
from requests import exceptions
from nonebot.plugin import on_command
-from nonebot.adapters.cqhttp import Bot, Event
+from nonebot.typing import Bot, Event
-from utils.utils_error import errorRepo
-from utils.utils_request import request_get
-from utils.utils_rule import check_banlist, check_switch
+from ATRI.utils.utils_error import errorRepo
+from ATRI.utils.utils_img import aio_download_pics
+from ATRI.utils.utils_rule import check_banlist, check_switch
plugin_name_0 = "pixiv-pic-search"
pixivSearchIMG = on_command('p站搜图',
- rule=check_banlist() & check_switch(plugin_name_0))
+ rule=check_banlist() & check_switch(plugin_name_0, True))
-@pixivSearchIMG.handle() # type: ignore
+@pixivSearchIMG.handle()
async def _(bot: Bot, event: Event, state: dict) -> None:
user = str(event.user_id)
group = str(event.group_id)
@@ -40,7 +40,7 @@ async def _(bot: Bot, event: Event, state: dict) -> None:
state["pid"] = pid
-@pixivSearchIMG.got("pid", prompt="请发送目标PID码") # type: ignore
+@pixivSearchIMG.got("pid", prompt="请发送目标PID码")
async def _(bot: Bot, event: Event, state: dict) -> None:
pid = state["pid"]
pid = re.findall(r"\d+", pid)
@@ -52,24 +52,27 @@ async def _(bot: Bot, event: Event, state: dict) -> None:
await bot.send(event, "别急!在搜索了!")
- URL = f"https://api.imjad.cn/pixiv/v1/?type=illust&id={pid}"
+ URL = f"https://api.imjad.cn/pixiv/v1/?type=illust&id={pid[0]}"
data = {}
try:
- data = json.loads(request_get(URL))
+ data = json.loads(await aio_download_pics(URL))
except exceptions:
await pixivSearchIMG.finish(errorRepo("请求数据失败"))
+ IMG = data["response"][0]["image_urls"]["large"]
+ IMG = IMG.replace("i.pximg.net", "i.pixiv.cat")
+
msg0 = f'[CQ:at,qq={state["user"]}]\n'
msg0 += "Search result:\n"
- msg0 += f"Pid: {pid}\n"
+ msg0 += f"Pid: {pid[0]}\n"
msg0 += f'Title {data["response"][0]["title"]}\n'
msg0 += f'W&H: {data["response"][0]["width"]}x{data["response"][0]["height"]}\n'
msg0 += f'Tags: {data["response"][0]["tags"]}\n'
msg0 += f'Account Name: {data["response"][0]["user"]["account"]}\n'
msg0 += f'Author Name: {data["response"][0]["user"]["name"]}\n'
msg0 += f'Link: https://www.pixiv.net/users/{data["response"][0]["user"]["id"]}\n'
- msg0 += f'IMG: https://pixiv.cat/{pid}.jpg'
+ msg0 += IMG
await pixivSearchIMG.finish(msg0)
@@ -77,10 +80,10 @@ async def _(bot: Bot, event: Event, state: dict) -> None:
plugin_name_1 = "pixiv-author-search"
pixivSearchAuthor = on_command("p站画师",
rule=check_banlist()
- & check_switch(plugin_name_1))
+ & check_switch(plugin_name_1, True))
-@pixivSearchAuthor.handle() # type: ignore
+@pixivSearchAuthor.handle()
async def _(bot: Bot, event: Event, state: dict) -> None:
user = str(event.user_id)
group = str(event.group_id)
@@ -94,7 +97,7 @@ async def _(bot: Bot, event: Event, state: dict) -> None:
state["author_id"] = author_id
-@pixivSearchAuthor.got("author_id", prompt="请发送目标画师id") # type: ignore
+@pixivSearchAuthor.got("author_id", prompt="请发送目标画师id")
async def _(bot: Bot, event: Event, state: dict) -> None:
author_id = state["author_id"]
author_id = re.findall(r"\d+", author_id)
@@ -104,43 +107,48 @@ async def _(bot: Bot, event: Event, state: dict) -> None:
else:
await pixivSearchAuthor.reject("请发送纯阿拉伯数字的画师id")
- await bot.send(event, f"别急!在搜索了!\n将展示画师[{author_id}]的前三项作品")
+ await bot.send(event, f"别急!在搜索了!\n将展示画师[{author_id[0]}]的前三项作品")
- URL = f"https://api.imjad.cn/pixiv/v1/?type=member_illust&id={author_id}"
+ URL = f"https://api.imjad.cn/pixiv/v1/?type=member_illust&id={author_id[0]}"
data = {}
try:
- data = json.loads(request_get(URL))
+ data = json.loads(await aio_download_pics(URL))
except exceptions:
await pixivSearchAuthor.finish(errorRepo("请求网络失败"))
+ d = {}
+
for i in range(0, 3):
pid = data["response"][i]["id"]
- IMG = f"https://pixiv.cat/{author_id}.jpg"
- data[i] = [f"{pid}", f"{IMG}"]
+ title = data["response"][i]["title"]
+ IMG = data["response"][i]["image_urls"]["large"]
+ IMG = IMG.replace("i.pximg.net", "i.pixiv.cat")
+ d[i] = [f"{pid}", f"{title}", f"{IMG}"]
- msg0 = f'[CQ:at,qq={state["user"]}]\n'
+ msg = f'[CQ:at,qq={state["user"]}]'
- result = sorted(data.items(), key=lambda x: x[1], reverse=True)
+ result = sorted(d.items(), key=lambda x: x[1], reverse=True)
t = 0
for i in result:
t += 1
- msg = "\n---------------\n"
+ msg += "\n————————————\n"
msg += f"({t})\n"
- msg += f"Pid: {i[1][0]}\n{i[1][1]}"
- msg0 += msg
+ msg += f"Title: {i[1][1]}\n"
+ msg += f"Pid: {i[1][0]}\n"
+ msg += f"{i[1][2]}"
- await pixivSearchAuthor.finish(msg0)
+ await pixivSearchAuthor.finish(msg)
plugin_name_2 = "pixiv-rank"
pixivRank = on_command("p站排行榜",
- rule=check_banlist() & check_switch(plugin_name_2))
+ rule=check_banlist() & check_switch(plugin_name_2, True))
-@pixivRank.handle() # type: ignore
+@pixivRank.handle()
async def _(bot: Bot, event: Event, state: dict) -> None:
user = str(event.user_id)
@@ -150,27 +158,31 @@ async def _(bot: Bot, event: Event, state: dict) -> None:
data = {}
try:
- data = json.loads(request_get(URL))
+ data = json.loads(await aio_download_pics(URL))
except exceptions:
await pixivRank.finish(errorRepo("网络请求失败"))
+ d = {}
+
for i in range(0, 5):
pid = data["response"][0]["works"][i]["work"]["id"]
- IMG = f"https://pixiv.cat/{pid}.jpg"
- data[i] = [f"{pid}", f"{IMG}"]
+ title = data["response"][0]["works"][i]["work"]["title"]
+ IMG = data["response"][i]["works"]["image_urls"]["large"]
+ IMG = IMG.replace("i.pximg.net", "i.pixiv.cat")
+ d[i] = [f"{pid}", f"{title}", f"{IMG}"]
- msg0 = f"[CQ:at,qq={user}]"
+ msg = f"[CQ:at,qq={user}]"
- result = sorted(data.items(), key=lambda x: x[1], reverse=True)
+ result = sorted(d.items(), key=lambda x: x[1], reverse=True)
t = 0
for i in result:
t += 1
- msg = "\n---------------\n"
+ msg += "\n————————————\n"
msg += f"({t})\n"
+ msg += f"Title: {i[1][1]}"
msg += f"Pid: {i[1][0]}"
- msg += f"{i[1][1]}"
- msg0 += msg
+ msg += f"{i[1][2]}"
- await pixivRank.finish(msg0)
+ await pixivRank.finish(msg)
diff --git a/ATRI/plugins/plugin_rich/__init__.py b/ATRI/plugins/plugin_rich/__init__.py
index 51b86e8..6d2dec8 100644
--- a/ATRI/plugins/plugin_rich/__init__.py
+++ b/ATRI/plugins/plugin_rich/__init__.py
@@ -15,13 +15,13 @@ import json
import requests
from nonebot.log import logger
+from nonebot.typing import Bot, Event
from nonebot.plugin import on_message
-from nonebot.adapters.cqhttp import Bot, Event
-from utils.utils_times import countX
-from utils.utils_rule import check_banlist
-from utils.utils_request import request_get
-from .body import dec
+from ATRI.utils.utils_times import countX
+from ATRI.utils.utils_rule import check_banlist
+from ATRI.utils.utils_request import request_get
+from .data_source import dec
BILI_REPORT_FORMAT = """[{aid}] Info:
Title: {title}
@@ -36,7 +36,7 @@ bilibiliRich = on_message(rule=check_banlist())
b_list = []
-@bilibiliRich.handle() # type: ignore
+@bilibiliRich.handle()
async def _(bot: Bot, event: Event, state: dict) -> None:
global b_list
user = event.user_id
@@ -101,7 +101,7 @@ cloudmusicRich = on_message(rule=check_banlist())
c_list = []
-@cloudmusicRich.handle() # type: ignore
+@cloudmusicRich.handle()
async def _(bot: Bot, event: Event, state: dict) -> None:
global c_list
user = event.user_id
diff --git a/ATRI/plugins/plugin_rich/body.py b/ATRI/plugins/plugin_rich/body.py
deleted file mode 100644
index ae3d99b..0000000
--- a/ATRI/plugins/plugin_rich/body.py
+++ /dev/null
@@ -1,32 +0,0 @@
-#!/usr/bin/env python3
-# -*- encoding: utf-8 -*-
-'''
-@File : body.py
-@Time : 2020/10/11 14:40:43
-@Author : Kyomotoi
-@Contact : kyomotoiowo@gmail.com
-@Github : https://github.com/Kyomotoi
-@License : Copyright © 2018-2020 Kyomotoi, All Rights Reserved.
-'''
-__author__ = 'kyomotoi'
-
-table='fZodR9XQDSUm21yCkr6zBqiveYah8bt4xsWpHnJE7jL5VG3guMTKNPAwcF'
-tr={}
-for i in range(58):
- tr[table[i]]=i
-s=[11,10,3,8,4,6]
-xor=177451812
-add=8728348608
-
-def dec(x) -> int:
- r=0
- for i in range(6):
- r+=tr[x[s[i]]]*58**i
- return (r-add)^xor
-
-def enc(x) -> str:
- x=(x^xor)+add
- r=list('BV1 4 1 7 ')
- for i in range(6):
- r[s[i]]=table[x//58**i%58]
- return ''.join(r) \ No newline at end of file
diff --git a/ATRI/plugins/plugin_rich/data_source.py b/ATRI/plugins/plugin_rich/data_source.py
new file mode 100644
index 0000000..148d64b
--- /dev/null
+++ b/ATRI/plugins/plugin_rich/data_source.py
@@ -0,0 +1,34 @@
+#!/usr/bin/env python3
+# -*- encoding: utf-8 -*-
+'''
+@File : data_source.py
+@Time : 2020/11/21 11:11:37
+@Author : Kyomotoi
+@Contact : kyomotoiowo@gmail.com
+@Github : https://github.com/Kyomotoi
+@License : Copyright © 2018-2020 Kyomotoi, All Rights Reserved.
+'''
+__author__ = 'kyomotoi'
+
+table = 'fZodR9XQDSUm21yCkr6zBqiveYah8bt4xsWpHnJE7jL5VG3guMTKNPAwcF'
+tr = {}
+for i in range(58):
+ tr[table[i]] = i
+s = [11, 10, 3, 8, 4, 6]
+xor = 177451812
+add = 8728348608
+
+
+def dec(x) -> int:
+ r = 0
+ for i in range(6):
+ r += tr[x[s[i]]] * 58**i
+ return (r - add) ^ xor
+
+
+def enc(x) -> str:
+ x = (x ^ xor) + add
+ r = list('BV1 4 1 7 ')
+ for i in range(6):
+ r[s[i]] = table[x // 58**i % 58]
+ return ''.join(r)
diff --git a/ATRI/plugins/plugin_sqlite/__init__.py b/ATRI/plugins/plugin_sqlite/__init__.py
index a1208f1..45c33da 100644
--- a/ATRI/plugins/plugin_sqlite/__init__.py
+++ b/ATRI/plugins/plugin_sqlite/__init__.py
@@ -14,18 +14,18 @@ import os
import json
import sqlite3
from pathlib import Path
+from nonebot.typing import Bot, Event
from aiohttp import client_exceptions
from nonebot.plugin import on_command
from nonebot.permission import SUPERUSER
-from nonebot.adapters.cqhttp import Bot, Event
-from utils.utils_error import errorRepo
-from utils.utils_request import aio_get_bytes
+from ATRI.utils.utils_error import errorRepo
+from ATRI.utils.utils_request import aio_get_bytes
SetuData = on_command('setu', permission=SUPERUSER)
-@SetuData.handle() # type: ignore
+@SetuData.handle()
async def _(bot: Bot, event: Event, state: dict) -> None:
msg0 = "-==ATRI Setu Data System==-\n"
msg0 += "Upload:\n"
@@ -39,7 +39,7 @@ async def _(bot: Bot, event: Event, state: dict) -> None:
UploadSetu = on_command('setu-upload', permission=SUPERUSER)
-@UploadSetu.handle() # type: ignore
+@UploadSetu.handle()
async def _(bot: Bot, event: Event, state: dict) -> None:
msg = str(event.message).strip().split(' ')
@@ -72,10 +72,11 @@ async def _(bot: Bot, event: Event, state: dict) -> None:
name = info["user"]["name"]
u_id = info["user"]["id"]
user_link = f'https://www.pixiv.net/users/{u_id}'
- img = f'https://pixiv.cat/{pid}.jpg'
+ IMG = info["iamge_urls"]["large"]
+ IMG = IMG.replace("i.pximg.net", "i.pixiv.cat")
data_setu = (f'{pid}', f'{title}', f'{tags}', f'{account}', f'{name}',
- f'{u_id}', f'{user_link}', f'{img}')
+ f'{u_id}', f'{user_link}', f'{IMG}')
if s_type == "nearr18":
s_type = "nearR18"
@@ -84,6 +85,8 @@ async def _(bot: Bot, event: Event, state: dict) -> None:
else:
pass
+ os.makedirs('ATRI/data/data_Sqlite/setu', exist_ok=True)
+
if os.path.exists(f'ATRI/data/data_Sqlite/setu/{s_type}.db'):
print('数据文件存在!')
else:
@@ -114,7 +117,7 @@ async def _(bot: Bot, event: Event, state: dict) -> None:
DeleteSetu = on_command('setu-delete', permission=SUPERUSER)
-@DeleteSetu.handle() # type: ignore
+@DeleteSetu.handle()
async def _(bot: Bot, event: Event, state: dict) -> None:
msg = str(event.message).strip().split(' ')
diff --git a/ATRI/plugins/plugin_status/__init__.py b/ATRI/plugins/plugin_status/__init__.py
index bc4fd13..0f9098d 100644
--- a/ATRI/plugins/plugin_status/__init__.py
+++ b/ATRI/plugins/plugin_status/__init__.py
@@ -15,15 +15,15 @@ import sqlite3
from pathlib import Path
from nonebot.plugin import on_command
-from nonebot.adapters.cqhttp import Bot, Event
+from nonebot.typing import Bot, Event
-from utils.utils_error import errorRepo
-from utils.utils_rule import check_banlist
+from ATRI.utils.utils_error import errorRepo
+from ATRI.utils.utils_rule import check_banlist
status_info = on_command('status', rule=check_banlist())
-@status_info.handle() # type: ignore
+@status_info.handle()
async def _(bot: Bot, event: Event, state: dict) -> None:
msg = str(event.message).strip()
diff --git a/ATRI/plugins/plugin_test/__init__.py b/ATRI/plugins/plugin_test/__init__.py
index a83052d..72c7372 100644
--- a/ATRI/plugins/plugin_test/__init__.py
+++ b/ATRI/plugins/plugin_test/__init__.py
@@ -16,16 +16,16 @@ from pathlib import Path
from random import sample
import nonebot
+from nonebot.typing import Bot, Event
from nonebot.plugin import on_command
from nonebot.permission import SUPERUSER
-from nonebot.adapters.cqhttp import Bot, Event
# 此目录下均为功能测试!
testRecord = on_command('测试语音', permission=SUPERUSER)
-@testRecord.handle() # type: ignore
+@testRecord.handle()
async def _(bot: Bot, event: Event, state: dict) -> None:
await testRecord.finish(
f"[CQ:record,file=file:///{os.path.abspath(Path('.') / 'ATRI' / 'plugins' / 'plugin_test' / 'test.mp3')}]"
@@ -35,17 +35,8 @@ async def _(bot: Bot, event: Event, state: dict) -> None:
testGroupList = on_command('获取群列表', permission=SUPERUSER)
-@testGroupList.handle() # type: ignore
+@testGroupList.handle()
async def _(bot: Bot, event: Event, state: dict) -> None:
group_list = await bot.get_group_list()
group = sample(group_list, 1)
print(group[0]['group_id'], type(group[0]['group_id']))
-
-
-testBot = on_command('获取bot', permission=SUPERUSER)
-
-
-@testBot.handle() # type: ignore
-async def _(bot: Bot, event: Event, state: dict) -> None:
- test_bot = nonebot.get_bots()
- print(test_bot, type(test_bot.keys()))
diff --git a/ATRI/plugins/plugin_utils/__init__.py b/ATRI/plugins/plugin_utils/__init__.py
index 9d29a82..16a57d2 100644
--- a/ATRI/plugins/plugin_utils/__init__.py
+++ b/ATRI/plugins/plugin_utils/__init__.py
@@ -16,23 +16,22 @@ from time import strftime
from datetime import datetime, timedelta
from nonebot.plugin import on_command
-from nonebot.adapters.cqhttp import Bot, Event
+from nonebot.typing import Bot, Event
-from utils.utils_error import errorRepo
-from utils.utils_rule import check_banlist, check_switch
-
-from .roll import roll_dice
-from .generate import infoID, numberID
-from .genshin import GetInfo, JsonAnalysis
+from ATRI.utils.utils_error import errorRepo
+from ATRI.utils.utils_rule import check_banlist, check_switch
+from .data_source import Generate, Genshin, Roll
plugin_name_0 = "one-key-adult"
generateID = on_command("我要转大人,一天打25小时游戏",
- rule=check_banlist() & check_switch(plugin_name_0))
+ aliases={'虚拟身份', '一键成年'},
+ rule=check_banlist()
+ & check_switch(plugin_name_0, True))
-@generateID.handle() # type: ignore
+@generateID.handle()
async def _(bot: Bot, event: Event, state: dict) -> None:
- NAME, AREA = infoID()
+ NAME, AREA = Generate().infoID()
BIRTH_BEGIN = datetime(*[1980, 10, 10]) # type: ignore
BIRTH_END = datetime(*[2002, 10, 10]) # type: ignore
@@ -45,7 +44,8 @@ async def _(bot: Bot, event: Event, state: dict) -> None:
(BIRTH_BEGIN + id_card_year_old).timetuple())
id_card_sex = random.choice([0, 1])
id_card_name = random.choice(NAME[{0: "female", 1: "male"}[id_card_sex]])
- id_card_id = numberID(id_card_area, id_card_sex, id_card_birth_day) # type: ignore
+ id_card_id = Generate().numberID(id_card_area, id_card_sex,
+ id_card_birth_day) # type: ignore
msg0 = "恭喜,你已经成大人了!\n"
msg0 += "这是你一天25h游戏的通行证:\n"
@@ -61,7 +61,7 @@ async def _(bot: Bot, event: Event, state: dict) -> None:
rollD = on_command("roll", rule=check_banlist())
-@rollD.handle() # type: ignore
+@rollD.handle()
async def _(bot: Bot, event: Event, state: dict) -> None:
args = str(event.message).strip()
@@ -69,8 +69,7 @@ async def _(bot: Bot, event: Event, state: dict) -> None:
state['resu'] = args
-@rollD.got("resu",
- prompt="roll 参数不能为空~!\ndemo:1d10 或 2d10+2d10") # type: ignore
+@rollD.got("resu", prompt="roll 参数不能为空~!\ndemo:1d10 或 2d10+2d10")
async def _(bot: Bot, event: Event, state: dict) -> None:
resu = state['resu']
match = re.match(r'^([\dd+\s]+?)$', resu)
@@ -78,15 +77,16 @@ async def _(bot: Bot, event: Event, state: dict) -> None:
if not match:
await rollD.finish("请输入正确的参数!!\ndemo:1d10 或 2d10+2d10")
- await rollD.finish(roll_dice(resu))
+ await rollD.finish(Roll().roll_dice(resu))
plugin_name_1 = 'genshin-search'
genshinInfo = on_command('genshin',
- rule=check_banlist() & check_switch(plugin_name_1))
+ rule=check_banlist()
+ & check_switch(plugin_name_1, True))
-@genshinInfo.handle() # type: ignore
+@genshinInfo.handle()
async def _(bot: Bot, event: Event, state: dict) -> None:
args = str(event.message).strip()
@@ -94,7 +94,7 @@ async def _(bot: Bot, event: Event, state: dict) -> None:
state['uid'] = args
-@genshinInfo.got('uid', prompt='请告诉咱需要查询的UID,暂时只支持国服嗷~(') # type: ignore
+@genshinInfo.got('uid', prompt='请告诉咱需要查询的UID,暂时只支持国服嗷~(')
async def _(bot: Bot, event: Event, state: dict) -> None:
uid = str(state['uid'])
@@ -103,12 +103,14 @@ async def _(bot: Bot, event: Event, state: dict) -> None:
uid_info = ''
try:
- uid_info = JsonAnalysis(GetInfo(uid))
+ uid_info = Genshin().JsonAnalysis(Genshin().GetInfo(uid))
except:
- await genshinInfo.finish(errorRepo("数据请求错误,原因可能为ID输入错误或不存在\n暂时只支持国服查询("))
+ await genshinInfo.finish(
+ errorRepo("数据请求错误,原因可能为ID输入错误或不存在\n暂时只支持国服查询("))
msg0 = f'{uid} Genshin Info:\n'
msg0 += uid_info
+ print(uid_info)
await genshinInfo.finish(msg0)
else:
diff --git a/ATRI/plugins/plugin_utils/data_source.py b/ATRI/plugins/plugin_utils/data_source.py
new file mode 100644
index 0000000..da6c52c
--- /dev/null
+++ b/ATRI/plugins/plugin_utils/data_source.py
@@ -0,0 +1,194 @@
+#!/usr/bin/env python3
+# -*- encoding: utf-8 -*-
+'''
+@File : data_source.py
+@Time : 2020/11/21 11:13:42
+@Author : Kyomotoi
+@Contact : kyomotoiowo@gmail.com
+@Github : https://github.com/Kyomotoi
+@License : Copyright © 2018-2020 Kyomotoi, All Rights Reserved.
+'''
+__author__ = 'kyomotoi'
+
+import re
+import os
+import time
+import json
+import string
+import random
+import hashlib
+import requests
+from pathlib import Path
+from zipfile import PyZipFile
+from typing import Tuple, Dict, List
+
+
+class Generate:
+ """虚拟身份证部分"""
+ GENERATE_DATA_PATH = Path(
+ '.') / 'ATRI' / 'plugins' / 'plugin_utils' / 'main.bin'
+
+ def infoID(self) -> Tuple[Dict[str, List[str]], Dict[str, str]]:
+ with PyZipFile(os.path.abspath(self.GENERATE_DATA_PATH),
+ "r") as zipFile:
+ with zipFile.open("name.json", "r") as f:
+ name = json.loads(f.read().decode())
+ with zipFile.open("area.json", "r") as f:
+ area = json.loads(f.read().decode())
+ return name, area
+
+ def numberID(self, area: int, sex: int, birth: int) -> str:
+ def checkSum(fullCode: str) -> int or str:
+ assert len(fullCode) == 17
+ checkSum = sum([((1 << (17 - i)) % 11) * int(fullCode[i])
+ for i in range(0, 17)])
+ checkDigit = (12 - (checkSum % 11)) % 11
+ if checkDigit < 10:
+ return checkDigit
+ else:
+ return "X" # type: ignore
+
+ orderCode = str(random.randint(10, 99))
+ sexCode = str(random.randrange(sex, 10, step=2))
+ fullCode = str(area) + str(birth) + str(orderCode) + str(sexCode)
+ fullCode += str(checkSum(fullCode))
+ return fullCode
+
+
+class Genshin:
+ """原神部分"""
+ def md5(self, text: str) -> str:
+ """text 转 md5"""
+ md5 = hashlib.md5()
+ md5.update(text.encode())
+ return md5.hexdigest()
+
+ def DSGet(self) -> str:
+ mhyVersion = "2.1.0"
+ n = self.md5(mhyVersion)
+ i = str(int(time.time()))
+ r = ''.join(random.sample(string.ascii_lowercase + string.digits, 6))
+ c = self.md5("salt=" + n + "&t=" + i + "&r=" + r)
+ return i + "," + r + "," + c
+
+ def GetInfo(self, uid: str) -> str:
+ """请求API"""
+ req = requests.get(
+ url=
+ f"https://api-takumi.mihoyo.com/game_record/genshin/api/index?server=cn_gf01&role_id={uid}",
+ headers={
+ 'Accept': 'application/json, text/plain, */*',
+ 'DS': self.DSGet(),
+ 'Origin': 'https://webstatic.mihoyo.com',
+ 'x-rpc-app_version': '2.1.0',
+ 'User-Agent':
+ 'Mozilla/5.0 (Linux; Android 9; Unspecified Device) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/39.0.0.0 Mobile Safari/537.36 miHoYoBBS/2.2.0',
+ 'x-rpc-client_type': '4',
+ 'Referer':
+ 'https://webstatic.mihoyo.com/app/community-game-records/index.html?v=6',
+ 'Accept-Encoding': 'gzip, deflate',
+ 'Accept-Language': 'zh-CN,en-US;q=0.8',
+ 'X-Requested-With': 'com.mihoyo.hyperion'
+ })
+ return req.text
+
+ def JsonAnalysis(self, JsonText) -> str:
+ """解析数据"""
+ data = json.loads(JsonText)
+
+ Character_Info = "Roles:\n"
+ Character_List = []
+ Character_List = data["data"]["avatars"]
+ for i in Character_List:
+ if (i["element"] == "None"):
+ Character_Type = "无属性"
+ elif (i["element"] == "Anemo"):
+ Character_Type = "风属性"
+ elif (i["element"] == "Pyro"):
+ Character_Type = "火属性"
+ elif (i["element"] == "Geo"):
+ Character_Type = "岩属性"
+ elif (i["element"] == "Electro"):
+ Character_Type = "雷属性"
+ elif (i["element"] == "Cryo"):
+ Character_Type = "冰属性"
+ elif (i["element"] == "Hydro"):
+ Character_Type = "水属性"
+ else:
+ Character_Type = "草属性"
+
+ if (i["name"] == "旅行者"):
+ if (i["image"].find("UI_AvatarIcon_PlayerGirl") != -1):
+ TempText = f'* {i["name"]}:\n'
+ TempText += f' - [萤——妹妹] {i["level"]}级 {Character_Type}\n'
+
+ elif (i["image"].find("UI_AvatarIcon_PlayerBoy") != -1):
+ TempText = f'* {i["name"]}:\n'
+ TempText += f' - [空——哥哥] {i["level"]}级 {Character_Type}\n'
+
+ else:
+ TempText = f'* {i["name"]}:\n'
+ TempText += f' - [性别判断失败] {i["level"]}级 {Character_Type}\n'
+ else:
+ TempText = f'* {i["name"]} {i["rarity"]}★角色:\n'
+ TempText += f' - {i["level"]}级 好感度({i["fetter"]})级 {Character_Type}\n'
+
+ Character_Info = Character_Info + TempText
+
+ a1 = data["data"]["stats"]["spiral_abyss"]
+
+ Account_Info = 'Account Info:\n'
+ Account_Info += f'- 活跃天数:{data["data"]["stats"]["active_day_number"]} 天\n'
+ Account_Info += f'- 达成成就:{data["data"]["stats"]["achievement_number"]} 个\n'
+ Account_Info += f'- 获得角色:{data["data"]["stats"]["avatar_number"]}个\n'
+ Account_Info += f'- 深渊螺旋:{"没打" if (data["data"]["stats"]["spiral_abyss"] == "-") else f"打到了{a1}"}\n'
+ Account_Info += f'* 收集:\n'
+ Account_Info += f' - 风神瞳{data["data"]["stats"]["anemoculus_number"]}个 岩神瞳{data["data"]["stats"]["geoculus_number"]}个\n'
+ Account_Info += f'* 解锁:\n'
+ Account_Info += f' - 传送点{data["data"]["stats"]["way_point_number"]}个 秘境{data["data"]["stats"]["domain_number"]}个\n'
+ Account_Info += f'* 共开启宝箱:\n'
+ Account_Info += f' - 普通:{data["data"]["stats"]["common_chest_number"]}个 精致:{data["data"]["stats"]["exquisite_chest_number"]}个\n'
+ Account_Info += f' - 珍贵:{data["data"]["stats"]["luxurious_chest_number"]}个 华丽:{data["data"]["stats"]["precious_chest_number"]}个'
+
+ return Character_Info + "\r\n" + Account_Info
+
+
+class Roll:
+ """骰娘部分"""
+ def roll_dice(self, par: str) -> str:
+ """掷骰子"""
+ result = 0
+ proc = ''
+ proc_list = []
+ p = par.split('+')
+
+ # 计算每个单独的roll
+ for i in p:
+ args = re.findall(r"(\d{0,10})(?:(d)(\d{1,10}))", i)
+ args = list(args[0])
+
+ if not args[0]:
+ args[0] = 1
+
+ if int(args[0]) >= 5000 or int(args[2]) >= 5000:
+ return '阿..好大...'
+
+ for a in range(1, int(args[0]) + 1):
+ rd = random.randint(1, int(args[2]))
+ result = result + rd
+
+ if len(proc_list) <= 10:
+ proc_list.append(rd)
+
+ if len(proc_list) <= 10:
+ proc += "+".join(map(str, proc_list))
+
+ elif len(proc_list) >= 10:
+ proc += '太长了不展示了就酱'
+
+ else:
+ proc += str(result)
+
+ result = f"{par}=({proc})={result}"
+
+ return str(result) \ No newline at end of file
diff --git a/ATRI/plugins/plugin_utils/generate.py b/ATRI/plugins/plugin_utils/generate.py
deleted file mode 100644
index 4749bab..0000000
--- a/ATRI/plugins/plugin_utils/generate.py
+++ /dev/null
@@ -1,47 +0,0 @@
-#!/usr/bin/env python3
-# -*- encoding: utf-8 -*-
-'''
-@File : generateID.py
-@Time : 2020/11/08 10:35:09
-@Author : Kyomotoi
-@Contact : kyomotoiowo@gmail.com
-@Github : https://github.com/Kyomotoi
-@License : Copyright © 2018-2020 Kyomotoi, All Rights Reserved.
-'''
-__author__ = 'kyomotoi'
-
-import os
-import json
-import random
-from pathlib import Path
-from zipfile import PyZipFile
-from typing import Tuple, Dict, List
-
-FILE = Path('.') / 'ATRI' / 'plguins' / 'plugin_utils' / 'main.bin'
-
-
-def infoID() -> Tuple[Dict[str, List[str]], Dict[str, str]]:
- with PyZipFile(os.path.abspath(FILE), "r") as zipFile:
- with zipFile.open("name.json", "r") as f:
- name = json.loads(f.read().decode())
- with zipFile.open("area.json", "r") as f:
- area = json.loads(f.read().decode())
- return name, area
-
-
-def numberID(area: int, sex: int, birth: int) -> str:
- def checkSum(fullCode: str) -> int or str:
- assert len(fullCode) == 17
- checkSum = sum([((1 << (17 - i)) % 11) * int(fullCode[i])
- for i in range(0, 17)])
- checkDigit = (12 - (checkSum % 11)) % 11
- if checkDigit < 10:
- return checkDigit
- else:
- return "X" # type: ignore
-
- orderCode = str(random.randint(10, 99))
- sexCode = str(random.randrange(sex, 10, step=2))
- fullCode = str(area) + str(birth) + str(orderCode) + str(sexCode)
- fullCode += str(checkSum(fullCode))
- return fullCode
diff --git a/ATRI/plugins/plugin_utils/genshin.py b/ATRI/plugins/plugin_utils/genshin.py
deleted file mode 100644
index 642773d..0000000
--- a/ATRI/plugins/plugin_utils/genshin.py
+++ /dev/null
@@ -1,118 +0,0 @@
-#!/usr/bin/env python3
-# -*- encoding: utf-8 -*-
-'''
-@File : genshin.py
-@Time : 2020/11/07 22:34:58
-@Author : Kyomotoi
-@Contact : kyomotoiowo@gmail.com
-@Github : https://github.com/Kyomotoi
-@License : Copyright © 2018-2020 Kyomotoi, All Rights Reserved.
-@Docs : Fork from https://github.com/Womsxd/YuanShen_User_Info
-'''
-__author__ = 'kyomotoi'
-
-import json
-import time
-import string
-import random
-import hashlib
-import requests
-
-
-def md5(text: str) -> str:
- """text 转 md5"""
- md5 = hashlib.md5()
- md5.update(text.encode())
- return md5.hexdigest()
-
-
-def DSGet() -> str:
- mhyVersion = "2.1.0"
- n = md5(mhyVersion)
- i = str(int(time.time()))
- r = ''.join(random.sample(string.ascii_lowercase + string.digits, 6))
- c = md5("salt=" + n + "&t=" + i + "&r=" + r)
- return i + "," + r + "," + c
-
-
-def GetInfo(uid: str) -> str:
- """请求API"""
- req = requests.get(
- url=
- f"https://api-takumi.mihoyo.com/game_record/genshin/api/index?server=cn_gf01&role_id={uid}",
- headers={
- 'Accept': 'application/json, text/plain, */*',
- 'DS': DSGet(),
- 'Origin': 'https://webstatic.mihoyo.com',
- 'x-rpc-app_version': '2.1.0',
- 'User-Agent':
- 'Mozilla/5.0 (Linux; Android 9; Unspecified Device) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/39.0.0.0 Mobile Safari/537.36 miHoYoBBS/2.2.0',
- 'x-rpc-client_type': '4',
- 'Referer':
- 'https://webstatic.mihoyo.com/app/community-game-records/index.html?v=6',
- 'Accept-Encoding': 'gzip, deflate',
- 'Accept-Language': 'zh-CN,en-US;q=0.8',
- 'X-Requested-With': 'com.mihoyo.hyperion'
- })
- return req.text
-
-
-def JsonAnalysis(JsonText) -> str:
- """解析数据"""
- data = json.loads(JsonText)
-
- Character_Info = "Roles:\n"
- Character_List = []
- Character_List = data["data"]["avatars"]
- for i in Character_List:
- if (i["element"] == "None"):
- Character_Type = "无属性"
- elif (i["element"] == "Anemo"):
- Character_Type = "风属性"
- elif (i["element"] == "Pyro"):
- Character_Type = "火属性"
- elif (i["element"] == "Geo"):
- Character_Type = "岩属性"
- elif (i["element"] == "Electro"):
- Character_Type = "雷属性"
- elif (i["element"] == "Cryo"):
- Character_Type = "冰属性"
- elif (i["element"] == "Hydro"):
- Character_Type = "水属性"
- else:
- Character_Type = "草属性"
-
- if (i["name"] == "旅行者"):
- if (i["image"].find("UI_AvatarIcon_PlayerGirl") != -1):
- TempText = f'* {i["name"]}:\n'
- TempText += f' - [萤——妹妹] {i["level"]}级 {Character_Type}\n'
-
- elif (i["image"].find("UI_AvatarIcon_PlayerBoy") != -1):
- TempText = f'* {i["name"]}:\n'
- TempText += f' - [空——哥哥] {i["level"]}级 {Character_Type}\n'
-
- else:
- TempText = f'* {i["name"]}:\n'
- TempText += f' - [性别判断失败] {i["level"]}级 {Character_Type}\n'
- else:
- TempText = f'* {i["name"]} {i["rarity"]}★角色:\n'
- TempText += f' - {i["level"]}级 好感度({i["fetter"]})级 {Character_Type}\n'
-
- Character_Info = Character_Info + TempText
-
- a1 = data["data"]["stats"]["spiral_abyss"]
-
- Account_Info = 'Account Info:\n'
- Account_Info += f'- 活跃天数:{data["data"]["stats"]["active_day_number"]} 天\n'
- Account_Info += f'- 达成成就:{data["data"]["stats"]["achievement_number"]} 个\n'
- Account_Info += f'- 获得角色:{data["data"]["stats"]["avatar_number"]}个\n'
- Account_Info += f'- 深渊螺旋:{"没打" if (data["data"]["stats"]["spiral_abyss"] == "-") else f"打到了{a1}"}\n'
- Account_Info += f'* 收集:\n'
- Account_Info += f' - 风神瞳{data["data"]["stats"]["anemoculus_number"]}个 岩神瞳{data["data"]["stats"]["geoculus_number"]}个\n'
- Account_Info += f'* 解锁:\n'
- Account_Info += f' - 传送点{data["data"]["stats"]["way_point_number"]}个 秘境{data["data"]["stats"]["domain_number"]}个\n'
- Account_Info += f'* 共开启宝箱:\n'
- Account_Info += f' - 普通:{data["data"]["stats"]["common_chest_number"]}个 精致:{data["data"]["stats"]["exquisite_chest_number"]}个\n'
- Account_Info += f' - 珍贵:{data["data"]["stats"]["luxurious_chest_number"]}个 华丽:{data["data"]["stats"]["precious_chest_number"]}个'
-
- return Character_Info + "\r\n" + Account_Info \ No newline at end of file
diff --git a/ATRI/plugins/plugin_utils/roll.py b/ATRI/plugins/plugin_utils/roll.py
deleted file mode 100644
index bf87aa3..0000000
--- a/ATRI/plugins/plugin_utils/roll.py
+++ /dev/null
@@ -1,59 +0,0 @@
-#!/usr/bin/env python3
-# -*- encoding: utf-8 -*-
-'''
-@File : roll.py
-@Time : 2020/11/07 15:56:02
-@Author : Kyomotoi
-@Contact : kyomotoiowo@gmail.com
-@Github : https://github.com/Kyomotoi
-@License : Copyright © 2018-2020 Kyomotoi, All Rights Reserved.
-'''
-__author__ = 'kyomotoi'
-
-import re
-from random import randint
-
-
-def roll_dice(par: str) -> str:
- """掷骰子"""
- result = 0
- proc = ''
- proc_list = []
- p = par.split('+')
-
- # 计算每个单独的roll
- for i in p:
- args = re.findall(r"(\d{0,10})(?:(d)(\d{1,10}))", i)
- args = list(args[0])
-
- if not args[0]:
- args[0] = 1
-
- if int(args[0]) >= 5000 or int(args[2]) >= 5000:
- return '阿..好大...'
-
- for a in range(1, int(args[0]) + 1):
- rd = randint(1, int(args[2]))
- result = result + rd
-
- if len(proc_list) <= 10:
- proc_list.append(rd)
-
- if len(proc_list) == 10:
- temp_list = []
- for i in proc_list:
- if len(temp_list) == 9:
- proc += str(i)
- else:
- proc += str(i) + '+'
- temp_list.append(i)
-
- elif len(proc_list) >= 10:
- proc += '太长了不展示了'
-
- else:
- proc += str(result)
-
- result = f"{par}=({proc})={result}"
-
- return str(result)