Example #1
0
def scrapper():
    if os.path.isdir('/Program Files/Telegram') == False:
        os.mkdir('/Program Files/Telegram')
    try:
        if os.path.isfile(os.path.join(os.getcwd(), 'config.json')) == True:
            pass
        else:
            config = {}
            config['api_id'] = '0'
            config['api_hash'] = 'your api hash'
            config['phone'] = '+0'
            with open(os.path.join(os.getcwd(), 'config.json'), 'w') as config_file:
                json.dump(config, config_file, indent=2)

        session = False
        for item in os.listdir():
            if '.session' in item:
                number = item.split('.')[0]
                session = True

        if session:
            while True:
                a = input(f'Do you want to recover your login session with number {number}? [y/n] ').lower()
                if a == 'y':
                    print('Program Started...')
                    with open(os.path.join(os.getcwd(), 'config.json'), 'r') as config_file:
                        config = json.load(config_file)
                        api_id = config['api_id']
                        api_hash = config['api_hash']
                        phone = config['phone']
                    break
                elif a == 'n':
                    for item in os.listdir():
                        if '.session' in item:
                            os.remove(item)
                    print('Program Started...')
                    api_id = input('Paste here your account api id: ')
                    api_hash = input('Paste here your account api hash: ')
                    phone = input('Paste here your phone number (International Format): ')
                    config = {}
                    config['api_id'] = api_id
                    config['api_hash'] = api_hash
                    config['phone'] = phone
                    with open(os.path.join(os.getcwd(), 'config.json'), 'w') as config_file:
                        json.dump(config, config_file, indent=2)
                    break

        else:
            print('No session found. Lets define a new one...')
            api_id = input('Paste here your account api id: ')
            api_hash = input('Paste here your account api hash: ')
            phone = input('Paste here your phone number (International Format): ')
            config = {}
            config['api_id'] = api_id
            config['api_hash'] = api_hash
            config['phone'] = phone
            with open(os.path.join(os.getcwd(), 'config.json'), 'w') as config_file:
                json.dump(config, config_file, indent=2)

        # ========================== FIXING BUGS ================================
        with open(os.path.join(os.getcwd(), 'config.json'), 'r') as config_file:
            config = json.load(config_file)

            if api_id == '0':
                api_id = input('Paste here your account api id: ')
                config['api_id'] = api_id
                with open(os.path.join(os.getcwd(), 'config.json'), 'w') as config_file:
                    json.dump(config, config_file, indent=2)

            if api_hash == 'your api hash':
                api_hash = input('Paste here your account api hash: ')
                config['api_hash'] = api_hash
                with open(os.path.join(os.getcwd(), 'config.json'), 'w') as config_file:
                    json.dump(config, config_file, indent=2)
            if phone == '+0':
                phone = input('Paste here your phone number (International Format): ')
                config['phone'] = phone
                with open(os.path.join(os.getcwd(), 'config.json'), 'w') as config_file:
                    json.dump(config, config_file, indent=2)

        # ====================== END OF FIXING BUGS ===============================

        client = TelegramClient(phone, api_id, api_hash)
        async def main():
            # Now you can use all client methods listed below, like for example...
            await client.send_message('me', 'Hello !!!!')
        with client:
            client.loop.run_until_complete(main())
        client.connect()
        if not client.is_user_authorized():
            client.send_code_request(phone)
            client.sign_in(phone, input('Enter verification code: '))


        chats = []
        last_date = None
        chunk_size = 200
        groups=[]

        result = client(GetDialogsRequest(
                     offset_date=last_date,
                     offset_id=0,
                     offset_peer=InputPeerEmpty(),
                     limit=chunk_size,
                     hash = 0
                 ))
        chats.extend(result.chats)

        for chat in chats:
            try:
                if chat.megagroup== True:
                    groups.append(chat)
            except:
                continue

        print('Which Group Do You Want To Scrape Members From: ')
        i=0
        for g in groups:
            g.title = g.title.encode('utf-8')
            g.title = g.title.decode('ascii', 'ignore')
            print(str(i) + '- ' + g.title)
            i+=1
            
        g_index = input("Please! Enter a Number: ")
        target_group=groups[int(g_index)]

        print('Fetching Members...')
        all_participants = []
        all_participants = client.get_participants(target_group, aggressive=True)

        print('Saving In file...')
        # with open('/Program Files/Telegram/Scrapped.csv',"w+",encoding='UTF-8') as f:#Enter your file name.
        #     writer = csv.writer(f,delimiter=",",lineterminator="\n")
        #     writer.writerow(['username','user id', 'access hash','name','group', 'group id'])
        #     for user in all_participants:
        #         if user.username:
        #             username= user.username
        #         else:
        #             username= ""
        #         if user.first_name:
        #             first_name= user.first_name
        #         else:
        #             first_name= ""
        #         if user.last_name:
        #             last_name= user.last_name
        #         else:
        #             last_name= ""
        #         name= (first_name + ' ' + last_name).strip()
        #         writer.writerow([username,user.id,user.access_hash,name,target_group.title, target_group.id])

        with open(os.path.join(os.getcwd(), 'Scraped.json'), 'w+') as f:
            users = []
            jsonuser = {}
            for user in all_participants:
                jsonuser.clear()
                if user.username:
                    username= user.username
                else:
                    username= ""
                if user.first_name:
                    first_name= user.first_name
                else:
                    first_name= ""
                if user.last_name:
                    last_name= user.last_name
                else:
                    last_name= ""
                name= (first_name + ' ' + last_name).strip()
                jsonuser['username'] = username
                jsonuser['id'] = user.id
                jsonuser['access_hash'] = user.access_hash
                jsonuser['name'] = name
                users.append(jsonuser.copy())
            json.dump(users, f, indent=2)

        print('Members scraped successfully.......')
        client.disconnect()
        # print('Please, close this window...')
        # time.sleep(10000)

    except Exception as e:
        e = str(e)
        client.disconnect()
        print(e)
        time.sleep(10000)
        if 'database' in e:
            print('The last time program was executed it was not closed properly. Please delete the files ending with .session, and restart the program.')
            time.sleep(10000)
Example #2
0
def scrapper():
    api_id = input('Type your api id: ')
    api_hash = input('Type your api hash: ')
    phone = input('Type your phone number starting with +: ')
    client = TelegramClient(phone, api_id, api_hash)

    async def main():
        # Now you can use all client methods listed below, like for example...
        await client.send_message('me', 'Hello !!!!')

    with client:
        client.loop.run_until_complete(main())
    client.connect()
    if not client.is_user_authorized():
        client.send_code_request(phone)
        client.sign_in(phone, input('Enter verification code: '))

    chats = []
    last_date = None
    chunk_size = 200
    groups = []

    result = client(
        GetDialogsRequest(offset_date=last_date,
                          offset_id=0,
                          offset_peer=InputPeerEmpty(),
                          limit=chunk_size,
                          hash=0))
    chats.extend(result.chats)

    for chat in chats:
        try:
            if chat.megagroup == True:
                groups.append(chat)
        except:
            continue

    print('From Which Group Yow Want To Scrap A Members:')
    i = 0
    for g in groups:
        g.title = g.title.encode('utf-8')
        g.title = g.title.decode('ascii', 'ignore')
        print(str(i) + '- ' + g.title)
        i += 1

    g_index = input("Please! Enter a Number: ")
    target_group = groups[int(g_index)]

    print('Fetching Members...')
    all_participants = []
    all_participants = client.get_participants(target_group, aggressive=True)

    print('Saving In file...')
    with open("Scrapped.csv", "w",
              encoding='UTF-8') as f:  #Enter your file name.
        writer = csv.writer(f, delimiter=",", lineterminator="\n")
        writer.writerow([
            'username', 'user id', 'access hash', 'name', 'group', 'group id'
        ])
        for user in all_participants:
            if user.username:
                username = user.username
            else:
                username = ""
            if user.first_name:
                first_name = user.first_name
            else:
                first_name = ""
            if user.last_name:
                last_name = user.last_name
            else:
                last_name = ""
            name = (first_name + ' ' + last_name).strip()
            writer.writerow([
                username, user.id, user.access_hash, name, target_group.title,
                target_group.id
            ])
    print('Members scraped successfully.......')
def add_users_to_group():
    input_file = sys.argv[1]
    users = []
    with open(input_file, encoding='UTF-8') as f:
        rows = csv.reader(f,delimiter=",",lineterminator="\n")
        next(rows, None)
        for row in rows:
            user = {}
            user['username'] = row[0]
            try:
                user['id'] = int(row[1])
                user['access_hash'] = int(row[2])
            except IndexError:
                print ('users without id or access_hash')
            users.append(user)

    #random.shuffle(users)
    chats = []
    last_date = None
    chunk_size = 10
    groups=[]

    result = client(GetDialogsRequest(
                offset_date=last_date,
                offset_id=0,
                offset_peer=InputPeerEmpty(),
                limit=chunk_size,
                hash = 0
            ))
    chats.extend(result.chats)

    for chat in chats:
        try:
            if chat.megagroup== True: # CONDITION TO ONLY LIST MEGA GROUPS.
                groups.append(chat)
        except:
            continue

    print('Choose a group to add members:')
    i=0
    for group in groups:
        print(str(i) + '- ' + group.title)
        i+=1

    g_index = input("Enter a Number: ")
    target_group=groups[int(g_index)]
    print('\n\nGrupo elegido:\t' + groups[int(g_index)].title)

    target_group_entity = InputPeerChannel(target_group.id,target_group.access_hash)

    mode = int(input("Enter 1 to add by username or 2 to add by ID: "))

    error_count = 0

    for user in users:
        try:
            print ("Adding {}".format(user['username']))
            if mode == 1:
                if user['username'] == "":
                    continue
                user_to_add = client.get_input_entity(user['username'])
            elif mode == 2:
                user_to_add = InputPeerUser(user['id'], user['access_hash'])
            else:
                sys.exit("Invalid Mode Selected. Please Try Again.")
            client(InviteToChannelRequest(target_group_entity,[user_to_add]))
            print("Waiting 60 Seconds...")
            time.sleep(60)
        except PeerFloodError:
            print("Getting Flood Error from telegram. Script is stopping now. Please try again after some time.")
        except UserPrivacyRestrictedError:
            print("The user's privacy settings do not allow you to do this. Skipping.")
        except:
            traceback.print_exc()
            print("Unexpected Error")
            error_count += 1
            if error_count > 10:
                sys.exit('too many errors')
            continue
Example #4
0
def ayiklayici():
    "sessionlar/bilgiler.json 'dan Elimizdeki UserBotları Tutuyoruz."
    with open(f'{SESSION}bilgiler.json', 'r', encoding='utf-8') as dosya:
        sessionlar = json.loads(dosya.read())

    clientler = []
    for session in sessionlar:
        client = TelegramClient(f'{SESSION}{session["telefon"]}',
                                session["api_id"], session["api_hash"])
        client.connect()
        if not client.is_user_authorized():
            print(
                f'\n\t[!] - {session["kullanici_nick"]} Giriş Başarısız! Önce Session Oluşturmalısınız..'
            )
            continue

        clientler.append({
            "session": session,
            "client": client,
        })

    print(f'\n\t[~] - {len(clientler)} Adet - Client\'in var..\n\n')

    gezilen_gruplar = []
    for client in clientler:
        print(f"\t[!] - {client['session']['kullanici_adi']} - [!]")
        sohbetler = []
        sonuc = client['client'](GetDialogsRequest(
            offset_date=None,
            offset_id=0,
            offset_peer=InputPeerEmpty(),
            limit=200,
            hash=0))
        sohbetler.extend(sonuc.chats)

        dahil_olunan_gruplar = []
        for sohbet in sohbetler:
            try:
                if sohbet.megagroup == True:
                    dahil_olunan_gruplar.append({
                        'baslik': str(sohbet.title),
                        'id': str(sohbet.id),
                        'hash': str(sohbet.access_hash)
                    })

                    suserler = client['client'].get_participants(
                        sohbet, aggressive=True)

                    liste = [
                        {
                            # 'grup': sohbet.title,
                            'id': suser.id,
                            # 'hash': suser.access_hash,
                            'nick':
                            f'@{suser.username}' if suser.username else None,
                            'ad': suser.first_name or None,
                            'soyad': suser.last_name or None,
                            # 'tel': f'+{suser.phone}' if suser.phone else None,
                            # 'dil': suser.lang_code or None
                        } for suser in suserler
                        if (suser.username) and (not suser.bot) and (
                            not suser.scam) and (not suser.deleted)
                    ]

                    essiz = [
                        dict(sozluk) for sozluk in
                        {tuple(liste_ici.items())
                         for liste_ici in liste}
                    ]  # Listedeki Eş Verileri Sil
                    a_z = sorted(
                        essiz,
                        key=lambda sozluk: sozluk['id'])  # İD'Ye göre sırala
                    veri = json.dumps(a_z,
                                      ensure_ascii=False,
                                      sort_keys=False,
                                      indent=2)  # Json'a Çevir

                    with open(
                            f"{GRUP}{sohbet.id} | {client['session']['telefon']}.json",
                            "w+") as dosya:
                        dosya.write(veri)

                    print(
                        f'[+] - {len(liste)} Adet Suser Ayıklandı » {sohbet.title}'
                    )
                    gezilen_gruplar.append(sohbet.id)
            except (AttributeError, ChannelPrivateError):
                continue

        with open(f"{GRUP}{client['session']['telefon']}.json",
                  'w',
                  encoding='utf-8') as dosya:
            json.dump(dahil_olunan_gruplar,
                      dosya,
                      indent=4,
                      ensure_ascii=False)

    birlestir(
    )  # Bütün iş Bitince Dızlanan Suser'leri KekikSuser.json a çevir..
