Ejemplo n.º 1
0
def load_channel(modules: Union[str, List[str]]) -> Dict[str, Exception]:
    ignore = ["__init__.py", "__pycache__"]
    exceptions = {}
    if isinstance(modules, str):
        modules = [modules]
    with AppCore.get_core_instance().get_saya().module_context():
        for module in modules:
            if module in ignore:
                continue
            try:
                AppCore.get_core_instance().get_saya().require(module)
            except Exception as e:
                exceptions[module] = e
    return exceptions
Ejemplo n.º 2
0
async def send_friend_message(friend_id: int, message: list, token: bool = Depends(certify_token)):
    if token:
        core = AppCore.get_core_instance()
        ariadne_app = core.get_app()
        loop = core.get_loop()
        message = parse_messagechain(message)
        if friend := asyncio.run_coroutine_threadsafe(ariadne_app.getFriend(friend_id), loop).result():
            if isinstance(message, MessageChain):
                asyncio.run_coroutine_threadsafe(
                    ariadne_app.sendFriendMessage(
                        friend, message
                    ),
                    loop
                ).result()
                return GeneralResponse()
            else:
                return GeneralResponse(
                    code=403,
                    data=message,
                    message="missing parameters!"
                )
        else:
            return GeneralResponse(
                code=402,
                message=f"friend {friend_id} does not exist!"
            )
Ejemplo n.º 3
0
async def reload_channel(channel: str, token: bool = Depends(certify_token)):
    if token:
        saya = AppCore.get_core_instance().get_saya()
        exceptions = {}
        loaded_channels = get_installed_channels()
        if channel not in loaded_channels:
            return GeneralResponse(
                code=403,
                message=f"module {channel} does not exist!"
            )
        with saya.module_context():
            try:
                saya.reload_channel(loaded_channels[channel])
            except Exception as e:
                return GeneralResponse(
                    code=500,
                    data={"error": e},
                    message=f"Module {channel} reload error"
                )
        if not exceptions:
            return GeneralResponse()
    else:
        return GeneralResponse(
            code=401,
            message="invalid token!"
        )
Ejemplo n.º 4
0
def saya_init():
    channels = Saya.current().channels
    core = AppCore.get_core_instance()
    bcc = core.get_bcc()
    for channel in channels.values():
        cubes = channel.content
        logger.info(f"converting saya module: {channel.module}")
        for cube in cubes:
            if isinstance(cube.metaclass, ListenerSchema):
                bcc.removeListener(bcc.getListener(cube.content))
                if all([
                        issubclass(i, GroupEvent)
                        for i in cube.metaclass.listening_events
                ]):
                    cube.metaclass.decorators.append(manageable(
                        channel.module))
                else:
                    cube.metaclass.decorators.append(
                        manageable(channel.module, False))
                listener = cube.metaclass.build_listener(cube.content, bcc)
                if not listener.namespace:
                    listener.namespace = bcc.getDefaultNamespace()
                bcc.listeners.append(listener)
                if not cube.metaclass.inline_dispatchers:
                    logger.warning(
                        f"插件{channel._name}未使用inline_dispatchers!默认notice为False!"
                    )
                    saya_data.add_saya(channel.module, notice=False)
                else:
                    saya_data.add_saya(channel.module)
Ejemplo n.º 5
0
async def send_group_message(group_id: int, message: list, token: bool = Depends(certify_token)):
    if token:
        core = AppCore.get_core_instance()
        ariadne_app = core.get_app()
        loop = core.get_loop()
        message = parse_messagechain(message)
        if group := asyncio.run_coroutine_threadsafe(ariadne_app.getGroup(group_id), loop).result():
            if isinstance(message, MessageChain):
                asyncio.run_coroutine_threadsafe(
                    ariadne_app.sendGroupMessage(
                        group, message
                        # MessageChain(message)
                        # MessageChain.fromPersistentString(message).asSendable()
                    ),
                    loop
                ).result()
                return GeneralResponse()
            else:
                return GeneralResponse(
                    code=403,
                    data=message,
                    message="missing parameters!"
                )
        else:
            return GeneralResponse(
                code=402,
                message=f"group {group_id} does not exist!"
            )
