API Reference¶
Автоматически сгенерированная документация из исходного кода. Для руководств с примерами смотрите соответствующие разделы документации.
VKBot¶
- class vk_bot.VKBot(token, group_id=None, state_storage=None, http_config=None)[исходный код]¶
Базовые классы:
objectMain bot class for VK API interaction.
Provides an interface for sending messages, handling Long Poll events, and managing user states (FSM). Uses dishka DI container internally to manage HttpClient and ApiClient lifecycle.
- Параметры:
token (
str) – VK community token.group_id (
int|None) – Community ID. Resolved automatically if not provided.state_storage (
BaseStorage|None) – State storage backend (MemoryStorage, RedisStorage, PostgresStorage). Defaults to MemoryStorage.http_config (
HttpConfig|None) – HTTP transport configuration (proxy, timeouts, retries).
- answer_callback_query(callback_query_id, user_id, peer_id, event_data=None, text=None)[исходный код]¶
Send a response to a callback button press.
- Параметры:
callback_query_id (
str) – Callback event ID.user_id (
int) – User who pressed the button.peer_id (
int) – Peer where the button was pressed.event_data (
dict[str,Any] |None) – Event data dict (serialised to JSON automatically).text (
str|None) – Shortcut — show a snackbar with this text.
- Тип результата:
dict[str,Any]
- callback_query_handler(func=None, data=None, state=None)[исходный код]¶
Decorator for handling callback events (inline button presses).
Handles
message_eventtype events from VK API.- Параметры:
func (
Callable[...,Any] |None) – Custom filter function (takes CallbackQuery).data (
str|Pattern[str] |None) – String or regex pattern for callback_data filtering.state (
str|list[str] |None) – FSM state(s) that trigger this handler.
- Тип результата:
Callable[...,Any]
- close()[исходный код]¶
Close the DI container and release resources.
- Тип результата:
None
- get_state(user_id)[исходный код]¶
- Тип результата:
str|None
- get_state_data(user_id)[исходный код]¶
- Тип результата:
dict[str,Any]
- property group_id: int¶
- message_handler(commands=None, regexp=None, func=None, content_types=None, chat_types=None, state=None)[исходный код]¶
Decorator for registering incoming message handlers.
- Параметры:
commands (
list[str] |None) – List of commands (without „/“), e.g. [„start“, „help“].regexp (
str|None) – Regular expression for text filtering.func (
Callable[...,Any] |None) – Custom filter function (takes Message, returns bool).content_types (
list[str] |None) – Content types („text“, „photo“, „doc“, etc.).chat_types (
list[str] |None) – Chat types („private“, „group“).state (
str|list[str] |None) – FSM state(s) that trigger this handler.
- Тип результата:
Callable[...,Any]
- middleware_handler(update_types=None)[исходный код]¶
Decorator for registering middleware.
Middleware is called before handlers. If it returns False, event processing is stopped.
- Параметры:
update_types (
list[str] |None) – Event types to filter (None = all).- Тип результата:
Callable[...,Any]
- polling(non_stop=True, interval=1)[исходный код]¶
Start Long Poll server polling.
Uses Bots Long Poll API to receive events.
- Параметры:
non_stop (
bool) – If True, restarts on errors.interval (
int) – Delay between retries on error (seconds).
- Тип результата:
None
- reply_to(message, text, **kwargs)[исходный код]¶
Reply to a message (automatically uses chat_id and reply_to).
- Тип результата:
dict[str,Any]
- reset_state(user_id)[исходный код]¶
- Тип результата:
None
- send_document(chat_id, document, caption=None, reply_markup=None, **kwargs)[исходный код]¶
Send a document.
Uploads via
docs.getMessagesUploadServerand sends.- Параметры:
chat_id (
int) – User or conversation ID.document (
str|bytes|BinaryIO) – File path, bytes, or file-like object.caption (
str|None) – Document caption.reply_markup (
ReplyKeyboardMarkup|InlineKeyboardMarkup|None) – Keyboard.
- Тип результата:
dict[str,Any]
- send_message(chat_id, text, reply_markup=None, reply_to=None, **kwargs)[исходный код]¶
Send a text message to a user or chat.
Uses VK API method
messages.send.- Параметры:
chat_id (
int) – User or conversation ID.text (
str) – Message text.reply_markup (
ReplyKeyboardMarkup|InlineKeyboardMarkup|None) – Keyboard (ReplyKeyboardMarkup or InlineKeyboardMarkup).reply_to (
int|None) – ID of the message to reply to.**kwargs (
Any) – Additional VK API parameters.
- Тип результата:
dict[str,Any]- Результат:
VK API response.
- send_photo(chat_id, photo, caption=None, reply_markup=None, **kwargs)[исходный код]¶
Send a photo.
Uploads via
photos.getMessagesUploadServerand sends.- Параметры:
chat_id (
int) – User or conversation ID.photo (
str|bytes|BinaryIO) – File path, bytes, or file-like object.caption (
str|None) – Photo caption.reply_markup (
ReplyKeyboardMarkup|InlineKeyboardMarkup|None) – Keyboard.
- Тип результата:
dict[str,Any]
- set_state(user_id, state)[исходный код]¶
- Тип результата:
None
- stop_polling()[исходный код]¶
- Тип результата:
None
- property token: str¶
- update_state_data(user_id, **kwargs)[исходный код]¶
- Тип результата:
None
Types¶
- class vk_bot.types.Audio(**data)[исходный код]¶
Базовые классы:
BaseModel-
artist:
str¶
- property attachment: str¶
-
duration:
int¶
-
id:
int¶
- model_config: ClassVar[ConfigDict] = {}¶
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
-
owner_id:
int¶
-
title:
str¶
-
url:
str|None¶
-
artist:
- class vk_bot.types.CallbackQuery(**data)[исходный код]¶
Базовые классы:
BaseModelCallback event from an inline button press.
Corresponds to a
message_eventin VK API.-
data:
str|None¶
- extract_data_from_payload()[исходный код]¶
- Тип результата:
-
from_id:
int¶
-
id:
str¶
-
message_id:
int¶
- model_config: ClassVar[ConfigDict] = {'arbitrary_types_allowed': True}¶
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- model_post_init(context, /)¶
This function is meant to behave like a BaseModel method to initialise private attributes.
It takes context as an argument since that’s what pydantic-core passes when calling it.
- Параметры:
self (
BaseModel) – The BaseModel instance.context (
Any) – The context.
- Тип результата:
None
- classmethod parse_payload(v)[исходный код]¶
- Тип результата:
Any
-
payload:
dict[str,Any] |None¶
-
peer_id:
int¶
-
data:
- class vk_bot.types.Chat(**data)[исходный код]¶
Базовые классы:
BaseModel- classmethod from_peer_id(peer_id)[исходный код]¶
- Тип результата:
-
id:
int¶
- model_config: ClassVar[ConfigDict] = {}¶
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
-
photo_100:
str|None¶
-
title:
str|None¶
-
type:
str¶
- class vk_bot.types.Document(**data)[исходный код]¶
Базовые классы:
BaseModel-
access_key:
str|None¶
- property attachment: str¶
-
ext:
str¶
-
id:
int¶
- model_config: ClassVar[ConfigDict] = {}¶
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
-
owner_id:
int¶
-
size:
int¶
-
title:
str¶
-
url:
str|None¶
-
access_key:
- class vk_bot.types.InlineKeyboardButton(**data)[исходный код]¶
Базовые классы:
BaseModelInline keyboard button (callback, link, or VK App).
-
callback_data:
str|None¶
-
hash:
str|None¶
- model_config: ClassVar[ConfigDict] = {'extra': 'forbid'}¶
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
-
owner_id:
int|None¶
-
text:
str¶
- to_dict()[исходный код]¶
- Тип результата:
dict[str,Any]
-
url:
str|None¶
-
vk_app_id:
int|None¶
-
callback_data:
- class vk_bot.types.InlineKeyboardMarkup(**data)[исходный код]¶
Базовые классы:
BaseModelInline keyboard embedded in a message.
Callback buttons send a
message_event.- add(*buttons)[исходный код]¶
- Тип результата:
-
keyboard:
list[list[InlineKeyboardButton]]¶
- model_config: ClassVar[ConfigDict] = {}¶
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- row(*buttons)[исходный код]¶
- Тип результата:
- to_dict()[исходный код]¶
- Тип результата:
dict[str,Any]
- class vk_bot.types.KeyboardButton(**data)[исходный код]¶
Базовые классы:
BaseModelReply keyboard button.
-
color:
str¶
- model_config: ClassVar[ConfigDict] = {'extra': 'forbid'}¶
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
-
text:
str¶
- to_dict()[исходный код]¶
- Тип результата:
dict[str,Any]
-
color:
- class vk_bot.types.Message(**data)[исходный код]¶
Базовые классы:
BaseModelIncoming message.
Corresponds to the
messageobject inmessage_newVK API event.-
action:
dict[str,Any] |None¶
-
attachments:
list[dict[str,Any]]¶
- property content_type: str¶
-
date:
datetime¶
-
deleted:
bool¶
-
from_id:
int¶
-
fwd_messages:
list[Message]¶
- get_documents()[исходный код]¶
- Тип результата:
list[Document]
- get_photos()[исходный код]¶
- Тип результата:
list[Photo]
-
id:
int¶
-
important:
bool¶
- property is_private: bool¶
- model_config: ClassVar[ConfigDict] = {'arbitrary_types_allowed': True}¶
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- model_post_init(context, /)¶
This function is meant to behave like a BaseModel method to initialise private attributes.
It takes context as an argument since that’s what pydantic-core passes when calling it.
- Параметры:
self (
BaseModel) – The BaseModel instance.context (
Any) – The context.
- Тип результата:
None
-
out:
bool¶
-
payload:
dict[str,Any] |None¶
-
peer_id:
int¶
- reply_message: Message | None¶
-
text:
str¶
-
action:
- class vk_bot.types.Photo(**data)[исходный код]¶
Базовые классы:
BaseModel-
access_key:
str|None¶
- property attachment: str¶
-
id:
int¶
- model_config: ClassVar[ConfigDict] = {}¶
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
-
owner_id:
int¶
-
sizes:
list[dict[str,Any]]¶
- property url: str | None¶
-
access_key:
- class vk_bot.types.ReplyKeyboardMarkup(**data)[исходный код]¶
Базовые классы:
BaseModelReply keyboard displayed below the input field.
Corresponds to the
keyboardobject in VK API.- add(*buttons)[исходный код]¶
- Тип результата:
-
keyboard:
list[list[KeyboardButton]]¶
- model_config: ClassVar[ConfigDict] = {}¶
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
-
one_time_keyboard:
bool¶
- row(*buttons)[исходный код]¶
- Тип результата:
- to_dict()[исходный код]¶
- Тип результата:
dict[str,Any]
- class vk_bot.types.Update(**data)[исходный код]¶
Базовые классы:
BaseModelUpdate from VK Long Poll server.
Contains event type and data object. Supports lazy parsing of message and callback_query.
- property callback_query: CallbackQuery | None¶
- model_config: ClassVar[ConfigDict] = {'arbitrary_types_allowed': True, 'extra': 'allow'}¶
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- model_post_init(context, /)¶
This function is meant to behave like a BaseModel method to initialise private attributes.
It takes context as an argument since that’s what pydantic-core passes when calling it.
- Параметры:
self (
BaseModel) – The BaseModel instance.context (
Any) – The context.
- Тип результата:
None
-
object:
dict[str,Any]¶
-
type:
str¶
-
update_id:
int¶
- classmethod validate_type(v)[исходный код]¶
- Тип результата:
str
- class vk_bot.types.User(**data)[исходный код]¶
Базовые классы:
BaseModelVK user object.
Corresponds to the
userobject in VK API.-
can_access_closed:
bool¶
-
first_name:
str¶
- property full_name: str¶
-
id:
int¶
-
is_closed:
bool¶
-
last_name:
str¶
- property mention: str¶
- model_config: ClassVar[ConfigDict] = {}¶
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
-
online:
bool¶
-
photo_100:
str|None¶
-
can_access_closed:
- class vk_bot.types.Video(**data)[исходный код]¶
Базовые классы:
BaseModel-
access_key:
str|None¶
- property attachment: str¶
-
description:
str¶
-
duration:
int¶
-
id:
int¶
- model_config: ClassVar[ConfigDict] = {}¶
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
-
owner_id:
int¶
-
title:
str¶
-
access_key:
- vk_bot.types.build_attachment_string(owner_id, media_id, access_key=None)[исходный код]¶
Build a VK attachment string like
photo-123_456orphoto-123_456_key.- Тип результата:
str
- vk_bot.types.parse_attachment_string(attachment)[исходный код]¶
Parse a VK attachment string (e.g.
photo123_456_key).- Тип результата:
tuple[str|None,int|None,int|None,str|None]- Результат:
Tuple of
(type, owner_id, media_id, access_key).
FSM¶
Transitions¶
- class vk_bot.state.fsm.VKBotFSM(name='default')[исходный код]¶
Finite-state-machine graph shared across all users.
Use
set_initial(),add_state(),add_transition()to define the graph, then letStateContextdrive per-user transitions.- Параметры:
name (
str) – Identifier used byFSMRegistry.
- add_state(state, group=None, on_enter=None, on_exit=None, **kwargs)[исходный код]¶
Register a state in the graph.
- Параметры:
state (
str) – State name.group (
str|None) – Optional group name for grouping related states.on_enter (
Callable[...,Any] |None) – Callback invoked when entering this state.on_exit (
Callable[...,Any] |None) – Callback invoked when exiting this state.
- Тип результата:
- add_transition(from_state, to_state, condition=None, action=None, **kwargs)[исходный код]¶
Register an allowed transition between two states.
- Параметры:
from_state (
str) – Source state.to_state (
str) – Destination state.condition (
Callable[...,Any] |None) – Callable(context) -> bool; transition is blocked if it returnsFalse.action (
Callable[...,Any] |None) – Callable invoked during the transition.
- Тип результата:
- can_transition(from_state, to_state, context=None)[исходный код]¶
Return
Trueif the transitionfrom_state → to_stateis allowed.A transition is allowed when it exists in the graph and all registered conditions evaluate to
True.If
from_stateisNoneor no Machine has been defined, every transition is permitted (open FSM).- Тип результата:
bool
- execute_transition(from_state, to_state, context=None)[исходный код]¶
Execute callbacks associated with a transition.
Runs (in order): on_exit of
from_state, transitionaction, on_enter ofto_state.Does not store any state — the caller is responsible for persisting the new state to storage.
- Параметры:
from_state (
str|None) – Current state (Nonefor the very first transition).to_state (
str) – Destination state.context (
Any) – Arbitrary context object forwarded to each callback.
- Тип результата:
None
- get_next_states(from_state, context=None)[исходный код]¶
Return the list of states reachable from
from_state.Deduplicates destinations so each state appears at most once.
- Тип результата:
list[str]
- is_in_group(state, group)[исходный код]¶
Return
Trueifstatebelongs togroup.- Параметры:
state (
str) – The current state string (read from storage by the caller).group (
str) – Group name to check membership in.
- Тип результата:
bool
- set_initial(state)[исходный код]¶
Set the initial state and create the internal Machine graph.
Must be called before
add_state()oradd_transition().- Параметры:
state (
str) – Name of the initial state.- Тип результата:
- class vk_bot.state.fsm.FSMRegistry[исходный код]¶
Global registry of named
VKBotFSMinstances.One FSM graph is defined per logical flow (e.g.
"registration"). It is shared between all users; it does not store per-user state.- classmethod clear()[исходный код]¶
Remove all registered FSMs (primarily used in tests).
- Тип результата:
None
- classmethod get_or_create(name)[исходный код]¶
Return an existing FSM by name or create a fresh one.
- Тип результата:
- classmethod register(name, fsm)[исходный код]¶
Manually register a pre-built FSM under
name.- Тип результата:
None
StatesGroup¶
- class vk_bot.state.group.StatesGroup[исходный код]¶
- classmethod get_all_states()[исходный код]¶
- Тип результата:
list[str]
- classmethod get_state(name)[исходный код]¶
- Тип результата:
str|None
- classmethod is_in_group(state)[исходный код]¶
- Тип результата:
bool
- class vk_bot.state.manager.State(name=None)[исходный код]¶
StateContext¶
- class vk_bot.state.context.StateContext(bot, user_id, fsm_name='default')[исходный код]¶
User state context.
Provides a convenient interface for managing FSM states and user data within handlers.
- Параметры:
bot (
VKBot) – VKBot instance.user_id (
int) – User ID.fsm_name (
str) – Finite state machine name.
- clear_data()[исходный код]¶
Clear all user data without resetting the state.
- Тип результата:
None
- property current: str | None¶
Current state of this user, read from storage.
- property data: dict[str, Any]¶
User data stored alongside the state.
- finish()[исходный код]¶
Reset the user’s state and clear all stored data.
- Тип результата:
None
-
fsm_name:
str¶
- get()[исходный код]¶
Return the current state (alias for
current).- Тип результата:
str|None
- get_next_states()[исходный код]¶
Return all states reachable from the user’s current state.
- Тип результата:
list[str]
- is_in_group(group)[исходный код]¶
Return
Trueif the user’s current state belongs togroup.- Тип результата:
bool
- is_state(state)[исходный код]¶
Return
Trueif the user is currently instate.- Тип результата:
bool
- set(state)[исходный код]¶
Transition the user to
state.Validates the transition against the FSM graph, executes any registered callbacks, then persists the new state to storage.
- Исключение:
ValueError – If the transition is not allowed by the graph.
- Тип результата:
bool
- update(**kwargs)[исходный код]¶
Merge
kwargsinto the user’s stored data.- Тип результата:
None
-
user_id:
int¶
Storage¶
- class vk_bot.state.storage.BaseStorage[исходный код]¶
Abstract base class for state storage backends.
- abstract delete(user_id)[исходный код]¶
- Тип результата:
None
- abstract get_data(user_id)[исходный код]¶
- Тип результата:
dict[str,Any]
- abstract get_state(user_id)[исходный код]¶
- Тип результата:
str|None
- abstract set_data(user_id, data)[исходный код]¶
- Тип результата:
None
- abstract set_state(user_id, state)[исходный код]¶
- Тип результата:
None
- abstract update_data(user_id, **kwargs)[исходный код]¶
- Тип результата:
None
- class vk_bot.state.storage.MemoryStorage[исходный код]¶
Базовые классы:
BaseStorageIn-memory state storage.
Data is lost on restart. Suitable for development.
- delete(user_id)[исходный код]¶
- Тип результата:
None
- get_data(user_id)[исходный код]¶
- Тип результата:
dict[str,Any]
- get_state(user_id)[исходный код]¶
- Тип результата:
str|None
- set_data(user_id, data)[исходный код]¶
- Тип результата:
None
- set_state(user_id, state)[исходный код]¶
- Тип результата:
None
- update_data(user_id, **kwargs)[исходный код]¶
- Тип результата:
None
- class vk_bot.state.storage.RedisStorage(host='localhost', port=6379, db=0, password=None)[исходный код]¶
Базовые классы:
BaseStorageRedis-backed state storage.
Persistent storage. Suitable for production.
- delete(user_id)[исходный код]¶
- Тип результата:
None
- get_data(user_id)[исходный код]¶
- Тип результата:
dict[str,Any]
- get_state(user_id)[исходный код]¶
- Тип результата:
str|None
- set_data(user_id, data)[исходный код]¶
- Тип результата:
None
- set_state(user_id, state)[исходный код]¶
- Тип результата:
None
- update_data(user_id, **kwargs)[исходный код]¶
- Тип результата:
None
- class vk_bot.state.storage.PostgresStorage(dsn, table_prefix='vk_bot')[исходный код]¶
Базовые классы:
BaseStoragePostgreSQL-backed state storage using psycopg3 (synchronous).
Persistent storage with full transaction support. Suitable for production.
Requires the
postgresextra:pip install vk-bot[postgres].- Параметры:
dsn (
str) – PostgreSQL connection string, e.g.postgresql://user:pass@localhost/dbname.table_prefix (
str) – Prefix for the tables created by this storage.
- close()[исходный код]¶
Close the database connection.
- Тип результата:
None
- delete(user_id)[исходный код]¶
- Тип результата:
None
- get_data(user_id)[исходный код]¶
- Тип результата:
dict[str,Any]
- get_state(user_id)[исходный код]¶
- Тип результата:
str|None
- set_data(user_id, data)[исходный код]¶
- Тип результата:
None
- set_state(user_id, state)[исходный код]¶
- Тип результата:
None
- update_data(user_id, **kwargs)[исходный код]¶
- Тип результата:
None
HttpConfig¶
- class vk_bot.config.HttpConfig(**data)[исходный код]¶
HTTP transport settings.
-
long_poll_timeout:
int¶
- model_config: ClassVar[ConfigDict] = {}¶
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
-
proxy:
str|None¶
-
retries:
int¶
-
timeout:
int¶
-
user_agent:
str¶
-
long_poll_timeout:
Exceptions¶
- class vk_bot.exception.VKAPIError(error_code, error_msg, request_params=None)[исходный код]¶
Utilities¶
- vk_bot.util.create_link(text, url)[исходный код]¶
Build a VK-formatted link:
[url|text].- Тип результата:
str
- vk_bot.util.format_time(timestamp)[исходный код]¶
Format a Unix timestamp to a human-readable string.
- Тип результата:
str
- vk_bot.util.split_text(text, max_length=4096)[исходный код]¶
Split long text into parts for sending.
VK API limits messages to 4096 characters. Splits by lines and words without breaking words.
- Тип результата:
list[str]
Handlers¶
- vk_bot.handlers.extract_command(text)[исходный код]¶
Extract command and arguments from message text.
- Параметры:
text (
str) – Message text, e.g./start hello.- Тип результата:
tuple[str|None,str|None]- Результат:
Tuple of
(command, args), e.g.('start', 'hello'). Both values areNoneif the text is not a command.
- vk_bot.handlers.extract_mentions(text)[исходный код]¶
Extract mentioned user IDs from text.
Supports
[id123|Name]and@id123formats.- Тип результата:
list[int]
- vk_bot.handlers.is_group_event(event_type)[исходный код]¶
Return True if the event type belongs to the community events group.
- Тип результата:
bool