django-telegram-q2 1.0.0__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 (40) hide show
  1. django_telegram_q2-1.0.0/LICENSE +201 -0
  2. django_telegram_q2-1.0.0/PKG-INFO +275 -0
  3. django_telegram_q2-1.0.0/README.md +247 -0
  4. django_telegram_q2-1.0.0/pyproject.toml +135 -0
  5. django_telegram_q2-1.0.0/src/django_telegram_q2/__init__.py +0 -0
  6. django_telegram_q2-1.0.0/src/django_telegram_q2/common/__init__.py +0 -0
  7. django_telegram_q2-1.0.0/src/django_telegram_q2/common/admin.py +63 -0
  8. django_telegram_q2-1.0.0/src/django_telegram_q2/common/fields.py +93 -0
  9. django_telegram_q2-1.0.0/src/django_telegram_q2/common/sanitize.py +23 -0
  10. django_telegram_q2-1.0.0/src/django_telegram_q2/common/schedules.py +121 -0
  11. django_telegram_q2-1.0.0/src/django_telegram_q2/common/tests/__init__.py +0 -0
  12. django_telegram_q2-1.0.0/src/django_telegram_q2/common/tests/test_fields.py +108 -0
  13. django_telegram_q2-1.0.0/src/django_telegram_q2/common/tests/test_sanitize.py +99 -0
  14. django_telegram_q2-1.0.0/src/django_telegram_q2/common/tests/test_schedules.py +209 -0
  15. django_telegram_q2-1.0.0/src/django_telegram_q2/py.typed +0 -0
  16. django_telegram_q2-1.0.0/src/django_telegram_q2/telegram/__init__.py +0 -0
  17. django_telegram_q2-1.0.0/src/django_telegram_q2/telegram/admin.py +254 -0
  18. django_telegram_q2-1.0.0/src/django_telegram_q2/telegram/apps.py +67 -0
  19. django_telegram_q2-1.0.0/src/django_telegram_q2/telegram/client.py +289 -0
  20. django_telegram_q2-1.0.0/src/django_telegram_q2/telegram/intake.py +97 -0
  21. django_telegram_q2-1.0.0/src/django_telegram_q2/telegram/migrations/0001_initial.py +223 -0
  22. django_telegram_q2-1.0.0/src/django_telegram_q2/telegram/migrations/__init__.py +0 -0
  23. django_telegram_q2-1.0.0/src/django_telegram_q2/telegram/models.py +217 -0
  24. django_telegram_q2-1.0.0/src/django_telegram_q2/telegram/signals.py +52 -0
  25. django_telegram_q2-1.0.0/src/django_telegram_q2/telegram/tasks.py +413 -0
  26. django_telegram_q2-1.0.0/src/django_telegram_q2/telegram/tests/__init__.py +0 -0
  27. django_telegram_q2-1.0.0/src/django_telegram_q2/telegram/tests/test_admin.py +432 -0
  28. django_telegram_q2-1.0.0/src/django_telegram_q2/telegram/tests/test_client.py +452 -0
  29. django_telegram_q2-1.0.0/src/django_telegram_q2/telegram/tests/test_delivery.py +360 -0
  30. django_telegram_q2-1.0.0/src/django_telegram_q2/telegram/tests/test_logging.py +40 -0
  31. django_telegram_q2-1.0.0/src/django_telegram_q2/telegram/tests/test_models.py +58 -0
  32. django_telegram_q2-1.0.0/src/django_telegram_q2/telegram/tests/test_predicates.py +139 -0
  33. django_telegram_q2-1.0.0/src/django_telegram_q2/telegram/tests/test_schedules.py +272 -0
  34. django_telegram_q2-1.0.0/src/django_telegram_q2/telegram/tests/test_signals.py +80 -0
  35. django_telegram_q2-1.0.0/src/django_telegram_q2/telegram/tests/test_tasks_branches.py +762 -0
  36. django_telegram_q2-1.0.0/src/django_telegram_q2/telegram/tests/test_views.py +174 -0
  37. django_telegram_q2-1.0.0/src/django_telegram_q2/telegram/tests/test_worker.py +157 -0
  38. django_telegram_q2-1.0.0/src/django_telegram_q2/telegram/urls.py +9 -0
  39. django_telegram_q2-1.0.0/src/django_telegram_q2/telegram/views.py +58 -0
  40. django_telegram_q2-1.0.0/src/django_telegram_q2/telegram/worker.py +156 -0
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to computer software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is evidently marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 Dmitrii Safronov
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,275 @@
1
+ Metadata-Version: 2.4
2
+ Name: django-telegram-q2
3
+ Version: 1.0.0
4
+ Summary: Django reusable app — Telegram Bot pipeline backed by django-q2
5
+ Keywords: django,telegram,bot,django-q2,pipeline
6
+ Author: Dmitrii Safronov
7
+ Author-email: Dmitrii Safronov <dhameoelin+django-telegram-q2@gmail.com>
8
+ License-Expression: Apache-2.0
9
+ License-File: LICENSE
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: Programming Language :: Python :: 3.11
12
+ Classifier: Programming Language :: Python :: 3.12
13
+ Classifier: Programming Language :: Python :: 3.13
14
+ Classifier: Programming Language :: Python :: 3.14
15
+ Classifier: Programming Language :: Python :: 3 :: Only
16
+ Classifier: Framework :: Django
17
+ Classifier: Framework :: Django :: 5.2
18
+ Classifier: Intended Audience :: Developers
19
+ Classifier: Topic :: Communications :: Chat
20
+ Requires-Dist: django>=5.2.15,<6.0
21
+ Requires-Dist: django-q2>=1.0.0,<2.0.0
22
+ Requires-Dist: httpx>=0.28.0,<1.0.0
23
+ Requires-Dist: cryptography>=44.0.0,<49.0.0
24
+ Requires-Python: >=3.11, <3.15
25
+ Project-URL: Source, https://github.com/disafronov/django-telegram-q2
26
+ Project-URL: Issues, https://github.com/disafronov/django-telegram-q2/issues
27
+ Description-Content-Type: text/markdown
28
+
29
+ # django-telegram-q2
30
+
31
+ A reusable Django app that turns a Telegram bot into a durable, queue-backed
32
+ pipeline: inbound messages are buffered, turned into `Job` records, processed by
33
+ a worker you supply, and the result is delivered back to the chat — all driven by
34
+ [django-q2](https://github.com/django-q2/django-q2) task scheduling.
35
+
36
+ ```
37
+ Telegram ──► intake (webhook or polling) ──► IntakeBuffer (debounce)
38
+ │
39
+ ▼
40
+ Job ──► processing worker (your code)
41
+ │ │
42
+ │ ▼
43
+ │ raw_output / error
44
+ ▼ │
45
+ telegram_deliver ◄────────┘
46
+ │
47
+ ▼
48
+ Telegram
49
+ ```
50
+
51
+ ## Features
52
+
53
+ - **At-least-once, resumable pipeline.** Every message becomes a `Job` with
54
+ explicit `processing_*` / `delivery_*` timestamps and database-level
55
+ check constraints, so a crashed worker or dropped task is safe to retry.
56
+ - **Webhook *and* long-polling ingest.** `telegram_setup` heals/registers the
57
+ webhook and transparently falls back to polling when Telegram reports errors
58
+ or the public `BASE_URL` is unavailable. The two never race (a `409` from
59
+ Telegram is tolerated).
60
+ - **Message debouncing.** Consecutive messages in the same chat within
61
+ `TELEGRAM_INTAKE_DEBOUNCE_SECONDS` are concatenated into a single `Job`, so a
62
+ multi-line thought is processed as one unit.
63
+ - **Encrypted secrets at rest.** Bot API tokens and webhook secrets are stored
64
+ with deterministic AES-SIV encryption (`FIELD_ENCRYPTION_KEY`), while still
65
+ allowing exact-match lookups.
66
+ - **Shipped admin + migrations.** `Bot`/`Job`/`IntakeBuffer` are registered with
67
+ the admin, including "retry job", "retry delivery" and "rotate webhook secret"
68
+ actions. Migrations are included.
69
+ - **Zero worker assumptions.** The package owns transport and scheduling; you
70
+ implement `process()` and point `Q2_PROCESSING_FUNC` at it.
71
+
72
+ ## Requirements
73
+
74
+ - Python **3.11**, **3.12**, **3.13**, or **3.14**
75
+ - Django **>= 5.2, < 6.0**
76
+ - django-q2 **>= 1.0, < 2.0** (and its broker — Redis/ORM/…)
77
+ - `cryptography` and `httpx` (declared as dependencies)
78
+ - **PostgreSQL recommended** for production (the pipeline relies on
79
+ `SELECT … SKIP LOCKED`; SQLite works for local development and tests).
80
+
81
+ ## Installation
82
+
83
+ ```console
84
+ uv add django-telegram-q2
85
+ # or
86
+ pip install django-telegram-q2
87
+ ```
88
+
89
+ ## Quick start
90
+
91
+ ### 1. Apps and URLs
92
+
93
+ ```python
94
+ # settings.py
95
+ INSTALLED_APPS = [
96
+ # … Django apps …
97
+ "django_q", # django-q2
98
+ "django_telegram_q2.telegram", # this app (app label: "telegram")
99
+ ]
100
+
101
+ # urls.py
102
+ from django.urls import include, path
103
+
104
+ urlpatterns = [
105
+ path("", include("django_telegram_q2.telegram.urls")), # exposes /webhook/
106
+ ]
107
+ ```
108
+
109
+ The webhook endpoint is exposed at `/webhook/` (no `app_name` namespace).
110
+
111
+ ### 2. Configure django-q2
112
+
113
+ The package schedules its work through django-q2, so a `Q_CLUSTER` config is
114
+ required. See the django-q2 docs for broker options (Redis/ORM/etc.) and run a
115
+ cluster (`manage.py qcluster`).
116
+
117
+ ### 3. Required settings
118
+
119
+ ```python
120
+ import os
121
+
122
+ # 32-byte key, hex-encoded (64 hex chars).
123
+ # Generate: python -c "import secrets; print(secrets.token_bytes(32).hex())"
124
+ os.environ["FIELD_ENCRYPTION_KEY"] = "…64-hex-chars…"
125
+
126
+ # Public base URL used to register webhooks. Leave empty to use polling only.
127
+ BASE_URL = "https://bot.example.com"
128
+
129
+ # Processing function — dotted path to a callable taking one int (job_pk).
130
+ Q2_PROCESSING_FUNC = "myproject.workers.process_job"
131
+
132
+ # Managed Q2 schedule intervals (in minutes).
133
+ Q2_TELEGRAM_SETUP_MINUTES = 5
134
+ Q2_TELEGRAM_INGEST_MINUTES = 1
135
+ Q2_TELEGRAM_DELIVER_MINUTES = 1
136
+ Q2_TELEGRAM_INTAKE_FLUSH_MINUTES = 1
137
+ Q2_PROCESSING_MINUTES = 1
138
+
139
+ # Webhook health management.
140
+ WEBHOOK_COOLDOWN_SECONDS = 300
141
+ WEBHOOK_FALLBACK_PENDING_THRESHOLD = 100
142
+
143
+ # How long a claimed-but-unfinished Job stays stuck before being reset (seconds).
144
+ Q2_PROCESSING_STALE_JOB_SECONDS = 3600
145
+
146
+ # Emoji sent to acknowledge receipt; empty string disables the reaction.
147
+ TELEGRAM_ACK_REACTION = "🤖"
148
+ ```
149
+
150
+ ### 4. Migrate
151
+
152
+ ```console
153
+ python manage.py migrate
154
+ ```
155
+
156
+ Migrations for the `telegram` app are shipped, so no `makemigrations` is needed
157
+ for the package models.
158
+
159
+ ## Models
160
+
161
+ | Model | Purpose |
162
+ | ---------------- | ----------------------------------------------------------------------- |
163
+ | `Bot` | A Telegram bot identity: encrypted `telegram_api_token`, `webhook_secret`, poll `telegram_update_offset`, webhook state. |
164
+ | `Job` | One pipeline execution: `raw_input` → (`raw_output` \| `processing_error`) → delivery state. Carries DB-level check constraints and partial indexes for queue queries. |
165
+ | `IntakeBuffer` | Mutable accumulator of consecutive chat messages before a `Job` is created; one open buffer per `bot`+`chat`. |
166
+
167
+ `Job.objects` is a `JobQuerySet` with `ready_for_processing()`,
168
+ `stale_processing(cutoff)` and `ready_for_delivery()` for queue queries.
169
+
170
+ ## How the pipeline runs
171
+
172
+ 1. **Intake.** Either the `/webhook/` view (when a webhook is registered) or
173
+ `telegram_ingest` (long-polling) calls `accept_telegram_message`. Messages
174
+ within `TELEGRAM_INTAKE_DEBOUNCE_SECONDS` of the last one are appended to the
175
+ open `IntakeBuffer`; otherwise the buffer is flushed into a `Job` first.
176
+ 2. **Processing.** A `post_save` signal on the new `Job` enqueues
177
+ `Q2_PROCESSING_FUNC(job_pk)`. Your worker runs `process()`, stores the result
178
+ on the `Job`, and a second signal enqueues `telegram_deliver`.
179
+ 3. **Delivery.** `telegram_deliver` sends `raw_output` back to the chat as a
180
+ text document (format auto-detected as HTML/Markdown/plain text), or the
181
+ `processing_error` as a plain message. On failure it records `delivery_error`
182
+ and re-raises; it deliberately does **not** auto-resend an already-started
183
+ delivery, because Telegram sends are not idempotent.
184
+
185
+ `telegram_setup`, `telegram_ingest`, `telegram_deliver`,
186
+ `telegram_flush_intake_buffers` and your processing function are all managed
187
+ **Q2 schedules** created on `post_migrate` and protected from admin drift (any
188
+ edit is reverted, any delete is recreated) via `pre_save`/`post_delete`
189
+ handlers.
190
+
191
+ ## Implementing a worker
192
+
193
+ Subclass `django_telegram_q2.telegram.worker.Worker` and implement `process()`:
194
+
195
+ ```python
196
+ # myproject/workers.py
197
+ from django_telegram_q2.telegram.worker import Worker
198
+
199
+
200
+ class EchoWorker(Worker):
201
+ # Optional: restrict which Jobs are polled, and what to select_related.
202
+ poll_filters: dict = {}
203
+ poll_select_related: tuple[str, ...] = ()
204
+ pk_select_related: tuple[str, ...] = ()
205
+
206
+ def process(self, *, bot_id: int, raw_input: str) -> tuple[str | None, str | None]:
207
+ # Return (result, None) on success,
208
+ # return (None, "error message") on a handled error (no re-raise),
209
+ # or raise on an unexpected failure (re-raised by run()).
210
+ return f"You said: {raw_input}", None
211
+
212
+
213
+ def process_job(job_pk: int) -> None:
214
+ EchoWorker().run(job_pk)
215
+ ```
216
+
217
+ ```python
218
+ # settings.py
219
+ Q2_PROCESSING_FUNC = "myproject.workers.process_job"
220
+ ```
221
+
222
+ `Worker.run` handles Job selection, locking (`skip_locked`), transaction
223
+ management, stale-Job reset, and persisting the outcome.
224
+
225
+ ## Webhook vs polling
226
+
227
+ - Set `BASE_URL` to a publicly reachable HTTPS URL. `telegram_setup` registers
228
+ the webhook (with the per-bot `webhook_secret` sent as the
229
+ `X-Telegram-Bot-Api-Secret-Token` header, which the view verifies).
230
+ - If `BASE_URL` is empty, or Telegram reports a webhook error / too many pending
231
+ updates, the app deletes the webhook and falls back to `telegram_ingest`
232
+ long-polling. After `WEBHOOK_COOLDOWN_SECONDS` it retries webhook
233
+ registration.
234
+ - The view rejects any request without a matching secret header with `404`.
235
+
236
+ ## Settings reference
237
+
238
+ | Setting | Required | Default | Description |
239
+ | ------------------------------------ | -------- | ------- | ------------------------------------------------------------------ |
240
+ | `Q2_PROCESSING_FUNC` | yes | — | Dotted path to the processing entry function `(job_pk: int) -> None`. |
241
+ | `Q2_TELEGRAM_SETUP_MINUTES` | yes | — | Interval for `telegram_setup` (webhook health). |
242
+ | `Q2_TELEGRAM_INGEST_MINUTES` | yes | — | Interval for `telegram_ingest` (polling). |
243
+ | `Q2_TELEGRAM_DELIVER_MINUTES` | yes | — | Interval for `telegram_deliver` (drain deliveries). |
244
+ | `Q2_TELEGRAM_INTAKE_FLUSH_MINUTES` | yes | — | Interval for the intake-buffer safety flush. |
245
+ | `Q2_PROCESSING_MINUTES` | yes | — | Interval for your processing schedule. |
246
+ | `WEBHOOK_COOLDOWN_SECONDS` | yes | — | Quiet period after falling back to polling before retrying webhook. |
247
+ | `WEBHOOK_FALLBACK_PENDING_THRESHOLD` | yes | — | `pending_update_count` above which the webhook is considered unhealthy. |
248
+ | `Q2_PROCESSING_STALE_JOB_SECONDS` | yes | — | Age after which a claimed-but-unfinished Job is reset for retry. |
249
+ | `TELEGRAM_ACK_REACTION` | yes | — | Emoji acknowledgement; `""` disables it. |
250
+ | `BASE_URL` | no | `""` | Public base URL for webhook registration (empty ⇒ polling only). |
251
+ | `TELEGRAM_INTAKE_DEBOUNCE_SECONDS` | no | `10` | Window for grouping consecutive chat messages into one `Job`. |
252
+
253
+ | Env var | Required | Description |
254
+ | ------------------- | -------- | ------------------------------------------------------ |
255
+ | `FIELD_ENCRYPTION_KEY` | yes | 32-byte (16/24/32 accepted) key, hex-encoded, for AES-SIV field encryption. |
256
+
257
+ ## Development
258
+
259
+ This repository ships its own dev tooling:
260
+
261
+ ```console
262
+ make install # install deps + pre-commit hooks
263
+ make lint # black, isort, flake8, mypy, bandit
264
+ make test # pytest with 100% branch coverage
265
+ make dead-code # vulture
266
+ make audit # pip-audit
267
+ make all # lint → test → dead-code
268
+ ```
269
+
270
+ Tests run against SQLite in-memory by default, and against PostgreSQL when
271
+ `DATABASE_HOST` is set (e.g. via `compose.yml`).
272
+
273
+ ## License
274
+
275
+ Apache-2.0. See [LICENSE](LICENSE).