def receive_events(ctx: EventMsg):
    join_data = ep.group_join(ctx)
    if join_data is None:
        return
    userKey = "{}_{}".format(join_data.UserID, ctx.FromUin)
    code, capcha = genCapcha()
    with lock:
        new_users[userKey] = code
        Action(ctx.CurrentQQ).sendGroupPic(
            ctx.FromUin,
            picBase64Buf=capcha,
            content=
            f"请在{wait_time}分钟内发送验证码数字!否则将踢出本群!\n(验证成功才会回复提示!发送 看不清 可刷新验证码)",
            atUser=join_data.UserID,
        )

    time.sleep(wait_time * 60)
    if userKey in new_users:
        Action(ctx.CurrentQQ).sendGroupText(
            ctx.FromUin,
            content=
            f"由于你({join_data.UserName})在进群后{wait_time}分钟内未成功验证, 即将踢出本群!\n如果没踢出去,说明本机器人不是管理员,请自行退群或联系群主管理员办理退群手续!谢谢~~",
            atUser=join_data.UserID,
        )
        time.sleep(1)
        Action(ctx.CurrentQQ).driveUserAway(ctx.FromUin, join_data.UserID)
        with lock:
            new_users.pop(userKey)
Esempio n. 2
0
 def sendText(userGroup, msg, bot: Action, model=Model.SEND_DEFAULT, atQQ=""):
     if msg not in ("", Status.FAILURE):
         if model == Model.SEND_DEFAULT:
             bot.sendGroupText(userGroup, content=str(msg))
         if model == Model.SEND_AT:
             if atQQ == "":
                 raise Exception("没有指定 at 的人!")
             at = f"[ATUSER({atQQ})]\n"
             bot.sendGroupText(userGroup, content=at + str(msg))
Esempio n. 3
0
 def sendPictures(cls,
                  userGroup,
                  picPath,
                  bot: Action,
                  content="",
                  atUser=0):
     bot.sendGroupPic(
         userGroup,
         picBase64Buf=cls.base64conversion(picPath),
         atUser=atUser,
         content=str(content),
     )
Esempio n. 4
0
def receive_group_msg(ctx: GroupMsg):
    try:
        if ctx.Content.startswith(const.PREFIX + "云图"):
            text = ctx.Content[3:].lstrip()
            if text == "":
                Text(const.BOTNAME + "现已支持的云图\n风云二号全国云图: {0}云图 fy2\n风云二号西北太平洋云图: {0}云图 fy2f\n风云四号全国云图: {0}云图 fy4a\n风云四号全圆盘云图: {0}云图 fy4af\n向日葵8号机动观测:{0}云图 h8".format(const.PREFIX))
                return

            cloud_atlas_list = {
                "fy2": cloud_atlas.fy2,
                "fy2f": cloud_atlas.fy2f,
                "fy4a": cloud_atlas.fy4a,
                "fy4af": cloud_atlas.fy4af,
                "h8": cloud_atlas.h8
            }

            if text in cloud_atlas_list:
                pic_url = cloud_atlas_list.get(text)()
                Action(ctx.CurrentQQ).sendGroupPic(
                    ctx.FromGroupId,
                    picUrl = pic_url
                )
            else:
                Text(const.BOTNAME + "没有此类云图")
        elif ctx.Content.startswith(const.PREFIX + "预报"):
            text = ctx.Content[3:].lstrip()
            if text == "":
                text = "24"

            weather_forecast_list = {
                "24": weather_forecast.hour_pic("24"),
                "48": weather_forecast.hour_pic("48"),
                "72": weather_forecast.hour_pic("72")
            }

            if text in weather_forecast_list:
                pic_url = weather_forecast_list.get(text)
                if pic_url == None:
                    Text("今日还没有{}小时降水量预报图,请6点后再试".format(text))
                else:
                    Action(ctx.CurrentQQ).sendGroupPic(
                    ctx.FromGroupId,
                    picUrl = pic_url
                )

    except BaseException as err:
        Text("执行指令时出错:\n{}\nline {}: {}".format(
        err.__traceback__.tb_frame.f_globals["__file__"],
        err.__traceback__.tb_lineno,
        err))
 def sendPictures(cls,
                  userGroup,
                  picPath,
                  bot: Action,
                  standardization=True,
                  content="",
                  atUser=0):
     if standardization:
         content = str(content) + "[PICFLAG]"
     bot.sendGroupPic(
         userGroup,
         picBase64Buf=cls.base64conversion(picPath),
         atUser=atUser,
         content=content,
     )
Esempio n. 6
0
def receive_group_msg(ctx: GroupMsg):
    try:
        if ctx.Content.startswith(const.PREFIX + "mc"):
            text = ctx.Content[3:].lstrip()
            if text == "":
                Text(const.BOTNAME + "指令无效,{}mc <ip地址>".format(const.PREFIX))
                return

            msg_text, pic_base64 = get_server_info(text)
            if pic_base64 != 0:
                Action(ctx.CurrentQQ).sendGroupPic(ctx.FromGroupId,
                                                   content=msg_text,
                                                   picBase64Buf=pic_base64)
            else:
                Text(msg_text)
        elif ctx.Content.startswith(const.PREFIX + "player"):
            text = ctx.Content[7:].lstrip()
            if text == "":
                Text(const.BOTNAME +
                     "指令无效,{}player <ip地址>".format(const.PREFIX))
                return

            Text(const.BOTNAME + get_server_player(text))
    except BaseException as err:
        Text("执行指令时出错:\n{}\nline {}: {}".format(
            err.__traceback__.tb_frame.f_globals["__file__"],
            err.__traceback__.tb_lineno, err))
