Skip to content

Commit

Permalink
improve: finish logger(no output:( ), and fix some bugs
Browse files Browse the repository at this point in the history
  • Loading branch information
Chenwe_i_lin committed Feb 29, 2020
1 parent 9791363 commit 0fa4e06
Show file tree
Hide file tree
Showing 7 changed files with 41 additions and 16 deletions.
6 changes: 3 additions & 3 deletions mirai/logger.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
from logbook import Logger, StreamHandler
import sys

StreamHandler(sys.stdout).push_application()
StreamHandler(sys.stdout, level=20).push_application()

Event = Logger('Event')
Network = Logger("Network", level="DEBUG")
Event = Logger('Event', level=20)
Network = Logger("Network", level=10)
4 changes: 2 additions & 2 deletions mirai/message/components.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,13 +45,13 @@ class At(GenericModel, BaseMessageComponent):
target: int

def toString(self):
return f"[At::target={self.target},group={message.get().message.sender.group.id},sender={message.get().message.sender.id}]"
return f"[At::target={self.target}]"

class AtAll(BaseMessageComponent):
type: MessageComponentTypes = "AtAll"

def toString(self):
return f"[AtAll::group={message.get().message.sender.group.id},sender={message.get().message.sender.id}]"
return f"[AtAll]"

class Face(BaseMessageComponent):
type: MessageComponentTypes = "Face"
Expand Down
6 changes: 5 additions & 1 deletion mirai/network.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
import mimetypes
import typing as T
from pathlib import Path
import eliot
from .logger import Network

import aiohttp

Expand All @@ -16,15 +16,18 @@ async def http_post(url, data_map):
async with aiohttp.ClientSession() as session:
async with session.post(url, json=data_map) as response:
if response.status != 200:
Network.error(f"requested {url=}, by {data_map=}, and {response.status=}")
raise NetworkError(f"method=POST, url={url}, data={data_map}, status={response.status}")
data = await response.text(encoding="utf-8")
Network.debug(f"requested {url=}, by {data_map=}, and {response.status=}, {data=}")
return json.loads(data)

@staticmethod
async def http_get(url, params=None):
async with aiohttp.ClientSession() as session:
async with session.get(url, params=params) as response:
data = await response.text(encoding="utf-8")
Network.debug(f"requested {url=}, by {params=}, and {response.status=}, {data=}")
return json.loads(data)

@staticmethod
Expand All @@ -37,4 +40,5 @@ async def upload(url, file: Path, addon_dict: dict):
upload_data.add_fields(item)
async with aiohttp.ClientSession() as session:
async with session.post(url, data=upload_data) as response:
Network.debug(f"requested {url=}, by {file.name=}, and {response.status=}, {addon_dict=}")
return await response.text("utf-8")
2 changes: 1 addition & 1 deletion mirai/protocol.py
Original file line number Diff line number Diff line change
Expand Up @@ -306,7 +306,7 @@ def handleMessageAsFriend(
# 对Image特殊处理
if type(i) != components.Image else \
{"type": "Image", "imageId": i.asFriendImage()} \
for i in message
for i in message if i
] \
if isinstance(message, (tuple, list)) else \
[json.loads(components.Plain(text=message).json())] \
Expand Down
24 changes: 17 additions & 7 deletions mirai/session.py
Original file line number Diff line number Diff line change
Expand Up @@ -247,6 +247,15 @@ async def throw_exception_event(self, event_context, queue, exception):
else:
EventLogger.critical(f"threw a exception by {event_context.name}, Exception: {exception}, it's a exception handler.")

def argument_compiler(self, annotations, event_context):
annotations_mapping = self.get_annotations_mapping()
translated_mapping = {
k: annotations_mapping[v](event_context)\
for k, v in annotations.items()\
if k != "return" # 以免撞到 return type
}
return translated_mapping

async def event_runner(self, exit_signal_status, queue: asyncio.Queue):
while not exit_signal_status():
event_context: InternalEvent
Expand All @@ -269,19 +278,20 @@ async def event_runner(self, exit_signal_status, queue: asyncio.Queue):
self.throw_exception_event(event_context, queue, e)
continue
if condition_result:
annotations_mapping = self.get_annotations_mapping()
translated_mapping = {
k: annotations_mapping[v](event_context)\
for k, v in run_body.__annotations__.items()\
if k != "return" # 以免撞到 return type
}
EventLogger.info(f"handling a event: {event_context}")
self.setting_context(event_context)
translated_mapping = self.argument_compiler(
run_body.__annotations__,
event_context
)

try:
await run_body(**translated_mapping)
asyncio.create_task(run_body(**translated_mapping))
except (NameError, TypeError) as e:
EventLogger.error(f"threw a exception by {event_context.name}, it's about Annotations Checker, please report to developer.")
traceback.print_exc()
except Exception as e:
EventLogger.error(f"threw a exception by {event_context.name}, and it's {e}")
await self.throw_exception_event(event_context, queue, e)

async def close_session(self, ignoreError=False):
Expand Down
Binary file added photo_2020-02-28_16-55-34.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
15 changes: 13 additions & 2 deletions test.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,22 @@ async def main():
@session.receiver("GroupMessage")
async def event_gm(session: Session, message: MessageChain, group: Group):
if message.toString().startswith("/image"):
print("meow!")
await session.sendGroupMessage(group, [
printer(await Image.fromFileSystem("./photo_2020-02-28_16-55-34.jpg" , "group"))
#await Image.fromFileSystem("./photo_2020-02-28_16-55-34.jpg" , "group"),
Plain(text="??")
])

@session.receiver("FriendMessage")
async def event_gm(session: Session, message: MessageChain, friend: Friend):
if message.toString().startswith("/image"):
print("meow!")

await asyncio.sleep(10)
await session.sendFriendMessage(friend, [
#await Image.fromFileSystem("./photo_2020-02-28_16-55-34.jpg" , "friend"),
Plain(text="??")
])

print(session.enabled)
await session.joinMainThread()

Expand Down

0 comments on commit 0fa4e06

Please sign in to comment.