Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Little bit improvement 😕 #48

Open
Magneto-noob opened this issue Mar 20, 2024 · 3 comments
Open

Little bit improvement 😕 #48

Magneto-noob opened this issue Mar 20, 2024 · 3 comments

Comments

@Magneto-noob
Copy link

Magneto-noob commented Mar 20, 2024

If we start batch process for private/public channel.. for example :- https://t.me/private or public_channel/1 - 10
and it Massage ID - 3,5,7 does not contain any media or content. Bot sending "Error : Telegram says: [400 MESSAGE_EMPTY] - The message sent is empty or contains invalid characters (caused by "messages.SendMessage")"

How to solve this problem.. i just want to skip those messages ID that doesn't contain any content by bot itself instead of sending error message [400 MESSAGE_EMPTY]

From Both public and private channel getting error like this.
Developer Please solve the problem. 😔🙏🏻

@davad00
Copy link

davad00 commented Mar 23, 2024

If we start batch process for private/public channel.. for example :- https://t.me/private or public_channel/1 - 10 and it Massage ID - 3,5,7 does not contain any media or content. Bot sending "Error : Telegram says: [400 MESSAGE_EMPTY] - The message sent is empty or contains invalid characters (caused by "messages.SendMessage")"

How to solve this problem.. i just want to skip those messages ID that doesn't contain any content by bot itself instead of sending error message [400 MESSAGE_EMPTY]

From Both public and private channel getting error like this. Developer Please solve the problem. 😔🙏🏻

#21 (comment)

you can try my iterated version its still not a100% stable under abuse but it works very nice :)

@pyphan1
Copy link

pyphan1 commented Mar 27, 2024

here is my fix for it
add this function anywhere in the code:

@bot.on_message(filters.command(["findlinks"]))
def find_links(client: pyrogram.client.Client, message: pyrogram.types.messages_and_media.message.Message):
    channel_username = message.text.split(" ", 1)[1].strip()
    chat = acc.get_chat(channel_username)
    print(chat.id)
    try:
        messages = acc.get_chat_history(chat.id) 
        photo_links = []
        video_links = []
        for msg in messages:
            if msg.photo:
                photo_links.append(f"https://t.me/{channel_username}/{msg.id}")
            elif msg.video:
                video_links.append(f"https://t.me/{channel_username}/{msg.id}")
        chunk_size = 100 
        if photo_links:
            bot.send_message(message.chat.id, 'photo links:')
        for i in range(0, len(photo_links), chunk_size):
            photo_chunk = photo_links[i:i+chunk_size]
            if photo_chunk:
                bot.send_message(message.chat.id, "\n".join(photo_chunk))
                time.sleep(1)
        if video_links:
            bot.send_message(message.chat.id, 'video links:')
        for i in range(0, len(video_links), chunk_size):
            video_chunk = video_links[i:i+chunk_size]
            if video_chunk:
                bot.send_message(message.chat.id,"\n".join(video_chunk))
                time.sleep(1)

    except Exception as e:
        bot.send_message(message.chat.id, f"Error occurred: {e}")

and then edit the save function's beggining
replace:

@bot.on_message(filters.text)
def save(client: pyrogram.client.Client, message: pyrogram.types.messages_and_media.message.Message):
	print(message.text)

with:

@bot.on_message(filters.text)
def save(client: pyrogram.client.Client, message: pyrogram.types.messages_and_media.message.Message):
	print(message.text)
	lines = message.text.split("\n")
	for line in lines:
                message.text = line

after you did this, use '/sendlinks channelname(without @)'
and then you recieve links for all photos, then you recieve links for all videos
copy the message and paste it and the bot will download them line by line
*you must specify string session to use this

@davad00
Copy link

davad00 commented Apr 14, 2024

here is my fix for it add this function anywhere in the code:

@bot.on_message(filters.command(["findlinks"]))
def find_links(client: pyrogram.client.Client, message: pyrogram.types.messages_and_media.message.Message):
    channel_username = message.text.split(" ", 1)[1].strip()
    chat = acc.get_chat(channel_username)
    print(chat.id)
    try:
        messages = acc.get_chat_history(chat.id) 
        photo_links = []
        video_links = []
        for msg in messages:
            if msg.photo:
                photo_links.append(f"https://t.me/{channel_username}/{msg.id}")
            elif msg.video:
                video_links.append(f"https://t.me/{channel_username}/{msg.id}")
        chunk_size = 100 
        if photo_links:
            bot.send_message(message.chat.id, 'photo links:')
        for i in range(0, len(photo_links), chunk_size):
            photo_chunk = photo_links[i:i+chunk_size]
            if photo_chunk:
                bot.send_message(message.chat.id, "\n".join(photo_chunk))
                time.sleep(1)
        if video_links:
            bot.send_message(message.chat.id, 'video links:')
        for i in range(0, len(video_links), chunk_size):
            video_chunk = video_links[i:i+chunk_size]
            if video_chunk:
                bot.send_message(message.chat.id,"\n".join(video_chunk))
                time.sleep(1)

    except Exception as e:
        bot.send_message(message.chat.id, f"Error occurred: {e}")

