Пример #1
0
            cards.remove(sim)
            time.sleep(2)
            continue

        except (ConnectionError, RpcCallFailError):
            print("Connection Error! skipping sim..")
            continue

        # keeping count how many left
        print(Fore.GREEN +
              "The amount of users left is: {}".format(len(participants) - i))

        # use every sim add 1 user and go to the next
        while True:
            try:
                target_group = client.get_input_entity(
                    PeerChannel(int(TARGET_ID)))  # the group to add to
                user_to_add = client.get_input_entity(
                    participants[i].username)  # the user to add
                client(InviteToChannelRequest(target_group, [user_to_add]))
                print(Fore.GREEN + "Added member {} from sim {}".format(
                    participants[i].id, sim.name))
                time.sleep(5)
                if isFull(client, target_group):
                    print(Fore.BLUE +
                          "TARGET GROUP IS FULL! PULLING OUT SIM CARDS..")
                    client.disconnect()
                    del client
                    JoinOrLeave(False)
                    exit(1)
                client.disconnect()
                del client
Пример #2
0
                    line[2] = members
                    line[3] = topID
                writer.writerow(line)
            offset = lines[-1][0]  # First element of last row in csv
            if offset != 'id':  # Checks if csv is empty apart from header row
                minimum = int(offset)
                offset = minimum + 100

            # If a log file has been created but only has a header row, set minimum to 0
            else:
                offset = 101
                minimum = 0

    # Opens csv file and sets group_entity to be used in GetHistoryRequest
    writer = csv.writer(open(logFile, 'a', encoding='utf-8', newline=''))
    group_entity = client.get_input_entity(username)
    print('\nStarting Group', username, 'at ID:', minimum, 'of', topID)

    # Loop until topID has been reached
    while True:
        # Queries Telegram client to retrieve messages
        # Will start at offset_id, capture up to 100 messages until min_id
        posts = client(
            GetHistoryRequest(peer=group_entity,
                              limit=100,
                              offset_date=None,
                              offset_id=offset,
                              max_id=0,
                              min_id=minimum,
                              add_offset=0,
                              hash=0))
Пример #3
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".'
            )
Пример #4
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')
Пример #5
0
    def send_sms():
        try:
            cpass = configparser.RawConfigParser()
            cpass.read('config.data')
            api_id = cpass['cred']['id']
            api_hash = cpass['cred']['hash']
            phone = cpass['cred']['phone']
        except KeyError:
            os.system('clear')
            main.banner()
            print(re + "[!] run python3 setup.py first !!\n")
            sys.exit(1)

        client = TelegramClient(phone, api_id, api_hash)

        client.connect()
        if not client.is_user_authorized():
            client.send_code_request(phone)
            os.system('clear')
            main.banner()
            client.sign_in(phone, input(gr + '[+] Enter the code: ' + re))

        os.system('clear')
        main.banner()
        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]
                user['id'] = int(row[1])
                user['access_hash'] = int(row[2])
                user['name'] = row[3]
                users.append(user)
        print(gr + "[1] User İD ilə göndər\n[2] İsrifadəçi adı ilə göndər ")
        mode = int(input(gr + "Input : " + re))

        message = input(gr + "[+] Mesajınızı daxil edin : " + re)

        for user in users:
            if mode == 2:
                if user['username'] == "":
                    continue
                receiver = client.get_input_entity(user['username'])
            elif mode == 1:
                receiver = InputPeerUser(user['id'], user['access_hash'])
            else:
                print(re + "[!] Invalid Mode. Exiting.")
                client.disconnect()
                sys.exit()
            try:
                print(gr + "[+] Mesaj göndərilir:", user['name'])
                client.send_message(receiver, message.format(user['name']))
                print(gr + "[+] Gözlənilir {} saniyə".format(SLEEP_TIME))
                time.sleep(SLEEP_TIME)
            except PeerFloodError:
                print(
                    re +
                    "[!] Getting Flood Error from telegram. \n[!] Script is stopping now. \n[!] Please try again after some time."
                )
                client.disconnect()
                sys.exit()
            except Exception as e:
                print(re + "[!] Xəta:", e)
                print(re + "[!] Davam etməyə çalışılır...")
                continue
        client.disconnect()
        print("Tamamlandı! Mesaj bütün istifadəçilərə göndərildi")
Пример #6
0
from telethon.sync import TelegramClient, events
from telethon.tl.types import InputPeerChannel
import asyncio
from decouple import config

# Defining the need variables
api_id = config('API_ID')  #Input your api_id here
api_hash = config('API_HASH')  #Input your api_hash here

loop = asyncio.new_event_loop()
client = TelegramClient('runner', api_id, api_hash, loop=loop)
client.start()

channel = client.get_input_entity('https://t.me/techguided')

