예제 #1
0
async def last_logged(message: Message):
    """get last traceback from main account"""
    limit_ = message.input_str
    if not limit_:
        limit_ = 5
    elif not limit_.isdigit():
        return await message.edit("`Provide a number as limit.`", del_in=5)
    if limit_ > 10:
        return await message.edit("`Can't search more than 10 messages.`",
                                  del_in=5)
    await message.edit("`Looking for last traceback...`")
    num = 0
    me_ = (await userge.get_me()).first_name
    async for msg_ in userge.search_messages(Config.LOG_CHANNEL_ID):
        if msg_type(msg_) == "text":
            num += 1
            if "-e" in message.flags:
                search_ = "#EXECUTOR"
                found_ = "eval traceback"
            else:
                search_ = "#TRACEBACK"
                found_ = "traceback"
            if search_ in msg_.text:
                text_ = msg_.text.html
                text_ = text_.replace("\n", "<br>")
                link_ = post_to_telegraph(
                    f"{found_.capitalize()} from log channel of {me_}.", text_)
                return await message.edit(
                    f"Last <b>{found_}</b> is [<b>HERE</b>]({link_}).",
                    disable_web_page_preview=True,
                )
            if num == limit_:
                return await message.edit(
                    f"`Couldn't find {found_} in last {limit_} messages.`",
                    del_in=5)
예제 #2
0
async def song_search(message: Message):
    """get songs from channel"""
    song = message.input_str
    if not song:
        await message.err("Provide a song name or artist name to search",
                          del_in=10)
        return
    search = await message.edit("ЁЯФН __Searching For__ **{}**".format(song))
    chat_id = message.chat.id
    f_id = ""
    f_ref = ""
    try:
        async for msg in userge.search_messages(-1001271479322,
                                                query=song,
                                                limit=1,
                                                filter="audio"):
            f_id, f_ref = get_file_id_and_ref(msg)
    except BadRequest:
        await search.edit(
            "Join [THIS](https://t.me/joinchat/DdR2SUvJPBouSW4QlbJU4g) channel first"
        )
        return
    if not (f_id or f_ref):
        await search.edit("тЪая╕П Song Not Found !", del_in=5)
        return
    await userge.send_audio(chat_id, f_id, f_ref)
    await search.delete()
예제 #3
0
async def load_all_plugins():
    success = 0
    total = 0
    p_error = ''
    async for _file in userge.search_messages(PLUGINS_CHAT_ID,
                                              filter="document"):
        total += 1
        file_ = _file.document
        if file_.file_name.endswith('.py') and file_.file_size < 2**20:
            if not os.path.isdir(Config.TMP_PATH):
                os.makedirs(Config.TMP_PATH)
            t_path = os.path.join(Config.TMP_PATH, file_.file_name)
            if os.path.isfile(t_path):
                os.remove(t_path)
            await _file.download(file_name=t_path)
            plugin = get_import_path(ROOT, t_path)
            try:
                await userge.load_plugin(plugin, reload_plugin=True)
                await userge.finalize_load()
            except (ImportError, SyntaxError, NameError) as i_e:
                os.remove(t_path)
                p_error += f'\n\n**PLUGIN:** `{file_.file_name}`\n**ERROR:** `{i_e}`'
            else:
                success += 1
                _LOG.info(f"Loaded {plugin}")
    return (success, total, p_error)
예제 #4
0
async def media_h(message: Message):
    reply = message.reply_to_message
    if not reply:
        return await message.err("reply to a User")
    start = time.time()
    await message.edit(
        'This process takes soo much F*ing Time 😂 so here\'s a quote 🙆‍♀️\n\n`"All you gotta do is chill out... Let go of control and chill out... Let it be, Trust."`\n- **Esther Hicks**'
    )
    x = PrettyTable()
    media_dict = {}
    # Generate json
    for m in TYPES:
        media_dict[m] = {}
        media_dict[m]["file_size"] = 0
        media_dict[m]["count"] = 0
        media_dict[m]["max_size"] = 0
        media_dict[m]["max_file_link"] = ""
    # Count
    msg_count = 0
    x.title = "File Summary:"
    x.field_names = ["Media", "Count", "File size"]
    largest = "   <b>Largest Size</b>\n"
    u_mention = mention_html(reply.from_user.id, reply.from_user.first_name)
    async for msg in userge.search_messages(
        message.chat.id, "", from_user=reply.from_user.id
    ):
        msg_count += 1
        for media in TYPES:
            if msg[media]:
                media_dict[media]["file_size"] += msg[media].file_size
                media_dict[media]["count"] += 1
                if msg[media].file_size > media_dict[media]["max_size"]:
                    media_dict[media]["max_size"] = msg[media].file_size
                    media_dict[media]["max_file_link"] = msg.link

    for mediax in TYPES:
        x.add_row(
            [
                mediax,
                media_dict[mediax]["count"],
                humanbytes(media_dict[mediax]["file_size"]),
            ]
        )
        if media_dict[mediax]["count"] != 0:
            largest += f"•  [{mediax}]({media_dict[mediax]['max_file_link']}) : <code>{humanbytes(media_dict[mediax]['max_size'])}</code>\n"

    result = f"<b>{message.chat.title}</b>\n"
    result += f"👤 <b>User</b> : {u_mention}\n"
    result += f"<code>Total Messages: {msg_count}</code>\n"
    result += f"```{str(x)}```\n"
    result += f"{largest}\n"
    end = time.time()
    result += f"⏳ <code>Process took: {time_formatter(end - start)}</code>."
    await message.edit(result, disable_web_page_preview=True)
