Exemple #1
0
    def create_new_contact(self, phone, first_name, last_name=None):
        contactModel = None
        inputContact = InputPhoneContact(
            0, phone, first_name, '' if last_name is None else last_name)
        result = self.invoke(ImportContactsRequest([inputContact], True))
        logging.debug(result)
        if type(result) is ImportedContacts and len(result.users) > 0:
            # logging.info('New contact added: {}'.format(str(len(result.users))))
            for user in result.users:
                if type(user) is User:
                    # do second check here
                    user_phone_norm = phone_norm(user.phone)
                    contactModel = self.create_tl_contact(
                        user_phone_norm,
                        user.first_name,
                        user.access_hash,
                        user.id,
                        last_name=user.last_name,
                        username=user.username)

                    if contactModel is None:
                        # check contact exist, but fetch is error
                        # or error on save()
                        logging.error('Failed adding contact...{} - {}'.format(
                            self.user_phone, user_phone_norm))
        return contactModel
    def write_telegram(self, match: Match, offset: int):
        telegram = json.loads(
            TinderDb.get_match_tgs(match_id=match.match_id))[offset]
        asyncio.set_event_loop(self.loop)

        messages = MessageProvider.messages_for_telegram()

        if TextAnalyzer.try_parse_login(strings=[telegram]):
            receiver = f"@{telegram}"

            for message in messages:
                try:
                    self.client.send_message(receiver, message)
                    time.sleep(2)
                except ValueError as e:
                    print(e.args)

        elif TextAnalyzer.try_parse_phone(telegram):
            contact = InputPhoneContact(
                client_id=0,  # For new contacts use client_id = 0
                phone=f"+7{telegram}",
                first_name=f"{match.name} {match.age}",
                last_name='Tinder')

            c = self.client(ImportContactsRequest([contact]))
            if c.users:
                for message in messages:
                    self.client.send_message(c.users[0], message)
Exemple #3
0
def contact_add():
    log.debug('{}'.format(request.form))

    first_name = request.form['first_name']
    last_name = request.form['last_name']
    phone_number = request.form['phone_number']

    if request.form['contactChange'] == '1':
        action = 'изменен'
    else:
        action = 'добавлен'

    log.info('Adding user {}_{} {}'.format(first_name, last_name,
                                           phone_number))

    input_contact = InputPhoneContact(0, phone_number, first_name, last_name)
    contact = client(ImportContactsRequest([input_contact]))
    if contact.users:
        errormsg = ''
        log.debug('Contacts found: {}'.format(contact))
        for user in contact.users:
            errormsg += 'Контакт {}_{} ({}) успешно {}'.format(
                user.first_name, user.last_name, user.phone, action)
            session['error'] = errormsg
    else:
        log.debug('Contacts not found: {}'.format(input_contact))
        session['error'] = 'Пользователь {} не найден.'.format(phone_number)

    return redirect(url_for('contacts.contact_list'))
def get_names(phone_number):
    try:
        contact = InputPhoneContact(client_id=0,
                                    phone=phone_number,
                                    first_name="",
                                    last_name="")
        contacts = client(functions.contacts.ImportContactsRequest([contact]))
        username = contacts.to_dict()['users'][0]['username']
        if not username:
            print(
                "*" * 5 +
                f' Response detected, but no user name returned by the API for the number: {phone_number} '
                + "*" * 5)
            del_usr = client(
                functions.contacts.DeleteContactsRequest(id=[username]))
            return
        else:
            del_usr = client(
                functions.contacts.DeleteContactsRequest(id=[username]))
            return username
    except IndexError as e:
        return f'ERROR: there was no response for the phone number: {phone_number}'
    except TypeError as e:
        return f"TypeError: {e}. --> The error might have occured due to the inability to delete the {phone_number} from the contact list."
    except:
        raise