Esempio n. 7
0
def manage_plugin(ctx: GroupMsg):
    if ctx.FromUserId != ctx.master:
        return
    action = Action(ctx.CurrentQQ)
    c = ctx.Content
    if c == "插件管理":
        action.sendGroupText(
            ctx.FromGroupId,
            (
                "py插件 => 发送启用插件列表\n"
                "已停用py插件 => 发送停用插件列表\n"
                "刷新py插件 => 刷新所有插件,包括新建文件\n"
                "重载py插件+插件名 => 重载指定插件\n"
                "停用py插件+插件名 => 停用指定插件\n"
                "启用py插件+插件名 => 启用指定插件\n"
            ),
        )
        return
    # 发送启用插件列表
    if c == "py插件":
        action.sendGroupText(ctx.FromGroupId, "\n".join(bot.plugins))
        return
    # 发送停用插件列表
    if c == "已停用py插件":
        action.sendGroupText(ctx.FromGroupId, "\n".join(bot.removed_plugins))
        return
    try:
        if c == "刷新py插件":
            bot.reload_plugins()
        # 重载指定插件 重载py插件+[插件名]
        elif c.startswith("重载py插件"):
            plugin_name = c[6:]
            bot.reload_plugin(plugin_name)
        # 停用指定插件 停用py插件+[插件名]
        elif c.startswith("停用py插件"):
            plugin_name = c[6:]
            bot.remove_plugin(plugin_name)
        # 启用指定插件 启用py插件+[插件名]
        elif c.startswith("启用py插件"):
            plugin_name = c[6:]
            bot.recover_plugin(plugin_name)
    except Exception as e:
        action.sendGroupText(ctx.FromGroupId, "操作失败: %s" % e)
Esempio n. 8
0
def receive_group_msg(ctx: GroupMsg):
    ans = whatis(ctx.Content[1:])
    if ans:
        Action(ctx.CurrentQQ).replyGroupMsg(
            ctx.FromGroupId,
            ans,
            ctx.MsgSeq,
            ctx.MsgTime,
            ctx.FromUserId,
            ctx.Content,
        )
Esempio n. 9
0
def receive_events(ctx: EventMsg):
    revoke_data = ep.group_revoke(ctx)
    if revoke_data is None:
        return

    admin = revoke_data.AdminUserID
    group_id = revoke_data.GroupID
    user_id = revoke_data.UserID
    msg_random = revoke_data.MsgRandom
    msg_seq = revoke_data.MsgSeq

    if any([
            user_id == ctx.CurrentQQ,  # 忽略机器人自己撤回的消息
            admin != user_id,  # 忽略管理员撤回的消息
    ]):
        return

    db_name = f"group{group_id}"
    db: DB = db_map[db_name]
    db.init(db_name)

    data = db.find(msg_random=msg_random,
                   msg_seq=msg_seq,
                   user_id=user_id,
                   group_id=group_id)
    if not data:
        return
    data = data[0]
    (
        _,
        msg_type,
        _,
        _,
        _,
        user_id,
        user_name,
        group_id,
        content,
    ) = data
    action = Action(
        ctx.CurrentQQ,
        host=ctx._host,
        port=ctx._port  # type:ignore
    )
    if msg_type == MsgTypes.TextMsg:
        action.sendGroupText(group_id, f"{user_name}想撤回以下内容: \n{content}")
    elif msg_type == MsgTypes.PicMsg:
        pic_data = json.loads(content)
        action.sendGroupText(group_id, f"{user_name}想撤回以下内容: ")
        action.sendGroupPic(
            group_id, picMd5s=[pic["FileMd5"] for pic in pic_data["GroupPic"]])
Esempio n. 10
0
def receive_group_msg(ctx: GroupMsg):
    if ctx.MsgType == MsgTypes.TextMsg:
        if ctx.Content.startswith(const.PREFIX + "复读"):
            text = ctx.Content[3:]
            while text.startswith(const.PREFIX + "复读"):
                text = text[3:]
            if text:
                Text(text)
    elif ctx.MsgType == MsgTypes.PicMsg:
        pic_ctx = refine_pic_group_msg(ctx)
        Action(ctx.CurrentQQ).sendGroupPic(
            ctx.FromGroupId, picMd5s=[pic.FileMd5 for pic in pic_ctx.GroupPic])
Esempio n. 11
0
    def test_rate_limit(self):
        action = Action(qq=self.uin, host=self.host, port=self.port)
        requests = ['getUserList', 'getGroupList']

        def send(func: str):
            c = getattr(action, func)
            c()

        i = 0
        while i <= 5:
            threading.Thread(target=send, args=[requests[i % 2]]).start()
            i += 1
Esempio n. 12
0
def receive_group_msg(ctx: GroupMsg):
    delay = re.findall(_KEYWORD + r"\[(\d+)\]", ctx.Content)
    if delay:
        delay = min(int(delay[0]), 90)
    else:
        random.seed(os.urandom(30))
        delay = random.randint(30, 80)
    time.sleep(delay)
    Action(ctx.CurrentQQ).revokeGroupMsg(
        group=ctx.FromGroupId,
        msgSeq=ctx.MsgSeq,
        msgRandom=ctx.MsgRandom,
    )
