aiostep


Nameaiostep JSON
Version 0.2.0 PyPI version JSON
download
home_pagehttps://github.com/NasrollahYusefi/aiostep/
SummaryA Python library to handle steps in aiogram framework.
upload_time2024-10-18 22:25:08
maintainerNone
docs_urlNone
authorNasrollah Yusefi
requires_python>=3.8
licenseMIT
keywords aiogram steps states telegram bot asynchronous aiostep
VCS
bugtrack_url
requirements cachebox
Travis-CI No Travis.
coveralls test coverage No coveralls.
            ![PyPI Version](https://img.shields.io/pypi/v/aiostep)
![Python Version](https://img.shields.io/pypi/pyversions/aiostep)
![License](https://img.shields.io/pypi/l/aiostep)
![Total Downloads](https://static.pepy.tech/badge/aiostep)
![Downloads](https://img.shields.io/pypi/dm/aiostep)

# aiostep

**aiostep** is an extension library for [aiogram](https://github.com/aiogram/aiogram), designed to streamline building Telegram bots in Python. It simplifies user interactions by providing intuitive methods for handling conversations and state management.

---

## Key Features

- **Direct User Interaction**: Easily ask questions and receive user responses directly within handlers, reducing boilerplate code.
- **Step-Based Flow**: Seamlessly manage multi-step conversation flows with support for dynamic callbacks.
- **State Management**: Built-in state management with support for both in-memory and Redis-based storage options.

---

## Installation

To install the latest version of `aiostep`, run:

```bash
pip install -U aiostep
```

---

## Quick Start

### 1. Middleware Integration

To use `aiostep`, add the `Listen` middleware to your `Dispatcher` instance:

```python
from aiogram import Dispatcher
from aiostep import Listen

dp = Dispatcher()
dp.message.outer_middleware(Listen())
```

### 2. Direct Interaction Using `wait_for`

With `aiostep`, you can wait for a user's response directly within a handler using the `wait_for` function:

```python
import aiostep

@dp.message(filters.Command("echo"))
async def echo_handler(message: Message):
    await message.reply("Please type something:")
    try:
        response = await aiostep.wait_for(message.from_user.id, timeout=25)  # timeout is optional
    except TimeoutError:
        await message.reply("You took too long to answer.")
    else:
        await message.reply(f"You typed: {response.text}")
```

**Note**: The `timeout` parameter is optional; if not provided, the bot will wait indefinitely for a response.

### 3. Managing Multi-Step Flows with `register_next_step`

Easily manage multi-step conversation flows where the user's next input is handled by a different function:

```python
import aiostep

@dp.message(filters.CommandStart())
async def start(message: Message):
    await message.reply("What is your name?")
    await aiostep.register_next_step(message.from_user.id, ask_age)

async def ask_age(msg: Message):
    user_name = msg.text
    await msg.reply("How old are you?")
    await aiostep.register_next_step(msg.from_user.id, confirm_details, kwargs={"name": user_name})

async def confirm_details(msg: Message, name: str):
    try:
        age = int(msg.text)
    except ValueError:
        await msg.reply("Please provide a valid age!")
        await aiostep.register_next_step(msg.from_user.id, confirm_details, kwargs={"name": name})
    else:
        await msg.reply(f"Your name is {name} and you're {age} years old. Thanks!")
```

Again, the `timeout` parameter can be passed to `register_next_step` as an option to limit how long to wait for a user's response.

---

## State Management

A key feature of `aiostep` is state management, which allows you to store and retrieve user-specific data across sessions. You can choose between **in-memory** storage (ideal for quick setups) or **Redis** for distributed environments.

### Example Usage with Redis-Based Storage

To store and manage states in Redis, you need to initialize `RedisStateStorage` and integrate it with your bot:

```python
from redis.asyncio import Redis
from aiostep.storage import RedisStateStorage

redis_instance = Redis()
storage = RedisStateStorage(redis_instance)

# Setting a state for a user
await storage.set_state(user_id=12345, state="awaiting_input")

# Getting the current state for a user
state_context = await storage.get_state(user_id=12345)
print(state_context.current_state)

# Deleting the current state for a user
await storage.delete_state(user_id=12345)
```

### Example with In-Memory State Storage

For simpler setups where persistence is not required, use `MemoryStateStorage`:

```python
from aiostep.storage import MemoryStateStorage
from cachebox import TTLCache

storage = MemoryStateStorage(TTLCache(1000, 86400))

# Set a state
await storage.set_state(user_id=12345, state="awaiting_input")

# Retrieve the state
state_context = await storage.get_state(user_id=12345)
print(state_context.current_state)

# Delete the state
await storage.delete_state(user_id=12345)
```

### Data Management with States

In addition to states, you can attach custom data to users' sessions. Here's an example of managing user data:

```python
# Set custom data
await storage.set_data(user_id=12345, data={"age": 30, "name": "Alice"})

# Get the stored data
user_data = await storage.get_data(user_id=12345)
print(user_data)  # Outputs: {'age': 30, 'name': 'Alice'}

# Update existing data
await storage.update_data(user_id=12345, data={"location": "Berlin"})

# Clear all data for the user
await storage.clear_data(user_id=12345)
```

---

## Advanced State Management

The state management system in `aiostep` allows you to define flexible workflows and manage conversation states efficiently. Here are a few additional features:

- **Custom State Objects**: You can define your own states using Python enums for better structure and clarity.
- **Dynamic Callbacks**: Store and invoke callback functions dynamically as part of the state context.

---

## License

This project is licensed under the MIT License. See the [LICENSE](LICENSE) file for more details.

---

By leveraging `aiostep`, you can significantly reduce complexity when building advanced Telegram bots with multiple conversation flows. Whether you're managing a simple Q&A session or a multi-step wizard, `aiostep` provides the tools to do it efficiently.

For any contributions, issues, or feedback, feel free to check out the repository and open a discussion or pull request!

---

            

Raw data

            {
    "_id": null,
    "home_page": "https://github.com/NasrollahYusefi/aiostep/",
    "name": "aiostep",
    "maintainer": null,
    "docs_url": null,
    "requires_python": ">=3.8",
    "maintainer_email": null,
    "keywords": "aiogram, steps, states, Telegram bot, asynchronous, aiostep",
    "author": "Nasrollah Yusefi",
    "author_email": null,
    "download_url": "https://files.pythonhosted.org/packages/de/d2/68fecb20f892f9cbd0c431c187285d025ce9e75abe434514c28360abce18/aiostep-0.2.0.tar.gz",
    "platform": null,
    "description": "![PyPI Version](https://img.shields.io/pypi/v/aiostep)\r\n![Python Version](https://img.shields.io/pypi/pyversions/aiostep)\r\n![License](https://img.shields.io/pypi/l/aiostep)\r\n![Total Downloads](https://static.pepy.tech/badge/aiostep)\r\n![Downloads](https://img.shields.io/pypi/dm/aiostep)\r\n\r\n# aiostep\r\n\r\n**aiostep** is an extension library for [aiogram](https://github.com/aiogram/aiogram), designed to streamline building Telegram bots in Python. It simplifies user interactions by providing intuitive methods for handling conversations and state management.\r\n\r\n---\r\n\r\n## Key Features\r\n\r\n- **Direct User Interaction**: Easily ask questions and receive user responses directly within handlers, reducing boilerplate code.\r\n- **Step-Based Flow**: Seamlessly manage multi-step conversation flows with support for dynamic callbacks.\r\n- **State Management**: Built-in state management with support for both in-memory and Redis-based storage options.\r\n\r\n---\r\n\r\n## Installation\r\n\r\nTo install the latest version of `aiostep`, run:\r\n\r\n```bash\r\npip install -U aiostep\r\n```\r\n\r\n---\r\n\r\n## Quick Start\r\n\r\n### 1. Middleware Integration\r\n\r\nTo use `aiostep`, add the `Listen` middleware to your `Dispatcher` instance:\r\n\r\n```python\r\nfrom aiogram import Dispatcher\r\nfrom aiostep import Listen\r\n\r\ndp = Dispatcher()\r\ndp.message.outer_middleware(Listen())\r\n```\r\n\r\n### 2. Direct Interaction Using `wait_for`\r\n\r\nWith `aiostep`, you can wait for a user's response directly within a handler using the `wait_for` function:\r\n\r\n```python\r\nimport aiostep\r\n\r\n@dp.message(filters.Command(\"echo\"))\r\nasync def echo_handler(message: Message):\r\n    await message.reply(\"Please type something:\")\r\n    try:\r\n        response = await aiostep.wait_for(message.from_user.id, timeout=25)  # timeout is optional\r\n    except TimeoutError:\r\n        await message.reply(\"You took too long to answer.\")\r\n    else:\r\n        await message.reply(f\"You typed: {response.text}\")\r\n```\r\n\r\n**Note**: The `timeout` parameter is optional; if not provided, the bot will wait indefinitely for a response.\r\n\r\n### 3. Managing Multi-Step Flows with `register_next_step`\r\n\r\nEasily manage multi-step conversation flows where the user's next input is handled by a different function:\r\n\r\n```python\r\nimport aiostep\r\n\r\n@dp.message(filters.CommandStart())\r\nasync def start(message: Message):\r\n    await message.reply(\"What is your name?\")\r\n    await aiostep.register_next_step(message.from_user.id, ask_age)\r\n\r\nasync def ask_age(msg: Message):\r\n    user_name = msg.text\r\n    await msg.reply(\"How old are you?\")\r\n    await aiostep.register_next_step(msg.from_user.id, confirm_details, kwargs={\"name\": user_name})\r\n\r\nasync def confirm_details(msg: Message, name: str):\r\n    try:\r\n        age = int(msg.text)\r\n    except ValueError:\r\n        await msg.reply(\"Please provide a valid age!\")\r\n        await aiostep.register_next_step(msg.from_user.id, confirm_details, kwargs={\"name\": name})\r\n    else:\r\n        await msg.reply(f\"Your name is {name} and you're {age} years old. Thanks!\")\r\n```\r\n\r\nAgain, the `timeout` parameter can be passed to `register_next_step` as an option to limit how long to wait for a user's response.\r\n\r\n---\r\n\r\n## State Management\r\n\r\nA key feature of `aiostep` is state management, which allows you to store and retrieve user-specific data across sessions. You can choose between **in-memory** storage (ideal for quick setups) or **Redis** for distributed environments.\r\n\r\n### Example Usage with Redis-Based Storage\r\n\r\nTo store and manage states in Redis, you need to initialize `RedisStateStorage` and integrate it with your bot:\r\n\r\n```python\r\nfrom redis.asyncio import Redis\r\nfrom aiostep.storage import RedisStateStorage\r\n\r\nredis_instance = Redis()\r\nstorage = RedisStateStorage(redis_instance)\r\n\r\n# Setting a state for a user\r\nawait storage.set_state(user_id=12345, state=\"awaiting_input\")\r\n\r\n# Getting the current state for a user\r\nstate_context = await storage.get_state(user_id=12345)\r\nprint(state_context.current_state)\r\n\r\n# Deleting the current state for a user\r\nawait storage.delete_state(user_id=12345)\r\n```\r\n\r\n### Example with In-Memory State Storage\r\n\r\nFor simpler setups where persistence is not required, use `MemoryStateStorage`:\r\n\r\n```python\r\nfrom aiostep.storage import MemoryStateStorage\r\nfrom cachebox import TTLCache\r\n\r\nstorage = MemoryStateStorage(TTLCache(1000, 86400))\r\n\r\n# Set a state\r\nawait storage.set_state(user_id=12345, state=\"awaiting_input\")\r\n\r\n# Retrieve the state\r\nstate_context = await storage.get_state(user_id=12345)\r\nprint(state_context.current_state)\r\n\r\n# Delete the state\r\nawait storage.delete_state(user_id=12345)\r\n```\r\n\r\n### Data Management with States\r\n\r\nIn addition to states, you can attach custom data to users' sessions. Here's an example of managing user data:\r\n\r\n```python\r\n# Set custom data\r\nawait storage.set_data(user_id=12345, data={\"age\": 30, \"name\": \"Alice\"})\r\n\r\n# Get the stored data\r\nuser_data = await storage.get_data(user_id=12345)\r\nprint(user_data)  # Outputs: {'age': 30, 'name': 'Alice'}\r\n\r\n# Update existing data\r\nawait storage.update_data(user_id=12345, data={\"location\": \"Berlin\"})\r\n\r\n# Clear all data for the user\r\nawait storage.clear_data(user_id=12345)\r\n```\r\n\r\n---\r\n\r\n## Advanced State Management\r\n\r\nThe state management system in `aiostep` allows you to define flexible workflows and manage conversation states efficiently. Here are a few additional features:\r\n\r\n- **Custom State Objects**: You can define your own states using Python enums for better structure and clarity.\r\n- **Dynamic Callbacks**: Store and invoke callback functions dynamically as part of the state context.\r\n\r\n---\r\n\r\n## License\r\n\r\nThis project is licensed under the MIT License. See the [LICENSE](LICENSE) file for more details.\r\n\r\n---\r\n\r\nBy leveraging `aiostep`, you can significantly reduce complexity when building advanced Telegram bots with multiple conversation flows. Whether you're managing a simple Q&A session or a multi-step wizard, `aiostep` provides the tools to do it efficiently.\r\n\r\nFor any contributions, issues, or feedback, feel free to check out the repository and open a discussion or pull request!\r\n\r\n---\r\n",
    "bugtrack_url": null,
    "license": "MIT",
    "summary": "A Python library to handle steps in aiogram framework.",
    "version": "0.2.0",
    "project_urls": {
        "Homepage": "https://github.com/NasrollahYusefi/aiostep/"
    },
    "split_keywords": [
        "aiogram",
        " steps",
        " states",
        " telegram bot",
        " asynchronous",
        " aiostep"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "a00a3537839e281b2e62b894fac0b4b9082189efd97a6fb63b48b4416aa40ea9",
                "md5": "e57dc0700415b3544c6019ee40c629dc",
                "sha256": "3cacd4c17c190a5a6aa190d528bb5704aa3d8cf9342029570b73ce09089539be"
            },
            "downloads": -1,
            "filename": "aiostep-0.2.0-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "e57dc0700415b3544c6019ee40c629dc",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.8",
            "size": 10664,
            "upload_time": "2024-10-18T22:25:05",
            "upload_time_iso_8601": "2024-10-18T22:25:05.879443Z",
            "url": "https://files.pythonhosted.org/packages/a0/0a/3537839e281b2e62b894fac0b4b9082189efd97a6fb63b48b4416aa40ea9/aiostep-0.2.0-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "ded268fecb20f892f9cbd0c431c187285d025ce9e75abe434514c28360abce18",
                "md5": "711b50ff72752da367f80a670849d01e",
                "sha256": "5768d79aca7eda252f3a58d8b698a226ff2fbbc6095b6166d18d6ff608c496f1"
            },
            "downloads": -1,
            "filename": "aiostep-0.2.0.tar.gz",
            "has_sig": false,
            "md5_digest": "711b50ff72752da367f80a670849d01e",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.8",
            "size": 11070,
            "upload_time": "2024-10-18T22:25:08",
            "upload_time_iso_8601": "2024-10-18T22:25:08.343765Z",
            "url": "https://files.pythonhosted.org/packages/de/d2/68fecb20f892f9cbd0c431c187285d025ce9e75abe434514c28360abce18/aiostep-0.2.0.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2024-10-18 22:25:08",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "NasrollahYusefi",
    "github_project": "aiostep",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": false,
    "requirements": [
        {
            "name": "cachebox",
            "specs": [
                [
                    ">=",
                    "4.2.3"
                ]
            ]
        }
    ],
    "lcname": "aiostep"
}
        
Elapsed time: 0.35747s