async def get_c(client: Client, message): if message.forward_from: return dir= "./temp/" try: os.makedirs("./temp/") except: pass channel_username= message.command[1][1:] command = ['ls','temp','|','wc','-l' ] await message.edit("Downloading All Media From this Channel.") async for msgs in client.iter_history(chat_id=channel_username): if msgs.document is not None: try: await client.download_media(msgs,dir) except FloodWait: await asyncio.sleep(20) await client.download_media(msgs,dir) ps = subprocess.Popen(('ls', 'temp'), stdout=subprocess.PIPE) output = subprocess.check_output(('wc', '-l'), stdin=ps.stdout) ps.wait() output = str(output) output = output.replace("b'","") output = output.replace("\n'","") await message.edit("Downloaded "+output+" files.")
async def purge_command(client: Client, message: Message): """ Purge messages in any chat, supports 2 working modes: my messages and all messages. """ args = get_args(message.text or message.caption) me_mode = True if "me" in args else False if message.chat.type in ("group", "supergroup") and not me_mode: # Check admin rights if we delete all messages member = await message.chat.get_member(message.from_user.id) if not member.can_delete_messages and member.status != "creator": me_mode = True # Not enough rights, so we'll delete our messages only message_list: List[int] = [] try: async for msg in client.iter_history( message.chat.id, offset_id=message.reply_to_message.message_id, reverse=True ): if me_mode and msg.from_user.id != message.from_user.id: continue # Skip messages sent by other users if the me_mode is True else: if len(message_list) < 100: message_list.append(msg.message_id) else: await client.delete_messages(message.chat.id, message_ids=message_list) message_list = [] if message_list: await client.delete_messages(message.chat.id, message_ids=message_list) except RPCError as ex: logger.error(f"Could not .purge messages due to {ex}")
async def undlt(client: Client, message): deleted_msg = "Deleted 10 Messages in {}\n".format(message.chat.title) async for msg in client.iter_history(chat_id=message.chat.id, limit=10, reverse=False): deleted_msg += "👉 {}\n".format(msg.text) await message.edit(deleted_msg)
async def main(): """Guarde archivos antiguos en la base de datos con la ayuda del bot de usuario""" user_bot = Client(USER_SESSION, API_ID, API_HASH) bot = Client(SESSION, API_ID, API_HASH, bot_token=BOT_TOKEN) await user_bot.start() await bot.start() try: for channel in CHANNELS: async for user_message in user_bot.iter_history(channel): message = await bot.get_messages( channel, user_message.message_id, replies=0, ) for file_type in ("document", "video", "audio"): media = getattr(message, file_type, None) if media is not None: break else: continue media.file_type = file_type media.caption = message.caption await save_file(media) finally: await user_bot.stop() await bot.stop()
async def main(): """Save old files in database with the help of user bot""" user_bot = Client(USER_SESSION, API_ID, API_HASH) bot = Client(SESSION, API_ID, API_HASH, bot_token=BOT_TOKEN) await user_bot.start() await bot.start() try: for channel in CHANNELS: async for user_message in user_bot.iter_history(channel): message = await bot.get_messages( channel, user_message.message_id, replies=0, ) for file_type in ("document", "video", "audio"): media = getattr(message, file_type, None) if media is not None: break else: continue media.file_type = file_type media.caption = message.caption await save_file(media) finally: await user_bot.stop() await bot.stop()
async def index_files(bot, message): """Save channel or group files with the help of user bot""" if not USERBOT_STRING_SESSION: await message.reply( 'Set `USERBOT_STRING_SESSION` in info.py file or in environment variables.' ) elif len(message.command) == 1: await message.reply( 'Please specify channel username or id in command.\n\n' 'Example: `/index -10012345678`') elif lock.locked(): await message.reply('Wait until previous process complete.') else: msg = await message.reply('Processing...⏳') raw_data = message.command[1:] user_bot = Client(USERBOT_STRING_SESSION, API_ID, API_HASH) chats = [ int(chat) if id_pattern.search(chat) else chat for chat in raw_data ] total_files = 0 async with lock: try: async with user_bot: for chat in chats: async for user_message in user_bot.iter_history(chat): try: message = await bot.get_messages( chat, user_message.message_id, replies=0, ) except FloodWait as e: await asyncio.sleep(e.x) message = await bot.get_messages( chat, user_message.message_id, replies=0, ) for file_type in ("document", "video", "audio"): media = getattr(message, file_type, None) if media is not None: break else: continue media.file_type = file_type media.caption = message.caption await save_file(media) total_files += 1 except Exception as e: logger.exception(e) await msg.edit(f'Error: {e}') else: await msg.edit(f'Total {total_files} checked!')
async def Kanger(c: Client, m: Message): await m.edit(text=f"Checking `{str(Config.FORWARD_FROM_CHAT_ID[0])}` ...") await asyncio.sleep(2) try: ForwardFromChat = await c.get_chat( chat_id=Config.FORWARD_FROM_CHAT_ID[0]) await m.edit( text=f"Successfully Linked with `{ForwardFromChat.title}` !") except Exception as err: await m.edit( text=f"Sorry, can't get **Forward From Chat**!\n\n**Error:** `{err}`" ) return 400 await asyncio.sleep(2) for i in range(len(Config.FORWARD_TO_CHAT_ID)): await m.edit(text=f"Checking `{Config.FORWARD_TO_CHAT_ID[i]}` ...") await asyncio.sleep(2) try: ForwardToChat = await c.get_chat_member( chat_id=Config.FORWARD_TO_CHAT_ID[i], user_id=(await c.get_me()).id) if ForwardToChat.can_send_messages is False: await m.edit( text= f"Sorry, you don't have permission to send messages in {ForwardToChat.title} !" ) return 400 await m.edit( text=f"Successfully Linked with `{ForwardToChat.title}` !") await asyncio.sleep(2) except Exception as err: await m.edit( text= f"Sorry, can't get **Forward To Chat**!\n\n**Error:** `{err}`") return 400 await asyncio.sleep(2) await m.edit(text="Trying to Forward Now ...") async for message in c.iter_history(chat_id=Config.FORWARD_FROM_CHAT_ID[0], reverse=True): await asyncio.sleep(Config.SLEEP_TIME) try: try_forward = await ForwardMessage(c, message) if try_forward == 400: return 400 except UserDeactivatedBan: print( "Congratulations!\nYour Account Banned Successfully!\nI already told you use a Fake Account. Hope you remember." ) break except Exception as err: await c.send_message(chat_id="me", text=f"#ERROR: `{err}`") await m.edit( text= "Channel Files Successfully Kanged!\n\n©️ A Forwarder Userbot by @AbirHasan2005" )
def clear(app: Client, msg: Message): chatid = msg.chat.id messageid = msg.message_id msglist = [] for message in app.iter_history(chatid, limit=1000): count = int(message.message_id) msglist.append(count) try: app.delete_messages(chatid, msglist) except: app.delete_messages(chatid, msglist)
async def firewatch(c: Client, m: Message): if m.text.startswith("/firewatch "): text_list = m.text.split(" ") # /firewatch dump @heipchat/or_it's_chat_id @someone/or_it's_user_id dest_chat_id [optional]offset_id if text_list[1] == "dump": chat_id = 0 user_id = 0 dst_id = 0 try: chat_id = (await c.get_chat(text_list[2])).id user_id = (await c.get_users(text_list[3])).id dst_id = (await c.get_chat(text_list[4])).id try: offset_id = int(text_list[5]) except: offset_id = 0 except: await m.reply( "Error occurred while parsing ids, check your input.\n" "Chat ID: {}, User ID: {}, DST ID: {}".format(chat_id, user_id, dst_id) ) return counter = 0 all_history = c.iter_history(chat_id=chat_id, offset_id=offset_id, reverse=True) if user_id == "any": async for i in all_history: if not i.service: await i.forward(dst_id) counter += 1 else: async for i in all_history: if not i.service and i.from_user: if i.from_user.id == user_id: await i.forward(dst_id) counter += 1 await m.reply("{} messages dumped successfully.".format(counter))
async def purge_handler(client: Client, message: Message): """ Purge messages in any chat, supports 2 working modes: my messages and all messages. """ args = message.text.split(maxsplit=2) me_mode = True if 'me' in args else False if message.chat.type in [ 'group', 'supergroup' ] and not me_mode: # Check admin rights if we delete all messages member = await message.chat.get_member(message.from_user.id) if not member.can_delete_messages and member.status != 'creator': me_mode = True # Not enough rights, so we'll delete our messages only elif message.chat.type == 'channel': return # TODO: Think about channels msgs = [] try: async for msg in client.iter_history( # noqa message.chat.id, offset_id=message.reply_to_message.message_id, reverse=True): if me_mode and msg.from_user.id != message.from_user.id: continue # Skip messages sent by other users if the me_mode is True else: if len(msgs) < 100: msgs.append(msg.message_id) else: await client.delete_messages(message.chat.id, message_ids=msgs) msgs = [] if msgs: await client.delete_messages(message.chat.id, message_ids=msgs) except RPCError as ex: logger.error(f'Could not .purge messages due to {ex}')
with open("_speed_stats.txt", "w") as file: file.write("") with app: a = time() for channel_code in CHANNELS: channel_code = channel_code["login"] if channel_code.get( "login") else channel_code["link"] try: finded_chat = app.join_chat(channel_code) chat = app.get_chat(finded_chat.id) with open("{}.txt".format(chat.title), "w") as file: file.write("{title} @{username}\n".format( title=chat.title if chat.title else "NoTitle", username=chat.username if chat.username else "NoLogin")) chat_messages = app.iter_history(chat_id=chat.id) messages_count = 0 for message in chat_messages: messages_count += 1 # if messages_count > 500: # break sleep(random() / 77.7) with open("{}.txt".format(chat.title), "a") as file: if message.text: file.write("<message views='{}'>\t{}\n".format( message.views, " ".join(message.text.splitlines()))) elif message.media: file.write("<media_m views='{}'>\t{}\n".format( message.views, " ".join(message.caption.splitlines())
app.start() class TqdmUpTo(tqdm): last_block = 0 def my_update(self, total, current): return self.update_to(total, current) def update_to(self, current, total): self.update(current - self.last_block) self.last_block = current for message in app.iter_history(chat_id=channel_name, offset_id=offset_id, reverse=reverse): try: if message.document.file_name in os.listdir(save_path): pass else: if message.document.file_name.endswith('.7z'): #过滤指定类型文件。 continue #elif message.document.file_name.endswith('.zip'): # continue #elif message.document.file_name.endswith('.rar'): # continue else: tqdm = TqdmUpTo( total=message.document.file_size, desc=f'{message.message_id} - {message.document.file_name}',
# Get the count of Members in a chat and check how many of those have sent a message # in the last x messages. Change the limit variable to check more messages. from pyrogram import Client app = Client("my_account") chat = "pyrogramchat" people = {} with app: total = app.get_chat_members_count(chat) for msg in app.iter_history(chat, limit=1000): if msg.from_user and not msg.from_user.is_bot: people[msg.from_user.id] = msg.from_user.first_name print(len(people) / total)
except (UserNotParticipant): print(" ") print(" !! The user is not a participant in this chat") continue except (AssertionError): print(" ") print(" !! The user does not have delete perms in this chat") continue # Create empty array and variables messages = [] messagecount = 0 deleted = 0 # Ask for array of messages (oldest to newest) and iterate through it for message in app.iter_history(chatobj.id, reverse=True): # TG only allows deleting upto 100 messages at once, then delete messages and reset array if (messagecount == 100): print(" ++ Deleting " + str(messagecount) + " messages at " + str(message.date)) app.delete_messages(chatobj.id, messages) deleted = deleted + messagecount messages = [] messagecount = 0 # If message is old, add its id to array if (delete_before > message.date): messages += [message.message_id] messagecount = messagecount + 1 else:
# Get a Chat History and check how many images # in that chat are above or below a certain threshold. from pyrogram import Client app = Client("my_account") threshold = 100 * 1024 # 100 kb below = 0 above = 0 exact = 0 chat = "me" # Saved Messages, any other @username works, too. with app: for msg in app.iter_history(chat): if msg.photo and msg.photo.file_size < threshold: below += 1 elif msg.photo and msg.photo.file_size > threshold: above += 1 print(f"Below: {below}\nAbove: {above}\nTotal: {above+below}")
# This script will iterate through all of the chats you're in (private, too) and # delete every single message of yours*. This can not be undone, so make sure you # actually want to purge everything you've ever sent. This includes "Saved Messages" # *(except "x joined", this needs administrative permissions) from collections import defaultdict from pyrogram import Client app = Client("my_account") ALL_MESSAGES = defaultdict(list) with app: for dialog in app.iter_dialogs(): if dialog.chat.type in ["bot", "channel"]: continue for message in app.iter_history(dialog.chat.id): if not message.service and message.from_user.is_self: ALL_MESSAGES[dialog.chat.id].append(message.message_id) # start deleting messages for chat_id, messages in ALL_MESSAGES.items(): for i in range(1, len(messages), 100): app.delete_messages(chat_id, messages[i : i + 100], revoke=True)
class TransferHandler: def __init__( self, config: dict, s_file: str, progress_fun: callable, # Pointer to progress function data_fun: callable, # Called for multi chunk transfers local_library: bool = True): # Where to search for library self.asyncFiles = AsyncFiles("{}transferHandler_extern.{}".format( '' if local_library else '../', 'dll' if sys.platform == 'win32' else 'so')) try: self.telegram_channel_id = int(config['telegram']['channel_id']) except ValueError: self.telegram_channel_id = config['telegram']['channel_id'] self.data_path = config['paths']['data_path'] self.tmp_path = config['paths']['tmp_path'] self.s_file = s_file # we need this for the naming when uploading self.progress_fun = progress_fun self.data_fun = data_fun self.download_full_path = config['paths']['download_full_path'] self.now_transmitting = 0 # no, single chunk, multi chunk (0-2) self.should_stop = 0 self.mul_chunk_size = 2000 * 1024 self.chunk_size = self.mul_chunk_size * 1024 self.telegram = Client(path.join(self.data_path, "a{}".format(s_file)), config['telegram']['api_id'], config['telegram']['api_hash']) async def initSession(self): # Connect to telegram servers when starting # So that if we are missing any sessions it will prompt for login # Before starting the UI async with self.telegram: pass async def uploadFiles(self, fileData: dict): tot_chunks = (fileData['size'] // self.chunk_size) + 1 # used by progress fun self.now_transmitting = 1 if fileData['size'] <= self.chunk_size else 2 while True: # not end of file if self.now_transmitting == 2: copied_file_path = path.join( self.tmp_path, "tfilemgr", "{}_{}".format(self.s_file, fileData['index'])) fileData['chunkIndex'] = await self.asyncFiles.splitFile( fileData['chunkIndex'], fileData['path'].encode('ascii'), copied_file_path.encode('ascii'), self.mul_chunk_size, 1024) async with self.telegram: msg_obj = await self.telegram.send_document( self.telegram_channel_id, copied_file_path if self.now_transmitting == 2 else \ fileData['path'], file_name = None if self.now_transmitting == 2 else \ "{}_{}".format(self.s_file, fileData['index']), progress=self.progress_fun, progress_args=(len(fileData['fileID']), tot_chunks, self.s_file) ) if self.now_transmitting == 2: await self.asyncFiles.remove(copied_file_path) # delete the chunk if self.should_stop == 2: # force stop if self.now_transmitting == 1: self.should_stop = 0 return break fileData['fileID'].append(msg_obj.message_id) fileData['index'] += 1 if not fileData['chunkIndex']: # reached EOF break self.data_fun(fileData, self.s_file) if self.should_stop == 1: break self.now_transmitting = 0 self.should_stop = 0 # Set this to 0 no matter what if not fileData['chunkIndex']: # finished uploading return { 'fileData': { 'rPath': fileData['rPath'], 'fileID': fileData['fileID'], 'size': fileData['size'] }, 'index': fileData['index'] } # return file information async def downloadFiles(self, fileData: dict): self.now_transmitting = 1 if fileData['size'] <= self.chunk_size else 2 if self.download_full_path: final_dir_path = path.join(fileData['dPath'], *fileData['rPath'][:-1]) if fileData['dPath'] else \ path.join(self.data_path, "downloads", *fileData['rPath'][:-1]) final_file_path = path.join(fileData['dPath'], *fileData['rPath']) if fileData['dPath'] else \ path.join(self.data_path, "downloads", *fileData['rPath']) tmp_file_path = path.join(self.tmp_path, "tfilemgr", "{}_chunk".format(fileData['rPath'][-1])) if not path.isdir(final_dir_path): makedirs(final_dir_path) else: final_file_path = path.join(fileData['dPath'], fileData['rPath'][-1]) if fileData['dPath'] else \ path.join(self.data_path, "downloads", fileData['rPath'][-1]) tmp_file_path = path.join(self.tmp_path, "tfilemgr", "{}_chunk".format(fileData['rPath'][-1])) while fileData['IDindex'] < len(fileData['fileID']): async with self.telegram: message = await self.telegram.get_messages( self.telegram_channel_id, fileData['fileID'][fileData['IDindex']]) await message.download( file_name=final_file_path if self.now_transmitting == 1 else tmp_file_path, progress=self.progress_fun, progress_args=(fileData['IDindex'], len(fileData['fileID']), self.s_file)) if self.should_stop == 2: # force stop break fileData['IDindex'] += 1 if self.now_transmitting == 2: await self.asyncFiles.concatFiles( tmp_file_path.encode('ascii'), final_file_path.encode('ascii'), 1024) await self.asyncFiles.remove(tmp_file_path) if fileData['IDindex'] == len(fileData['fileID']): # finished or canceled with 1 but it was last chunk self.should_stop = 0 # download finished break # stores only ids of files that haven't yet been downloaded self.data_fun(fileData, self.s_file) if self.should_stop == 1: # issued normal cancel break self.now_transmitting = 0 if self.should_stop: self.should_stop = 0 # don't confuse future transfers return 0 return 1 async def deleteUseless(self, IDList: list, mode: int = 1): # mode is 1 for everything except IDList, # 2 for only IDList deletedList = [] async with self.telegram: if mode == 1: async for tFile in self.telegram.iter_history( self.telegram_channel_id): if (tFile.media) and (not tFile.message_id in IDList): deletedList.append(tFile.message_id) if deletedList: await self.telegram.delete_messages( self.telegram_channel_id, deletedList) elif mode == 2: await self.telegram.delete_messages(self.telegram_channel_id, IDList) return deletedList async def stop(self, stop_type: int): # Values of stop_type: # 1 - Wait until the current chunk transfer ended and appended # 2 - Cancel transfer, will still wait for appending to finish if not stop_type in (1, 2): raise IndexError("stop_type should be 1 or 2.") if self.now_transmitting == 1 and stop_type == 1: raise IndexError( "stop_type can't be 1 when transmitting single chunk files.") self.should_stop = stop_type if stop_type == 2: # force stop async with self.telegram: await self.telegram.stop_transmission()
chat = "pyrogramlounge" limit = 2000 # Limit is for how many messages you want to look through app = Client("my_account") class custom(dict): def __missing__(self, key): return 0 with app: words = custom() progress = app.send_message(chat, "`processed 0 messages...`") total = 0 for msg in app.iter_history(chat, limit): total += 1 if total % 200 == 0: progress.edit_text(f"`processed {total} messages...`") if msg.text: for word in msg.text.split(): words[word.lower()] += 1 if msg.caption: for word in msg.caption.split(): words[word.lower()] += 1 freq = sorted(words, key=words.get, reverse=True) out = "Word Counter\n" for i in range(50): out += f"{i+1}. {words[freq[i]]}: {freq[i]}\n" progress.edit_text(out, parse_mode=None)
"""This example shows how to get the full message history of a chat, starting from the latest message""" from pyrogram import Client app = Client("my_account") target = "me" # "me" refers to your own chat (Saved Messages) with app: for message in app.iter_history(target): print(message.text)
from pyrogram import Client apiID = 12345 # Edit this! apiHash = "" string oldChat = "" #chat name in string or chat id in interger newChat = "" #chat name in string or chat id in interger app = Client( "tgMigrate", api_id=, api_hash=) with app: forwarded_count = 0 prev_media_group_id = "" for message in app.iter_history(oldChat, reverse = True): if message.service == True: continue media_group_id = message.media_group_id if media_group_id == prev_media_group_id: continue prev_media_group_id = message.media_group_id message_ids = [message.message_id] if media_group_id: #if it's not None message_group = app.get_media_group(oldChat, message.message_id) message_ids = [message.message_id for message in message_group] app.forward_messages(