Esempio n. 13
0
def receive_group_msg(ctx: GroupMsg):
    userGroup = ctx.FromGroupId

    if Tools.commandMatch(userGroup, blockGroupNumber):
        return

    if not Tools.atOnly(ctx.MsgType):
        return

    msg = ctx.Content

    bot = Action(ctx.CurrentQQ)

    match(msg, bot, userGroup)
Esempio n. 14
0
def receive_group_msg(ctx: GroupMsg):
    userKey = "{}_{}".format(ctx.FromUserId, ctx.FromGroupId)
    if userKey not in new_users:
        return
    content = ctx.Content
    with lock:
        if content.isdigit() and int(content) == new_users[userKey]:
            new_users.pop(userKey)
            Action(ctx.CurrentQQ).sendGroupText(
                ctx.FromGroupId,
                content="验证成功, 成为正式群员, 欢迎你!",
                atUser=ctx.FromUserId,
            )
            return
    if content == "看不清":
        code, capcha = genCapcha()
        with lock:
            new_users[userKey] = code
            Action(ctx.CurrentQQ).sendGroupPic(
                ctx.FromGroupId,
                picBase64Buf=capcha,
                content="验证码已刷新,请尽快验证! 时间不多啦! \n(验证成功才会回复提示! 发送 看不清 可刷新验证码)",
                atUser=ctx.FromUserId,
            )
Esempio n. 15
0
def receive_group_msg(ctx: GroupMsg):
    userGroup = ctx.FromGroupId

    if Tools.commandMatch(userGroup, blockGroupNumber):
        return

    if not Tools.textOnly(ctx.MsgType):
        return

    userQQ = ctx.FromUserId
    msg = ctx.Content
    nickname = ctx.FromNickName
    bot = Action(ctx.CurrentQQ)

    mainProgram(bot, userQQ, userGroup, msg, nickname)
Esempio n. 16
0
def receive_group_msg(ctx: GroupMsg):
    key = f"{ctx.FromGroupId}{uuid.uuid4()}"

    action = Action.from_ctx(ctx)
    action.sendGroupXml(
        ctx.FromGroupId,
        build_card(
            "窥屏检测",
            title=random.choice(("小👶你是否有很多❓", "小🐈🐈能有什么坏♥️👀", "大🐔大🍐今晚吃🐥",
                                 "🅾️🍐给!", "🃏竟是我自己🌝", "🌶👇💩💉💦🐮🍺")),
            summary="\n你在偷窥啥(流汗黄豆)",
            cover=f"{api}/{key}",  # ?r=重定向地址
        ),
    )

    if delay := re.findall(r"谁在窥屏(\d+)", ctx.Content):
        delay = min(int(delay[0]), 30)
Esempio n. 17
0
def receive_group_msg(ctx: GroupMsg):
    global action
    if action is None:
        action = Action(ctx.CurrentQQ,
                        host=getattr(ctx, "_host"),
                        port=getattr(ctx, "_port"))

    if ctx.Content == "疫情订阅":
        cache_data.insert_group(ctx.FromGroupId)
        action.sendGroupText(ctx.FromGroupId, "ok")
    elif ctx.Content == "疫情退订":
        cache_data.delete_group(ctx.FromGroupId)
        action.sendGroupText(ctx.FromGroupId, "ok")
Esempio n. 18
0
def receive_events(ctx: EventMsg):
    join_ctx = refine_group_join_event_msg(ctx)
    if join_ctx is not None:
        action = Action(ctx.CurrentQQ)
        action.sendGroupText(
            join_ctx.FromUin,
            '{} 已加入组织~'.format(join_ctx.UserName),
        )
        pic = draw_text('欢迎 {} 入群!'.format(join_ctx.UserName))
        pic_base64 = base64.b64encode(pic).decode()
        action.sendGroupPic(
            join_ctx.FromUin,
            picBase64Buf=pic_base64,
        )
Esempio n. 19
0
def get_msg(ctx):
    action = Action(ctx.CurrentQQ)
    if ctx.MsgType == "ReplayMsg":
        # Mark the event as completed
        mark_event()
        return

    # Try to add new event
    parse_ret = parse_input(ctx, action)
    if parse_ret is None:
        return
    # action.sendFriendText(ctx.FromUin, str(parse_ret[0])+'\n'+str(parse_ret[1]))
    # Insert data to SQL
    try:
        insert_data(parse_ret[0], parse_ret[1])
    except psycopg2.DatabaseError:
        action.sendFriendText(ctx.FromUin, "数据库故障了Σ(っ °Д °;)っ")
  
    rmsg = "任务收到!\n" + str(parse_ret[0]) + "\n" + parse_ret[1]
    action.sendFriendText(ctx.FromUin, rmsg)
