add doc for __init__.py

This commit is contained in:
yanyongyu 2020-08-18 17:24:49 +08:00
parent 76cfe34fa5
commit e523aa8d89
11 changed files with 10877 additions and 83 deletions

View File

@ -27,7 +27,7 @@ module.exports = {
editLinkText: "在 GitHub 上编辑此页", editLinkText: "在 GitHub 上编辑此页",
docsDir: "docs", docsDir: "docs",
lastUpdated: "上次更新", lastUpdated: "上次更新",
nav: [{ text: "API", link: "/api.md" }], nav: [{ text: "API", link: "/api/" }],
sidebar: {} sidebar: {}
}, },

7
docs_build/README.rst Normal file
View File

@ -0,0 +1,7 @@
NoneBot Api Reference
=====================
:模块索引:
- `nonebot <nonebot.html>`_
- `nonebot.typing <typing.html>`_
- `nonebot.config <config.html>`_

View File

@ -1,68 +0,0 @@
---
sidebar: auto
---
nonebot api reference
===============
.. automodule:: nonebot
:members:
:undoc-members:
:show-inheritance:
`nonebot.matcher` 模块
----------------------
.. automodule:: nonebot.matcher
:members:
:undoc-members:
:show-inheritance:
`nonebot.plugin` 模块
---------------------
.. automodule:: nonebot.plugin
:members:
:undoc-members:
:show-inheritance:
`nonebot.rule` 模块
-------------------
.. automodule:: nonebot.rule
:members:
:undoc-members:
:show-inheritance:
`nonebot.event` 模块
--------------------
.. automodule:: nonebot.event
:members:
:undoc-members:
:show-inheritance:
`nonebot.exception` 模块
------------------------
.. automodule:: nonebot.exception
:members:
:undoc-members:
:show-inheritance:
`nonebot.log` 模块
------------------
.. automodule:: nonebot.log
:members:
:undoc-members:
:show-inheritance:
`nonebot.typing` 模块
---------------------
.. automodule:: nonebot.typing
:members:
:undoc-members:
:show-inheritance:

View File

@ -51,7 +51,7 @@ templates_path = ['_templates']
# Usually you set "language" from the command line for these cases. # Usually you set "language" from the command line for these cases.
language = 'zh' language = 'zh'
master_doc = "api" master_doc = "README"
# List of patterns, relative to source directory, that match files and # List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files. # directories to ignore when looking for source files.

7
docs_build/nonebot.rst Normal file
View File

@ -0,0 +1,7 @@
NoneBot 模块
===============
.. automodule:: nonebot
:members:
:undoc-members:
:show-inheritance:

View File

@ -3,29 +3,108 @@
import logging import logging
import importlib import importlib
from ipaddress import IPv4Address from nonebot.typing import Bot, Dict, Type, Union, Driver, Optional, NoReturn
from nonebot.typing import Type, Union, Driver, Optional, NoReturn
_driver: Optional[Driver] = None _driver: Optional[Driver] = None
def get_driver() -> Union[NoReturn, Driver]: def get_driver() -> Union[NoReturn, Driver]:
"""
- **说明**:
获取全局 Driver 对象可用于在计划任务的回调中获取当前 Driver 对象
- **返回**:
* ``Driver``: 全局 Driver 对象
- **异常**:
* ``ValueError``: 全局 Driver 对象尚未初始化 (nonebot.init 尚未调用)
- **用法**:
.. code-block:: python
driver = nonebot.get_driver()
"""
if _driver is None: if _driver is None:
raise ValueError("NoneBot has not been initialized.") raise ValueError("NoneBot has not been initialized.")
return _driver return _driver
def get_app(): def get_app():
"""
- **说明**:
获取全局 Driver 对应 Server App 对象
- **返回**:
* ``Any``: Server App 对象
- **异常**:
* ``ValueError``: 全局 Driver 对象尚未初始化 (nonebot.init 尚未调用)
- **用法**:
.. code-block:: python
app = nonebot.get_app()
"""
driver = get_driver() driver = get_driver()
return driver.server_app return driver.server_app
def get_asgi(): def get_asgi():
"""
- **说明**:
获取全局 Driver 对应 Asgi 对象
- **返回**:
* ``Any``: Asgi 对象
- **异常**:
* ``ValueError``: 全局 Driver 对象尚未初始化 (nonebot.init 尚未调用)
- **用法**:
.. code-block:: python
asgi = nonebot.get_asgi()
"""
driver = get_driver() driver = get_driver()
return driver.asgi return driver.asgi
def get_bots(): def get_bots() -> Dict[str, Bot]:
"""
- **说明**:
获取所有通过 ws 连接 NoneBot Bot 对象
- **返回**:
* ``Dict[str, Bot]``: 一个以字符串 ID 为键Bot 对象为值的字典
- **异常**:
* ``ValueError``: 全局 Driver 对象尚未初始化 (nonebot.init 尚未调用)
- **用法**:
.. code-block:: python
bots = nonebot.get_bots()
"""
driver = get_driver() driver = get_driver()
return driver.bots return driver.bots
@ -41,6 +120,29 @@ except ImportError:
def init(*, _env_file: Optional[str] = None, **kwargs): def init(*, _env_file: Optional[str] = None, **kwargs):
"""
- **说明:**
初始化 NoneBot 以及 全局 Driver 对象
NoneBot 将会从 .env 文件中读取环境信息并使用相应的 env 文件配置
你也可以传入自定义的 _env_file 来指定 NoneBot 从该文件读取配置
- **参数:**
* ``_env_file: Optional[str]``: 配置文件名默认从 .env.{env_name} 中读取配置
* ``**kwargs``: 任意变量将会存储到 Config 对象里
- **返回:**
- `None`
- **用法:**
.. code-block:: python
nonebot.init(database=Database(...))
"""
global _driver global _driver
env = Env() env = Env()
config = Config(**kwargs, _env_file=_env_file or f".env.{env.environment}") config = Config(**kwargs, _env_file=_env_file or f".env.{env.environment}")
@ -61,10 +163,33 @@ def init(*, _env_file: Optional[str] = None, **kwargs):
nonebot_test.init() nonebot_test.init()
def run(host: Optional[IPv4Address] = None, def run(host: Optional[str] = None,
port: Optional[int] = None, port: Optional[int] = None,
*args, *args,
**kwargs): **kwargs):
"""
- **说明:**
启动 NoneBot即运行全局 Driver 对象
- **参数:**
* ``host: Optional[str]``: 主机名IP若不传入则使用配置文件中指定的值
* ``port: Optional[int]``: 端口若不传入则使用配置文件中指定的值
* ``*args``: 传入 Driver.run 的位置参数
* ``**kwargs``: 传入 Driver.run 的命名参数
- **返回:**
- `None`
- **用法:**
.. code-block:: python
nonebot.run(host="127.0.0.1", port=8080)
"""
get_driver().run(host, port, *args, **kwargs) get_driver().run(host, port, *args, **kwargs)

View File

@ -6,7 +6,7 @@ from pathlib import Path
from datetime import timedelta from datetime import timedelta
from ipaddress import IPv4Address from ipaddress import IPv4Address
from pydantic import BaseSettings from pydantic import BaseSettings, IPvAnyAddress
from pydantic.env_settings import SettingsError, env_file_sentinel, read_env_file from pydantic.env_settings import SettingsError, env_file_sentinel, read_env_file
from nonebot.typing import Set, Dict, Union, Mapping, Optional from nonebot.typing import Set, Dict, Union, Mapping, Optional
@ -96,7 +96,7 @@ class Config(BaseConfig):
""" """
# nonebot configs # nonebot configs
driver: str = "nonebot.drivers.fastapi" driver: str = "nonebot.drivers.fastapi"
host: IPv4Address = IPv4Address("127.0.0.1") host: IPvAnyAddress = IPv4Address("127.0.0.1") # type: ignore
port: int = 8080 port: int = 8080
secret: Optional[str] = None secret: Optional[str] = None
debug: bool = False debug: bool = False

View File

@ -2,11 +2,10 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
import abc import abc
from ipaddress import IPv4Address
from nonebot.log import logger from nonebot.log import logger
from nonebot.config import Env, Config from nonebot.config import Env, Config
from nonebot.typing import Bot, Dict, Type, Optional, Callable from nonebot.typing import Bot, Dict, Type, Union, Optional, Callable
class BaseDriver(abc.ABC): class BaseDriver(abc.ABC):
@ -57,7 +56,7 @@ class BaseDriver(abc.ABC):
@abc.abstractmethod @abc.abstractmethod
def run(self, def run(self,
host: Optional[IPv4Address] = None, host: Optional[str] = None,
port: Optional[int] = None, port: Optional[int] = None,
*args, *args,
**kwargs): **kwargs):

View File

@ -3,7 +3,6 @@
import json import json
import logging import logging
from ipaddress import IPv4Address
import uvicorn import uvicorn
from fastapi import FastAPI, status from fastapi import FastAPI, status
@ -16,7 +15,7 @@ from nonebot.config import Env, Config
from nonebot.utils import DataclassEncoder from nonebot.utils import DataclassEncoder
from nonebot.adapters.cqhttp import Bot as CQBot from nonebot.adapters.cqhttp import Bot as CQBot
from nonebot.drivers import BaseDriver, BaseWebSocket from nonebot.drivers import BaseDriver, BaseWebSocket
from nonebot.typing import Optional, Callable, overrides from nonebot.typing import Union, Optional, Callable, overrides
class Driver(BaseDriver): class Driver(BaseDriver):
@ -66,7 +65,7 @@ class Driver(BaseDriver):
@overrides(BaseDriver) @overrides(BaseDriver)
def run(self, def run(self,
host: Optional[IPv4Address] = None, host: Optional[str] = None,
port: Optional[int] = None, port: Optional[int] = None,
*, *,
app: Optional[str] = None, app: Optional[str] = None,
@ -99,7 +98,7 @@ class Driver(BaseDriver):
}, },
} }
uvicorn.run(app or self.server_app, uvicorn.run(app or self.server_app,
host=host or str(self.config.host), host=str(host) or str(self.config.host),
port=port or self.config.port, port=port or self.config.port,
reload=app and self.config.debug, reload=app and self.config.debug,
debug=self.config.debug, debug=self.config.debug,

10721
package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

View File

@ -2,4 +2,8 @@ DRIVER=nonebot.drivers.fastapi
HOST=0.0.0.0 HOST=0.0.0.0
PORT=2333 PORT=2333
DEBUG=true DEBUG=true
COMMAND_START={"", "/", "#"}
COMMAND_SEP={"/", "."}
CUSTOM_CONFIG={"custom": 1} CUSTOM_CONFIG={"custom": 1}