Skip to content

Commit

Permalink
🔀 Merge pull request #490
Browse files Browse the repository at this point in the history
Release 2.0.0a15
  • Loading branch information
yanyongyu committed Aug 12, 2021
2 parents 037a5cc + 57a60ae commit c4e3309
Show file tree
Hide file tree
Showing 78 changed files with 314 additions and 183 deletions.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
Original file line number Diff line number Diff line change
Expand Up @@ -133,7 +133,11 @@ pip install nonebot-adapter-mirai
from nonebot.adapters.mirai import Bot

nonebot.init()
nonebot.get_driver().register_adapter('mirai', Bot, qq=12345678) # qq参数需要填在mah中登录的qq
nonebot.get_driver().register_adapter('mirai',
Bot,
qq=12345678)
# qq参数需要填在mah中登录的qq, 如果需要多个帐号, 可以填写类似于 [123456,789100] 的数组形式

nonebot.load_builtin_plugins() # 加载 nonebot 内置插件
nonebot.run()
```
Expand Down
File renamed without changes.
2 changes: 1 addition & 1 deletion docs/.vuepress/versions.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
[
"2.0.0a14",
"2.0.0a15",
"2.0.0a13.post1",
"2.0.0a10",
"2.0.0a8.post2",
Expand Down
6 changes: 5 additions & 1 deletion docs/guide/mirai-guide.md
Original file line number Diff line number Diff line change
Expand Up @@ -133,7 +133,11 @@ pip install nonebot-adapter-mirai
from nonebot.adapters.mirai import Bot

nonebot.init()
nonebot.get_driver().register_adapter('mirai', Bot, qq=12345678) # qq参数需要填在mah中登录的qq
nonebot.get_driver().register_adapter('mirai',
Bot,
qq=12345678)
# qq参数需要填在mah中登录的qq, 如果需要多个帐号, 可以填写类似于 [123456,789100] 的数组形式

nonebot.load_builtin_plugins() # 加载 nonebot 内置插件
nonebot.run()
```
Expand Down
4 changes: 2 additions & 2 deletions nonebot/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -232,8 +232,8 @@ def init(*, _env_file: Optional[str] = None, **kwargs):
default_filter.level = (
"DEBUG" if config.debug else
"INFO") if config.log_level is None else config.log_level
logger.opt(
colors=True).info(f"Current <y><b>Env: {env.environment}</b></y>")
logger.opt(colors=True).info(
f"Current <y><b>Env: {escape_tag(env.environment)}</b></y>")
logger.opt(colors=True).debug(
f"Loaded <y><b>Config</b></y>: {escape_tag(str(config.dict()))}")

Expand Down
16 changes: 8 additions & 8 deletions nonebot/adapters/_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
from copy import deepcopy
from functools import partial
from typing_extensions import Protocol
from dataclasses import dataclass, field
from dataclasses import dataclass, field, asdict
from typing import (Any, Set, List, Dict, Type, Tuple, Union, TypeVar, Mapping,
Generic, Optional, Iterable)

Expand Down Expand Up @@ -275,28 +275,28 @@ def __radd__(self, other: Union[str, Mapping, Iterable[Mapping]]) -> TM:
return self.get_message_class()(other) + self # type: ignore

def __getitem__(self, key: str):
return self.data[key]
return getattr(self, key)

def __setitem__(self, key: str, value: Any):
self.data[key] = value
return setattr(self, key, value)

def __iter__(self):
yield from self.data.__iter__()
yield from asdict(self).keys()

def __contains__(self, key: Any) -> bool:
return key in self.data
return key in asdict(self).keys()

def get(self, key: str, default: Any = None):
return getattr(self, key, default)

def keys(self):
return self.data.keys()
return asdict(self).keys()

def values(self):
return self.data.values()
return asdict(self).values()

def items(self):
return self.data.items()
return asdict(self).items()

def copy(self: T) -> T:
return deepcopy(self)
Expand Down
13 changes: 7 additions & 6 deletions nonebot/drivers/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
from typing import Any, Set, Dict, Type, Union, Optional, Callable, Awaitable, TYPE_CHECKING

from nonebot.log import logger
from nonebot.utils import escape_tag
from nonebot.config import Env, Config
from nonebot.typing import T_BotConnectionHook, T_BotDisconnectionHook

Expand Down Expand Up @@ -87,13 +88,13 @@ def register_adapter(self, name: str, adapter: Type["Bot"], **kwargs):
* ``**kwargs``: 其他传递给适配器的参数
"""
if name in self._adapters:
logger.opt(
colors=True).debug(f'Adapter "<y>{name}</y>" already exists')
logger.opt(colors=True).debug(
f'Adapter "<y>{escape_tag(name)}</y>" already exists')
return
self._adapters[name] = adapter
adapter.register(self, self.config, **kwargs)
logger.opt(
colors=True).debug(f'Succeeded to load adapter "<y>{name}</y>"')
logger.opt(colors=True).debug(
f'Succeeded to load adapter "<y>{escape_tag(name)}</y>"')

@property
@abc.abstractmethod
Expand All @@ -119,7 +120,7 @@ def run(self, *args, **kwargs):
* ``**kwargs``
"""
logger.opt(colors=True).debug(
f"<g>Loaded adapters: {', '.join(self._adapters)}</g>")
f"<g>Loaded adapters: {escape_tag(', '.join(self._adapters))}</g>")