Esempio n. 20
0
    def __init__(self, client_id: str, config: Dict[str, Any], channel):
        super().__init__(client_id, config)
        self.client_config = config[self.client_id]
        self.uin = self.client_config['qq']
        self.host = self.client_config.get('host', 'http://127.0.0.1')
        self.port = self.client_config.get('port', 8888)
        IOTConfig.configs = self.client_config
        self.bot = Botoy(qq=self.uin, host=self.host, port=self.port)
        self.action = Action(qq=self.uin, host=self.host, port=self.port)
        IOTFactory.bot = self.bot
        IOTFactory.action = self.action
        self.channel = channel
        ChatMgr.slave_channel = channel
        self.iot_msg = IOTMsgProcessor(self.uin)

        @self.bot.when_connected
        def on_ws_connected():
            self.logger.info("Connected to OPQBot!")

        @self.bot.when_disconnected
        def on_ws_disconnected():
            self.logger.info("Disconnected from OPQBot!")

        @self.bot.on_friend_msg
        def on_friend_msg(ctx: FriendMsg):
            self.logger.debug(ctx)
            if int(ctx.FromUin) == int(self.uin) and not IOTConfig.configs.get(
                    'receive_self_msg', True):
                self.logger.info(
                    "Received self message and flag set. Cancel delivering...")
                return
            remark_name = self.get_friend_remark(ctx.FromUin)
            if not remark_name:
                info = self.get_stranger_info(ctx.FromUin)
                if info:
                    remark_name = info.get('nickname', '')
                else:
                    remark_name = str(ctx.FromUin)
            if ctx.MsgType == 'TempSessionMsg':  # Temporary chat
                chat_uid = f'private_{ctx.FromUin}_{ctx.TempUin}'
            elif ctx.MsgType == 'PhoneMsg':
                chat_uid = f'phone_{ctx.FromUin}'
            else:
                chat_uid = f'friend_{ctx.FromUin}'
            chat = ChatMgr.build_efb_chat_as_private(
                EFBPrivateChat(
                    uid=chat_uid,
                    name=remark_name,
                ))
            author = chat.other

            # Splitting messages
            messages: List[Message] = []
            func = getattr(self.iot_msg, f'iot_{ctx.MsgType}_friend')
            messages.extend(func(ctx, chat))

            # Sending messages one by one
            message_id = ctx.MsgSeq
            for idx, val in enumerate(messages):
                if not isinstance(val, Message):
                    continue
                val.uid = f"friend_{ctx.FromUin}_{message_id}_{idx}"
                val.chat = chat
                val.author = author
                val.deliver_to = coordinator.master
                coordinator.send_message(val)
                if val.file:
                    val.file.close()

        @self.bot.on_group_msg
        def on_group_msg(ctx: GroupMsg):
            # OPQbot has no indicator for anonymous user, so we have to test the uin
            nickname = ctx.FromNickName
            if int(ctx.FromUserId) == int(
                    self.uin) and not IOTConfig.configs.get(
                        'receive_self_msg', True):
                self.logger.info(
                    "Received self message and flag set. Cancel delivering...")
                return
            remark_name = self.get_friend_remark(ctx.FromUserId)
            if not remark_name:
                info = self.get_stranger_info(ctx.FromUserId)
                if info:
                    remark_name = info.get('nickname', '')
            chat = ChatMgr.build_efb_chat_as_group(
                EFBGroupChat(uid=f"group_{ctx.FromGroupId}",
                             name=ctx.FromGroupName))
            author = ChatMgr.build_efb_chat_as_member(
                chat,
                EFBGroupMember(name=nickname,
                               alias=remark_name,
                               uid=str(ctx.FromUserId)))
            # Splitting messages
            messages: List[Message] = []
            func = getattr(self.iot_msg, f'iot_{ctx.MsgType}_group')
            messages.extend(func(ctx, chat))

            # Sending messages one by one
            message_id = ctx.MsgSeq
            for idx, val in enumerate(messages):
                if not isinstance(val, Message):
                    continue
                val.uid = f"group_{ctx.FromGroupId}_{message_id}_{idx}"
                val.chat = chat
                val.author = author
                val.deliver_to = coordinator.master
                coordinator.send_message(val)
                if val.file:
                    val.file.close()

        @self.bot.on_event
        def on_event(ctx: EventMsg):
            pass  # fixme
Esempio n. 21
0
except Exception:
    import json

# ==========================================
RESOURCES_BASE_PATH = "./resources/vtuber-fortune"

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

# 屏蔽群 例:[12345678, 87654321]
blockGroupNumber = []
# 触发命令列表
commandList = ["今日人品", "今日运势", "抽签", "人品", "运势", "小狐狸签", "吹雪签"]

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

bot = Action(int(os.getenv("BOTQQ")))


@ignore_botself
def receive_group_msg(ctx: GroupMsg):
    userGroup = ctx.FromGroupId

    if Tools.commandMatch(userGroup, blockGroupNumber):
        return

    if not Tools.textOnly(ctx.MsgType):
        return

    userQQ = ctx.FromUserId
    msg = ctx.Content