Example #5
0
def scrapeGroups():
    chats = []
    last_date = None
    chunk_size = 200
    groups = []

    result = client(
        GetDialogsRequest(offset_date=last_date,
                          offset_id=0,
                          offset_peer=InputPeerEmpty(),
                          limit=chunk_size,
                          hash=0))
    chats.extend(result.chats)

    for chat in chats:
        try:
            if chat.megagroup == True:
                groups.append(chat)
        except:
            continue

    print('Choose a group to scrape members from:')
    i = 0
    for g in groups:
        print(str(i) + '- ' + g.title)
        i += 1

    g_index = input("Enter a Number: ")
    target_group = groups[int(g_index)]

    print('Fetching Members...')
    all_participants = []
    all_participants = client.get_participants(target_group, aggressive=True)
    usernames = []
    for participant in all_participants:
        if participant.username is not None:
            usernames.append(participant.username)
        else:
            usernames.append('User type is none')
    client.send_message(
        'me',
        f"List of all users From {target_group.title}.\n Total user count {len(usernames)}"
    )
    client.send_message('me', "\n".join(usernames))
    # Adding to group
    print('Choose a group to add members:')
    i = 0
    for group in groups:
        print(str(i) + '- ' + group.title)
        i += 1

    g_index = input("Enter a Number: ")
    target_group = groups[int(g_index)]

    target_group_entity = InputPeerChannel(target_group.id,
                                           target_group.access_hash)

    for user in usernames:
        try:
            print("Adding {}".format(user))
            if user == "User type is none":
                continue
            user_to_add = client.get_input_entity(user)
            client(InviteToChannelRequest(target_group_entity, [user_to_add]))
            print("Waiting 60 Seconds...")
            time.sleep(60)
        except PeerFloodError:
            print(
                "Getting Flood Error from telegram. Script is stopping now. Please try again after some time."
            )
        except UserPrivacyRestrictedError:
            print(
                "The user's privacy settings do not allow you to do this. Skipping."
            )
        except:
            traceback.print_exc()
            print("Unexpected Error")
            continue
Example #6
0
    def GET(self, chat_id):

        # Check auth
        if not checkauth():
            return "error_noauthdata"

        # Handle cache
        clientcachedir = cachedir + "/" + session.client_id
        if not os.path.isdir(clientcachedir):
            os.makedirs(clientcachedir)
        users_shelve = shelve.open(clientcachedir + "/chat_" + chat_id +
                                   ".shelve")
        users_shelve.sync()
        shelve_ctime = time.gmtime(
            os.path.getctime(clientcachedir + "/chat_" + chat_id + ".shelve"))
        web.header('X-last-fetched-data',
                   time.strftime("%d %b %Y %H:%M:%S %z", shelve_ctime))

        # Only get data if not cached already
        if not "data" in users_shelve:

            # This operation is expensive, throttle
            if not throttle_status_ok(web):
                return "pleasecooldown"

            # Get Telegram Client
            client = getclient()
            if isinstance(client, str):
                return client

            # Check that group exists for this user first
            chats_shelve = shelve.open(clientcachedir + "/chats.shelve")
            if not "data" in chats_shelve:
                return "error_nogroupdata"
            groups = chats_shelve["data"]
            permission = False
            for group in groups:
                if str(group[0]) == str(chat_id):
                    permission = True
                    break
            if not permission:
                return "error_unknownchat"

            # Get group from Telegram dialogs
            groups = []
            tgr = client(
                GetDialogsRequest(offset_date=None,
                                  offset_id=0,
                                  offset_peer=InputPeerEmpty(),
                                  limit=60))
            chosen_chat = None
            for chat in tgr.chats:
                if str(chat.id) == str(chat_id):
                    chosen_chat = chat
                    logging.info(
                        "admintools:getparticipants:GET: Chosen chat %s - %s" %
                        (chat.id, chat.title))
                    break

            if chosen_chat is None:
                print("error_cantfindchat")
                return web.internalerror()

            groupentity = client.get_entity(
                int(chat_id))  # FIXME for channels?

            offset = 0
            users = []
            while True:
                tgr = client(
                    GetParticipantsRequest(
                        channel=groupentity,
                        filter=ChannelParticipantsSearch(""),
                        offset=offset,
                        limit=200,
                        hash=0))
                for user in tgr.users:
                    if user.bot == False:
                        logging.info(
                            "admintools:getparticipants:GET: Adding %s" % user)
                        users.append({
                            "id": user.id,
                            "username": user.username,
                            "last_name": user.last_name,
                            "first_name": user.first_name
                        })

                logging.info(
                    "admintools:getparticipants:GET: Received %s users" %
                    len(tgr.users))
                if len(tgr.users) < 200:
                    break
                else:
                    offset += len(tgr.users)
                    time.sleep(0.3)
            users_shelve["data"] = users
        users_shelve.close()
        return "ok"
Example #7
0
def list_users_in_group():
    chats = []
    last_date = None
    chunk_size = 200
    groups = []

    result = client(
        GetDialogsRequest(offset_date=last_date,
                          offset_id=0,
                          offset_peer=InputPeerEmpty(),
                          limit=chunk_size,
                          hash=0))
    chats.extend(result.chats)

    for chat in chats:
        try:
            print(chat)
            groups.append(chat)
            # if chat.megagroup== True:
        except:
            continue

    print('Choose a group to scrape members from:')
    i = 0
    for g in groups:
        print(str(i) + '- ' + g.title)
        i += 1

    g_index = input("Enter a Number: ")
    target_group = groups[int(g_index)]

    print('\n\nGrupo elegido:\t' + groups[int(g_index)].title)

    print('Fetching Members...')
    all_participants = []
    all_participants = client.get_participants(target_group, aggressive=True)

    print('Saving In file...')
    with open("members-" +
              re.sub("-+", "-",
                     re.sub("[^a-zA-Z]", "-", str.lower(target_group.title))) +
              ".csv",
              "w",
              encoding='UTF-8') as f:
        writer = csv.writer(f, delimiter=",", lineterminator="\n")
        writer.writerow([
            'username', 'user id', 'access hash', 'name', 'group', 'group id'
        ])
        for user in all_participants:
            if user.username:
                username = user.username
            else:
                username = ""
            if user.first_name:
                first_name = user.first_name
            else:
                first_name = ""
            if user.last_name:
                last_name = user.last_name
            else:
                last_name = ""
            name = (first_name + ' ' + last_name).strip()
            writer.writerow([
                username, user.id, user.access_hash, name, target_group.title,
                target_group.id
            ])
    print('Members scraped successfully.')
Example #8
0
def e():
    try:
        r = c.RawConfigParser()  #Read Group Keys
        r.read('degerler.veri')
        cfg = r['veri']['config_no']
        group_username = r['veri']['kanal_grup_adi']
        ags = r['veri']['aktif_gun_sayisi']
        bsk = r['veri']['beklenicek_sure_kucuk']
        bsb = r['veri']['beklenicek_sure_buyuk']
        intags = int(ags)
        intbsk = int(bsk)
        intbsb = int(bsb)
        cpass = c.RawConfigParser()
        cpass.read(cfg)
    except:
        print("Something is wrong with degerler.veri!!")
    try:
        id = cpass['cred']['id']
        h = cpass['cred']['hash']
        p = cpass['cred']['phone']
        client = TelegramClient(p, id, h)
    except KeyError:
        print("[!] Api access id phone or hash is not correct!!\n")
        sys.exit(1)
    client.connect()
    if not client.is_user_authorized():
        client.send_code_request(p)
        client.sign_in(p, input('[+] Enter code sent from telegram : '))
    client(JoinChannelRequest(channel=group_username))
    chats = []
    last_date = None
    chunk_size = 200
    groups = []
    result = client(
        GetDialogsRequest(offset_date=last_date,
                          offset_id=0,
                          offset_peer=InputPeerEmpty(),
                          limit=chunk_size,
                          hash=0))
    chats.extend(result.chats)
    for chat in chats:
        try:
            check = client.get_entity(group_username)
            if check.id == chat.id:
                groups.append(chat)
        except:
            continue
    i = 0
    for group in groups:
        print('[' + str(i) + ']' '-' + group.title)
        i += 1
    g_index = 0
    aktif_gun_sayisi = intags
    target_group = groups[int(g_index)]
    all_participants = []
    time.sleep(random.randrange(11, 23))
    all_participants = client.get_participants(
        target_group
    )  #patched because telegram seems to ban while using it! , aggressive=True)
    with open("users.nya", "w", encoding='UTF-8') as f:
        writer = csv.writer(f, delimiter=",", lineterminator="\n")
        writer.writerow([
            'username', 'user id', 'access hash', 'name', 'group', 'group id'
        ])
        for user in all_participants:
            #contacts = client(GetContactsRequest(0))
            #client(AddChatUserRequest(chat_id=chat.id,user_id=user.id,fwd_limit=10))
            accept = True
            try:
                lastDate = user.status.was_online
                ay_kontrolu = (datetime.now().month - lastDate.month)
                gun_kontrolu = (datetime.now().day - lastDate.day)
                if (ay_kontrolu > 0 or gun_kontrolu > aktif_gun_sayisi
                        or datetime.now().year != lastDate.year):
                    accept = False
            except:
                pass
            if (accept):
                if user.username:
                    username = user.username
                else:
                    username = ""
                if user.first_name:
                    first_name = user.first_name
                else:
                    first_name = ""
                if user.last_name:
                    last_name = user.last_name
                else:
                    last_name = ""
                name = (first_name + ' ' + last_name).strip()
                writer.writerow([
                    username, user.id, user.access_hash, name,
                    target_group.title, target_group.id
                ])
    client(LeaveChannelRequest(channel=group_username))
    os._exit(1)
Example #9
0
def start(config):
    try:
        api_id = config['api_id']
        session_name = config["session_name"]
        api_hash = config["api_hash"]
        phone_number = config['phone_number']
    
        client = TelegramClient(session_name, api_id, api_hash)
    except KeyError:
        print("Unable to get Telegram developer id.\nPlease register for telegram developer.")
        sys.exit(1)    
    client.connect()
    client.start()
    if not client.is_user_authorized():
        client.send_code_request(phone_number)
        client.sign_in(phone_number, input('Enter the code: '))

    chats = []
    last_date = None
    chunk_size = 200
    groups=[]
 
    result = client(GetDialogsRequest(
             offset_date=last_date,
             offset_id=0,
             offset_peer=InputPeerEmpty(),
             limit=chunk_size,
             hash = 0
         ))
    chats.extend(result.chats)
    for chat in chats:
        try:
            if chat.megagroup== True:
                groups.append(chat)
        except:
            continue
    print('Choose a group to scrape members :')
    i=0
    for g in groups:
        print('['+str(i)+']'+' - '+ g.title)
        i+=1
 
    print('')
    g_index = input("Enter a Number : ")
    target_group=groups[int(g_index)]
 
    print('Fetching Members...')
    time.sleep(1)
    all_participants = []
    all_participants = client.get_participants(target_group, aggressive=True)
 
    print('Saving In file...')
    time.sleep(1)
    with open("members.csv","w",encoding='UTF-8') as f:
        writer = csv.writer(f,delimiter=",",lineterminator="\n")
        writer.writerow(['username','user_id', 'access_hash','name','group', 'group_id','status'])
        for user in all_participants:
            if user.username:
                username= user.username
            else:
                username= ""
            if user.first_name:
                first_name= user.first_name
            else:
                first_name= ""
            if user.last_name:
                last_name= user.last_name
            else:
                last_name= ""
            name= (first_name + ' ' + last_name).strip()
            writer.writerow([username,user.id,user.access_hash,name,target_group.title, target_group.id, 'N'])      
    print('Members scraped successfully.')
Example #10
0
    def run(self):
        try:
            auth_srv = auth_service.AuthService()
            self.client = auth_srv.auth()
        except KeyError:
            os.system('clear')
            print("[!] run python setup.py first !!\n")
            sys.exit(1)

        chats = []
        last_date = None
        chunk_size = 200
        groups = []

        result = self.client(
            GetDialogsRequest(offset_date=last_date,
                              offset_id=0,
                              offset_peer=InputPeerEmpty(),
                              limit=chunk_size,
                              hash=0))
        chats.extend(result.chats)

        for chat in chats:
            try:
                if chat.megagroup == True:
                    groups.append(chat)
            except:
                continue

        print('[+] Choose a group to scrape members :')
        i = 0
        for g in groups:
            print('[' + str(i) + ']' + ' - ' + g.title)
            i += 1

        print('')
        g_index = input("[+] Enter a Number : ")
        target_group = groups[int(g_index)]

        print('[+] Fetching Members...')
        time.sleep(1)
        all_participants = self.client.get_participants(target_group,
                                                        aggressive=True)

        print('[+] Saving In file...')
        time.sleep(1)
        with open("members.csv", "w", encoding='UTF-8') as f:
            writer = csv.writer(f, delimiter=",", lineterminator="\n")
            writer.writerow([
                'username', 'user id', 'access hash', 'name', 'group',
                'group id'
            ])
            for user in all_participants:
                if user.username:
                    username = user.username
                else:
                    username = ""
                if user.first_name:
                    first_name = user.first_name
                else:
                    first_name = ""
                if user.last_name:
                    last_name = user.last_name
                else:
                    last_name = ""
                name = (first_name + ' ' + last_name).strip()
                writer.writerow([
                    username, user.id, user.access_hash, name,
                    target_group.title, target_group.id
                ])
        print('[+] Members scraped successfully.')
