Exemplo n.º 1
0
 def __init__(self, app_configs: Dict, configs: Dict):
     self.directs = {}
     self.docs = {}
     self.schedules = {}
     self.inner_commands = {}
     self.commands = {}
     self.schedule_task_list = []
     self.message_queue = Queue()
     self.command_queue = Queue()
     self.history = None
     self.loop = asyncio.get_event_loop()
     self.bcc = Broadcast(loop=self.loop)
     self.counters = [0, 0]
     if configs['debug']:
         global defaultLogger
         defaultLogger.close()
         defaultLogger = DefaultLogger(level=DEBUG)
     self.logger = defaultLogger
     self.app = GraiaMiraiApplication(broadcast=self.bcc,
                                      connect_info=Session(**app_configs),
                                      logger=self.logger,
                                      debug=configs['debug'])
     self.prefix = configs['prefix']
     self.db = Storage.load()
     self.load_mods()
Exemplo n.º 2
0
 def __init__(self, config: dict):
     if not self.__first_init:
         logger.info("Initializing")
         if any(parameter not in config
                for parameter in self.necessary_parameters):
             raise ValueError(
                 f"Missing necessary parameters! (miraiHost, authKey, BotQQ)"
             )
         self.__loop = asyncio.get_event_loop()
         self.__bcc = Broadcast(loop=self.__loop)
         self.__app = GraiaMiraiApplication(broadcast=self.__bcc,
                                            connect_info=Session(
                                                host=config["miraiHost"],
                                                authKey=config["authKey"],
                                                account=config["BotQQ"],
                                                websocket=True),
                                            enable_chat_log=False)
         self.__saya = Saya(self.__bcc)
         self.__saya.install_behaviours(BroadcastBehaviour(self.__bcc))
         self.__app.debug = False
         self.__config = config
         AppCore.__first_init = True
         logger.info("Initialize end")
     else:
         raise AppCoreAlreadyInitialized()
Exemplo n.º 3
0
 def __init__(self, account, key):
     self.loop = asyncio.get_event_loop()
     self.bcc = Broadcast(loop=self.loop)
     self.scheduler = AsyncIOScheduler()
     self.mirai = GraiaMiraiApplication(broadcast=self.bcc,
                                        connect_info=Session(
                                            host="http://localhost:8080",
                                            authKey=key,
                                            account=account,
                                            websocket=True))