Esempio n. 22
0
def receive_group_msg(ctx: GroupMsg):
    if ctx.FromUserId != ctx.master:  # 需要在中间件部分提前设置该参数,也可以自行设置其他判断条件
        return

    action = Action(ctx.CurrentQQ)
    content = ctx.Content
    if ctx.MsgType == MsgTypes.TextMsg:
        # 1. 全体禁言       => 开全体禁言
        if content == "全体禁言":
            action.shutAllUp(ctx.FromGroupId, 1)
            return
        # 2. 关全体禁言     => 关全体禁言
        if content == "关全体禁言":
            action.shutAllUp(ctx.FromGroupId, 0)
            return
    if ctx.MsgType == MsgTypes.AtMsg:
        at_data = json.loads(ctx.Content)
        at_content = at_data['Content']
        at_users = at_data['UserID']

        # 3. @改名 + <card> => 艾特一个人,发送改名加新名称,将修改他的群名片
        card = re.findall(r'改名(.*?)', at_content)
        if card:
            action.modifyGroupCard(at_users[0], ctx.FromGroupId, card[0])
            return
        # 4. @禁言 + <time> => 艾特一个人,发送禁言加多少分钟,将禁言对应用户指定分钟
        time = re.findall(r'禁言(\d+)', at_content)
        if time:
            action.shutUserUp(ctx.FromGroupId, at_users[0], time[0])
            return
        # 5. @取消禁言      => 艾特一个人, 解除禁言
        cacel = re.findall(r'取消禁言', at_content)
        if cacel:
            action.shutUserUp(ctx.FromGroupId, at_users[0], 0)
            return
Esempio n. 23
0
from botoy import Action, Botoy, GroupMsg
from botoy.collection import MsgTypes
from botoy.decorators import ignore_botself, these_msgtypes
from botoy.session import SessionController
from botoy.sugar import Text

host = None
qq = None
assert all([host, qq])
bot = Botoy(qq=qq, host=host, log=False)
action = Action(qq, host=host)


# 功能1, 查询
# 指令查询+关键字
def search(word):
    return f'已查询{word}'


# 新建一个会话控制器,每个功能对应一个控制器(我是避免用这样听起来很高级的名词的,但这里我也不知道用什么描述比较好)
# 这里的参数表示生成的session无任何操作该时长后被自动关闭
sc = SessionController(1 * 60)


@bot.on_group_msg
@ignore_botself
@these_msgtypes(MsgTypes.TextMsg)
def _(ctx: GroupMsg):
    if ctx.Content.startswith('查询'):
        # 取需要查询的内容,如果发送的消息直接包含了需要查询的关键字
        # 则直接返回查询结果即可
Esempio n. 24
0
def receive_events(ctx: EventMsg):
    Action(ctx.CurrentQQ)
