Restructure

This commit is contained in:
Richard Chien 2018-06-25 21:14:27 +08:00
parent 1392382244
commit e52aa34f85
7 changed files with 70 additions and 27 deletions

View File

@ -55,14 +55,14 @@ _plugins = set()
def load_plugins(): def load_plugins():
_plugins.clear() _plugins.clear()
root_dir = os.path.dirname(__path__[0]) none_dir = __path__[0]
plugins_dir = os.path.join(root_dir, 'plugins') plugins_dir = os.path.join(none_dir, 'plugins')
saved_cwd = os.getcwd() saved_cwd = os.getcwd()
os.chdir(root_dir) os.chdir(none_dir)
for item in os.listdir(plugins_dir): for item in os.listdir(plugins_dir):
path = os.path.join(plugins_dir, item) path = os.path.join(plugins_dir, item)
if os.path.isfile(path) and \ if os.path.isfile(path) and \
(path.startswith('_') or not path.endswith('.py')): (item.startswith('_') or not item.endswith('.py')):
continue continue
if os.path.isdir(path) and \ if os.path.isdir(path) and \
(path.startswith('_') or not os.path.exists( (path.startswith('_') or not os.path.exists(
@ -73,7 +73,7 @@ def load_plugins():
if not m: if not m:
continue continue
mod_name = 'plugins.' + m.group(1) mod_name = 'none.plugins.' + m.group(1)
try: try:
_plugins.add(importlib.import_module(mod_name)) _plugins.add(importlib.import_module(mod_name))
logger.info('Succeeded to import "{}"'.format(mod_name)) logger.info('Succeeded to import "{}"'.format(mod_name))

View File

@ -1,13 +1,16 @@
import re import re
import asyncio import asyncio
from datetime import datetime from datetime import datetime
from typing import Tuple, Union, Callable, Iterable, Dict, Any, Optional, List from typing import (
Tuple, Union, Callable, Iterable, Dict, Any, Optional, List, Sequence
)
from aiocqhttp import CQHttp, Error as CQHttpError from aiocqhttp import CQHttp, Error as CQHttpError
from aiocqhttp.message import Message from aiocqhttp.message import Message
from . import permissions as perm from . import permissions as perm
from .helpers import context_source from .helpers import context_source
from .expression import render
# Key: str (one segment of command name) # Key: str (one segment of command name)
# Value: subtree or a leaf Command object # Value: subtree or a leaf Command object
@ -160,7 +163,8 @@ class Session:
return False return False
return True return True
def require_arg(self, key: str, prompt: str, *, def require_arg(self, key: str, prompt: str = None, *,
prompt_expr: Union[str, Sequence[str], Callable] = None,
interactive: bool = True) -> Any: interactive: bool = True) -> Any:
""" """
Get an argument with a given key. Get an argument with a given key.
@ -174,6 +178,7 @@ class Session:
:param key: argument key :param key: argument key
:param prompt: prompt to ask the user :param prompt: prompt to ask the user
:param prompt_expr: prompt expression to ask the user
:param interactive: should enter interactive mode while key missing :param interactive: should enter interactive mode while key missing
:return: the argument value :return: the argument value
:raise FurtherInteractionNeeded: further interaction is needed :raise FurtherInteractionNeeded: further interaction is needed
@ -184,6 +189,8 @@ class Session:
self.current_key = key self.current_key = key
# ask the user for more information # ask the user for more information
if prompt_expr is not None:
prompt = render(prompt_expr, key=key)
asyncio.ensure_future(self.send(prompt)) asyncio.ensure_future(self.send(prompt))
raise FurtherInteractionNeeded raise FurtherInteractionNeeded
@ -196,6 +203,11 @@ class Session:
if not ignore_failure: if not ignore_failure:
raise raise
async def send_expr(self,
expr: Union[str, Sequence[str], Callable],
**kwargs):
return await self.send(render(expr, **kwargs))
def _new_command_session(bot: CQHttp, def _new_command_session(bot: CQHttp,
ctx: Dict[str, Any]) -> Optional[Session]: ctx: Dict[str, Any]) -> Optional[Session]:

18
none/expression.py Normal file
View File

@ -0,0 +1,18 @@
import random
from typing import Union, Sequence, Callable
from aiocqhttp import message
from aiocqhttp.message import Message
def render(expr: Union[str, Sequence[str], Callable], *, escape_args=True,
**kwargs) -> Message:
if isinstance(expr, Callable):
expr = expr()
elif isinstance(expr, Sequence):
expr = random.choice(expr)
if escape_args:
for k, v in kwargs.items():
if isinstance(v, str):
kwargs[k] = message.escape(v)
return expr.format(**kwargs)

View File

@ -0,0 +1,12 @@
WHICH_CITY = (
'你想知道哪个城市的天气呢?',
'你要查询的城市是哪个呢?',
'你要查询哪个城市呢?',
'哪个城市呢?',
'请告诉我你要查询的城市~',
)
REPORT = (
'你查询了{city}的天气',
'{city}的天气是……',
)

21
none/plugins/weather.py Normal file
View File

@ -0,0 +1,21 @@
import none
from none.command import Session
from none.expressions import weather as expr
@none.on_command(('weather', 'weather'), aliases=('天气', '天气预报'))
async def weather(session: Session):
city = session.require_arg('city', prompt_expr=expr.WHICH_CITY)
await session.send_expr(expr.REPORT, city=city)
@weather.args_parser
async def _(session: Session):
if session.current_key:
session.args[session.current_key] = session.current_arg.strip()
@none.on_command(('weather', 'suggestion'),
aliases=('生活指数', '生活建议', '生活提示'))
async def suggestion(session: Session):
await session.send('suggestion')

View File

@ -1,20 +0,0 @@
import none
from none.command import Session
@none.on_command(('weather', 'weather'), aliases=('天气',))
async def weather(session: Session):
city = session.require_arg('city', prompt='你想知道哪个城市的天气呢?')
other = session.require_arg('other', prompt='其他信息?')
await session.send(f'你查询了{city}的天气,{other}')
@weather.args_parser
async def _(session: Session):
if session.current_key:
session.args[session.current_key] = session.current_arg.strip()
@none.on_command(('weather', 'suggestion'), aliases=('生活指数', '生活提示'))
async def suggestion(session: Session):
await session.send('suggestion')