chat = InputPeerChannel(
    channel_id=channel.channel_id,
    access_hash=channel.access_hash)  # Input channel id and access_hash

# import pdb; pdb.set_trace()
channel = client.get_entity(1270515419)


# Handler to receive the channel message
@client.on(events.NewMessage(incoming=True))
async def handler(event):
    await client.send_message('codefred', f'{event.stringify()}')


client.add_event_handler(handler)
	print(f"\t[!] channel hash: {channel_hash}")
	print("\t[!] CONFIRM THAT INFO IS CORRECT [!]")

	print("\n[!] starting ...")
	target_group_entity = InputPeerChannel(channel_id,channel_hash)


	mode=1

	for user in users:
	    try:
	        print ("Adding {}".format(user['id']))
	        if mode == 1:
	            if user['id'] == "":
	                continue
	            user_to_add = client.get_input_entity(user['id'])
	        else:
	            sys.exit("Invalid Mode Selected. Please Try Again.")
	        client(InviteToChannelRequest(target_group_entity,[user_to_add]))
	        print("Waiting 20 Seconds...")
	        time.sleep(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
except KeyboardInterrupt:
	sys.exit("\nProgram closed")
Пример #8
0
    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)

mode = int(input("Enter 1 to send by user ID or 2 to send by username: "******"Hello {}, How are you? Did You Join the Latest Telegram trusted channel yet?\n IF Not join it by this link below:\n https://t.me/joinchat/AAAAAEvgO_zy3jhsp-Ba7A"]
for user in users:
    if mode == 2:
        if user['username'] == "":
            continue
        receiver = client.get_input_entity(user['username'])
    elif mode == 1:
        receiver = InputPeerUser(user['id'],user['access_hash'])
    else:
        print("Invalid Mode. Exiting.")
        client.disconnect()
        sys.exit()
    message = random.choice(messages)
    try:
        print("Sending Message to:", user['name'])
        client.send_message(receiver, message.format(user['name']))
        print("Waiting {} seconds".format(SLEEP_TIME))
        time.sleep(SLEEP_TIME)
    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))
Пример #9
0
# print('Choose a group to scrape members from:')
i = 0
for g in groups:
    print(str(i) + '/ ' + g.title)
    print(g)
    i += 1

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

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

print('Fetching Members...')

participants = client.get_participants(target_group, aggressive=True)

for user in participants:
    if not user.is_self:
        print(user)
        user_to_remove.append(client.get_input_entity(user))
        client(
            EditBannedRequest(
                target_group_entity, user,
                ChatBannedRights(
                    until_date=None,
                    view_messages=True,
                )))
Пример #10
0
def parse_1(channels,
            amount_to_parse=180,
            sleep_period=49,
            sleep_time=120,
            update_id=True):
    from config import (API_ID, API_HASH, USERNAME)
    client = TelegramClient(USERNAME, API_ID, API_HASH)
    client.start()
    ''' Ограничение примерно в 500 тг каналов '''
    if channels is None:
        print('None')
        return 0
    con = psycopg2.connect(database="postgres",
                           user="******",
                           password="******",
                           host="127.0.0.1",
                           port="5433")
    cur = con.cursor()
    for i in range(min(amount_to_parse, len(channels))):
        if i % sleep_period == 0 and i != 0:
            time.sleep(sleep_time)
        cur.execute('SELECT name,last_id from TGCHANNELS2 WHERE name = %s',
                    (channels[i], ))
        row = cur.fetchall()
        new_id = last_id = row[0][1]
        limit_to_parse = 100
        if last_id == 0:
            limit_to_parse = 1
        try:
            channel_entity = client.get_input_entity(channels[i])
            post = client(
                GetHistoryRequest(peer=channel_entity,
                                  limit=limit_to_parse,
                                  offset_date=None,
                                  offset_id=0,
                                  max_id=0,
                                  min_id=last_id,
                                  add_offset=0,
                                  hash=0))
            messages = post.messages
            last_message = []
            for message in messages:
                last_message.append(message.to_dict())

            for j in range(len(last_message)):
                jsnfile = last_message[j]
                if jsnfile['message'] == '':
                    break
                insert = """INSERT INTO TEMPDATA (POSTID,CHANNEL,ID,POST) VALUES (%s,%s,%s,%s)"""
                to_insert = (0, channels[i], jsnfile['id'], jsnfile['message'])
                cur.execute(insert, to_insert)
                if jsnfile['id'] > new_id:
                    new_id = jsnfile['id']

            con.commit()

        except (ValueError, KeyError,
                telethon.errors.rpcerrorlist.UsernameNotOccupiedError,
                TypeError, telethon.errors.rpcerrorlist.ChannelPrivateError,
                telethon.errors.rpcerrorlist.UsernameInvalidError):
            pass
        except telethon.errors.rpcerrorlist.FloodWaitError as e:
            print(e)
            break

        if update_id:
            cur.execute('UPDATE TGCHANNELS2 SET last_id = %s WHERE name = %s',
                        (
                            int(new_id),
                            channels[i],
                        ))
            con.commit()

    con.close()
