def getMessages(request, user): app = Client("my_account", api_id=255229, api_hash="97eaaf0eed893b617612bf74d39b6a1d") target = user # "me" refers to your own chat (Saved Messages) messages = [] # List that will contain all the messages of the target chat offset_id = 0 # ID of the last message of the chunk app.start() while True: try: m = app.get_history(target, offset_id=offset_id, limit=10) except FloodWait as e: # For very large chats the method call can raise a FloodWait print("waiting {}".format(e.x)) time.sleep(e.x) # Sleep X seconds before continuing continue if not m.messages: break messages += m.messages offset_id = m.messages[-1].message_id app.stop() return HttpResponse(messages)
class TelegramClient: def __init__(self): api_id = os.getenv("API_ID") api_hash = os.getenv("API_HASH") session = os.getenv("TG_SESSION") self.client = Client(session, api_id, api_hash) self.client.start() self.wait = lambda: sleep(3) def send(self, chat_id, message): self.client.send_message(chat_id, message) def receive(self, chat_id): self.wait() return self.client.get_history(chat_id, limit=1)
def get_code(): app = Client( phone_number.strip('+'), api_id, api_hash, phone_number=phone_number, phone_code=phone_code_callback, workdir='tmp', ) app.start() if DEBUG: for dialog in app.get_dialogs().dialogs: if dialog.chat.first_name == 'Telegram': print(dialog.chat.id, dialog.chat.type, [ dialog.chat.title, dialog.chat.username, dialog.chat.first_name ]) print('\t', dialog.top_message.message_id, dialog.top_message.date, dialog.top_message.text) ret = app.get_history(777000, limit=10) for message in ret.messages: m = re.search( r'(?:Код подтверждения|Login code|Your login code): (\d+)', message.text) if m: code = m.group(1) ret = { 'message_id': message.message_id, 'date': message.date, 'first_name': message.from_user.first_name, 'text': message.text, 'code': code, } print(str(ret)) app.stop() print('---END---') os._exit(0)
else: words = word + key print('набираемое сообщение:', words) app.start() #_____sendmessage_______ smsuser = input("username/1351754478: ") if smsuser == 'me': smguser = '******' if smsuser[:1] == '@': smguser = smsuser[1:] else: smguser = int(smsuser) print(app.get_history(smguser, 0, 1)) #print(app.get_chat(smguser)) us = smguser out_thread = threading.Thread(target=catcher(us)) my_thread = threading.Thread(target=inmess(smguser)) my_thread.start() out_thread.start() #catcher(us) #smgtext=input("message: ") #print(smgtext) #app.send_message(smguser,smgtext) #b=int(input("b не больше 3="))
def main(scan_chats): app_config = load_yaml("app_config.yml") n_workers = len(app_config['api_keys']) local_rank = get_local_rank(n_workers) args = Args(app_config, local_rank) app = Client( session_name=args.session_name, phone_code=args.phone_code, phone_number=args.phone, api_hash=args.api_hash, api_id=args.api_id, workdir=args.workdir_path ) dirname = args.base_dir unknown_exceptions_count = 0 if type(scan_chats) is not list: scan_chats = [scan_chats] total_chats = len(scan_chats) exit = False with app: for current, target in enumerate(scan_chats): if exit: break print(f"worker [{local_rank}]: begins processing [{target}]") save_result_path = os.path.join(dirname, args.data_dir, "{}.json".format(target)) if os.path.exists(save_result_path): with open(save_result_path, "r") as fi: messages = json.load(fi) offset_id = min(get_message_ids(messages)) print(f"worker [{local_rank}]: loaded [{len(messages)}] samples, " f"proceeding from message_id [{offset_id}]") else: messages = [] offset_id = 0 while True: chat_history = [] unknown_exceptions_count = 0 try: chat_history = app.get_history(target, offset_id=offset_id) chat_history = chat_history[::-1] time.sleep(args.delay) except UsernameNotOccupied as e: print(f"worker [{local_rank}]: chat [{target}] does not exist, skipping .") break except Exception as e: print(f"worker [{local_rank}]: unknown exception [{e}], waiting 60 seconds .") unknown_exceptions_count += 1 time.sleep(60) continue except KeyboardInterrupt: print(f"worker [{local_rank}]: caught KeyboardInterrupt, saving and exiting .") exit = True break if len(chat_history) == 0: print(f"worker [{local_rank}]: finished processing [{target}]") break try: mids = get_message_ids(chat_history) offset_id = min(mids) messages += map(message_to_dict, chat_history) total = len(set(get_message_ids(messages))) if not total%args.print_every: print(f"worker [{local_rank}]: got [{total}] messages @ offset [{offset_id}] | " f"@{target} - {current + 1} of {total_chats}") if not total%args.save_every and not exit: save_messages(messages, save_result_path) print(f"worker [{local_rank}]: saving to {save_result_path}") except KeyboardInterrupt: print(f"worker [{local_rank}]: caught KeyboardInterrupt, saving and exiting .") exit = True break if len(chat_history) > 0: save_messages(messages, save_result_path) print(f"worker [{local_rank}]: saving to {save_result_path}")
def do_test(path, chat_id, path_db, num, task_files): for task_file in task_files: TW = TaskWorker() TW.load_config_from_yaml(f'{path}/tasks.d/{task_file}') app = Client(TW.task_name) app.start() for task in TW.tasks: print(TW.tasks) delta = 0 if task.task_type == 'text': app.send_message('AV100_bot', task.command) elif task.task_type == 'call_back': if getattr(task, 'id_msg', False): app.request_callback_answer("AV100_bot", task.id_msg, task.command) else: TW.errors.append( Error(task.description, f'', "Не было найдено сообщение с данной кнопкой", TW.description)) continue elif task.task_type == 'image': app.send_photo('AV100_bot', path + task.command) last_task = task.timeout elif task.task_type == 'result': delta = last_task else: continue command_time = datetime.now().timestamp( ) - 2 # Поправка на милисекунды command_time -= delta # Костыль для проверки ответа на картинку sleep(task.timeout) messages = [] while True: msg = app.get_history("AV100_bot", limit=1, offset=len(messages))[0] if command_time >= msg.date or msg.from_user.is_self: break else: messages.append(msg) if messages: result_flag = False for i, sub_tusk in enumerate(task.messages, 1): try: result = TW.check_task(sub_tusk, messages) except Exception as ex: # print(ex) result = {'status': False, 'alert': 'Упал с ошибкой'} if not result['status']: result_flag = True TW.errors.append( Error(task.description, f'Подзадача №{i}', result['alert'], TW.description)) else: result = { 'status': False, 'alert': 'Ответ не пришел за отведенное время' } TW.errors.append( Error(task.description, '', result['alert'], TW.description)) TW.results.append( Result(task.description, "Провал" if result_flag else "Успех", TW.description)) app.__exit__() conn = sqlite3.connect(path_db) cursor = conn.cursor() for er in TW.errors: cursor.execute( f"""INSERT INTO errors VALUES ('{er.task}', '{er.sub_task}\n{er.alert}', {num}, '{er.description}')""" ) for res in TW.results: cursor.execute( f"""INSERT INTO results VALUES ('{res.task}', '{res.result}', {num}, '{res.description}')""" ) conn.commit() conn.close() for _ in range(3): try: send_message(chat_id, path) break except: sleep(1)
from pyrogram import Client from pyrogram.api.errors import FloodWait """This example shows how to retrieve the full message history of a chat""" app = Client("my_account") target = "me" # "me" refers to your own chat (Saved Messages) messages = [] # List that will contain all the messages of the target chat offset_id = 0 # ID of the last message of the chunk app.start() while True: try: m = app.get_history(target, offset_id=offset_id) except FloodWait as e: # For very large chats the method call can raise a FloodWait print("waiting {}".format(e.x)) time.sleep(e.x) # Sleep X seconds before continuing continue if not m.messages: break messages += m.messages offset_id = m.messages[-1].message_id print("Messages: {}".format(len(messages))) app.stop()
#print(delete_before) for target in targets: app = Client("my_account") messages = [] # List that will contain all the messages of the target chat offset_id = 0 # ID of the last message of the chunk app.start() chat_id = app.get_chat(target).id while True: try: m = app.get_history(chat_id, offset_id=offset_id) except FloodWait as e: # For very large chats the method call can raise a FloodWait print("waiting {}".format(e.x)) time.sleep(e.x) # Sleep X seconds before continuing continue if not m.messages: break messages += m.messages offset_id = m.messages[-1].message_id for message in messages: if (type(message.from_user.username) is str): username = message.from_user.username