Last active
August 14, 2024 23:54
-
-
Save alexandrebl/33f15a7cfd464d0a8a7528124026bd84 to your computer and use it in GitHub Desktop.
Read MEssages from Telegram using Python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import datetime, os | |
| from telethon import TelegramClient, events | |
| from telethon.sync import TelegramClient | |
| # Substitua esses valores pelos seus próprios | |
| api_id = 'API_ID' | |
| api_hash = 'API_HASH' | |
| phone_number = 'PHONE_NUMBER' | |
| client = TelegramClient('session_name', api_id, api_hash) | |
| session_name = 'my_session' | |
| # Inicializa o cliente Telegram | |
| client = TelegramClient(session_name, api_id, api_hash) | |
| async def main(): | |
| # Conecta e autentica o cliente | |
| await client.start(phone_number) | |
| print("Cliente conectado e autenticado.") | |
| # Escuta todas as mensagens recebidas | |
| @client.on(events.NewMessage()) | |
| async def handler(event): | |
| # Obtém a mensagem | |
| message = event.message | |
| chat = await message.get_chat() | |
| sender = await message.get_sender() | |
| # Exibe informações sobre a mensagem | |
| print(f"De: {sender.id} ({sender.username})") | |
| print(f"Chat: {chat.id} ({chat.username})") | |
| print(f"Mensagem: {message.text}\n") | |
| now = datetime.datetime.now() | |
| # Formata a data e hora para usar no nome do arquivo | |
| timestamp = now.strftime('%Y-%m-%d_%H-%M-%S') | |
| # Define o nome do arquivo com a data e hora | |
| filename = f'tlmsg_{timestamp}_{chat.id}_{chat.username}.txt' | |
| directory = 'tlmsg' | |
| if not os.path.exists(directory): | |
| os.makedirs(directory) | |
| file_path = os.path.join(directory, filename) | |
| # Cria ou abre o arquivo para escrita | |
| with open(file_path, 'w') as file: | |
| file.write(message.text) | |
| print(f"File name {filename} generated\n") | |
| # Mantém o cliente em execução | |
| print("Escutando novas mensagens...") | |
| await client.run_until_disconnected() | |
| # Executa o cliente | |
| with client: | |
| client.loop.run_until_complete(main()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment