def test_cdn_download(): client = TelegramClient(None, api_id, api_hash) client.session.set_dc(0, '149.154.167.40', 80) assert client.connect() try: phone = '+999662' + str(randint(0, 9999)).zfill(4) client.send_code_request(phone) client.sign_up('22222', 'Test', 'DC') me = client.get_me() data = os.urandom(2 ** 17) client.send_file( me, data, progress_callback=lambda c, t: print('test_cdn_download:uploading {:.2%}...'.format(c/t)) ) msg = client.get_message_history(me)[1][0] out = BytesIO() client.download_media(msg, out) assert sha256(data).digest() == sha256(out.getvalue()).digest() out = BytesIO() client.download_media(msg, out) # Won't redirect assert sha256(data).digest() == sha256(out.getvalue()).digest() client.log_out() finally: client.disconnect()
def upload(filePath, fileName): client = TelegramClient('session_name', api_id, api_hash) client.start() try: client.send_file(bot_username, filePath, caption=fileName, force_document=True) except Exception as e: print(e) else: r = requests.get('https://api.telegram.org/bot' + bot_token + '/getUpdates?offset=-1').json() file_name = r["result"][0]['message']['document']['file_name'] file_id = r["result"][0]['message']['document']['file_id'] ts = r["result"][0]['message']['date'] fname = pathlib.Path(filePath) assert fname.exists( ), f'No such file: {fname}' # check that the file exists upload_date = datetime.utcfromtimestamp(ts).strftime( '%Y-%m-%d %H:%M:%S') created_date = datetime.utcfromtimestamp( fname.stat().st_mtime).strftime('%Y-%m-%d %H:%M:%S') f = open(dir_path + folders[0] + files[0], 'a') info = f"{fileName},{created_date},{upload_date},{file_id}\n" f.write(info) print(f'Uploaded {fileName}') client.disconnect()
def get_participants_hash(api_id: int, api_hash: str, channel_id: int): client = TelegramClient('session_name', api_id, api_hash) try: client.start() return str(client.get_participants(channel_id)) finally: client.disconnect()
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 main(secrets, opts): phone = secrets.get("phone") if phone is None: raise ValueError("No phone.") recipient = secrets.get("address_book", {}).get(opts.to, None) if recipient is None: raise ValueError("No one to send message to.") if opts.msg is None: raise ValueError("No message to send.") credentials = (secrets.get("api_id"), secrets.get("api_hash")) if None in credentials: raise ValueError("Error with API ID or hash.") # Create a Telegram session: client = TelegramClient('session', *credentials) # Connect and build the session: client.start() # When run for the first time, it asks for log in: if not client.is_user_authorized(): client.send_code_request(phone) client.sign_in(phone, input('Enter the code: ')) # Send message: client.send_message(opts.to, opts.msg) # Disconnect the Telegram session: client.disconnect()
def main(): # Create the client and connect client = TelegramClient(username, api_id, api_hash, update_workers=1, spawn_read_thread=False) client.start(phone) @client.on(events.NewMessage(incoming=True)) def _(event): if event.is_private: # print(time.asctime(), '-', event.message) # optionally log time and message # time.sleep(1) # pause for 1 second to rate-limit automatic replies print('Receive message from:', event.message.from_id) event.message.message = ''.join(e for e in event.message.message if e.isalnum()) print(event) for i in received: if i in event.message.message: event.reply(message[received.index(i)]) # print(event) if '幫我' in event.message.message and ( '吃什麼' in event.message.message or '吃啥' in event.message.message or '吃甚麼' in event.message.message): print('有人問吃啥') event.reply(eatWhat[random.randint(0, len(eatWhat))]) print(time.asctime(), '-', 'Auto-replying...') client.idle() client.disconnect() print(time.asctime(), '-', 'Stopped!')
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 handle(): client = TelegramClient("sessions", API_ID, API_KEY) try: client.start() docs = client.get_messages(args.channel, None, filter=InputMessagesFilterDocument) books = filter(filter_by_name, docs) if args.extensions: books = list(filter(filter_by_ext, books)) total = len(books) print("{} books found".format(total)) for i, book in enumerate(books): book_name = get_name(book) if args.action == "list": print(i + 1, book_name) elif args.action == "download": print("Downloading {index} of {total} | {name}".format( index=i + 1, total=total, name=book_name)) book.download_media(args.path + book_name) finally: client.disconnect()
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
class Crawler: def __init__(self, session, api_id, api_hash, rabbitmq_channel): self.client = TelegramClient(session, api_id, api_hash) self.rabbitmq_channel = rabbitmq_channel def start(self): self.rabbitmq_channel.queue_declare('telecrawl_message') self.client.add_event_handler(self._on_message) self.client.start() # keep application alive during event listening try: print('(Press Ctrl+C to stop this)') self.client.run_until_disconnected() finally: self.client.disconnect() @events.register(events.NewMessage(incoming=True, outgoing=False)) async def _on_message(self, event): sender = await event.get_sender() sender_name = utils.get_display_name(sender) message_text = event.text if message_text is not None and message_text != '': payload = {'text': message_text, 'sender': sender_name} print('message from {0}: {1}'.format(payload['sender'], payload['text'])) # publish the message to rabbitmq self.rabbitmq_channel.basic_publish( exchange='', routing_key='telecrawl_message', body=json.dumps(payload))
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 main(): api_id = input('Enter API_ID:') api_hash = input('Enter API_HASH:') client = TelegramClient(api_id, int(api_id), api_hash) client.start() client.disconnect()
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 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 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)
class TelegramDriver: def __init__(self, config, bot_dialog_config): self.config = config self.bot_dialog_config = bot_dialog_config self.client = None self.logger = logging.getLogger() self.updater_telegram_channel = Updater( self.config["crypto-bot"]["token"]) def log_started(self): self.send_to_channel(self.config["crypto-bot"]["channel_id"], self.bot_dialog_config["Start"]) self.send_to_channel(self.config["crypto-bot"]["channel_id"], self.bot_dialog_config["Ready"]) def first_connection(self): self.client.send_code_request( self.config["telegram-api"]["phone_number"]) myself = self.client.sign_in( self.config["telegram-api"]["phone_number"], input('Enter code: ')) self.logger.info(myself.stringify()) def connect(self): self.client = TelegramClient("User", self.config["telegram-api"]["api_id"], self.config["telegram-api"]["api_hash"], update_workers=1, spawn_read_thread=False) self.client.connect() if self.client.is_connected(): if not self.client.is_user_authorized(): self.first_connection() self.logger.info("Client connected to Telegram.") else: self.logger.error("Client not connected") def send_to_channel(self, channel_id, msg): self.updater_telegram_channel.bot.send_message(chat_id=channel_id, text=msg) def add_handler_update(self, callback): self.client.add_update_handler(callback) def call_idle(self): self.client.idle() self.send_to_channel(self.config["crypto-bot"]["channel_id"], self.bot_dialog_config["Stop"]) def disconnect(self): self.client.disconnect()
def tg(): try: client = TelegramClient(listener_session, api_id, api_hash) client.start() except Exception as e: print(str(e)) client.disconnect() else: me = client.get_me() print(me) client.disconnect()
def main(): hero = Hero() client = TelegramClient('autoforest', api_id, api_hash) client.start() main_cycle(client, hero) with client.start(): print('(Press Ctrl+C to stop this)') client.run_until_disconnected() client.disconnect()
def auth(self, request, context): asyncio.set_event_loop(asyncio.new_event_loop()) client = TelegramClient('api/tg_sessions/' + request.uid, api_id, api_hash) client.connect() if request.code == '': response = common_pb2.AuthResponse(data=client.send_code_request(request.phone).__dict__['phone_code_hash']) else: client.sign_in(phone=request.phone, code=request.code, phone_code_hash=request.code_hash) response = common_pb2.AuthResponse(data='Test') client.disconnect() return response
def tg(): api_id = 0 # use app id of telegram account api_hash = '' # use app hash of your telegram account # please change your prefix of session name , and don,t send to anyone session_name = '544dfsdfdhg-4ui-s_htypy_channel' #hardcode channel id channel_id = 0 try: # tg client start # same session would lock the database, nothing can do if this session is in process client = TelegramClient(session_name, api_id, api_hash) client.start() except Exception as e: print(str(e)) else: try: users = [] mychannel = client.get_entity(PeerChannel(channel_id)) start = True total = 0 offset = 0 while start == True or total > 0: channel_members = client( functions.channels.GetParticipantsRequest( channel=mychannel, filter=types.ChannelParticipantsSearch(''), offset=offset, limit=200, hash=0)) offset += 200 start = False total = len(channel_members.participants) users = [] if len(channel_members.participants) > 0: for member in channel_members.participants: if member.__class__.__name__ != 'ChannelParticipantSelf': #print(member) #print(member.user_id) users.append(member.user_id) all_users = client( functions.users.GetUsersRequest(id=users)) for user in all_users: print(user.stringify()) except Exception as e: client.disconnect() print(str(e)) else: client.disconnect()
def send_code_request(account_id): try: account = TelegramAccount.objects.get(pk=account_id) try: random_confirmed_account = random.choice( TelegramAccount.objects.filter(active=True, confirmed=True)) except IndexError: random_confirmed_account = None if random_confirmed_account: api_id, api_hash = random_confirmed_account.api_id, random_confirmed_account.api_hash else: api_id, api_hash = settings.API_ID, settings.API_HASH proxy_settings = (socks.HTTP, settings.PROXY_HOST, settings.PROXY_PORT, True, settings.PROXY_USERNAME + '-session-{}'.format(random.randint(9999, 9999999)), settings.PROXY_PASSWORD) client = TelegramClient(StringSession(), api_id, api_hash, proxy=proxy_settings) client.connect() try: r = client.send_code_request(account.phone_number, force_sms=True) account.phone_code_hash = r.phone_code_hash account.session = client.session.save() account.api_id = api_id account.api_hash = api_hash account.save() client.disconnect() return {'success': True, 'error': None} except PhoneNumberBannedError: return { 'success': False, 'error': _('The used phone number has been ' 'banned from Telegram and cannot ' 'be used anymore.') } except Exception as e: logger.exception(e) return { 'success': False, 'error': _('Error sending code request.') } except Exception as e: logger.exception(e) return {'success': False, 'error': _('Error sending code request.')}
def message(internal_compliments, internal_api_id, internal_api_hash): # Функция отправки сообщения # Инициализируем подключение internal_client = TelegramClient( 'Compliments', internal_api_id, internal_api_hash) # Задаем параметры клиента internal_client.start() # Подключаемся rand_compl = random.choice( internal_compliments ) # Выбираем случайный комплимент из списка отфильтрованных по длине комплиментов internal_client.send_message( sendToUsername, rand_compl) # Отправляем комплимент адресату internal_client.disconnect() # Отключаемся после отправки сообщения print('ОТПРАВЛЕН КОМПЛИМЕНТ: ' + str(rand_compl)) # Сообщаем в
def save_api_config(): """Function that runs a little _installer_ INCOMPLETE""" if os.geteuid() != 0: os.chdir(system_config.SYNC_INSTALLATION_FOLDER+"src/") print("Go to https://my.telegram.org/ for activating an application and get an api id and an api hash") save_api_id() save_api_hash() api_id = api_config.get_api_id() api_hash = api_config.get_hash_id() client = TelegramClient("TeleSync", api_id, api_hash) client.start() client.disconnect() else: sys.stderr.write("Called as root, insecure, exiting.\nCall it without root permissions.\n")
def t_login(): form = LoginTelegram() tel_numb = '' if form.phone_numb: client = TelegramClient("ses", 614719, "fc06672d383206bf1ba342571da5b318") client.connect() client.send_code_request(form.phone_numb) client.disconnect() tel_numb = form.phone_numb return render_template("login.html", title="login", form=form, tel_numb=tel_numb)
class Client(): def __init__(self, phone, api_id, api_hash): self.phone = phone self.api_id = api_id self.available = True self.client = TelegramClient(phone, api_id, api_hash) self.client.connect() if not self.client.is_user_authorized(): self.client.send_code_request(phone) self.client.sign_in(phone, input('Enter the code: ')) self.client.disconnect() def send_message(self, participant, message): try: self.client.connect() self.client.send_message(participant.id, message) self.client.disconnect() except FloodWaitError: self.available = False except PeerFloodError: self.available = False except: self.client.disconnect() def send_messages(self, participant, messages, tempo): self.client.connect() for message in messages: self.client.invoke( SendMessageRequest(self.client.get_input_entity(participant), message)) #self.client.send_message(participant.id, message) time.sleep(tempo) self.client.disconnect() def connect(self): self.client.connect() def disconnect(self): self.client.disconnect() def is_available(self): return self.available def get_entity(self, entity): return self.client.get_entity(entity) def invoke(self, request): return self.client.invoke(request)
async def main(): if not config.followers: logging.error('Please edit the config') exit(1) print('''Welcome! Please input your API ID and Hash. What is an API ID/Hash? i cannot bother explaining, and for what? How do I get them? Go to https://me.telegram.org Log in 'API Development Tools' Enter anything you like for Application Name and Short Name and Platform There you go :) **DON"T SHARE YOUR API HASH TO ANYONE**''') api_id = int(input('API ID: ')) api_hash = input('API Hash: ') fwlrs = [] for i in config.followers: clients.info( 'Testing client %s, if it asks for your phone number please login', i.name) client = TelegramClient(i.session_path, api_id, api_hash, base_logger=i.name) await client.start() fwlrs.append(client) await asyncio.wait([client.disconnect() for client in fwlrs])
class Main(): def __init__(self, config): self.simulator = Simulator() self.teleClient = TelegramClient(config['API_NAME'], config['API_ID'], config['API_HASH']) self.teleClient.start() ZaraBot(self.teleClient, config['CLICK_CHANNEL']['TGZaraBot'], self.simulator) ClickBot(self.teleClient, config['CLICK_CHANNEL']['click_bot'], self.simulator) print('sleep 1h') time.sleep(3600) def __del__(self): print("Close connection") self.teleClient.disconnect()
def userbot(): """ Launch the userbot for the duration of the tests. The fixture above makes the userbot available to all the tests via the name "userbot" """ # Start a bot so the userbot has someone to talk to bot = subprocess.Popen([ 'python', '-W', 'ignore', os.path.join(local_settings.ROOT_DIR, 'core.py') ]) client = TelegramClient('telethon', local_settings.API_ID, local_settings.API_HASH).start() yield client # Disconnect the userbot when all the tests are run client.disconnect() # Stop the bot bot.kill()
def main(): # Create the client and connect client = TelegramClient(username, api_id, api_hash, update_workers=1, spawn_read_thread=False) client.start(phone, password) @client.on(events.NewMessage(incoming=True)) def _(event): if event.is_private: # from_id is the id of the bot # to check the id you can print(event.message.from_id) and get a message in the chat # so you will have the id of that conversation # CHANGE 123456789 WITH THE BOT BTC FAUCET FROM_ID if event.message.from_id == 123456789: if "balance" in event.message.message: # it prints the balance in console print(event.message.message[event.message.message. index("balance"):]) time.sleep( 29) # pause for 29 second to rate-limit automatic replies # it sends the message after time.sleep() client.send_message(event.message.from_id, message) # it prints the sending time print('Sent...', time.asctime()) # your from_id, the id of the conversation with yourself # used to turn off the script from a telegram client # CHANGE 123456789 WITH YOUR FROM_ID elif event.message.from_id == 123456789: # check if the message sent is equals to "TURNOFFTHESCRIPT" if (event.is_private and event.message.message == "TURNOFFTHESCRIPT"): newmessage = "Ok Boss, turning off!" # it sends the message client.send_message(event.message.from_id, newmessage) # disconnect the client client.disconnect() print(time.asctime(), '-', 'Auto-replying...') client.idle() client.disconnect() print(time.asctime(), '-', 'Stopped!')
def run_main(mainf): """Function for running the main function Args: mainf (Function): async main function that receives as parameter the client """ # Changing root dir to the source dir os.chdir(system_config.SYNC_INSTALLATION_FOLDER+"src/") # Retrieving api_id and api_hash api_id = api_config.get_api_id() api_hash = api_config.get_hash_id() # Creating and starting the client client = TelegramClient('TeleSync', api_id, api_hash) client.start() client.loop.run_until_complete(mainf(client)) client.disconnect()
global variable variable=str(variable) variablestr=str(variable) print('Starting Trade of: ' + variablestr) process0='./zenbot.sh trade poloniex.' + variablestr subprocess.Popen(process0,shell=True) time.sleep(3600) print('Starting node kill process) process1='sudo killall node' subprocess.Popen(process1,shell=True) print('Starting final sell Of:' + variablestr + ' In Case of Error') process2='./zenbot.sh sell --order_adjust_time=1000000000 --sell_pct=100 --markup_pct=0 poloniex.' + variablestr proc2 = subprocess.Popen(process2,shell=True) proc2.communicate() print('Starting final sell Of:' + variablestr + ' In Case of Error') process3='./zenbot.sh sell --order_adjust_time=1000000000 --sell_pct=100 --markup_pct=0 poloniex.' + variablestr proc3 = subprocess.Popen(process3,shell=True) proc3.communicate() os.remove(pid) print('Done running loop, process file deleted. Waiting for another coin...') # From now on, any update received will be passed to 'update_handler' NOTE... Later, Zenbot will be modified to cancel on order adjust. while True: client.add_update_handler(update_handler) input('Press <ENTER> to exit...') client.disconnect()