예제 #5
0
async def check_audio_files_in_channel(channel: str):
    try:
        list = []
        async for _ in userge.search_messages(channel, filter="audio"):
            list.append(_.audio.file_id)
            total = len(list)
            if total == 0:
                return "ERROR no audio files."
            else:
                return f"found {total} audio files in @{channel}"
    except Exception as e:
        print("ERROR:", e)
예제 #6
0
파일: copies.py 프로젝트: prono69/Custom
async def copy_channel_(message: Message):
    """copy channel content"""
    await message.edit("`Checking channels...`")
    me_ = await userge.get_me()
    input_ = message.input_str
    from_chann = input_.split()[0]
    to_chann = input_.split()[1]
    try:
        try:
            from_chann = int(from_chann)
        except BaseException:
            pass
        from_ = await userge.get_chat(from_chann)
    except BaseException as e:
        return await message.edit(
            f"`Given from_channel '{from_chann}' is invalid...`\nERROR: {str(e)}",
            del_in=5,
        )
    try:
        try:
            to_chann = int(to_chann)
        except BaseException:
            pass
        to_ = await userge.get_chat(to_chann)
    except BaseException:
        return await message.edit(
            f"`Given to_channel '{to_chann}' is invalid...`", del_in=5)
    if from_.type != "channel" or to_.type != "channel":
        return await message.edit(
            "`One or both of the given chat is/are not channel...`", del_in=5)
    total = 0
    list_ = []
    await message.edit(
        f"`Copying posts from `<b>{from_.title}</b>` to `<b>{to_.title}</b>..."
    )
    async for post in userge.search_messages(from_.id):
        list_.append(post.message_id)
    list_.reverse()
    try:
        for one_msg in list_:
            await userge.copy_message(to_.id, from_.id, one_msg)
            total += 1
    except FloodWait as e:
        await asyncio.sleep(e.x + 3)
    except Exception as e:
        await CHANNEL.log(f"ERROR: {str(e)}")
        return await message.edit(
            "`Something went wrong, see log channel for error...`")
    out_ = f"`Forwarded `<b>{total}</b>` from `<b>{from_.title}</b>` to `<b>{to_.title}</b>`.`"
    await message.edit(out_)
    await CHANNEL.log(out_)
예제 #7
0
async def purgeme_(message: Message):
    """purge given no. of your messages"""
    await message.edit("`purging ...`")
    if not (message.input_str and message.input_str.isdigit()):
        return await message.err("Provide a valid number of message to delete",
                                 del_in=3)
    start_t = datetime.datetime.now()
    number = min(int(message.input_str), 100)
    mid = message.message_id
    msg_list = []
    # https://t.me/pyrogramchat/266224
    # search_messages takes some minutes to index new messages
    # so using iter_history to get messages newer than 5 mins.
    old_msg = (start_t - datetime.timedelta(minutes=5)).timestamp()

    async for msg in userge.search_messages(message.chat.id,
                                            "",
                                            limit=number,
                                            from_user="******"):
        msg_list.append(msg.message_id)

    async for new_msg in userge.iter_history(message.chat.id,
                                             offset_id=mid,
                                             offset=0):
        if new_msg.from_user.is_self:
            msg_list.append(new_msg.message_id)
        if old_msg > new_msg.date or (msg_list and
                                      (msg_list[-1] > new_msg.message_id)):
            break

    # https://stackoverflow.com/questions/39734485/python-combining-two-lists-and-removing-duplicates-in-a-functional-programming
    del_list = list(set(msg_list))
    if mid in del_list:
        del_list.remove(mid)
    del_list.reverse()
    del_list_ = del_list[:number]

    await userge.delete_messages(message.chat.id, message_ids=del_list_)

    end_t = datetime.datetime.now()
    time_taken_s = (end_t - start_t).seconds
    out = f"<u>purged</u> {len(del_list_)} messages in {time_taken_s} seconds."
    await message.edit(out, del_in=3)
