Beispiel #1
0
async def force_subscribe_join(event: ChatAction.Event):
    if not redis_status():
        return
    if not (event.user_joined or event.user_added):
        return
    join_chat = redis.get(f"sub.chat_id.{event.chat_id}")
    if not join_chat:
        return
    else:
        join_chat = join_chat.decode()
    user = await event.get_user()
    if user.bot:
        return
    if redis.get(f"sub.chat_id.{event.chat_id}.{user.id}"):
        return
    try:
        try:
            await bot(GetParticipantRequest(join_chat, user.id))
        except ValueError:
            user_input = await event.get_input_user()
            await bot(GetParticipantRequest(join_chat, user_input))
        redis.set(f'sub.chat_id.{event.chat_id}.{user.id}', 'true')
        redis.expire(f'sub.chat_id.{event.chat_id}.{user.id}', 3600)
    except UserNotParticipantError:
        msg = await event.reply(
            f'[{user.first_name}](tg://user?id={user.id}) 您需要先加入频道 @{join_chat} 才能发言。'
        )
        await sleep(5)
        await msg.delete()
    except ChatAdminRequiredError:
        redis.delete(f"sub.chat_id.{event.chat_id}")
Beispiel #2
0
async def force_sub(context):
    if not redis_status():
        await context.edit(f"{lang('error_prefix')}{lang('redis_dis')}")
        return
    if len(context.parameter) != 1:
        await context.edit(f"{lang('error_prefix')}{lang('arg_error')}")
        return
    myself = await context.client.get_me()
    self_user_id = myself.id
    if context.parameter[0] == "false":
        if context.chat_id == self_user_id:
            await context.edit(lang('ghost_e_mark'))
            return
        redis.delete(f"sub.chat_id.{context.chat_id}")
        await context.edit(f'成功关闭强制关注频道功能。')
    elif context.parameter[0] == "status":
        if redis.get(f"sub.chat_id.{context.chat_id}"):
            join_chat = redis.get(f"sub.chat_id.{context.chat_id}").decode()
            await context.edit(f'当前群组强制需要关注频道的频道为: @{join_chat} 。')
        else:
            await context.edit('当前群组未开启强制关注频道功能。')
    else:
        if context.chat_id == self_user_id:
            await context.edit(lang('ghost_e_mark'))
            return
        sub_channel = context.parameter[0].replace('@', '')
        try:
            await context.client.get_participants(
                sub_channel, filter=ChannelParticipantsAdmins)
        except:
            await context.edit(f'设置失败:不是频道 @{sub_channel} 的管理员。')
            return
        redis.set(f"sub.chat_id.{context.chat_id}", sub_channel)
        await context.edit(f'已设置当前群组强制需要关注频道的频道为: @{sub_channel} 。')
Beispiel #3
0
def get_bot():
    data = [1527463252, "msg_schedule_bot"]
    if redis_status():
        n_id = redis.get("msgst.bot_id")
        n_un = redis.get("msgst.bot_un")
        if n_id and is_num(str(n_id, "ascii")): data[0] = int(str(n_id, "ascii"))
        if n_un: data[1] = str(n_un, "ascii")
    return data
Beispiel #4
0
async def message_removal_user(context):
    """ Event handler to infinitely delete denied messages. """
    if not redis_status():
        return
    uid = context.sender_id
    if redis.get(f"denieduser.{context.chat_id}.{uid}"):
        # 避免和 -deny 冲突
        if not redis.get(f"denied.chat_id.{context.chat_id}"):
            await context.delete()
Beispiel #5
0
async def shift_channel_message(context):
    """ Event handler to auto forward channel messages. """
    if not redis_status():
        return
    if not redis.get("shift." + str(context.chat_id)):
        return
    if context.chat_id in [-1001441461877]:
        return
    cid = int(redis.get("shift." + str(context.chat_id)).decode())
    try:
        await context.forward_to(cid)
    except Exception as e:
        pass
