-
-
Notifications
You must be signed in to change notification settings - Fork 48
Expand file tree
/
Copy pathcompiler.py
More file actions
669 lines (596 loc) · 19.1 KB
/
compiler.py
File metadata and controls
669 lines (596 loc) · 19.1 KB
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
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
# Hydrogram - Telegram MTProto API Client Library for Python
# Copyright (C) 2023-present Hydrogram <https://hydrogram.org>
#
# This file is part of Hydrogram.
#
# Hydrogram is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Hydrogram is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with Hydrogram. If not, see <http://www.gnu.org/licenses/>.
import ast
import re
import shutil
from pathlib import Path
DOCS_HOME_PATH = Path(__file__).parent.resolve()
REPO_HOME_PATH = DOCS_HOME_PATH.parent.parent
DOCS_DEST_PATH = REPO_HOME_PATH / "docs" / "source" / "telegram"
API_DOCS_DEST_PATH = REPO_HOME_PATH / "docs" / "source" / "api"
FUNCTIONS_PATH = REPO_HOME_PATH / "hydrogram" / "raw" / "functions"
TYPES_PATH = REPO_HOME_PATH / "hydrogram" / "raw" / "types"
BASE_PATH = REPO_HOME_PATH / "hydrogram" / "raw" / "base"
FUNCTIONS_BASE = "functions"
TYPES_BASE = "types"
BASE_BASE = "base"
def snake(s: str):
s = re.sub(r"(.)([A-Z][a-z]+)", r"\1_\2", s)
return re.sub(r"([a-z0-9])([A-Z])", r"\1_\2", s).lower()
def generate(source_path: Path, base_name: str):
all_entities: dict[str, list[str]] = {}
def build(path: Path, level=0):
last = path.name
for i in path.iterdir():
if not i.name.startswith("__"):
item_path = path / i
if item_path.is_dir():
build(item_path, level=level + 1)
elif item_path.is_file():
with item_path.open(encoding="utf-8") as f:
p = ast.parse(f.read())
for node in ast.walk(p):
if isinstance(node, ast.ClassDef):
name = node.name
break
else:
continue
full_path = Path(last, snake(name).replace("_", "-") + ".rst")
if level:
full_path = Path(base_name, full_path)
namespace = "" if last in {"base", "types", "functions"} else last
full_name = f"{f'{namespace}.' if namespace else ''}{name}"
(DOCS_DEST_PATH / full_path).parent.mkdir(parents=True, exist_ok=True)
with (DOCS_DEST_PATH / full_path).open("w", encoding="utf-8") as f:
f.write(
page_template.format(
title=full_name,
title_markup="=" * len(full_name),
full_class_path="hydrogram.raw.{}".format(
".".join(full_path.parts[:-1]) + "." + name
),
)
)
if last not in all_entities:
all_entities[last] = []
all_entities[last].append(name)
build(source_path)
for k, v in sorted(all_entities.items()):
v = sorted(v)
entities = []
entities = [f"{i} <{snake(i).replace('_', '-')}>" for i in v]
if k != base_name:
inner_path = Path(base_name, k, "index.rst")
module = f"hydrogram.raw.{base_name}.{k}"
else:
for i in sorted(all_entities, reverse=True):
if i != base_name:
entities.insert(0, f"{i}/index")
inner_path = Path(base_name, "index.rst")
module = f"hydrogram.raw.{base_name}"
with (DOCS_DEST_PATH / inner_path).open("w", encoding="utf-8") as f:
if k == base_name:
f.write(":tocdepth: 1\n\n")
k = f"Raw {k}"
f.write(
toctree.format(
title=k.title(),
title_markup="=" * len(k),
module=module,
entities="\n ".join(entities),
)
)
f.write("\n")
def hydrogram_api():
def get_title_list(s: str) -> list[str]:
return [i.strip() for i in [j.strip() for j in s.split("\n") if j] if i]
# Methods
categories = {
"utilities": """
Utilities
start
stop
run
restart
add_handler
remove_handler
stop_transmission
export_session_string
set_parse_mode
""",
"messages": """
Messages
send_message
forward_messages
copy_message
copy_media_group
send_photo
send_audio
send_document
send_sticker
send_video
send_animation
send_voice
send_video_note
send_media_group
send_location
send_venue
send_contact
send_cached_media
send_reaction
edit_message_text
edit_message_caption
edit_message_media
edit_message_reply_markup
edit_inline_text
edit_inline_caption
edit_inline_media
edit_inline_reply_markup
send_chat_action
delete_messages
get_messages
get_media_group
get_chat_history
get_chat_history_count
read_chat_history
send_poll
vote_poll
stop_poll
retract_vote
send_dice
search_messages
search_messages_count
search_global
search_global_count
download_media
stream_media
get_discussion_message
get_discussion_replies
get_discussion_replies_count
get_custom_emoji_stickers
""",
"chats": """
Chats
join_chat
leave_chat
ban_chat_member
unban_chat_member
restrict_chat_member
promote_chat_member
set_administrator_title
set_chat_photo
delete_chat_photo
set_chat_title
set_chat_description
set_chat_permissions
pin_chat_message
unpin_chat_message
unpin_all_chat_messages
get_chat
get_chat_member
get_chat_members
get_chat_members_count
get_dialogs
get_dialogs_count
set_chat_username
get_nearby_chats
archive_chats
unarchive_chats
add_chat_members
create_channel
create_group
create_supergroup
delete_channel
delete_supergroup
delete_user_history
set_slow_mode
mark_chat_unread
get_chat_event_log
get_chat_online_count
get_send_as_chats
set_send_as_chat
set_chat_protected_content
transfer_chat_ownership
""",
"users": """
Users
get_me
get_users
get_chat_photos
get_chat_photos_count
set_profile_photo
delete_profile_photos
set_username
update_profile
block_user
unblock_user
get_common_chats
get_default_emoji_statuses
set_emoji_status
""",
"invite_links": """
Invite Links
get_chat_invite_link
export_chat_invite_link
create_chat_invite_link
edit_chat_invite_link
revoke_chat_invite_link
delete_chat_invite_link
get_chat_invite_link_joiners
get_chat_invite_link_joiners_count
get_chat_admin_invite_links
get_chat_admin_invite_links_count
get_chat_admins_with_invite_links
get_chat_join_requests
delete_chat_admin_invite_links
approve_chat_join_request
approve_all_chat_join_requests
decline_chat_join_request
decline_all_chat_join_requests
""",
"contacts": """
Contacts
add_contact
delete_contacts
import_contacts
get_contacts
get_contacts_count
""",
"password": """
Password
enable_cloud_password
change_cloud_password
remove_cloud_password
""",
"bots": """
Bots
get_inline_bot_results
send_inline_bot_result
answer_callback_query
answer_inline_query
request_callback_answer
send_game
set_game_score
get_game_high_scores
set_bot_commands
get_bot_commands
delete_bot_commands
set_bot_default_privileges
get_bot_default_privileges
set_chat_menu_button
get_chat_menu_button
answer_web_app_query
""",
"authorization": """
Authorization
connect
disconnect
initialize
terminate
send_code
resend_code
sign_in
sign_in_bot
sign_up
get_password_hint
check_password
send_recovery_code
recover_password
accept_terms_of_service
log_out
""",
"advanced": """
Advanced
invoke
resolve_peer
save_file
""",
"phone": """
Phone:
create_video_chat
discard_group_call
invite_group_call_members
""",
}
root = API_DOCS_DEST_PATH / "methods"
shutil.rmtree(root, ignore_errors=True)
root.mkdir(parents=True)
with (DOCS_HOME_PATH / "template" / "methods.rst").open() as f:
template = f.read()
with (root / "index.rst").open("w") as f:
fmt_keys = {}
for k, v in categories.items():
_, *methods = get_title_list(v)
fmt_keys[k] = "\n ".join(f"{m} <{m}>" for m in methods)
for method in methods:
with (root / f"{method}.rst").open("w") as f2:
title = f"{method}()"
f2.write(title + "\n" + "=" * len(title) + "\n\n")
f2.write(f".. automethod:: hydrogram.Client.{method}()")
functions = ["idle", "compose"]
for func in functions:
with (root / f"{func}.rst").open("w") as f2:
title = f"{func}()"
f2.write(title + "\n" + "=" * len(title) + "\n\n")
f2.write(f".. autofunction:: hydrogram.{func}()")
f.write(template.format(**fmt_keys))
# Types
categories = {
"users_chats": """
Users & Chats
User
Chat
ChatPreview
ChatPhoto
ChatMember
ChatPermissions
ChatPrivileges
ChatInviteLink
ChatAdminWithInviteLinks
ChatEvent
ChatEventFilter
ChatMemberUpdated
ChatJoinRequest
ChatJoiner
Dialog
Restriction
EmojiStatus
ChatBackground
""",
"messages_media": """
Messages & Media
Message
MessageEntity
Photo
Thumbnail
Audio
Document
Animation
Video
Voice
VideoNote
Contact
Location
Venue
Sticker
Game
WebPage
Poll
PollOption
Dice
Reaction
VideoChatScheduled
VideoChatStarted
VideoChatEnded
VideoChatMembersInvited
WebAppData
MessageReactions
ChatReactions
""",
"bot_keyboards": """
Bot keyboards
ReplyKeyboardMarkup
KeyboardButton
ReplyKeyboardRemove
InlineKeyboardMarkup
InlineKeyboardButton
LoginUrl
ForceReply
CallbackQuery
GameHighScore
CallbackGame
WebAppInfo
MenuButton
MenuButtonCommands
MenuButtonWebApp
MenuButtonDefault
SentWebAppMessage
""",
"bot_commands": """
Bot commands
BotCommand
BotCommandScope
BotCommandScopeDefault
BotCommandScopeAllPrivateChats
BotCommandScopeAllGroupChats
BotCommandScopeAllChatAdministrators
BotCommandScopeChat
BotCommandScopeChatAdministrators
BotCommandScopeChatMember
""",
"input_media": """
Input Media
InputMedia
InputMediaPhoto
InputMediaVideo
InputMediaAudio
InputMediaAnimation
InputMediaDocument
InputPhoneContact
""",
"inline_mode": """
Inline Mode
InlineQuery
InlineQueryResult
InlineQueryResultCachedAudio
InlineQueryResultCachedDocument
InlineQueryResultCachedAnimation
InlineQueryResultCachedPhoto
InlineQueryResultCachedSticker
InlineQueryResultCachedVideo
InlineQueryResultCachedVoice
InlineQueryResultArticle
InlineQueryResultAudio
InlineQueryResultContact
InlineQueryResultDocument
InlineQueryResultAnimation
InlineQueryResultLocation
InlineQueryResultPhoto
InlineQueryResultVenue
InlineQueryResultVideo
InlineQueryResultVoice
ChosenInlineResult
""",
"input_message_content": """
InputMessageContent
InputMessageContent
InputPollOption
InputTextMessageContent
""",
"authorization": """
Authorization
SentCode
TermsOfService
""",
}
root = API_DOCS_DEST_PATH / "types"
shutil.rmtree(root, ignore_errors=True)
root.mkdir(parents=True)
with (DOCS_HOME_PATH / "template" / "types.rst").open() as f:
template = f.read()
with (root / "index.rst").open("w") as f:
fmt_keys = {}
for k, v in categories.items():
_, *types = get_title_list(v)
fmt_keys[k] = "\n ".join(types)
for type in types:
with (root / f"{type}.rst").open("w") as f2:
f2.write(f"{type}\n" + "=" * len(type) + "\n\n")
f2.write(f".. autoclass:: hydrogram.types.{type}()\n")
f.write(template.format(**fmt_keys))
# Bound Methods
categories = {
"message": """
Message
Message.click
Message.delete
Message.download
Message.forward
Message.copy
Message.pin
Message.unpin
Message.edit
Message.edit_text
Message.edit_caption
Message.edit_media
Message.edit_reply_markup
Message.reply
Message.reply_text
Message.reply_animation
Message.reply_audio
Message.reply_cached_media
Message.reply_chat_action
Message.reply_contact
Message.reply_document
Message.reply_game
Message.reply_inline_bot_result
Message.reply_location
Message.reply_media_group
Message.reply_photo
Message.reply_poll
Message.reply_sticker
Message.reply_venue
Message.reply_video
Message.reply_video_note
Message.reply_voice
Message.get_media_group
Message.react
""",
"chat": """
Chat
Chat.archive
Chat.unarchive
Chat.set_title
Chat.set_description
Chat.set_photo
Chat.ban_member
Chat.unban_member
Chat.restrict_member
Chat.promote_member
Chat.get_member
Chat.get_members
Chat.add_members
Chat.join
Chat.leave
Chat.mark_unread
Chat.set_protected_content
Chat.unpin_all_messages
Chat.ask
Chat.listen
Chat.stop_listening
""",
"user": """
User
User.archive
User.unarchive
User.block
User.unblock
User.ask
User.listen
User.stop_listening
""",
"callback_query": """
Callback Query
CallbackQuery.answer
CallbackQuery.edit_message_text
CallbackQuery.edit_message_caption
CallbackQuery.edit_message_media
CallbackQuery.edit_message_reply_markup
""",
"inline_query": """
InlineQuery
InlineQuery.answer
""",
"chat_join_request": """
ChatJoinRequest
ChatJoinRequest.approve
ChatJoinRequest.decline
""",
}
root = API_DOCS_DEST_PATH / "bound-methods"
shutil.rmtree(root, ignore_errors=True)
root.mkdir(parents=True)
with (DOCS_HOME_PATH / "template" / "bound-methods.rst").open() as f:
template = f.read()
with (root / "index.rst").open("w") as f:
fmt_keys = {}
for k, v in categories.items():
_, *bound_methods = get_title_list(v)
fmt_keys[f"{k}_hlist"] = "\n ".join(f"- :meth:`~{bm}`" for bm in bound_methods)
fmt_keys[f"{k}_toctree"] = "\n ".join(
"{} <{}>".format(bm.split(".")[1], bm) for bm in bound_methods
)
for bm in bound_methods:
with (root / f"{bm}.rst").open("w") as f2:
title = f"{bm}()"
f2.write(title + "\n" + "=" * len(title) + "\n\n")
f2.write(f".. automethod:: hydrogram.types.{bm}()")
f.write(template.format(**fmt_keys))
def start():
global page_template, toctree
shutil.rmtree(DOCS_DEST_PATH, ignore_errors=True)
with (DOCS_HOME_PATH / "template" / "page.txt").open(encoding="utf-8") as f:
page_template = f.read()
with (DOCS_HOME_PATH / "template" / "toctree.txt").open(encoding="utf-8") as f:
toctree = f.read()
generate(TYPES_PATH, TYPES_BASE)
generate(FUNCTIONS_PATH, FUNCTIONS_BASE)
generate(BASE_PATH, BASE_BASE)
hydrogram_api()
if __name__ == "__main__":
start()