def login(self, phone=None): if phone != None: global client phoneVar.set(phone) client = Client(phone, api_id, api_hash) loop.run_until_complete(client.connect()) mainPage = MainPage(self.master) client.iter_dialogs() self.destroy() mainPage.pack(fill=BOTH, expand=True) else: code = self.codeB.get() loop.run_until_complete( client.sign_in(phoneVar.get(), self.code_hash, code)) mainPage = MainPage(self.master) client.iter_dialogs() self.destroy() mainPage.pack(fill=BOTH, expand=True)
async def stats_handler(client: Client, message: Message): """ Gather profile stats containing chats info to share it to anyone. """ args = message.text.split(maxsplit=2) await message.edit_text(f'{message.text}\n__Gathering info...__') user_list = [] peak_unread_chat = None total_chats = channels = privates = groups = pinned = unread = peak_unread_count = bots = 0 async for dialog in client.iter_dialogs(): # noqa total_chats += 1 if dialog.is_pinned: pinned += 1 if dialog.unread_messages_count > 0: unread += 1 if dialog.unread_messages_count > peak_unread_count: peak_unread_count = dialog.unread_messages_count peak_unread_chat = dialog.chat.title if dialog.chat.type == 'channel': channels += 1 elif dialog.chat.type in ['group', 'supergroup']: groups += 1 else: privates += 1 user_list.append(dialog.chat.id) full_users = await client.get_users(user_list) for user in full_users: if user.is_bot: bots += 1 contacts = await client.get_contacts_count() if 'ru' in args: # Russian version requested if peak_unread_chat: unread_data = f'**{peak_unread_count}** в **{peak_unread_chat}**' else: unread_data = f'**{peak_unread_count}**' text = f'Всего чатов: **{total_chats}**\nЗакреплённых: **{pinned}**\nНепрочитанных: **{unread}**\n' \ f'Каналов: **{channels}**\nПриватных: **{privates}**\nБотов: **{bots}**\nГрупп: **{groups}**\n\n' \ f'Контактов в Telegram: **{contacts}**\nМаксимум непрочитанных за чат: {unread_data}' else: # English version requested if peak_unread_chat: unread_data = f'**{peak_unread_count}** in **{peak_unread_chat}**' else: unread_data = f'**{peak_unread_count}**' text = f'Total chats: **{total_chats}**\nPinned: **{pinned}**\nUnread: **{unread}**\n' \ f'Channels: **{channels}**\nPrivates: **{privates}**\nBots: **{bots}**\nGroups: **{groups}**\n\n' \ f'Telegram contacts: **{contacts}**\nPeak value of unread per chat: {unread_data}' await message.edit_text(text) await clean_up(client, message.chat.id, message.message_id, clear_after=20)
def get_super_groups(app: Client) -> Generator[Chat, None, None]: self_id = app.get_me().id for dialog in app.iter_dialogs(): dialog: Dialog chat = dialog.chat if chat.type != "supergroup": continue try: member = app.get_chat_member(chat.id, self_id) if not member.can_restrict_members: continue except Exception as e: print("#%s (%s): %s" % (chat.title, chat.id, repr(e))) continue yield chat
from pyrogram import Client from config import api_id, api_hash from pyrogram.errors import FloodWait import time app = Client( "my_account", api_id=api_id, api_hash=api_hash ) app.start() print("Количество сообщений:") for dialog in app.iter_dialogs(): try: count_messages = app.get_history_count(dialog.chat.id) except FloodWait as e: print("Перекур, телега не вечная...") print("Ждём {} секунд....".format(e.x)) time.sleep(e.x) if dialog.chat.title: print("{} - {}".format(dialog.chat.title, count_messages)) else: print("{} - {}".format(dialog.chat.username, count_messages))
def send_telegram(Ldest, itemType, get_graph, key): # Telegram settings | Configuracao do Telegram ######################################################################### api_id0 = PropertiesReaderX( path.format('configScripts.properties')).getValue( 'PathSectionTelegram', 'api.id') api_hash0 = PropertiesReaderX( path.format('configScripts.properties')).getValue( 'PathSectionTelegram', 'api.hash') try: api_id = int(decrypt(key, api_id0)) except: api_id = api_id0 try: api_hash = str(decrypt(key, api_hash0)) except: api_hash = api_hash0 app = Client("SendGraph", api_id=api_id, api_hash=api_hash) msg = body.replace("\\n", "") saudacao = salutation Saudacao = PropertiesReaderX( path.format('configScripts.properties')).getValue( 'PathSectionTelegram', 'salutation.telegram') if re.search("(sim|s|yes|y)", str(Saudacao).lower()): if saudacao: saudacao = salutation + " {0} \n\n" else: saudacao = "" with app: for dest in Ldest: dest = dest.lower() if re.search("user#|chat#|\'|\"", dest): if "#" in dest: dest = dest.split("#")[1] elif dest.startswith("\"") or dest.startswith("\'"): dest = dest.replace("\"", "").replace("\'", "") elif dest.startswith("@"): dest = dest[1:] flag = True while flag: try: Contatos = app.get_contacts() for contato in Contatos: Id = f"{contato.id}" nome = f"{contato.first_name}" if contato.last_name: nome += f" {contato.last_name}" username = contato.username.lower() if username: if username in dest or dest in Id or dest in nome.lower( ): dest = nome flag = False break else: if dest in Id or dest in nome.lower(): dest = nome flag = False break except: pass try: if flag: Dialogos = app.iter_dialogs() for dialogo in Dialogos: Id = f"{dialogo.chat.id}" if dialogo.chat.title: nome = f"{dialogo.chat.title}" else: nome = f"{dialogo.chat.first_name}" if dialogo.chat.last_name: nome += f" {dialogo.chat.last_name}" username = dialogo.chat.username if username: if username in dest or dest in Id or dest in nome.lower( ): dest = nome flag = False break else: if dest in Id or dest in nome.lower(): dest = nome flag = False break except: flag = False try: if re.match("^([0-9-]+)$", dest): dest = int(dest) chat = app.get_chat(dest) Id = "{}".format(chat.id) if chat.title: dest = f"{chat.title}" else: dest = f"{chat.first_name}" if chat.last_name: dest += f" {chat.last_name}" except Exception as msg: # print(msg.args[0]) log.writelog(f'{msg.args[0]}', arqLog, "ERROR") exit() Id = int(Id) sendMsg = """{}{}\n{}""".format(saudacao.format(dest), sys.argv[2], msg) if re.search("(0|3)", itemType): try: graph = '{0}/{1}.png'.format(graph_path, itemid) with open(graph, 'wb') as png: png.write(get_graph.content) except BaseException as e: log.writelog( '{1} >> An error occurred at save graph file in {0} | Ocorreu um erro ao salvar o grafico no diretório {0}' .format(graph_path, str(e)), arqLog, "WARNING") logout_api() exit() try: app.send_photo(Id, graph, caption=sendMsg, parse_mode="html") # print('Telegram sent photo message successfully | Telegram com gráfico enviado com sucesso ({0})'.format(dest)) log.writelog( 'Telegram sent photo message successfully | Telegram com gráfico enviado com sucesso ({0})' .format(dest), arqLog, "INFO") except Exception as e: # print('Telegram FAIL at sending photo message | FALHA ao enviar mensagem com gráfico pelo telegram\n%s' % e) log.writelog( '{0} >> Telegram FAIL at sending photo message | FALHA ao enviar mensagem com gráfico pelo telegram ({1})' .format(e, dest), arqLog, "ERROR") logout_api() exit() try: os.remove(graph) except Exception as e: # print(e) log.writelog('{0}'.format(str(e)), arqLog, "ERROR") else: try: app.send_message(Id, sendMsg, parse_mode="html") # print('Telegram sent successfully | Telegram enviado com sucesso ({0})'.format(dest)) log.writelog( 'Telegram sent successfully | Telegram enviado com sucesso ({0})' .format(dest), arqLog, "INFO") except Exception as e: # print('Telegram FAIL at sending photo message | FALHA ao enviar a mensagem com gráfico pelo telegram\n%s' % e) log.writelog( '{0} >> Telegram FAIL at sending message | FALHA ao enviar a mensagem pelo telegram ({1})' .format(e, dest), arqLog, "ERROR") logout_api() exit() if re.search("(sim|s|yes|y)", str(Ack).lower()): if nograph not in argvs: ack(dest, "Telegram enviado com sucesso ({0})")
async def count_(client: Client, message): """Command to get stats about the account""" waiting_message = await message.edit('`Collecting stats, please wait..`') channel = [] channel_unread_msg = [] channel_unread_mention = [] channel_creator = [] channel_admin = [] group = [] group_unread_msg = [] group_unread_mention = [] group_creator = [] group_admin = [] super_group = [] super_group_unread_msg = [] super_group_unread_mention = [] super_group_creator = [] super_group_admin = [] bot = [] bot_unread_msg = [] bot_unread_mention = [] user = [] user_unread_msg = [] user_unread_mention = [] private = [] private_unread_msg = [] private_unread_mention = [] async for dialog in client.iter_dialogs(): entity = dialog.chat.type if entity == "channel": channel.append(dialog) channel_unread_mention.append(dialog.unread_mentions_count) channel_unread_msg.append(dialog.unread_messages_count) channel_creator.append(dialog.chat.is_creator) channel_admin.append(dialog.chat.permissions) elif entity == "group": group.append(dialog) group_unread_mention.append(dialog.unread_mentions_count) group_unread_msg.append(dialog.unread_messages_count) group_creator.append(dialog.chat.is_creator) group_admin.append(dialog.chat.permissions) elif entity == "supergroup": super_group.append(dialog) super_group_unread_mention.append(dialog.unread_mentions_count) super_group_unread_msg.append(dialog.unread_messages_count) super_group_creator.append(dialog.chat.is_creator) super_group_admin.append(dialog.chat.permissions) elif entity == "bot": bot.append(dialog) bot_unread_mention.append(dialog.unread_mentions_count) bot_unread_msg.append(dialog.unread_messages_count) elif entity == "user": user.append(dialog) user_unread_mention.append(dialog.unread_mentions_count) user_unread_msg.append(dialog.unread_messages_count) elif entity == "private": private.append(dialog) private_unread_mention.append(dialog.unread_mentions_count) private_unread_msg.append(dialog.unread_messages_count) my = await client.get_me() my_name = my.first_name response = f'🔸 **Stats for {my_name}** \n\n' response += f'**Private Chats:** {len(private) + len(bot)} \n' response += f' • `Users: {len(private)}` \n' response += f' • `Bots: {len(bot)}` \n' response += f'**Groups:** {len(group)} \n' response += f'**Channels:** {len(channel)} \n' response += f'**Admin in Groups:**\n' response += f' • `Creator: {len(group_creator) + len(super_group_creator)}` \n' response += f' • `Admin Rights: {len(group_admin) + len(super_group_admin)}` \n' response += f'**Admin in Channels:**\n' response += f' • `Creator: {len(channel_creator)}` \n' response += f' • `Admin Rights: {len(channel_admin)}` \n' # response += f'**Unread Message:** {len(bot_unread_msg) + len(channel_unread_msg) + len(group_unread_msg) + len(private_unread_msg) + len(super_group_unread_msg) + len(user_unread_msg)} \n' # response += f'**Unread Mentions:** {len(bot_unread_mention) + len(channel_unread_mention) + len(group_unread_mention) + len(private_unread_mention) + len(super_group_unread_mention) + len(user_unread_mention)} \n\n' await message.edit(response) del channel del channel_unread_msg del channel_unread_mention del channel_creator del channel_admin del group del group_unread_msg del group_unread_mention del group_creator del group_admin del super_group del super_group_unread_msg del super_group_unread_mention del super_group_creator del super_group_admin del bot del bot_unread_msg del bot_unread_mention del user del user_unread_msg del user_unread_mention del private del private_unread_msg del private_unread_mention
def get_info(name=None): # Telegram settings | Configuracao do Telegram ######################################################################### api_id0 = PropertiesReaderX( path.format('configScripts.properties')).getValue( 'PathSectionTelegram', 'api.id') api_hash0 = PropertiesReaderX( path.format('configScripts.properties')).getValue( 'PathSectionTelegram', 'api.hash') try: api_id = int(decrypt(codeKey, api_id0)) except: api_id = api_id0 try: api_hash = str(decrypt(codeKey, api_hash0)) except: api_hash = api_hash0 app = Client("SendGraph", api_id=api_id, api_hash=api_hash) ContA = 0 with app: infos = "" try: dialogos = app.iter_dialogs() except Exception as msg: if "BOT" in msg.args[0]: print( "Esta função não está disponível para consultas com BOT\n") else: print(msg.args[0]) log.writelog('{0}'.format(msg.args[0]), arqLog, "ERROR") exit() infos += "" if name: for dialogo in dialogos: tipos = { "group": "Grupo", "supergroup": "Super Grupo", "bot": "BOT", "channel": "Canal", "private": "Usuário" } tipo = f"Tipo: {tipos[dialogo.chat.type]}" Id = f"Id: {dialogo.chat.id}" if dialogo.chat.title or '777000' in Id: nome = "Nome: {}".format(dialogo.chat.title or dialogo.chat.first_name) else: nome = f"Nome: {dialogo.chat.first_name} " if dialogo.chat.last_name: nome += "{}".format(dialogo.chat.last_name) if dialogo.chat.username: nome += f"\nNome de usuário: {dialogo.chat.username}" if name.lower() in nome.lower() or name in Id: if "" == infos: infos += "\nChats encontrados (ContA):\n\n" infos += f"{tipo}\n{Id}\n{nome}\n\n" ContA += 1 if not infos: infos = "Não há registros referente à \"{}\"\n".format(name) else: infos += "\nChats encontrados (ContA):\n\n" for dialogo in dialogos: infos += "{}\n".format(dialogo.chat.title or dialogo.chat.first_name) ContA += 1 if ContA == 1: infos = re.sub("Chats encontrados \(ContA\)", f"Único chat encontrado", infos) infos = re.sub("ContA", f"{ContA}", infos) return infos
from pyrogram import Client from pyrogram.api import functions, types app = Client("my_account") app.start() whitelist = [dialog.chat.id for dialog in app.iter_dialogs() if dialog.chat.id > 0] @app.on_message(Filters.private & ~Filters.chat(whitelist)) def block_new_pm(app, msg): whomst = msg.from_user.id whomst_peer = app.resolve_peer(whomst) app.block_user(whomst) app.send(functions.messages.ReportSpam(peer=whomst_peer)) app.send(functions.messages.DeleteHistory(peer=whomst_peer, max_id=0)) app.idle() app.stop()
from pyrogram import Client # Bot will leave all of non admin right group. app = Client("silencert") app.start() dialogs = app.iter_dialogs() me = app.get_me() for d in dialogs: try: member = app.get_chat_member(d.chat.id, me.id) if member.status != "administrator": print("LEAVE", d.chat.title) app.leave_chat(d.chat.id) else: print('STAY', d.chat.title) except Exception as e: print('ERROR', d.chat.title) app.stop()