diff --git a/config/config.yml b/config/config.yml index 5e47ae3..4a893ea 100644 --- a/config/config.yml +++ b/config/config.yml @@ -4,8 +4,8 @@ adapter: # Mirai-Api-Http verify_key: NekoRabi botconfig: - botname: '' # 机器人名字 - qq: 123456 # 机器人QQ + botname: "" # 机器人名字 + qq: 123456 # 机器人QQ admin: # 以下都是管理员 - 1215791340 @@ -19,11 +19,11 @@ blacklist: # 黑名单 mutegrouplist: - 0 -commandpre: '' # 指令前缀 +commandpre: "" # 指令前缀 -master: 0 # 机器人主人,必填 +master: 0 # 机器人主人,必填 -replyimgpath : fox # 表情包路径 +replyimgpath: fox # 表情包路径 loglevel: INFO # 日志等级 @@ -31,36 +31,41 @@ loglevel: INFO # 日志等级 nudgeconfig: # 在某群禁用 摸头事件 disnudgegroup: - - 0 - sendnudgechance: 1 # 被戳时 以 "戳一戳" 还击的概率 + - 469789730 + - 586468489 + sendnudgechance: 1 # 被戳时 以 "戳一戳" 还击的概率 supersendnudgechance: 0.2 # 还击的"戳一戳"中,触发超级还击的概率 supernudgequantity: 10 # 单次超级还击的发送 "戳一戳" 的次数 # 在某群关闭自动回复 norepeatgroup: - - 0 + - 586468489 silencegroup: - - 0 # 设置单群沉默 + - 586468489 # 设置单群沉默 -welcomeinfo: # 新人入群欢迎词,%ps%为新人名字,%gn%为群聊名字 +welcomeinfo: # 新人入群欢迎词,%ps%为新人名字,%gn%为群聊名字 - 欢迎%ps%加入%gn% +no_welcome: + - 586468489 + whitelist: - - 0 # 白名单 + - 1215791340 # 白名单 trash_folders: # 需要清理垃圾的文件夹 - - './images/MajSoulInfo' - - './images/PetPet' - - './images/Remake' - - './images/ImgGenerator' + - "./images/MajSoulInfo" + - "./images/PetPet" + - "./images/Remake" + - "./images/ImgGenerator" settings: # 功能开关 - autogetpaipu: true # 自动获取雀魂牌谱 - autowelcome: true # 自动欢迎新人 - nudgereply: true # 是否启用摸头事件 - r18talk: true # 开启管理员词库 - silence: false # 全局沉默,降低发言频率 - norepeat: false # 全局自动回复 - help: true # 是否显示帮助 - saveflashimg: false # 保存闪照 + autogetpaipu: true # 自动获取雀魂牌谱 + autowelcome: true # 自动欢迎新人 + nudgereply: true # 是否启用摸头事件 + r18talk: true # 开启管理员词库 + silence: false # 全局沉默,降低发言频率 + norepeat: false # 全局自动回复 + help: true # 是否显示帮助 + # saveflashimg: false # 保存闪照 + general_help: true # 自动生成帮助图片 diff --git a/core/fun/roll.py b/core/fun/roll.py index 15d3c25..5f87cb9 100644 --- a/core/fun/roll.py +++ b/core/fun/roll.py @@ -88,15 +88,35 @@ async def roll_item(event: GroupMessage or FriendMessage): if m2: return await messagechain_sender(event=event, msg=await messagechain_builder( text=f'{_random_int_general(m2.group(1), m2.group(2))}')) - m3 = re.match(r'[Dd](\d+)$', content) + m3 = re.match(r'(\d+)?[Dd](\d+)$', content) if m3: - dice = int(m3.group(1)) + counts = m3.group(1) + if counts: + counts = int(counts) + else: + counts = 1 + if counts < 1: + counts = 1 + elif counts > 100: + return await messagechain_sender(event=event, msg=await messagechain_builder(at=event.sender.id, text='我累了')) + dice = int(m3.group(2)) if dice < 1 or dice > 100: return await messagechain_sender(event=event, msg=await messagechain_builder(at=event.sender.id, text='我没有这样的骰子')) elif dice % 2 == 1 and dice > 9: return await messagechain_sender(event=event, msg=await messagechain_builder(at=event.sender.id, text='我只有10面以下的奇数面骰子~')) + each_rnd = _random_int_general(dn=dice) + sum = each_rnd + rnd_str = f'{each_rnd}' + for i in range(counts): + if i == 0: + continue + each_rnd = _random_int_general(dn=dice) + sum += each_rnd + rnd_str += f' + {each_rnd}' + rnd_str += f' = {sum}' + return await messagechain_sender(event=event, msg=await messagechain_builder( - text=f'{_random_int_general(dn=dice)}')) + text=f'{rnd_str}')) m4 = content.split(' ') return await messagechain_sender(event=event, msg=await messagechain_builder(text=_random_item(m4))) return await messagechain_sender(event=event, msg=await messagechain_builder(text=f'{_random_int_general()}')) @@ -107,7 +127,7 @@ async def roll_item(event: GroupMessage or FriendMessage): "roll 正整数a : 返回 0-a 的随机整数 ", "roll a-b : 返回 a-b 之间的随机整数", "roll itemA itemB …… : 返回随机一个元素", - "roll dn: 投掷n面骰" + "roll ndn: 投掷n次n面骰" ] add_help('group', [ 'roll 返回100以内的随机整数', diff --git a/core/fun/welcome.py b/core/fun/welcome.py index 6efbd40..93b8590 100644 --- a/core/fun/welcome.py +++ b/core/fun/welcome.py @@ -28,6 +28,8 @@ async def welcome(event: MemberJoinEvent) -> None: personname = event.member.member_name groupname = event.member.group.name groupid = event.member.group.id + if groupid in config.get('no_welcome', []): + return info: str = random.choice(config['welcomeinfo']) info = info.replace('%ps%', personname).replace('%gn%', groupname) await messagechain_sender( diff --git a/main.py b/main.py index 65074d1..a8e0ca6 100644 --- a/main.py +++ b/main.py @@ -17,7 +17,8 @@ if __name__ == '__main__': config = load_config() - create_helpimg() + if config.get('setting',{}).get('general_help',True): + create_helpimg() settings = config['settings'] botname = config['botconfig']['botname'] diff --git "a/other/\350\207\252\347\224\250mirai/mcl-2.1.1.zip" "b/other/\350\207\252\347\224\250mirai/mcl-2.1.1.zip" deleted file mode 100644 index 76c4c9b..0000000 Binary files "a/other/\350\207\252\347\224\250mirai/mcl-2.1.1.zip" and /dev/null differ diff --git a/plugin/ImgGenerator/KissKiss/Kisskiss.py b/plugin/ImgGenerator/KissKiss/Kisskiss.py index 311a3e5..68345c8 100644 --- a/plugin/ImgGenerator/KissKiss/Kisskiss.py +++ b/plugin/ImgGenerator/KissKiss/Kisskiss.py @@ -16,6 +16,7 @@ from moviepy.editor import ImageSequenceClip as imageclip from io import BytesIO from core import bot, commands_map, commandpre, blacklist +from utils import read_file from utils.MessageChainBuilder import messagechain_builder from utils.MessageChainSender import messagechain_sender @@ -24,6 +25,8 @@ __all__ = ['on_kiss'] +_cfg = read_file(r'./config/ImgGenerator/config.yml') + async def save_gif(gif_frames, dest, fps=10): clip = imageclip(gif_frames, fps=fps) @@ -87,6 +90,8 @@ async def kiss(operator_id, target_id) -> None: @bot.on(GroupMessage) async def on_kiss(event: GroupMessage): + if not _cfg.get('Kiss', True): + return if event.sender.id in blacklist: return msg = "".join(map(str, event.message_chain[Plain])) @@ -97,9 +102,11 @@ async def on_kiss(event: GroupMessage): target_id = event.message_chain.get_first(At).target if operator_id == target_id: # return await bot.send(event, await messagechain_builder(text="请不要自交", rndimg=True)) - return await messagechain_sender(event=event, msg= await messagechain_builder(text="请不要自交", rndimg=True, at=event.sender.id)) + return await messagechain_sender(event=event, msg=await messagechain_builder(text="请不要自交", rndimg=True, + at=event.sender.id)) else: await kiss(operator_id=operator_id, target_id=target_id) # await bot.send(event, await messagechain_builder( # imgpath=f'./images/ImgGenerator/KissKiss/tempKiss-{operator_id}-{target_id}.gif')) - return await messagechain_sender(event=event, msg= await messagechain_builder(imgpath=f'./images/ImgGenerator/KissKiss/tempKiss-{operator_id}-{target_id}.gif')) + return await messagechain_sender(event=event, msg=await messagechain_builder( + imgpath=f'./images/ImgGenerator/KissKiss/tempKiss-{operator_id}-{target_id}.gif')) diff --git a/plugin/ImgGenerator/__init__.py b/plugin/ImgGenerator/__init__.py index 406595d..c844aad 100644 --- a/plugin/ImgGenerator/__init__.py +++ b/plugin/ImgGenerator/__init__.py @@ -1,22 +1,12 @@ -import os - +from .file_init import * from core.help import add_help -from plugin.ImgGenerator.bwimg import * -from plugin.ImgGenerator.csgokill import * -from plugin.ImgGenerator.groupmember_imgoperation import * -if not os.path.exists('./images/ImgGenerator'): - os.mkdir(f'./images/ImgGenerator') -if os.path.exists(r'./main.exe'): - from plugin.ImgGenerator.KissKiss import * - from plugin.ImgGenerator.jupai import * - from plugin.ImgGenerator.prank_on_groupmember import * -else: - _plugins = os.listdir(r'./plugin/ImgGenerator') - for path in _plugins: - if os.path.isdir(f'./plugin/ImgGenerator/{path}'): - if os.path.exists(f'./plugin/ImgGenerator/{path}/__init__.py'): - exec(f'from plugin.ImgGenerator.{path} import *') +from .bwimg import * +from .csgokill import * +from .groupmember_imgoperation import * +from .jupai import * +from .KissKiss import * +from .prank_on_groupmember import * add_help('group', [ @@ -27,6 +17,7 @@ "丢/举(我自己)@群友 : 把群友丢出去/举起来\n ", "吃掉 @群友 : 把群友吃了\n", "bw [<文本>] [<图片>] : 返回一张黑白处理后的图片,底部有一行文字\n", + "娶群友 : 不解释了\n", "截图 <回复消息> : 将一条文本聊天记录截图\n", "击杀[<文本> 或 @群友] : 击杀群友\n" ]) diff --git a/plugin/ImgGenerator/bwimg.py b/plugin/ImgGenerator/bwimg.py index c409eb9..514980d 100644 --- a/plugin/ImgGenerator/bwimg.py +++ b/plugin/ImgGenerator/bwimg.py @@ -13,6 +13,8 @@ from core import bot, commandpre, blacklist +from utils.cfg_loader import read_file + __all__ = ['bwimg'] from utils.MessageChainBuilder import messagechain_builder @@ -21,6 +23,8 @@ if not os.path.exists("./images/ImgGenerator"): os.mkdir("./images/ImgGenerator") +_cfg = read_file(r'./config/ImgGenerator/config.yml') + def makebwimg(imgname, text: str = ""): filename = os.path.splitext(imgname)[0] @@ -61,6 +65,8 @@ def deletesource(imgname): @bot.on(GroupMessage) async def bwimg(event: GroupMessage): + if not _cfg.get('BW_img', False): + return if event.sender.id in blacklist: return msg = "".join(map(str, event.message_chain[Plain])) @@ -73,7 +79,8 @@ async def bwimg(event: GroupMessage): await img.download(filename=f'./images/tempimg/{imgname}') makebwimg(imgname, m.group(1)) # await bot.send(event, await messagechain_builder(imgpath=f'./images/ImgGenerator/{imgname}')) - await messagechain_sender(event=event,msg=await messagechain_builder(imgpath=f'./images/ImgGenerator/{imgname}')) + await messagechain_sender(event=event, + msg=await messagechain_builder(imgpath=f'./images/ImgGenerator/{imgname}')) deletesource(imgname) # except Exception as e: # print(e) diff --git a/plugin/ImgGenerator/csgokill.py b/plugin/ImgGenerator/csgokill.py index 39adadf..c03ad2b 100644 --- a/plugin/ImgGenerator/csgokill.py +++ b/plugin/ImgGenerator/csgokill.py @@ -13,12 +13,15 @@ from PIL import Image, ImageFont, ImageDraw from mirai import GroupMessage, Plain, At from core import bot, blacklist +from utils import read_file from utils.MessageChainBuilder import messagechain_builder __all__ = ['cskill'] from utils.MessageChainSender import messagechain_sender +_cfg = read_file(r'./config/ImgGenerator/config.yml') + async def jisha(user: str, target: str, headshot=None, penetrate=None): """ @@ -88,6 +91,8 @@ async def jisha(user: str, target: str, headshot=None, penetrate=None): @bot.on(GroupMessage) async def cskill(event: GroupMessage): + if not _cfg.get('CSGOKill', False): + return if event.sender.id in blacklist: return msg = "".join(map(str, event.message_chain[Plain])) diff --git a/plugin/ImgGenerator/file_init.py b/plugin/ImgGenerator/file_init.py new file mode 100644 index 0000000..0634888 --- /dev/null +++ b/plugin/ImgGenerator/file_init.py @@ -0,0 +1,13 @@ +import os + +from utils.cfg_loader import write_file + +if not os.path.exists('./images/ImgGenerator'): + os.mkdir(f'./images/ImgGenerator') +if not os.path.exists(r'./config/ImgGenerator'): + os.mkdir(r'./config/ImgGenerator') + +if not os.path.exists(r'./config/ImgGenerator/config.yml'): + cfg = {'HoldUpCard': True, 'HoldUp': True, 'Kiss': True, 'Arrest': True, 'SmallLove': True, 'Throw': True, + 'Eat': True, 'BW_img': True, 'Marry': True, 'Screenshot': True, 'CSGOKill': True} + write_file(content=cfg, path=r'./config/ImgGenerator/config.yml') \ No newline at end of file diff --git a/plugin/ImgGenerator/groupmember_imgoperation.py b/plugin/ImgGenerator/groupmember_imgoperation.py index ffb699d..dd9aadd 100644 --- a/plugin/ImgGenerator/groupmember_imgoperation.py +++ b/plugin/ImgGenerator/groupmember_imgoperation.py @@ -5,12 +5,13 @@ :Describe: 群成员图片制作 :Version: 0.0.1 """ +import datetime import random -from utils import root_logger +from utils import root_logger, read_file from utils.MessageChainBuilder import messagechain_builder from mirai import GroupMessage, At, Plain -from core import bot, blacklist +from core import bot, blacklist, commandpre from io import BytesIO from PIL import Image, ImageFont, ImageDraw @@ -24,7 +25,9 @@ if not os.path.exists("./images/ImgGenerator"): os.mkdir("./images/ImgGenerator") -__all__ = ['xka', 'daiburen', 'diuren', 'chiren', 'juren'] +__all__ = ['xka', 'daiburen', 'diuren', 'chiren', 'juren', 'merry_random_group_member', 'merry_group_member'] + +_cfg = read_file(r'./config/ImgGenerator/config.yml') def img_to_base64(img: Image): @@ -146,6 +149,8 @@ async def holdup(userid): @bot.on(GroupMessage) async def daiburen(event: GroupMessage): """生成逮捕图""" + if not _cfg.get('Arrest', False): + return if event.sender.id in blacklist: return msg = "".join(map(str, event.message_chain[Plain])) @@ -167,6 +172,8 @@ async def daiburen(event: GroupMessage): @bot.on(GroupMessage) async def xka(event: GroupMessage): + if not _cfg.get('SmallLove', False): + return if event.sender.id in blacklist: return msg = "".join(map(str, event.message_chain[Plain])) @@ -200,6 +207,8 @@ async def xka(event: GroupMessage): @bot.on(GroupMessage) async def diuren(event: GroupMessage): """丢人制作""" + if not _cfg.get('Throw', False): + return if event.sender.id in blacklist: return msg = "".join(map(str, event.message_chain[Plain])) @@ -223,6 +232,8 @@ async def diuren(event: GroupMessage): @bot.on(GroupMessage) async def chiren(event: GroupMessage): """吃掉头像""" + if not _cfg.get('Eat', False): + return if event.sender.id in blacklist: return msg = "".join(map(str, event.message_chain[Plain])) @@ -238,6 +249,8 @@ async def chiren(event: GroupMessage): @bot.on(GroupMessage) async def juren(event: GroupMessage): """举高高""" + if not _cfg.get('HoldUp', False): + return if event.sender.id in blacklist: return msg = "".join(map(str, event.message_chain[Plain])) @@ -253,3 +266,59 @@ async def juren(event: GroupMessage): img = await holdup(userid) await bot.messagechain_sender(event=event, msg=await messagechain_builder(imgbase64=img)) return + + +@bot.on(GroupMessage) +async def merry_random_group_member(event: GroupMessage): + """每日找对象""" + if not _cfg.get('Marry', False): + return + msg = "".join(map(str, event.message_chain[Plain])) + m = re.match( + fr"^{commandpre}\s*(娶群友|找对象)\s*$", msg.strip()) + if m: + if At in event.message_chain: + at = event.message_chain.get_first(At) + avatar = await get_head_sculpture(at.target) + userimg = avatar.resize((200, 200), Image.ANTIALIAS) + userimg = img_to_base64(userimg) + return await messagechain_sender(event=event, msg=await messagechain_builder(at=event.sender.id, + text=f'你今天的老婆是 {at.display}', + imgbase64=userimg)) + else: + time = datetime.datetime.now().strftime('%Y%m%d') + seed = int(time) + event.sender.id + random.seed(seed) + memberlist = await bot.member_list.get(event.group.id) + memberlist = memberlist.data + member = memberlist[random.randint(0, len(memberlist) - 1)] + avatar = await get_head_sculpture(member.id) + userimg = avatar.resize((200, 200), Image.ANTIALIAS) + userimg = img_to_base64(userimg) + return await messagechain_sender(event=event, msg=await messagechain_builder(at=event.sender.id, + text=f'你今天的老婆是 {member.member_name}', + imgbase64=userimg)) + + +@bot.on(GroupMessage) +async def merry_group_member(event: GroupMessage): + """和指定群友结婚""" + if not _cfg.get('Marry', False): + return + msg = "".join(map(str, event.message_chain[Plain])) + m = re.match( + fr"^{commandpre}\s*(结婚|娶)\s*$", msg.strip()) + if m: + if At in event.message_chain: + at = event.message_chain.get_first(At) + avatar = await get_head_sculpture(at.target) + userimg = avatar.resize((200, 200), Image.ANTIALIAS) + userimg = img_to_base64(userimg) + count = random.random() * 100 + if count < 1: + pass + else: + pass + return await messagechain_sender(event=event, msg=await messagechain_builder(at=event.sender.id, + text=f'恭喜你和 {at.display} 结婚', + imgbase64=userimg)) diff --git a/plugin/ImgGenerator/jupai/holdup.py b/plugin/ImgGenerator/jupai/holdup.py index abe803f..a6cd2e3 100644 --- a/plugin/ImgGenerator/jupai/holdup.py +++ b/plugin/ImgGenerator/jupai/holdup.py @@ -10,6 +10,7 @@ import re import numpy as np +from utils import read_file from utils.MessageChainBuilder import messagechain_builder from PIL import ImageFont, ImageDraw, Image from mirai import GroupMessage, Plain @@ -21,6 +22,8 @@ __all__ = ['jupai'] +_cfg = read_file(r'./config/ImgGenerator/config.yml') + def find_coeffs(pa, pb): matrix = [] @@ -81,6 +84,8 @@ def imgoutput(senderid: int, textMessage='拉克丝真可爱'): @bot.on(GroupMessage) async def jupai(event: GroupMessage): """创建举牌文字""" + if not _cfg.get('HoldUpCard', True): + return if event.sender.id in blacklist: return msg = "".join(map(str, event.message_chain[Plain])) diff --git a/plugin/ImgGenerator/prank_on_groupmember/persecute_groupmenber.py b/plugin/ImgGenerator/prank_on_groupmember/persecute_groupmenber.py index 83da388..0f64cb3 100644 --- a/plugin/ImgGenerator/prank_on_groupmember/persecute_groupmenber.py +++ b/plugin/ImgGenerator/prank_on_groupmember/persecute_groupmenber.py @@ -12,6 +12,7 @@ from PIL import Image, ImageFont, ImageDraw from mirai.models import Plain, GroupMessage, Quote from core import bot, blacklist +from utils import read_file from utils.MessageChainBuilder import messagechain_builder from utils.MessageChainSender import messagechain_sender @@ -19,6 +20,8 @@ default_maxwidth = default_fontsize * 15 +_cfg = read_file(r'./config/ImgGenerator/config.yml') + __all__ = ['groupmessage_screenshot'] @@ -166,11 +169,15 @@ def addfont(text: str, sender_name=None, position: tuple = (0, 0), textcolor=(0, return maxwidth + 2 * fontsize, (line_count + 1) * line_heaight, img + @bot.on(GroupMessage) async def groupmessage_screenshot(event: GroupMessage): """ - 迫害群友 + 迫害群友,截图聊天记录 """ + + if not _cfg.get('Screenshot', True): + return if event.sender.id in blacklist: return quote_find_error = False diff --git a/plugin/Setu/setu.py b/plugin/Setu/setu.py index 1b2ab6b..996f1ae 100644 --- a/plugin/Setu/setu.py +++ b/plugin/Setu/setu.py @@ -169,6 +169,7 @@ async def getsetu(self, description, groupid, num=1) -> dict: _mahversion = None + @bot.on(FriendMessage) async def global_setu_control(event: FriendMessage): msg = "".join(map(str, event.message_chain[Plain])) @@ -246,7 +247,6 @@ async def getsomesetu(event: GroupMessage): if _mahversion is None: _mahversion = await bot.about() _mahversion = _mahversion.data.get('version')[:3] - print(_mahversion) # 匹配指令 m1 = re.match( fr"^{commandpre}{commands_map['setu']['getsetu1']}", msg.strip()) diff --git a/plugin/Tarot/__init__.py b/plugin/Tarot/__init__.py index 5c330c1..a7ac654 100644 --- a/plugin/Tarot/__init__.py +++ b/plugin/Tarot/__init__.py @@ -1 +1,9 @@ +""" +:Author: NekoRabi +:Create: 2023/7/29 15:17 +:Update: / +:Describe: 该插件已经内嵌,无许需引用,可删除 +:Version: 0.0.1 +""" + # from plugin.Tarot.tarot import * diff --git a/plugin/Template/helloworld.py b/plugin/Template/helloworld.py index b7bd0ef..8bbc5c6 100644 --- a/plugin/Template/helloworld.py +++ b/plugin/Template/helloworld.py @@ -15,7 +15,6 @@ from core import bot, config, bot_cfg - # bot 是必须导入的, config 和 bot_cfg 是可选 # config 是系统配置文件,有 指令前缀、黑白名单 等等 # bot_cfg 是机器人的配置,比如 QQ号、昵称 等等数据 @@ -23,6 +22,9 @@ # 还可以import其他的模块,比如 工具类,sqlite3,asyncio,time,math 等等 # 推荐使用 utils.MessageChainBuilder和 utils.MessageChainSender 中的方法来构造和发送消息链 +from utils.MessageChainBuilder import * +from utils.MessageChainSender import * + async def asy_hello(): """ @@ -61,6 +63,7 @@ def readfile(path): print(data) return data + @bot.on(GroupMessage) # 当群聊事件发生时 async def helloworld(event: GroupMessage): """ @@ -82,7 +85,12 @@ async def helloworld(event: GroupMessage): # from utils.MessageChainBuilder import messagechain_builder # 最后让机器人发信息,给出反馈,可以用utils.MessageChainBuilder包的 messagechain_builder() 方法来快速构造一个消息链 - await bot.send(event, f'114514191810 ! This is {bot_cfg.get("nickname")}') + # await bot.send(event, f'114514191810 ! This is {bot_cfg.get("nickname")}') + msgchain = await MessageChainBuilder().addText('Hello Word!').addAt(event.sender.id).build() + # or + msgchain = await messagechain_builder(text='Hello World', at=event.sender.id) + + await messagechain_sender(event=event, msg=msgchain) @bot.on(FriendMessage) # 当私聊事件发生时 @@ -106,4 +114,4 @@ async def helloworld(event: FriendMessage): from utils.MessageChainBuilder import messagechain_builder # 最后让机器人发信息,给出反馈,可以用utils.MessageChainBuilder包的 messagechain_builder(text=msg) 方法来快速构造一个消息链 - await bot.send(event, f'私聊成功! This is {bot_cfg.get("nickname")}') + await bot.send(event, f'Hello ! This is {bot_cfg.get("nickname")}') diff --git a/plugin/__init__.py b/plugin/__init__.py index b511a60..77a1aaf 100644 --- a/plugin/__init__.py +++ b/plugin/__init__.py @@ -24,16 +24,17 @@ # 'Else' -from plugin.AlarmClock import * -from plugin.AutoReply import * -from plugin.BilibiliPlugin import * -from plugin.ImgGenerator import * -from plugin.LocalImageAutoSender import * -from plugin.MajSoulInfo import * -from plugin.paili_analysis import * -from plugin.Petpet import * -from plugin.Remake import * -from plugin.RichiMahjongMatchControl import * -from plugin.Setu import * -from plugin.TencentCloudAPI import * -from plugin.TenHouPlugin import * +from .AlarmClock import * +from .AutoReply import * +from .BilibiliPlugin import * +from .fakenews import * +from .ImgGenerator import * +from .LocalImageAutoSender import * +from .MajSoulInfo import * +from .paili_analysis import * +from .Petpet import * +from .Remake import * +from .RichiMahjongMatchControl import * +from .Setu import * +from .TencentCloudAPI import * +from .TenHouPlugin import * diff --git a/plugin/fakenews/__init__.py b/plugin/fakenews/__init__.py new file mode 100644 index 0000000..276367b --- /dev/null +++ b/plugin/fakenews/__init__.py @@ -0,0 +1 @@ +from .fakenews import * \ No newline at end of file diff --git a/plugin/fakenews/fakenews.py b/plugin/fakenews/fakenews.py new file mode 100644 index 0000000..b2d8319 --- /dev/null +++ b/plugin/fakenews/fakenews.py @@ -0,0 +1,40 @@ +import re + +from mirai import GroupMessage, Plain + +from core import bot, commandpre, add_help +from utils.MessageChainBuilder import messagechain_builder +from utils.MessageChainSender import messagechain_sender + +from mirai import At +from mirai.models import ForwardMessageNode, Forward + +__all__ = ['fakenews'] + +@bot.on(GroupMessage) +async def fakenews(event: GroupMessage): + """假消息""" + msg = "".join(map(str, event.message_chain[Plain])) + m = re.match( + fr"^{commandpre}\s*fakenews\s*(\S+)\s*$", msg.strip()) + if m: + if At in event.message_chain: + at = event.message_chain[At][0].target + + member_profile = await bot.member_profile.get(event.group.id, at) + memberinfo = await bot.get_group_member(group=event.group.id, id_=at) + if memberinfo: + name = memberinfo.member_name + else: + name = member_profile.nickname + fmn = ForwardMessageNode( + sender_id=at, + sender_name=name, + message_chain=await messagechain_builder( + text=m.group(1)) + ) + await messagechain_sender(event=event, msg=Forward(node_list=[fmn])) + +add_help('group',[ + "fakenews @群友 [文本]: 假消息\n" +]) \ No newline at end of file diff --git a/utils/MessageChainBuilder.py b/utils/MessageChainBuilder.py index db73ce8..70ddb38 100644 --- a/utils/MessageChainBuilder.py +++ b/utils/MessageChainBuilder.py @@ -32,7 +32,7 @@ class MessageChainBuilder: atAll = False def __init__(self): - self.messageChain = [] + self._messageChain = [] self.text = '' self.at = [] self.rndImg = False @@ -131,6 +131,9 @@ def addImgBase64(self, imgbase64: Union[str, list]): self.imgPath.extend(imgbase64) return self + def getMessaheChain(self): + return self._messageChain + async def build(self) -> MessageChain: """ 构建消息链 """ messageChain = [] @@ -156,11 +159,11 @@ async def build(self) -> MessageChain: messageChain.append(Image(url=url)) if self.rndImg: if enable_countenance: - self.messageChain.append( + self._messageChain.append( await Image.from_local( filename=f"./data/reply/img/{replydata['replyimgpath']}/{random.choice(replydata['img'])}")) - if len(self.messageChain) > 0: - return MessageChain(self.messageChain) + if len(self._messageChain) > 0: + return MessageChain(self._messageChain) else: raise ValueError("消息链为空") diff --git a/utils/MessageChainSender.py b/utils/MessageChainSender.py index 8ff5e82..b48ca38 100644 --- a/utils/MessageChainSender.py +++ b/utils/MessageChainSender.py @@ -12,6 +12,7 @@ import mirai.exceptions from mirai import MessageChain, MessageEvent, GroupMessage, FriendMessage from mirai.models import MessageComponent +from mirai.models.api import MessageResponse from core import bot, bot_cfg, master from utils import root_logger @@ -21,6 +22,10 @@ _last_error_message = dict(groupmessage=dict(), friendmessage=dict(), other=dict()) +# _mahversion = await bot.about() # 获取MAH的版本 +# _mahversion = _mahversion.data.get('version')[:3] # MAH的版本我只取前三位,如'2.4','2.9' + + # # class MessageChainSender: # target: str @@ -81,6 +86,8 @@ async def messagechain_sender(msg: Union[MessageChain, str, MessageComponent], e target = grouptarget if bot.get_group(target): res = await bot.send_group_message(grouptarget, msg) + # if isinstance(res, MessageResponse): + # res = res.message_id if res == -1 and not onlyImg: await bot.send_group_message(grouptarget, errtext) # errtext += f'消息类型:GroupMessageEvent,消息目标:{grouptarget}' @@ -90,7 +97,9 @@ async def messagechain_sender(msg: Union[MessageChain, str, MessageComponent], e elif friendtarget: target = friendtarget if bot.get_friend(target): - res = await bot.send_friend_message(friendtarget, msg).message_id + res = await bot.send_friend_message(friendtarget, msg) + # if isinstance(res, MessageResponse): + # res = res.message_id if res == -1 and not onlyImg: await bot.send_group_message(friendtarget, errtext) # errtext += f'消息类型:FriendMessageEvent,消息目标:{friendtarget}' @@ -116,6 +125,11 @@ async def messagechain_sender(msg: Union[MessageChain, str, MessageComponent], e await bot.send_friend_message(master, f"向 {target} 发送消息失败,可能被禁言") print(f"向 {target} 发送消息失败,可能被禁言") root_logger.error(f"向 {target} 发送消息失败,可能被禁言") + elif _e.code == 6: + if nowtime - last_time > 3600: + await bot.send_friend_message(master, f"向 {target} 发送消息失败,指定图片不存在") + print(f"向 {target} 发送消息失败,指定图片不存在") + root_logger.error(f"向 {target} 发送消息失败,指定图片不存在\n{_e.args}") else: if nowtime - last_time > 3600: _last_error_message['groupmessage'] = dict(time=nowtime, target=target, message=msg, error=_e) diff --git a/utils/cfg_loader.py b/utils/cfg_loader.py index 1fb49db..b3e45d3 100644 --- a/utils/cfg_loader.py +++ b/utils/cfg_loader.py @@ -64,7 +64,7 @@ def write_file(content, path: str, filetype: str = None, encoding='utf-8', allow if filetype in ['yml', 'yaml']: yaml.dump(content, filecfg, allow_unicode=allow_unicode) elif filetype in ['json']: - json.dump(content, filecfg, allow_unicode=allow_unicode) + json.dump(content, filecfg, ensure_ascii=not allow_unicode) else: raise Exception("不支持的文件类型! 目前仅支持 JSON、 YML") return True diff --git a/utils/echarts.py b/utils/echarts.py index 4a0e714..51b16f4 100644 --- a/utils/echarts.py +++ b/utils/echarts.py @@ -60,10 +60,10 @@ def create_charts_from_option(option: dict, filename: str) -> dict: def create_chart(chart: RectChart, html_name, png_name, del_html=True): - make_snapshot(snapshot, chart.render(f"{html_name}.html"), f"images/MajSoulInfo/{png_name}.png") + make_snapshot(snapshot, chart.render(f"images/MajSoulInfo/{html_name}.html"), f"images/MajSoulInfo/{png_name}.png") # make_snapshot(snapshot, bar.render(f"{filename}.html"), f"{filename}.png") if del_html: - os.remove(f'{html_name}.html') + os.remove(f'images/MajSoulInfo/{html_name}.html') # return 0