Exemple #1
0
async def upload_document(client: Client, file_path: str,
                          chat_id: int) -> raw.base.InputDocument:
    media = await client.send(
        raw.functions.messages.UploadMedia(
            peer=await client.resolve_peer(chat_id),
            media=raw.types.InputMediaUploadedDocument(
                mime_type=client.guess_mime_type(file_path)
                or "application/zip",
                file=await client.save_file(file_path),
                attributes=[
                    raw.types.DocumentAttributeFilename(
                        file_name=os.path.basename(file_path))
                ])))
    return raw.types.InputDocument(
        id=media.document.id,
        access_hash=media.document.access_hash,
        file_reference=media.document.file_reference)
Exemple #2
0
def getext(c: Client, msg: Message) -> Optional[str]:
    """Get the extension of a document in a message"""

    if msg.reply_to_message.photo:
        return ".jpeg"

    elif msg.reply_to_message.sticker:
        return ".webp"

    for media_type in ("document", "audio", "video", "animation", "voice",
                       "videonote"):
        if hasattr(msg.reply_to_message, media_type):

            if msg.reply_to_message[media_type].file_name:
                return c.guess_extension(
                    c.guess_mime_type(
                        msg.reply_to_message[media_type].file_name)
                ) or os.path.splitext(
                    msg.reply_to_message[media_type].file_name)[-1]

            if msg.reply_to_message[media_type].mime_type:
                return c.guess_extension(
                    msg.reply_to_message[media_type].mime_type)