Ejemplo n.º 6
0
async def get_friend_list(token: bool = Depends(certify_token)):
    if token:
        core = AppCore.get_core_instance()
        ariadne_app = core.get_app()
        loop = core.get_loop()
        return GeneralResponse(
            data={
                friend.id: {
                    "nickname": friend.nickname,
                    "remark": friend.remark
                }
                for friend in (asyncio.run_coroutine_threadsafe(ariadne_app.getFriendList(), loop).result())
            }
        )
    else:
        return GeneralResponse(
            code=401,
            message="invalid token!"
        )
Ejemplo n.º 7
0
async def get_group_list(token: bool = Depends(certify_token)):
    if token:
        core = AppCore.get_core_instance()
        ariadne_app = core.get_app()
        loop = core.get_loop()
        return GeneralResponse(
            data={
                group.id: {
                    "name": group.name,
                    "accountPerm": group.accountPerm
                }
                for group in (asyncio.run_coroutine_threadsafe(ariadne_app.getGroupList(), loop).result())
            }
        )
    else:
        return GeneralResponse(
            code=401,
            message="invalid token!"
        )
Ejemplo n.º 8
0
async def installed_channels(token: bool = Depends(certify_token)):
    if token:
        channels = AppCore.get_core_instance().get_saya_channels()
        modules = list(channels.keys())
        modules.sort()
        return GeneralResponse(
            data={
                module: {
                    "name": channels[module]._name,
                    "author": channels[module]._author,
                    "description": channels[module]._description
                }
                for module in modules
            }
        )
    else:
        return GeneralResponse(
            code=401,
            message="invalid token!"
        )
Ejemplo n.º 9
0
async def get_friend_detail(friend_id: int, token: bool = Depends(certify_token)):
    if token:
        core = AppCore.get_core_instance()
        ariadne_app = core.get_app()
        loop = core.get_loop()
        if friend := asyncio.run_coroutine_threadsafe(ariadne_app.getFriend(friend_id), loop).result():
            friend_profile = asyncio.run_coroutine_threadsafe(friend.getProfile(), loop).result()
            return GeneralResponse(
                data={
                    "nickname": friend_profile.nickname,
                    "email": friend_profile.email,
                    "age": friend_profile.age,
                    "level": friend_profile.level,
                    "sign": friend_profile.sign,
                    "sex": friend_profile.sex
                }
            )
        else:
            return GeneralResponse(
                code=402,
                message=f"friend {friend_id} does not exist!"
            )
Ejemplo n.º 10
0
async def get_group_detail(group_id: int, token: bool = Depends(certify_token)):
    if token:
        core = AppCore.get_core_instance()
        ariadne_app = core.get_app()
        loop = core.get_loop()
        if group := asyncio.run_coroutine_threadsafe(ariadne_app.getGroup(group_id), loop).result():
            group_config = asyncio.run_coroutine_threadsafe(group.getConfig(), loop).result()
            return GeneralResponse(
                data={
                    "name": group_config.name,
                    "announcement": group_config.announcement,
                    "confessTalk": group_config.confessTalk,
                    "allowMemberInvite": group_config.allowMemberInvite,
                    "autoApprove": group_config.autoApprove,
                    "anonymousChat": group_config.anonymousChat
                }
            )
        else:
            return GeneralResponse(
                code=402,
                message=f"group {group_id} does not exist!"
            )
