nonebot2/nonebot/__init__.py

65 lines
1.5 KiB
Python
Raw Normal View History

2020-06-30 10:13:58 +08:00
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import logging
2020-07-04 22:51:10 +08:00
import importlib
from ipaddress import IPv4Address
2020-07-05 20:39:34 +08:00
from nonebot.log import logger
from nonebot.config import Env, Config
from nonebot.drivers import BaseDriver
2020-08-13 15:23:04 +08:00
from nonebot.adapters.cqhttp import Bot as CQBot
from nonebot.typing import Union, Optional, NoReturn
2020-07-04 22:51:10 +08:00
2020-08-13 18:16:59 +08:00
try:
import nonebot_test
except ImportError:
nonebot_test = None
2020-07-04 22:51:10 +08:00
_driver: Optional[BaseDriver] = None
2020-08-10 13:06:02 +08:00
def get_driver() -> Union[NoReturn, BaseDriver]:
2020-07-04 22:51:10 +08:00
if _driver is None:
raise ValueError("NoneBot has not been initialized.")
return _driver
def get_app():
driver = get_driver()
return driver.server_app
def get_asgi():
driver = get_driver()
return driver.asgi
def init(*, _env_file: Optional[str] = None, **kwargs):
2020-07-04 22:51:10 +08:00
global _driver
env = Env()
config = Config(**kwargs, _env_file=_env_file or f".env.{env.environment}")
logger.setLevel(logging.DEBUG if config.debug else logging.INFO)
logger.debug(f"Loaded config: {config.dict()}")
Driver = getattr(importlib.import_module(config.driver), "Driver")
2020-08-10 13:06:02 +08:00
_driver = Driver(env, config)
2020-07-04 22:51:10 +08:00
2020-08-13 18:16:59 +08:00
# register build-in adapters
2020-08-13 15:23:04 +08:00
_driver.register_adapter("cqhttp", CQBot)
2020-08-13 18:16:59 +08:00
# load nonebot test frontend if debug
if config.debug and nonebot_test:
nonebot_test.init()
2020-07-04 22:51:10 +08:00
def run(host: Optional[IPv4Address] = None,
port: Optional[int] = None,
*args,
**kwargs):
get_driver().run(host, port, *args, **kwargs)
2020-06-30 10:13:58 +08:00
2020-07-05 20:39:34 +08:00
from nonebot.plugin import load_plugins, get_loaded_plugins