Skip to content

Commit

Permalink
Merge branch 'dev'
Browse files Browse the repository at this point in the history
  • Loading branch information
Wybxc committed Jun 18, 2022
2 parents 1f11bfd + d6f01fc commit 865cb28
Show file tree
Hide file tree
Showing 12 changed files with 694 additions and 645 deletions.
2 changes: 1 addition & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -130,7 +130,7 @@ dmypy.json


# test cases
/*.py
/test*.py

# pdoc documents
/docs
Expand Down
130 changes: 130 additions & 0 deletions gen_pyi.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,130 @@
# -*- coding: utf-8 -*-
# type: ignore

import mirai
import pdoc
import textwrap
import re


def indent(text, n):
return textwrap.indent(text, ' ' * n * 4)


module = pdoc.Module(mirai.models.api)
s = ""
for api in sorted(
set(mirai.models.api.ApiModel.__indexes__.values()),
key=lambda x: x.__name__
):
c = module.find_class(api)
print('正在处理:', api.__name__)
anno = api.__annotations__
params = ', '.join(
'{}: {}'.format(
k, c.doc[k].type_annotation().replace("\xa0", "") + (
"" if api.__fields__[k].
required else f" = {api.__fields__[k].default!r}"
)
) for k, v in anno.items() if k[0] != '_' and k != 'Info'
)

params_doc = '\n'.join(
'{} (`{}`): {}'.format(
k, c.doc[k].type_annotation().replace("\xa0", ""),
c.doc[k].docstring.rstrip('。') + (
"。" if api.__fields__[k].
required else f",默认值 {api.__fields__[k].default!r}。"
)
) for k, v in anno.items() if k[0] != '_' and k != 'Info'
)

s += f'''
# {api.__name__}
'''

try:
response_type = api.Info.response_type
response_type_name = response_type.__qualname__
except AttributeError:
response_type_name = 'None'

try:
response_post_type = api.Info.response_type_post
response_post_type_name = response_post_type.__name__
except AttributeError:
response_post_type_name = 'None'

if issubclass(api, mirai.models.api.ApiGet):
s += f'''
@type_check_only
class __{api.__name__}Proxy():
async def get(self, {params}) -> {response_type_name}:
"""{c.docstring}
Args:
{indent(params_doc, 4)}
"""
async def __call__(self, {params}) -> {response_type_name}:
"""{c.docstring}
Args:
{indent(params_doc, 4)}
"""
'''
elif issubclass(api, mirai.models.api.ApiPost):
s += f'''
@type_check_only
class __{api.__name__}Proxy():
async def set(self, {params}) -> {response_type_name}:
"""{c.docstring}
Args:
{indent(params_doc, 4)}
"""
async def __call__(self, {params}) -> {response_type_name}:
"""{c.docstring}
Args:
{indent(params_doc, 4)}
"""
'''
elif issubclass(api, mirai.models.api.ApiRest):
s += f'''
@type_check_only
class __{api.__name__}Proxy():
async def get(self, {params}) -> {response_type_name}:
"""{c.docstring}
Args:
{indent(params_doc, 4)}
"""
async def set(self, {params}) -> {response_post_type_name}:
"""{c.docstring}
Args:
{indent(params_doc, 4)}
"""
async def __call__(self, {params}) -> {response_type_name}:
"""{c.docstring}
Args:
{indent(params_doc, 4)}
"""
'''

s += f'''
@property
def {api.Info.alias}(self) -> __{api.__name__}Proxy:
"""{c.docstring}
Args:
{indent(params_doc, 3)}
"""
'''

s = re.sub(r'Args:(\n\s*)*\s*"""', '"""', s)
s = re.sub(r'"""(.+)(\n\s*)+\s*"""', r'"""\1"""', s)
s = s.replace('NoneType', 'None').replace(', )', ')')
s = s.replace('pathlib.Path', 'Path')
s = re.sub(r'mirai\.(\w+\.)*(\w)', lambda m: m.group(2), s)

with open('./mirai/bot.pyi', 'r', encoding='utf-8') as f:
pyi = f.read()
p = '### 以下为自动生成 ###'
s = pyi[:pyi.find(p) + len(p)] + s

with open('./mirai/bot.pyi', 'w', encoding='utf-8') as f:
f.write(s)
12 changes: 12 additions & 0 deletions mirai/bot.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import asyncio
import contextlib
import logging
import warnings
from typing import (
Any, Awaitable, Callable, Dict, Iterable, List, Optional, Type, Union, cast
)
Expand Down Expand Up @@ -88,6 +89,7 @@ async def call_api(self, api: str, *args, **kwargs):
*args: 参数。
**kwargs: 参数。
"""
warnings.warn("SimpleMirai 已弃用,将在 0.3 后移除。", DeprecationWarning)
return await self._adapter.call_api(api, *args, **kwargs)

def on(self, event: str, priority: int = 0) -> Callable:
Expand Down Expand Up @@ -307,6 +309,16 @@ def __init__(self, qq: int, adapter: Adapter):
def bus(self) -> ModelEventBus:
return self._bus

async def call_api(self, api: str, *args, **kwargs):
"""调用 API。
Args:
api: API 名称。
*args: 参数。
**kwargs: 参数。
"""
return await self._adapter.call_api(api, *args, **kwargs)

def on(
self,
event_type: Union[Type[Event], str],
Expand Down
Loading

0 comments on commit 865cb28

Please sign in to comment.