Untitled

mail@pastecode.io avatar
unknown
plain_text
2 years ago
12 kB
4
Indexable
Never
#shit
from hachoir.metadata import extractMetadata
from hachoir.parser import createParser
#end shit

from pyrogram.types import Message, InlineKeyboardMarkup, InlineKeyboardButton
import asyncio, time, os, re
from pyrogram.enums import MessageMediaType
from pyrogram.errors import exceptions
from .. import Bot, bot, bot as Drone, API_ID, API_HASH, userbot 
from main.plugins.progress import progress_for_pyrogram
from main.plugins.helpers import screenshot
#fucking login
from pyrogram.errors import (
    SessionPasswordNeeded, FloodWait,
    PhoneNumberInvalid, ApiIdInvalid,
    PhoneCodeInvalid, PhoneCodeExpired
)
#end fucking login
from pyrogram import Client, filters
from pyrogram.errors import ChannelBanned, ChannelInvalid, ChannelPrivate, ChatIdInvalid, ChatInvalid
#from ethon.pyfunc import video_metadata
from telethon import events
def thumbnail(sender):
    if os.path.exists(f'{sender}.jpg'):
        return f'{sender}.jpg'
    else:
         return None

async def check(userbot, client, link):
    msg_id = int(link.split("/")[-1])
    if 't.me/c/' in link:
        try:
            chat = int('-100' + str(link.split("/")[-2]))
            await userbot.get_messages(chat, msg_id)
            return True, None
        except ValueError:
            return False, "Error 601"
        except Exception as e:
            return False, f"`{str(e)}`"
    else:
        try:
            chat = str(link.split("/")[-2])
            await client.get_messages(chat, msg_id)
            return True, None
        except Exception as e:
            return False, f"{str(e)}"



async def get_msg(userbot, client, sender, edit_id, msg_link, i):
    edit = ""
    chat = ""
    msg_id = int(msg_link.split("/")[-1]) + int(i)
    if 't.me/c/' in msg_link:
        chat = int('-100' + str(msg_link.split("/")[-2]))
        try:
            msg = await userbot.get_messages(chat, msg_id)
            if msg.media:
                if msg.media == MessageMediaType.WEB_PAGE:
                    edit = await client.edit_message_text(sender, edit_id, "Forwarding...")
                    await client.send_message(sender, msg.text.markdown)
                    await edit.delete()
                    return
            if not msg.media:
                if msg.text:
                    edit = await client.edit_message_text(sender, edit_id, "Forwarding..")
                    await client.send_message(sender, msg.text.markdown)
                    await edit.delete()
                    return
                if msg.empty or msg.service or msg.dice or msg.location:
                    edit = await client.edit_message_text(sender, edit_id, "Passing message...")
                    #await client.send_message(sender, msg.text.markdown)
                    await edit.delete()
                    return
            edit = await client.edit_message_text(sender, edit_id, "📥 Starting Download")
            file = await userbot.download_media(
                msg,
                progress=progress_for_pyrogram,
                progress_args=(
                    client,
                    "**Downloading:**\n",
                    edit,
                    time.time()
                )
            )
            await edit.edit('📤 Uploading...')
            #caption = str(file)
            #f msg.caption is not None:
            #    caption = msg.caption
            caption = msg.caption
            caption_entities=msg.caption_entities
            #if str(file).split(".")[-1] in ['mkv', 'mp4', 'webm']:
            if msg.video or str(file).split(".")[-1] in ['mkv', 'mp4', 'webm', 'mov', 'MOV']:
                if str(file).split(".")[-1] in ['webm', 'mkv']:
                    path = str(file).split(".")[0] + ".mp4"
                    os.rename(file, path) 
                    file = str(file).split(".")[0] + ".mp4"
                #data = video_metadata(file)
                metadata = extractMetadata(createParser(file))
                duration = 0
                if metadata.has("duration"):
                    duration = metadata.get('duration').seconds
                width = 0
                height = 0
                #duration = data["duration"]
                thumb_path = await screenshot(file, duration, sender)
                await client.send_video(
                    chat_id=sender,
                    video=file,
                    caption=caption,
                    caption_entities=caption_entities,
                    supports_streaming=True,
                    duration=duration,
                    thumb=thumb_path,
                    progress=progress_for_pyrogram,
                    progress_args=(
                        client,
                        f'**Uploading {caption}**\n',
                        edit,
                        time.time()
                    )
                )
                try:
                    os.remove(file)
                except:
                    pass
