Skip to content

Commit

Permalink
add: middleware(no global), fixed image, and improve Image.fromFileSy…
Browse files Browse the repository at this point in the history
…stem
  • Loading branch information
Chenwe_i_lin committed Mar 2, 2020
1 parent e92a4cc commit 069ad7b
Show file tree
Hide file tree
Showing 10 changed files with 156 additions and 48 deletions.
9 changes: 9 additions & 0 deletions examples/depend_start.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
from mirai import Session, Depend, Plain
import asyncio

authKey = "213we355gdfbaerg"
qq = 208924405

async def main():
async with Session(f"mirai://localhost:8070/?authKey={authKey}&qq={qq}") as session:
pass
22 changes: 14 additions & 8 deletions mirai/command.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
from .session import Session
from . import (
MessageChain,
Plain
Plain,
GroupMessage, FriendMessage
)

class Command:
Expand All @@ -16,15 +17,20 @@ class CommandManager:

def __init__(self,
session: Session,
listenEvents=("GroupMessage", "FriendMessage")):
listenEvents=(GroupMessage, FriendMessage)
):
self.session = Session

for event in listenEvents:
session.receiver(event)(self.event_listener)

def newCommand(self, prefix="/", addon_parser={}):
pass

def event_listener(self, context):
"""用于监听事件, 并做出分析, 解析到相应的 Command 上.
"""
context.message.messageChain: MessageChain
context.message.messageChain.getFirstComponent(Plain)
def event_listener(self,
session: Session,
message: MessageChain,
sender: "Sender",
type: "Type"
):
"""用于监听事件, 并做出分析, 解析到相应的 Command 上."""
message.toString()
3 changes: 3 additions & 0 deletions mirai/event/message/chain.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,9 @@ def hasComponent(self, component_class) -> bool:
else:
return False

def __len__(self) -> int:
return len(self.__root__)

def getFirstComponent(self, component_class) -> T.Optional[BaseMessageComponent]:
for i in self:
if type(i) == component_class:
Expand Down
14 changes: 6 additions & 8 deletions mirai/event/message/components.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
from io import BytesIO
from PIL import Image as PILImage
from pathlib import Path
from mirai.image import InternalImage
import re

__all__ = [
Expand Down Expand Up @@ -42,6 +43,7 @@ def toString(self):
class At(GenericModel, BaseMessageComponent):
type: MessageComponentTypes = "At"
target: int
display: str

def toString(self):
return f"[At::target={self.target}]"
Expand All @@ -62,7 +64,7 @@ def toString(self):
class Image(BaseMessageComponent):
type: MessageComponentTypes = "Image"
imageId: UUID
url: HttpUrl
url: T.Optional[HttpUrl] = None

@validator("imageId", always=True, pre=True)
@classmethod
Expand Down Expand Up @@ -91,13 +93,9 @@ async def getPillowImage(self) -> PILImage.Image:
async with session.get(self.url) as response:
return PILImage.open(BytesIO(await response.read()))

@classmethod
async def fromFileSystem(cls,
path: T.Union[Path, str],
session,
imageType: ImageType
) -> "Image":
return await session.uploadImage(imageType, path)
@staticmethod
def fromFileSystem(path: T.Union[Path, str]) -> InternalImage:
return InternalImage(path)

class Unknown(BaseMessageComponent):
type: MessageComponentTypes = "Unknown"
Expand Down
11 changes: 11 additions & 0 deletions mirai/image.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
from pathlib import Path

class InternalImage:
path: Path

def __init__(self, path):
if isinstance(path, str):
self.path = Path(path)
elif isinstance(path, Path):
self.path = path

5 changes: 4 additions & 1 deletion mirai/logger.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,11 @@
)
import sys

StreamHandler(sys.stdout, level=INFO).push_application()
stream_handler = StreamHandler(sys.stdout, level=INFO)
stream_handler.format_string = '[{record.time:%Y-%m-%d %H:%M:%S}][Mirai] {record.level_name}: {record.channel}: {record.message}'
stream_handler.push_application()

Event = Logger('Event', level=INFO)
Network = Logger("Network", level=DEBUG)
Session = Logger("Session", level=INFO)
Protocol = Logger("Protocol", level=INFO)
19 changes: 17 additions & 2 deletions mirai/misc.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
from threading import Thread, Lock
import typing as T
import random
from .logger import Protocol

def assertOperatorSuccess(result, raise_exception=False, return_as_is=False):
if "code" in result:
Expand Down Expand Up @@ -50,7 +51,10 @@ def getMatchedString(regex_result):
return regex_result.string[slice(*regex_result.span())]

def findKey(mapping, value):
index = list(mapping.values()).index(value)
try:
index = list(mapping.values()).index(value)
except ValueError:
return "Unknown"
return list(mapping.keys())[index]

def raiser(error):
Expand All @@ -69,4 +73,15 @@ def randomNumberString():

def randomRangedNumberString(length_range=(9,)):
length = random.choice(length_range)
return random.choice(range(10**(length - 1), int("9"*(length))))
return random.choice(range(10**(length - 1), int("9"*(length))))

def protocol_log(func):
async def warpper(*args, **kwargs):
try:
result = await func(*args, **kwargs)
Protocol.info(f"protocol method {func.__name__} was called")
return result
except Exception as e:
Protocol.error(f"protocol method {func.__name__} raised a error: {e.__class__.__name__}")
raise e
return warpper
Loading

0 comments on commit 069ad7b

Please sign in to comment.