Skip to content

Commit 96e7f6a

Browse files
1. Fix Python distribution 2. change handle_message to handle_user_message for avoid methdo name conflict
1 parent 90f112c commit 96e7f6a

File tree

2 files changed

+61
-47
lines changed

2 files changed

+61
-47
lines changed

.github/workflows/build.yml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,7 @@ jobs:
5454
files: |
5555
./dist/chatgpt_mixin-${{ env.VERSION }}-py3-none-any.whl
5656
- name: Publish a Python distribution to PyPI
57-
if: ${{ startsWith(github.ref, 'refs/tags/') && matrix.os == 'ubuntu-18.04' }}
57+
if: ${{ startsWith(github.ref, 'refs/tags/') && matrix.os == 'ubuntu-20.04' }}
5858
uses: pypa/gh-action-pypi-publish@release/v1
5959
with:
6060
user: __token__

src/mixinbot.py

Lines changed: 60 additions & 46 deletions
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,24 @@
11
# -*- coding: utf-8 -*-
22

3-
import asyncio
4-
import base64
53
import os
6-
import platform
7-
import signal
84
import sys
95
import time
6+
import asyncio
7+
import signal
8+
import base64
9+
import yaml
1010
import traceback
11-
from dataclasses import dataclass
11+
import websockets
12+
import platform
13+
import httpx
1214
from datetime import datetime
13-
from typing import Any, Dict, List, Optional, Set, Union
15+
from typing import Optional, List, Dict, Any, Union, Set
1416

15-
import httpx
16-
import websockets
17-
import yaml
18-
from pymixin import log, utils
19-
from pymixin.mixin_ws_api import MessageView, MixinWSApi
17+
from pymixin.mixin_ws_api import MixinWSApi, MessageView
18+
from pymixin import utils
19+
from pymixin import log
20+
21+
from dataclasses import dataclass
2022

2123
logger = log.get_logger(__name__)
2224
logger.addHandler(log.handler)
@@ -142,13 +144,21 @@ def __init__(self, config_file):
142144
# openai_api_key
143145
self.bots = []
144146
self.standby_bots = []
147+
self._paused = False
148+
149+
@property
150+
def paused(self):
151+
return self._paused
152+
153+
@paused.setter
154+
def paused(self, value):
155+
self._paused = value
145156

146157
async def init(self):
147158
asyncio.create_task(self.handle_questions())
148159

149160
if self.chatgpt_accounts:
150161
from playwright.async_api import async_playwright
151-
152162
from .chatgpt_browser import ChatGPTBot
153163
PLAY = await async_playwright().start()
154164
for account in self.chatgpt_accounts:
@@ -173,9 +183,14 @@ async def init(self):
173183

174184
async def handle_signal(self, signum):
175185
logger.info("+++++++handle signal: %s", signum)
186+
for bot in self.bots:
187+
logger.info("++close bot: %s", bot)
188+
await bot.close()
176189
loop = asyncio.get_running_loop()
177-
for task in asyncio.all_tasks(loop):
178-
task.cancel()
190+
loop.remove_signal_handler(signal.SIGINT)
191+
loop.remove_signal_handler(signal.SIGTERM)
192+
sys.exit(0)
193+
# os.kill(os.getpid(), signal.SIGINT)
179194

180195
def choose_bot(self, user_id):
181196
bots = []
@@ -247,32 +262,26 @@ async def send_message_to_chat_gpt2(self, conversation_id, user_id, message):
247262

248263
async def handle_questions(self):
249264
while True:
250-
try:
251-
await asyncio.sleep(15.0)
252-
handled_question = []
253-
saved_questions = self.saved_questions.copy()
254-
for user_id, question in saved_questions.items():
255-
try:
256-
logger.info("++++++++handle question: %s", question.data)
257-
if await self.send_message_to_chat_gpt2(question.conversation_id, question.user_id, question.data):
258-
handled_question.append(user_id)
259-
except Exception as e:
260-
logger.info("%s", str(e))
261-
continue
262-
for question in handled_question:
263-
del self.saved_questions[question]
264-
except asyncio.exceptions.CancelledError:
265-
logger.info("++++handle_questions received CancelledError exception, exit..")
266-
return
265+
await asyncio.sleep(15.0)
266+
handled_question = []
267+
saved_questions = self.saved_questions.copy()
268+
for user_id, question in saved_questions.items():
269+
try:
270+
logger.info("++++++++handle question: %s", question.data)
271+
if await self.send_message_to_chat_gpt2(question.conversation_id, question.user_id, question.data):
272+
handled_question.append(user_id)
273+
except Exception as e:
274+
logger.info("%s", str(e))
275+
continue
276+
for question in handled_question:
277+
del self.saved_questions[question]
267278

268279
def save_question(self, conversation_id, user_id, data):
269280
self.saved_questions[user_id] = SavedQuestion(conversation_id, user_id, data)
270281

271-
async def handle_message(self, conversation_id, user_id, message):
282+
async def handle_user_message(self, conversation_id, user_id, message):
272283
try:
273284
await self.send_message_to_chat_gpt(conversation_id, user_id, message)
274-
except asyncio.exceptions.CancelledError:
275-
logger.info("++++handle_group_message received CancelledError, exit...")
276285
except Exception as e:
277286
logger.exception(e)
278287
if self.developer_user_id:
@@ -305,10 +314,7 @@ async def get_web_result(self, message: str):
305314
querys.append(f"\nInstructions: Using the provided web search results, write a comprehensive reply to the given prompt. Make sure to cite results using [[number](URL)] notation after the reference. If the provided search results refer to multiple subjects with the same name, write separate answers for each subject.\nPrompt: {prompt}")
306315
return "\n".join(querys)
307316
async def handle_group_message(self, conversation_id, user_id, data):
308-
try:
309-
await self.send_message_to_chat_gpt2(conversation_id, user_id, data)
310-
except asyncio.exceptions.CancelledError:
311-
logger.info("++++handle_group_message received CancelledError, exit...")
317+
await self.send_message_to_chat_gpt2(conversation_id, user_id, data)
312318

313319
async def on_message(self, id: str, action: str, msg: Optional[MessageView]):
314320
if action not in ["ACKNOWLEDGE_MESSAGE_RECEIPT", "CREATE_MESSAGE", "LIST_PENDING_MESSAGES"]:
@@ -358,19 +364,31 @@ async def on_message(self, id: str, action: str, msg: Optional[MessageView]):
358364
pass
359365

360366
if utils.unique_conversation_id(msg.user_id, self.client_id) == msg.conversation_id:
361-
asyncio.create_task(self.handle_message(msg.conversation_id, msg.user_id, data))
367+
asyncio.create_task(self.handle_user_message(msg.conversation_id, msg.user_id, data))
362368
else:
363369
asyncio.create_task(self.handle_group_message(msg.conversation_id, msg.user_id, data))
364370

365371
async def run(self):
366372
try:
367-
await super().run()
373+
while not self.paused:
374+
try:
375+
await super().run()
376+
except websockets.exceptions.ConnectionClosedError as e:
377+
logger.exception(e)
378+
await asyncio.sleep(3.0)
379+
self.ws = None
380+
#asyncio.exceptions.TimeoutError
381+
except Exception as e:
382+
#
383+
logger.exception(e)
384+
await asyncio.sleep(3.0)
385+
self.ws = None
368386
except asyncio.CancelledError:
369387
if self.ws:
370388
await self.ws.close()
371389
if self.web_client:
372390
await self.web_client.aclose()
373-
logger.info("mixin websocket received CancelledError, exit...")
391+
logger.info("mixin websocket was cancelled!")
374392

375393
async def close(self):
376394
for bot in self.bots:
@@ -390,11 +408,7 @@ async def start(config_file):
390408
asyncio.create_task(bot.run())
391409
print('started')
392410
while not bot.paused:
393-
try:
394-
await asyncio.sleep(1.0)
395-
except asyncio.CancelledError:
396-
logger.info("+++start received CancelledError, exit...")
397-
return
411+
await asyncio.sleep(1.0)
398412

399413
async def stop():
400414
global bot

0 commit comments

Comments
 (0)