AiotraQ

website·Indexed 29 days ago

https://toshi-pono.github.io/aiotraq

A Python library designed for the rapid development of traQ bots. It provides tools for creating HTTPBot servers, an asynchronous API client, and various components for sending messages, images, pandas DataFrames, Matplotlib figures, and managing stamps within traQ.

Tokens
4.8K
Snippets
24
Records
40
Agent score
75%

What's inside AiotraQ

  1. Overview of AiotraQ libraries

    AiotraQ is a set of Python libraries designed for rapid traQ Bot development. It consists of three main components:

    • aiotraq: An asynchronous wrapper for the traQ API.
    • aiotraq-bot: A traQ Bot library built using FastAPI.
    • aiotraq-message: A library specifically for sending and managing messages in traQ Bots.
  2. Use AiotraQ Component Base Response for rapid bot development

    The AiotraQ Component Base Response allows developers to combine multiple UI elements—including images, loading indicators, tables, and text—into a single line/response. This is designed to accelerate the development of bots by simplifying the delivery of complex content layouts.
  3. Send messages using TraqMessageManager

    Use TraqMessageManager to handle message delivery to traQ. You can specify a channel_id to send to a channel or a user_id to send a Direct Message (DM). The manager executes 'components' (async functions) that receive a TraqMessage object to perform the actual sending operations.
    import os
    import asyncio
    from aiotraq_bot import TraqHttpBot
    from aiotraq_message import TraqMessage, TraqMessageManager
    
    # A component that defines what to send
    async def component(am: TraqMessage, payload: str):
        am.write("Hello, World!")
        am.write(payload)
    
    bot = TraqHttpBot(verification_token=os.getenv("BOT_VERIFICATION_TOKEN"))
    # Initialize the manager with bot, token, API URL, and base URL
    response = TraqMessageManager(
        bot, 
        os.getenv("BOT_ACCESS_TOKEN"), 
        "https://q.trap.jp/api/v3", 
        "https://q.trap.jp"
    )
    
    @bot.event("MESSAGE_CREATED")
    async def on_message_created(payload) -> None:
        channel_id = payload.message.channelId
        message = payload.message.plainText
        # Execute the component for the specified channel
        await response(component, channel_id=channel_id, payload=message)
    
    if __name__ == "__main__":
        bot.run(port=8080)
  4. Register event handlers for traQ Bot

    Event handlers must be asynchronous functions registered using the @bot.event() decorator. There are two ways to specify which event a handler should process:

    1. Type Hinting: Use the specific payload type (e.g., MessageCreatedPayload) in the function signature.
    2. Event Name: Pass the event name as a string argument to the decorator (e.g., @bot.event("MESSAGE_CREATED")).
    from aiotraq_bot import TraqHttpBot
    # Assuming MessageCreatedPayload is imported from the appropriate module
    
    # Method 1: Using type hints
    @bot.event()
    async def on_message(payload: MessageCreatedPayload):
        print(payload)
    
    # Method 2: Using the event name string
    @bot.event("MESSAGE_CREATED")
    async def on_message2(payload):
        print(payload)
  5. Create and use an AuthenticatedClient in AiotraQ

    Use the AuthenticatedClient to interact with the API. It is recommended to use the client within a with statement to ensure the client is automatically closed after use. If the client needs to be used again after the block ends, a new AuthenticatedClient instance must be created.
    import os
    from aiotraq import AuthenticatedClient
    from aiotraq.api.channel import get_channels
    
    BOT_ACCESS_TOKEN = os.getenv("BOT_ACCESS_TOKEN")
    assert BOT_ACCESS_TOKEN is not None
    
    client = AuthenticatedClient(base_url="https://q.trap.jp/api/v3", token=BOT_ACCESS_TOKEN)
    
    with client as client:
        channels = get_channels.sync_detailed(client=client)
        print(channels.status_code)
  6. Create and run a traQ HTTPBot server

    To create a traQ Bot server, use the TraqHttpBot class from the aiotraq_bot library. The server requires a BOT_VERIFICATION_TOKEN (obtained from the bot-console) to verify incoming requests from traQ. The server is built on FastAPI and handles event handlers asynchronously. Python 3.10 or higher is required.

    By default, the server listens on 0.0.0.0:8080, but this can be customized via the host and port arguments in the run() method.

    import os
    from aiotraq_bot import TraqHttpBot
    
    # Initialize the bot with the verification token
    bot = TraqHttpBot(verification_token=os.getenv("BOT_VERIFICATION_TOKEN"))
    
    # ... register event handlers here ...
    
    if __name__ == "__main__":
        # Start the server (default: 0.0.0.0:8080)
        bot.run(host="0.0.0.0", port=8080)
  7. Explore AiotraQ application examples

    AiotraQ provides several reference implementations to demonstrate how to build applications. Available examples include:

    • bot-kitchen-timer: A countdown timer built with AiotraQ.
    • trap-daily-stamp: An application that uses the API Client to update stamp images in real-time.

    These examples include configuration files for deployment on NeoShowcase.

  8. Activate and configure a traQ BOT on NeoShowcase

    After starting the application in NeoShowcase, you must activate the bot and configure its event subscriptions:

    1. Access the Bot Console.
    2. Click the Activation button in the bottom left.
    3. Navigate to the Subscription Events tab and select the events the bot needs to receive.
  9. Create a basic traQ Bot that responds to messages

    This example demonstrates how to set up a TraqHttpBot that listens for the MESSAGE_CREATED event and uses TraqMessageManager to send a response with a loading spinner for a long-running task.
    import os
    import asyncio
    from aiotraq_bot import TraqHttpBot
    from aiotraq_message import TraqMessage, TraqMessageManager
    
    async def component(am: TraqMessage, payload: str):
        am.write(payload)
        # long task
        with am.spinner():
            await asyncio.sleep(3)
        am.write(":done: Done!")
    
    bot = TraqHttpBot(verification_token=os.getenv("BOT_VERIFICATION_TOKEN"))
    response = TraqMessageManager(bot, os.getenv("BOT_ACCESS_TOKEN", ""), "https://q.trap.jp/api/v3", "https://q.trap.jp")
    
    @bot.event("MESSAGE_CREATED")
    async def on_message_created(payload) -> None:
        channel_id = payload.message.channelId
        message = payload.message.plainText
    
        await response(component, channnel_id=channel_id, payload=message)
    
    if __name__ == "__main__":
        bot.run(port=8080)
  10. Prepare dependencies for NeoShowcase deployment

    To deploy an AiotraQ application to NeoShowcase, you must create a requirements.txt file in the application's root directory listing all dependencies. If using uv, you can generate this file from pyproject.toml.
    uv pip compile pyproject.toml > requirements.txt