Exemple #5
0
def get_telegram_contact_info(contact_phone_number):
    try:
        contact = InputPhoneContact(client_id=92,
                                    phone=contact_phone_number,
                                    first_name="",
                                    last_name="")
        result = client(ImportContactsRequest([contact]))
        res = []
        contact_info = client.get_entity(contact_phone_number)
        res.append(contact_info.phone)
        res.append(contact_info.id)
        res.append(contact_info.username)
        res.append(contact_info.first_name)
        res.append(contact_info.last_name)
        res.append(client.download_profile_photo(contact_info.id))
        try:
            res.append(
                contact_info.status.was_online.astimezone(
                    pytz.timezone('Europe/Kiev')))
        except:
            res.append("None")
        return res
    except Exception as err:
        print(err)
        print('Cannot find any entity corresponding to "{}"'.format(
            contact_phone_number))
        pass
Exemple #6
0
    def detect_numbers(self, phone_numbers):
        self.authenticate()
        with TelegramClient('detect', self.api_ID, self.api_hash) as client:
            input_contact_list = []
            for phone_number in phone_numbers:
                input_contact_list.append(
                    InputPhoneContact(
                        client_id=0,
                        phone=phone_number.get_phone_number(),
                        first_name=phone_number.get_phone_number(),
                        last_name=phone_number.get_phone_number()))
            client(ImportContactsRequest(input_contact_list))
            for phone_number in phone_numbers:
                try:
                    contact = client.get_input_entity(
                        phone_number.get_phone_number())
                    # If the user's id is not 0 then the user has an account in Telegram
                    phone_number.set_app_state(
                        self.get_name(), AppUsageEnum.USAGE
                        if contact.user_id > 0 else AppUsageEnum.NO_USAGE)

                except ValueError as e:

                    # TODO Use an error logger
                    if "Cannot find any entity corresponding to" in str(e):
                        # If this error happens that means the API call was successfully, but the phone number does
                        # not have Telegram
                        phone_number.set_app_state(self.get_name(),
                                                   AppUsageEnum.NO_USAGE)
                    else:
                        print(e)
                        phone_number.set_app_state(self.get_name(),
                                                   AppUsageEnum.ERROR)
        return phone_numbers
Exemple #7
0
async def add_user(user, links):
    """
        Adds the specified user to the telegram channel of the specified region.
        First adds the user as a contact; this gives permission to add them to
        a channel.

        TODO: remove the user from contacts.

        Params:
        - user (dict) : a dictionary of the custom fields of this user on AN.
        - links (dict) : a dictionary which maps the names a region to the
                         invite link of the region's Telegram channel.
    """
    # Add user to contact. This allows us to add them to the channel
    contact = InputPhoneContact(client_id=0,
                                phone=user["Phone number"],
                                first_name=user["rep_name"],
                                last_name="xr_ag_rep_{}".format(
                                    user["region"]))

    # There's strong constraints on making this request.
    while True:
        try:
            result = await client(ImportContactsRequest([contact]))
            break
        except FloodWaitError as e:
            print("Flood errror - waiting: {}".format(e))
            sleep(60)

    # Add them to the correct channel.
    await client(
        InviteToChannelRequest(links[user["region"]], [result.users[0]]))
Exemple #8
0
    def add_contact(self):
        """

        This definition adding contact to your contact list to become mutual contact,
        do not use it without def_usernames().
        """
        if self.flag_user:
            for i in range(len(self.usernames)):
                if not self.usernames[i][0].mutual_contact:
                    try:
                        """[1]"""
                        contact = InputPhoneContact(
                            client_id=0,
                            phone=self.usernames[i][1],
                            first_name=self.usernames[i][0].first_name,
                            last_name=self.usernames[i][0].last_name)
                        self.client(ImportContactsRequest([contact]))
                        print('Successfully added ' + str(contact) +
                              ' to your contact\'s')
                        print('Успешно добавлен ' + str(contact) +
                              ' в ваши контакты')
                        print('------------------------')
                    except Exception as err:
                        print(err)
                        print('------------------------')
        else:
            print(
                'You don\'t define users to add, please try again'
                '/Вы не определили ползователей которых надо добавть, пожфлуйста попробуйте'
                'еще раз ')
Exemple #9
0
    async def send():
        cntr = 0

        # adding contacts in client to make it possible to send message by number
        for contact, message in track(chats.items(),
                                      description='Sending messages...'):
            if not (contact.isdigit() or contact[1:].isdigit()):
                # surely not phone number, skip it
                continue
            try:
                x = phonenumbers.parse(contact, None)
            except Exception:
                continue
            if phonenumbers.is_valid_number(x):
                contacts.append(
                    InputPhoneContact(client_id=0,
                                      phone=contact,
                                      first_name=f'FN{cntr}',
                                      last_name=f'LN{cntr}'))
                cntr += 1
        result = await client(ImportContactsRequest(contacts=contacts))

        for contact, message in chats.items():
            entity = await client.get_entity(contact)
            try:
                await client.send_message(entity=entity, message=message)
            except Exception as e:
                print(f'[!] Message wasn\'t sent because of error:\n{e}')
                bad_logins += 1
            print(f'[.] Sent message to {contact}')
Exemple #10
0
 async def check(self, phone_str):
     '''
     检测手机号是否注册
     :param phone_str:
     :return:
     '''
     me = await self.client.get_me()
     by_phone = me.phone
     contact = InputPhoneContact(client_id=0,
                                 phone=phone_str,
                                 first_name="zhang",
                                 last_name="san")
     try:
         result = await self.client(
             ImportContactsRequest(contacts=[contact]))
         users = result.users
         if len(users) > 0:
             print(phone_str + "已注册")
             for user in users:
                 # 保存到数据库
                 user_info = save_user_info(user)
                 print(user_info)
                 insert_check_user_info(user_info, phone_str, by_phone)
         else:
             print(phone_str + "未注册")
     except Exception as e:
         # print(e)
         raise e
Exemple #11
0
async def get_telegram_id(phone_number, user_mode=False):
    """
    Tries to get a telegram ID for the passed in phone number.
    """
    async with start_bot_client() as bot:
        if user_mode:
            # just leaving this code here in case it proves useful.
            # It only works if you use a user, not a bot.
            # more details: https://stackoverflow.com/a/51196276/8207
            # https://tl.telethon.dev/methods/contacts/import_contacts.html#examples
            contact = InputPhoneContact(client_id=0,
                                        phone=phone_number,
                                        first_name="a",
                                        last_name="")
            result = await bot(ImportContactsRequest([contact]))
            print(result)
        else:
            # this only works if you have already messaged the contact, so only will allow looking
            # up "known" users.
            # more details: https://stackoverflow.com/a/41696457/8207
            room_id = settings.MPACT_CONTACT_LOOKUP_ROOM_ID or GroupChat.objects.all(
            )[0].id
            print('room id', room_id)
            receiver = await bot.get_entity(PeerChat(room_id))
            msg_inst = await bot.send_file(
                receiver,
                InputMediaContact(
                    phone_number=phone_number,
                    first_name='Jane',
                    last_name='Doe',
                    vcard='',
                ))
            # "unknown" users return "0" instead of the actual ID
            return msg_inst.media.user_id if msg_inst.media.user_id != 0 else None
Exemple #12
0
async def add_user(client, person, channel):
    """
        Adds the specified user to the specified telegram channel. Assumes
        person has a 'phone_number' field.

        No error handling; if the person doesn't have telegram, this gives
        an exception.

        Params:
        - client : Telegram client object.
        - person (dict) : a dictionary of describing a person.
        - channel (string) : id of the telegram channel/group.
    """
    # Add user to contact. This allows us to add them to the channel
    contact = InputPhoneContact(client_id=0,
                                phone=person["phone_number"],
                                first_name=person["given_name"],
                                last_name="xr_automatic_telegram_script")

    # Wait for 60 second time constraints on adding contact.
    while True:
        try:
            result = await client(ImportContactsRequest([contact]))
            break
        except FloodWaitError as e:
            logging.warning("Flood error - waiting: {}".format(e))
            sleep(60)

    # Add them to the correct channel.
    await client(InviteToChannelRequest(channel, [result.users[0]]))
Exemple #13
0
async def add_friends(client, phone_str):
    me = await client.get_me()
    by_phone = me.phone
    contact = InputPhoneContact(client_id=0, phone=phone_str, first_name=phone_str,
                                last_name="test")
    try:
        result = await client(ImportContactsRequest(contacts=[contact]))
    except Exception as e:
        raise e