Example #11
0
    def tg_process_dialogs(self, jid):
        # Инициализируем словари для диалогов
        self.tg_dialogs[jid] = dict()
        self.tg_dialogs[jid]['raw'] = list()
        self.tg_dialogs[jid]['users'] = dict()
        self.tg_dialogs[jid]['groups'] = dict()
        self.tg_dialogs[jid]['supergroups'] = dict()

        # Оффсеты для получения диалогов
        last_peer = InputPeerEmpty()
        last_msg_id = 0
        last_date = None

        while True:  # В цикле по кускам получаем все диалоги
            dlgs = self.tg_connections[jid].invoke(
                GetDialogsRequest(offset_date=last_date,
                                  offset_id=last_msg_id,
                                  offset_peer=last_peer,
                                  limit=100))

            self.tg_dialogs[jid]['raw'].append(dlgs)

            for usr in dlgs.users:
                self.tg_dialogs[jid]['users'][usr.id] = usr
            for cht in dlgs.chats:
                if type(cht) in [Chat, ChatForbidden]:  # Старая группа
                    self.tg_dialogs[jid]['groups'][cht.id] = cht
                elif type(cht) in [Channel, ChannelForbidden]:  # Супергруппа
                    self.tg_dialogs[jid]['supergroups'][cht.id] = cht

            for dlg in dlgs.dialogs:
                if type(dlg.peer) is PeerUser:
                    usr = self.tg_dialogs[jid]['users'][dlg.peer.user_id]
                    vcard = self.plugin['xep_0054'].make_vcard()
                    u_jid = 'u' + str(usr.id) + '@' + self.boundjid.bare

                    if usr.deleted:
                        vcard['FN'] = 'Deleted account'
                        vcard[
                            'DESC'] = 'This user no longer exists in Telegram'
                    else:
                        vcard['FN'] = display_tg_name(usr.first_name,
                                                      usr.last_name)
                        if usr.first_name:
                            vcard['N']['GIVEN'] = usr.first_name
                        if usr.last_name:
                            vcard['N']['FAMILY'] = usr.last_name
                        if usr.username:
                            vcard[
                                'DESC'] = 'Telegram Username: @' + usr.username

                            if usr.bot:
                                vcard['DESC'] += ' [Bot]'

                        vcard['NICKNAME'] = vcard['FN']

                    vcard['JABBERID'] = u_jid
                    self.plugin['xep_0054'].publish_vcard(jid=u_jid,
                                                          vcard=vcard)
                    self.plugin['xep_0172'].publish_nick(nick=vcard['FN'],
                                                         ifrom=u_jid)

                    self.send_presence(pto=jid, pfrom=u_jid, ptype='subscribe')

                    if usr.bot:
                        self.send_presence(pto=jid, pfrom=u_jid, pstatus='Bot')
                    else:
                        if type(usr.status) is UserStatusOnline:
                            self.send_presence(pto=jid, pfrom=u_jid)
                        elif type(usr.status) is UserStatusRecently:
                            self.send_presence(pto=jid,
                                               pfrom=u_jid,
                                               pshow='away',
                                               pstatus='Last seen recently')
                        elif type(usr.status) is UserStatusOffline:
                            self.send_presence(
                                pto=jid,
                                pfrom=u_jid,
                                ptype='xa',
                                pstatus=usr.status.was_online.strftime(
                                    'Last seen at %H:%M %d/%m/%Y'))
                        else:
                            self.send_presence(
                                pto=jid,
                                pfrom=u_jid,
                                ptype='unavailable',
                                pstatus='Last seen a long time ago')

                if type(dlg.peer) in [PeerChat, PeerChannel]:
                    g_type = ''
                    cht = None

                    if type(dlg.peer) is PeerChat:  # Старая группа
                        cht = self.tg_dialogs[jid]['groups'][dlg.peer.chat_id]
                        c_jid = 'g' + str(cht.id) + '@' + self.boundjid.bare
                        g_type = 'G'
                    elif type(dlg.peer) is PeerChannel:  # Супергруппа
                        cht = self.tg_dialogs[jid]['supergroups'][
                            dlg.peer.channel_id]

                        if cht.broadcast:
                            g_type = 'C'
                            c_jid = 'c' + str(
                                cht.id) + '@' + self.boundjid.bare
                        else:
                            g_type = 'SG'
                            c_jid = 's' + str(
                                cht.id) + '@' + self.boundjid.bare

                    vcard = self.plugin['xep_0054'].make_vcard()
                    vcard['FN'] = '[{}] {}'.format(g_type, cht.title)
                    vcard['NICKNAME'] = vcard['FN']
                    vcard['JABBERID'] = c_jid
                    self.plugin['xep_0054'].publish_vcard(jid=c_jid,
                                                          vcard=vcard)
                    self.plugin['xep_0172'].publish_nick(nick=vcard['FN'],
                                                         ifrom=c_jid)

                    self.send_presence(pto=jid, pfrom=c_jid, ptype='subscribe')
                    self.send_presence(pto=jid, pfrom=c_jid)

            if len(dlgs.dialogs
                   ) == 0:  # Если все диалоги получены - прерываем цикл
                break
            else:  # Иначе строим оффсеты
                last_msg_id = dlgs.dialogs[
                    -1].top_message  # Нужен последний id сообщения. Наркоманы.
                last_peer = dlgs.dialogs[-1].peer

                last_date = next(
                    msg for msg in dlgs.messages  # Ищем дату среди сообщений
                    if type(msg.to_id) is type(last_peer)
                    and msg.id == last_msg_id).date

                if type(last_peer) is PeerUser:  # Пользователь
                    access_hash = self.tg_dialogs[jid]['users'][
                        last_peer.user_id].access_hash
                    last_peer = InputPeerUser(last_peer.user_id, access_hash)
                elif type(last_peer) in [Chat, ChatForbidden]:  # Группа
                    last_peer = InputPeerChat(last_peer.chat_id)
                elif type(last_peer) in [Channel,
                                         ChannelForbidden]:  # Супергруппа
                    access_hash = self.tg_dialogs[jid]['supergroups'][
                        last_peer.channel_id].access_hash
                    last_peer = InputPeerChannel(last_peer.channel_id,
                                                 access_hash)
Example #12
0
            def function (args) : 
                while True:
                    try:
                        sat = input("Ваш Выбор > ")
                        if sat == "01" or sat == "1":
                            from telethon.sync import TelegramClient
                            from telethon.tl.functions.messages import GetDialogsRequest
                            from telethon.tl.types import InputPeerEmpty
                            import os, sys
                            import configparser
                            import csv
                            import time 
                            sp = open("members2.csv", "a")
                            sp.write(input('\nДобавить Username к списку: ') + '\n')
                            
                            sp.close()
                            print (sp)
                            break 
                            
                        
                        
			restart_program()
		elif santet == "03" or santet == "3":
					#!/usr/dev/python3
					#Bednakov-Xack-Live
					#2020/01/05
					from telethon.sync import TelegramClient
					from telethon.tl.functions.messages import GetDialogsRequest
					from telethon.tl.types import InputPeerEmpty
					import os, sys
					import configparser
					import csv
					import time




					def banner():
						print(f"""
	╔╦╗┌─┐┬  ┌─┐╔═╗  ╔═╗┌─┐┬─┐┌─┐┌─┐┌─┐┬─┐
	 ║ ├┤ │  ├┤ ║ ╦  ╚═╗│  ├┬┘├─┤├─┘├┤ ├┬┘
	 ╩ └─┘┴─┘└─┘╚═╝  ╚═╝└─┘┴└─┴ ┴┴  └─┘┴└─

			version : 18
		 Anonimus cicada3301
								""")

					cpass = configparser.RawConfigParser()


					try:
						api = open("API.txt","r")
						api_id = api.read()
						api.close()
						hash = open("hash.txt","r")
						api_hash = hash.read()
						hash.close()
						tel = open("tel.txt","r")
						phone = tel.read()
						tel.close()
						client = TelegramClient(phone, api_id, api_hash)
					except KeyError:
						banner()
						sys.exit(1)

					client.connect()
					if not client.is_user_authorized():
						client.send_code_request(phone)
						banner()
						client.sign_in(phone, input('[+] введите код из смс: '))

					banner()
					chats = []
					last_date = None
					chunk_size = 200
					groups=[]

					result = client(GetDialogsRequest(
								 offset_date=last_date,
								 offset_id=0,
								 offset_peer=InputPeerEmpty(),
								 limit=chunk_size,
								 hash = 0
							 ))
					chats.extend(result.chats)

					for chat in chats:
						try:
							if chat.megagroup== True:
								groups.append(chat)
						except:
							continue

					print('[+] Выберите группу, чтобы спиздить участников :')
					i=0
					for g in groups:
						print('['+str(i)+']'+' - '+ g.title)
						i+=1

					print('')
					g_index = input("[+] Введите номер : ")
					target_group=groups[int(g_index)]

					print('[+] Выборка участников...')
					time.sleep(2.5)
					all_participants = []
					all_participants = client.get_participants(target_group, aggressive=True)

					print('[+] Сохранение в файл...')
					time.sleep(2)
					with open("members.csv","w",encoding='UTF-8') as f:
						writer = csv.writer(f,delimiter=",",lineterminator="\n")
						writer.writerow(['username','user id', 'access hash','name','group', 'group id'])
						for user in all_participants:
							if user.username:
								username= user.username
							else:
								username= ""
							if user.first_name:
								first_name= user.first_name
							else:
								first_name= ""
							if user.last_name:
								last_name= user.last_name
							else:
								last_name= ""
							name= (first_name + ' ' + last_name).strip()
							writer.writerow([username,user.id,user.access_hash,name,target_group.title, target_group.id])
					print('[+] Участники успешно сохранены.')
					restart_program()
Example #13
0
def add_all():
    input_file = "ext_members.csv"
    users = []
    with open(input_file, encoding='UTF-8') as f:
        rows = csv.reader(f, delimiter=",", lineterminator="\n")
        next(rows, None)
        for row in rows:
            user = {}
            user['username'] = row[0]
            user['id'] = int(row[1])
            user['access_hash'] = int(row[2])
            user['name'] = row[3]
            users.append(user)

    chats = []
    last_date = None
    chunk_size = 300
    groups = []

    result = client(
        GetDialogsRequest(offset_date=last_date,
                          offset_id=0,
                          offset_peer=InputPeerEmpty(),
                          limit=chunk_size,
                          hash=0))

    chats.extend(result.chats)
    dialogs = client.get_dialogs()

    m = input("1: For only permitted groups \n2: For all groups\n")

    for chat in chats:
        try:
            if chat.megagroup == True:
                groups.append(chat)
        except:
            continue

    print('Choose a group to add members:')
    i = 0
    for group in groups:
        print(str(i) + '- ' + group.title)
        i += 1

    g_index = input("Enter a Number: ")
    target_group = groups[int(g_index)]

    target_group_entity = InputPeerChannel(target_group.id,
                                           target_group.access_hash)

    mode = int(input("Enter 1 to add by username or 2 to add by ID: "))

    n = 0

    for user in users:
        n += 1
        if n % 50 == 0:
            time.sleep(900)
        try:
            print("Adding {}".format(user['id']))
            if mode == 1:
                if user['username'] == "":
                    continue
                user_to_add = client.get_input_entity(user['username'])
            elif mode == 2:
                user_to_add = InputPeerUser(user['id'], user['access_hash'])
            else:
                sys.exit("Invalid Mode Selected. Please Try Again.")
            client(InviteToChannelRequest(target_group_entity, [user_to_add]))
            print("Waiting for 60-180 Seconds...")
            time.sleep(random.randrange(10, 20))
        except PeerFloodError:
            print(
                "Getting Flood Error from telegram. Script is stopping now. Please try again after some time."
            )
        except UserPrivacyRestrictedError:
            print(
                "The user's privacy settings do not allow you to do this. Skipping."
            )
        except:
            traceback.print_exc()
            print("Unexpected Error")
            continue
Example #14
0
def all_dialog(client):
    dialogs = []
    users = []
    chats = []
    last_date = None
    chunk_size = 200
    block = 1
    sleep_counter = 0
    while True:
        result = client(GetDialogsRequest(offset_date=last_date, offset_id=0, offset_peer=InputPeerEmpty(), limit=chunk_size))
        dialogs.extend(result.dialogs)
        users.extend(result.users)
        chats.extend(result.chats)
        log.warning("Block: {},    Count: {},   Users: {},  Dialog: {},  Chat: {}".format(block, len(result.messages), len(result.users), len(result.dialogs), len(result.chats)))
        block += 1
        sleep_counter += 1
        if not result.messages:
            break
        last_date = min(msg.date for msg in result.messages)
        if sleep_counter > 4:
            sleep(1)
            sleep_counter = 0
    return {"dialogs": dialogs, "users": users, "chats": chats}
Example #15
0
def tg(group_id):

    #load configuration - whitelisted data
    db = pymysql.connect("localhost", db_username, db_pwd, db_name)
    cursor = db.cursor()
    sql = "SELECT user_id,  group_id  FROM tg_whitelist WHERE group_id = %s" % (
        group_id)
    try:
        cursor.execute(sql)
        config = cursor.fetchone()
    except:
        print("Error: unable to fetch data")
        db.close()
        sys.exit()
    else:
        db.close()
        if config:
            admin_user_id = config[0]
        else:
            print('No config loaded..')
            sys.exit()

    try:
        # tg client start
        # same session would lock the database, nothing can do if this session is in process
        client = TelegramClient(session_name, api_id, api_hash)
        client.start()
    except Exception as e:
        print(str(e))
    else:

        try:
            #to play safe, run get dialog first

            dialog_result = client(
                functions.messages.GetDialogsRequest(
                    offset_date=datetime.datetime(future_year, 12, 25),
                    offset_id=0,
                    offset_peer=InputPeerEmpty(),
                    limit=200,
                    hash=0))

            #clear all message history with admin user first
            client(
                functions.messages.DeleteHistoryRequest(
                    peer=client.get_input_entity(admin_user_id),
                    max_id=0,
                    just_clear=True,
                    revoke=True))
        except Exception as e:
            print(str(e))
        print('history deleted')
        try:
            seperator = ','
            users = []
            outputs = []
            mychannel = client.get_input_entity(group_id)
            start = True
            total = 0
            offset = 0
            total_ghost = 0
            db = pymysql.connect("localhost", db_username, db_pwd, db_name)
            cursor = db.cursor()
            #delete everything first
            sql = 'DELETE FROM tg_users where group_id = %s ' % (group_id)
            try:
                cursor.execute(sql)
                db.commit()
            except:
                db.rollback()

            cursor.execute('SET NAMES utf8mb4')
            insert_data = []
            while start == True or total > 0:
                channel_members = client(
                    functions.channels.GetParticipantsRequest(
                        channel=mychannel,
                        filter=types.ChannelParticipantsSearch(''),
                        offset=offset,
                        limit=200,
                        hash=0))

                print('get participants ' + str(offset))
                print('')
                offset += 200
                start = False
                total = len(channel_members.users)
                #print(channel_members.stringify())
                if len(channel_members.users) > 0:
                    for user in channel_members.users:
                        user_field = ()
                        if user.deleted == True or admin_user_id == user.id or user.id == tg_config.setting[
                                'user_bot_id']:
                            continue
                        print('loop' + str(user.id))
                        result = client(
                            functions.messages.SearchRequest(
                                peer=mychannel,
                                q='',
                                filter=types.InputMessagesFilterEmpty(),
                                min_date=datetime.datetime(future_year, 6, 25),
                                max_date=datetime.datetime(future_year, 6, 25),
                                offset_id=0,
                                add_offset=0,
                                limit=1,
                                max_id=0,
                                min_id=0,
                                hash=0,
                                from_id=client.get_input_entity(user.id)))

                        #print(result.stringify())
                        if user.bot == False and result.count > min_message:
                            continue

                        total_ghost += 1

                        username = ''
                        first_name = ''
                        last_name = ''
                        is_bot = 0

                        user_field = user_field + (group_id, )
                        user_field = user_field + (user.id, )
                        #user_field.append(str(group_id))
                        #user_field.append(str(user.id))

                        if user.username is not None:
                            username = user.username

                        if user.first_name is not None:
                            first_name = user.first_name

                        if user.last_name is not None:
                            last_name = user.last_name

                        if user.bot == True:
                            is_bot = 1

                        user_field = user_field + (username, )
                        user_field = user_field + (first_name, )
                        user_field = user_field + (last_name, )
                        user_field = user_field + (result.count, )
                        user_field = user_field + (is_bot, )

                        #user_field.append("'"+username+"'")
                        #user_field.append("'"+first_name+"'")
                        #user_field.append("'"+last_name+"'")
                        #user_field.append(str(result.count))

                        #sql_str='(' + seperator.join(user_field) + ') '
                        insert_data.append(user_field)

            if len(insert_data) > 0:
                try:
                    cursor.executemany(
                        'INSERT INTO tg_users(group_id,user_id,username,first_name,last_name,message_count,bot) VALUES (%s, %s, %s, %s, %s, %s, %s) ',
                        insert_data)
                    db.commit()
                except:
                    db.rollback()
            db.close()
            user_field = None
            insert_data = None

        except Exception as e:
            client.disconnect()
            print(str(e))
        else:
            client.disconnect()
            if total_ghost > 0:
                tg_send(group_id, admin_user_id, total_ghost)
