telekit 2.6.0a5__tar.gz → 2.6.0a7__tar.gz

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.
Files changed (98) hide show
  1. telekit-2.6.0a7/CHANGELOG.md +56 -0
  2. telekit-2.6.0a7/MANIFEST.in +4 -0
  3. {telekit-2.6.0a5 → telekit-2.6.0a7}/PKG-INFO +46 -7
  4. {telekit-2.6.0a5 → telekit-2.6.0a7}/README.md +9 -3
  5. {telekit-2.6.0a5 → telekit-2.6.0a7}/setup.cfg +0 -3
  6. telekit-2.6.0a7/setup.py +71 -0
  7. {telekit-2.6.0a5 → telekit-2.6.0a7}/telekit/__init__.py +8 -4
  8. telekit-2.6.0a5/telekit/_version.py → telekit-2.6.0a7/telekit/__version__.py +1 -2
  9. {telekit-2.6.0a5 → telekit-2.6.0a7}/telekit/_chain.py +2 -2
  10. {telekit-2.6.0a5 → telekit-2.6.0a7}/telekit/_chain_base.py +6 -3
  11. {telekit-2.6.0a5 → telekit-2.6.0a7}/telekit/_chain_inline_keyboards_logic.py +6 -4
  12. telekit-2.6.0a7/telekit/_file_cache.py +136 -0
  13. telekit-2.6.0a7/telekit/_logger.py +206 -0
  14. telekit-2.6.0a7/telekit/_timeout.py +424 -0
  15. telekit-2.6.0a7/telekit/example/example_handlers/__init__.py +9 -0
  16. {telekit-2.6.0a5 → telekit-2.6.0a7}/telekit/example/example_server.py +3 -20
  17. telekit-2.6.0a7/telekit/requirements.txt +3 -0
  18. {telekit-2.6.0a5 → telekit-2.6.0a7}/telekit/senders.py +128 -9
  19. telekit-2.6.0a7/telekit/server.py +540 -0
  20. {telekit-2.6.0a5 → telekit-2.6.0a7}/telekit/utils.py +54 -33
  21. {telekit-2.6.0a5 → telekit-2.6.0a7}/telekit.egg-info/PKG-INFO +46 -7
  22. {telekit-2.6.0a5 → telekit-2.6.0a7}/telekit.egg-info/SOURCES.txt +5 -2
  23. telekit-2.6.0a5/setup.py +0 -73
  24. telekit-2.6.0a5/telekit/_logger.py +0 -129
  25. telekit-2.6.0a5/telekit/_timeout.py +0 -73
  26. telekit-2.6.0a5/telekit/example/example_handlers/__init__.py +0 -23
  27. telekit-2.6.0a5/telekit/server.py +0 -160
  28. {telekit-2.6.0a5 → telekit-2.6.0a7}/LICENSE +0 -0
  29. {telekit-2.6.0a5 → telekit-2.6.0a7}/telekit/_buildtext/__init__.py +0 -0
  30. {telekit-2.6.0a5 → telekit-2.6.0a7}/telekit/_buildtext/formatter.py +0 -0
  31. {telekit-2.6.0a5 → telekit-2.6.0a7}/telekit/_buildtext/styles.py +0 -0
  32. {telekit-2.6.0a5 → telekit-2.6.0a7}/telekit/_callback_query_handler.py +0 -0
  33. {telekit-2.6.0a5 → telekit-2.6.0a7}/telekit/_chain_entry_logic.py +0 -0
  34. {telekit-2.6.0a5 → telekit-2.6.0a7}/telekit/_chapters/__init__.py +0 -0
  35. {telekit-2.6.0a5 → telekit-2.6.0a7}/telekit/_chapters/chapters.py +0 -0
  36. {telekit-2.6.0a5 → telekit-2.6.0a7}/telekit/_handler.py +0 -0
  37. {telekit-2.6.0a5 → telekit-2.6.0a7}/telekit/_init.py +0 -0
  38. {telekit-2.6.0a5 → telekit-2.6.0a7}/telekit/_inline_buttons.py +0 -0
  39. {telekit-2.6.0a5 → telekit-2.6.0a7}/telekit/_inline_keyboard.py +0 -0
  40. {telekit-2.6.0a5 → telekit-2.6.0a7}/telekit/_input_handler.py +0 -0
  41. {telekit-2.6.0a5 → telekit-2.6.0a7}/telekit/_on.py +0 -0
  42. {telekit-2.6.0a5 → telekit-2.6.0a7}/telekit/_reply_keyboard.py +0 -0
  43. {telekit-2.6.0a5 → telekit-2.6.0a7}/telekit/_rich.py +0 -0
  44. {telekit-2.6.0a5 → telekit-2.6.0a7}/telekit/_snapvault/__init__.py +0 -0
  45. {telekit-2.6.0a5 → telekit-2.6.0a7}/telekit/_snapvault/snapcode.py +0 -0
  46. {telekit-2.6.0a5 → telekit-2.6.0a7}/telekit/_snapvault/snapvault.py +0 -0
  47. {telekit-2.6.0a5 → telekit-2.6.0a7}/telekit/_state.py +0 -0
  48. {telekit-2.6.0a5 → telekit-2.6.0a7}/telekit/_telekit_dsl/__init__.py +0 -0
  49. {telekit-2.6.0a5 → telekit-2.6.0a7}/telekit/_telekit_dsl/mixin.py +0 -0
  50. {telekit-2.6.0a5 → telekit-2.6.0a7}/telekit/_telekit_dsl/parser/__init__.py +0 -0
  51. {telekit-2.6.0a5 → telekit-2.6.0a7}/telekit/_telekit_dsl/parser/builder.py +0 -0
  52. {telekit-2.6.0a5 → telekit-2.6.0a7}/telekit/_telekit_dsl/parser/canvas_parser.py +0 -0
  53. {telekit-2.6.0a5 → telekit-2.6.0a7}/telekit/_telekit_dsl/parser/lexer.py +0 -0
  54. {telekit-2.6.0a5 → telekit-2.6.0a7}/telekit/_telekit_dsl/parser/nodes.py +0 -0
  55. {telekit-2.6.0a5 → telekit-2.6.0a7}/telekit/_telekit_dsl/parser/parser.py +0 -0
  56. {telekit-2.6.0a5 → telekit-2.6.0a7}/telekit/_telekit_dsl/parser/token.py +0 -0
  57. {telekit-2.6.0a5 → telekit-2.6.0a7}/telekit/_telekit_dsl/telekit_dsl.py +0 -0
  58. {telekit-2.6.0a5 → telekit-2.6.0a7}/telekit/_telekit_dsl/telekit_orm.py +0 -0
  59. {telekit-2.6.0a5 → telekit-2.6.0a7}/telekit/_text_builder.py +0 -0
  60. {telekit-2.6.0a5 → telekit-2.6.0a7}/telekit/_trait.py +0 -0
  61. {telekit-2.6.0a5 → telekit-2.6.0a7}/telekit/_user.py +0 -0
  62. {telekit-2.6.0a5 → telekit-2.6.0a7}/telekit/chat.py +0 -0
  63. {telekit-2.6.0a5 → telekit-2.6.0a7}/telekit/debug.py +0 -0
  64. {telekit-2.6.0a5 → telekit-2.6.0a7}/telekit/dices.py +0 -0
  65. {telekit-2.6.0a5 → telekit-2.6.0a7}/telekit/example/__init__.py +0 -0
  66. {telekit-2.6.0a5 → telekit-2.6.0a7}/telekit/example/example_handlers/article.py +0 -0
  67. {telekit-2.6.0a5 → telekit-2.6.0a7}/telekit/example/example_handlers/calendar.py +0 -0
  68. {telekit-2.6.0a5 → telekit-2.6.0a7}/telekit/example/example_handlers/complete_hotel.py +0 -0
  69. {telekit-2.6.0a5 → telekit-2.6.0a7}/telekit/example/example_handlers/counter.py +0 -0
  70. {telekit-2.6.0a5 → telekit-2.6.0a7}/telekit/example/example_handlers/dsl.py +0 -0
  71. {telekit-2.6.0a5 → telekit-2.6.0a7}/telekit/example/example_handlers/entry.py +0 -0
  72. {telekit-2.6.0a5 → telekit-2.6.0a7}/telekit/example/example_handlers/faq.py +0 -0
  73. {telekit-2.6.0a5 → telekit-2.6.0a7}/telekit/example/example_handlers/hotel.py +0 -0
  74. {telekit-2.6.0a5 → telekit-2.6.0a7}/telekit/example/example_handlers/on_text.py +0 -0
  75. {telekit-2.6.0a5 → telekit-2.6.0a7}/telekit/example/example_handlers/pages.py +0 -0
  76. {telekit-2.6.0a5 → telekit-2.6.0a7}/telekit/example/example_handlers/pyapi.py +0 -0
  77. {telekit-2.6.0a5 → telekit-2.6.0a7}/telekit/example/example_handlers/qr.py +0 -0
  78. {telekit-2.6.0a5 → telekit-2.6.0a7}/telekit/example/example_handlers/quiz.py +0 -0
  79. {telekit-2.6.0a5 → telekit-2.6.0a7}/telekit/example/example_handlers/rich.py +0 -0
  80. {telekit-2.6.0a5 → telekit-2.6.0a7}/telekit/example/example_handlers/spells.py +0 -0
  81. {telekit-2.6.0a5 → telekit-2.6.0a7}/telekit/example/example_handlers/start.py +0 -0
  82. {telekit-2.6.0a5 → telekit-2.6.0a7}/telekit/example/example_handlers/style.py +0 -0
  83. {telekit-2.6.0a5 → telekit-2.6.0a7}/telekit/example/example_handlers/text_document.py +0 -0
  84. {telekit-2.6.0a5 → telekit-2.6.0a7}/telekit/html_text.py +0 -0
  85. {telekit-2.6.0a5 → telekit-2.6.0a7}/telekit/inline_buttons.py +0 -0
  86. {telekit-2.6.0a5 → telekit-2.6.0a7}/telekit/parameters.py +0 -0
  87. {telekit-2.6.0a5 → telekit-2.6.0a7}/telekit/reply_buttons.py +0 -0
  88. {telekit-2.6.0a5 → telekit-2.6.0a7}/telekit/scheduler.py +0 -0
  89. {telekit-2.6.0a5 → telekit-2.6.0a7}/telekit/styles.py +0 -0
  90. {telekit-2.6.0a5 → telekit-2.6.0a7}/telekit/traits/__init__.py +0 -0
  91. {telekit-2.6.0a5 → telekit-2.6.0a7}/telekit/traits/calendar_pick.py +0 -0
  92. {telekit-2.6.0a5 → telekit-2.6.0a7}/telekit/traits/paginated_choice.py +0 -0
  93. {telekit-2.6.0a5 → telekit-2.6.0a7}/telekit/traits/paginated_text.py +0 -0
  94. {telekit-2.6.0a5 → telekit-2.6.0a7}/telekit/traits/track_handoff_origin.py +0 -0
  95. {telekit-2.6.0a5 → telekit-2.6.0a7}/telekit/types.py +0 -0
  96. {telekit-2.6.0a5 → telekit-2.6.0a7}/telekit.egg-info/dependency_links.txt +0 -0
  97. {telekit-2.6.0a5 → telekit-2.6.0a7}/telekit.egg-info/requires.txt +0 -0
  98. {telekit-2.6.0a5 → telekit-2.6.0a7}/telekit.egg-info/top_level.txt +0 -0