Ejemplo n.º 11
0
async def install_channel(channel: str, token: bool = Depends(certify_token)):
    if token:
        saya = AppCore.get_core_instance().get_saya()
        ignore = ["__init__.py", "__pycache__"]
        with saya.module_context():
            if channel in ignore:
                return GeneralResponse(
                    code=202,
                    message=f"module {channel} is on the ignore list"
                )
            try:
                saya.require(channel)
            except Exception as e:
                return GeneralResponse(
                    code=500,
                    data={"error": e},
                    message=f"Module {channel} installation error"
                )
        return GeneralResponse()
    else:
        return GeneralResponse(
            code=401,
            message="invalid token!"
        )
Ejemplo n.º 12
0
from graia.ariadne.model import Friend, Group
from graia.scheduler.timers import crontabify
from graia.ariadne.message.element import Image
from graia.ariadne.message.chain import MessageChain
from graia.scheduler.saya.schema import SchedulerSchema
from graia.saya.builtins.broadcast.schema import ListenerSchema
from graia.ariadne.event.message import FriendMessage, GroupMessage
from graia.ariadne.message.parser.twilight import Twilight, FullMatch

from sagiri_bot.utils import group_setting
from sagiri_bot.orm.async_orm import Setting
from sagiri_bot.core.app_core import AppCore

saya = Saya.current()
channel = Channel.current()
host_qq = AppCore.get_core_instance().get_config().host_qq

channel.name("DailyNewspaper")
channel.author("SAGIRI-kawaii")
channel.description("一个定时发送每日日报的插件\n"
                    "主人私聊bot发送 `发送早报` 可在群中发送早报\n"
                    "在群中发送 `今日早报` 可在群中发送早报")


@channel.use(SchedulerSchema(crontabify("30 8 * * *")))
async def something_scheduled(app: Ariadne):
    await send_newspaper(app)


