diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..a6c849b --- /dev/null +++ b/.gitignore @@ -0,0 +1,4 @@ +# Output file +*.json +# Ini file with privat info +*.ini diff --git a/README.md b/README.md index 35b9b7e..0e88d48 100644 --- a/README.md +++ b/README.md @@ -1 +1,22 @@ -# nodear \ No newline at end of file +# nodear + + +https://github.com/thedemons/opentele/pull/74/files + + https://my.telegram.org/apps username + +``` +[Telegram] +api_id = 12345678 +api_hash = 999e888777ab66bf555cb44aa33a220f +username = telethon +``` + telegram . + ```python open_tele.py``` + %USERPROFILE%\AppData\Roaming\Telegram Desktop\tdata telethon.session + + ```python tele_reader.py``` + + , : + : + diff --git a/open_tele.py b/open_tele.py new file mode 100644 index 0000000..1b4836c --- /dev/null +++ b/open_tele.py @@ -0,0 +1,28 @@ +from opentele.td import TDesktop +from opentele.tl import TelegramClient +from opentele.api import API, CreateNewSession, UseCurrentSession +import asyncio +import os + +async def main(): + + # Load TDesktop client from tdata folder + userprofile = os.environ["USERPROFILE"] + tdataFolder = userprofile + "\\AppData\\Roaming\\Telegram Desktop\\tdata" + tdesk = TDesktop(tdataFolder) + + + # Check if we have loaded any accounts + assert tdesk.isLoaded() + + # flag=UseCurrentSession + # + # Convert TDesktop to Telethon using the current session. + client = await tdesk.ToTelethon(session="telethon.session", flag=UseCurrentSession) + + # Connect and print all logged-in sessions of this client. + # Telethon will save the session to telethon.session on creation. + await client.connect() + await client.PrintSessions() + +asyncio.run(main()) diff --git a/tele_reader.py b/tele_reader.py new file mode 100644 index 0000000..de6057b --- /dev/null +++ b/tele_reader.py @@ -0,0 +1,110 @@ +import configparser +import json + +from telethon.sync import TelegramClient +from telethon import connection + +# для корректного переноса времени сообщений в json +from datetime import date, datetime + +# классы для работы с каналами +from telethon.tl.functions.channels import GetParticipantsRequest +from telethon.tl.types import ChannelParticipantsSearch + +# класс для работы с сообщениями +from telethon.tl.functions.messages import GetHistoryRequest + +# Считываем учетные данные +config = configparser.ConfigParser() +config.read("config.ini") + +# Присваиваем значения внутренним переменным +api_id = config['Telegram']['api_id'] +api_hash = config['Telegram']['api_hash'] +username = config['Telegram']['username'] + +#proxy = (proxy_server, proxy_port, proxy_key) + +client = TelegramClient(username, api_id, api_hash) + +client.start() + + +async def dump_all_participants(channel): + """Записывает json-файл с информацией о всех участниках канала/чата""" + offset_user = 0 # номер участника, с которого начинается считывание + limit_user = 100 # максимальное число записей, передаваемых за один раз + + all_participants = [] # список всех участников канала + filter_user = ChannelParticipantsSearch('') + + while True: + participants = await client(GetParticipantsRequest(channel, + filter_user, offset_user, limit_user, hash=0)) + if not participants.users: + break + all_participants.extend(participants.users) + offset_user += len(participants.users) + + all_users_details = [] # список словарей с интересующими параметрами участников канала + + for participant in all_participants: + all_users_details.append({"id": participant.id, + "first_name": participant.first_name, + "last_name": participant.last_name, + "user": participant.username, + "phone": participant.phone, + "is_bot": participant.bot}) + + with open('channel_users.json', 'w', encoding='utf8') as outfile: + json.dump(all_users_details, outfile, ensure_ascii=False) + + +async def dump_all_messages(channel): + """Записывает json-файл с информацией о всех сообщениях канала/чата""" + offset_msg = 0 # номер записи, с которой начинается считывание + limit_msg = 100 # максимальное число записей, передаваемых за один раз + + all_messages = [] # список всех сообщений + total_messages = 0 + total_count_limit = 0 # поменяйте это значение, если вам нужны не все сообщения + + class DateTimeEncoder(json.JSONEncoder): + '''Класс для сериализации записи дат в JSON''' + def default(self, o): + if isinstance(o, datetime): + return o.isoformat() + if isinstance(o, bytes): + return list(o) + return json.JSONEncoder.default(self, o) + + while True: + history = await client(GetHistoryRequest( + peer=channel, + offset_id=offset_msg, + offset_date=None, add_offset=0, + limit=limit_msg, max_id=0, min_id=0, + hash=0)) + if not history.messages: + break + messages = history.messages + for message in messages: + all_messages.append(message.to_dict()) + offset_msg = messages[len(messages) - 1].id + total_messages = len(all_messages) + if total_count_limit != 0 and total_messages >= total_count_limit: + break + + with open('channel_messages.json', 'w', encoding='utf8') as outfile: + json.dump(all_messages, outfile, ensure_ascii=False, cls=DateTimeEncoder) + + +async def main(): + url = input("Введите ссылку на канал или чат: ") + channel = await client.get_entity(url) + #await dump_all_participants(channel) + await dump_all_messages(channel) + +with client: + client.loop.run_until_complete(main()) + \ No newline at end of file diff --git a/telethon.session b/telethon.session new file mode 100644 index 0000000..15ae8d7 Binary files /dev/null and b/telethon.session differ