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}')
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
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' '/Вы не определили ползователей которых надо добавть, пожфлуйста попробуйте' 'еще раз ')
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 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
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
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
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]]))
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]]))
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)
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
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
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 from_group_ten_first_persons(group, togroup): flag = True if group == '-': flag = False return flag elif togroup == '-': flag = False return flag users = client.get_participants(group) channel = client.get_entity(togroup) for i in range(10): try: contact = InputPhoneContact(client_id=user[i].id, phone=user[i].phone, first_name=user[i].first_name, last_name=user[i].last_name) result = client.invoke(ImportContactsRequest([contact])) client( InviteToChannelRequest( InputChannel(channel.id, channel.access_hash), [InputUser(users[i].id, users[i].access_hash)])) except errors.rpcerrorlist.UserPrivacyRestrictedError as err: print('>>>>0. UserPrivacyRestrictedError...') print(err) except errors.rpcerrorlist.ChatAdminRequiredError as err: print('>>>>1. ChatAdminRequiredError...') print(err) except errors.rpcerrorlist.ChatIdInvalidError as err: print('>>>>2. ChatIdInvalidError...') print(err) except errors.rpcerrorlist.InputUserDeactivatedError as err: print('>>>>3. InputUserDeactivatedError...') print(err) except errors.rpcerrorlist.PeerIdInvalidError as err: print('>>>>4. PeerIdInvalidError...') print(err) except errors.rpcerrorlist.UserAlreadyParticipantError as err: print('>>>>5. UserAlreadyParticipantError...') print(err) except errors.rpcerrorlist.UserIdInvalidError as err: print('>>>>6. UserIdInvalidError...') print(err) except errors.rpcerrorlist.UserNotMutualContactError as err: print('>>>>>7. UserNotMutualContactError...') print(err) except errors.rpcerrorlist.UsersTooMuchError as err: print('>>>>>8. UsersTooMuchError...') print(err) except errors.rpcerrorlist.PeerFloodError as err: print( '>>>>>9. PeerFloodError try again in 24 Hours...Yes, you in spam' ) print(err) return flag
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
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)
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
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.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) if hasattr(contact_info.status, "was_online"):
def main(): flag = False client.connect() if not client.is_user_authorized(): client.send_code_request(phone_number) me = client.sign_in(phone_number, input('Enter code: ')) while True: channel_name = input( 'Link of channel pls, example: https://t.me/qwertyuiop1234567890, or \'-\'(without \'\') ' 'if you need to convert 10 persons from other group (10 first persons)' ) is_correct = re.search(r'(http?s:\/\/)(t\.me)(\/[A-Za-z0-9]+)', channel_name) if channel_name == is_correct: channel = client.get_entity(channel_name) # channel_ id or name users_in_channel = client.get_participants( channel_name) # channel id or name print(users_in_channel) break elif channel_name == '-': flag = True break continue def from_group_ten_first_persons(group, togroup): flag = True if group == '-': flag = False return flag elif togroup == '-': flag = False return flag users = client.get_participants(group) channel = client.get_entity(togroup) for i in range(10): try: contact = InputPhoneContact(client_id=user[i].id, phone=user[i].phone, first_name=user[i].first_name, last_name=user[i].last_name) result = client.invoke(ImportContactsRequest([contact])) client( InviteToChannelRequest( InputChannel(channel.id, channel.access_hash), [InputUser(users[i].id, users[i].access_hash)])) except errors.rpcerrorlist.UserPrivacyRestrictedError as err: print('>>>>0. UserPrivacyRestrictedError...') print(err) except errors.rpcerrorlist.ChatAdminRequiredError as err: print('>>>>1. ChatAdminRequiredError...') print(err) except errors.rpcerrorlist.ChatIdInvalidError as err: print('>>>>2. ChatIdInvalidError...') print(err) except errors.rpcerrorlist.InputUserDeactivatedError as err: print('>>>>3. InputUserDeactivatedError...') print(err) except errors.rpcerrorlist.PeerIdInvalidError as err: print('>>>>4. PeerIdInvalidError...') print(err) except errors.rpcerrorlist.UserAlreadyParticipantError as err: print('>>>>5. UserAlreadyParticipantError...') print(err) except errors.rpcerrorlist.UserIdInvalidError as err: print('>>>>6. UserIdInvalidError...') print(err) except errors.rpcerrorlist.UserNotMutualContactError as err: print('>>>>>7. UserNotMutualContactError...') print(err) except errors.rpcerrorlist.UsersTooMuchError as err: print('>>>>>8. UsersTooMuchError...') print(err) except errors.rpcerrorlist.PeerFloodError as err: print( '>>>>>9. PeerFloodError try again in 24 Hours...Yes, you in spam' ) print(err) return flag def is_in_group(username): if username in users_in_channel: return True else: return False with open('im.txt') as f: # file with list of usernames for line in f: print(line) tmp = line[1:].replace('\n', '') print(tmp) if not flag: try: user = client.get_entity( tmp) # (ResolveUsernameRequest(tmp)) print(user) except UsernameInvalidError as err: print(err) continue if user: try: contact = InputPhoneContact(client_id=user.id, phone=user.phone, first_name=user.first_name, last_name=user.last_name) result = client.invoke(ImportContactsRequest([contact ])) sleep(31) client( InviteToChannelRequest( InputChannel(channel.id, channel.access_hash), [InputUser(user.id, user.access_hash)])) except errors.rpcerrorlist.UserPrivacyRestrictedError as err: print('>>>>0. UserPrivacyRestrictedError...') print(err) except errors.rpcerrorlist.ChatAdminRequiredError as err: print('>>>>1. ChatAdminRequiredError...') print(err) except errors.rpcerrorlist.ChatIdInvalidError as err: print('>>>>2. ChatIdInvalidError...') print(err) except errors.rpcerrorlist.InputUserDeactivatedError as err: print('>>>>3. InputUserDeactivatedError...') print(err) except errors.rpcerrorlist.PeerIdInvalidError as err: print('>>>>4. PeerIdInvalidError...') print(err) except errors.rpcerrorlist.UserAlreadyParticipantError as err: print('>>>>5. UserAlreadyParticipantError...') print(err) except errors.rpcerrorlist.UserIdInvalidError as err: print('>>>>6. UserIdInvalidError...') print(err) except errors.rpcerrorlist.UserNotMutualContactError as err: print('>>>>>7. UserNotMutualContactError...') print(err) except errors.rpcerrorlist.UsersTooMuchError as err: print('>>>>>8. UsersTooMuchError...') print(err) except errors.rpcerrorlist.PeerFloodError as err: print( '>>>>>9. PeerFloodError try again in 24 Hours...Yes, you in spam' ) print(err) # sleep(86400) elif from_group_ten_first_persons( input('From group get partisipants or - '), input('To group or - ')): break else: continue client.disconnect()
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()
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") except (IndexError, TypeError):
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)