Skip to content

Commit

Permalink
feat: reconnect qqbot
Browse files Browse the repository at this point in the history
  • Loading branch information
Bluefissure committed Nov 20, 2023
1 parent 10248fd commit 7de9710
Showing 1 changed file with 22 additions and 3 deletions.
25 changes: 22 additions & 3 deletions qqbot/QQBot.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,8 @@ def _refresh_token(self):
if time.time() >= self.expiration:
self._log.info('Refreshing token...')
self._get_token()
else:
self._log.debug('Token still valid, expires in %s seconds', int(self.expiration - time.time()))

def _get_token(self):
token_url = "https://bots.qq.com/app/getAppAccessToken"
Expand All @@ -45,7 +47,7 @@ def _get_token(self):
self._log.info(response.json())
self.token = response.json()['access_token']
self.expiration = time.time() + int(response.json()['expires_in'])
self._log.info('Token refreshed, expires in %s',
self._log.info('Token refreshed, expires in %s seconds',
response.json()['expires_in'])

@property
Expand Down Expand Up @@ -120,6 +122,7 @@ def _logged_in(self, ready_data: dict):
self._spawn_heartbeat()

async def try_login(self):
self._log.info('Try logging in...')
await self.ws.send(json.dumps({
"op": 2,
"d": {
Expand All @@ -128,6 +131,16 @@ async def try_login(self):
"shard": [0, 1],
}}))

async def reconnect(self):
self._log.info('Try reconnecting...')
await self.ws.send(json.dumps({
"op": 6,
"d": {
"token": f"QQBot {self.token}",
"session_id": self.session_id,
"seq": self.s,
}}))

def send_group_message(self, group_id: str, content: str, reply_msg_id: str = "", image: str = None):
self._log.debug('Sending message %s to group %s...', content, group_id)
post_data = {
Expand Down Expand Up @@ -176,18 +189,24 @@ def reply_channel_message(self, message:dict, content: str, image: str = None):

async def handle(self, message: dict):
op = message['op']
s = message.get('s', -1)
if s > -1:
self.s = s
if op == 10:
self._log.debug('QQ says hello.')
if not self.logged_in:
self._log.info('Try logging in...')
await self.try_login()
elif op == 7:
self._log.debug('QQ requires reconnect.')
await self.reconnect()
elif op == 0:
t = message['t']
self.s = message['s']
if t == 'READY':
if not self.logged_in:
self._logged_in(message['d'])
self._log.info('%s logged in.', self)
elif t == "RESUMED":
self._log.info('%s resumed.', self)
elif t in self._subscriptions:
for func in self._subscriptions[t]:
func(message)
Expand Down

0 comments on commit 7de9710

Please sign in to comment.