Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Dev #87

Merged
merged 5 commits into from
Jan 23, 2024
Merged

Dev #87

Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion amiyabot/adapters/tencent/qqGroup/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,8 @@ async def start(self, private: bool, handler: HANDLER_TYPE):
if hasattr(self.__default_chain_builder, 'start'):
self.__default_chain_builder.start()

asyncio.create_task(self.__seq_service.run())
if not self.__seq_service.alive:
asyncio.create_task(self.__seq_service.run())

await super().start(private, handler)

Expand Down
45 changes: 36 additions & 9 deletions amiyabot/adapters/tencent/qqGroup/builder.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@

from graiax import silkcoder
from dataclasses import asdict, field
from amiyabot.util import create_dir, get_public_ip, random_code, Singleton
from amiyabot.util import create_dir, get_public_ip, random_code
from amiyabot.adapters import MessageCallback
from amiyabot.network.httpServer import HttpServer
from amiyabot.builtin.messageChain import Chain
Expand All @@ -15,7 +15,7 @@
class SeqService:
def __init__(self):
self.seq_rec = {}
self.alive = True
self.alive = False

def msg_req(self, msg_id: str):
if msg_id not in self.seq_rec:
Expand All @@ -26,14 +26,29 @@ def msg_req(self, msg_id: str):
return self.seq_rec[msg_id]['seq']

async def run(self):
while self.alive:
await asyncio.sleep(1)
self.seq_rec = {m_id: item for m_id, item in self.seq_rec.items() if time.time() - item['last'] < 30}
if not self.alive:
self.alive = True

while self.alive:
await asyncio.sleep(1)
self.seq_rec = {m_id: item for m_id, item in self.seq_rec.items() if time.time() - item['last'] < 300}

async def stop(self):
self.alive = False


class PortSingleton(type):
ports = {}

def __call__(cls, *args, **kwargs):
options: QQGroupChainBuilderOptions = args[0]

if options.port not in cls.ports:
cls.ports[options.port] = super(PortSingleton, cls).__call__(*args, **kwargs)

return cls.ports[options.port]


@dataclass
class GroupPayload:
content: str = ''
Expand All @@ -57,7 +72,7 @@ class QQGroupChainBuilderOptions:
http_server_options: dict = field(default_factory=dict)


class QQGroupChainBuilder(ChainBuilder, metaclass=Singleton):
class QQGroupChainBuilder(ChainBuilder, metaclass=PortSingleton):
def __init__(self, options: QQGroupChainBuilderOptions):
create_dir(options.resource_path)

Expand All @@ -70,12 +85,16 @@ def __init__(self, options: QQGroupChainBuilderOptions):

self.file_caches = {}

self.running = False

@property
def domain(self):
return f'{self.http}://{self.ip}:{self.options.port}/resource'

def start(self):
asyncio.create_task(self.server.serve())
if not self.running:
asyncio.create_task(self.server.serve())
self.running = True

def temp_filename(self, suffix: str):
filename = f'{int(time.time())}{random_code(10)}.{suffix}'
Expand Down Expand Up @@ -133,6 +152,12 @@ async def build_message_send(api: QQGroupAPI, chain: Chain, seq_service: SeqServ
payload_list: List[GroupPayload] = []
payload = GroupPayload(msg_id=msg_id, msg_seq=seq_service.msg_req(msg_id))

def refresh_payload():
nonlocal payload

payload_list.append(payload)
payload = GroupPayload(msg_id=msg_id, msg_seq=seq_service.msg_req(msg_id))

async def insert_media(url: str, file_type: int = 1):
nonlocal payload

Expand All @@ -144,13 +169,15 @@ async def insert_media(url: str, file_type: int = 1):
res = await api.upload_file(chain.data.channel_openid, file_type, url)
if res:
if 'file_info' in res.json:
if file_type != 1:
refresh_payload()

file_info = res.json['file_info']

payload.msg_type = 7
payload.media = {'file_info': file_info}

payload_list.append(payload)
payload = GroupPayload(msg_id=msg_id, msg_seq=seq_service.msg_req(msg_id))
refresh_payload()
else:
log.warning('file upload fail.')

Expand Down
10 changes: 4 additions & 6 deletions amiyabot/adapters/tencent/qqGuild/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ def __init__(self, appid: str, token: str):

self.appid = appid
self.token = token
self.bot_name = ''

self.shards_record: Dict[int, ShardsRecord] = {}

Expand Down Expand Up @@ -54,7 +55,7 @@ async def start(self, private: bool, handler: HANDLER_TYPE):

resp = await self.api.gateway_bot()

if not resp:
if not resp or 'url' not in resp.json:
if self.keep_run:
await asyncio.sleep(10)
asyncio.create_task(self.start(private, handler))
Expand Down Expand Up @@ -88,12 +89,9 @@ async def create_connection(self, handler: ConnectionHandler, shards_index: int

if payload.op == 0:
if payload.t == 'READY':
self.bot_name = payload.d['user']['username']
log.info(
f'connected({sign}): %s(%s)'
% (
payload.d['user']['username'],
'private' if handler.private else 'public',
)
f'connected({sign}): {self.bot_name}(%s)' % ('private' if handler.private else 'public')
)
self.shards_record[shards_index].session_id = payload.d['session_id']

Expand Down
6 changes: 5 additions & 1 deletion amiyabot/network/httpRequests.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,11 @@ async def request(

if res.status not in cls.success + cls.async_success:
if not ignore_error:
log.warning(f'Request failed <{url}>[{request_name}]. Got code {res.status} {res.reason}')
log.warning(
f'Request failed <{url}>[{request_name}]. '
f'Got code {res.status} {res.reason}. '
f'Response: {response.text}'
)

return response

Expand Down