@@ -0,0 +1,56 @@
1
+ ### v2.6.0 `a7`
2
+ #### Server
3
+ - Added `restart` parameter to `Server`: `"always"` (default), `"network"` or `"never"`; accepts `RestartMode` or the matching string
4
+ - Deprecated `Server(auto_restart=...)`: `True` is now `restart="always"`, `False` is `restart="never"`; emits `DeprecationWarning` and a log warning. Cannot be combined with `restart` (`TypeError`)
5
+ - Added network protection to `Server.polling()` and `Server.long_polling()`: restarts are now delayed by exponential backoff (5 s up to 60 s, reset after 120 s of stable work) instead of a fixed 10 s / 5 s. Tunable via `Server.RESTART_DELAY_MIN`, `RESTART_DELAY_MAX` and `STABLE_AFTER`
6
+ - Added `restart="network"`: survives only network errors and Bot API `429`, `500`, `502`, `503`, `504`; any other error (bad token, `409` conflict, bugs) is re-raised. `retry_after` from Telegram is respected
7
+ - Changed `Server.__init__()` to wait for the Bot API to become reachable before calling `getMe` (skipped for `restart="never"` and when `apihelper.proxy` is set)
8
+ - Fixed `Server.polling()` and `Server.long_polling()` restarting after `stop_polling()`: they now return instead
9
+ - Fixed a failed `getMe` in the restart cycle killing the server and hiding the original error
10
+ - Fixed bot tokens leaking into logs through request URLs: they are now masked as `bot<hidden>`
11
+ - Changed log levels in `Server`: network errors are logged as `WARNING` (without traceback), unexpected errors as `ERROR` (with traceback), `FATAL` is kept for `[server dead]`.
12
+ #### Logging
13
+ - Added Rich output for logs when `rich` is installed; set `TELEKIT_NO_RICH=1` to disable it
14
+ - Added direct exports `server_logger`, `library_logger`, `user_logger` and `get_user_logger()` to `_logger.py`. `logger.server`, `logger.library`, `logger.users()`, `_server` and `_library` still work
15
+ - Added `set_level()`, `disable_user_logging()` and `UserLogger.exception()`
16
+ - Changed `telekit` loggers to `propagate=False`: records no longer reach the root logger, so they are not duplicated when the app configures it. Attach custom handlers to `logging.getLogger("telekit")`
17
+ - Changed `enable_file_logging()` to be idempotent, to create parent folders, and to use one format (with `filename:lineno`) for all files, including `server.log`
18
+ - Fixed `UserLogger` reporting its own module as the log source
19
+ #### Sender
20
+ - Added a `FileIdCache` that stores Telegram `file_id` for local files (photo, document, video, animation, audio, voice, video note), so repeated sends skip the upload
21
+ - Added `BaseSender.configure_file_cache()`: a class method that sets the database path, table name and global on/off switch
22
+ - Added `Sender.set_use_file_cache()`: a per-sender override of the global setting (`None` restores it)
23
+ - Changed missing local files to raise on `send()` instead of in the setter
24
+ - A rejected cached `file_id` is dropped and the send is retried with the original file
25
+ - Notes: URLs, `bytes` and file-like objects are not cached; rich messages and media groups are unaffected. A changed file is detected by `size/mtime`, with a `SHA-256` comparison as a fallback
26
+
27
+ ### v2.6.0 `a6` (fixes #6)
28
+ - Reworked the timeout engine to fix thread exhaustion with many concurrent chats (#6): every `set_timeout()` used to start its own `threading.Timer` (one OS thread per waiting chat), so ~1000 active users crashed the bot with `can't start new thread`
29
+ - Timeout callback exceptions are now logged
30
+ - Added `configure_timeouts(max_workers, *, idle_timeout, log_worker_changes, warn_on_max_workers)` to tune the worker pool, log worker start/stop, and control the "all workers busy" warning (enabled by default)
31
+
32
+ ### v2.6.0 `a4`
33
+ - Added `handle_handoff()` to `Handler`: a shortcut for `handoff(handler).handle()` that takes the target handler as an argument, so it can be passed to `add_callback()` without an extra closure
34
+ - Added `handle_handoff_back_or()` to `TrackHandoffOrigin`: a closure-free counterpart of `handoff_back_or()`
35
+ - Reworked `handoff_back_or()` as a thin `functools.partial` wrapper around `handle_handoff_back_or()`
36
+ - Fixed the `handoff_back_or()` docstring: the returned callable forwards its arguments to `handle()` instead of being zero-argument
37
+ - Converted the `handoff()` docstring to reST
38
+
39
+ ### v2.6.0 `a3`
40
+ - Added support for Rich HTML messages (Bot API 10.1+)
41
+ - Added the `_rich.py` module for Rich HTML parsing and serialization
42
+ - Added new rich tags to `styles.py` for enhanced text formatting
43
+ - Added the `rich.py` example handler demonstrating Rich HTML: inline styles, blocks, lists, tables, media, and sender integration
44
+
45
+ ### v2.6.0 `a2`
46
+ - Reworked `.env` and token/canvas file reading in `utils`
47
+ - Added full `.env` syntax support: comments, `export`, quotes and escapes, multi-line values, `$VAR` interpolation
48
+ - Added the `cache` parameter (default `True`) and `clear_cache()`
49
+ - Added detailed errors with fix suggestions and creation commands, and new `Env*Error` exceptions
50
+ - Changed `load_env()` to raise `EnvFileNotFoundError` for a missing file instead of returning `{}`
51
+
52
+ ### v2.6.0 `a1`
53
+ - Added a module-loading utility to `utils`
54
+
55
+ ### v2.6.0 `a0`
56
+ - Improved formatting in `_on.py`
@@ -0,0 +1,4 @@
1
+ include README.md
2
+ include CHANGELOG.md
3
+ include LICENSE
4
+ include telekit/requirements.txt
@@ -1,19 +1,20 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: telekit
3
- Version: 2.6.0a5
3
+ Version: 2.6.0a7
4
4
  Summary: Declarative, developer-friendly framework for building Telegram bots
5
5
  Home-page: https://github.com/Romashkaa/telekit
6
6
  Author: romashka
7
7
  Author-email: notromashka@gmail.com
8
- License: GPLv3
8
+ License: GPL-3.0-or-later
9
9
  Project-URL: GitHub, https://github.com/Romashkaa/telekit
10
10
  Project-URL: Telegram, https://t.me/TelekitLib
11
11
  Keywords: telegram bot api declarative tools bot-api
12
12
  Classifier: Programming Language :: Python
13
+ Classifier: Programming Language :: Python :: 3 :: Only
13
14
  Classifier: Programming Language :: Python :: 3.12
14
15
  Classifier: Programming Language :: Python :: 3.13
15
16
  Classifier: Programming Language :: Python :: 3.14
16
- Classifier: License :: OSI Approved :: GNU General Public License v3 (GPLv3)
17
+ Classifier: License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)
17
18
  Classifier: Operating System :: OS Independent
18
19
  Requires-Python: >=3.12
19
20
  Description-Content-Type: text/markdown
@@ -28,6 +29,7 @@ Dynamic: description
28
29
  Dynamic: description-content-type
29
30
  Dynamic: home-page
30
31
  Dynamic: keywords
32
+ Dynamic: license
31
33
  Dynamic: license-file
32
34
  Dynamic: project-url
33
35
  Dynamic: requires-dist
@@ -57,7 +59,9 @@ class MyStartHandler(telekit.Handler):
57
59
  self.chain.sender.set_photo("robot.png")
58
60
  self.chain.send()
59
61
 
60
- telekit.Server("BOT_TOKEN").polling()
62
+ TOKEN: str = telekit.utils.read_token(".env")
63
+
64
+ telekit.Server(TOKEN).polling()
61
65
  ```
62
66
 
63
67
  > Send "Hello!" with a photo on `/start`
@@ -83,6 +87,7 @@ Even in its beta stage, Telekit accelerates bot development, offering typed **co
83
87
  - **Chains** handle complex conversations without state machines
84
88
  - [Ready-to-use DSL](https://github.com/Romashkaa/telekit/blob/main/docs/tutorial/11_telekit_dsl.md) for FAQs and interactive scripts
85
89
  - Automatic [message formatting](https://github.com/Romashkaa/telekit/blob/main/docs/tutorial2/6_styles.md) via [Sender](https://github.com/Romashkaa/telekit/blob/main/docs/tutorial2/5_senders.md) and **callback routing**
90
+ - Automatic **`file_id` caching**: local files are uploaded once and reused afterwards
86
91
  - **Deep Linking** with type-checked [Command Parameters](https://github.com/Romashkaa/telekit/blob/main/docs/tutorial2/command_trigger_parameters.md)
87
92
  - Built-in **Permission** and **Logging** system
88
93
  - Reusable **Traits** for pluggable behavior modules
@@ -291,6 +296,8 @@ self.chain.sender.set_text_as_document("Hello, this is a text document!") # Conv
291
296
  self.chain.sender.send_chat_action(ChatAction.TYPING) # Send chat action. Use enum or string
292
297
  ```
