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.4.tar.gz (21.7 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.4-py3-none-any.whl (22.5 kB view details)

Uploaded Python 3

File details

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

File metadata

  • Download URL: nonebot-plugin-exdi-0.1.4.tar.gz
  • Upload date:
  • Size: 21.7 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.4.tar.gz
Algorithm Hash digest
SHA256 9120aa549fc6fe624f98221ed5d7417f70150767961da741d119021ef3daf6d2
MD5 93b0407162239d0b65d884e109c7ea2b
BLAKE2b-256 b412af2eee08e38c8643cdef91200b4884e6c05edb9e2e6e07fe8a69d5a91133

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for nonebot_plugin_exdi-0.1.4-py3-none-any.whl
Algorithm Hash digest
SHA256 f67b03efd9c217838019537666709087e724aa3d2cc1946b1e9d3d469f25c30e
MD5 b5f4dd601e2c6e48602b8285eedaff2a
BLAKE2b-256 b129dad11f464aab9100f54d12ab25e0e96f369fae8339b76114e1e245060da7

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