# darkob — complete reference darkob 0.18.0 — async Python for the Rubika and Shad messaging platforms. Read this file top to bottom before writing code. It contains the full public API (every real signature), the filter catalogue, the patterns, and the mistakes to avoid. No other page is required. Hard rules: - Handlers are `async def name(bot, event)`. - `event`, never `message`; `event.chat_id`, never `event.chat.id`. - Filters come from `darkob.bot.filters` and are INSTANTIATED: `IsGroup()`, not `IsGroup`. - There is no Dispatcher, no message_handler, no aiogram/Pyrogram types. - If a method is not in the API section below, it does not exist. --- # SOURCE: get-started/installation.md ## Requirements - Python **3.9 – 3.14** - Linux, macOS or Windows ## Install ```bash pip install darkob ``` The core install is deliberately small — `aiohttp`, `aiofiles` and `pycryptodome`. Nothing else is required, and no method is lost when the extras are absent. Optional extras: ```bash pip install "darkob[speed]" # msgspec: faster JSON on every update pip install "darkob[cli]" # rich: styled console banner and prompts ``` Media metadata (audio duration, image and video dimensions) needs **no** dependency at all: `darkob.utils.media_parser` reads the binary headers directly with the standard library. That used to require `mutagen` plus a temporary file per upload. Further extras, needed only for specific media features: ```bash pip install "darkob[opencv]" # video thumbnails via OpenCV pip install "darkob[movie]" # video thumbnails via MoviePy pip install "darkob[pillow]" # image thumbnails via Pillow pip install "darkob[aiortc]" # voice chats pip install "darkob[pro]" # everything above ``` ## Verify ```bash python -c "import darkob; print(darkob.__version__)" ``` Importing darkob performs no network I/O and prints nothing unless you ask it to. ## Development install ```bash git clone https://github.com/ManiTheFerfri/darkob.git cd darkob pip install -e ".[dev]" pytest # 121 tests, no network required ruff check . # lint pytest --cov=darkob # coverage ``` ## The banner `Bot(...)` and `Messenger(...)` print a one-time welcome banner. Disable it when it would pollute logs: ```python bot = Bot(token="...", show_welcome=False) ``` ## Checking for updates Never automatic. Call it yourself if you want a notice: ```python import darkob darkob.check_for_updates() # returns the new version string, or None ``` --- # SOURCE: get-started/quickstart.md ## 1. Get a bot token Create a bot with Rubika's official bot creator and copy the token it gives you. A valid token looks like 64 uppercase alphanumeric characters. ## 2. Your first bot ```python from darkob import Bot bot = Bot(token="YOUR_BOT_TOKEN") @bot.on_command("start") async def start(bot, event): await event.reply("Welcome 👋") @bot.on_new_message() async def echo(bot, event): await event.reply(event.text) bot.run() ``` `bot.run()` starts long polling and blocks until you stop it with Ctrl+C. ## 3. Send messages from a handler ```python @bot.on_command("hello") async def hello(bot, event): await bot.send_message(event.chat_id, "Hello!") ``` `event` carries the incoming update: | Attribute | Meaning | | --- | --- | | `event.chat_id` | Conversation to reply in | | `event.author_id` | User who sent it | | `event.text` | Message text (`""` when there is none) | | `event.reply(text)` | Shortcut: send into the same chat | | `event.forward()`, `event.delete()` | Act on the message | ## 4. Run as a webhook instead Polling needs no public address; webhooks need one. ```python bot.run( webhook_url="https://example.com/wk", host="0.0.0.0", port=8080, ) ``` Turbo mode is `bot.run()` with no arguments — it polls every 5 ms by default, tunable with `poll_interval`. !!! warning "Always set a webhook secret" A webhook URL that leaks lets anyone inject fake updates into your bot — a fake `/start`, a fake admin command. darkob cannot verify who posted, so agree on a shared secret: ```python bot = Bot(token="...", webhook_secret="long-random-string") bot.run(webhook_url="https://example.com/wk?secret=long-random-string") ``` Requests without a matching `?secret=` or `X-Webhook-Secret` header are rejected with `401`. With no secret configured, a warning is logged on the first webhook request. ## 5. Tell users what the bot can do ```python bot.set_commands({ "start": "Start the bot", "help": "Show help", }) ``` ## 6. Grow the bot Once one file stops being enough: - [Handlers](handlers.md) — every decorator and what triggers it - [Filters](filters.md) — narrow down which events a handler sees - [Routers](routers.md) — split handlers into modules - [Conversations](fsm.md) — multi-step flows - [Errors](errors.md) — stop silent failures ## Async or not? Every method works both ways. Without `await`, darkob runs the call on a background loop and returns the result: ```python bot = Bot(token="YOUR_TOKEN") me = bot.get_me() # blocking, returns the result me = await bot.get_me() # async, same result ``` Mixing is safe, but pick one style per codebase. See [Sync and async](../guides/sync-and-async.md). --- # SOURCE: get-started/migrating-from-maxrubika.md darkob is a fork of [maxrubika](https://github.com/MEH2RAB/maxrubika). It keeps the same concepts and most of the same method names, so most bots port in minutes. ## 1. Change the package name ```bash pip uninstall maxrubika pip install darkob ``` ```diff - import maxrubika - from maxrubika import Bot + import darkob + from darkob import Bot ``` The exported names are unchanged: `Bot`, `bot`, `Client`, `Messenger`, `messenger`, `Shad`, `shad`. ## 1b. Or change nothing but the import If you would rather migrate later, run the existing code through the compatibility shim — the only change is the import line: ```diff - from maxrubika import Messenger + from darkob.compat.maxrubika import Messenger ``` Everything maxrubika exported is re-exported there, plus the new darkob APIs, so a half-migrated file still imports cleanly. The module emits a `DeprecationWarning` on import to remind you it is a migration aid, not a destination. ## 2. Re-authenticate existing sessions !!! warning "Old session files will not load" darkob derives its session encryption key from a different salt than maxrubika, and prefixes session files with `darkob_` instead of `maxrubika_`. Existing encrypted sessions, string sessions and bot tokens cannot be carried over — log in again and store the new credentials. This is deliberate: a fork should not silently reuse key material from a different package. ## 3. Behaviour that changed | Area | Change | Action needed | | --- | --- | --- | | Import | No PyPI update check at import | None. Call `darkob.check_for_updates()` if you want it | | TLS | Verification **on** by default | If you use a proxy that cannot verify upstreams, pass `verify_ssl=False` | | Errors | Bare `except:` blocks narrowed | Failures you previously never saw may now surface as exceptions — this is intentional | | Retries | `max_retries` is a per-request budget, not per endpoint | Expect faster failure and fewer duplicate requests | | Dispatch | Handlers are indexed by update name | None; ordering within a name is preserved | | Threads | Sync handlers use a bounded executor | None for normal handlers | | Sessions | Downloads reuse a pooled session | `download_file` now raises `NoConnection` if you never called `start()` | ## 4. New capabilities - [`Router`](../guides/routers.md) — group handlers into modules - [`FSMContext`](../guides/fsm.md) — multi-step conversations - Generated [API reference](../api/bot.md) that matches the runtime ## 5. Verify ```python import darkob print(darkob.__version__) # 0.2.x ``` Then run your bot through its normal path. If something that used to log and continue now raises, that is the stability work doing its job — open an issue if the new behaviour is wrong. --- # SOURCE: tutorials/first-bot.md A hands-on walkthrough that ends with a bot which echoes, answers one command, and puts a working button under a message. ## 1. Install ```bash pip install darkob ``` darkob needs Python 3.9 or newer. Confirm the install: ```bash python -c "import darkob; print(darkob.__version__)" ``` Importing darkob performs no network I/O, so this works offline. ## 2. Get a bot token Create a bot with Rubika's official bot creator and copy the token it shows you. A token is 64 characters: five uppercase letters, then 59 characters that are digits or uppercase letters. !!! warning "The token is a password" Anyone holding it can send messages as your bot. Keep it out of the repository and read it from the environment instead: ```python import os token = os.environ["RUBIKA_BOT_TOKEN"] ``` ## 3. A bot that echoes messages Create `bot.py`: ```python title="bot.py" from darkob import Bot bot = Bot(token="YOUR_BOT_TOKEN") @bot.on_new_message() async def echo(bot, event): await event.reply(event.text) bot.run() ``` `Bot(...)` validates the token and creates its handler registry; the HTTP session is opened on first use. `bot.run()` then starts long polling and blocks until you stop it. Run it and send the bot any message: ```bash python bot.py ``` A one-time banner appears, then `Bot started in polling mode...`. The bot answers with the same text you sent. Stop it with Ctrl+C. A handler is a plain async function taking two arguments: the bot, and the event. `event.text` holds the message text, or `None` when the update carries none, and `event.reply(text)` sends into the same chat as a threaded reply. !!! note "A mistyped token does not raise" If the token does not match the expected shape, `Bot(...)` asks for one interactively in the terminal. A prompt in the middle of a deployment log means the token was wrong, not missing. ## 4. Only answer commands Echoing everything is rarely useful. A filter decides whether a handler runs, so add one: ```python title="bot.py" from darkob import Bot from darkob.bot.filters import Command bot = Bot(token="YOUR_BOT_TOKEN") @bot.on_new_message(Command("echo")) async def echo(bot, event): await event.reply(event.command_args or "nothing to echo") bot.run() ``` Now `/echo hello` replies `hello`, while a plain `hello` is ignored. The filter matches `/echo` and `/echo@your_bot`, and lets every other command fall through to other handlers. `event.command_args` is everything after the command, or `""`. !!! tip "One decorator instead of two filters" `@bot.on_command("echo")` applies the message and command filters for you, and takes a list: `@bot.on_command(["echo", "بازگو"])`. Once your bot has several commands, that shortcut keeps the code shorter. ## 5. Add an inline keyboard button Buttons live under the message, so they need an inline keypad. Give each button an `id`; that id is what comes back when somebody presses it. ```python title="bot.py" from darkob import Bot, Button, Keyboard bot = Bot(token="YOUR_BOT_TOKEN") @bot.on_command("menu") async def menu(bot, event): keypad = Keyboard().row( Button("Say hi", id="hi"), Button("Docs", id="docs"), ) await bot.send_message(event.chat_id, "Pick one:", inline_keypad=keypad) @bot.on_callback() async def on_button(bot, event): if event.button_id == "hi": await event.reply("Hi there 👋") else: await event.reply("Docs: https://github.com/ManiTheFerfri/darkob") bot.run() ``` A press arrives as an `InlineMessage` update, and `@bot.on_callback()` fires on exactly that. `event.button_id` holds the `id` you set, and `event.reply(...)` still works because the payload carries the chat and message it belongs to. Buttons without an explicit `id` get a numeric one assigned for you (`"100"`, `"101"`, …). That is fine for a static menu, but an explicit id is what makes the handler readable. ## 6. Run it The finished file: ```python title="bot.py" import os from darkob import Bot, Button, Keyboard from darkob.bot.filters import Command bot = Bot(token=os.environ["RUBIKA_BOT_TOKEN"]) @bot.on_new_message(Command("echo")) async def echo(bot, event): await event.reply(event.command_args or "nothing to echo") @bot.on_command("menu") async def menu(bot, event): keypad = Keyboard().row( Button("Say hi", id="hi"), Button("Docs", id="docs"), ) await bot.send_message(event.chat_id, "Pick one:", inline_keypad=keypad) @bot.on_callback() async def on_button(bot, event): if event.button_id == "hi": await event.reply("Hi there 👋") else: await event.reply("Docs: https://github.com/ManiTheFerfri/darkob") bot.run() ``` ```bash python bot.py ``` Send `/echo hi`, then `/menu` and press a button. Both handlers fire, in that order of registration, for events that match them. ## Where to go next - More decorators and middleware: [Handlers](../guides/handlers.md) - Narrow handlers by chat, media or text: [Filters](../guides/filters.md) - Every button type the API accepts: [Keyboards and formatting](../guides/keyboards.md) - Multi-step conversations: [Conversations (FSM)](../guides/fsm.md) - Test all of this without a token: [Testing without a token](testing-without-a-token.md) ## See also - [Quickstart](../get-started/quickstart.md) - [Installation](../get-started/installation.md) - [Errors](../guides/errors.md) - [Testing bots](../guides/testing.md) - [Architecture](../explanation/architecture.md) --- # SOURCE: guides/handlers.md A handler is an async (or plain) function registered on the bot. darkob calls it as `handler(bot, event)` when a matching update arrives. ## Decorators All decorators are available on a `Bot` instance. | Decorator | Fires on | | --- | --- | | `@bot.on_new_message()` | Brand-new messages | | `@bot.on_edit_message()` | Edited messages | | `@bot.on_delete_message()` | Deleted messages | | `@bot.on_message()` | Any of new / edit / delete / inline | | `@bot.on_callback()` | Inline keyboard clicks | | `@bot.on_command("start")` | Messages that start with a command | | `@bot.on_update()` | **Any** update the server sends | | `@bot.on_event_data()` | System events (joins, leaves, pins, …) | | `@bot.on_bot_joined()` | Bot added to a chat | | `@bot.on_bot_removed()` | Bot removed from a chat | | `@bot.on_bot_permissions_changed()` | Bot rights changed | | `@bot.on_started_bot()` / `@bot.on_stopped_bot()` | Bot lifecycle on the server | | `@bot.on_start()` / `@bot.on_shutdown()` | Your process starting / stopping | ## Basic handler ```python @bot.on_new_message() async def echo(bot, event): await event.reply(event.text) ``` ## Adding constraints Every decorator accepts constraints, which decide whether the handler runs. They compose with `&`, `|` and `~`. ```python from darkob.bot.filters import IsGroup, IsImage @bot.on_new_message(IsGroup(), IsImage()) async def group_photo(bot, event): await event.reply("Nice picture") ``` See [Filters](filters.md) for the full list. ## Commands ```python @bot.on_command("start") @bot.on_command(["start", "begin", "شروع"]) @bot.on_command() # any command @bot.on_command("help", prefixes=["/", "!"]) ``` ## Editing a message ```python await bot.edit_message( event.chat_id, event.message_id, "Updated text", inline_keypad=Keyboard().row("Done"), ) ``` The inline keypad is optional; omit it to leave the existing buttons alone. ## Middleware A middleware wraps dispatch. Call `call_next()` to continue, or return without calling it to stop the chain. ```python @bot.middleware() async def log_everything(bot, event, call_next): print("incoming:", getattr(event, "text", "")) await call_next() ``` Middlewares run in registration order, outermost first. ## Ordering and stopping By default every matching handler runs, in registration order. Set `run_all_handlers=False` on the bot to run only the first match: ```python bot = Bot(token="...", run_all_handlers=False) ``` A handler that raises does not stop the others; the exception is logged. ## Lifecycle hooks ```python @bot.on_start() async def warm_up(bot): print("bot is starting") @bot.on_shutdown() async def clean_up(bot): print("bot is stopping") ``` ## Sync handlers A plain function works too — it is executed in a bounded thread pool so it cannot block the event loop: ```python @bot.on_command("ping") def ping(bot, event): bot.send_message(event.chat_id, "pong") ``` --- # SOURCE: guides/filters.md Filters decide whether a handler runs. Import them from `darkob.bot.filters`. ```python from darkob.bot.filters import IsGroup, Text, IsImage ``` ## Composing Filters combine with Python operators: `&` (both), `|` (either), `~` (not). ```python @bot.on_new_message(IsGroup() & ~IsImage()) async def text_in_group(bot, event): ... ``` Precedence follows Python: `~` binds tighter than `&`, which binds tighter than `|`. ## Message shape | Filter | Matches | | --- | --- | | `IsMessage()` | A new message | | `IsEdited()` | An edit | | `IsDeleted()` | A deletion | | `IsCallback()` | An inline keyboard callback | | `IsStartedBot()` / `IsStoppedBot()` | Bot lifecycle updates | | `IsEventData()` | System event payloads | ## Text | Filter | Matches | | --- | --- | | `Text("hello")` | Text containing the pattern (regex) | | `TextMatch(r"name: (\w+)")` | Same, and stores the match on `event.pattern_match` | | `Command("start")` | A command, optionally with a bot suffix | | `IsText()` | Any text message | ```python @bot.on_new_message(TextMatch(r"order\s+(\d+)")) async def order(bot, event): number = event.pattern_match.group(1) await event.reply(f"Order #{number}") ``` ## Chat kind | Filter | Matches | | --- | --- | | `IsUser()` | A direct chat | | `IsGroup()` | A group | | `IsChannel()` | A channel | | `ChatType("Group")` | By explicit type name | | `FromChat("g0…")` | A specific chat | | `FromUser("u0…")` | A specific user | ## Media `IsFile()`, `IsImage()`, `IsVideo()`, `IsVoice()`, `IsMusic()`, `IsSticker()`, `IsPoll()`, `IsLocation()`, `IsReply()`, `IsForwarded()`. Forward details: `ForwardedFromUser()`, `ForwardedFromChannel()`, `ForwardedFromBot()`, `ForwardedNoLink()`. ## Formatting metadata | Filter | Matches | | --- | --- | | `HasMetadata()` | Text carrying bold/italic/link formatting | | `MetadataType("Bold")` | A specific metadata type | ## Membership and rights | Filter | Matches | | --- | --- | | `IsJoined()` | The bot/user is a member | | `IsAdmin()` | Admin rights | | `IsOwner()` | Ownership | ## Events ```python from darkob.bot.filters import EventType @bot.on_event_data(EventType("AddedGroupMembers")) async def someone_joined(bot, event): await event.reply("Welcome to the group!") ``` ## Writing your own Subclass `EventConstraint` and implement `evaluate`: ```python from darkob.bot.filters import EventConstraint class IsLongMessage(EventConstraint): def __init__(self, minimum: int = 500): self.minimum = minimum async def evaluate(self, event) -> bool: return len(getattr(event, "text", "") or "") >= self.minimum ``` `evaluate` may be async and may do I/O. A filter that raises is treated as "no match" and the error is logged. --- # SOURCE: guides/routers.md A `Router` collects handlers without needing a bot instance, then registers them all at once. Use it to split a bot into feature modules. ## Basic use ```python from darkob import Bot, Router bot = Bot(token="YOUR_BOT_TOKEN") admin = Router("admin") @admin.command("ban") async def ban(bot, event): await bot.ban_member(event.chat_id, event.author_id) await event.reply("Banned.") bot.include_router(admin) bot.run() ``` ## Why bother - Handlers live next to the feature they implement, in their own file. - A module can be tested without a token. - Nested routers let one root assemble the whole bot. ## Nesting ```python root = Router("root") admin = Router("admin") moderation = Router("moderation") admin.include_router(moderation) root.include_router(admin) bot.include_router(root) # registers everything, recursively ``` `len(router)` counts all routes including children. ## Router decorators Mirror the bot decorators exactly: `update()`, `message()`, `new_message()`, `edit_message()`, `delete_message()`, `callback()`, `command()`, `event_data()`. ```python @router.command("start") @router.command(["help", "?", "راهنما"]) @router.message(IsGroup()) ``` Constraints are passed through unchanged, so a router route behaves identically to the same decorator written on the bot. ## Router middleware A middleware declared on a router wraps **only** that router's handlers, including routers nested inside it. ```python @router.middleware() async def log(bot, event, call_next): print("before") await call_next() print("after") ``` Call `await call_next()` to continue; return without calling it to stop the handler. Multiple middlewares run outermost-first. ## Inspecting a router ```python router.routes # routes declared directly on this router router.children # nested routers len(router) # total routes, recursively router.apply(bot) # register manually; returns the number registered ``` ## Registration rules - `include_router` returns the router, so calls chain. - Including the same child twice is a no-op. - A router cannot include itself (`ValueError`). - `bot.include_router(obj)` raises `TypeError` if `obj` is not a `Router`. - Handlers register in declaration order; middleware, if any, is bot-level. ## Testing a router without a token ```python router = Router() @router.command("ping") async def ping(bot, event): ... assert len(router) == 1 assert router.routes[0].kind == "on_command" ``` --- # SOURCE: guides/fsm.md A finite state machine tracks which step a user is on, and what they have already told you. ## The idea Two pieces of data per conversation: - **state** — a string like `"waiting_for_address"`, or `None` - **data** — a free-form dict Both live in a `Storage`, keyed by chat (or user) id. ## Complete example ```python from darkob import Bot, FSMContext, JsonFileStorage, StateFilter bot = Bot(token="YOUR_BOT_TOKEN") storage = JsonFileStorage("fsm.json") # survives restarts @bot.on_command("order") async def order(bot, event): ctx = FSMContext(storage, key=event.chat_id) await ctx.set_state("address") await event.reply("What is your delivery address?") @bot.on_new_message(StateFilter(storage, "address")) async def address(bot, event): ctx = FSMContext(storage, key=event.chat_id) await ctx.update_data(address=event.text) await ctx.clear() await event.reply("Order received ✅") ``` The second handler only runs while the conversation is in the `address` state, so it will not hijack unrelated messages. ## Storage backends | Storage | Survives restart | Use for | | --- | --- | --- | | `MemoryStorage()` | No | Tests, ephemeral bots | | `JsonFileStorage("fsm.json")` | Yes | Single-process bots | | `TTLMemoryStorage(ttl=3600)` | No | State that should expire | | `SQLiteStorage("fsm.db")` | Yes | Durable and concurrency-safe | `JsonFileStorage` writes atomically, tolerates a corrupt file (it starts empty rather than crashing), and is safe to call from concurrent tasks. `JsonFileStorage` writes atomically and tolerates a corrupt file. `SQLiteStorage` runs in WAL mode, so it survives a hard kill mid-write and is safe for several tasks writing at once. ```python from darkob import SQLiteStorage, TTLMemoryStorage storage = SQLiteStorage("darkob_fsm.db") # durable storage = TTLMemoryStorage(ttl=1800) # forgets after 30 min ``` ## FSMContext ```python ctx = FSMContext(storage, key="g0abc") # explicit key ctx = FSMContext.from_event(storage, event) # key from the event await ctx.get_state() # str | None await ctx.set_state("waiting") await ctx.set_state(None) # clear the state await ctx.get_data() # dict await ctx.set_data({"a": 1}) # replace await ctx.update_data(a=2, b=3) # merge, returns the new dict await ctx.clear() # state + data ``` ## StateFilter ```python StateFilter(storage, "address") StateFilter(storage, "address", key_func=lambda e: e.author_id) ``` It is a normal filter, so it composes: ```python from darkob.bot.filters import IsGroup @bot.on_new_message(IsGroup() & StateFilter(storage, "address")) async def group_address(bot, event): ... ``` ## Choosing a key `default_storage_key` prefers `chat_id`, then `object_guid`, then `author_object_guid`, falling back to `"default"`. Use a custom key to scope a conversation per user instead of per chat: ```python ctx = FSMContext(storage, key=f"order:{event.author_id}") ``` ## Custom storage Implement `Storage` to back it with Redis or SQL: ```python from darkob import Storage class RedisStorage(Storage): async def get_state(self, key): ... async def set_state(self, key, state): ... async def get_data(self, key): ... async def set_data(self, key, data): ... ``` The four methods are all you need; `clear()` and `close()` have default implementations. --- # SOURCE: guides/inline-conversations.md Two ways to ask a user something without writing a state machine. ## `ask()` — wait for the next reply ```python from darkob import Bot, NoReply bot = Bot(token="...") @bot.on_command("signup") async def signup(bot, event): await event.reply("What is your name?") try: reply = await bot.ask(event.chat_id, timeout=60) except NoReply: await event.reply("Never mind.") return await event.reply(f"Nice to meet you, {reply.text}") ``` While the prompt is pending, the next message in that chat is handed to **you** instead of being dispatched to handlers, so no `waiting_for = True` flag is needed. ### With a prompt and filters ```python reply = await bot.ask( event.chat_id, "Send me a photo", filters=[lambda ev: ev.text and ev.text.startswith("/")], timeout=30, ) ``` The `text` argument is optional — pass it to send the question for you: ```python reply = await bot.ask(event.chat_id, "Pick one", inline_keypad=Keyboard().row("A", "B")) ``` Both surfaces support it: `bot.ask(...)` and `client.ask(...)`. | Behaviour | Detail | | --- | --- | | Timeout | Raises `darkob.NoReply` (a `TimeoutError` subclass) | | Queueing | Two pending asks in one chat are served oldest-first | | Filters | Each is called with the event; sync or async, exceptions count as "no match" | | Cleanup | The waiter is removed on success, timeout or cancellation | ## `StatesGroup` — named states Plain strings work, but a class keeps them together and typo-free: ```python from darkob import FSMContext, JsonFileStorage, State, StateFilter, StatesGroup storage = JsonFileStorage("fsm.json") class Form(StatesGroup): name = State() email = State() @bot.on_command("register") async def register(bot, event): ctx = FSMContext(storage, key=event.chat_id) await ctx.set_state(Form.name) await event.reply("Name?") @bot.on_new_message(StateFilter(storage, Form.name)) async def got_name(bot, event): ctx = FSMContext(storage, key=event.chat_id) await ctx.update_data(name=event.text) await ctx.set_state(Form.email) await event.reply("Email?") ``` `State` is a `str` subclass ordered by its group, so it flows through every existing helper — storage backends, `StateFilter`, and comparisons — with no changes: ```python Form.name == "Form.name" # True Form.states() # {"name": State('Form.name'), ...} list(Form.values()) # ["Form.name", "Form.other"] ``` Two groups cannot collide: `Form.name` and `Survey.name` are different state strings. ## Which to use | Need | Use | | --- | --- | | One question, then continue | `ask()` | | Several steps, resumable after a restart | `StatesGroup` + `FSMContext` | | Steps that must survive the process | FSM with `JsonFileStorage` or `SQLiteStorage` | --- # SOURCE: guides/keyboards.md Two helpers remove most of the boilerplate from bot code: keypad builders, and text formatting. ## Keypads A :class:`Keyboard` **is** a dict (`{"rows": [...]}`), so it can be passed anywhere the API accepts a raw keypad. Ids and button types are filled in automatically. ```python from darkob import Keyboard keypad = Keyboard().row("Yes", "No").row("Cancel") await bot.send_message(chat_id, "Continue?", inline_keypad=keypad) ``` Chat keyboards (the persistent bottom keyboard) use the same builder: ```python await bot.send_message(chat_id, "Menu", chat_keypad=Keyboard().row("Help", "Settings")) ``` ### Chaining ```python Keyboard() # empty .row("A", "B") # one row, two buttons .row("C") # second row .button("Alone") # a row with a single button .clear() # remove all rows ``` Inspect before sending: ```python keyboard.row_count # number of rows keyboard.button_count # total buttons keyboard.to_dict() # plain-dict copy Keyboard.from_rows([["A", "B"], ["C"]]) ``` ### Explicit buttons ```python from darkob import Button Button("Delete", id=42, type="Selection") Keyboard().row( Button("Delete", id=42, type="Selection"), "Plain string button", {"button_text": "Raw dict", "type": "Simple"}, ) ``` `Button` accepts `text`, `id`, `type` and any extra keyword fields, which are forwarded to the API verbatim: ```python Button("Open", url="https://example.com") ``` An empty button label raises `ValueError` immediately instead of failing server-side. ### With the Messenger surface The userbot `send_message` takes `inline_keypad` and `chat_keypad` too, and accepts the same `Keyboard`. ## Text formatting Rubika renders a small Markdown dialect. These helpers produce it exactly: | Helper | Output | | --- | --- | | `bold("x")` | `**x**` | | `italic("x")` | `__x__` | | `strike("x")` | `~~x~~` | | `underline("x")` | `--x--` | | `spoiler("x")` | `\|\|x\|\|` | | `code("x")` | `` `x` `` | | `pre("x", "python")` | fenced block | | `link("text", url)` | `[text](url)` | | `join([...])` | skips empty fragments | ```python from darkob import bold, code, link await event.reply( f"{bold('Deployed')} {code('v0.2.1')} — {link('logs', 'https://example.com')}" ) ``` They return plain strings, so they compose inside f-strings and nest: ```python bold(f"{italic('nested')} works") ``` `link()` raises `ValueError` on an empty URL rather than sending a malformed message. ## Button types The Bot API documents 19 button types. Every one has a builder, and the fields each builder sends are the ones the reference lists — nothing is invented. ```python from darkob import Button, Keyboard keypad = ( Keyboard() .row(Button.simple("Plain"), Button.link("Docs", "https://rubika.ir")) .row(Button.selection("Pick", title="Choose", items=[{"text": "A"}])) .row(Button.calendar("Date", min_year=2024, max_year=2030)) ) ``` | Builder | `type` sent | Notes | | --- | --- | --- | | `Button.simple(text)` | `Simple` | | | `Button.link(text, url)` | `Link` | | | `Button.selection(text, title=, items=, columns_count=, is_multi_selection=)` | `Selection` | | | `Button.calendar(text, title=, min_year=, max_year=)` | `Calendar` | Persian/Gregorian field is not named in the reference | | `Button.number_picker(text, title=, min_value=, max_value=)` | `NumberPicker` | | | `Button.string_picker(text, title=, items=)` | `StringPicker` | | | `Button.location(text, image_url=)` | `Location` | | | `Button.text_box(text)` | `Textbox` | | | `Button.ask_my_phone(text)` / `Button.ask_my_location(text)` | `AskMyPhoneNumber` / `AskMyLocation` | | | `Button.barcode(text)` | `Barcode` | | | `Button.payment(text, **fields)` | `Payment` | **Requires** extra fields; a bare one is rejected by the API | | `Button.of("CameraImage", text)` | any | Escape hatch for the remaining types | Verified against the live API: all 19 types are accepted, except a bare `Payment` button, which returns `INVALID_INPUT`. `Button.payment` therefore raises `ValueError` if you do not pass the fields it needs. ## Enums The documented enums live in `darkob.bot.models`, and the common ones are also exported from the package root: ```python from darkob import ButtonType, ChatType, FileType from darkob.bot.models import ChatKeypadType, PollStatus, EventType FileType.Voice # "Voice" ButtonType.Selection # "Selection" ``` They subclass `str`, so they serialise to the exact wire value and compare equal to plain strings. ## Putting them together ```python from darkob import Bot, Keyboard, bold bot = Bot(token="...") @bot.on_command("order") async def order(bot, event): keypad = Keyboard().row("Confirm", "Cancel") await bot.send_message( event.chat_id, f"{bold('Order #42')}\nShall I confirm?", inline_keypad=keypad, ) ``` --- # SOURCE: guides/composing-messages.md Two helpers keep message code short: a builder for the message itself, and formatting helpers for the text. ## MessageBuilder Handlers often assemble the same pieces — text, a keypad, a reply target, a silent flag. The builder keeps them in one place and emits only the options you actually set. ```python from darkob import Keyboard, MessageBuilder message = ( MessageBuilder("Order #42 confirmed") .append("Delivery tomorrow between 9 and 12") .inline(Keyboard().row("Track", "Cancel")) .silent() ) await message.send(bot, event.chat_id) ``` ### Building text ```python builder = MessageBuilder("Line one") builder.append("Line two") # newline separated builder.line() # blank line builder.line("After the gap") builder.set_text("Start over") # replace everything builder.text # the string so far len(builder) # character count ``` `append` takes any separator: ```python MessageBuilder("a").append("b", separator=" · ").text # "a · b" ``` ### Options | Method | Sets | | --- | --- | | `.keypad(kb)` | `chat_keypad` — the persistent bottom keyboard | | `.inline(kb)` | `inline_keypad` — buttons attached to the message | | `.reply_to(message_id)` | `reply_to_message_id` | | `.silent()` | `disable_notification` | | `.metadata(meta)` | Rubika text metadata | | `.option(name, value)` | Any other `send_message` keyword | | `.clear_options()` | Drops every option, keeps the text | ### Sending or inspecting ```python message.build() # {"text": ..., **options} await message.send(bot, chat_id) ``` `build()` is plain data, so it is easy to assert on in tests: ```python assert MessageBuilder("hi").silent().build() == { "text": "hi", "disable_notification": True, } ``` ## Formatting | Helper | Output | | --- | --- | | `bold("x")` | `**x**` | | `italic("x")` | `__x__` | | `strike("x")` | `~~x~~` | | `underline("x")` | `--x--` | | `spoiler("x")` | `\|\|x\|\|` | | `code("x")` | `` `x` `` | | `pre("x", "python")` | fenced block | | `link("text", url)` | `[text](url)` | | `join([...])` | skips empty fragments | ```python from darkob import bold, code, link await event.reply(f"{bold('Done')} in {code('1.2s')} — {link('logs', url)}") ``` ## Both together ```python from darkob import Keyboard, MessageBuilder, bold message = ( MessageBuilder(bold("Deployment finished")) .append("All checks passed") .inline(Keyboard().row("View logs", "Roll back")) .reply_to(event.message_id) ) await message.send(bot, event.chat_id) ``` --- # SOURCE: guides/errors.md darkob raises typed exceptions instead of returning `None` and hoping. ## Bot API exceptions Import from `darkob.bot.exceptions`. All inherit from `APIException`. | Exception | Raised when | | --- | --- | | `Network` | The request could not complete after the retry budget | | `Timeout` | The request or the server timed out | | `BadGateway` | Upstream returned HTTP 502 | | `ServerError` | Server-side failure (`SERVER_ERROR`) | | `JSONDecode` | The response body was not valid JSON | | `InvalidResponse` | Unexpected response shape | | `InvalidInput` | The request was rejected (`INVALID_INPUT`) | | `InvalidAccess` | Not authorised (`INVALID_ACCESS`) | | `TooRequests` | Rate limited (`TOO_REQUESTS`) | | `TokenError` | The bot token is malformed | ```python from darkob.bot.exceptions import TooRequests, Network try: await bot.send_message(chat_id, "hi") except TooRequests: await asyncio.sleep(5) except Network: log.warning("network down, giving up on this message") ``` ## Messenger exceptions | Exception | Raised when | | --- | --- | | `NetworkError` | Could not reach a data centre | | `RequestError` | The API rejected the request | | `ValidationError` | Bad argument passed by you | | `InvalidInput`, `InvalidAccess`, `TooRequests`, `ServerError` | API-level statuses | | `AuthError`, `SessionError`, `ApiVersionError`, `PlatformError` | Construction / login problems | | `TimeoutError`, `MaxRetriesError`, `ProxyError` | Configuration problems | | `NoConnection` | You called a method before `start()` | ## Retries `max_retries` is a **budget for one request**, not per endpoint. - Attempts rotate across known data-centre endpoints before repeating. - Backoff carries jitter, so many bots do not retry in lockstep. - HTTP `429` and a `TOO_REQUESTS` payload get a longer, escalating delay. - The endpoint that answered last is promoted for the next request. ```python bot = Bot(token="...", max_retries=3) # 3 attempts total ``` Set `max_retries=0` to fail fast in tests. ## Surviving a bad connection `SendQueue` wraps sending so a dropped connection does not lose messages: ```python from darkob import Bot, SendQueue bot = Bot(token="...") queue = SendQueue(bot, path="outbox.json") # survives a restart queue.start() # flush in the background await queue.put(event.chat_id, "report ready") ``` `put` returns `True` when the message went out immediately and `False` when it was queued. Only transient failures (network, timeout) are queued; a permanent error such as an invalid chat id is raised at once, and is dropped during a flush rather than blocking everything behind it. ## Bounding concurrency Inbound updates run as background tasks under a semaphore, so a burst cannot create unbounded work: ```python bot = Bot(token="...", max_concurrent_updates=16) ``` The default is 32. The same limit applies to the Messenger WebSocket path. ## Tracking protocol drift Rubika reshuffles its data-centre endpoints from time to time. A tracker makes that visible instead of mysterious: `python from darkob import ProtocolTracker tracker = ProtocolTracker(path="protocol.json") changes = tracker.record(client.connection, client) if changes: print("protocol changed:", changes) ` It snapshots the API and socket URLs, the endpoint codes, the platform and the app version, stores the last snapshot, and reports differences. ## Rate limiting Rubika throttles bots, and a burst of sends is the fastest way to earn a `TOO_REQUESTS`. A limiter keeps you under the ceiling before the server has to enforce it. ```python from darkob import Bot, RateLimiter bot = Bot( token="...", rate_limiter=RateLimiter(rate=20, burst=5, per_chat_rate=3), ) ``` `rate` is tokens per second, `burst` the bucket size. With `per_chat_rate`, each conversation gets its own bucket so one busy group cannot starve the rest; the buckets are capped and evicted oldest-first, so memory stays bounded. The limiter applies to every attempt, including retries. ## Circuit breaker Each data-centre endpoint has its own breaker. After 5 consecutive failures it opens, and requests stop being sent to that endpoint for 30 seconds. After the timeout it half-opens and one request is allowed through as a probe; success closes it, failure reopens it. This stops a dead endpoint from consuming the retry budget of every request. The class is darkob.CircuitBreaker, and each connection keeps one per endpoint: ```python client.connection.breaker_for("https://api.example") breaker.threshold = 10 # be more tolerant breaker.reset_timeout = 60.0 # wait longer before probing ``` If every endpoint is open, the request fails immediately with a log line instead of timing out. ## Retry policy For anything more than a count, pass a :class:`Retry` policy. It overrides `max_retries` on both the Bot and Messenger surfaces. ```python from darkob import Retry bot = Bot(token="...", retry=Retry(attempts=5, backoff=0.5)) bot = Bot(token="...", retry=Retry.none()) # fail fast bot = Bot(token="...", retry=Retry.patient()) # few, slow tries bot = Bot(token="...", retry=Retry.aggressive()) # many, quick tries ``` | Field | Meaning | | --- | --- | | `attempts` | Total attempts, including the first | | `backoff` | Base delay in seconds, growing linearly | | `jitter` | Fraction of the delay randomised (0–1) | | `max_delay` | Ceiling for any single wait | | `rate_limit_backoff` | Base delay when the server reports rate limiting | `Retry.delay(attempt)` and `Retry.should_retry(attempt)` are pure functions, so they are easy to unit test. ## What darkob does not do - It never swallows `KeyboardInterrupt` or `SystemExit` — only `Exception`. - It does not retry `4xx` responses from the Bot API; those are your bug. - It does not hide handler crashes: a failing handler is logged with a traceback and the remaining handlers still run. ## Debugging a silent bot 1. Turn on logging: ```python import logging logging.basicConfig(level=logging.DEBUG) ``` 2. Check that your filter actually matches — log inside the handler. 3. Check the bot token and chat id. 4. If nothing is delivered at all, switch to polling to rule out the webhook path. --- # SOURCE: guides/sync-and-async.md Every public method exists in both flavours. ## The rule - Called with `await` → runs on the current event loop. - Called without `await` → darkob submits the coroutine to one shared background loop and blocks until it returns. ```python me = await bot.get_me() # async me = bot.get_me() # sync, same result ``` ## How it works `darkob.hybrid` starts one daemon thread when the first sync call is made. That thread owns an asyncio loop; sync calls hand work to it with `run_coroutine_threadsafe` and wait. There is no per-call thread, and the loop is shut down at interpreter exit. ## Choosing a style | Style | Use when | | --- | --- | | `async` | You already run a loop, or you need concurrency | | `sync` | A script, a cron job, a quick prototype | Pick one per codebase. Mixing works, but sync calls inside an async handler block the loop while they wait. ## Calling sync code inside an async handler If you must, hand it to a thread so the loop keeps running: ```python import asyncio @bot.on_command("report") async def report(bot, event): await asyncio.to_thread(bot.get_chats) # careful: pre-bound args ``` Prefer rewriting the call as `await`. ## Comparing with the original library maxrubika derived sync behaviour from the same idea. darkob additionally: - uses a **bounded** executor for blocking handlers, so a burst of events cannot spawn unbounded OS threads; - rejects a sync call made from inside the worker thread itself (it would deadlock otherwise) with a clear `RuntimeError`. ## Shutting down ```python from darkob.hybrid import close_sync_loop close_sync_loop() # optional; also runs at exit ``` Long-running processes rarely need this. Tests that use the sync API should close the loop so the interpreter exits promptly. --- # SOURCE: guides/testing.md darkob's own suite runs entirely offline — no sockets, no tokens. You can do the same for your bot. ## Install the test extras ```bash pip install pytest pytest-asyncio ``` ```ini # pyproject.toml [tool.pytest.ini_options] asyncio_mode = "auto" ``` ## Test a handler without a bot Handlers are plain functions. Call them with a stand-in event: ```python from types import SimpleNamespace async def test_echo_replies(monkeypatch): replies = [] fake_event = SimpleNamespace( text="hello", chat_id="g0test", reply=lambda text: replies.append(text) or _noop(), ) await echo(bot=object(), event=fake_event) assert replies == ["hello"] ``` For `async def reply(...)` handlers, make the stub awaitable: ```python from types import SimpleNamespace class FakeEvent: def __init__(self, text, chat_id="g0test"): self.text = text self.chat_id = chat_id self.replies = [] async def reply(self, text): self.replies.append(text) ``` ## Test routers without a token ```python from darkob import Router def test_routes_are_registered(): router = Router() @router.command("start") async def start(bot, event): ... assert len(router) == 1 assert router.routes[0].kind == "on_command" ``` ## Test conversations `MemoryStorage` makes FSM tests trivial and isolated: ```python from darkob import FSMContext, MemoryStorage, StateFilter async def test_address_flow(): storage = MemoryStorage() ctx = FSMContext(storage, key="chat") await ctx.set_state("address") assert await StateFilter(storage, "address").evaluate( SimpleNamespace(chat_id="chat") ) await ctx.update_data(address="Main St") assert await ctx.get_data() == {"address": "Main St"} ``` ## Assert that nothing hits the network Guard the socket layer in a test: ```python import socket def test_import_is_offline(monkeypatch): def boom(*args, **kwargs): raise AssertionError("network access") monkeypatch.setattr(socket.socket, "connect", boom) import darkob # already imported in practice; use a subprocess for a real check ``` darkob itself checks this in a subprocess, which is the only reliable way to catch import-time I/O. ## Testing filters Filters are async predicates over an event-shaped object: ```python from types import SimpleNamespace from darkob.bot.filters import Text, IsGroup async def test_text_filter(): event = SimpleNamespace(original_data={"message": {"text": "hi there"}}) assert await Text("hi").evaluate(event) is True ``` ## Golden rules 1. Never let a test hit a real API. 2. Freeze time and randomness when asserting on retries. 3. Test the failure path as often as the happy path — that is where darkob's own bugs were found. ## `darkob.testing` Ship-ready fakes, so a handler test needs no token, no network and no hand-written stubs: ```python from darkob.testing import FakeBot, make_message async def test_echo(bot=None): bot = FakeBot() event = make_message(text="hi") await echo(bot, event) assert event.replies == ["hi"] ``` `FakeBot` records every call and returns an `{"status": "OK"}` payload: ```python await bot.send_message("chat", "hi") bot.called("send_message") # True bot.calls_to("send_message") # [(("chat", "hi"), {})] bot.last_call()[0] # "send_message" bot.reset() # forget everything ``` `FakeEvent` records what a handler does to it: ```python event = make_message(text="hello", chat_id="g0abc") await event.reply("thanks") event.replies # ["thanks"] event.edits # [] event.deleted # False ``` Both accept extra keyword attributes, so you can shape the event to match your filters: ```python event = make_message(text="hi", is_group=True) ``` --- # SOURCE: how-to/observe-in-production.md Turn on darkob's in-process metrics, read them as a dict, and expose them to Prometheus without adding a metrics server dependency. ## Turn it on ```python from darkob.metrics import enable_metrics, metrics enable_metrics() # off by default bot.run() ``` `enable_metrics()` configures and enables the shared registry and returns it. All arguments are keyword-only: | Argument | Default | Meaning | | --- | --- | --- | | `prefix` | `"darkob"` | Prefix applied to every metric name when rendering | | `histogram_capacity` | `512` | Samples kept per histogram for percentiles | | `reset` | `True` | Clear anything recorded before enabling | `disable_metrics()` turns instrumentation off again and keeps whatever was already recorded. !!! note "Import `metrics` from `darkob.metrics`" The registry instance is deliberately **not** re-exported from the package root: `from darkob import metrics` would be ambiguous with the module of the same name. Import the functions from the root, the instance from the module: ```python from darkob import enable_metrics # function from darkob.metrics import metrics # registry instance ``` ## What gets recorded for you | Metric | Kind | Recorded when | | --- | --- | --- | | `darkob.updates` | counter | An update is received | | `darkob.update.seconds` | histogram | Dispatch of one update finishes | | `darkob.handlers.skipped` | counter | A handler's filters did not match | | `darkob.handlers.called` | counter | A handler passed its filters | | `darkob.handlers.errors` | counter | A handler raised | | `darkob.api.requests` | counter | An HTTP call is issued | | `darkob.api.errors` | counter | An HTTP call failed | | `darkob.api.retries` | counter | A retry follows a failure | | `darkob.api.ratelimited` | counter | The server throttled a call | | `darkob.api.seconds` | histogram | Latency of one HTTP call | | `darkob.queue.pending` | gauge | Messages waiting in a `SendQueue` | !!! note "Where the counters fire" Both surfaces are instrumented. On `Messenger`/`Shad` the counters come from the client request loop and its dispatch path; on `Bot` they come from `Bot.request` and the polling/webhook funnel, so `darkob.api.*`, `darkob.updates` and the `darkob.handlers.*` counters all tick there too. `SendQueue` publishes `darkob.queue.pending` itself, on every enqueue, flush and drain — you do not have to poll it. This was not always true: 0.18.0 wired the `Bot` surface, which had been bypassing the instrumentation entirely because it owns a separate request path. If you are on an earlier build, set the gauge yourself: ```python metrics.set("darkob.queue.pending", queue.pending) ``` Every counter, gauge and histogram you create yourself works the same way on both surfaces. ## Read a snapshot ```python snapshot = metrics.snapshot() ``` ```python { "counters": {"darkob.api.requests": 1284}, "gauges": {}, "histograms": { "darkob.api.seconds": { "count": 1284, "sum": 23.5, "min": 0.004, "max": 2.1, "mean": 0.018, "p50": 0.012, "p95": 0.041, "p99": 0.5, } }, } ``` (Values shortened for readability.) `snapshot()` is plain JSON-safe data, so `json.dumps(metrics.snapshot())` works as-is. Percentiles come from a bounded ring buffer of the last `histogram_capacity` samples per histogram — memory stays flat however long the bot runs, and the sort only happens when you ask for a snapshot. ## Render the Prometheus text format ```python print(metrics.render_prometheus()) ``` ```text # TYPE darkob_api_requests counter darkob_api_requests 1284 # TYPE darkob_api_seconds summary darkob_api_seconds{quantile="0.5"} 0.012 darkob_api_seconds{quantile="0.95"} 0.041 darkob_api_seconds{quantile="0.99"} 0.5 darkob_api_seconds_count 1284 darkob_api_seconds_sum 23.5 ``` Dots become underscores, the configured prefix is prepended once, counters become `counter` lines, gauges `gauge` lines, and histograms become `summary` metrics with `quantile` labels plus `_count` and `_sum`. Pass `render_prometheus(prefix="mybot")` to change the prefix for one render. ## Scrape it with aiohttp darkob's webhook server is created inside `bot.run()` and is not exposed, so serve metrics on their own port: ```python title="metrics_server.py" from aiohttp import web from darkob.metrics import metrics async def scrape(request): return web.Response( text=metrics.render_prometheus(), content_type="text/plain", charset="utf-8", ) app = web.Application() app.router.add_get("/metrics", scrape) web.run_app(app, host="127.0.0.1", port=9101) ``` ```yaml title="prometheus.yml" scrape_configs: - job_name: darkob static_configs: - targets: ["127.0.0.1:9101"] ``` Bind to `127.0.0.1` and let Prometheus reach it over a private network or an authenticated proxy: metric names and label-less values are harmless, but the endpoint still leaks your traffic volume. ## Record your own numbers The same registry is public, so application metrics sit next to the built-in ones: ```python from darkob.metrics import metrics metrics.increment("orders.created") metrics.decrement("orders.queued") metrics.set("workers.busy", 3) metrics.adjust("workers.busy", -1) metrics.observe("orders.total_seconds", 0.42) with metrics.timer("orders.checkout"): await checkout() @metrics.time_it("catalog.search") async def search(query: str) -> list: ... ``` `time_it` handles sync and async callables, and uses `module.qualname` when you pass no name. !!! note "What 'off' actually costs" While the registry is disabled the library's own instrumentation costs one attribute read and a branch per hot-path call — it records nothing, which is why metrics are opt-in. Your own `metrics.increment(...)` calls are not guarded: they record whether or not you called `enable_metrics()` first. ## See also - [Health checks](health-checks.md) - [Rate-limit safely](rate-limit-safely.md) - [Reliability](../explanation/reliability.md) - [Architecture](../explanation/architecture.md) - [Errors](../guides/errors.md) --- # SOURCE: how-to/health-checks.md Expose liveness and readiness probes so a container orchestrator restarts a wedged bot and stops routing traffic to one that cannot reach Rubika. ## Liveness versus readiness A polling bot needs no health endpoint: if the process runs, it works. A bot behind a webhook, in a container, or behind a load balancer does need one, because "the process is up" and "the bot can do its job" are different facts. | Probe | Question | Failure means | | --- | --- | --- | | **liveness** | Is this process still functioning? | Restart it | | **readiness** | Should traffic be sent here? | Stop routing, keep running | Only **critical readiness** checks can make a service unready. A failing non-critical check marks the report `degraded` and still answers `200`: a missing optional dependency should not get your pod killed. ## Register checks ```python from darkob.health import HealthRegistry, queue_backlog_check, tcp_check health = HealthRegistry() # default per-check timeout: 5s health.add("api", tcp_check("messenger.rubika.ir", 443), kind="readiness") health.add("outbox", queue_backlog_check(queue, max_pending=500), kind="readiness", critical=False) health.add("loop", lambda: True, kind="liveness") ``` `add(name, check, *, kind="readiness", critical=True, timeout=None)` returns the check unchanged, so it doubles as a decorator: ```python @health.add("db") async def check_db() -> bool: return await pool.ping() ``` | Argument | Default | Meaning | | --- | --- | --- | | `name` | required | Identifier in the report | | `check` | `None` | Callable; omit it to use `add` as a decorator | | `kind` | `"readiness"` | `"readiness"` or `"liveness"` — anything else is a `ValueError` | | `critical` | `True` | Whether a failing readiness check makes the service unready | | `timeout` | `None` | Overrides the registry timeout for this check | `remove(name)`, `clear()`, `names` and `len(health)` manage the registry. ## Writing a check A check returns `True`, `False`, a string, or an awaitable of either. A **string means "unhealthy"** and is used as the detail, which is the cheapest way to say why: ```python @health.add("quota") async def quota_ok(): left = await remaining_quota() return True if left > 100 else f"only {left} requests left" ``` darkob catches whatever a check raises and reports it as a failure (`"TimeoutError: …"`), including timeouts, so one broken probe can never take the endpoint down with it. Checks run concurrently. !!! warning "Do not probe the API from a readiness check" A check that logs in or calls `getMe` spends your quota and can be throttled. Prefer a TCP connect, a queue depth, or a value your bot already tracks. ## The two ready-made checks ```python from darkob.health import queue_backlog_check, tcp_check tcp_check("messenger.rubika.ir", 443) # port=443, timeout=2.0 queue_backlog_check(queue, max_pending=1000) # accepts a SendQueue ``` `tcp_check(host, port=443, *, timeout=2.0)` opens a TCP connection and closes it immediately: enough to separate "the network is gone" from "the process is wedged", without authenticating. `queue_backlog_check(queue, max_pending=1000)` reads `queue.pending`, and falls back to `len(queue)` for any object without that attribute. A `SendQueue` that keeps growing is the earliest sign that sends are failing. Pair it with `critical=False`: a backlog should degrade, not restart. ## Read the report ```python report = await health.report() # or report("readiness") / report("liveness") report.status # "ok" | "degraded" | "down" report.ok # True when the service is usable report.live, report.ready report.http_status # 200 or 503 report.to_dict() # JSON-safe dict report.to_json() # compact JSON string ``` The body looks like this: ```json {"status": "ok", "ok": true, "live": true, "ready": true, "duration": 0.004, "checks": [{"name": "api", "healthy": true, "detail": "ok", "kind": "readiness", "duration": 0.004}]} ``` `await health.ready()` and `await health.live()` are shortcuts returning a single boolean. | Situation | `status` | `ok` | HTTP | | --- | --- | --- | --- | | Everything passes | `ok` | `True` | 200 | | A non-critical readiness check fails | `degraded` | `True` | 200 | | A critical readiness check fails | `down` | `False` | 503 | | A liveness check fails | `down` | `False` | 503 | A liveness failure also sets `live=False`; readiness only affects `ready`. ## Serve it ### aiohttp ```python title="health_server.py" from aiohttp import web from darkob.health import HealthRegistry, queue_backlog_check health = HealthRegistry() health.add("outbox", queue_backlog_check(queue, 500), critical=False) app = web.Application() app.router.add_get("/healthz", health.aiohttp_handler()) app.router.add_get("/livez", health.aiohttp_handler("/livez")) web.run_app(app, host="127.0.0.1", port=8081) ``` `aiohttp_handler(path=None)` answers with `request.path` by default, so pass the path explicitly when you mount the handler somewhere outside the standard names below. ### Any ASGI framework The registry maps paths itself: | Paths | Probe | | --- | --- | | `/health`, `/healthz`, `/health/ready`, `/ready`, `/readyz` | readiness | | `/health/live`, `/live`, `/livez`, `/health/liveness` | liveness | `health.asgi_app()` returns a self-contained ASGI application for those paths — it answers `GET` and `HEAD`, refuses other methods with `405`, and returns `404` for unknown paths. Hand it to any server that accepts an ASGI app. If your framework's router wants a request handler instead, return the report yourself — three lines that work anywhere aiohttp does: ```python from aiohttp import web async def healthz(request): report = await health.report() return web.Response( text=report.to_json(), status=report.http_status, content_type="application/json", ) ``` ## See also - [Observe in production](observe-in-production.md) - [Reliability](../explanation/reliability.md) - [Errors](../guides/errors.md) - [Architecture](../explanation/architecture.md) - [Project layout](../guides/project-layout.md) --- # SOURCE: how-to/write-a-plugin.md Package cross-cutting behaviour — filtering, rewriting, error reporting — as a `Plugin` with a lifecycle instead of another handler. ## A plugin is a class and some metadata ```python title="plugins/anti_spam.py" from darkob.plugin import Plugin, PluginMeta class AntiSpam(Plugin): meta = PluginMeta( name="anti-spam", version="1.0.0", description="Drops messages that contain blocked words.", dependencies=(), default_config={"words": ["buy crypto"]}, ) async def setup(self) -> None: self.blocked = {w.lower() for w in self.get_config("words", [])} async def on_update(self, event): text = (event.text or "").lower() if any(word in text for word in self.blocked): return True # consume: no handler sees this update return None # let dispatch continue ``` `PluginMeta` is a frozen dataclass: | Field | Default | Purpose | | --- | --- | --- | | `name` | required | Identifier, lowercased on registration | | `version` | `"1.0.0"` | Reported by `get_plugin_info` | | `description` | `""` | Human-readable summary | | `author` | `"Unknown"` | Reported by `get_plugin_info` | | `homepage` | `None` | Reported by `get_plugin_info` | | `dependencies` | `()` | Plugin names enabled before this one | | `required_permissions` | `()` | Declarative only — **not** enforced by the manager | | `default_config` | `{}` | Merged under the config you pass in | | `enabled_by_default` | `False` | Picked up by `enable_defaults()` | Without a `name`, the identifier falls back to the lowercased class name; `register_plugin(MyPlugin, name="custom")` overrides both. ## Lifecycle and configuration ```python async def setup(self) -> None: # called by enable() ... async def teardown(self) -> None: # called by disable() ... def configure(self, config: dict) -> dict: # validate/rewrite config return config self.get_config("words", []) # one value self.update_config({"words": []}) # merged over the defaults self.is_ready # True between setup and teardown ``` A plugin receives its config at construction; `set_config()` on the manager also applies to a live instance. ## The four hooks | Hook | Signature | Return value | | --- | --- | --- | | `on_update` | `(event)` | `True` consumes the update; `None`/`False` continues | | `before_request` | `(action, data)` | A dict replaces the request body; `None` keeps it | | `after_response` | `(action, data)` | A replacement payload; `None` keeps it | | `on_error` | `(error, context)` | Ignored | Every hook is a no-op in the base class, so a plugin that only implements `setup()`/`teardown()` keeps working. At dispatch, only the hooks a plugin actually **overrides** are called, in the order the plugins were enabled. ```python title="plugins/audit.py" class Audit(Plugin): meta = PluginMeta(name="audit") def __init__(self, bot, *, config=None): super().__init__(bot, config=config) self.seen = [] async def before_request(self, action, data): if action == "sendMessage": return {**data, "disable_notification": True} return None # keep the original body async def after_response(self, action, data): self.seen.append(action) return None # keep the payload async def on_error(self, error, context): print("failed:", type(error).__name__, context.get("action")) ``` !!! warning "`before_request` must return a dict" Anything else is reported to the hook-failure path and ignored, and the original body is sent, so a typo in a rewrite hook cannot silently corrupt every request — but it also means the failure is quiet unless you watch the logs. ## Register and enable ```python from plugins.anti_spam import AntiSpam bot = Bot(token="YOUR_BOT_TOKEN") identifier = bot.plugin_manager.register_plugin(AntiSpam) # "anti-spam" plugin = await bot.plugin_manager.enable(identifier) # instance ``` `Bot(...)` creates the manager for you, so registration is one call. !!! note "Where the hooks actually fire" Both surfaces call all four hooks. On `Messenger`/`Shad` they run from the client's request and dispatch loop; on `Bot` they run from `Bot.request` and from `_safe_feed`, the funnel that polling and webhook updates both pass through. This was not always true. Until 0.18.0 the `Bot` surface had its own request path and dispatch loop that never invoked a hook, so a plugin written against the client worked on the userbot and silently did nothing on a bot. `tests/test_bot_instrumentation.py` now asserts the wiring on `Bot` specifically, because asserting it on the internal helper is what let the gap survive. A plugin can consume an update and stop dispatch below it: ```python async def on_update(self, event): if is_spam(event): return True # no handler, and no ask(), will see it return None ``` `register_plugin` returns the normalised identifier and raises `PluginDefinitionError` for a class that does not subclass `Plugin`, an empty name, or a duplicate. `enable()` returns the live instance and, on the way, enables the plugin's `dependencies` first. A failure in `setup()` raises `PluginLoadError` and leaves the plugin disabled; a circular dependency raises `PluginLoadError` too. ```python bot.plugin_manager.is_registered("anti-spam") # True bot.plugin_manager.is_enabled("anti-spam") # True bot.plugin_manager.enabled_plugins # ["anti-spam"] bot.plugin_manager.get_plugin("anti-spam") # the instance await bot.plugin_manager.disable("anti-spam") # teardown, returns bool await bot.plugin_manager.disable_all() await bot.plugin_manager.reload("anti-spam") # re-executes the file ``` `disable()` refuses while another enabled plugin depends on this one, and returns `False` instead of raising. ## Failure isolation A plugin that raises inside a hook is logged and skipped; the bot keeps running. Turn that off when a plugin must fail closed — a security filter that breaks should stop traffic, not vanish: ```python from darkob.plugin import PluginManager manager = PluginManager(bot, auto_discover=False, strict_hooks=True) manager.register_plugin(AntiSpam) await manager.enable("anti-spam") ``` With `strict_hooks=True` the hook's exception propagates out of `run_on_update`, `apply_before_request`, `apply_after_response` or `run_on_error` instead of being swallowed. `PluginTester(MyPlugin, strict_hooks=True)` wires the strict manager for you, which is the easiest way to assert that a hook *does* raise. ## Test it with `PluginTester` `PluginTester` registers, enables and drives plugins against a `FakeBot` — no token, no network: ```python title="tests/test_anti_spam.py" from darkob.plugin import PluginTester from darkob.testing import make_message from plugins.anti_spam import AntiSpam async def test_blocked_word_is_consumed(): async with PluginTester(AntiSpam) as tester: assert await tester.on_update(make_message("buy crypto now")) is True assert await tester.on_update(make_message("hello")) is False ``` `PluginTester` can also drive the other three hooks — `before_request`, `after_response`, `on_error` — plus `enabled` and `active`. Pass `config={"anti-spam": {"words": ["spam"]}}` to override the meta defaults before `setup()` runs. ## Discovery `PluginManager(bot)` auto-discovers by default: it imports every `*.py` in the `plugins/` directory next to your bot, and every entry point registered under the `rubika.plugins` group. Pass `auto_discover=False` (or `plugins_dir=None`) to keep enabling explicit. ## See also - [Handlers](../guides/handlers.md) - [Errors](../guides/errors.md) - [Architecture](../explanation/architecture.md) - [Testing without a token](../tutorials/testing-without-a-token.md) - [Project layout](../guides/project-layout.md) --- # SOURCE: explanation/concurrency.md darkob runs on one event loop and owns its state without locks — which is why it is safe to share a client between tasks, and unsafe to share it between loops or threads. ## One loop owns everything Every mutable structure inside the library belongs to the event loop that is running it: | State | Where it lives | | --- | --- | | Handler dispatch index | `Api._dispatch_index` | | Endpoint latency averages | `Api._latency` | | Circuit breakers | `Api._breakers` | | Rate-limit buckets | `RateLimiter._global`, `RateLimiter._chats` | | Conversation registry | `ConversationManager._waiters` | | Metric registry | `darkob.metrics.metrics` | None of these needs a lock, because `asyncio` is cooperative: a section of code that never awaits cannot be interleaved with another task. Every mutation above is such a section — a dict read followed by a dict write, a counter increment, a deque append. Where an operation genuinely has to span an await, the code uses an `asyncio.Lock` instead of a thread lock: - `TokenBucket` locks around refill-plus-take, and sleeps *outside* the lock; - `SendQueue` locks around the whole flush so two flushes cannot interleave. These locks are `LazyLock` wrappers: the underlying `asyncio.Lock` is created on first `async with`, not at construction. That lets a `RateLimiter`, a `SendQueue` or a storage backend be built at import time, where Python 3.9 has no running loop to bind a lock to. The lock binds to the first loop that uses it, which is another way of saying the same thing as the rule below. The one thread lock in the library is `SQLiteStorage`, which guards blocking `sqlite3` calls; it is safe cross-thread precisely because it does not touch the event-loop state above. !!! warning "One client per loop, one loop per client" darkob is **not** safe to share across threads or across event loops. Awaiting one `Bot` from two `asyncio.run()` calls, or from a second thread's loop, can corrupt the dispatch index, the breakers and the buckets — the exact failures the lock-free design avoids by assuming a single loop. Create the client inside the loop that will use it and keep it there. Sharing a client between **tasks** on that loop is fine and is the intended model: a handler, a background task and a metrics scrape can all use the same object. ## The sync bridge does not change the rule Calling an async method without `await` runs it on a dedicated worker thread's loop (`darkob/hybrid.py`). That is still exactly one loop, so it is safe — as long as you do not also drive the same client from your own loop. The wrapper detects a running loop and returns the coroutine unchanged, so mixed style within one process means "pick one per client". ## `darkob.utils.concurrency` `asyncio.TaskGroup` and `asyncio.timeout` are Python 3.11 additions, and darkob supports 3.9. This module makes one style available everywhere: ```python from darkob.utils.concurrency import TaskGroup, timeout_after async with TaskGroup() as group: group.create_task(fetch(a)) group.create_task(fetch(b)) # both finished, or the first failure cancelled the other one async with timeout_after(5.0): await slow_call() ``` | Name | Meaning | | --- | --- | | `native_task_group` / `native_timeout` | `True` on 3.11+, `False` below | | `TaskGroup` | `asyncio.TaskGroup` on 3.11+, else a compatible reimplementation | | `timeout_after(seconds)` | `asyncio.timeout` on 3.11+, else a compatible reimplementation; `None` means no timeout | | `TaskGroupError` | Raised on 3.9/3.10 when one or more grouped tasks fail | | `LazyLock` | An `async with`-compatible lock created on first use, so objects can be built outside a loop | The failure type therefore differs by interpreter, and callers should not depend on it: - on 3.9/3.10 a `TaskGroupError` is raised, a plain `Exception` subclass carrying `.exceptions` (and `.errors`) as a tuple; - on 3.11+ the interpreter's native `ExceptionGroup` is raised. A failing task cancels its siblings in both cases, which is the whole point of structured concurrency — and the reason the library does not use it everywhere. ## Why handler dispatch does not use `TaskGroup` Handlers are independent. One failing handler must not cancel the others, and one slow handler must not take its siblings down with it. Structured concurrency gives the opposite guarantee: the first failure cancels the group. So: - **Bot** dispatch awaits each handler in turn, inside a `try/except` that logs the failure and keeps going (`HandlerRegistry._invoke`). - **Messenger/Shad** dispatch spawns each matching handler as a task and keeps a strong reference to it, with a done-callback that logs the exception (`Api._spawn`). One handler's exception is a log line, not a cancellation of the rest. Wrapping either in a `TaskGroup` would be a regression: a broken command in one handler would silently cancel the sibling that was still replying. The same reasoning applies to health checks. `HealthRegistry.report()` runs every probe with `asyncio.gather`, not `TaskGroup`, so that one failing probe still lets the others report — a liveness endpoint that hides six green checks because the seventh raised is worse than useless. ## Free-threaded builds (PEP 703) !!! warning "Not validated" darkob has never been run on a free-threaded interpreter. Nothing in the codebase special-cases a `--disable-gil` build. The GIL is load-bearing for the lock-free updates described above: `dict.get()` followed by `dict[key] = value`, or `counter += 1`, is atomic only while a single thread holds the GIL. On a free-threaded build those sequences can interleave, so the "no locks needed" argument stops holding. The supported configuration on such a build is unchanged: **one client, one event loop, one thread driving it.** Do not treat the absence of locks as a promise of thread safety — it is a consequence of the single-loop rule. (On CPython 3.13 and later, `sys._is_gil_enabled()` reports whether the GIL is active in the running interpreter.) ## Practical rules 1. Construct clients inside the loop that will use them. 2. Share a client across tasks; never across loops or threads. 3. Use `asyncio.create_task` for fire-and-forget work and keep a reference to the task, so it is not garbage-collected mid-flight. 4. Bound concurrency: `max_concurrent_updates` (default 32) caps updates, `RateLimiter` caps outgoing calls. 5. Prefer `timeout_after()` over hand-rolled `wait_for` when the code has to run on 3.9 as well as 3.11+. ## See also - [Architecture](architecture.md) - [Reliability](reliability.md) - [Errors](../guides/errors.md) - [Sync and async](../guides/sync-and-async.md) - [Project layout](../guides/project-layout.md) --- # SOURCE: performance.md darkob is measured against [maxrubika](https://github.com/MEH2RAB/maxrubika) on five hot paths, with each case running in a fresh process so neither library inherits the other's warm state. Both libraries run on the same machine, in the same run. | Benchmark | darkob | maxrubika | Result | | --- | --- | --- | --- | | Read `event.text` ×20,000 | 13.5 ms | 20.9 ms | **1.5× faster** | | Nested key lookup ×20,000 | 3.0 ms | 16.8 ms | **5.7× faster** | | Filter evaluation ×5,000 | 5.1 ms | 10.5 ms | **1.4× faster** | | Route 5,000 updates, 50 handlers | 160 ms | 344 ms | **2.2× faster** | | Route 5,000 updates, 500 handlers | 1.50 s | 3.33 s | **2.2× faster** | Measured on an i5-12400F, Windows 11, CPython 3.14.7, against maxrubika 1.17.0. Your absolute times will differ; the *ratio* between the columns is what should hold. Under realistic load, routing 1,000 updates against 100 registered handlers runs at about **17,500 updates/s**, and a 4 MiB download resumed from 50% costs **1.9 ms** of library overhead. ## Where the difference comes from **Lookups are indexed.** A payload builds a key index the first time anything looks into it, so `event.text` — which searches `text` and then `caption` — does not walk the structure on every read. **Dispatch is an index, not a scan.** Handlers are grouped by the update name they handle, once. Routing cost then scales with the handlers that match, not with the handlers that exist. **The per-update bookkeeping is nearly free.** `capitalize()` is memoised, and a pending `ask()` costs one integer check per update rather than an `Event` construction. ## What these numbers do not show - **No network.** Nothing here measures latency against the Rubika API. In a running bot, network time dominates every row; these figures describe CPU work per update. - **The dispatch rows time the client dispatch path**, the one both libraries expose identically, which is what keeps the comparison fair. `darkob.Bot` routes through its own handler registry — a linear scan, not an index — so its per-update cost differs and is not what those rows measure. - **The micro-benchmarks isolate one code path each.** The 5.7× nested lookup is a real measurement on a payload shape those properties actually walk, but the end-to-end gain in a bot is smaller. The dispatch rows are the ones you will notice, because routing runs on every single update. - **A benchmark bug is worse than no benchmark.** The dispatch cases used to register their handlers as `{handler: Handler() for _ in range(count)}` — a dict keyed by the function, so 500 identical entries collapsed into one key. Both "50 handlers" and "500 handlers" were measuring a single handler. With distinct handlers the gap widened from 1.5× to 2.2×, because an index only helps once there is something to index. Numbers published before 0.18.0 should be discarded. ## Reproducing it ```bash git clone https://github.com/ManiTheFerfri/darkob cd darkob python -m venv .venv .venv/Scripts/activate # .venv/bin/activate on Linux/macOS pip install -e . pip install "maxrubika==1.17.0" python benchmarks/benchmark_suite.py # head-to-head table python benchmarks/scenarios.py # absolute throughput ``` If `maxrubika` is not installed the competitor column reads `n/a`; the suite will not fabricate a comparison. ## The regression gate CI runs `python benchmarks/check_regression.py` on every push. It compares two *derived* quantities and never an absolute duration: - **Head-to-head factors** (darkob ÷ maxrubika). Machine-independent by construction, because both libraries run on the same runner. - **Calibration-normalised ratios.** Every scenario run also measures a fixed, allocation-free integer loop, and reports `case_seconds ÷ calibration`. This removes the host's raw CPU speed, which is what makes a baseline recorded in one place meaningful in another. A head-to-head factor that *drops* past tolerance is a regression; a scenario ratio that *rises* past tolerance is a regression. CI's tolerance is wider than the one a contributor gets locally, because a shared runner is noisier than a quiet machine. See the [benchmarks README](https://github.com/ManiTheFerfri/darkob/blob/main/benchmarks/README.md) for the full methodology, the recording hardware and how to add a case. ## See also - [Architecture](explanation/architecture.md) — the request pipeline these numbers measure. - [Rate limiting](how-to/rate-limit-safely.md) — staying under the API's ceiling without wasting throughput. --- # SOURCE: ai/index.md Most darkob bots are written by an AI assistant. These docs are built for that: machine-readable, deterministic, and complete. ## Feed the model context Pick the smallest input that answers your question: | Asset | Size | Use it when | | --- | --- | --- | | [`api.json`](../api.json) | ~1 MB | You need exact signatures. Structured, greppable | | [`llms.txt`](../llms.txt) | small | The model needs to know *what exists* and where | | [`llms-full.txt`](../llms-full.txt) | large | The model must answer anything; paste wholesale | | `api/bot.md`, `api/messenger.md` | medium | You are working on one surface | Every page on this site is also available as raw Markdown: replace `.html` with `.md` in any URL. That gives an assistant clean text with no navigation chrome. ## The minimum viable prompt ```text You are writing a chatbot with the Python library `darkob` (v0.2+), for the Rubika messaging platform. Rules: - Import from `darkob`: `from darkob import Bot, Router, FSMContext`. - Handlers are `async def name(bot, event)` and are registered with decorators on a Bot instance. - Filters come from `darkob.bot.filters`. - Do not invent methods. If you are unsure of a signature, say so. - async and sync both work; use `await` consistently. ``` A longer, tested version is in the [prompt pack](prompt-pack.md). ## Rules that prevent most AI mistakes Models trained on Telegram/Pyrogram confuse the two ecosystems. darkob's API is different in specific ways, so state them explicitly: 1. **`event`, not `message`.** Handlers receive `(bot, event)`. 2. **`event.chat_id`, not `event.chat.id`.** 3. **Reply with `await event.reply(text)`**, not `message.reply(...)`. 4. **Decorators are bot methods**: `@bot.on_new_message()`, never `@dp.message_handler`. 5. **Filters are classes you instantiate**: `IsGroup()`, not `IsGroup`. 6. **There is no `Dispatcher`.** A `Bot` registers and dispatches. 7. **There is no `aiogram`-style `types.Message` class.** Use the `event` object you are given. ## Validate what the model writes ```python import darkob, inspect # Does the method exist? assert hasattr(darkob.Bot, "send_message"), "hallucinated method" # Does the signature match? print(inspect.signature(darkob.Bot.send_message)) ``` Or check `api.json` mechanically: ```python import json, darkob api = json.load(open("api.json")) names = {m["name"] for m in api["classes"]["Bot"]["methods"]} for method in proposed_methods: assert method in names, f"not a real Bot method: {method}" ``` ## Generate rather than recall A workflow that reliably produces working bots: 1. Ask the model to list the handlers it plans to write, with triggers. 2. Paste `llms.txt` so it knows the real surface. 3. Ask for one handler at a time, then run it. 4. On failure, paste the traceback **and** the relevant `api/bot.md` section back into the conversation. ## What the model will get wrong without help | Symptom | Cause | Fix in your prompt | | --- | --- | --- | | `TypeError: object NoneType can't be used in 'await'` | Called a sync method with `await` inside a non-async path, or vice versa | "All documented methods are awaitable unless marked sync" | | `ModuleNotFoundError: maxrubika` | Model defaulted to the upstream package | "The package is darkob; maxrubika is deprecated" | | Handler never fires | Wrong decorator for the update type | Point it at [Handlers](../guides/handlers.md) | | Filters never match | Passing the class instead of an instance | "Filters are instantiated: `IsGroup()`" | | Bot replies to itself or loops | No guard on own messages | Add `FromUser(...)` or an ownership check | --- # COMPLETE API: every public signature ## Bot (48 methods) ### `ask(localself, chat_id: str, text: Optional[str]=None, *, filters: Optional[list]=None, timeout: float=60.0, inline_keypad: Any=None, chat_keypad: Any=None)` Send a prompt and await the next matching reply in that chat. While the prompt is pending, the first message in the chat that passes *filters* is returned to you instead of being dispatched to handlers, so a two-step flow needs no state flag:: name = await bot.ask(chat_id, "Your name?", timeout=30) Raises: darkob.NoReply: when nothing arrives within ``timeout``. ### `auto_delete_message(self: 'darkob.Bot', chat_id: str, message_id: Union[str, int], time: Union[float, int])` Automatically delete a message after a specified time. Parameters: chat_id (str): chat_id of the object associated with the message (e.g., user, group, channel). message_id (str): The ID of the message to be deleted. time (Union[float, int]): The time delay (in seconds) before deleting the message. Returns: The updated information after deleting the message. ### `ban_member(self: 'darkob.Bot', chat_id: str, sender_id: str)` Ban a member from a group or channel. Parameters: chat_id (str): chat_id of group (starts with 'g0') or channel (starts with 'c0'). sender_id (str): sender_id of member to ban (starts with 'u0'). Returns: dict: API response. ### `close(self: 'darkob.Bot')` Async close — must be awaited inside the session's loop. ### `delete(localself, event: Any)` Delete the message that produced *event*. ### `delete_message(self: 'darkob.Bot', chat_id: str, message_id: Union[int, str])` Provides a method to delete messages. Parameters: chat_id (str): chat_id of group (starts with 'g0') or channel (starts with 'c0') or user (starts with 'b0'). message_id (Union[str, int]): message_id of the message to be deleted. Returns: dict: API response with delete message information. ### `disconnect(self: 'darkob.Bot')` Close the session synchronously, from any context: - if a loop is running, schedule the close on it; - if the owning loop is running in another thread, schedule there; - otherwise, run a new/owner loop to completion. ### `download_file(self: 'darkob.Bot', file_id: str, name: str=None, path: str=None, save_as: bool=False, as_base64: bool=False, callback=None, resume: bool=True)` Downloads the file associated with the specified file ID. Parameters: file_id (str): The identifier of the file to download. name (str, optional): Custom filename (without extension). path (str, optional): Custom save path (absolute). save_as (bool, optional): If True, save to disk. If False, return bytes only. Defaults to False. as_base64 (bool, optional): If True, return as base64 encoded string. Only works when save_as=False. Defaults to False. callback (callable, optional): Progress callback function(downloaded, total, percent). Defaults to None. resume (bool, optional): When saving to disk, continue a partial file using a byte range instead of starting over. Defaults to True. Returns: If save_as = True: dict with status and file_path. If save_as = False and as_base64 = False: bytes of the file. If save_as = False and as_base64 = True: base64 encoded string. ### `edit(localself, event: Any, text: str, **kwargs: Any)` Edit the message that produced *event* to say *text*. ### `edit_chat_keypad(self: 'darkob.Bot', chat_id: str, chat_keypad: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]], resize_keyboard: bool=True, one_time_keyboard: bool=False)` Edits or adds a new chat keypad (custom keyboard) to the chat. Parameters: chat_id (str): chat_id of the group (starts with 'g0') or user (starts with 'b0'). chat_keypad (Dict[str, Any] or List): The keyboard layout to set. Supports three formats: 1. Simple list of strings: [ ["Button 1", "Button 2"], ["Button 3"] ] Each inner list is a row. Buttons are strings. The type is set to "Simple" and IDs are assigned automatically starting from 100. 2. List of tuples: (button_text, button_id, button_type) [ [("راهنما", "help")], [("تلاش مجدد", "retry"), ("بستن", "close")], [("پنل مدیریت", "panel", "Simple"), ("تنظیمات", "settings", "Simple")], [("درباره", None), ("پشتیبانی", None)], [("✅ تایید", "confirm"), ("❌ لغو", "cancel"), ("🔄 بازگشت", "back")], ] Tuple structure: (text, id, type) - text: button text - id: button ID (if None, auto-assigned starting from 100) - type: button type (if omitted, defaults to "Simple") Note: comma after text is required for single-item tuples. 3. Full dictionary (raw API format): { "rows": [ {"buttons": [{"id": "1", "button_text": "Button 1", "type": "Simple"}]}, {"buttons": [{"id": "2", "button_text": "Button 2", "type": "Simple"}]} ] } resize_keyboard (bool, optional): Requests clients to resize the keyboard vertically. Defaults to True. one_time_keyboard (bool, optional): Requests clients to hide the keyboard as soon as it's been used. Defaults to False. Returns: The API response after editing the chat keypad. Raises: InvalidInput: If 'chat_id' format is invalid, or if 'chat_keypad' is empty/None. ### `edit_inline_keypad(self: 'darkob.Bot', chat_id: str, message_id: Union[str, int], inline_keypad: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]])` Edits the inline keyboard of a specific message in a chat. Parameters: chat_id (str): chat_id of the chat containing the message. Must be a valid GUID (c0..., g0..., b0...) or a username (@username). message_id (str or int): Identifier of the message whose inline keypad should be updated. If passed as a string, it must contain only digits. inline_keypad (Dict[str, Any] or List): The new inline keyboard layout. Supports three formats: 1. Simple list of strings: [ ["Button 1", "Button 2"], ["Button 3"] ] Each inner list is a row. Buttons are strings. The type is set to "Simple" and IDs are assigned automatically starting from 100. 2. List of tuples: (button_text, button_id, button_type) [ [("راهنما", "help")], [("تلاش مجدد", "retry"), ("بستن", "close")], [("پنل مدیریت", "panel", "Simple"), ("تنظیمات", "settings", "Simple")], [("درباره", None), ("پشتیبانی", None)], [("✅ تایید", "confirm"), ("❌ لغو", "cancel"), ("🔄 بازگشت", "back")], ] Tuple structure: (text, id, type) - text: button text - id: button ID (if None, auto-assigned starting from 100) - type: button type (if omitted, defaults to "Simple") Note: comma after text is required for single-item tuples. 3. Full dictionary (raw API format): { "rows": [ {"buttons": [{"id": "1", "button_text": "Button 1", "type": "Simple"}]}, {"buttons": [{"id": "2", "button_text": "Button 2", "type": "Simple"}]} ] } Note: Passing an empty list ([]) or None removes the inline keypad from the message. Uses the ``editMessageKeypad`` endpoint. The reference page's cURL sample shows ``editInlineKeypad``, but that name returns ``INVALID_INPUT: Invalid Method`` against the live API, while ``editMessageKeypad`` answers ``OK``. The prose heading is right and the sample is stale. Returns: dict: API response with message information. Raises: InvalidInput: If 'chat_id' format is invalid, or if 'message_id' is not a digit-only string or an integer. ### `edit_message(self: 'darkob.Bot', chat_id: str, message_id: Union[str, int], text: str, metadata: Optional[Dict[str, Any]]=None, inline_keypad: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]]=None)` Edits an existing message in a chat. Parameters: chat_id (str): chat_id of the chat. message_id (Union[str, int]): The unique identifier of the message to edit. text (str): The new text of the message. metadata (dict, optional): Pre-formatted metadata (Bold, Italic, etc.). inline_keypad (dict or list, optional): Replacement inline keyboard. Accepts a Keyboard builder, a list of rows, or a raw keypad dict. Pass an empty list to remove it. Returns: dict: API response with message information. ### `forward_message(self: 'darkob.Bot', from_chat_id: str, message_id: Union[str, int], to_chat_id: str, disable_notification: bool=False)` Provides a method to forward messages. Parameters: from_chat_id (str): chat_id of the source object from which messages are forwarded. message_id (str): message_id of the message to be frowarded. to_chat_id (str): chat_id of the destination object to which messages are forwarded. disable_notification (bool): If set to True, the message will be sent silently without triggering a notification for users. Defaults to False. Returns: dict: API response with message information. ### `get_chat_info(self: 'darkob.Bot', chat_id: str)` Get information about a user, group, or channel. Parameters: chat_id (str): chat_id of group (starts with 'g0') or channel (starts with 'c0') or user (starts with 'b0'). Returns: dict: API response with chat information. ### `get_chat_member(self: 'darkob.Bot', chat_id: str, user_id: str)` Get information about a single member of a chat. Parameters: chat_id (str): chat_id of group (starts with 'g0') or channel (starts with 'c0'). user_id (str): user_id of member to look up (starts with 'u0'). Returns: dict: API response. ### `get_file(self: 'darkob.Bot', file_id: str)` Requests the file associated with the specified file ID. Parameters: file_id (str): The identifier of the file to retrieve. This should be a valid file ID within the system. ### `get_me(self: 'darkob.Bot', refresh: bool=False)` Get information about the authenticated bot. The result is cached for the lifetime of the bot, because a bot's identity does not change. Pass ``refresh=True`` to force a new request. Parameters: refresh (bool): Ignore the cache and re-fetch. Defaults to False. Returns: Information about the authenticated bot. ### `get_token_string(self: 'darkob.Bot', password: Optional[str]=None)` Export current bot token as an encrypted TokenString. Parameters: password (Optional[str]): Optional password for encryption. If provided, TokenString can only be opened with this password. Returns: str: Encrypted TokenString that can be used later with `Bot(token_string=..., password=...)`. ### `get_updates(self: 'darkob.Bot', offset_id: str=None, limit: int=100)` Fetches new updates (like messages) from the API. Parameters: offset_id (str, optional): Identifier to fetch subsequent updates. Defaults to None. limit (int, optional): Maximum number of updates to retrieve. Defaults to 100. Returns: dict: The API response including updates and the next_offset_id. ### `include_router(self, router)` Register every handler declared on *router*, recursively. Lets a bot be split into feature modules:: bot.include_router(admin_router) Returns the router so calls can be chained. ### `iter_updates(localself, limit: int=100, max_pages: Optional[int]=None)` Yield updates one at a time, handling the offset cursor. Args: limit: Updates requested per round-trip. max_pages: Stop after this many round-trips (``None`` = forever). Yields: Individual update payloads, in server order. ### `member_is_admin(self: 'darkob.Bot', chat_id: str, user_id: str)` Check whether a member is an admin or owner of the given chat. Parameters: chat_id (str): chat_id of group (g0...) or channel (c0...). user_id (str): user_id of the member (u0...). Returns: bool: True if status is 'Admin' or 'Creator', else False. ### `member_is_joined(self: 'darkob.Bot', chat_id: str, user_id: str)` Check whether a user is a member of the given chat. Parameters: chat_id (str): chat_id of group (g0...) or channel (c0...). user_id (str): user_id of the user (u0...). Returns: bool: True if the user is a member, else False. ### `member_is_owner(self: 'darkob.Bot', chat_id: str, user_id: str)` Check whether a member is the owner of the given chat. Parameters: chat_id (str): chat_id of group (g0...) or channel (c0...). user_id (str): user_id of the member (u0...). Returns: bool: True if status is 'Creator', else False. ### `register_all_endpoints(self: 'darkob.Bot', base_url: str, endpoints: Optional[List[str]]=None)` Register all webhook endpoints at once. This is a convenience method that calls ``update_bot_endpoints`` for every event type. Useful during initial setup. Parameters: base_url (str): Base URL of your server (e.g. `"https://myserver.com"`). The path `/wk` will be appended automatically. endpoints : list of str, optional Which endpoints to register. If `None`, registers all five. Returns: list_of_dict: Responses for each registration call. ### `remove_chat_keypad(self: 'darkob.Bot', chat_id: str)` Removes the custom reply keyboard from the specified chat. Parameters: chat_id (str): chat_id of the chat where the keypad should be removed. Returns: The API response after removing the chat keypad. ### `remove_commands(self: 'darkob.Bot')` Remove every custom command previously registered for this bot. The Bot API exposes this as ``setCommands`` with an empty ``bot_commands`` list, which is what this calls. Returns: The API response. ### `remove_member(self: 'darkob.Bot', chat_id: str, sender_id: str)` Remove (Ban) a member from a group or channel. Parameters: chat_id (str): chat_id of group (starts with 'g0') or channel (starts with 'c0'). sender_id (str): sender_id of member to ban. Returns: The API response. ### `reply(localself, event: Any, text: str, **kwargs: Any)` Reply to the message that produced *event*. Equivalent to ``send_message`` with ``chat_id`` and ``reply_to_message_id`` filled in from the event. ### `request(self: 'darkob.Bot', method: str, endpoint: str, **kwargs)` Send an HTTP request to the Bot API with automatic retry and error mapping. Parameters: method (str): HTTP method, e.g. "POST" or "GET" (case-insensitive). endpoint (str): API method name appended to `base_url`, e.g. "getMe". **kwargs: Extra arguments passed to `aiohttp.ClientSession.request`, such as `json=` or `data=`. Returns: Response: The parsed API response. ### `request_send_file(self: 'darkob.Bot', file_type: Literal['File', 'Image', 'Voice', 'Video', 'Music', 'Gif']='File')` Request an upload URL for sending a file to the server. Parameters: file_type (str): Type of file to upload. Options: 'File', 'Image', 'Voice', 'Video', 'Music', 'Gif'. Defaults to 'File'. Returns: str: Upload URL for the file. Examples: # Get upload URL for an image upload_url = await bot.request_send_file(file_type="Image") # Then upload file using that URL file_id = await bot.upload_file(upload_url, "photo.jpg") ### `run(self: 'darkob.Bot', poll_interval: float=0.005, webhook_url: Optional[str]=None, webhook_path: str='/wk', host: str='0.0.0.0', port: int=8080)` Start the bot. Parameters: poll_interval (float): Seconds between polls in polling mode. Defaults to 0.005 seconds. webhook_url (str, optional): Public URL for webhook mode. Defaults to None. webhook_path (str): Path for the webhook receiver. Defaults to "/wk". host (str): Bind address for the webhook server. Defaults to "0.0.0.0". port (int): Bind port for the webhook server. Defaults to 8080. ### `send_contact(self: 'darkob.Bot', chat_id: str, phone_number: str, first_name: str, last_name: str='', chat_keypad: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]]=None, inline_keypad: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]]=None, reply_to_message_id: Optional[Union[int, str]]=None, disable_notification: bool=False, resize_keyboard: bool=True, one_time_keyboard: bool=False)` Sends a contact message to a chat. Parameters: chat_id (str): chat_id for the target chat. phone_number (str): Contact's phone number. first_name (str): Contact's first name. last_name (str, optional): Contact's last name. Defaults to ' '. chat_keypad (Dict[str, Any], optional): Custom keyboard attached to the message. Defaults to None. inline_keypad (Dict[str, Any], optional): Custom inline keyboard attached to the message. Defaults to None. reply_to_message_id (Union[int, str], optional): If the message is a reply, the original message's ID. Defaults to None. disable_notification (bool, optional): Sends the message silently. Users will not receive a notification. Defaults to False. resize_keyboard (bool, optional): Requests clients to resize the keyboard vertically. Defaults to True. one_time_keyboard (bool, optional): Requests clients to hide the keyboard as soon as it's been used. Defaults to False. Returns: dict: API response with message information. ### `send_file(self: 'darkob.Bot', chat_id: str, file: Optional[Union[str, bytes]]=None, file_type: Literal['File', 'Image', 'Voice', 'Video', 'Music', 'Gif']='File', text: Optional[str]=None, file_id: Optional[str]=None, base64: Optional[str]=None, file_name: Optional[str]=None, metadata: Optional[Dict[str, Any]]=None, chat_keypad: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]]=None, inline_keypad: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]]=None, reply_to_message_id: Optional[Union[int, str]]=None, disable_notification: bool=False, resize_keyboard: bool=True, one_time_keyboard: bool=False)` Sends a file to a chat. Parameters: chat_id (str): Target chat ID. file (str | bytes, optional): Path to file, URL, or raw bytes. file_type (str): Type of file ('File', 'Image', 'Voice', 'Video', 'Music', 'Gif'). text (str, optional): Caption text. file_id (str, optional): Already uploaded file_id (skips upload). base64 (str, optional): Base64 encoded file data. file_name (str, optional): Custom file name. If not provided, auto-generated. metadata (dict, optional): Pre-formatted metadata (Bold, Italic, etc.). chat_keypad (Dict, optional): Custom keyboard attached to the message. inline_keypad (Dict, optional): Custom inline keyboard attached to the message. reply_to_message_id (Union[int, str], optional): Message ID to reply to. disable_notification (bool): Disable notification. resize_keyboard (bool): Resize keyboard vertically. one_time_keyboard (bool): Hide keyboard after use. Returns: dict: API response with message information. ### `send_gif(self: 'darkob.Bot', chat_id: str, gif: Optional[Union[str, bytes]]=None, text: Optional[str]=None, file_id: Optional[str]=None, base64: Optional[str]=None, file_name: Optional[str]=None, chat_keypad: Dict[str, Any]=None, inline_keypad: Dict[str, Any]=None, reply_to_message_id: Optional[Union[int, str]]=None, disable_notification: bool=False, resize_keyboard: bool=True, one_time_keyboard: bool=False)` Sends a gif to a chat. Parameters: chat_id (str): Target chat ID. gif (str | bytes, optional): Path to the gif file OR raw bytes. text (str, optional): Caption text. file_id (str, optional): Already uploaded file_id. base64 (str, optional): Base64 encoded gif data. file_name (str, optional): Custom file name. If not provided, auto-generated. chat_keypad (Dict, optional): Custom keyboard attached to the message. inline_keypad (Dict, optional): Custom inline keyboard attached to the message. reply_to_message_id (Union[int, str], optional): Message ID to reply to. disable_notification (bool): Disable notification. resize_keyboard (bool): Resize keyboard vertically. one_time_keyboard (bool): Hide keyboard after use. Returns: dict: API response with message information. ### `send_image(self: 'darkob.Bot', chat_id: str, image: Optional[Union[str, bytes]]=None, text: Optional[str]=None, file_id: Optional[str]=None, base64: Optional[str]=None, file_name: Optional[str]=None, chat_keypad: Dict[str, Any]=None, inline_keypad: Dict[str, Any]=None, reply_to_message_id: Optional[Union[int, str]]=None, disable_notification: bool=False, resize_keyboard: bool=True, one_time_keyboard: bool=False)` Sends an image to a chat. Parameters: chat_id (str): Target chat ID. image (str | bytes, optional): Path to the image file OR raw bytes. text (str, optional): Caption text. file_id (str, optional): Already uploaded file_id. base64 (str, optional): Base64 encoded image data. file_name (str, optional): Custom file name. If not provided, auto-generated. chat_keypad (Dict, optional): Custom keyboard attached to the message. inline_keypad (Dict, optional): Custom inline keyboard attached to the message. reply_to_message_id (Union[int, str], optional): Message ID to reply to. disable_notification (bool): Disable notification. resize_keyboard (bool): Resize keyboard vertically. one_time_keyboard (bool): Hide keyboard after use. Returns: dict: API response with message information. ### `send_location(self: 'darkob.Bot', chat_id: str, latitude: float, longitude: float, chat_keypad: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]]=None, inline_keypad: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]]=None, reply_to_message_id: Optional[Union[int, str]]=None, disable_notification: bool=False, resize_keyboard: bool=True, one_time_keyboard: bool=False)` Sends a location message to a chat. Parameters: chat_id (str): chat_id for the target chat. latitude (float): Latitude of the location. longitude (float): Longitude of the location. chat_keypad (Dict[str, Any], optional): Custom keyboard attached to the message. Defaults to None. inline_keypad (Dict[str, Any], optional): Custom inline keyboard attached to the message. Defaults to None. reply_to_message_id (Union[int, str], optional): If the message is a reply, the original message's ID. Defaults to None. disable_notification (bool, optional): Sends the message silently. Users will not receive a notification. Defaults to False. resize_keyboard (bool, optional): Requests clients to resize the keyboard vertically. Defaults to True. one_time_keyboard (bool, optional): Requests clients to hide the keyboard as soon as it's been used. Defaults to False. Returns: dict: API response with message information. ### `send_message(self: 'darkob.Bot', chat_id: str, text: str, metadata: Optional[Dict[str, Any]]=None, chat_keypad: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]]=None, inline_keypad: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]]=None, reply_to_message_id: Optional[Union[int, str]]=None, disable_notification: bool=False, resize_keyboard: bool=True, one_time_keyboard: bool=False)` Sends a text message to a chat. Parameters: chat_id (str): chat_id for the target chat. text (str): The text of the message to be sent. metadata (dict, optional): Pre-formatted metadata (Bold, Italic, etc.). chat_keypad (Dict[str, Any], optional): Custom keyboard attached to the message. inline_keypad (Dict[str, Any], optional): Custom inline keyboard attached to the message. reply_to_message_id (Union[int, str], optional): If the message is a reply, the original message's ID. disable_notification (bool, optional): Sends the message silently. resize_keyboard (bool, optional): Requests clients to resize the keyboard vertically. one_time_keyboard (bool, optional): Requests clients to hide the keyboard as soon as it's been used. Returns: MessageResult: API response with message information and action methods. ### `send_music(self: 'darkob.Bot', chat_id: str, music: Optional[Union[str, bytes]]=None, text: Optional[str]=None, file_id: Optional[str]=None, base64: Optional[str]=None, file_name: Optional[str]=None, chat_keypad: Dict[str, Any]=None, inline_keypad: Dict[str, Any]=None, reply_to_message_id: Optional[Union[int, str]]=None, disable_notification: bool=False, resize_keyboard: bool=True, one_time_keyboard: bool=False)` Sends a music to a chat. Parameters: chat_id (str): Target chat ID. music (str | bytes, optional): Path to the music file OR raw bytes. text (str, optional): Caption text. file_id (str, optional): Already uploaded file_id. base64 (str, optional): Base64 encoded music data. file_name (str, optional): Custom file name. If not provided, auto-generated. chat_keypad (Dict, optional): Custom keyboard attached to the message. inline_keypad (Dict, optional): Custom inline keyboard attached to the message. reply_to_message_id (Union[int, str], optional): Message ID to reply to. disable_notification (bool): Disable notification. resize_keyboard (bool): Resize keyboard vertically. one_time_keyboard (bool): Hide keyboard after use. Returns: dict: API response with message information. ### `send_poll(self: 'darkob.Bot', chat_id: str, question: str, options: List[str], is_anonymous: bool=True, multi_select: bool=False, chat_keypad: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]]=None, inline_keypad: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]]=None, reply_to_message_id: Optional[Union[int, str]]=None, disable_notification: bool=False, resize_keyboard: bool=True, one_time_keyboard: bool=False)` Send a poll message with the specified parameters. Parameters: chat_id (str): chat_id of the object associated with the poll (e.g., group or channel). question (str): The question for the poll. options (list): A list of string values representing the poll options. is_anonymous (bool): Whether the poll is anonymous or not. Defaults to True. multi_select (bool): Whether the poll allows multiple answers or not. Defaults to False. chat_keypad (Dict, optional): Custom keyboard attached to the message. inline_keypad (Dict, optional): Custom inline keyboard attached to the message. reply_to_message_id (Union[str, int]): The ID of the message to reply to. disable_notification (bool): If set to True, the poll will be sent silently without triggering a notification for users. Defaults to False. resize_keyboard (bool): Resize keyboard vertically. one_time_keyboard (bool): Hide keyboard after use. Returns: dict: API response with message information. ### `send_quiz(self: 'darkob.Bot', chat_id: str, question: str, options: List[str], correct_option: Union[int, str], hint: Optional[str]=None, is_anonymous: bool=True, chat_keypad: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]]=None, inline_keypad: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]]=None, reply_to_message_id: Optional[Union[int, str]]=None, disable_notification: bool=False, resize_keyboard: bool=True, one_time_keyboard: bool=False)` Send a quiz-type poll message with the specified parameters. Parameters: chat_id (str): chat_id of the object associated with the quiz (e.g., group or channel). question (str): The question for the quiz. options (list): A list of string values representing the quiz options. correct_option: Union[int, str]: The index or text of the correct option for quiz-type polls. hint (str): A hint for the correct answer in quiz-type polls. Defaults to None. is_anonymous (bool): Whether the poll is anonymous or not. Defaults to True. chat_keypad (Dict, optional): Custom keyboard attached to the message. inline_keypad (Dict, optional): Custom inline keyboard attached to the message. reply_to_message_id (Union[str, int]): The ID of the message to reply to. disable_notification (bool): If set to True, the poll will be sent silently without triggering a notification for users. Defaults to False. resize_keyboard (bool): Resize keyboard vertically. one_time_keyboard (bool): Hide keyboard after use. Returns: dict: API response with message information. ### `send_video(self: 'darkob.Bot', chat_id: str, video: Optional[Union[str, bytes]]=None, text: Optional[str]=None, file_id: Optional[str]=None, base64: Optional[str]=None, file_name: Optional[str]=None, chat_keypad: Dict[str, Any]=None, inline_keypad: Dict[str, Any]=None, reply_to_message_id: Optional[Union[int, str]]=None, disable_notification: bool=False, resize_keyboard: bool=True, one_time_keyboard: bool=False)` Sends a video to a chat. Parameters: chat_id (str): Target chat ID. video (str | bytes, optional): Path to the video file OR raw bytes. text (str, optional): Caption text. file_id (str, optional): Already uploaded file_id. base64 (str, optional): Base64 encoded video data. file_name (str, optional): Custom file name. If not provided, auto-generated. chat_keypad (Dict, optional): Custom keyboard attached to the message. inline_keypad (Dict, optional): Custom inline keyboard attached to the message. reply_to_message_id (Union[int, str], optional): Message ID to reply to. disable_notification (bool): Disable notification. resize_keyboard (bool): Resize keyboard vertically. one_time_keyboard (bool): Hide keyboard after use. Returns: dict: API response with message information. ### `send_voice(self: 'darkob.Bot', chat_id: str, voice: Optional[Union[str, bytes]]=None, text: Optional[str]=None, file_id: Optional[str]=None, base64: Optional[str]=None, file_name: Optional[str]=None, chat_keypad: Dict[str, Any]=None, inline_keypad: Dict[str, Any]=None, reply_to_message_id: Optional[Union[int, str]]=None, disable_notification: bool=False, resize_keyboard: bool=True, one_time_keyboard: bool=False)` Sends a voice to a chat. Parameters: chat_id (str): Target chat ID. voice (str | bytes, optional): Path to the voice file OR raw bytes. text (str, optional): Caption text. file_id (str, optional): Already uploaded file_id. base64 (str, optional): Base64 encoded voice data. file_name (str, optional): Custom file name. If not provided, auto-generated. chat_keypad (Dict, optional): Custom keyboard attached to the message. inline_keypad (Dict, optional): Custom inline keyboard attached to the message. reply_to_message_id (Union[int, str], optional): Message ID to reply to. disable_notification (bool): Disable notification. resize_keyboard (bool): Resize keyboard vertically. one_time_keyboard (bool): Hide keyboard after use. Returns: dict: API response with message information. ### `set_commands(self: 'darkob.Bot', commands: Optional[Union[List[Dict[str, str]], Dict[str, str]]]=None)` Sets custom commands for the bot. Pass empty list/dict to remove all commands. Parameters: commands (List[Dict[str, str]] or Dict[str, str], optional): Either a list of dictionaries with 'command' and 'description', or a simple dictionary like {"start": "Start the bot", "help": "Help"}. Example: [{"command": "start", "description": "Start the bot"}, ...] or: {"start": "Start the bot", "help": "Show help"} If None or empty, all commands will be removed. Returns: dict: API response. ### `start(self: 'darkob.Bot', poll_interval: float=0.005, webhook_url: Optional[str]=None, webhook_path: str='/wk', host: str='0.0.0.0', port: int=8080)` Starts the server or polling mechanism with specified configurations. Parameters: poll_interval: The interval (in seconds) between each polling operation. Default is 0.005 seconds. webhook_url: Optional URL for webhook integration. If provided, webhooks will be used. webhook_path: The URL path on the server to handle webhook requests. Default is "/wk". host: The hostname or IP address to bind the server. Default is "0.0.0.0" (all interfaces). port: The port number on which to run the server. Default is 8080. Returns: None ### `unban_member(self: 'darkob.Bot', chat_id: str, sender_id: str)` Unban a member from a group or channel. Parameters: chat_id (str): chat_id of group (starts with 'g0') or channel (starts with 'c0'). sender_id (str): sender_id of member to unban. Returns: dict: API response. ### `update_bot_endpoints(self: 'darkob.Bot', url: str, endpoint_type: Literal['ReceiveUpdate', 'ReceiveInlineMessage', 'ReceiveQuery', 'GetSelectionItem', 'SearchSelectionItems']='ReceiveUpdate')` Register a single webhook endpoint on the Rubika server. Parameters: url (str): Full URL that Rubika should call when an event occurs. Must be publicly reachable (HTTPS recommended). endpoint_type (str): Which kind of event this URL handles. Accepted values: - `"ReceiveUpdate"` – new messages, edits, deletions - `"ReceiveInlineMessage"` – inline-keyboard button presses - `"ReceiveQuery"` – inline-query results - `"GetSelectionItem"` – selection menu picks - `"SearchSelectionItems"` – search-in-selection requests Returns: dict: Raw response from the server confirming the registration. ### `upload_file(self: 'darkob.Bot', url: str, file: Optional[Union[str, bytes]]=None, base64: Optional[str]=None, file_name: Optional[str]=None)` Upload a file to the server and return file_id. Supports: local path, URL, raw bytes, base64. The entire file is uploaded in a single request. Parameters: url (str): Upload URL from ``request_send_file``. file (str | bytes, optional): Path, URL, or raw bytes. base64 (str, optional): Base64-encoded file data. file_name (str, optional): Name of the file. Auto-detected when possible. Returns: Optional[str]: file_id or None if failed. ## Messenger (325 methods) ### `abort_two_step_setup(self: 'darkob.Client')` Abort the two-step verification setup process. Returns: The result of the operation. ### `accept_all_join_requests(self: 'darkob.Client', chat: str, exclude: Optional[Union[str, List[str]]]=None)` Accept all pending join requests in a group or channel. Parameters: chat (str): The GUID, link, or username of the group or channel. exclude (Optional[Union[str, List[str]]]): User GUID(s) or username(s) to exclude. Returns: Result containing accepted count and details. ### `accept_join_request(self: 'darkob.Client', chat: str, user: str)` Accept a join request for a group or channel. Parameters: chat (str): The GUID, link, or username of the group/channel. user (str): The user GUID or username of the requester. Returns: The result of the API call. ### `accept_ownership_request(self: 'darkob.Client', chat: str)` Accept an ownership transfer request. Parameters: chat (str): The GUID, link, or username of the chat (channel/group). Returns: The result of the API call. ### `add_contact(self: 'darkob.Client', phone_number: Union[str, int], first_name: str, last_name: str='')` Adds a contact to the client's address book. Parameters: phone_number (str): The phone number of the contact to be added. first_name (str): The first name of the contact. last_name (str, optional): The last name of the contact. Defaults to an empty string. Returns: The result of the API call. Note: The `phone_number` parameter should be a valid phone number. The `first_name` and `last_name` parameters represent the name of the contact. If the contact has no last name, `last_name` can be an empty string. ### `add_folder(self: 'darkob.Client', name: str, include_chats: Optional[Union[str, List[str]]]=None, exclude_chats: Optional[Union[str, List[str]]]=None, include_chat_types: Optional[List[str]]=None, exclude_chat_types: Optional[List[str]]=None, is_add_to_top: bool=True, suggestion_folder_id: str=None, folder_id: str=None)` Add a new folder to organize chats. Parameters: name (str): Folder name. include_chats: Chats (GUIDs, links, usernames) to include in folder. exclude_chats: Chats (GUIDs, links, usernames) to exclude from folder. include_chat_types: Chat types to include (case-insensitive). Valid values: 'Contacts', 'NonContacts' / 'Users', 'Groups', 'Channels', 'Bots', 'Services'. Note: 'Users' expands to both 'Contacts' and 'NonContacts'. exclude_chat_types: Chat types to exclude (case-insensitive). Valid values: 'Mute', 'Read', 'Archive'. is_add_to_top (bool): Add folder to top of list. suggestion_folder_id (str): Suggestion folder ID. folder_id (str): Folder ID. Returns: The result of the API call. ### `add_handler(self: 'darkob.Client', func: Callable, handler: Union[ChatUpdates, MessageUpdates, ShowActivities, ShowNotifications, RemoveNotifications])` _No docstring._ ### `add_live_comment(self: 'darkob.Client', access_token: str, live_id: str, comment: str)` Adds a comment to a live stream. Parameters: access_token (str): The access token for authentication. live_id (str): The ID of the live stream. comment (str): The text of the comment. Returns: The result of the API call. ### `add_members(self: 'darkob.Client', chat: str, members: Union[str, List[str]])` Add members to a channel or group. Parameters: chat (str): The GUID, link, or username of the channel/group. members (Union[str, List[str]]): The GUID(s) or username(s) of the member(s) to be added. Returns: The result of the API call. ### `add_reaction(self: 'darkob.Client', chat: str, message_id: Union[str, int], reaction_id: Union[int, str])` Add a reaction to a specific message. Parameters: chat (str): The GUID, link, or username of the chat associated with the message. message_id (Union[str, int]): The ID of the message to which the reaction will be added. reaction_id (Union[str, int]): The ID of the reaction to be added. Returns: The result of the API call. ### `add_saved_music_playlist(self: 'darkob.Client', files: Union[Path, str, List[Union[Path, str]]]=None, file_inlines: List[dict]=None, time: Optional[int]=None, performer: Optional[str]=None, file_name: Optional[str]=None, **kwargs)` Add a saved music playlist on your profile. Parameters: files: A single file path or a list of file paths to music files. file_inlines: Pre-uploaded file_inline dicts to add directly. time: Custom duration in seconds. If not provided, auto-detected. performer: Custom performer name. If not provided, auto-detected. file_name: Custom file name. If not provided, uses original file name. Returns: The result of the API call. ### `add_saved_music_track(self: 'darkob.Client', track: Union[Path, str]=None, file_inline: dict=None, time: Optional[int]=None, performer: Optional[str]=None, file_name: Optional[str]=None, **kwargs)` Add a single music track to your saved music playlist. Parameters: track: A file path (str or Path) to a music file, or raw bytes. file_inline: A pre-uploaded file_inline dict to add directly. time: Custom duration in seconds. If not provided, auto-detected. performer: Custom performer name. If not provided, auto-detected. file_name: Custom file name. If not provided, uses original file name. Returns: The result of the API call. ### `add_sticker_set(self: 'darkob.Client', sticker_set_id: str)` Add a sticker set. Parameters: sticker_set_id (str): The ID of the sticker set. Returns: The result of the API call. ### `add_to_my_gif_set(self: 'darkob.Client', chat: str, message_id: Union[str, int])` Adds a GIF message to the user's personal GIF set. Parameters: chat (str): The GUID, link, or username of the chat. message_id (Union[str, int]): The ID of the GIF message. Returns: The result of the API call. ### `archive_chat(self: 'darkob.Client', chat: str)` Archive a chat. Parameters: chat (str): The GUID, link, or username of the chat to archive. Returns: The result of the API call. ### `archive_sticker_set(self: 'darkob.Client', sticker_set_id: str)` Archive a sticker set. Parameters: sticker_set_id (str): The ID of the sticker set. Returns: The result of the API call. ### `ask(self, chat_id: str, text: Optional[str]=None, *, filters: Optional[list]=None, timeout: float=60.0, inline_keypad: Any=None, chat_keypad: Any=None)` Send a prompt and await the next matching reply in that chat. The reply is returned to you instead of being dispatched to handlers while the prompt is pending. ### `auto_delete_account(self: 'darkob.Client', setting: Union[int, str])` Set account auto-deletion after months of inactivity. Parameters: setting (Union[int, str]): Months of inactivity. Accepts: 3, 6, 12, or 24. Can be int (3, 6, 12, 24) or str ("3", "6", "12", "24", "3m", "6m", "12m", "24m") Returns: The updated privacy settings. Examples: >>> await client.auto_delete_account(6) # doctest: +SKIP >>> await client.auto_delete_account("12m") # doctest: +SKIP ### `auto_delete_message(self: 'darkob.Client', chat: str, message_id: Union[str, int], time: Union[float, int])` Automatically delete a message after a specified time. Parameters: chat (str): The GUID, link, or username of the chat associated with the message (e.g., user, group, channel). message_id (Union[str, int]): The ID of the message to be deleted. time (Union[float, int]): The time delay (in seconds) before deleting the message. Returns: The updated information after deleting the message. ### `ban_member(self: 'darkob.Client', chat: str, member: str)` Ban a member from a group or channel. Parameters: chat (str): The GUID, link, or username of group/channel. member (str): The GUID or username of member to ban. Returns: Result of the operation. ### `ban_members(self: 'darkob.Client', chat: str, members: List[str])` Ban multiple members from a group or channel. Parameters: chat (str): The GUID, link, or username of group/channel. members (List[str]): List of GUIDs or usernames of members to ban. Returns: Results of all operations. ### `block_user(self: 'darkob.Client', user: str)` Block a user. Parameters: user (str): The GUID or username of the user to block. Returns: The result of the block operation. ### `cancel_change_owner(self: 'darkob.Client', chat: str)` Cancels a pending ownership transfer request for a channel or group. Parameters: chat (str): The GUID, link, or username of the chat (channel/group). Returns: The result of the API call. ### `change_owner(self: 'darkob.Client', chat: str, new_owner: str)` Request to transfer ownership of a chat to another user. Parameters: chat (str): The GUID, link, or username of the chat (channel/group). new_owner (str): The GUID or username of the user to become new owner. Returns: The result of the API call. Note: - Only works if you are the current owner - New owner must accept the request - Irreversible action ### `change_password(self: 'darkob.Client', password: str, new_password: str, new_hint: str)` Changes the user's password. Parameters: password (str): The current password. new_password (str): The new password. new_hint (str): The new password hint. Returns: The result of the API call. ### `check_channel_username(self: 'darkob.Client', username: str)` Check the availability of a username for a channel. Parameters: username (str): The username to check. Returns: The result of the API call. ### `check_join(self: 'darkob.Client', chat: str, member: str)` Check if a user or bot is a member of a specific group or channel. Parameters: chat (str): The GUID, link, or username of the chat to check. member (str): The GUID or username of the user/bot to check. Returns: bool: True if user/bot is a member, False otherwise. ### `check_two_step_passcode(self: 'darkob.Client', password: str)` Check if the provided two-step verification password is correct. Parameters: password (str): The two-step verification password to check. Returns: Result containing status and user data if successful. ### `check_user_username(self: 'darkob.Client', username: str)` Check the availability of a username for a user. Parameters: username (str): The username to be checked. Returns: The result of the username availability check. ### `clear_all_drafts(self: 'darkob.Client')` Clear all drafts. Returns: The result of the API call. ### `clear_black_list(self: 'darkob.Client', chat: str, exclude: Optional[Union[str, List[str]]]=None)` Clear black list with unban all banned members in a group or channel. Parameters: chat (str): The GUID, link, or username of the group or channel. exclude (Optional[Union[str, List[str]]]): Member GUID(s) or username(s) to exclude from unban. Default is None. Returns: Result of unban operation. ### `clear_chat_draft(self: 'darkob.Client', chat: str)` Clear the draft of a specific chat. Parameters: chat (str): The GUID, link, or username of the chat. Returns: The result of the API call. ### `click_chat_ads(self: 'darkob.Client', chat_ads_id: str)` Register a click action on a chat ad. The `chat_ads_id` is obtained from the `get_chat_ads` method. Parameters: chat_ads_id (str): The chat ads ID to register a click on. Returns: The result of the operation. ### `click_inline_button(self: 'darkob.Client', chat: str, message_id: Union[str, int], button_id: str)` Send API call response to a chat's inline keypad button. Parameters: chat (str): The GUID, link, or username of the chat. message_id (Union[str, int]): The ID of the message containing inline keyboard. button_id (str): The ID of the button. Returns: The result of the API call. ### `click_keypad_button(self: 'darkob.Client', chat: str, button_id: str)` Click a button in the chat keypad. Parameters: chat (str): The GUID, link, or username of the chat (must be a bot). button_id (str): The button ID to click. Returns: The result of the button click. ### `click_message_url(self: 'darkob.Client', chat: str, message_id: typing.Union[str, int], link_url: str)` Simulate clicking a URL contained within a specific message. Parameters: chat (str): The GUID, link or username of the chat. message_id (Union[str, int]): The unique ID of the message that includes the URL. link_url(str): The URL string embedded in the message to be clicked. Returns: The result of the API call. ### `close(self: 'darkob.Client')` Close the connection to the Darkob server (async version). ### `confirm_unconfirmed_session(self: 'darkob.Client', unconfirmed_session_key: str)` Confirm an unconfirmed (pending) session. Parameters: unconfirmed_session_key (str): The session key to confirm. Returns: The result of the API call. ### `connect(self: 'darkob.Client')` Establish a connection to the Rubika API. Creates an Api instance and loads stored session information (auth, guid, private_key, user_agent) if available. Returns: Client instance with active connection. ### `create_channel(self: 'darkob.Client', title: str, members: Optional[Union[str, list]]=None, channel_type: str='Public', description: Optional[str]=None, avatar: Optional[Union[Path, str, bytes]]=None, thumbnail_avatar: Optional[Union[Path, str, bytes]]=None, *args, **kwargs)` Create a new channel. Parameters: title (str): The title of the new channel. members (Union[str, list], optional): The GUID(s) or username(s) of the member(s) to be added to the new channel. Default is None. channel_type (str): Set type of the channel. 'Public' or 'Private'. Default is 'Public'. description (str, optional): The description of the new channel. Default is None. avatar (Optional[Union[Path, str, bytes]]): The image to be used as the channel avatar. Default is None. thumbnail_avatar (Optional[Union[Path, str, bytes]]): The image to be used as the channel thumbnail avatar. Default is None. Returns: The result of the API call. Note: If only `avatar` is provided, the thumbnail is taken from the same image. If none of them are provided, no avatar is set for the channel. ### `create_group(self: 'darkob.Client', title: str, members: Union[str, List[str]], description: Optional[str]=None, avatar: Optional[Union[Path, str, bytes]]=None, thumbnail_avatar: Optional[Union[Path, str, bytes]]=None, *args, **kwargs)` Create a new group. Parameters: title (str): The title of the group. members (Union[str, List[str]]): A single member GUID/Username or a list of member GUIDs/Usernames to be added to the group. description (Optional[str]): Description of the group (optional). Defaults to None. avatar (Optional[Union[Path, str, bytes]]): The image to be used as the group avatar. Default is None. thumbnail_avatar (Optional[Union[Path, str, bytes]]): The image to be used as the group thumbnail avatar. Default is None. Returns: The result of the API call. Note: If only `avatar` is provided, the thumbnail is taken from the same image. If none of them are provided, no avatar is set for the group. ### `create_join_link(self: 'darkob.Client', chat: str, expire_time: Optional[int]=None, request_needed: bool=False, title: Optional[str]=None, usage_limit: int=0)` Creates an invite link for a group or channel. Parameters: chat (str): The GUID, link, or username of the target group or channel. expire_time (Optional[int]): The expiration time of the link in seconds. request_needed (bool): Whether join requests must be approved manually. title (Optional[str]): A custom title for the invite link. usage_limit (int): The maximum number of times the link can be used. Returns: The API response containing the created invite link. ### `delete_account(self: 'darkob.Client')` Request to permanently delete your Rubika account. Returns: str: User-friendly confirmation message. ### `delete_all_avatars(self: 'darkob.Client', chat: str)` Delete all avatars from a chat or user profile. Parameters: chat (str): The GUID, link, or username of the chat. Returns: Data: Result of the operation. Note: If `chat` is 'me', 'cloud', 'self', or 'myself', it will be replaced with the client's GUID. ### `delete_all_messages(self: 'darkob.Client', chat: str, exclude_message_ids: Optional[Union[str, int, List[Union[str, int]]]]=None)` Delete all messages in a chat except the first creation event message and optionally specified message IDs. This method retrieves all messages from the chat and deletes them, while preserving: - Any message IDs specified in `exclude_message_ids`. Parameters: chat (str): The GUID, link, or username of the chat exclude_message_ids (Union[str, int, List[Union[str, int]]], optional): Message ID(s) to preserve (not delete). Can be string, integer, or list. Default is None. Returns: Result of the deletion operation. ### `delete_all_my_gif_set(self: 'darkob.Client')` Delete all GIFs from the user's personal GIF set. Returns: Data: A Data object containing the deletion result. ### `delete_avatar(self: 'darkob.Client', chat: str, avatar_id: str)` Delete an avatar. Parameters: chat (str): The GUID, link, or username of the chat that owns the avatar. avatar_id (str): The identifier of the avatar to be deleted. Returns: The result of the API call. Note: If `chat` is 'me', 'cloud', 'self', or 'myself', it will be replaced with the client's GUID. ### `delete_bot_chat(self: 'darkob.Client', bot: str)` Delete a bot chat. Parameters: bot (str): The GUID or username of the bot. Returns: The result of the API call. ### `delete_channel(self: 'darkob.Client', channel: str, confirm: bool=True)` Delete a channel. Parameters: channel (str): The GUID, link, or username of the channel. confirm (bool): If True, ask the user for confirmation before deleting the channel. If False, delete immediately. Default is True. Returns: The result of the API call. Exits if cancelled. ### `delete_chat_history(self: 'darkob.Client', chat: str)` Delete chat history up to the last message. Parameters: chat (str): The GUID, link, or username of the chat (e.g., user, group). Returns: The result of the API call. ### `delete_contact(self: 'darkob.Client', user: str)` Deletes a contact from the client's address book. Parameters: user (str): The GUID or username of the contact to be deleted. Returns: The result of the contact deletion operation. Note: - The `user` parameter should be the GUID or username of the contact to be deleted. ### `delete_folder(self: 'darkob.Client', folder_id: str)` Delete a folder. Parameters: folder_id (str): The ID of the folder to be deleted. Returns: Result of the delete folder operation. ### `delete_group(self: 'darkob.Client', group: str, confirm: bool=True)` Delete a group. Parameters: group (str): The GUID or link of the group. confirm (bool): If True, ask the user for confirmation before deleting the group. If False, delete immediately. Default is True. Returns: The result of the API call. Exits if cancelled. ### `delete_messages(self: 'darkob.Client', chat: str, message_ids: Union[str, int, list], type: Literal['Local', 'Global', 'Scheduled']='Global')` Delete specified messages associated with the given chat. Parameters: chat (str): The GUID, link, or username of the chat associated with the messages (e.g., user, group, channel). message_ids (Union[str, int, list]): The ID or list of IDs of the messages to be deleted. type (str): The type of deletion, can be 'Global', 'Local', or 'Scheduled'. Default is 'Global'. Returns: The updated information after deleting the messages. ### `delete_my_gif_set(self: 'darkob.Client', file_id: str)` Deletes a GIF from the user's personal GIF set. Parameters: file_id (str): The file ID of the GIF to be removed. Returns: The result of the API call. ### `delete_my_messages(self: 'darkob.Client', chat: str, exclude_message_ids: Optional[Union[str, int, List[Union[str, int]]]]=None)` Delete all messages sent by the authenticated user in a chat. Parameters: chat (str): The GUID, link, or username of the chat. exclude_message_ids (Optional[Union[str, int, List[Union[str, int]]]]): Message ID(s) to exclude from deletion (preserve them). Default is None. Returns: Result of the deletion operation. ### `delete_saved_music_playlist(self: 'darkob.Client', position: int=None)` Delete tracks from the saved music playlist on your profile. Parameters: position (int, optional): The position of the track to delete. If None, deletes all. Returns: The result of the API call. ### `delete_service_chat(self: 'darkob.Client', service: str)` Delete a service chat. Parameters: service (str): The GUID of the service chat to delete. Returns: The result of the API call. ### `delete_sticker_set(self: 'darkob.Client', sticker_set_id: str)` Delete a sticker set. Parameters: sticker_set_id (str): The ID of the sticker set. Returns: The result of the API call. ### `delete_user_chat(self: 'darkob.Client', user: str)` Delete a user chat. Parameters: user (str): The GUID or username of the user whose chat is to be deleted. Returns: The result of the user chat deletion. ### `deny_unconfirmed_session(self: 'darkob.Client', unconfirmed_session_key: str)` Deny an unconfirmed (pending) session. Parameters: unconfirmed_session_key (str): The session key to deny. Returns: The result of the API call. ### `discard_call(self: 'darkob.Client', call_id: str, duration: int=0, reason: str='Disconnect')` Discard/end an active call. Parameters: call_id (str): ID of the call to discard duration (int): Call duration in seconds reason (str): Reason for ending the call. Common options: 'Missed' and 'Disconnect'. Default: 'Disconnect' Returns: Result of the discard operation. ### `discard_voice_chat(self: 'darkob.Client', chat: str)` Discard/End a voice chat for a channel or group. Parameters: chat (str): The GUID, link, or username of the channel or group. Returns: The result of the API call. ### `disconnect(self: 'darkob.Client')` Disconnect from the Darkob server (sync version). ### `dont_show_chat_ads(self: 'darkob.Client', chat_ads_id: str)` Register a 'don't show' action on a chat ad. The `chat_ads_id` is obtained from the `get_chat_ads` method. Parameters: chat_ads_id (str): The chat ads ID to hide. Returns: The result of the operation. ### `download_file(self: 'darkob.Client', file_inline: Optional[Union[dict, Data]]=None, dc_id: Optional[int]=None, file_id: Optional[int]=None, access_hash: Optional[str]=None, size: Optional[int]=None, chunk: int=131072, callback: Optional[Callable[[int, int], Union[None, asyncio.Future]]]=None, gather: bool=False, save_as: Optional[Union[str, bool]]=None, file_name: Optional[str]=None, as_base64: bool=False, *args, **kwargs)` Download a file from Rubika/Shad. Parameters: file_inline (dict or Data, optional): File inline object from messages. If provided, dc_id, file_id, access_hash, size will be extracted. dc_id (int, optional): Data center ID (if file_inline not provided). file_id (int, optional): Unique identifier of the file. access_hash (str, optional): Access hash associated with the file. size (int, optional): Total size of the file in bytes. chunk (int, optional): Size of each download chunk (default: 131072). callback (callable, optional): Progress callback(total_size, downloaded_size). gather (bool, optional): Download chunks in parallel (default: False). save_as (str or bool, optional): Directory path or True for current dir. If None, returns bytes. file_name (str, optional): Custom file name. as_base64 (bool, optional): Return as base64 encoded string (default: False). Returns: bytes, str, or Data: File content (bytes), base64 string, or Data object (when save_as used). ### `download_profile_picture(self: 'darkob.Client', chat: Optional[str]=None, file_id: Optional[str]=None, access_hash_rec: Optional[str]=None, dc_id: Optional[str]=None, save_as: Optional[Union[str, bool]]=None, save_all: bool=False)` Download the profile picture of a user, group, or channel. Parameters: chat (str, optional): The GUID, link, or username of the user, group, channel, or other chats. file_id (str, optional): Direct file_id for download without fetching avatars. access_hash_rec (str, optional): Direct access_hash_rec for download without fetching avatars. dc_id (str, optional): DC ID required when using file_id and access_hash_rec directly. save_as (str or bool, optional): Directory path to save the file(s). If True, saves in current directory. If None, returns bytes only. save_all (bool): If True, downloads all avatars instead of just the latest. Returns list of bytes if save_as is None. Returns: bytes, List[bytes]: Binary data or saved file paths. ### `edit_can_called_by(self: 'darkob.Client', setting: str, exceptions: Optional[Dict[str, List[str]]]=None)` Edits the setting to control who can call you. Parameters: setting (str): 'Everybody', 'MyContacts' or 'Nobody' exceptions (Optional[Dict[str, List[str]]]): - 'include_users': List[str] - Users to always allow - 'exclude_users': List[str] - Users to always deny To clear exceptions, pass {'exclude_users': []} Returns: The updated privacy settings after the change. ### `edit_can_join_chat_by(self: 'darkob.Client', setting: str, exceptions: Optional[Dict[str, List[str]]]=None)` Edits the setting to control who can join your chats by link. Parameters: setting (str): 'Everybody', 'MyContacts' or 'Nobody' exceptions (Optional[Dict[str, List[str]]]): - 'include_users': List[str] - Users to always allow - 'exclude_users': List[str] - Users to always deny To clear exceptions, pass {'exclude_users': []} Returns: The updated privacy settings after the change. ### `edit_channel_info(self: 'darkob.Client', channel: str, title: Optional[str]=None, description: Optional[str]=None, username: Optional[str]=None, channel_type: Literal['Public', 'Private']=None, sign_messages: Optional[bool]=None, is_restricted_content: Optional[bool]=None, reactions: Optional[Union[Literal['All', 'Disable'], List[int]]]=None)` Edit information of a channel. Parameters: channel (str): The GUID, link, or username of the channel. title (str, optional): The new title of the channel. Max 60 characters. description (str, optional): The new description of the channel. Max 300 characters. username (str, optional): The new username of the channel. Max 32 characters. channel_type (str, optional): The new type of the channel. 'Public' or 'Private'. sign_messages (bool, optional): Whether to sign messages in the channel. is_restricted_content (bool, optional): Restrict content (prevent screenshots and file saving). reactions (Union[Literal['All', 'Disable'], List[int]], optional): - 'All': Enable all reactions - 'Disable': Disable all reactions - List[int]: List of reaction IDs to enable (e.g., [1, 2, 6, 7, 8, 23, 44]) Returns: The result of the API call. ### `edit_channel_title(self: 'darkob.Client', channel: str, title: str)` Edit title of a channel. Parameters: channel (str): The GUID, link, or username of the channel. title (str): The new title of the channel. Returns: The result of the API call. ### `edit_group_info(self: 'darkob.Client', group: str, title: Optional[str]=None, description: Optional[str]=None, slow_mode: Optional[str]=None, event_messages: Optional[bool]=None, is_restricted_content: Optional[bool]=None, reactions: Optional[Union[Literal['All', 'Disable'], List[int]]]=None, chat_history_for_new_members: Optional[str]=None, restricted_period: Optional[List[Dict[str, Union[List[str], str]]]]=None)` Edit the information of a group. Parameters: group (str): The GUID or link of the group. title (Optional[str]): The new title for the group (max 60 characters). description (Optional[str]): The new description for the group (max 300 characters). slow_mode (Optional[str]): The new slow mode setting for the group. event_messages (Optional[bool]): Enable or disable event messages for the group. is_restricted_content (Optional[bool]): Restrict content (prevent screenshots and file saving). reactions (Union[Literal['All', 'Disable'], List[int]], optional): - 'All': Enable all reactions - 'Disable': Disable all reactions - List[int]: List of reaction IDs to enable (e.g., [1, 2, 6, 7, 8, 23, 44]) chat_history_for_new_members (Optional[str]): The new chat history setting for new members. restricted_period (Optional[List[Dict[str, Union[List[str], str]]]]): Time restrictions for sending messages (list of periods). Each period should contain: - days_of_week: List of days ['Saturday', 'Sunday', ..., 'Friday'] - from_time: Start time in "HH:MM" format (24-hour) - to_time: End time in "HH:MM" format (24-hour) Note: Can accept multiple periods as a list of dictionaries. Returns: The result of the API call. Examples: # Enable all reactions await client.edit_group_info( group="g0...", reactions="All" ) # Disable all reactions await client.edit_group_info( group="g0...", reactions="Disable" ) # Enable specific reactions await client.edit_group_info( group="g0...", reactions=[1, 2, 6, 7, 8, 23, 44] ) # Single restricted period await client.edit_group_info( group="g0...", restricted_period=[{ "days_of_week": ["Saturday", "Sunday"], "from_time": "00:00", "to_time": "06:00" }] ) # Multiple restricted periods await client.edit_group_info( group="g0...", restricted_period=[ { "days_of_week": ["Saturday", "Sunday", "Monday"], "from_time": "01:13", "to_time": "08:16" }, { "days_of_week": ["Tuesday", "Wednesday"], "from_time": "22:00", "to_time": "04:00" # Can cross midnight } ] ) ### `edit_group_timer(self: 'darkob.Client', group: str, timer: typing.Union[str, int])` Parameters: group (str): The GUID or link of the group. timer (Union[str, int]): The new slow mode setting for the group. Returns: The result of the API call. ### `edit_group_title(self: 'darkob.Client', group: str, title: str)` Edit title of a group. Parameters: group (str): The GUID or link of the group. title (str): The new title of the group. Returns: The result of the API call. ### `edit_join_link(self: 'darkob.Client', chat: str, join_link: str, title: Optional[str]=None, expire_time: Optional[int]=None, request_needed: Optional[bool]=None, usage_limit: Optional[int]=None)` Edit an existing invite link for a group or channel. Parameters: chat (str): The GUID, link, or username of the target group or channel. join_link (str): The join link to edit. expire_time (Optional[int]): The new expiration time of the link in seconds. request_needed (Optional[bool]): Whether join requests must be approved manually. title (Optional[str]): A new custom title for the invite link. usage_limit (Optional[int]): The new maximum number of times the link can be used. Returns: The API response containing the edited invite link. ### `edit_message(self: 'darkob.Client', chat: str, message_id: Union[int, str], text: str, metadata: Optional[dict]=None)` Edit the specified message associated with the given chat. Parameters: chat (str): The GUID, link, or username of the chat associated with the message (e.g., user, group, channel). message_id (Union[int, str]): The ID of the message to be edited. text (str): The new text content for the message. metadata (dict, optional): Pre-formatted metadata (Bold, Italic, etc.). Returns: The updated information after editing the message. ### `edit_show_birthday(self: 'darkob.Client', setting: str, exceptions: Optional[Dict[str, List[str]]]=None)` Edits the setting to show or hide the user's birthday. Parameters: setting (str): 'Everybody', 'MyContacts' or 'Nobody' exceptions (Optional[Dict[str, List[str]]]): - 'include_users': List[str] - Users to always allow - 'exclude_users': List[str] - Users to always deny To clear exceptions, pass {'exclude_users': []} Returns: The updated privacy settings after the change. ### `edit_show_last_online(self: 'darkob.Client', setting: str, exceptions: Optional[Dict[str, List[str]]]=None)` Edits the setting to control who can see the user's last online status. Parameters: setting (str): 'Everybody', 'MyContacts' or 'Nobody' exceptions (Optional[Dict[str, List[str]]]): - 'include_users': List[str] - Users to always allow - 'exclude_users': List[str] - Users to always deny To clear exceptions, pass {'exclude_users': []} Returns: The updated privacy settings after the change. ### `edit_show_phone_number(self: 'darkob.Client', setting: str, exceptions: Optional[Dict[str, List[str]]]=None)` Edits the setting to control who can see the user's phone number. Parameters: setting (str): 'Everybody', 'MyContacts' or 'Nobody' exceptions (Optional[Dict[str, List[str]]]): - 'include_users': List[str] - Users to always allow - 'exclude_users': List[str] - Users to always deny To clear exceptions, pass {'exclude_users': []} Returns: The updated privacy settings after the change. ### `edit_show_profile_photo(self: 'darkob.Client', setting: str, exceptions: Optional[Dict[str, List[str]]]=None)` Edits the setting to control who can see the user's profile photo. Parameters: setting (str): 'Everybody', 'MyContacts' or 'Nobody' exceptions (Optional[Dict[str, List[str]]]): - 'include_users': List[str] - Users to always allow - 'exclude_users': List[str] - Users to always deny To clear exceptions, pass {'exclude_users': []} Returns: The updated privacy settings after the change. ### `edit_slow_mode(self: 'darkob.Client', group: str, slow_mode: typing.Union[str, int])` Parameters: group (str): The GUID or link of the group. slow_mode (Union[str, int]): The new slow mode setting for the group. Returns: The result of the API call. ### `feedback_voice_transcription(self: 'darkob.Client', chat: Union[str, int], message_id: Union[str, int], feedback_type: str, feedback_text: str=None)` Send feedback for a voice transcription. Parameters: chat (str): The GUID, link, or username of the chat. message_id (Union[str, int]): The ID of the voice message. feedback_type (str): 'OK' or 'Incorrect'. feedback_text (str, optional): Feedback text. If not provided, uses the transcription text. Returns: The result of the API call. ### `forward_messages(self: 'darkob.Client', from_chat: str, message_ids: Union[str, int, list], to_chat: str, hide_author: bool=False, is_mute: bool=False, schedule_time: Optional[Union[int, float, timedelta, datetime]]=None, schedule_type: Optional[Literal['Default', 'WhenOnline']]=None)` Forward specified messages from one chat to another. Parameters: from_chat (str): The GUID, link, or username of the source chat. message_ids (Union[str, int, list]): The IDs of the messages to forward. to_chat (str): The GUID, link, or username of the destination chat. hide_author (bool): Hide the original sender's identity. Default is False. is_mute (bool): Forward silently without notification. Default is False. schedule_time (Optional[Union[int, float, timedelta, datetime]]): When to send the forwarded message. - Unix timestamp (int/float): Absolute time - timedelta: Relative time from now - datetime: Absolute date and time schedule_type (Optional[Literal['Default', 'WhenOnline']]): 'Default' uses schedule_time, 'WhenOnline' sends when user comes online. Returns: The updated information after forwarding the messages. ### `get_all_drafts(self: 'darkob.Client')` Get all saved message drafts. Returns: The result of the API call containing all drafts. ### `get_all_messages(self: 'darkob.Client', chat: str, show_message_ids: bool=False)` Retrieve all messages from a chat. Parameters: chat (str): Chat identifier or link (username, GUID, or invite link) show_message_ids (bool, optional): Include message IDs in output. Default is False. Returns: Result containing all messages with total count, first/last IDs, and chat GUID. ### `get_available_reactions(self: 'darkob.Client')` Retrieve the list of available message reactions that can be used in chats. Returns: Shows available reactions data from the server. ### `get_avatars(self: 'darkob.Client', chat: str)` Get avatars of a specific chat. Parameters: chat (str): The GUID, link, or username of the chat to retrieve avatars for. Returns: The result of the API call. ### `get_banned_members(self: 'darkob.Client', chat: str, show_member_guids: bool=False)` Get a list of banned members in a channel or group. Parameters: chat (str): The GUID, link, or username of the channel or group. show_member_guids (bool, optional): Show member GUIDs in output. Default is False. Returns: The result containing banned members with total count and optionally GUIDs. ### `get_blocked_users(self: 'darkob.Client', show_user_guids: bool=False)` Get a list of all blocked users. Parameters: show_user_guids (bool, optional): Show user GUIDs in output. Default is False. Returns: The result containing all blocked users with total count. ### `get_bot_info(self: 'darkob.Client', bot: str)` Get information about a bot. Parameters: bot (str): The GUID or username of the bot. Returns: The result of the API call. ### `get_channel_admin_access(self: 'darkob.Client', channel: str, admin: str)` Get the admin access list for a specific member in a channel. Parameters: channel (str): The GUID, link, or username of the channel. admin (str): The GUID or username of the admin for whom admin access is being checked. Returns: The result of the API call. ### `get_channel_admins(self: 'darkob.Client', channel: str, show_admin_guids: bool=False)` Get the list of admins in a channel. Parameters: channel (str): The GUID, link, or username of the channel. show_admin_guids (bool, optional): Show member GUIDs in output. Default is False. Returns: Result containing all admins with total count and optionally member_guids. ### `get_channel_info(self: 'darkob.Client', channel: str)` Get information about a channel. Parameters: channel (str): The GUID, link, or username of the channel. Returns: The result of the API call. ### `get_channel_link(self: 'darkob.Client', channel: str)` Get the join link of a channel. Parameters: channel (str): The GUID of the channel. Returns: The result of the API call. ### `get_channel_members(self: 'darkob.Client', channel: str, search_text: str=None, start_id: str=None)` Get members in a channel. Parameters: channel (str): The GUID, link, or username of the channel. search_text (str, optional): Text to search for in members. Defaults to None. start_id (str, optional): The ID to start fetching from. Defaults to None. Returns: The result of the API call. ### `get_channel_post_by_link(self: 'darkob.Client', url: str)` Retrieves channel post by application URL. Parameters: url (str): The channel post URL. Returns: Channel info and message data. ### `get_channel_seen_count(self: 'darkob.Client', channel: str, min_id: Union[str, int], max_id=Union[str, int])` Get the view count of a channel within a specific message ID range. Parameters: channel (str): The GUID, link, or username of the channel. min_id (Union[str, int]): Minimum message ID in the range (inclusive). max_id (Union[str, int]): Maximum message ID in the range (inclusive). Returns: The result of the API call. ### `get_channel_statistics(self: 'darkob.Client', channel: str)` Get all statistics for a channel. Parameters: channel (str): The GUID, link, or username of the channel. Returns: The result of the API call containing channel statistics. ### `get_chat_ads(self: 'darkob.Client', state: int=round(time()) - 150)` Retrieves advertising information for chats. Parameters: state (int, optional): The timestamp state to filter chat ads. Defaults to the current time minus 150 seconds. Returns: The result of the API call. ### `get_chat_info(self: 'darkob.Client', chat: str)` Get information about a user, group, or channel. Parameters: chat (str): The GUID, link, or username of the chat (user, group, or channel). Returns: The update containing information about the chat. ### `get_chat_messages(self: 'darkob.Client', chat: str, max_id: Union[str, int]=None, sort: Literal['FromMax', 'FromMin']='FromMin', filter_type: Optional[Literal['Voice', 'File', 'Music', 'Gif', 'Media', 'Link']]=None, limit: int=None)` Get messages from a chat with filtering and pagination. Parameters: chat (str): The GUID, link, or username of the chat. max_id (Union[str, int], optional): Maximum message ID to start from. sort (Literal['FromMax', 'FromMin']): Sort direction. Default is 'FromMin'. filter_type (Literal, optional): Filter messages by type: 'Voice', 'File', 'Music', 'Gif', 'Media', 'Link' limit (int, optional): Maximum number of messages to retrieve. If None, fetches all messages. Returns: The result containing messages, count, and pagination info. ### `get_chat_voice_chat(self: 'darkob.Client', chat: str)` Get the voice chat information for a group or channel. Parameters: chat (str): The GUID, link, or username of the group/channel. Returns: The voice chat information. ### `get_chats(self: 'darkob.Client', show_chat_guids: bool=False, auto_start_id: bool=True, start_id: str=None)` Get a list of all chats. Parameters: show_chat_guids (bool, optional): If True, include chat GUIDs in the result. Default is False. auto_start_id (bool, optional): If True, automatically fetch all pages of chats. If False, only fetch one page using start_id. Default is True. start_id (str, optional): Starting chat ID for pagination. Only used when auto_start_id is False. Returns: Data: The result containing chats with total count and optionally GUIDs. ### `get_chats_info(self: 'darkob.Client', chats: Union[str, List[str]])` Get information about multiple chats by their GUIDs. Parameters: chats (Union[str, List[str]]): A single chat (GUID, username, or link) or a list of them. Returns: The result of the API call containing chats information. ### `get_chats_updates(self: 'darkob.Client', state: Optional[Union[str, int]]=None)` Get updates for chats. Parameters: state (Optional[Union[str, int]]): State parameter for syncing updates. If not provided, it uses the current time minus 150 seconds. Returns: The result of the API call. ### `get_common_groups(self: 'darkob.Client', user: str)` Get groups in common with a user. Parameters: user (str): User's GUID/username. Returns: Common groups list. ### `get_contacts(self: 'darkob.Client', show_user_guids: bool=False)` Get a list of all contacts. Parameters: show_user_guids (bool, optional): Show user GUIDs in output. Default is False. Returns: The result containing all contacts with total count. ### `get_contacts_last_online(self: 'darkob.Client', users: Union[str, List[str]])` Get the last online status of multiple users. Parameters: users (Union[str, List[str]]): The GUID(s) or username(s) of the contacts. Returns: Last online status for each user. ### `get_contacts_stories(self: 'darkob.Client')` Get stories from contacts in the chat page. Returns: The result of the API call containing contacts stories. ### `get_contacts_updates(self: 'darkob.Client', state: Optional[Union[str, int]]=round(time()) - 150)` Get updates related to contacts. Parameters: state (Optional[Union[str, int]], optional): The state parameter to filter updates. Defaults to `round(time()) - 150`. Returns: The update related to contacts. ### `get_first_message(self: 'darkob.Client', chat: str)` Get the first message of a chat. Parameters: chat (str): The GUID, link, or username of the chat. Returns: The first message details. ### `get_first_messages(self: 'darkob.Client', chat: str, limit: int=100)` Get the first messages of a chat up to a limit. Parameters: chat (str): The GUID, link, or username of the chat. limit (int): Maximum number of messages to retrieve (max 100, min 1). Returns: List of first messages and count. ### `get_folders(self: 'darkob.Client', last_state: Union[int, str]=round(time()) - 150)` Get a list of folders. Parameters: last_state (Union[int, str]): The last state to retrieve folders. Returns: List of folders. ### `get_group_admin_access(self: 'darkob.Client', group: str, admin: str)` Get the admin access for a member in a group. Parameters: group (str): The GUID or link of the group. admin (str): The GUID or username of the admin for whom admin access is being checked. Returns: The result of the API call. ### `get_group_admins(self: 'darkob.Client', group: str, show_admin_guids: bool=False)` Get the list of admins in a group. Parameters: group (str): The GUID, link, or username of the group. show_admin_guids (bool, optional): Show admin GUIDs in output. Default is False. Returns: Result containing all admins with total count. ### `get_group_default_access(self: 'darkob.Client', group: str)` Get the default access settings for a group. Parameters: group (str): The GUID or link of the group. Returns: The result of the API call. ### `get_group_info(self: 'darkob.Client', group: str)` Get information about a group. Parameters: group (str): The GUID or link of the group. Returns: The result of the API call. ### `get_group_link(self: 'darkob.Client', group: str)` Get the link associated with a group. Parameters: group (str): The GUID or link of the group. Returns: The result of the API call. ### `get_group_members(self: 'darkob.Client', group: str, search_text: str=None, start_id: str=None)` Get members of a group. Parameters: group (str): The GUID or link of the group. search_text (str, optional): Search text for filtering members. Defaults to None. start_id (str, optional): The starting ID for pagination. Defaults to None. Returns: The result of the API call. ### `get_group_mention_list(self: 'darkob.Client', group: str, search_mention: str=None)` Get the mention list for a group. Parameters: group (str): The GUID or link of the group. search_mention (str, optional): Search text for mentions. Returns: The result of the API call. ### `get_group_message_read_participants(self: 'darkob.Client', group: str, message_id: Union[str, int])` Get list of participants who have read a specific message in a group. Parameters: group (str): The GUID or link of the group. message_id (Union[str, int]): The ID of the message. Returns: The result of the API call containing read participants. ### `get_group_online_count(self: 'darkob.Client', group: str)` Retrieves the number of online members in a specified group. Parameters: group (str): The GUID or link of the group. Returns: The result of the API call. ### `get_guid(self: 'darkob.Client', chat: str)` Retrieves the GUID of a user, group, channel, or bot. Parameters: chat (str): The username, group link, channel link, or bot username. Returns: str: The GUID of the chat. ### `get_info_by_link(self: 'darkob.Client', link: str)` Get group or channel preview by join link. Parameters: link (str): The join link. Returns: The result of the API call. ### `get_info_by_username(self: 'darkob.Client', username: str)` Get an chat (user, bot, or channel) by its username. Parameters: username (str): The username of the chat. Returns: The result of the API call. ### `get_inline_bots(self: 'darkob.Client', bots: Union[str, List[str]])` Retrieve information about inline bots by their GUIDs or usernames. Parameters: bots (Union[str, List[str]]): A single bot GUID/username or a list of bot GUIDs/usernames. Returns: The result of the API call. ### `get_join_links(self: 'darkob.Client', chat: str, creator: str=None)` Retrieves a list of join links for a specific group or channel. Parameters: chat (str): The GUID, link, or username of the target group or channel. Returns: The API response containing the join links. ### `get_join_requests(self: 'darkob.Client', chat: str, show_user_guids: bool=False)` Get a list of join requests in a channel or group. Parameters: chat (str): The GUID, link, or username of the channel or group. show_user_guids (bool, optional): Show user GUIDs in output. Default is False. Returns: Data: The result containing all join requests with total count. ### `get_last_message(self: 'darkob.Client', chat: str)` Get the last message from a chat and retrieve its details. Parameters: chat (str): The GUID, link, or username of the chat. Returns: The last message details. ### `get_last_messages(self: 'darkob.Client', chat: str, limit: int=100)` Get the last messages of a chat up to a limit. Parameters: chat (str): The GUID, link, or username of the chat. limit (int): Maximum number of messages to retrieve (max 1000). Returns: List of last messages and count. ### `get_last_online(self: 'darkob.Client', user: str)` Get the last online status of a user. Parameters: user (str): The GUID, link, or username of the user. Returns: Last online status with details. ### `get_link_from_app_url(self: 'darkob.Client', url: str)` Get a direct link from an application URL. Parameters: url (str): The application URL to extract the link from. Returns: Data: The result containing the extracted link. ### `get_live_comments(self: 'darkob.Client', live_id: str, access_token: str)` Get live stream comments. Parameters: live_id (str): Live stream ID. access_token (str): Access token from send_live response. Returns: The result of the API call. ### `get_live_play_url(self: 'darkob.Client', access_token: str, live_id: str)` Retrieves the play URL for a live stream. Parameters: access_token (str): The access token for authentication. live_id (str): The ID of the live stream. Returns: The result of the API call. ### `get_live_status(self: 'darkob.Client', live_id: str, access_token: str)` Get live stream status. Parameters: live_id (str): Live stream ID. access_token (str): Access token from send_live response. Returns: Live status info. ### `get_location_view(self: 'darkob.Client', latitude: float, longitude: float)` Get map view for a location. Parameters: latitude (float): Latitude (-90 to 90) longitude (float): Longitude (-180 to 180) Returns: Map view data. ### `get_me(self: 'darkob.Client', refresh: bool=False, ttl: float=300.0)` Get information about the authenticated user. The result is cached for ``ttl`` seconds (default 5 minutes), because profile reads are frequent and rarely change. Pass ``refresh=True`` to force a new request. Parameters: refresh (bool): Ignore the cache. Defaults to False. ttl (float): Cache lifetime in seconds. Defaults to 300. Returns: Information about the authenticated user. ### `get_message_info(self: 'darkob.Client', chat: str, message_id: Union[str, int])` Get detailed information about a message. Parameters: chat (str): The GUID, link, or username of the chat. message_id (Union[str, int]): The ID of the message to retrieve. Returns: Message information. ### `get_message_url(self: 'darkob.Client', chat: str, message_id: Union[str, int])` Get the shareable URL of a specific message. Parameters: chat (str): The GUID, link, or username of the chat to which the message belongs. message_id (Union[str, int]): The ID of the message for which to retrieve the shareable URL. Returns: The shareable URL of the specified message. ### `get_messages(self: 'darkob.Client', chat: str, types: Optional[Union[str, List[str]]]=None)` Get messages from a chat with optional type filtering. Parameters: chat (str): The GUID, link, or username of the chat. types (Optional[Union[str, List[str]]]): Type(s) of messages to filter by. Each item is independent. Available types: - "text": Text messages - "image": Image messages - "video": Video messages (non-round) - "video_message": Round video messages - "voice": Voice messages - "music": Music messages - "file": File messages - "gif": GIF messages - "live": Live messages - "location": Location messages - "poll": Poll messages - "contact": Contact messages (only private chats) - "event": Event messages - "edited": Edited messages - "forwarded": Forwarded messages - "sticker": Sticker messages - "me": Messages sent by the client itself - "bots": Messages sent by bots - "users": Messages sent by users You can also pass a member GUID or username for member filtering. If None, returns all messages. Returns: - messages: list of filtered messages. - count: number of filtered messages. - chat_guid: The GUID of the chat. - total_all: total messages before filtering. - filter_types: list of applied type filters. - member_guids: list of applied member GUID filters. ### `get_messages_by_id(self: 'darkob.Client', chat: str, message_ids: Union[str, int, list])` Retrieve messages by their IDs. Parameters: chat (str): The GUID, link, or username of the chat to which the messages belong. message_ids (Union[str, int, list]): The ID or list of IDs of the messages to retrieve. Returns: The retrieved messages identified by their IDs. ### `get_messages_interval(self: 'darkob.Client', chat: str, middle_message_id: Union[int, str])` Retrieve messages in an interval around a middle message ID. Parameters: chat (str): The GUID, link, or username of the chat to which the messages belong. middle_message_id (Union[int, str]): The middle message ID around which the interval is determined. Returns: The retrieved messages in the specified interval. ### `get_messages_reactions(self: 'darkob.Client', chat: str, min_id: Union[str, int], max_id: Union[str, int])` Get reactions of messages in a chat within a specific ID range. Parameters: chat (str): Chat identifier (link, username, or GUID) min_id (Union[str, int]): Minimum message ID (lower bound) max_id (Union[str, int]): Maximum message ID (upper bound) Returns: List of reactions for messages in the specified range. ### `get_messages_updates(self: 'darkob.Client', chat: str, state: int=round(time()) - 150)` Get message updates for a specific chat. Parameters: chat (str): The GUID, link, or username of the chat for which updates are requested. state (int): The state at which updates are requested. Defaults to a timestamp approximately 150 seconds ago. Returns: The message updates for the specified chat. ### `get_my_archived_sticker_sets(self: 'darkob.Client', start_id: str=None)` Get archived sticker sets of the current user. Parameters: start_id (str, optional): The ID to start fetching from. Defaults to None. Returns: The result of the API call. ### `get_my_gif_set(self: 'darkob.Client')` Gets the user's personal GIF set. Returns: Information about the user's GIF set. ### `get_my_guid(self: 'darkob.Client')` Get the GUID of the currently authenticated user. Returns: str: The user's GUID. ### `get_my_sessions(self: 'darkob.Client')` Get information about the current user's sessions. Returns: Information about the user's sessions. ### `get_my_sticker_sets(self: 'darkob.Client')` Get the sticker sets owned by the user. Returns: The sticker sets owned by the user. ### `get_notification_setting(self: 'darkob.Client')` Retrieves the current notification settings for the account. Returns: The result of the API call. ### `get_pending_owner(self: 'darkob.Client', chat: str)` Retrieves the pending owner information for a specified chat. Parameters: chat (str): The GUID, link, or username of the chat. Returns: An update chat containing details about the pending owner of the specified chat. ### `get_pinned_messages(self: 'darkob.Client', chat: str)` Get all pinned messages from a chat. Parameters: chat (str): The GUID, link, or username of the chat. Returns: Data: Dictionary containing pinned messages and optionally message IDs. ### `get_poll_option_voters(self: 'darkob.Client', poll_id: str, selection_index: Union[str, int], start_id: Optional[str]=None)` Get voters for a specific poll option. Parameters: poll_id (str): The ID of the poll for which voters are requested. selection_index (Union[str, int]): The index of the poll option for which voters are requested. start_id (Optional[str]): The ID from which to start fetching voters. Defaults to None. Returns: The voters for the specified poll option. ### `get_poll_status(self: 'darkob.Client', poll_id: str)` Get the status of a specific poll. Parameters: poll_id (str): The ID of the poll for which the status is requested. Returns: The status of the specified poll. ### `get_post_by_ask_link(self: 'darkob.Client', url: str)` Retrieves channel post by ask_join_link (go.rubika.ir link). Parameters: url (str): The go.rubika.ir link. Returns: Channel info and message data. ### `get_privacy_setting(self: 'darkob.Client')` Get the current user's privacy setting. Returns: The current user's privacy setting. ### `get_profile_link_items(self: 'darkob.Client', chat: str)` Get profile link items for a given chat. Parameters: chat (str): The GUID, link, or username of the chat. Returns: The result of the API call. ### `get_related_chats(self: 'darkob.Client', chat: str)` Get related chats for a given chat. Parameters: chat (str): The GUID, link, or username of the chat. Returns: The result of the API call. ### `get_saved_music_playlist(self: 'darkob.Client', user: str)` Get the saved music playlist of a user. Parameters: user (str): The GUID or username of the user. Returns: The result of the API call containing saved music playlist. ### `get_scheduled_messages(self: 'darkob.Client', chat: str, start_id: str=None)` Get scheduled messages in a chat. Parameters: chat (str): The GUID, link, or username of the chat. start_id (str, optional): The ID to start fetching from. Defaults to None. Returns: The result of the API call containing scheduled messages. ### `get_service_info(self: 'darkob.Client', service: str)` Get information about a service. Parameters: service (str): The GUID of the service. Returns: The result of the API call. ### `get_sticker_set_by_id(self: 'darkob.Client', sticker_set_id: str)` Get a sticker set by its ID. Parameters: sticker_set_id (str): The ID of the sticker set. Returns: The sticker set corresponding to the provided ID. ### `get_sticker_setting(self: 'darkob.Client')` Get the sticker settings of the current user. Returns: The result of the API call containing sticker settings. ### `get_stickers_by_emoji(self: 'darkob.Client', emoji: str, suggest_by: str='All')` Get stickers by emoji. Parameters: emoji (str): The emoji character. suggest_by (str): The type of suggestion (default is 'All'). Returns: Stickers corresponding to the provided emoji and suggestion type. ### `get_stickers_by_set_ids(self: 'darkob.Client', sticker_set_ids: Union[str, list])` Get stickers by set IDs. Parameters: sticker_set_ids (Union[str, list]): The sticker set ID or a list of sticker set IDs. Returns: Stickers corresponding to the provided set IDs. ### `get_string_session(self: 'darkob.Client', password: Optional[str]=None)` Export current session as an encrypted StringSession. Parameters: password (Optional[str]): Optional password for encryption. If provided, StringSession can only be opened with this password. Returns: str: Encrypted StringSession that can be used later with `Messenger(string_session=..., password=...)`. ### `get_suggested_folders(self: 'darkob.Client')` Get the suggested folders for the user. Returns: The suggested folders for the user. ### `get_time(self: 'darkob.Client')` Retrieve the current server time. Returns: The result of the API call. ### `get_top_users(self: 'darkob.Client')` Get list of top users. Returns: List of top users. ### `get_trend_sticker_sets(self: 'darkob.Client', start_id: str=None)` Get trending sticker sets. Parameters: start_id (str): The start ID for pagination. Returns: Trending sticker sets. ### `get_two_passcode_status(self: 'darkob.Client')` Get the two-passcode status for the user. Returns: The two-passcode status for the user. ### `get_unconfirmed_sessions(self: 'darkob.Client')` Get a list of unconfirmed (pending) sessions for the current account. Returns: The result of the API call containing unconfirmed sessions. ### `get_unread_mentions(self: 'darkob.Client', group: str, max_id: Union[str, int], min_id: Union[str, int], sort: str=None)` Get unread mentions in a group. Parameters: group (str): The GUID or link of the group. max_id (Union[str, int]): Maximum message ID. min_id (Union[str, int]): Minimum message ID. sort (str, optional): Sort order. Defaults to None. Returns: The result of the API call containing unread mentions. ### `get_updates(self: 'darkob.Client')` Listen for updates from Rubika's WebSocket. Returns: None ### `get_user_info(self: 'darkob.Client', user: str=None)` Get information about a specific user. Parameters: user (str): The GUID or username of the user. Returns: Information about the specified user. ### `get_voice_chat_participants(self: 'darkob.Client', chat: str, show_user_guids: bool=False)` Get list of participants in a voice chat. Parameters: chat (str): The GUID, link, or username of the group/channel. show_user_guids (bool, optional): Show user GUIDs in output. Default is False. Returns: The result containing all voice chat participants with total count. ### `get_voice_chat_updates(self: 'darkob.Client', chat: str, state: int=None)` Get voice chat updates for a group. Parameters: chat (str): The GUID, link, or username of the group/channel. state (int, optional): The state for updates. If not provided, it defaults to the current time minus 150 seconds. Returns: Update group containing the voice chat updates. ### `get_wallet_transaction_message(self: 'darkob.Client', transfer_id: str, access_transfer: str)` Get the message associated with a wallet transaction. Parameters: transfer_id (str): The ID of the wallet transaction. access_transfer (str): The access hash for the transaction. Returns: The result of the API call. ### `get_wallpapers(self: 'darkob.Client')` Get the current chat wallpaper settings. Returns: The result of the API call containing wallpaper information. ### `heartbeat(self: 'darkob.Client', chat_guid: str)` _No docstring._ ### `iter_messages(self: 'darkob.Client', chat: str, *, sort: str='FromMin', filter_type: Optional[str]=None, page_size: int=25, max_items: Optional[int]=None)` Yield messages from *chat*, one page at a time. Parameters: chat (str): Chat GUID, link or username. sort (str): 'FromMin' (oldest first) or 'FromMax' (newest first). filter_type (str, optional): 'Voice', 'File', 'Music', 'Gif', 'Media' or 'Link'. page_size (int): Messages requested per round-trip. max_items (int, optional): Stop after this many messages. Yields: Each message as a :class:`~darkob.data.Data` object. ### `join_channel(self: 'darkob.Client', channel: str)` Join a channel. Parameters: channel (str): The GUID, link, or username of the channel. Returns: Result of the API call. ### `join_chat(self: 'darkob.Client', chat: str)` Join a chat (channel or group). Parameters: chat (str): The GUID, link, or username of the chat (channel or group). Returns: The result of the API call. ### `join_group(self: 'darkob.Client', group: str)` Join a group using the provided link. Parameters: group (str): The group link. Returns: The result of the API call. ### `join_voice_chat(self: 'darkob.Client', chat: str, sdp_offer_data: str | None = None)` Join to the group | channel voice chat. Parameters: chat (str): The GUID, link, or username of the group/channel. sdp_offer_data (str, optional): SDP offer data. If not provided, uses default. Returns: The result of the API call. ### `leave_channel(self: 'darkob.Client', channel: str)` Leave a channel. Parameters: channel (str): The GUID, link, or username of the channel. Returns: The result of the API call. ### `leave_chat(self: 'darkob.Client', chat: str)` Leave a chat (channel or group). Parameters: chat (str): The GUID, link, or username of the chat (channel or group). Returns: The result of the API call. ### `leave_group(self: 'darkob.Client', group: str)` Leave a group. Parameters: group (str): The GUID or link of the group. Returns: The result of the API call. ### `leave_voice_chat(self: 'darkob.Client', chat: str)` Leave a voice chat in a group or channel. Parameters: chat (str): The GUID, link, or username of the group/channel. Returns: The result of the API call. ### `lock_group(self: 'darkob.Client', group: str)` Lock a group by disabling SendMessage access. Parameters: group (str): The GUID or link of the group. Returns: Result message. ### `login_disable_two_step(self: 'darkob.Client', phone_number: str, email_code: str, forget_password_code_hash: str)` Disable two-step verification during login. Parameters: phone_number (str): The phone number associated with the account. email_code (str): The verification code sent to email. forget_password_code_hash (str): The code hash for forgotten password flow. Returns: The result of the API call. ### `login_two_step_forget_password(self: 'darkob.Client', phone_number: str)` Start the password recovery process for two-step verification. Use this when the user has forgotten their two-step verification password. This will initiate the recovery flow (e.g. sending a code to email/phone). Parameters: phone_number (str): The phone number associated with the account. Returns: The result of the API call, typically containing a hash or instructions for the next step of recovery. ### `logout(self: 'darkob.Client', confirm: bool=True)` Log out of the current session. Parameters: confirm (bool): If True, ask the user for confirmation before logging out. If False, log out immediately. Default is True. Returns: The result of the logout operation if confirmed. Exits if cancelled. ### `mark_as_read(self: 'darkob.Client', chat: str)` Mark a chat as read by seeing the last message. Parameters: chat (str): The GUID, link, or username of the chat. Returns: Result of the operation. ### `mark_as_seen(self: 'darkob.Client', chat: str, message_id: Union[str, int]=None)` Mark a specific message as seen. Parameters: chat (str): The GUID, link, or username of the chat. message_id (Union[str, int], optional): Specific message ID. Defaults to last message. Returns: Result of the operation. ### `member_is_admin(self: 'darkob.Client', chat: str, member: str)` Checks if a member is an admin in a group or channel. Parameters: chat (str): The GUID, link, or username of the group or channel. member (str): The GUID or username of the member. Returns: bool: True if the user is an admin, False otherwise. ### `mute_chat(self: 'darkob.Client', chat: str, duration: Union[int, timedelta]=None)` Mute a chat. Parameters: chat (str): The GUID, link, or username of the chat to mute. duration (Union[int, timedelta], optional): Duration of mute. - int: seconds, must be at least 1800 (30 minutes). - timedelta: e.g., timedelta(hours=1), timedelta(minutes=30). Defaults to None (permanent mute). Returns: Result of the operation. ### `on_add_reaction(self: 'darkob.Client', *filters: Filter)` Decorator for reaction added. ### `on_call_signal(self: 'darkob.Client', *filters: Filter)` Decorator for call signal data. ### `on_call_update(self: 'darkob.Client', *filters: Filter)` Decorator for call updates. ### `on_chat_updates(self: 'darkob.Client', *filters: Filter)` Decorator for chat updates with optional filters. ### `on_delete_message(self: 'darkob.Client', *filters: Filter)` Decorator for deleted messages. ### `on_draft_message(self: 'darkob.Client', *filters: Filter)` Decorator for draft message updates. ### `on_edit_message(self: 'darkob.Client', *filters: Filter)` Decorator for edited messages with optional filters. ### `on_message(self: 'darkob.Client', *filters: Filter)` Decorator for message updates with optional filters. ### `on_new_message(self: 'darkob.Client', *filters: Filter)` Decorator for new messages with optional filters. ### `on_remove_notifications(self: 'darkob.Client', *args, **kwargs)` _No docstring._ ### `on_remove_reaction(self: 'darkob.Client', *filters: Filter)` Decorator for reaction removed. ### `on_scheduled_message(self: 'darkob.Client', *filters: Filter)` Decorator for scheduled message updates. ### `on_show_activities(self: 'darkob.Client', *filters: Filter)` Decorator for show activities (typing, uploading, recording) with optional filters. ### `on_show_notifications(self: 'darkob.Client', *filters: Filter)` Decorator for show notifications with optional filters. ### `on_unconfirmed_session(self: 'darkob.Client', *filters: Filter)` Decorator for unconfirmed session updates (anti-login). ### `on_voice_chat_participant(self: 'darkob.Client', *filters: Filter)` Decorator for voice chat participant updates. ### `on_voice_chat_update(self: 'darkob.Client', *filters: Filter)` Decorator for voice chat updates. ### `pin_chat(self: 'darkob.Client', chat: str)` Pin a chat. Parameters: chat (str): The GUID, link, or username of the chat to pin. Returns: Result of the operation. ### `pin_chat_in_folder(self: 'darkob.Client', chat: str, folder_id: str)` Pin a chat in a folder. Parameters: chat (str): The GUID, link, or username of the chat to pin. folder_id (str): The folder ID to pin the chat in. Returns: The result of the API call. ### `pin_message(self: 'darkob.Client', chat: str, message_id: Union[str, int])` pin a message. Parameters: chat (str): The GUID, link, or username of the recipient. message_id (Union[str, int]): The ID of the message to pin. Returns: The update indicating the success of the operation. ### `play_voice_chat(self: 'darkob.Client', chat: str, media: pathlib.Path)` Plays voice media in a chat. Parameters: chat: The GUID, link, or username of the chat to play the voice media in. media: The path to the voice media file. ### `register_device(self: 'darkob.Client', device_model: str=None, *args, **kwargs)` Register the current device with the Rubika server. Parameters: device_model (str, optional): Custom device model name. Returns: The result of the API call. ### `reject_join_request(self: 'darkob.Client', chat: str, user: str)` Reject a join request for a group or channel. Parameters: chat (str): The GUID, link, or username of the group/channel. user (str): The user GUID or username of the requester. Returns: The result of the API call. ### `reject_ownership_request(self: 'darkob.Client', chat: str)` Reject an ownership transfer request. Parameters: chat (str): The GUID, link, or username of the chat (channel/group). Returns: The result of the API call. ### `remove_from_top_users(self: 'darkob.Client', user: str)` Remove user from top users list. Parameters: user (str): The user GUID or username to remove. Returns: The result of the API call. ### `remove_handler(self: 'darkob.Client', func)` _No docstring._ ### `remove_reaction(self: 'darkob.Client', chat: str, message_id: Union[str, int], reaction_id: Union[int, str])` Remove a reaction from a specific message. Parameters: chat (str): The GUID, link, or username of the chat associated with the message. message_id (str): The ID of the message from which the reaction will be removed. reaction_id (int): The ID of the reaction to be removed. Returns: The update indicating the success of removing the reaction. ### `reorder_folder(self: 'darkob.Client', folder_ids: Union[str, List[str]])` Reorder folders. Parameters: folder_ids (Union[str, List[str]]): A single folder ID or a list of folder IDs in the new order. Returns: The result of the API call. ### `reorder_sticker_sets(self: 'darkob.Client', ordered_sticker_set_ids: Union[str, List[str]])` Reorder sticker sets in the user's collection. Parameters: ordered_sticker_set_ids (Union[str, List[str]]): A single sticker set ID or a list of sticker set IDs in the desired order. Returns: The result of the API call. ### `report_chat(self: 'darkob.Client', chat: str, report_type: Union[int, str], description: Optional[str]=None)` Report a chat (user, channel, group, etc.) for a specific reason. Parameters: chat (str): The GUID, link, or username of the chat to be reported. report_type (Union[int, str]): The report reason. Can be: - Integer code between 100 and 106 - String name (case-insensitive): 'Other', 'Violence', 'Spam', 'Porn', 'ChildAbuse', 'Copyright', 'Fraud' If set to 100 (Other), `description` becomes required. description (Optional[str]): Description for the report. Required when `report_type` is 100 (Other). Returns: The result of the API call. ### `report_chat_ads(self: 'darkob.Client', chat_ads_id: str)` Register a report action on a chat ad. The `chat_ads_id` is obtained from the `get_chat_ads` method. Parameters: chat_ads_id (str): The chat ads ID to report. Returns: The result of the operation. ### `report_live(self: 'darkob.Client', live_id: str, report_type: Union[int, str], description: Optional[str]=None)` Report a live stream. Parameters: live_id (str): The ID of the live stream to report. report_type (Union[int, str]): The report reason. Can be: - Integer code between 100 and 106 - String name (case-insensitive): 'Other', 'Violence', 'Spam', 'Porn', 'ChildAbuse', 'Copyright', 'Fraud' If set to 100 (Other), `description` becomes required. description (Optional[str]): Description for the report. Required when `report_type` is 100 (Other). Returns: The result of the API call. ### `report_message(self: 'darkob.Client', chat: str, message_id: Union[str, int], report_type: Union[int, str], description: Optional[str]=None)` Report a message for a specific reason. Parameters: chat (str): The GUID, link, or username of the chat. message_id (Union[str, int]): The ID of the message to be reported. report_type (Union[int, str]): The report reason. Can be: - Integer code between 100 and 106 - String name (case-insensitive): 'Other', 'Violence', 'Spam', 'Porn', 'ChildAbuse', 'Copyright', 'Fraud' If set to 100 (Other), `description` becomes required. description (Optional[str]): Description for the report. Required when `report_type` is 100 (Other). Returns: The result of the API call. ### `request(self: 'darkob.Client', method: str, input: Optional[Dict]=None, tmp_session: bool=False, encrypt: bool=True)` Build and send a request to the Rubika API. Parameters: method (str): API method name (e.g., 'sendMessage', 'getUserInfo'). input (dict, optional): Input data for the method. tmp_session (bool): Use temporary session instead of auth (default: False). When True, the client will auto-connect if not connected yet. encrypt (bool): Encrypt the request data (default: True). Returns: Data or None: The API response. Raises: NoConnection: If the client has not been started and `tmp_session=False`. ### `request_change_phone_number(self: 'darkob.Client', new_phone_number: str)` Request to change the account phone number. Parameters: new_phone_number (str): The new phone number (e.g., 09123456789, +989123456789, +1234567890). Returns: The result of the API call containing phone_code_hash for verification. ### `request_forget_password(self: 'darkob.Client')` Request to reset the account password. Returns: The result of the API call. ### `request_recovery_email(self: 'darkob.Client', password: str, recovery_email: str)` Request a recovery code to be sent to the recovery email. Parameters: password (str): User's current password. recovery_email (str): Recovery email address. Returns: The result of the API call. ### `request_send_file(self: 'darkob.Client', file_name: str, size: Union[str, int, float], mime: str=None)` Request sending a file. Parameters: file_name (str): The name of the file to be sent. size (Union[str, int, float]): The size of the file to be sent. mime (str, optional): The MIME type of the file. If None, it will be derived from the file name. Returns: The update indicating the success of the file sending request. ### `request_video_call(self: 'darkob.Client', user: str, library_versions: Optional[List[str]]=None, max_layer: int=92, min_layer: int=65, sip_version: int=1, support_call_out: bool=True)` Request a video call with a user. Parameters: user (str): The GUID or username of the user to call. library_versions (List[str], optional): List of supported library versions. Default: ['2.7.7', '2.4.4'] max_layer (int): Maximum protocol layer. Default: 92 min_layer (int): Minimum protocol layer. Default: 65 sip_version (int): SIP version. Default: 1 support_call_out (bool): Support outgoing calls. Default: True Returns: Call request result containing session info. ### `request_voice_call(self: 'darkob.Client', user: str, library_versions: Optional[List[str]]=None, max_layer: int=92, min_layer: int=65, sip_version: int=1, support_call_out: bool=True)` Request a voice call with a user. Parameters: user (str): The GUID or username of the user to call. library_versions (List[str], optional): List of supported library versions. Default: ['2.7.7', '2.4.4'] max_layer (int): Maximum protocol layer. Default: 92 min_layer (int): Minimum protocol layer. Default: 65 sip_version (int): SIP version. Default: 1 support_call_out (bool): Support outgoing calls. Default: True Returns: Call request result containing session info. ### `reset_contacts(self: 'darkob.Client')` Reset all saved contacts for the authenticated user. This method clears the entire contact list on the server side. Returns: The result of the API call. ### `reset_wallpapers(self: 'darkob.Client')` Reset all chat wallpapers to default. Returns: The result of the API call. ### `retract_poll(self: 'darkob.Client', poll_id: str)` Retract a poll. Parameters: poll_id (str): The ID of the poll to retract. Returns: The result of the API call. ### `revoke_join_link(self: 'darkob.Client', chat: str, join_link: str)` Revoke a invite link for a group or channel. Parameters: chat (str): The GUID, link, or username of the group/channel. join_link (str): The join link to revoke. Returns: The result of the API call. ### `run(self, coroutine: Optional[Coroutine]=None)` Start the client and listen for updates. Parameters: coroutine: Optional coroutine to run before listening for updates. Returns: None when used normally (runs forever until stopped). ### `search_chat_messages(self: 'darkob.Client', chat: str, search_text: str)` Searches for chat messages based on the specified criteria. Parameters: chat (str): The GUID, link, or username of the chat. search_text (str): The text to search for in messages. Returns: The search results containing messages. ### `search_global_chats(self: 'darkob.Client', text: str, filter_type: Optional[Union[str, List[str]]]=None, start_id: Optional[str]=None)` Search for global chats (users, channels, etc.) based on the given search text. Parameters: text (str): The text to search for. filter_type (str or list, optional): Filter results by type. 'User', 'Channel', 'Bot' or a list of them. start_id (str, optional): The ID to start fetching from. Defaults to None. Returns: The update containing search results. ### `search_global_messages(self: 'darkob.Client', search_text: str, start_id: Optional[str]=None)` Search for messages globally across all chats. Parameters: search_text (str): The text or hashtag to search for. start_id (str, optional): The ID to start fetching from. Defaults to None. Returns: The result of the API call. ### `search_messages(self: 'darkob.Client', chat: str, text: str)` Search for messages containing specific text in a chat. Parameters: chat (str): The GUID, link, or username of the chat. text (str): The text to search for. Returns: The search results. ### `search_stickers(self: 'darkob.Client', search_text: str='', start_id: str=None)` Search for stickers. Parameters: search_text (str): The search text. start_id (str): The start ID for pagination. Returns: Stickers matching the search criteria. ### `seen_channel_messages(self: 'darkob.Client', channel: str, min_id: Union[int, str], max_id: Union[int, str])` Mark channel messages as seen within a specific range. Parameters: channel (str): The GUID, link, or username of the channel. min_id (Union[int, str]): The minimum message ID to mark as seen. max_id (Union[int, str]): The maximum message ID to mark as seen. Returns: The result of the API call. ### `seen_chats(self: 'darkob.Client', seen_list: dict)` Marks multiple chats as seen. Parameters: seen_list (dict): A dictionary containing chat GUIDs and their last seen message IDs. Returns: The result of the operation. ### `send_chat_activity(self: 'darkob.Client', chat: str, activity: Literal['Typing', 'Recording', 'Uploading']='Typing')` Sends a chat activity, such as typing, uploading, or recording. Parameters: chat (str): The GUID, link, or username of the group/user. activity (str, optional): The type of activity. Defaults to 'Typing'. Returns: The result of the operation. Raises: InvalidInput: If the `activity` argument is not one of `"Typing", "Uploading", or "Recording"`. ### `send_code(self: 'darkob.Client', phone_number: str, pass_key: Optional[str]=None)` Send a verification code to a phone number. Parameters: phone_number (str): The target phone number. pass_key (str): The optional account pass key. Returns: The result of the API call. ### `send_contact(self: 'darkob.Client', chat: str, phone_number: Union[str, int], user: str, first_name: str, last_name: str='', vcard: Optional[str]=None, reply_to_message_id: Optional[Union[str, int]]=None)` Send a contact message to a specified chat. Parameters: chat (str): The GUID or username of the user or bot. phone_number (Union[str, int]): Contact's phone number. user (str): Contact's username or user GUID. first_name (str): Contact's first name. last_name (str, optional): Contact's last name. Defaults to "". vcard (str, optional): Custom vCard string. Defaults to None. reply_to_message_id (Union[str, int], optional): ID of the message to reply to. Defaults to None. Returns: The result of the API call. ### `send_file(self: 'darkob.Client', chat: str, file: Union[Path, bytes]=None, text: Optional[str]=None, reply_to_message_id: Optional[Union[str, int]]=None, via_bot: Optional[str]=None, schedule_time: Optional[Union[int, float, timedelta, datetime]]=None, schedule_type: Optional[Literal['Default', 'WhenOnline']]=None, base64: str=None, **kwargs)` Send a file. Parameters: chat (str): The GUID, link, or username of the chat. file (Union[Path, bytes], optional): The file data (path or bytes). text (Optional[str]): The caption for the file. Defaults to None. reply_to_message_id (Optional[Union[str, int]]): The ID of the message to which this is a reply. Defaults to None. via_bot (Optional[str]): Bot GUID or username to send the message via. Defaults to None. schedule_time (Optional[Union[int, float, timedelta, datetime]]): When to send the message. - Unix timestamp (int/float): Absolute time - timedelta: Relative time from now - datetime: Absolute date and time schedule_type (Optional[Literal['Default', 'WhenOnline']]): 'Default' uses schedule_time, 'WhenOnline' sends when user comes online (users only). base64 (str, optional): Base64 encoded file data. Returns: The result of the API call. ### `send_gif(self: 'darkob.Client', chat: str, gif: Union[Path, bytes]=None, text: Optional[str]=None, reply_to_message_id: Optional[Union[str, int]]=None, via_bot: Optional[str]=None, thumb: Optional[Union[bool, str]]=None, width: Optional[int]=None, height: Optional[int]=None, time: Optional[int]=None, schedule_time: Optional[Union[int, float, timedelta, datetime]]=None, schedule_type: Optional[Literal['Default', 'WhenOnline']]=None, base64: str=None, **kwargs)` Send a GIF to a chat. Parameters: chat (str): The GUID, link, or username of the chat. gif (Path, bytes, optional): The GIF data. Can be a file path or bytes. text (Optional[str]): Caption for the GIF. Defaults to None. reply_to_message_id (Optional[Union[str, int]]): ID of the message to reply to. Defaults to None. via_bot (Optional[str]): Bot GUID or username to send the message via. Defaults to None. thumb (Optional[Union[bool, str]]): Thumbnail behavior: - None or True: Auto-generate thumbnail using available libraries (default) - False: Use default thumbnail - str: Custom thumbnail as Base64 string (pure Base64, no data:image header) width (Optional[int]): Custom width for the GIF. Defaults to None (auto-detect). height (Optional[int]): Custom height for the GIF. Defaults to None (auto-detect). time (Optional[int]): Custom duration for the GIF in seconds. Defaults to None (auto-detect). schedule_time (Optional[Union[int, float, timedelta, datetime]]): When to send the message. - Unix timestamp (int/float): Absolute time - timedelta: Relative time from now - datetime: Absolute date and time schedule_type (Optional[Literal['Default', 'WhenOnline']]): 'Default' uses schedule_time, 'WhenOnline' sends when user comes online (users only). base64 (str, optional): Base64 encoded GIF data. Returns: The API response containing the sent message details. ### `send_image(self: 'darkob.Client', chat: str, image: Union[Path, bytes]=None, text: Optional[str]=None, reply_to_message_id: Optional[Union[str, int]]=None, is_spoil: bool=False, via_bot: Optional[str]=None, thumb: Optional[Union[bool, str]]=None, width: Optional[int]=None, height: Optional[int]=None, schedule_time: Optional[Union[int, float, timedelta, datetime]]=None, schedule_type: Optional[Literal['Default', 'WhenOnline']]=None, base64: str=None, **kwargs)` Send an image to a chat. Parameters: chat (str): The GUID, link, or username of the chat. image (Path, bytes, optional): The image data. Can be a file path or bytes. text (Optional[str]): Caption for the image. Defaults to None. reply_to_message_id (Optional[Union[str, int]]): ID of the message to reply to. Defaults to None. is_spoil (bool): Whether the image should be marked as a spoiler. Defaults to False. via_bot (Optional[str]): Bot GUID or username to send the message via. Defaults to None. thumb (Optional[Union[bool, str]]): Thumbnail behavior: - None or True: Auto-generate thumbnail using available libraries (or default). - str: Custom thumbnail as Base64 string. width (Optional[int]): Custom width for the image. Defaults to None (auto-detect). height (Optional[int]): Custom height for the image. Defaults to None (auto-detect). schedule_time (Optional[Union[int, float, timedelta, datetime]]): When to send the message. - Unix timestamp (int/float): Absolute time - timedelta: Relative time from now - datetime: Absolute date and time schedule_type (Optional[Literal['Default', 'WhenOnline']]): 'Default' uses schedule_time, 'WhenOnline' sends when user comes online (users only). base64 (str, optional): Base64 encoded image data. Returns: The API response containing the sent message details. ### `send_live(self: 'darkob.Client', chat: str, title: str=None, reply_to_message_id: Union[str, int]=None, thumb: Optional[Union[str, Path, bytes]]=None)` Send a live stream. Parameters: chat (str): The GUID, link, or username of the chat. title (str): Live stream title. reply_to_message_id (Optional[Union[str, int]]): The ID of the message to which this is a reply. Defaults to None. thumb (Optional[Union[str, Path, bytes]]): Thumbnail for the live stream. - str: Base64 encoded string, file path, or URL. - Path: Path to thumbnail file. - bytes: Raw thumbnail bytes. If not provided, a default thumbnail will be used. Returns: The result of the API call. ### `send_location(self: 'darkob.Client', chat: str, latitude: float, longitude: float, reply_to_message_id: Union[str, int]=None)` Send a map location. Parameters: chat (str): The GUID, link, or username of the chat. latitude (float): Latitude (-90 to 90). longitude (float): Longitude (-180 to 180). reply_to_message_id (Optional[Union[str, int]]): The ID of the message to which this is a reply. Defaults to None. Returns: The result of the API call. ### `send_message(self: 'darkob.Client', chat: str, text: Optional[str]=None, reply_to_message_id: Optional[Union[str, int]]=None, via_bot: Optional[str]=None, file_inline: Optional[Union[Data, Path, bytes]]=None, base64_data: Optional[str]=None, sticker: Optional[Union[Data, dict]]=None, type: str='File', is_spoil: bool=False, thumb: Optional[Union[bool, str, Path, bytes]]=None, audio_info: bool=True, metadata: Optional[dict]=None, performer: Optional[str]=None, schedule_time: Optional[Union[int, float, timedelta, datetime]]=None, schedule_type: Optional[Literal['Default', 'WhenOnline']]=None, **kwargs)` Send a message to a chat. Parameters: chat (str): The GUID, link, or username of the chat. text (Optional[str]): The text content of the message. reply_to_message_id (Optional[Union[str, int]]): The ID of the message to reply to. via_bot (Optional[str]): Bot GUID or username to send the message via. metadata (Optional[dict]): Additional metadata for text formatting. schedule_time (Optional[Union[int, float, timedelta, datetime]]): When to send the message. Accepts: - Unix timestamp (int/float): Absolute time - timedelta: Relative time from now (e.g., timedelta(hours=1)) - datetime: Absolute date and time schedule_type (Optional[Literal['Default', 'WhenOnline']]): 'Default' uses schedule_time, 'WhenOnline' sends when user comes online. Returns: MessageResult: The API response containing the sent message details, with action methods like edit, delete, reply, forward, pin. ### `send_message_api_call(self: 'darkob.Client', chat: str, message_id: Union[str, int], button_id: str)` Send API call response to a chat's inline keyboard button. Parameters: chat (str): The GUID, link, or username of the chat. message_id (Union[str, int]): ID of the message containing inline keyboard. button_id (str): ID of the button. Returns: The result of the API call. Example: >>> await client.send_message_api_call( # doctest: +SKIP ... chat="b0C2y04506bd2306f068aa161e0502db", ... message_id="1499338519906784", ... button_id="b0SPm00c8ab83b689ac2eeffe16ec7db" ... ) ### `send_music(self: 'darkob.Client', chat: str, music: Union[Path, bytes]=None, text: Optional[str]=None, reply_to_message_id: Optional[Union[str, int]]=None, via_bot: Optional[str]=None, performer: Optional[str]=None, time: Optional[int]=None, schedule_time: Optional[Union[int, float, timedelta, datetime]]=None, schedule_type: Optional[Literal['Default', 'WhenOnline']]=None, base64: str=None, **kwargs)` Send a music file to a chat. Parameters: chat (str): The GUID, link, or username of the chat. music (Path, bytes, optional): The music data. Can be a file path or bytes. text (Optional[str]): Caption for the music. Defaults to None. reply_to_message_id (Optional[Union[str, int]]): ID of the message to reply to. Defaults to None. via_bot (Optional[str]): Bot GUID or username to send the message via. Defaults to None. performer (Optional[str]): Name of the performer/artist. Defaults to None (auto-detect). time (Optional[int]): Custom duration for the music in seconds. Defaults to None (auto-detect). schedule_time (Optional[Union[int, float, timedelta, datetime]]): When to send the message. - Unix timestamp (int/float): Absolute time - timedelta: Relative time from now - datetime: Absolute date and time schedule_type (Optional[Literal['Default', 'WhenOnline']]): 'Default' uses schedule_time, 'WhenOnline' sends when user comes online (users only). base64 (str, optional): Base64 encoded music data. Returns: The API response containing the sent message details. ### `send_now_scheduled_message(self: 'darkob.Client', chat: str, message_id: Union[int, str])` Send a scheduled message immediately. Parameters: chat (str): The GUID, link, or username of the chat. message_id (int): The ID of the scheduled message to send now. Returns: The result of the API call. ### `send_poll(self: 'darkob.Client', chat: str, question: str, options: list, is_anonymous: bool=True, multiple_answers: bool=False, reply_to_message_id: Optional[Union[str, int]]=None)` Send a poll message with the specified parameters. Parameters: chat (str): The GUID, link or username of the chat associated with the poll (e.g., group, channel). question (str): The question for the poll. options (list): A list of string values representing the poll options. is_anonymous (bool): Whether the poll is anonymous or not. Defaults to True. multiple_answers (bool): Whether the poll allows multiple answers or not. Defaults to False. reply_to_message_id (Optional[Union[str, int]]): The ID of the message to reply to. Defaults to None. Returns: The updated information after creating the poll. ### `send_quiz(self: 'darkob.Client', chat: str, question: str, options: list, correct_option: Union[int, str], hint: str=None, is_anonymous: bool=True, reply_to_message_id: Optional[Union[str, int]]=None)` Send a quiz-type poll message with the specified parameters. Parameters: chat (str): The GUID or link or username of the chat associated with the quiz (e.g., group, channel). question (str): The question for the quiz. options (list): A list of string values representing the quiz options. correct_option (Union[int, str]): The index or ID of the correct option for quiz-type polls. hint (str): A hint for the correct answer in quiz-type polls. Defaults to None. is_anonymous (bool): Whether the poll is anonymous or not. Defaults to True. reply_to_message_id (Union[str, int]): The ID of the message to reply to. Defaults to None. Returns: The updated information after creating the quiz-type poll. ### `send_rubino_post(self: 'darkob.Client', chat: str, post_id: str, post_profile_id: str, is_mute: bool=False)` Send a Rubino post to a chat. Parameters: chat (str): The GUID, link, or username of the chat. post_id (str): The post ID to send. post_profile_id (str): The post profile ID. is_mute (bool): Send silently without notification. Default is False. Returns: The result of the API call. ### `send_rubino_product(self: 'darkob.Client', chat: str, store_id: str, product_id: str, product_varieties: List[dict])` Send a Rubino product to a chat. Parameters: chat (str): The GUID, link, or username of the chat. store_id (str): The store ID. product_id (str): The product ID. product_varieties (List[dict]): List of product varieties. Returns: The result of the API call. ### `send_rubino_story(self: 'darkob.Client', chat: str, story_id: str, story_profile_id: str, reply_text: str='', type: Literal['Reply', 'Direct']='Reply', is_mute: bool=False)` Send a Rubino story reply or direct message. Parameters: chat (str): The GUID, link, or username of the chat. story_id (str): The story ID. story_profile_id (str): The story profile ID. reply_text (str): Reply text. Default is empty string. type (str): 'Reply' or 'Direct'. Default is 'Reply'. is_mute (bool): Send silently without notification. Default is False. Returns: The result of the API call. ### `send_sticker(self: 'darkob.Client', chat: str, emoji_character: str, sticker_id: str, sticker_set_id: str, file: dict, w_h_ratio: str='1.0', reply_to_message_id: Optional[Union[str, int]]=None, via_bot: Optional[str]=None, schedule_time: Optional[Union[int, float, timedelta, datetime]]=None, schedule_type: Optional[Literal['Default', 'WhenOnline']]=None)` Send a sticker. Parameters: chat (str): The GUID, link, or username of the chat. emoji_character (str): The emoji character associated with the sticker. sticker_id (str): The ID of the sticker. sticker_set_id (str): The ID of the sticker set. file (dict): The file data for the sticker. w_h_ratio (str): The width-to-height ratio of the sticker. Defaults to '1.0'. reply_to_message_id (Optional[Union[str, int]]): The ID of the message to which this is a reply. Defaults to None. via_bot (Optional[str]): Bot GUID or username to send the message via. Defaults to None. schedule_time (Optional[Union[int, float, timedelta, datetime]]): When to send the message. - Unix timestamp (int/float): Absolute time - timedelta: Relative time from now - datetime: Absolute date and time schedule_type (Optional[Literal['Default', 'WhenOnline']]): 'Default' uses schedule_time, 'WhenOnline' sends when user comes online (users only). ### `send_video(self: 'darkob.Client', chat: str, video: Union[Path, bytes]=None, text: Optional[str]=None, reply_to_message_id: Optional[Union[str, int]]=None, is_spoil: bool=False, via_bot: Optional[str]=None, thumb: Optional[Union[bool, str]]=None, width: Optional[int]=None, height: Optional[int]=None, time: Optional[int]=None, schedule_time: Optional[Union[int, float, timedelta, datetime]]=None, schedule_type: Optional[Literal['Default', 'WhenOnline']]=None, base64: str=None, **kwargs)` Send a video to a chat. Parameters: chat (str): The GUID, link, or username of the chat. video (Path, bytes, optional): The video data. Can be a file path or bytes. text (Optional[str]): Caption for the video. Defaults to None. reply_to_message_id (Optional[Union[str, int]]): ID of the message to reply to. Defaults to None. is_spoil (bool): Whether the video should be marked as a spoiler. Defaults to False. via_bot (Optional[str]): Bot GUID or username to send the message via. Defaults to None. thumb (Optional[Union[bool, str]]): Thumbnail behavior: - None or True: Auto-generate thumbnail using available libraries (or default). - str: Custom thumbnail as Base64 string. width (Optional[int]): Custom width for the video. Defaults to None (auto-detect). height (Optional[int]): Custom height for the video. Defaults to None (auto-detect). time (Optional[int]): Custom duration for the video in seconds. Defaults to None (auto-detect). schedule_time (Optional[Union[int, float, timedelta, datetime]]): When to send the message. - Unix timestamp (int/float): Absolute time - timedelta: Relative time from now - datetime: Absolute date and time schedule_type (Optional[Literal['Default', 'WhenOnline']]): 'Default' uses schedule_time, 'WhenOnline' sends when user comes online (users only). base64 (str, optional): Base64 encoded video data. Returns: The API response containing the sent message details. ### `send_video_message(self: 'darkob.Client', chat: str, video_message: Union[Path, bytes]=None, text: Optional[str]=None, reply_to_message_id: Optional[Union[str, int]]=None, is_spoil: bool=False, via_bot: Optional[str]=None, thumb: Optional[Union[bool, str]]=None, width: Optional[int]=None, height: Optional[int]=None, time: Optional[int]=None, schedule_time: Optional[Union[int, float, timedelta, datetime]]=None, schedule_type: Optional[Literal['Default', 'WhenOnline']]=None, base64: str=None, **kwargs)` Send a video message (round video) to a chat. Parameters: chat (str): The GUID, link, or username of the chat. video_message (Path, bytes, optional): The video message data. Can be a file path or bytes. text (Optional[str]): Caption for the video message. Defaults to None. reply_to_message_id (Optional[Union[str, int]]): ID of the message to reply to. Defaults to None. is_spoil (bool): Whether the video message should be marked as a spoiler. Defaults to False. via_bot (Optional[str]): Bot GUID or username to send the message via. Defaults to None. thumb (Optional[Union[bool, str]]): Thumbnail behavior: - None or True: Auto-generate thumbnail using available libraries (or default). - str: Custom thumbnail as Base64 string. width (Optional[int]): Custom width for the video message. Defaults to None (auto-detect). height (Optional[int]): Custom height for the video message. Defaults to None (auto-detect). time (Optional[int]): Custom duration for the video message in seconds. Defaults to None (auto-detect). schedule_time (Optional[Union[int, float, timedelta, datetime]]): When to send the message. - Unix timestamp (int/float): Absolute time - timedelta: Relative time from now - datetime: Absolute date and time schedule_type (Optional[Literal['Default', 'WhenOnline']]): 'Default' uses schedule_time, 'WhenOnline' sends when user comes online (users only). base64 (str, optional): Base64 encoded video message data. Returns: The API response containing the sent message details. ### `send_voice(self: 'darkob.Client', chat: str, voice: Union[Path, bytes]=None, text: Optional[str]=None, reply_to_message_id: Optional[Union[str, int]]=None, via_bot: Optional[str]=None, time: Optional[int]=None, schedule_time: Optional[Union[int, float, timedelta, datetime]]=None, schedule_type: Optional[Literal['Default', 'WhenOnline']]=None, base64: str=None, **kwargs)` Send a voice message to a chat. Parameters: chat (str): The GUID, link, or username of the chat. voice (Path, bytes, optional): The voice data. Can be a file path or bytes. text (Optional[str]): Caption for the voice message. Defaults to None. reply_to_message_id (Optional[Union[str, int]]): ID of the message to reply to. Defaults to None. via_bot (Optional[str]): Bot GUID or username to send the message via. Defaults to None. time (Optional[int]): Custom duration for the voice message in seconds. Defaults to None (auto-detect). schedule_time (Optional[Union[int, float, timedelta, datetime]]): When to send the message. - Unix timestamp (int/float): Absolute time - timedelta: Relative time from now - datetime: Absolute date and time schedule_type (Optional[Literal['Default', 'WhenOnline']]): 'Default' uses schedule_time, 'WhenOnline' sends when user comes online (users only). base64 (str, optional): Base64 encoded voice data. Returns: The API response containing the sent message details. ### `send_voice_chat_activity(self: 'darkob.Client', chat: str, activity: Literal['Speaking']='Speaking', participant_chat_guid: str=None)` Set voice chat activity automatically. Parameters: chat (str): The GUID, link, or username of the group/channel. activity (str): Literal['Speaking'] and Default is `Speaking`. participant_chat_guid (str): Participant chat guid, Default is `self.guid`. Returns: The result of the API call. ### `set_admin(self: 'darkob.Client', chat: str, member: str, access: Union[List[str], str]=[], custom_title: str='')` Set a member as admin in a group or channel. Parameters: chat (str): The GUID, link, or username of group/channel. member (str): The GUID or username of member to set as admin. access (Union[List[str], str]): List of allowed permissions or single permission string. Can also be 'all' or 'All' to grant all permissions. custom_title (str): Custom title for admin in groups. (optional) Returns: Result of the operation. ### `set_ask_spam(self: 'darkob.Client', chat: str, action: Literal['AddToContact', 'BlockUser', 'Cancel', 'ReportAndLeave']='Cancel')` Perform an action for a pending spam request. Parameters: chat (str): The GUID, link, or username of the user, group, or channel. action (str): The action to apply: - For user (u0): 'AddToContact', 'BlockUser', 'Cancel'. - For group/channel (g0/c0): 'ReportAndLeave'. Returns: The result of the API call. ### `set_channel_link(self: 'darkob.Client', channel: str)` Set a custom link for the channel. Parameters: channel (str): The GUID of the channel. Returns: The result of the API call. ### `set_channel_type(self: 'darkob.Client', channel: str, channel_type: typing.Literal['Public', 'Private'])` Set type of a channel. Parameters: channel (str): The GUID, link, or username of the channel. channel_type (str): The new type of the channel. 'Public' or 'Private'. Returns: The result of the API call. ### `set_chat_auto_delete(self: 'darkob.Client', chat: Union[str, List[str]], auto_delete: Union[str, int])` Set auto-delete timer for one or more groups or channels. Parameters: chat (Union[str, List[str]]): The GUID, link, username of a group/channel, or a list of them. auto_delete (Union[str, int]): Auto-delete duration. Accepts: - Integer: 1-365 (days) - String: '1m'-'60m', '1h'-'24h', '1d'-'365d', '1w'-'52w', '1y', 'off' - Common words: 'day', 'week', 'month', 'year', 'never', 'disabled' Returns: The result of the API call. ### `set_chat_protected_content(self: 'darkob.Client', chat: str, enabled: bool)` Set the chat protected content setting. Parameters: chat (int): The GUID or username of the target chat. enabled (bool): Pass True to enable the protected content setting, False to disable. Returns: The result of the API call. ### `set_chat_use_time(self: 'darkob.Client', chat: str, use_time: int)` Send chat usage time to the server. This helps the server recognize natural user behavior and can reduce rate limiting and bot detection. Parameters: chat (str): The GUID, link, or username of the chat. use_time (int): Time spent in the chat in seconds. Returns: The result of the API call. ### `set_current_live_location(self: 'darkob.Client', longitude: float, latitude: float, tile_side_count: int, tile_urls: List[str], x_loc: float, y_loc: float)` Set the current live location. Parameters: longitude (float): Longitude coordinate. latitude (float): Latitude coordinate. tile_side_count (int): Number of tiles per side. tile_urls (List[str]): URLs of map tiles. x_loc (float): X position on the map. y_loc (float): Y position on the map. Returns: The result of the API call. ### `set_group_default_access(self: 'darkob.Client', group: str, access: Union[str, list])` Set default access for a group. Parameters: group (str): The GUID or link of the group. access (Union[str, list]): List of allowed actions. Must be one or more of: - "ViewMembers": Allows viewing group members. - "ViewAdmins": Allows viewing group admins. - "SendMessages": Allows sending messages. - "AddMember": Allows adding members. If only specific actions are listed (e.g. ["SendMessages"]), ONLY those are enabled and others are disabled. If empty list "[]", ALL access permissions are disabled/closed. Returns: The result of the API call. ### `set_group_link(self: 'darkob.Client', group: str)` Set private link for group. Parameters: group (str): The GUID or link of the group. Returns: The result of the API call. ### `set_notification(self: 'darkob.Client', user_notification: Optional[bool]=None, user_message_preview: Optional[bool]=None, group_notification: Optional[bool]=None, group_message_preview: Optional[bool]=None, channel_notification: Optional[bool]=None, channel_message_preview: Optional[bool]=None, in_app_sound: Optional[bool]=None, in_app_preview: Optional[bool]=None, new_contacts: Optional[bool]=None)` Update notification settings. Parameters: user_notification (bool, optional): Enable/disable user notifications. user_message_preview (bool, optional): Show/hide user message preview. group_notification (bool, optional): Enable/disable group notifications. group_message_preview (bool, optional): Show/hide group message preview. channel_notification (bool, optional): Enable/disable channel notifications. channel_message_preview (bool, optional): Show/hide channel message preview. in_app_sound (bool, optional): Enable/disable in-app sound. in_app_preview (bool, optional): Enable/disable in-app preview. new_contacts (bool, optional): Enable/disable new contacts notification. Returns: The updated notification settings. ### `set_saved_music_playlist(self: 'darkob.Client', files: Union[Path, str, List[Union[Path, str]]]=None, file_inlines: List[dict]=None, time: Optional[int]=None, performer: Optional[str]=None, file_name: Optional[str]=None, **kwargs)` Replace the saved music playlist on your profile. Parameters: files: A single file path or a list of file paths to music files. file_inlines: Pre-uploaded file_inline dicts to set directly. time: Custom duration in seconds. If not provided, auto-detected. performer: Custom performer name. If not provided, auto-detected. file_name: Custom file name. If not provided, uses original file name. Returns: The result of the API call. ### `set_setting(self: 'darkob.Client', show_my_last_online: Optional[PrivacyValue]=None, show_my_phone_number: Optional[PrivacyValue]=None, show_my_profile_photo: Optional[PrivacyValue]=None, link_forward_message: Optional[PrivacyValue]=None, can_join_chat_by: Optional[PrivacyValue]=None, show_my_birth_date: Optional[PrivacyValue]=None, can_called_by: Optional[PrivacyValue]=None, auto_delete_messages: Optional[Union[str, int]]=None, inactive_account_delete: Optional[int]=None, show_my_last_online_exceptions: Optional[Dict[str, List[str]]]=None, show_my_phone_number_exceptions: Optional[Dict[str, List[str]]]=None, show_my_profile_photo_exceptions: Optional[Dict[str, List[str]]]=None, can_join_chat_by_exceptions: Optional[Dict[str, List[str]]]=None, show_my_birth_date_exceptions: Optional[Dict[str, List[str]]]=None, can_called_by_exceptions: Optional[Dict[str, List[str]]]=None)` Set various privacy and auto-delete settings for the user. Parameters: Privacy Settings (accept: 'Everybody', 'MyContacts', 'Nobody'): show_my_last_online: Who can see your last online status show_my_phone_number: Who can see your phone number show_my_profile_photo: Who can see your profile photo link_forward_message: Who can forward your message links can_join_chat_by: Who can join your chats by link show_my_birth_date: Who can see your birth date can_called_by: Who can call you Exceptions (for privacy settings except link_forward_message): Each exception should be a dict with: - 'include_users': List[str] - Users to always allow - 'exclude_users': List[str] - Users to always deny To CLEAR exceptions for a setting, pass {'exclude_users': []}: can_called_by_exceptions={'exclude_users': []} Example: show_my_last_online_exceptions={ 'include_users': ['u0abc123...'], 'exclude_users': ['u0xyz789...'] } Auto Delete Messages: auto_delete_messages: Message auto-delete duration. Delete Inactive Account: inactive_account_delete: Delete account after X months. Returns: The result of the setting operation. ### `set_two_step_verification(self: 'darkob.Client', password: Union[int, str], hint: str=None, recovery_email: str=None)` Set up two-step verification for the user. Parameters: password (Union[int, str]): The current user password. hint (str): A hint to help remember the password. Defaults to None. recovery_email (str): The recovery email for two-step verification. Defaults to None. Returns: The updated user information after setting up two-step verification. ### `set_voice_chat_setting(self: 'darkob.Client', chat: str, title: str=None, join_muted: bool=None)` Set voice chat settings for group or channel. Parameters: chat (str): The GUID, link, or username of the group/channel. title (str, optional): New title for voice chat. join_muted (bool, optional): Whether new participants join muted. (Only for groups) Returns: The result of the API call. ### `set_voice_chat_state(self: 'darkob.Client', chat: str, action: typing.Literal['Mute', 'Unmute', 'RequestSpeak', 'CancelRequestSpeak']='Unmute', participant_chat_guid: str=None)` Set group or channel voice chat state automatically. Parameters: chat (str): The GUID, link, or username of the group/channel. action (str): Literal['Mute', 'Unmute'] and Default is `Unmute`. participant_chat_guid (str): Participant chat guid, Default is `self.guid`. Returns: The result of the API call. ### `sign_in(self: 'darkob.Client', phone_number: str, phone_code: str, phone_code_hash: str, public_key: str)` Sign in using the verification code. Parameters: phone_number (str): The phone number. phone_code (str): The verification code. phone_code_hash (str): The verification code hash. public_key (str): The client's public key. Returns: The result of the API call. ### `speaking(self: 'darkob.Client', chat_guid: str)` _No docstring._ ### `start(self: 'darkob.Client', phone_number: str=None)` Start the client, handling authentication and registration. Parameters: phone_number (str, optional): Phone number for registration. Returns: Client: The initialized client instance. ### `start_bot(self: 'darkob.Client', bot: str)` Parameters: bot (str): The GUID or username of the bot. Returns: The result of the API call. ### `start_voice_chat(self: 'darkob.Client', chat: str)` Start a voice chat for a channel or group. Parameters: chat (str): The GUID, link, or username of the channel/group. Returns: The result of the API call. ### `stop(self)` _No docstring._ ### `stop_bot(self: 'darkob.Client', bot: str)` Parameters: bot (str): The GUID or username of the bot. Returns: The result of the API call. ### `stop_poll(self: 'darkob.Client', poll_id: str)` Stop a poll. Parameters: poll_id (str): The ID of the poll to stop. Returns: The result of the API call. ### `terminate_other_sessions(self: 'darkob.Client')` Terminate other account sessions. Returns: The result of the API call. ### `terminate_session(self: 'darkob.Client', session_key: str)` Terminate a user session. Parameters: session_key (str): The session key of the session to be terminated. Returns: The result of the API call. ### `transcribe_voice(self: 'darkob.Client', chat: Union[str, int], message_id: Union[str, int])` Transcribes voice messages. Parameters: chat (str): The GUID, link, or username of the chat (chat, channel, or group) containing the voice message. message_id (str): The ID of the voice message. Returns: The transcription result. ### `turn_off_two_step(self: 'darkob.Client', password: str)` Turn off two-step verification passcode for the account. Parameters: password (str): Current two-step verification password Returns: Result of the operation. ### `unarchive_chat(self: 'darkob.Client', chat: str)` Unarchive a chat. Parameters: chat (str): The GUID, link, or username of the chat to unarchive. Returns: Result of the operation. ### `unban_all_members(self: 'darkob.Client', chat: str, exclude: Optional[Union[str, List[str]]]=None)` Unban all banned members in a group or channel. Parameters: chat (str): The GUID, link, or username of the group or channel. exclude (Optional[Union[str, List[str]]]): Member GUID(s) or username(s) to exclude from unban. Default is None. Returns: Result of unban operation. ### `unban_member(self: 'darkob.Client', chat: str, member: str)` Unban a member from a group or channel. Parameters: chat (str): The GUID, link, or username of group/channel. member (str): The GUID or username of member to unban. Returns: Result of the operation. ### `unban_members(self: 'darkob.Client', chat: str, members: List[str])` Unban multiple members from a group or channel. Parameters: chat (str): The GUID, link, or username of group/channel. members (List[str]): List of GUIDs or usernames of members to unban. Returns: Results of all operations. ### `unblock_all_users(self: 'darkob.Client', exclude: Optional[Union[str, List[str]]]=None)` Unblock all blocked users. Parameters: exclude (Optional[Union[str, List[str]]]): User GUID(s) or username(s) to exclude from unblock. Default is None. Returns: Result of unblock operation. ### `unblock_user(self: 'darkob.Client', user: str)` Unblock a user. Parameters: user (str): The GUID or username of the user to unblock. Returns: The result of the unblock operation. ### `unlock_group(self: 'darkob.Client', group: str)` Unlock a group by enabling SendMessage access. Parameters: group (str): The GUID or link of the group. Returns: Result message. ### `unmute_chat(self: 'darkob.Client', chat: str)` Unmute a chat. Parameters: chat (str): The GUID, link, or username of the chat to unmute. Returns: Result of the operation. ### `unpin_all_messages(self: 'darkob.Client', chat: str)` Unpin all pinned messages in a group, channel, or private chat. Parameters: chat (str): The GUID, link, or username of the chat. Returns: The update indicating the success of the operation. ### `unpin_chat(self: 'darkob.Client', chat: str)` Unpin a chat. Parameters: chat (str): The GUID, link, or username of the chat to unpin. Returns: Result of the operation. ### `unpin_chat_in_folder(self: 'darkob.Client', chat: str, folder_id: str)` Unpin a chat from a folder. Parameters: chat (str): The GUID, link, or username of the chat to unpin. folder_id (str): The folder ID to unpin the chat from. Returns: The result of the API call. ### `unpin_message(self: 'darkob.Client', chat: str, message_id: Union[str, int])` unpin a message. Parameters: chat (str): The GUID, link, or username of the chat. message_id (Union[str, int]): The ID of the message to unpin. Returns: The update indicating the success of the operation. ### `unset_admin(self: 'darkob.Client', chat: str, member: str)` Unset a member as admin in a group or channel. Parameters: chat (str): The GUID, link, or username of group/channel. member (str): The GUID or username of member to unset as admin. Returns: Result of the operation. ### `update_channel_username(self: 'darkob.Client', channel: str, username: str)` Update the username of a channel. Parameters: channel (str): The GUID or username of the channel. username (str): The new username for the channel. Must be between 7 and 32 characters Can only contain English letters (a-z, A-Z), numbers (0-9), and underscore (_) Should not start with number or underscore Should not end with underscore Returns: The result of the API call. ### `update_my_bio(self: 'darkob.Client', bio: str)` Update user's biography. Parameters: bio (str): The updated biography (max 150 characters). Returns: The updated user information. Raises: InvalidInput: If bio exceeds 150 characters. ### `update_my_birthday(self: 'darkob.Client', birthday: Union[str, datetime])` Update the birthday in your profile. Parameters: birthday (str | datetime): Birthday in format YYYY-MM-DD (e.g., "2026-02-03") or a datetime object. Returns: The updated user information. ### `update_my_name(self: 'darkob.Client', first_name: Optional[str]=None, last_name: Optional[str]=None)` Update user's first name and/or last name. Parameters: first_name (Optional[str]): The updated first name (max 30 characters). last_name (Optional[str]): The updated last name (max 50 characters). Returns: The updated user information. ### `update_my_profile(self: 'darkob.Client', first_name: Optional[str]=None, last_name: Optional[str]=None, bio: Optional[str]=None, birthday: Optional[str]=None, location: Optional[Dict[str, Union[float, Dict[str, Union[int, List[str], float]]]]]=None)` Update user profile information. Parameters: first_name (Optional[str]): The updated first name. last_name (Optional[str]): The updated last name. bio (Optional[str]): The updated biography. birthday (str): Birthday in format YYYY-MM-DD (e.g., "2026-07-05"). location (Optional[dict]): Location information containing: - longitude (float): Longitude coordinate. - latitude (float): Latitude coordinate. - map_view (dict): Map view details with: - tile_side_count (int): Number of tile sides. - tile_urls (List[str]): List of tile URLs. - x_loc (float): X location on map. - y_loc (float): Y location on map. Returns: The updated user information after the profile update. ### `update_my_username(self: 'darkob.Client', username: str)` Update the username of the user. Parameters: username (str): The new username for the user. - Must be between 7 and 32 characters - Can only contain English letters (a-z, A-Z), numbers (0-9), and underscore (_) - Should not start with number or underscore - Should not end with underscore Returns: The updated user information. ### `upgrade_to_api6(self: 'darkob.Client', save_as: bool=True, file_name: Optional[str]=None)` Upgrade from API v5 to v6 by setting an RSA public key. This allows old v5 auth keys to be used with API v6. After upgrade, save the returned private_key for future v6 logins. Parameters: save_as (bool): If True (default), saves auth and private_key to a JSON file. file_name (str, optional): Custom file name for the JSON file. Defaults to 'darkob_{auth[:10]}'. Returns: Data: Response with status, message, auth, and private_key. ### `upload_avatar(self: 'darkob.Client', chat: str, main_image: Union[Path, str, bytes], thumbnail_image: Optional[Union[Path, str, bytes]]=None, *args, **kwargs)` Uploads an avatar image for a specified chat (user, group, or channel). Parameters: chat (str): The GUID, link, or username of the chat for which the avatar is being uploaded. main_image (Union[Path, str, bytes]): The image file or bytes to be used as the avatar. thumbnail_image (Optional[Union[Path, str, bytes]]): The image file or bytes of the thumbnail image. Returns: The result of the avatar upload operation. Note: If `chat` is 'me', 'cloud', or 'self', it will be replaced with the client's GUID. If `main_image` is a string or Path (path to a file), the file name is extracted from the path. Otherwise, a default file name ('darkob.jpg') is used. The `upload_file` method is used internally to handle the file upload process. ### `upload_file(self: 'darkob.Client', file: Union[str, bytes, None]=None, base64_data: Optional[str]=None, mime: Optional[str]=None, file_name: Optional[str]=None, chunk: int=1048576, callback: Optional[Callable[[int, int], Union[None, asyncio.Future]]]=None, *args, **kwargs)` Upload a file to Rubika with chunked transfer and retry logic. Parameters: file (str, bytes, or None): File path, bytes, or URL to upload. base64_data (str, optional): Base64 encoded file data. mime (str, optional): MIME type of the file. file_name (str, optional): Name of the file. chunk (int, optional): Chunk size in bytes (default: 1MB). callback (callable, optional): Progress callback(total_size, uploaded_bytes). Returns: Metadata about the uploaded file. ### `verify_change_phone_number(self: 'darkob.Client', code: Union[str, int], hash: str)` Verify phone number change with the received code. Parameters: code (str): The verification code sent to the new phone number. hash (str): The hash received from request_change_phone_number. Returns: The result of the API call. ### `verify_recovery_email(self: 'darkob.Client', password: str, code: Union[str, int])` Verify the recovery code sent to the recovery email. Parameters: password (str): User's current password. code (Union[str, int]): The verification code received in email. Can be a string or an integer. Returns: The result of the API call. ### `view_chat_ads(self: 'darkob.Client', chat_ads_id: str)` Register a view action on a chat ad. The `chat_ads_id` is obtained from the `get_chat_ads` method. Parameters: chat_ads_id (str): The chat ads ID to register a view on. Returns: The result of the operation. ### `vote_poll(self: 'darkob.Client', poll_id: str, selection_index: Union[str, int])` Vote on a poll option. Parameters: poll_id (str): The ID of the poll. selection_index (Union[str, int]): The index of the option to vote for. Returns: The update indicating the success of the vote. ## Shad (325 methods) ### `abort_two_step_setup(self: 'darkob.Client')` Abort the two-step verification setup process. Returns: The result of the operation. ### `accept_all_join_requests(self: 'darkob.Client', chat: str, exclude: Optional[Union[str, List[str]]]=None)` Accept all pending join requests in a group or channel. Parameters: chat (str): The GUID, link, or username of the group or channel. exclude (Optional[Union[str, List[str]]]): User GUID(s) or username(s) to exclude. Returns: Result containing accepted count and details. ### `accept_join_request(self: 'darkob.Client', chat: str, user: str)` Accept a join request for a group or channel. Parameters: chat (str): The GUID, link, or username of the group/channel. user (str): The user GUID or username of the requester. Returns: The result of the API call. ### `accept_ownership_request(self: 'darkob.Client', chat: str)` Accept an ownership transfer request. Parameters: chat (str): The GUID, link, or username of the chat (channel/group). Returns: The result of the API call. ### `add_contact(self: 'darkob.Client', phone_number: Union[str, int], first_name: str, last_name: str='')` Adds a contact to the client's address book. Parameters: phone_number (str): The phone number of the contact to be added. first_name (str): The first name of the contact. last_name (str, optional): The last name of the contact. Defaults to an empty string. Returns: The result of the API call. Note: The `phone_number` parameter should be a valid phone number. The `first_name` and `last_name` parameters represent the name of the contact. If the contact has no last name, `last_name` can be an empty string. ### `add_folder(self: 'darkob.Client', name: str, include_chats: Optional[Union[str, List[str]]]=None, exclude_chats: Optional[Union[str, List[str]]]=None, include_chat_types: Optional[List[str]]=None, exclude_chat_types: Optional[List[str]]=None, is_add_to_top: bool=True, suggestion_folder_id: str=None, folder_id: str=None)` Add a new folder to organize chats. Parameters: name (str): Folder name. include_chats: Chats (GUIDs, links, usernames) to include in folder. exclude_chats: Chats (GUIDs, links, usernames) to exclude from folder. include_chat_types: Chat types to include (case-insensitive). Valid values: 'Contacts', 'NonContacts' / 'Users', 'Groups', 'Channels', 'Bots', 'Services'. Note: 'Users' expands to both 'Contacts' and 'NonContacts'. exclude_chat_types: Chat types to exclude (case-insensitive). Valid values: 'Mute', 'Read', 'Archive'. is_add_to_top (bool): Add folder to top of list. suggestion_folder_id (str): Suggestion folder ID. folder_id (str): Folder ID. Returns: The result of the API call. ### `add_handler(self: 'darkob.Client', func: Callable, handler: Union[ChatUpdates, MessageUpdates, ShowActivities, ShowNotifications, RemoveNotifications])` _No docstring._ ### `add_live_comment(self: 'darkob.Client', access_token: str, live_id: str, comment: str)` Adds a comment to a live stream. Parameters: access_token (str): The access token for authentication. live_id (str): The ID of the live stream. comment (str): The text of the comment. Returns: The result of the API call. ### `add_members(self: 'darkob.Client', chat: str, members: Union[str, List[str]])` Add members to a channel or group. Parameters: chat (str): The GUID, link, or username of the channel/group. members (Union[str, List[str]]): The GUID(s) or username(s) of the member(s) to be added. Returns: The result of the API call. ### `add_reaction(self: 'darkob.Client', chat: str, message_id: Union[str, int], reaction_id: Union[int, str])` Add a reaction to a specific message. Parameters: chat (str): The GUID, link, or username of the chat associated with the message. message_id (Union[str, int]): The ID of the message to which the reaction will be added. reaction_id (Union[str, int]): The ID of the reaction to be added. Returns: The result of the API call. ### `add_saved_music_playlist(self: 'darkob.Client', files: Union[Path, str, List[Union[Path, str]]]=None, file_inlines: List[dict]=None, time: Optional[int]=None, performer: Optional[str]=None, file_name: Optional[str]=None, **kwargs)` Add a saved music playlist on your profile. Parameters: files: A single file path or a list of file paths to music files. file_inlines: Pre-uploaded file_inline dicts to add directly. time: Custom duration in seconds. If not provided, auto-detected. performer: Custom performer name. If not provided, auto-detected. file_name: Custom file name. If not provided, uses original file name. Returns: The result of the API call. ### `add_saved_music_track(self: 'darkob.Client', track: Union[Path, str]=None, file_inline: dict=None, time: Optional[int]=None, performer: Optional[str]=None, file_name: Optional[str]=None, **kwargs)` Add a single music track to your saved music playlist. Parameters: track: A file path (str or Path) to a music file, or raw bytes. file_inline: A pre-uploaded file_inline dict to add directly. time: Custom duration in seconds. If not provided, auto-detected. performer: Custom performer name. If not provided, auto-detected. file_name: Custom file name. If not provided, uses original file name. Returns: The result of the API call. ### `add_sticker_set(self: 'darkob.Client', sticker_set_id: str)` Add a sticker set. Parameters: sticker_set_id (str): The ID of the sticker set. Returns: The result of the API call. ### `add_to_my_gif_set(self: 'darkob.Client', chat: str, message_id: Union[str, int])` Adds a GIF message to the user's personal GIF set. Parameters: chat (str): The GUID, link, or username of the chat. message_id (Union[str, int]): The ID of the GIF message. Returns: The result of the API call. ### `archive_chat(self: 'darkob.Client', chat: str)` Archive a chat. Parameters: chat (str): The GUID, link, or username of the chat to archive. Returns: The result of the API call. ### `archive_sticker_set(self: 'darkob.Client', sticker_set_id: str)` Archive a sticker set. Parameters: sticker_set_id (str): The ID of the sticker set. Returns: The result of the API call. ### `ask(self, chat_id: str, text: Optional[str]=None, *, filters: Optional[list]=None, timeout: float=60.0, inline_keypad: Any=None, chat_keypad: Any=None)` Send a prompt and await the next matching reply in that chat. The reply is returned to you instead of being dispatched to handlers while the prompt is pending. ### `auto_delete_account(self: 'darkob.Client', setting: Union[int, str])` Set account auto-deletion after months of inactivity. Parameters: setting (Union[int, str]): Months of inactivity. Accepts: 3, 6, 12, or 24. Can be int (3, 6, 12, 24) or str ("3", "6", "12", "24", "3m", "6m", "12m", "24m") Returns: The updated privacy settings. Examples: >>> await client.auto_delete_account(6) # doctest: +SKIP >>> await client.auto_delete_account("12m") # doctest: +SKIP ### `auto_delete_message(self: 'darkob.Client', chat: str, message_id: Union[str, int], time: Union[float, int])` Automatically delete a message after a specified time. Parameters: chat (str): The GUID, link, or username of the chat associated with the message (e.g., user, group, channel). message_id (Union[str, int]): The ID of the message to be deleted. time (Union[float, int]): The time delay (in seconds) before deleting the message. Returns: The updated information after deleting the message. ### `ban_member(self: 'darkob.Client', chat: str, member: str)` Ban a member from a group or channel. Parameters: chat (str): The GUID, link, or username of group/channel. member (str): The GUID or username of member to ban. Returns: Result of the operation. ### `ban_members(self: 'darkob.Client', chat: str, members: List[str])` Ban multiple members from a group or channel. Parameters: chat (str): The GUID, link, or username of group/channel. members (List[str]): List of GUIDs or usernames of members to ban. Returns: Results of all operations. ### `block_user(self: 'darkob.Client', user: str)` Block a user. Parameters: user (str): The GUID or username of the user to block. Returns: The result of the block operation. ### `cancel_change_owner(self: 'darkob.Client', chat: str)` Cancels a pending ownership transfer request for a channel or group. Parameters: chat (str): The GUID, link, or username of the chat (channel/group). Returns: The result of the API call. ### `change_owner(self: 'darkob.Client', chat: str, new_owner: str)` Request to transfer ownership of a chat to another user. Parameters: chat (str): The GUID, link, or username of the chat (channel/group). new_owner (str): The GUID or username of the user to become new owner. Returns: The result of the API call. Note: - Only works if you are the current owner - New owner must accept the request - Irreversible action ### `change_password(self: 'darkob.Client', password: str, new_password: str, new_hint: str)` Changes the user's password. Parameters: password (str): The current password. new_password (str): The new password. new_hint (str): The new password hint. Returns: The result of the API call. ### `check_channel_username(self: 'darkob.Client', username: str)` Check the availability of a username for a channel. Parameters: username (str): The username to check. Returns: The result of the API call. ### `check_join(self: 'darkob.Client', chat: str, member: str)` Check if a user or bot is a member of a specific group or channel. Parameters: chat (str): The GUID, link, or username of the chat to check. member (str): The GUID or username of the user/bot to check. Returns: bool: True if user/bot is a member, False otherwise. ### `check_two_step_passcode(self: 'darkob.Client', password: str)` Check if the provided two-step verification password is correct. Parameters: password (str): The two-step verification password to check. Returns: Result containing status and user data if successful. ### `check_user_username(self: 'darkob.Client', username: str)` Check the availability of a username for a user. Parameters: username (str): The username to be checked. Returns: The result of the username availability check. ### `clear_all_drafts(self: 'darkob.Client')` Clear all drafts. Returns: The result of the API call. ### `clear_black_list(self: 'darkob.Client', chat: str, exclude: Optional[Union[str, List[str]]]=None)` Clear black list with unban all banned members in a group or channel. Parameters: chat (str): The GUID, link, or username of the group or channel. exclude (Optional[Union[str, List[str]]]): Member GUID(s) or username(s) to exclude from unban. Default is None. Returns: Result of unban operation. ### `clear_chat_draft(self: 'darkob.Client', chat: str)` Clear the draft of a specific chat. Parameters: chat (str): The GUID, link, or username of the chat. Returns: The result of the API call. ### `click_chat_ads(self: 'darkob.Client', chat_ads_id: str)` Register a click action on a chat ad. The `chat_ads_id` is obtained from the `get_chat_ads` method. Parameters: chat_ads_id (str): The chat ads ID to register a click on. Returns: The result of the operation. ### `click_inline_button(self: 'darkob.Client', chat: str, message_id: Union[str, int], button_id: str)` Send API call response to a chat's inline keypad button. Parameters: chat (str): The GUID, link, or username of the chat. message_id (Union[str, int]): The ID of the message containing inline keyboard. button_id (str): The ID of the button. Returns: The result of the API call. ### `click_keypad_button(self: 'darkob.Client', chat: str, button_id: str)` Click a button in the chat keypad. Parameters: chat (str): The GUID, link, or username of the chat (must be a bot). button_id (str): The button ID to click. Returns: The result of the button click. ### `click_message_url(self: 'darkob.Client', chat: str, message_id: typing.Union[str, int], link_url: str)` Simulate clicking a URL contained within a specific message. Parameters: chat (str): The GUID, link or username of the chat. message_id (Union[str, int]): The unique ID of the message that includes the URL. link_url(str): The URL string embedded in the message to be clicked. Returns: The result of the API call. ### `close(self: 'darkob.Client')` Close the connection to the Darkob server (async version). ### `confirm_unconfirmed_session(self: 'darkob.Client', unconfirmed_session_key: str)` Confirm an unconfirmed (pending) session. Parameters: unconfirmed_session_key (str): The session key to confirm. Returns: The result of the API call. ### `connect(self: 'darkob.Client')` Establish a connection to the Rubika API. Creates an Api instance and loads stored session information (auth, guid, private_key, user_agent) if available. Returns: Client instance with active connection. ### `create_channel(self: 'darkob.Client', title: str, members: Optional[Union[str, list]]=None, channel_type: str='Public', description: Optional[str]=None, avatar: Optional[Union[Path, str, bytes]]=None, thumbnail_avatar: Optional[Union[Path, str, bytes]]=None, *args, **kwargs)` Create a new channel. Parameters: title (str): The title of the new channel. members (Union[str, list], optional): The GUID(s) or username(s) of the member(s) to be added to the new channel. Default is None. channel_type (str): Set type of the channel. 'Public' or 'Private'. Default is 'Public'. description (str, optional): The description of the new channel. Default is None. avatar (Optional[Union[Path, str, bytes]]): The image to be used as the channel avatar. Default is None. thumbnail_avatar (Optional[Union[Path, str, bytes]]): The image to be used as the channel thumbnail avatar. Default is None. Returns: The result of the API call. Note: If only `avatar` is provided, the thumbnail is taken from the same image. If none of them are provided, no avatar is set for the channel. ### `create_group(self: 'darkob.Client', title: str, members: Union[str, List[str]], description: Optional[str]=None, avatar: Optional[Union[Path, str, bytes]]=None, thumbnail_avatar: Optional[Union[Path, str, bytes]]=None, *args, **kwargs)` Create a new group. Parameters: title (str): The title of the group. members (Union[str, List[str]]): A single member GUID/Username or a list of member GUIDs/Usernames to be added to the group. description (Optional[str]): Description of the group (optional). Defaults to None. avatar (Optional[Union[Path, str, bytes]]): The image to be used as the group avatar. Default is None. thumbnail_avatar (Optional[Union[Path, str, bytes]]): The image to be used as the group thumbnail avatar. Default is None. Returns: The result of the API call. Note: If only `avatar` is provided, the thumbnail is taken from the same image. If none of them are provided, no avatar is set for the group. ### `create_join_link(self: 'darkob.Client', chat: str, expire_time: Optional[int]=None, request_needed: bool=False, title: Optional[str]=None, usage_limit: int=0)` Creates an invite link for a group or channel. Parameters: chat (str): The GUID, link, or username of the target group or channel. expire_time (Optional[int]): The expiration time of the link in seconds. request_needed (bool): Whether join requests must be approved manually. title (Optional[str]): A custom title for the invite link. usage_limit (int): The maximum number of times the link can be used. Returns: The API response containing the created invite link. ### `delete_account(self: 'darkob.Client')` Request to permanently delete your Rubika account. Returns: str: User-friendly confirmation message. ### `delete_all_avatars(self: 'darkob.Client', chat: str)` Delete all avatars from a chat or user profile. Parameters: chat (str): The GUID, link, or username of the chat. Returns: Data: Result of the operation. Note: If `chat` is 'me', 'cloud', 'self', or 'myself', it will be replaced with the client's GUID. ### `delete_all_messages(self: 'darkob.Client', chat: str, exclude_message_ids: Optional[Union[str, int, List[Union[str, int]]]]=None)` Delete all messages in a chat except the first creation event message and optionally specified message IDs. This method retrieves all messages from the chat and deletes them, while preserving: - Any message IDs specified in `exclude_message_ids`. Parameters: chat (str): The GUID, link, or username of the chat exclude_message_ids (Union[str, int, List[Union[str, int]]], optional): Message ID(s) to preserve (not delete). Can be string, integer, or list. Default is None. Returns: Result of the deletion operation. ### `delete_all_my_gif_set(self: 'darkob.Client')` Delete all GIFs from the user's personal GIF set. Returns: Data: A Data object containing the deletion result. ### `delete_avatar(self: 'darkob.Client', chat: str, avatar_id: str)` Delete an avatar. Parameters: chat (str): The GUID, link, or username of the chat that owns the avatar. avatar_id (str): The identifier of the avatar to be deleted. Returns: The result of the API call. Note: If `chat` is 'me', 'cloud', 'self', or 'myself', it will be replaced with the client's GUID. ### `delete_bot_chat(self: 'darkob.Client', bot: str)` Delete a bot chat. Parameters: bot (str): The GUID or username of the bot. Returns: The result of the API call. ### `delete_channel(self: 'darkob.Client', channel: str, confirm: bool=True)` Delete a channel. Parameters: channel (str): The GUID, link, or username of the channel. confirm (bool): If True, ask the user for confirmation before deleting the channel. If False, delete immediately. Default is True. Returns: The result of the API call. Exits if cancelled. ### `delete_chat_history(self: 'darkob.Client', chat: str)` Delete chat history up to the last message. Parameters: chat (str): The GUID, link, or username of the chat (e.g., user, group). Returns: The result of the API call. ### `delete_contact(self: 'darkob.Client', user: str)` Deletes a contact from the client's address book. Parameters: user (str): The GUID or username of the contact to be deleted. Returns: The result of the contact deletion operation. Note: - The `user` parameter should be the GUID or username of the contact to be deleted. ### `delete_folder(self: 'darkob.Client', folder_id: str)` Delete a folder. Parameters: folder_id (str): The ID of the folder to be deleted. Returns: Result of the delete folder operation. ### `delete_group(self: 'darkob.Client', group: str, confirm: bool=True)` Delete a group. Parameters: group (str): The GUID or link of the group. confirm (bool): If True, ask the user for confirmation before deleting the group. If False, delete immediately. Default is True. Returns: The result of the API call. Exits if cancelled. ### `delete_messages(self: 'darkob.Client', chat: str, message_ids: Union[str, int, list], type: Literal['Local', 'Global', 'Scheduled']='Global')` Delete specified messages associated with the given chat. Parameters: chat (str): The GUID, link, or username of the chat associated with the messages (e.g., user, group, channel). message_ids (Union[str, int, list]): The ID or list of IDs of the messages to be deleted. type (str): The type of deletion, can be 'Global', 'Local', or 'Scheduled'. Default is 'Global'. Returns: The updated information after deleting the messages. ### `delete_my_gif_set(self: 'darkob.Client', file_id: str)` Deletes a GIF from the user's personal GIF set. Parameters: file_id (str): The file ID of the GIF to be removed. Returns: The result of the API call. ### `delete_my_messages(self: 'darkob.Client', chat: str, exclude_message_ids: Optional[Union[str, int, List[Union[str, int]]]]=None)` Delete all messages sent by the authenticated user in a chat. Parameters: chat (str): The GUID, link, or username of the chat. exclude_message_ids (Optional[Union[str, int, List[Union[str, int]]]]): Message ID(s) to exclude from deletion (preserve them). Default is None. Returns: Result of the deletion operation. ### `delete_saved_music_playlist(self: 'darkob.Client', position: int=None)` Delete tracks from the saved music playlist on your profile. Parameters: position (int, optional): The position of the track to delete. If None, deletes all. Returns: The result of the API call. ### `delete_service_chat(self: 'darkob.Client', service: str)` Delete a service chat. Parameters: service (str): The GUID of the service chat to delete. Returns: The result of the API call. ### `delete_sticker_set(self: 'darkob.Client', sticker_set_id: str)` Delete a sticker set. Parameters: sticker_set_id (str): The ID of the sticker set. Returns: The result of the API call. ### `delete_user_chat(self: 'darkob.Client', user: str)` Delete a user chat. Parameters: user (str): The GUID or username of the user whose chat is to be deleted. Returns: The result of the user chat deletion. ### `deny_unconfirmed_session(self: 'darkob.Client', unconfirmed_session_key: str)` Deny an unconfirmed (pending) session. Parameters: unconfirmed_session_key (str): The session key to deny. Returns: The result of the API call. ### `discard_call(self: 'darkob.Client', call_id: str, duration: int=0, reason: str='Disconnect')` Discard/end an active call. Parameters: call_id (str): ID of the call to discard duration (int): Call duration in seconds reason (str): Reason for ending the call. Common options: 'Missed' and 'Disconnect'. Default: 'Disconnect' Returns: Result of the discard operation. ### `discard_voice_chat(self: 'darkob.Client', chat: str)` Discard/End a voice chat for a channel or group. Parameters: chat (str): The GUID, link, or username of the channel or group. Returns: The result of the API call. ### `disconnect(self: 'darkob.Client')` Disconnect from the Darkob server (sync version). ### `dont_show_chat_ads(self: 'darkob.Client', chat_ads_id: str)` Register a 'don't show' action on a chat ad. The `chat_ads_id` is obtained from the `get_chat_ads` method. Parameters: chat_ads_id (str): The chat ads ID to hide. Returns: The result of the operation. ### `download_file(self: 'darkob.Client', file_inline: Optional[Union[dict, Data]]=None, dc_id: Optional[int]=None, file_id: Optional[int]=None, access_hash: Optional[str]=None, size: Optional[int]=None, chunk: int=131072, callback: Optional[Callable[[int, int], Union[None, asyncio.Future]]]=None, gather: bool=False, save_as: Optional[Union[str, bool]]=None, file_name: Optional[str]=None, as_base64: bool=False, *args, **kwargs)` Download a file from Rubika/Shad. Parameters: file_inline (dict or Data, optional): File inline object from messages. If provided, dc_id, file_id, access_hash, size will be extracted. dc_id (int, optional): Data center ID (if file_inline not provided). file_id (int, optional): Unique identifier of the file. access_hash (str, optional): Access hash associated with the file. size (int, optional): Total size of the file in bytes. chunk (int, optional): Size of each download chunk (default: 131072). callback (callable, optional): Progress callback(total_size, downloaded_size). gather (bool, optional): Download chunks in parallel (default: False). save_as (str or bool, optional): Directory path or True for current dir. If None, returns bytes. file_name (str, optional): Custom file name. as_base64 (bool, optional): Return as base64 encoded string (default: False). Returns: bytes, str, or Data: File content (bytes), base64 string, or Data object (when save_as used). ### `download_profile_picture(self: 'darkob.Client', chat: Optional[str]=None, file_id: Optional[str]=None, access_hash_rec: Optional[str]=None, dc_id: Optional[str]=None, save_as: Optional[Union[str, bool]]=None, save_all: bool=False)` Download the profile picture of a user, group, or channel. Parameters: chat (str, optional): The GUID, link, or username of the user, group, channel, or other chats. file_id (str, optional): Direct file_id for download without fetching avatars. access_hash_rec (str, optional): Direct access_hash_rec for download without fetching avatars. dc_id (str, optional): DC ID required when using file_id and access_hash_rec directly. save_as (str or bool, optional): Directory path to save the file(s). If True, saves in current directory. If None, returns bytes only. save_all (bool): If True, downloads all avatars instead of just the latest. Returns list of bytes if save_as is None. Returns: bytes, List[bytes]: Binary data or saved file paths. ### `edit_can_called_by(self: 'darkob.Client', setting: str, exceptions: Optional[Dict[str, List[str]]]=None)` Edits the setting to control who can call you. Parameters: setting (str): 'Everybody', 'MyContacts' or 'Nobody' exceptions (Optional[Dict[str, List[str]]]): - 'include_users': List[str] - Users to always allow - 'exclude_users': List[str] - Users to always deny To clear exceptions, pass {'exclude_users': []} Returns: The updated privacy settings after the change. ### `edit_can_join_chat_by(self: 'darkob.Client', setting: str, exceptions: Optional[Dict[str, List[str]]]=None)` Edits the setting to control who can join your chats by link. Parameters: setting (str): 'Everybody', 'MyContacts' or 'Nobody' exceptions (Optional[Dict[str, List[str]]]): - 'include_users': List[str] - Users to always allow - 'exclude_users': List[str] - Users to always deny To clear exceptions, pass {'exclude_users': []} Returns: The updated privacy settings after the change. ### `edit_channel_info(self: 'darkob.Client', channel: str, title: Optional[str]=None, description: Optional[str]=None, username: Optional[str]=None, channel_type: Literal['Public', 'Private']=None, sign_messages: Optional[bool]=None, is_restricted_content: Optional[bool]=None, reactions: Optional[Union[Literal['All', 'Disable'], List[int]]]=None)` Edit information of a channel. Parameters: channel (str): The GUID, link, or username of the channel. title (str, optional): The new title of the channel. Max 60 characters. description (str, optional): The new description of the channel. Max 300 characters. username (str, optional): The new username of the channel. Max 32 characters. channel_type (str, optional): The new type of the channel. 'Public' or 'Private'. sign_messages (bool, optional): Whether to sign messages in the channel. is_restricted_content (bool, optional): Restrict content (prevent screenshots and file saving). reactions (Union[Literal['All', 'Disable'], List[int]], optional): - 'All': Enable all reactions - 'Disable': Disable all reactions - List[int]: List of reaction IDs to enable (e.g., [1, 2, 6, 7, 8, 23, 44]) Returns: The result of the API call. ### `edit_channel_title(self: 'darkob.Client', channel: str, title: str)` Edit title of a channel. Parameters: channel (str): The GUID, link, or username of the channel. title (str): The new title of the channel. Returns: The result of the API call. ### `edit_group_info(self: 'darkob.Client', group: str, title: Optional[str]=None, description: Optional[str]=None, slow_mode: Optional[str]=None, event_messages: Optional[bool]=None, is_restricted_content: Optional[bool]=None, reactions: Optional[Union[Literal['All', 'Disable'], List[int]]]=None, chat_history_for_new_members: Optional[str]=None, restricted_period: Optional[List[Dict[str, Union[List[str], str]]]]=None)` Edit the information of a group. Parameters: group (str): The GUID or link of the group. title (Optional[str]): The new title for the group (max 60 characters). description (Optional[str]): The new description for the group (max 300 characters). slow_mode (Optional[str]): The new slow mode setting for the group. event_messages (Optional[bool]): Enable or disable event messages for the group. is_restricted_content (Optional[bool]): Restrict content (prevent screenshots and file saving). reactions (Union[Literal['All', 'Disable'], List[int]], optional): - 'All': Enable all reactions - 'Disable': Disable all reactions - List[int]: List of reaction IDs to enable (e.g., [1, 2, 6, 7, 8, 23, 44]) chat_history_for_new_members (Optional[str]): The new chat history setting for new members. restricted_period (Optional[List[Dict[str, Union[List[str], str]]]]): Time restrictions for sending messages (list of periods). Each period should contain: - days_of_week: List of days ['Saturday', 'Sunday', ..., 'Friday'] - from_time: Start time in "HH:MM" format (24-hour) - to_time: End time in "HH:MM" format (24-hour) Note: Can accept multiple periods as a list of dictionaries. Returns: The result of the API call. Examples: # Enable all reactions await client.edit_group_info( group="g0...", reactions="All" ) # Disable all reactions await client.edit_group_info( group="g0...", reactions="Disable" ) # Enable specific reactions await client.edit_group_info( group="g0...", reactions=[1, 2, 6, 7, 8, 23, 44] ) # Single restricted period await client.edit_group_info( group="g0...", restricted_period=[{ "days_of_week": ["Saturday", "Sunday"], "from_time": "00:00", "to_time": "06:00" }] ) # Multiple restricted periods await client.edit_group_info( group="g0...", restricted_period=[ { "days_of_week": ["Saturday", "Sunday", "Monday"], "from_time": "01:13", "to_time": "08:16" }, { "days_of_week": ["Tuesday", "Wednesday"], "from_time": "22:00", "to_time": "04:00" # Can cross midnight } ] ) ### `edit_group_timer(self: 'darkob.Client', group: str, timer: typing.Union[str, int])` Parameters: group (str): The GUID or link of the group. timer (Union[str, int]): The new slow mode setting for the group. Returns: The result of the API call. ### `edit_group_title(self: 'darkob.Client', group: str, title: str)` Edit title of a group. Parameters: group (str): The GUID or link of the group. title (str): The new title of the group. Returns: The result of the API call. ### `edit_join_link(self: 'darkob.Client', chat: str, join_link: str, title: Optional[str]=None, expire_time: Optional[int]=None, request_needed: Optional[bool]=None, usage_limit: Optional[int]=None)` Edit an existing invite link for a group or channel. Parameters: chat (str): The GUID, link, or username of the target group or channel. join_link (str): The join link to edit. expire_time (Optional[int]): The new expiration time of the link in seconds. request_needed (Optional[bool]): Whether join requests must be approved manually. title (Optional[str]): A new custom title for the invite link. usage_limit (Optional[int]): The new maximum number of times the link can be used. Returns: The API response containing the edited invite link. ### `edit_message(self: 'darkob.Client', chat: str, message_id: Union[int, str], text: str, metadata: Optional[dict]=None)` Edit the specified message associated with the given chat. Parameters: chat (str): The GUID, link, or username of the chat associated with the message (e.g., user, group, channel). message_id (Union[int, str]): The ID of the message to be edited. text (str): The new text content for the message. metadata (dict, optional): Pre-formatted metadata (Bold, Italic, etc.). Returns: The updated information after editing the message. ### `edit_show_birthday(self: 'darkob.Client', setting: str, exceptions: Optional[Dict[str, List[str]]]=None)` Edits the setting to show or hide the user's birthday. Parameters: setting (str): 'Everybody', 'MyContacts' or 'Nobody' exceptions (Optional[Dict[str, List[str]]]): - 'include_users': List[str] - Users to always allow - 'exclude_users': List[str] - Users to always deny To clear exceptions, pass {'exclude_users': []} Returns: The updated privacy settings after the change. ### `edit_show_last_online(self: 'darkob.Client', setting: str, exceptions: Optional[Dict[str, List[str]]]=None)` Edits the setting to control who can see the user's last online status. Parameters: setting (str): 'Everybody', 'MyContacts' or 'Nobody' exceptions (Optional[Dict[str, List[str]]]): - 'include_users': List[str] - Users to always allow - 'exclude_users': List[str] - Users to always deny To clear exceptions, pass {'exclude_users': []} Returns: The updated privacy settings after the change. ### `edit_show_phone_number(self: 'darkob.Client', setting: str, exceptions: Optional[Dict[str, List[str]]]=None)` Edits the setting to control who can see the user's phone number. Parameters: setting (str): 'Everybody', 'MyContacts' or 'Nobody' exceptions (Optional[Dict[str, List[str]]]): - 'include_users': List[str] - Users to always allow - 'exclude_users': List[str] - Users to always deny To clear exceptions, pass {'exclude_users': []} Returns: The updated privacy settings after the change. ### `edit_show_profile_photo(self: 'darkob.Client', setting: str, exceptions: Optional[Dict[str, List[str]]]=None)` Edits the setting to control who can see the user's profile photo. Parameters: setting (str): 'Everybody', 'MyContacts' or 'Nobody' exceptions (Optional[Dict[str, List[str]]]): - 'include_users': List[str] - Users to always allow - 'exclude_users': List[str] - Users to always deny To clear exceptions, pass {'exclude_users': []} Returns: The updated privacy settings after the change. ### `edit_slow_mode(self: 'darkob.Client', group: str, slow_mode: typing.Union[str, int])` Parameters: group (str): The GUID or link of the group. slow_mode (Union[str, int]): The new slow mode setting for the group. Returns: The result of the API call. ### `feedback_voice_transcription(self: 'darkob.Client', chat: Union[str, int], message_id: Union[str, int], feedback_type: str, feedback_text: str=None)` Send feedback for a voice transcription. Parameters: chat (str): The GUID, link, or username of the chat. message_id (Union[str, int]): The ID of the voice message. feedback_type (str): 'OK' or 'Incorrect'. feedback_text (str, optional): Feedback text. If not provided, uses the transcription text. Returns: The result of the API call. ### `forward_messages(self: 'darkob.Client', from_chat: str, message_ids: Union[str, int, list], to_chat: str, hide_author: bool=False, is_mute: bool=False, schedule_time: Optional[Union[int, float, timedelta, datetime]]=None, schedule_type: Optional[Literal['Default', 'WhenOnline']]=None)` Forward specified messages from one chat to another. Parameters: from_chat (str): The GUID, link, or username of the source chat. message_ids (Union[str, int, list]): The IDs of the messages to forward. to_chat (str): The GUID, link, or username of the destination chat. hide_author (bool): Hide the original sender's identity. Default is False. is_mute (bool): Forward silently without notification. Default is False. schedule_time (Optional[Union[int, float, timedelta, datetime]]): When to send the forwarded message. - Unix timestamp (int/float): Absolute time - timedelta: Relative time from now - datetime: Absolute date and time schedule_type (Optional[Literal['Default', 'WhenOnline']]): 'Default' uses schedule_time, 'WhenOnline' sends when user comes online. Returns: The updated information after forwarding the messages. ### `get_all_drafts(self: 'darkob.Client')` Get all saved message drafts. Returns: The result of the API call containing all drafts. ### `get_all_messages(self: 'darkob.Client', chat: str, show_message_ids: bool=False)` Retrieve all messages from a chat. Parameters: chat (str): Chat identifier or link (username, GUID, or invite link) show_message_ids (bool, optional): Include message IDs in output. Default is False. Returns: Result containing all messages with total count, first/last IDs, and chat GUID. ### `get_available_reactions(self: 'darkob.Client')` Retrieve the list of available message reactions that can be used in chats. Returns: Shows available reactions data from the server. ### `get_avatars(self: 'darkob.Client', chat: str)` Get avatars of a specific chat. Parameters: chat (str): The GUID, link, or username of the chat to retrieve avatars for. Returns: The result of the API call. ### `get_banned_members(self: 'darkob.Client', chat: str, show_member_guids: bool=False)` Get a list of banned members in a channel or group. Parameters: chat (str): The GUID, link, or username of the channel or group. show_member_guids (bool, optional): Show member GUIDs in output. Default is False. Returns: The result containing banned members with total count and optionally GUIDs. ### `get_blocked_users(self: 'darkob.Client', show_user_guids: bool=False)` Get a list of all blocked users. Parameters: show_user_guids (bool, optional): Show user GUIDs in output. Default is False. Returns: The result containing all blocked users with total count. ### `get_bot_info(self: 'darkob.Client', bot: str)` Get information about a bot. Parameters: bot (str): The GUID or username of the bot. Returns: The result of the API call. ### `get_channel_admin_access(self: 'darkob.Client', channel: str, admin: str)` Get the admin access list for a specific member in a channel. Parameters: channel (str): The GUID, link, or username of the channel. admin (str): The GUID or username of the admin for whom admin access is being checked. Returns: The result of the API call. ### `get_channel_admins(self: 'darkob.Client', channel: str, show_admin_guids: bool=False)` Get the list of admins in a channel. Parameters: channel (str): The GUID, link, or username of the channel. show_admin_guids (bool, optional): Show member GUIDs in output. Default is False. Returns: Result containing all admins with total count and optionally member_guids. ### `get_channel_info(self: 'darkob.Client', channel: str)` Get information about a channel. Parameters: channel (str): The GUID, link, or username of the channel. Returns: The result of the API call. ### `get_channel_link(self: 'darkob.Client', channel: str)` Get the join link of a channel. Parameters: channel (str): The GUID of the channel. Returns: The result of the API call. ### `get_channel_members(self: 'darkob.Client', channel: str, search_text: str=None, start_id: str=None)` Get members in a channel. Parameters: channel (str): The GUID, link, or username of the channel. search_text (str, optional): Text to search for in members. Defaults to None. start_id (str, optional): The ID to start fetching from. Defaults to None. Returns: The result of the API call. ### `get_channel_post_by_link(self: 'darkob.Client', url: str)` Retrieves channel post by application URL. Parameters: url (str): The channel post URL. Returns: Channel info and message data. ### `get_channel_seen_count(self: 'darkob.Client', channel: str, min_id: Union[str, int], max_id=Union[str, int])` Get the view count of a channel within a specific message ID range. Parameters: channel (str): The GUID, link, or username of the channel. min_id (Union[str, int]): Minimum message ID in the range (inclusive). max_id (Union[str, int]): Maximum message ID in the range (inclusive). Returns: The result of the API call. ### `get_channel_statistics(self: 'darkob.Client', channel: str)` Get all statistics for a channel. Parameters: channel (str): The GUID, link, or username of the channel. Returns: The result of the API call containing channel statistics. ### `get_chat_ads(self: 'darkob.Client', state: int=round(time()) - 150)` Retrieves advertising information for chats. Parameters: state (int, optional): The timestamp state to filter chat ads. Defaults to the current time minus 150 seconds. Returns: The result of the API call. ### `get_chat_info(self: 'darkob.Client', chat: str)` Get information about a user, group, or channel. Parameters: chat (str): The GUID, link, or username of the chat (user, group, or channel). Returns: The update containing information about the chat. ### `get_chat_messages(self: 'darkob.Client', chat: str, max_id: Union[str, int]=None, sort: Literal['FromMax', 'FromMin']='FromMin', filter_type: Optional[Literal['Voice', 'File', 'Music', 'Gif', 'Media', 'Link']]=None, limit: int=None)` Get messages from a chat with filtering and pagination. Parameters: chat (str): The GUID, link, or username of the chat. max_id (Union[str, int], optional): Maximum message ID to start from. sort (Literal['FromMax', 'FromMin']): Sort direction. Default is 'FromMin'. filter_type (Literal, optional): Filter messages by type: 'Voice', 'File', 'Music', 'Gif', 'Media', 'Link' limit (int, optional): Maximum number of messages to retrieve. If None, fetches all messages. Returns: The result containing messages, count, and pagination info. ### `get_chat_voice_chat(self: 'darkob.Client', chat: str)` Get the voice chat information for a group or channel. Parameters: chat (str): The GUID, link, or username of the group/channel. Returns: The voice chat information. ### `get_chats(self: 'darkob.Client', show_chat_guids: bool=False, auto_start_id: bool=True, start_id: str=None)` Get a list of all chats. Parameters: show_chat_guids (bool, optional): If True, include chat GUIDs in the result. Default is False. auto_start_id (bool, optional): If True, automatically fetch all pages of chats. If False, only fetch one page using start_id. Default is True. start_id (str, optional): Starting chat ID for pagination. Only used when auto_start_id is False. Returns: Data: The result containing chats with total count and optionally GUIDs. ### `get_chats_info(self: 'darkob.Client', chats: Union[str, List[str]])` Get information about multiple chats by their GUIDs. Parameters: chats (Union[str, List[str]]): A single chat (GUID, username, or link) or a list of them. Returns: The result of the API call containing chats information. ### `get_chats_updates(self: 'darkob.Client', state: Optional[Union[str, int]]=None)` Get updates for chats. Parameters: state (Optional[Union[str, int]]): State parameter for syncing updates. If not provided, it uses the current time minus 150 seconds. Returns: The result of the API call. ### `get_common_groups(self: 'darkob.Client', user: str)` Get groups in common with a user. Parameters: user (str): User's GUID/username. Returns: Common groups list. ### `get_contacts(self: 'darkob.Client', show_user_guids: bool=False)` Get a list of all contacts. Parameters: show_user_guids (bool, optional): Show user GUIDs in output. Default is False. Returns: The result containing all contacts with total count. ### `get_contacts_last_online(self: 'darkob.Client', users: Union[str, List[str]])` Get the last online status of multiple users. Parameters: users (Union[str, List[str]]): The GUID(s) or username(s) of the contacts. Returns: Last online status for each user. ### `get_contacts_stories(self: 'darkob.Client')` Get stories from contacts in the chat page. Returns: The result of the API call containing contacts stories. ### `get_contacts_updates(self: 'darkob.Client', state: Optional[Union[str, int]]=round(time()) - 150)` Get updates related to contacts. Parameters: state (Optional[Union[str, int]], optional): The state parameter to filter updates. Defaults to `round(time()) - 150`. Returns: The update related to contacts. ### `get_first_message(self: 'darkob.Client', chat: str)` Get the first message of a chat. Parameters: chat (str): The GUID, link, or username of the chat. Returns: The first message details. ### `get_first_messages(self: 'darkob.Client', chat: str, limit: int=100)` Get the first messages of a chat up to a limit. Parameters: chat (str): The GUID, link, or username of the chat. limit (int): Maximum number of messages to retrieve (max 100, min 1). Returns: List of first messages and count. ### `get_folders(self: 'darkob.Client', last_state: Union[int, str]=round(time()) - 150)` Get a list of folders. Parameters: last_state (Union[int, str]): The last state to retrieve folders. Returns: List of folders. ### `get_group_admin_access(self: 'darkob.Client', group: str, admin: str)` Get the admin access for a member in a group. Parameters: group (str): The GUID or link of the group. admin (str): The GUID or username of the admin for whom admin access is being checked. Returns: The result of the API call. ### `get_group_admins(self: 'darkob.Client', group: str, show_admin_guids: bool=False)` Get the list of admins in a group. Parameters: group (str): The GUID, link, or username of the group. show_admin_guids (bool, optional): Show admin GUIDs in output. Default is False. Returns: Result containing all admins with total count. ### `get_group_default_access(self: 'darkob.Client', group: str)` Get the default access settings for a group. Parameters: group (str): The GUID or link of the group. Returns: The result of the API call. ### `get_group_info(self: 'darkob.Client', group: str)` Get information about a group. Parameters: group (str): The GUID or link of the group. Returns: The result of the API call. ### `get_group_link(self: 'darkob.Client', group: str)` Get the link associated with a group. Parameters: group (str): The GUID or link of the group. Returns: The result of the API call. ### `get_group_members(self: 'darkob.Client', group: str, search_text: str=None, start_id: str=None)` Get members of a group. Parameters: group (str): The GUID or link of the group. search_text (str, optional): Search text for filtering members. Defaults to None. start_id (str, optional): The starting ID for pagination. Defaults to None. Returns: The result of the API call. ### `get_group_mention_list(self: 'darkob.Client', group: str, search_mention: str=None)` Get the mention list for a group. Parameters: group (str): The GUID or link of the group. search_mention (str, optional): Search text for mentions. Returns: The result of the API call. ### `get_group_message_read_participants(self: 'darkob.Client', group: str, message_id: Union[str, int])` Get list of participants who have read a specific message in a group. Parameters: group (str): The GUID or link of the group. message_id (Union[str, int]): The ID of the message. Returns: The result of the API call containing read participants. ### `get_group_online_count(self: 'darkob.Client', group: str)` Retrieves the number of online members in a specified group. Parameters: group (str): The GUID or link of the group. Returns: The result of the API call. ### `get_guid(self: 'darkob.Client', chat: str)` Retrieves the GUID of a user, group, channel, or bot. Parameters: chat (str): The username, group link, channel link, or bot username. Returns: str: The GUID of the chat. ### `get_info_by_link(self: 'darkob.Client', link: str)` Get group or channel preview by join link. Parameters: link (str): The join link. Returns: The result of the API call. ### `get_info_by_username(self: 'darkob.Client', username: str)` Get an chat (user, bot, or channel) by its username. Parameters: username (str): The username of the chat. Returns: The result of the API call. ### `get_inline_bots(self: 'darkob.Client', bots: Union[str, List[str]])` Retrieve information about inline bots by their GUIDs or usernames. Parameters: bots (Union[str, List[str]]): A single bot GUID/username or a list of bot GUIDs/usernames. Returns: The result of the API call. ### `get_join_links(self: 'darkob.Client', chat: str, creator: str=None)` Retrieves a list of join links for a specific group or channel. Parameters: chat (str): The GUID, link, or username of the target group or channel. Returns: The API response containing the join links. ### `get_join_requests(self: 'darkob.Client', chat: str, show_user_guids: bool=False)` Get a list of join requests in a channel or group. Parameters: chat (str): The GUID, link, or username of the channel or group. show_user_guids (bool, optional): Show user GUIDs in output. Default is False. Returns: Data: The result containing all join requests with total count. ### `get_last_message(self: 'darkob.Client', chat: str)` Get the last message from a chat and retrieve its details. Parameters: chat (str): The GUID, link, or username of the chat. Returns: The last message details. ### `get_last_messages(self: 'darkob.Client', chat: str, limit: int=100)` Get the last messages of a chat up to a limit. Parameters: chat (str): The GUID, link, or username of the chat. limit (int): Maximum number of messages to retrieve (max 1000). Returns: List of last messages and count. ### `get_last_online(self: 'darkob.Client', user: str)` Get the last online status of a user. Parameters: user (str): The GUID, link, or username of the user. Returns: Last online status with details. ### `get_link_from_app_url(self: 'darkob.Client', url: str)` Get a direct link from an application URL. Parameters: url (str): The application URL to extract the link from. Returns: Data: The result containing the extracted link. ### `get_live_comments(self: 'darkob.Client', live_id: str, access_token: str)` Get live stream comments. Parameters: live_id (str): Live stream ID. access_token (str): Access token from send_live response. Returns: The result of the API call. ### `get_live_play_url(self: 'darkob.Client', access_token: str, live_id: str)` Retrieves the play URL for a live stream. Parameters: access_token (str): The access token for authentication. live_id (str): The ID of the live stream. Returns: The result of the API call. ### `get_live_status(self: 'darkob.Client', live_id: str, access_token: str)` Get live stream status. Parameters: live_id (str): Live stream ID. access_token (str): Access token from send_live response. Returns: Live status info. ### `get_location_view(self: 'darkob.Client', latitude: float, longitude: float)` Get map view for a location. Parameters: latitude (float): Latitude (-90 to 90) longitude (float): Longitude (-180 to 180) Returns: Map view data. ### `get_me(self: 'darkob.Client', refresh: bool=False, ttl: float=300.0)` Get information about the authenticated user. The result is cached for ``ttl`` seconds (default 5 minutes), because profile reads are frequent and rarely change. Pass ``refresh=True`` to force a new request. Parameters: refresh (bool): Ignore the cache. Defaults to False. ttl (float): Cache lifetime in seconds. Defaults to 300. Returns: Information about the authenticated user. ### `get_message_info(self: 'darkob.Client', chat: str, message_id: Union[str, int])` Get detailed information about a message. Parameters: chat (str): The GUID, link, or username of the chat. message_id (Union[str, int]): The ID of the message to retrieve. Returns: Message information. ### `get_message_url(self: 'darkob.Client', chat: str, message_id: Union[str, int])` Get the shareable URL of a specific message. Parameters: chat (str): The GUID, link, or username of the chat to which the message belongs. message_id (Union[str, int]): The ID of the message for which to retrieve the shareable URL. Returns: The shareable URL of the specified message. ### `get_messages(self: 'darkob.Client', chat: str, types: Optional[Union[str, List[str]]]=None)` Get messages from a chat with optional type filtering. Parameters: chat (str): The GUID, link, or username of the chat. types (Optional[Union[str, List[str]]]): Type(s) of messages to filter by. Each item is independent. Available types: - "text": Text messages - "image": Image messages - "video": Video messages (non-round) - "video_message": Round video messages - "voice": Voice messages - "music": Music messages - "file": File messages - "gif": GIF messages - "live": Live messages - "location": Location messages - "poll": Poll messages - "contact": Contact messages (only private chats) - "event": Event messages - "edited": Edited messages - "forwarded": Forwarded messages - "sticker": Sticker messages - "me": Messages sent by the client itself - "bots": Messages sent by bots - "users": Messages sent by users You can also pass a member GUID or username for member filtering. If None, returns all messages. Returns: - messages: list of filtered messages. - count: number of filtered messages. - chat_guid: The GUID of the chat. - total_all: total messages before filtering. - filter_types: list of applied type filters. - member_guids: list of applied member GUID filters. ### `get_messages_by_id(self: 'darkob.Client', chat: str, message_ids: Union[str, int, list])` Retrieve messages by their IDs. Parameters: chat (str): The GUID, link, or username of the chat to which the messages belong. message_ids (Union[str, int, list]): The ID or list of IDs of the messages to retrieve. Returns: The retrieved messages identified by their IDs. ### `get_messages_interval(self: 'darkob.Client', chat: str, middle_message_id: Union[int, str])` Retrieve messages in an interval around a middle message ID. Parameters: chat (str): The GUID, link, or username of the chat to which the messages belong. middle_message_id (Union[int, str]): The middle message ID around which the interval is determined. Returns: The retrieved messages in the specified interval. ### `get_messages_reactions(self: 'darkob.Client', chat: str, min_id: Union[str, int], max_id: Union[str, int])` Get reactions of messages in a chat within a specific ID range. Parameters: chat (str): Chat identifier (link, username, or GUID) min_id (Union[str, int]): Minimum message ID (lower bound) max_id (Union[str, int]): Maximum message ID (upper bound) Returns: List of reactions for messages in the specified range. ### `get_messages_updates(self: 'darkob.Client', chat: str, state: int=round(time()) - 150)` Get message updates for a specific chat. Parameters: chat (str): The GUID, link, or username of the chat for which updates are requested. state (int): The state at which updates are requested. Defaults to a timestamp approximately 150 seconds ago. Returns: The message updates for the specified chat. ### `get_my_archived_sticker_sets(self: 'darkob.Client', start_id: str=None)` Get archived sticker sets of the current user. Parameters: start_id (str, optional): The ID to start fetching from. Defaults to None. Returns: The result of the API call. ### `get_my_gif_set(self: 'darkob.Client')` Gets the user's personal GIF set. Returns: Information about the user's GIF set. ### `get_my_guid(self: 'darkob.Client')` Get the GUID of the currently authenticated user. Returns: str: The user's GUID. ### `get_my_sessions(self: 'darkob.Client')` Get information about the current user's sessions. Returns: Information about the user's sessions. ### `get_my_sticker_sets(self: 'darkob.Client')` Get the sticker sets owned by the user. Returns: The sticker sets owned by the user. ### `get_notification_setting(self: 'darkob.Client')` Retrieves the current notification settings for the account. Returns: The result of the API call. ### `get_pending_owner(self: 'darkob.Client', chat: str)` Retrieves the pending owner information for a specified chat. Parameters: chat (str): The GUID, link, or username of the chat. Returns: An update chat containing details about the pending owner of the specified chat. ### `get_pinned_messages(self: 'darkob.Client', chat: str)` Get all pinned messages from a chat. Parameters: chat (str): The GUID, link, or username of the chat. Returns: Data: Dictionary containing pinned messages and optionally message IDs. ### `get_poll_option_voters(self: 'darkob.Client', poll_id: str, selection_index: Union[str, int], start_id: Optional[str]=None)` Get voters for a specific poll option. Parameters: poll_id (str): The ID of the poll for which voters are requested. selection_index (Union[str, int]): The index of the poll option for which voters are requested. start_id (Optional[str]): The ID from which to start fetching voters. Defaults to None. Returns: The voters for the specified poll option. ### `get_poll_status(self: 'darkob.Client', poll_id: str)` Get the status of a specific poll. Parameters: poll_id (str): The ID of the poll for which the status is requested. Returns: The status of the specified poll. ### `get_post_by_ask_link(self: 'darkob.Client', url: str)` Retrieves channel post by ask_join_link (go.rubika.ir link). Parameters: url (str): The go.rubika.ir link. Returns: Channel info and message data. ### `get_privacy_setting(self: 'darkob.Client')` Get the current user's privacy setting. Returns: The current user's privacy setting. ### `get_profile_link_items(self: 'darkob.Client', chat: str)` Get profile link items for a given chat. Parameters: chat (str): The GUID, link, or username of the chat. Returns: The result of the API call. ### `get_related_chats(self: 'darkob.Client', chat: str)` Get related chats for a given chat. Parameters: chat (str): The GUID, link, or username of the chat. Returns: The result of the API call. ### `get_saved_music_playlist(self: 'darkob.Client', user: str)` Get the saved music playlist of a user. Parameters: user (str): The GUID or username of the user. Returns: The result of the API call containing saved music playlist. ### `get_scheduled_messages(self: 'darkob.Client', chat: str, start_id: str=None)` Get scheduled messages in a chat. Parameters: chat (str): The GUID, link, or username of the chat. start_id (str, optional): The ID to start fetching from. Defaults to None. Returns: The result of the API call containing scheduled messages. ### `get_service_info(self: 'darkob.Client', service: str)` Get information about a service. Parameters: service (str): The GUID of the service. Returns: The result of the API call. ### `get_sticker_set_by_id(self: 'darkob.Client', sticker_set_id: str)` Get a sticker set by its ID. Parameters: sticker_set_id (str): The ID of the sticker set. Returns: The sticker set corresponding to the provided ID. ### `get_sticker_setting(self: 'darkob.Client')` Get the sticker settings of the current user. Returns: The result of the API call containing sticker settings. ### `get_stickers_by_emoji(self: 'darkob.Client', emoji: str, suggest_by: str='All')` Get stickers by emoji. Parameters: emoji (str): The emoji character. suggest_by (str): The type of suggestion (default is 'All'). Returns: Stickers corresponding to the provided emoji and suggestion type. ### `get_stickers_by_set_ids(self: 'darkob.Client', sticker_set_ids: Union[str, list])` Get stickers by set IDs. Parameters: sticker_set_ids (Union[str, list]): The sticker set ID or a list of sticker set IDs. Returns: Stickers corresponding to the provided set IDs. ### `get_string_session(self: 'darkob.Client', password: Optional[str]=None)` Export current session as an encrypted StringSession. Parameters: password (Optional[str]): Optional password for encryption. If provided, StringSession can only be opened with this password. Returns: str: Encrypted StringSession that can be used later with `Messenger(string_session=..., password=...)`. ### `get_suggested_folders(self: 'darkob.Client')` Get the suggested folders for the user. Returns: The suggested folders for the user. ### `get_time(self: 'darkob.Client')` Retrieve the current server time. Returns: The result of the API call. ### `get_top_users(self: 'darkob.Client')` Get list of top users. Returns: List of top users. ### `get_trend_sticker_sets(self: 'darkob.Client', start_id: str=None)` Get trending sticker sets. Parameters: start_id (str): The start ID for pagination. Returns: Trending sticker sets. ### `get_two_passcode_status(self: 'darkob.Client')` Get the two-passcode status for the user. Returns: The two-passcode status for the user. ### `get_unconfirmed_sessions(self: 'darkob.Client')` Get a list of unconfirmed (pending) sessions for the current account. Returns: The result of the API call containing unconfirmed sessions. ### `get_unread_mentions(self: 'darkob.Client', group: str, max_id: Union[str, int], min_id: Union[str, int], sort: str=None)` Get unread mentions in a group. Parameters: group (str): The GUID or link of the group. max_id (Union[str, int]): Maximum message ID. min_id (Union[str, int]): Minimum message ID. sort (str, optional): Sort order. Defaults to None. Returns: The result of the API call containing unread mentions. ### `get_updates(self: 'darkob.Client')` Listen for updates from Rubika's WebSocket. Returns: None ### `get_user_info(self: 'darkob.Client', user: str=None)` Get information about a specific user. Parameters: user (str): The GUID or username of the user. Returns: Information about the specified user. ### `get_voice_chat_participants(self: 'darkob.Client', chat: str, show_user_guids: bool=False)` Get list of participants in a voice chat. Parameters: chat (str): The GUID, link, or username of the group/channel. show_user_guids (bool, optional): Show user GUIDs in output. Default is False. Returns: The result containing all voice chat participants with total count. ### `get_voice_chat_updates(self: 'darkob.Client', chat: str, state: int=None)` Get voice chat updates for a group. Parameters: chat (str): The GUID, link, or username of the group/channel. state (int, optional): The state for updates. If not provided, it defaults to the current time minus 150 seconds. Returns: Update group containing the voice chat updates. ### `get_wallet_transaction_message(self: 'darkob.Client', transfer_id: str, access_transfer: str)` Get the message associated with a wallet transaction. Parameters: transfer_id (str): The ID of the wallet transaction. access_transfer (str): The access hash for the transaction. Returns: The result of the API call. ### `get_wallpapers(self: 'darkob.Client')` Get the current chat wallpaper settings. Returns: The result of the API call containing wallpaper information. ### `heartbeat(self: 'darkob.Client', chat_guid: str)` _No docstring._ ### `iter_messages(self: 'darkob.Client', chat: str, *, sort: str='FromMin', filter_type: Optional[str]=None, page_size: int=25, max_items: Optional[int]=None)` Yield messages from *chat*, one page at a time. Parameters: chat (str): Chat GUID, link or username. sort (str): 'FromMin' (oldest first) or 'FromMax' (newest first). filter_type (str, optional): 'Voice', 'File', 'Music', 'Gif', 'Media' or 'Link'. page_size (int): Messages requested per round-trip. max_items (int, optional): Stop after this many messages. Yields: Each message as a :class:`~darkob.data.Data` object. ### `join_channel(self: 'darkob.Client', channel: str)` Join a channel. Parameters: channel (str): The GUID, link, or username of the channel. Returns: Result of the API call. ### `join_chat(self: 'darkob.Client', chat: str)` Join a chat (channel or group). Parameters: chat (str): The GUID, link, or username of the chat (channel or group). Returns: The result of the API call. ### `join_group(self: 'darkob.Client', group: str)` Join a group using the provided link. Parameters: group (str): The group link. Returns: The result of the API call. ### `join_voice_chat(self: 'darkob.Client', chat: str, sdp_offer_data: str | None = None)` Join to the group | channel voice chat. Parameters: chat (str): The GUID, link, or username of the group/channel. sdp_offer_data (str, optional): SDP offer data. If not provided, uses default. Returns: The result of the API call. ### `leave_channel(self: 'darkob.Client', channel: str)` Leave a channel. Parameters: channel (str): The GUID, link, or username of the channel. Returns: The result of the API call. ### `leave_chat(self: 'darkob.Client', chat: str)` Leave a chat (channel or group). Parameters: chat (str): The GUID, link, or username of the chat (channel or group). Returns: The result of the API call. ### `leave_group(self: 'darkob.Client', group: str)` Leave a group. Parameters: group (str): The GUID or link of the group. Returns: The result of the API call. ### `leave_voice_chat(self: 'darkob.Client', chat: str)` Leave a voice chat in a group or channel. Parameters: chat (str): The GUID, link, or username of the group/channel. Returns: The result of the API call. ### `lock_group(self: 'darkob.Client', group: str)` Lock a group by disabling SendMessage access. Parameters: group (str): The GUID or link of the group. Returns: Result message. ### `login_disable_two_step(self: 'darkob.Client', phone_number: str, email_code: str, forget_password_code_hash: str)` Disable two-step verification during login. Parameters: phone_number (str): The phone number associated with the account. email_code (str): The verification code sent to email. forget_password_code_hash (str): The code hash for forgotten password flow. Returns: The result of the API call. ### `login_two_step_forget_password(self: 'darkob.Client', phone_number: str)` Start the password recovery process for two-step verification. Use this when the user has forgotten their two-step verification password. This will initiate the recovery flow (e.g. sending a code to email/phone). Parameters: phone_number (str): The phone number associated with the account. Returns: The result of the API call, typically containing a hash or instructions for the next step of recovery. ### `logout(self: 'darkob.Client', confirm: bool=True)` Log out of the current session. Parameters: confirm (bool): If True, ask the user for confirmation before logging out. If False, log out immediately. Default is True. Returns: The result of the logout operation if confirmed. Exits if cancelled. ### `mark_as_read(self: 'darkob.Client', chat: str)` Mark a chat as read by seeing the last message. Parameters: chat (str): The GUID, link, or username of the chat. Returns: Result of the operation. ### `mark_as_seen(self: 'darkob.Client', chat: str, message_id: Union[str, int]=None)` Mark a specific message as seen. Parameters: chat (str): The GUID, link, or username of the chat. message_id (Union[str, int], optional): Specific message ID. Defaults to last message. Returns: Result of the operation. ### `member_is_admin(self: 'darkob.Client', chat: str, member: str)` Checks if a member is an admin in a group or channel. Parameters: chat (str): The GUID, link, or username of the group or channel. member (str): The GUID or username of the member. Returns: bool: True if the user is an admin, False otherwise. ### `mute_chat(self: 'darkob.Client', chat: str, duration: Union[int, timedelta]=None)` Mute a chat. Parameters: chat (str): The GUID, link, or username of the chat to mute. duration (Union[int, timedelta], optional): Duration of mute. - int: seconds, must be at least 1800 (30 minutes). - timedelta: e.g., timedelta(hours=1), timedelta(minutes=30). Defaults to None (permanent mute). Returns: Result of the operation. ### `on_add_reaction(self: 'darkob.Client', *filters: Filter)` Decorator for reaction added. ### `on_call_signal(self: 'darkob.Client', *filters: Filter)` Decorator for call signal data. ### `on_call_update(self: 'darkob.Client', *filters: Filter)` Decorator for call updates. ### `on_chat_updates(self: 'darkob.Client', *filters: Filter)` Decorator for chat updates with optional filters. ### `on_delete_message(self: 'darkob.Client', *filters: Filter)` Decorator for deleted messages. ### `on_draft_message(self: 'darkob.Client', *filters: Filter)` Decorator for draft message updates. ### `on_edit_message(self: 'darkob.Client', *filters: Filter)` Decorator for edited messages with optional filters. ### `on_message(self: 'darkob.Client', *filters: Filter)` Decorator for message updates with optional filters. ### `on_new_message(self: 'darkob.Client', *filters: Filter)` Decorator for new messages with optional filters. ### `on_remove_notifications(self: 'darkob.Client', *args, **kwargs)` _No docstring._ ### `on_remove_reaction(self: 'darkob.Client', *filters: Filter)` Decorator for reaction removed. ### `on_scheduled_message(self: 'darkob.Client', *filters: Filter)` Decorator for scheduled message updates. ### `on_show_activities(self: 'darkob.Client', *filters: Filter)` Decorator for show activities (typing, uploading, recording) with optional filters. ### `on_show_notifications(self: 'darkob.Client', *filters: Filter)` Decorator for show notifications with optional filters. ### `on_unconfirmed_session(self: 'darkob.Client', *filters: Filter)` Decorator for unconfirmed session updates (anti-login). ### `on_voice_chat_participant(self: 'darkob.Client', *filters: Filter)` Decorator for voice chat participant updates. ### `on_voice_chat_update(self: 'darkob.Client', *filters: Filter)` Decorator for voice chat updates. ### `pin_chat(self: 'darkob.Client', chat: str)` Pin a chat. Parameters: chat (str): The GUID, link, or username of the chat to pin. Returns: Result of the operation. ### `pin_chat_in_folder(self: 'darkob.Client', chat: str, folder_id: str)` Pin a chat in a folder. Parameters: chat (str): The GUID, link, or username of the chat to pin. folder_id (str): The folder ID to pin the chat in. Returns: The result of the API call. ### `pin_message(self: 'darkob.Client', chat: str, message_id: Union[str, int])` pin a message. Parameters: chat (str): The GUID, link, or username of the recipient. message_id (Union[str, int]): The ID of the message to pin. Returns: The update indicating the success of the operation. ### `play_voice_chat(self: 'darkob.Client', chat: str, media: pathlib.Path)` Plays voice media in a chat. Parameters: chat: The GUID, link, or username of the chat to play the voice media in. media: The path to the voice media file. ### `register_device(self: 'darkob.Client', device_model: str=None, *args, **kwargs)` Register the current device with the Rubika server. Parameters: device_model (str, optional): Custom device model name. Returns: The result of the API call. ### `reject_join_request(self: 'darkob.Client', chat: str, user: str)` Reject a join request for a group or channel. Parameters: chat (str): The GUID, link, or username of the group/channel. user (str): The user GUID or username of the requester. Returns: The result of the API call. ### `reject_ownership_request(self: 'darkob.Client', chat: str)` Reject an ownership transfer request. Parameters: chat (str): The GUID, link, or username of the chat (channel/group). Returns: The result of the API call. ### `remove_from_top_users(self: 'darkob.Client', user: str)` Remove user from top users list. Parameters: user (str): The user GUID or username to remove. Returns: The result of the API call. ### `remove_handler(self: 'darkob.Client', func)` _No docstring._ ### `remove_reaction(self: 'darkob.Client', chat: str, message_id: Union[str, int], reaction_id: Union[int, str])` Remove a reaction from a specific message. Parameters: chat (str): The GUID, link, or username of the chat associated with the message. message_id (str): The ID of the message from which the reaction will be removed. reaction_id (int): The ID of the reaction to be removed. Returns: The update indicating the success of removing the reaction. ### `reorder_folder(self: 'darkob.Client', folder_ids: Union[str, List[str]])` Reorder folders. Parameters: folder_ids (Union[str, List[str]]): A single folder ID or a list of folder IDs in the new order. Returns: The result of the API call. ### `reorder_sticker_sets(self: 'darkob.Client', ordered_sticker_set_ids: Union[str, List[str]])` Reorder sticker sets in the user's collection. Parameters: ordered_sticker_set_ids (Union[str, List[str]]): A single sticker set ID or a list of sticker set IDs in the desired order. Returns: The result of the API call. ### `report_chat(self: 'darkob.Client', chat: str, report_type: Union[int, str], description: Optional[str]=None)` Report a chat (user, channel, group, etc.) for a specific reason. Parameters: chat (str): The GUID, link, or username of the chat to be reported. report_type (Union[int, str]): The report reason. Can be: - Integer code between 100 and 106 - String name (case-insensitive): 'Other', 'Violence', 'Spam', 'Porn', 'ChildAbuse', 'Copyright', 'Fraud' If set to 100 (Other), `description` becomes required. description (Optional[str]): Description for the report. Required when `report_type` is 100 (Other). Returns: The result of the API call. ### `report_chat_ads(self: 'darkob.Client', chat_ads_id: str)` Register a report action on a chat ad. The `chat_ads_id` is obtained from the `get_chat_ads` method. Parameters: chat_ads_id (str): The chat ads ID to report. Returns: The result of the operation. ### `report_live(self: 'darkob.Client', live_id: str, report_type: Union[int, str], description: Optional[str]=None)` Report a live stream. Parameters: live_id (str): The ID of the live stream to report. report_type (Union[int, str]): The report reason. Can be: - Integer code between 100 and 106 - String name (case-insensitive): 'Other', 'Violence', 'Spam', 'Porn', 'ChildAbuse', 'Copyright', 'Fraud' If set to 100 (Other), `description` becomes required. description (Optional[str]): Description for the report. Required when `report_type` is 100 (Other). Returns: The result of the API call. ### `report_message(self: 'darkob.Client', chat: str, message_id: Union[str, int], report_type: Union[int, str], description: Optional[str]=None)` Report a message for a specific reason. Parameters: chat (str): The GUID, link, or username of the chat. message_id (Union[str, int]): The ID of the message to be reported. report_type (Union[int, str]): The report reason. Can be: - Integer code between 100 and 106 - String name (case-insensitive): 'Other', 'Violence', 'Spam', 'Porn', 'ChildAbuse', 'Copyright', 'Fraud' If set to 100 (Other), `description` becomes required. description (Optional[str]): Description for the report. Required when `report_type` is 100 (Other). Returns: The result of the API call. ### `request(self: 'darkob.Client', method: str, input: Optional[Dict]=None, tmp_session: bool=False, encrypt: bool=True)` Build and send a request to the Rubika API. Parameters: method (str): API method name (e.g., 'sendMessage', 'getUserInfo'). input (dict, optional): Input data for the method. tmp_session (bool): Use temporary session instead of auth (default: False). When True, the client will auto-connect if not connected yet. encrypt (bool): Encrypt the request data (default: True). Returns: Data or None: The API response. Raises: NoConnection: If the client has not been started and `tmp_session=False`. ### `request_change_phone_number(self: 'darkob.Client', new_phone_number: str)` Request to change the account phone number. Parameters: new_phone_number (str): The new phone number (e.g., 09123456789, +989123456789, +1234567890). Returns: The result of the API call containing phone_code_hash for verification. ### `request_forget_password(self: 'darkob.Client')` Request to reset the account password. Returns: The result of the API call. ### `request_recovery_email(self: 'darkob.Client', password: str, recovery_email: str)` Request a recovery code to be sent to the recovery email. Parameters: password (str): User's current password. recovery_email (str): Recovery email address. Returns: The result of the API call. ### `request_send_file(self: 'darkob.Client', file_name: str, size: Union[str, int, float], mime: str=None)` Request sending a file. Parameters: file_name (str): The name of the file to be sent. size (Union[str, int, float]): The size of the file to be sent. mime (str, optional): The MIME type of the file. If None, it will be derived from the file name. Returns: The update indicating the success of the file sending request. ### `request_video_call(self: 'darkob.Client', user: str, library_versions: Optional[List[str]]=None, max_layer: int=92, min_layer: int=65, sip_version: int=1, support_call_out: bool=True)` Request a video call with a user. Parameters: user (str): The GUID or username of the user to call. library_versions (List[str], optional): List of supported library versions. Default: ['2.7.7', '2.4.4'] max_layer (int): Maximum protocol layer. Default: 92 min_layer (int): Minimum protocol layer. Default: 65 sip_version (int): SIP version. Default: 1 support_call_out (bool): Support outgoing calls. Default: True Returns: Call request result containing session info. ### `request_voice_call(self: 'darkob.Client', user: str, library_versions: Optional[List[str]]=None, max_layer: int=92, min_layer: int=65, sip_version: int=1, support_call_out: bool=True)` Request a voice call with a user. Parameters: user (str): The GUID or username of the user to call. library_versions (List[str], optional): List of supported library versions. Default: ['2.7.7', '2.4.4'] max_layer (int): Maximum protocol layer. Default: 92 min_layer (int): Minimum protocol layer. Default: 65 sip_version (int): SIP version. Default: 1 support_call_out (bool): Support outgoing calls. Default: True Returns: Call request result containing session info. ### `reset_contacts(self: 'darkob.Client')` Reset all saved contacts for the authenticated user. This method clears the entire contact list on the server side. Returns: The result of the API call. ### `reset_wallpapers(self: 'darkob.Client')` Reset all chat wallpapers to default. Returns: The result of the API call. ### `retract_poll(self: 'darkob.Client', poll_id: str)` Retract a poll. Parameters: poll_id (str): The ID of the poll to retract. Returns: The result of the API call. ### `revoke_join_link(self: 'darkob.Client', chat: str, join_link: str)` Revoke a invite link for a group or channel. Parameters: chat (str): The GUID, link, or username of the group/channel. join_link (str): The join link to revoke. Returns: The result of the API call. ### `run(self, coroutine: Optional[Coroutine]=None)` Start the client and listen for updates. Parameters: coroutine: Optional coroutine to run before listening for updates. Returns: None when used normally (runs forever until stopped). ### `search_chat_messages(self: 'darkob.Client', chat: str, search_text: str)` Searches for chat messages based on the specified criteria. Parameters: chat (str): The GUID, link, or username of the chat. search_text (str): The text to search for in messages. Returns: The search results containing messages. ### `search_global_chats(self: 'darkob.Client', text: str, filter_type: Optional[Union[str, List[str]]]=None, start_id: Optional[str]=None)` Search for global chats (users, channels, etc.) based on the given search text. Parameters: text (str): The text to search for. filter_type (str or list, optional): Filter results by type. 'User', 'Channel', 'Bot' or a list of them. start_id (str, optional): The ID to start fetching from. Defaults to None. Returns: The update containing search results. ### `search_global_messages(self: 'darkob.Client', search_text: str, start_id: Optional[str]=None)` Search for messages globally across all chats. Parameters: search_text (str): The text or hashtag to search for. start_id (str, optional): The ID to start fetching from. Defaults to None. Returns: The result of the API call. ### `search_messages(self: 'darkob.Client', chat: str, text: str)` Search for messages containing specific text in a chat. Parameters: chat (str): The GUID, link, or username of the chat. text (str): The text to search for. Returns: The search results. ### `search_stickers(self: 'darkob.Client', search_text: str='', start_id: str=None)` Search for stickers. Parameters: search_text (str): The search text. start_id (str): The start ID for pagination. Returns: Stickers matching the search criteria. ### `seen_channel_messages(self: 'darkob.Client', channel: str, min_id: Union[int, str], max_id: Union[int, str])` Mark channel messages as seen within a specific range. Parameters: channel (str): The GUID, link, or username of the channel. min_id (Union[int, str]): The minimum message ID to mark as seen. max_id (Union[int, str]): The maximum message ID to mark as seen. Returns: The result of the API call. ### `seen_chats(self: 'darkob.Client', seen_list: dict)` Marks multiple chats as seen. Parameters: seen_list (dict): A dictionary containing chat GUIDs and their last seen message IDs. Returns: The result of the operation. ### `send_chat_activity(self: 'darkob.Client', chat: str, activity: Literal['Typing', 'Recording', 'Uploading']='Typing')` Sends a chat activity, such as typing, uploading, or recording. Parameters: chat (str): The GUID, link, or username of the group/user. activity (str, optional): The type of activity. Defaults to 'Typing'. Returns: The result of the operation. Raises: InvalidInput: If the `activity` argument is not one of `"Typing", "Uploading", or "Recording"`. ### `send_code(self: 'darkob.Client', phone_number: str, pass_key: Optional[str]=None)` Send a verification code to a phone number. Parameters: phone_number (str): The target phone number. pass_key (str): The optional account pass key. Returns: The result of the API call. ### `send_contact(self: 'darkob.Client', chat: str, phone_number: Union[str, int], user: str, first_name: str, last_name: str='', vcard: Optional[str]=None, reply_to_message_id: Optional[Union[str, int]]=None)` Send a contact message to a specified chat. Parameters: chat (str): The GUID or username of the user or bot. phone_number (Union[str, int]): Contact's phone number. user (str): Contact's username or user GUID. first_name (str): Contact's first name. last_name (str, optional): Contact's last name. Defaults to "". vcard (str, optional): Custom vCard string. Defaults to None. reply_to_message_id (Union[str, int], optional): ID of the message to reply to. Defaults to None. Returns: The result of the API call. ### `send_file(self: 'darkob.Client', chat: str, file: Union[Path, bytes]=None, text: Optional[str]=None, reply_to_message_id: Optional[Union[str, int]]=None, via_bot: Optional[str]=None, schedule_time: Optional[Union[int, float, timedelta, datetime]]=None, schedule_type: Optional[Literal['Default', 'WhenOnline']]=None, base64: str=None, **kwargs)` Send a file. Parameters: chat (str): The GUID, link, or username of the chat. file (Union[Path, bytes], optional): The file data (path or bytes). text (Optional[str]): The caption for the file. Defaults to None. reply_to_message_id (Optional[Union[str, int]]): The ID of the message to which this is a reply. Defaults to None. via_bot (Optional[str]): Bot GUID or username to send the message via. Defaults to None. schedule_time (Optional[Union[int, float, timedelta, datetime]]): When to send the message. - Unix timestamp (int/float): Absolute time - timedelta: Relative time from now - datetime: Absolute date and time schedule_type (Optional[Literal['Default', 'WhenOnline']]): 'Default' uses schedule_time, 'WhenOnline' sends when user comes online (users only). base64 (str, optional): Base64 encoded file data. Returns: The result of the API call. ### `send_gif(self: 'darkob.Client', chat: str, gif: Union[Path, bytes]=None, text: Optional[str]=None, reply_to_message_id: Optional[Union[str, int]]=None, via_bot: Optional[str]=None, thumb: Optional[Union[bool, str]]=None, width: Optional[int]=None, height: Optional[int]=None, time: Optional[int]=None, schedule_time: Optional[Union[int, float, timedelta, datetime]]=None, schedule_type: Optional[Literal['Default', 'WhenOnline']]=None, base64: str=None, **kwargs)` Send a GIF to a chat. Parameters: chat (str): The GUID, link, or username of the chat. gif (Path, bytes, optional): The GIF data. Can be a file path or bytes. text (Optional[str]): Caption for the GIF. Defaults to None. reply_to_message_id (Optional[Union[str, int]]): ID of the message to reply to. Defaults to None. via_bot (Optional[str]): Bot GUID or username to send the message via. Defaults to None. thumb (Optional[Union[bool, str]]): Thumbnail behavior: - None or True: Auto-generate thumbnail using available libraries (default) - False: Use default thumbnail - str: Custom thumbnail as Base64 string (pure Base64, no data:image header) width (Optional[int]): Custom width for the GIF. Defaults to None (auto-detect). height (Optional[int]): Custom height for the GIF. Defaults to None (auto-detect). time (Optional[int]): Custom duration for the GIF in seconds. Defaults to None (auto-detect). schedule_time (Optional[Union[int, float, timedelta, datetime]]): When to send the message. - Unix timestamp (int/float): Absolute time - timedelta: Relative time from now - datetime: Absolute date and time schedule_type (Optional[Literal['Default', 'WhenOnline']]): 'Default' uses schedule_time, 'WhenOnline' sends when user comes online (users only). base64 (str, optional): Base64 encoded GIF data. Returns: The API response containing the sent message details. ### `send_image(self: 'darkob.Client', chat: str, image: Union[Path, bytes]=None, text: Optional[str]=None, reply_to_message_id: Optional[Union[str, int]]=None, is_spoil: bool=False, via_bot: Optional[str]=None, thumb: Optional[Union[bool, str]]=None, width: Optional[int]=None, height: Optional[int]=None, schedule_time: Optional[Union[int, float, timedelta, datetime]]=None, schedule_type: Optional[Literal['Default', 'WhenOnline']]=None, base64: str=None, **kwargs)` Send an image to a chat. Parameters: chat (str): The GUID, link, or username of the chat. image (Path, bytes, optional): The image data. Can be a file path or bytes. text (Optional[str]): Caption for the image. Defaults to None. reply_to_message_id (Optional[Union[str, int]]): ID of the message to reply to. Defaults to None. is_spoil (bool): Whether the image should be marked as a spoiler. Defaults to False. via_bot (Optional[str]): Bot GUID or username to send the message via. Defaults to None. thumb (Optional[Union[bool, str]]): Thumbnail behavior: - None or True: Auto-generate thumbnail using available libraries (or default). - str: Custom thumbnail as Base64 string. width (Optional[int]): Custom width for the image. Defaults to None (auto-detect). height (Optional[int]): Custom height for the image. Defaults to None (auto-detect). schedule_time (Optional[Union[int, float, timedelta, datetime]]): When to send the message. - Unix timestamp (int/float): Absolute time - timedelta: Relative time from now - datetime: Absolute date and time schedule_type (Optional[Literal['Default', 'WhenOnline']]): 'Default' uses schedule_time, 'WhenOnline' sends when user comes online (users only). base64 (str, optional): Base64 encoded image data. Returns: The API response containing the sent message details. ### `send_live(self: 'darkob.Client', chat: str, title: str=None, reply_to_message_id: Union[str, int]=None, thumb: Optional[Union[str, Path, bytes]]=None)` Send a live stream. Parameters: chat (str): The GUID, link, or username of the chat. title (str): Live stream title. reply_to_message_id (Optional[Union[str, int]]): The ID of the message to which this is a reply. Defaults to None. thumb (Optional[Union[str, Path, bytes]]): Thumbnail for the live stream. - str: Base64 encoded string, file path, or URL. - Path: Path to thumbnail file. - bytes: Raw thumbnail bytes. If not provided, a default thumbnail will be used. Returns: The result of the API call. ### `send_location(self: 'darkob.Client', chat: str, latitude: float, longitude: float, reply_to_message_id: Union[str, int]=None)` Send a map location. Parameters: chat (str): The GUID, link, or username of the chat. latitude (float): Latitude (-90 to 90). longitude (float): Longitude (-180 to 180). reply_to_message_id (Optional[Union[str, int]]): The ID of the message to which this is a reply. Defaults to None. Returns: The result of the API call. ### `send_message(self: 'darkob.Client', chat: str, text: Optional[str]=None, reply_to_message_id: Optional[Union[str, int]]=None, via_bot: Optional[str]=None, file_inline: Optional[Union[Data, Path, bytes]]=None, base64_data: Optional[str]=None, sticker: Optional[Union[Data, dict]]=None, type: str='File', is_spoil: bool=False, thumb: Optional[Union[bool, str, Path, bytes]]=None, audio_info: bool=True, metadata: Optional[dict]=None, performer: Optional[str]=None, schedule_time: Optional[Union[int, float, timedelta, datetime]]=None, schedule_type: Optional[Literal['Default', 'WhenOnline']]=None, **kwargs)` Send a message to a chat. Parameters: chat (str): The GUID, link, or username of the chat. text (Optional[str]): The text content of the message. reply_to_message_id (Optional[Union[str, int]]): The ID of the message to reply to. via_bot (Optional[str]): Bot GUID or username to send the message via. metadata (Optional[dict]): Additional metadata for text formatting. schedule_time (Optional[Union[int, float, timedelta, datetime]]): When to send the message. Accepts: - Unix timestamp (int/float): Absolute time - timedelta: Relative time from now (e.g., timedelta(hours=1)) - datetime: Absolute date and time schedule_type (Optional[Literal['Default', 'WhenOnline']]): 'Default' uses schedule_time, 'WhenOnline' sends when user comes online. Returns: MessageResult: The API response containing the sent message details, with action methods like edit, delete, reply, forward, pin. ### `send_message_api_call(self: 'darkob.Client', chat: str, message_id: Union[str, int], button_id: str)` Send API call response to a chat's inline keyboard button. Parameters: chat (str): The GUID, link, or username of the chat. message_id (Union[str, int]): ID of the message containing inline keyboard. button_id (str): ID of the button. Returns: The result of the API call. Example: >>> await client.send_message_api_call( # doctest: +SKIP ... chat="b0C2y04506bd2306f068aa161e0502db", ... message_id="1499338519906784", ... button_id="b0SPm00c8ab83b689ac2eeffe16ec7db" ... ) ### `send_music(self: 'darkob.Client', chat: str, music: Union[Path, bytes]=None, text: Optional[str]=None, reply_to_message_id: Optional[Union[str, int]]=None, via_bot: Optional[str]=None, performer: Optional[str]=None, time: Optional[int]=None, schedule_time: Optional[Union[int, float, timedelta, datetime]]=None, schedule_type: Optional[Literal['Default', 'WhenOnline']]=None, base64: str=None, **kwargs)` Send a music file to a chat. Parameters: chat (str): The GUID, link, or username of the chat. music (Path, bytes, optional): The music data. Can be a file path or bytes. text (Optional[str]): Caption for the music. Defaults to None. reply_to_message_id (Optional[Union[str, int]]): ID of the message to reply to. Defaults to None. via_bot (Optional[str]): Bot GUID or username to send the message via. Defaults to None. performer (Optional[str]): Name of the performer/artist. Defaults to None (auto-detect). time (Optional[int]): Custom duration for the music in seconds. Defaults to None (auto-detect). schedule_time (Optional[Union[int, float, timedelta, datetime]]): When to send the message. - Unix timestamp (int/float): Absolute time - timedelta: Relative time from now - datetime: Absolute date and time schedule_type (Optional[Literal['Default', 'WhenOnline']]): 'Default' uses schedule_time, 'WhenOnline' sends when user comes online (users only). base64 (str, optional): Base64 encoded music data. Returns: The API response containing the sent message details. ### `send_now_scheduled_message(self: 'darkob.Client', chat: str, message_id: Union[int, str])` Send a scheduled message immediately. Parameters: chat (str): The GUID, link, or username of the chat. message_id (int): The ID of the scheduled message to send now. Returns: The result of the API call. ### `send_poll(self: 'darkob.Client', chat: str, question: str, options: list, is_anonymous: bool=True, multiple_answers: bool=False, reply_to_message_id: Optional[Union[str, int]]=None)` Send a poll message with the specified parameters. Parameters: chat (str): The GUID, link or username of the chat associated with the poll (e.g., group, channel). question (str): The question for the poll. options (list): A list of string values representing the poll options. is_anonymous (bool): Whether the poll is anonymous or not. Defaults to True. multiple_answers (bool): Whether the poll allows multiple answers or not. Defaults to False. reply_to_message_id (Optional[Union[str, int]]): The ID of the message to reply to. Defaults to None. Returns: The updated information after creating the poll. ### `send_quiz(self: 'darkob.Client', chat: str, question: str, options: list, correct_option: Union[int, str], hint: str=None, is_anonymous: bool=True, reply_to_message_id: Optional[Union[str, int]]=None)` Send a quiz-type poll message with the specified parameters. Parameters: chat (str): The GUID or link or username of the chat associated with the quiz (e.g., group, channel). question (str): The question for the quiz. options (list): A list of string values representing the quiz options. correct_option (Union[int, str]): The index or ID of the correct option for quiz-type polls. hint (str): A hint for the correct answer in quiz-type polls. Defaults to None. is_anonymous (bool): Whether the poll is anonymous or not. Defaults to True. reply_to_message_id (Union[str, int]): The ID of the message to reply to. Defaults to None. Returns: The updated information after creating the quiz-type poll. ### `send_rubino_post(self: 'darkob.Client', chat: str, post_id: str, post_profile_id: str, is_mute: bool=False)` Send a Rubino post to a chat. Parameters: chat (str): The GUID, link, or username of the chat. post_id (str): The post ID to send. post_profile_id (str): The post profile ID. is_mute (bool): Send silently without notification. Default is False. Returns: The result of the API call. ### `send_rubino_product(self: 'darkob.Client', chat: str, store_id: str, product_id: str, product_varieties: List[dict])` Send a Rubino product to a chat. Parameters: chat (str): The GUID, link, or username of the chat. store_id (str): The store ID. product_id (str): The product ID. product_varieties (List[dict]): List of product varieties. Returns: The result of the API call. ### `send_rubino_story(self: 'darkob.Client', chat: str, story_id: str, story_profile_id: str, reply_text: str='', type: Literal['Reply', 'Direct']='Reply', is_mute: bool=False)` Send a Rubino story reply or direct message. Parameters: chat (str): The GUID, link, or username of the chat. story_id (str): The story ID. story_profile_id (str): The story profile ID. reply_text (str): Reply text. Default is empty string. type (str): 'Reply' or 'Direct'. Default is 'Reply'. is_mute (bool): Send silently without notification. Default is False. Returns: The result of the API call. ### `send_sticker(self: 'darkob.Client', chat: str, emoji_character: str, sticker_id: str, sticker_set_id: str, file: dict, w_h_ratio: str='1.0', reply_to_message_id: Optional[Union[str, int]]=None, via_bot: Optional[str]=None, schedule_time: Optional[Union[int, float, timedelta, datetime]]=None, schedule_type: Optional[Literal['Default', 'WhenOnline']]=None)` Send a sticker. Parameters: chat (str): The GUID, link, or username of the chat. emoji_character (str): The emoji character associated with the sticker. sticker_id (str): The ID of the sticker. sticker_set_id (str): The ID of the sticker set. file (dict): The file data for the sticker. w_h_ratio (str): The width-to-height ratio of the sticker. Defaults to '1.0'. reply_to_message_id (Optional[Union[str, int]]): The ID of the message to which this is a reply. Defaults to None. via_bot (Optional[str]): Bot GUID or username to send the message via. Defaults to None. schedule_time (Optional[Union[int, float, timedelta, datetime]]): When to send the message. - Unix timestamp (int/float): Absolute time - timedelta: Relative time from now - datetime: Absolute date and time schedule_type (Optional[Literal['Default', 'WhenOnline']]): 'Default' uses schedule_time, 'WhenOnline' sends when user comes online (users only). ### `send_video(self: 'darkob.Client', chat: str, video: Union[Path, bytes]=None, text: Optional[str]=None, reply_to_message_id: Optional[Union[str, int]]=None, is_spoil: bool=False, via_bot: Optional[str]=None, thumb: Optional[Union[bool, str]]=None, width: Optional[int]=None, height: Optional[int]=None, time: Optional[int]=None, schedule_time: Optional[Union[int, float, timedelta, datetime]]=None, schedule_type: Optional[Literal['Default', 'WhenOnline']]=None, base64: str=None, **kwargs)` Send a video to a chat. Parameters: chat (str): The GUID, link, or username of the chat. video (Path, bytes, optional): The video data. Can be a file path or bytes. text (Optional[str]): Caption for the video. Defaults to None. reply_to_message_id (Optional[Union[str, int]]): ID of the message to reply to. Defaults to None. is_spoil (bool): Whether the video should be marked as a spoiler. Defaults to False. via_bot (Optional[str]): Bot GUID or username to send the message via. Defaults to None. thumb (Optional[Union[bool, str]]): Thumbnail behavior: - None or True: Auto-generate thumbnail using available libraries (or default). - str: Custom thumbnail as Base64 string. width (Optional[int]): Custom width for the video. Defaults to None (auto-detect). height (Optional[int]): Custom height for the video. Defaults to None (auto-detect). time (Optional[int]): Custom duration for the video in seconds. Defaults to None (auto-detect). schedule_time (Optional[Union[int, float, timedelta, datetime]]): When to send the message. - Unix timestamp (int/float): Absolute time - timedelta: Relative time from now - datetime: Absolute date and time schedule_type (Optional[Literal['Default', 'WhenOnline']]): 'Default' uses schedule_time, 'WhenOnline' sends when user comes online (users only). base64 (str, optional): Base64 encoded video data. Returns: The API response containing the sent message details. ### `send_video_message(self: 'darkob.Client', chat: str, video_message: Union[Path, bytes]=None, text: Optional[str]=None, reply_to_message_id: Optional[Union[str, int]]=None, is_spoil: bool=False, via_bot: Optional[str]=None, thumb: Optional[Union[bool, str]]=None, width: Optional[int]=None, height: Optional[int]=None, time: Optional[int]=None, schedule_time: Optional[Union[int, float, timedelta, datetime]]=None, schedule_type: Optional[Literal['Default', 'WhenOnline']]=None, base64: str=None, **kwargs)` Send a video message (round video) to a chat. Parameters: chat (str): The GUID, link, or username of the chat. video_message (Path, bytes, optional): The video message data. Can be a file path or bytes. text (Optional[str]): Caption for the video message. Defaults to None. reply_to_message_id (Optional[Union[str, int]]): ID of the message to reply to. Defaults to None. is_spoil (bool): Whether the video message should be marked as a spoiler. Defaults to False. via_bot (Optional[str]): Bot GUID or username to send the message via. Defaults to None. thumb (Optional[Union[bool, str]]): Thumbnail behavior: - None or True: Auto-generate thumbnail using available libraries (or default). - str: Custom thumbnail as Base64 string. width (Optional[int]): Custom width for the video message. Defaults to None (auto-detect). height (Optional[int]): Custom height for the video message. Defaults to None (auto-detect). time (Optional[int]): Custom duration for the video message in seconds. Defaults to None (auto-detect). schedule_time (Optional[Union[int, float, timedelta, datetime]]): When to send the message. - Unix timestamp (int/float): Absolute time - timedelta: Relative time from now - datetime: Absolute date and time schedule_type (Optional[Literal['Default', 'WhenOnline']]): 'Default' uses schedule_time, 'WhenOnline' sends when user comes online (users only). base64 (str, optional): Base64 encoded video message data. Returns: The API response containing the sent message details. ### `send_voice(self: 'darkob.Client', chat: str, voice: Union[Path, bytes]=None, text: Optional[str]=None, reply_to_message_id: Optional[Union[str, int]]=None, via_bot: Optional[str]=None, time: Optional[int]=None, schedule_time: Optional[Union[int, float, timedelta, datetime]]=None, schedule_type: Optional[Literal['Default', 'WhenOnline']]=None, base64: str=None, **kwargs)` Send a voice message to a chat. Parameters: chat (str): The GUID, link, or username of the chat. voice (Path, bytes, optional): The voice data. Can be a file path or bytes. text (Optional[str]): Caption for the voice message. Defaults to None. reply_to_message_id (Optional[Union[str, int]]): ID of the message to reply to. Defaults to None. via_bot (Optional[str]): Bot GUID or username to send the message via. Defaults to None. time (Optional[int]): Custom duration for the voice message in seconds. Defaults to None (auto-detect). schedule_time (Optional[Union[int, float, timedelta, datetime]]): When to send the message. - Unix timestamp (int/float): Absolute time - timedelta: Relative time from now - datetime: Absolute date and time schedule_type (Optional[Literal['Default', 'WhenOnline']]): 'Default' uses schedule_time, 'WhenOnline' sends when user comes online (users only). base64 (str, optional): Base64 encoded voice data. Returns: The API response containing the sent message details. ### `send_voice_chat_activity(self: 'darkob.Client', chat: str, activity: Literal['Speaking']='Speaking', participant_chat_guid: str=None)` Set voice chat activity automatically. Parameters: chat (str): The GUID, link, or username of the group/channel. activity (str): Literal['Speaking'] and Default is `Speaking`. participant_chat_guid (str): Participant chat guid, Default is `self.guid`. Returns: The result of the API call. ### `set_admin(self: 'darkob.Client', chat: str, member: str, access: Union[List[str], str]=[], custom_title: str='')` Set a member as admin in a group or channel. Parameters: chat (str): The GUID, link, or username of group/channel. member (str): The GUID or username of member to set as admin. access (Union[List[str], str]): List of allowed permissions or single permission string. Can also be 'all' or 'All' to grant all permissions. custom_title (str): Custom title for admin in groups. (optional) Returns: Result of the operation. ### `set_ask_spam(self: 'darkob.Client', chat: str, action: Literal['AddToContact', 'BlockUser', 'Cancel', 'ReportAndLeave']='Cancel')` Perform an action for a pending spam request. Parameters: chat (str): The GUID, link, or username of the user, group, or channel. action (str): The action to apply: - For user (u0): 'AddToContact', 'BlockUser', 'Cancel'. - For group/channel (g0/c0): 'ReportAndLeave'. Returns: The result of the API call. ### `set_channel_link(self: 'darkob.Client', channel: str)` Set a custom link for the channel. Parameters: channel (str): The GUID of the channel. Returns: The result of the API call. ### `set_channel_type(self: 'darkob.Client', channel: str, channel_type: typing.Literal['Public', 'Private'])` Set type of a channel. Parameters: channel (str): The GUID, link, or username of the channel. channel_type (str): The new type of the channel. 'Public' or 'Private'. Returns: The result of the API call. ### `set_chat_auto_delete(self: 'darkob.Client', chat: Union[str, List[str]], auto_delete: Union[str, int])` Set auto-delete timer for one or more groups or channels. Parameters: chat (Union[str, List[str]]): The GUID, link, username of a group/channel, or a list of them. auto_delete (Union[str, int]): Auto-delete duration. Accepts: - Integer: 1-365 (days) - String: '1m'-'60m', '1h'-'24h', '1d'-'365d', '1w'-'52w', '1y', 'off' - Common words: 'day', 'week', 'month', 'year', 'never', 'disabled' Returns: The result of the API call. ### `set_chat_protected_content(self: 'darkob.Client', chat: str, enabled: bool)` Set the chat protected content setting. Parameters: chat (int): The GUID or username of the target chat. enabled (bool): Pass True to enable the protected content setting, False to disable. Returns: The result of the API call. ### `set_chat_use_time(self: 'darkob.Client', chat: str, use_time: int)` Send chat usage time to the server. This helps the server recognize natural user behavior and can reduce rate limiting and bot detection. Parameters: chat (str): The GUID, link, or username of the chat. use_time (int): Time spent in the chat in seconds. Returns: The result of the API call. ### `set_current_live_location(self: 'darkob.Client', longitude: float, latitude: float, tile_side_count: int, tile_urls: List[str], x_loc: float, y_loc: float)` Set the current live location. Parameters: longitude (float): Longitude coordinate. latitude (float): Latitude coordinate. tile_side_count (int): Number of tiles per side. tile_urls (List[str]): URLs of map tiles. x_loc (float): X position on the map. y_loc (float): Y position on the map. Returns: The result of the API call. ### `set_group_default_access(self: 'darkob.Client', group: str, access: Union[str, list])` Set default access for a group. Parameters: group (str): The GUID or link of the group. access (Union[str, list]): List of allowed actions. Must be one or more of: - "ViewMembers": Allows viewing group members. - "ViewAdmins": Allows viewing group admins. - "SendMessages": Allows sending messages. - "AddMember": Allows adding members. If only specific actions are listed (e.g. ["SendMessages"]), ONLY those are enabled and others are disabled. If empty list "[]", ALL access permissions are disabled/closed. Returns: The result of the API call. ### `set_group_link(self: 'darkob.Client', group: str)` Set private link for group. Parameters: group (str): The GUID or link of the group. Returns: The result of the API call. ### `set_notification(self: 'darkob.Client', user_notification: Optional[bool]=None, user_message_preview: Optional[bool]=None, group_notification: Optional[bool]=None, group_message_preview: Optional[bool]=None, channel_notification: Optional[bool]=None, channel_message_preview: Optional[bool]=None, in_app_sound: Optional[bool]=None, in_app_preview: Optional[bool]=None, new_contacts: Optional[bool]=None)` Update notification settings. Parameters: user_notification (bool, optional): Enable/disable user notifications. user_message_preview (bool, optional): Show/hide user message preview. group_notification (bool, optional): Enable/disable group notifications. group_message_preview (bool, optional): Show/hide group message preview. channel_notification (bool, optional): Enable/disable channel notifications. channel_message_preview (bool, optional): Show/hide channel message preview. in_app_sound (bool, optional): Enable/disable in-app sound. in_app_preview (bool, optional): Enable/disable in-app preview. new_contacts (bool, optional): Enable/disable new contacts notification. Returns: The updated notification settings. ### `set_saved_music_playlist(self: 'darkob.Client', files: Union[Path, str, List[Union[Path, str]]]=None, file_inlines: List[dict]=None, time: Optional[int]=None, performer: Optional[str]=None, file_name: Optional[str]=None, **kwargs)` Replace the saved music playlist on your profile. Parameters: files: A single file path or a list of file paths to music files. file_inlines: Pre-uploaded file_inline dicts to set directly. time: Custom duration in seconds. If not provided, auto-detected. performer: Custom performer name. If not provided, auto-detected. file_name: Custom file name. If not provided, uses original file name. Returns: The result of the API call. ### `set_setting(self: 'darkob.Client', show_my_last_online: Optional[PrivacyValue]=None, show_my_phone_number: Optional[PrivacyValue]=None, show_my_profile_photo: Optional[PrivacyValue]=None, link_forward_message: Optional[PrivacyValue]=None, can_join_chat_by: Optional[PrivacyValue]=None, show_my_birth_date: Optional[PrivacyValue]=None, can_called_by: Optional[PrivacyValue]=None, auto_delete_messages: Optional[Union[str, int]]=None, inactive_account_delete: Optional[int]=None, show_my_last_online_exceptions: Optional[Dict[str, List[str]]]=None, show_my_phone_number_exceptions: Optional[Dict[str, List[str]]]=None, show_my_profile_photo_exceptions: Optional[Dict[str, List[str]]]=None, can_join_chat_by_exceptions: Optional[Dict[str, List[str]]]=None, show_my_birth_date_exceptions: Optional[Dict[str, List[str]]]=None, can_called_by_exceptions: Optional[Dict[str, List[str]]]=None)` Set various privacy and auto-delete settings for the user. Parameters: Privacy Settings (accept: 'Everybody', 'MyContacts', 'Nobody'): show_my_last_online: Who can see your last online status show_my_phone_number: Who can see your phone number show_my_profile_photo: Who can see your profile photo link_forward_message: Who can forward your message links can_join_chat_by: Who can join your chats by link show_my_birth_date: Who can see your birth date can_called_by: Who can call you Exceptions (for privacy settings except link_forward_message): Each exception should be a dict with: - 'include_users': List[str] - Users to always allow - 'exclude_users': List[str] - Users to always deny To CLEAR exceptions for a setting, pass {'exclude_users': []}: can_called_by_exceptions={'exclude_users': []} Example: show_my_last_online_exceptions={ 'include_users': ['u0abc123...'], 'exclude_users': ['u0xyz789...'] } Auto Delete Messages: auto_delete_messages: Message auto-delete duration. Delete Inactive Account: inactive_account_delete: Delete account after X months. Returns: The result of the setting operation. ### `set_two_step_verification(self: 'darkob.Client', password: Union[int, str], hint: str=None, recovery_email: str=None)` Set up two-step verification for the user. Parameters: password (Union[int, str]): The current user password. hint (str): A hint to help remember the password. Defaults to None. recovery_email (str): The recovery email for two-step verification. Defaults to None. Returns: The updated user information after setting up two-step verification. ### `set_voice_chat_setting(self: 'darkob.Client', chat: str, title: str=None, join_muted: bool=None)` Set voice chat settings for group or channel. Parameters: chat (str): The GUID, link, or username of the group/channel. title (str, optional): New title for voice chat. join_muted (bool, optional): Whether new participants join muted. (Only for groups) Returns: The result of the API call. ### `set_voice_chat_state(self: 'darkob.Client', chat: str, action: typing.Literal['Mute', 'Unmute', 'RequestSpeak', 'CancelRequestSpeak']='Unmute', participant_chat_guid: str=None)` Set group or channel voice chat state automatically. Parameters: chat (str): The GUID, link, or username of the group/channel. action (str): Literal['Mute', 'Unmute'] and Default is `Unmute`. participant_chat_guid (str): Participant chat guid, Default is `self.guid`. Returns: The result of the API call. ### `sign_in(self: 'darkob.Client', phone_number: str, phone_code: str, phone_code_hash: str, public_key: str)` Sign in using the verification code. Parameters: phone_number (str): The phone number. phone_code (str): The verification code. phone_code_hash (str): The verification code hash. public_key (str): The client's public key. Returns: The result of the API call. ### `speaking(self: 'darkob.Client', chat_guid: str)` _No docstring._ ### `start(self: 'darkob.Client', phone_number: str=None)` Start the client, handling authentication and registration. Parameters: phone_number (str, optional): Phone number for registration. Returns: Client: The initialized client instance. ### `start_bot(self: 'darkob.Client', bot: str)` Parameters: bot (str): The GUID or username of the bot. Returns: The result of the API call. ### `start_voice_chat(self: 'darkob.Client', chat: str)` Start a voice chat for a channel or group. Parameters: chat (str): The GUID, link, or username of the channel/group. Returns: The result of the API call. ### `stop(self)` _No docstring._ ### `stop_bot(self: 'darkob.Client', bot: str)` Parameters: bot (str): The GUID or username of the bot. Returns: The result of the API call. ### `stop_poll(self: 'darkob.Client', poll_id: str)` Stop a poll. Parameters: poll_id (str): The ID of the poll to stop. Returns: The result of the API call. ### `terminate_other_sessions(self: 'darkob.Client')` Terminate other account sessions. Returns: The result of the API call. ### `terminate_session(self: 'darkob.Client', session_key: str)` Terminate a user session. Parameters: session_key (str): The session key of the session to be terminated. Returns: The result of the API call. ### `transcribe_voice(self: 'darkob.Client', chat: Union[str, int], message_id: Union[str, int])` Transcribes voice messages. Parameters: chat (str): The GUID, link, or username of the chat (chat, channel, or group) containing the voice message. message_id (str): The ID of the voice message. Returns: The transcription result. ### `turn_off_two_step(self: 'darkob.Client', password: str)` Turn off two-step verification passcode for the account. Parameters: password (str): Current two-step verification password Returns: Result of the operation. ### `unarchive_chat(self: 'darkob.Client', chat: str)` Unarchive a chat. Parameters: chat (str): The GUID, link, or username of the chat to unarchive. Returns: Result of the operation. ### `unban_all_members(self: 'darkob.Client', chat: str, exclude: Optional[Union[str, List[str]]]=None)` Unban all banned members in a group or channel. Parameters: chat (str): The GUID, link, or username of the group or channel. exclude (Optional[Union[str, List[str]]]): Member GUID(s) or username(s) to exclude from unban. Default is None. Returns: Result of unban operation. ### `unban_member(self: 'darkob.Client', chat: str, member: str)` Unban a member from a group or channel. Parameters: chat (str): The GUID, link, or username of group/channel. member (str): The GUID or username of member to unban. Returns: Result of the operation. ### `unban_members(self: 'darkob.Client', chat: str, members: List[str])` Unban multiple members from a group or channel. Parameters: chat (str): The GUID, link, or username of group/channel. members (List[str]): List of GUIDs or usernames of members to unban. Returns: Results of all operations. ### `unblock_all_users(self: 'darkob.Client', exclude: Optional[Union[str, List[str]]]=None)` Unblock all blocked users. Parameters: exclude (Optional[Union[str, List[str]]]): User GUID(s) or username(s) to exclude from unblock. Default is None. Returns: Result of unblock operation. ### `unblock_user(self: 'darkob.Client', user: str)` Unblock a user. Parameters: user (str): The GUID or username of the user to unblock. Returns: The result of the unblock operation. ### `unlock_group(self: 'darkob.Client', group: str)` Unlock a group by enabling SendMessage access. Parameters: group (str): The GUID or link of the group. Returns: Result message. ### `unmute_chat(self: 'darkob.Client', chat: str)` Unmute a chat. Parameters: chat (str): The GUID, link, or username of the chat to unmute. Returns: Result of the operation. ### `unpin_all_messages(self: 'darkob.Client', chat: str)` Unpin all pinned messages in a group, channel, or private chat. Parameters: chat (str): The GUID, link, or username of the chat. Returns: The update indicating the success of the operation. ### `unpin_chat(self: 'darkob.Client', chat: str)` Unpin a chat. Parameters: chat (str): The GUID, link, or username of the chat to unpin. Returns: Result of the operation. ### `unpin_chat_in_folder(self: 'darkob.Client', chat: str, folder_id: str)` Unpin a chat from a folder. Parameters: chat (str): The GUID, link, or username of the chat to unpin. folder_id (str): The folder ID to unpin the chat from. Returns: The result of the API call. ### `unpin_message(self: 'darkob.Client', chat: str, message_id: Union[str, int])` unpin a message. Parameters: chat (str): The GUID, link, or username of the chat. message_id (Union[str, int]): The ID of the message to unpin. Returns: The update indicating the success of the operation. ### `unset_admin(self: 'darkob.Client', chat: str, member: str)` Unset a member as admin in a group or channel. Parameters: chat (str): The GUID, link, or username of group/channel. member (str): The GUID or username of member to unset as admin. Returns: Result of the operation. ### `update_channel_username(self: 'darkob.Client', channel: str, username: str)` Update the username of a channel. Parameters: channel (str): The GUID or username of the channel. username (str): The new username for the channel. Must be between 7 and 32 characters Can only contain English letters (a-z, A-Z), numbers (0-9), and underscore (_) Should not start with number or underscore Should not end with underscore Returns: The result of the API call. ### `update_my_bio(self: 'darkob.Client', bio: str)` Update user's biography. Parameters: bio (str): The updated biography (max 150 characters). Returns: The updated user information. Raises: InvalidInput: If bio exceeds 150 characters. ### `update_my_birthday(self: 'darkob.Client', birthday: Union[str, datetime])` Update the birthday in your profile. Parameters: birthday (str | datetime): Birthday in format YYYY-MM-DD (e.g., "2026-02-03") or a datetime object. Returns: The updated user information. ### `update_my_name(self: 'darkob.Client', first_name: Optional[str]=None, last_name: Optional[str]=None)` Update user's first name and/or last name. Parameters: first_name (Optional[str]): The updated first name (max 30 characters). last_name (Optional[str]): The updated last name (max 50 characters). Returns: The updated user information. ### `update_my_profile(self: 'darkob.Client', first_name: Optional[str]=None, last_name: Optional[str]=None, bio: Optional[str]=None, birthday: Optional[str]=None, location: Optional[Dict[str, Union[float, Dict[str, Union[int, List[str], float]]]]]=None)` Update user profile information. Parameters: first_name (Optional[str]): The updated first name. last_name (Optional[str]): The updated last name. bio (Optional[str]): The updated biography. birthday (str): Birthday in format YYYY-MM-DD (e.g., "2026-07-05"). location (Optional[dict]): Location information containing: - longitude (float): Longitude coordinate. - latitude (float): Latitude coordinate. - map_view (dict): Map view details with: - tile_side_count (int): Number of tile sides. - tile_urls (List[str]): List of tile URLs. - x_loc (float): X location on map. - y_loc (float): Y location on map. Returns: The updated user information after the profile update. ### `update_my_username(self: 'darkob.Client', username: str)` Update the username of the user. Parameters: username (str): The new username for the user. - Must be between 7 and 32 characters - Can only contain English letters (a-z, A-Z), numbers (0-9), and underscore (_) - Should not start with number or underscore - Should not end with underscore Returns: The updated user information. ### `upgrade_to_api6(self: 'darkob.Client', save_as: bool=True, file_name: Optional[str]=None)` Upgrade from API v5 to v6 by setting an RSA public key. This allows old v5 auth keys to be used with API v6. After upgrade, save the returned private_key for future v6 logins. Parameters: save_as (bool): If True (default), saves auth and private_key to a JSON file. file_name (str, optional): Custom file name for the JSON file. Defaults to 'darkob_{auth[:10]}'. Returns: Data: Response with status, message, auth, and private_key. ### `upload_avatar(self: 'darkob.Client', chat: str, main_image: Union[Path, str, bytes], thumbnail_image: Optional[Union[Path, str, bytes]]=None, *args, **kwargs)` Uploads an avatar image for a specified chat (user, group, or channel). Parameters: chat (str): The GUID, link, or username of the chat for which the avatar is being uploaded. main_image (Union[Path, str, bytes]): The image file or bytes to be used as the avatar. thumbnail_image (Optional[Union[Path, str, bytes]]): The image file or bytes of the thumbnail image. Returns: The result of the avatar upload operation. Note: If `chat` is 'me', 'cloud', or 'self', it will be replaced with the client's GUID. If `main_image` is a string or Path (path to a file), the file name is extracted from the path. Otherwise, a default file name ('darkob.jpg') is used. The `upload_file` method is used internally to handle the file upload process. ### `upload_file(self: 'darkob.Client', file: Union[str, bytes, None]=None, base64_data: Optional[str]=None, mime: Optional[str]=None, file_name: Optional[str]=None, chunk: int=1048576, callback: Optional[Callable[[int, int], Union[None, asyncio.Future]]]=None, *args, **kwargs)` Upload a file to Rubika with chunked transfer and retry logic. Parameters: file (str, bytes, or None): File path, bytes, or URL to upload. base64_data (str, optional): Base64 encoded file data. mime (str, optional): MIME type of the file. file_name (str, optional): Name of the file. chunk (int, optional): Chunk size in bytes (default: 1MB). callback (callable, optional): Progress callback(total_size, uploaded_bytes). Returns: Metadata about the uploaded file. ### `verify_change_phone_number(self: 'darkob.Client', code: Union[str, int], hash: str)` Verify phone number change with the received code. Parameters: code (str): The verification code sent to the new phone number. hash (str): The hash received from request_change_phone_number. Returns: The result of the API call. ### `verify_recovery_email(self: 'darkob.Client', password: str, code: Union[str, int])` Verify the recovery code sent to the recovery email. Parameters: password (str): User's current password. code (Union[str, int]): The verification code received in email. Can be a string or an integer. Returns: The result of the API call. ### `view_chat_ads(self: 'darkob.Client', chat_ads_id: str)` Register a view action on a chat ad. The `chat_ads_id` is obtained from the `get_chat_ads` method. Parameters: chat_ads_id (str): The chat ads ID to register a view on. Returns: The result of the operation. ### `vote_poll(self: 'darkob.Client', poll_id: str, selection_index: Union[str, int])` Vote on a poll option. Parameters: poll_id (str): The ID of the poll. selection_index (Union[str, int]): The index of the option to vote for. Returns: The update indicating the success of the vote. --- # PUBLIC API: classes and helpers Every name exported from the package root, so no part of the library is missing from this file. - `darkob.Bot` - `darkob.Client` - `darkob.Messenger` - `darkob.Shad` - `darkob.show_welcome_message` — Print the one-time welcome banner. - `darkob.check_for_updates` — Compare the installed version against the latest release on PyPI. - `darkob.Router` — Groups handlers so they can be registered on a bot all at once. - `darkob.FSMContext` — State and data for one conversation, bound to a storage and key. - `darkob.Storage` — Minimal async key/value store used by :class:`FSMContext`. - `darkob.MemoryStorage` — In-process storage. Fast, but lost when the process exits. - `darkob.TTLMemoryStorage` — In-memory storage whose entries expire after ``ttl`` seconds. - `darkob.SQLiteStorage` — Durable storage backed by SQLite, safe for concurrent tasks. - `darkob.JsonFileStorage` — Storage that persists to a JSON file and survives restarts. - `darkob.StateFilter` — Matches events whose conversation is currently in a given state. - `darkob.Keyboard` — An API-ready keypad: ``{"rows": [{"buttons": [...]}, ...]}``. - `darkob.Button` — A single keypad button. - `darkob.MessageBuilder` — Fluent builder for ``send_message`` arguments. - `darkob.ButtonType` — ``ButtonTypeEnum`` — what a keypad button does. - `darkob.ChatType` — ``ChatTypeEnum`` - `darkob.FileType` — ``FileTypeEnum`` — accepted values for ``request_send_file``. - `darkob.Retry` — How many times to retry, and how long to wait between attempts. - `darkob.CircuitBreaker` — Track failures for one endpoint and trip when they pile up. - `darkob.ConversationManager` — Registry of pending conversations, keyed by chat. - `darkob.NoReply` — Raised when a conversation prompt goes unanswered in time. - `darkob.State` — A named conversation state. Compares equal to its string form. - `darkob.StatesGroup` — Base class collecting ``State`` attributes into a namespace. - `darkob.RateLimiter` — A global bucket plus optional per-conversation buckets. - `darkob.AdaptiveRateLimiter` — A :class:`RateLimiter` with AIMD tuning switched on. - `darkob.TokenBucket` — A classic token bucket with async acquisition. - `darkob.SendQueue` — A durable, bounded outbox for messages that could not be sent. - `darkob.QueueFull` — Raised when the queue is at capacity and cannot accept more. - `darkob.Metrics` — A small, allocation-light metric registry. - `darkob.Histogram` — A counter plus a bounded sample window for percentiles. - `darkob.enable_metrics` — Turn on the shared registry and return it. - `darkob.disable_metrics` — Turn off instrumentation (recorded data is kept). - `darkob.get_metrics` — Return the shared registry. - `darkob.HealthRegistry` — A named collection of health checks. - `darkob.HealthReport` — The aggregate outcome of a probe. - `darkob.HealthResult` — The outcome of one named check. - `darkob.tcp_check` — A check that the *host*:*port* accepts a TCP connection. - `darkob.queue_backlog_check` — A check that an outbox has not grown past *max_pending*. - `darkob.Plugin` - `darkob.PluginManager` - `darkob.PluginMeta` - `darkob.PluginTester` — Drive a plugin's lifecycle and hooks without a real bot. - `darkob.create_plugin` - `darkob.TaskGroup` — Asynchronous context manager for managing groups of tasks. - `darkob.LazyLock` — An ``asyncio.Lock`` created on first use, not on construction. - `darkob.async_timeout` — Awaitable context manager bounding the body by *seconds*. - `darkob.ProtocolTracker` — Keep the last snapshot on disk and report what changed. - `darkob.ProtocolSnapshot` — The endpoint layout a client discovered. - `darkob.bold` — ``**text**`` - `darkob.italic` — ``__text__`` - `darkob.strike` — ``~~text~~`` - `darkob.underline` — ``--text--`` - `darkob.spoiler` — ``||text||`` — hidden until the user taps it. - `darkob.code` — ``\`text\`` — inline monospace. - `darkob.pre` — A fenced code block, optionally with a language hint. - `darkob.link` — ``[text](url)`` - `darkob.join` — Join already-formatted fragments, skipping empty ones. - `darkob.__version__` — str(object='') -> str