Skip to main content

Alconna Adapter for Nonebot

Project description

nonebot

NoneBot Plugin Alconna

✨ Alconna Usage For NoneBot2 ✨

license pypi python

该插件提供了 AlconnaNonebot2 适配版本与工具

特性

  • 完整的 Alconna 特性支持
  • 基本的 rule, matcher 与 依赖注入
  • 自动回复命令帮助信息 (help, shortcut, completion) 选项
  • 现有全部协议的 Segment 标注
  • match_value, match_path 等检查函数
  • 补全会话支持

讨论

QQ 交流群: 链接

使用方法

Nonebot文档: 📖这里 详细介绍: 📦这里

消息解析

from nonebot.adapters.onebot.v12 import Message, MessageSegment
from arclet.alconna import Alconna, Option, Args

msg = Message("Hello! --foo 123")
img = MessageSegment.image("1.png")
print(msg)

alc = Alconna("Hello!", Option("--foo", Args["foo", int]))
res = alc.parse(msg)
assert res.matched
assert res.query("foo.foo") == 123
assert not alc.parse(Message(["Hello!", img])).matched

MessageSegment 标注

特定适配器:

from nonebot_plugin_alconna.adapters.onebot12 import Mention
from nonebot.adapters.onebot.v12 import Message
from arclet.alconna import Alconna, Args

msg = Message(["Hello!", Mention("123")])
print(msg)  # Hello![mention:user_id=123]

alc = Alconna("Hello!", Args["target", Mention])
res = alc.parse(msg)
assert res.matched
assert res.query("target").data['user_id'] == '123'

通用标注:

from nonebot.adapters.onebot.v12 import Message as Ob12Msg, MessageSegment as Ob12MS
from nonebot.adapters.onebot.v11 import Message as Ob11Msg, MessageSegment as Ob11MS
from nonebot_plugin_alconna.adapters import At
from arclet.alconna import Alconna, Args

msg1 = Ob12Msg(["Hello!", Ob12MS.mention("123")]) # Hello![mention:user_id=123]
msg2 = Ob11Msg(["Hello!", Ob11MS.at(123)]) # Hello![CQ:at,qq=123]


alc = Alconna("Hello!", Args["target", At])
res1 = alc.parse(msg1)
assert res1.matched
target = res1.query("target")
assert isinstance(target, At)
assert target.target == '123'

res2 = alc.parse(msg2)
assert res2.matched
target = res2.query("target")
assert isinstance(target, At)
assert target.target == '123'

Matcher 与 依赖注入

...
from nonebot import require
require("nonebot_plugin_alconna")
...

from nonebot_plugin_alconna import (
    on_alconna, 
    Match,
    Query,
    AlconnaMatch, 
    AlconnaQuery,
    AlcMatches,
    AlcResult
)
from arclet.alconna import Alconna, Args, Option

test = on_alconna(
    Alconna(
        "test",
        Option("foo", Args["bar", int]),
        Option("baz", Args["qux", bool, False])
    ),
    auto_send_output=True
)


@test.handle()
async def handle_test1(result: AlcResult):
    await test.send(f"matched: {result.matched}")
    await test.send(f"maybe output: {result.output}")

@test.handle()
async def handle_test2(result: AlcMatches):
    await test.send(f"head result: {result.header_result}")
    await test.send(f"args: {result.all_matched_args}")

@test.handle()
async def handle_test3(bar: Match[int] = AlconnaMatch("bar")):
    if bar.available:    
        await test.send(f"foo={bar.result}")

@test.handle()
async def handle_test4(qux: Query[bool] = AlconnaQuery("baz.qux", False)):
    if qux.available:
        await test.send(f"baz.qux={qux.result}")

条件控制

...
from nonebot import require
require("nonebot_plugin_alconna")
...

from arclet.alconna import Alconna, Subcommand, Option, Args
from nonebot_plugin_alconna import assign, on_alconna, AlconnaResult, CommandResult, Check

pip = Alconna(
    "pip",
    Subcommand(
        "install", 
        Args["pak", str],
        Option("--upgrade"),
        Option("--force-reinstall")
    ),
    Subcommand(
        "list",
        Option("--out-dated")
    )
)

pip_cmd = on_alconna(pip)

@pip_cmd.handle([Check(assign("install.pak", "pip"))])
async def update(arp: CommandResult = AlconnaResult()):
    ...

@pip_cmd.handle([Check(assign("list"))])
async def list_(arp: CommandResult = AlconnaResult()):
    ...

@pip_cmd.handle([Check(assign("install"))])
async def install(arp: CommandResult = AlconnaResult()):
    ...

Duplication

...
from nonebot import require
require("nonebot_plugin_alconna")
...

from nonebot_plugin_alconna import (
    on_alconna, 
    AlconnaDuplication
)
from arclet.alconna import Alconna, Args, Duplication, Option, OptionStub

test = on_alconna(
    Alconna(
        "test",
        Option("foo", Args["bar", int]),
        Option("baz", Args["qux", bool, False])
    ),
    auto_send_output=True
)

class MyResult(Duplication):
    bar: int
    qux: bool
    foo: OptionStub

@test.handle()
async def handle_test1(result: MyResult = AlconnaDuplication(MyResult)):
    await test.send(f"matched: bar={result.bar}, qux={result.qux}")
    await test.send(f"options: foo={result.foo.origin}")

配置

目前配置项有:

  • ALCONNA_AUTO_SEND_OUTPUT : 是否全局启用输出信息自动发送
  • ALCONNA_USE_COMMAND_START : 是否将 COMMAND_START 作为全局命令前缀
  • ALCONNA_AUTO_COMPLETION: 是否全局启用补全会话功能

参数解释

def on_alconna(
    command: Alconna | str,
    skip_for_unmatch: bool = True,
    auto_send_output: bool = False,
    output_converter: Callable[[OutputType, str], Message | Awaitable[Message]] | None = None,
    aliases: set[str | tuple[str, ...]] | None = None,
    comp_config: CompConfig | None = None,
    **kwargs,
) -> type[Matcher]:
  • command: Alconna 命令
  • skip_for_unmatch: 是否在命令不匹配时跳过该响应
  • auto_send_output: 是否自动发送输出信息并跳过响应
  • output_converter: 输出信息字符串转换为 Message 方法
  • aliases: 命令别名, 作用类似于 on_command
  • comp_config: 补全会话配置, 不传入则不启用补全会话

提供了 MessageSegment标注 的协议:

协议名称 路径
OneBot 协议 adapters.onebot11, adapters.onebot12
Telegram adapters.telegram
飞书 adapters.feishu
GitHub adapters.github
QQ 频道 adapters.qqguild
钉钉 adapters.ding
Console adapters.console
开黑啦 adapters.kook
Mirai adapters.mirai
Ntchat adapters.ntchat
MineCraft adapters.minecraft
BiliBili Live adapters.bilibili

便捷装饰器

funcommand 装饰器用于将一个接受任意参数,返回 strMessageMessageSegment 的函数转换为命令响应器。

from nonebot_plugin_alconna import funcommand

@funcommand()
async def echo(msg: str):
    return msg

体验

demo bot

Project details


Release history Release notifications | RSS feed

This version

0.9.0

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

nonebot-plugin-alconna-0.9.0.tar.gz (19.8 kB view details)

Uploaded Source

Built Distribution

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

nonebot_plugin_alconna-0.9.0-py3-none-any.whl (28.8 kB view details)

Uploaded Python 3

File details

Details for the file nonebot-plugin-alconna-0.9.0.tar.gz.

File metadata

  • Download URL: nonebot-plugin-alconna-0.9.0.tar.gz
  • Upload date:
  • Size: 19.8 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: pdm/2.7.4 CPython/3.9.13

File hashes

Hashes for nonebot-plugin-alconna-0.9.0.tar.gz
Algorithm Hash digest
SHA256 5be311290e732c7ed53a576b96fa8875af7f458b5609a61c2b9b3a9c1ecab14e
MD5 51a4b74bfcc17654d3ea85f559257880
BLAKE2b-256 c8671065373af14f845f6112a3d2cb8d6187d838b4c0d90d89282ccef9f5133d

See more details on using hashes here.

File details

Details for the file nonebot_plugin_alconna-0.9.0-py3-none-any.whl.

File metadata

File hashes

Hashes for nonebot_plugin_alconna-0.9.0-py3-none-any.whl
Algorithm Hash digest
SHA256 b11eecba4fa1442ce288d744629757124662ada4343ff3b1b05e4ecb99da86e7
MD5 cd1506f8cd49c889031e23ce380c0d21
BLAKE2b-256 ef5f8fc09d2973092612c462be4321906ddc4b7207aa37c853a6ace73d36ca93

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