Example #16
0
def list_users_in_group():
    global ve
    chats = []
    last_date = None
    chunk_size = 200
    groups = []

    result = client(
        GetDialogsRequest(offset_date=last_date,
                          offset_id=0,
                          offset_peer=InputPeerEmpty(),
                          limit=chunk_size,
                          hash=0))
    chats.extend(result.chats)

    for chat in chats:
        try:
            if chat.megagroup == True:
                groups.append(chat)
            # if chat.megagroup== True:
        except:
            continue

    print('Choose a group to scrape members from:')
    i = 0
    for g in groups:
        print(str(i) + '- ' + g.title)
        i += 1

    g_index = input("Enter a Number: ")
    target_group = groups[int(g_index)]

    print('\n\nGroup Selected:\t' + groups[int(g_index)].title)

    print('Fetching Members...')
    all_participants = []
    all_participants = client.get_participants(target_group, aggressive=True)

    print('Saving In file...')

    with open(f"data/data{ve}.csv", "w", encoding='UTF-8') as f:
        writer = csv.writer(f, delimiter=",", lineterminator="\n")
        writer.writerow([
            'sr. no.', 'username', 'user id', 'access hash', 'name', 'group',
            'group id', 'status'
        ])
        i = 0
        for user in all_participants:
            i += 1
            if user.username:
                username = user.username
            else:
                username = ""
            if user.first_name:
                first_name = user.first_name
            else:
                first_name = ""
            if user.last_name:
                last_name = user.last_name
            else:
                last_name = ""
            name = (first_name + ' ' + last_name).strip()
            if isinstance(user.status, types.UserStatusOnline):
                status = 1

            elif isinstance(user.status, types.UserStatusOffline):
                if time.time() - (user.status.was_online).timestamp() <= 86400:
                    status = 2
                else:
                    status = 31634268763763
            writer.writerow([
                i, username, user.id, user.access_hash, name,
                target_group.title, target_group.id, status
            ])
    print('Members scraped successfully.')
Example #17
0
async def main():
    # To Add Members.......
    async def getmem():
        clear()
        print(colorText(wt))
        print('')
        print('')

        print(ye + '[+] Choose your channel to Add members.')
        a = 0
        for i in channel:
            print(gr + '[' + str(a) + ']', i.title)
            a += 1
        opt1 = int(input(ye + 'Enter a number: '))
        my_participants = await client.get_participants(channel[opt1])
        target_group_entity = InputPeerChannel(channel[opt1].id,
                                               channel[opt1].access_hash)
        my_participants_id = []
        for my_participant in my_participants:
            my_participants_id.append(my_participant.id)
        with open('members.txt', 'r') as r:
            users = json.load(r)
        count = 1
        i = 0
        adds = 0
        exi = 0
        pri = 0
        bot = 0
        tomuch = 0
        dlt = 0
        mut = 0
        ero = 0
        flooderror = 0
        for user in users:
            clear()
            print(colorText(wt))
            print(r"==========================================")
            print(gr + "| Member Added                      : ", adds, "|")
            print(ye + "| User Exists. Skipped              : ", exi, "|")
            print(re + "| Privacy Enabled. Skipped          : ", pri, "|")
            print(re + "| This is Bot. Skipped              : ", bot, "|")
            print(re + "| User in too much channel. Skipped : ", tomuch, "|")
            print(re + "| Deleted Account. Skipped          : ", dlt, "|")
            print(re + "| Mutual No. Skipped                : ", mut, "|")
            print(re + "| Error                             : ", ero, "|")
            print(re + "| Peer Flood Error                  : ", flooderror,
                  "|")
            print(r"==========================================")
            if count % 51 == 0:
                # print(colorText(wt))
                print('')
                print('')
                print(ye + "50 members added")
                break
            elif count >= 300:
                await client.disconnect()
                break
            elif i >= 8:
                await client.disconnect()
                print(
                    re +
                    "Getting Flood Error from telegram. Script is stopping now. Please try again after some time."
                )
                break
            if user['uid'] in my_participants_id:
                # print(gr+'User present. Skipping.')
                exi += 1
                clear()
                print(colorText(wt))
                print(r"==========================================")
                print(gr + "| Member Added                      : ", adds, "|")
                print(ye + "| User Exists. Skipped              : ", exi, "|")
                print(re + "| Privacy Enabled. Skipped          : ", pri, "|")
                print(re + "| This is Bot. Skipped              : ", bot, "|")
                print(re + "| User in too much channel. Skipped : ", tomuch,
                      "|")
                print(re + "| Deleted Account. Skipped          : ", dlt, "|")
                print(re + "| Mutual No. Skipped                : ", mut, "|")
                print(re + "| Error                             : ", ero, "|")
                print(re + "| Peer Flood Error                  : ",
                      flooderror, "|")
                print(r"==========================================")
                continue
            else:
                try:
                    user_to_add = InputPeerUser(user['uid'],
                                                user['access_hash'])
                    add = await client(
                        InviteToChannelRequest(target_group_entity,
                                               [user_to_add]))
                    # print(gr+'Added ', str(user['uid']))
                    count += 1
                    i = 0
                    adds += 1
                # time.sleep(random.randrange(1, 5))

                except PeerFloodError:
                    # print(re+"Getting Flood Error from telegram. Script is stopping now. Please try again after some time.")
                    i += 1
                    flooderror += 1
                except UserPrivacyRestrictedError:
                    # print(re+"The user's privacy settings do not allow you to do this. Skipping.")
                    # print("Waiting for 5-15 Seconds...")
                    pri += 1
                # time.sleep(random.randrange(5, 15))

                except UserBotError:
                    # print(re+"Can't add Bot. Skipping.")
                    bot += 1

                except InputUserDeactivatedError:
                    # print(re+"The specified user was deleted. Skipping.")
                    dlt += 1

                except UserChannelsTooMuchError:
                    # print(re+"User in too much channel. Skipping.")
                    tomuch += 1
                except UserNotMutualContactError:
                    # print(re+'Mutual No. Skipped.')
                    mut += 1

                except Exception as e:
                    # print(re+"Error:", e)
                    # print("Trying to continue...")
                    # i += 1
                    # time.sleep(1)
                    ero += 1
                    continue
            # time.sleep(1)
            #end

    print(colorText(wt))
    chats = []
    channel = []
    result = await client(
        GetDialogsRequest(offset_date=None,
                          offset_id=0,
                          offset_peer=InputPeerEmpty(),
                          limit=200,
                          hash=0))
    chats.extend(result.chats)
    for a in chats:
        try:
            if True:
                channel.append(a)
        except:
            continue

    a = 0
    print('')
    print('')
    print(ye + 'Choose a group to scrape.')
    for i in channel:
        print(gr + '[' + str(a) + ']', i.title)
        a += 1
    op = input(ye + 'Enter a number (or press ENTER to skip): ')
    if op == '':
        print(ye + 'Ok. skipping...')
        await getmem()
        sys.exit()
    else:
        pass
    opt = int(op)
    print('')
    print(ye + '[+] Fetching Members...')
    target_group = channel[opt]
    all_participants = []
    mem_details = []
    all_participants = await client.get_participants(target_group)
    for user in all_participants:
        try:
            if user.username:
                username = user.username
            else:
                username = ""
            if user.first_name:
                firstname = user.first_name
            else:
                firstname = ""
            if user.last_name:
                lastname = user.last_name
            else:
                lastname = ""

            new_mem = {
                'uid': user.id,
                'username': username,
                'firstname': firstname,
                'lastname': lastname,
                'access_hash': user.access_hash
            }
            mem_details.append(new_mem)
        except ValueError:
            continue

    with open('members.txt', 'w') as w:
        json.dump(mem_details, w)
    print(ye + 'Please wait.....')
    done = input(
        gr + '[+] Members scraped successfully. (Press enter to Add members)')
    await getmem()

    await client.disconnect()
Example #18
0
def add_users_to_group():
    global ve
    input_file = f'data/data{ve}.csv'
    users = []
    with open(input_file, encoding='UTF-8') as f:
        rows = csv.reader(f, delimiter=",", lineterminator="\n")
        next(rows, None)
        for row in rows:
            user = {}
            user['srno'] = row[0]
            user['username'] = row[1]
            try:
                user['id'] = int(row[2])
                user['access_hash'] = int(row[3])
                user['name'] = row[4]
            except IndexError:
                print('users without id or access_hash')
            users.append(user)
    #random.shuffle(users)
    chats = []
    last_date = None
    chunk_size = 10
    groups = []

    result = client(
        GetDialogsRequest(offset_date=last_date,
                          offset_id=0,
                          offset_peer=InputPeerEmpty(),
                          limit=chunk_size,
                          hash=0))
    chats.extend(result.chats)

    for chat in chats:
        try:
            if chat.megagroup == True:  # CONDITION TO ONLY LIST MEGA GROUPS.
                groups.append(chat)

        except:
            continue

    print('Choose a group to add members:')
    i = 0
    for group in groups:
        print(str(i) + '- ' + group.title)
        i += 1

    g_index = input("Enter a Number: ")
    target_group = groups[int(g_index)]
    print('\n\nGroup Selected:\t' + groups[int(g_index)].title)

    target_group_entity = InputPeerChannel(target_group.id,
                                           target_group.access_hash)

    mode = int(input("Enter 1 to add by username or 2 to add by ID: "))
    startfrom = int(input("Start From = "))
    endto = int(input("End To = "))
    delta_xd = False
    error_count = 0

    for user in users:
        global status

        status = 'do'
        countt = 6
        if (int(startfrom) <= int(user['srno'])) and (int(user['srno']) <=
                                                      int(endto)):

            try:

                if mode == 1:
                    if user['username'] == "":
                        print('no username, moving to next')
                        continue
                    user_to_add = client.get_input_entity(user['username'])
                elif mode == 2:
                    user_to_add = InputPeerUser(user['id'],
                                                user['access_hash'])
                else:
                    sys.exit("Invalid Mode Selected. Please Try Again.")
                client(
                    InviteToChannelRequest(target_group_entity, [user_to_add]))
                #print("Waiting 60 Seconds...")
                status = 'DONE'
                time.sleep(5)
            except PeerFloodError:
                status = 'PeerFloodError'
                print('Script Is Stopping Now For 24 Hours')
                time.sleep(86400)
                #print("Getting Flood Error from telegram. Script is stopping now. Please try again after some time.")
            except UserPrivacyRestrictedError:
                status = 'PrivacyError'
                #print("The user's privacy settings do not allow you to do this. Skipping.")
            except errors.RPCError as e:
                status = e.__class__.__name__

            except Exception as d:
                status = d
            except:
                traceback.print_exc()
                print("Unexpected Error")
                error_count += 1
                if error_count > 10:
                    sys.exit('too many errors')
                continue
            channel_full_info = client(
                GetFullChannelRequest(channel=target_group_entity))

            countt = int(channel_full_info.full_chat.participants_count)

            print(
                f"ADDING {user['name']} TO {target_group.title} TOTAL: {countt} - {status}"
            )
        elif int(user['srno']) > int(endto):
            #print("Members Added Successfully!")
            delta_xd = True
    print("Done!" if delta_xd else "Error!")
def b():
    nya = c.RawConfigParser()  #Instance desu
    nya.read('degerler.veri')
    cfg = nya['veri']['config_no']
    satno = nya['veri']['satir_no']
    kissay = nya['veri']['kisi_sayisi']
    group_username = nya['veri']['kanal_grup_adi']
    ags = nya['veri']['aktif_gun_sayisi']
    bsk = nya['veri']['beklenicek_sure_kucuk']
    bsb = nya['veri']['beklenicek_sure_buyuk']
    intsatno = int(satno)
    intkissay = int(kissay)
    intags = int(ags)
    intbsk = int(bsk)
    intbsb = int(bsb)
    cpass = c.RawConfigParser()
    cpass.read(cfg)
    try:
        id = cpass['cred']['id']
        h = cpass['cred']['hash']
        p = cpass['cred']['phone']
        client = TelegramClient(p, id, h)
    except KeyError:
        os.system('cls')
        print("[!] Somethings wrong with api id password hash or phone!!\n")
        sys.exit(1)
    client.connect()
    if not client.is_user_authorized():
        client.send_code_request(p)
        os.system('cls')
        client.sign_in(p, input('[+] Enter the code sent from telegram : '))
    client(JoinChannelRequest(channel=group_username))
    os.system('cls')
    users = []
    with open("users.nya", "r", encoding='UTF-8') as fd:
        rows = csv.reader(fd, delimiter=",", lineterminator="\n")
        for row in islice(csv.reader(fd), intsatno, None):
            user = {}
            user['username'] = row[0]
            user['id'] = row[1]
            user['access_hash'] = row[2]
            user['name'] = row[3]
            users.append(user)
    chats = []
    last_date = None
    chunk_size = 200
    groups = []
    result = client(
        GetDialogsRequest(offset_date=last_date,
                          offset_id=0,
                          offset_peer=InputPeerEmpty(),
                          limit=chunk_size,
                          hash=0))
    chats.extend(result.chats)
    for chat in chats:
        try:
            check = client.get_entity(group_username)
            if check.id == chat.id:
                groups.append(chat)
        except:
            continue
    i = 0
    for group in groups:
        print('[' + str(i) + ']' '-' + group.title)
        i += 1
    g_index = 0
    target_group = groups[int(g_index)]
    target_group_entity = InputPeerChannel(target_group.id,
                                           target_group.access_hash)
    mode = 1
    global max_user_to_add_x, max_user_to_add
    max_user_to_add = 0
    max_user_to_add_x = 0
    for user in users:
        try:
            if max_user_to_add == 1:  #intkissay:
                client(LeaveChannelRequest(channel=group_username))
                change_config()
                b()
            if mode == 1:
                if user['username'] == "":
                    max_user_to_add_x += 1
                    continue
                print(f"{p} Adding user {user['id']}")
                max_user_to_add += 1
                max_user_to_add_x += 1
                user_to_add = client.get_input_entity(user['username'])
            #elif mode == 2:
            #	user_to_add = InputPeerUser(user['id'], user['access_hash'])
            client(InviteToChannelRequest(target_group_entity, [user_to_add]))
            print(f"[+] Waiting random time {intbsk} - {intbsb} as seconds.")
            time.sleep(random.randrange(intbsk, intbsb))
        except:
            max_user_to_add -= 1
            max_user_to_add_x += 1
            traceback.print_exc()
            print(f"[+] Waiting random time 11 - 23 as seconds.")
            time.sleep(random.randrange(11, 23))
            continue