@channel.use(
    ListenerSchema(listening_events=[FriendMessage],
Ejemplo n.º 13
0
def get_not_installed_channels() -> List[str]:
    installed_channels = AppCore.get_core_instance().get_saya().channels.keys()
    all_channels = get_all_channels()
    return [channel for channel in all_channels if channel not in installed_channels]
Ejemplo n.º 14
0
from sagiri_bot.orm.async_orm import orm
from sagiri_bot.core.app_core import AppCore
from sagiri_bot.orm.async_orm import KeywordReply
from sagiri_bot.utils import user_permission_require
from sagiri_bot.control import BlackListControl, Function

saya = Saya.current()
channel = Channel.current()

channel.name("KeywordRespondent")
channel.author("SAGIRI-kawaii")
channel.description("一个关键字回复插件,在群中发送已添加关键词可自动回复\n"
                    "在群中发送 `添加回复关键词#{keyword}#{reply}` 可添加关键词\n"
                    "在群中发送 `删除回复关键词#{keyword}` 可删除关键词")

inc = InterruptControl(AppCore.get_core_instance().get_bcc())
regex_list = []
parse_big_bracket = "\\{"
parse_mid_bracket = "\\["
parse_bracket = "\\("


class NumberWaiter(Waiter.create([GroupMessage])):
    """ 超时Waiter """
    def __init__(self, group: Union[int, Group], member: Union[int, Member],
                 max_length: int):
        self.group = group if isinstance(group, int) else group.id
        self.member = (member if isinstance(member, int) else
                       member.id) if member else None
        self.max_length = max_length
Ejemplo n.º 15
0
# -*- coding: utf-8 -*-
import os
import threading
from loguru import logger
from datetime import datetime
from pathlib import Path

from graia.ariadne.event.lifecycle import ApplicationLaunched
from graia.ariadne.event.message import Group, Member, MessageChain, Friend
from graia.ariadne.event.message import ActiveFriendMessage, ActiveGroupMessage

from sagiri_bot.core.app_core import AppCore
from sagiri_bot.utils import online_notice, load_config
from sagiri_bot.core.api_server.app import run_api_server, set_log

core = AppCore(load_config())

app = core.get_app()
bcc = core.get_bcc()
saya = core.get_saya()
config = core.get_config()

if not os.path.exists(
        Path(os.getcwd()) / "log" / datetime.now().strftime('%Y-%m-%d')):
    os.makedirs(
        Path(os.getcwd()) / "log" / datetime.now().strftime('%Y-%m-%d'))

logger.add(str(
    Path(os.getcwd()) / "log" / datetime.now().strftime('%Y-%m-%d') /
    "common.log"),
           level="INFO",
Ejemplo n.º 16
0
from graia.ariadne.message.parser.twilight import Twilight
from graia.ariadne.event.message import Group, GroupMessage
from graia.saya.builtins.broadcast.schema import ListenerSchema
from graia.ariadne.message.parser.twilight import FullMatch, ArgumentMatch, ArgResult

from sagiri_bot.control import Permission
from sagiri_bot.core.app_core import AppCore

saya = Saya.current()
channel = Channel.current()

channel.name("SystemStatus")
channel.author("SAGIRI-kawaii")
channel.description("查看系统状态")

image_path = AppCore.get_core_instance().get_config().image_path


@channel.use(
    ListenerSchema(
        listening_events=[GroupMessage],
        inline_dispatchers=[
            Twilight([
                FullMatch("/sys"),
                ArgumentMatch("-a", "-all", optional=True,
                              action="store_true") @ "all_info",
                ArgumentMatch(
                    "-i", "-info", optional=True, action="store_true")
                @ "info",
                ArgumentMatch(
                    "-s", "-storage", optional=True, action="store_true")
Ejemplo n.º 17
0
from graia.saya.builtins.broadcast.schema import ListenerSchema
from graia.ariadne.message.parser.twilight import RegexMatch, FullMatch, RegexResult

from sagiri_bot.core.app_core import AppCore
from sagiri_bot.message_sender.strategy import QuoteSource
from sagiri_bot.message_sender.message_item import MessageItem
from sagiri_bot.control import FrequencyLimit, Function, BlackListControl, UserCalledCountControl

saya = Saya.current()
channel = Channel.current()

channel.name("WolframAlpha")
channel.author("SAGIRI-kawaii")
channel.description("一个接入WolframAlpha的插件,在群中发送 `/solve {content}` 即可")

api_key = AppCore.get_core_instance().get_config().functions.get(
    "wolfram_alpha_key", None)


@channel.use(
    ListenerSchema(
        listening_events=[GroupMessage],
        inline_dispatchers=[
            Twilight([FullMatch("/solve"),
                      RegexMatch(".+") @ "content"])
        ],
        decorators=[
            FrequencyLimit.require("wolfram_alpha", 4),
            Function.require(channel.module),
            BlackListControl.enable(),
            UserCalledCountControl.add(UserCalledCountControl.FUNCTIONS)
        ]))
Ejemplo n.º 18
0
def get_installed_channels() -> Dict[str, Channel]:
    return AppCore.get_core_instance().get_saya().channels
Ejemplo n.º 19
0
            time.strptime(d['end_time'], "%Y-%m-%d %H:%M:%S"))
        if not (begin_time < time.time() < end_time):
            continue

        pool_name = str(d['gacha_name'])
        pool_url = f"https://webstatic.mihoyo.com/hk4e/gacha_info/cn_gf01/{d['gacha_id']}/zh-cn.json"
        pool_data = await get_url_data(pool_url)
        pool_data = json.loads(pool_data.decode("utf-8"))

        for prob_list in ['r3_prob_list', 'r4_prob_list', 'r5_prob_list']:
            for i in pool_data[prob_list]:
                item_name = i['item_name']
                item_type = i["item_type"]
                item_star = str(i["rank"])
                key = ''
                key += item_star
                if str(i["is_up"]) == "1":
                    key += "_star_UP"
                else:
                    key += "_star_not_UP"
                POOL[pool_name][key].append(item_name)

                if item_type == '角色':
                    await up_role_icon(name=item_name, star=item_star)
                else:
                    await up_arm_icon(name=item_name, star=item_star)


loop = AppCore.get_core_instance().get_loop()
loop.run_in_executor(None, init_pool_list) if AUTO_UPDATE else None
Ejemplo n.º 20
0
from typing import Optional
from datetime import datetime
from bs4 import BeautifulSoup

from graia.ariadne import get_running
from graia.ariadne.adapter import Adapter
from sagiri_bot.core.app_core import AppCore
from graia.ariadne.message.chain import MessageChain
from graia.ariadne.message.element import Plain, Image, Forward, ForwardNode

config = AppCore.get_core_instance().get_config()
proxy = config.proxy if config.proxy != "proxy" else ''


async def search(*,
                 keyword: Optional[str] = None,
                 data_bytes: Optional[bytes] = None) -> MessageChain:
    search_url = "https://xslist.org/search?lg=en&query="
    pic_search_url = "https://xslist.org/search/pic"
    if not keyword and not data_bytes:
        raise ValueError("You should give keyword or data_bytes!")
    elif keyword:
        keyword = keyword.strip()
        async with get_running(Adapter).session.get(search_url + keyword,
                                                    proxy=proxy) as resp:
            html = await resp.text()
    elif data_bytes:
        async with get_running(Adapter).session.post(pic_search_url,
                                                     data={
                                                         "pic": data_bytes,
                                                         "lg": "en"
Ejemplo n.º 21
0
    "app-channel": "2",
    "app-version": "2.2.1.3.3.4",
    "app-uuid": "defaultUuid",
    "image-quality": "original",
    "app-platform": "android",
    "app-build-version": "44",
    "Content-Type": "application/json; charset=UTF-8",
    "User-Agent": "okhttp/3.8.1",
    "accept": "application/vnd.picacomic.com.v1+json",
    "time": 0,
    "nonce": "",
    "signature": "encrypt",
}
path_filter = ['\\', '/', ':', '*', '?', '"', '<', '>', '|']

core = AppCore.get_core_instance()
config = core.get_config()
proxy = config.proxy if config.proxy != "proxy" else ''
pica_config = config.functions.get("pica")
username = pica_config.get("username", None)
password = pica_config.get("password", None)
compress_password = pica_config.get("compress_password", "i_luv_sagiri")
loop = core.get_loop()
DOWNLOAD_CACHE = pica_config.get("download_cache", True)


class Pica:
    def __init__(self, account, password):
        if not os.path.exists(CACHE_PATH):
            os.makedirs(CACHE_PATH)
        self.init = False
Ejemplo n.º 22
0
from graia.ariadne.message.parser.twilight import RegexMatch, FullMatch, RegexResult

from sagiri_bot.core.app_core import AppCore
from sagiri_bot.control import FrequencyLimit, Function, BlackListControl, UserCalledCountControl

saya = Saya.current()
channel = Channel.current()

channel.name("EmojiMix")
channel.author("SAGIRI-kawaii")
channel.author("from: MeetWq")
channel.description("一个生成emoji融合图的插件,发送 '{emoji1}+{emoji2}' 即可")

EmojiData = Tuple[List[int], str, str]
API = 'https://www.gstatic.com/android/keyboard/emojikitchen/'
proxy = AppCore.get_core_instance().get_config().proxy


@channel.use(
    ListenerSchema(listening_events=[GroupMessage],
                   inline_dispatchers=[
                       Twilight([
                           RegexMatch(u"[\u200d-\U0001fab5]") @ "emoji1",
                           FullMatch("+"),
                           RegexMatch(u"[\u200d-\U0001fab5]") @ "emoji2"
                       ])
                   ],
                   decorators=[
                       FrequencyLimit.require("emoji_mix", 2),
                       Function.require(channel.module),
                       BlackListControl.enable(),