Esempio n. 25
0
class iot(BaseClient):
    client_name: str = "IOTbot Client"
    client_id: str = "iot"
    client_config: Dict[str, Any]
    bot: Botoy
    action: Action
    channel: SlaveChannel
    logger: logging.Logger = logging.getLogger(__name__)

    info_list = TTLCache(maxsize=2, ttl=600)

    info_dict = TTLCache(maxsize=2, ttl=600)

    group_member_list = TTLCache(maxsize=20, ttl=3600)
    stranger_cache = TTLCache(maxsize=100, ttl=3600)

    sio: socketio.Client = None
    event: threading.Event = None

    def __init__(self, client_id: str, config: Dict[str, Any], channel):
        super().__init__(client_id, config)
        self.client_config = config[self.client_id]
        self.uin = self.client_config['qq']
        self.host = self.client_config.get('host', 'http://127.0.0.1')
        self.port = self.client_config.get('port', 8888)
        IOTConfig.configs = self.client_config
        self.bot = Botoy(qq=self.uin, host=self.host, port=self.port)
        self.action = Action(qq=self.uin, host=self.host, port=self.port)
        IOTFactory.bot = self.bot
        IOTFactory.action = self.action
        self.channel = channel
        ChatMgr.slave_channel = channel
        self.iot_msg = IOTMsgProcessor(self.uin)

        @self.bot.when_connected
        def on_ws_connected():
            self.logger.info("Connected to OPQBot!")

        @self.bot.when_disconnected
        def on_ws_disconnected():
            self.logger.info("Disconnected from OPQBot!")

        @self.bot.on_friend_msg
        def on_friend_msg(ctx: FriendMsg):
            self.logger.debug(ctx)
            if int(ctx.FromUin) == int(self.uin) and not IOTConfig.configs.get(
                    'receive_self_msg', True):
                self.logger.info(
                    "Received self message and flag set. Cancel delivering...")
                return
            remark_name = self.get_friend_remark(ctx.FromUin)
            if not remark_name:
                info = self.get_stranger_info(ctx.FromUin)
                if info:
                    remark_name = info.get('nickname', '')
                else:
                    remark_name = str(ctx.FromUin)
            if ctx.MsgType == 'TempSessionMsg':  # Temporary chat
                chat_uid = f'private_{ctx.FromUin}_{ctx.TempUin}'
            elif ctx.MsgType == 'PhoneMsg':
                chat_uid = f'phone_{ctx.FromUin}'
            else:
                chat_uid = f'friend_{ctx.FromUin}'
            chat = ChatMgr.build_efb_chat_as_private(
                EFBPrivateChat(
                    uid=chat_uid,
                    name=remark_name,
                ))
            author = chat.other

            # Splitting messages
            messages: List[Message] = []
            func = getattr(self.iot_msg, f'iot_{ctx.MsgType}_friend')
            messages.extend(func(ctx, chat))

            # Sending messages one by one
            message_id = ctx.MsgSeq
            for idx, val in enumerate(messages):
                if not isinstance(val, Message):
                    continue
                val.uid = f"friend_{ctx.FromUin}_{message_id}_{idx}"
                val.chat = chat
                val.author = author
                val.deliver_to = coordinator.master
                coordinator.send_message(val)
                if val.file:
                    val.file.close()

        @self.bot.on_group_msg
        def on_group_msg(ctx: GroupMsg):
            # OPQbot has no indicator for anonymous user, so we have to test the uin
            nickname = ctx.FromNickName
            if int(ctx.FromUserId) == int(
                    self.uin) and not IOTConfig.configs.get(
                        'receive_self_msg', True):
                self.logger.info(
                    "Received self message and flag set. Cancel delivering...")
                return
            remark_name = self.get_friend_remark(ctx.FromUserId)
            if not remark_name:
                info = self.get_stranger_info(ctx.FromUserId)
                if info:
                    remark_name = info.get('nickname', '')
            chat = ChatMgr.build_efb_chat_as_group(
                EFBGroupChat(uid=f"group_{ctx.FromGroupId}",
                             name=ctx.FromGroupName))
            author = ChatMgr.build_efb_chat_as_member(
                chat,
                EFBGroupMember(name=nickname,
                               alias=remark_name,
                               uid=str(ctx.FromUserId)))
            # Splitting messages
            messages: List[Message] = []
            func = getattr(self.iot_msg, f'iot_{ctx.MsgType}_group')
            messages.extend(func(ctx, chat))

            # Sending messages one by one
            message_id = ctx.MsgSeq
            for idx, val in enumerate(messages):
                if not isinstance(val, Message):
                    continue
                val.uid = f"group_{ctx.FromGroupId}_{message_id}_{idx}"
                val.chat = chat
                val.author = author
                val.deliver_to = coordinator.master
                coordinator.send_message(val)
                if val.file:
                    val.file.close()

        @self.bot.on_event
        def on_event(ctx: EventMsg):
            pass  # fixme

    def login(self):
        pass

    def logout(self):
        self.action.logout()

    def relogin(self):
        pass

    def send_message(self, msg: 'Message') -> 'Message':
        chat_info = msg.chat.uid.split('_')
        chat_type = chat_info[0]
        chat_uid = chat_info[1]
        if msg.edit:
            pass  # todo Revoke message & resend

        if msg.type in [MsgType.Text, MsgType.Link]:
            if isinstance(msg.target, Message):  # Reply to message
                max_length = 50
                tgt_alias = iot_at_user(msg.target.author.uid)
                tgt_text = process_quote_text(msg.target.text, max_length)
                msg.text = "%s%s\n\n%s" % (tgt_alias, tgt_text, msg.text)
            self.iot_send_text_message(chat_type, chat_uid, msg.text)
            msg.uid = str(uuid.uuid4())
            self.logger.debug('[%s] Sent as a text message. %s', msg.uid,
                              msg.text)
        elif msg.type in (MsgType.Image, MsgType.Sticker, MsgType.Animation):
            self.logger.info("[%s] Image/Sticker/Animation %s", msg.uid,
                             msg.type)
            self.iot_send_image_message(chat_type, chat_uid, msg.file,
                                        msg.text)
            msg.uid = str(uuid.uuid4())
        elif msg.type is MsgType.Voice:
            self.logger.info(f"[{msg.uid}] Voice.")
            if not VOICE_SUPPORTED:
                self.iot_send_text_message(chat_type, chat_uid, "[语音消息]")
            else:
                pydub.AudioSegment.from_file(msg.file).export(
                    msg.file,
                    format='s16le',
                    parameters=["-ac", "1", "-ar", "24000"])
                output_file = tempfile.NamedTemporaryFile()
                if not Silkv3.encode(msg.file.name, output_file.name):
                    self.iot_send_text_message(chat_type, chat_uid, "[语音消息]")
                else:
                    self.iot_send_voice_message(chat_type, chat_uid,
                                                output_file)
                if msg.text:
                    self.iot_send_text_message(chat_type, chat_uid, msg.text)
            msg.uid = str(uuid.uuid4())
        return msg

    def send_status(self, status: 'Status'):
        raise NotImplementedError

    def receive_message(self):
        # replaced by on_*
        pass

    def get_friends(self) -> List['Chat']:
        if not self.info_list.get('friend', None):
            self.update_friend_list()
        friends = []
        self.info_dict['friend'] = {}
        for friend in self.info_list.get('friend', []):
            friend_uin = friend['FriendUin']
            friend_name = friend['NickName']
            friend_remark = friend['Remark']
            new_friend = EFBPrivateChat(uid=f"friend_{friend_uin}",
                                        name=friend_name,
                                        alias=friend_remark)
            self.info_dict['friend'][friend_uin] = friend
            friends.append(ChatMgr.build_efb_chat_as_private(new_friend))
        return friends

    def get_groups(self) -> List['Chat']:
        if not self.info_list.get('group', None):
            self.update_group_list()
        groups = []
        self.info_dict['group'] = {}
        for group in self.info_list.get('group', []):
            group_name = group['GroupName']
            group_id = group['GroupId']
            new_group = EFBGroupChat(uid=f"group_{group_id}", name=group_name)
            self.info_dict['group'][group_id] = IOTGroup(group)
            groups.append(ChatMgr.build_efb_chat_as_group(new_group))
        return groups

    def get_login_info(self) -> Dict[Any, Any]:
        pass

    def get_stranger_info(self, user_id) -> Union[Dict, None]:
        if not self.stranger_cache.get(user_id, None):
            response = self.action.getUserInfo(user=user_id)
            if response.get('code', 1) != 0:  # Failed to get info
                return None
            else:
                self.stranger_cache[user_id] = response.get('data', None)
        return self.stranger_cache.get(user_id)

    def get_group_info(self,
                       group_id: int,
                       no_cache=True) -> Union[None, IOTGroup]:
        if no_cache or not self.info_dict.get('group', None):
            self.update_group_list()
        return self.info_dict['group'].get(group_id, None)

    def get_chat_picture(self, chat: 'Chat') -> BinaryIO:
        chat_type = chat.uid.split('_')
        if chat_type[0] == 'private':
            private_uin = chat_type[1].split('_')[0]
            return download_user_avatar(private_uin)
        elif chat_type[0] == 'friend':
            return download_user_avatar(chat_type[1])
        elif chat_type[0] == 'group':
            return download_group_avatar(chat_type[1])

    def get_chat(self, chat_uid: ChatID) -> 'Chat':
        chat_info = chat_uid.split('_')
        chat_type = chat_info[0]
        chat_attr = chat_info[1]
        chat = None
        if chat_type == 'friend':
            chat_uin = int(chat_attr)
            remark_name = self.get_friend_remark(chat_uin)
            chat = ChatMgr.build_efb_chat_as_private(
                EFBPrivateChat(
                    uid=chat_attr,
                    name=remark_name if remark_name else "",
                ))
        elif chat_type == 'group':
            chat_uin = int(chat_attr)
            group_info = self.get_group_info(chat_uin, no_cache=False)
            group_members = self.get_group_member_list(chat_uin,
                                                       no_cache=False)
            chat = ChatMgr.build_efb_chat_as_group(
                EFBGroupChat(uid=f"group_{chat_uin}",
                             name=group_info.get('GroupName', "")),
                group_members)
        elif chat_type == 'private':
            pass  # fixme
        elif chat_type == 'phone':
            pass  # fixme
        return chat

    def get_chats(self) -> Collection['Chat']:
        return self.get_friends() + self.get_groups()

    def get_group_member_list(self, group_id, no_cache=True):
        if no_cache \
                or not self.group_member_list.get(group_id, None):  # Key expired or not exists
            # Update group member list
            group_members = self.action.getGroupMembers(group_id)
            efb_group_members: List[EFBGroupMember] = []
            for qq_member in group_members:
                qq_member = IOTGroupMember(qq_member)
                efb_group_members.append(
                    EFBGroupMember(name=qq_member['NickName'],
                                   alias=qq_member['GroupCard'],
                                   uid=qq_member['MemberUin']))
            self.group_member_list[group_id] = efb_group_members
        return self.group_member_list[group_id]

    def poll(self):
        # threading.Thread(target=self.bot.run, daemon=True).start()
        # self.bot.run()
        self.sio = self.bot.run_no_wait()
        self.event = threading.Event()
        self.event.wait()
        self.logger.info("IOTBot quited.")

    def stop_polling(self):
        if self.sio:
            self.sio.disconnect()
        if self.bot.pool:
            self.bot.pool.shutdown(wait=False)
        if self.event:
            self.event.set()

    def update_friend_list(self):
        """
        Update friend list from OPQBot

        """
        self.info_list['friend'] = self.action.getUserList()

    def update_group_list(self):
        self.info_list['group'] = self.action.getGroupList()

    def get_friend_remark(self, uin: int) -> Union[None, str]:
        count = 0
        while count <= 1:
            if not self.info_list.get('friend', None):
                self.update_friend_list()
                self.get_friends()
                count += 1
            else:
                break
        if count > 1:  # Failure or friend not found
            raise Exception("Failed to update friend list!"
                            )  # todo Optimize error handling
        if not self.info_dict.get('friend',
                                  None) or uin not in self.info_dict['friend']:
            return None
        # When there is no mark available, the OPQBot API will fill the remark field with nickname
        # Thus no need to test whether isRemark is true or not
        return self.info_dict['friend'][uin].get('Remark', None)

    def iot_send_text_message(self, chat_type: str, chat_uin: str,
                              content: str):
        if chat_type == 'phone':  # Send text to self
            self.action.sendPhoneText(content)
        elif chat_type == 'group':
            chat_uin = int(chat_uin)
            self.action.sendGroupText(chat_uin, content)
        elif chat_type == 'friend':
            chat_uin = int(chat_uin)
            self.action.sendFriendText(chat_uin, content)
        elif chat_type == 'private':
            user_info = chat_uin.split('_')
            chat_uin = int(user_info[0])
            chat_origin = int(user_info[1])
            self.action.sendPrivateText(chat_uin, chat_origin, content)

    def iot_send_image_message(self,
                               chat_type: str,
                               chat_uin: str,
                               file: IO,
                               content: Union[str, None] = None):
        image_base64 = base64.b64encode(file.read()).decode("UTF-8")
        md5_sum = hashlib.md5(file.read()).hexdigest()
        content = content if content else ""
        if chat_type == 'private':
            user_info = chat_uin.split('_')
            chat_uin = int(user_info[0])
            chat_origin = int(user_info[1])
            self.action.sendPrivatePic(user=chat_uin,
                                       group=chat_origin,
                                       picBase64Buf=image_base64,
                                       content=content)
        elif chat_type == 'friend':
            chat_uin = int(chat_uin)
            self.action.sendFriendPic(user=chat_uin,
                                      picBase64Buf=image_base64,
                                      content=content)
        elif chat_type == 'group':
            chat_uin = int(chat_uin)
            self.action.sendGroupPic(group=chat_uin,
                                     picBase64Buf=image_base64,
                                     content=content)

    def iot_send_voice_message(self, chat_type: str, chat_uin: str, file: IO):
        voice_base64 = base64.b64encode(file.read()).decode("UTF-8")
        if chat_type == 'private':
            user_info = chat_uin.split('_')
            chat_uin = int(user_info[0])
            chat_origin = int(user_info[1])
            self.action.sendPrivateVoice(user=chat_uin,
                                         group=chat_origin,
                                         voiceBase64Buf=voice_base64)
        elif chat_type == 'friend':
            chat_uin = int(chat_uin)
            self.action.sendFriendVoice(user=chat_uin,
                                        voiceBase64Buf=voice_base64)
        elif chat_type == 'group':
            chat_uin = int(chat_uin)
            self.action.sendGroupVoice(group=chat_uin,
                                       voiceBase64Buf=voice_base64)