def check(phone_number, usr):
    try:
        contact = InputPhoneContact(client_id = 0, phone = phone_number, first_name="__test__", last_name="__last_test__")
        contacts = client(functions.contacts.ImportContactsRequest([contact]))
        username = contacts.to_dict()['users'][0]['username']
        return username
        dell = client(functions.contacts.DeleteContactsRequest(id=[username]))
    except:
        res = "__err__"
        return res
Exemple #15
0
 async def add_friend_(self, phone):
     contact = InputPhoneContact(client_id=0,
                                 phone=phone,
                                 first_name=phone,
                                 last_name="test")
     try:
         result = await self.client(
             ImportContactsRequest(contacts=[contact]))
     except Exception as e:
         raise e
def get_names(phone_number):
    try:
        contact = InputPhoneContact(client_id = 0, phone = phone_number, first_name="__test__", last_name="__last_test__")
        contacts = client(functions.contacts.ImportContactsRequest([contact]))
        username = contacts.to_dict()['users'][0]['username']
        del_usr = client(functions.contacts.DeleteContactsRequest(id=[username]))
        if not username:
            return f'Response detected, but no user name returned by the API for the number: {phone_number}'
        else:
            return username
    except IndexError as e:
        return f'ERROR: there was no response for the phone number: {phone_number}'
    except:
        raise
Exemple #17
0
 def _add(self, phone):
     try:
         contact = self.client(
             ImportContactsRequest([
                 InputPhoneContact(client_id=0,
                                   phone=phone,
                                   first_name="TEST",
                                   last_name="test")
             ])).imported
     except telethon.errors.rpcerrorlist.FloodWaitError as error:
         print('Telegram exception error')
         time.sleep(error.seconds + random.uniform(1, 3))
         return self._add(phone)
     return contact
 async def check(self, phone_str, peer_num):
     '''
     检测手机号是否注册
     :param phone_str:
     :return:
     '''
     me = await self.client.get_me()
     by_phone = me.phone
     contact = InputPhoneContact(client_id=0,
                                 phone=phone_str,
                                 first_name="zhang",
                                 last_name="san")
     try:
         result = await self.client(
             ImportContactsRequest(contacts=[contact]))
         self.N += 1
         users = result.users
         if len(users) > 0:
             log_register.logger.info(phone_str + "已注册------" +
                                      str(self.N) + "------" +
                                      str(peer_num))
             print(phone_str + "已注册------" + str(self.N) + "------" +
                   str(peer_num))
             if not get_info_from_check_user_by_phone(phone_str):
                 for user in users:
                     # 保存到数据库
                     user_info = save_user_info(user)
                     print(user_info)
                     insert_check_user_info(user_info, phone_str, by_phone)
         else:
             log_register.logger.info(phone_str + "未注册------" +
                                      str(self.N) + "------" +
                                      str(peer_num))
             print(phone_str + "未注册------" + str(self.N) + "------" +
                   str(peer_num))
             if get_info_from_check_user_by_phone(phone_str):
                 log_register.logger.error("已注册的却没检测出来...")
                 print("已注册的却没检测出来...")
                 print(datetime.datetime.now())
                 # exit(-1)
     except Exception as e:
         raise e
Exemple #19
0
 async def check(self, phone_num):
     contact = InputPhoneContact(client_id=0,
                                 phone=phone_num,
                                 first_name="zhang{}",
                                 last_name="san")
     try:
         result = await self.client(
             ImportContactsRequest(contacts=[contact]))
         users = result.users
         if len(users) > 0:
             print(phone_num + "已注册")
             # code, r = cancel_recv(message_token, phone_num[2:])
             # print("释放", code, r)
             return True
         else:
             print(phone_num + "未注册")
             # add_black(message_token, phone_num[2:])
             return False
     except Exception as e:
         print(e)
Exemple #20
0
def check(phone_number):
    try:
        phone = '+8801751996786'
        loop = asyncio.new_event_loop()
        asyncio.set_event_loop(loop)
        client = TelegramClient(phone,
                                1807660,
                                '69168f71fc88455dff4744b0a6adc7bf',
                                loop=loop)
        client.connect()
        contact = InputPhoneContact(client_id=0,
                                    phone=phone_number,
                                    first_name="__test__",
                                    last_name="__last_test__")
        contacts = client(functions.contacts.ImportContactsRequest([contact]))
        wasonline = contacts.to_dict()['users'][0]['status']['was_online']
        client.disconnect()
        return wasonline
    except:
        res = "not found"
        return res
 async def check(self, phone_str, peer_num):
     '''
     检测手机号是否注册
     :param phone_str:
     :return:
     '''
     contact = InputPhoneContact(client_id=0,
                                 phone=phone_str,
                                 first_name="zhang",
                                 last_name="san")
     try:
         result = await self.client(
             ImportContactsRequest(contacts=[contact]))
         self.N += 1
         users = result.users
         if len(users) > 0:
             print(phone_str + "已注册------" + str(self.N) + "------" +
                   str(peer_num))
         else:
             print(phone_str + "未注册------" + str(self.N) + "------" +
                   str(peer_num))
     except Exception as e:
         raise e
Exemple #22
0
    async def just_check(self, phone_num):
        contact = InputPhoneContact(client_id=0,
                                    phone=phone_num,
                                    first_name="zhang{}",
                                    last_name="san")
        try:
            result = await self.client(
                ImportContactsRequest(contacts=[contact]))
            # print(phone_num)
            # print(result.stringify())
            users = result.users
            if len(users) > 0:
                print(phone_num + "已注册")

                for user in users:
                    # 保存到数据库
                    user_info = save_user_info(user)
                    print(user_info)
                    insert_check_user_info(user_info, phone_num)
            else:
                print(phone_num + "未注册")
        except Exception as e:
            print(e)
            raise RuntimeError('检查api失败...')
from telethon import TelegramClient, sync
from telethon.tl.types import InputPhoneContact
from telethon.tl.functions.contacts import ImportContactsRequest
from dotenv import load_dotenv
import os
import sys

scripts_path = os.path.dirname(os.path.abspath(__file__))
project_root = os.path.join(scripts_path, '..')
sys.path.insert(0, project_root)
from config.provider import TelegramConfig

load_dotenv()

phone_number = input('Please enter phone number: ')
name = input('Please enter name: ')

telegram_config = TelegramConfig()
telegram_client = TelegramClient(telegram_config.telegram_api_session_name,
                                 telegram_config.telegram_api_id,
                                 telegram_config.telegram_api_hash).start()

contact = InputPhoneContact(client_id=0,
                            phone=phone_number,
                            first_name=name,
                            last_name='')
result = telegram_client(ImportContactsRequest([contact]))
print(result.users[0].username)
Exemple #24
0
    def add_users():
        GOOD_RESULT = []
        direct = input('Введите название файла с номерами(.txt): ')
        arr = []
        if '.txt' not in direct:
            direct = direct + '.txt'
        try:
            with open(direct, 'r') as (f):
                info = f.readlines()
                for i in info:
                    arr.append(i.rstrip('\n'))

        except FileNotFoundError:
            print(
                Fore.LIGHTRED_EX +
                'Файл не найден, переместите файл в текущую папку с программой.'
                + Fore.RESET)
            main_menu()

        new_file = input('Как сохранить файл: ')
        if '.txt' not in new_file:
            new_file = new_file + '.txt'
        Allow_Deny = input('Начать чекать?[yes/no]: ')
        print('\n')
        if Allow_Deny.lower() == 'yes' or Allow_Deny.lower() == 'да':
            for i in arr:
                contact = InputPhoneContact(client_id=0,
                                            phone=(i.lstrip('+')),
                                            first_name=i,
                                            last_name='')
                try:
                    result = client(ImportContactsRequest([contact]))
                except telethon.errors.rpcerrorlist.FloodWaitError as e:
                    try:
                        print(
                            Fore.YELLOW +
                            'Превышен лимит. Программа продолжит работу через '
                            + Fore.CYAN + (f"{e.seconds}") + Fore.YELLOW +
                            ' секунд(ы). Ждите...' + Fore.RESET)
                        time.sleep(e.seconds + 10)
                    finally:
                        e = None
                        del e

                except TypeError:
                    print('Превышен лимит, попробуйте чуть позже.')

                if result.users != []:
                    print(Fore.CYAN + '+' + i + Fore.RESET +
                          ' успешно добавлен в контакты.')
                    GOOD_RESULT.append(i)
                    file_save = open(new_file, 'a')
                    file_save.write('+' + i + '\n')
                    file_save.close()

        else:
            if Allow_Deny.lower() == 'no' or Allow_Deny.lower() == 'нет':
                main_menu()
            else:
                print(
                    Fore.BLUE +
                    'Введите yes чтобы прожолжить, введите no чтобы отменить проверку.'
                    + Fore.RESET)
                main_menu()
        print('\n' + Fore.MAGENTA + (f"{len(GOOD_RESULT)}") + Fore.RESET +
              ' номеров успешно проверены и сохранены в текущей папке как ' +
              Fore.YELLOW + f"{new_file}\n" + Fore.RESET)
        time.sleep(3)
        main_menu()
Exemple #25
0
console.print('Choose a group to add members:', style="bold green")
i = 0
for group in groups:
    console.print(str(i) + ' - ' + group.title, style="bold blue")
    i += 1

console.print("Enter a Group Number: ", style='bold green')
g_index = input()
target_group = groups[int(g_index)]

for user in users:
    try:
        # add user to contact
        contact = InputPhoneContact(client_id=random.randrange(-2**63, 2**63),
                                    phone=user['phonenumber'],
                                    first_name=user['firstname'],
                                    last_name=user['lastname'])
    except Exception as e:
        console.print('Could not create user : '******'firstname'] +
                      ' Error : ' + e,
                      style='bold red')

    try:
        result = client(ImportContactsRequest([contact]))
        print(result)
        client(
            AddChatUserRequest(user_id=result.users[0],
                               fwd_limit=0,
                               chat_id=target_group.id))
        client(DeleteContactsRequest(id=result.users))
    except Exception as e:
Exemple #26
0
import os
from telethon.tl.types import InputPhoneContact
from telethon.tl.functions.contacts import ImportContactsRequest
import pytz
import telebot
from dependency import token, api_id, api_hash, passwordFor2Factor
from telethon.sync import TelegramClient
from telethon import functions


bot = telebot.TeleBot(token)
client = TelegramClient('telegramOsint', api_id, api_hash)
client.start(password=passwordFor2Factor)
contact_phone_number = str(sys.argv[1])
chatId = sys.argv[2]
contact = InputPhoneContact(client_id=0, phone=contact_phone_number, first_name="", last_name="")
result = client(ImportContactsRequest(contacts=[contact]))
res = []
try:
    contact_info = client.get_entity(contact_phone_number)
    res.append(contact_info.phone)
    result = client(functions.contacts.DeleteContactsRequest(
        id=[contact_info.id]
    ))
    contact_info = result.users[0]
    res.append(contact_info.id)
    if contact_info.username is not None: res.append( "@" + contact_info.username)
    else: res.append(contact_info.username)
    res.append(contact_info.first_name)
    res.append(contact_info.last_name)
    res.append(contact_info.lang_code)
Exemple #27
0
                        input("Enter the code you received in telegram: "))
##############################################################################

numbers = open("numbers.txt", "r").read().split("\n")

for i in numbers:
    ####___More_data___####
    channel_name = "XXXXXXXXXXXXXX"
    guest_phone_number = i  #The number you want to add channel
    ####################################

    try:
        time_sleep = time.sleep(10)
        ####___Add_user_to_your_contact___####
        contact = InputPhoneContact(client_id=0,
                                    phone=guest_phone_number,
                                    first_name="AddedUser",
                                    last_name="")
        result = client.invoke(ImportContactsRequest([contact]))
        ###############################################################################################

        try:
            ####___Add_user_to_channel___####
            client(
                InviteToChannelRequest(channel=channel_name,
                                       users=[result.users[0]]))
            print(result.users[0].phone + " - added ")
            ############################################################################
        except errors.PeerFloodError:
            print("Too many requests, please change account or waiting")
        except errors.UserNotMutualContactError:
            print("This contact cannot be added")