async def _get_entity_from_string(self: 'TelegramClient', string): """ Gets a full entity from the given string, which may be a phone or a username, and processes all the found entities on the session. The string may also be a user link, or a channel/chat invite link. This method has the side effect of adding the found users to the session database, so it can be queried later without API calls, if this option is enabled on the session. Returns the found entity, or raises TypeError if not found. """ phone = utils.parse_phone(string) if phone: try: for user in (await self(functions.contacts.GetContactsRequest(0) )).users: if user.phone == phone: return user except errors.BotMethodInvalidError: raise ValueError('Cannot get entity by phone number as a ' 'bot (try using integer IDs, not strings)') elif string.lower() in ('me', 'self'): return await self.get_me() else: username, is_join_chat = utils.parse_username(string) if is_join_chat: invite = await self( functions.messages.CheckChatInviteRequest(username)) if isinstance(invite, types.ChatInvite): raise ValueError( 'Cannot get entity from a channel (or group) ' 'that you are not part of. Join the group and retry') elif isinstance(invite, types.ChatInviteAlready): return invite.chat elif username: try: result = await self( functions.contacts.ResolveUsernameRequest(username)) except errors.UsernameNotOccupiedError as e: raise ValueError( 'No user has "{}" as username'.format(username)) from e try: pid = utils.get_peer_id(result.peer, add_mark=False) if isinstance(result.peer, types.PeerUser): return next(x for x in result.users if x.id == pid) else: return next(x for x in result.chats if x.id == pid) except StopIteration: pass try: # Nobody with this username, maybe it's an exact name/title return await self.get_entity( await self.session.get_input_entity(string)) except ValueError: pass raise ValueError( 'Cannot find any entity corresponding to "{}"'.format(string))
writer.writerows(rows) f.close() if __name__ == '__main__': done = False try: api_info_list = read_csv('api.csv') phone_list = sum(read_csv('phone.csv'), start=[]) config = configparser.ConfigParser() config.read("config.ini") from_channel = config['Telegram']['from_channel'] to_channel = config['Telegram']['to_channel'] main_phone = utils.parse_phone(config['Telegram']['main_phone']) user_rows = read_csv('users.csv') main_client = TelegramClient(f"sessions/{main_phone}", *api_info_list[0]) main_client.start(main_phone) from_channel_entity = main_client.get_entity(from_channel) to_channel_entity = main_client.get_entity(to_channel) try: for api in api_info_list: print(f"\n*** Using App {api[0]} ***\n") for unparsed_phone in phone_list:
def autos(): channel_username = to_group 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) startfrom = int(input("Start From = ")) endto = int(input("End To = ")) for user in users: if (int(startfrom) <= int(user['srno'])) and (int(user['srno']) <= int(endto)): try: status = 'delta' if user['username'] == "": print("no username, moving to next") continue client( InviteToChannelRequest(channel_username, [user['username']])) status = 'DONE' #print("Waiting for 60-180 Seconds...") time.sleep(random.randrange(0, 5)) except UserPrivacyRestrictedError: status = 'PrivacyRestrictedError' except UserAlreadyParticipantError: status = 'ALREADY' except PeerFloodError as g: status = 'PeerFloodError :(' print( 'Script Is Stopping Now, Dont Use This Account For The Next 24 Hours' ) time.sleep(86400) except ChatWriteForbiddenError as cwfe: client(JoinChannelRequest(channel_username)) continue except errors.RPCError as e: status = e.__class__.__name__ except Exception as d: status = d except: traceback.print_exc() print("Unexpected Error") continue channel_connect = client.get_entity(channel_username) channel_full_info = client( GetFullChannelRequest(channel=channel_connect)) countt = int(channel_full_info.full_chat.participants_count) print( f"ADDING {user['name']} TO {channel_username} TOTAL: {countt} - {status}" ) elif int(user['srno']) > int(endto): print("Members Added 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()
list_of_rows = list(csv_reader) row_number = ve col_number = 1 deltaop = list_of_rows[row_number - 1][col_number - 1] with open('../api.csv', 'r') as hash_obj: csv_reader = csv.reader(hash_obj) list_of_rows = list(csv_reader) row_number = ve col_number = 2 deltaxd = list_of_rows[row_number - 1][col_number - 1] api_id = int(deltaop) api_hash = str(deltaxd) pphone = value phone = utils.parse_phone(pphone) print(f"Using {phone} - Along With {api_id}") client = TelegramClient(f"../sessions/{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: ')) def add_users_to_group(): global ve input_file = f'data/data{ve}.csv' users = [] with open(input_file, encoding='UTF-8') as f: rows = csv.reader(f, delimiter=",", lineterminator="\n")
from telethon.sync import TelegramClient from telethon import utils from add import read_csv from licensing.models import * from licensing.methods import Key, Helpers print( f""" .................................. > www.arshmaan.com < .................................. """) try: phone_list = sum(read_csv('phone.csv'), start=[]) api = read_csv('api.csv')[0] for unparsed_phone in phone_list: phone = utils.parse_phone(unparsed_phone) print(f"Login {phone}") client = TelegramClient(f"sessions/{phone}", *api) client.start(phone) client.disconnect() print() done = True finally: input("Done!" if done else "Error!")
writer.writerows(rows) f.close() if __name__ == '__main__': done = False try: api_info_list = read_csv('api.csv') phone_list = sum(read_csv('phone.csv'), start=[]) config = configparser.ConfigParser() config.read("config.ini") from_channel = config['Telegram']['from_channel'] to_channel = config['Telegram']['to_channel'] export_phone = utils.parse_phone(config['Telegram']['export_phone']) user_rows = read_csv('users.csv') main_client = TelegramClient(f"sessions/{export_phone}", *api_info_list[0]) main_client.start(export_phone) from_channel_entity = main_client.get_entity(from_channel) to_channel_entity = main_client.get_entity(to_channel) try: for api in api_info_list: print(f"\n*** Using App {api[0]} ***\n") for unparsed_phone in phone_list:
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()
async def authorize_phone( phone: str, password: Union[None, str] = None, bot_token: Union[None, str] = None, force_sms: bool = False, code: Union[None, str] = None, phone_code_hash: Union[None, str] = None, session: Union[None, str] = None, ): logger.info( f"Args: phone={phone}, password={password}, bot_token={bot_token}, force_sms={force_sms}, code={code}." ) bot = TelegramClientUpdateCollector( session=StringSession(session), api_id=TG_APP_ID, api_hash=TG_APP_HASH, mode=UpdateModes.SILENT, ) if not bot.is_connected(): await bot.connect() # end if if not bot_token: # Turn the callable into a valid phone number (or bot token) phone = parse_phone(phone) else: me = await bot.sign_in(bot_token=bot_token) if not isinstance(me, User): me = await bot.get_me() # end if user_id = me.user_id if hasattr(me, 'user_id') else me.id assert user_id bots[user_id] = bot return r_success( result=PhoneAuthorisation( message='SUCCESS: registered bot', reason=PhoneAuthorisationReasons.SUCCESS_BOT, data=PhoneAuthorisationData(token='bot' + bot_token, # session=bot.session.save(), )), description= "OK: Logged in. Use the token to connect to this service.", status_code=200, ) # end if logger.info(f'Phone Number: {phone}') if not code: logger.info('Sending code request.') sent_code = await bot.send_code_request(phone, force_sms=force_sms) logger.info(f'sent_code: {sent_code}') # sign_up = not sent_code.phone_registered logger.warning( "Needs code now!\n" "Please provide via '$TELEGRAM_LOGGER_PHONE_LOGIN_CODE' environment variable.\n" f"Also set '$TELEGRAM_LOGGER_PHONE_LOGIN_HASH={sent_code.phone_code_hash}'." ) session_str = bot.session.save() return r_error( result=PhoneAuthorisation( message='LOGIN FAILED: Please provide the code sent to you', reason=PhoneAuthorisationReasons.CODE_NEEDED, data=PhoneAuthorisationData( phone_code_hash=sent_code.phone_code_hash, session=session_str, ), ), error_code=401, description= "UNAUTHORIZED: Login failed, please provide the code sent to you", ) else: logger.info('Signing in.') try: # me = await self.sign_in(phone, code=code, phone_code_hash=phone_code_hash) result = await bot(SignInRequest(phone, phone_code_hash, str(code))) logger.warning(f"Sign in result: {result}") me = bot._on_login(result.user) except PhoneCodeExpiredError: session_str = bot.session.save() # TODO: Status 502 return r_error( result=PhoneAuthorisation( message= 'LOGIN FAILED: Code expired. Please provide the new code sent to you', reason=PhoneAuthorisationReasons.CODE_EXPIRED, data=PhoneAuthorisationData( phone_code_hash=phone_code_hash, session=session_str, )), error_code=401, description= 'UNAUTHORIZED: Login failed, code expired. Please provide the new code sent to you', ) except SessionPasswordNeededError: if not password: txt = "Two-step verification is enabled for this account. Please provide the 'TELEGRAM_LOGGER_PHONE_LOGIN_CODE' environment variable." session_str = bot.session.save() logger.error(txt) # TODO: Status 502 return r_error( result=PhoneAuthorisation( message= 'LOGIN FAILED: Please provide your personal two factor login (2FA) password you set in your account', reason=PhoneAuthorisationReasons. TWO_FACTOR_PASSWORD_NEEDED, data=PhoneAuthorisationData( phone_code_hash=phone_code_hash, code=code, session=session_str, )), error_code=401, description= 'UNAUTHORIZED: Login failed, please provide your personal two factor login (2FA) password you set in your account', ) # end if me = await bot.sign_in(phone=phone, password=password, phone_code_hash=phone_code_hash) except Exception as e: logger.exception('sign in didn\'t work') raise e # end try assert await bot.is_user_authorized(), "should be authorized now." if not isinstance(me, User): me = await bot.get_me() # end if if hasattr(me, 'id'): chat_id = me.id elif hasattr(me, 'chat_id'): chat_id = me.chat_id elif hasattr(me, 'channel_id'): chat_id = me.channel_id elif hasattr(me, 'user_id'): chat_id = me.user_id else: logger.warn(f'me has no id like attribute:\n{me!r}\n{me!s}') raise ValueError('me is wrong?') # end if secret = bot.session.save() user_token = f'user{chat_id!s}@{secret}' # noinspection PyTypeChecker return r_success( result=SuccessfulPhoneAuthorisationData(user_token=user_token), description= "OK: Logged in. Use the token to connect to this service.", status_code=200)
print(' ', msg[:75] + '...' if len(msg) > 78 else msg) # channel = client.get_entity('https://t.me/huytest') # print(channel.stringify()) # print(client.get_messages(channel, 5)) client.add_event_handler(print_message, events.NewMessage(chats=1332837514, incoming=True)) client.catch_up() print('event handlers:', client.list_event_handlers()) def stop(client): client.disconnect() if __name__ == "__main__": if len(sys.argv) < 2: print('Usage:', os.path.basename(__file__), '<phone_number>') exit(1) client = TelegramClient( os.path.abspath( config.get('paths', 'sessions') + '/' + parse_phone(sys.argv[1]) ), config.get('telegram', 'api_id'), config.get('telegram', 'api_hash') ) try: start(client) client.run_until_disconnected() finally: stop(client)