@abc.abstractmethod
def on_startup(self, func: Callable) -> Callable:
Expand Down Expand Up @@ -346,7 +347,7 @@ def type(self) -> str:

@property
@abc.abstractmethod
def closed(self):
def closed(self) -> bool:
"""
:类型: ``bool``
:说明: 连接是否已经关闭
Expand Down
50 changes: 35 additions & 15 deletions nonebot/drivers/aiohttp.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@

from nonebot.log import logger
from nonebot.adapters import Bot
from nonebot.utils import escape_tag
from nonebot.typing import overrides
from nonebot.config import Env, Config
from nonebot.drivers import (ForwardDriver, HTTPPollingSetup, WebSocketSetup,
Expand Down Expand Up @@ -213,7 +214,8 @@ async def _build_request(
url = URL(setup.url)
if not url.is_absolute() or not url.host:
logger.opt(colors=True).error(
f"<r><bg #f8bbd0>Error parsing url {url}</bg #f8bbd0></r>")
f"<r><bg #f8bbd0>Error parsing url {escape_tag(str(url))}</bg #f8bbd0></r>"
)
return
host = f"{url.host}:{url.port}" if url.port else url.host
return HTTPRequest(setup.http_version, url.scheme, url.path,
Expand All @@ -226,17 +228,26 @@ async def _build_request(
setup_: Optional[HTTPPollingSetup] = None

logger.opt(colors=True).info(
f"Start http polling for <y>{setup.adapter.upper()} "
f"Bot {setup.self_id}</y>")
f"Start http polling for <y>{escape_tag(setup.adapter.upper())} "
f"Bot {escape_tag(setup.self_id)}</y>")

try:
async with aiohttp.ClientSession() as session:
while not self.should_exit.is_set():
if not bot:

try:
if callable(setup):
setup_ = await setup()
else:
setup_ = setup
except Exception as e:
logger.opt(colors=True, exception=e).error(
f"<r><bg #f8bbd0>Error while parsing setup {setup!r}.</bg #f8bbd0></r>"
)
await asyncio.sleep(3)
continue

if not bot:
request = await _build_request(setup_)
if not request:
return
Expand All @@ -245,7 +256,6 @@ async def _build_request(
bot = BotClass(setup.self_id, request)
self._bot_connect(bot)
elif callable(setup):
setup_ = await setup()
request = await _build_request(setup_)
if not request:
await asyncio.sleep(setup_.poll_interval)
Expand All @@ -265,7 +275,8 @@ async def _build_request(
else:
logger.opt(colors=True).error(
"<r><bg #f8bbd0>Unsupported HTTP Version "
f"{request.http_version}</bg #f8bbd0></r>")
f"{escape_tag(request.http_version)}</bg #f8bbd0></r>"
)
return

logger.debug(
Expand All @@ -284,7 +295,7 @@ async def _build_request(
asyncio.create_task(bot.handle_message(data))
except aiohttp.ClientResponseError as e:
logger.opt(colors=True, exception=e).error(
f"<r><bg #f8bbd0>Error occurred while requesting {setup_.url}. "
f"<r><bg #f8bbd0>Error occurred while requesting {escape_tag(setup_.url)}. "
"Try to reconnect...</bg #f8bbd0></r>")

await asyncio.sleep(setup_.poll_interval)
Expand All @@ -305,15 +316,23 @@ async def _ws_loop(self, setup: WEBSOCKET_SETUP):
try:
async with aiohttp.ClientSession() as session:
while True:
if callable(setup):
setup_ = await setup()
else:
setup_ = setup

try:
if callable(setup):
setup_ = await setup()
else:
setup_ = setup
except Exception as e:
logger.opt(colors=True, exception=e).error(
f"<r><bg #f8bbd0>Error while parsing setup {setup!r}.</bg #f8bbd0></r>"
)
await asyncio.sleep(3)
continue

url = URL(setup_.url)
if not url.is_absolute() or not url.host:
logger.opt(colors=True).error(
f"<r><bg #f8bbd0>Error parsing url {url}</bg #f8bbd0></r>"
f"<r><bg #f8bbd0>Error parsing url {escape_tag(str(url))}</bg #f8bbd0></r>"
)
await asyncio.sleep(setup_.reconnect_interval)
continue
Expand All @@ -329,8 +348,9 @@ async def _ws_loop(self, setup: WEBSOCKET_SETUP):
headers=headers,
timeout=30.) as ws:
logger.opt(colors=True).info(
f"WebSocket Connection to <y>{setup_.adapter.upper()} "
f"Bot {setup_.self_id}</y> succeeded!")
f"WebSocket Connection to <y>{escape_tag(setup_.adapter.upper())} "
f"Bot {escape_tag(setup_.self_id)}</y> succeeded!"
)
request = WebSocket(
"1.1", url.scheme, url.path,
url.raw_query_string.encode("latin-1"), headers,
Expand Down Expand Up @@ -360,7 +380,7 @@ async def _ws_loop(self, setup: WEBSOCKET_SETUP):
except (aiohttp.ClientResponseError,
aiohttp.ClientConnectionError) as e:
logger.opt(colors=True, exception=e).error(
f"<r><bg #f8bbd0>Error while connecting to {url}. "
f"<r><bg #f8bbd0>Error while connecting to {escape_tag(str(url))}. "
"Try to reconnect...</bg #f8bbd0></r>")
finally:
if bot:
Expand Down
Loading

0 comments on commit c4e3309

Please sign in to comment.