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的逻辑运行

你可以通过 overwrite_check 函数来检测当前是否适合进覆盖。该函数会检测是否有适配器已经加载。

结尾

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.5.tar.gz (21.3 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.5-py3-none-any.whl (22.3 kB view details)

Uploaded Python 3

File details

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

File metadata

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

File hashes

Hashes for nonebot-plugin-exdi-0.1.5.tar.gz
Algorithm Hash digest
SHA256 9b8fec56f06a08d3a85c891df6d2966a7fabd2207938ab25dff7825d7f5e0180
MD5 47204f57e5a7e4a7663414682b45dd63
BLAKE2b-256 74210e9ff39ac4346228e16c988c1359b14385138ebba8e2ca045de78a4a5c7a

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for nonebot_plugin_exdi-0.1.5-py3-none-any.whl
Algorithm Hash digest
SHA256 a94ab869d54ef11ec92a73dd245af7bede2136b612d594f0b451519b2613dfa4
MD5 7ab361813fff2ccc8e36eb31f400fc51
BLAKE2b-256 c01aba7998ea6fcba0170a90c9226cd93006ed7c53dd6c191206aeda4cc293b7

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