コード例 #1
0
 def __init__(self, auth_key: str, host: str, port: int, qq: int):
     logging.info("Using Mirai backend")
     self.auth_key = auth_key
     self.host = host
     self.port = port
     self.qq = qq
     self.mirai_instance = Mirai(qq=self.qq,
                                 host=f"http://{self.host}:{self.port}",
                                 authKey=self.auth_key)
     self._api = Api(self.mirai_instance)
     self.server_app = Quart(__name__)
コード例 #2
0
ファイル: __init__.py プロジェクト: leinlin/MiraiBot
async def execute(app: Mirai, monitor: Monitor) -> None:
    # noinspection PyBroadException
    try:
        resp, groups = await monitor.run()
        if resp:
            EventLogger.info(f'{resp.name}直播:{resp.url}')

            if resp.cover:
                cover: Image = await app.uploadImage("group", await Image.fromRemote(resp.cover))
                components = [Plain(f'(直播){resp.name}: {resp.title}\n{resp.url}\n'), cover]
            else:
                components = [Plain(f'(直播){resp.name}: {resp.title}\n{resp.url}')]

            tasks = [asyncio.create_task(
                app.sendGroupMessage(group=group_id, message=components)
            ) for group_id in groups]

            done, pending = await asyncio.wait(tasks)
            for task in done:
                if e := task.exception():
                    EventLogger.error(e)

    except ChannelResolveError as e:
        EventLogger.warning(e)
    except Exception:
        EventLogger.error(traceback.format_exc())
コード例 #3
0
ファイル: __init__.py プロジェクト: weearc/MiraiBot
async def execute(app: Mirai) -> None:
    delay = 10
    while True:
        targets = Database.load().__root__
        if not targets:
            await asyncio.sleep(delay)
            continue
        for target in targets:
            if target.groups:
                try:
                    await asyncio.sleep(delay)
                    resp = await getDynamicStatus(target.uid)
                    if resp:
                        footer = f"\n\n动态地址: https://t.bilibili.com/{resp.dynamic_id}"
                        EventLogger.info(
                            f'{target.name}动态更新:https://t.bilibili.com/{resp.dynamic_id}'
                        )
                        # noinspection PyTypeChecker,PydanticTypeChecker
                        components = [Plain(resp.msg)] + \
                                     [await app.uploadImage(
                                         'group', await Image.fromRemote(url)
                                     ) for url in resp.imgs] + \
                                     [Plain(footer)]
                        [
                            asyncio.create_task(
                                app.sendGroupMessage(group=group_id,
                                                     message=components))
                            for group_id in target.groups
                        ]
                except Exception as e:
                    EventLogger.error(f'动态检查出错:{target.name} {e}')
                    EventLogger.error(traceback.format_exc())
                    continue
コード例 #4
0
async def GMHandler(app: Mirai, group:Group, message:MessageChain, member:Member):
    sender=member.id
    groupId=member.group.id
    print("来自群%s("%getSetting(groupId,"groupName"),groupId,")中成员%s("%qq2name(MemberList[groupId],sender),sender,")的消息:",message.toString(),sep='')
    if message.hasComponent(Image) and getSearchReady(groupId,sender):
        await app.sendGroupMessage(group,[
            At(target=sender),
            Plain(text="正在搜索请稍后呐~没反应了可能就是卡了呐~多等等呐~")
        ])
    Msg= await Process(message,groupId,sender)
    if Msg=="noneReply":
        pass
    else:
        msg = await app.sendGroupMessage(group,Msg)
        if getSetting(groupId,"r18"):
            app.revokeMessage(msg)
