Skip to content

Commit f47f839

Browse files
committed
Minor fixes and improvements.
1 parent 85b65b8 commit f47f839

14 files changed

Lines changed: 18989 additions & 17022 deletions

File tree

.github/workflows/build-tdlib.yml

Lines changed: 17 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -12,21 +12,21 @@ jobs:
1212

1313
steps:
1414
- name: Clone Pytdbot
15-
uses: actions/checkout@v4
15+
uses: actions/checkout@v6
1616
with:
1717
fetch-depth: 1
1818

1919
- name: Clone TDLib
20-
uses: actions/checkout@v4
20+
uses: actions/checkout@v6
2121
with:
2222
repository: tdlib/td
2323
fetch-depth: 1
2424
path: "td/"
2525

26-
- name: Install Python 3.9
27-
uses: actions/setup-python@v5
26+
- name: Install Python 3.10
27+
uses: actions/setup-python@v6
2828
with:
29-
python-version: "3.9"
29+
python-version: "3.10"
3030

3131
# - name: Install PHP 7.4
3232
# uses: shivammathur/setup-php@v2
@@ -38,15 +38,15 @@ jobs:
3838
# with:
3939
# cmake-version: "3.25.1"
4040

41-
- name: Increase swap
42-
run: |
43-
free -h
44-
export SWAP_PATH=$(sudo swapon --show=NAME | tail -1)
45-
sudo swapoff -a
46-
sudo fallocate -l 7G $SWAP_PATH
47-
sudo mkswap $SWAP_PATH
48-
sudo swapon $SWAP_PATH
49-
free -h
41+
# - name: Increase swap
42+
# run: |
43+
# free -h
44+
# export SWAP_PATH=$(sudo swapon --show=NAME | tail -1)
45+
# sudo swapoff -a
46+
# sudo fallocate -l 7G $SWAP_PATH
47+
# sudo mkswap $SWAP_PATH
48+
# sudo swapon $SWAP_PATH
49+
# free -h
5050

5151
- name: Install TDLib dependencies
5252
id: td
@@ -95,8 +95,10 @@ jobs:
9595
run: |
9696
python generate_json.py "${{ steps.vars.outputs.LATEST_TDLIB_VERSION }}" "${{ steps.vars.outputs.LATEST_TDLIB_COMMIT_HASH }}"
9797
python generate_files.py
98+
TD_FILES="pytdbot/types/td_types.py pytdbot/methods/td_functions.py pytdbot/handlers/td_updates.py"
9899
python -m pip install ruff
99-
python -m ruff format .
100+
python -m ruff check $TD_FILES --select I --fix
101+
python -m ruff format $TD_FILES
100102
101103
CURRENT_VERSION=${{ steps.vars.outputs.CURRENT_TDLIB_VERSION }}
102104
sed --binary -i "s/${CURRENT_VERSION//./\\.}/${{ steps.vars.outputs.LATEST_TDLIB_VERSION }}/g" README.md

examples/chatIDBot.py

Lines changed: 4 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -112,9 +112,7 @@ async def increase_usage(by: int = 1):
112112
async def start(client: Client, message: types.Message):
113113
if message.text == "/start":
114114
await message.reply_text(
115-
"*Your ID*: {}".format(
116-
utils.code(str(message.from_id)),
117-
),
115+
f"*Your ID*: {utils.code(str(message.from_id))}",
118116
reply_markup=request_buttons,
119117
)
120118
await increase_usage()
@@ -133,17 +131,12 @@ async def handle_shared_chat(client: Client, message: types.Message):
133131
user_type_text = "*Bot ID*"
134132

135133
await message.reply_text(
136-
"{}: {}".format(
137-
user_type_text,
138-
utils.code(str(message.content.users[0].user_id)),
139-
),
134+
f"{user_type_text}: {utils.code(str(message.content.users[0].user_id))}",
140135
)
141136
await increase_usage()
142137
elif isinstance(message.content, types.MessageChatShared):
143138
await message.reply_text(
144-
"*Chat ID*: {}".format(
145-
utils.code(str(message.content.chat.chat_id)),
146-
),
139+
f"*Chat ID*: {utils.code(str(message.content.chat.chat_id))}",
147140
)
148141
await increase_usage()
149142

@@ -157,9 +150,7 @@ async def chat_member(client: Client, update: types.UpdateChatMember):
157150
if isinstance(update.new_chat_member.status, types.ChatMemberStatusMember):
158151
await client.sendTextMessage(
159152
update.chat_id,
160-
"*Chat ID*: {}".format(
161-
utils.code(str(update.chat_id)),
162-
),
153+
f"*Chat ID*: {utils.code(str(update.chat_id))}",
163154
)
164155
await client.leaveChat(chat_id=update.chat_id)
165156
await increase_usage()

generate_files.py

Lines changed: 33 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -83,18 +83,18 @@ def getArgTypePython(
8383
if is_function:
8484
if is_docstring:
8585
return f":class:`~pytdbot.types.{class_name}`"
86-
return f'"pytdbot.types.{class_name}"'
86+
return f"pytdbot.types.{class_name}"
8787

8888
return class_name
8989

9090

9191
def generate_arg_value(arg_type, arg_name):
9292
if arg_type == "int":
93-
arg_value = f"int({arg_name})"
93+
arg_value = f"{arg_name}"
9494
elif arg_type == "float":
95-
arg_value = f"float({arg_name})"
95+
arg_value = f"{arg_name}"
9696
elif arg_type == "bool":
97-
arg_value = f"bool({arg_name})"
97+
arg_value = f"{arg_name}"
9898
elif arg_type.startswith("list[") or arg_type == "list":
9999
arg_value = f"{arg_name} or []"
100100
else:
@@ -120,27 +120,29 @@ def generate_arg_default(arg_type):
120120
return arg_value
121121

122122

123-
def generate_args_def(args, is_function: bool = False):
123+
def generate_args_def(args, classes, is_function: bool = False):
124124
args_list = ["self"]
125125
for arg_name, arg_data in args.items():
126126
if arg_name in keyword.kwlist:
127127
arg_name += "_"
128128

129129
arg_type = getArgTypePython(arg_data["type"], is_function)
130130
arg_default = generate_arg_default(arg_type)
131+
arg_type = generate_union_types(
132+
arg_type, arg_data["type"], classes, is_function=is_function
133+
)
131134

132-
if arg_default == "None":
133-
args_list.append(f"{arg_name}: {arg_type} | None = None")
134-
else:
135-
args_list.append(f"{arg_name}: {arg_type} = {arg_default}")
135+
args_list.append(f"{arg_name}: {arg_type} = {arg_default}")
136136

137137
if len(args_list) > 1:
138138
args_list.insert(1, "*")
139139

140140
return ", ".join(args_list)
141141

142142

143-
def generate_union_types(arg_type, arg_type_name, classes, noneable=True):
143+
def generate_union_types(
144+
arg_type, arg_type_name, classes, noneable=True, is_function=False
145+
):
144146
unions = [arg_type]
145147

146148
if (
@@ -149,7 +151,12 @@ def generate_union_types(arg_type, arg_type_name, classes, noneable=True):
149151
unions.pop(0)
150152

151153
for type_name in classes[arg_type_name]["types"]:
152-
unions.append(to_camel_case(type_name, is_class=True))
154+
if is_function:
155+
unions.append(
156+
f"pytdbot.types.{to_camel_case(type_name, is_class=True)}"
157+
)
158+
else:
159+
unions.append(to_camel_case(type_name, is_class=True))
153160

154161
if noneable:
155162
unions.append("None")
@@ -165,11 +172,9 @@ def generate_self_args(args, classes):
165172

166173
arg_type = getArgTypePython(arg_data["type"])
167174
arg_value = generate_arg_value(arg_type, arg_name)
168-
if arg_value == arg_name: # a.k.a field can be None
169-
arg_type = generate_union_types(arg_type, arg_data["type"], classes)
170175

171176
args_list.append(
172-
f'self.{arg_name}: {arg_type} = {arg_value}\n{indent * 2}r"""{escape_quotes(arg_data["description"])}"""'
177+
f'self.{arg_name} = {arg_value}\n{indent * 2}r"""{escape_quotes(arg_data["description"])}"""'
173178
)
174179
if not args_list:
175180
return "pass"
@@ -284,7 +289,7 @@ def to_dict(self) -> dict:
284289
return {{{to_dict_return}}}
285290
286291
@classmethod
287-
def from_dict(cls, data: dict) -> "{class_name}" | None:
292+
def from_dict(cls, data: dict) -> {class_name} | None:
288293
if data:
289294
data_class = cls()
290295
{from_dict_kwargs}
@@ -295,7 +300,7 @@ def from_dict(cls, data: dict) -> "{class_name}" | None:
295300
def generate_types(f, types, updates, classes):
296301
def gen(t):
297302
for type_name, type_data in t.items():
298-
args_def = generate_args_def(type_data["args"])
303+
args_def = generate_args_def(type_data["args"], classes)
299304
self_args = generate_self_args(type_data["args"], classes)
300305
to_return_dict = generate_to_dict_return(type_data["args"])
301306
from_dict_kwargs = generate_from_dict_kwargs(type_data["args"])
@@ -323,7 +328,7 @@ def gen(t):
323328
gen(updates)
324329

325330

326-
functions_template = """async def {function_name}({function_args}) -> "pytdbot.types.Error" | "pytdbot.types.{return_type}":
331+
functions_template = """async def {function_name}({function_args}) -> pytdbot.types.Error | pytdbot.types.{return_type}:
327332
r\"\"\"{docstring}
328333
{docstring_args}
329334
Returns:
@@ -333,9 +338,9 @@ def gen(t):
333338
return await self.invoke({{'@type': '{method_name}', {function_invoke_args}}})"""
334339

335340

336-
def generate_functions(f, types):
341+
def generate_functions(f, types, classes):
337342
for function_name, function_data in types.items():
338-
args_def = generate_args_def(function_data["args"], True)
343+
args_def = generate_args_def(function_data["args"], classes, True)
339344
invoke_args = generate_function_invoke_args(function_data["args"])
340345

341346
f.write(
@@ -354,10 +359,10 @@ def generate_functions(f, types):
354359

355360

356361
updates_template = """ def on_{update_name}(
357-
self: "pytdbot.Client" = None,
358-
filters: "pytdbot.filters.Filter" = None,
359-
position: int = None,
360-
timeout: float = None,
362+
self: pytdbot.Client | None = None,
363+
filters: pytdbot.filters.Filter | None = None,
364+
position: int | None = None,
365+
timeout: float | None = None,
361366
) -> Callable:
362367
r\"\"\"{description}
363368
@@ -405,10 +410,11 @@ def generate_updates(f, updates):
405410

406411

407412
if __name__ == "__main__":
408-
with open("td_api.json", "r", encoding="utf-8") as f:
413+
with open("td_api.json", encoding="utf-8") as f:
409414
tl_json = json.loads(f.read())
410415

411416
with open("pytdbot/types/td_types.py", "w", encoding="utf-8") as types_file:
417+
types_file.write("from __future__ import annotations\n")
412418
types_file.write("from typing import Literal\n")
413419
types_file.write("from base64 import b64decode\n")
414420
types_file.write(
@@ -484,16 +490,18 @@ def from_dict(cls, data: dict):
484490
with open(
485491
"pytdbot/methods/td_functions.py", "w", encoding="utf-8"
486492
) as functions_file:
493+
functions_file.write("from __future__ import annotations\n")
487494
functions_file.write("import pytdbot\n\n")
488495

489496
functions_file.write("class TDLibFunctions:\n")
490497
functions_file.write(
491498
f'{indent}"""A class that include all TDLib functions"""\n\n'
492499
)
493500

494-
generate_functions(functions_file, tl_json["functions"])
501+
generate_functions(functions_file, tl_json["functions"], tl_json["classes"])
495502

496503
with open("pytdbot/handlers/td_updates.py", "w", encoding="utf-8") as updates_file:
504+
updates_file.write("from __future__ import annotations\n")
497505
updates_file.write(
498506
'import pytdbot\n\nfrom .handler import Handler\nfrom collections.abc import Callable\nfrom asyncio import iscoroutinefunction\nfrom logging import getLogger\n\nlogger = getLogger(__name__)\n\n\nclass Updates:\n """Auto generated TDLib updates"""\n\n'
499507
)

0 commit comments

Comments
 (0)