Exemplo n.º 4
0
    def start(self):

        message_handler = MsgHandler()
        # message_handler.initHandler()

        loop = asyncio.get_event_loop()

        bcc = Broadcast(loop=loop)
        app = GraiaMiraiApplication(
            broadcast=bcc,
            connect_info=Session(
                host="http://*****:*****@bcc.receiver("FriendMessage")
        async def friend_message_listener(graia_app: GraiaMiraiApplication,
                                          friend: Friend,
                                          message: MessageChain):
            async def friend_sender(send_msg):
                result = await graia_app.sendFriendMessage(
                    friend, MessageChain.create([send_msg]))
                if result:
                    self.set_send_msg_flag(False)
                    threading.Timer(5.0, self.set_send_msg_flag).start()

            msg = message.asDisplay()
            log.i("receive friend message: %s" % msg)
            await message_handler.handle(msg, friend_sender, friend=friend)

        @bcc.receiver("GroupMessage")
        async def group_message_listener(graia_app: GraiaMiraiApplication,
                                         group: Group, member: Member,
                                         message: MessageChain):
            async def group_sender(send_msg):
                should_respond = True
                if member.id == aqiang_id:
                    should_respond = False

                if should_respond:
                    result = await graia_app.sendGroupMessage(
                        group, MessageChain.create([send_msg]))
                    if result:
                        self.set_send_msg_flag(False)
                        threading.Timer(5.0, self.set_send_msg_flag).start()

            msg = message.asDisplay()
            log.i("receive group message: %s" % msg)
            await message_handler.handle(msg, group_sender)

        app.launch_blocking()
Exemplo n.º 5
0
    def __init__(self, config_dict: dict, **kwargs):
        super().__init__(
            connect_info=Session(
                host=f"http://{config_dict['HOST']}:{config_dict['PORT']}",  # 填入 httpapi 服务运行的地址 # noqa
                authKey=config_dict['AUTHKEY'],  # 填入 authKey
                account=config_dict['QQ'],  # 你的机器人的 qq 号
                websocket=True  # Graia 已经可以根据所配置的消息接收的方式来保证消息接收部分的正常运作.
            ),
            **kwargs
        )
        self.logger.debug(f'加载的配置: {config_dict}')

        self.config = config_dict
Exemplo n.º 6
0
def main():
    loop = asyncio.get_event_loop()
    bcc = Broadcast(loop=loop)
    app = GraiaMiraiApplication(
        broadcast=bcc,
        connect_info=Session(
            host="http://xqh.ma:12321",  # 填入 httpapi 服务运行的地址
            authKey="ltrump923429",  # 填入 authKey
            account=3218088431,  # 你的机器人的 qq 号
            websocket=True  # Graia 已经可以根据所配置的消息接收的方式来保证消息接收部分的正常运作.
        ))
    env['app'] = app
    env['bcc'] = bcc
    load_plugins()
    app.launch_blocking()
Exemplo n.º 7
0
    def __init__(self):

        host = Util.getConfig("mirai", "host")
        port = Util.getConfig("mirai", "port")
        authKey = Util.getConfig("mirai", "authKey")
        account = Util.getConfig("mirai", "account")
        url = "http://" + "{}:{}".format(host, port)
        self.app = GraiaMiraiApplication(
            broadcast=bcc,
            connect_info=Session(
                host=url,  # 填入 httpapi 服务运行的地址
                authKey=authKey,  # 填入 authKey
                account=account,  # 你的机器人的 qq 号
                websocket=False  # Graia `已经可以根据所配置的消息接收的方式来保证消息接收部分的正常运作.
            ))
Exemplo n.º 8
0
        for dirpath, dirnames, filenames in os.walk(folderspach):
            for file in filenames:
                filepachs.append(folderspach + '/' + file)
    setulen = len(filepachs)
    if filepachs == []:print('没有找到色图')
    else:print('色图载入成功')
except Exception:
    print('色图载入错误')
print('读取配置完成')
loop = asyncio.get_event_loop()
bcc = Broadcast(loop=loop)
app = GraiaMiraiApplication(
    broadcast=bcc,
    connect_info=Session(
        host=host_,
        authKey=authkey,
        account=bot_qq,
        websocket=True
    )
)
def sdir(tdir):
    if not os.path.exists(tdir):
        print('新建目录:',tdir)
        os.makedirs(tdir)
def restart_program():
    python = sys.executable
    os.execl(python, python, * sys.argv)
def savecfg():
    try:
        jsonfile=open("cfg.json","w")
        json.dump(cfg,jsonfile,indent=4)
        jsonfile.close()
Exemplo n.º 9
0
if os.path.exists("config.ini"):
    conf = configparser.ConfigParser()
    conf.read("setting.ini")
    api_url = conf.get("API", "API", fallback='http://*****:*****@bcc.receiver("FriendMessage")
async def group_message_handler(message: MessageChain, friend: Friend,
                                graia_app: GraiaMiraiApplication):
    if message.has(Plain):
        request_text = message[Plain][0].text  # 获取传来的数据的要求
        request_parm = request_text.split()  # 将传来的数据split开
        if len(request_parm) > 1:  # 当传来的request可以分为多于一个值的时候
            if request_parm[0].lower() == "search":  # 如果第一个单词是search,则执行查询论文指令
                # 解析传入的查询信息
                search_flag = "query"
                search = {"key": "all", "strict": False, "page": '1'}
import asyncio
from os.path import abspath

from graia.application import GraiaMiraiApplication, Session
from graia.broadcast import Broadcast

from config import config

loop = asyncio.get_event_loop()
config_filename = 'config.cfg'
config_path = abspath('./config/' + config_filename)


def c(q):
    return config(config_path, q)


bcc = Broadcast(loop=loop, debug_flag=c('debug_flag'))
app = GraiaMiraiApplication(
    broadcast=bcc,
    enable_chat_log=c('enable_chat_log'),
    connect_info=Session(
        host=c('host'),  # 填入 httpapi 服务运行的地址
        authKey=c('authkey'),  # 填入 authKey
        account=c('account'),  # 你的机器人的 qq 号
        websocket=c('websocket')  # Graia 已经可以根据所配置的消息接收的方式来保证消息接收部分的正常运作.
    ))
Exemplo n.º 11
0
start_baiDu_group = []
mast_manager_group = []
quick_find_question_list = {}
shutdown_all_group = []
loop = asyncio.get_event_loop()  # 获取bot运行的协程

json_config = {}

bcc = Broadcast(loop=loop)

app = GraiaMiraiApplication(
    broadcast=bcc,
    connect_info=Session(
        host=API_ROOT,  # httpapi 服务运行的地址
        authKey=AuthKey,  # authKey
        account=BOTQQ,  # 机器人的 qq 号
        websocket=True  # Graia 已经可以根据所配置的消息接收的方式来保证消息接收部分的正常运作.
    ))


async def ReadConfig():
    try:
        with open('config.json', 'r') as f:
            global json_config
            json_config = json.load(f).copy()
            if 'baiDu_group' in json_config.keys():
                for i in json_config['baiDu_group']:
                    start_baiDu_group.append(i)
            if 'shutdown_all_group' in json_config.keys():
                for i in json_config['shutdown_all_group']:
                    shutdown_all_group.append(i)
Exemplo n.º 12
0
from graia.application.event.lifecycle import ApplicationLaunched, ApplicationShutdowned
from graia.broadcast import Broadcast

from handler import *
from handler.handler_manager import HandlerManager
from pixiv import start_auto_auth, start_search_helper, start_illust_cacher, stop_illust_cacher, stop_search_helper
from utils import settings, start_reply_queue, stop_reply_queue, LoguruWarpper

loop = asyncio.get_event_loop()
bcc = Broadcast(loop=loop)
app = GraiaMiraiApplication(
    broadcast=bcc,
    connect_info=Session(
        host=
        f"""http://{settings["mirai"]["host"]}:{settings["mirai"]["port"]}""",  # 填入 httpapi 服务运行的地址
        authKey=settings["mirai"]["auth_key"],  # 填入 authKey
        account=int(settings["mirai"]["qq"]),  # 你的机器人的 qq 号
        # Graia 已经可以根据所配置的消息接收的方式来保证消息接收部分的正常运作.
        websocket=settings["mirai"]["enable_websocket"]),
    logger=LoguruWarpper())

manager = HandlerManager(bcc)
manager.register(HelpQueryHandler(tag="help query", settings=settings["help"]),
                 priority=settings["function"]["priority"]["help"],
                 allow_friend=settings["function"]["friend"]["listen"]
                 if settings["function"]["friend"]["help"] else [],
                 allow_group=settings["function"]["group"]["listen"]
                 if settings["function"]["group"]["help"] else [])
manager.register(PixivRankingQueryHandler(tag="ranking query",
                                          settings=settings["ranking"]),
                 priority=settings["function"]["priority"]["ranking"],
Exemplo n.º 13
0
    r = requests.post(url, params=payload, headers=headers)
    rr = r.json()
    return rr['trans_result'][0]['dst']


def ai(ms):
    r = requests.get(
        f'http://api.qingyunke.com/api.php?key=free&appid=0&msg={ms}').json()
    return re.sub('''{br}''', '\n', r['content'])


loop = asyncio.get_event_loop()
bcc = Broadcast(loop=loop)
app = GraiaMiraiApplication(broadcast=bcc,
                            connect_info=Session(host="http://*****:*****@bcc.receiver("FriendMessage")
async def deff(
    message: MessageChain,
    app: GraiaMiraiApplication,
    friend: Friend,
):
    fll = 0
    for mme in range(1, 10):
        if message.asDisplay().startswith('xx' + str(mme)):
            await app.sendFriendMessage(friend,
                                        MessageChain.create([Plain(kkb(mme))]))
            fll = 1
Exemplo n.º 14
0
    menu += "5. [获取某个人微博内容]             格式:      /微博 昵称 数量[1~3|默认为2|0表示只获取个人信息]\n"
    menu += "6. [监控某个人的微博,有新动态在第一时间提醒您]           /[具体请联系Owner]\n"
    menu += "7. [爬取B站视频, 默认清晰度为1080P]                格式:       /B站 BV号\n"
    menu += "8. [未完待续……]\n"
    menu += "您有什么需要尽管吩咐, 但要自觉遵守输入规则哦~~"
    return menu


city_code_dict = getWeather.get_city_code()
loop = asyncio.get_event_loop()
bcc = Broadcast(loop=loop)
app = GraiaMiraiApplication(
    broadcast=bcc,
    connect_info=Session(
        host=myconfigs["host"],  # 填入 httpapi 服务运行的地址
        authKey=myconfigs["authKey"],  # 填入 authKey
        account=myconfigs["account"],  # 机器人的 qq 号
        websocket=True  # Graia 已经可以根据所配置的消息接收的方式来保证消息接收部分的正常运作.
    ))

inc = InterruptControl(bcc)
blog_id_set = set()

# async def init_blog_id_set(blog_id_set : Set):
#     try:
#         with open("blog_id.txt", 'r') as file:
#             for line in file:
#                 tempStr = re.sub(r'\n', '', line)
#                 blog_id_set.add(tempStr)
#     except:
#         pass
#     print(blog_id_set)
Exemplo n.º 15
0
    def MiraiRun(self):
        Cfg = self.RecorderInstance.GetConfig

        asyncio.set_event_loop(asyncio.new_event_loop())
        loop = asyncio.get_event_loop()

        bcc = Broadcast(loop=loop)
        app = GraiaMiraiApplication(
            broadcast=bcc,
            connect_info=Session(
                host="http://" + Cfg().
                plugin_notifybot_mirai_api_http_locate,  # 填入 httpapi 服务运行的地址
                authKey=Cfg().plugin_notifybot_authkey,  # 填入 authKey
                account=Cfg().plugin_notifybot_qq_number,  # 你的机器人的 qq 号
                websocket=True  # Graia 已经可以根据所配置的消息接收的方式来保证消息接收部分的正常运作.
            ))

        @bcc.receiver("FriendMessage")
        async def event_fm(app: GraiaMiraiApplication, friend: Friend,
                           msg: MessageChain):
            self.PrintLog("Receive friend message: " + str(msg))
            for Callback in self.RecorderInstance.GetCallbackCollection(
                    "QQInterface", "OnFriendMessage"):
                try:
                    Callback(room_info)
                except Exception as pe:
                    self.PrintLog("Plugin exception: " + repr(e))
                    traceback.print_exc()
            await app.sendFriendMessage(
                friend, MessageChain.create([Plain(text="机器人没有私聊功能")]))

        def GetSelfName():
            Names = Cfg().plugin_notifybot_say_selfname
            if len(Names) > 0:
                return Names[random.randint(0, len(Names) - 1)]
            else:
                return ""

        def GetCalendarMessage():
            try:
                TxtResult = []
                CalData = self.requirements[
                    "RoomPollingClient"].GetLiveCalendar()
                ts = CalData["now"]
                rts = datetime.datetime.fromtimestamp(ts)

                prog_today_passed = None
                prog_scheduled = None
                for prog in CalData["programs"]:
                    prog_ts = prog["ts"]
                    prog_rts = datetime.datetime.fromtimestamp(prog_ts)
                    if prog_ts < ts and prog_rts.day == rts.day:
                        prog_today_passed = prog
                    if prog_ts >= ts:
                        prog_scheduled = prog
                        break
                TxtResult.append("让我康康直播日历,")
                if prog_scheduled:
                    prog_ts = prog_scheduled["ts"]
                    prog_rts = datetime.datetime.fromtimestamp(prog_ts)
                    if prog_rts.day == rts.day:
                        TxtResult.append("今天 " + prog_rts.strftime("%H:%M") +
                                         " 有直播哦!标题:" + prog_scheduled["title"])
                    else:
                        if prog_today_passed:
                            TxtResult.append("今天播过了!标题:" +
                                             prog_today_passed["title"])
                            TxtResult.append("今天接下来没有了!下一场:" +
                                             prog_rts.strftime("%m-%d %H:%M") +
                                             " 标题:" + prog_scheduled["title"])
                        else:
                            TxtResult.append("今天没有!下一场:" +
                                             prog_rts.strftime("%m-%d %H:%M") +
                                             " 标题:" + prog_scheduled["title"])
                else:
                    if prog_today_passed:
                        TxtResult.append("今天播过了!标题:" +
                                         prog_today_passed["title"])
                        TxtResult.append("之后的日历全是空的!")
                    else:
                        TxtResult.append("今天没有!之后的日历也全是空的!")
                return "\n".join(TxtResult)
            except Exception as e:
                self.PrintLog("Query calendar failed: " + repr(e))
                traceback.print_exc()
                return "不知道咋回事,出错了"

        def IsInvolved(msg):
            for i in msg.get(At):
                if i.target == Cfg().plugin_notifybot_qq_number:
                    return True
            return False

        async def ProcessRevoke(group, msg):
            Ret = False
            if IsInvolved(msg):
                msgtxt = msg.asDisplay()
                if "撤回" in msgtxt:
                    if self.LastSentMsgId[group.id] != 0:
                        await app.revokeMessage(self.LastSentMsgId[group.id])
                    self.LastSentMsgId[group.id] = 0
                    Ret = True
            return Ret

        async def SendGroupMsg(group, msg):
            BotMsg = await app.sendGroupMessage(group,
                                                MessageChain.create(msg))
            self.LastSentMsgId[group] = BotMsg.messageId

        async def ProcessAnyLiveMsg(group, msg):
            Ret = False
            msgtxt = msg.asDisplay()
            Matched = False
            for Keyword in Cfg().plugin_notifybot_recognise_selfname:
                if Keyword in msgtxt:
                    if "播吗" in msgtxt:
                        Matched = True
                        break
                    if "播嘛" in msgtxt:
                        Matched = True
                        break
            for Keyword in Cfg().plugin_notifybot_anylive_keyword:
                if Keyword in msgtxt:
                    Matched = True
                    break
            if Matched == True:
                if (datetime.datetime.now() -
                        self.LastAnyLiveReportTime[group.id]).seconds > 60:
                    await SendGroupMsg(group.id, [Plain(GetCalendarMessage())])
                    Ret = True
                self.LastAnyLiveReportTime[group.id] = datetime.datetime.now()
            return Ret

        async def ProcessConversations(group, member, msg):
            Ret = False
            SenderID = member.id
            if Cfg().plugin_notifybot_conversation_blacklist.__contains__(
                    SenderID):
                if random.random() >= Cfg(
                ).plugin_notifybot_conversation_blacklist[SenderID]:
                    return Ret
            msgtxt = msg.asDisplay()
            for Conv in Cfg().plugin_notifybot_conversations:
                IsKeywordFound = False
                for Keyword in Conv[0]:
                    if Keyword in msgtxt:
                        IsKeywordFound = True
                        break
                if IsKeywordFound == True:
                    if len(Conv[1]) != 0:
                        while True:
                            RandItem = Conv[1][random.randint(
                                0,
                                len(Conv[1]) - 1)]
                            if random.random() <= RandItem[0]:
                                if RandItem[1] != "":
                                    NewOvertalkCounter = self.OvertalkCounter[
                                        group.id] - (datetime.datetime.now(
                                        ) - self.LastTalkTime[group.id]
                                                     ).seconds / 60
                                    if NewOvertalkCounter < 0:
                                        NewOvertalkCounter = 0
                                    NewOvertalkCounter += 1
                                    self.LastTalkTime[
                                        group.id] = datetime.datetime.now()
                                    if NewOvertalkCounter > Cfg(
                                    ).plugin_notifybot_overtalk_threshold:
                                        if self.OvertalkCounter[group.id] <= Cfg(
                                        ).plugin_notifybot_overtalk_threshold:
                                            await SendGroupMsg(
                                                group.id, [
                                                    Plain(
                                                        emoji.
                                                        emojize(Cfg(
                                                        ).plugin_notifybot_overtalk_word,
                                                                use_aliases=True
                                                                ))
                                                ])
                                    else:
                                        await SendGroupMsg(
                                            group.id, [
                                                Plain(
                                                    emoji.emojize(
                                                        RandItem[1],
                                                        use_aliases=True))
                                            ])
                                    self.OvertalkCounter[
                                        group.id] = NewOvertalkCounter
                                    Ret = True
                                break
                    break
            return Ret

        async def ProcessRepeat(group, msg):
            Ret = False
            msgtxt = msg.include(Plain, Face, Image).asSerializationString()
            if msgtxt == self.LastRepeatMsg[group.id]:
                Matched = False
                for Keyword in Cfg().plugin_notifybot_repeat_keyword:
                    if Keyword in msgtxt:
                        if random.random() < Cfg(
                        ).plugin_notifybot_repeat_keyword_prob:
                            Matched = True
                        break
                if random.random() < Cfg().plugin_notifybot_repeat_prob:
                    Matched = True
                for Keyword in Cfg().plugin_notifybot_repeat_blacklist:
                    if Keyword in msgtxt:
                        Matched = False
                        break
                if Matched == True:
                    NewMsg = msg.include(Face, Plain, Image).__root__
                    if len(NewMsg):
                        await SendGroupMsg(group.id, NewMsg)
                        Ret = True
            self.LastRepeatMsg[group.id] = msgtxt
            return Ret

        @bcc.receiver("GroupMessage")
        async def event_gm(app: GraiaMiraiApplication, group: Group,
                           member: Member, msg: MessageChain):
            try:
                if Cfg().plugin_notifybot_group_number.__contains__(group.id):
                    MsgSent = False
                    if MsgSent == False:
                        MsgSent = await ProcessRevoke(group, msg)
                    if MsgSent == False:
                        MsgSent = await ProcessAnyLiveMsg(group, msg)
                    if MsgSent == False:
                        MsgSent = await ProcessConversations(
                            group, member, msg)
                    if MsgSent == False:
                        MsgSent = await ProcessRepeat(group, msg)
            except Exception as e:
                self.PrintLog("Exception in gm processing: " + repr(e))
                traceback.print_exc()

        @bcc.receiver("TempMessage")
        async def event_tm(app: GraiaMiraiApplication, group: Group,
                           member: Member, msg: MessageChain):
            await app.sendTempMessage(
                group, member, MessageChain.create([Plain(text="机器人没有私聊功能")]))

        async def SendLiveOnMessageAsync():
            for Grp in Cfg().plugin_notifybot_group_number:
                if Cfg().plugin_notifybot_atall:
                    Message = [
                        Plain(text=GetSelfName() + "开播了! " +
                              self.RecorderInstance.GetRoomTitle() +
                              "https://live.bilibili.com/" +
                              self.RecorderInstance.room_id),
                        AtAll()
                    ]
                else:
                    Message = [
                        Plain(text=GetSelfName() + "开播了! " +
                              self.RecorderInstance.GetRoomTitle() +
                              "https://live.bilibili.com/" +
                              self.RecorderInstance.room_id),
                    ]
                try:
                    await SendGroupMsg(Grp, Message)
                except Exception as e:
                    self.PrintLog("Send QQ live notify message failed: " +
                                  repr(e))
                    traceback.print_exc()

        def SendLiveOnMessage():
            try:
                fut = asyncio.run_coroutine_threadsafe(
                    SendLiveOnMessageAsync(), loop)
            except Exception as e:
                self.PrintLog("Send QQ live notify message failed: " + repr(e))
                traceback.print_exc()

        def ProcessLiveStartEvent(FileNameGen):
            t = threading.Thread(target=SendLiveOnMessage)
            t.daemon = True
            t.start()

        async def SendDiskWarningMessageAsync():
            for MgrQQ in Cfg().plugin_notifybot_manager_qq_number:
                try:
                    await app.sendFriendMessage(
                        MgrQQ, MessageChain.create([Plain(text="磁盘空间紧张!")]))
                    await asyncio.sleep(2)
                except Exception as e:
                    self.PrintLog("Send disk warning message failed: " +
                                  repr(e))
                    traceback.print_exc()

        def DiskWarning():
            try:
                fut = asyncio.run_coroutine_threadsafe(
                    SendDiskWarningMessageAsync(), loop)
            except Exception as e:
                self.PrintLog("Send disk warning message failed: " + repr(e))
                traceback.print_exc()

        self.app = app

        self.RecorderInstance.RegisterCallback("RecorderInstance",
                                               "OnLiveStart",
                                               ProcessLiveStartEvent)
        self.RecorderInstance.RegisterCallback("DiskSpaceMonitor", "OnWarning",
                                               DiskWarning)

        self.LastAnyLiveReportTime = {}
        self.LastTalkTime = {}
        self.OvertalkCounter = {}
        self.LastSentMsgId = {}
        self.LastRepeatMsg = {}
        for GrpNum in Cfg().plugin_notifybot_group_number:
            self.LastAnyLiveReportTime[
                GrpNum] = datetime.datetime.fromtimestamp(0)
            self.LastTalkTime[GrpNum] = datetime.datetime.now()
            self.OvertalkCounter[GrpNum] = 0
            self.LastSentMsgId[GrpNum] = 0
            self.LastRepeatMsg[GrpNum] = ""

        app.launch_blocking()
Exemplo n.º 16
0
    '[%(levelname)s][%(asctime)s][%(filename)s]at line:%(lineno)d %(message)s',
    datefmt='%D %H:%M:%S')

logging.info("Starting QQ bot, please wait.")

# bot
loop = asyncio.get_event_loop()

# Config mirai bot
mirai_config = util.config_mirai
logging.info(f"Config Mirai HTTP API:{mirai_config['host']}")
bcc = Broadcast(loop=loop)
app = GraiaMiraiApplication(broadcast=bcc,
                            connect_info=Session(
                                host=mirai_config["host"],
                                authKey=mirai_config["authKey"],
                                account=int(mirai_config["account"]),
                                websocket=mirai_config["webSocket"]))


@bcc.receiver("GroupMessage")
async def group_message_handler(bot_app: GraiaMiraiApplication,
                                message: MessageChain, group: Group):
    # TODO([email protected]): Use "Middle Ware"
    # Only spy groups in config file.
    if str(group.id) in util.config_group:
        logging.info(f"Detected message from group: {str(group.id)}")
        print(message)
        # Interpreter commands input.
        input_msg = message.asDisplay()
Exemplo n.º 17
0
from graia.application import GraiaMiraiApplication, Session
from graia.broadcast import Broadcast
import asyncio
from config import *

loop = asyncio.get_event_loop()
bcc = Broadcast(loop=loop)
app = GraiaMiraiApplication(
    broadcast=bcc,
    connect_info=Session(
        host=HOST,  # 填入http api服务运行的地址
        authKey=AUTHKEY,  # 填入 authKey
        account=ACCOUNT,  # 你的机器人的 qq 号
        websocket=True  # Graia 已经可以根据所配置的消息接收的方式来保证消息接收部分的正常运作.
    ))
Exemplo n.º 18
0
from graia.application.message.chain import MessageChain
from graia.application.message.elements.internal import Plain
from graia.broadcast import Broadcast

from BaiduOCRApi import pic_to_word
from BaiduTran import translation
from Forecast import forecast

loop = asyncio.get_event_loop()

bcc = Broadcast(loop=loop)
app = GraiaMiraiApplication(
    broadcast=bcc,
    connect_info=Session(
        host="http://*****:*****@bcc.receiver("FriendMessage")
async def friend_message_listener(app: GraiaMiraiApplication, friend: Friend):
    print(friend)
    await app.sendFriendMessage(friend,
                                MessageChain.create([Plain("Hello, World!")]))


@bcc.receiver("GroupMessage")
async def friend_message_listener(message: MessageChain,
                                  app: GraiaMiraiApplication, group: Group):
    print(message.__root__)  # 字符串在[1], 时间信息在[0], 图像在[2], 如果只有图像没有图片,则图像在[1]
Exemplo n.º 19
0
from graia.broadcast import Broadcast
from graia.application.entry import Friend, FriendMessage, MessageChain, Group, GroupMessage, Plain
from graia.application.entry import ApplicationLaunched, MemberMuteEvent, At, MemberUnmuteEvent, Member

import yaml
import aiohttp

# 包含mirai-api-http的配置文件中的对应部分以及qq号
with open('setting.yml') as f:
    setting = yaml.load(f, yaml.BaseLoader)
loop = asyncio.get_event_loop()
bcc = Broadcast(loop=loop)
app = GraiaApp(broadcast=bcc,
               connect_info=Session(
                   host=f"http://{setting['host']}:{setting['port']}",
                   authKey=f"{setting['authKey']}",
                   account=setting['qq'],
                   websocket=setting['enableWebsocket']))


# 复读
# @bcc.receiver(FriendMessage)
async def echoer(app: GraiaApp, message: MessageChain, friend: Friend):
    if message.asDisplay().startswith("复读"):
        await app.sendFriendMessage(friend, message.asSendable())


echoer = bcc.receiver(FriendMessage)(echoer)  # 如果不用修饰器

TEST_GROUP_LIST = [943603660]
Exemplo n.º 20
0
loop = asyncio.get_event_loop()

bcc = Broadcast(loop=loop)
sche = GraiaScheduler(loop=loop, broadcast=bcc)

with open('config.json', 'r', encoding='utf-8') as f:  # 从json读配置
    configs = json.loads(f.read())

if configs["highPerformance"]:
    from SAGIRIBOT.high_performances.porn_identification import porn_identification
    from SAGIRIBOT.basics.tools import save_img

app = GraiaMiraiApplication(broadcast=bcc,
                            connect_info=Session(host=configs["miraiHost"],
                                                 authKey=configs["authKey"],
                                                 account=configs["BotQQ"],
                                                 websocket=True))

# 复读判断
group_repeat = dict()
tasks = Queue()
lock = threading.Lock()
frequency_limit_dict = {}
frequency_limit_instance = None
exception_resender_instance = None


# async def group_message_sender(message_info: GroupMessage, message: list, group: Group,
#                                app: GraiaMiraiApplication) -> None:
#     message_send = await group_message_process(message, message_info, app)
#     await group_assist_process(message, message_info, message_send, group)
Exemplo n.º 21
0
from function.live import getlive, liveend, livechange

loop = asyncio.get_event_loop()
info = {}

ua = Faker()
headers = {'User-Agent': str(ua.user_agent)}
global null
null = ''
groups = [372733015, 875626950, 766517688, 862315052, 729801800]
bcc = Broadcast(loop=loop)
app = GraiaMiraiApplication(
    broadcast=bcc,
    connect_info=Session(
        host="http://42.193.102.81:8080",  # 填入 httpapi 服务运行的地址
        authKey="myon759572692",  # 填入 authKey
        account=2157510360,  # 你的机器人的 qq 号
        websocket=True  # Graia 已经可以根据所配置的消息接收的方式来保证消息接收部分的正常运作.
    ))
inc = InterruptControl(bcc)

bvpattern = re.compile(r'BV1[1-9A-NP-Za-km-z]{9}')


@bcc.receiver(GroupMessage)
async def group_message_handler(app: GraiaMiraiApplication,
                                message: MessageChain, group: Group,
                                member: Member):

    url = ""
    b23_url = ""  # 先申请好两种要用的url
    if Msg_element.Xml in message:
Exemplo n.º 22
0
            char = "凯尔希.png"
        elif tmp < 0.8:
            char = "浊心斯卡蒂.png"
    if up:
        if random.random() <= 0.5 and up + ".png" in chars:
            char = up + ".png"
    return rarity, char


loop = asyncio.get_event_loop()
bcc = Broadcast(loop=loop)
app = GraiaMiraiApplication(
    broadcast=bcc,
    connect_info=Session(
        host="http://*****:*****@bcc.receiver("GroupMessage")
async def group_message_listener(app: GraiaMiraiApplication, group: Group,
                                 message: MessageChain, member: Member):
    if message.asDisplay() == "单抽":
        times = user.get_times(member.id)
        rarity, char = await gacha(times=times)
        await user.change(member.id, member.name, rarity, char)
        await app.sendGroupMessage(
            group,
            MessageChain.create([
                Image.fromLocalFile("chars/{}/{}".format(rarity, char)),
Exemplo n.º 23
0
from graia.application import GraiaMiraiApplication, Session
from graia.application.entry import MemberJoinRequestEvent, MessageChain, Plain
from graia.broadcast import Broadcast
from graia.broadcast.builtin.decoraters import Depend
from graia.broadcast.exceptions import ExecutionStop

from chancechecker import chanceChecker
from verifyuid import verifyQmailUid

# Application & BCC 初始化
loop = asyncio.get_event_loop()
bcc = Broadcast(loop=loop)
app = GraiaMiraiApplication(broadcast=bcc,
                            connect_info=Session(
                                host=os.environ['graia-host'],
                                authKey=os.environ['graia-authkey'],
                                account=int(os.environ['graia-account']),
                                websocket=True),
                            enable_chat_log=False
                            )


class qqGroup(object):
    '''QQ 群号'''
    main = 586146922  # 主用户群
    cafe = 651672723  # 咖啡馆
    admins = 985317265  # 运营组


workInGroups = [qqGroup.main, qqGroup.cafe]  # 在这些群内工作
Exemplo n.º 24
0
loop = asyncio.get_event_loop()
bcc = Broadcast(loop=loop)
saya = Saya(bcc)

config_path = Path("config.yaml")
if not config_path.is_file():
    config_path.write_text(Path("config.yaml.sample").read_text())
    sys.exit(1)
config = yaml.load(config_path.read_text(), Loader=SafeLoader)

saya.install_behaviours(BroadcastBehaviour(bcc))
app = GraiaMiraiApplication(
    broadcast=bcc,
    connect_info=Session(
        host=config["mirai"]["host"],
        authKey=config["mirai"]["authKey"],
        account=config["mirai"]["account"],
        websocket=config["mirai"]["websocket"],
    ),
)

with saya.module_context():
    for i in get_all_package_name("functions/"):
        saya.require("functions.{}".format(i), config)

try:
    app.launch_blocking()
except KeyboardInterrupt:
    sys.exit()
Exemplo n.º 25
0
from graia.application.friend import Friend
from graia.application.group import Group, Member
from graia.application.message.chain import MessageChain
from graia.application.message.elements.internal import Source, Plain, At, Image, Face
from graia.broadcast import Broadcast

from commands import std, easter_eggs
from config import host, auth_key, account, database_path, information_groups
from icu.decorator import command
from icu.database import Database

loop = asyncio.get_event_loop()
bcc = Broadcast(loop=loop)
app = GraiaMiraiApplication(broadcast=bcc,
                            connect_info=Session(host=host,
                                                 authKey=auth_key,
                                                 account=account,
                                                 websocket=True))

database = Database(database_path)
command.register(
    registers=(
        std.register_common_commands,
        std.register_database_commands,
        easter_eggs.register_common_commands,
    ),
    database=database,
)
# average_message_length,用于判断大喘气:member_id, length, count
aml = collections.defaultdict(lambda: [0, 0, 0])

Exemplo n.º 26
0
import asyncio
from pathlib import Path
from graia.application import GraiaMiraiApplication, Session
from graia.application.message.chain import MessageChain
from graia.application.group import Group
from graia.broadcast import Broadcast
from graia.application.message.elements.internal import Image
loop = asyncio.get_event_loop()

bcc = Broadcast(loop=loop)
app = GraiaMiraiApplication(
    broadcast=bcc,
    connect_info=Session(
        host="http://127.0.0.1:8080", # 填入 httpapi 服务运行的地址
        authKey="1234567890", # 填入 authKey
        account=554568768, # 你的机器人的 qq 号
        websocket=False # Graia 已经可以根据所配置的消息接收的方式来保证消息接收部分的正常运作.
    )
)

@bcc.receiver("GroupMessage")

async def group_message_handler(app: GraiaMiraiApplication, message: MessageChain, group: Group):
    if message.asDisplay().startswith("本地"):
        await app.sendGroupMessage(group, MessageChain.create([
            Image.fromLocalFile(az) #在这输入你的本地路径
        ]))
        


Exemplo n.º 27
0
from SAGIRIBOT.functions.petpet import petpet
from SAGIRIBOT.functions.get_abbreviation_explain import get_abbreviation_explain

loop = asyncio.get_event_loop()

bcc = Broadcast(loop=loop)
sche = GraiaScheduler(loop=loop, broadcast=bcc)

with open('config.json', 'r', encoding='utf-8') as f:  # 从json读配置
    configs = json.loads(f.read())

app = GraiaMiraiApplication(
    broadcast=bcc,
    connect_info=Session(
        host="http://localhost:8080",
        authKey="1234567890",
        account=configs["BotQQ"],
        websocket=True
    )
)

# 复读判断
group_repeat = dict()
tasks = Queue()
lock=threading.Lock()


# async def group_message_sender(message_info: GroupMessage, message: list, group: Group,
#                                app: GraiaMiraiApplication) -> None:
#     message_send = await group_message_process(message, message_info, app)
#     await group_assist_process(message, message_info, message_send, group)
Exemplo n.º 28
0
import AutoUpdate
import logging
import json

logging.basicConfig(level=logging.INFO)

loop = asyncio.get_event_loop()

with open('./config.json', encoding='utf-8') as config_file:
    config = json.load(config_file)

bcc = Broadcast(loop=loop)
app = GraiaMiraiApplication(broadcast=bcc,
                            connect_info=Session(
                                host='http://*****:*****@bcc.receiver("GroupMessage")
Exemplo n.º 29
0
import tenxun_voice
import huangli
import Tao

config = configparser.ConfigParser() # ini类实例化
loop = asyncio.get_event_loop()

config.read("tao.ini")
bcc = Broadcast(loop=loop)


app = GraiaMiraiApplication(
    broadcast=bcc,
    connect_info=Session(
        host="{}:{}".format(config['connect_mirai']['host'],config['connect_mirai']['port']),  # 填入 httpapi 服务运行的地址
        authKey=config['connect_mirai']['authKey'],  # 填入 authKey
        account=config.getint('connect_mirai','account'),  # 机器人的 qq 号
        websocket=config.getboolean('connect_mirai','websocket')  # Graia 已经可以根据所配置的消息接收的方式来保证消息接收部分的正常运作.
    ),
    logger=log.CustomLogger() #继承日志输出的抽象调用方法
)
inc =InterruptControl(bcc)

async def netease_cloud_music_hot(some,*member):
    send_message = MessageChain.create([Plain(wangyiyun.reping())])
    if member[0] == ():
        await app.sendFriendMessage(some, send_message)
    else:
        at = MessageChain.create([At(member[0][0].id)])
        await app.sendGroupMessage(some,MessageChain.join(at,send_message))

async def netease_cloud_music_get(some,rmsg,*member):
Exemplo n.º 30
0
from graia.application.event.mirai import NewFriendRequestEvent
from graia.application.message.chain import MessageChain
from graia.application.message.elements.internal import Plain, Image
from graia.application.friend import Friend
from graia.application.group import Group, Member
from graia.broadcast import Broadcast

loop = asyncio.get_event_loop()

bcc = Broadcast(loop=loop)

qqClient = GraiaMiraiApplication(
    broadcast=bcc,
    connect_info=Session(
        host="http://0.0.0.0:8080",  # 填入 httpapi 服务运行的地址
        authKey="INITKEYjzSpjHUR",  # 填入 authKey
        account=3277619822,  # 你的机器人的 qq 号
        websocket=True  # Graia 已经可以根据所配置的消息接收的方式来保证消息接收部分的正常运作.
    ),
    enable_chat_log=True)


class QQChan:
    def __init__(self):
        self.lock = asyncio.Lock()
        self.group = None
        self.member = None

    def SetId(self, group, member):
        self.group = group
        self.member = member