Skip to content

Commit

Permalink
v1.2 添加热更新依赖支持
Browse files Browse the repository at this point in the history
  • Loading branch information
tom-snow committed May 16, 2023
1 parent 5e51f60 commit 61fb54b
Show file tree
Hide file tree
Showing 4 changed files with 55 additions and 5 deletions.
54 changes: 50 additions & 4 deletions PyroEdgeGptBot.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,16 @@
# -*- coding: utf-8 -*-

import re
import sys, importlib
import json
import time
import pytz
import logging
import asyncio
import contextlib

import EdgeGPT

# import py3langid as langid
from logging.handlers import TimedRotatingFileHandler
from datetime import datetime
Expand All @@ -19,7 +22,6 @@
from pyrogram.types import InlineKeyboardMarkup, InlineKeyboardButton, ReplyKeyboardMarkup, \
ReplyKeyboardRemove, InlineQueryResultPhoto, InlineQueryResultArticle, InputTextMessageContent, \
InputMediaPhoto
from EdgeGPT import Chatbot, ConversationStyle

from config import API_ID, API_KEY, BOT_TOKEN, ALLOWED_USER_IDS, COOKIE_FILE, NOT_ALLOW_INFO, \
BOT_NAME, SUGGEST_MODE, DEFAULT_CONVERSATION_STYLE_TYPE, RESPONSE_TYPE, STREAM_INTERVAL, \
Expand Down Expand Up @@ -78,7 +80,7 @@ def formatTime(self, record, datefmt=None):


def check_conversation_style(style):
if style in ConversationStyle.__members__:
if style in EdgeGPT.ConversationStyle.__members__:
return True
return False

Expand All @@ -103,8 +105,8 @@ class BAD_CONFIG_ERROR(Exception):
tmpLoop = asyncio.get_event_loop()
for user_id in ALLOWED_USER_IDS:
EDGES[user_id] = {
"bot": tmpLoop.run_until_complete(Chatbot.create(cookie_path=COOKIE_FILE)), # 共用一个 cookie.json 文件
"style": ConversationStyle[DEFAULT_CONVERSATION_STYLE_TYPE],
"bot": tmpLoop.run_until_complete(EdgeGPT.Chatbot.create(cookie_path=COOKIE_FILE)), # 共用一个 cookie.json 文件
"style": EdgeGPT.ConversationStyle[DEFAULT_CONVERSATION_STYLE_TYPE],
"response": RESPONSE_TYPE,
"interval": STREAM_INTERVAL,
"suggest": SUGGEST_MODE,
Expand Down Expand Up @@ -183,6 +185,50 @@ async def set_response_handle(bot, update):
reply_text = f"{BOT_NAME}: set RESPONSE_TYPE to '{EDGES[update.chat.id]['response']}'."
await bot.send_message(chat_id=update.chat.id, text=reply_text)

# 更新依赖
@pyro.on_message(filters.command("update") & filters.private & filters.chat(ALLOWED_USER_IDS))
async def set_update_handle(bot, update):
logger.info(f"Receive commands [{update.command}] from [{update.chat.id}]")
msg = await bot.send_message(chat_id=update.chat.id
, text=f"{BOT_NAME}: Updateing [EdgeGPT](https://github.com/acheong08/EdgeGPT)."
, disable_web_page_preview=True)
# 关闭连接
for user_id in EDGES:
await EDGES[user_id]["bot"].close()
# 更新&重载依赖
python_path = sys.executable
executor = await asyncio.create_subprocess_shell(f"{python_path} -m pip install -U EdgeGPT"
, stdout=asyncio.subprocess.PIPE
, stderr=asyncio.subprocess.PIPE
, stdin=asyncio.subprocess.PIPE)
stdout, stderr = await executor.communicate()
logger.info(f"[set_update_handle] stdout: {stdout.decode()}")
result = ""
old_version = ""
new_version = ""
for line in stdout.decode().split("\n"): # 解析日志
if "Successfully uninstalled EdgeGPT-" in line:
old_version = line.replace("Successfully uninstalled EdgeGPT-", "").strip()
if "Successfully installed EdgeGPT-" in line:
new_version = line.replace("Successfully installed EdgeGPT-", "").strip()
if old_version and new_version:
result = f"[EdgeGPT](https://github.com/acheong08/EdgeGPT): {old_version} -> {new_version}"
err = False
if "WARNING" not in stderr.decode():
err = True
if err:
logger.error(f"[set_update_handle] stderr: {stderr.decode()}")
result += stderr.decode()
else:
logger.warning(f"[set_update_handle] stderr: {stderr.decode()}")

importlib.reload(EdgeGPT)
# 重新连接
for user_id in EDGES:
EDGES[user_id]["bot"] = await EdgeGPT.Chatbot.create(cookie_path=COOKIE_FILE)
EDGES[user_id]["style"] = EdgeGPT.ConversationStyle[DEFAULT_CONVERSATION_STYLE_TYPE]
await msg.edit_text(f"{BOT_NAME}: Updated!\n\n{result}", disable_web_page_preview=True)

# 设置 stream 模式消息更新间隔
@pyro.on_message(filters.command("interval") & filters.private & filters.chat(ALLOWED_USER_IDS))
async def set_interval_handle(bot, update):
Expand Down
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ _A telegram bot with Bing AI ( using [EdgeGPT](https://github.com/acheong08/Edge
- [ ] Prompt Support
- [x] Image generation (inline query and command mode)
- [ ] Export conversation to Notion
- [x] Hot update the EdgeGPT dependence

# Setup
## Requirements
Expand Down Expand Up @@ -95,6 +96,7 @@ switch - Switch the conversation style
interval - Set edit interval
suggest_mode - Set the suggest mode
image_gen - Generate images
update - Update the EdgeGPT dependence
```

</details>
Expand Down
2 changes: 2 additions & 0 deletions README_zh.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ _在 Telegram 上使用 Bing AI ( 使用 [EdgeGPT](https://github.com/acheong08/
- [ ] 支持 prompt
- [x] 图片生成 (inline query 与命令模式)
- [ ] 导出会话到 notion
- [x] 热更新 EdgeGPT 依赖

# 安装
## 依赖
Expand Down Expand Up @@ -99,6 +100,7 @@ switch - 切换聊天模式
interval - 设置修改消息间隔
suggest_mode - 建议消息模式
image_gen - 图片生成
update - 热更新 EdgeGPT 依赖
```

</details>
Expand Down
2 changes: 1 addition & 1 deletion requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

python-dotenv>=1.0.0
Pyrogram>=2.0
EdgeGPT>=0.3.8
EdgeGPT>=0.4.2
tgcrypto
aiohttp
pytz
Expand Down

0 comments on commit 61fb54b

Please sign in to comment.