Skip to main content

在聊天中执行带有上下文的 Python 代码

Project description

NoneBotPluginLogo

NoneBotPluginText

nonebot-plugin-exe-code

✨ 在聊天中执行带有上下文的 Python 代码 ✨

license pypi python

Imports: isort Code style: black

📖 介绍

在聊天中执行带有上下文的 Python 代码

💿 安装

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

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

plugins = ["nonebot_plugin_exe_code"]

⚙️ 配置

在 nonebot2 项目的.env文件中添加下表中的必填配置

配置项 必填 默认值 说明
exe_code__user 允许执行代码的用户 ID
exe_code__group 允许执行代码的群组 ID
exe_code__qbot_id OneBot V11 发送 ark 卡片所需的官 Bot QQ 号

权限说明

对于 exe_code__user 中配置的用户,在私聊/任意群聊中均可触发命令。

对于 exe_code__group 中配置的群组,任意用户均可触发命令。

🎉 使用

命令概览

  • code [代码] 在用户执行环境中执行代码。

    代码中包含的 at 消息段将被转换为 用户ID 字符串。

    代码中包含的 图片 消息段将被转换为 图片URL 字符串。

    具体参考 ~depends:_ExtractCode

  • getraw 获取引用消息的消息段文本形式。

    例:对于 OneBot V11 适配器,将返回消息的 CQ码

    提供变量: gemgurl

  • getmid 获取引用消息的消息 ID。

    提供变量: gemgurl

  • getimg [varname] 获取指定的图片。

    PIL.Image.Image 格式保存至上下文的 [varname] 变量中。未指定时默认为 img

    提供变量: gurl

  • terminate [@someone] 中止指定用户的代码。

    未指定时为自己的代码。仅 SUPERUSERS 可用。

对于上述 getxxx 命令,均可使用引用消息来指定传入的消息内容。

gem: 传入消息内容的消息体,类型为适配器给出的消息类。

gurl: 当传入消息包含图片时,自动提取的图片 URL。

执行环境

用户执行环境保存于 ~code_context:Context._contexts,随 NoneBot 重启而重置。

用户执行环境由 初始环境 深拷贝生成,包含 UniMessage 及一些常用消息段。

在传入代码开始执行前,用户执行环境将获得一个 API 实例,变量名固定为 api。同时,qid 变量将被设置为执行者的 用户IDgid 变量将被设置为当前 群组ID (私聊则为 None)

api 中被 @export 装饰的方法将被导出到用户执行环境。例: printfeedbackhelp,...

传入的代码经过一次异步函数包装后,可以正常执行异步代码。具体参考 ~code_context:Context._solve_code

对于供用户使用的接口方法,插件中使用 @descript 装饰器添加了描述。在执行代码时,可以通过 await help(api.method) 获取函数信息。

对于部分协议,插件提供了额外的接口,便于执行一些平台特化的操作。目前提供适配的协议:OneBot V11QQ

示例

await feedback(At(qid) + " Hi there")   # 向当前会话发送消息
await user(qid).send(f"Hello {qid}!")   # 向指定用户发送消息
await group(gid).send(f"Hello {gid}!")  # 向指定群组发送消息

# 插件重写的 print 函数,用法同原 print
# print 的内容将写入缓冲区,在代码段执行结束后输出
print("test", end=" ")
print("NoneBot", "Plugin", sep="-")

📝 更新日志

更新日志
  • 2024.07.21 v1.0.0

    插件开源

鸣谢

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_exe_code-1.0.1.tar.gz (20.4 kB view hashes)

Uploaded Source

Built Distribution

nonebot_plugin_exe_code-1.0.1-py3-none-any.whl (26.0 kB view hashes)

Uploaded Python 3

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page