Пример #11
0
    def send_sms():
        try:
            cpass = configparser.RawConfigParser()
            cpass.read('config.data')
            api_id = cpass['cred']['id']
            api_hash = cpass['cred']['hash']
            phone = cpass['cred']['phone']
        except KeyError:
            os.system('clear')
            main.banner()
            print(re + "[!] run python3 setup.py first !!\n")
            sys.exit(1)

        client = TelegramClient(phone, api_id, api_hash)

        client.connect()
        if not client.is_user_authorized():
            client.send_code_request(phone)
            os.system('clear')
            main.banner()
            client.sign_in(phone, input(gr + '[+] Enter the code: ' + re))

        os.system('clear')
        main.banner()
        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]
                user['id'] = int(row[1])
                user['access_hash'] = int(row[2])
                user['name'] = row[3]
                users.append(user)
        print(gr + "[1] send sms by user ID\n[2] send sms by username ")
        mode = int(input(gr + "Input : " + re))

        message = input(gr + "[+] Enter Your Message : " + re)
        n = 0
        for user in users:
            n += 1
            if n % 50 == 0:
                sleep(300)
            try:
                print("Adding {}".format(user['id']))
                if mode == 1:
                    if user['username'] == "":
                        continue
                    receiver = client.get_input_entity(user['username'])
                elif mode == 2:
                    receiver = 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, 180))
            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

        client.disconnect()
        print("Done. Message sent to all users.")
Пример #12
0
api_id = -----

api_hash = '--------'

phone = '+917776808085'

username = '******'

SLEEP_TIME = 30
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: '))
 

user = '******'
 
messages= ["Hello {}, How are you?", "Hi {}, What's up?", "Hey {}, do you want to gotrained?"]

receiver = client.get_input_entity(user)
message = random.choice(messages)

print("Sending Message to:", user)
client.send_message(receiver, message.format(user))

client.disconnect()
print("Done. Message sent ")
Пример #13
0
def autos():

    phone = utils.parse_phone(pphone)

    client = TelegramClient(f"sessions/{phone}", api_id, api_hash)

    client.connect()
    if not client.is_user_authorized():
        print('some thing has changed')
        client.send_code_request(phone)
        client.sign_in(phone, input('Enter the code: '))

    input_file = 'data.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]
            user['id'] = int(row[2])
        #user['access_hash'] = int(row[2])
            user['name'] = row[3]
            users.append(user)

    with open('memory.csv', 'r') as hash_obj:
        csv_reader = reader(hash_obj)
        list_of_rows = list(csv_reader)
        row_number = 1
        col_number = 2
        numnext = list_of_rows[row_number - 1][col_number - 1]

    startfrom = int(numnext)
    nextstart = startfrom+50

    with open('memory.csv', 'r') as hash_obj:
        csv_reader = reader(hash_obj)
        list_of_rows = list(csv_reader)
        row_number = 1
        col_number = 3
        numend = list_of_rows[row_number - 1][col_number - 1]

    endto = int(numend)
    nextend = endto+50

    # Enter your file name.
    with open("memory.csv", "w", encoding='UTF-8') as df:
        writer = csv.writer(df, delimiter=",", lineterminator="\n")
        writer.writerow([nextdelta, nextstart, nextend])
    print("Next")
    j = 0
    for user in users:

        if (int(startfrom) <= int(user['srno'])) and (int(user['srno']) <= int(endto)):
            try:
                j += 1
                status = 'delta'
                receiver = client.get_input_entity(user['username'])
                if user['username'] == "":
                    print("no username, moving to next")
                    continue

                client.send_message(receiver, str(deltamessage))
                status = 'DONE'

                #print("Waiting for 60-180 Seconds...")
                time.sleep(random.randrange(1, 3))

            except UserPrivacyRestrictedError:
                status = 'PrivacyRestrictedError'

            except UserAlreadyParticipantError:
                status = 'ALREADY'

            except PeerFloodError as g:
                status = 'PeerFloodError :('
            except FloodWaitError as t:
                stime = t.seconds
                print(f"wait {stime} seconds")
                time.sleep(stime)
            except errors.RPCError as e:
                status = e.__class__.__name__

            except:
                traceback.print_exc()
                print("Unexpected Error")
                continue
            print(f"SENDING TO {user['name']} TOTAL: {j} - {status}")
        elif int(user['srno']) > int(endto):
            print("Message sended Successfully!")
            stat = input(
                'Done!\nChoose From Below:\n\n1 - Repeat The Script\nOR Just Hit Enter To Quit\n\nEnter: ')
            if stat == '1':
                autos()
            else:
                quit()
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
Пример #15
0
    def send_sms():
        try:
            cpass = configparser.RawConfigParser()
            cpass.read('config.data')
            api_id = cpass['cre']['id']
            api_hash = cpass['cre']['hash']
            phone = cpass['cre']['phone']
        except KeyError:
            os.system('clear')
            main.banner()
            print(red + "[!] Execute: python3 setup.py antes.\n")
            sys.exit(1)

        client = TelegramClient(phone, api_id, api_hash)

        client.connect()
        if not client.is_user_authorized():
            client.send_code_request(phone)
            os.system('clear')
            main.banner()
            client.sign_in(
                phone, input(green + '[+] Insira o código recebido: ' + red))

        os.system('clear')
        main.banner()
        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]
                user['id'] = int(row[1])
                user['access_hash'] = int(row[2])
                user['name'] = row[3]
                users.append(user)
        print(
            green +
            "[1] Enviar SMS por ID de usuário\n[2] Enviar SMS por NOME de usuário"
        )
        mode = int(input(green + "[+] Opção: " + red))

        message = input(green + "[+] Insira uma mensagem: " + red)

        for user in users:
            if mode == 2:
                if user['username'] == "":
                    continue
                receiver = client.get_input_entity(user['username'])
            elif mode == 1:
                receiver = InputPeerUser(user['id'], user['access_hash'])
            else:
                print(red + "[!] Modo inválido, saindo!")
                client.disconnect()
                sys.exit()
            try:
                print(green + "[+] Enviando mensagem para:", user['name'])
                client.send_message(receiver, message.format(user['name']))
                print(green + "[+] O intervalo de envio e de 5 segundos")
                time.sleep(random.randrange(1, 5))
            except PeerFloodError:
                print(
                    red +
                    "[!] Erro de flod do telegram. \n[!] Script parando. \n[!] Tente novamente mais tarde."
                )
                client.disconnect()
                sys.exit()
            except Exception as e:
                print(red + "[!] Erro:", e)
                print(red + "[!] Tentando continuar...")
                continue
        client.disconnect()
        print(green + "[!] Mensagem enviada a todos os usuários.")
