### Install melobot with OneBot Support Source: https://context7.com/meloland/melobot/llms.txt Installs the melobot framework with OneBot v11 protocol support, commonly used for QQ bots. This command uses pip or uv to manage the installation. ```bash pip install "melobot[onebot]" # or using uv uv pip install "melobot[onebot]" ``` -------------------------------- ### Load Plugins in Melobot Source: https://context7.com/meloland/melobot/llms.txt Shows how to initialize and run a Melobot bot. It demonstrates adding protocols like OneBot V11 and loading plugins from both local directories and installed package names. ```python from melobot import Bot from melobot.protocols.onebot.v11 import ForwardWebSocketIO, OneBotV11Protocol bot = Bot(__name__) bot.add_protocol(OneBotV11Protocol(ForwardWebSocketIO("ws://127.0.0.1:8080"))) # Load plugin from directory path bot.load_plugin("./plugins/echo_plugin") # Load plugin from package name (pip-installed) bot.load_plugin("melobot_plugin_weather") bot.run() ``` -------------------------------- ### Command Parsing with Arguments Source: https://context7.com/meloland/melobot/llms.txt Shows how to use the `on_command` decorator and `CmdArgs` to parse commands with arguments. This example defines a weather command that extracts a city and number of days from the input, demonstrating argument access and default value handling. ```python from melobot import send_text from melobot.handle import on_command from melobot.utils.parse import CmdParser, CmdArgs, CmdArgFormatter as Fmtter # Simple command with arguments @on_command(cmd_start=".", cmd_sep=" ", targets=["weather", "天气"]) async def weather_handler(args: CmdArgs) -> None: # Input: ".weather Beijing 7" # args.name = "weather" or "天气" (matched target) # args.vals = ["Beijing", "7"] city = args.vals[0] if args.vals else "Unknown" days = args.vals[1] if len(args.vals) > 1 else "3" await send_text(f"Weather for {city} ({days} days): Sunny") ``` -------------------------------- ### Send Messages via Adapters Source: https://context7.com/meloland/melobot/llms.txt Provides examples of sending text and image content using the Melobot adapter interface, which abstracts protocol-specific details. ```python @on_message() async def generic_send() -> None: await send_text("Hello from melobot!") await send_image("https://example.com/image.png") ``` -------------------------------- ### Console Protocol for Terminal Testing Source: https://context7.com/meloland/melobot/llms.txt Explains how to use the Console protocol for testing bot functionality directly in the terminal. It includes examples of handling text input from the console and exiting the bot. ```python from melobot import Bot, PluginPlanner, send_text from melobot.handle import on_start_match, on_text from melobot.protocols.console import ConsoleProtocol, StdinEvent @on_text() async def console_handler(event: StdinEvent) -> None: print(f"Received from console: {event.text}") await send_text(f"You said: {event.text}") @on_start_match("exit") async def exit_handler() -> None: await send_text("Goodbye!") from melobot.bot import get_bot await get_bot().close() plugin = PluginPlanner(version="1.0.0", flows=[console_handler, exit_handler]) if __name__ == "__main__": bot = Bot(__name__) bot.add_protocol(ConsoleProtocol()) bot.load_plugin(plugin) bot.run() ``` -------------------------------- ### Create and Run a Bot with OneBot v11 Protocol Source: https://context7.com/meloland/melobot/llms.txt Demonstrates the basic structure of a melobot application. It defines a simple message handler using `@on_start_match`, creates a plugin, configures the OneBot v11 protocol with WebSocket IO, loads the plugin, and starts the bot. ```python from melobot import Bot, PluginPlanner, on_start_match, send_text from melobot.protocols.onebot.v11 import ForwardWebSocketIO, OneBotV11Protocol # Define a simple message handler @on_start_match(".sayhi") async def echo_hi() -> None: await send_text("Hello, melobot!") # Create a plugin with the handler test_plugin = PluginPlanner(version="1.0.0", flows=[echo_hi]) if __name__ == "__main__": # Create the bot instance bot = Bot(__name__) # Add OneBot v11 protocol support with WebSocket IO bot.add_protocol(OneBotV11Protocol(ForwardWebSocketIO("ws://127.0.0.1:8080"))) # Load the plugin bot.load_plugin(test_plugin) # Start the bot (blocking call) bot.run() ``` -------------------------------- ### Bot Lifecycle Hooks Source: https://context7.com/meloland/melobot/llms.txt Demonstrates how to use lifecycle hooks to execute code at specific points in the bot's lifecycle, such as when the bot is loaded, started, or stopped. It shows both decorator and shorthand decorator syntaxes, and how to check hook invocation times. ```python from melobot import Bot from melobot.bot import BotLifeSpan from melobot.protocols.onebot.v11 import ForwardWebSocketIO, OneBotV11Protocol bot = Bot(__name__) # Hook using decorator syntax @bot.on(BotLifeSpan.LOADED) async def on_loaded() -> None: print("Bot loaded - plugins registered") @bot.on_loaded # Shorthand decorator async def on_loaded_2() -> None: print("Alternative syntax for LOADED hook") @bot.on(BotLifeSpan.STARTED) async def on_started() -> None: print("Bot started - all adapters running") @bot.on(BotLifeSpan.STOPPED) async def on_stopped() -> None: print("Bot stopped - cleanup complete") @bot.on_restarted # Called after bot.restart() async def on_restarted() -> None: print("Bot restarted!") # Check if lifecycle was reached timestamp = bot.get_hook_evoke_time(BotLifeSpan.STARTED) if timestamp > 0: print(f"Bot started at: {timestamp}") # Add protocol and run bot.add_protocol(OneBotV11Protocol(ForwardWebSocketIO("ws://127.0.0.1:8080"))) bot.run() ``` -------------------------------- ### Implement Dependency Injection for Handlers Source: https://context7.com/meloland/melobot/llms.txt Shows how to inject contextual objects like Bot instances, adapters, and event data into handlers using type annotations. Includes examples of custom dependency providers and reflective injection for session-aware handlers. ```python @on_text() async def handler_with_injection( event: MessageEvent, bot: Bot, adapter: Adapter, store: FlowStore, ) -> None: print(f"Bot name: {bot.name}") print(f"Message: {event.text}") store["last_message"] = event.text def get_config() -> dict: return {"max_retries": 3, "timeout": 30} @inject_deps async def custom_handler( config: Annotated[dict, Depends(get_config)] ) -> None: print(f"Config: {config}") ``` -------------------------------- ### Scheduling Asynchronous Tasks with async_later in Python Source: https://context7.com/meloland/melobot/llms.txt Illustrates how to use the `async_later` utility function to schedule an asynchronous task to run after a specified delay. The example shows scheduling a simple `delayed_task` to execute after 5 seconds. The returned `asyncio.Task` object can be further managed. ```python import asyncio from melobot.utils import async_later from melobot.handle import on_text async def delayed_task(): print("Task executed!") @on_text() async def schedule_example() -> None: # Run delayed_task after 5 seconds task = await async_later(delayed_task, delay=5.0) # task is an asyncio.Task that can be awaited or cancelled ``` -------------------------------- ### Event Binding Functions for Handling Events Source: https://context7.com/meloland/melobot/llms.txt Illustrates various melobot decorators for binding event handlers. These include matching text by start, content, end, exact match, regex, and commands, as well as handling any event or specific OneBot events like messages, notices, and requests. ```python from melobot import send_text from melobot.handle import ( on_event, # Any event from any protocol on_text, # Any text event on_start_match, # Text starting with pattern on_contain_match,# Text containing pattern on_end_match, # Text ending with pattern on_full_match, # Exact text match on_regex_match, # Regex pattern match on_command, # Command with arguments ) from melobot.protocols.onebot.v11 import on_message, on_notice, on_request, MessageEvent # Match messages starting with ".echo" @on_start_match(".echo") async def echo_handler() -> None: await send_text("Echo received!") # Match messages containing "hello" (case insensitive with regex) @on_regex_match(r"(?i)hello") async def hello_handler() -> None: await send_text("Hello there!") # Full match for specific commands @on_full_match(["help", "帮助"]) async def help_handler() -> None: await send_text("Available commands: .echo, .weather") # OneBot-specific message handler with event injection @on_message() async def message_handler(event: MessageEvent) -> None: print(f"Received message from {event.sender.user_id}: {event.text}") ``` -------------------------------- ### Organizing Features with the Plugin System Source: https://context7.com/meloland/melobot/llms.txt Demonstrates the initialization of a bot plugin using PluginPlanner to manage versioning and submodule auto-importing. ```python ECHO_PLUGIN = PluginPlanner( version="1.0.0", auto_import=True, ) ``` -------------------------------- ### Add Flows with use() Decorator and Plugin Lifecycle Hooks Source: https://context7.com/meloland/melobot/llms.txt Demonstrates how to add event handlers using the `@ECHO_PLUGIN.use` decorator and how to hook into plugin initialization events using `@ECHO_PLUGIN.on(PluginLifeSpan.INITED)`. It also shows how to share objects between plugins using `@SyncShare` and `@AsyncShare` decorators. ```python from melobot.plugin import PluginLifeSpan # Add flows using the use() decorator @ECHO_PLUGIN.use @on_start_match(".echo") async def echo_handler() -> None: await send_text("Echo!") # Plugin lifecycle hooks @ECHO_PLUGIN.on(PluginLifeSpan.INITED) async def on_plugin_init() -> None: print("Plugin initialized!") # Shared objects between plugins @ECHO_PLUGIN.use @SyncShare def get_version() -> str: return "1.0.0" @ECHO_PLUGIN.use @AsyncShare async def get_status() -> dict: return {"active": True, "users": 100} ``` -------------------------------- ### Handling Action Results with ActionHandle Source: https://context7.com/meloland/melobot/llms.txt Shows how to wait for action completion and retrieve response data (echo) from protocol implementations using ActionHandle and ActionHandleGroup. ```python @on_message() async def action_with_echo(adapter: Adapter) -> None: handle_group: ActionHandleGroup = await adapter.send("Hello!") echoes = await handle_group echo = await handle_group.unwrap(0) if echo.is_ok(): data = echo.result() msg_id = data.get('message_id') print(f"Message sent with ID: {msg_id}") await (await adapter.send("First message")) await (await adapter.send("Second message")) await (await adapter.send("Third message")) handle_group = await adapter.get_group_member_list(group_id=123456) echo = await handle_group.unwrap(0) if echo.is_ok(): members = echo.result() for member in members: print(f"Member: {member['nickname']}") ``` -------------------------------- ### Manage Multi-turn Conversations with Sessions Source: https://context7.com/meloland/melobot/llms.txt Explains how to use session suspension to pause execution and wait for user input. Demonstrates both legacy session handling and manual session management with custom rules. ```python @on_text(legacy_session=True) async def registration_flow( event: Annotated[TextEvent, Reflect()] ) -> None: if not event.text.startswith("register"): return await send_text("Welcome! What's your name?") if not await suspend(timeout=60): return name = event.text await send_text(f"Nice to meet you, {name}! What's your age?") if not await suspend(timeout=60): return age = event.text await send_text(f"Great! {name}, age {age} - registration complete!") ``` -------------------------------- ### Singleton Decorator and Conditional Execution in Python Source: https://context7.com/meloland/melobot/llms.txt Demonstrates the use of the `singleton` decorator to ensure a single instance of a class and the `if_` decorator for conditional execution of an asynchronous handler based on a configuration setting. The `on_text` decorator is used to trigger the handler. ```python from melobot.utils import ( singleton, # Singleton decorator to_async, # Convert sync to async async_later, # Schedule async task async_at, # Run at specific time if_, # Conditional decorator ) from melobot.handle import on_text, stop # Singleton class @singleton class Config: def __init__(self): self.debug = True # Conditional execution @on_text() @if_( lambda: Config().debug, # Condition reject=stop, # Called if condition is False ) async def debug_only() -> None: print("Debug mode is enabled") ``` -------------------------------- ### Protocol-specific message sending with Adapter Source: https://context7.com/meloland/melobot/llms.txt Demonstrates sending text, images, combined segments, and custom messages using the OneBot adapter. It also covers sending forward messages with custom nodes. ```python @on_message() async def onebot_send(adapter: Adapter, event: MessageEvent) -> None: await adapter.send("Hello!") img = ImageSegment(file="https://example.com/image.jpg") await adapter.send(img) await adapter.send([ TextSegment("Check out this image: "), ImageSegment(file="https://example.com/photo.jpg"), ]) await adapter.send_custom("Private message", user_id=12345678) await adapter.send_custom("Group message", group_id=987654321) nodes = [ NodeSegment(content="Message 1", name="Bot", uin=10001), NodeSegment(content="Message 2", name="Bot", uin=10001), ] await adapter.send_forward(nodes) ``` -------------------------------- ### Define Command Handlers with Validation and Type Conversion Source: https://context7.com/meloland/melobot/llms.txt Demonstrates how to use the @on_command decorator to define command handlers with automatic argument parsing, type conversion, and range validation. It supports default values and structured error handling for input arguments. ```python @on_command( cmd_start=".", cmd_sep=" ", targets="add", fmtters=[ Fmtter( convert=float, validate=lambda x: 0 <= x <= 100, src_desc="First operand", src_expect="Float between 0 and 100", ), Fmtter( convert=float, validate=lambda x: 0 <= x <= 100, src_desc="Second operand", src_expect="Float between 0 and 100", default=0.0, ), ], ) async def add_handler(args: CmdArgs) -> None: result = args.vals[0] + args.vals[1] await send_text(f"Result: {result}") ``` -------------------------------- ### Advanced Event Handling with Processing Flows Source: https://context7.com/meloland/melobot/llms.txt Illustrates advanced event handling using Melobot's Flow API. It covers creating nodes with decorators, defining flow structures, and implementing flow control mechanisms like stop, block, bypass, and rewind. It also shows how to use custom contexts with `nextn()`. ```python from melobot.handle import Flow, FlowNode, node, stop, block, bypass, rewind, nextn from melobot.adapter import TextEvent from melobot.protocols.onebot.v11 import MessageEvent # Create nodes using decorator @node async def validate_input(event: MessageEvent) -> bool: if not event.text.strip(): return False # Skip successor nodes return True @node async def process_text(event: MessageEvent) -> None: text = event.text.lower() print(f"Processing: {text}") @node async def log_result() -> None: print("Processing complete!") # Create a flow with node paths flow = Flow( "text-processor", [validate_input, process_text, log_result], priority=5, # Higher priority runs first ) # Flow control methods @node async def control_example(event: MessageEvent) -> None: if event.text == "stop": await stop() # Immediately terminate flow if event.text == "block": await block() # Block event propagation to lower priority if event.text == "skip": await bypass() # Skip to next node if event.text == "retry": await rewind() # Re-run current node # Custom context with nextn() @node async def with_context() -> None: import aiofiles async with aiofiles.open("log.txt", "a") as f: await f.write("Starting processing\n") await nextn() # Run successor nodes here await f.write("Processing finished\n") ``` -------------------------------- ### Register Notice and Meta Event Handlers in Melobot Source: https://github.com/meloland/melobot/blob/main/docs/source/ob_api/v11.handle.md These decorators allow developers to register asynchronous or synchronous handlers for specific OneBot V11 event types. They return a FlowDecorator and support advanced configuration like event filtering via rules and checkers. ```python from melobot.protocols.onebot.v11.handle import on_notice, on_meta @on_notice(priority=1, block=True) async def handle_notice(event): # Logic for handling NoticeEvent pass @on_meta(priority=0, temp=False) async def handle_meta(event): # Logic for handling MetaEvent pass ``` -------------------------------- ### Event Filtering with Checkers and Matchers Source: https://context7.com/meloland/melobot/llms.txt Implements permission control and event filtering using built-in checkers, custom lambda functions, and custom Checker classes to restrict handler execution. ```python checker_factory = MsgCheckerFactory(owner=10001, super_users=[10002, 10003], white_users=[10004, 10005], white_groups=[123456, 789012]) @on_message(checker=checker_factory.get_base(role=LevelRole.OWNER)) async def owner_only() -> None: await send_text("Owner command executed!") @on_message(checker=lambda e: e.sender.user_id in [10001, 10002]) async def custom_check_handler() -> None: await send_text("VIP user detected!") class FrequencyChecker(Checker[MessageEvent]): def __init__(self, max_calls: int): super().__init__() self.count = 0 self.max_calls = max_calls async def check(self, event: MessageEvent) -> bool: if self.count >= self.max_calls: return False self.count += 1 return True ``` -------------------------------- ### Leave or Dismiss Group (Python) Source: https://github.com/meloland/melobot/blob/main/docs/source/ob_api/v11.adapter.md Asynchronously handles leaving a group or dismissing it. Requires the group ID and a boolean to specify if it's a dismissal. Returns an ActionHandleGroup. ```python async def set_group_leave(group_id: int, is_dismiss: bool = False) -> ActionHandleGroup: # Implementation details... ``` -------------------------------- ### Set Group Admin (Python) Source: https://github.com/meloland/melobot/blob/main/docs/source/ob_api/v11.adapter.md Asynchronously sets or revokes administrator privileges for a specified group. Requires a group ID and a boolean to enable/disable admin status. Returns an ActionHandleGroup. ```python async def set_group_admin(group_id: int, enable: bool = True) -> ActionHandleGroup: # Implementation details... ``` -------------------------------- ### Set Group Card (Python) Source: https://github.com/meloland/melobot/blob/main/docs/source/ob_api/v11.adapter.md Asynchronously sets or clears a user's card (nickname) within a group. Requires group ID, user ID, and the desired card string. Returns an ActionHandleGroup. ```python async def set_group_card(group_id: int, user_id: int, card: str = '') -> ActionHandleGroup: # Implementation details... ``` -------------------------------- ### Set Group Name (Python) Source: https://github.com/meloland/melobot/blob/main/docs/source/ob_api/v11.adapter.md Asynchronously sets a new name for a specified group. Requires the group ID and the new name string. Returns an ActionHandleGroup. ```python async def set_group_name(group_id: int, name: str) -> ActionHandleGroup: # Implementation details... ``` -------------------------------- ### Set Group Whole Ban (Python) Source: https://github.com/meloland/melobot/blob/main/docs/source/ob_api/v11.adapter.md Asynchronously sets or disables the whole group ban for a specified group. Requires a group ID and a boolean to enable/disable the ban. Returns an ActionHandleGroup. ```python async def set_group_whole_ban(group_id: int, enable: bool = True) -> ActionHandleGroup: # Implementation details... ``` -------------------------------- ### Set Group Anonymous Mode (Python) Source: https://github.com/meloland/melobot/blob/main/docs/source/ob_api/v11.adapter.md Asynchronously enables or disables anonymous messaging within a group. Requires a group ID and a boolean to control the mode. Returns an ActionHandleGroup. ```python async def set_group_anonymous(group_id: int, enable: bool = True) -> ActionHandleGroup: # Implementation details... ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.