Exemple #3
0
async def kang_sticker(c: Client, m: Message):
    prog_msg = await m.reply_text(await tld(m.chat.id, "stickers_kanging"))
    user = await c.get_me()
    bot_username = user.username
    sticker_emoji = "🤔"
    packnum = 0
    packname_found = False
    resize = False
    animated = False
    reply = m.reply_to_message
    user = await c.resolve_peer(m.from_user.username or m.from_user.id)

    if reply and reply.media:
        if reply.photo:
            resize = True
        elif reply.document:
            if "image" in reply.document.mime_type:
                # mime_type: image/webp
                resize = True
            elif "tgsticker" in reply.document.mime_type:
                # mime_type: application/x-tgsticker
                animated = True
        elif reply.sticker:
            if not reply.sticker.file_name:
                return await prog_msg.edit_text(await tld(
                    m.chat.id, "err_sticker_no_file_name"))
            if reply.sticker.emoji:
                sticker_emoji = reply.sticker.emoji
            animated = reply.sticker.is_animated
            if not reply.sticker.file_name.endswith(".tgs"):
                resize = True
        else:
            return await prog_msg.edit_text(await tld(m.chat.id,
                                                      "invalid_media_string"))
        pack_prefix = "anim" if animated else "a"
        packname = f"{pack_prefix}_{m.from_user.id}_by_{bot_username}"

        if len(m.command) > 1:
            if m.command[1].isdigit() and int(m.command[1]) > 0:
                # provide pack number to kang in desired pack
                packnum = m.command.pop(1)
                packname = f"{pack_prefix}{packnum}_{m.from_user.id}_by_{bot_username}"
            if len(m.command) > 1:
                # matches all valid emojis in input
                sticker_emoji = ("".join(
                    set(EMOJI_PATTERN.findall("".join(m.command[1:]))))
                                 or sticker_emoji)
        filename = await c.download_media(m.reply_to_message)
        if not filename:
            # Failed to download
            await prog_msg.delete()
            return
    elif m.entities and len(m.entities) > 1:
        packname = f"c{m.from_user.id}_by_{bot_username}"
        pack_prefix = "a"
        # searching if image_url is given
        img_url = None
        filename = "sticker.png"
        for y in m.entities:
            if y.type == "url":
                img_url = m.text[y.offset:(y.offset + y.length)]
                break
        if not img_url:
            await prog_msg.delete()
            return
        try:
            r = await http.get(img_url)
            if r.status_code == 200:
                with open(filename, mode="wb") as f:
                    f.write(r.read())
        except Exception as r_e:
            return await prog_msg.edit_text(f"{r_e.__class__.__name__} : {r_e}"
                                            )
        if len(m.command) > 2:
            # m.command[1] is image_url
            if m.command[2].isdigit() and int(m.command[2]) > 0:
                packnum = m.command.pop(2)
                packname = f"a{packnum}_{m.from_user.id}_by_{bot_username}"
            if len(m.command) > 2:
                sticker_emoji = ("".join(
                    set(EMOJI_PATTERN.findall("".join(m.command[2:]))))
                                 or sticker_emoji)
            resize = True
    else:
        return await prog_msg.edit_text(await tld(m.chat.id,
                                                  "stickers_kang_noreply"))
    try:
        if resize:
            filename = resize_image(filename)
        max_stickers = 50 if animated else 120
        while not packname_found:
            try:
                stickerset = await c.send(
                    GetStickerSet(
                        stickerset=InputStickerSetShortName(
                            short_name=packname),
                        hash=0,
                    ))
                if stickerset.set.count >= max_stickers:
                    packnum += 1
                    packname = (
                        f"{pack_prefix}_{packnum}_{m.from_user.id}_by_{bot_username}"
                    )
                else:
                    packname_found = True
            except StickersetInvalid:
                break
        file = await c.save_file(filename)
        media = await c.send(
            SendMedia(
                peer=(await c.resolve_peer(CHAT_LOGS)),
                media=InputMediaUploadedDocument(
                    file=file,
                    mime_type=c.guess_mime_type(filename),
                    attributes=[DocumentAttributeFilename(file_name=filename)],
                ),
                message=f"#Sticker kang by UserID -> {m.from_user.id}",
                random_id=c.rnd_id(),
            ), )
        msg_ = media.updates[-1].message
        stkr_file = msg_.media.document
        if packname_found:
            await prog_msg.edit_text(await tld(m.chat.id, "use_existing_pack"))
            await c.send(
                AddStickerToSet(
                    stickerset=InputStickerSetShortName(short_name=packname),
                    sticker=InputStickerSetItem(
                        document=InputDocument(
                            id=stkr_file.id,
                            access_hash=stkr_file.access_hash,
                            file_reference=stkr_file.file_reference,
                        ),
                        emoji=sticker_emoji,
                    ),
                ))
        else:
            await prog_msg.edit_text(await tld(m.chat.id,
                                               "create_new_pack_string"))
            stkr_title = f"{m.from_user.first_name[:32]}'s "
            if animated:
                stkr_title += "Anim. "
            stkr_title += "Smudge Pack"
            if packnum != 0:
                stkr_title += f" v{packnum}"
            try:
                await c.send(
                    CreateStickerSet(
                        user_id=user,
                        title=stkr_title,
                        short_name=packname,
                        stickers=[
                            InputStickerSetItem(
                                document=InputDocument(
                                    id=stkr_file.id,
                                    access_hash=stkr_file.access_hash,
                                    file_reference=stkr_file.file_reference,
                                ),
                                emoji=sticker_emoji,
                            )
                        ],
                        animated=animated,
                    ))
            except PeerIdInvalid:
                return await prog_msg.edit_text(
                    await tld(m.chat.id, "stickers_pack_contact_pm"),
                    reply_markup=InlineKeyboardMarkup([[
                        InlineKeyboardButton(
                            "/start", url=f"https://t.me/{bot_username}?start")
                    ]]),
                )
    except Exception as all_e:
        await prog_msg.edit_text(f"{all_e.__class__.__name__} : {all_e}")
    else:
        await prog_msg.edit_text(
            (await
             tld(m.chat.id,
                 "sticker_kanged_string")).format(packname, sticker_emoji))
        # Cleanup
        await c.delete_messages(chat_id=CHAT_LOGS,
                                message_ids=msg_.id,
                                revoke=True)
        try:
            os.remove(filename)
        except OSError:
            pass