Пример #16
0
    def send_sms():
        try:
            cpass = configparser.RawConfigParser()
            cpass.read('config.data')
            api_id = cpass['cred']['id']
            api_hash = cpass['cred']['hash']
            phone = cpass['cred']['phone']
        except KeyError:
            os.system('clear')
            main.banner()
            print(re+"[!] run python3 setup.py first !!\n")
            sys.exit(1)

        client = TelegramClient(phone, api_id, api_hash)
         
        client.connect()
        if not client.is_user_authorized():
            client.send_code_request(phone)
            os.system('clear')
            main.banner()
            client.sign_in(phone, input(gr+'[+] Enter the code: '+re))
        
        os.system('clear')
        main.banner()
        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]
                user['id'] = int(row[1])
                user['access_hash'] = int(row[2])
                user['name'] = row[3]
                users.append(user)
        print(gr+"[1] send sms by user ID\n[2] send sms by username ")
        mode = int(input(gr+"Input : "+re))
         
        message = input(gr+"[+] Enter Your Message : "+re)
         
        for user in users:
            if mode == 2:
                if user['username'] == "":
                    continue
                receiver = client.get_input_entity(user['username'])
            elif mode == 1:
                receiver = InputPeerUser(user['id'],user['access_hash'])
            else:
                print(re+"[!] Invalid Mode. Exiting.")
                client.disconnect()
                sys.exit()
            try:
                print(gr+"[+] Sending Message to:", user['name'])
                client.send_message(receiver, message.format(user['name']))
                print(gr+"[+] Waiting {} seconds".format(SLEEP_TIME))
                time.sleep(SLEEP_TIME)
            except PeerFloodError:
                print(re+"[!] Getting Flood Error from telegram. \n[!] Script is stopping now. \n[!] Please try again after some time.")
                client.disconnect()
                sys.exit()
            except Exception as e:
                print(re+"[!] Error:", e)
                print(re+"[!] Trying to continue...")
                continue
        client.disconnect()
        print("Done. Message sent to all users.")
Пример #17
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()
Пример #18
0
                                       target_group.access_hash)

print(gr + "[1] add member by user ID\n[2] add member by username ")
mode = int(input(gr + "Input : " + re))
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(re + "[!] Invalid Mode Selected. Please Try Again.")
            client(InviteToChannelRequest(target_group_entity, [user_to_add]))
            print(gr + "[+] Waiting for 60-180 Seconds...")
            time.sleep(random.randrange(60, 180))
        except PeerFloodError:
            print(
                re +
                "[!] Getting Flood Error from telegram. \n[!] Script is stopping now. \n[!] Please try again after some time."
            )
        except UserPrivacyRestrictedError:
            print(
                re +
Пример #19
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')