and then edit the save function's beggining replace:

@bot.on_message(filters.text)
def save(client: pyrogram.client.Client, message: pyrogram.types.messages_and_media.message.Message):
	print(message.text)

with:

@bot.on_message(filters.text)
def save(client: pyrogram.client.Client, message: pyrogram.types.messages_and_media.message.Message):
	print(message.text)
	lines = message.text.split("\n")
	for line in lines:
                message.text = line

after you did this, use '/sendlinks channelname(without @)' and then you recieve links for all photos, then you recieve links for all videos copy the message and paste it and the bot will download them line by line *you must specify string session to use this

i allowed myself to improve on your system :)

here it is if you want to use it:

async def find_links_command(self, message):
        try:
            channel_username = message.text.split(" ", 1)[1].strip()
            limit = 100  # Default limit
            limitMax = 500
            # Check if the user specified a custom limit
            parts = channel_username.split()
            if len(parts) > 1 and parts[-1].isdigit():
                custom_limit = int(parts[-1])
                if custom_limit > 0 and custom_limit <= limitMax:
                    await telegram_bot.bot.send_message(message.chat.id, f"Retrieving last {custom_limit} links...", reply_to_message_id=message.id, disable_web_page_preview=True)
                    limit = custom_limit
                    await asyncio.sleep(1)
                else:
                    await telegram_bot.bot.send_message(message.chat.id, "Next time try with a valid number between 1 and 500\nfor now retrieving last 100 links", reply_to_message_id=message.id, disable_web_page_preview=True)
                    limit = limit
                channel_username = " ".join(parts[:-1])

            photo_links = []
            video_links = []

            try:
                # Check if the channel username is an integer
                try:
                    
                    chat = await self.acc.get_chat(int("-100" + channel_username))
                    chatid = int(channel_username)
                    print("Channel Provided is ID: ", chatid)
                except ValueError:
                    # Assume the channel username is a string
                    chat = await self.acc.get_chat(channel_username)
                    chatid = str(channel_username)
                    print("Channel Provided is username: ", chatid)

                async for msg in self.acc.get_chat_history(chat.id, limit=limit):
                    if msg.photo:
                        photo_links.append(f"https://t.me/{channel_username}/{msg.id}")
                    elif msg.video:
                        video_links.append(f"https://t.me/{channel_username}/{msg.id}")

                # Sort photo_links and video_links by message ID in ascending order
                photo_links.sort(key=lambda link: int(link.split("/")[-1]))
                video_links.sort(key=lambda link: int(link.split("/")[-1]))

                # Group continuous links for photos and videos
                grouped_photo_links = self.group_continuous_links(photo_links)
                grouped_video_links = self.group_continuous_links(video_links)

                # Construct the final URLs with the channel username and prefix
                
                if isinstance(chatid, int):
                    final_photo_links = [f"https://t.me/c/{chatid}/{link}" for link in grouped_photo_links]
                    final_video_links = [f"https://t.me/c/{chatid}/{link}" for link in grouped_video_links]
                else:
                    if isinstance(chatid, str):
                        final_photo_links = [f"https://t.me/{channel_username}/{link}" for link in grouped_photo_links]
                        final_video_links = [f"https://t.me/{channel_username}/{link}" for link in grouped_video_links]
                    else:
                        final_photo_links = [f"https://t.me/c/{channel_username}/{link}" for link in grouped_photo_links]
                        final_video_links = [f"https://t.me/c/{channel_username}/{link}" for link in grouped_video_links]

                # Combine links and labels into a single message
                message_text = ""
                if final_photo_links:
                    message_text += "**Photo Links:**\n" + "\n".join(final_photo_links)
                if final_video_links:
                    if message_text:
                        message_text += "\n\n"
                    message_text += "**Video Links:**\n" + "\n".join(final_video_links)

                # Split message into chunks if it's too long
                message_chunks = self.split_message_into_chunks(message_text)

                # Send message chunks
                try:
                    for chunk in message_chunks:
                        await telegram_bot.bot.send_message(message.chat.id, chunk, reply_to_message_id=message.id, disable_web_page_preview=True)
                except pyrogram.errors.exceptions.bad_request_400.MessageEmpty:
                        await telegram_bot.bot.send_message(message.chat.id, "**no pictures or videos found recently in the provided channel**", reply_to_message_id=message.id, disable_web_page_preview=True)

            except Exception as e:
                print("find links", e)
                await telegram_bot.bot.send_message(message.chat.id, f"Error occurred: {e}")
        finally:
            self.cancel_current_task()

it has some functionality that can be removed or just make a pseudo code for it..
you can also remove the limit function but if you fetch a chat or a group with hundreds of thousnds of messages it can be pretty heavy.
anyways enjoy if you want to use it :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants