Skip to main content

依赖注入扩展,允许对非handle函数进行依赖注入

Project description

NoneBotPluginLogo

NoneBotPluginText

nonebot-plugin-exdi

✨ 依赖注入扩展,将依赖注入的范围从钩子扩展到其他函数 ✨

license pypi python

📖 介绍

该插件允许在Matcher响应范围内,对所有调用的函数使用依赖注入向上下文获取参数,不再需要handle函数传参了

💿 安装

使用 nb-cli 安装 在 nonebot2 项目的根目录下打开命令行, 输入以下指令即可安装
nb plugin install nonebot-plugin-exdi
使用包管理器安装 在 nonebot2 项目的插件目录下, 打开命令行, 根据你使用的包管理器, 输入相应的安装命令
pip
pip install nonebot-plugin-exdi
pdm
pdm add nonebot-plugin-exdi
poetry
poetry add nonebot-plugin-exdi
conda
conda install nonebot-plugin-exdi

打开 nonebot2 项目根目录下的 pyproject.toml 文件, 在 [tool.nonebot] 部分追加写入

plugins = ["nonebot_plugin_exdi"]

⚙️ 使用说明

一般使用
exdi = require("nonebot_plugin_exdi")
matcher1 = on_command('cs')

@matcher1.handle(parameterless=[exdi.init_di()])
async def my_handle():
	await my_func1()

@exdi.di()
async def my_func1(bot: Bot, matcher: Matcher, arg: Message = CommandArg()):
	await matcher.send(f'你的bot是:{bot}')
	await matcher.send(f'收到的参数是:{arg}')

运行结果:

结果

自定义Depends支持
exdi = require("nonebot_plugin_exdi")

def _depend1(bot: Bot, event: Event):
	# do someting
	return 'depend1返回值'

def _depend2(bot: Bot, event: Event):
	# do someting
	return 'depend2返回值'

depend1 = Annotated[str, Depends(_depend1)]
depend2 = Depends(_depend2)

@dataclass
class ClassDependency:
	event: Event
	depend1: depend1

	def __str__(self) -> str:
		return f'(event type:{self.event.get_type()}, depend1: {self.depend1})'

classDepend = Annotated[ClassDependency, Depends(ClassDependency)]

matcher1 = on_command('cs')

@matcher1.handle(parameterless=[exdi.init_di()])
async def my_handle():
	for msg in my_func2():
		await matcher1.send(msg)

@exdi.di()
def my_func2(d1: depend1, classDepend: classDepend, d2: str = depend2):
	yield f'depend1: {d1}, depend2: {d2}'
	yield f'classDepend: {classDepend}'

运行结果:

结果

手动传入参数,默认值参数支持
exdi = require("nonebot_plugin_exdi")

matcher1 = on_command('cs')

@matcher1.handle(parameterless=[exdi.init_di()])
async def my_handle():
	await my_func3(arg1='cillo world')

@exdi.di()
async def my_func3(matcher: Matcher, arg1: str, arg2: str = 'defaultValue'):
	await matcher.send(f'arg1: {arg1}')
	await matcher.send(f'arg2: {arg2}')

运行结果:

结果

注意,通常情况下不支持生成器依赖,同时不和matcher共用缓存。这是由于nonebot不对外暴漏dependency_cachestack,缓存需要dependency_cache,生成器依赖需要stack。如果有需要请参考下面的重写NoneBot

重写NoneBot事件发布函数

搞清楚你在做什么后再继续往下看,如果你不了解nonebot的运作规律,请勿使用该项

如果想要更好的运行效果,必须要重写`nonebot.message.handle_event`函数来获取`dependency_cache`和`stack`。重写该函数后不再需要`init_di`来初始化依赖注入。
配置项 必填 默认值 说明
exdi_overwrite_nb False 重写nonebotnonebot.message.handle_event函数
exdi_hand_overwrite False 你手动重写nonebot.message.handle_event函数

你可以通过设置exdi_overwrite_nbTrue来让插件自己覆盖handle_event,但注意的是插件需要在

你也可以自己手动重写handle_event,并且符合一下要求:

将原handle_event处创建stack的代码

async with AsyncExitStack() as stack:

替换为以下代码

exdi = require("nonebot_plugin_exdi")

async with exdi.DiBaseParamsManager(bot=bot, event=event) as base_params:

DiBaseParamsManager的模型设计

属性 说明
bot bot
event event
state state
stack stack
dependency_cache dependency_cache

完成重写后,你可以把exdi_overwrite_nb设置为False,把exdi_hand_overwrite设置为True。此时插件不会尝试重写handle_event,但同时会按照重写过handle_event的逻辑运行

结尾

readme模板来自A-kirami

这是萌新的第一个插件,异步学的有限...有问题,大佬不要骂了,欢迎提issue

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

nonebot-plugin-exdi-0.1.3.tar.gz (19.5 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_exdi-0.1.3-py3-none-any.whl (22.0 kB view details)

Uploaded Python 3

File details

Details for the file nonebot-plugin-exdi-0.1.3.tar.gz.

File metadata

  • Download URL: nonebot-plugin-exdi-0.1.3.tar.gz
  • Upload date:
  • Size: 19.5 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.12.9

File hashes

Hashes for nonebot-plugin-exdi-0.1.3.tar.gz
Algorithm Hash digest
SHA256 85977a99f350379f8f24eb5c5c92660641e2629aac47453d1b8b37d9e6f92ab1
MD5 1d9e188df0be74fe05ce4953f910e252
BLAKE2b-256 ea07f8bf6a9ebd1e7cc2e7a4247ea7614e0175c40fbf1710b9b17744671c5366

See more details on using hashes here.

File details

Details for the file nonebot_plugin_exdi-0.1.3-py3-none-any.whl.

File metadata

File hashes

Hashes for nonebot_plugin_exdi-0.1.3-py3-none-any.whl
Algorithm Hash digest
SHA256 59f5c5d8e83dde82f5a6a52b41bdbd8959753097371aa4e74a1674db7f8ae5c2
MD5 45f130154ecff0c2730dc824c2c27332
BLAKE2b-256 8239e0bee2d5931401bf779d1b331a12d6d01dbc67174214a8cb410c47fd71eb

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