Skip to main content

Async VK bot framework with FastAPI-style decorators and aiogram-style FSM

Project description

Async VK bot framework with FastAPI-style decorators and aiogram-style FSM.

Package version Supported Python versions GitHub Stars License


Source Code: https://github.com/ndugram/fastvk


FastVK is a modern async VK bot framework for Python. It brings a decorator-based handler API — similar to FastAPI and aiogram, but for VK — with FSM, middleware, filters, and clean dependency injection out of the box.

Key features:

  • Familiar — if you know FastAPI or aiogram, you already know FastVK. Same patterns, same ergonomics.
  • Async — built on aiohttp with full async/await support from top to bottom.
  • FSM — built-in Finite State Machine with State, StatesGroup, and pluggable storage backends.
  • FiltersCommand, Text, StateFilter, FromUser, IsChat and custom filters via any callable.
  • Injection — handler parameters injected by name: message, state, api, update — no manual wiring.
  • Routers — split handlers across multiple Router instances, include them into the main bot.
  • Middleware — intercept every update before and after handlers with BaseMiddleware.
  • Typed — full type annotations throughout; works great with mypy and pyright.

Requirements

Python 3.10+

FastVK depends on:

  • aiohttp — async HTTP transport for Long Poll and VK API calls.
  • annotated-docDoc() annotations for rich parameter documentation.

Installation

$ pip install fastvk

---> 100%

Example

Create it

Create a file main.py:

from fastvk import FastVK
from fastvk.filters import Command
from fastvk.types import Message

bot = FastVK(token="vk1.a.YOUR_TOKEN", group_id=123456789)


@bot.message(Command("start"))
async def start(message: Message) -> None:
    await message.answer("Привет! Я FastVK бот 🤖")


if __name__ == "__main__":
    bot.run_polling()

Run it

$ python main.py

Check it

You will see output like:

INFO  fastvk  FastVK started (group_id=123456789)
INFO  fastvk  Polling started

Send /start to your bot — it replies instantly.

Upgrade the example

With FSM (multi-step forms)...

Use StatesGroup and State to collect data across multiple messages:

from fastvk import FastVK
from fastvk.filters import Command, StateFilter
from fastvk.fsm import FSMContext, State, StatesGroup
from fastvk.types import Message

bot = FastVK(token="vk1.a.YOUR_TOKEN", group_id=123456789)


class RegistrationForm(StatesGroup):
    waiting_name = State()
    waiting_age  = State()


@bot.message(Command("start"))
async def cmd_start(message: Message, state: FSMContext) -> None:
    await state.set_state(RegistrationForm.waiting_name)
    await message.answer("Как тебя зовут?")


@bot.message(StateFilter(RegistrationForm.waiting_name))
async def got_name(message: Message, state: FSMContext) -> None:
    await state.update_data(name=message.text)
    await state.set_state(RegistrationForm.waiting_age)
    await message.answer(f"Отлично, {message.text}! Сколько тебе лет?")


@bot.message(StateFilter(RegistrationForm.waiting_age))
async def got_age(message: Message, state: FSMContext) -> None:
    data = await state.update_data(age=message.text)
    await state.clear()
    await message.answer(
        f"Готово!\nИмя: {data['name']}\nВозраст: {data['age']}"
    )


if __name__ == "__main__":
    bot.run_polling()
With routers...

Split handlers into separate modules and include them into the bot:

from fastvk import FastVK, Router
from fastvk.filters import Command, Text
from fastvk.types import Message

shop_router = Router()


@shop_router.message(Command("catalog"))
async def catalog(message: Message) -> None:
    await message.answer("📦 Наш каталог: ...")


@shop_router.message(Text("цена", contains=True, ignore_case=True))
async def price_mention(message: Message) -> None:
    await message.answer("Цены начинаются от 99₽")


bot = FastVK(token="vk1.a.YOUR_TOKEN", group_id=123456789)
bot.include_router(shop_router)

if __name__ == "__main__":
    bot.run_polling()
With middleware...

Intercept every incoming update to add logging, rate limiting, or custom data:

from collections.abc import Awaitable, Callable
from typing import Any

from fastvk import FastVK
from fastvk.middleware import BaseMiddleware
from fastvk.filters import Command
from fastvk.types import Message


class LoggingMiddleware(BaseMiddleware):
    async def __call__(
        self,
        handler: Callable[[Any, dict], Awaitable[Any]],
        event: Any,
        data: dict,
    ) -> Any:
        print(f"→ incoming: {type(event).__name__}")
        result = await handler(event, data)
        print(f"← handled")
        return result


bot = FastVK(
    token="vk1.a.YOUR_TOKEN",
    group_id=123456789,
    middleware=[LoggingMiddleware()],
)


@bot.message(Command("ping"))
async def ping(message: Message) -> None:
    await message.answer("pong")


if __name__ == "__main__":
    bot.run_polling()
With filters...

Combine built-in and custom filters on any handler:

from fastvk import FastVK
from fastvk.filters import Command, FromUser, IsChat, Text
from fastvk.types import Message

ADMIN_ID = 123456789

bot = FastVK(token="vk1.a.YOUR_TOKEN", group_id=987654321)


@bot.message(Command("ban"), FromUser(ADMIN_ID))
async def admin_ban(message: Message) -> None:
    await message.answer("Пользователь заблокирован.")


@bot.message(IsChat("private"), Text("помощь", contains=True, ignore_case=True))
async def help_in_pm(message: Message) -> None:
    await message.answer("Список команд: /start, /help")


def is_long_message(message: Message, data: dict) -> bool:
    return len(message.text or "") > 200


@bot.message(is_long_message)
async def long_message(message: Message) -> None:
    await message.answer("Это очень длинное сообщение!")


if __name__ == "__main__":
    bot.run_polling()
With raw VK API calls...

Access the full VK API via the injected api parameter:

from fastvk import FastVK
from fastvk import Bot
from fastvk.filters import Command
from fastvk.types import Message

bot = FastVK(token="vk1.a.YOUR_TOKEN", group_id=123456789)


@bot.message(Command("me"))
async def cmd_me(message: Message, bot: Bot) -> None:
    users = await bot.users.get(user_ids=message.from_id, fields="photo_200")
    name = f"{users[0]['first_name']} {users[0]['last_name']}"
    await message.answer(f"Ты: {name}")


@bot.message(Command("members"))
async def cmd_members(message: Message, bot: Bot) -> None:
    data = await bot.groups.getMembers(group_id=app.group_id, count=1)
    await message.answer(f"Участников в группе: {data['count']}")


if __name__ == "__main__":
    bot.run_polling()
With event handlers...

Handle any VK event type — not just messages:

from fastvk import FastVK
from fastvk import Bot
from fastvk.types import Update

bot = FastVK(token="vk1.a.YOUR_TOKEN", group_id=123456789)


@bot.group_join()
async def on_join(event: dict, bot: Bot) -> None:
    user_id = event.get("user_id")
    await api.messages.send(
        peer_id=user_id,
        message="Добро пожаловать в группу!",
        random_id=0,
    )


@bot.wall_post_new()
async def on_new_post(event: dict) -> None:
    print(f"Новый пост: {event.get('id')}")


@bot.on("photo_new")
async def on_photo(update: Update) -> None:
    print(f"Новое фото: {update.object}")


if __name__ == "__main__":
    bot.run_polling()

Dependency injection

Handler parameters are injected by type — declare what you need, framework provides it. No manual wiring:

Type What you get
Message Parsed incoming message (for message_new events)
FSMContext FSM context for current user
Bot VK Bot API client
Update Full raw update object
@router.message()
async def handler(
    message: Message,
    state: FSMContext,
    bot: Bot,
) -> None:
    ...

Contributing

Contributions are welcome! Please open an issue before submitting a pull request.

Found a bug? Open an issue on GitHub.

License

This project is licensed under the terms of the MIT license.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

fastvk-0.0.2.tar.gz (20.4 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

fastvk-0.0.2-py3-none-any.whl (22.3 kB view details)

Uploaded Python 3

File details

Details for the file fastvk-0.0.2.tar.gz.

File metadata

  • Download URL: fastvk-0.0.2.tar.gz
  • Upload date:
  • Size: 20.4 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.13.13

File hashes

Hashes for fastvk-0.0.2.tar.gz
Algorithm Hash digest
SHA256 f7c378851bbad6822c3ca002a0c897cda98e37fd1e40955e5a6c34fd25653425
MD5 b452345ebb04b6a940e07342c2733ec0
BLAKE2b-256 3a220553064f4d8d7662aec3961e0d4f661bc6cb43849a29a34592bdaac4d9b7

See more details on using hashes here.

File details

Details for the file fastvk-0.0.2-py3-none-any.whl.

File metadata

  • Download URL: fastvk-0.0.2-py3-none-any.whl
  • Upload date:
  • Size: 22.3 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.13.13

File hashes

Hashes for fastvk-0.0.2-py3-none-any.whl
Algorithm Hash digest
SHA256 1d240471c1f9711c438381301b82ee716bc0e06032f38cb3a81f70606b9c2ac4
MD5 ec07e8e4a9c090ea531b9cfba421b848
BLAKE2b-256 e7e8b7385ec86dafb8885a8436a315de37733c140876c07f928249f2df73dbc2

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page