Skip to content

Commit

Permalink
add: eliot and avatar getter
Browse files Browse the repository at this point in the history
  • Loading branch information
Chenwe_i_lin committed Feb 28, 2020
1 parent ae52997 commit 05024dc
Show file tree
Hide file tree
Showing 7 changed files with 125 additions and 24 deletions.
1 change: 1 addition & 0 deletions Pipfile
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ aiohttp = "*"
pydantic = "*"
pillow = "*"
parse = "*"
eliot = "*"

[requires]
python_version = "3.8"
74 changes: 73 additions & 1 deletion Pipfile.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

10 changes: 10 additions & 0 deletions mirai/friend.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
from uuid import UUID
from pydantic import BaseModel
from typing import Optional
from mirai.network import session
from PIL import Image
from io import BytesIO

class Friend(BaseModel):
id: int
Expand All @@ -9,3 +12,10 @@ class Friend(BaseModel):

def __repr__(self):
return f"<Friend id={self.id} nickname='{self.nickname}' remark='{self.remark}'>"

def getAvatarUrl(self) -> str:
return f'http://q4.qlogo.cn/g?b=qq&nk={self.id}&s=140'

async def getAvatarAsPillowImage(self) -> Image.Image:
async with session.get(self.getAvatarUrl()) as response:
return Image.open(BytesIO(await response.read()))
17 changes: 17 additions & 0 deletions mirai/group.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
from enum import Enum
from dataclasses import dataclass
from pydantic import BaseModel
from PIL import Image
from mirai.network import session
from io import BytesIO

class Permission(Enum):
Member = "MEMBER"
Expand All @@ -15,6 +18,13 @@ class Group(BaseModel):
def __repr__(self):
return f"<Group id={self.id} name='{self.name}' permission={self.permission.name}>"

def getAvatarUrl(self) -> str:
return f'https://p.qlogo.cn/gh/{self.id}/{self.id}_1/140'

async def getAvatarAsPillowImage(self) -> Image.Image:
async with session.get(self.getAvatarUrl()) as response:
return Image.open(BytesIO(await response.read()))

class Member(BaseModel):
id: int
memberName: str
Expand All @@ -24,6 +34,13 @@ class Member(BaseModel):
def __repr__(self):
return f"<GroupMember id={self.id} group={self.group} permission={self.permission} group={self.group.id}>"

def getAvatarUrl(self) -> str:
return f'http://q4.qlogo.cn/g?b=qq&nk={self.id}&s=140'

async def getAvatarAsPillowImage(self) -> Image.Image:
async with session.get(self.getAvatarUrl()) as response:
return Image.open(BytesIO(await response.read()))

class MemberChangeableSetting(BaseModel):
name: str
specialTitle: str
Expand Down
6 changes: 5 additions & 1 deletion mirai/message/components.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
from PIL import Image as PILImage
from pathlib import Path
import re
from mirai.context import Direct

__all__ = [
"Plain",
Expand Down Expand Up @@ -97,9 +98,12 @@ async def getPillowImage(self) -> PILImage.Image:
@classmethod
async def fromFileSystem(cls,
path: T.Union[Path, str],
miraiSession: "MiraiProtocol",
imageType: ImageType
) -> "Image":
if Direct.WorkingType == "Message":
miraiSession = Direct.Message.session
else:
miraiSession = Direct.Event.session
return await miraiSession.uploadImage(imageType, path)

class Unknown(BaseMessageComponent):
Expand Down
21 changes: 10 additions & 11 deletions mirai/session.py
Original file line number Diff line number Diff line change
Expand Up @@ -102,9 +102,9 @@ async def enable_session(self) -> "Session":
raise ValueError('invaild args: unknown response')

if self.cache_options['groups']:
self.cached_groups = {group.id: group for group in await super().groupList()}
await self.cacheBotGroups()
if self.cache_options['friends']:
self.cached_friends = {friend.id: friend for friend in await super().friendList()}
await self.cacheBotFriends()

self.enabled = True
return self
Expand Down Expand Up @@ -135,23 +135,22 @@ def start_event_runtime(self):
self.async_runtime.start()

async def __aenter__(self) -> "Session":
await self.enable_session()
self.setting_event_runtime()
self.start_event_runtime()
return await self.enable_session()
return self

async def __aexit__(self, exc_type, exc, tb):
await self.close_session(ignoreError=True)
await session.close()

def get_tasks(self) -> T.Awaitable:
async def get_tasks(self):
"用于为外部的事件循环注入 event_runner 和 message_polling"
async def connect():
with self.shared_lock:
await asyncio.wait([
self.event_runner(lambda: self.exit_signal, self.event_stacks),
self.message_polling(lambda: self.exit_signal, self.event_stacks)
])
return connect()
with self.shared_lock:
await asyncio.wait([
self.event_runner(lambda: self.exit_signal, self.event_stacks),
self.message_polling(lambda: self.exit_signal, self.event_stacks)
])

async def message_polling(self, exit_signal_status, queue, count=10):
while not exit_signal_status():
Expand Down
20 changes: 9 additions & 11 deletions test.py
Original file line number Diff line number Diff line change
@@ -1,22 +1,20 @@
import asyncio
from mirai import Session, Plain, Friend, BotMuteEvent, BotUnmuteEvent, Group, Member
from mirai import Session, Plain, Friend, BotMuteEvent, BotUnmuteEvent, Group, Member, MessageChain, Image
from devtools import debug
from mirai.misc import printer

authKey = "213we355gdfbaerg"
qq = 208924405

async def main():
async with Session(f"mirai://localhost:8070/?authKey={authKey}&qq={qq}") as session:
@session.receiver("FriendMessage")
async def event_friendmessage(session: Session, sender: Friend):
await session.sendFriendMessage(
sender.id,
[Plain(text="Hello, world!")]
)

@session.receiver("BotMuteEvent")
async def event_BotMuteEvent(event: BotMuteEvent):
debug(event)
@session.receiver("GroupMessage")
async def event_gm(session: Session, message: MessageChain, group: Group):
if printer(message.toString().startswith("/image")):
await session.sendGroupMessage(group, [
printer(await Image.fromFileSystem("./photo_2020-02-28_16-55-34.jpg" , "group"))
])
print("meow!")

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

0 comments on commit 05024dc

Please sign in to comment.