def get_cached_client(): """Gets an authorized TelegramClient, performing the authorization process if it's the first time""" global cached_client if not cached_client: print('Loading client...') settings = load_settings() cached_client = TelegramClient(session_user_id=settings.get('session_name', 'anonymous'), api_id=settings['api_id'], api_hash=settings['api_hash']) cached_client.connect() # Then, ensure we're authorized and have access if not cached_client.is_user_authorized(): # Import the login window locally to avoid cyclic dependencies from gui.windows import LoginWindow print('First run, client not authorized. Sending code request.') cached_client.send_code_request(str(settings['user_phone'])) start_app(LoginWindow, client=cached_client, phone=settings['user_phone']) del LoginWindow print('Client loaded and authorized.') return cached_client
class PushTelegram(Pusher): def __init__(self): config = configparser.ConfigParser() config.read('../conf/config.ini') api_id = config['TELEGRAM']['api_id'] api_hash = config['TELEGRAM']['api_hash'] print(api_id,' ',api_hash) self.telegram = TelegramClient("BitCoinDev", api_id, api_hash) self.telegram.connect() if not self.telegram.is_user_authorized(): self.telegram.send_code_request('+821097950344') self.telegram.sign_in('+821097950344', input('Enter the code: ')) def send_message(self, username = None, message = None): self.telegram.send_message(username, message)
def start(client: TelegramClient): # client.start() #bot_token=config.get('telegram', 'bot_token') client.connect() # me = client.get_me() # print(me.stringify()) for dialog in client.iter_dialogs(): if not dialog.is_channel: continue if isinstance(dialog.entity.photo, types.ChatPhotoEmpty): print(dialog.entity.id, dialog.entity.title) else: fn = os.path.join( config.get('paths', 'avatars'), 'channel-' + str(dialog.entity.id) + '.jpg' ) # if not os.path.exists(fn): # fn = client.download_profile_photo(dialog.entity, fn, download_big=False) print(dialog.entity.id, dialog.entity.title, '🖕', fn) msg = dialog.message.message if msg: 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 main(): client = TelegramClient('session_name', config.API_ID, config.API_HASH) client.connect() # me = client.sign_in(code='27105') me = client.get_me() target_user = client.get_entity(config.TARGET_USER_ID) limit = None total_messages, messages, users = client.get_message_history( config.TARGET_USER_ID, limit=limit) header = [ 'id', 'from_id', 'to_id', 'date', 'message', 'is_media', 'is_edited' ] with open('message_history.csv', 'w') as f: writer = csv.writer(f) writer.writerow(header) for message in messages: print_message(message) is_media = message.media is not None is_edited = message.edit_date is not None row = [ message.id, message.from_id, message.to_id.user_id, message.date, message.message, is_media, is_edited ] writer.writerow(row) if message.views is not None: print('What are those?') import pdb pdb.set_trace()
def confirm_tg_account(bot, update, user_data): code = update.message.text tg_session = session.query(TelegramSession).filter( TelegramSession.id == int(user_data['session_id'])).first() user = session.query(User).filter( User.tg_id == update.message.chat_id).first() client = TelegramClient( os.path.join(config.TELETHON_SESSIONS_DIR, tg_session.phone_number), user.api_id if user.api_id else config.TELEGRAM_API_ID, user.api_hash if user.api_hash else config.TELEGRAM_API_HASH) client.connect() try: client.sign_in(tg_session.phone_number, code, phone_code_hash=tg_session.phone_code_hash) tg_session.active = True update.message.reply_text('Account added successfully.') except Exception as e: update.message.reply_text('Error: {}.'.format(e)) path = os.path.join(config.TELETHON_SESSIONS_DIR, '{}.session'.format(tg_session.phone_number)) if os.path.exists(path): os.remove(path) session.delete(tg_session) session.commit() client.disconnect() return ConversationHandler.END
def add_account(bot, update, args, user_data): if len(args) == 1: phone_number = args[0] user = session.query(User).filter( User.tg_id == update.message.chat_id).first() tg_sessions = session.query(TelegramSession).filter( TelegramSession.user == user).all() phone_numbers = [s.phone_number for s in tg_sessions] if phone_number in phone_numbers: update.message.reply_text( "Sorry, this phone number already exists.") return ConversationHandler.END client = TelegramClient( os.path.join(config.TELETHON_SESSIONS_DIR, phone_number), user.api_id if user.api_id else config.TELEGRAM_API_ID, user.api_hash if user.api_hash else config.TELEGRAM_API_HASH) client.connect() result = client.send_code_request(phone_number, force_sms=True) client.disconnect() tg_session = TelegramSession(phone_number=phone_number, phone_code_hash=result.phone_code_hash, user=user) session.add(tg_session) session.commit() user_data['session_id'] = tg_session.id update.message.reply_text("Please, send the login code to continue") return LOGIN_CODE else: update.message.reply_text("Please, include the phone number to this " "command.") return ConversationHandler.END
def start_sending(mailing, segment, **kwargs): client = TelegramClient(mailing.user.profile.get_tg_config_loc(), settings.TG_CONF['API_ID'], settings.TG_CONF['API_HASH']) client.connect() sent, failed = 0, 0 for user in segment.users.all(): msg = TGMessage.objects.create(user=mailing.user, mailing=mailing, sent=timezone.now(), recipient=user) try: if not user.phone and user.username: raise Exception("No target address") t_msg = client.send_message(user.username or user.phone, mailing.content) msg.status = TGMessage.SENT msg.sid = t_msg.id sent += 1 except Exception as e: msg.status = TGMessage.FAILED failed += 1 finally: msg.save() sleep(2) if sent == 0 and failed > 0: mailing.status = mailing.FAILED elif sent > 0 and failed > 0: mailing.status = mailing.PARTIALLY_COMPLETED elif sent > 0 and failed == 0: mailing.status = mailing.COMPLETED mailing.save()
def sigh_in_cli(self, user, session=None): """ :param str session: :param User|str user: :return: TelegramClient """ api_id, api_hash = self.get_app_data() print(api_id) print(api_hash) if user is None: print("empty user!") return None if type(user) == User: mobile = user.mobile else: mobile = user if session is None: session = self.make_session(user) else: session = self.generated_sessions_dir + '/' + session print(session) client = TelegramClient(session, api_id, api_hash, timeout=timedelta(seconds=10)) client.connect() client.sign_in(phone=mobile) code = input('Enter code:') client.sign_in(code=code) return client
def main(_config, consts): with open('configs/' + _config + '.json', 'r', encoding='utf-8') as f: config = json.loads(f.read()) accounts = config['accounts'] for account in accounts: api_id = account['api_id'] api_hash = account['api_hash'] phone = account['phone'] client = TelegramClient(folder_session + phone, api_id, api_hash) client.connect() if client.is_user_authorized() and phone != consts['check_phone'][ 0] and phone != consts['check_phone'][1]: isBan = asyncio.get_event_loop().run_until_complete( send_bot(client, phone, consts)) account['ban'] = isBan else: print('Login fail: ' + phone) client.disconnect() with open(folder_configs + _config + consts['type_file'][2], 'w', encoding='utf-8') as f: json.dump(config, f, indent=4, ensure_ascii=False) print('---------------- End ' + _config + ' !(O~0)! ----------------')
def initClient(configName='config.ini'): #Checkin if not inited if not os.path.exists(configName): print("Config file doesn't exist!") return #Init config to read config = ConfigParser() config.read(configName) #Get basic information api_id = config.get("TelegramAPI", "api_id") api_hash = config.get("TelegramAPI", "api_hash") phone = config.get("Telegram", "phone") username = config.get("Telegram", "username") #Init client client = TelegramClient(username, api_id, api_hash) client.connect() #If not .session file if not client.is_user_authorized(): client.send_code_request(phone) try: client.sign_in( phone, input('Enter the code which you had in your telegram: ')) except: client.sign_in(password=input('Enter password: ')) return client
def establish_connection(api_id, api_hash, session): client = TelegramClient(session, api_id, api_hash) client.connect() if client.is_user_authorized() is False: print('Not authorized') sys.exit() return client
class Client: def __init__(self, session, api_id, api_hash, try_logging_in=False): self.session = session self.api_id = api_id self.api_hash = api_hash self.account = TelegramClient(session, api_id, api_hash) self.account.connect() self.lastupdate = get_now() - timedelta(minutes=1) if try_logging_in: self.account.start() async def edit_bio(self, new_bio): logging.debug('check for changing bio') # 1 minute try: if get_now().minute != self.lastupdate.minute: logging.info(f"Change bio to {new_bio}") await self.account(UpdateProfileRequest(about=new_bio, )) self.lastupdate = get_now() except FloodWaitError as e: logging.warning(f"Got flood message: {e}. sleep for {e.seconds}") await sleep(e.seconds) async def set_time_to_bio(self): await self.edit_bio(choice(BIO_MESSAGES) % get_current_time_in_words()) def __str__(self): me = self.account.get_me() return f"TelegramClient({me.first_name} {me.last_name}, @{me.username})"
def main(): session_name = environ.get('TG_SESSION', 'session') user_phone = environ['TG_PHONE'] client = TelegramClient(session_name, int(environ['TG_API_ID']), environ['TG_API_HASH'], proxy=None, update_workers=4) print('INFO: Connecting to Telegram Servers...', end='', flush=True) client.connect() print('Done!') if not client.is_user_authorized(): print('INFO: Unauthorized user') client.send_code_request(user_phone) code_ok = False while not code_ok: code = input('Enter the auth code: ') try: code_ok = client.sign_in(user_phone, code) except SessionPasswordNeededError: password = getpass( 'Two step verification enabled. Please enter your password: '******'INFO: Client initialized succesfully!') client.add_update_handler(update_handler) input('Press Enter to stop this!\n')
def putOtp(request): context = {} if request.method == "POST": mob = request.POST.get('mob') otp = request.POST.get('otp') thephone = ClientApiKey.objects.get(mobile_no=mob) api_id = thephone.apikey api_hash = thephone.apihash try: os.remove('session_name' + str(api_id)) except: pass client = TelegramClient('session_name' + str(api_id), api_id, api_hash) client.connect() phone_code_hash = client.send_code_request(mob).phone_code_hash request.session['phone_code_hash'] = phone_code_hash try: client.sign_in(mob, otp, phone_code_hash=phone_code_hash) except: return render(request, "otp.html", { 'mob': mob, 'title': 'OTP Again', 'otperror': 'invalid OTP' }) context['mobile'] = ClientApiKey.objects.all() context['mob'] = mob return HttpResponseRedirect(reverse('index')) else: return render(request, "otp.html", context)
class ProcessUpload(Thread): def __init__(self, name, client, q_request=None): Thread.__init__(self) self.name = name self.client = TelegramClient(client._session_name, client.api_id, client.api_hash, update_workers=None, spawn_read_thread=False) self.q_request = q_request self.result = None def run(self): # print('Thread %s started' % self.name) time.sleep(random.randrange(20, 200, 10) * 0.001) if not self.client.is_connected(): self.client.connect() while True: request = self.q_request.get() if request is None: break self.result = None # time.sleep(random.randrange(20, 100, 1) * 0.001) self.result = self.client.invoke(request) if self.result is False: break self.q_request.task_done() self.client.disconnect() # print('Thread {0} stopped result {1}'.format(self.name, self.result)) return
def get_group(): client = TelegramClient(folder_session + phone, api_id, api_hash) client.connect() if not client.is_user_authorized(): print('Login fail, need to run init_session') else: get_data_group(client)
def get_cached_client(): """Gets an authorized TelegramClient, performing the authorization process if it's the first time""" global cached_client if not cached_client: print('Loading client...') settings = load_settings() cached_client = TelegramClient(session_user_id=settings.get( 'session_name', 'anonymous'), api_id=settings['api_id'], api_hash=settings['api_hash']) cached_client.connect() # Then, ensure we're authorized and have access if not cached_client.is_user_authorized(): # Import the login window locally to avoid cyclic dependencies from gui.windows import LoginWindow print('First run, client not authorized. Sending code request.') cached_client.send_code_request(str(settings['user_phone'])) start_app(LoginWindow, client=cached_client, phone=settings['user_phone']) del LoginWindow print('Client loaded and authorized.') return cached_client
class Main: def __init__(self): self.config = config.Config() self.user_phone = self.config.get_phone() print('Connecting to Telegram servers...') self.client = TelegramClient('session_name', self.config.get_api_id(), self.config.get_api_hash()) if not self.client.connect(): print('Initial connection failed. Retrying...') if not self.client.connect(): print('Could not connect to Telegram servers.') return if not self.client.is_user_authorized(): print('First run. Sending code request...') try: self.me = self.client.sign_in(phone=self.user_phone) code = input('Enter the code: ') self.me = self.client.sign_in(code=code) except SessionPasswordNeededError: pw = getpass('Please enter your password: '******'Hello! Talking to you from Telethon')
def main(): api_id = 1199490 api_hash = '78fc29abd4ede127b2488e9e273cfb66' client = TelegramClient('love_session', api_id, api_hash) client.connect() if not client.is_user_authorized(): phone = input('please input your phone number (+XXxxx): ') client.send_code_request(phone, force_sms=True) key = input('please insert the key you have received: ') me = client.sign_in(phone=phone, code=key) peer = input( 'please insert your peer\'s telegram account name (@xxx): ') peer_file = open('/home/pi/peer', 'w') peer_file.write(peer.strip()) peer_file.close() else: print('already authorized.') recv_other = '' recv_path = '/home/pi/recv_other' while recv_other not in ['y', 'n']: recv_other = input('play messages from other users? (y/n): ') if recv_other == 'y': if not os.path.exists(recv_path): os.mknod(recv_path) elif os.path.exists(recv_path): os.remove(recv_path)
def telegram_login(user_id): client = TelegramClient('session#' + str(user_id), api_id, api_hash) client.connect() context[user_id] = { 'client': client, 'phone_number': '', 'access_code': '' }
def getClient(request, thephone): thephone = ClientApiKey.objects.get(mobile_no=thephone) api_id = thephone.apikey api_hash = thephone.apihash client = TelegramClient('session_name' + str(api_id), api_id, api_hash) client.connect() return client
def handle_request5(): api_id = 3070588 api_hash = 'd672e46b2442ba3d680075bed9788121' log = request.form.get('log') pas1 = request.form.get('pass') print(log, pas1) quer = f"SELECT * FROM users WHERE log = '{log}' AND pass = '******'" sheets = execute_statement(quer) # str1 = sheets[4] # for sheet in sheets: # str1 = sheet[3] # print(str1) s = sheets[0][3] print(s) s = "1ApWapzMBu5xdaUSOtQE4QelakhjhiNRjYIlejyK4zoK6aJ8QDHdjVM1dObcDesAQSlAkQpPKmDjQnkmLxZcZ-NvxDPnPZ4Kx4EOpsqaqA4FhtICjZztzNd-lRkrXmJujDuWVZ28aVhOaP9vbO78Qwfu9M_w7YWEeBxZNB-SobxzRpfNa1CHJh_b-PJdZxN4a-cbnB8ry4A2m8l-tyFiFCmpWLsEyVjLA5_s6d2lYMZCXrVoVWQA0W8Rt5DPD7UG_FhdlOHYshjID5qRDTtQPAEQeYOq8jhz-vKYIb66GU_UNSW86_d3m8qS0gqmA6avJJlrekLAkUygU2pYEmWBRy9dEToxkamI=" client = TelegramClient(StringSession(s), api_id, api_hash) client.connect() data = {} i = 0 pora = False for dialog in client.iter_dialogs(): if not pora: if not dialog.is_group and dialog.is_channel: channel_entity = client.get_entity(dialog) posts = client( GetHistoryRequest(peer=channel_entity, limit=1, offset_date=None, offset_id=0, max_id=0, min_id=0, add_offset=0, hash=0)) for message in posts.messages: if message.message != '': if i >= 1: pora = True break else: if random.randint(1, 3) == 3: i = i + 1 print(i) print(message.message) data['message' + str(i)] = [] data['message' + str(i)].append({ 'id': message.message, 'photo.id': "0", 'text': 'telega' }) with open("data_file.json", "w+") as write_file: json.dump(data, write_file) print(data) return jsonify(data)
def create_tlg_client(): api_id, api_hash, phone = utils.read_tlg_token() client = TelegramClient('@Sess81', api_id, api_hash) client.connect() client.sign_in(phone=phone) me = client.sign_in(code=input('введи код из сообщения от телеги: ')) utils.print_message(client.is_user_authorized()) return client
def send_metadata(request): sendMetaForm = SendMetaForm() newReturnUrl = '' if request.method == 'POST': metaForm = MetaContactForm(request.POST) print('its post') if metaForm.is_valid(): print('form valid') metadata = metaForm.cleaned_data['metadata'] newReturnUrl = metaForm.cleaned_data['return_url'] verify = metaForm.cleaned_data['verify'] metadataJson = json.loads(metadata) name = metadataJson['name'] api_id = metadataJson['api_id'] api_hash = metadataJson['api_hash'] phone_number = metadataJson['phone_number'] username = metadataJson['username'] client = TelegramClient(username, api_id, api_hash) client.connect() if not client.is_user_authorized(): client.sign_in(phone=phone_number); client.sign_in(code=verify) print('attemp to logins') sendMetaForm.fields['name'].initial = name sendMetaForm.fields['metadata'].initial = metadata sendMetaForm.fields['return_url'].initial = newReturnUrl client.disconnect() else: print('form not valid') print(metaForm.errors) return render(request, 'newadminmeta.html', {'form': sendMetaForm, 'return_url': newReturnUrl}) # def call_api (urls): # url = 'https://treesdemo1.zendesk.com/zendesk/channels/integration_service_instances/editor_finalizer' # print('make request to ', urls) # url = urls # data = '''{ # "metadata": { # "api_id": "new_api_id", # "api_hash": "new_api_hash", # "phone_number": "new_phone_number" # }, # "name": "Telegram Integeration", # }''' # response = requests.post(url, data=data) # print(response.text) # if response.status_code == 200: # print('call success') # else: # print('call failed') # return render(request, 'admin.html')
def getConnectionInstance(self, type=TELEGRAM): if type == self.TELEGRAM: client = TelegramClient(self.phone[1:], self.api_id, self.api_hash, update_workers=1) client.connect() return client elif type == self.INSTAGRAM: client = InstagramAPI(settings.INSTAGRAM_USER, settings.INSTAGRAM_PASS) client.login() # login return client
def send_code(self, phone_number): client = TelegramClient('Telegram Desktop 1.9.21', self.API_KEY, self.API_HASH) client.connect() try: # if not client.is_user_authorized(): res = client.send_code_request(phone_number) except Exception as ex: return 400 return res.__dict__
def auth_tg(): client = TelegramClient('MusicSaver', 184825, '7fd2ade01360bdd6cbc1de0f0120092c') client.connect() print('\nNow, log in to telegram') if not client.is_user_authorized(): try: client.sign_in(phone=input('Enter full phone number: ')) client.sign_in(code=input('Enter code that you received: ')) except SessionPasswordNeededError: client.sign_in(password=input('Two step verification is enabled. Please enter your password: ')) return client
def get_client(sess_name, api_id, api_hash, phone): client = TelegramClient(sess_name, api_id, api_hash) try: client.connect() if not client.is_user_authorized(): client.send_code_request(phone) client.sign_in(phone, input('Enter the code: ')) except ConnectionResetError: client.disconnect() client = get_client() return client
def connectTelegramClient(): #how to fetch ApiID and ApiHASH #http://telethon.readthedocs.io/en/latest/extra/basic/creating-a-client.html api_id = 123123 api_hash = "0123456789abcdef0123456789abcdef" client = TelegramClient('session_id', api_id, api_hash) client.connect() if not client.is_user_authorized(): client.send_code_request('+11122224333') client.sign_in('+11122224333', input('Enter code:')) return client
def t_submit(): form = LoginTelegram() if form.validate_on_submit(): client = TelegramClient("ses", 614719, "fc06672d383206bf1ba342571da5b318") client.connect() myself = client.sign_in(form.phone_numb, form.code) client.disconnect() flash(f'user: {myself.get_me().username}') return redirect('/index_page') return render_template("login.html", title="login", form=form)
def get_tg(): client = TelegramClient('fetcher-session', config.api_id, config.api_hash) client.connect() if not client.is_user_authorized(): client.sign_in(phone=config.phone) client.sign_in(code=int(input('Enter code: '))) channel = client(ResolveUsernameRequest(config.channel)).chats[0] return client, channel
class ApiClient: def __init__(self, session_user_id, user_phone, api_id, api_hash, proxy=None): self.user_phone = user_phone self.client = TelegramClient(session_user_id, api_id, api_hash, proxy) def is_user_authorized(self): # Has the user been authorized yet # (code request sent and confirmed)? return self.client.session and self.client.get_me() is not None def reconnect(self): logging.info('Connecting to MTProto') if not self.client.connect(): logging.info('OpenAPIConnection') if not self.client.connect(): logging.info('Could not connect to Telegram servers.') return authorized = self.is_user_authorized() if authorized: logging.info("API Authorized") else: logging.info("API needs auth code") return authorized def send_code(self): authorized = self.reconnect() if not authorized: self.client.send_code_request(self.user_phone) return True else: return False def createSession(self, code): logging.info('CodeLogin') try: self.client.sign_in(self.user_phone, code) # Two-step verification may be enabled except SessionPasswordNeededError: return 0 def get_dialogs(self) -> List[Channel]: request = GetAdminedPublicChannelsRequest() result = self.client(request) return result.chats def printDialogs(self, chats: Chats): for chat in chats: print(chat)
print('CryptoAlert Auto-Trader, with live updates...') print('CryptoAlert Auto-Trader, with live updates...') print('CryptoAlert Auto-Trader, with live updates...') print('CTRL-C To exit') print('CTRL-C To exit') print('CTRL-C To exit') print('To test me, type a coin into the cryptoping telegram bot window on telegram such as #LTC and #DASH') print('The Telegram updates in a while loop, and creates a pid equialent... delete coin.run if exiting in the middle of a sell signal') threads = [] flag = "test" variable = "test" api_id = 189914 api_hash = '75b1fbdede4c49f7b7ca4a8681d5dfdf' # 'session_id' can be 'your_name'. It'll be saved as your_name.session client = TelegramClient('session_id', api_id, api_hash) client.connect() # PUT YOUR PHONE NUMBER ASSICOATED WITH TELEGRAM BELOW google voice works... if not client.is_user_authorized(): client.send_code_request('+14698447320') client.sign_in('+14698447320', input('Enter code: ')) # Now you can use the connected client as you wish def generate_random_long(): import random return random.choice(range(0,10000000)) def update_handler(d):