internlm/SWE-Fixer-Train-110K huggingface dataset:
Repository: nonebot/nonebot2

Issue:
Bug: 事件响应器异常
**描述问题：**

任意事件响应器
```
from nonebot import on_message
message = on_message()
```
对于任何消息都会引发异常
```
01-01 14:57:55 [DEBUG] nonebot | CQHTTP | Event Parser Error
Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "C:\Users\...\AppData\Local\Programs\Python\Python38\lib\multiprocessing\spawn.py", line 116, in spawn_main
    exitcode = _main(fd, parent_sentinel)
  File "C:\Users\...\AppData\Local\Programs\Python\Python38\lib\multiprocessing\spawn.py", line 129, in _main
    return self._bootstrap(parent_sentinel)
  File "C:\Users\...\AppData\Local\Programs\Python\Python38\lib\multiprocessing\process.py", line 315, in _bootstrap
    self.run()
  File "C:\Users\...\AppData\Local\Programs\Python\Python38\lib\multiprocessing\process.py", line 108, in run
    self._target(*self._args, **self._kwargs)
  File "C:\Users\...\PycharmProjects\nonebot2\venv\lib\site-packages\uvicorn\subprocess.py", line 62, in subprocess_started
    target(sockets=sockets)
  File "C:\Users\...\PycharmProjects\nonebot2\venv\lib\site-packages\uvicorn\main.py", line 390, in run
    loop.run_until_complete(self.serve(sockets=sockets))
  File "C:\Users\...\AppData\Local\Programs\Python\Python38\lib\asyncio\base_events.py", line 603, in run_until_complete
    self.run_forever()
  File "C:\Users\...\AppData\Local\Programs\Python\Python38\lib\asyncio\base_events.py", line 570, in run_forever
    self._run_once()
  File "C:\Users\...\AppData\Local\Programs\Python\Python38\lib\asyncio\base_events.py", line 1859, in _run_once
    handle._run()
  File "C:\Users\...\AppData\Local\Programs\Python\Python38\lib\asyncio\events.py", line 81, in _run
    self._context.run(self._callback, *self._args)
> File "C:\Users\...\PycharmProjects\nonebot2\venv\lib\site-packages\nonebot\adapters\cqhttp\bot.py", line 307, in handle_message
    event = model.parse_obj(message)
  File "pydantic\main.py", line 520, in pydantic.main.BaseModel.parse_obj
    return cls(**obj)
  File "pydantic\main.py", line 362, in pydantic.main.BaseModel.__init__
    raise validation_error
pydantic.error_wrappers.ValidationError: 1 validation error for GroupMessageEvent
anonymous
  none is not an allowed value (type=type_error.none.not_allowed)
```

**环境信息：**

 - OS: Windows 10 20H2 19042.685
 - Python Version: 3.8
 - Nonebot Version: 2.0.0a8 (从2.0.0a7升级)




Discussion:

Resolving patch:
diff --git a/nonebot/adapters/cqhttp/event.py b/nonebot/adapters/cqhttp/event.py
--- a/nonebot/adapters/cqhttp/event.py
+++ b/nonebot/adapters/cqhttp/event.py
@@ -184,7 +184,7 @@ class GroupMessageEvent(MessageEvent):
     __event__ = "message.group"
     message_type: Literal["group"]
     group_id: int
-    anonymous: Anonymous
+    anonymous: Optional[Anonymous] = None
 
     @overrides(Event)
     def get_event_description(self) -> str:


Test patch:
Repository: nonebot/nonebot2

Issue:
Bug: 错误删除未执行过的`temp matcher`
**描述问题：**

处理事件时错误地删除了未执行过的 `temp matcher`

**环境信息：**

 - OS: any
 - Python Version: any
 - Nonebot Version: 2.0.0a8



Discussion:

Resolving patch:
diff --git a/nonebot/message.py b/nonebot/message.py
--- a/nonebot/message.py
+++ b/nonebot/message.py
@@ -117,8 +117,7 @@ async def _check(Matcher: Type[Matcher], bot: "Bot", event: "Event",
         return None
 
     async def _check_expire(Matcher: Type[Matcher]) -> Optional[Type[Matcher]]:
-        if Matcher.temp or (Matcher.expire_time and
-                            datetime.now() > Matcher.expire_time):
+        if Matcher.expire_time and datetime.now() > Matcher.expire_time:
             return Matcher
         return None
 
@@ -128,14 +127,19 @@ async def _check_expire(Matcher: Type[Matcher]) -> Optional[Type[Matcher]]:
     checking_expire_tasks = [
         _check_expire(Matcher) for Matcher in current_matchers
     ]
-    results = await asyncio.gather(*checking_tasks, return_exceptions=True)
+    results = await asyncio.gather(*checking_tasks)
     expired = await asyncio.gather(*checking_expire_tasks)
     for expired_matcher in filter(lambda x: x, expired):
         try:
             matchers[priority].remove(expired_matcher)  # type: ignore
         except Exception:
             pass
-    return filter(lambda x: x, results)
+    for temp_matcher in filter(lambda x: x and x.temp, results):
+        try:
+            matchers[priority].remove(temp_matcher)  # type: ignore
+        except Exception:
+            pass
+    return filter(lambda x: x, results)  # type: ignore
 
 
 async def _run_matcher(Matcher: Type[Matcher], bot: "Bot", event: "Event",


Test patch:
Repository: nonebot/nonebot2

Issue:
Bug: @on_notice(sth).send() reply a group message when receive notice in private chat
**描述问题：**

私聊注册一个on_notice以后（比如戳一戳），生成的PokeNotifyEvent中存在attr 'group_id' = None；
但是在cqhttp的adapter中（_见nonebot/adapters/cqhttp/bot.py function Bot.send()_)，send只会检测group_id是否存在于字典中，而不检测它是否为None，因此会把这条私聊的notice作为群聊消息返回。
详细代码如下：
```python
        if "message_type" not in params:
            if "group_id" in params:
                params["message_type"] = "group"
            elif "user_id" in params:
                params["message_type"] = "private"
            else:
                raise ValueError("Cannot guess message type to reply!")
```
（实际上改动一下if statement就好？但我不敢提pr，没怎么读过代码）

**如何复现？**

见上文。

**期望的结果**

@on_notice(sth).send() 应该发送私聊消息

**环境信息：**

 - OS: OS Independent
 - Python Version: 3.8
 - Nonebot Version: 2.0.0a8post1

**截图**

暂无


Discussion:

Resolving patch:
diff --git a/nonebot/adapters/cqhttp/bot.py b/nonebot/adapters/cqhttp/bot.py
--- a/nonebot/adapters/cqhttp/bot.py
+++ b/nonebot/adapters/cqhttp/bot.py
@@ -421,19 +421,19 @@ async def send(self,
         message = escape(message) if isinstance(message, str) else message
         msg = message if isinstance(message, Message) else Message(message)
 
-        at_sender = at_sender and hasattr(event, "user_id")
+        at_sender = at_sender and getattr(event, "user_id", None)
 
         params = {}
-        if hasattr(event, "user_id"):
+        if getattr(event, "user_id", None):
             params["user_id"] = getattr(event, "user_id")
-        if hasattr(event, "group_id"):
+        if getattr(event, "group_id", None):
             params["group_id"] = getattr(event, "group_id")
         params.update(kwargs)
 
         if "message_type" not in params:
-            if "group_id" in params:
+            if params.get("group_id", None):
                 params["message_type"] = "group"
-            elif "user_id" in params:
+            elif params.get("user_id", None):
                 params["message_type"] = "private"
             else:
                 raise ValueError("Cannot guess message type to reply!")


Test patch:
Repository: nonebot/nonebot2

Issue:
Bug: 发送窗口抖动消息，在msg中是无消息内容的，如果通过[0]索引或报错
cqhttp包下bot.py模块中    first_msg_seg = event.message[0] 超出索引

问题如上，另外建议连续二次索引时增加第一次索引的默认值防止第二次索引超出，state["_prefix"]["command"] in commands



Discussion:
窗口抖动消息应该有[CQ:poke]才对
能否提供一下cqhttp实现以及复现方法信息

二次索引这边都做了长度判断以及message长度补充确保长度>0

Resolving patch:
diff --git a/nonebot/adapters/cqhttp/bot.py b/nonebot/adapters/cqhttp/bot.py
--- a/nonebot/adapters/cqhttp/bot.py
+++ b/nonebot/adapters/cqhttp/bot.py
@@ -82,6 +82,10 @@ def _check_at_me(bot: "Bot", event: "Event"):
     if not isinstance(event, MessageEvent):
         return
 
+    # ensure message not empty
+    if not event.message:
+        event.message.append(MessageSegment.text(""))
+
     if event.message_type == "private":
         event.to_me = True
     else:


Test patch:
Repository: nonebot/nonebot2

Issue:
自动生成 api 文档
**是否在使用中遇到某些问题而需要新的特性？请描述：**

```python
self._server_app = FastAPI(
            debug=config.debug,
            openapi_url=None,
            docs_url=None,
            redoc_url=None,
        )
```

源码好像禁止了API文档自动生成的功能，能否改为根据配置决定？例如添加一个配置项。

因为开发时要进行 API 请求调试，所以感觉这个功能还是挺有必要的



Discussion:
[根据FastAPI文档](https://fastapi.tiangolo.com/advanced/sub-applications/#check-the-automatic-api-docs), 你似乎可以自己挂载一个启用了文档生成功能的Sub Application
这个后续可以进行支持

Resolving patch:
diff --git a/nonebot/drivers/fastapi.py b/nonebot/drivers/fastapi.py
--- a/nonebot/drivers/fastapi.py
+++ b/nonebot/drivers/fastapi.py
@@ -14,18 +14,28 @@
 from typing import Optional, Callable
 
 import uvicorn
+from pydantic import BaseSettings
 from fastapi.responses import Response
 from fastapi import Body, status, Request, FastAPI, HTTPException
 from starlette.websockets import WebSocketDisconnect, WebSocket as FastAPIWebSocket
 
 from nonebot.log import logger
 from nonebot.typing import overrides
-from nonebot.config import Env, Config
 from nonebot.utils import DataclassEncoder
 from nonebot.exception import RequestDenied
+from nonebot.config import Env, Config as NoneBotConfig
 from nonebot.drivers import Driver as BaseDriver, WebSocket as BaseWebSocket
 
 
+class Config(BaseSettings):
+    fastapi_openapi_url: Optional[str] = None
+    fastapi_docs_url: Optional[str] = None
+    fastapi_redoc_url: Optional[str] = None
+
+    class Config:
+        extra = "ignore"
+
+
 class Driver(BaseDriver):
     """
     FastAPI 驱动框架
@@ -38,14 +48,16 @@ class Driver(BaseDriver):
       * ``/{adapter name}/ws/``: WebSocket 上报
     """
 
-    def __init__(self, env: Env, config: Config):
+    def __init__(self, env: Env, config: NoneBotConfig):
         super().__init__(env, config)
 
+        self.fastapi_config = Config(**config.dict())
+
         self._server_app = FastAPI(
             debug=config.debug,
-            openapi_url=None,
-            docs_url=None,
-            redoc_url=None,
+            openapi_url=self.fastapi_config.fastapi_openapi_url,
+            docs_url=self.fastapi_config.fastapi_docs_url,
+            redoc_url=self.fastapi_config.fastapi_redoc_url,
         )
 
         self._server_app.post("/{adapter}/")(self._handle_http)


Test patch:
Repository: nonebot/nonebot2

Issue:
Feature: 将`.env`作为公共配置文件
**是否在使用中遇到某些问题而需要新的特性？请描述：**

由于目前使用 `.env.*` 各配置文件来区分环境进行配置，不少配置在不同环境下一致却需要复制粘贴。

**描述你所需要的特性：**

将 `.env` 文件作为公共的配置文件，可以由 `.env.*` 覆盖部分配置



Discussion:

Resolving patch:
diff --git a/nonebot/__init__.py b/nonebot/__init__.py
--- a/nonebot/__init__.py
+++ b/nonebot/__init__.py
@@ -175,6 +175,7 @@ def init(*, _env_file: Optional[str] = None, **kwargs):
         logger.opt(
             colors=True).info(f"Current <y><b>Env: {env.environment}</b></y>")
         config = Config(**kwargs,
+                        _common_config=env.dict(),
                         _env_file=_env_file or f".env.{env.environment}")
 
         default_filter.level = "DEBUG" if config.debug else "INFO"
diff --git a/nonebot/config.py b/nonebot/config.py
--- a/nonebot/config.py
+++ b/nonebot/config.py
@@ -20,12 +20,41 @@
 from ipaddress import IPv4Address
 from typing import Any, Set, Dict, Union, Mapping, Optional
 
+from pydantic.utils import deep_update
 from pydantic import BaseSettings, IPvAnyAddress
 from pydantic.env_settings import SettingsError, env_file_sentinel, read_env_file
 
 
 class BaseConfig(BaseSettings):
 
+    def __init__(
+            __pydantic_self__,  # type: ignore
+            _common_config: Optional[Dict[Any, Any]] = None,
+            _env_file: Union[Path, str, None] = env_file_sentinel,
+            _env_file_encoding: Optional[str] = None,
+            _secrets_dir: Union[Path, str, None] = None,
+            **values: Any) -> None:
+        super(BaseSettings,
+              __pydantic_self__).__init__(**__pydantic_self__._build_values(
+                  values,
+                  _common_config=_common_config,
+                  _env_file=_env_file,
+                  _env_file_encoding=_env_file_encoding,
+                  _secrets_dir=_secrets_dir))
+
+    def _build_values(
+        self,
+        init_kwargs: Dict[str, Any],
+        _common_config: Optional[Dict[Any, Any]] = None,
+        _env_file: Union[Path, str, None] = None,
+        _env_file_encoding: Optional[str] = None,
+        _secrets_dir: Union[Path, str, None] = None,
+    ) -> Dict[str, Any]:
+        return deep_update(self._build_secrets_files(_secrets_dir),
+                           _common_config or {},
+                           self._build_environ(_env_file,
+                                               _env_file_encoding), init_kwargs)
+
     def _build_environ(
             self,
             _env_file: Union[Path, str, None] = None,
@@ -92,7 +121,7 @@ def __getattr__(self, name: str) -> Any:
         return self.__dict__.get(name)
 
 
-class Env(BaseSettings):
+class Env(BaseConfig):
     """
     运行环境配置。大小写不敏感。
 
@@ -109,6 +138,7 @@ class Env(BaseSettings):
     """
 
     class Config:
+        extra = "allow"
         env_file = ".env"
 
 


Test patch:
diff --git a/tests/.env b/tests/.env
--- a/tests/.env
+++ b/tests/.env
@@ -1 +1,2 @@
 ENVIRONMENT=dev
+CUSTOM_CONFIG=common
Repository: nonebot/nonebot2

Issue:
Bug: 内置的single_session插件有一些bug
**描述问题：**

内置的`single_session`插件只能处理有`get_session_id`方法的`event`，如果一个`matcher`监听了`metaevent`，那么其中的`run_preprocessor`会报错

**如何复现？**

[这一行](https://github.com/nonebot/nonebot2/blob/93ffc93a80cf9e3103eb4a164e7b32ab3cdd0882/nonebot/plugins/single_session.py#L13)限制了只能监听有`get_session_id`的事件，但是对没有这个方法的事件没有做额外的处理，导致报错。
除此之外，下面的[判断语句](https://github.com/nonebot/nonebot2/blob/93ffc93a80cf9e3103eb4a164e7b32ab3cdd0882/nonebot/plugins/single_session.py#L16)也有问题，如果这个事件第一次遇到的话不应该被忽略

**期望的结果**
插件正常使用

````



Discussion:

Resolving patch:
diff --git a/nonebot/plugins/single_session.py b/nonebot/plugins/single_session.py
--- a/nonebot/plugins/single_session.py
+++ b/nonebot/plugins/single_session.py
@@ -10,17 +10,23 @@
 
 @run_preprocessor
 async def _(matcher: Matcher, bot: Bot, event: Event, state: T_State):
-    session_id = event.get_session_id()
-    event_id = id(event)
-
-    if _running_matcher.get(session_id, None) != event_id:
+    try:
+        session_id = event.get_session_id()
+    except Exception:
+        return
+    current_event_id = id(event)
+    event_id = _running_matcher.get(session_id, None)
+    if event_id and event_id != current_event_id:
         raise IgnoredException("Annother matcher running")
 
-    _running_matcher[session_id] = event_id
+    _running_matcher[session_id] = current_event_id
 
 
 @run_postprocessor
 async def _(matcher: Matcher, exception: Optional[Exception], bot: Bot, event: Event, state: T_State):
-    session_id = event.get_session_id()
+    try:
+        session_id = event.get_session_id()
+    except Exception:
+        return
     if session_id in _running_matcher:
         del _running_matcher[session_id]


Test patch:
Repository: nonebot/nonebot2

Issue:
Bug: Mirai模块处理仅含@Bot的消息时报错
**描述问题：**

对于单独的@bot消息处理时报错。

**如何复现？**

使用mirai模块处理消息，当在群聊中单独@机器人（不跟随其他信息）时消息处理报错

**期望的结果**

能够正常处理

**环境信息：**

 - OS: CentOS & Winodws
 - Python Version: 3.9.2
 - Nonebot Version: nonebot cli version 0.4.0

**截图**
![image](https://user-images.githubusercontent.com/44700327/112746873-7a2cbd80-8fe4-11eb-9b6a-46620c3ee67f.png)




Discussion:

Resolving patch:
diff --git a/packages/nonebot-adapter-mirai/nonebot/adapters/mirai/utils.py b/packages/nonebot-adapter-mirai/nonebot/adapters/mirai/utils.py
--- a/packages/nonebot-adapter-mirai/nonebot/adapters/mirai/utils.py
+++ b/packages/nonebot-adapter-mirai/nonebot/adapters/mirai/utils.py
@@ -11,7 +11,7 @@
 from nonebot.utils import escape_tag, logger_wrapper
 
 from .event import Event, GroupMessage, MessageEvent, MessageSource
-from .message import MessageType
+from .message import MessageType, MessageSegment
 
 if TYPE_CHECKING:
     from .bot import Bot
@@ -64,7 +64,7 @@ def __repr__(self):
 class InvalidArgument(exception.AdapterException):
     """
     :说明:
-    
+
       调用API的参数出错
     """
 
@@ -106,7 +106,7 @@ def argument_validation(function: _AnyCallable) -> _AnyCallable:
     :说明:
 
       通过函数签名中的类型注解来对传入参数进行运行时校验
-      
+
       会在参数出错时释放 ``InvalidArgument`` 异常
     """
     function = validate_arguments(config={
@@ -138,6 +138,8 @@ def process_at(bot: "Bot", event: GroupMessage) -> GroupMessage:
             event.to_me = True
         else:
             event.message_chain.insert(0, at)
+    if not event.message_chain:
+        event.message_chain.append(MessageSegment.plain(''))
     return event
 
 
@@ -175,4 +177,4 @@ async def process_event(bot: "Bot", event: Event) -> None:
             event = process_nick(bot, event)
             event = process_at(bot, event)
             event = process_reply(bot, event)
-    await handle_event(bot, event)
\ No newline at end of file
+    await handle_event(bot, event)


Test patch:
Repository: nonebot/nonebot2

Issue:
Bug: Logger 发起对象名一律为 nonebot
**描述问题：**
![image](https://user-images.githubusercontent.com/59906398/115154552-ff6c3500-a0ad-11eb-8cca-7bbb0b1cc9d6.png)
在 [v2.0.0a11](https://github.com/nonebot/nonebot2/tree/v2.0.0a11) 及更早版本中，通过在事件处理的文件或者包中调用 `loguru.logger` 其输出的日志之发起对象名为该文件或包之名称
![image](https://user-images.githubusercontent.com/59906398/115154578-2cb8e300-a0ae-11eb-94f0-93857c642110.png)
在 [v2.0.0a13.post1](https://github.com/nonebot/nonebot2/tree/v2.0.0a13.post1) 中，使用相同方式输出的日志，其发起对象名一律为 nonebot

**期望的结果**

日志之发起对象名为该文件或包之名称

**环境信息：**

 - OS: windows-latest
 - Python Version: 3.9.4
 - Nonebot Version: v2.0.0a13.post1


Discussion:

Resolving patch:
diff --git a/nonebot/log.py b/nonebot/log.py
--- a/nonebot/log.py
+++ b/nonebot/log.py
@@ -47,6 +47,10 @@ def __init__(self) -> None:
         self.level = "DEBUG"
 
     def __call__(self, record):
+        module = sys.modules.get(record["name"])
+        if module:
+            plugin_name = getattr(module, "__plugin_name__", record["name"])
+            record["name"] = plugin_name
         record["name"] = record["name"].split(".")[0]
         levelno = logger.level(self.level).no
         return record["level"].no >= levelno
diff --git a/nonebot/plugin/manager.py b/nonebot/plugin/manager.py
--- a/nonebot/plugin/manager.py
+++ b/nonebot/plugin/manager.py
@@ -215,6 +215,9 @@ def exec_module(self, module: ModuleType) -> None:
             return
         # really need?
         # setattr(module, "__manager__", self.manager)
+        if self._plugin_token:
+            setattr(module, "__plugin_name__",
+                    _current_plugin.get(self._plugin_token))
         if self._export_token:
             setattr(module, "__export__", _export.get())
 


Test patch:
Repository: nonebot/nonebot2

Issue:
Bug:Mirai 邀请入群和入群操作报错
**描述问题：**

Mirai 邀请机器人入群报错

**如何复现？**

1. 邀请机器人入群
2. approve(bot)

**期望的结果**



**环境信息：**

 - OS: [windows]
 - Python Version: [3.8.8]
 - Nonebot Version: [2.0.0a13.post1]

**截图**

![image](https://user-images.githubusercontent.com/36364025/120922223-714e1b80-c6fa-11eb-9aa9-f4948fa73d1d.png)

Bug:Mirai 邀请入群和入群操作报错
**描述问题：**

Mirai 邀请机器人入群报错

**如何复现？**

1. 邀请机器人入群
2. approve(bot)

**期望的结果**



**环境信息：**

 - OS: [windows]
 - Python Version: [3.8.8]
 - Nonebot Version: [2.0.0a13.post1]

**截图**

![image](https://user-images.githubusercontent.com/36364025/120922223-714e1b80-c6fa-11eb-9aa9-f4948fa73d1d.png)



Discussion:

Resolving patch:
diff --git a/packages/nonebot-adapter-mirai/nonebot/adapters/mirai/event/request.py b/packages/nonebot-adapter-mirai/nonebot/adapters/mirai/event/request.py
--- a/packages/nonebot-adapter-mirai/nonebot/adapters/mirai/event/request.py
+++ b/packages/nonebot-adapter-mirai/nonebot/adapters/mirai/event/request.py
@@ -91,7 +91,8 @@ async def approve(self, bot: "Bot"):
                                       'eventId': self.event_id,
                                       'groupId': self.group_id,
                                       'fromId': self.from_id,
-                                      'operate': 0
+                                      'operate': 0,
+                                      'message': ''
                                   })
 
     async def reject(self,
@@ -147,7 +148,8 @@ async def approve(self, bot: "Bot"):
                                       'eventId': self.event_id,
                                       'groupId': self.group_id,
                                       'fromId': self.from_id,
-                                      'operate': 0
+                                      'operate': 0,
+                                      'message': ''
                                   })
 
     async def reject(self, bot: "Bot", message: str = ""):


Test patch:
Repository: nonebot/nonebot2

Issue:
Bug: mirai adapter调用upload_image上传图片报错
**描述问题：**

mirai adapter调用upload_image上传图片报错：

```powershell
httpx.HTTPStatusError: 400 Client Error: Bad Request for url: http://127.0.0.1:8000/uploadImage
For more information check: https://httpstatuses.com/400
```

**如何复现？**

```python
with open('file.png', 'rb') as f:
    img = BytesIO(f.read())
img_id = await bot.upload_image('group', img)
```

**期望的结果**

```
{'imageId': '{******-****-FD90-491D-141D77303EE5}.png', 'url': 'http://gchat.qpic.cn/gchatpic_new/*********', 'path': ''}
```

**环境信息：**

 - OS: Windows10
 - Python Version: 3.8.2
 - Nonebot Version: 2.0.0a13.post1
 - Mirai Version: 2.7-M1
 - mirai-api-http Version: 1.12.0

**截图**

![image-20210707135254327](https://user-images.githubusercontent.com/49870766/124708711-39223e80-df2d-11eb-9601-6626106317e9.png)


**原因**

mah v-1.8.4 的uploadImage api需要提供sessionKey。
经过测试，mah 版本1.12.0，在增加sessionKey后能返回预期结果，
是个新手，代码写的不好，就不提pr了。
> ### [图片文件上传](https://github.com/zxsean/mirai-api-http/blob/master/docs/API.md#%E5%9B%BE%E7%89%87%E6%96%87%E4%BB%B6%E4%B8%8A%E4%BC%A0)
>
> ```
> [POST] /uploadImage
> ```
>
> 使用此方法上传图片文件至服务器并返回ImageId
>
> #### 请求
>
> Content-Type：multipart/form-data
>
> | 名字       | 类型   | 可选  | 举例        | 说明                          |
> | ---------- | ------ | ----- | ----------- | ----------------------------- |
> | sessionKey | String | false | YourSession | 已经激活的Session             |
> | type       | String | false | "friend "   | "friend" 或 "group" 或 "temp" |
> | img        | File   | false | -           | 图片文件                      |



在mah v-2.0的http adapter中就不需要了

> ### [图片文件上传](https://github.com/project-mirai/mirai-api-http/blob/master/docs/adapter/HttpAdapter.md#%E5%9B%BE%E7%89%87%E6%96%87%E4%BB%B6%E4%B8%8A%E4%BC%A0)
>
> 使用此方法上传图片文件至服务器并返回ImageId
>
> ```
> [POST] /uploadImage
> ```
>
> **本接口为[POST]请求, 参数格式为`multipart/form-data`**
>
> #### 请求:
>
> | 名字       | 类型   | 可选  | 举例        | 说明                          |
> | ---------- | ------ | ----- | ----------- | ----------------------------- |
> | sessionKey | String | true  | YourSession | 已经激活的Session             |
> | type       | String | false | "friend"    | "friend" 或 "group" 或 "temp" |
> | img        | File   | false | -           | 图片文件                      |




Discussion:

Resolving patch:
diff --git a/packages/nonebot-adapter-mirai/nonebot/adapters/mirai/bot.py b/packages/nonebot-adapter-mirai/nonebot/adapters/mirai/bot.py
--- a/packages/nonebot-adapter-mirai/nonebot/adapters/mirai/bot.py
+++ b/packages/nonebot-adapter-mirai/nonebot/adapters/mirai/bot.py
@@ -95,6 +95,7 @@ async def upload(self, path: str, *, params: Dict[str, Any]) -> Any:
         """
         files = {k: v for k, v in params.items() if isinstance(v, BytesIO)}
         form = {k: v for k, v in params.items() if k not in files}
+        form['sessionKey'] = self.session_key
         response = await self.client.post(
             path,
             data=form,


Test patch: