django-telegram-bot-api 0.1.0__tar.gz → 0.1.2__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.
@@ -0,0 +1,587 @@
1
+ Metadata-Version: 2.3
2
+ Name: django-telegram-bot-api
3
+ Version: 0.1.2
4
+ Summary: A typed Telegram Bot API client for Django
5
+ Author: reza
6
+ Author-email: reza <rza.karampour@gmail.com>
7
+ Requires-Dist: django>=6.1.2
8
+ Requires-Dist: djangorestframework>=3.18.3
9
+ Requires-Dist: pydantic
10
+ Requires-Dist: requests>=2.34.2
11
+ Requires-Python: >=3.13
12
+ Description-Content-Type: text/markdown
13
+
14
+ # django-telegram-bot-api
15
+
16
+ A typed Telegram Bot API client for Django.
17
+
18
+ Every Bot API method is a plain Python method, every Telegram type is a [Pydantic](https://docs.pydantic.dev/) model, and responses come back as typed objects instead of raw dictionaries.
19
+
20
+ ```bash
21
+ pip install django-telegram-bot-api
22
+ ```
23
+
24
+ ```python
25
+ from django_telegram import Telegram
26
+
27
+ bot = Telegram() # reads BOT_TOKEN from your Django settings
28
+ message = bot.send_message(chat_id=123456, text="Hello!")
29
+ print(message.chat.id)
30
+ ```
31
+
32
+ > The package is installed as `django-telegram-bot-api` and imported as `django_telegram`.
33
+
34
+ ## Features
35
+
36
+ - **Every Bot API method** on a single `Telegram` client: send messages, answer callback queries, set webhooks, and the rest of the API.
37
+ - **Every Telegram type** as a Pydantic model, with validation and editor autocompletion.
38
+ - **Typed responses.** Use `message.chat.id` or `update.callback_query.data` instead of digging through dictionaries.
39
+ - **A small dispatcher.** Write one class per kind of update (commands, messages, button presses, inline queries) and the library routes incoming updates to it.
40
+ - **Built for Django.** Configuration comes from your Django settings, and you keep your own views and URLs.
41
+ - **Synchronous.** No event loop or async runtime required.
42
+
43
+ ## Contents
44
+
45
+ - [Installation](#installation)
46
+ - [Quick start](#quick-start)
47
+ - [Handling updates](#handling-updates)
48
+ - [More examples](#more-examples)
49
+ - [Calling the API directly](#calling-the-api-directly)
50
+ - [Configuration reference](#configuration-reference)
51
+
52
+ ## Installation
53
+
54
+ ```bash
55
+ pip install django-telegram-bot-api
56
+ ```
57
+
58
+ or with [uv](https://docs.astral.sh/uv/):
59
+
60
+ ```bash
61
+ uv add django-telegram-bot-api
62
+ ```
63
+
64
+ You do **not** need to add `django_telegram` to `INSTALLED_APPS`.
65
+
66
+ Requirements are listed in `pyproject.toml` (Python 3.13+ at the time of writing).
67
+
68
+ ## Quick start
69
+
70
+ This walks you from zero to a bot that answers `/start`. It has five steps:
71
+
72
+ 1. Configure your settings
73
+ 2. Create the bot client
74
+ 3. Write a handler
75
+ 4. Add the webhook view and URL
76
+ 5. Tell Telegram where your webhook is
77
+
78
+ ### 1. Configure your settings
79
+
80
+ Create a bot with [@BotFather](https://t.me/BotFather) to get a token, then add a `TELEGRAM` dictionary to your Django settings:
81
+
82
+ ```python
83
+ # settings.py
84
+ TELEGRAM = {
85
+ "BOT_TOKEN": "your-telegram-bot-token",
86
+ "TM_WEBHOOK_URL": "https://api.telegram.org",
87
+ }
88
+ ```
89
+
90
+ | Key | Required | Default | Description |
91
+ |---|---|---|---|
92
+ | `BOT_TOKEN` | Yes | n/a | Your bot token from [@BotFather](https://t.me/BotFather). |
93
+ | `TM_WEBHOOK_URL` | Yes | n/a | Base URL of the Telegram Bot API. Use `https://api.telegram.org`, or the address of your own local Bot API server. |
94
+ | `PROXY_SOCKS` | No | `""` | SOCKS proxy for outgoing requests, e.g. `127.0.0.1:1080`. |
95
+
96
+ If a required key is missing, `ImproperlyConfigured` is raised and the message tells you which one.
97
+
98
+ > [!TIP]
99
+ > Keep secrets out of your repository by reading them from environment variables:
100
+ >
101
+ > ```python
102
+ > import os
103
+ >
104
+ > TELEGRAM = {
105
+ > "BOT_TOKEN": os.environ["TELEGRAM_BOT_TOKEN"],
106
+ > "TM_WEBHOOK_URL": os.getenv("TELEGRAM_API_URL", "https://api.telegram.org"),
107
+ > }
108
+ > ```
109
+
110
+ ### 2. Create the bot client
111
+
112
+ Create a Django app for your bot (this guide calls it `bot`):
113
+
114
+ ```bash
115
+ python manage.py startapp bot
116
+ ```
117
+
118
+ Add it to `INSTALLED_APPS`, then create one shared client that all your handlers will import:
119
+
120
+ ```python
121
+ # bot/client.py
122
+ from django_telegram import Telegram
123
+
124
+ bot = Telegram() # reads BOT_TOKEN and TM_WEBHOOK_URL from settings
125
+ ```
126
+
127
+ > [!NOTE]
128
+ > You can still pass a token explicitly, for example in tests or when running several bots: `Telegram(token="123456:ABC-DEF")`.
129
+
130
+ Your app will end up looking like this:
131
+
132
+ ```text
133
+ bot/
134
+ ├── __init__.py
135
+ ├── client.py
136
+ ├── urls.py
137
+ ├── views.py
138
+ └── handlers/
139
+ ├── __init__.py
140
+ └── command_handlers.py
141
+ ```
142
+
143
+ ### 3. Write a handler
144
+
145
+ Handlers are classes. You inherit from one base class per kind of update and implement `handle(self, update)`. Commands (any message that starts with `/`) go to `CommandHandler`:
146
+
147
+ ```python
148
+ # bot/handlers/command_handlers.py
149
+ from django_telegram import CommandHandler, Update
150
+
151
+ from bot.client import bot
152
+
153
+
154
+ class Commands(CommandHandler):
155
+
156
+ def handle(self, update: Update):
157
+ chat_id = update.message.chat.id
158
+ text = update.message.text
159
+
160
+ if text.startswith("/start"):
161
+ bot.send_message(chat_id=chat_id, text="Hello!")
162
+ ```
163
+
164
+ Now register the file by importing it in your app's `__init__.py`:
165
+
166
+ ```python
167
+ # bot/__init__.py
168
+ from .handlers import command_handlers # noqa: F401
169
+ ```
170
+
171
+ > [!IMPORTANT]
172
+ > **A handler only exists once its file has been imported.**
173
+ >
174
+ > The dispatcher finds your handlers by looking at the subclasses of `CommandHandler`, `MessageHandler`, and the other base classes. If the file that defines a class is never imported, the dispatcher sees nothing and the update is silently ignored.
175
+ >
176
+ > Django loads `bot/__init__.py` when it starts (because `bot` is in `INSTALLED_APPS`), so your handlers are registered before the first update arrives. Each time you add a handler file, add it to the import in `bot/__init__.py`.
177
+
178
+ > [!NOTE]
179
+ > `bot/__init__.py` runs before Django's app registry is ready. If a handler file imports your Django models at the top, startup fails with `AppRegistryNotReady`. Import the models inside `handle()` instead.
180
+
181
+ ### 4. Add the webhook view and URL
182
+
183
+ The view receives Telegram's updates and passes them to the dispatcher:
184
+
185
+ ```python
186
+ # bot/views.py
187
+ import logging
188
+
189
+ from django_telegram import Dispatcher, Update
190
+ from rest_framework import status
191
+ from rest_framework.request import Request
192
+ from rest_framework.response import Response
193
+ from rest_framework.views import APIView
194
+
195
+ logger = logging.getLogger(__name__)
196
+
197
+
198
+ class TelegramWebhookView(APIView):
199
+ authentication_classes = []
200
+ permission_classes = []
201
+
202
+ def post(self, request: Request) -> Response:
203
+ try:
204
+ update = Update(**request.data)
205
+ Dispatcher(update).dispatch()
206
+ except Exception:
207
+ logger.exception("Error while processing Telegram update")
208
+
209
+ # Always answer 200, otherwise Telegram keeps retrying the same update.
210
+ return Response({"ok": True}, status=status.HTTP_200_OK)
211
+ ```
212
+
213
+ Add the route to the app, then include the app in your project URLs:
214
+
215
+ ```python
216
+ # bot/urls.py
217
+ from django.urls import path
218
+
219
+ from .views import TelegramWebhookView
220
+
221
+ app_name = "bot"
222
+
223
+ urlpatterns = [
224
+ path("webhook/", TelegramWebhookView.as_view(), name="webhook"),
225
+ ]
226
+ ```
227
+
228
+ ```python
229
+ # config/urls.py
230
+ from django.urls import include, path
231
+
232
+ urlpatterns = [
233
+ path("bot/", include("bot.urls", namespace="bot")),
234
+ ]
235
+ ```
236
+
237
+ Your webhook is now served at `https://your-domain.com/bot/webhook/`.
238
+
239
+ > [!NOTE]
240
+ > The view uses Django REST framework only because it is convenient. The library itself does not depend on it. Any Django view that builds an `Update` from the request body and calls `Dispatcher(update).dispatch()` works. `authentication_classes = []` and `permission_classes = []` make sure your project's default DRF permissions do not reject Telegram's requests.
241
+
242
+ ### 5. Tell Telegram where your webhook is
243
+
244
+ Telegram needs to know which URL to send updates to. Register it once with a `curl` request to the Bot API (replace `<BOT_TOKEN>` with your bot token and the URL with your own):
245
+
246
+ ```bash
247
+ curl -X POST "https://api.telegram.org/bot<BOT_TOKEN>/setWebhook" \
248
+ -d "url=https://your-domain.com/bot/webhook/"
249
+ ```
250
+
251
+ If it worked, Telegram answers:
252
+
253
+ ```json
254
+ {"ok": true, "result": true, "description": "Webhook was set"}
255
+ ```
256
+
257
+ To check the current webhook at any time:
258
+
259
+ ```bash
260
+ curl "https://api.telegram.org/bot<BOT_TOKEN>/getWebhookInfo"
261
+ ```
262
+
263
+ If you use your own local Bot API server, replace `https://api.telegram.org` with its address (the same value as `TM_WEBHOOK_URL` in your settings).
264
+
265
+ Telegram only delivers webhooks over **HTTPS** to a public address. While developing locally, expose your server with a tunnel such as [ngrok](https://ngrok.com/) or [cloudflared](https://developers.cloudflare.com/cloudflare-one/connections/connect-networks/) and use the tunnel URL.
266
+
267
+ Now send `/start` to your bot. It should answer `Hello!`.
268
+ ## Handling updates
269
+
270
+ `Dispatcher` looks at an incoming update, decides what kind it is, and calls `handle(update)` on your subclass of the matching base class.
271
+
272
+ | What the user does | Base class to inherit from |
273
+ |---|---|
274
+ | Sends a command such as `/start` | `CommandHandler` |
275
+ | Sends anything else (text, photo, document, voice, ...) | `MessageHandler` |
276
+ | Presses an inline button | `CallbackQueryHandler` |
277
+ | Types `@yourbot something` in any chat | `InlineQueryHandler` |
278
+ | Picks one of your inline results | `ChosenInlineResultHandler` |
279
+
280
+ Things to know:
281
+
282
+ - **The dispatcher does not look at the command name or the text.** Every command goes to your `CommandHandler` subclass, and you decide what to do for `/start`, `/help`, and so on inside `handle()`.
283
+ - **One class per kind is the intended setup.** If you define several subclasses of the same base class, all of them are called, in the order they were defined.
284
+ - **Updates with no matching handler are ignored.** If you do not write a `CallbackQueryHandler`, button presses are simply dropped.
285
+ - **Handlers run inside the web request.** Hand slow work (long downloads, heavy computation) to a task queue such as Celery.
286
+
287
+ The next section shows one example of each.
288
+
289
+ ## More examples
290
+
291
+ All examples assume the shared client from step 2 (`from bot.client import bot`) and the layout below. Remember to import each new file in `bot/__init__.py`.
292
+
293
+ ```text
294
+ bot/handlers/
295
+ ├── __init__.py (empty)
296
+ ├── command_handlers.py
297
+ ├── message_handlers.py
298
+ └── callback_query_handlers.py
299
+ ```
300
+
301
+ ```python
302
+ # bot/__init__.py
303
+ from .handlers import (
304
+ callback_query_handlers, # noqa: F401
305
+ command_handlers, # noqa: F401
306
+ message_handlers, # noqa: F401
307
+ )
308
+ ```
309
+
310
+ ### Commands: several commands and a reply keyboard
311
+
312
+ ```python
313
+ # bot/handlers/command_handlers.py
314
+ from django_telegram import CommandHandler, Update
315
+ from django_telegram.telegram_models import KeyboardButton, ReplyKeyboardMarkup
316
+
317
+ from bot.client import bot
318
+
319
+
320
+ class Commands(CommandHandler):
321
+
322
+ def handle(self, update: Update):
323
+ chat_id = update.message.chat.id
324
+ text = update.message.text
325
+
326
+ if text.startswith("/start"):
327
+ bot.send_message(chat_id=chat_id, text="Hello!")
328
+
329
+ elif text.startswith("/help"):
330
+ bot.send_message(
331
+ chat_id=chat_id,
332
+ text="Send /products to see what we sell.",
333
+ )
334
+
335
+ elif text.startswith("/products"):
336
+ bot.send_message(
337
+ chat_id=chat_id,
338
+ text="Choose one:",
339
+ reply_markup=ReplyKeyboardMarkup(
340
+ keyboard=[
341
+ [
342
+ KeyboardButton(text="product 1"),
343
+ KeyboardButton(text="product 2"),
344
+ ],
345
+ [
346
+ KeyboardButton(text="product 3"),
347
+ KeyboardButton(text="product 4"),
348
+ ],
349
+ ],
350
+ resize_keyboard=True,
351
+ ),
352
+ )
353
+
354
+ else:
355
+ bot.send_message(chat_id=chat_id, text="Unknown command.")
356
+ ```
357
+
358
+ ### Commands: reading arguments
359
+
360
+ Telegram sends everything after the command in the same text, so `/greet Reza` arrives as `"/greet Reza"`:
361
+
362
+ ```python
363
+ class Commands(CommandHandler):
364
+
365
+ def handle(self, update: Update):
366
+ chat_id = update.message.chat.id
367
+ parts = update.message.text.split()
368
+
369
+ command = parts[0] # "/greet"
370
+ args = parts[1:] # ["Reza"]
371
+
372
+ if command == "/greet":
373
+ name = args[0] if args else "stranger"
374
+ bot.send_message(chat_id=chat_id, text=f"Hello, {name}!")
375
+ ```
376
+
377
+ > [!TIP]
378
+ > In groups, Telegram may send commands as `/greet@yourbot`. If your bot is used in groups, strip the suffix with `command.split("@")[0]`.
379
+
380
+ ### Messages: reply keyboard text and an inline button
381
+
382
+ When the user presses a **reply keyboard** button, Telegram sends its text as a normal message, so you handle it in a `MessageHandler`. Here the bot answers with a message that has an **inline button** attached:
383
+
384
+ ```python
385
+ # bot/handlers/message_handlers.py
386
+ from django_telegram import MessageHandler, Update
387
+ from django_telegram.telegram_models import InlineKeyboardButton, InlineKeyboardMarkup
388
+
389
+ from bot.client import bot
390
+
391
+
392
+ class Messages(MessageHandler):
393
+
394
+ def handle(self, update: Update):
395
+ chat_id = update.message.chat.id
396
+ text = update.message.text
397
+
398
+ if text == "product 1":
399
+ bot.send_message(
400
+ chat_id=chat_id,
401
+ text="product 1",
402
+ reply_markup=InlineKeyboardMarkup(
403
+ inline_keyboard=[
404
+ [
405
+ InlineKeyboardButton(text="Details", callback_data="pro1"),
406
+ InlineKeyboardButton(text="Buy", callback_data="buy:1"),
407
+ ],
408
+ [
409
+ InlineKeyboardButton(text="Open website", url="https://example.com"),
410
+ ],
411
+ ],
412
+ ),
413
+ )
414
+
415
+ else:
416
+ bot.send_message(chat_id=chat_id, text=f"You said: {text}")
417
+ ```
418
+
419
+ A button either has a `callback_data` (Telegram sends it back to your bot when pressed) or a `url` (Telegram opens the link and tells your bot nothing).
420
+
421
+ ### Messages: photos and documents
422
+
423
+ There is no separate handler for media. Photos, documents, voice messages, and the like arrive in the same `MessageHandler`, with `message.text` empty and the matching field filled in. Check which one is present inside `handle()`:
424
+
425
+ ```python
426
+ # bot/handlers/message_handlers.py
427
+ from django_telegram import MessageHandler, Update
428
+
429
+ from bot.client import bot
430
+
431
+
432
+ class Messages(MessageHandler):
433
+
434
+ def handle(self, update: Update):
435
+ message = update.message
436
+ chat_id = message.chat.id
437
+
438
+ if message.photo:
439
+ # Telegram sends several sizes; the last one is the largest.
440
+ file_id = message.photo[-1].file_id
441
+ bot.send_message(chat_id=chat_id, text=f"Nice photo! file_id: {file_id}")
442
+
443
+ elif message.document:
444
+ bot.send_message(
445
+ chat_id=chat_id,
446
+ text=f"Got your file: {message.document.file_name}",
447
+ )
448
+
449
+ elif message.voice:
450
+ bot.send_message(chat_id=chat_id, text="Got your voice message.")
451
+
452
+ else:
453
+ bot.send_message(chat_id=chat_id, text=f"You said: {message.text}")
454
+ ```
455
+
456
+ If your bot handles both text buttons and media, put all the branches in the same `handle()`, since there is one `MessageHandler` subclass.
457
+
458
+ ### Callback queries: alerts, toasts, and editing the message
459
+
460
+ When the user presses an inline button, Telegram sends a callback query instead of a message:
461
+
462
+ ```python
463
+ # bot/handlers/callback_query_handlers.py
464
+ from django_telegram import CallbackQueryHandler, Update
465
+
466
+ from bot.client import bot
467
+
468
+
469
+ class Callbacks(CallbackQueryHandler):
470
+
471
+ def handle(self, update: Update):
472
+ query = update.callback_query
473
+ data = query.data
474
+
475
+ if data == "pro1":
476
+ # Pop-up alert with an OK button
477
+ bot.answer_callback_query(
478
+ callback_query_id=query.id,
479
+ text="hi this is product 1",
480
+ show_alert=True,
481
+ )
482
+
483
+ elif data.startswith("buy:"):
484
+ product_id = data.split(":")[1]
485
+
486
+ # Small toast at the top of the screen
487
+ bot.answer_callback_query(
488
+ callback_query_id=query.id,
489
+ text=f"Product {product_id} added to your cart",
490
+ )
491
+
492
+ # Replace the text of the message that held the button
493
+ bot.edit_message_text(
494
+ chat_id=query.message.chat.id,
495
+ message_id=query.message.message_id,
496
+ text=f"Product {product_id} is in your cart.",
497
+ )
498
+ ```
499
+
500
+ > [!IMPORTANT]
501
+ > Always call `answer_callback_query` for every callback query, even with no text. It stops the loading spinner on the button.
502
+
503
+ Putting data in `callback_data` (`"buy:1"`) is the usual way to tell buttons apart. Telegram limits it to 64 bytes.
504
+
505
+ ### Inline queries
506
+
507
+ When someone types `@yourbot something` in any chat, Telegram sends an inline query. Answer it with a list of results:
508
+
509
+ ```python
510
+ # bot/handlers/inline_query_handlers.py
511
+ from django_telegram import InlineQueryHandler, Update
512
+
513
+ from bot.client import bot
514
+
515
+
516
+ class InlineQueries(InlineQueryHandler):
517
+
518
+ def handle(self, update: Update):
519
+ query = update.inline_query
520
+
521
+ bot.answer_inline_query(
522
+ inline_query_id=query.id,
523
+ results=[
524
+ {
525
+ "type": "article",
526
+ "id": "1",
527
+ "title": f"Search for {query.query}",
528
+ "input_message_content": {"message_text": query.query},
529
+ },
530
+ ],
531
+ )
532
+ ```
533
+
534
+ Inline mode must be enabled for your bot in [@BotFather](https://t.me/BotFather) (`/setinline`). Do not forget to import the file in `bot/__init__.py`.
535
+
536
+ ## Calling the API directly
537
+
538
+ You do not need handlers to use the client. Anywhere in your Django project (a view, a management command, a Celery task, a signal), you can call the API and work with the typed response:
539
+
540
+ ```python
541
+ from bot.client import bot
542
+
543
+ # Send a message and read the response
544
+ message = bot.send_message(chat_id=123456, text="Your order has shipped.")
545
+ print(message.message_id, message.chat.id, message.date)
546
+
547
+ # Send a message with formatting
548
+ bot.send_message(
549
+ chat_id=123456,
550
+ text="<b>Order #42</b> is on its way.",
551
+ parse_mode="HTML",
552
+ )
553
+ ```
554
+
555
+ Because the types are Pydantic models, you also get `message.model_dump()` and `message.model_dump_json()` for free.
556
+
557
+ A common use is notifying users from your own code, for example when an order changes status:
558
+
559
+ ```python
560
+ # orders/signals.py
561
+ from django.db.models.signals import post_save
562
+ from django.dispatch import receiver
563
+
564
+ from bot.client import bot
565
+ from .models import Order
566
+
567
+
568
+ @receiver(post_save, sender=Order)
569
+ def notify_customer(sender, instance, **kwargs):
570
+ if instance.status == "shipped":
571
+ bot.send_message(
572
+ chat_id=instance.customer.telegram_id,
573
+ text=f"Order #{instance.pk} has shipped.",
574
+ )
575
+ ```
576
+
577
+ ## Configuration reference
578
+
579
+ All settings live in the `TELEGRAM` dictionary in your Django settings.
580
+
581
+ | Key | Required | Default | Description |
582
+ |---|---|---|---|
583
+ | `BOT_TOKEN` | Yes | n/a | Bot token from [@BotFather](https://t.me/BotFather). |
584
+ | `TM_WEBHOOK_URL` | Yes | n/a | Base URL of the Telegram Bot API (`https://api.telegram.org` or your own local Bot API server). |
585
+ | `PROXY_SOCKS` | No | `""` | SOCKS proxy for outgoing requests, e.g. `127.0.0.1:1080`. |
586
+
587
+ Settings are read when the client is created, not when Django starts, and `override_settings` works as usual in your tests.