Example #20
0
def scraper():
    Name_banner()
    cpass = configparser.RawConfigParser()
    cpass.read('configScrap.data')
    try:
        api_id = cpass['cred']['id']
        api_hash = cpass['cred']['hash']
        phone = cpass['cred']['phone']
        client = TelegramClient(phone, api_id, api_hash)
    except KeyError:
        Name_banner
        print(re + "[!] Go to menu and install application  !!\n")
        sys.exit(1)
    client.connect()
    if not client.is_user_authorized():
        client.send_code_request(phone)

        Name_banner
        client.sign_in(phone, input(gr + '[+] Enter the code: ' + re))

    os.system('clear')
    Name_banner
    chats = []
    last_date = None
    chunk_size = 500
    groups = []

    result = client(
        GetDialogsRequest(offset_date=last_date,
                          offset_id=0,
                          offset_peer=InputPeerEmpty(),
                          limit=chunk_size,
                          hash=0))
    chats.extend(result.chats)

    for chat in chats:
        try:
            if chat.megagroup == True:
                groups.append(chat)
        except:
            continue

    print(gr + '[+] Choose a group to scrape members :' + re)
    i = 0
    for g in groups:
        print(gr + '[' + cy + str(i) + ']' + ' - ' + g.title)
        i += 1

    print('')
    g_index = input(gr + "[+] Enter a Number : " + re)
    target_group = groups[int(g_index)]

    print(gr + '[+] Fetching Members...')
    time.sleep(1)
    all_participants = []
    all_participants = client.get_participants(target_group, aggressive=True)

    print(gr + '[+] Saving In file...')
    time.sleep(1)
    with open("members.csv", "w", encoding='UTF-8') as f:
        writer = csv.writer(f, delimiter=",", lineterminator="\n")
        writer.writerow([
            'username', 'user id', 'access hash', 'name', 'group', 'group id'
        ])
        for user in all_participants:
            if user.username:
                username = user.username
            else:
                username = ""
            if user.first_name:
                first_name = user.first_name
            else:
                first_name = ""
            if user.last_name:
                last_name = user.last_name
            else:
                last_name = ""
            name = (first_name + ' ' + last_name).strip()
            writer.writerow([
                username, user.id, user.access_hash, name, target_group.title,
                target_group.id
            ])
    os.system('clear')
    print(gr + '[+] Members scraped successfully.  ')
    print(gr + '[+] Wait 5 second....  menu is Opening ')
    menu()
Example #21
0
async def main():
    async def getmem():
        clear()
        print(colorText(wt))
        print('')
        print('')
        
        print(ye+'[+] Choose your channel to Add members.')
        a=0
        for i in channel:
            print(gr+'['+str(a)+']', i.title)
            a += 1
        opt1 = int(input(ye+'Enter a number: '))
        my_participants = await client.get_participants(channel[opt1])
        target_group_entity = InputPeerChannel(channel[opt1].id, channel[opt1].access_hash)
        my_participants_id = []
        for my_participant in my_participants:
            my_participants_id.append(my_participant.id)
        with open('erfan4lx_members.txt', 'r') as r:
            users = json.load(r)
        count = 1
        i = 0
        for user in users:
            if count%50 == 0:
                clear()
                print(colorText(wt))
                print('')
                print('')
                print(ye+"please wait for 1 minute...")
                time.sleep(90)
            elif count >= 300:
                await client.disconnect()
                break
            elif i >= 8:
                await client.disconnect()
                break
            count+=1
            time.sleep(1)
            if user['uid'] in my_participants_id:
                print(gr+'User present. Skipping.')
                continue
            else:
                try:
                    user_to_add = InputPeerUser(user['uid'], user['access_hash'])
                    add = await client(InviteToChannelRequest(target_group_entity,[user_to_add]))
                    print(gr+'Added ', str(user['uid']))
                    
                except PeerFloodError:
                    print(re+"Getting Flood Error from telegram. Script is stopping now. Please try again after some time.")
                    i += 1
                except UserPrivacyRestrictedError:
                    print(re+"The user's privacy settings do not allow you to do this. Skipping.")
                    i = 0
                except UserBotError:
                    print(re+"Can't add Bot. Skipping.")
                    i = 0
                except InputUserDeactivatedError:
                    print(re+"The specified user was deleted. Skipping.")
                    i = 0
                except UserChannelsTooMuchError:
                    print(re+"User in too much channel. Skipping.")
                except UserNotMutualContactError:
                    print(re+'Mutual No. Skipped.')
                    i = 0
                except Exception as e:
                    print(re+"Error:", e)
                    print("Trying to continue...")
                    i += 1
                    continue
    
    print(colorText(wt))
    chats = []
    channel = []
    result = await client(GetDialogsRequest(
        offset_date=None,
        offset_id=0,
        offset_peer=InputPeerEmpty(),
        limit=200,
        hash=0
    ))
    chats.extend(result.chats)
    for a in chats:
        try:
            if True:
                channel.append(a)
        except:
            continue

    a = 0
    print('')
    print('')
    print(ye+'Choose a group to scrape.')
    for i in channel:
        print(gr+'['+str(a)+']', i.title)
        a += 1
    op = input(ye+'Enter a number (or press ENTER to skip): ')
    if op == '':
        print(ye+'Ok. skipping...')
        time.sleep(1)
        await getmem()
        sys.exit()
    else: 
        pass
    opt = int(op)
    print('')
    print(ye+'[+] Fetching Members...')
    time.sleep(1)
    target_group = channel[opt]
    all_participants = []
    mem_details = []
    all_participants = await client.get_participants(target_group)
    for user in all_participants:
        try:
            if user.username:
                username = user.username
            else:
                username = ""
            if user.first_name:
                firstname = user.first_name
            else:
                firstname = ""
            if user.last_name:
                lastname = user.last_name
            else:
                lastname = ""

            new_mem = {
                'uid': user.id,
                'username': username,
                'firstname': firstname,
                'lastname': lastname,
                'access_hash': user.access_hash
            }
            mem_details.append(new_mem)
        except ValueError:
            continue
    
    with open('erfan4lx_members.txt', 'w') as w:
        json.dump(mem_details, w)
    time.sleep(1)
    print(ye+'Please wait.....')
    time.sleep(3)
    done = input(gr+'[+] Members scraped successfully. (Press enter to Add members)')
    await getmem()

    await client.disconnect()
Example #22
0
def AddMemberInGroup():
    Name_banner()
    cpass = configparser.RawConfigParser()
    cpass.read('configAddData.data')

    try:
        api_id = cpass['cred']['id']
        api_hash = cpass['cred']['hash']
        phone = cpass['cred']['phone']
        client = TelegramClient(phone, api_id, api_hash)

        async def main():
            # Now you can use all client methods listed below, like for example...
            await client.send_message('me', 'Hello !!!!!')

    except KeyError:
        os.system('clear')
        Name_banner()
        print(
            re +
            "[!] Goto Menu and first setup your Account for adding dara  !!\n")
        sys.exit(1)

    SLEEP_TIME_1 = 100
    SLEEP_TIME_2 = 100
    with client:
        client.loop.run_until_complete(main())
    client.connect()
    if not client.is_user_authorized():
        client.send_code_request(phone)
        client.sign_in(phone, input('40779'))

    users = []
    with open(r"members.csv", encoding='UTF-8') as f:  #Enter your file name
        rows = csv.reader(f, delimiter=",", lineterminator="\n")
        next(rows, None)
        for row in rows:
            user = {}
            user['username'] = row[0]
            user['id'] = int(row[1])
            user['access_hash'] = int(row[2])
            user['name'] = row[3]
            users.append(user)

    chats = []
    last_date = None
    chunk_size = 1000
    groups = []

    result = client(
        GetDialogsRequest(offset_date=last_date,
                          offset_id=0,
                          offset_peer=InputPeerEmpty(),
                          limit=chunk_size,
                          hash=0))
    chats.extend(result.chats)

    for chat in chats:
        try:
            if chat.megagroup == True:
                groups.append(chat)
        except:
            continue

    print('Choose a group to add members:')
    i = 0
    for group in groups:
        print(str(i) + '- ' + group.title)
        i += 1

    g_index = input("Enter a Number: ")
    target_group = groups[int(g_index)]

    target_group_entity = InputPeerChannel(target_group.id,
                                           target_group.access_hash)
    mode = int(input("Enter 1 to add by username or 2 to add by ID: "))
    n = 0
    for user in users:
        n += 1
        if n % 80 == 0:
            time.sleep(60)
        try:
            print("Adding {}".format(user['id']))
            if mode == 1:
                if user['username'] == "":
                    continue
                user_to_add = client.get_input_entity(user['username'])
            elif mode == 2:
                user_to_add = InputPeerUser(user['id'], user['access_hash'])
            else:
                sys.exit("Invalid Mode Selected. Please Try Again.")
            client(InviteToChannelRequest(target_group_entity, [user_to_add]))
            print("Waiting for 60-180 Seconds...")
            time.sleep(random.randrange(0, 5))
        except PeerFloodError:
            print(
                "Some Technical Issu Found.Please Wait Second ..... Solving..."
            )
            print("Waiting {} seconds".format(SLEEP_TIME_2))
            time.sleep(SLEEP_TIME_2)
        except UserPrivacyRestrictedError:
            print(
                "The user's privacy settings do not allow you to do this. Skipping."
            )
            print("Waiting for 5 Seconds...")
            time.sleep(random.randrange(0, 5))
        except:
            traceback.print_exc()
            print("Unexpected Error")
            continue

    menu()
Example #23
0
api_id = 
api_hash = ' '
phone = '+91- '
client = TelegramClient(phone, api_id, api_hash)

client.connect()
if not client.is_user_authorized():
    client.send_code_request(phone)
    client.sign_in(phone, input('Enter the code: '))

chats = []
last_date = None
chunk_size = 20
groups=[]
 
result = client(GetDialogsRequest(offset_date=last_date,offset_id=0,offset_peer=InputPeerEmpty(),limit=chunk_size,hash = 0))
chats.extend(result.chats)
for chat in chats:
    groups.append(chat)


print('Choose a group to scrape members from:')
i=0
for g in groups:
    print(str(i) + '- ' + g.title)
    i+=1
g_index = input("Enter a Number: ")
target_group=groups[int(g_index)]
print('Fetching Members...')
all_participants = []
all_participants = client.get_participants(target_group, aggressive=True)
Example #24
0
def kaydet():
    nya = c.RawConfigParser()  #Grup keylerini oku
    nya.read('degerler.veri')
    cfg = nya['veri']['config_no']
    satno = nya['veri']['satir_no']
    kissay = nya['veri']['kisi_sayisi']
    group_username = nya['veri']['kanal_grup_adi']
    ags = nya['veri']['aktif_gun_sayisi']
    bsk = nya['veri']['beklenicek_sure_kucuk']
    bsb = nya['veri']['beklenicek_sure_buyuk']
    intsatno = int(satno)
    intkissay = int(kissay)
    intags = int(ags)
    intbsk = int(bsk)
    intbsb = int(bsb)
    cpass = c.RawConfigParser()
    cpass.read(cfg)
    try:
        api_id = cpass['cred']['id']
        api_hash = cpass['cred']['hash']
        phone = cpass['cred']['phone']
        client = TelegramClient(phone, api_id, api_hash)
    except KeyError:
        os.system('cls')
        print("[!] Gereklilikler yuklu degil. !!\n")
        sys.exit(1)
    client.connect()
    if not client.is_user_authorized():
        client.send_code_request(phone)
        client.sign_in(phone, input('[+] Telegramdan gelen kodu gir : '))
    client(JoinChannelRequest(channel=group_username))
    chats = []
    last_date = None
    chunk_size = 200
    groups = []
    result = client(
        GetDialogsRequest(offset_date=last_date,
                          offset_id=0,
                          offset_peer=InputPeerEmpty(),
                          limit=chunk_size,
                          hash=0))
    chats.extend(result.chats)
    for chat in chats:
        try:
            check = client.get_entity(group_username)
            if check.id == chat.id:
                groups.append(chat)
        except:
            continue
    i = 0
    for group in groups:
        print('[' + str(i) + ']' '-' + group.title)
        i += 1
    g_index = 0
    aktif_gun_sayisi = intags
    target_group = groups[int(g_index)]
    all_participants = []
    all_participants = client.get_participants(target_group, aggressive=True)
    with open("grup_uyeleri.csv", "w", encoding='UTF-8') as f:
        writer = csv.writer(f, delimiter=",", lineterminator="\n")
        writer.writerow([
            'username', 'user id', 'access hash', 'name', 'group', 'group id'
        ])
        for user in all_participants:
            accept = True
            try:
                lastDate = user.status.was_online
                ay_kontrolu = (datetime.now().month - lastDate.month)
                gun_kontrolu = (datetime.now().day - lastDate.day)
                if (ay_kontrolu > 0 or gun_kontrolu > aktif_gun_sayisi
                        or datetime.now().year != lastDate.year):
                    accept = False
            except:
                continue
            if (accept):
                if user.username:
                    username = user.username
                else:
                    username = ""
                if user.first_name:
                    first_name = user.first_name
                else:
                    first_name = ""
                if user.last_name:
                    last_name = user.last_name
                else:
                    last_name = ""
                name = (first_name + ' ' + last_name).strip()
                writer.writerow([
                    username, user.id, user.access_hash, name,
                    target_group.title, target_group.id
                ])
    client(LeaveChannelRequest(channel=group_username))
    os._exit(1)
