def init_telegram(): t = Telegram(api_id=app_config.app_id, api_hash=app_config.api_hash, phone=app_config.phone, database_encryption_key=app_config.database_encryption_key, tdlib_verbosity=app_config.tdlib_verbosity) t.login() chats = t.get_chats() chats.wait() return t
def login(): """ This function creates and authenticates Telegram client and calls the call_back with Telegram client, phone no and chat id as arguments. """ (ph_no, chat_id, bup_folders) = load_data() tg_client = Telegram(api_id=API_ID, api_hash=API_HASH, files_directory=FILES_DIR, database_encryption_key=DATABASE_ENCRYPTION_KEY, tdlib_verbosity=0, phone=ph_no) tg_client.call_method( "setTdlibParameters", { "use_file_database": True, "use_chat_info_database": True, "use_message_database": True, "application_version": VERSION }, ) if chat_id is None: print("A code has been sent to you via telegram.") try_login_with_code(tg_client) if chat_id is None: chat_id = get_chat_id(tg_client, ph_no, bup_folders) if confirm("Do you want to load previously backed-up file list?"): print("Getting file list, this might take some time...") tg_client.get_chats().wait() return tg_client, chat_id, bup_folders
class TgClient(object): logger = logging.getLogger(__name__) def __init__(self, phone: str, files_directory: str = None) -> None: assert phone.startswith( '+'), f'the phone number must have a "+" prefix, had {phone}' self.logger.debug(f'Login as {phone}') self.tg = Telegram( api_id='94575', api_hash='a3406de8d171bb422bb6ddf3bbd800e2', phone=phone, files_directory=files_directory, database_encryption_key='dfaafaad2972d7636bf277ab', ) self.results = {} self.tg.add_update_handler('updateFile', self._update_file_handler) self.tg.add_update_handler('updateMessageSendSucceeded', self._update_message_send_succeeded_handler) self.tg.login() def _update_file_handler(self, update): expected_size = update["file"]["expected_size"] uploaded_size = update["file"]["remote"]["uploaded_size"] if not expected_size: return print('uploaded {:.0f} MB of {:.0f} MB ({:.01f}%)'.format( uploaded_size / 1024 / 1024, expected_size / 1024 / 1024, uploaded_size * 100 / expected_size), end='\r') def _update_message_send_succeeded_handler(self, update): self.logger.debug( 'Message {} sent successfully. New message id {}'.format( update['old_message_id'], update['message']['id'])) self.results[update['old_message_id']] = update def upload_video( self, path: str, chat_id: int, thumb_path: str = None, thumb_width: int = 0, thumb_height: int = 0, duration: int = 0, width: int = 0, height: int = 0, caption: str = None, supports_streaming: bool = False, ) -> str: args = list(map(lambda t: f'{t[0]}: {t[1]}', locals().items())) self.logger.debug('Updating chat list') result = self.tg.get_chats() result.wait() self.logger.debug('Sending {}'.format(', '.join(args[1:]))) content = { '@type': 'inputMessageVideo', 'video': { '@type': 'inputFileLocal', 'path': path, }, 'duration': duration, 'width': width, 'height': height, 'supports_streaming': supports_streaming, } if thumb_path: content['thumbnail'] = { '@type': 'inputThumbnail', 'thumbnail': { '@type': 'inputFileLocal', 'path': thumb_path, }, 'width': thumb_width, 'height': thumb_height, } if caption: content['caption'] = { '@type': 'formattedText', 'text': caption, } data = { '@type': 'sendMessage', 'chat_id': chat_id, 'input_message_content': content, } result = self.tg._send_data(data) result.wait() if result.error: self.logger.error( f'ok_received: {result.ok_received}, error_info: {result.error_info}, update: {result.update}' ) message_id = result.update['id'] self.logger.debug(f'Awaiting message {message_id} to be sent') while message_id not in self.results: time.sleep(0.1) return self.results[message_id]['message']['content']['video'][ 'video']['remote']['id']
parser.add_argument('user_id', help='User ID to call') parser.add_argument('dbkey', help='Database encryption key') args = parser.parse_args() tg = Telegram(api_id=args.api_id, api_hash=args.api_hash, phone=args.phone, td_verbosity=5, files_directory=os.path.expanduser("~/.telegram/" + args.phone), database_encryption_key=args.dbkey) tg.login() # if this is the first run, library needs to preload all chats # otherwise the message will not be sent r = tg.get_chats() r.wait() r = tg.call_method( 'createCall', { 'user_id': args.user_id, 'protocol': { 'udp_p2p': True, 'udp_reflector': True, 'min_layer': 65, 'max_layer': 65 } }) r.wait() outgoing = r.update
parser.add_argument('chat_id', help='Chat id', type=int) parser.add_argument('text', help='Message text') args = parser.parse_args() tg = Telegram( api_id=args.api_id, api_hash=args.api_hash, phone=args.phone, database_encryption_key='changeme1234', ) # you must call login method before others tg.login() # if this is the first run, library needs to preload all chats # otherwise the message will not be sent result = tg.get_chats() # `tdlib` is asynchronous, so `python-telegram` always returns you an `AsyncResult` object. # You can wait for a result with the blocking `wait` method. result.wait() if result.error: print(f'get chats error: {result.error_info}') else: print(f'chats: {result.update}') result = tg.send_message( chat_id=args.chat_id, text=args.text, )
def _sendMessage(self, telegram_text): telegram_api_id = self.config.get("telegram_api_id", None) if telegram_api_id is None: raise self.server.error("telegram_api_id not configured!") telegram_api_hash = self.config.get("telegram_api_hash", None) if telegram_api_hash is None: raise self.server.error("telegram_api_hash not configured!") telegram_bot_token = self.config.get("telegram_bot_token", None) if telegram_bot_token is None: raise self.server.error("telegram_bot_token not configured!") telegram_database_encryption_key = self.config.get( "telegram_database_encryption_key", None) if telegram_database_encryption_key is None: raise self.server.error( "telegram_database_encryption_key not configured!") telegram_chat_id = self.config.get("telegram_chat_id", None) if telegram_chat_id is None: raise self.server.error("telegram_chat_id not configured!") telegram_code = self.config.get("telegram_code", None) if telegram_code is None: raise self.server.error("telegram_code not configured!") telegram_password = self.config.get("telegram_password", None) if telegram_password is None: raise self.server.error("telegram_password not configured!") try: logging.info(f"Login to telegram") tg = Telegram( api_id=telegram_api_id, api_hash=telegram_api_hash, phone=telegram_bot_token, # you can pass 'bot_token' instead database_encryption_key=telegram_database_encryption_key) state = tg.login(blocking=False) if state == AuthorizationState.WAIT_CODE: # Telegram expects a pin code tg.send_code(telegram_code) state = tg.login(blocking=False) # continue the login process if state == AuthorizationState.WAIT_PASSWORD: tg.send_password(telegram_password) state = tg.login(blocking=False) # continue the login process if state != AuthorizationState.READY: raise self.server.error( f"Error at the telegram login. Authorization state: {tg.authorization_state}" ) logging.info(f"Loading chats") # if this is the first run, library needs to preload all chats # otherwise the message will not be sent result = tg.get_chats() result.wait() logging.info(f"Sending message: to chat {telegram_chat_id}") result = tg.send_message( chat_id=telegram_chat_id, text=telegram_text, ) # `tdlib` is asynchronous, so `python-telegram` always returns you an `AsyncResult` object. # You can receive a result with the `wait` method of this object. result.wait() logging.info(result.update) tg.stop() # you must call `stop` at the end of the script except Exception as e: logging.error("Error: unable to send message to channel", e)
message_id = update['message']['id'] # We want to process only messages from specific channel if message_chat_id != src_chat: return # Check if message is forwarded if 'forward_info' in update['message']: copy_message(message_chat_id, message_id, False) else: copy_message(message_chat_id, message_id) if __name__ == "__main__": tg.login() result = tg.get_chats() result = tg.get_chats(9223372036854775807) # const 2^62-1: from the first result.wait() chats = result.update['chat_ids'] for chat_id in chats: r = tg.get_chat(chat_id) r.wait() title = r.update['title'] print(f"{chat_id}, {title}") if (src_chat is None or dst_chat is None): print("\nPlease enter SOURCE and DESTINATION in .env file") exit(1) else: src_chat = int(src_chat)
for sender_user_id in sender_user_ids: user_ids.add(sender_user_id) if len(messages) == 0 or ( last_message_id > 0 and last_stored_message_id > last_message_id): break else: last_message_id = messages[len(messages) - 1]['id'] print('Total fetched for chat_id=', chat_id, count, 'messages') fetch_and_store_users(list(user_ids)) # import datetime # message = {'id':11647582208, 'date': datetime.datetime.fromisoformat("2020-03-05 21:38:35").timestamp(), # 'chat_id':-1001198134786, 'sender_user_id': 574136325, 'content': # {'@type':'messageText', 'text': { 'text': """Арнольд Шварценеггер подал в суд на российскую компанию. Она создала робота-няню с его лицом 🤖 — Meduza # https://meduza.io/shapito/2020/03/05/arnold-shvartsenegger-podal-v-sud-na-rossiyskuyu-kompaniyu-ona-sozdala-robota-nyanyu-s-ego-litsom"""} } } # # db.store_message(message) tg.login() chats_result = tg.get_chats(offset_order=9223372036854775807) chats_result.wait() chat_ids = chats_result.update['chat_ids'] chats = fetch_and_store_chats(chat_ids) chats = get_chats_by_titles(chats, config['chats']) chat_ids = list(map(lambda chat: chat['id'], chats)) fetch_and_store_chats_history(chat_ids)