コード例 #5
0
ファイル: __init__.py プロジェクト: weearc/Ptilopsis
  def __init__(self,
    app: Mirai,
    listen_events: List[str] = [
      "FriendMessage",
      "GroupMessage"
    ],
    command_prefix: List[str] = [">"],
    global_dependencies: List[Depend] = [],
    global_middlewares: List = []
  ):
    self.application = app
    self.listen_events = listen_events
    self.command_prefix = [re.escape(i) for i in command_prefix]

    self.global_dependencies = global_dependencies
    self.global_middlewares = global_middlewares
    if "^/" in self.command_prefix:
      SessionLogger.warn("you shouldn't use '/' as a prefix, because it's used by mirai-console...")
      SessionLogger.warn("ok, we will support '/' as a prefix in the future..")
    
    if "GroupMessage" in listen_events:
      app.receiver("GroupMessage")(self.GroupMessageListener)
    if "FriendMessage" in listen_events:
      app.receiver("FriendMessage")(self.FriendMessageListener)
コード例 #6
0
#!/bin/env python3
from mirai import Mirai, Plain, MessageChain, Group, Member, GroupMessage, At, Source, Plain
import asyncio
from search import *

tmp = '仓库:%s\
\n包名:%s\
\n版本:%s\
\n描述:%s\
\n更新时间:%s\
\n链接:%s'

qq = 3552600542
authKey = '1234567890'

app = Mirai(f"mirai://*****:*****@app.receiver("GroupMessage")
async def Main(app: Mirai, group: Group, member: Member, message: MessageChain,
               source: Source):
    m_id = message.getSource()
    m_text = message.toString()
    if m_text.startswith("pkg"):
        if m_text == "pkg":
            await app.sendGroupMessage(group, [Plain(text="使用pkg+空格+包名来使用!")])
            raise IndexError(message.toString())
        try:
            await app.sendGroupMessage(group, [Plain(text="正在搜索...请稍后...")])
            nn = await search(m_text[4:])
        except IndexError:
コード例 #7
0
ファイル: test.py プロジェクト: weearc/Ptilopsis
from ptilopsis import Ptilopsis
from mirai import Mirai
from devtools import debug

app = Mirai(
    "mirai://192.168.31.188:8070/ws?qq=208924405&authKey=213we355gdfbaerg")
cm = Ptilopsis(app)


@cm.register("test `fa`[something]")
async def u(something=None):
    debug(something)


if __name__ == "__main__":
    app.run()
コード例 #8
0
from mirai import Mirai, Plain, MessageChain, Friend, Group, GroupMessage, FriendMessage
import asyncio
import os

import config

print(config.setting)
# httpapi所在主机的地址端口, 如果 setting.yml 文件里字段 "enableWebsocket" 的值为 "true" 则需要将 "/" 换成 "/ws", 否则将接收不到消息.
mirai_api_http_locate = 'localhost:' + str(config.setting['port'])
if config.setting['enableWebsocket']:
    mirai_api_http_locate += '/ws'

app = Mirai(
    f"mirai://{mirai_api_http_locate}?authKey={config.setting['authKey']}&qq={config.data['qq']}"
)

msg_count = 0
last_msg = ''


@app.receiver("GroupMessage")
async def msg_indeed(app: Mirai, group: Group, message: MessageChain):
    global last_msg
    if message.__root__[1].text == last_msg:
        await app.sendGroupMessage(group, [Plain(text="确实")])
    last_msg = message.__root__[1].text


if __name__ == "__main__":
    app.run()
コード例 #9
0
    "Upgrade-Insecure-Requests":"1",
    "User-Agent":"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36"
}).text)[0]

enable_this = True

# exec(open("""Callable.py""").read())

# java -jar mirai-console-wrapper-0.2.0-all.jar -Djava.awt.headless=true

with open('authdata','r') as f:
    qq = int(f.readline().strip())
    authKey = f.readline().strip()
    mirai_api_http_locate = f.readline().strip() # httpapi所在主机的地址端口,如果 setting.yml 文件里字段 "enableWebsocket" 的值为 "true" 则需要将 "/" 换成 "/ws", 否则将接收不到消息.

irori = Mirai(f"mirai://{mirai_api_http_locate}?authKey={authKey}&qq={qq}")

try:
    with open('cfg.json','r',encoding='utf-8') as jfr:
        cfg = json.load(jfr)
        banGroup = {int(k):v for k,v in cfg.get('banGroup',{}).items()}
        allowGroup = {int(k):v for k,v in cfg.get('allowGroup',{}).items()}
        botList = set(cfg.get('botList',[]))
        proxy = cfg.get('proxy',{})
        muteList = set(cfg.get('muteList',[]))
        masterID = set(cfg.get('masters',[]))
        
except Exception as e:
    print(e)
    banGroup = {}
    allowGroup={}
コード例 #10
0
import random
import time

from mirai import (At, Face, Friend, FriendMessage, Group, GroupMessage,
                   Member, MessageChain, Mirai, Plain)
from mirai.face import QQFaces

# =================================

DEBUG = False

# =================================

with open("./config.json", "r", encoding='utf-8') as f:
    _js = json.loads(f.read())

MIRAI_API_HTTP_LOCATE = _js['MIRAI_API_HTTP_LOCATE']
AUTH_KEY              = _js['AUTH_KEY']

BOT_QQ_ID             = _js['BOT_QQ_ID']
MASTER_QQ_ID          = _js['MASTER_QQ_ID']

HEARTBEAT_GROUP_ID    = _js['HEARTBEAT_GROUP_ID']

STEAM_GROUP_ID        = _js['STEAM_GROUP_ID']
RR_GROUP_ID           = _js['RR_GROUP_ID']

app = Mirai(f"mirai://{MIRAI_API_HTTP_LOCATE}?authKey={AUTH_KEY}&qq={BOT_QQ_ID}")


コード例 #11
0
# from mirai.face import QQFaces
# from mirai import Face
# import asyncio
import requests
from ostest import picbase, randompic

num = randompic()
dir = "./PixivImage/" + num
url1 = "https://nmsl.shadiao.app/api.php?from=sunbelife"
url2 = "https://chp.shadiao.app/api.php?from=sunbelife"
qq = 3207033875  # 字段 qq 的值
authKey = '1234567890'  # 字段 authKey 的值
mirai_api_http_locate = 'localhost:8080/'
# httpapi所在主机的地址端口,如果 setting.yml 文件里字段 "enableWebsocket" 的值为 "true" 则需要将 "/" 换成 "/ws", 否则将接收不到消息.

app = Mirai(f"mirai://{mirai_api_http_locate}?authKey={authKey}&qq={qq}")


@app.receiver("GroupMessage")
async def quote(app: Mirai, group: Group, message: MessageChain,
                member: Member, source: Source):
    if message.toString().find("骂我") != -1:
        txt1 = requests.get(url1)
        await app.sendGroupMessage(
            group, [At(member.id), Plain(text=txt1.text)], quoteSource=source)
        return True
    if message.toString().find("夸我") != -1:
        txt2 = requests.get(url2)
        await app.sendGroupMessage(
            group, [At(member.id), Plain(text=txt2.text)], quoteSource=source)
        return True
コード例 #12
0
import yaml
from mirai import Mirai, MessageChain, Member, Plain

import gl
from plugin import load_plugins
from plugins.group_msg import handle_group_msg

f = open('config/bot.yaml', encoding="utf-8")
cfg = yaml.load(f, Loader=yaml.FullLoader)

bot = Mirai(f"{cfg['host']}?authKey={cfg['authKey']}&qq={cfg['qq']}",
            websocket={cfg['enableWebsocket']})

gl.init()
gl.setK('bot', bot)


@bot.receiver("GroupMessage")
async def event_gm(app: Mirai, member: Member, message: MessageChain):
    plains = message.getAllofComponent(Plain)
    if len(plains) == 0:
        return

    msg = ''
    for plain in plains:
        msg += plain.toString().strip() + ' '
    msg = msg.strip()
    if msg == '':
        return

    if member.id == 623697643 and '更新插件' == msg:
コード例 #13
0
ファイル: Bot.py プロジェクト: Sakura-Fox/Toy_qqBot
from mirai import (Mirai, Plain, MessageChain, Friend, Group, Member,
                   FriendMessage, GroupMessage, Image, At, MemberJoinEvent,
                   BotJoinGroupEvent)
import asyncio
from typing import List
import utility, recg_face, Account

app = Mirai(
    f"mirai://{Account.mirai_api_http_locate}?authKey={Account.authKey}&qq={Account.qq}"
)


@app.receiver("FriendMessage")
async def event_gm(app: Mirai, friend: Friend, message: MessageChain):
    if friend.id == Account.admin:
        aplain: Plain = message.getFirstComponent(Plain)
        atext = aplain.text
        if atext == "save image":
            aimage: Image = message.getFirstComponent(Image)
            if aimage is not None:
                utility.download_imgae2(aimage.url, "Downloads/Images")
                await app.sendFriendMessage(friend, [Plain(text="已存储")])
        else:
            await app.sendFriendMessage(friend, [Plain(text="Greetings!")])


@app.receiver("MemberJoinEvent")
async def member_join(app: Mirai, event: MemberJoinEvent):
    await app.sendGroupMessage(
        event.member.group.id,
        [At(target=event.member.id),
コード例 #14
0
ファイル: newbiecheck.py プロジェクト: wyapx/bot
from datetime import datetime
import time
from UTC8 import UTC8
from pbc import main
import json
import requests
from mirai import Mirai, Group, MessageChain, Member, Plain, At, Source, Image, Friend
import traceback
qq = 2052142661 # 字段 qq 的值
authKey = '1145141919810' # 字段 authKey 的值
mirai_api_http_locate = 'localhost:11919/ws' # httpapi所在主机的地址端口,如果 setting.yml 文件里字段 "enableWebsocket" 的值为 "true" 则需要将 "/" 换成 "/ws", 否则将接收不到消息.

app = Mirai(f"mirai://{mirai_api_http_locate}?authKey={authKey}&qq={qq}",websocket=True)
@app.subroutine
async def newbie(app: Mirai):
    try:
        await app.sendGroupMessage(731397727,[Plain('开始检测新人。')])
        url = 'https://minecraft-zh.gamepedia.com/api.php?action=query&list=logevents&letype=newusers&format=json'
        while True:
            try:
                q = requests.get(url, timeout=10)
                file = json.loads(q.text)
                qq = []
                for x in file['query']['logevents'][:]:
                    qq.append(x['title'])
                    print('!' + x['title'])
                while True:
                    c = 'f'
                    try:
                        qqq = requests.get(url, timeout=10)
                        qqqq = json.loads(qqq.text)
コード例 #15
0
ファイル: app.py プロジェクト: Matszs/hva-pepper-robot
    # WEEK PROGRAM
    mirai.face_detection().start_detection()
    # WEEK PROGRAM


if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument(
        "--pip",
        type=str,
        default="127.0.0.1",
        help="Robot IP address. On robot or Local Naoqi: use '127.0.0.1'.")
    parser.add_argument("--pport",
                        type=int,
                        default=9559,
                        help="Naoqi port number")

    args = parser.parse_args()

    #mirai = Mirai("145.28.47.180")
    #mirai = Mirai("192.168.50.121")
    mirai = Mirai(args.pip, args.pport)

    mqtt_client = mqtt.Client(client_id="pepper_robot")
    mqtt_client.on_connect = mqtt_connected
    mqtt_client.on_message = mqtt_message
    mqtt_client.username_pw_set("ldr", "xJPriWagGxc68tpwYmDdHWEkg")
    mqtt_client.connect("akoo.nl", 7777, 60)

    threading.Thread(target=program).start()
    mqtt_client.loop_forever()
コード例 #16
0
        loops = asyncio.new_event_loop()
        asyncio.set_event_loop(loops)
        tasks = [
            watcher.clock_check(bot, now.hour, now.minute),
            watcher.muteall_schedule(bot, now.hour, now.minute),
            watcher.RPG_rank(bot, now.hour, now.minute)
        ]
        loops.run_until_complete(asyncio.wait(tasks))
        time.sleep(60)


# 主程序类
if __name__ == '__main__':
    bot = Mirai(
        qq=1812322920,  # 改成你的机器人的 QQ 号
        adapter=WebSocketAdapter(verify_key='Xiao_Qi_Key',
                                 host='localhost',
                                 port=8080))

    # 朋友消息
    @bot.on(FriendMessage)
    async def on_friend_message(event: FriendMessage):
        await message_processing.run(bot, event, 0, event.message_chain,
                                     At(bot.qq) in event.message_chain)

    # 群消息
    @bot.on(GroupMessage)
    async def on_group_message(event: GroupMessage):
        await message_processing.run(bot, event, 1, event.message_chain,
                                     At(bot.qq) in event.message_chain)
コード例 #17
0
from mirai import Mirai, Group, Member, MessageChain, GroupMessage

from utils.config import config
from handler.task import TaskHandler
from handler.group import GroupHandler

groups = {}
cfg = config['mirai_http_api']
lnk = 'mirai://{}?authKey={}&qq={}'
app = Mirai(lnk.format(cfg['address'], cfg['auth_key'], cfg['qq']))


@app.receiver(GroupMessage)
async def GMHandler(app: Mirai, group: Group, member: Member,
                    message: MessageChain):
    if group.id not in groups:
        groups[group.id] = GroupHandler()
        TaskHandler(app, group.id)

    await groups[group.id].handle(app, group, member, message)


if __name__ == "__main__":
    app.run()
コード例 #18
0
from mirai import Mirai, Member, Group, MessageChain, Source, MemberMuteEvent, Plain, BotJoinGroupEvent, \
    MemberUnmuteEvent, MemberJoinEvent, At
from .helpers import run_queue, run_command, strQ2B
from .config import conf
from .loader import manager

basic = conf.get("basic")
if not basic["auth_key"] or not basic["bind_qq"]:
    raise ValueError(
        "auth_key or bind_qq not found, please check your configFile")
if basic["use_websocket"]:
    ws = "ws"
else:
    ws = ""
app = Mirai(
    f'mirai://{basic["host"]}:{basic["port"]}/{ws}?authKey={basic["auth_key"]}&qq={basic["bind_qq"]}'
)

if "total_handle" not in conf.get("storage"):
    conf.get("storage")["total_handle"] = 0
active_group = conf.get("active", "group_id")
storage = conf.get("storage")


@app.receiver("GroupMessage")
async def group_recv(app: Mirai, message: MessageChain, group: Group,
                     member: Member, source: Source):
    data_pack = {
        Mirai: app,
        MessageChain: message,
        Group: group,
コード例 #19
0
from mirai import Mirai
import config
from telegram.ext import Updater

app = Mirai(
    f"mirai://{config.mirai_api_http_locate}?authKey={config.authKey}&qq={config.qq}"
)
updater = Updater(token=config.token,
                  use_context=True,
                  request_kwargs={'proxy_url': config.proxy})
コード例 #20
0
class MiraiHttp:
    auth_key: str
    host: str
    port: int
    qq: int
    _api: Api
    loop: asyncio.AbstractEventLoop
    server_app: Quart
    mirai_instance: Mirai

    def __init__(self, auth_key: str, host: str, port: int, qq: int):
        logging.info("Using Mirai backend")
        self.auth_key = auth_key
        self.host = host
        self.port = port
        self.qq = qq
        self.mirai_instance = Mirai(qq=self.qq,
                                    host=f"http://{self.host}:{self.port}",
                                    authKey=self.auth_key)
        self._api = Api(self.mirai_instance)
        self.server_app = Quart(__name__)

    def run(self, host: str, port: int, debug: bool, use_reloader: bool,
            loop: asyncio.AbstractEventLoop):
        self.loop = loop
        self.mirai_instance.init_loop(self.loop)
        self.server_app.run(host=host,
                            port=port,
                            debug=debug,
                            use_reloader=use_reloader,
                            loop=self.loop)

    # 为了兼容原有代码... 别看我 ¯\_(ツ)_/¯
    def on_message(self, func: Callable):
        def on_message_handler(event: Event):
            # 将消息转换成CQ消息
            cq_message = self.mirai_message_to_cq_message(event.context)

            # 把消息传给订阅者
            async def call_receiver(context):
                # 获取要回复的消息
                reply = await func(context)
                # 如果有要回复的消息
                if reply is not None:
                    logging.debug(context)
                    text = reply["reply"]
                    if context["message_type"] == "group":
                        group_id = context["group_id"]
                        await self._api.send_group_msg(group_id=group_id,
                                                       message=text)
                    elif context["message_type"] == "private":
                        message = context
                        message["message"] = text
                        message["raw_message"] = "reply"
                        await self._api.send_msg(**message)

            # 调用
            self.loop.create_task(call_receiver(cq_message))

        # 订阅消息事件
        self.mirai_instance.add_handler(EventType.Message, on_message_handler)
        return on_message_handler

    def mirai_message_to_cq_message(self, mirai_message: Dict) -> Dict:
        cq_message = {}

        # 消息类型
        if mirai_message["type"] == "GroupMessage":
            message_type = "group"
        elif mirai_message["type"] == "FriendMessage":
            message_type = "private"
        elif mirai_message["type"] == "TempMessage":
            message_type = "private"
        else:
            message_type = "NotImplemented"
        cq_message["message_type"] = message_type

        # 字体
        cq_message["font"] = 7228224  # 不去支持

        # 消息ID
        cq_message["message_id"] = mirai_message["messageChain"][0]["id"]

        # 上报类型
        cq_message["post_type"] = "message"  # 不去支持事件

        # 机器人QQ
        cq_message["self_id"] = self.qq

        # 发送者 QQ 号
        cq_message["user_id"] = mirai_message["sender"]["id"]

        # 存放发送人信息
        sender = {
            "age": 0,
            "sex": "",
            "user_id": mirai_message["sender"]["id"]
        }

        # 群组消息
        if message_type == "group":
            # 匿名消息
            cq_message["anonymous"] = None  # 不去支持

            # 群号
            cq_message["group_id"] = mirai_message["sender"]["group"]["id"]

            # 消息子类型
            cq_message["sub_type"] = "normal"  # 不去支持事件

            sender["nickname"] = mirai_message["sender"]["memberName"]
            sender["area"] = ""
            sender["card"] = ""
            sender["level"] = ""
            sender["role"] = mirai_message["sender"]["permission"].lower()
        else:
            # 消息子类型
            if mirai_message["type"] == "FriendMessage":
                sender["nickname"] = mirai_message["sender"]["nickname"]
                cq_message["sub_type"] = "friend"
            elif mirai_message["type"] == "TempMessage":
                sender["nickname"] = mirai_message["sender"]["memberName"]
                cq_message["sub_type"] = "group"
                cq_message["from_group"] = mirai_message["sender"]["group"][
                    "id"]  # 此块CQ中并不存在, 额外添加来回复临时会话
            else:
                cq_message["sub_type"] = "other"  # 不去支持来自谈论组

        # 发送人信息
        cq_message["sender"] = sender

        # 存放消息体
        message = ""
        raw_message = ""
        for chain in mirai_message["messageChain"]:
            if chain["type"] == "Source":
                continue  # 消息元数据
            elif chain["type"] == "Quote":
                continue  # 引用消息, CQ不支持
            elif chain["type"] == "At":
                message += f"[CQ:at,qq={chain['target']}]"
                raw_message += f"[CQ:at,qq={chain['target']}]"
            elif chain["type"] == "Plain":
                message += chain["text"]
                raw_message += chain["text"]
            elif chain["type"] == "Image":
                message += f"[CQ:image,file={chain['imageId'].replace('-', '')}.png,url={chain['url']}]"
                raw_message += f"[CQ:image,file={chain['imageId'].replace('-', '')}]"
            else:
                continue  # 不去支持

        cq_message["message"] = message
        cq_message["raw_message"] = raw_message
        return cq_message
コード例 #21
0
ファイル: __init__.py プロジェクト: leinlin/MiraiBot
详细说明:https://github.com/Lycreal/MiraiBot/blob/master/plugins/live_monitor/README.md
"""

import re
import asyncio
import traceback
import typing as T

from mirai import Mirai, Group, MessageChain, GroupMessage, Plain, Image
from mirai.logger import Event as EventLogger

from .monitor import Monitor
from .channels import ChannelResolveError
from .enums import ChannelTypes

sub_app = Mirai(f"mirai://localhost:8080/?authKey=0&qq=0")


class Command:
    @classmethod
    def getCommand(cls, msg: str) -> T.Optional[T.Callable[[Group, str], T.Coroutine[T.Any, T.Any, str]]]:
        if '直播' in msg and '监控' in msg:
            command_map = {
                re.compile(r'新增|增|添|加'): cls.add,
                re.compile(r'取消|删|减|除'): cls.remove,
                re.compile(r'显示|列表'): cls.show
            }
            for pattern in command_map.keys():
                if pattern.search(msg):
                    return command_map[pattern]
            else:
コード例 #22
0
ファイル: run.py プロジェクト: leinlin/MiraiBot
import sys
from mirai import Mirai
from plugins import load_plugins

if __name__ == '__main__':
    if len(sys.argv) >= 2:
        app = Mirai(sys.argv[1])
        load_plugins(app)
        app.run()
    else:
        print(f'Usage: python3 {sys.argv[0]} mirai://localhost:8080/ws?authKey=$authKey&qq=$qq\n\n'
              'Visit https://natriumlab.github.io/tutorial/hello-world.html#hello-world-2 for more details.')
        exit(1)
コード例 #23
0
from mirai import Mirai, Image, Plain, MessageChain, Group, Member, Depend
import asyncio
from devtools import debug

authKey = "213we355gdfbaerg"
qq = 208924405

app = Mirai(f"mirai://*****:*****@app.receiver("GroupMessage")
async def event_gm(app: Mirai, message: MessageChain, group: Group,
                   member: Member):
    debug(message)


{
    'type':
    'GroupMessage',
    'messageChain': [{
        'type': 'Source',
        'id': 3755531209654991,
        'time': 1584024199
    }, {
        'type': 'At',
        'target': 1924257498,
        'display': '@幼天使珈百璃٩(ˊ〇ˋ*)و'
    }, {
        'type': 'Plain',
        'text': ' '
    }, {
コード例 #24
0
ファイル: __init__.py プロジェクト: chenquanjun/MiraiBot
import asyncio
import random
import re
from typing import List, Set, Union

from mirai import (Mirai, Group, Member, GroupMessage, Image, Plain, At)
from mirai.event.message.chain import Source
from mirai.logger import Event as EventLogger

from .SetuData import SetuData, SetuResp, SetuDatabase, LoadFrequencyFile
from .._utils import CoolDown, shuzi2number

cd = CoolDown(app='setu', td=5)

sub_app = Mirai(f"mirai://*****:*****@sub_app.receiver("GroupMessage")
async def GMHandler(app: Mirai, message: GroupMessage):
    match = re.match(r'(?:.*?([\d一二两三四五六七八九十]*)张|来点)?(.{0,10}?)的?色图$',
                     message.toString())
    if match:
        number: int = shuzi2number(match[1])
        if number > 10:
            number = 1
        keyword = match[2]
        try:
            await setuExecutor(app, message, number, keyword)
        except Exception as e:
コード例 #25
0
ファイル: qqbot.py プロジェクト: KianWeng/QQBot
from mirai import Mirai, Plain, MessageChain, Friend, At, Group
import asyncio
from tuling import Tuling, Info


qq = 3538826616 # 字段 qq 的值
authKey = 'adhekYgFgrf' # 字段 authKey 的值
mirai_api_http_locate = 'localhost:8080/ws' # httpapi所在主机的地址端口,如果 setting.yml 文件里字段 "enableWebsocket" 的值为 "true" 则需要将 "/" 换成 "/ws", 否则将接收不到消息.

app = Mirai(host="localhost", port="8080", authKey=authKey, qq=qq, websocket=True)
tuling = Tuling(api_key='XXX') #xxx图灵机器人apikey
info = Info(city='杭州', province='浙江', street = '滨康路')

@app.receiver("FriendMessage")
async def event_gm(app: Mirai, friend: Friend, message: MessageChain):
    print(message.toString())
    reply = tuling.reply_text(0, message.toString(), info)
    
    if reply['url'] != '':
        print('sent url')
        await app.sendFriendMessage(friend, [
            Plain(text=reply['url']), Plain(text=reply['text'])
        ])
    else:
        await app.sendFriendMessage(friend, [
                Plain(text=reply['text'])
            ])

@app.receiver("GroupMessage")
async def event_gm(app: Mirai, group: Group, message: MessageChain):
    print(message.toString())
コード例 #26
0
ファイル: deploy.py プロジェクト: OrbitZore/zhihuishu-cli
from loguru import logger

from mirai import Mirai, MessageChain
from mirai.messages import Image
from main import ZhiHuiShuCourseWorkerBlocking

from json import loads

mirai_config = loads(open('./mirai/mirai.config.json', 'r').read())
qq = mirai_config['qq']
client = Mirai(mirai_config['host'], mirai_config['auth_key'], qq)
target_group = mirai_config['target_group']


def force_auth(_qq: int):
    try:
        client.auth(_qq)
    except:
        logger.exception('重新连接mirai')
        force_auth(_qq)


class ZhiHuiShuCourseWorkerBlockingMirai(ZhiHuiShuCourseWorkerBlocking):
    def job_start(self):
        force_auth(qq)
        client.send_group_message(target_group, '开始学习')

    def lesson_finish(self):
        force_auth(qq)
        client.send_group_message(target_group, '扫码成功')
コード例 #27
0
ファイル: hello.py プロジェクト: zdf0221/Hothot
    Source,
    At,
    MemberJoinEvent,
    BotJoinGroupEvent,
    BotMuteEvent,
    BotUnmuteEvent,
)
from mirai.face import QQFaces
from mirai.exceptions import *
from InfoLib import *

qq = 2715723655  # 字段 qq 的值
authKey = '543112018'  # 字段 authKey 的值
mirai_api_http_locate = '172.105.231.148'  # httpapi所在主机的地址端口,如果 setting.yml 文件里字段 "enableWebsocket" 的值为 "true" 则需要将 "/" 换成 "/ws", 否则将接收不到消息.

app = Mirai(host=mirai_api_http_locate, port=8070, authKey=authKey, qq=qq)

headers = {
    "User-Agent":
    "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:52.0) Gecko/20100101 Firefox/52.0",
    "Accept": "*/*",
    "Accept-Language": "zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3",
    "Accept-Encoding": "",
    "Connection": "keep-alive",
}


async def preprocess_command(message: MessageChain):
    print(message)
    return message.toString()