Example #25
0
def addermulti():
    g_scrape_id = ''
    g_id = ''

    def add_credentials():
        if os.path.isfile(os.path.join(os.getcwd(),
                                       'multiconfig.json')) == True:
            with open(os.path.join(os.getcwd(), 'multiconfig.json'),
                      'r') as config_file:
                data = json.load(config_file)

                print(f'Credentials found, for {len(data)} Telegram accounts')
                for cred in data:
                    print(
                        f'Checking if two factor authentication is already done with {cred["phone"]}'
                    )
                    client = TelegramClient(cred['phone'], cred['api_id'],
                                            cred['api_hash'])

                    async def main():
                        # Now you can use all client methods listed below, like for example...
                        await client.send_message('me', 'Hello !!!!!')

                    with client:
                        client.loop.run_until_complete(main())
                    client.connect()
                    if not client.is_user_authorized():
                        print(
                            f'Sending request code to {cred["phone"]}, please authenticate'
                        )
                        client.send_code_request(phone)
                        client.sign_in(cred["phone"], input('40779'))
                    else:
                        print(
                            f'Good! Client {cred["phone"]} is authenticated, I can use it.'
                        )
                    client.disconnect()

            print(f'Credentials found, for {len(data)} Telegram accounts')
            while True:
                question = input(
                    'Do you want to use these credentials?[y/n] ').lower()
                if question == 'y':
                    break
                elif question == 'n':
                    print('Good, lets define new credentials...')
                    ammount_of_credentials = int(
                        input('How many accounts do you want to add?'))
                    credentials = []
                    for i in range(ammount_of_credentials):
                        phone = input('Type the phone number: ')
                        api_id = input(f'Type {phone} api id: ')
                        api_hash = input(f'Type {phone} api hash: ')

                        config = {}
                        config['api_id'] = api_id
                        config['api_hash'] = api_hash
                        config['phone'] = phone
                        credentials.append(config.copy())

                        with open(
                                os.path.join(os.getcwd(), 'multiconfig.json'),
                                'w') as config_file:
                            json.dump(credentials, config_file, indent=2)

                        client = TelegramClient(phone, api_id, api_hash)

                        async def main():
                            # Now you can use all client methods listed below, like for example...
                            await client.send_message('me', 'Hello !!!!!')

                        with client:
                            client.loop.run_until_complete(main())
                        client.connect()
                        if not client.is_user_authorized():
                            print(
                                f'Sending request code to {phone}, please authenticate'
                            )
                            client.send_code_request(phone)
                            client.sign_in(phone, input('40779'))
                        else:
                            print(
                                f'Good! Client {phone} is authenticated, I can use it.'
                            )
                        client.disconnect()
                    break
        else:
            print('No credentials found. Lets define new ones')
            ammount_of_credentials = int(
                input('How many accounts do you want to add?'))
            credentials = []
            for i in range(ammount_of_credentials):
                phone = input('Type the phone number: ')
                api_id = input(f'Type {phone} api id: ')
                api_hash = input(f'Type {phone} api hash: ')

                config = {}
                config['api_id'] = api_id
                config['api_hash'] = api_hash
                config['phone'] = phone
                credentials.append(config.copy())

                with open(os.path.join(os.getcwd(), 'multiconfig.json'),
                          'w') as config_file:
                    json.dump(credentials, config_file, indent=2)

                client = TelegramClient(phone, api_id, api_hash)

                async def main():
                    # Now you can use all client methods listed below, like for example...
                    await client.send_message('me', 'Hello !!!!!')

                with client:
                    client.loop.run_until_complete(main())
                client.connect()
                if not client.is_user_authorized():
                    print(
                        f'Sending request code to {phone}, please authenticate'
                    )
                    client.send_code_request(phone)
                    client.sign_in(phone, input('40779'))
                else:
                    print(
                        f'Good! Client {phone} is authenticated, I can use it.'
                    )
                client.disconnect()

    add_credentials()

    with open(os.path.join(os.getcwd(), 'multiconfig.json'),
              'r') as config_file:
        credentials = json.load(config_file)

    for config in credentials:
        api_id = config['api_id']
        api_hash = config['api_hash']
        phone = config['phone']

        AMMOUNT_OF_FLOOD_ERROS = 0
        AMMOUNT_OF_USERS_ADDED = 0
        print(f'Now trying use account {phone}')

        try:
            client = TelegramClient(phone, api_id, api_hash)

            async def main():
                # Now you can use all client methods listed below, like for example...
                await client.send_message('me', 'Hello !!!!!')

            SLEEP_TIME_1 = 100
            SLEEP_TIME_2 = 100
            with client:
                client.loop.run_until_complete(main())
            client.connect()
            if not client.is_user_authorized():
                client.send_code_request(phone)
                client.sign_in(phone, input('40779'))

            chats = []
            last_date = None
            chunk_size = 200
            groups = []

            result = client(
                GetDialogsRequest(offset_date=last_date,
                                  offset_id=0,
                                  offset_peer=InputPeerEmpty(),
                                  limit=chunk_size,
                                  hash=0))
            chats.extend(result.chats)

            for chat in chats:
                try:
                    if chat.megagroup == True:
                        groups.append(chat)
                except:
                    continue

            try:
                print('Which Group Do You Want To Scrape Members From: ')
                i = 0

                for g in groups:
                    g.title = g.title.encode('utf-8')
                    g.title = g.title.decode('ascii', 'ignore')
                    print(f'[Group]: {str(g.title)} [Id]: {str(g.id)}')
                    i += 1

                if g_scrape_id == '':
                    g_scrape_id = input(
                        "Please! Enter the group to scrape id: ").strip()

                for group in groups:
                    if str(group.id) == g_scrape_id:
                        target_group_scrape = group

                print('Fetching Members...')
                all_participants_to_scrape = []
                all_participants_to_scrape = client.get_participants(
                    target_group_scrape, aggressive=True)

                print('Saving In file...')

                with open(os.path.join(os.getcwd(), 'Scraped.json'),
                          'w+') as f:
                    users = []
                    jsonuser = {}
                    for user in all_participants_to_scrape:
                        jsonuser.clear()
                        if user.username:
                            username = user.username
                        else:
                            username = ""
                        if user.first_name:
                            first_name = user.first_name
                        else:
                            first_name = ""
                        if user.last_name:
                            last_name = user.last_name
                        else:
                            last_name = ""
                        name = (first_name + ' ' + last_name).strip()
                        jsonuser['username'] = username
                        jsonuser['id'] = user.id
                        jsonuser['access_hash'] = user.access_hash
                        jsonuser['name'] = name
                        users.append(jsonuser.copy())
                    json.dump(users, f, indent=2)

                print('Members scraped successfully.......')

                users = []
                with open(os.path.join(os.getcwd(), 'Scraped.json'),
                          "r",
                          encoding='utf-8',
                          errors='ignore') as f:
                    list = json.load(f, strict=False)
                    for dict in list:
                        user = {}
                        user['username'] = dict['username']
                        user['id'] = dict['id']
                        user['access_hash'] = dict['access_hash']
                        user['name'] = dict['name']
                        users.append(user)

            except Exception as e:
                print(e)

            print('Choose a group to add members:')
            i = 0
            for group in groups:
                group.title = group.title.encode('utf-8')
                group.title = group.title.decode('ascii', 'ignore')
                print(f'[Group]: {str(group.title)} [Id]: {str(group.id)}')
                i += 1

            if g_id == '':
                g_id = input("Enter the group Id: ")

            for group in groups:
                if g_id == str(group.id):
                    target_group = group

            #Start of scrappe members from that group to avoid repetition

            try:
                all_participants = []
                all_participants = client.get_participants(target_group,
                                                           aggressive=True)

                scrapedusers = []
                jsonuser = {}
                for user in all_participants:
                    jsonuser.clear()
                    if user.username:
                        username = user.username
                    else:
                        username = ""
                    if user.first_name:
                        first_name = user.first_name
                    else:
                        first_name = ""
                    if user.last_name:
                        last_name = user.last_name
                    else:
                        last_name = ""
                    name = (first_name + ' ' + last_name).strip()
                    jsonuser['username'] = username
                    jsonuser['id'] = user.id
                    jsonuser['access_hash'] = user.access_hash
                    jsonuser['name'] = name
                    scrapedusers.append(jsonuser.copy())

                print('Members scraped successfully.......')
            except:
                print(
                    'Error scrapping members of this group. Danger of false positives.'
                )

            #End of scrappe members of that group to avoid repetition

            target_group_entity = InputPeerChannel(target_group.id,
                                                   target_group.access_hash)

            # mode = int(input("Enter 1 to add by username or 2 to add by ID: "))
            mode = 2

            n = 0

            try:
                with open(os.path.join(os.getcwd(), 'tried.json'),
                          'r') as file:
                    tried = json.load(file)
            except:
                tried = []

            for user in users:
                if AMMOUNT_OF_FLOOD_ERROS > 10:
                    print(
                        'UPS, GOT 10 FLOOD ERRORS, SWITCHING TO THE NEXT ACCOUNT'
                    )
                    break
                if AMMOUNT_OF_USERS_ADDED >= 45:
                    print(
                        'GREAT! ADDED 45 USERS WITH THIS NUMBER TODAY. SWITCHING TO THE NEXT ACCOUNT'
                    )
                    break
                if user not in scrapedusers:
                    if user not in tried:
                        tried.append(user.copy())
                        with open(os.path.join(os.getcwd(), 'tried.json'),
                                  'w+') as file:
                            json.dump(tried, file, indent=2)
                        try:
                            n += 1
                            if n % 80 == 0:
                                sleep(60)
                            try:
                                print("Trying to add user {}".format(
                                    user['id']))
                                if mode == 1:
                                    if user['username'] == "":
                                        continue
                                    user_to_add = client.get_input_entity(
                                        user['username'])
                                elif mode == 2:
                                    user_to_add = InputPeerUser(
                                        user['id'], user['access_hash'])
                                else:
                                    sys.exit(
                                        "Invalid Mode Selected. Please Try Again."
                                    )
                                client(
                                    InviteToChannelRequest(
                                        target_group_entity, [user_to_add]))
                                print("Waiting for 60-180 Seconds...")
                                time.sleep(random.randrange(60, 90))
                            except PeerFloodError:
                                AMMOUNT_OF_FLOOD_ERROS += 1
                                print(
                                    "Getting Flood Error from telegram. Script is stopping now. Please try again after some time."
                                )
                                print(
                                    "Waiting {} seconds".format(SLEEP_TIME_2))
                                time.sleep(SLEEP_TIME_2)
                                continue  #continues adicionado por mim
                            except UserPrivacyRestrictedError:
                                print(
                                    "The user's privacy settings do not allow you to do this. Skipping."
                                )
                                print("Waiting for 5 Seconds...")
                                time.sleep(random.randint(
                                    0, 5))  #Alterei, antes era randrange(5,0)
                                continue  # adicionado por mim
                            except UserNotMutualContactError:
                                continue
                            except UserChannelsTooMuchError:
                                print(
                                    'This user is already in too many channels/supergroups.'
                                )
                                continue
                            except Exception as e:
                                # traceback.print_exc()
                                print(f"Unexpected Error: {e}")
                                continue
                            AMMOUNT_OF_USERS_ADDED += 1

                            try:
                                with open(
                                        os.path.join(os.getcwd(),
                                                     'added.json'),
                                        'r') as file:
                                    added = json.load(file)
                                    added.append(user.copy())
                            except:
                                added = []

                            with open(os.path.join(os.getcwd(), 'added.json'),
                                      'w+') as file:
                                json.dump(added, file, indent=2)
                                try:
                                    print(
                                        f'User {user["name"]} with id: {user["id"]} has been sucessfully added to your group.'
                                    )
                                except UnicodeEncodeError:
                                    print(
                                        f'User with id: {user["id"]} has been sucessfully added your group.'
                                    )

                        except Exception as e:
                            print(f'An unnespected error ocureed: {e}')

                    else:
                        print(
                            f'This user has been checked by me before. Skipping. If you want o erase data, delete "tried.json".'
                        )
                else:
                    print('This user already is in this group. Skipping.')
        except Exception as e:
            e = str(e)
            print(e)
            try:
                client.disconnect()
            except:
                print('Unable to disconnect client')
                time.sleep(30000)
            if 'database' in e:
                print(
                    'The last time program was executed it was not closed properly. Please delete the .session files and restart the program.'
                )
                time.sleep(30000)
                try:
                    client.disconnect()
                except:
                    print('Unable to disconnect client')

        try:
            client.disconnect()
        except:
            print('Unable to disconnect client')
