Ejemplo n.º 1
0
async def recovery(context):
    message = await context.get_reply_message()

    if message and message.media:  # Overwrite local backup
        if isinstance(message.media, MessageMediaDocument):
            try:
                if message.media.document.attributes[0].file_name.find(
                        ".tar.gz") != -1:  # Verify filename
                    await context.edit(lang('recovery_down'))
                    # Start download process
                    _file = BytesIO()
                    await context.client.download_file(message.media.document,
                                                       _file)
                    with open(pgm_backup_zip_name, "wb") as f:
                        f.write(_file.getvalue())
                else:
                    return await context.edit(lang('recovery_file_error'))
            except Exception as e:  # noqa
                print(e, format_exc())
                return await context.edit(lang('recovery_file_error'))
        else:
            return await context.edit(lang('recovery_file_error'))

    # Extract backup files
    await context.edit(lang('recovery_process'))
    if not os.path.exists(pgm_backup_zip_name):
        return await context.edit(lang('recovery_file_not_found'))
    elif not un_tar_gz(pgm_backup_zip_name, ""):
        os.remove(pgm_backup_zip_name)
        return await context.edit(lang('recovery_file_error'))

    # Recovery redis
    if redis_status() and os.path.exists(f"data{os.sep}redis.json"):
        with open(f"data{os.sep}redis.json", "r", encoding='utf-8') as f:
            try:
                redis_data = json.load(f)
                for k, v in redis_data.items():
                    redis.set(k, v)
            except json.JSONDecodeError:
                """JSON load failed, skip redis recovery"""
            except Exception as e:  # noqa
                print(e, format_exc())

    # Cleanup
    if os.path.exists(pgm_backup_zip_name):
        os.remove(pgm_backup_zip_name)
    if os.path.exists(f"data{os.sep}redis.json"):
        os.remove(f"data{os.sep}redis.json")

    result = await context.edit(
        lang('recovery_success') + " " + lang('apt_reboot'))
    if redis_status():
        redis.set("restart_edit", f"{result.id}|{result.chat_id}")
    await context.client.disconnect()
Ejemplo n.º 2
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')}")
Ejemplo n.º 3
0
def index():
    if not current_user.is_authenticated:
        return redirect(url_for('login'))
    memory = virtual_memory()
    memory_total = memory.total
    memory_available = memory.available
    memory_available_percentage = round(
        100 * float(memory_available) / float(memory_total), 2)
    memory_free = memory.free
    memory_free_percentage = round(
        100 * float(memory_free) / float(memory_total), 2)
    memory_buffered = memory.buffers
    memory_buffered_percentage = round(
        100 * float(memory_buffered) / float(memory_total), 2)
    memory_cached = memory.cached
    memory_cached_percentage = round(
        100 * float(memory_cached) / float(memory_total), 2)
    return render_template(
        'pages/index.html',
        hostname=uname().node,
        platform=platform,
        kernel=uname().release,
        python=python_version(),
        telethon=telethon_version.__version__,
        redis="Connected" if redis_status() else "Disconnected",
        memory_total=round(memory_total / 1048576, 2),
        memory_available=round(memory_available / 1048576, 2),
        memory_available_percentage=memory_available_percentage,
        memory_free=round(memory_free / 1048576, 2),
        memory_free_percentage=memory_free_percentage,
        memory_buffered=round(memory_buffered / 1048576, 2),
        memory_buffered_percentage=memory_buffered_percentage,
        memory_cached=round(memory_cached / 1048576, 2),
        memory_cached_percentage=memory_cached_percentage)
Ejemplo n.º 4
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')}")
Ejemplo n.º 5
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"))
Ejemplo n.º 6
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} 。')
Ejemplo n.º 7
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.")
Ejemplo n.º 8
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'成功在当前群组开启强制加入频道讨论群功能。')
Ejemplo n.º 9
0
async def status(context):
    # database
    database = lang('status_online') if redis_status() else lang(
        'status_offline')
    # uptime https://gist.github.com/borgstrom/936ca741e885a1438c374824efb038b3
    time_units = (('%m', 60 * 60 * 24 * 30), ('%d', 60 * 60 * 24),
                  ('%H', 60 * 60), ('%M', 60), ('%S', 1))

    async def human_time_duration(seconds):
        parts = {}
        for unit, div in time_units:
            amount, seconds = divmod(int(seconds), div)
            parts[unit] = str(amount)
        try:
            time_form = config['start_form']
        except (ValueError, KeyError):
            time_form = "%m/%d %H:%M"
        for key, value in parts.items():
            time_form = time_form.replace(key, value)
        return time_form

    current_time = datetime.utcnow()
    uptime_sec = (current_time - start_time).total_seconds()
    uptime = await human_time_duration(int(uptime_sec))
    text = (f"**{lang('status_hint')}** \n"
            f"{lang('status_name')}: `{uname().node}` \n"
            f"{lang('status_platform')}: `{platform}` \n"
            f"{lang('status_release')}: `{uname().release}` \n"
            f"{lang('status_python')}: `{python_version()}` \n"
            f"{lang('status_telethon')}: `{telethon_version.__version__}` \n"
            f"{lang('status_db')}: `{database}` \n"
            f"{lang('status_uptime')}: `{uptime}`")
    await context.edit(text)