Esempio n. 26
0
import urllib
import demjson
import requests
import base64

# tgbot debug mode
#import logging

#logger = telebot.logger
# telebot.logger.setLevel(logging.DEBUG) # Outputs debug messages to console.

from botoy import Action, AsyncBotoy, Botoy, EventMsg, FriendMsg, GroupMsg, AsyncAction

qq_num = 000000000
qqbot = Botoy(qq=qq_num)
action = Action(qq_num)

tg_token = "000000000:XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
tgbot = telebot.TeleBot(tg_token)

qq_group_id = 000000000
tg_chat_id = -000000000000

proxy_config = 'socks5://127.0.0.1:1080'

telebot.apihelper.proxy = {'https': proxy_config}

proxies = {
    'http': proxy_config,
    'https': proxy_config,
}
Esempio n. 27
0
import base64

from botoy import Action

from .dbs import config

action = Action(qq=config['BotQQ'])


class Send:
    @staticmethod
    def _tobase64(filename):
        with open(filename, 'rb') as f:
            coding = base64.b64encode(f.read())  # 读取文件内容,转换为base64编码
            # logger.info('本地base64转码~')
            return coding.decode()

    @staticmethod
    def send_text(ctx, text, atUser: bool = False):
        if ctx.__class__.__name__ == 'GroupMsg':
            if atUser:
                action.sendGroupText(ctx.FromGroupId, text, ctx.FromUserId)
            else:
                action.sendGroupText(ctx.FromGroupId, text)
        else:
            if ctx.TempUin is None:  # None为好友会话
                action.sendFriendText(ctx.FromUin, text)
            else:  # 临时会话
                action.sendPrivateText(ctx.FromUin, text, ctx.TempUin)
        return