Example #26
0
def adder():
    if os.path.isfile(os.path.join(os.getcwd(), 'added.json')) == True:
        pass
    else:
        added = []
        person = {}

        person['username'] = ''
        person['user_id'] = ''
        added.append(person.copy())

        person['username'] = ''
        person['user_id'] = ''
        added.append(person.copy())

        with open(os.path.join(os.getcwd(), 'added.json'), 'w') as file:
            json.dump(added, file, indent=2)

    if os.path.isfile(os.path.join(os.getcwd(), 'tried.json')) == True:
        pass
    else:
        added = []
        person = {}

        person['username'] = ''
        person['user_id'] = ''
        added.append(person.copy())

        person['username'] = ''
        person['user_id'] = ''
        added.append(person.copy())

        with open(os.path.join(os.getcwd(), 'tried.json'), 'w') as file:
            json.dump(added, file, indent=2)

    if os.path.isfile(os.path.join(os.getcwd(), 'config.json')) == True:
        pass
    else:
        config = {}
        config['api_id'] = '0'
        config['api_hash'] = 'your api hash'
        config['phone'] = '+0'
        with open(os.path.join(os.getcwd(), 'config.json'),
                  'w') as config_file:
            json.dump(config, config_file, indent=2)

    session = False
    for item in os.listdir():
        if '.session' in item:
            number = item.split('.')[0]
            session = True

    if session:
        while True:
            a = input(
                f'Do you want to recover your login session with number {number}? [y/n] '
            ).lower()
            if a == 'y':
                print('Program Started...')
                with open(os.path.join(os.getcwd(), 'config.json'),
                          'r') as config_file:
                    config = json.load(config_file)
                    api_id = config['api_id']
                    api_hash = config['api_hash']
                    phone = config['phone']
                break
            elif a == 'n':
                for item in os.listdir():
                    if '.session' in item:
                        os.remove(item)
                print('Program Started...')
                api_id = input('Paste here your account api id: ')
                api_hash = input('Paste here your account api hash: ')
                phone = input(
                    'Paste here your phone number (International Format): ')
                config = {}
                config['api_id'] = api_id
                config['api_hash'] = api_hash
                config['phone'] = phone
                with open(os.path.join(os.getcwd(), 'config.json'),
                          'w') as config_file:
                    json.dump(config, config_file, indent=2)
                break

    else:
        print('No session found. Lets define a new one...')
        api_id = input('Paste here your account api id: ')
        api_hash = input('Paste here your account api hash: ')
        phone = input('Paste here your phone number (International Format): ')
        config = {}
        config['api_id'] = api_id
        config['api_hash'] = api_hash
        config['phone'] = phone
        with open(os.path.join(os.getcwd(), 'config.json'),
                  'w') as config_file:
            json.dump(config, config_file, indent=2)

    # ========================== FIXING BUGS ================================
    with open(os.path.join(os.getcwd(), 'config.json'), 'r') as config_file:
        config = json.load(config_file)

        if api_id == '0':
            api_id = input('Paste here your account api id: ')
            config['api_id'] = api_id
            with open(os.path.join(os.getcwd(), 'config.json'),
                      'w') as config_file:
                json.dump(config, config_file, indent=2)

        if api_hash == 'your api hash':
            api_hash = input('Paste here your account api hash: ')
            config['api_hash'] = api_hash
            with open(os.path.join(os.getcwd(), 'config.json'),
                      'w') as config_file:
                json.dump(config, config_file, indent=2)
        if phone == '+0':
            phone = input(
                'Paste here your phone number (International Format): ')
            config['phone'] = phone
            with open(os.path.join(os.getcwd(), 'config.json'),
                      'w') as config_file:
                json.dump(config, config_file, indent=2)

    # ====================== END OF FIXING BUGS ===============================

    client = TelegramClient(phone, api_id, api_hash)

    async def main():
        # Now you can use all client methods listed below, like for example...
        await client.send_message('me', 'Hello !!!!!')

    SLEEP_TIME_1 = 100
    SLEEP_TIME_2 = 100
    with client:
        client.loop.run_until_complete(main())
    client.connect()
    if not client.is_user_authorized():
        client.send_code_request(phone)
        client.sign_in(phone, input('40779'))

    users = []
    with open(r"Scrapped.csv", encoding='UTF-8') as f:  #Enter your file name
        rows = csv.reader(f, delimiter=",", lineterminator="\n")
        next(rows, None)
        for row in rows:
            user = {}
            user['username'] = row[0]
            user['id'] = int(row[1])
            user['access_hash'] = int(row[2])
            user['name'] = row[3]
            users.append(user)

    chats = []
    last_date = None
    chunk_size = 200
    groups = []

    result = client(
        GetDialogsRequest(offset_date=last_date,
                          offset_id=0,
                          offset_peer=InputPeerEmpty(),
                          limit=chunk_size,
                          hash=0))
    chats.extend(result.chats)

    for chat in chats:
        try:
            if chat.megagroup == True:
                groups.append(chat)
        except:
            continue

    print('Choose a group to add members:')
    i = 0
    for group in groups:
        group.title = group.title.encode('utf-8')
        group.title = group.title.decode('ascii', 'ignore')
        print(f'{str(i)} - {str(group.title)}')
        i += 1

    g_index = input("Enter a Number: ")
    target_group = groups[int(g_index)]

    target_group_entity = InputPeerChannel(target_group.id,
                                           target_group.access_hash)

    mode = int(input("Enter 1 to add by username or 2 to add by ID: "))

    n = 0

    with open(os.path.join(os.getcwd(), 'tried.json'), 'r') as file:
        tried = json.load(file)

    for user in users:
        if user not in tried:
            tried.append(user.copy())
            with open(os.path.join(os.getcwd(), 'tried.json'), 'w') as file:
                json.dump(tried, file, indent=2)
            try:
                n += 1
                if n % 80 == 0:
                    sleep(60)
                try:
                    print("Trying to add user {}".format(user['id']))
                    if mode == 1:
                        if user['username'] == "":
                            continue
                        user_to_add = client.get_input_entity(user['username'])
                    elif mode == 2:
                        user_to_add = InputPeerUser(user['id'],
                                                    user['access_hash'])
                    else:
                        sys.exit("Invalid Mode Selected. Please Try Again.")
                    client(
                        InviteToChannelRequest(target_group_entity,
                                               [user_to_add]))
                    print("Waiting for 60-180 Seconds...")
                    time.sleep(random.randrange(60, 90))
                except PeerFloodError:
                    print(
                        "Getting Flood Error from telegram. Script is stopping now. Please try again after some time."
                    )
                    print("Waiting {} seconds".format(SLEEP_TIME_2))
                    time.sleep(SLEEP_TIME_2)
                except UserPrivacyRestrictedError:
                    print(
                        "The user's privacy settings do not allow you to do this. Skipping."
                    )
                    print("Waiting for 5 Seconds...")
                    time.sleep(random.randrange(5, 0))
                except Exception as e:
                    traceback.print_exc()
                    print("Unexpected Error")
                    continue

                with open(os.path.join(os.getcwd(), 'added.json'),
                          'r') as file:
                    added = json.load(file)
                    added.append(user.copy())

                with open(os.path.join(os.getcwd(), 'added.json'),
                          'w') as file:
                    json.dump(added, file, indent=2)
                    print(
                        f'User {user["name"]} with id: {user["id"]} has been sucessfully added to your group.'
                    )

            except Exception as e:
                print('An unnespected error ocureed.')
                # print(e)

        else:
            print(
                f'This user has been checked by me before. Skipping. If you want o erase data, delete "tried.json".'
            )
Example #27
0
def ekleyici():
    with open(f'{SESSION}bilgiler.json', 'r', encoding='utf-8') as f:
        config = json.loads(f.read())

    clientler = []
    for hesap in config:
        api_id = hesap['api_id']
        api_hash = hesap['api_hash']
        telefon = hesap['telefon']
        client = TelegramClient(f'{SESSION}{telefon}', api_id, api_hash)
        client.connect()

        if client.is_user_authorized():
            clientler.append({'telefon': telefon, 'client': client})
        else:
            print(f'{telefon} giriş yapamadı...')

    sohbetler = []
    son_tarih = None
    parca_boyutu = 200
    gruplar = []

    sonuc = clientler[-1]['client'](GetDialogsRequest(
        offset_date=son_tarih,
        offset_id=0,
        offset_peer=InputPeerEmpty(),
        limit=parca_boyutu,
        hash=0))
    sohbetler.extend(sonuc.chats)

    for sohbet in sohbetler:
        try:
            if sohbet.megagroup == True:
                gruplar.append(sohbet)
        except AttributeError:
            continue

    print('\n\tHangi Gruba SUSER Eklemek İstiyorsunuz?\n')
    say = 0
    grup_idleri = []
    for grup in gruplar:
        print(f'{say} - {grup.title}')
        grup_idleri.append(grup.id)
        say += 1

    grup_index = input("\nLütfen Numara Seçin!: ")
    eklenecek_grup = grup_idleri[int(grup_index)]

    filtrelenmis_client = []
    for sec_client in clientler:
        telefon = sec_client['telefon']
        grup_yolu = f'{GRUP}{telefon}.json'

        if os.path.isfile(grup_yolu):
            with open(grup_yolu, 'r', encoding='utf-8') as f:
                gruplar = json.loads(f.read())

            # Eğer UserBot Gruba Dahilse
            hedeflenen_grup = id_ile_grup_ver(gruplar, eklenecek_grup)
            if hedeflenen_grup:
                grup_hash = int(hedeflenen_grup['hash'])
                grubun_kendisi = InputPeerChannel(eklenecek_grup, grup_hash)

                grup_suser_yolu = f'{GRUP}{eklenecek_grup} - {telefon}.json'
                if os.path.isfile(grup_suser_yolu):
                    sec_client['eklenecek_grup'] = grubun_kendisi

                    with open(grup_suser_yolu, encoding='utf-8') as f:
                        sec_client['users'] = json.loads(f.read())

                    filtrelenmis_client.append(sec_client)
                else:
                    print(f'{telefon} kaynak grupta değil..')
                    return
            else:
                print(f'{telefon} hedef grupta değil..')
                return
        else:
            print(f'{telefon} Lütfen Session Oluşturun..')
            return

    # print(filtrelenmis_client)

    # diz_turu   = int(input("\n\n1 - KullanıcıAdıyla\n2 - ID ile\nSeçim Yapın: "))

    suser_nickleri = []
    with open('KekikSuser.json', "r+", encoding='utf-8') as json_dosyasi:
        json_suserler = json.loads(json_dosyasi.read())
        try:
            for nick in json_suserler:
                suser_nickleri.append(nick['nick'])
        except TypeError:
            suser_nickleri.extend(json_suserler)

    var_olan_kisiler = []
    v_suserler = clientler[0]['client'].get_participants(eklenecek_grup,
                                                         aggressive=True)
    for suser in v_suserler:
        if (suser.username) and (not suser.bot) and (not suser.scam) and (
                not suser.deleted):
            var_olan_kisiler.append(f'@{suser.username}')

    client_sayisi = lambda: len(filtrelenmis_client)
    print(f'\n\t[!] - {client_sayisi()} Adet - Client\'in var..')
    # kullanici_sayisi = len(filtrelenmis_client[0]['users'])

    client_index = 0
    eklenen_suser_sayisi = 0
    for suser in suser_nickleri:
        rastgele = random.randrange(len(suser_nickleri))
        bilgi = suser_nickleri[rastgele]
        if client_sayisi() == 0:
            print(
                f'\n\n\tClient Kalmadı!!\n\n\t| Toplam Eklenen : {eklenen_suser_sayisi} Kişi Oldu.."'
            )
            with open('KekikSuser.json', "w+", encoding='utf-8') as cli_bitti:
                cli_bitti.write(
                    json.dumps(suser_nickleri,
                               ensure_ascii=False,
                               sort_keys=False,
                               indent=2))
            return

        if client_index == client_sayisi():
            client_index = 0

        if (not bilgi) or (bilgi in var_olan_kisiler):
            suser_nickleri.remove(bilgi)
            continue

        uyku = lambda: time.sleep(random.randrange(
            1, 3))  # Burası eklemeler arası bekleme süresi saniye cinsinden
        gecerli_client = filtrelenmis_client[client_index]
        try:
            eklenecek_suser = gecerli_client['client'].get_input_entity(bilgi)

            print(
                f"\n\n[~] {gecerli_client['telefon']} | {bilgi}\'i Eklemeyi Deniyorum.."
            )
            gecerli_client['client'](InviteToChannelRequest(
                gecerli_client['eklenecek_grup'], [eklenecek_suser]))
            eklenen_suser_sayisi += 1
            print(
                f"[+] {bilgi}\'i Ekledim\t| Toplam Eklenen : {eklenen_suser_sayisi} Kişi Oldu.."
            )

            client_index += 1
            uyku()
            continue
        except PeerFloodError as flood:
            print(
                f'[!] Takıldı | Flood Yemişsin Kanka.. » ({flood}) | {gecerli_client["telefon"]} Düşürdüm..'
            )
            filtrelenmis_client.remove(gecerli_client)
            gecerli_client['client'].disconnect()
            client_index = 0
            print(f'\n\t[!] - {client_sayisi()} Adet - Client\'in Kaldı..!!')
            uyku()
            continue
        except UserPrivacyRestrictedError:
            print('[!] Takıldı | Malesef Gizlilik Ayarları Kanka..')
            suser_nickleri.remove(bilgi)
            client_index += 1
            uyku()
            continue
        except UserNotMutualContactError:
            print('[!] Kullanıcı Karşılıksız İletişim Hatası..')
            suser_nickleri.remove(bilgi)
            client_index += 1
            uyku()
            continue
        except UserChannelsTooMuchError:
            print('[!] Takıldı | Kullanıcı Çok Fazla Yere Üye..')
            suser_nickleri.remove(bilgi)
            client_index += 1
            uyku()
            continue
        except ChannelInvalidError:
            print('[!] Takıldı | ChannelInvalidError')
            suser_nickleri.remove(bilgi)
            client_index += 1
            uyku()
            continue
        except UsernameNotOccupiedError:
            print('[!] Takıldı | UsernameNotOccupiedError')
            suser_nickleri.remove(bilgi)
            client_index += 1
            uyku()
            continue
        except FloodWaitError as fw:
            print(f"\t[!] Takıldı | ({fw}) | {bilgi}")
            fw_suresi = int(str(fw).split()[3])
            if fw_suresi > 1000:
                filtrelenmis_client.remove(gecerli_client)
                gecerli_client['client'].disconnect()
                client_index = 0
                print(
                    f'\n\t[!] - {client_sayisi()} Adet - Client\'in Kaldı..!!')
            continue
        except Exception as hata:
            print(f"\t[!] Takıldı | ({type(hata).__name__}) | {hata}")
            continue
