telekit 2.6.0a4__tar.gz → 2.6.0a6__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 (90) hide show
  1. {telekit-2.6.0a4 → telekit-2.6.0a6}/PKG-INFO +11 -4
  2. {telekit-2.6.0a4 → telekit-2.6.0a6}/README.md +4 -2
  3. {telekit-2.6.0a4 → telekit-2.6.0a6}/telekit/__init__.py +2 -1
  4. {telekit-2.6.0a4 → telekit-2.6.0a6}/telekit/_chain.py +3 -1
  5. {telekit-2.6.0a4 → telekit-2.6.0a6}/telekit/_chain_base.py +5 -2
  6. {telekit-2.6.0a4 → telekit-2.6.0a6}/telekit/_chain_inline_keyboards_logic.py +4 -2
  7. telekit-2.6.0a6/telekit/_timeout.py +424 -0
  8. {telekit-2.6.0a4 → telekit-2.6.0a6}/telekit/_version.py +1 -1
  9. {telekit-2.6.0a4 → telekit-2.6.0a6}/telekit/senders.py +7 -0
  10. {telekit-2.6.0a4 → telekit-2.6.0a6}/telekit/utils.py +40 -30
  11. {telekit-2.6.0a4 → telekit-2.6.0a6}/telekit.egg-info/PKG-INFO +11 -4
  12. telekit-2.6.0a4/telekit/_timeout.py +0 -73
  13. {telekit-2.6.0a4 → telekit-2.6.0a6}/LICENSE +0 -0
  14. {telekit-2.6.0a4 → telekit-2.6.0a6}/setup.cfg +0 -0
  15. {telekit-2.6.0a4 → telekit-2.6.0a6}/setup.py +0 -0
  16. {telekit-2.6.0a4 → telekit-2.6.0a6}/telekit/_buildtext/__init__.py +0 -0
  17. {telekit-2.6.0a4 → telekit-2.6.0a6}/telekit/_buildtext/formatter.py +0 -0
  18. {telekit-2.6.0a4 → telekit-2.6.0a6}/telekit/_buildtext/styles.py +0 -0
  19. {telekit-2.6.0a4 → telekit-2.6.0a6}/telekit/_callback_query_handler.py +0 -0
  20. {telekit-2.6.0a4 → telekit-2.6.0a6}/telekit/_chain_entry_logic.py +0 -0
  21. {telekit-2.6.0a4 → telekit-2.6.0a6}/telekit/_chapters/__init__.py +0 -0
  22. {telekit-2.6.0a4 → telekit-2.6.0a6}/telekit/_chapters/chapters.py +0 -0
  23. {telekit-2.6.0a4 → telekit-2.6.0a6}/telekit/_handler.py +0 -0
  24. {telekit-2.6.0a4 → telekit-2.6.0a6}/telekit/_init.py +0 -0
  25. {telekit-2.6.0a4 → telekit-2.6.0a6}/telekit/_inline_buttons.py +0 -0
  26. {telekit-2.6.0a4 → telekit-2.6.0a6}/telekit/_inline_keyboard.py +0 -0
  27. {telekit-2.6.0a4 → telekit-2.6.0a6}/telekit/_input_handler.py +0 -0
  28. {telekit-2.6.0a4 → telekit-2.6.0a6}/telekit/_logger.py +0 -0
  29. {telekit-2.6.0a4 → telekit-2.6.0a6}/telekit/_on.py +0 -0
  30. {telekit-2.6.0a4 → telekit-2.6.0a6}/telekit/_reply_keyboard.py +0 -0
  31. {telekit-2.6.0a4 → telekit-2.6.0a6}/telekit/_rich.py +0 -0
  32. {telekit-2.6.0a4 → telekit-2.6.0a6}/telekit/_snapvault/__init__.py +0 -0
  33. {telekit-2.6.0a4 → telekit-2.6.0a6}/telekit/_snapvault/snapcode.py +0 -0
  34. {telekit-2.6.0a4 → telekit-2.6.0a6}/telekit/_snapvault/snapvault.py +0 -0
  35. {telekit-2.6.0a4 → telekit-2.6.0a6}/telekit/_state.py +0 -0
  36. {telekit-2.6.0a4 → telekit-2.6.0a6}/telekit/_telekit_dsl/__init__.py +0 -0
  37. {telekit-2.6.0a4 → telekit-2.6.0a6}/telekit/_telekit_dsl/mixin.py +0 -0
  38. {telekit-2.6.0a4 → telekit-2.6.0a6}/telekit/_telekit_dsl/parser/__init__.py +0 -0
  39. {telekit-2.6.0a4 → telekit-2.6.0a6}/telekit/_telekit_dsl/parser/builder.py +0 -0
  40. {telekit-2.6.0a4 → telekit-2.6.0a6}/telekit/_telekit_dsl/parser/canvas_parser.py +0 -0
  41. {telekit-2.6.0a4 → telekit-2.6.0a6}/telekit/_telekit_dsl/parser/lexer.py +0 -0
  42. {telekit-2.6.0a4 → telekit-2.6.0a6}/telekit/_telekit_dsl/parser/nodes.py +0 -0
  43. {telekit-2.6.0a4 → telekit-2.6.0a6}/telekit/_telekit_dsl/parser/parser.py +0 -0
  44. {telekit-2.6.0a4 → telekit-2.6.0a6}/telekit/_telekit_dsl/parser/token.py +0 -0
  45. {telekit-2.6.0a4 → telekit-2.6.0a6}/telekit/_telekit_dsl/telekit_dsl.py +0 -0
  46. {telekit-2.6.0a4 → telekit-2.6.0a6}/telekit/_telekit_dsl/telekit_orm.py +0 -0
  47. {telekit-2.6.0a4 → telekit-2.6.0a6}/telekit/_text_builder.py +0 -0
  48. {telekit-2.6.0a4 → telekit-2.6.0a6}/telekit/_trait.py +0 -0
  49. {telekit-2.6.0a4 → telekit-2.6.0a6}/telekit/_user.py +0 -0
  50. {telekit-2.6.0a4 → telekit-2.6.0a6}/telekit/chat.py +0 -0
  51. {telekit-2.6.0a4 → telekit-2.6.0a6}/telekit/debug.py +0 -0
  52. {telekit-2.6.0a4 → telekit-2.6.0a6}/telekit/dices.py +0 -0
  53. {telekit-2.6.0a4 → telekit-2.6.0a6}/telekit/example/__init__.py +0 -0
  54. {telekit-2.6.0a4 → telekit-2.6.0a6}/telekit/example/example_handlers/__init__.py +0 -0
  55. {telekit-2.6.0a4 → telekit-2.6.0a6}/telekit/example/example_handlers/article.py +0 -0
  56. {telekit-2.6.0a4 → telekit-2.6.0a6}/telekit/example/example_handlers/calendar.py +0 -0
  57. {telekit-2.6.0a4 → telekit-2.6.0a6}/telekit/example/example_handlers/complete_hotel.py +0 -0
  58. {telekit-2.6.0a4 → telekit-2.6.0a6}/telekit/example/example_handlers/counter.py +0 -0
  59. {telekit-2.6.0a4 → telekit-2.6.0a6}/telekit/example/example_handlers/dsl.py +0 -0
  60. {telekit-2.6.0a4 → telekit-2.6.0a6}/telekit/example/example_handlers/entry.py +0 -0
  61. {telekit-2.6.0a4 → telekit-2.6.0a6}/telekit/example/example_handlers/faq.py +0 -0
  62. {telekit-2.6.0a4 → telekit-2.6.0a6}/telekit/example/example_handlers/hotel.py +0 -0
  63. {telekit-2.6.0a4 → telekit-2.6.0a6}/telekit/example/example_handlers/on_text.py +0 -0
  64. {telekit-2.6.0a4 → telekit-2.6.0a6}/telekit/example/example_handlers/pages.py +0 -0
  65. {telekit-2.6.0a4 → telekit-2.6.0a6}/telekit/example/example_handlers/pyapi.py +0 -0
  66. {telekit-2.6.0a4 → telekit-2.6.0a6}/telekit/example/example_handlers/qr.py +0 -0
  67. {telekit-2.6.0a4 → telekit-2.6.0a6}/telekit/example/example_handlers/quiz.py +0 -0
  68. {telekit-2.6.0a4 → telekit-2.6.0a6}/telekit/example/example_handlers/rich.py +0 -0
  69. {telekit-2.6.0a4 → telekit-2.6.0a6}/telekit/example/example_handlers/spells.py +0 -0
  70. {telekit-2.6.0a4 → telekit-2.6.0a6}/telekit/example/example_handlers/start.py +0 -0
  71. {telekit-2.6.0a4 → telekit-2.6.0a6}/telekit/example/example_handlers/style.py +0 -0
  72. {telekit-2.6.0a4 → telekit-2.6.0a6}/telekit/example/example_handlers/text_document.py +0 -0
  73. {telekit-2.6.0a4 → telekit-2.6.0a6}/telekit/example/example_server.py +0 -0
  74. {telekit-2.6.0a4 → telekit-2.6.0a6}/telekit/html_text.py +0 -0
  75. {telekit-2.6.0a4 → telekit-2.6.0a6}/telekit/inline_buttons.py +0 -0
  76. {telekit-2.6.0a4 → telekit-2.6.0a6}/telekit/parameters.py +0 -0
  77. {telekit-2.6.0a4 → telekit-2.6.0a6}/telekit/reply_buttons.py +0 -0
  78. {telekit-2.6.0a4 → telekit-2.6.0a6}/telekit/scheduler.py +0 -0
  79. {telekit-2.6.0a4 → telekit-2.6.0a6}/telekit/server.py +0 -0
  80. {telekit-2.6.0a4 → telekit-2.6.0a6}/telekit/styles.py +0 -0
  81. {telekit-2.6.0a4 → telekit-2.6.0a6}/telekit/traits/__init__.py +0 -0
  82. {telekit-2.6.0a4 → telekit-2.6.0a6}/telekit/traits/calendar_pick.py +0 -0
  83. {telekit-2.6.0a4 → telekit-2.6.0a6}/telekit/traits/paginated_choice.py +0 -0
  84. {telekit-2.6.0a4 → telekit-2.6.0a6}/telekit/traits/paginated_text.py +0 -0
  85. {telekit-2.6.0a4 → telekit-2.6.0a6}/telekit/traits/track_handoff_origin.py +0 -0
  86. {telekit-2.6.0a4 → telekit-2.6.0a6}/telekit/types.py +0 -0
  87. {telekit-2.6.0a4 → telekit-2.6.0a6}/telekit.egg-info/SOURCES.txt +0 -0
  88. {telekit-2.6.0a4 → telekit-2.6.0a6}/telekit.egg-info/dependency_links.txt +0 -0
  89. {telekit-2.6.0a4 → telekit-2.6.0a6}/telekit.egg-info/requires.txt +0 -0
  90. {telekit-2.6.0a4 → telekit-2.6.0a6}/telekit.egg-info/top_level.txt +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: telekit
3
- Version: 2.6.0a4
3
+ Version: 2.6.0a6
4
4
  Summary: Declarative, developer-friendly framework for building Telegram bots
5
5
  Home-page: https://github.com/Romashkaa/telekit
6
6
  Author: romashka
@@ -42,7 +42,7 @@ Dynamic: summary
42
42
 
43
43
  # Telekit
44
44
 
45
- **Telekit** is a declarative, developer-friendly library for building Telegram bots. It gives developers a dedicated Sender for composing and sending messages and a Chain for handling dialogue between the user and the bot. The library also handles inline keyboards and callback routing automatically, letting you focus on the bot's behavior instead of repetitive tasks.
45
+ **Telekit** is a declarative, developer-friendly framework for building Telegram bots. It gives developers a dedicated Sender for composing and sending messages and a Chain for handling dialogue between the user and the bot. The framework also handles inline keyboards and callback routing automatically, letting you focus on the bot's behavior instead of repetitive tasks.
46
46
 
47
47
  ```py
48
48
  import telekit
@@ -57,7 +57,9 @@ class MyStartHandler(telekit.Handler):
57
57
  self.chain.sender.set_photo("robot.png")
58
58
  self.chain.send()
59
59
 
60
- telekit.Server("BOT_TOKEN").polling()
60
+ TOKEN: str = telekit.utils.read_token(".env")
61
+
62
+ telekit.Server(TOKEN).polling()
61
63
  ```
62
64
 
63
65
  > Send "Hello!" with a photo on `/start`
@@ -471,7 +473,12 @@ Telekit focuses on one job: making Telegram bot development easier.
471
473
 
472
474
  ---
473
475
 
474
- # Changes in version 2.6.0a4
476
+ # Changes in version 2.6.0a6
477
+
478
+ ### v2.6.0 `a6` (Fixes #6)
479
+ - 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`
480
+ - Timeout callback exceptions are now logged
481
+ - 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
482
 
476
483
  ### v2.6.0 `a4`
477
484
  - 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
@@ -6,7 +6,7 @@
6
6
 
7
7
  # Telekit
8
8
 
9
- **Telekit** is a declarative, developer-friendly library for building Telegram bots. It gives developers a dedicated Sender for composing and sending messages and a Chain for handling dialogue between the user and the bot. The library also handles inline keyboards and callback routing automatically, letting you focus on the bot's behavior instead of repetitive tasks.
9
+ **Telekit** is a declarative, developer-friendly framework for building Telegram bots. It gives developers a dedicated Sender for composing and sending messages and a Chain for handling dialogue between the user and the bot. The framework also handles inline keyboards and callback routing automatically, letting you focus on the bot's behavior instead of repetitive tasks.
10
10
 
11
11
  ```py
12
12
  import telekit
@@ -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`
@@ -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
@@ -62,6 +62,7 @@ __all__ = [
62
62
  "scheduler",
63
63
  "chat",
64
64
  "html_text",
65
+ "configure_timeouts",
65
66
 
66
67
  "Styles",
67
68
  "User",
@@ -153,7 +153,9 @@ class Chain(ChainInlineKeyboardLogic, ChainEntryLogic):
153
153
 
154
154
  # reset edit target and store new previous message
155
155
  self.sender.set_edit_message(None)
156
- self._previous_message = message
156
+
157
+ if message is not None:
158
+ self._previous_message = message
157
159
 
158
160
  if Debug.timeout_warnings and _handler and not _timeout:
159
161
  _library.warning(
@@ -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
 
@@ -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,424 @@
1
+ #
2
+ # Copyright (C) 2026 Romashka
3
+ #
4
+ # This file is part of Telekit.
5
+ #
6
+ # Telekit is free software: you can redistribute it and/or modify it
7
+ # under the terms of the GNU General Public License as published by
8
+ # the Free Software Foundation, either version 3 of the License, or
9
+ # (at your option) any later version.
10
+ #
11
+ # Telekit is distributed in the hope that it will be useful,
12
+ # but WITHOUT ANY WARRANTY; without even the implied warranty
13
+ # of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See
14
+ # the GNU General Public License for more details.
15
+ #
16
+ # You should have received a copy of the GNU General Public License
17
+ # along with Telekit. If not, see <https://www.gnu.org/licenses/>.
18
+ #
19
+
20
+ from typing import Any, Callable
21
+ import heapq
22
+ import itertools
23
+ import queue
24
+ import threading
25
+ import time
26
+
27
+ from ._logger import _library
28
+
29
+ __all__ = ["configure_timeouts", "timeout_stats"]
30
+
31
+ _DEFAULT_MAX_WORKERS = 16
32
+ _DEFAULT_IDLE_TIMEOUT = 60.0
33
+ _COMPACT_MIN_SIZE = 1024
34
+
35
+
36
+ def _invoke(callback: Callable[[], None]) -> None:
37
+ try:
38
+ callback()
39
+ except Exception:
40
+ _library.exception("Unhandled exception in timeout callback")
41
+
42
+
43
+ # ---------------------------------------------------------------------------
44
+ # Worker pool
45
+ # ---------------------------------------------------------------------------
46
+
47
+ class _WorkerPool:
48
+ """
49
+ Minimal thread pool with lazy worker creation and idle retirement.
50
+
51
+ Accounting (all under `_lock`):
52
+ _workers - existing worker threads
53
+ _idle - workers waiting for a task
54
+ _pending - tasks put in the queue and not yet taken by a worker
55
+ A new worker is started only if `_pending > _idle`.
56
+ """
57
+
58
+ def __init__(
59
+ self,
60
+ max_workers: int = _DEFAULT_MAX_WORKERS,
61
+ idle_timeout: float = _DEFAULT_IDLE_TIMEOUT,
62
+ log_worker_changes: bool = False,
63
+ warn_on_max_workers: bool = True,
64
+ ):
65
+ self.max_workers = max_workers
66
+ self.idle_timeout = idle_timeout
67
+ self.log_worker_changes = log_worker_changes
68
+ self.warn_on_max_workers = warn_on_max_workers
69
+
70
+ self._queue: "queue.Queue[Callable[[], None]]" = queue.Queue()
71
+ self._lock = threading.Lock()
72
+ self._workers = 0
73
+ self._idle = 0
74
+ self._pending = 0
75
+ self._saturated = False
76
+ self._ids = itertools.count(1)
77
+
78
+ def submit(self, callback: Callable[[], None]) -> None:
79
+ with self._lock:
80
+ self._queue.put(callback)
81
+ self._pending += 1
82
+
83
+ if self._pending <= self._idle:
84
+ return # an idle worker will take it
85
+
86
+ if self._workers < self.max_workers:
87
+ self._start_worker()
88
+ elif not self._saturated:
89
+ self._saturated = True
90
+ if self.warn_on_max_workers:
91
+ _library.warning(
92
+ f"Timeout worker pool is saturated: all {self._workers} "
93
+ f"workers are busy and {self._pending} callback(s) are waiting. "
94
+ "Increase the limit with telekit.configure_timeouts(max_workers=...) "
95
+ "or make timeout callbacks faster."
96
+ )
97
+
98
+ def _start_worker(self) -> None:
99
+ """Must be called with the lock held."""
100
+ thread = threading.Thread(
101
+ target=self._worker,
102
+ name=f"telekit-timeout-{next(self._ids)}",
103
+ daemon=True,
104
+ )
105
+ self._workers += 1
106
+ try:
107
+ thread.start()
108
+ except RuntimeError:
109
+ self._workers -= 1
110
+ _library.exception("Cannot start a timeout worker thread")
111
+ return
112
+
113
+ if self.log_worker_changes:
114
+ _library.info(
115
+ f"Timeout worker started ({self._workers}/{self.max_workers}, "
116
+ f"{self._idle} idle, {self._pending} pending)"
117
+ )
118
+
119
+ def _retire(self, reason: str) -> None:
120
+ """Must be called with the lock held."""
121
+ self._workers -= 1
122
+ if self.log_worker_changes:
123
+ _library.info(
124
+ f"Timeout worker stopped: {reason} "
125
+ f"({self._workers}/{self.max_workers} left)"
126
+ )
127
+
128
+ def _worker(self) -> None:
129
+ while True:
130
+ with self._lock:
131
+ if self._workers > self.max_workers:
132
+ self._retire("pool was shrunk")
133
+ return
134
+ self._idle += 1
135
+
136
+ try:
137
+ callback = self._queue.get(timeout=self.idle_timeout)
138
+ except queue.Empty:
139
+ with self._lock:
140
+ self._idle -= 1
141
+ if self._queue.empty():
142
+ self._retire(f"idle for {self.idle_timeout:g}s")
143
+ return
144
+ continue # a task arrived at the last moment
145
+
146
+ with self._lock:
147
+ self._idle -= 1
148
+ self._pending -= 1
149
+ if self._pending == 0:
150
+ self._saturated = False
151
+
152
+ _invoke(callback)
153
+
154
+ def stats(self) -> dict[str, int]:
155
+ with self._lock:
156
+ return {
157
+ "workers": self._workers,
158
+ "workers_idle": self._idle,
159
+ "workers_busy": self._workers - self._idle,
160
+ "tasks_pending": self._pending,
161
+ "max_workers": self.max_workers,
162
+ }
163
+
164
+
165
+ # ---------------------------------------------------------------------------
166
+ # Scheduler
167
+ # ---------------------------------------------------------------------------
168
+
169
+ class _TimeoutScheduler:
170
+
171
+ def __init__(self):
172
+ self._heap: list[tuple[float, int, "Timeout"]] = []
173
+ self._seq = itertools.count(1)
174
+ self._cond = threading.Condition()
175
+ self._thread: threading.Thread | None = None
176
+ self._compact_at = _COMPACT_MIN_SIZE
177
+ self.pool = _WorkerPool()
178
+
179
+ def next_seq(self) -> int:
180
+ return next(self._seq)
181
+
182
+ def push(self, deadline: float, seq: int, timeout: "Timeout") -> None:
183
+ with self._cond:
184
+ heapq.heappush(self._heap, (deadline, seq, timeout))
185
+
186
+ if len(self._heap) > self._compact_at:
187
+ self._compact()
188
+
189
+ if self._thread is None or not self._thread.is_alive():
190
+ self._thread = threading.Thread(
191
+ target=self._run, name="telekit-timeout-scheduler", daemon=True
192
+ )
193
+ self._thread.start()
194
+
195
+ # wake the scheduler only if the nearest deadline changed
196
+ if self._heap[0][1] == seq:
197
+ self._cond.notify()
198
+
199
+ def _compact(self) -> None:
200
+ """
201
+ Drops dead entries (cancelled / orphaned).
202
+
203
+ ! Must be called with the lock held !
204
+ """
205
+ alive = [entry for entry in self._heap if entry[2]._keep(entry[1])]
206
+ heapq.heapify(alive)
207
+ self._heap = alive
208
+ self._compact_at = max(_COMPACT_MIN_SIZE, 2 * len(alive))
209
+
210
+ def _run(self) -> None:
211
+ while True:
212
+ with self._cond:
213
+ while True:
214
+ if not self._heap:
215
+ self._cond.wait()
216
+ continue
217
+ delay = self._heap[0][0] - time.monotonic()
218
+ if delay <= 0:
219
+ break
220
+ self._cond.wait(delay)
221
+ _, seq, timeout = heapq.heappop(self._heap)
222
+
223
+ try:
224
+ callback = timeout._on_due(seq)
225
+ if callback is not None:
226
+ self.pool.submit(callback)
227
+ except Exception:
228
+ _library.exception("Timeout scheduler error")
229
+
230
+ def stats(self) -> dict[str, Any]:
231
+ with self._cond:
232
+ total = len(self._heap)
233
+ live = sum(1 for _, seq, t in self._heap if t._is_live(seq))
234
+ compact_at = self._compact_at
235
+
236
+ return {
237
+ "heap_total": total,
238
+ "heap_live": live,
239
+ "heap_dead": total - live,
240
+ "heap_compact_at": compact_at,
241
+ **self.pool.stats(),
242
+ }
243
+
244
+
245
+ _scheduler = _TimeoutScheduler()
246
+
247
+
248
+ def configure_timeouts(
249
+ max_workers: int | None = None,
250
+ *,
251
+ idle_timeout: float | None = None,
252
+ log_worker_changes: bool | None = None,
253
+ warn_on_max_workers: bool | None = None,
254
+ ) -> None:
255
+ """
256
+ Configures the timeout worker pool. Only the passed values are changed.
257
+
258
+ :param max_workers: Upper bound of worker threads (default 16). Workers are
259
+ created lazily; if the pool is shrunk, surplus workers stop after
260
+ their current task.
261
+ :param idle_timeout: Seconds an idle worker waits for work before it stops
262
+ (default 60). Affects workers on their next wait.
263
+ :param log_worker_changes: Log every worker start / stop (default False).
264
+ :param warn_on_max_workers: Log a warning when all workers are busy and
265
+ callbacks have to wait (default True). Logged once per saturation episode.
266
+ """
267
+ pool = _scheduler.pool
268
+
269
+ if max_workers is not None:
270
+ if max_workers < 1:
271
+ raise ValueError("max_workers must be >= 1")
272
+ pool.max_workers = max_workers
273
+ if idle_timeout is not None:
274
+ if idle_timeout <= 0:
275
+ raise ValueError("idle_timeout must be > 0")
276
+ pool.idle_timeout = idle_timeout
277
+ if log_worker_changes is not None:
278
+ pool.log_worker_changes = log_worker_changes
279
+ if warn_on_max_workers is not None:
280
+ pool.warn_on_max_workers = warn_on_max_workers
281
+
282
+
283
+ def timeout_stats() -> dict[str, Any]:
284
+ """
285
+ Returns a snapshot of the timeout internals (for debugging).
286
+
287
+ - ``heap_total`` / ``heap_live`` / ``heap_dead``: entries in the scheduler
288
+ heap; dead = cancelled (or replaced) entries waiting to be dropped
289
+ - ``heap_compact_at``: heap size that triggers the next compaction
290
+ - ``workers`` / ``workers_idle`` / ``workers_busy``: worker threads
291
+ - ``tasks_pending``: callbacks waiting for a free worker
292
+ - ``max_workers``: current limit
293
+ """
294
+ return _scheduler.stats()
295
+
296
+
297
+ # ---------------------------------------------------------------------------
298
+ # Timeout
299
+ # ---------------------------------------------------------------------------
300
+
301
+ class Timeout:
302
+ """
303
+ A re-startable timeout. One object = at most one live heap entry.
304
+ """
305
+
306
+ __slots__ = (
307
+ "callback", "_deadline", "_queued_seq", "_queued_deadline", "_lock"
308
+ )
309
+
310
+ def __init__(self):
311
+ self.callback: Callable[[], None] | None = None
312
+ self._deadline: float | None = None # None -> inactive
313
+ self._queued_seq: int | None = None # seq of the valid heap entry
314
+ self._queued_deadline: float = 0.0 # deadline of that entry
315
+ self._lock = threading.Lock()
316
+
317
+ # API
318
+
319
+ def start(self, callback: Callable[[], None], total_seconds: float) -> None:
320
+ """(Re)starts the timeout: it fires `total_seconds` from now."""
321
+ deadline = time.monotonic() + total_seconds
322
+
323
+ with self._lock:
324
+ self.callback = callback
325
+ self._deadline = deadline
326
+
327
+ if self._queued_seq is not None and self._queued_deadline <= deadline:
328
+ # an existing entry fires earlier; it will re-queue itself
329
+ return
330
+
331
+ seq = _scheduler.next_seq()
332
+ self._queued_seq = seq
333
+ self._queued_deadline = deadline
334
+
335
+ _scheduler.push(deadline, seq, self)
336
+
337
+ def cancel(self) -> None:
338
+ """
339
+ Cancels the timeout and releases the callback (and its closure).
340
+ """
341
+ with self._lock:
342
+ self._deadline = None
343
+ self.callback = None
344
+
345
+ # Scheduler hooks
346
+
347
+ def _on_due(self, seq: int) -> Callable[[], None] | None:
348
+ """
349
+ Called by the scheduler when the heap entry `seq` is due.
350
+ Returns the callback to run, or None if there is nothing to run.
351
+ """
352
+ requeue: tuple[float, int] | None = None
353
+
354
+ with self._lock:
355
+ if self._queued_seq != seq:
356
+ return None # orphan entry, a newer one exists
357
+
358
+ if self._deadline is None:
359
+ self._queued_seq = None # cancelled
360
+ return None
361
+
362
+ if self._deadline > time.monotonic():
363
+ # restarted with a later deadline: move the entry, don't fire
364
+ new_seq = _scheduler.next_seq()
365
+ self._queued_seq = new_seq
366
+ self._queued_deadline = self._deadline
367
+ requeue = (self._deadline, new_seq)
368
+ else:
369
+ callback = self.callback
370
+ self.callback = None
371
+ self._deadline = None
372
+ self._queued_seq = None
373
+ return callback
374
+
375
+ _scheduler.push(requeue[0], requeue[1], self)
376
+ return None
377
+
378
+ def _keep(self, seq: int) -> bool:
379
+ """Compaction check: should the heap entry `seq` stay in the heap?"""
380
+ with self._lock:
381
+ if self._queued_seq != seq:
382
+ return False # orphan
383
+ if self._deadline is not None:
384
+ return True
385
+ self._queued_seq = None # cancelled: forget the entry
386
+ return False
387
+
388
+ def _is_live(self, seq: int) -> bool:
389
+ """Read-only version of `_keep` (for stats)."""
390
+ with self._lock:
391
+ return self._queued_seq == seq and self._deadline is not None
392
+
393
+
394
+ class TimeoutHandler:
395
+ def __init__(self):
396
+ self.total_seconds: int = 0
397
+ self.callback: Callable | None = None
398
+ self.timeout: Timeout = Timeout()
399
+
400
+ def set_time(self, seconds=0, minutes=0, hours=0):
401
+ self.total_seconds = seconds + minutes * 60 + hours * 3600
402
+
403
+ def set_callback(self, callback: Callable):
404
+ self.callback = callback
405
+
406
+ def maybe_start(self) -> bool:
407
+ """
408
+ Starts the timeout counting from now. If it was already running,
409
+ it is restarted (the previous countdown is discarded).
410
+ """
411
+ if self.callback and self.total_seconds:
412
+ self.timeout.start(self.callback, self.total_seconds)
413
+ return True
414
+
415
+ self.timeout.cancel()
416
+ return False
417
+
418
+ def cancel(self):
419
+ self.timeout.cancel()
420
+
421
+ def remove(self):
422
+ self.cancel()
423
+ self.callback = None
424
+ self.total_seconds = 0
@@ -3,4 +3,4 @@
3
3
  # PyPI history: https://pypi.org/project/telekit/#history
4
4
  # ––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––
5
5
 
6
- __version__ = "2.6.0a4"
6
+ __version__ = "2.6.0a6"
@@ -945,6 +945,13 @@ class BaseSender:
945
945
  # silently delete and resend
946
946
  self._delete_message(self.edit_message_id)
947
947
  except Exception as exception:
948
+ if "message content and reply markup are exactly the same" in str(exception):
949
+ library.warning(
950
+ f"Failed to edit message {self.edit_message_id}, "
951
+ f"do nothing instead. Exception: {exception}"
952
+ )
953
+ return None, False
954
+
948
955
  _SILENT_EDIT_ERRORS = (
949
956
  "Bad Request: there is no text in the message to edit",
950
957
  "Bad Request: message can't be edited",
@@ -435,7 +435,7 @@ def _load_env(path: str, cache: bool, example: str) -> dict[str, str]:
435
435
  return dict(_ENV_CACHE[key])
436
436
 
437
437
 
438
- def load_env(path=".env", *, cache: bool = True) -> dict[str, str]:
438
+ def load_env(path: str = ".env", *, cache: bool = True) -> dict[str, str]:
439
439
  """
440
440
  Load all key-value pairs from a ``.env`` file.
441
441
 
@@ -463,7 +463,7 @@ def load_env(path=".env", *, cache: bool = True) -> dict[str, str]:
463
463
  return _load_env(path, cache, "KEY=value")
464
464
 
465
465
 
466
- def read_envar(path: str, name: str, *, cache: bool = True) -> str:
466
+ def read_envar(name: str, path: str = ".env", *, cache: bool = True) -> str:
467
467
  """
468
468
  Read a single environment variable from a ``.env`` file.
469
469
 
@@ -539,29 +539,35 @@ def _read_first_value(path: str, example: str, kind: str, cache: bool) -> str:
539
539
  )
540
540
 
541
541
 
542
- def read_token(path: str = "token.txt", *, cache: bool = True) -> str:
542
+ def read_token(path: str = ".env", name: str = "TOKEN", cache: bool = True) -> str:
543
543
  """
544
- Read the bot token from a file or ``.env``.
544
+ Read the bot token from a ``.env`` file or a plain text file.
545
545
 
546
- **Plain text file** (default)::
546
+ **Environment file** (default)::
547
+
548
+ read_token() # reads the key "TOKEN" from ".env" file
549
+ read_token(name="TOKEN") # same, explicit key
550
+ read_token("secret/.env", "BOT_KEY") # custom path & custom key
551
+
552
+ **Plain text file** (``token.txt``)::
547
553
 
548
554
  # token.txt
549
555
  123456789:BotSecretToken Main production bot
550
556
  987654321:AnotherToken Backup bot
551
557
 
558
+ >> read_token("token.txt")
559
+ "123456789:BotSecretToken"
560
+
552
561
  Reads only the first meaningful line (blank lines and ``#`` comments are
553
562
  skipped). Inline comments (everything after the first whitespace) are
554
563
  ignored. Multiple tokens can be stored and swapped by reordering lines.
555
564
 
556
- **Environment file** (``.env``)::
557
-
558
- read_token(".env") # reads the key named TOKEN
559
- read_token(".env:TOKEN") # same, explicit key
560
- read_token(".env:BOT_KEY") # reads a custom key
561
-
562
- :param path: Path to a token file, or ``".env"`` / ``".env:KEY"`` for
563
- environment files. Defaults to ``"token.txt"``.
565
+ :param path: Path to a ``.env`` file or to a plain text file with tokens.
566
+ Defaults to ``".env"``.
564
567
  :type path: ``str``
568
+ :param name: Key to read from the ``.env`` file. Ignored for plain text
569
+ files. Defaults to ``"TOKEN"``.
570
+ :type name: ``str``
565
571
  :param cache: If ``True`` (default), use the in-memory copy if available; if
566
572
  ``False``, re-read the file and refresh the cache.
567
573
  :type cache: ``bool``
@@ -575,12 +581,11 @@ def read_token(path: str = "token.txt", *, cache: bool = True) -> str:
575
581
  example = "123456789:YourBotToken"
576
582
 
577
583
  if _is_env_path(path):
578
- file_path, name = _split_env_path(path, "TOKEN")
579
- token = read_envar(file_path, name, cache=cache).strip()
584
+ token = read_envar(name, path, cache=cache).strip()
580
585
 
581
586
  if not token:
582
587
  raise EnvValueError(
583
- f"Variable '{name}' in '{file_path}' is empty.\n"
588
+ f"Variable '{name}' in '{path}' is empty.\n"
584
589
  f" Hint: set the token after '=', e.g. `{name}={example}` "
585
590
  f"(get one from @BotFather in Telegram)."
586
591
  )
@@ -590,30 +595,36 @@ def read_token(path: str = "token.txt", *, cache: bool = True) -> str:
590
595
  return line.split()[0]
591
596
 
592
597
 
593
- def read_canvas_path(path: str = "canvas_path.txt", *, cache: bool = True) -> str:
598
+ def read_canvas_path(path: str = ".env", name: str = "CANVAS_PATH", cache: bool = True) -> str:
594
599
  """
595
- Read the ``.canvas`` file path from a file or ``.env``.
600
+ Read the ``.canvas`` file path from a ``.env`` file or a plain text file.
596
601
 
597
- **Plain text file** (default)::
602
+ **Environment file** (default)::
603
+
604
+ read_canvas_path() # reads the key "CANVAS_PATH" from ".env" file
605
+ read_canvas_path(name="CANVAS_PATH") # same, explicit key
606
+ read_canvas_path("secret/.env", "MY_CANVAS") # custom path & custom key
607
+
608
+ **Plain text file** (``canvas_path.txt``)::
598
609
 
599
610
  # canvas_path.txt
600
611
  /home/user/project/main.canvas Production canvas
601
612
  /home/user/project/test.canvas Test canvas
602
613
 
614
+ >> read_canvas_path("canvas_path.txt")
615
+ "/home/user/project/main.canvas"
616
+
603
617
  Reads only the first meaningful line (blank lines and ``#`` comments are
604
618
  skipped). A comment may follow the path after two or more spaces or a tab
605
619
  (single spaces are part of the path). Multiple paths can be stored and
606
620
  swapped by reordering lines.
607
621
 
608
- **Environment file** (``.env``)::
609
-
610
- read_canvas_path(".env") # reads the key named CANVAS_PATH
611
- read_canvas_path(".env:CANVAS_PATH") # same, explicit key
612
- read_canvas_path(".env:MY_CANVAS") # reads a custom key
613
-
614
- :param path: Path to a canvas path file, or ``".env"`` / ``".env:KEY"`` for
615
- environment files. Defaults to ``"canvas_path.txt"``.
622
+ :param path: Path to a ``.env`` file or to a plain text file with canvas
623
+ paths. Defaults to ``".env"``.
616
624
  :type path: ``str``
625
+ :param name: Key to read from the ``.env`` file. Ignored for plain text
626
+ files. Defaults to ``"CANVAS_PATH"``.
627
+ :type name: ``str``
617
628
  :param cache: If ``True`` (default), use the in-memory copy if available; if
618
629
  ``False``, re-read the file and refresh the cache.
619
630
  :type cache: ``bool``
@@ -627,12 +638,11 @@ def read_canvas_path(path: str = "canvas_path.txt", *, cache: bool = True) -> st
627
638
  example = "/path/to/project/main.canvas"
628
639
 
629
640
  if _is_env_path(path):
630
- file_path, name = _split_env_path(path, "CANVAS_PATH")
631
- value = read_envar(file_path, name, cache=cache).strip()
641
+ value = read_envar(name, path, cache=cache).strip()
632
642
 
633
643
  if not value:
634
644
  raise EnvValueError(
635
- f"Variable '{name}' in '{file_path}' is empty.\n"
645
+ f"Variable '{name}' in '{path}' is empty.\n"
636
646
  f" Hint: set the path after '=', e.g. `{name}={example}`."
637
647
  )
638
648
  return value
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: telekit
3
- Version: 2.6.0a4
3
+ Version: 2.6.0a6
4
4
  Summary: Declarative, developer-friendly framework for building Telegram bots
5
5
  Home-page: https://github.com/Romashkaa/telekit
6
6
  Author: romashka
@@ -42,7 +42,7 @@ Dynamic: summary
42
42
 
43
43
  # Telekit
44
44
 
45
- **Telekit** is a declarative, developer-friendly library for building Telegram bots. It gives developers a dedicated Sender for composing and sending messages and a Chain for handling dialogue between the user and the bot. The library also handles inline keyboards and callback routing automatically, letting you focus on the bot's behavior instead of repetitive tasks.
45
+ **Telekit** is a declarative, developer-friendly framework for building Telegram bots. It gives developers a dedicated Sender for composing and sending messages and a Chain for handling dialogue between the user and the bot. The framework also handles inline keyboards and callback routing automatically, letting you focus on the bot's behavior instead of repetitive tasks.
46
46
 
47
47
  ```py
48
48
  import telekit
@@ -57,7 +57,9 @@ class MyStartHandler(telekit.Handler):
57
57
  self.chain.sender.set_photo("robot.png")
58
58
  self.chain.send()
59
59
 
60
- telekit.Server("BOT_TOKEN").polling()
60
+ TOKEN: str = telekit.utils.read_token(".env")
61
+
62
+ telekit.Server(TOKEN).polling()
61
63
  ```
62
64
 
63
65
  > Send "Hello!" with a photo on `/start`
@@ -471,7 +473,12 @@ Telekit focuses on one job: making Telegram bot development easier.
471
473
 
472
474
  ---
473
475
 
474
- # Changes in version 2.6.0a4
476
+ # Changes in version 2.6.0a6
477
+
478
+ ### v2.6.0 `a6` (Fixes #6)
479
+ - 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`
480
+ - Timeout callback exceptions are now logged
481
+ - 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
482
 
476
483
  ### v2.6.0 `a4`
477
484
  - 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
@@ -1,73 +0,0 @@
1
- #
2
- # Copyright (C) 2026 Romashka
3
- #
4
- # This file is part of Telekit.
5
- #
6
- # Telekit is free software: you can redistribute it and/or modify it
7
- # under the terms of the GNU General Public License as published by
8
- # the Free Software Foundation, either version 3 of the License, or
9
- # (at your option) any later version.
10
- #
11
- # Telekit is distributed in the hope that it will be useful,
12
- # but WITHOUT ANY WARRANTY; without even the implied warranty
13
- # of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See
14
- # the GNU General Public License for more details.
15
- #
16
- # You should have received a copy of the GNU General Public License
17
- # along with Telekit. If not, see <https://www.gnu.org/licenses/>.
18
- #
19
-
20
- from typing import Callable
21
- import threading
22
-
23
- class Timeout:
24
- def __init__(self, callback: Callable, total_seconds: int):
25
- self.total_seconds = total_seconds
26
- self.callback = callback
27
- self._timer = None
28
- self._cancelled = False
29
-
30
- def start(self):
31
- self._cancelled = False
32
- self._timer = threading.Timer(self.total_seconds, self._execute)
33
- self._timer.start()
34
-
35
- def _execute(self):
36
- if self._cancelled:
37
- return
38
- self.callback()
39
-
40
- def cancel(self):
41
- self._cancelled = True
42
- if self._timer:
43
- self._timer.cancel()
44
-
45
- class TimeoutHandler:
46
- def __init__(self):
47
- self.total_seconds: int = 0
48
- self.callback: Callable | None = None
49
- self.timeout: Timeout | None = None
50
-
51
- def set_time(self, seconds=0, minutes=0, hours=0):
52
- self.total_seconds = seconds + minutes * 60 + hours * 3600
53
-
54
- def set_callback(self, callback: Callable):
55
- self.callback = callback
56
-
57
- def maybe_start(self) -> bool:
58
- if self.callback and self.total_seconds:
59
- self.timeout = Timeout(self.callback, self.total_seconds)
60
- self.timeout.start()
61
-
62
- return True
63
- return False
64
-
65
- def cancel(self):
66
- if self.timeout:
67
- self.timeout.cancel()
68
- self.timeout = None
69
-
70
- def remove(self):
71
- self.cancel()
72
- self.callback = None
73
- self.total_seconds = 0
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes