Pytdbot 0.10.2.dev0__py3-none-any.whl → 0.10.2.dev1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
pytdbot/ai/lookup.py ADDED
@@ -0,0 +1,326 @@
1
+ """Local TDLib / Pytdbot API lookup for coding agents and the docs CLI."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import re
7
+ from functools import lru_cache
8
+ from importlib import resources
9
+ from pathlib import Path
10
+ from typing import Any
11
+
12
+
13
+ def _package_path(*parts: str) -> Path | None:
14
+ """Resolve a file shipped inside the ``pytdbot`` package."""
15
+ try:
16
+ base = resources.files("pytdbot")
17
+ target = base.joinpath(*parts)
18
+ # importlib.resources may return a Traversable
19
+ if hasattr(target, "is_file") and target.is_file():
20
+ return Path(str(target))
21
+ except (TypeError, FileNotFoundError, ModuleNotFoundError, AttributeError):
22
+ pass
23
+
24
+ # Fallback: filesystem next to installed / source package
25
+ pkg_root = Path(__file__).resolve().parents[1]
26
+ candidate = pkg_root.joinpath(*parts)
27
+ if candidate.is_file():
28
+ return candidate
29
+
30
+ return None
31
+
32
+
33
+ def _load_json(path: Path) -> Any:
34
+ with path.open(encoding="utf-8") as f:
35
+ return json.load(f)
36
+
37
+
38
+ def _norm(s: str) -> str:
39
+ return re.sub(r"[^a-z0-9]", "", s.lower())
40
+
41
+
42
+ def _score_match(query: str, name: str, description: str = "") -> int:
43
+ """Higher is better. 0 means no match."""
44
+ q = query.strip()
45
+ if not q:
46
+ return 0
47
+ qn = _norm(q)
48
+ nn = _norm(name)
49
+ desc = (description or "").lower()
50
+ ql = q.lower()
51
+
52
+ if qn == nn:
53
+ return 1000
54
+ if nn.startswith(qn) or qn.startswith(nn):
55
+ return 800
56
+ if qn in nn:
57
+ return 600
58
+ if ql in name.lower():
59
+ return 500
60
+ if ql in desc or qn in _norm(desc):
61
+ return 200
62
+ # token overlap
63
+ tokens = [t for t in re.split(r"\W+", ql) if t]
64
+ if tokens and all(t in name.lower() or t in desc for t in tokens):
65
+ return 100 + 10 * len(tokens)
66
+ return 0
67
+
68
+
69
+ class ApiLookup:
70
+ """Search and fetch TDLib entities and Pytdbot helpers from local files."""
71
+
72
+ def __init__(
73
+ self,
74
+ td_api: dict[str, Any] | None = None,
75
+ helpers: list[dict[str, Any]] | None = None,
76
+ ) -> None:
77
+ if td_api is None:
78
+ path = _package_path("td_api.json")
79
+ if path is None:
80
+ raise FileNotFoundError(
81
+ "pytdbot/td_api.json not found. Reinstall pytdbot or run "
82
+ "generate_json.py from the repo root."
83
+ )
84
+ td_api = _load_json(path)
85
+ self.td_api = td_api
86
+
87
+ if helpers is None:
88
+ path = _package_path("ai", "helpers.json")
89
+ helpers = _load_json(path) if path else []
90
+ self.helpers = helpers
91
+
92
+ self.version = str(td_api.get("version", "unknown"))
93
+ self.commit_hash = str(td_api.get("commit_hash", ""))
94
+
95
+ # --- TDLib sections -------------------------------------------------
96
+
97
+ def _section(self, kind: str) -> dict[str, Any]:
98
+ key = {
99
+ "function": "functions",
100
+ "functions": "functions",
101
+ "type": "types",
102
+ "types": "types",
103
+ "class": "classes",
104
+ "classes": "classes",
105
+ "update": "updates",
106
+ "updates": "updates",
107
+ }.get(kind, kind)
108
+ data = self.td_api.get(key)
109
+ if not isinstance(data, dict):
110
+ raise KeyError(f"Unknown API section: {kind}")
111
+ return data
112
+
113
+ def get_function(self, name: str) -> dict[str, Any] | None:
114
+ return self._get_entity("functions", name)
115
+
116
+ def get_type(self, name: str) -> dict[str, Any] | None:
117
+ return self._get_entity("types", name)
118
+
119
+ def get_class(self, name: str) -> dict[str, Any] | None:
120
+ return self._get_entity("classes", name)
121
+
122
+ def get_update(self, name: str) -> dict[str, Any] | None:
123
+ return self._get_entity("updates", name)
124
+
125
+ _KIND_BY_SECTION = {
126
+ "functions": "function",
127
+ "types": "type",
128
+ "classes": "class",
129
+ "updates": "update",
130
+ }
131
+
132
+ def _get_entity(self, section: str, name: str) -> dict[str, Any] | None:
133
+ data = self.td_api.get(section) or {}
134
+ kind = self._KIND_BY_SECTION.get(section, section)
135
+ if name in data:
136
+ return {"name": name, "kind": kind, **data[name]}
137
+ # case-insensitive / camel-insensitive
138
+ target = _norm(name)
139
+ for key, value in data.items():
140
+ if _norm(key) == target:
141
+ return {"name": key, "kind": kind, **value}
142
+ return None
143
+
144
+ def search(
145
+ self,
146
+ query: str,
147
+ *,
148
+ kinds: list[str] | None = None,
149
+ limit: int = 20,
150
+ ) -> list[dict[str, Any]]:
151
+ """Search functions, types, classes, updates, and helpers."""
152
+ kinds = kinds or ["function", "type", "class", "update", "helper"]
153
+ results: list[tuple[int, dict[str, Any]]] = []
154
+
155
+ section_map = {
156
+ "function": "functions",
157
+ "type": "types",
158
+ "class": "classes",
159
+ "update": "updates",
160
+ }
161
+
162
+ for kind, section in section_map.items():
163
+ if kind not in kinds and f"{kind}s" not in kinds:
164
+ continue
165
+ for name, meta in (self.td_api.get(section) or {}).items():
166
+ desc = meta.get("description") or ""
167
+ score = _score_match(query, name, desc)
168
+ if score:
169
+ results.append(
170
+ (
171
+ score,
172
+ {
173
+ "kind": kind,
174
+ "name": name,
175
+ "description": desc,
176
+ "return_type": meta.get("type"),
177
+ "score": score,
178
+ },
179
+ )
180
+ )
181
+
182
+ if "helper" in kinds or "helpers" in kinds:
183
+ for h in self.helpers:
184
+ desc = h.get("description") or h.get("doc") or ""
185
+ label = f"{h.get('on', '')}.{h['name']}"
186
+ score = max(
187
+ _score_match(query, h["name"], desc),
188
+ _score_match(query, label, desc),
189
+ )
190
+ if score:
191
+ results.append(
192
+ (
193
+ score,
194
+ {
195
+ "kind": "helper",
196
+ "name": h["name"],
197
+ "on": h.get("on"),
198
+ "helper_kind": h.get("kind"),
199
+ "description": h.get("description") or "",
200
+ "score": score,
201
+ },
202
+ )
203
+ )
204
+
205
+ results.sort(key=lambda x: (-x[0], x[1].get("name", "")))
206
+ return [item for _, item in results[:limit]]
207
+
208
+ def get_helper(self, name: str) -> list[dict[str, Any]]:
209
+ """Return all helpers matching name (may be multiple hosts)."""
210
+ target = _norm(name)
211
+ # allow Message.reply_text
212
+ if "." in name:
213
+ on, _, method = name.partition(".")
214
+ on_n, method_n = _norm(on), _norm(method)
215
+ return [
216
+ h
217
+ for h in self.helpers
218
+ if _norm(h["name"]) == method_n and _norm(h.get("on", "")) == on_n
219
+ ]
220
+ return [h for h in self.helpers if _norm(h["name"]) == target]
221
+
222
+ def search_helpers(self, query: str, *, limit: int = 30) -> list[dict[str, Any]]:
223
+ return self.search(query, kinds=["helper"], limit=limit)
224
+
225
+ def format_entity(self, entity: dict[str, Any]) -> str:
226
+ """Pretty markdown for a function/type/class/update."""
227
+ lines: list[str] = []
228
+ kind = entity.get("kind", "entity")
229
+ name = entity.get("name", "?")
230
+ lines.append(f"# {kind}: `{name}`")
231
+ if entity.get("description"):
232
+ lines.append("")
233
+ lines.append(entity["description"])
234
+ if entity.get("type") and kind != "class":
235
+ lines.append("")
236
+ lines.append(f"**Returns / parent type:** `{entity['type']}`")
237
+
238
+ args = entity.get("args")
239
+ if isinstance(args, dict) and args:
240
+ lines.append("")
241
+ lines.append("## Arguments")
242
+ for arg_name, info in args.items():
243
+ if isinstance(info, dict):
244
+ opt = "optional" if info.get("is_optional") else "required"
245
+ lines.append(
246
+ f"- `{arg_name}` (`{info.get('type', '?')}`, {opt}): "
247
+ f"{info.get('description', '')}"
248
+ )
249
+ else:
250
+ lines.append(f"- `{arg_name}`: {info}")
251
+
252
+ if kind == "class":
253
+ types_list = entity.get("types") or []
254
+ funcs = entity.get("functions") or []
255
+ if types_list:
256
+ lines.append("")
257
+ lines.append("## Concrete types")
258
+ for t in types_list:
259
+ lines.append(f"- `{t}`")
260
+ if funcs:
261
+ lines.append("")
262
+ lines.append("## Related functions")
263
+ for f in funcs:
264
+ lines.append(f"- `{f}`")
265
+
266
+ lines.append("")
267
+ lines.append(
268
+ f"_TDLib {self.version}"
269
+ + (f" ({self.commit_hash[:8]})" if self.commit_hash else "")
270
+ + "_"
271
+ )
272
+ return "\n".join(lines)
273
+
274
+ def format_helper(self, helper: dict[str, Any]) -> str:
275
+ lines = [
276
+ f"# helper: `{helper.get('on', '?')}.{helper['name']}`",
277
+ "",
278
+ f"**Kind:** {helper.get('kind', '?')}",
279
+ f"**Async:** {helper.get('async', False)}",
280
+ ]
281
+ if helper.get("returns"):
282
+ lines.append(f"**Returns:** `{helper['returns']}`")
283
+ if helper.get("description"):
284
+ lines.append("")
285
+ lines.append(helper["description"])
286
+ args = helper.get("args") or []
287
+ if args:
288
+ lines.append("")
289
+ lines.append("## Arguments")
290
+ for a in args:
291
+ if isinstance(a, dict):
292
+ bits = [f"`{a['name']}`"]
293
+ if a.get("type"):
294
+ bits.append(f"(`{a['type']}`)")
295
+ if a.get("optional"):
296
+ bits.append("optional")
297
+ if "default" in a:
298
+ bits.append(f"default={a['default']}")
299
+ lines.append("- " + " ".join(bits))
300
+ else:
301
+ lines.append(f"- `{a}`")
302
+ doc = helper.get("doc") or ""
303
+ if doc and doc != helper.get("description"):
304
+ lines.append("")
305
+ lines.append("## Documentation")
306
+ lines.append(doc)
307
+ if helper.get("source"):
308
+ lines.append("")
309
+ lines.append(f"_Source: {helper['source']}_")
310
+ return "\n".join(lines)
311
+
312
+ def stats(self) -> dict[str, Any]:
313
+ return {
314
+ "tdlib_version": self.version,
315
+ "commit_hash": self.commit_hash,
316
+ "functions": len(self.td_api.get("functions") or {}),
317
+ "types": len(self.td_api.get("types") or {}),
318
+ "classes": len(self.td_api.get("classes") or {}),
319
+ "updates": len(self.td_api.get("updates") or {}),
320
+ "helpers": len(self.helpers),
321
+ }
322
+
323
+
324
+ @lru_cache(maxsize=1)
325
+ def get_lookup() -> ApiLookup:
326
+ return ApiLookup()
pytdbot/docs.py ADDED
@@ -0,0 +1,203 @@
1
+ """CLI: ``python -m pytdbot.docs`` / ``pytdbot-docs``."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import json
7
+ import sys
8
+
9
+ from pytdbot.ai.lookup import get_lookup
10
+
11
+
12
+ def _print_json(data: object) -> None:
13
+ json.dump(data, sys.stdout, indent=2, ensure_ascii=False)
14
+ sys.stdout.write("\n")
15
+
16
+
17
+ def cmd_stats(_: argparse.Namespace) -> int:
18
+ _print_json(get_lookup().stats())
19
+ return 0
20
+
21
+
22
+ def cmd_search(args: argparse.Namespace) -> int:
23
+ lookup = get_lookup()
24
+ kinds = args.kind
25
+ results = lookup.search(args.query, kinds=kinds, limit=args.limit)
26
+ if args.json:
27
+ _print_json(results)
28
+ else:
29
+ if not results:
30
+ print(f"No results for {args.query!r}")
31
+ return 1
32
+ for r in results:
33
+ kind = r.get("kind")
34
+ name = r.get("name")
35
+ on = r.get("on")
36
+ label = f"{on}.{name}" if on else name
37
+ desc = (r.get("description") or "").replace("\n", " ")
38
+ if len(desc) > 100:
39
+ desc = desc[:97] + "..."
40
+ print(f"[{kind:8}] {label:40} {desc}")
41
+ return 0
42
+
43
+
44
+ def cmd_function(args: argparse.Namespace) -> int:
45
+ lookup = get_lookup()
46
+ entity = lookup.get_function(args.name)
47
+ if not entity:
48
+ print(f"Function not found: {args.name}", file=sys.stderr)
49
+ return 1
50
+ if args.json:
51
+ _print_json(entity)
52
+ else:
53
+ print(lookup.format_entity(entity))
54
+ return 0
55
+
56
+
57
+ def cmd_type(args: argparse.Namespace) -> int:
58
+ lookup = get_lookup()
59
+ entity = lookup.get_type(args.name)
60
+ if not entity:
61
+ print(f"Type not found: {args.name}", file=sys.stderr)
62
+ return 1
63
+ if args.json:
64
+ _print_json(entity)
65
+ else:
66
+ print(lookup.format_entity(entity))
67
+ return 0
68
+
69
+
70
+ def cmd_class(args: argparse.Namespace) -> int:
71
+ lookup = get_lookup()
72
+ entity = lookup.get_class(args.name)
73
+ if not entity:
74
+ print(f"Class not found: {args.name}", file=sys.stderr)
75
+ return 1
76
+ if args.json:
77
+ _print_json(entity)
78
+ else:
79
+ print(lookup.format_entity(entity))
80
+ return 0
81
+
82
+
83
+ def cmd_update(args: argparse.Namespace) -> int:
84
+ lookup = get_lookup()
85
+ entity = lookup.get_update(args.name)
86
+ if not entity:
87
+ print(f"Update not found: {args.name}", file=sys.stderr)
88
+ return 1
89
+ if args.json:
90
+ _print_json(entity)
91
+ else:
92
+ print(lookup.format_entity(entity))
93
+ return 0
94
+
95
+
96
+ def cmd_helper(args: argparse.Namespace) -> int:
97
+ lookup = get_lookup()
98
+ if args.name:
99
+ matches = lookup.get_helper(args.name)
100
+ if not matches:
101
+ # fall back to search
102
+ matches = [
103
+ h
104
+ for h in lookup.helpers
105
+ if args.name.lower() in h["name"].lower()
106
+ or args.name.lower() in (h.get("on") or "").lower()
107
+ ]
108
+ if not matches:
109
+ print(f"Helper not found: {args.name}", file=sys.stderr)
110
+ return 1
111
+ if args.json:
112
+ _print_json(matches if len(matches) > 1 else matches[0])
113
+ else:
114
+ for i, h in enumerate(matches):
115
+ if i:
116
+ print("\n---\n")
117
+ print(lookup.format_helper(h))
118
+ return 0
119
+
120
+ # list / search helpers
121
+ if args.query:
122
+ results = lookup.search_helpers(args.query, limit=args.limit)
123
+ if args.json:
124
+ _print_json(results)
125
+ else:
126
+ for r in results:
127
+ print(
128
+ f"{r.get('on', '?')}.{r['name']:30} {r.get('description', '')[:80]}"
129
+ )
130
+ return 0 if results else 1
131
+
132
+ # list all
133
+ if args.json:
134
+ _print_json(lookup.helpers)
135
+ else:
136
+ for h in lookup.helpers:
137
+ print(f"[{h.get('kind', '?'):14}] {h.get('on', '?'):28} {h['name']}")
138
+ return 0
139
+
140
+
141
+ def build_parser() -> argparse.ArgumentParser:
142
+ parser = argparse.ArgumentParser(
143
+ prog="pytdbot-docs",
144
+ description="Look up TDLib methods/types and Pytdbot helpers",
145
+ )
146
+ parser.add_argument(
147
+ "--json",
148
+ action="store_true",
149
+ help="Machine-readable JSON output",
150
+ )
151
+ sub = parser.add_subparsers(dest="command", required=True)
152
+
153
+ p_stats = sub.add_parser("stats", help="Show API surface counts")
154
+ p_stats.set_defaults(func=cmd_stats)
155
+
156
+ p_search = sub.add_parser("search", help="Search functions, types, classes, updates, helpers")
157
+ p_search.add_argument("query", help="Search query")
158
+ p_search.add_argument(
159
+ "--kind",
160
+ action="append",
161
+ choices=["function", "type", "class", "update", "helper"],
162
+ help="Limit to kind (repeatable)",
163
+ )
164
+ p_search.add_argument("--limit", type=int, default=20)
165
+ p_search.set_defaults(func=cmd_search)
166
+
167
+ p_fn = sub.add_parser("function", aliases=["fn"], help="Show a TDLib function")
168
+ p_fn.add_argument("name", help="Function name, e.g. sendMessage")
169
+ p_fn.set_defaults(func=cmd_function)
170
+
171
+ p_ty = sub.add_parser("type", help="Show a TDLib type")
172
+ p_ty.add_argument("name", help="Type name, e.g. inputMessagePhoto")
173
+ p_ty.set_defaults(func=cmd_type)
174
+
175
+ p_cl = sub.add_parser("class", help="Show a TDLib abstract class")
176
+ p_cl.add_argument("name", help="Class name, e.g. InputFile")
177
+ p_cl.set_defaults(func=cmd_class)
178
+
179
+ p_up = sub.add_parser("update", help="Show a TDLib update")
180
+ p_up.add_argument("name", help="Update name, e.g. updateNewMessage")
181
+ p_up.set_defaults(func=cmd_update)
182
+
183
+ p_help = sub.add_parser("helper", help="Show or list Pytdbot helpers / bound methods")
184
+ p_help.add_argument(
185
+ "name",
186
+ nargs="?",
187
+ help="Helper name (e.g. reply_text or Message.reply_text)",
188
+ )
189
+ p_help.add_argument("-q", "--query", help="Search helpers")
190
+ p_help.add_argument("--limit", type=int, default=30)
191
+ p_help.set_defaults(func=cmd_helper)
192
+
193
+ return parser
194
+
195
+
196
+ def main(argv: list[str] | None = None) -> int:
197
+ parser = build_parser()
198
+ args = parser.parse_args(argv)
199
+ return int(args.func(args))
200
+
201
+
202
+ if __name__ == "__main__":
203
+ raise SystemExit(main())