293
298
 
299
+ Local files are uploaded to Telegram once. Telekit stores the returned `file_id` in a database and reuses it on every next send, so repeated messages with the same photo, document or video go out almost instantly.
300
+
294
301
  > [!NOTE]
295
302
  > Telekit picks `bot.send_message` or `bot.send_photo` based on the content you attach.
296
303
 
@@ -457,9 +464,10 @@ It includes example commands, dialogs, keyboards, and style usage.
457
464
  - Chains instead of an FSM.
458
465
  - Declarative, behavior-focused bot logic with minimal boilerplate.
459
466
  - Automatic callback routing and input handling.
460
- - A Styles API for rich text (`Bold`, `Italic`, links) with automatic escaping.
467
+ - Automatic `file_id` caching for local files: no re-uploads, no manual bookkeeping.
468
+ - Styles API for rich text (`Bold`, `Italic`, links) with automatic escaping.
461
469
  - Deep linking and typed command parameters.
462
- - A built-in DSL for menus, FAQs, and simple bots.
470
+ - Built-in DSL for menus, FAQs, and simple bots.
463
471
  - Reusable Traits for composable behavior, including a built-in calendar picker.
464
472
  - Zero-code mode [Obsidian Canvas](https://github.com/Romashkaa/telekit/blob/main/docs/examples/canvas_faq.md) mode.
465
473
  - Works with `pyTelegramBotAPI`.
@@ -471,7 +479,38 @@ Telekit focuses on one job: making Telegram bot development easier.
471
479
 
472
480
  ---
473
481
 
474
- # Changes in version 2.6.0a5
482
+ # Changelog
483
+
484
+ ### v2.6.0 `a7`
485
+ #### Server
486
+ - Added `restart` parameter to `Server`: `"always"` (default), `"network"` or `"never"`; accepts `RestartMode` or the matching string
487
+ - Deprecated `Server(auto_restart=...)`: `True` is now `restart="always"`, `False` is `restart="never"`; emits `DeprecationWarning` and a log warning. Cannot be combined with `restart` (`TypeError`)
488
+ - Added network protection to `Server.polling()` and `Server.long_polling()`: restarts are now delayed by exponential backoff (5 s up to 60 s, reset after 120 s of stable work) instead of a fixed 10 s / 5 s. Tunable via `Server.RESTART_DELAY_MIN`, `RESTART_DELAY_MAX` and `STABLE_AFTER`
489
+ - Added `restart="network"`: survives only network errors and Bot API `429`, `500`, `502`, `503`, `504`; any other error (bad token, `409` conflict, bugs) is re-raised. `retry_after` from Telegram is respected
490
+ - Changed `Server.__init__()` to wait for the Bot API to become reachable before calling `getMe` (skipped for `restart="never"` and when `apihelper.proxy` is set)
491
+ - Fixed `Server.polling()` and `Server.long_polling()` restarting after `stop_polling()`: they now return instead
492
+ - Fixed a failed `getMe` in the restart cycle killing the server and hiding the original error
493
+ - Fixed bot tokens leaking into logs through request URLs: they are now masked as `bot<hidden>`
494
+ - Changed log levels in `Server`: network errors are logged as `WARNING` (without traceback), unexpected errors as `ERROR` (with traceback), `FATAL` is kept for `[server dead]`.
495
+ #### Logging
496
+ - Added Rich output for logs when `rich` is installed; set `TELEKIT_NO_RICH=1` to disable it
497
+ - Added direct exports `server_logger`, `library_logger`, `user_logger` and `get_user_logger()` to `_logger.py`. `logger.server`, `logger.library`, `logger.users()`, `_server` and `_library` still work
498
+ - Added `set_level()`, `disable_user_logging()` and `UserLogger.exception()`
499
+ - Changed `telekit` loggers to `propagate=False`: records no longer reach the root logger, so they are not duplicated when the app configures it. Attach custom handlers to `logging.getLogger("telekit")`
500
+ - Changed `enable_file_logging()` to be idempotent, to create parent folders, and to use one format (with `filename:lineno`) for all files, including `server.log`
501
+ - Fixed `UserLogger` reporting its own module as the log source
502
+ #### Sender
503
+ - Added a `FileIdCache` that stores Telegram `file_id` for local files (photo, document, video, animation, audio, voice, video note), so repeated sends skip the upload
504
+ - Added `BaseSender.configure_file_cache()`: a class method that sets the database path, table name and global on/off switch
505
+ - Added `Sender.set_use_file_cache()`: a per-sender override of the global setting (`None` restores it)
506
+ - Changed missing local files to raise on `send()` instead of in the setter
507
+ - A rejected cached `file_id` is dropped and the send is retried with the original file
508
+ - Notes: URLs, `bytes` and file-like objects are not cached; rich messages and media groups are unaffected. A changed file is detected by `size/mtime`, with a `SHA-256` comparison as a fallback
509
+
510
+ ### v2.6.0 `a6` (fixes #6)
511
+ - Reworked the timeout engine to fix thread exhaustion with many concurrent chats (#6): every `set_timeout()` used to start its own `threading.Timer` (one OS thread per waiting chat), so ~1000 active users crashed the bot with `can't start new thread`
512
+ - Timeout callback exceptions are now logged
513
+ - Added `configure_timeouts(max_workers, *, idle_timeout, log_worker_changes, warn_on_max_workers)` to tune the worker pool, log worker start/stop, and control the "all workers busy" warning (enabled by default)
475
514
 
476
515
  ### v2.6.0 `a4`
477
516
  - Added `handle_handoff()` to `Handler`: a shortcut for `handoff(handler).handle()` that takes the target handler as an argument, so it can be passed to `add_callback()` without an extra closure
@@ -21,7 +21,9 @@ class MyStartHandler(telekit.Handler):
21
21
  self.chain.sender.set_photo("robot.png")
22
22
  self.chain.send()
23
23
 
24
- telekit.Server("BOT_TOKEN").polling()
24
+ TOKEN: str = telekit.utils.read_token(".env")
25
+
26
+ telekit.Server(TOKEN).polling()
25
27
  ```
26
28
 
27
29
  > Send "Hello!" with a photo on `/start`
@@ -47,6 +49,7 @@ Even in its beta stage, Telekit accelerates bot development, offering typed **co
47
49
  - **Chains** handle complex conversations without state machines
48
50
  - [Ready-to-use DSL](https://github.com/Romashkaa/telekit/blob/main/docs/tutorial/11_telekit_dsl.md) for FAQs and interactive scripts
49
51
  - Automatic [message formatting](https://github.com/Romashkaa/telekit/blob/main/docs/tutorial2/6_styles.md) via [Sender](https://github.com/Romashkaa/telekit/blob/main/docs/tutorial2/5_senders.md) and **callback routing**
52
+ - Automatic **`file_id` caching**: local files are uploaded once and reused afterwards
50
53
  - **Deep Linking** with type-checked [Command Parameters](https://github.com/Romashkaa/telekit/blob/main/docs/tutorial2/command_trigger_parameters.md)
51
54
  - Built-in **Permission** and **Logging** system
52
55
  - Reusable **Traits** for pluggable behavior modules
@@ -255,6 +258,8 @@ self.chain.sender.set_text_as_document("Hello, this is a text document!") # Conv
255
258
  self.chain.sender.send_chat_action(ChatAction.TYPING) # Send chat action. Use enum or string
256
259
  ```
257
260
 
261
+ Local files are uploaded to Telegram once. Telekit stores the returned `file_id` in a database and reuses it on every next send, so repeated messages with the same photo, document or video go out almost instantly.
262
+
258
263
  > [!NOTE]
259
264
  > Telekit picks `bot.send_message` or `bot.send_photo` based on the content you attach.
260
265
 
@@ -421,9 +426,10 @@ It includes example commands, dialogs, keyboards, and style usage.
421
426
  - Chains instead of an FSM.
422
427
  - Declarative, behavior-focused bot logic with minimal boilerplate.
423
428
  - Automatic callback routing and input handling.
424
- - A Styles API for rich text (`Bold`, `Italic`, links) with automatic escaping.
429
+ - Automatic `file_id` caching for local files: no re-uploads, no manual bookkeeping.
430
+ - Styles API for rich text (`Bold`, `Italic`, links) with automatic escaping.
425
431
  - Deep linking and typed command parameters.
426
- - A built-in DSL for menus, FAQs, and simple bots.
432
+ - Built-in DSL for menus, FAQs, and simple bots.
427
433
  - Reusable Traits for composable behavior, including a built-in calendar picker.
428
434
  - Zero-code mode [Obsidian Canvas](https://github.com/Romashkaa/telekit/blob/main/docs/examples/canvas_faq.md) mode.
429
435
  - Works with `pyTelegramBotAPI`.
@@ -2,6 +2,3 @@
2
2
  tag_build =
3
3
  tag_date = 0
4
4
 
5
- [metadata]
6
- license = GPLv3
7
-
@@ -0,0 +1,71 @@
1
+ import re
2
+ from pathlib import Path
3
+
4
+ from setuptools import setup, find_packages
5
+
6
+ ROOT = Path(__file__).resolve().parent
7
+
8
+ # -----------------------------------------------------------------------------
9
+ # Read files
10
+ # -----------------------------------------------------------------------------
11
+
12
+ def read(name: str) -> str:
13
+ return (ROOT / name).read_text(encoding="utf-8")
14
+
15
+
16
+ def read_version() -> str:
17
+ text = read("telekit/__version__.py")
18
+ match = re.search(r'__version__\s*=\s*["\']([^"\']+)["\']', text)
19
+ if match is None:
20
+ raise RuntimeError("Could not find __version__ in telekit/__version__.py")
21
+ return match.group(1)
22
+
23
+
24
+ def install_requires() -> list[str]:
25
+ return [
26
+ line.strip()
27
+ for line in read("telekit/requirements.txt").splitlines()
28
+ if line.strip() and not line.lstrip().startswith("#")
29
+ ]
30
+
31
+
32
+ def long_description() -> str:
33
+ return f"{read('README.md')}\n\n---\n\n# Changelog\n\n{read('CHANGELOG.md')}"
34
+
35
+
36
+ version = read_version()
37
+
38
+ # -----------------------------------------------------------------------------
39
+ # Setup
40
+ # -----------------------------------------------------------------------------
41
+
42
+ setup(
43
+ name="telekit",
44
+ version=version,
45
+ description="Declarative, developer-friendly framework for building Telegram bots",
46
+ long_description=long_description(),
47
+ long_description_content_type="text/markdown",
48
+ keywords="telegram bot api declarative tools bot-api",
49
+ author="romashka",
50
+ author_email="notromashka@gmail.com",
51
+ url="https://github.com/Romashkaa/telekit",
52
+ packages=find_packages(),
53
+ include_package_data=True,
54
+ install_requires=install_requires(),
55
+ python_requires=">=3.12",
56
+ license="GPL-3.0-or-later",
57
+ license_files=["LICENSE"],
58
+ classifiers=[
59
+ "Programming Language :: Python",
60
+ "Programming Language :: Python :: 3 :: Only",
61
+ "Programming Language :: Python :: 3.12",
62
+ "Programming Language :: Python :: 3.13",
63
+ "Programming Language :: Python :: 3.14",
64
+ "License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)",
65
+ "Operating System :: OS Independent",
66
+ ],
67
+ project_urls={
68
+ "GitHub": "https://github.com/Romashkaa/telekit",
69
+ "Telegram": "https://t.me/TelekitLib",
70
+ },
71
+ )
@@ -21,7 +21,7 @@ from ._handler import Handler
21
21
  from ._trait import Trait
22
22
  from ._chain import Chain
23
23
  from ._callback_query_handler import CallbackQueryHandler
24
- from .server import Server, example
24
+ from .server import Server, RestartMode, RestartLiteral, ProxyType, example
25
25
  from ._inline_keyboard import InlineKeyboard
26
26
  from ._reply_keyboard import ReplyKeyboard
27
27
  from ._text_builder import TextBuilder
@@ -32,7 +32,7 @@ from ._telekit_dsl.telekit_dsl import TelekitDSL
32
32
  from ._telekit_dsl.mixin import DSLHandler, InstanceDSLHandler
33
33
  from ._logger import enable_file_logging
34
34
  from .chat import Chat
35
-
35
+ from ._timeout import configure_timeouts
36
36
  from . import senders
37
37
  from . import types
38
38
  from . import styles
@@ -48,8 +48,8 @@ from . import html_text
48
48
 
49
49
  Styles = styles.Styles
50
50
 
51
- from ._version import __version__
52
-
51
+ from .__version__ import __version__
52
+
53
53
  __all__ = [
54
54
  "traits",
55
55
  "utils",
@@ -62,11 +62,15 @@ __all__ = [
62
62
  "scheduler",
63
63
  "chat",
64
64
  "html_text",
65
+ "configure_timeouts",
65
66
 
66
67
  "Styles",
67
68
  "User",
68
69
 
69
70
  "Server",
71
+ "RestartMode",
72
+ "RestartLiteral",
73
+ "ProxyType",
70
74
  "Chat",
71
75
  "Chain",
72
76
  "Trait",
@@ -1,6 +1,5 @@
1
1
  # ––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––
2
- # PyPI package version: https://img.shields.io/pypi/v/telekit.svg
3
2
  # PyPI history: https://pypi.org/project/telekit/#history
4
3
  # ––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––
5
4
 
6
- __version__ = "2.6.0a5"
5
+ __version__ = "2.6.0a7"
@@ -30,7 +30,7 @@ from .debug import Debug
30
30
  from .styles import TextEntity
31
31
 
32
32
  # Chain modules
33
- from ._chain_base import _library
33
+ from ._chain_base import library_logger
34
34
  from ._chain_inline_keyboards_logic import ChainInlineKeyboardLogic
35
35
  from ._chain_entry_logic import ChainEntryLogic, TextDocument
36
36
 
@@ -158,7 +158,7 @@ class Chain(ChainInlineKeyboardLogic, ChainEntryLogic):
158
158
  self._previous_message = message
159
159
 
160
160
  if Debug.timeout_warnings and _handler and not _timeout:
161
- _library.warning(
161
+ library_logger.warning(
162
162
  "Next-message handler is active, but no timeout was set for the chain. "
163
163
  "This may cause the bot to wait indefinitely."
164
164
  )
@@ -31,7 +31,7 @@ from . import _timeout
31
31
 
32
32
  # Logging
33
33
  from .debug import Debug
34
- from ._logger import _library as _library
34
+ from ._logger import library_logger
35
35
 
36
36
  class ChainBase:
37
37
 
@@ -130,9 +130,12 @@ class ChainBase:
130
130
  """
131
131
  Enables or disables automatic timeout removal after sending a message.
132
132
 
133
- When True, the timeout handler will be cleared after each message,
133
+ When True, the timeout handler will be cleared after each message,
134
134
  preventing it from triggering for every subsequent message.
135
- Set to False if you want to keep the same timeout across messages.
135
+
136
+ When False, the timeout callback is kept and the countdown starts over
137
+ after every `chain.send()` / `chain.edit()`: the timeout is measured from
138
+ the last sent message, not from the first one.
136
139
  """
137
140
  self._do_remove_timeout = remove_timeout
138
141
 
@@ -34,7 +34,7 @@ from ._callback_query_handler import CallbackQueryHandler
34
34
  from ._inline_keyboard import InlineKeyboard
35
35
  from ._reply_keyboard import ReplyKeyboard
36
36
  from ._inline_buttons import InlineButton, CallbackButton
37
- from ._chain_base import ChainBase, _library
37
+ from ._chain_base import ChainBase, library_logger
38
38
 
39
39
  if typing.TYPE_CHECKING:
40
40
  from ._chain import Chain # only for type hints
@@ -251,7 +251,7 @@ class ChainInlineKeyboardLogic(ChainBase):
251
251
  if not isinstance(choices, dict):
252
252
  for c in choices:
253
253
  if type(c).__str__ is object.__str__:
254
- _library.warning(
254
+ library_logger.warning(
255
255
  f"{type(c).__name__} does not implement __str__. "
256
256
  f"Consider passing a dict with explicit labels.",
257
257
  stacklevel=3
@@ -421,11 +421,13 @@ class ChainInlineKeyboardLogic(ChainBase):
421
421
  return invoker
422
422
 
423
423
  def _answer_callback_query(self, call: CallbackQuery, query_answer: tuple[str, bool] | None = None):
424
+ call_id: int = int(call.id)
425
+
424
426
  if query_answer is None:
425
- self.bot.answer_callback_query(call.id)
427
+ self.bot.answer_callback_query(call_id)
426
428
  else:
427
429
  self.bot.answer_callback_query(
428
- call.id,
430
+ call_id,
429
431
  text=query_answer[0],
430
432
  show_alert=query_answer[1]
431
433
  )
@@ -0,0 +1,136 @@
1
+ import hashlib
2
+ import os
3
+ from typing import Any, Literal
4
+
5
+ from telebot.types import Message
6
+
7
+ from ._logger import logger
8
+ library = logger.library
9
+
10
+ FileKind = Literal["photo", "document", "video", "animation", "audio", "voice", "video_note"]
11
+
12
+ # for BaseSender
13
+ FILE_KINDS: tuple[FileKind, ...] = (
14
+ "photo", "document", "video", "animation", "audio", "voice", "video_note"
15
+ )
16
+ """Supported file kinds. See :meth:`senders.BaseSender._active_kind`."""
17
+
18
+ CacheEntry = tuple[str, str, str]
19
+ """(db key, stat signature, content hash)"""
20
+
21
+
22
+ class FileIdCache:
23
+ """Caches Telegram file_id for LOCAL files, validated by a content hash."""
24
+
25
+ enabled: bool = True
26
+ path: str = "file_cache"
27
+ table_name: str = "file_ids"
28
+
29
+ _vault: Any = None
30
+
31
+ @classmethod
32
+ def configure(
33
+ cls, *,
34
+ path: str | None = None,
35
+ enabled: bool | None = None,
36
+ table_name: str | None = None,
37
+ ) -> None:
38
+ if path is not None and path != cls.path:
39
+ cls.path = path
40
+ cls._vault = None
41
+ if table_name is not None and table_name != cls.table_name:
42
+ cls.table_name = table_name
43
+ cls._vault = None
44
+ if enabled is not None:
45
+ cls.enabled = enabled
46
+
47
+ @classmethod
48
+ def _get_vault(cls):
49
+ if cls._vault is None:
50
+ from telekit import Vault
51
+ cls._vault = Vault(
52
+ path=cls.path,
53
+ table_name=cls.table_name,
54
+ key_field_name="source",
55
+ value_field_name="file_id",
56
+ )
57
+ return cls._vault
58
+
59
+ # ---------------- hashing ----------------
60
+
61
+ @staticmethod
62
+ def file_hash(path: str) -> str | None:
63
+ h = hashlib.sha256()
64
+ try:
65
+ with open(path, "rb") as f:
66
+ while chunk := f.read(1024 * 1024):
67
+ h.update(chunk)
68
+ except OSError:
69
+ return None
70
+ return h.hexdigest()
71
+
72
+ # ---------------- storage ----------------
73
+
74
+ @classmethod
75
+ def forget(cls, key: str) -> None:
76
+ try:
77
+ cls._get_vault()[key] = "" # empty value == miss
78
+ except Exception as e:
79
+ library.warning(f"file_id cache write failed: {e}")
80
+
81
+ @staticmethod
82
+ def extract(kind: str, message: Message | None) -> str | None:
83
+ if message is None:
84
+ return None
85
+ if kind == "photo":
86
+ return message.photo[-1].file_id if message.photo else None
87
+ obj = getattr(message, kind, None)
88
+ return getattr(obj, "file_id", None)
89
+
90
+ @classmethod
91
+ def lookup(cls, bot_id: str, kind: str, source: str) -> tuple[str | None, CacheEntry | None]:
92
+ """
93
+ Returns (file_id | None, entry | None).
94
+ entry is None if the file can't be read.
95
+ A hash is computed only when size/mtime differ from the stored record.
96
+ """
97
+ try:
98
+ st = os.stat(source)
99
+ except OSError:
100
+ return None, None
101
+
102
+ key = f"{bot_id}|{kind}|{os.path.abspath(source)}"
103
+ sig = f"{st.st_size}:{st.st_mtime_ns}"
104
+
105
+ stored_sig = stored_hash = stored_id = ""
106
+ try:
107
+ value = cls._get_vault().get(key, None)
108
+ if value:
109
+ parts = value.split("|")
110
+ if len(parts) == 3:
111
+ stored_sig, stored_hash, stored_id = parts
112
+ except Exception as e:
113
+ library.warning(f"file_id cache read failed: {e}")
114
+
115
+ # fast path: nothing changed
116
+ if stored_id and stored_sig == sig:
117
+ return stored_id, (key, sig, stored_hash)
118
+
119
+ # slow path: size/mtime changed (or no record) -> hash the content
120
+ file_hash = cls.file_hash(source)
121
+ if file_hash is None:
122
+ return None, None
123
+
124
+ if stored_id and stored_hash == file_hash:
125
+ # content is the same, only the stat changed: refresh the record
126
+ cls.set(key, sig, file_hash, stored_id)
127
+ return stored_id, (key, sig, file_hash)
128
+
129
+ return None, (key, sig, file_hash)
130
+
131
+ @classmethod
132
+ def set(cls, key: str, sig: str, file_hash: str, file_id: str) -> None:
133
+ try:
134
+ cls._get_vault()[key] = f"{sig}|{file_hash}|{file_id}"
135
+ except Exception as e:
136
+ library.warning(f"file_id cache write failed: {e}")