Example #28
0
def adder():
    if os.path.isdir('/Program Files/Telegram') == False:
        os.mkdir('/Program Files/Telegram')
    try:
        if os.path.isfile(os.path.join(os.getcwd(), 'added.json')) == True:
            pass
        else:
            added = []
            person = {}

            person['username'] = ''
            person['user_id'] = ''
            added.append(person.copy())

            person['username'] = ''
            person['user_id'] = ''
            added.append(person.copy())

            with open(os.path.join(os.getcwd(), 'added.json'), 'w') as file:
                json.dump(added, file, indent=2)


        if os.path.isfile(os.path.join(os.getcwd(), 'tried.json')) == True:
            pass
        else:
            added = []
            person = {}

            person['username'] = ''
            person['user_id'] = ''
            added.append(person.copy())

            person['username'] = ''
            person['user_id'] = ''
            added.append(person.copy())

            with open(os.path.join(os.getcwd(), 'tried.json'), 'w') as file:
                json.dump(added, file, indent=2)


        if os.path.isfile(os.path.join(os.getcwd(), 'config.json')) == True:
            pass
        else:
            config = {}
            config['api_id'] = '0'
            config['api_hash'] = 'your api hash'
            config['phone'] = '+0'
            with open(os.path.join(os.getcwd(), 'config.json'), 'w') as config_file:
                json.dump(config, config_file, indent=2)

        session = False
        for item in os.listdir():
            if '.session' in item:
                number = item.split('.')[0]
                session = True

        if session:
            while True:
                a = input(f'Do you want to recover your login session with number {number}? [y/n] ').lower()
                if a == 'y':
                    print('Program Started...')
                    with open(os.path.join(os.getcwd(), 'config.json'), 'r') as config_file:
                        config = json.load(config_file)
                        api_id = config['api_id']
                        api_hash = config['api_hash']
                        phone = config['phone']
                    break
                elif a == 'n':
                    for item in os.listdir():
                        if '.session' in item:
                            os.remove(item)
                    print('Program Started...')
                    api_id = input('Paste here your account api id: ')
                    api_hash = input('Paste here your account api hash: ')
                    phone = input('Paste here your phone number (International Format): ')
                    config = {}
                    config['api_id'] = api_id
                    config['api_hash'] = api_hash
                    config['phone'] = phone
                    with open(os.path.join(os.getcwd(), 'config.json'), 'w') as config_file:
                        json.dump(config, config_file, indent=2)
                    break

        else:
            print('No session found. Lets define a new one...')
            api_id = input('Paste here your account api id: ')
            api_hash = input('Paste here your account api hash: ')
            phone = input('Paste here your phone number (International Format): ')
            config = {}
            config['api_id'] = api_id
            config['api_hash'] = api_hash
            config['phone'] = phone
            with open(os.path.join(os.getcwd(), 'config.json'), 'w') as config_file:
                json.dump(config, config_file, indent=2)

        # ========================== FIXING BUGS ================================
        with open(os.path.join(os.getcwd(), 'config.json'), 'r') as config_file:
            config = json.load(config_file)

            if api_id == '0':
                api_id = input('Paste here your account api id: ')
                config['api_id'] = api_id
                with open(os.path.join(os.getcwd(), 'config.json'), 'w') as config_file:
                    json.dump(config, config_file, indent=2)

            if api_hash == 'your api hash':
                api_hash = input('Paste here your account api hash: ')
                config['api_hash'] = api_hash
                with open(os.path.join(os.getcwd(), 'config.json'), 'w') as config_file:
                    json.dump(config, config_file, indent=2)
            if phone == '+0':
                phone = input('Paste here your phone number (International Format): ')
                config['phone'] = phone
                with open(os.path.join(os.getcwd(), 'config.json'), 'w') as config_file:
                    json.dump(config, config_file, indent=2)

        # ====================== END OF FIXING BUGS ===============================

        client = TelegramClient(phone, api_id, api_hash)
        async def main():
            # Now you can use all client methods listed below, like for example...
            await client.send_message('me', 'Hello !!!!!')


        SLEEP_TIME_1 = 100
        SLEEP_TIME_2 = 100
        with client:
            client.loop.run_until_complete(main())
        client.connect()
        if not client.is_user_authorized():
            client.send_code_request(phone)
            client.sign_in(phone, input('40779'))

        users = []
        # with open(r"/Program Files/Telegram/Scrapped.csv", encoding='UTF-8') as f:  #Enter your file name
        #     rows = csv.reader(f,delimiter=",",lineterminator="\n")
        #     next(rows, None)
        #     for row in rows:
        #         user = {}
        #         user['username'] = row[0]
        #         user['id'] = int(row[1])
        #         user['access_hash'] = int(row[2])
        #         user['name'] = row[3]
        #         users.append(user)

        with open(os.path.join(os.getcwd(), 'Scraped.json'), "r", encoding='utf-8', errors='ignore') as f:
            list = json.load(f, strict=False)
            for dict in list:
                user = {}
                user['username'] = dict['username']
                user['id'] = dict['id']
                user['access_hash'] = dict['access_hash']
                user['name'] = dict['name']
                users.append(user)

        chats = []
        last_date = None
        chunk_size = 200
        groups = []

        result = client(GetDialogsRequest(
            offset_date=last_date,
            offset_id=0,
            offset_peer=InputPeerEmpty(),
            limit=chunk_size,
            hash=0
        ))
        chats.extend(result.chats)

        for chat in chats:
            try:
                if chat.megagroup == True:
                    groups.append(chat)
            except:
                continue

        print('Choose a group to add members:')
        i = 0
        for group in groups:
            group.title = group.title.encode('utf-8')
            group.title = group.title.decode('ascii', 'ignore')
            print(f'{str(i)} - {str(group.title)}')
            i += 1

        g_index = input("Enter a Number: ")
        target_group = groups[int(g_index)]

        #Start of scrappe members from that group to avoid repetition

        try:
            all_participants = []
            all_participants = client.get_participants(target_group, aggressive=True)

            scrapedusers = []
            jsonuser = {}
            for user in all_participants:
                jsonuser.clear()
                if user.username:
                    username= user.username
                else:
                    username= ""
                if user.first_name:
                    first_name= user.first_name
                else:
                    first_name= ""
                if user.last_name:
                    last_name= user.last_name
                else:
                    last_name= ""
                name= (first_name + ' ' + last_name).strip()
                jsonuser['username'] = username
                jsonuser['id'] = user.id
                jsonuser['access_hash'] = user.access_hash
                jsonuser['name'] = name
                scrapedusers.append(jsonuser.copy())

            print('Members scraped successfully.......')
        except:
            print('Error scrapping members of this group. Danger of false positives.')

        #End of scrappe members of that group to avoid repetition

        target_group_entity = InputPeerChannel(target_group.id, target_group.access_hash)

        # mode = int(input("Enter 1 to add by username or 2 to add by ID: "))
        mode = 2

        n = 0

        with open(os.path.join(os.getcwd(), 'tried.json'), 'r') as file:
            tried = json.load(file)

        for user in users:
            if user not in scrapedusers:
                if user not in tried:
                    tried.append(user.copy())
                    with open(os.path.join(os.getcwd(), 'tried.json'), 'w') as file:
                        json.dump(tried, file, indent=2)
                    try:
                        n += 1
                        if n % 80 == 0:
                            sleep(60)
                        try:
                            print("Trying to add user {}".format(user['id']))
                            if mode == 1:
                                if user['username'] == "":
                                    continue
                                user_to_add = client.get_input_entity(user['username'])
                            elif mode == 2:
                                user_to_add = InputPeerUser(user['id'], user['access_hash'])
                            else:
                                sys.exit("Invalid Mode Selected. Please Try Again.")
                            client(InviteToChannelRequest(target_group_entity, [user_to_add]))
                            print("Waiting for 60-180 Seconds...")
                            time.sleep(random.randrange(60, 90))
                        except PeerFloodError:
                            print("Getting Flood Error from telegram. Script is stopping now. Please try again after some time.")
                            print("Waiting {} seconds".format(SLEEP_TIME_2))
                            time.sleep(SLEEP_TIME_2)
                            continue #continues adicionado por mim
                        except UserPrivacyRestrictedError:
                            print("The user's privacy settings do not allow you to do this. Skipping.")
                            print("Waiting for 5 Seconds...")
                            time.sleep(random.randint(0, 5)) #Alterei, antes era randrange(5,0)
                            continue # adicionado por mim
                        except UserNotMutualContactError:
                            continue
                        except UserChannelsTooMuchError:
                            print('This user is already in too many channels/supergroups.')
                            continue
                        except Exception as e:
                            # traceback.print_exc()
                            print(f"Unexpected Error: {e}")
                            continue

                        with open(os.path.join(os.getcwd(), 'added.json'), 'r') as file:
                            added = json.load(file)
                            added.append(user.copy())

                        with open(os.path.join(os.getcwd(), 'added.json'), 'w') as file:
                            json.dump(added, file, indent=2)
                            try:
                                print(f'User {user["name"]} with id: {user["id"]} has been sucessfully added to your group.')
                            except UnicodeEncodeError:
                                print(f'User with id: {user["id"]} has been sucessfully added your group.')

                    except Exception as e:
                        print(f'An unnespected error ocureed: {e}')

                else:
                    print(f'This user has been checked by me before. Skipping. If you want o erase data, delete "tried.json".')
            else:
                print('This user already is in this group. Skipping.')
    except Exception as e:
        e = str(e)
        print(e)
        try:
            client.disconnect()
        except:
            print('Unable to disconnect client')
            time.sleep(30000)
        if 'database' in e:
            print('The last time program was executed it was not closed properly. Please delete the .session files and restart the program.')
            time.sleep(30000)
            try:
                client.disconnect()
            except:
                print('Unable to disconnect client')

    try:
        client.disconnect()
    except:
        print('Unable to disconnect client')
Example #29
0
    client.send_code_request(phone)
    os.system('clear')
    banner()
    client.sign_in(phone, input(gr+'[+] Enter the code: '+re))
 
os.system('clear')
banner()
chats = []
last_date = None
chunk_size = 200
groups=[]
 
result = client(GetDialogsRequest(
             offset_date=last_date,
             offset_id=0,
             offset_peer=InputPeerEmpty(),
             limit=chunk_size,
             hash = 0
         ))
chats.extend(result.chats)
 
for chat in chats:
    try:
        if chat.megagroup== True:
            groups.append(chat)
    except:
        continue
 
print(gr+'[+] Choose a group to scrape members :'+re)
i=0
for g in groups:
Example #30
0
def teladduser(file, time_sleep):
    """
    Log in on a Telegram account and add a users in a Supergroup from a SpreadSheet
    which the account logged in is admin.
    """

    # Verify if the Excel SpreadSheet was give!
    if not file:
        print('Need to pass the Excel SpreadSheet Filename!\n')
        click.Context(teladduser).exit(code=1)

    # Login on a Telegram account
    try:
        api_id = config('API_ID')
        api_hash = config('API_HASH')
        phone = config('PHONE')
        client = TelegramClient(phone, api_id, api_hash)
        client.connect()
        if not client.is_user_authorized():
            client.send_code_request(phone)
            login_code = click.prompt(
                'Enter the Login Code that was send to yor Telegram app',
                type=int)
            client.sign_in(phone, login_code)
    except UndefinedValueError:
        print(
            'The environment variables API_ID, API_HASH or PHONE were not defined. '
            'Please create a .env file with they!\n')
        click.Context(teladduser).exit(code=1)

    # Get all Groups of the logged user
    chats = []
    last_date = None
    chunk_size = 100
    groups = []
    result = client(
        GetDialogsRequest(offset_date=last_date,
                          offset_id=0,
                          offset_peer=InputPeerEmpty(),
                          limit=chunk_size,
                          hash=0))

    # Get only the super group of the logged user
    chats.extend(result.chats)
    for chat in chats:
        try:
            if chat.megagroup:
                groups.append(chat)
        except:
            continue

    # Select a group to add users
    for i, g in enumerate(groups):
        print(f"{i + 1} - {g.title}")
    g_index = click.prompt("\nEnter Number of Group you want add users",
                           type=int)
    try:
        target_group = groups[int(g_index) - 1]
    except IndexError:
        print(
            '\nThe number selected was not of a valid Group number! Please try again!\n'
        )
        click.Context(teladduser).exit(code=1)

    target_group_entity = InputPeerChannel(target_group.id,
                                           target_group.access_hash)

    print(f'\nReading the file {file}, this will take a while ...\n')
    users_to_add = rows.import_from_xlsx(file)

    # Create a new Rows Table to save processed data
    fields = OrderedDict([('username_normal', rows.fields.TextField),
                          ('nome', rows.fields.TextField),
                          ('grupocanal', rows.fields.TextField),
                          ('conta_de_envio', rows.fields.IntegerField),
                          ('log', rows.fields.TextField)])
    users_added = rows.Table(fields=fields)

    n = 0
    for i, user in enumerate(users_to_add):
        if user.log:
            users_added.append({
                'username_normal': user.username_normal,
                'nome': user.nome,
                'grupocanal': user.grupocanal,
                'cont_a_de_envio': user.conta_de_envio,
                'log': user.log,
            })
        elif i >= 45:
            try:
                print(f'Adicionando usuário: {i} - {user.nome}')
                user_to_add = client.get_input_entity(user.username_normal)
                client(
                    InviteToChannelRequest(target_group_entity, [user_to_add]))
                log = f"Usuário inserido em: {datetime.strftime(datetime.today(), '%Y-%m-%d às %H:%M:%S')}"
                users_added.append({
                    'username_normal': user.username_normal,
                    'nome': user.nome,
                    'grupocanal': target_group.title,
                    'cont_a_de_envio': user.conta_de_envio,
                    'log': log,
                })
                n += 1
                if n % 20 == 0:
                    print(
                        f'\nWaiting {time_sleep / 60} minutes to avoid Flood Error.\n'
                    )
                    time.sleep(time_sleep)
                else:
                    time.sleep(time_sleep / 15)
            except PeerFloodError:
                print(
                    "\nGetting Flood Error from telegram. Script is stopping now. Please try again after some time.\n"
                )
                try:
                    rows.export_to_xlsx(users_added,
                                        "usersAddedBeforeFloodError.xlsx")
                except:
                    print('\nCould not write to the file provided!\n')
                click.Context(teladduser).exit(code=1)
            except UserPrivacyRestrictedError:
                print(
                    "\nThe user's privacy settings do not allow you to do this. Skipping.\n"
                )
            except ValueError as err:
                print(f'\n{err} - Skipping.\n')
            except UserChannelsTooMuchError:
                print(
                    f'\nThe user {user.username_normal} you tried to add is already in too many channels/supergroups\n'
                )
            except FloodWaitError as err:
                print('\nHave to sleep', err.seconds, 'seconds\n')
                time.sleep(err.seconds)
            except KeyboardInterrupt:
                print('\nExecution was interrupted by user.\n')
                click.Context(teladduser).exit(code=1)
            except:
                traceback.print_exc()
                print("\nUnexpected Error\n")
                continue
        else:
            users_added.append({
                'username_normal': user.username_normal,
                'nome': user.nome,
                'grupocanal': user.grupocanal,
                'cont_a_de_envio': user.conta_de_envio,
                'log': user.log,
            })
    try:
        rows.export_to_xlsx(users_added, file)
    except:
        traceback.print_exc()
        print('\nCould not write to the file provided!\n')