-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTelegramCode.html
143 lines (122 loc) · 5.72 KB
/
TelegramCode.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
<head>
<title>
Telegram Python Code
</title>
<link rel="stylesheet"
href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/10.0.3/styles/default.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/10.0.3/highlight.min.js"></script>
<script>hljs.initHighlightingOnLoad();</script>
</head>
<body>
<h1>The code for the Telegram function:</h1>
<pre><code class="python">
# Create function to extract data from Telegram channel
def telegram():
# some functions to parse json date
class DateTimeEncoder(json.JSONEncoder):
def default(self, o):
if isinstance(o, datetime):
return o.isoformat()
if isinstance(o, bytes):
return list(o)
return json.JSONEncoder.default(self, o)
# Reading Configs
config = configparser.ConfigParser()
config.read("/Users/emansarahafi/Downloads/Telegram Files for Project/config.ini")
# Setting configuration values
api_id = config['Telegram']['api_id']
api_hash = config['Telegram']['api_hash']
api_hash = str(api_hash)
phone = config['Telegram']['phone']
username = config['Telegram']['username']
# Create the client and connect
client = TelegramClient(username, api_id, api_hash)
async def main(phone):
await client.start()
print("Client Created")
me = await client.get_me()
my_channel = await client.get_entity('Survey2022Channel')
messages = await client.get_messages('Survey2022Channel')
message = messages[0]
textmsg = print(message.raw_text) # raw_text for no formatting
# For Users
offset = 0
limit = 100
all_participants = []
while True:
participants = await client(GetParticipantsRequest(
my_channel, ChannelParticipantsSearch(''), offset, limit,
hash = 0
))
if not participants.users:
break
all_participants.extend(participants.users)
offset += len(participants.users)
all_user_details = []
for participant in all_participants:
all_user_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('user_data.json', 'w') as outfile:
json.dump(all_user_details, outfile)
# For Messages
offset_id = 0
limit = 100
all_messages = []
total_messages = 0
total_count_limit = 0
while True:
print("Current Offset ID is:", offset_id, "; Total Messages:", total_messages)
history = await client(GetHistoryRequest(
peer = my_channel,
offset_id = offset_id,
offset_date = None,
add_offset = 0,
limit = limit,
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_id = 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') as outfile:
json.dump(all_messages, outfile, cls = DateTimeEncoder)
# Convert JSON file to TXT
filename = "/Users/emansarahafi/Downloads/Telegram Files for Project/channel_messages.json"
if os.path.exists("/Users/emansarahafi/Downloads/Telegram Files for Project/channel_messages.txt"):
os.remove("/Users/emansarahafi/Downloads/Telegram Files for Project/channel_messages.txt")
with open(filename, 'r') as fr:
pre_ = fr.read()
lines = pre_.split('\n')
new_filename = filename.split('.')[0]+".txt" # To keep the same name except ext
with open(new_filename, "a") as fw:
fw.write("\n".join(lines))
else:
with open(filename, 'r') as fr:
pre_ = fr.read()
lines = pre_.split('\n')
new_filename = filename.split('.')[0]+".txt" # To keep the same name except ext
with open(new_filename, "a") as fw:
fw.write("\n".join(lines))
with client:
client.loop.run_until_complete(main(phone))
</code></pre>
<footer>
<style>
/* Styling Footer */
footer {
text-align: center;
color: rgb(0, 0, 0);
padding-top: 0px;
}
</style>
<p> Tashfeen Engineering Solutions 2022<br> <a href="https://www.tashfeen.tech"> Powered by Tashfeen</a></p>
</footer>
</body>