diff options
| -rw-r--r-- | ATRI/data/errorData/errorData.json | 1 | ||||
| -rw-r--r-- | ATRI/plugins/AIchangeFace.py | 34 | ||||
| -rw-r--r-- | ATRI/plugins/BlackList.py | 2 | ||||
| -rw-r--r-- | ATRI/plugins/Chat0.py | 18 | ||||
| -rw-r--r-- | ATRI/plugins/Chat1.py | 34 | ||||
| -rw-r--r-- | ATRI/plugins/Check.py | 28 | ||||
| -rw-r--r-- | ATRI/plugins/GetChatMSG.py | 30 | ||||
| -rw-r--r-- | ATRI/plugins/LearnRepo.py | 62 | ||||
| -rw-r--r-- | ATRI/plugins/LearnRepo/LearnRepo.json | 2 | ||||
| -rw-r--r-- | ATRI/plugins/SauceNAO.py | 75 | ||||
| -rw-r--r-- | ATRI/plugins/Scheduler.py | 6 | ||||
| -rw-r--r-- | ATRI/plugins/Setu.py | 235 | ||||
| -rw-r--r-- | ATRI/plugins/UploadSqlite.py | 102 | ||||
| -rw-r--r-- | ATRI/plugins/animeSearch.py | 45 | ||||
| -rw-r--r-- | ATRI/plugins/hitokoto.py | 15 | ||||
| -rw-r--r-- | ATRI/plugins/onMessage.py | 124 | ||||
| -rw-r--r-- | ATRI/plugins/other.py | 50 | ||||
| -rw-r--r-- | ATRI/plugins/pixiv.py | 89 | ||||
| -rw-r--r-- | ATRI/plugins/richBISS.py | 9 | ||||
| -rw-r--r-- | ATRI/plugins/switch.py | 138 | ||||
| -rw-r--r-- | ATRI/plugins/switch/switch.json | 1 | ||||
| -rw-r--r-- | ATRI/plugins/welcome.py | 43 | 
22 files changed, 739 insertions, 404 deletions
| diff --git a/ATRI/data/errorData/errorData.json b/ATRI/data/errorData/errorData.json new file mode 100644 index 0000000..9e26dfe --- /dev/null +++ b/ATRI/data/errorData/errorData.json @@ -0,0 +1 @@ +{}
\ No newline at end of file diff --git a/ATRI/plugins/AIchangeFace.py b/ATRI/plugins/AIchangeFace.py index 9431185..f442cb4 100644 --- a/ATRI/plugins/AIchangeFace.py +++ b/ATRI/plugins/AIchangeFace.py @@ -8,8 +8,9 @@ from random import choice  from pathlib import Path  from nonebot import on_command, CommandSession -import config # type: ignore -from ATRI.modules.funcControl import checkSwitch, checkNoob # type: ignore +import config +from ATRI.modules.error import errorBack +from ATRI.modules.funcControl import checkSwitch, checkNoob  bot = nonebot.get_bot() @@ -89,20 +90,23 @@ async def AIchFace(session: CommandSession):                  )              )          else: -            if checkSwitch(__plugin_name__): +            if checkSwitch(__plugin_name__, group):                  img1 = session.get('message1', prompt = '请发送需要换脸的图片')                  img2 = session.get('message2', prompt = '请发送素材图片') -                # 我承认了,我是取名废! -                a = img1.split(',') -                a = a[2].replace(']', '') -                a = a.replace('url=', '') -                imgres1 = requests.get(a) - -                b = img2.split(',') -                b = b[2].replace(']', '') -                b = b.replace('url=', '') -                imgres2 = requests.get(b) +                try: +                    # 我承认了,我是取名废! +                    a = img1.split(',') +                    a = a[2].replace(']', '') +                    a = a.replace('url=', '') +                    imgres1 = requests.get(a) + +                    b = img2.split(',') +                    b = b[2].replace(']', '') +                    b = b.replace('url=', '') +                    imgres2 = requests.get(b) +                except: +                    session.finish(errorBack('获取图片失败'))                  try:                      file1 = f'ATRI/data/temp/face/{user}' @@ -117,7 +121,7 @@ async def AIchFace(session: CommandSession):                      with open(file2 + '/img2.jpg', 'wb') as f:                          f.write(imgres2.content)                  except: -                    session.finish('请求数据貌似失败了...') +                    session.finish(errorBack('加载图片失败'))                  img1File = Path('.') / 'ATRI' / 'data' / 'temp' / 'face' / f'{user}' / 'img1.jpg'                  img2File = Path('.') / 'ATRI' / 'data' / 'temp' / 'face' / f'{user}' / 'img2.jpg' @@ -125,7 +129,7 @@ async def AIchFace(session: CommandSession):                  try:                      change_face(img1File, img2File, user, 1)                  except: -                    session.finish('emm...貌似失败了呢......') +                    session.finish(errorBack('换脸操作失败'))                  time.sleep(0.5)                  doneIMG = Path('.') / 'ATRI' / 'data' / 'temp' / 'face' / f'{user}' / 'img3.jpg' diff --git a/ATRI/plugins/BlackList.py b/ATRI/plugins/BlackList.py index 202e551..616d6fd 100644 --- a/ATRI/plugins/BlackList.py +++ b/ATRI/plugins/BlackList.py @@ -2,7 +2,7 @@ import json  from pathlib import Path  from nonebot import on_command, CommandSession -import config # type: ignore +import config  master = config.MASTER() diff --git a/ATRI/plugins/Chat0.py b/ATRI/plugins/Chat0.py index 36e5865..c720da0 100644 --- a/ATRI/plugins/Chat0.py +++ b/ATRI/plugins/Chat0.py @@ -10,9 +10,9 @@ from nonebot import on_command, scheduler  from nonebot import CommandSession  from apscheduler.triggers.date import DateTrigger -import config # type: ignore -from ATRI.modules.response import request_api # type: ignore -from ATRI.modules.funcControl import checkNoob # type: ignore +import config +from ATRI.modules.response import request_api +from ATRI.modules.funcControl import checkNoob  bot = nonebot.get_bot() @@ -619,7 +619,7 @@ async def _(session: CommandSession):                      pass                  else: -                    await session.send('是亚托莉......萝卜子可是对机器人的蔑称......\n这是第二次警告哦,接下来5分钟我不会再理你了!哼唧!') +                    await session.send('是亚托莉......萝卜子可是对机器人的蔑称......\n这是第二次警告哦,接下来10分钟我不会再理你了!哼唧!')                      bL[f"{user}"] = f"{user}"                      file = Path('.') / 'ATRI' / 'plugins' / 'noobList' / 'noobList.json'                      f = open(file, 'w') @@ -627,7 +627,7 @@ async def _(session: CommandSession):                      f.close()                      noobList0 = list(set(noobList0))                      print(noobList0) -                    delta = timedelta(minutes = 5) +                    delta = timedelta(minutes = 10)                      trigger = DateTrigger(                          run_date = datetime.now() + delta                      ) @@ -640,7 +640,7 @@ async def _(session: CommandSession):                      )  noobList1 = [] -@on_command('ntr', patterns = [r"[nNηиɴИ][tT][rR]|[牛🐂]头人"], only_to_me = False) +@on_command('ntr', patterns = [r"[nNηиɴИ][tT][rR]|[牛🐂🐮]头人"], only_to_me = False)  async def _(session: CommandSession):      global noobList1      user = session.event.user_id @@ -655,7 +655,7 @@ async def _(session: CommandSession):                      bL = json.load(f)              except:                  bL = {} -            pattern = r"[nNηиɴИ][tT][rR]|[牛🐂]头人" +            pattern = r"[nNηиɴИ][tT][rR]|[牛🐂🐮]头人"              if re.findall(pattern, msg):                  noobList1.append(user)                  if countX(noobList1, user) == 5: @@ -665,7 +665,7 @@ async def _(session: CommandSession):                          pass                      else: -                        await session.send(f'[CQ:at,qq={user}]哼!接下来10分钟别想让我理你!') +                        await session.send(f'[CQ:at,qq={user}]哼!接下来30分钟别想让我理你!')                          bL[f"{user}"] = f"{user}"                          file = Path('.') / 'ATRI' / 'plugins' / 'noobList' / 'noobList.json'                          f = open(file, 'w') @@ -673,7 +673,7 @@ async def _(session: CommandSession):                          f.close()                          noobList1 = list(set(noobList1))                          print(noobList1) -                        delta = timedelta(minutes = 10) +                        delta = timedelta(minutes = 30)                          trigger = DateTrigger(                              run_date = datetime.now() + delta                          ) diff --git a/ATRI/plugins/Chat1.py b/ATRI/plugins/Chat1.py index 47c8fdf..2c13df5 100644 --- a/ATRI/plugins/Chat1.py +++ b/ATRI/plugins/Chat1.py @@ -5,8 +5,9 @@ from random import choice, randint  from datetime import datetime  from nonebot import on_command, CommandSession -import config # type: ignore -from ATRI.modules.funcControl import checkNoob # type: ignore +import config +from ATRI.modules.error import errorBack +from ATRI.modules.funcControl import checkNoob  bot = nonebot.get_bot() @@ -99,26 +100,9 @@ async def _(session: CommandSession):      user = session.event.user_id      group = session.event.group_id      if checkNoob(user, group): -        voice = Path('.') / 'ATRI' / 'data' / 'voice' / 'ysdd.amr' -        voice = os.path.abspath(voice) -        await session.send(f'[CQ:record,file=file:///{voice}]') - -@bot.on_message('group') -async def _(context): -    user = context["user_id"] -    group = context["group_id"] -    if checkNoob(user, group): -        if 0 <= now_time() < 5.5: -            pass -        else: -            if randint(1,20) == 4: -                img = choice( -                    [ -                        '11.jpg', '12.jpg', '23.jpg' -                    ] -                ) -                img = os.path.abspath(Path('.') / 'ATRI' / 'data' / 'emoji' / 'senren' / f'{img}') -                await bot.send_msg(message = f'[CQ:image,file=file:///{img}]', auto_escape = False) # type: ignore -             -            else: -                pass
\ No newline at end of file +        try: +            voice = Path('.') / 'ATRI' / 'data' / 'voice' / 'ysdd.amr' +            voice = os.path.abspath(voice) +            await session.send(f'[CQ:record,file=file:///{voice}]') +        except: +            session.finish(errorBack('读取音频时出错'))
\ No newline at end of file diff --git a/ATRI/plugins/Check.py b/ATRI/plugins/Check.py index 9a39470..1dc64a0 100644 --- a/ATRI/plugins/Check.py +++ b/ATRI/plugins/Check.py @@ -197,4 +197,30 @@ async def _(session: CommandSession):  * disk: {disk}%  * BytesSENT: {inteSENT}  * BytesRECV: {inteRECV} -{status}""".strip())
\ No newline at end of file +{status}""".strip()) + + +@on_command('trackERROR', aliases = ['追踪'], only_to_me = False) +async def _(session: CommandSession): +    if session.event.user_id in master: +        msg = session.current_arg.strip() +        if not msg: +            msg = session.get('message', prompt = '请发送trackID') + +        try: +            with open(Path('.') / 'ATRI' / 'data' / 'errorData' / 'errorData.json', 'r') as f: +                data = json.load(f) +        except: +            data = {} + +        if str(msg) in data.keys(): +            err = data[f"{msg}"] +            msg0 = f'trackID: {msg}\n' +            msg0 += err +            await session.send(msg0) + +        else: +            session.finish('未发现该ID') +     +    else: +        await session.send('恁哪位呀~?')
\ No newline at end of file diff --git a/ATRI/plugins/GetChatMSG.py b/ATRI/plugins/GetChatMSG.py new file mode 100644 index 0000000..05d47b8 --- /dev/null +++ b/ATRI/plugins/GetChatMSG.py @@ -0,0 +1,30 @@ +import os +import json +import nonebot +from pathlib import Path + + +bot = nonebot.get_bot() + + +@bot.on_message('group') +async def _(ctx): +    group = ctx['group_id'] +    user = ctx['user_id'] +    msgID = ctx['message_id'] +    RAWmsg = ctx['message'] + +    try: +        with open(Path('.') / 'ATRI' / 'data' / 'groupData' / f'{group}' / 'msgData.json', 'r') as f: +            data = json.load(f) +    except: +        data = {} +     +    data[f'{msgID}'] = {"msg": f"{RAWmsg}", "user_id": f"{user}"} + +    try: +        with open(Path('.') / 'ATRI' / 'data' / 'groupData' / f'{group}' / 'msgData.json', 'w') as f: +            f.write(json.dumps(data)) +            f.close() +    except: +        os.mkdir(Path('.') / 'ATRI' / 'data' / 'groupData' / f'{group}')
\ No newline at end of file diff --git a/ATRI/plugins/LearnRepo.py b/ATRI/plugins/LearnRepo.py index 1d79836..01c04c2 100644 --- a/ATRI/plugins/LearnRepo.py +++ b/ATRI/plugins/LearnRepo.py @@ -1,13 +1,12 @@  import json -from random import randint  from datetime import datetime  from pathlib import Path  import nonebot  from nonebot import on_command  from nonebot import CommandSession -import config # type: ignore -from ATRI.modules.funcControl import checkNoob # type: ignore +import config +from ATRI.modules.error import errorBack  bot = nonebot.get_bot() @@ -41,46 +40,25 @@ async def _(session: CommandSession):                  await session.send('该词已存在~!')              else: -                data[f"{word}"] = [f"{repo}",prob] -                f = open(Path('.') / 'ATRI' / 'plugins' / 'LearnRepo' / 'LearnRepo.json', 'w') -                f.write(json.dumps(data)) -                f.close() -                session.finish(f"学習しました!\nWord:[{word}]\nRepo:[{repo}]\nProbability:[{'%.2f%%' % (round(1 / prob , 1) * 100)}]") -         +                try: +                    data[f"{word}"] = [f"{repo}",prob] +                    f = open(Path('.') / 'ATRI' / 'plugins' / 'LearnRepo' / 'LearnRepo.json', 'w') +                    f.write(json.dumps(data)) +                    f.close() +                    session.finish(f"学習しました!\nWord:[{word}]\nRepo:[{repo}]\nProbability:[{'%.2f%%' % (round(1 / prob , 1) * 100)}]") +                except: +                    session.finish(errorBack('写入失败')) +          elif w_tpye == '删除词汇':              if word in data.keys(): -                data.pop(f"{word}") -                f = open(Path('.') / 'ATRI' / 'plugins' / 'LearnRepo' / 'LearnRepo.json', 'w') -                f.write(json.dumps(data)) -                f.close() -                await session.send(f'已成功从ATRI记忆模块中抹除[{word}]') +                try: +                    data.pop(f"{word}") +                    f = open(Path('.') / 'ATRI' / 'plugins' / 'LearnRepo' / 'LearnRepo.json', 'w') +                    f.write(json.dumps(data)) +                    f.close() +                    await session.send(f'已成功从ATRI记忆模块中抹除[{word}]') +                except: +                    session.finish(errorBack('移除失败'))              else: -                 session.finish(f'ATRI貌似没法从记忆中找到关键词[{word}]呢...') - - -@bot.on_message("group") -async def repo(context): -    user = context["user_id"] -    group = context["group_id"] -    word = context["message"] -    if 0 <= now_time() < 5.5: -        pass -    else: -        if checkNoob(user, group): -            try: -                with open(Path('.') / 'ATRI' / 'plugins' / 'LearnRepo' / 'LearnRepo.json', 'r') as f: -                    data = json.load(f) -            except: -                data = {} - -            if str(word) in data.keys(): -                lt = data[f"{word}"] -                msg = lt[0] -                prob = int(lt[1]) -                res = randint(1,prob) -                if res == 1: -                    await bot.send_msg( -                        group_id = group, -                        message = msg -                    ) # type: ignore
\ No newline at end of file +                 session.finish(f'ATRI貌似没法从记忆中找到关键词[{word}]呢...')
\ No newline at end of file diff --git a/ATRI/plugins/LearnRepo/LearnRepo.json b/ATRI/plugins/LearnRepo/LearnRepo.json index 18a45e8..fb478b5 100644 --- a/ATRI/plugins/LearnRepo/LearnRepo.json +++ b/ATRI/plugins/LearnRepo/LearnRepo.json @@ -1 +1 @@ -{"test": ["TesT is SuccEss!", 1], "\ud83d\udd28": ["\ud83d\udd28", 2]}
\ No newline at end of file +{"test": ["TesT is SuccEss!", 1]}
\ No newline at end of file diff --git a/ATRI/plugins/SauceNAO.py b/ATRI/plugins/SauceNAO.py index cb32345..567b490 100644 --- a/ATRI/plugins/SauceNAO.py +++ b/ATRI/plugins/SauceNAO.py @@ -4,19 +4,15 @@ import re  from datetime import datetime
  from random import choice
  from nonebot import on_command, CommandSession
 -from aiohttp import ClientSession
 -import config # type: ignore
 -from ATRI.modules.funcControl import checkSwitch, checkNoob # type: ignore
 +import config
 +from ATRI.modules.error import errorBack
 +from ATRI.modules.funcControl import checkSwitch, checkNoob
 +
  API_KEY = config.SAUCENAO_KEY()
  __plugin_name__ = "saucenao_search"
 -async def get_bytes(url, headers = None):
 -    async with ClientSession() as asyncSession:
 -        async with asyncSession.get(url, headers = headers) as response:
 -            a = await response.read()
 -    return a
  def now_time():
      now_ = datetime.now()
 @@ -45,7 +41,7 @@ class SauceNAO:          res = requests.get(url=self.api,params=self.params)
          return res.content
 -@on_command('SauceNAO', aliases = ['以图识图'], only_to_me = False)
 +@on_command('SauceNAO', aliases = ['以图识图', '以图搜图'], only_to_me = False)
  async def SaucenaoSearch(session: CommandSession):
      user = session.event.user_id
      group = session.event.group_id
 @@ -65,45 +61,48 @@ async def SaucenaoSearch(session: CommandSession):                  )
              )
          else:
 -            if checkSwitch(__plugin_name__):
 +            if checkSwitch(__plugin_name__, group):
                  if not msg:
                      msg = session.get('message', prompt="请发送一张图片")
 -                await session.send("开始以图识图\n(如搜索时间过长或无反应则为图片格式有问题)")
 +                await session.send("开始以图识图")
 -                p = '\\[CQ\\:image\\,file\\=.*?\\,url\\=(.*?)\\]'
 +                try:
 +                    p = '\\[CQ\\:image\\,file\\=.*?\\,url\\=(.*?)\\]'
 -                img = re.findall(p, msg)
 +                    img = re.findall(p, msg)
 +
 +                    task = SauceNAO(api_key=API_KEY)
 +                    data = task.search(url=img)
 +                    msg0 = ''
 +
 +                    try:
 +                        data = json.loads(data)['results'][0]
 +                        title = data['data']['title']
 +                        pixiv_id = data['data']['pixiv_id']
 +                        member_name = data['data']['member_name']
 +                        member_id = data['data']['member_id']
 +                        similarity = data['header']['similarity']
 +                        mini_url = data['header']['thumbnail']
 +                        msg0 = f'[CQ:at,qq={user}]'
 +                        msg0 += f'SauceNAO结果:'
 +                        msg0 += f'[CQ:image,file={mini_url}]\n'
 +                        msg0 += f'相似度:{similarity}%\n'
 +                        msg0 += f'标题:{title}\n'
 +                        msg0 += f'插画ID:{pixiv_id}\n'
 +                        msg0 += f'画师:{member_name}\n'
 +                        msg0 += f'画师ID:{member_id}\n'
 +                        msg0 += f'直链:https://pixiv.cat/{pixiv_id}.jpg'
 +                    except:
 +                        msg = '数据处理失败'
 -                task = SauceNAO(api_key=API_KEY)
 -                data = task.search(url=img)
 -                msg0 = ''
 -                try:
 -                    data = json.loads(data)['results'][0]
 -                    url = data['data']['ext_urls'][0]
 -                    title = data['data']['title']
 -                    pixiv_id = data['data']['pixiv_id']
 -                    member_name = data['data']['member_name']
 -                    member_id = data['data']['member_id']
 -                    similarity = data['header']['similarity']
 -                    mini_url = data['header']['thumbnail']
 -                    msg0 = f'SauceNAO结果:'
 -                    msg0 += f'[CQ:image,file={mini_url}]\n'
 -                    msg0 += f'相似度:{similarity}%\n'
 -                    msg0 += f'标题:{title}\n'
 -                    msg0 += f'插画ID:{pixiv_id}\n'
 -                    msg0 += f'画师:{member_name}\n'
 -                    msg0 += f'画师ID:{member_id}\n'
 -                    msg0 += f'直链:https://pixiv.cat/{pixiv_id}.jpg'
 -                except:
 -                    print('网络请求失败...')
 -                if msg0:
                      if float(similarity) > 70:
                          await session.send(msg0)
                      else:
                          await session.send("找不到相似的图呢...")
 -                else:
 -                        await session.send("搜索似乎失败了呢...")
 +
 +                except Exception:
 +                    session.finish(errorBack(msg))
              else:
                  session.finish('该功能已关闭...')
 diff --git a/ATRI/plugins/Scheduler.py b/ATRI/plugins/Scheduler.py index 659c352..d389ca8 100644 --- a/ATRI/plugins/Scheduler.py +++ b/ATRI/plugins/Scheduler.py @@ -6,7 +6,7 @@ from datetime import datetime  from random import randint, choice  from pathlib import Path -import config # type: ignore +import config  bot = nonebot.get_bot() @@ -27,7 +27,7 @@ async def _():          group_list = await bot.get_group_list() #type: ignore          groups = [group['group_id'] for group in group_list]          g_list = len(group_list) -        msg = await choice( +        msg = choice(              [                  '啊......早上好...(哈欠)',                  '唔......吧唧...早上...哈啊啊~~~\n早上好......', @@ -69,7 +69,7 @@ async def _():          group_list = await bot.get_group_list() #type: ignore          groups = [group['group_id'] for group in group_list]          g_list = len(group_list) -        msg = await choice( +        msg = choice(              [                  '忙累了一天,快休息吧',                  '辛苦了一天,准备睡觉吧', diff --git a/ATRI/plugins/Setu.py b/ATRI/plugins/Setu.py index 2aa5c2b..289d9f0 100644 --- a/ATRI/plugins/Setu.py +++ b/ATRI/plugins/Setu.py @@ -12,10 +12,11 @@ from random import choice  import nonebot  from nonebot import on_command, CommandSession -import config # type: ignore -from ATRI.modules.b64 import b64_str_img_url # type: ignore -from ATRI.modules.response import request_api_params # type: ignore -from ATRI.modules.funcControl import checkSwitch, checkNoob # type: ignore +import config +from ATRI.modules.error import errorBack +from ATRI.modules.b64 import b64_str_img_url +from ATRI.modules.response import request_api_params +from ATRI.modules.funcControl import checkSwitch, checkNoob  bot = nonebot.get_bot() @@ -64,19 +65,19 @@ async def setu(session: CommandSession):                  )              )          else: -            if checkSwitch(__plugin_name__): +            if checkSwitch(__plugin_name__, group):                  res = randint(1,10) -                if 1 <= res < 9: +                if 1 <= res <= 9:                      res = randint(1,4) -                    if 1 <= res < 3: +                    if 1 <= res <= 3:                          if setu_type == 1: -                            res = randint(1,4) +                            res = randint(1,5)                              await session.send('别急!正在找图!')                              con = sqlite3.connect(Path('.') / 'ATRI' / 'data' / 'sqlite' / 'setu' / 'nearR18.db')                              cur = con.cursor()                              msg = cur.execute('SELECT * FROM nearR18 ORDER BY RANDOM() limit 1;') -                            if 1 <= res < 3: +                            if 1 <= res <= 4:                                  for i in msg:                                      pid = i[0]                                      title = i[1] @@ -90,7 +91,7 @@ async def setu(session: CommandSession):                                          time = round(end - start, 3)                                          )                                      ) -                            elif res == 4: +                            elif res == 5:                                  for i in msg:                                      pid = i[0]                                      title = i[1] @@ -103,7 +104,7 @@ async def setu(session: CommandSession):                                      )                          elif setu_type == 2: -                            res = randint(1,4) +                            res = randint(1,5)                              await session.send('别急!正在找图!')                              start = time.perf_counter()                              values = { @@ -118,9 +119,9 @@ async def setu(session: CommandSession):                                  pid = dc["data"][0]["pid"]                                  setu = dc["data"][0]["url"] #b64.b64_str_img_url(dc["data"][0]["url"])                              except: -                                await session.send('失败了失败了失败了失...') -                                return -                            if 1 <= res < 3: +                                session.finish(errorBack('请求数据失败')) + +                            if 1 <= res <= 4:                                  end = time.perf_counter()                                  await session.send(                                      SETU_REPLY.format( @@ -130,7 +131,7 @@ async def setu(session: CommandSession):                                      time = round(end - start, 3)                                      )                                  ) -                            elif res == 4: +                            elif res == 5:                                  end = time.perf_counter()                                  await session.send('我找到涩图了!但我发给主人了\nο(=•ω<=)ρ⌒☆')                                  await bot.send_private_msg( # type: ignore @@ -175,7 +176,7 @@ async def _(session: CommandSession):              setu_type = 2          else: -            pass +            session.finish('请检查输入~~~(')          await session.send('okay~~~~') @@ -186,7 +187,7 @@ async def _(context):      user = context["user_id"]      group = context["group_id"]      if checkNoob(user, group): -            if checkSwitch(__plugin_name1__): +            if checkSwitch(__plugin_name1__, group):                  try:                      img = str(context["message"])                      pattern = re.compile(r"url=(.*)]") @@ -197,121 +198,125 @@ async def _(context):                  except:                      return -                img = b64_str_img_url(img) -                if img: -                    try: -                        host = f'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id={API_KEY}&client_secret={SECRECT_KEY}' -                        headers = { -                            'Content-Type': 'application/json;charset=UTF-8' -                        } -                        res = json.loads(request_api_params(host, headers)) -                        access_token=res['access_token'] -                        url = f'https://aip.baidubce.com/rest/2.0/ocr/v1/general?access_token={access_token}' -                        headers = {'Content-Type': 'application/x-www-form-urlencoded'} -                        data = urlencode({'image': img}) -                        res = requests.post(url=url, headers=headers, data=data) -                    except: -                        return -                     -                    try: -                        words = json.loads(res.content)['words_result'][0]['words'] -                        print(words) -                    except: -                        return +                try: +                    img = b64_str_img_url(img) +                except: +                    return -                    if re.findall(r"[涩色]图|炼铜", words): -                        if checkSwitch(__plugin_name__): -                            res = randint(1,10) -                            if 1 <= res < 9: -                                res = randint(1,4) -                                if 1 <= res < 3: -                                    if setu_type == 1: -                                        res = randint(1,4) -                                        con = sqlite3.connect(Path('.') / 'ATRI' / 'data' / 'sqlite' / 'setu' / 'nearR18.db') -                                        cur = con.cursor() -                                        msg = cur.execute('SELECT * FROM nearR18 ORDER BY RANDOM() limit 1;') -                                     -                                        if 1 <= res < 3: -                                            for i in msg: -                                                pid = i[0] -                                                title = i[1] -                                                img = i[7] -                                                end = time.perf_counter() -                                                msg = SETU_REPLY.format( -                                                    title = title, -                                                    pid = pid, -                                                    setu = img, -                                                    time = round(end - start, 3) -                                                ) -                                                await bot.send_group_msg(group_id = group, message = msg) # type: ignore -                                        elif res == 4: -                                            for i in msg: -                                                pid = i[0] -                                                title = i[1] -                                                img = i[7] -                                                end = time.perf_counter() -                                                await bot.send_group_msg(group_id = group, message = '我找到涩图了!但我发给主人了\nο(=•ω<=)ρ⌒☆') # type: ignore -                                                await bot.send_private_msg( # type: ignore -                                                    user_id = master, -                                                    message = f"主人,从群{group}来的涩图!热乎着!\nTitle: {title}\nPid: {pid}\n{img}\nComplete time: {round(end - start, 3)}" -                                                ) -                                     -                                    elif setu_type == 2: -                                        res = randint(1,4) -                                        await bot.send_group_msg(group_id = group, message = '别急!正在找图!') # type: ignore -                                        start = time.perf_counter() -                                        values = { -                                            "apikey": apikey_LOLI, -                                            "r18": "0", -                                            "num": "1" -                                        } +                try: +                    host = f'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id={API_KEY}&client_secret={SECRECT_KEY}' +                    headers = { +                        'Content-Type': 'application/json;charset=UTF-8' +                    } +                    res = json.loads(request_api_params(host, headers)) +                    access_token=res['access_token'] +                    url = f'https://aip.baidubce.com/rest/2.0/ocr/v1/general?access_token={access_token}' +                    headers = {'Content-Type': 'application/x-www-form-urlencoded'} +                    data = urlencode({'image': img}) +                    res = requests.post(url=url, headers=headers, data=data) +                except: +                    return +                 +                try: +                    words = json.loads(res.content)['words_result'][0]['words'] +                    print(words) +                except: +                    return -                                        try: -                                            dc = json.loads(request_api_params(URL, values)) -                                            title = dc["data"][0]["title"] -                                            pid = dc["data"][0]["pid"] -                                            setu = dc["data"][0]["url"] #b64.b64_str_img_url(dc["data"][0]["url"]) -                                        except: -                                            await bot.send_group_msg(group_id = group, message = '失败了失败了失...') # type: ignore -                                            return -                                        if 1 <= res < 3: +                if re.findall(r"[涩色]图|炼铜", words): +                    if checkSwitch(__plugin_name__, group): +                        res = randint(1,10) +                        if 1 <= res <= 9: +                            res = randint(1,5) +                            if 1 <= res <= 4: +                                if setu_type == 1: +                                    res = randint(1,5) +                                    await bot.send_group_msg(group_id = group, message = '别急!正在找图!') # type: ignore +                                    con = sqlite3.connect(Path('.') / 'ATRI' / 'data' / 'sqlite' / 'setu' / 'nearR18.db') +                                    cur = con.cursor() +                                    msg = cur.execute('SELECT * FROM nearR18 ORDER BY RANDOM() limit 1;') +                                 +                                    if 1 <= res <= 4: +                                        for i in msg: +                                            pid = i[0] +                                            title = i[1] +                                            img = i[7]                                              end = time.perf_counter()                                              msg = SETU_REPLY.format( -                                                    title = title, -                                                    pid = pid, -                                                    setu = img, -                                                    time = round(end - start, 3) -                                                ) +                                                title = title, +                                                pid = pid, +                                                setu = img, +                                                time = round(end - start, 3) +                                            )                                              await bot.send_group_msg(group_id = group, message = msg) # type: ignore -                                        elif res == 4: +                                    elif res == 5: +                                        for i in msg: +                                            pid = i[0] +                                            title = i[1] +                                            img = i[7]                                              end = time.perf_counter()                                              await bot.send_group_msg(group_id = group, message = '我找到涩图了!但我发给主人了\nο(=•ω<=)ρ⌒☆') # type: ignore                                              await bot.send_private_msg( # type: ignore                                                  user_id = master, -                                                message = f"主人,从群{group}来的涩图!热乎着!\nTitle: {title}\nPid: {pid}\n{setu}\nComplete time: {round(end - start, 3)}" +                                                message = f"主人,从群{group}来的涩图!热乎着!\nTitle: {title}\nPid: {pid}\n{img}\nComplete time: {round(end - start, 3)}"                                              ) -                                elif res == 4: -                                    img = choice( -                                        [ -                                            'SP.jpg', 'SP1.jpg', 'SP2.jpg' -                                        ] -                                    ) -                                    img = Path('.') / 'ATRI' / 'data' / 'emoji' / f'{img}' -                                    img = os.path.abspath(img) -                                    await bot.send_group_msg(group_id = group, message = f'[CQ:image,file=file:///{img}]') # type: ignore -                             -                            elif res == 10: +                                 +                                elif setu_type == 2: +                                    res = randint(1,5) +                                    await bot.send_group_msg(group_id = group, message = '别急!正在找图!') # type: ignore +                                    start = time.perf_counter() +                                    values = { +                                        "apikey": apikey_LOLI, +                                        "r18": "0", +                                        "num": "1" +                                    } + +                                    try: +                                        dc = json.loads(request_api_params(URL, values)) +                                        title = dc["data"][0]["title"] +                                        pid = dc["data"][0]["pid"] +                                        setu = dc["data"][0]["url"] #b64.b64_str_img_url(dc["data"][0]["url"]) +                                    except: +                                        await bot.send_group_msg(group_id = group, message = errorBack('数据请求失败')) # type: ignore +                                        return +                                    if 1 <= res <= 4: +                                        end = time.perf_counter() +                                        msg = SETU_REPLY.format( +                                                title = title, +                                                pid = pid, +                                                setu = img, +                                                time = round(end - start, 3) +                                            ) +                                        await bot.send_group_msg(group_id = group, message = msg) # type: ignore +                                    elif res == 5: +                                        end = time.perf_counter() +                                        await bot.send_group_msg(group_id = group, message = '我找到涩图了!但我发给主人了\nο(=•ω<=)ρ⌒☆') # type: ignore +                                        await bot.send_private_msg( # type: ignore +                                            user_id = master, +                                            message = f"主人,从群{group}来的涩图!热乎着!\nTitle: {title}\nPid: {pid}\n{setu}\nComplete time: {round(end - start, 3)}" +                                        ) +                            elif res == 5:                                  img = choice(                                      [ -                                        'GDZ.png', 'SHZY1.jpg', 'SHZY2.jpg', 'SHZY3.jpg', 'SHZY4.jpg', 'SHZY5.jpg', 'SHZY6.jpg' +                                        'SP.jpg', 'SP1.jpg', 'SP2.jpg'                                      ]                                  ) -                                img = Path('.') / 'ATRI' / 'data' / 'img' / 'niceIMG' / f'{img}' +                                img = Path('.') / 'ATRI' / 'data' / 'emoji' / f'{img}'                                  img = os.path.abspath(img)                                  await bot.send_group_msg(group_id = group, message = f'[CQ:image,file=file:///{img}]') # type: ignore +                         +                        elif res == 10: +                            img = choice( +                                [ +                                    'GDZ.png', 'SHZY1.jpg', 'SHZY2.jpg', 'SHZY3.jpg', 'SHZY4.jpg', 'SHZY5.jpg', 'SHZY6.jpg' +                                ] +                            ) +                            img = Path('.') / 'ATRI' / 'data' / 'img' / 'niceIMG' / f'{img}' +                            img = os.path.abspath(img) +                            await bot.send_group_msg(group_id = group, message = f'[CQ:image,file=file:///{img}]') # type: ignore -                        else: -                            pass +                    else: +                        pass              else:                  pass
\ No newline at end of file diff --git a/ATRI/plugins/UploadSqlite.py b/ATRI/plugins/UploadSqlite.py index ffd2ecc..1e511ba 100644 --- a/ATRI/plugins/UploadSqlite.py +++ b/ATRI/plugins/UploadSqlite.py @@ -8,11 +8,12 @@ import nonebot  from pathlib import Path  from nonebot import on_command, CommandSession -from ATRI.modules import response # type: ignore +import config +from ATRI.modules.response import request_api  bot = nonebot.get_bot() -master = bot.config.SUPERUSERS # type: ignore +master = config.MASTER()  url = f'https://api.imjad.cn/pixiv/v1/?type=illust&id=' @@ -44,7 +45,7 @@ async def _(session: CommandSession):          URL = url + pid -        dc = json.loads(response.request_api(URL)) +        dc = json.loads(request_api(URL))          if not dc:              session.finish('ATRI在尝试解析数据时出问题...等会再试试吧...')          title = dc["response"][0]["title"] @@ -157,39 +158,74 @@ async def _(session: CommandSession):          await session.send(f'数据上传完成!\n耗时: {round(end - start, 3)}s') -# @on_command('del_setu', aliases = ['删除涩图'], only_to_me = False) -# async def _(session: CommandSession): -#     user = session.event.user_id -#     if user in master or user in sepi: -#         start = time.perf_counter() -#         msg = session.event.raw_message.split(' ', 2) -#         print(msg) -#         i_tpye = msg[1] -#         pid = msg[2] - -#         if i_tpye == '正常': -#             if os.path.exists(Path('.') / 'ATRI' / 'data' / 'sqlite' / 'setu' / 'normal.db'): -#                 print('数据文件存在!') -#             else: -#                 session.finish('ERROR: 恁都没库删锤子') -#             con = sqlite3.connect(Path('.') / 'ATRI' / 'data' / 'sqlite' / 'setu' / 'normal.db') -#             cur = con.cursor() -#             cur.execute(f'DELETE FROM COMPANY WHERE ID = {pid}') -#             con.commit() -#             con.close() +@on_command('del_setu', aliases = ['删除涩图'], only_to_me = False) +async def _(session: CommandSession): +    user = session.event.user_id +    if user in master or user in sepi: +        start = time.perf_counter() +        msg = session.event.raw_message.split(' ', 2) +        i_tpye = msg[1] +        pid = msg[2] + +        if i_tpye == '正常': +            if os.path.exists(Path('.') / 'ATRI' / 'data' / 'sqlite' / 'setu' / 'normal.db'): +                print('数据文件存在!') +            else: +                session.finish('ERROR: 恁都没库删锤子') +            con = sqlite3.connect(Path('.') / 'ATRI' / 'data' / 'sqlite' / 'setu' / 'normal.db') +            cur = con.cursor() +            cur.execute(f'DELETE FROM COMPANY WHERE ID = {pid}') +            con.commit() +            con.close() -#         elif i_tpye == '擦边球': -#             if os.path.exists(Path('.') / 'ATRI' / 'data' / 'sqlite' / 'setu' / 'normal.db'): -#                 print('数据文件存在!') -#             else: -#                 session.finish('ERROR: 恁都没库删锤子') +        elif i_tpye == '擦边球': +            if os.path.exists(Path('.') / 'ATRI' / 'data' / 'sqlite' / 'setu' / 'nearR18.db'): +                print('数据文件存在!') +            else: +                session.finish('ERROR: 恁都没库删锤子') +            con = sqlite3.connect(Path('.') / 'ATRI' / 'data' / 'sqlite' / 'setu' / 'nearR18.db') +            cur = con.cursor() +            cur.execute(f'DELETE FROM COMPANY WHERE ID = {pid}') +            con.commit() +            con.close() -#         elif i_tpye == 'r18': -#             if os.path.exists(Path('.') / 'ATRI' / 'data' / 'sqlite' / 'setu' / 'normal.db'): -#                 print('数据文件存在!') -#             else: -#                 session.finish('ERROR: 恁都没库删锤子') +        elif i_tpye == 'r18': +            if os.path.exists(Path('.') / 'ATRI' / 'data' / 'sqlite' / 'setu' / 'r18.db'): +                print('数据文件存在!') +            else: +                session.finish('ERROR: 恁都没库删锤子') +            con = sqlite3.connect(Path('.') / 'ATRI' / 'data' / 'sqlite' / 'setu' / 'r18.db') +            cur = con.cursor() +            cur.execute(f'DELETE FROM COMPANY WHERE ID = {pid}') +            con.commit() +            con.close() +         +        end = time.perf_counter() +         +        await session.send(f'数据删除完成!\n耗时: {round(end - start, 3)}s') + +@on_command('del_cloudmusic', aliases = ['删除网易云'], only_to_me = False) +async def _(session: CommandSession): +    user = session.event.user_id +    if user in master or user in cloudmusic: +        start = time.perf_counter() +        msg = session.event.raw_message.split(' ', 1) +        msg = msg[1] + +        if os.path.exists('ATRI/data/sqlite/cloudmusic/cloudmusic.db'): +            print('数据文件存在!') +        else: +            session.finish('ERROR: 恁都没库删锤子') +        con = sqlite3.connect(Path('.') / 'ATRI' / 'data' / 'sqlite' / 'cloudmusic' / 'cloudmusic.db') +        cur = con.cursor() +        cur.execute('INSERT INTO cloudmusic(msg) VALUES (?)', msg) +        con.commit() +        con.close() + +        end = time.perf_counter() + +        await session.send(f'数据删除完成!\n耗时: {round(end - start, 3)}s')  @on_command('add_check_sepi', aliases=['添加涩批', '移除涩批'], only_to_me = False) diff --git a/ATRI/plugins/animeSearch.py b/ATRI/plugins/animeSearch.py index a237b06..77e5470 100644 --- a/ATRI/plugins/animeSearch.py +++ b/ATRI/plugins/animeSearch.py @@ -5,7 +5,8 @@ from random import choice  from aiohttp import ClientSession  from nonebot import on_command, CommandSession -from ATRI.modules.funcControl import checkSwitch, checkNoob # type: ignore +from ATRI.modules.error import errorBack +from ATRI.modules.funcControl import checkSwitch, checkNoob  __plugin_name__ = "anime_search" @@ -78,7 +79,7 @@ async def AnimeSearch(session: CommandSession):                  )              )          else: -            if checkSwitch(__plugin_name__): +            if checkSwitch(__plugin_name__, group):                  if not msg:                      msg = session.get('message', prompt = "请发送一张图片") @@ -91,11 +92,14 @@ async def AnimeSearch(session: CommandSession):                  if img:                      URL = f'https://trace.moe/api/search?url={img[0]}' -                    req = await get_bytes(URL) +                    try: +                        req = await get_bytes(URL) +                    except: +                        session.finish(errorBack('请求数据失败')) -                    if req: -                        data = json.loads(req.decode()) +                    data = json.loads(req.decode()) +                    try:                          d = {}                          for i in range(len(data['docs'])): @@ -113,27 +117,26 @@ async def AnimeSearch(session: CommandSession):                                      n = data['docs'][i]['episode']                                  d[toSimpleString(data['docs'][i]['title_chinese'])] = [data['docs'][i]['similarity'],f'第{n}集',f'{int(m)}分{int(s)}秒处'] +                    except: +                        session.finish(errorBack('处理数据失败')) -                        result = sorted( -                            d.items(), -                            key = lambda x:x[1], -                            reverse = True -                        ) +                    result = sorted( +                        d.items(), +                        key = lambda x:x[1], +                        reverse = True +                    ) -                        t = 0 +                    t = 0 -                        msg0 = f'[CQ:at,qq={user}]\n根据所提供的图片按照相似度找到{len(d)}个结果:' +                    msg0 = f'[CQ:at,qq={user}]\n根据所提供的图片按照相似度找到{len(d)}个结果:' -                        for i in result: -                            t +=1 -                            lk = ('%.2f%%' % (i[1][0] * 100)) -                            msg = (f'\n——————————\n({t})\n相似度:{lk}\n动漫名:《{i[0]}》\n时间点:{i[1][1]} {i[1][2]}') -                            msg0 += msg -                         -                        await session.send(msg0) +                    for i in result: +                        t +=1 +                        lk = ('%.2f%%' % (i[1][0] * 100)) +                        msg = (f'\n——————————\n({t})\n相似度:{lk}\n动漫名:《{i[0]}》\n时间点:{i[1][1]} {i[1][2]}') +                        msg0 += msg -                    else: -                        await session.send("搜索似乎失败了呢...") +                    await session.send(msg0)              else:                  session.finish('该功能已关闭...') diff --git a/ATRI/plugins/hitokoto.py b/ATRI/plugins/hitokoto.py index 2da9eef..6f81f2f 100644 --- a/ATRI/plugins/hitokoto.py +++ b/ATRI/plugins/hitokoto.py @@ -4,8 +4,9 @@ from random import choice  from nonebot import on_command, on_natural_language, CommandSession  from nonebot import NLPSession, NLPResult -from ATRI.modules import response # type: ignore -from ATRI.modules.funcControl import checkNoob # type: ignore +from ATRI.modules.response import request_api +from ATRI.modules.error import errorBack +from ATRI.modules.funcControl import checkNoob  def now_time(): @@ -37,12 +38,12 @@ async def hitokoto(session: CommandSession):                  )              )          else: -            rep = response.request_api(url) +            try: +                rep = request_api(url) +            except: +                session.finish(errorBack('请求错误')) -            if not rep: -                session.finish('获取失败') -             -            dc = json.loads(response.request_api(url)) +            dc = json.loads(rep)              await session.send(dc["hitokoto"]) diff --git a/ATRI/plugins/onMessage.py b/ATRI/plugins/onMessage.py new file mode 100644 index 0000000..fc888e4 --- /dev/null +++ b/ATRI/plugins/onMessage.py @@ -0,0 +1,124 @@ +import re +import os +import json +import nonebot +from pathlib import Path +from random import randint, choice + +from ATRI.modules.error import errorBack +from ATRI.modules.funcControl import checkSwitch, checkNoob +from ATRI.plugins.SauceNAO import API_KEY, now_time, SauceNAO + + +bot = nonebot.get_bot() + + +@bot.on_message("group") +async def _(context): +    group = context["group_id"] +    user = context["user_id"] +    if 0 <= now_time() < 5.5: +        pass +    else: +        if checkNoob(user, group): +            msg = str(context["message"]) +            print(msg) +            if "搜图" in msg or "识图" in msg: +                if checkSwitch("saucenao_search", group): +                    try: +                        pattern = r"CQ:reply,id=(.*?)]" +                        info = re.findall(pattern, msg) +                        msgID = info[0] +                        print(msgID) +                    except: +                        print('ERROR-onMessage') +                        return + +                    try: +                        with open(Path('.') / 'ATRI' / 'data' / 'groupData' / f'{group}' / 'msgData.json', 'r') as f: +                            data = json.load(f) +                    except: +                        data = {} +                     +                    if msgID in data.keys(): +                        msgR = data[f"{msgID}"]["msg"] + +                        pattern = r"url=(.*?)]" +                        info = re.findall(pattern, msgR) +                        picURL = info[0] + +                        try: +                            task = SauceNAO(api_key=API_KEY) +                            data = task.search(url=picURL) +                            msg0 = '' +                        except: +                            await bot.send_msg(group_id = group, message = errorBack('请求数据失败')) # type: ignore +                            return + +                        print(data) +                        try: +                            data = json.loads(data)['results'][0] +                            title = data['data']['title'] +                            pixiv_id = data['data']['pixiv_id'] +                            member_name = data['data']['member_name'] +                            member_id = data['data']['member_id'] +                            similarity = data['header']['similarity'] +                            mini_url = data['header']['thumbnail'] +                            msg0 = f'[CQ:at,qq={user}]' +                            msg0 += f'SauceNAO结果:' +                            msg0 += f'[CQ:image,file={mini_url}]\n' +                            msg0 += f'相似度:{similarity}%\n' +                            msg0 += f'标题:{title}\n' +                            msg0 += f'插画ID:{pixiv_id}\n' +                            msg0 += f'画师:{member_name}\n' +                            msg0 += f'画师ID:{member_id}\n' +                            msg0 += f'直链:https://pixiv.cat/{pixiv_id}.jpg' +                        except: +                            await bot.send_msg(group_id = group, message = errorBack('处理数据失败')) # type: ignore +                            return +                        if msg0: +                            if float(similarity) > 70: +                                await bot.send_msg(group_id = group, message = msg0) # type: ignore +                            else: +                                await bot.send_msg(group_id = group,  message = 'ATRI无法找到相似的图呢...') # type: ignore +                     +                else: +                    await bot.send_msg(group_id = group, message = '该功能已关闭...') # type: ignore +             +            else: +                try: +                    with open(Path('.') / 'ATRI' / 'plugins' / 'LearnRepo' / 'LearnRepo.json', 'r') as f: +                        data = json.load(f) +                except: +                    data = {} + +                if str(msg) in data.keys(): +                    lt = data[f"{msg}"] +                    msg = lt[0] +                    prob = int(lt[1]) +                    res = randint(1,prob) +                    if res == 1: +                        await bot.send_msg( +                            group_id = group, +                            message = msg +                        ) # type: ignore + +@bot.on_message('group') +async def _(context): +    user = context["user_id"] +    group = context["group_id"] +    if checkNoob(user, group): +        if 0 <= now_time() < 5.5: +            pass +        else: +            if randint(1,20) == 4: +                img = choice( +                    [ +                        '11.jpg', '12.jpg', '23.jpg' +                    ] +                ) +                img = os.path.abspath(Path('.') / 'ATRI' / 'data' / 'emoji' / 'senren' / f'{img}') +                await bot.send_msg(message = f'[CQ:image,file=file:///{img}]', auto_escape = False) # type: ignore +             +            else: +                pass
\ No newline at end of file diff --git a/ATRI/plugins/other.py b/ATRI/plugins/other.py index ac99de3..917a5e0 100644 --- a/ATRI/plugins/other.py +++ b/ATRI/plugins/other.py @@ -1,13 +1,16 @@ +import os +import json  import random  import nonebot  import warnings  from datetime import datetime  from random import choice +from pathlib import Path  from nonebot import on_command, CommandSession  from nonebot.helpers import render_expression -import config # type: ignore -from ATRI.modules.funcControl import checkNoob # type: ignore +import config +from ATRI.modules.funcControl import checkNoob  bot = nonebot.get_bot() @@ -101,7 +104,7 @@ async def _(session: CommandSession):                  )              ) -@on_command('关于', aliases = ['关于机器人'], only_to_me = False) +@on_command('关于', aliases = ['关于'])  async def _(session: CommandSession):      user = session.event.user_id      group = session.event.group_id @@ -114,7 +117,7 @@ async def _(session: CommandSession):  欢迎star~w!"""          ) -@on_command('help', aliases = ['帮助', '如何使用ATRI', '机器人帮助'], only_to_me = False) +@on_command('help', aliases = ['帮助', '如何使用ATRI', '机器人帮助', '菜单'], only_to_me = False)  async def _(session: CommandSession):      user = session.event.user_id      group = session.event.group_id @@ -169,4 +172,41 @@ async def _():      try:          RepoList = []      except: -        await bot.send_private_msg(user_id = master, message = f'红茶重置失败...请手动重启ATRI以重置红茶...') # type: ignore
\ No newline at end of file +        await bot.send_private_msg(user_id = master, message = f'红茶重置失败...请手动重启ATRI以重置红茶...') # type: ignore +        return +    print('红茶重置成功!') + + +@on_command('switchLoad', aliases=['开关初始化']) +async def _(session: CommandSession): +    if session.event.user_id in master: +        group_list = await session.bot.get_group_list() # type: ignore +        g_list = len(group_list) + +        az = [] +        for group in group_list: +            g = group['group_id'] +            try: +                try: +                    os.mkdir(Path('.') / 'ATRI' / 'data' / 'groupData' / f'{g}') +                except: +                    pass +                data = {} +                data["pixiv_seach_img"] = "on" +                data["pixiv_seach_author"] = "on" +                data["pixiv_daily_rank"] = "on" +                data["setu"] = "on" +                data["setu_img"] = "on" +                data["anime_search"] = "on" +                data["change_face"] = "on" +                data["chouYou"] = "on" +                data["saucenao_search"] = "on" +                with open(Path('.') / 'ATRI' / 'data' / 'groupData' / f'{g}' / 'switch.json', 'w') as f: +                    f.write(json.dumps(data)) +                    f.close() +                az.append(group) +            except: +                pass +        az = len(az) +         +        await session.send(f'已初始化{az}个群,总共{g_list}个群')
\ No newline at end of file diff --git a/ATRI/plugins/pixiv.py b/ATRI/plugins/pixiv.py index 0f3f971..48f39da 100644 --- a/ATRI/plugins/pixiv.py +++ b/ATRI/plugins/pixiv.py @@ -2,12 +2,12 @@ import time  import json  from datetime import datetime  from random import choice -from pathlib import Path  import nonebot  from nonebot import on_command, CommandSession -from ATRI.modules import response # type: ignore -from ATRI.modules.funcControl import checkSwitch, checkNoob # type: ignore +from ATRI.modules.response import request_api +from ATRI.modules.error import errorBack +from ATRI.modules.funcControl import checkSwitch, checkNoob  bot = nonebot.get_bot() @@ -62,42 +62,45 @@ async def _(session: CommandSession):                  )              )          else: -            if checkSwitch(__plugin_name1__): +            if checkSwitch(__plugin_name1__, group):                  pid = session.current_arg.strip()                  if not pid:                      pid = session.get('message', prompt = '请告诉ATRI需要查询的Pid码')                  start =time.perf_counter() -                await session.send('开始P站搜图\n如搜索时间过长或许为图片过大上传较慢') +                await session.send('开始P站搜图')                  URL = URL_1 + pid -                dc = json.loads(response.request_api(URL)) - -                if not dc: -                    session.finish('ATRI在网络上走散了...请重试...') +                try: +                    dc = json.loads(request_api(URL)) +                except: +                    session.finish(errorBack('请求数据失败'))                  img = f'https://pixiv.cat/{pid}.jpg'                  end = time.perf_counter() -                await session.send( -                    IMG_SEACH_REPLY.format( -                        user = user, -                        pid = pid, -                        title = dc["response"][0]["title"], -                        width = dc["response"][0]["width"], -                        height = dc["response"][0]["height"], -                        tags = dc["response"][0]["tags"], -                        account = dc["response"][0]["user"]["account"], -                        name = dc["response"][0]["user"]["name"], -                        user_link = f'https://www.pixiv.net/users/' + f'{dc["response"][0]["user"]["id"]}', -                        img = img, -                        time = round(end - start, 3) +                try: +                    await session.send( +                        IMG_SEACH_REPLY.format( +                            user = user, +                            pid = pid, +                            title = dc["response"][0]["title"], +                            width = dc["response"][0]["width"], +                            height = dc["response"][0]["height"], +                            tags = dc["response"][0]["tags"], +                            account = dc["response"][0]["user"]["account"], +                            name = dc["response"][0]["user"]["name"], +                            user_link = f'https://www.pixiv.net/users/' + f'{dc["response"][0]["user"]["id"]}', +                            img = img, +                            time = round(end - start, 3) +                        )                      ) -                ) +                except: +                    session.finish(errorBack('处理数据失败'))              else:                  await session.send('该功能已关闭...') @@ -121,7 +124,7 @@ async def _(session: CommandSession):                  )              )          else: -            if checkSwitch(__plugin_name2__): +            if checkSwitch(__plugin_name2__, group):                  author_id = session.current_arg.strip()                  if not author_id: @@ -132,17 +135,20 @@ async def _(session: CommandSession):                  URL = URL_2 + author_id -                dc = json.loads(response.request_api(URL)) - -                if not dc: -                    session.finish('ATRI在网络上走散了...请重试...') +                try: +                    dc = json.loads(request_api(URL)) +                except: +                    session.finish(errorBack('请求数据失败'))                  d ={} -                for i in range(0,3): -                    pid = dc["response"][i]["id"] -                    pidURL = f'https://pixiv.cat/{pid}.jpg' -                    d[i] = [f'{pid}',f'{pidURL}'] +                try: +                    for i in range(0,3): +                        pid = dc["response"][i]["id"] +                        pidURL = f'https://pixiv.cat/{pid}.jpg' +                        d[i] = [f'{pid}',f'{pidURL}'] +                except: +                    session.finish(errorBack('处理数据失败'))                  msg0 = (f'[CQ:at,qq={user}]\n画师id:{author_id},接下来展示前三作品') @@ -187,18 +193,25 @@ async def _(session: CommandSession):                  )              )          else: -            if checkSwitch(__plugin_name__): +            if checkSwitch(__plugin_name__, group):                  await session.send('ATRI正在获取P站每日排行榜前五作品...')                  start =time.perf_counter() -                dc = json.loads(response.request_api(URL_3)) + +                try: +                    dc = json.loads(request_api(URL_3)) +                except: +                    session.finish(errorBack('请求数据失败'))                  d = {} -                for i in range(0,5): -                    pid = dc["response"][0]["works"][i]["work"]["id"] -                    pidURL = f'https://pixiv.cat/{pid}.jpg' -                    d[i] = [f'{pid}',f'{pidURL}'] +                try: +                    for i in range(0,5): +                        pid = dc["response"][0]["works"][i]["work"]["id"] +                        pidURL = f'https://pixiv.cat/{pid}.jpg' +                        d[i] = [f'{pid}',f'{pidURL}'] +                except: +                    session.finish('处理数据失败')                  msg0 = (f'[CQ:at,qq={user}]') diff --git a/ATRI/plugins/richBISS.py b/ATRI/plugins/richBISS.py index f60d7d0..88d4277 100644 --- a/ATRI/plugins/richBISS.py +++ b/ATRI/plugins/richBISS.py @@ -1,11 +1,10 @@  import re  import json  import nonebot -from pathlib import Path  from datetime import datetime -from ATRI.modules import response # type: ignore -from ATRI.modules.funcControl import checkNoob # type: ignore +from ATRI.modules.response import request_api +from ATRI.modules.funcControl import checkNoob  bot = nonebot.get_bot() @@ -70,7 +69,7 @@ async def Fuck_bili_rich(context):                  URL = f'https://api.imjad.cn/bilibili/v2/?aid={aid}'                  try: -                    res = response.request_api(URL) +                    res = request_api(URL)                      mg = json.loads(res)                      msg = BILI_REPORT_FORMAT.format(                          title = mg["data"]["title"], @@ -120,7 +119,7 @@ async def Fuck_CloudMusic(context):                      print(URL)                      try: -                        res = response.request_api(URL) +                        res = request_api(URL)                          mg = json.loads(res)                          msg = REPORT_FORMAT.format( diff --git a/ATRI/plugins/switch.py b/ATRI/plugins/switch.py index 71b7f62..1cb0220 100644 --- a/ATRI/plugins/switch.py +++ b/ATRI/plugins/switch.py @@ -1,19 +1,124 @@ +import os  import json  import nonebot  from nonebot import on_command, CommandSession +from pathlib import Path + +from nonebot.permission import GROUP_ADMIN + +import config  bot = nonebot.get_bot() -master = bot.config.SUPERUSERS +master = config.MASTER() -@on_command('switch', aliases = ['on', 'off'], only_to_me = False) +@on_command('switch', aliases = ['on', 'off'], only_to_me = False, permission = GROUP_ADMIN)  async def _(session: CommandSession): -    with open("ATRI/plugins/switch/switch.json", 'r') as f: -        data = json.load(f) -    print(data) +    group = session.event.group_id +    try: +        with open(Path('.') / 'ATRI' / 'data' / 'groupData' / f'{group}' / 'switch.json', 'r') as f: +            data = json.load(f) +    except: +        try: +            os.mkdir(Path('.') / 'ATRI' / 'data' / 'groupData' / f'{group}') +        except: +            pass +        data = {} +        data["pixiv_seach_img"] = "on" +        data["pixiv_seach_author"] = "on" +        data["pixiv_daily_rank"] = "on" +        data["setu"] = "on" +        data["setu_img"] = "on" +        data["anime_search"] = "on" +        data["change_face"] = "on" +        data["chouYou"] = "on" +        data["saucenao_search"] = "on" +        with open(Path('.') / 'ATRI' / 'data' / 'groupData' / f'{group}' / 'switch.json', 'w') as f: +            f.write(json.dumps(data)) +            f.close() + + +    command = session.event.raw_message.split(' ', 1) +    switch = command[0] +    com = command[1] +    print(command) + +    if switch == 'on': +        if com == 'PixivSearchIMG': +            data["pixiv_seach_img"] = "on" +         +        elif com == 'PixivSearchAuthor': +            data["pixiv_seach_author"] = "on" +         +        elif com == 'PixivRank': +            data["pixiv_daily_rank"] = "on" + +        elif com == 'Setu': +            data["setu"] = "on" +         +        elif com == 'SetuIMG': +            data["setu_img"] = "on" +         +        elif com == "AnimeSearch": +            data["anime_search"] = "on" +         +        elif com == 'AIchFace': +            data["change_face"] = "on" +         +        elif com == 'Kyaru': +            data["chouYou"] = "on" +         +        elif com == 'SauceNAO': +            data["saucenao_search"] = "on" +         +        else: +            session.finish('未找到此功能...请检查拼写奥...') + +    elif switch == 'off': +        if com == 'PixivSearchIMG': +            data["pixiv_seach_img"] = "off" +         +        elif com == 'PixivSearchAuthor': +            data["pixiv_seach_author"] = "off" +         +        elif com == 'PixivRank': +            data["pixiv_daily_rank"] = "off" +        elif com == 'Setu': +            data["setu"] = "off" +         +        elif com == 'SetuIMG': +            data["setu_img"] = "off" +         +        elif com == "AnimeSearch": +            data["anime_search"] = "off" +         +        elif com == 'AIchFace': +            data["change_face"] = "off" +         +        elif com == 'Kyaru': +            data["chouYou"] = "off" +         +        elif com == 'SauceNAO': +            data["saucenao_search"] = "off" +         +        else: +            session.finish('未找到此功能...请检查拼写奥...') +     +    f2 = open(Path('.') / 'ATRI' / 'data' / 'groupData' / f'{group}' / 'switch.json', 'w') +    f2.write(json.dumps(data)) +    f2.close() + +    await session.send('Success!') + + +@on_command('allSwitch', aliases = ['allon', 'alloff'], only_to_me = False) +async def _(session: CommandSession):      if session.event.user_id in master: +        with open(Path('.') / 'ATRI' / 'modules' / 'funcControl' / 'ALLswitch.json', 'r') as f: +            data = json.load(f) +                  command = session.event.raw_message.split(' ', 1)          switch = command[0]          com = command[1] @@ -28,12 +133,6 @@ async def _(session: CommandSession):              elif com == 'PixivRank':                  data["pixiv_daily_rank"] = "on" -             -            elif com == 'FriendADD': -                data["approve_friend_add"] = "on" -             -            elif com == 'GroupInvite': -                data["approve_invite_join_group"] = "on"              elif com == 'Setu':                  data["setu"] = "on" @@ -54,7 +153,7 @@ async def _(session: CommandSession):                  data["saucenao_search"] = "on"              else: -                pass +                session.finish('未找到此功能...请检查拼写奥...')          elif switch == 'off':              if com == 'PixivSearchIMG': @@ -66,12 +165,6 @@ async def _(session: CommandSession):              elif com == 'PixivRank':                  data["pixiv_daily_rank"] = "off" -            elif com == 'FriendADD': -                data["approve_friend_add"] = "off" -             -            elif com == 'GroupInvite': -                data["approve_invite_join_group"] = "off" -              elif com == 'Setu':                  data["setu"] = "off" @@ -91,13 +184,10 @@ async def _(session: CommandSession):                  data["saucenao_search"] = "off"              else: -                pass +                session.finish('未找到此功能...请检查拼写奥...') -        f2 = open("ATRI/plugins/switch/switch.json", 'w') +        f2 = open(Path('.') / 'ATRI' / 'modules' / 'funcControl' / 'ALLswitch.json', 'w')          f2.write(json.dumps(data))          f2.close() -        await session.send('Success!') -     -    else: -        await session.send('恁哪位?') +        await session.send('Success!')
\ No newline at end of file diff --git a/ATRI/plugins/switch/switch.json b/ATRI/plugins/switch/switch.json deleted file mode 100644 index df65fb7..0000000 --- a/ATRI/plugins/switch/switch.json +++ /dev/null @@ -1 +0,0 @@ -{"pixiv_seach_img": "on", "pixiv_seach_author": "off", "pixiv_daily_rank": "on", "approve_friend_add": "on", "approve_invite_join_group": "on", "setu": "on", "setu_img": "on", "anime_search": "on", "change_face": "on", "chouYou": "off", "saucenao_search": "on"} diff --git a/ATRI/plugins/welcome.py b/ATRI/plugins/welcome.py index a3a8fd0..04a210b 100644 --- a/ATRI/plugins/welcome.py +++ b/ATRI/plugins/welcome.py @@ -1,28 +1,27 @@ -import nonebot  from nonebot import on_notice -from nonebot.notice_request import NoticeSession, RequestSession  from nonebot.plugin import on_request -from nonebot.helpers import send_to_superusers +from nonebot.notice_request import NoticeSession, RequestSession -import config # type: ignore -from ATRI.modules.funcControl import checkNoob # type: ignore +import config +from ATRI.modules.funcControl import checkNoob -bot = nonebot.get_bot()  master = config.MASTER()  @on_notice('group_increase')  async def _(session: NoticeSession):      user = session.event.user_id +    group = session.event.group_id      me = session.event.self_id -    if user == me: -        await session.send('在下アトリ,今后请多指教呐❤') -    else: -        await session.send(f'[CQ:at,qq={user}]\nねえ❤...是新人欸!\nここでは遠慮はいらないのだからね❤') +    if checkNoob(group): +        if user == me: +            await session.send('在下アトリ,今后请多指教呐❤') +        else: +            await session.send(f'[CQ:at,qq={user}]\nねえ❤...是新人欸!\nここでは遠慮はいらないのだからね❤') -@on_notice('group_decrease') +@on_notice('group_decrease.leave')  async def _(session: NoticeSession):      user = session.event.user_id      group = session.event.group_id @@ -32,14 +31,18 @@ async def _(session: NoticeSession):              await session.send(f'[{user}]离开了我们......') -@on_request('friend_add') +@on_request('friend', 'group.invite')  async def _(session: RequestSession):      user = session.event.user_id -    await send_to_superusers(bot, f'{user}\n想认识ATRI欸欸欸!!') - -@on_request('group') -async def _(session: RequestSession): -    if session.event.user_id == master: -        await session.approve() -    else: -        await session.send(f'邀请入群请联系ATRI的主人[{master}]')
\ No newline at end of file +    if checkNoob(user): +        try: +            group = session.event.group_id +        except: +            group = False +         +        if group: +            await bot.send_private_msg(user_id = user, message = f'如有需要,请联系维护组{master}哦~') # type: ignore +            await bot.send_private_msg(user_id = master, message = f'报告主人!ATRI收到一条请求:\n类型:邀请入群\n邀请人:{user}\n对象群:{group}') # type: ignore +         +        else: +            await bot.send_private_msg(user_id = master, message = f'报告主人!ATRI收到一条请求:\n类型:添加好友\n申请人:{user}') # type: ignore
\ No newline at end of file | 