Esempio n. 28
0
from botoy import FriendMsg, GroupMsg, Action

from modules import bot_config
from modules.my_send import Send as send
from botoy import decorators as deco

action = Action(qq=bot_config.bot_qq,
                host=bot_config.host,
                port=bot_config.port)


@deco.ignore_botself
@deco.in_content("语音")
def receive_friend_msg(ctx: FriendMsg):
    print(ctx.FromUin)
    action.sendFriendVoice(ctx.FromUin,
                           voiceUrl="http://video.mnsd.xyz/voice/yyw.mp3")


@deco.ignore_botself
@deco.in_content("晓丹的月牙湾")
def receive_group_msg(ctx: GroupMsg):
    action.sendGroupVoice(ctx.FromGroupId,
                          voiceUrl="http://123.57.155.177/voice/yyw.mp3")
Esempio n. 29
0
 def sendPictures(cls, userGroup, picPath, bot: Action):
     bot.sendGroupPic(userGroup, picBase64Buf=cls.base64conversion(picPath))
Esempio n. 30
0
from botoy import Action, Botoy, GroupMsg, FriendMsg
from botoy import decorators as deco
from module import config, database
import json

bot = Botoy(
    qq=config.botqq,
    host=config.host,
    port=config.port,
    # log=True,
    log=False,
    use_plugins=True)

action = Action(qq=config.botqq, host=config.host, port=config.port)


@bot.group_context_use
def group_ctx_middleware(ctx: GroupMsg):
    ctx.type = 'group'  # 群聊
    ctx.QQ = ctx.FromUserId  # 这条消息的发送者
    ctx.QQG = ctx.FromGroupId  # 这条消息的QQ群
    ctx.accessLevel = database.BasicOperation.auth(ctx.QQG, ctx.QQ)  # 权限等级
    if ctx.MsgType == 'AtMsg':  # @消息
        ctx.AtContentDict = json.loads(ctx.Content)
        ctx.AtUserID = ctx.AtContentDict['UserID']
        ctx.AtTips = ctx.AtContentDict.get('Tips')  # 回复消息时才有
        ctx.Content = ctx.AtContentDict['Content']
    return ctx


@bot.friend_context_use