Code Monkey home page Code Monkey logo

Comments (3)

davad00 avatar davad00 commented on August 12, 2024 1

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 :)

from save-restricted-bot.

baqt99 avatar baqt99 commented on August 12, 2024 1

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

from save-restricted-bot.

davad00 avatar davad00 commented on August 12, 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 :)

from save-restricted-bot.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.