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.2.4.tar.gz (14.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.2.4-py3-none-any.whl (22.4 kB view details)

Uploaded Python 3

File details

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

File metadata

  • Download URL: aionvk-0.2.4.tar.gz
  • Upload date:
  • Size: 14.9 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/2.1.4 CPython/3.11.9 Windows/10

File hashes

Hashes for aionvk-0.2.4.tar.gz
Algorithm Hash digest
SHA256 41d6c5f23b638d11b7c6b403ce8639dacd7575dc90922c4b3bff432fc6de8ba2
MD5 1b872c983fc616eebe85678eb8900acd
BLAKE2b-256 cede81c2839642982c829dee4cd516027861c1ace1fc3509e7207c56796f7f5d

See more details on using hashes here.

File details

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

File metadata

  • Download URL: aionvk-0.2.4-py3-none-any.whl
  • Upload date:
  • Size: 22.4 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/2.1.4 CPython/3.11.9 Windows/10

File hashes

Hashes for aionvk-0.2.4-py3-none-any.whl
Algorithm Hash digest
SHA256 19d7c5945e985512c977ba4f0545021c5845799a000fcd50b783dc0d48e4efa7
MD5 0416703252ece08329239b9cea445ae0
BLAKE2b-256 d05a91e55962590a41e4245e2ad09d56cea3d04ed8bc221b7711e607cf0a5429

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