Ejemplo n.º 10
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("出错了呜呜呜 ~ 无效的参数。")
Ejemplo n.º 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
Ejemplo n.º 12
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("出错了呜呜呜 ~ 无效的参数。")
Ejemplo n.º 13
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}")
Ejemplo n.º 14
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')}")
Ejemplo n.º 15
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
Ejemplo n.º 16
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
Ejemplo n.º 17
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()
Ejemplo n.º 18
0
async def status(context):
    database = "Connected" if redis_status() else "Disconnected"
    await context.edit(
        f"**PagerMaid-Modify 运行状态** \n"
        f"主机名: `{uname().node}` \n"
        f"主机平台: `{platform}` \n"
        f"Kernel 版本: `{uname().release}` \n"
        f"Python 版本: `{python_version()}` \n"
        f"Library 版本: `{telethon_version.__version__}` \n"
        f"数据库状态: `{'Connected' if redis_status() else 'Disconnected'}`")
Ejemplo n.º 19
0
async def alias_commands(context):
    source_commands = []
    to_commands = []
    texts = []
    for key, value in alias_dict.items():
        source_commands.append(key)
        to_commands.append(value)
    if len(context.parameter) == 0:
        await context.edit(lang('arg_error'))
        return
    elif len(context.parameter) == 1:
        if not len(source_commands) == 0:
            for i in range(0, len(source_commands)):
                texts.append(f'`{source_commands[i]}` --> `{to_commands[i]}`')
            await context.edit(lang('alias_list') + '\n\n' + '\n'.join(texts))
        else:
            await context.edit(lang('alias_no'))
    elif len(context.parameter) == 2:
        source_command = context.parameter[1]
        try:
            del alias_dict[source_command]
            with open("data/alias.json", 'w') as f:
                json_dump(alias_dict, f)
            result = await context.edit(lang('alias_success'))
            if redis_status():
                redis.set("restart_edit", f"{result.id}|{result.chat_id}")
            await context.client.disconnect()
        except KeyError:
            await context.edit(lang('alias_no_exist'))
            return
    elif len(context.parameter) == 3:
        source_command = context.parameter[1]
        to_command = context.parameter[2]
        if to_command in help_messages:
            await context.edit(lang('alias_exist'))
            return
        alias_dict[source_command] = to_command
        with open("data/alias.json", 'w') as f:
            json_dump(alias_dict, f)
        result = await context.edit(lang('alias_success'))
        if redis_status():
            redis.set("restart_edit", f"{result.id}|{result.chat_id}")
        await context.client.disconnect()
Ejemplo n.º 20
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}')
Ejemplo n.º 21
0
async def status(context):
    database = "Connected" if redis_status() else "Disconnected"
    await context.edit(
        f"**PagerMaid Status** \n"
        f"Hostname: `{uname().node}` \n"
        f"Host Platform: `{platform}` \n"
        f"Kernel Version: `{uname().release}` \n"
        f"Python Version: `{python_version()}` \n"
        f"Library version: `{telethon_version.__version__}` \n"
        f"Database Status: `{'Connected' if redis_status() else 'Disconnected'}`"
    )
Ejemplo n.º 22
0
async def status(context):
    database = lang('status_online') if redis_status() else lang(
        'status_offline')
    text = (f"**{lang('status_hint')}** \n"
            f"{lang('status_name')}: `{uname().node}` \n"
            f"{lang('status_platform')}: `{platform}` \n"
            f"{lang('status_release')}: `{uname().release}` \n"
            f"{lang('status_python')}: `{python_version()}` \n"
            f"{lang('status_telethon')}: `{telethon_version.__version__}` \n"
            f"{lang('status_db')}: `{database}`")
    await context.edit(text)
Ejemplo n.º 23
0
async def restart(context):
    """ To re-execute PagerMaid. """
    if not context.text[0].isalpha():
        try:
            result = await context.edit(lang('restart_processing'))
            if redis_status():
                redis.set("restart_edit", f"{result.id}|{result.chat_id}")

        except:  # noqa
            pass
        await log(lang('restart_log'))
        await context.client.disconnect()
Ejemplo n.º 24
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}`")
Ejemplo n.º 25
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
Ejemplo n.º 26
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>`。")
Ejemplo n.º 27
0
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')}")
Ejemplo n.º 28
0
async def auto_reply(context):
    if not redis_status():
        return
    global msg_rate, last_time
    chat_id = context.chat_id
    sender_id = context.sender_id
    if chat_id < 0:
        plain_dict = get_redis(f"keyword.{chat_id}.plain")
        regex_dict = get_redis(f"keyword.{chat_id}.regex")
        g_settings = get_redis("keyword.settings")
        n_settings = get_redis(f"keyword.{chat_id}.settings")
        g_mode = g_settings.get("mode", None)
        n_mode = n_settings.get("mode", None)
        mode = "0"
        g_list = g_settings.get("list", None)
        n_list = n_settings.get("list", 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
        send_text = context.text
        for k, v in plain_dict.items():
            if k in send_text and time.time() - last_time > msg_rate:
                if validate(str(sender_id), int(mode), user_list):
                    last_time = time.time()
                    await send_reply(chat_id, parse_multi(v), context)
        for k, v in regex_dict.items():
            pattern = re.compile(k)
            if pattern.search(
                    send_text) and time.time() - last_time > msg_rate:
                if validate(str(sender_id), int(mode), user_list):
                    last_time = time.time()
                    catch_pattern = r"\$\{regex_(?P<str>((?!\}).)+)\}"
                    count = 0
                    while re.search(catch_pattern, v) and count < 20:
                        search_data = re.search(k, send_text)
                        group_name = re.search(catch_pattern, v).group("str")
                        capture_data = get_capture(search_data, group_name)
                        if not capture_data: capture_data = ""
                        if re.search(catch_pattern, capture_data):
                            capture_data = ""
                        v = v.replace("${regex_%s}" % group_name, capture_data)
                        count += 1
                    await send_reply(chat_id, parse_multi(v), context)
Ejemplo n.º 29
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
Ejemplo n.º 30
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}")