예제 #8
0
async def purgeme_(message: Message):
    """purge given no. of your messages"""
    await message.edit("`purging ...`")
    if not (message.input_str and message.input_str.isdigit()):
        return await message.err("Provide a valid number of message to delete",
                                 del_in=3)
    start_t = time.time()
    number = min(int(message.input_str), 100)
    msg_list = []
    async for msg in userge.search_messages(message.chat.id,
                                            "",
                                            limit=number,
                                            from_user="******"):
        msg_list.append(msg.message_id)
    await userge.delete_messages(message.chat.id, message_ids=msg_list)
    end_t = time.time()
    out = (
        f"<u>purged</u> {len(msg_list)} messages in {time_formatter(end_t - start_t)}."
    )
    await message.edit(out, del_in=3, log=__name__)
예제 #9
0
async def purgeme_(message: Message):
    """purge given no. of your messages"""
    await message.edit("`purging ...`")
    if not (message.input_str and message.input_str.isdigit()):
        return await message.err("Provide a valid number of message to delete",
                                 del_in=3)
    start_t = time.time()
    number = min(int(message.input_str), 100)
    msg_list = []
    new_msg = []

    old_msg = (datetime.datetime.now() -
               datetime.timedelta(minutes=5)).timestamp()

    async for msgg in userge.iter_history(message.chat.id,
                                          offset_id=message.message_id,
                                          offset=0):
        if msgg.from_user.is_self:
            new_msg.append(msgg.message_id)
        if old_msg > msgg.date:
            break

    async for msg in userge.search_messages(message.chat.id,
                                            "",
                                            limit=number,
                                            from_user="******"):
        msg_list.append(msg.message_id)
        if new_msg:
            for mids in new_msg:
                if mids > msg.message_id:
                    msg_list.append(mids)

    await userge.delete_messages(message.chat.id, message_ids=msg_list)
    end_t = time.time()
    out = (
        f"<u>purged</u> {len(msg_list)} messages in {time_formatter(end_t - start_t)}."
    )
    await message.edit(out, del_in=3)
예제 #10
0
async def copy_channel_(message: Message):
    """copy channel content"""
    await message.edit("`Checking channels...`")
    me_ = await userge.get_me()
    input_ = message.input_str
    from_chann = input_.split()[0]
    to_chann = input_.split()[1]
    try:
        if from_chann.isdigit():
            from_chann = int(from_chann)
        from_ = await userge.get_chat(from_chann)
    except BaseException:
        return await message.edit(
            f"`Given from_channel '{from_chann}' is invalid...`", del_in=5
        )
    try:
        if to_chann.isdigit():
            to_chann = int(to_chann)
        to_ = await userge.get_chat(to_chann)
    except BaseException:
        return await message.edit(
            f"`Given to_channel '{to_chann}' is invalid...`", del_in=5
        )
    if from_.type != "channel" or to_.type != "channel":
        return await message.edit(
            "`One or both of the given chat is/are not channel...`", del_in=5
        )
    from_owner = await admin_or_creator(from_.id, me_.id)
    if not from_owner["is_admin"] and not from_owner["is_creator"]:
        return await message.edit(
            f"`Owner or admin required in ('{from_.title}') to copy posts...`", del_in=5
        )
    to_admin = await admin_or_creator(to_.id, me_.id)
    if not to_admin["is_admin"] and not to_admin["is_creator"]:
        return await message.edit(
            f"Need admin rights to copy posts to {to_.title}...", del_in=5
        )
    total = 0
    del_list = []
    await message.edit(
        f"`Copying posts from `<b>{from_.title}</b>` to `<b>{to_.title}</b>..."
    )
    async for post in userge.search_messages(from_.id):
        total += 1
        try:
            # first posting, which'll be in reverse order of original posts
            first_post = await userge.copy_messages(to_.id, from_.id, post.message_id)
            del_list.append(first_post.message_id)
        except FloodWait as e:
            await asyncio.sleep(e.x + 3)
    await message.edit(
        f"`Posting the {total} posts again to correct the their order...`"
    )
    for post_again in del_list:
        try:
            # second posting to correct the order
            await userge.copy_messages(message.chat.id, message.chat.id, post_again)
        except FloodWait as e:
            await asyncio.sleep(e.x + 3)
    try:
        await userge.delete_messages(del_list)
    except FloodWait as e:
        await asyncio.sleep(e.x + 3)
    out_ = f"`Forwarded `<b>{total}</b>` from `<b>{from_.title}</b>` to `<b>{to_.title}</b>`.`"
    await message.edit(out_)
    await CHANNEL.log(out_)