async def anti_channel_msg(context):
    if not redis_status():
        await context.edit(f"{lang('error_prefix')}{lang('redis_dis')}")
        return
    if context.chat_id == user_id or not context.is_group:
        await context.edit(lang('ghost_e_mark'))
        return
    if len(context.parameter) == 0:
        await context.edit(f"{lang('error_prefix')}{lang('arg_error')}")
        return
    if context.parameter[0] == "true":
        data = await bot(GetFullChannelRequest(context.chat_id))
        if not data.full_chat.linked_chat_id:
            return await context.edit("当前群组未链接到频道,无法开启此功能。")
        redis.set("antichannelmsg." + str(context.chat_id), f"{data.full_chat.linked_chat_id}")
        await context.edit(f"已成功开启群组 {str(context.chat_id)} 的自动删除频道消息并且封禁频道功能。")
        await log(f"已成功开启群组 {str(context.chat_id)} 的自动删除频道消息并且封禁频道功能。")
    elif context.parameter[0] == "false":
        try:
            redis.delete("antichannelmsg." + str(context.chat_id))
        except:
            await context.edit('emm...当前对话不存在于自动删除频道消息并且封禁频道功能列表中。')
            return
        await context.edit(f"已成功关闭群组 {str(context.chat_id)} 的自动删除频道消息并且封禁频道功能。")
        await log(f"已成功关闭群组 {str(context.chat_id)} 的自动删除频道消息并且封禁频道功能。")
    elif context.parameter[0] == "add":
        data = redis.get("antichannelmsg." + str(context.chat_id))
        if not data:
            return await context.edit("emm...当前对话不存在于自动删除频道消息并且封禁频道功能列表中。")
        data = data.decode().split(" ")
        try:
            chat_id = context.parameter[1]
            channel_data = await bot(GetFullChannelRequest(int(chat_id)))  # noqa
        except TypeError:
            return await context.edit("频道 id 错误")
        except ValueError:
            return await context.edit("频道 id 不是 -100 开头的数字")
        except IndexError:
            return await context.edit("没有指定频道 id")
        data.append(str(channel_data.full_chat.id))
        redis.set("antichannelmsg." + str(context.chat_id), " ".join(data))
        await context.edit("添加频道到白名单成功。")
    elif context.parameter[0] == "status":
        if redis.get("antichannelmsg." + str(context.chat_id)):
            await context.edit('当前对话存在于自动删除频道消息并且封禁频道功能列表中。')
        else:
            await context.edit('当前对话不存在于自动删除频道消息并且封禁频道功能列表中。')
    else:
        await context.edit(f"{lang('error_prefix')}{lang('arg_error')}")
Beispiel #7
0
async def backup(context):
    await context.edit(lang('backup_process'))

    # Remove old backup
    if os.path.exists(pgm_backup_zip_name):
        os.remove(pgm_backup_zip_name)

    # remove mp3 , they are so big !
    for i in os.listdir("data"):
        if i.find(".mp3") != -1 or i.find(".jpg") != -1 or i.find(
                ".flac") != -1 or i.find(".ogg") != -1:
            os.remove(f"data{os.sep}{i}")

    # backup redis when available
    redis_data = {}
    if redis_status():
        for k in redis.keys():
            data_type = redis.type(k)
            if data_type == b'string':
                v = redis.get(k)
                redis_data[k.decode()] = v.decode()

        with open(f"data{os.sep}redis.json", "w", encoding='utf-8') as f:
            json.dump(redis_data, f, indent=4)

    # run backup function
    make_tar_gz(pgm_backup_zip_name, ["data", "plugins", "config.yml"])
    if strtobool(config['log']):
        await upload_attachment(pgm_backup_zip_name, int(config['log_chatid']),
                                None)
        await context.edit(lang("backup_success_channel"))
    else:
        await context.edit(lang("backup_success"))
Beispiel #8
0
async def setdata(context):
    try:
        chat_id = context.chat_id
        params = context.parameter
        if params[0] == "dump":
            data = redis.get(f"keyword.{chat_id}.{params[1]}")
            if not data:
                await context.edit("无规则数据")
                await del_msg(context, 5)
                return
            data = str(data, "ascii")
            await context.edit(data)
            return
        elif params[0] == "load":
            redis.set(f"keyword.{chat_id}.{params[1]}", params[2])
            await context.edit("设置成功")
            await del_msg(context, 5)
            return
        else:
            await context.edit("参数错误")
            await del_msg(context, 5)
            return
    except:
        await context.edit("运行错误")
        await del_msg(context, 5)
        return
Beispiel #9
0
async def deny(context):
    """ Toggles denying of a user. """
    if not redis_status():
        await context.edit("Redis is offline, cannot operate.")
        return
    if len(context.parameter) != 1:
        await context.edit("Invalid argument.")
        return
    myself = await context.client.get_me()
    self_user_id = myself.id
    if context.parameter[0] == "true":
        if context.chat_id == self_user_id:
            await context.edit("Unable to set flag on self.")
            return
        redis.set("denied.chat_id." + str(context.chat_id), "true")
        await context.delete()
        await log(f"ChatID {str(context.chat_id)} added to denied chats.")
    elif context.parameter[0] == "false":
        if context.chat_id == self_user_id:
            await context.edit("Unable to set flag on self.")
            return
        redis.delete("denied.chat_id." + str(context.chat_id))
        await context.delete()
        await log(f"ChatID {str(context.chat_id)} removed from denied chats.")
    elif context.parameter[0] == "status":
        if redis.get("denied.chat_id." + str(context.chat_id)):
            await context.edit("Current chat is denied.")
        else:
            await context.edit("Current chat is not denied.")
    else:
        await context.edit("Invalid argument.")
Beispiel #10
0
async def force_group(context):
    if not redis_status():
        await context.edit(f"{lang('error_prefix')}{lang('redis_dis')}")
        return
    if len(context.parameter) != 1:
        await context.edit(f"{lang('error_prefix')}{lang('arg_error')}")
        return
    myself = await context.client.get_me()
    self_user_id = myself.id
    if context.parameter[0] == "false":
        if context.chat_id == self_user_id:
            await context.edit(lang('ghost_e_mark'))
            return
        redis.delete(f"group.chat_id.{context.chat_id}")
        await context.edit(f'成功关闭强制加入频道讨论群功能。')
    elif context.parameter[0] == "status":
        if redis.get(f"group.chat_id.{context.chat_id}"):
            await context.edit(f'当前群组已开启强制加入频道讨论群功能。')
        else:
            await context.edit('当前群组未开启强制加入频道讨论群功能。')
    else:
        if context.chat_id == self_user_id:
            await context.edit(lang('ghost_e_mark'))
            return
        admins = await context.client.get_participants(
            context.chat, filter=ChannelParticipantsAdmins)
        if context.sender in admins:
            user = admins[admins.index(context.sender)]
            if not user.participant.admin_rights.delete_messages:
                await context.edit('无删除消息权限,拒绝开启此功能。')
                return
        redis.set(f"group.chat_id.{context.chat_id}", 'true')
        await context.edit(f'成功在当前群组开启强制加入频道讨论群功能。')
Beispiel #11
0
async def remove_others_message(context):
    """ Event handler to infinitely remove messages. """
    if not redis_status():
        return
    if not context.is_group:
        return
    chat_id = context.chat_id
    if not isinstance(context.from_id, PeerUser):
        return
    uid = context.from_id.user_id
    mid = context.id
    data = redis.get(f"autodel.{chat_id}.{uid}")
    if data:
        delta = float(data.decode())
        await sleep(delta)
        # 检查消息是否仍然存在
        chat = await context.get_chat()
        msg = await context.client.get_messages(chat, ids=mid)
        if msg:
            try:
                await context.delete()
            except Exception as e:
                try:
                    await send_msg(context, await context.get_chat(), str(e))
                except ValueError:
                    pass
Beispiel #12
0
async def deny(context):
    """ Toggles denying of a user. """
    if not redis_status():
        await context.edit(f"{lang('error_prefix')}{lang('redis_dis')}")
        return
    if len(context.parameter) != 1:
        await context.edit(f"{lang('error_prefix')}{lang('arg_error')}")
        return
    myself = await context.client.get_me()
    self_user_id = myself.id
    if context.parameter[0] == "true":
        if context.chat_id == self_user_id:
            await context.edit(lang('ghost_e_mark'))
            return
        redis.set("denied.chat_id." + str(context.chat_id), "true")
        await context.delete()
        await log(f"ChatID {str(context.chat_id)} {lang('deny_set')}")
    elif context.parameter[0] == "false":
        if context.chat_id == self_user_id:
            await context.edit(lang('ghost_e_mark'))
            return
        redis.delete("denied.chat_id." + str(context.chat_id))
        await context.delete()
        await log(f"ChatID {str(context.chat_id)} {lang('deny_cancel')}")
    elif context.parameter[0] == "status":
        if redis.get("denied.chat_id." + str(context.chat_id)):
            await context.edit(lang('deny_e_exist'))
        else:
            await context.edit(lang('deny_e_noexist'))
    else:
        await context.edit(f"{lang('error_prefix')}{lang('arg_error')}")
Beispiel #13
0
async def ghost(context):
    """ Toggles ghosting of a user. """
    if not redis_status():
        await context.edit("出错了呜呜呜 ~ Redis 好像离线了,无法执行命令。")
        return
    if len(context.parameter) != 1:
        await context.edit("出错了呜呜呜 ~ 无效的参数。")
        return
    myself = await context.client.get_me()
    self_user_id = myself.id
    if context.parameter[0] == "true":
        if context.chat_id == self_user_id:
            await context.edit("在?为什么要在收藏夹里面用?")
            return
        redis.set("ghosted.chat_id." + str(context.chat_id), "true")
        await context.delete()
        await log(f"已成功将 ChatID {str(context.chat_id)} 添加到自动已读对话列表中。")
    elif context.parameter[0] == "false":
        if context.chat_id == self_user_id:
            await context.edit("在?为什么要在收藏夹里面用?")
            return
        try:
            redis.delete("ghosted.chat_id." + str(context.chat_id))
        except:
            await context.edit("emm...当前对话不存在于自动已读对话列表中。")
            return
        await context.delete()
        await log(f"已成功将 ChatID {str(context.chat_id)} 从自动已读对话列表中移除。")
    elif context.parameter[0] == "status":
        if redis.get("ghosted.chat_id." + str(context.chat_id)):
            await context.edit("emm...当前对话存在于自动已读对话列表中。")
        else:
            await context.edit("emm...当前对话不存在于自动已读对话列表中。")
    else:
        await context.edit("出错了呜呜呜 ~ 无效的参数。")
Beispiel #14
0
async def span_ban_Set(context):
    """ Toggles sb of a group. """
    if not redis_status():
        await context.edit(f"{lang('error_prefix')}{lang('redis_dis')}")
        return
    if len(context.parameter) != 1:
        await context.edit(f"{lang('error_prefix')}{lang('arg_error')}")
        return
    if not context.is_group:
        await context.edit(lang('ghost_e_mark'))
        return
    admins = await context.client.get_participants(
        context.chat, filter=ChannelParticipantsAdmins)
    if context.sender in admins:
        user = admins[admins.index(context.sender)]
        if not user.participant.admin_rights.ban_users:
            await context.edit(lang('sb_no_per'))
            return
    else:
        await context.edit(lang('sb_no_per'))
        return
    groups = redis.get('sb_groups')
    if groups:
        groups = groups.decode()
        groups = groups.split('|')
        try:
            groups.remove('')
        except ValueError:
            pass
    else:
        groups = []
    if context.parameter[0] == "true":
        if str(context.chat_id) not in groups:
            groups.append(str(context.chat_id))
            groups = '|'.join(groups)
            redis.set('sb_groups', groups)
            await context.edit(
                f"ChatID {str(context.chat_id)} {lang('sb_set')}")
            await log(f"ChatID {str(context.chat_id)} {lang('sb_set')}")
        else:
            await context.edit(
                f"ChatID {str(context.chat_id)} {lang('sb_set')}")
    elif context.parameter[0] == "false":
        if str(context.chat_id) in groups:
            groups.remove(str(context.chat_id))
            groups = '|'.join(groups)
            redis.set('sb_groups', groups)
            await context.edit(
                f"ChatID {str(context.chat_id)} {lang('sb_remove')}")
            await log(f"ChatID {str(context.chat_id)} {lang('sb_remove')}")
        else:
            await context.edit(
                f"ChatID {str(context.chat_id)} {lang('sb_remove')}")
    elif context.parameter[0] == "status":
        if str(context.chat_id) in groups:
            await context.edit(lang('sb_exist'))
        else:
            await context.edit(lang('sb_no_exist'))
    else:
        await context.edit(f"{lang('error_prefix')}{lang('arg_error')}")
Beispiel #15
0
async def antichannelpin(context):
    if not redis_status():
        await context.edit(f"{lang('error_prefix')}{lang('redis_dis')}")
        return
    if len(context.parameter) != 1:
        await context.edit(f"{lang('error_prefix')}{lang('arg_error')}")
        return
    myself = await context.client.get_me()
    self_user_id = myself.id
    if context.parameter[0] == "true":
        if context.chat_id == self_user_id:
            await context.edit(lang('ghost_e_mark'))
            return
        redis.set("antichannelpin." + str(context.chat_id), "true")
        await context.edit(f"已成功开启群组 {str(context.chat_id)} 的自动取消频道置顶功能。")
        await log(f"已成功开启群组 {str(context.chat_id)} 的自动取消频道置顶功能。")
    elif context.parameter[0] == "false":
        if context.chat_id == self_user_id:
            await context.edit(lang('ghost_e_mark'))
            return
        try:
            redis.delete("antichannelpin." + str(context.chat_id))
        except:
            await context.edit('emm...当前对话不存在于自动取消频道置顶功能列表中。')
            return
        await context.edit(f"已成功关闭群组 {str(context.chat_id)} 的自动取消频道置顶功能。")
        await log(f"已成功关闭群组 {str(context.chat_id)} 的自动取消频道置顶功能。")
    elif context.parameter[0] == "status":
        if redis.get("antichannelpin." + str(context.chat_id)):
            await context.edit('当前对话存在于自动取消频道置顶功能列表中。')
        else:
            await context.edit('当前对话不存在于自动取消频道置顶功能列表中。')
    else:
        await context.edit(f"{lang('error_prefix')}{lang('arg_error')}")
Beispiel #16
0
async def deny(context):
    """ Toggles denying of a user. """
    if not redis_status():
        await context.edit("出错了呜呜呜 ~ Redis 离线,无法运行。")
        return
    if len(context.parameter) != 1:
        await context.edit("出错了呜呜呜 ~ 无效的参数。")
        return
    myself = await context.client.get_me()
    self_user_id = myself.id
    if context.parameter[0] == "true":
        if context.chat_id == self_user_id:
            await context.edit("在?为什么要在收藏夹里面用?")
            return
        redis.set("denied.chat_id." + str(context.chat_id), "true")
        await context.delete()
        await log(f"ChatID {str(context.chat_id)} 已被添加到自动拒绝对话列表中。")
    elif context.parameter[0] == "false":
        if context.chat_id == self_user_id:
            await context.edit("在?为什么要在收藏夹里面用?")
            return
        redis.delete("denied.chat_id." + str(context.chat_id))
        await context.delete()
        await log(f"ChatID {str(context.chat_id)} 已从自动拒绝对话列表中移除。")
    elif context.parameter[0] == "status":
        if redis.get("denied.chat_id." + str(context.chat_id)):
            await context.edit("emm...当前对话已被加入自动拒绝对话列表中。")
        else:
            await context.edit("emm...当前对话已从自动拒绝对话列表移除。")
    else:
        await context.edit("出错了呜呜呜 ~ 无效的参数。")
Beispiel #17
0
 async def _restart_complete_report():
     restart_args = redis.get("restart_edit")
     if restart_args:
         redis.delete("restart_edit")
         restart_args = restart_args.decode("utf-8")
         restart_msg, restart_chat = restart_args.split("|")
         await bot.edit_message(int(restart_chat), int(restart_msg),
                                lang('restart_complete'))
Beispiel #18
0
async def set_read_acknowledgement(context):
    """ Event handler to infinitely read ghosted messages. """
    if not redis_status():
        return
    if redis.get("ghosted.chat_id." + str(context.chat_id)):
        try:
            await context.client.send_read_acknowledge(context.chat_id)
        except ValueError:
            pass
Beispiel #19
0
async def updateConfig(context):
    configFileRemoteUrl = redis.get(configFileRemoteUrlKey)
    if configFileRemoteUrl:
        if downloadFileFromUrl(configFileRemoteUrl, configFilePath) != 0:
            redis.set(configFileRemoteUrlKey, configFileRemoteUrl)
            return -1
        else:
            return await loadConfigFile(context, True)
    return 0
Beispiel #20
0
async def auto_reply(context):
    global msg_rate, last_time
    chat_id = context.chat_id
    sender_id = context.sender_id
    if chat_id < 0:
        plain_rules = redis.get(f"keyword.{chat_id}.plain")
        regex_rules = redis.get(f"keyword.{chat_id}.regex")
        g_settings = redis.get("keyword.settings")
        n_settings = redis.get(f"keyword.{chat_id}.settings")
        plain_rules = plain_rules if plain_rules else b""
        regex_rules = regex_rules if regex_rules else b""
        g_settings = g_settings if g_settings else b""
        n_settings = n_settings if n_settings else b""
        plain_rules = str(plain_rules, "ascii")
        regex_rules = str(regex_rules, "ascii")
        g_settings = str(g_settings, "ascii")
        n_settings = str(n_settings, "ascii")
        plain_dict = parse_rules(plain_rules)
        regex_dict = parse_rules(regex_rules)
        g_settings = parse_rules(g_settings)
        n_settings = parse_rules(n_settings)
        g_mode = g_settings["mode"] if "mode" in g_settings else None
        n_mode = n_settings["mode"] if "mode" in n_settings else None
        mode = "0"
        g_list = g_settings["list"] if "list" in g_settings else None
        n_list = n_settings["list"] if "list" in n_settings else None
        user_list = []
        if g_mode and n_mode: mode = n_mode
        elif g_mode or n_mode: mode = g_mode if g_mode else n_mode
        if g_list and n_list: user_list = n_list
        elif g_list or n_list: user_list = g_list if g_list else n_list
        for k, v in plain_dict.items():
            if k in context.text and time.time() - last_time > msg_rate:
                if validate(str(sender_id), int(mode), user_list):
                    last_time = time.time()
                    await bot.send_message(chat_id, v)
        for k, v in regex_dict.items():
            pattern = re.compile(k)
            if pattern.search(
                    context.text) and time.time() - last_time > msg_rate:
                if validate(str(sender_id), int(mode), user_list):
                    last_time = time.time()
                    await bot.send_message(chat_id, v)
Beispiel #21
0
async def repeat_msg(context):
    """ Event handler. """
    if not redis_status():
        return
    if redis.get(f'repeat_{context.chat_id}_{context.sender_id}'):
        try:
            msg = await context.client.get_messages(context.chat_id, ids=context.id)
            return await context.client.send_message(context.chat_id, msg)
        except Exception as e:
            await log(f'Repeat Error:\n{e}')
Beispiel #22
0
async def force_group_msg(context: Message):
    if not redis_status():
        return
    join_chat = redis.get(f"group.chat_id.{context.chat_id}")
    if not join_chat:
        return
    if redis.get(f"group.chat_id.{context.chat_id}.{context.sender_id}"):
        return
    try:
        if context.sender.bot:
            pass
    except AttributeError:
        return
    try:
        try:
            await bot(GetParticipantRequest(context.chat, context.sender_id))
        except ValueError:
            await bot.get_participants(context.chat)
            await bot(GetParticipantRequest(context.chat, context.sender_id))
        redis.set(f'group.chat_id.{context.chat_id}.{context.sender_id}',
                  'true')
        redis.expire(f'group.chat_id.{context.chat_id}.{context.sender_id}',
                     3600)
    except UserNotParticipantError:
        try:
            reply = await context.get_reply_message()
            try:
                reply = reply.id
            except AttributeError:
                reply = None
            await context.delete()
            msg = await bot.send_message(
                context.chat_id,
                f'[{context.sender.first_name}](tg://user?id={context.sender_id}) '
                f'您需要先加入频道讨论群才能发言。',
                reply_to=reply)
            await sleep(5)
            await msg.delete()
        except ChatAdminRequiredError:
            redis.delete(f"group.chat_id.{context.chat_id}")
    except ChatAdminRequiredError:
        redis.delete(f"group.chat_id.{context.chat_id}")
Beispiel #23
0
async def sh(context):
    """ Run python commands from Telegram. """
    dev_mode = False
    # file
    if exists(f"data{sep}dev"):
        dev_mode = True
    # redis
    if redis_status():
        if redis.get("dev"):
            dev_mode = True
    if not dev_mode:
        return await context.edit(lang('eval_need_dev'))
    if context.is_channel and not context.is_group:
        await context.edit(lang('eval_channel'))
        return
    try:
        cmd = context.text.split(" ", maxsplit=1)[1]
    except IndexError:
        await context.edit(lang('arg_error'))
        return
    old_stderr = sys.stderr
    old_stdout = sys.stdout
    redirected_output = sys.stdout = io.StringIO()
    redirected_error = sys.stderr = io.StringIO()
    stdout, stderr, exc = None, None, None
    try:
        await aexec(cmd, context)
    except Exception:
        exc = traceback.format_exc()
    stdout = redirected_output.getvalue()
    stderr = redirected_error.getvalue()
    sys.stdout = old_stdout
    sys.stderr = old_stderr
    if exc:
        evaluation = exc
    elif stderr:
        evaluation = stderr
    elif stdout:
        evaluation = stdout
    else:
        evaluation = "Success"
    final_output = (
        "**>>>** ```{}``` \n```{}```".format(
            cmd,
            evaluation,
        )
    )
    if len(final_output) > 4096:
        await context.edit("**>>>** ```{}```".format(cmd))
        await attach_log(evaluation, context.chat_id, "output.log", context.id)
    else:
        await context.edit(final_output)
    await log(f"{lang('eval_success')}: `{cmd}`")
Beispiel #24
0
async def force_subscribe_msg(context: Message):
    if not redis_status():
        return
    join_chat = redis.get(f"sub.chat_id.{context.chat_id}")
    if not join_chat:
        return
    if redis.get(f"sub.chat_id.{context.chat_id}.{context.sender_id}"):
        return
    else:
        join_chat = join_chat.decode()
    try:
        if context.sender.bot:
            return
    except AttributeError:
        return
    try:
        try:
            await bot(GetParticipantRequest(join_chat, context.sender_id))
        except ValueError:
            await bot.get_participants(context.chat)
            await bot(GetParticipantRequest(join_chat, context.sender_id))
        redis.set(f'sub.chat_id.{context.chat_id}.{context.sender_id}', 'true')
        redis.expire(f'sub.chat_id.{context.chat_id}.{context.sender_id}',
                     3600)
    except UserNotParticipantError:
        try:
            await context.delete()
            try:
                msg = await bot.send_message(
                    context.chat_id,
                    f'[{context.sender.first_name}](tg://user?id={context.sender_id}) '
                    f'您需要先加入频道 @{join_chat} 才能发言。')
                await sleep(5)
                await msg.delete()
            except ValueError:
                pass
        except ChatAdminRequiredError:
            redis.delete(f"sub.chat_id.{context.chat_id}")
    except ChatAdminRequiredError:
        redis.delete(f"sub.chat_id.{context.chat_id}")
Beispiel #25
0
async def denyu(context):
    """ Toggles denying of a user. """
    if not redis_status():
        await context.edit("出错了呜呜呜 ~ Redis 离线,无法运行。")
        return
    myself = await context.client.get_me()
    self_user_id = myself.id
    uid = None
    offset = 0
    if len(context.parameter) != 2:
        reply_to_msg = await context.get_reply_message()
        if not reply_to_msg:
            await context.edit(
                "在某群中强制禁言某用户,需要删除他人消息权限,需要 redis。用法:回复某条消息,格式为 `-denyu <true|false|status>`"
            )
            return
        try:
            uid = reply_to_msg.sender.id
        except AttributeError:
            await context.edit("出错了呜呜呜 ~ 无法读取用户 id")
            return
        offset = 1
    else:
        uid = context.parameter[0]
    try:
        context.parameter[1 - offset]
    except IndexError:
        await context.edit("请指定参数 <true|false|status>!")
        return
    if context.parameter[1 - offset] == "true":
        if context.chat_id == self_user_id:
            await context.edit("在?为什么要在收藏夹里面用?")
            return
        redis.set(f"denieduser.{context.chat_id}.{uid}", "true")
        await context.delete()
        await log(f"ChatID {context.chat_id} UserID {uid} 已被添加到自动拒绝对话列表中。")
    elif context.parameter[1 - offset] == "false":
        if context.chat_id == self_user_id:
            await context.edit("在?为什么要在收藏夹里面用?")
            return
        redis.delete(f"denieduser.{context.chat_id}.{uid}")
        await context.delete()
        await log(f"ChatID {context.chat_id} UserID {uid} 已从自动拒绝对话列表中移除。")
    elif context.parameter[1 - offset] == "status":
        if redis.get(f"denieduser.{context.chat_id}.{uid}"):
            await context.edit("emm...当前对话的该用户已存在于自动拒绝对话列表中。")
        else:
            await context.edit("emm...当前对话不存在于自动拒绝对话列表中。")
    else:
        await context.edit("出错了呜呜呜 ~ 无效的参数。只能为 `<true|false|status>`。")
Beispiel #26
0
async def repeat(context):
    if not context.is_group:
        await context.edit('请在群组中运行。')
        return
    if not redis_status():
        await context.edit('出错了呜呜呜 ~ Redis 数据库离线。')
        return
    reply = await context.get_reply_message()
    if not reply or not reply.sender:
        await context.edit('请回复一个用户。')
        return
    uid = reply.sender_id
    if len(context.parameter) == 1:
        if redis.get(f'repeat_{context.chat_id}_{uid}'):
            await context.edit('此用户存在于自动复读列表。')
        else:
            await context.edit('此用户不存在于自动复读列表。')
        return
    if redis.get(f'repeat_{context.chat_id}_{uid}'):
        redis.delete(f'repeat_{context.chat_id}_{uid}')
        await context.edit('从自动复读列表移除成功。')
    else:
        redis.set(f'repeat_{context.chat_id}_{uid}', 'true')
        await context.edit('添加到自动复读列表成功。')
Beispiel #27
0
async def unpin_link_channel_message(context):
    """ Event handler to unpin linked channel messages. """
    if not redis_status():
        return
    if not redis.get("antichannelpin." + str(context.chat_id)):
        return
    try:
        if not isinstance(context.sender, Channel):
            return
    except:
        return
    await sleep(1)
    try:
        await context.unpin()
    except ChatAdminRequiredError:
        redis.delete("antichannelpin." + str(context.chat_id))
    except:
        pass
async def auto_process_channel_msg(context):
    """ Event handler to delete channel messages and ban channel. """
    if not redis_status():
        return
    if not context.is_group:
        return
    # 匿名管理员
    if not context.sender:
        return
    data = redis.get("antichannelmsg." + str(context.chat_id))
    if not data:
        return
    try:
        if not isinstance(context.sender, Channel):
            return
        data = data.decode().split(" ")
        # 白名单
        if str(context.sender.id) in data:
            return
        # 删除消息,封禁频道
        try:
            await context.delete()
            entity = await context.client.get_input_entity(context.chat_id)
            user = await context.client.get_input_entity(context.sender.id)
            await context.client(EditBannedRequest(
                channel=entity,
                participant=user,
                banned_rights=ChatBannedRights(
                    until_date=None, view_messages=True)
            ))
        except ChatAdminRequiredError:
            redis.delete("antichannelmsg." + str(context.chat_id))
    except:
        return
    try:
        await context.unpin()
    except ChatAdminRequiredError:
        redis.delete("antichannelmsg." + str(context.chat_id))
    except:
        pass
Beispiel #29
0
async def run_every_1_day():
    # remove mp3 , they are so big !
    for i in os.listdir("data"):
        if i.find(".mp3") != -1 or i.find(".jpg") != -1 or i.find(".flac") != -1 or i.find(".ogg") != -1:
            os.remove(f"data{os.sep}{i}")
    # backup redis
    redis_data = {}
    if redis_status():
        for k in redis.keys():
            data_type = redis.type(k)
            if data_type == b'string':
                v = redis.get(k)
                redis_data[k.decode()] = v.decode()
    with open(f"data{os.sep}redis.json", "w", encoding='utf-8') as f:
        json.dump(redis_data, f, indent=4)
    # run backup function
    if strtobool(config['log']):
        make_tar_gz(f"pagermaid_{datetime.now().date()}.tar.gz", ["data", "plugins", "config.yml"])
        await upload_attachment(f"pagermaid_{datetime.now().date()}.tar.gz", int(config['log_chatid']), None)
        os.remove(f"pagermaid_{datetime.now().date()}.tar.gz")
    else:
        make_tar_gz(f"pagermaid_backup.tar.gz", ["data", "plugins", "config.yml"])
