Skip to main content

Asynchronous VK API framework for building bots

Project description

aionvk

PyPI - Version Python Versions License: MIT

📦 Установка

pip install aionvk

quickstart Быстрый старт: Эхо-бот за 1 минуту

Этот простой бот будет отвечать на любое текстовое сообщение, отправляя его обратно пользователю.

# echo_bot.py
import asyncio
import os

from aiohttp import web
from dotenv import load_dotenv

from aionvk import Bot, Dispatcher, F, Router
from aionvk.types import Message

load_dotenv()

# Замените на ваши данные в .env файле
VK_TOKEN = os.getenv("VK_BOT_TOKEN")
VK_SECRET = os.getenv("VK_CALLBACK_SECRET")
VK_CONFIRMATION_TOKEN = os.getenv("VK_CALLBACK_CONFIRMATION_TOKEN")

# 1. Инициализация компонентов
router = Router()
bot = Bot(token=VK_TOKEN)
dp = Dispatcher()

# 2. Создание обработчика
@router.message(F.text) # Сработает на любое сообщение с текстом
async def echo_handler(event: Message, bot: Bot):
    await bot.send_message(
        peer_id=event.peer_id,
        text=f"Вы написали: {event.text}"
    )

# 3. Настройка веб-сервера для Callback API
async def handle_vk_callback(request: web.Request):
    data = await request.json()
    if data.get("secret") != VK_SECRET: return web.Response(status=403)
    if data.get("type") == "confirmation": return web.Response(text=VK_CONFIRMATION_TOKEN)
    
    # Передаем событие и объект бота в диспетчер
    asyncio.create_task(dp.feed_raw_event(data, bot=bot))
    return web.Response(text="ok")

async def main():
    dp.include_router(router) # Регистрируем наши обработчики
    
    app = web.Application()
    app.router.add_post("/callback", handle_vk_callback)
    
    # Не забудьте закрыть сессию бота при выходе
    app.on_shutdown.append(lambda _: bot.close())

    await web.run_app(app, host='localhost', port=8080)

if __name__ == "__main__":
    asyncio.run(main())

✨ Примеры использования

Клавиатуры и Callback-кнопки

aionvk позволяет легко создавать inline-клавиатуры.

from aionvk import KeyboardBuilder, Button, F
from aionvk.types import Message, Callback

router = Router()

@router.message(F.text.lower() == "/start")
async def start_with_keyboard(event: Message, bot: Bot):
    kb = KeyboardBuilder(inline=True)
    kb.add(Button.callback("Нажми меня!", payload={"cmd": "button_pressed"}))
    
    await bot.send_message(
        peer_id=event.peer_id,
        text="Это кнопка!",
        keyboard=kb.build()
    )

@router.callback(F.payload["cmd"] == "button_pressed")
async def button_handler(event: Callback, bot: Bot):
    # Убираем "часики" и показываем уведомление
    await bot.show_snackbar(event, text="Кнопка была нажата!")

Машина Состояний (FSM)

Создавайте сложные диалоги с помощью StatesGroup и FSMContext.

from aionvk.bot.fsm import FSMContext, State, StatesGroup

class Registration(StatesGroup):
    waiting_for_name = State()
    waiting_for_age = State()

@router.message(F.text.lower() == "/reg")
async def start_registration(event: Message, state: FSMContext, bot: Bot):
    await state.set_state(Registration.waiting_for_name)
    await bot.send_message(event.peer_id, "Введите ваше имя:")

@router.message(state=Registration.waiting_for_name)
async def name_entered(event: Message, state: FSMContext, bot: Bot):
    await state.update_data(name=event.text)
    await state.set_state(Registration.waiting_for_age)
    await bot.send_message(event.peer_id, "Отлично! Теперь введите ваш возраст:")

@router.message(state=Registration.waiting_for_age)
async def age_entered(event: Message, state: FSMContext, bot: Bot):
    if not event.text.isdigit():
        return await bot.send_message(event.peer_id, "Возраст должен быть числом!")
        
    user_data = await state.get_data()
    name = user_data.get("name")
    age = event.text
    
    await bot.send_message(event.peer_id, f"Регистрация завершена!\nИмя: {name}, Возраст: {age}")
    await state.clear()

🗺️ Дальнейшие планы

  • Тестирование: Покрытие кода юнит-тестами для обеспечения стабильности.
  • Расширение API: Добавление поддержки других типов событий, загрузки фото и т.д.
  • Документация: Создание полноценной документации по всем компонентам.

🤝 Участие в разработке

Проект находится на ранней стадии. Любые предложения, сообщения об ошибках (issues) и pull-реквесты приветствуются!

📜 Лицензия

Проект распространяется под лицензией MIT.

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

aionvk-0.3.0.tar.gz (15.9 kB view details)

Uploaded Source

Built Distribution

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

aionvk-0.3.0-py3-none-any.whl (23.8 kB view details)

Uploaded Python 3

File details

Details for the file aionvk-0.3.0.tar.gz.

File metadata

  • Download URL: aionvk-0.3.0.tar.gz
  • Upload date:
  • Size: 15.9 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/2.2.0 CPython/3.13.7 Windows/11

File hashes

Hashes for aionvk-0.3.0.tar.gz
Algorithm Hash digest
SHA256 9222102f9fd24ca30ea1171efba4b2aeab3dbd3178bcdc6029d2e31cbc2de58f
MD5 39c939e1a35fa87e5ae6a0db30083e7b
BLAKE2b-256 a565505799413fbefcc1266f9b38fd9b69d32a8f7a5c43c2221fb9a555926a44

See more details on using hashes here.

File details

Details for the file aionvk-0.3.0-py3-none-any.whl.

File metadata

  • Download URL: aionvk-0.3.0-py3-none-any.whl
  • Upload date:
  • Size: 23.8 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/2.2.0 CPython/3.13.7 Windows/11

File hashes

Hashes for aionvk-0.3.0-py3-none-any.whl
Algorithm Hash digest
SHA256 6cf5a42ff98e7e3b230efc11f8d2bb40e43c138bdc91133fc049270e6bcf9d92
MD5 b0bea21b82bece18d01747622dddcfdf
BLAKE2b-256 678a045f3801587eda9a31447e00f41af1bca8aade482b378aac0b07b6b0ba25

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