"""
            elif msg.photo:
                await edit.edit(f"📷 Uploading {caption}")
                await bot.send_file(sender, file, caption=caption)
"""
                try:
                    os.remove(file)
                except:
                    pass
            elif msg.audio:
                await edit.edit(f"Uploading {caption}.")
                await client.send_audio(sender, file, caption=caption, caption_entities=caption_entities)
                await edit.delete() 
                try:
                    os.remove(file)
                except:
                    pass
            else:
                thumb_path=thumbnail(sender)
                await client.send_document(
                    sender,
                    file, 
                    caption=caption,
                    caption_entities=caption_entities,
                    thumb=thumb_path,
                    progress=progress_for_pyrogram,
                    progress_args=(
                        client,
                        f'**Uploading {caption}...**\n',
                        edit,
                        time.time()
                    )
                )
            await edit.delete()
        except (ChannelBanned, ChannelInvalid, ChannelPrivate, ChatIdInvalid, ChatInvalid) as e:
            await client.edit_message_text(sender, edit_id, f"Error: {str(e)}")
            return 
        except exceptions.bad_request_400.MessageNotModified:
            pass
            try:
                os.remove(file)
            except:
                pass
        except Exception as e:
            await client.edit_message_text(sender, edit_id, f'Somethhing went wrong while downloading `{msg_link}` error is {str(e)}')   
            await client.send_message("🧭 Trying alt method...")
            await client.send_document(sender, file, caption=caption, caption_entities=caption_entities, thumb=thumb_path, progress=progress_for_pyrogram, progress_args=(client,'**Uploading Document...**\n', edit, time.time()))   
            await asyncio.sleep(2)
            try:
                os.remove(file)
            except:
                pass
            return 
    else:
        edit = await client.edit_message_text(sender, edit_id, "Forwarding....")
        chat =  msg_link.split("/")[-2]
        try:
            await client.copy_message(int(sender), chat, msg_id)
        except:
              try:
                  await get_pmsg(userbot, bot, sender, msg_link, edit)
              except Exception as e:
                  await client.send_message("Something Went Wrong,\nError is {str(e)}")
        await edit.delete()
        


##########################Public group#############################
async def get_pmsg(userbot, client, sender, msg_link, edit):
    chat = ""
    msg_id = int(msg_link.split("/")[-1])
    if 't.me/' in msg_link and not 't.me/c' in msg_link:
        #st, r = check_timer(sender, process, timer) 
        #if st == False:
            #return await edit.edit(r) 
        chat =  msg_link.split("/")[-2]
        try:
            msg = await userbot.get_messages(chat, msg_id)
            if msg.media:
                if msg.media == MessageMediaType.WEB_PAGE:
                    edit = await client.edit_message_text(sender, edit_id, "⚡")
                    await client.send_message(sender, msg.text.markdown)
                    await edit.delete()
                    return
            if not msg.media:
                if msg.text:
                    #edit = await client.edit_message_text(sender, edit_id, "⏳")
                    await client.send_message(sender, msg.text.markdown)
                    await edit.delete()
                    return
                if msg.media in [MessageMediaType.SERVICE, MessageMediaType.EMPTY, MessageMediaType.DICE, MessageMediaType.LOCATION]:
                    edit = await client.edit_message_text(sender, edit_id, "This message doesn't exist.")
                    return 
            edit = await edit.edit('Processing...')
#end

            file = await userbot.download_media(
                msg,
                progress=progress_for_pyrogram,
                progress_args=(
                    userbot,
                    "**Downloading:**\n",
                    edit,
                    time.time()
                )
            )
            await edit.edit('UploadinG...')
            caption = str(file)
            if msg.caption is not None:
                caption = msg.caption
            if str(file).split(".")[-1] in ['mkv', 'mp4', 'webm']:
                if str(file).split(".")[-1] in ['webm', 'mkv']:
                    path = str(file).split(".")[0] + ".mp4"
                    os.rename(file, path) 
                    file = str(file).split(".")[0] + ".mp4"
                data = video_metadata(file)
                duration = data["duration"]
                thumb_path = await screenshot(file, duration/2, sender)
                await Bot.send_video(
                    chat_id=sender,
                    video=file,
                    caption=caption,
                    supports_streaming=True,
                    duration=duration,
                    thumb=thumb_path,
                    progress=progress_for_pyrogram,
                    progress_args=(
                        client,
                        '**Uploading:**\n',
                        edit,
                        time.time()
                    )
                )
            elif str(file).split(".")[-1] in ['jpg', 'jpeg', 'png', 'webp']:
                await edit.edit("Uploading image file...")
                await Bot.send_photo(sender, file, caption=caption)
                await edit.delete()
               # await set_timer(client, sender, process, timer)
                #for audio
            elif str(file).split(".")[-1] in ['mp3', 'ogg', 'wav', 'm4a', 'Flac', 'AAC']:
                
                
                await edit.edit("Uploading Audio File...")
                await Bot.send_audio(sender, file, caption=caption)
                await edit.delete() 
               # await set_timer(client, sender, process, timer)
            else:
                await Bot.send_document(
                    sender,
                    file, 
                    caption=caption,
                    progress=progress_for_pyrogram,
                    progress_args=(
                        client,
                        '<b><u>Uploading...</b></u>\n',
                        edit,
                        time.time()
                    )
                )
            await edit.delete()
            #await set_timer(client, sender, process, timer) 
        except Exception as e:
            await edit.edit(F'ERROR: {str(e)}')
            return 
    else:
         await Bot.send_message(event.chat.id, "🥺 Something unexpected occurred, please let me know.")