Beispiel #30
0
async def span_ban(context):
    if context.reply_to_msg_id:
        reply_message = await context.get_reply_message()
        if reply_message:
            try:
                user = reply_message.from_id
            except AttributeError:
                await context.edit(lang('arg_error'))
                return
        else:
            await context.edit(lang('arg_error'))
            return
        if isinstance(user, PeerChannel):
            # 封禁频道
            try:
                entity = await context.client.get_input_entity(context.chat_id)
                user = await context.client.get_input_entity(
                    reply_message.sender.id)
                await context.client(
                    EditBannedRequest(
                        channel=entity,
                        participant=user,
                        banned_rights=ChatBannedRights(until_date=None,
                                                       view_messages=True)))
            except ChatAdminRequiredError:
                return await context.edit(lang('sb_no_per'))
            return await context.edit(lang('sb_channel'))
        elif not user:
            return await context.edit(lang('arg_error'))
        target_user = await context.client(GetFullUserRequest(user))
    else:
        if len(context.parameter) == 1:
            user = context.parameter[0].strip("`")
            if user.isnumeric():
                user = int(user)
                if user < 0:
                    return await context.edit(lang('arg_error'))
        else:
            return await context.edit(lang('arg_error'))
        if context.message.entities is not None:
            if isinstance(context.message.entities[0],
                          MessageEntityMentionName):
                user = context.message.entities[0].user_id
            elif isinstance(context.message.entities[0], MessageEntityPhone):
                user = int(context.parameter[0])
            elif isinstance(context.message.entities[0], MessageEntityCode):
                pass
            else:
                return await context.edit(
                    f"{lang('error_prefix')}{lang('arg_error')}")
        try:
            user_object = await context.client.get_entity(user)
            target_user = await context.client(
                GetFullUserRequest(user_object.id))
        except (TypeError, ValueError, OverflowError,
                StructError) as exception:
            if str(exception).startswith(
                    "Cannot find any entity corresponding to"):
                await context.edit(
                    f"{lang('error_prefix')}{lang('profile_e_no')}")
                return
            if str(exception).startswith("No user has"):
                await context.edit(
                    f"{lang('error_prefix')}{lang('profile_e_nou')}")
                return
            if str(exception).startswith(
                    "Could not find the input entity for") or isinstance(
                        exception, StructError):
                await context.edit(
                    f"{lang('error_prefix')}{lang('profile_e_nof')}")
                return
            if isinstance(exception, OverflowError):
                await context.edit(
                    f"{lang('error_prefix')}{lang('profile_e_long')}")
                return
            raise exception
    chat = await context.get_chat()
    if len(context.parameter) == 0:
        try:
            await context.client(
                DeleteUserHistoryRequest(channel=chat, user_id=target_user))
        except UserAdminInvalidError:
            pass
        except ChatAdminRequiredError:
            pass
    myself = await context.client.get_me()
    self_user_id = myself.id
    if target_user.user.id == self_user_id:
        await context.edit(lang('arg_error'))
        return
    result = await context.client(
        GetCommonChatsRequest(user_id=target_user, max_id=0, limit=100))
    count = 0
    groups = []
    for i in result.chats:
        try:
            chat = await context.client.get_entity(i.id)
            if len(context.parameter) == 0:
                await context.client(
                    DeleteUserHistoryRequest(channel=chat,
                                             user_id=target_user))
            await context.client.edit_permissions(i.id,
                                                  target_user,
                                                  view_messages=False)
            groups.append(mention_group(i))
            count += 1
        except FloodWaitError as e:
            # Wait flood secs
            await context.edit(
                f'{lang("sb_pause")} {e.seconds + uniform(0.5, 1.0)} s.')
            try:
                await sleep(e.seconds + uniform(0.5, 1.0))
            except Exception as e:
                print(f"Wait flood error: {e}")
                return
        except UserAdminInvalidError:
            pass
        except ChatAdminRequiredError:
            pass
        except ValueError:
            pass
    if redis_status():
        sb_groups = redis.get('sb_groups')
        if sb_groups:
            sb_groups = sb_groups.decode()
            sb_groups = sb_groups.split('|')
            try:
                sb_groups.remove('')
            except ValueError:
                pass
        else:
            sb_groups = []
        for i in sb_groups:
            try:
                chat = await context.client.get_entity(int(i))
                if len(context.parameter) == 0:
                    await context.client(
                        DeleteUserHistoryRequest(channel=chat,
                                                 user_id=target_user))
                await context.client.edit_permissions(chat,
                                                      target_user,
                                                      view_messages=False)
                groups.append(mention_group(chat))
                count += 1
            except FloodWaitError as e:
                # Wait flood secs
                await context.edit(
                    f'{lang("sb_pause")} {e.seconds + uniform(0.5, 1.0)} s.')
                try:
                    await sleep(e.seconds + uniform(0.5, 1.0))
                except Exception as e:
                    print(f"Wait flood error: {e}")
                    return
            except UserAdminInvalidError:
                pass
            except ChatAdminRequiredError:
                pass
    if count == 0:
        text = f'{lang("sb_no")} {mention_user(target_user.user)}'
    else:
        text = f'{lang("sb_per")} {count} {lang("sb_in")} {mention_user(target_user.user)}'
    await context.edit(text)
    if len(groups) > 0:
        groups = f'\n{lang("sb_pro")}\n' + "\n".join(groups)
    else:
        groups = ''
    await log(f'{text}\nuid: `{target_user.user.id}` {groups}')