From 24f52d899d773cd86605f2925132330298234be2 Mon Sep 17 00:00:00 2001 From: yym68686 Date: Thu, 23 May 2024 04:26:02 +0800 Subject: [PATCH] =?UTF-8?q?=F0=9F=92=BB=20Code:=201.=20Update=20button=20h?= =?UTF-8?q?ierarchy?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 2. Refactor the code and put the function call code in the same folder. 3. Upgrade ModelMerge version to 0.5.6 --- bot.py | 98 +++++++++++++++++++------- config.py | 174 ++++++++++++++++++++++++++++++----------------- requirements.txt | 2 +- utils/i18n.py | 34 ++++++++- 4 files changed, 217 insertions(+), 91 deletions(-) diff --git a/bot.py b/bot.py index d42851f2..7d38c55b 100644 --- a/bot.py +++ b/bot.py @@ -15,18 +15,21 @@ WEB_HOOK, PORT, BOT_TOKEN, - LONG_TEXT, Users, + PREFERENCES, update_first_buttons_message, - update_model_buttons, get_current_lang, update_info_message, update_ENGINE, reset_ENGINE, - update_language, get_robot, get_image_message, - get_ENGINE + get_ENGINE, + update_language_status, + update_models_buttons, + update_preferences_buttons, + update_language_buttons, + update_plugins_buttons, ) from utils.i18n import strings @@ -145,7 +148,7 @@ async def command_bot(update, context, language=None, prompt=translator_prompt, robot, role = get_robot(chatid) engine = get_ENGINE(chatid) - if LONG_TEXT: + if PREFERENCES["LONG_TEXT"]: current_time = time.time() if message_cache[chatid]["last_update"] == 0: message_cache[chatid]["last_update"] = current_time @@ -204,7 +207,7 @@ async def getChatGPT(update, context, title, robot, message, chatid, messageid): reply_to_message_id=messageid, ) answer_messageid = message.message_id - pass_history = config.PASS_HISTORY + pass_history = PREFERENCES["PASS_HISTORY"] image_has_send = 0 try: @@ -245,7 +248,7 @@ async def getChatGPT(update, context, title, robot, message, chatid, messageid): print(escape(tmpresult)) else: sent_message = await context.bot.edit_message_text(chat_id=chatid, message_id=answer_messageid, text=escape(tmpresult), parse_mode='MarkdownV2', disable_web_page_preview=True, read_timeout=time_out, write_timeout=time_out, pool_timeout=time_out, connect_timeout=time_out) - if config.FOLLOW_UP: + if PREFERENCES["FOLLOW_UP"]: prompt = ( f"You are a professional Q&A expert. You will now be given reference information. Based on the reference information, please help me ask three most relevant questions that you most want to know from my perspective. Be concise and to the point. Do not have numbers in front of questions. Separate each question with a line break. Only output three questions in {config.LANGUAGE}, no need for any explanation. reference infomation is provided inside XML tags." "Here is the reference infomation, inside XML tags:" @@ -273,48 +276,97 @@ async def button_press(update, context): info_message = update_info_message(chatid) await callback_query.answer() data = callback_query.data + # print("data", data) banner = strings['message_banner'][get_current_lang()] - if data.endswith("ENGINE"): - data = data[:-6] + if data.endswith("_MODELS"): + data = data[:-7] update_ENGINE(data, chatid) try: info_message = update_info_message(chatid) if info_message + banner != callback_query.message.text: message = await callback_query.edit_message_text( text=escape(info_message + banner), - reply_markup=InlineKeyboardMarkup(update_model_buttons()), + reply_markup=InlineKeyboardMarkup(update_models_buttons()), parse_mode='MarkdownV2' ) except Exception as e: logger.info(e) pass - elif "MODEL" in data: + elif data.startswith("MODELS"): message = await callback_query.edit_message_text( text=escape(info_message + banner), - reply_markup=InlineKeyboardMarkup(update_model_buttons()), + reply_markup=InlineKeyboardMarkup(update_models_buttons()), parse_mode='MarkdownV2' ) - elif "BACK" in data: + elif data.endswith("_LANGUAGES"): + data = data[:-10] + # print("LANGUAGES data", data) + update_language_status(data) + try: + info_message = update_info_message(chatid) + if info_message != callback_query.message.text: + message = await callback_query.edit_message_text( + text=escape(info_message), + reply_markup=InlineKeyboardMarkup(update_language_buttons()), + parse_mode='MarkdownV2' + ) + except Exception as e: + logger.info(e) + pass + elif data.startswith("LANGUAGE"): message = await callback_query.edit_message_text( text=escape(info_message), - reply_markup=InlineKeyboardMarkup(update_first_buttons_message()), + reply_markup=InlineKeyboardMarkup(update_language_buttons()), parse_mode='MarkdownV2' ) - elif "language" in data: - update_language() - update_ENGINE() - info_message = update_info_message(chatid) + if data.endswith("_PREFERENCES"): + data = data[:-12] + try: + PREFERENCES[data] = not PREFERENCES[data] + except Exception as e: + logger.info(e) + try: + info_message = update_info_message(chatid) + if info_message != callback_query.message.text: + message = await callback_query.edit_message_text( + text=escape(info_message), + reply_markup=InlineKeyboardMarkup(update_preferences_buttons()), + parse_mode='MarkdownV2' + ) + except Exception as e: + logger.info(e) + pass + elif data.startswith("PREFERENCES"): message = await callback_query.edit_message_text( text=escape(info_message), - reply_markup=InlineKeyboardMarkup(update_first_buttons_message()), + reply_markup=InlineKeyboardMarkup(update_preferences_buttons()), parse_mode='MarkdownV2' ) - else: + if data.endswith("_PLUGINS"): + data = data[:-8] try: PLUGINS[data] = not PLUGINS[data] - except: - setattr(config, data, not getattr(config, data)) - info_message = update_info_message(chatid) + except Exception as e: + logger.info(e) + try: + info_message = update_info_message(chatid) + if info_message != callback_query.message.text: + message = await callback_query.edit_message_text( + text=escape(info_message), + reply_markup=InlineKeyboardMarkup(update_plugins_buttons()), + parse_mode='MarkdownV2' + ) + except Exception as e: + logger.info(e) + pass + elif data.startswith("PLUGINS"): + message = await callback_query.edit_message_text( + text=escape(info_message), + reply_markup=InlineKeyboardMarkup(update_plugins_buttons()), + parse_mode='MarkdownV2' + ) + + elif data.startswith("BACK"): message = await callback_query.edit_message_text( text=escape(info_message), reply_markup=InlineKeyboardMarkup(update_first_buttons_message()), diff --git a/config.py b/config.py index 029854be..8a92836e 100644 --- a/config.py +++ b/config.py @@ -13,7 +13,6 @@ NICK = os.environ.get('NICK', None) PORT = int(os.environ.get('PORT', '8080')) BOT_TOKEN = os.environ.get('BOT_TOKEN', None) -LONG_TEXT = (os.environ.get('LONG_TEXT', "True") == "False") == False def replace_with_asterisk(string, start=10, end=45): return string[:start] + '*' * (end - start) + string[end:] @@ -22,7 +21,6 @@ def replace_with_asterisk(string, start=10, end=45): API_URL = os.environ.get('API_URL', 'https://api.openai.com/v1/chat/completions') API = os.environ.get('API', None) WEB_HOOK = os.environ.get('WEB_HOOK', None) -FOLLOW_UP = (os.environ.get('FOLLOW_UP', "False") == "False") == False GROQ_API_KEY = os.environ.get('GROQ_API_KEY', None) GOOGLE_AI_API_KEY = os.environ.get('GOOGLE_AI_API_KEY', None) @@ -31,33 +29,21 @@ def replace_with_asterisk(string, start=10, end=45): Current_Date = current_date.strftime("%Y-%m-%d") LANGUAGE = os.environ.get('LANGUAGE', 'English') + +LANGUAGES = { + "English": False, + "Simplified Chinese": False, + # "France": False, +} + +LANGUAGES_TO_CODE = { + "English": "en", + "Simplified Chinese": "zh", + # "France": "fr", +} systemprompt = os.environ.get('SYSTEMPROMPT', prompt.system_prompt.format(LANGUAGE, Current_Date)) claude_systemprompt = os.environ.get('SYSTEMPROMPT', prompt.claude_system_prompt.format(LANGUAGE)) -def get_current_lang(): - if LANGUAGE == "Simplified Chinese": - lang = "zh" - else: - lang = "en" - return lang - -def update_language(): - global LANGUAGE, systemprompt, claude_systemprompt - try: - if LANGUAGE == "Simplified Chinese": - LANGUAGE = "English" - systemprompt = systemprompt.replace("Simplified Chinese", "English") - claude_systemprompt = claude_systemprompt.replace("Simplified Chinese", "English") - else: - LANGUAGE = "Simplified Chinese" - systemprompt = systemprompt.replace("English", "Simplified Chinese") - claude_systemprompt = claude_systemprompt.replace("English", "Simplified Chinese") - except: - pass - -temperature = float(os.environ.get('temperature', '0.5')) -CLAUDE_API = os.environ.get('claude_api_key', None) - class UserConfig: def __init__(self, user_id: str = None, language="English", engine="gpt-4o", mode="global"): self.user_id = user_id @@ -105,14 +91,8 @@ def set_config(self, user_id = None, parameter_name = None, value = None): def get_ENGINE(user_id = None): return Users.get_config(user_id, "engine") -def update_info_message(user_id = None): - return ( - f"**Model:** `{get_ENGINE(user_id)}`\n\n" - f"**API_URL:** `{API_URL}`\n\n" - f"**API:** `{replace_with_asterisk(API)}`\n\n" - f"**WEB_HOOK:** `{WEB_HOOK}`\n\n" - f"**tokens usage:** `{get_robot(user_id)[0].tokens_usage[str(user_id)]}`\n\n" - ) +temperature = float(os.environ.get('temperature', '0.5')) +CLAUDE_API = os.environ.get('claude_api_key', None) ChatGPTbot, SummaryBot, translate_bot, claudeBot, claude3Bot, groqBot, gemini_Bot = None, None, None, None, None, None, None def update_ENGINE(data = None, chat_id=None): @@ -133,7 +113,37 @@ def update_ENGINE(data = None, chat_id=None): if GOOGLE_AI_API_KEY and "gemini" in engine: gemini_Bot = gemini(api_key=f"{GOOGLE_AI_API_KEY}", engine=engine, system_prompt=systemprompt, temperature=temperature) -update_ENGINE() +def update_language_status(language, chat_id=None): + global LANGUAGES, LANGUAGE, systemprompt, claude_systemprompt + LAST_LANGUAGE = LANGUAGE + LANGUAGE = language + # print("LANGUAGE", LANGUAGE) + for lang in LANGUAGES: + LANGUAGES[lang] = False + + LANGUAGES[language] = True + try: + systemprompt = systemprompt.replace(LAST_LANGUAGE, "English") + claude_systemprompt = claude_systemprompt.replace(LAST_LANGUAGE, "English") + except Exception as e: + print("error:", e) + pass + update_ENGINE() + # Users.set_config(chat_id, "language", language) + # print("update_language_status", LANGUAGES) + +update_language_status(LANGUAGE) + + + +def update_info_message(user_id = None): + return ( + f"**Model:** `{get_ENGINE(user_id)}`\n\n" + f"**API_URL:** `{API_URL}`\n\n" + f"**API:** `{replace_with_asterisk(API)}`\n\n" + f"**WEB_HOOK:** `{WEB_HOOK}`\n\n" + f"**tokens usage:** `{get_robot(user_id)[0].tokens_usage[str(user_id)]}`\n\n" + ) def reset_ENGINE(chat_id, message=None): global ChatGPTbot, translate_bot, claudeBot, claude3Bot, groqBot, gemini_Bot, systemprompt, claude_systemprompt @@ -215,7 +225,11 @@ def delete_model_digit_tail(lst): else: return "-".join(lst[:i + 1]) -def create_buttons(strings, plugins_status=False, lang="English", button_text=None): +def get_status(setting, item): + print(setting) + return "✅ " if setting[item] else "☑️ " + +def create_buttons(strings, plugins_status=False, lang="English", button_text=None, Suffix="", setting=""): # 过滤出长度小于15的字符串 filtered_strings1 = [s for s in strings if len(delete_model_digit_tail(s.split("-"))) <= 14] filtered_strings2 = [s for s in strings if len(delete_model_digit_tail(s.split("-"))) > 14] @@ -225,9 +239,9 @@ def create_buttons(strings, plugins_status=False, lang="English", button_text=No for string in filtered_strings1: if plugins_status: - button = InlineKeyboardButton(f"{get_plugins_status(string)}{button_text[string][lang]}", callback_data=string) + button = InlineKeyboardButton(f"{get_status(setting, string)}{button_text[string][lang]}", callback_data=string + Suffix) else: - button = InlineKeyboardButton(delete_model_digit_tail(string.split("-")), callback_data=string + "ENGINE") + button = InlineKeyboardButton(delete_model_digit_tail(string.split("-")), callback_data=string + Suffix) temp.append(button) # 每两个按钮一组 @@ -241,9 +255,9 @@ def create_buttons(strings, plugins_status=False, lang="English", button_text=No for string in filtered_strings2: if plugins_status: - button = InlineKeyboardButton(f"{get_plugins_status(string)}{button_text[string][lang]}", callback_data=string) + button = InlineKeyboardButton(f"{get_status(setting, string)}{button_text[string][lang]}", callback_data=string + Suffix) else: - button = InlineKeyboardButton(delete_model_digit_tail(string.split("-")), callback_data=string + "ENGINE") + button = InlineKeyboardButton(delete_model_digit_tail(string.split("-")), callback_data=string + Suffix) buttons.append([button]) return buttons @@ -281,12 +295,17 @@ def create_buttons(strings, plugins_status=False, lang="English", button_text=No initial_model.extend([model for model in CUSTOM_MODELS_LIST if model not in initial_model and model[0] != "-"]) -def update_model_buttons(): - buttons = create_buttons(initial_model) - if LANGUAGE == "Simplified Chinese": - lang = "zh" - else: - lang = "en" +def get_current_lang(): + for lang, is_active in LANGUAGES.items(): + # print(lang, is_active) + if is_active: + return LANGUAGES_TO_CODE[lang] + +def update_language_buttons(): + lang = get_current_lang() + lang_list = list(LANGUAGES.keys()) + update_language_status(LANGUAGE) + buttons = create_buttons(lang_list, plugins_status=True, lang=lang, button_text=strings, setting=LANGUAGES, Suffix="_LANGUAGES") buttons.append( [ InlineKeyboardButton(strings['button_back'][lang], callback_data="BACK"), @@ -294,27 +313,54 @@ def update_model_buttons(): ) return buttons -def get_plugins_status(item): - return "✅ " if PLUGINS[item] else "☑️ " - -PASS_HISTORY = (os.environ.get('PASS_HISTORY', "True") == "False") == False def update_first_buttons_message(): - history = "✅ " if PASS_HISTORY else "☑️ " - - if LANGUAGE == "Simplified Chinese": - lang = "zh" - else: - lang = "en" - - + lang = get_current_lang() first_buttons = [ [ - InlineKeyboardButton(strings["button_change_model"][lang], callback_data="MODEL"), - InlineKeyboardButton(strings['button_language'][lang], callback_data="language"), - InlineKeyboardButton(f"{history}{strings['button_history'][lang]}", callback_data="PASS_HISTORY"), + InlineKeyboardButton(strings["button_change_model"][lang], callback_data="MODELS"), + InlineKeyboardButton(strings['button_preferences'][lang], callback_data="PREFERENCES"), + ], + [ + InlineKeyboardButton(strings['button_language'][lang], callback_data="LANGUAGE"), + InlineKeyboardButton(strings['button_plugins'][lang], callback_data="PLUGINS"), ], ] + return first_buttons + +def update_models_buttons(): + lang = get_current_lang() + buttons = create_buttons(initial_model, Suffix="_MODELS") + buttons.append( + [ + InlineKeyboardButton(strings['button_back'][lang], callback_data="BACK"), + ], + ) + return buttons + +def update_plugins_buttons(): + lang = get_current_lang() PLUGINS_LIST = list(PLUGINS.keys()) - buttons = create_buttons(PLUGINS_LIST, plugins_status=True, lang=lang, button_text=strings) - first_buttons.extend(buttons) - return first_buttons \ No newline at end of file + buttons = create_buttons(PLUGINS_LIST, plugins_status=True, lang=lang, button_text=strings, setting=PLUGINS, Suffix="_PLUGINS") + buttons.append( + [ + InlineKeyboardButton(strings['button_back'][lang], callback_data="BACK"), + ], + ) + return buttons + +PREFERENCES = { + "PASS_HISTORY": (os.environ.get('PASS_HISTORY', "True") == "False") == False, + "LONG_TEXT" : (os.environ.get('LONG_TEXT', "True") == "False") == False, + "FOLLOW_UP" : (os.environ.get('FOLLOW_UP', "False") == "False") == False, +} + +def update_preferences_buttons(): + lang = get_current_lang() + preferences_list = list(PREFERENCES.keys()) + buttons = create_buttons(preferences_list, plugins_status=True, lang=lang, button_text=strings, setting=PREFERENCES, Suffix="_PREFERENCES") + buttons.append( + [ + InlineKeyboardButton(strings['button_back'][lang], callback_data="BACK"), + ], + ) + return buttons \ No newline at end of file diff --git a/requirements.txt b/requirements.txt index dac6558d..e79b68a1 100644 --- a/requirements.txt +++ b/requirements.txt @@ -2,7 +2,7 @@ pytz python-dotenv md2tgmd==0.1.9 -ModelMerge==0.5.5 +ModelMerge==0.5.6 fake_useragent oauth2client==3.0.0 python-telegram-bot[webhooks,rate-limiter]==21.0.1 \ No newline at end of file diff --git a/utils/i18n.py b/utils/i18n.py index b06bd57b..1382cee7 100644 --- a/utils/i18n.py +++ b/utils/i18n.py @@ -7,9 +7,17 @@ "zh": "切换模型", "en": "Change model", }, - "button_history": { - "zh": "历史记录", - "en": "Chat history", + "button_preferences": { + "zh": "偏好设置", + "en": "Preferences", + }, + "button_language": { + "zh": "语言", + "en": "Language", + }, + "button_plugins": { + "zh": "插件", + "en": "Plugins", }, "button_back": { "zh": "⬅️ 返回", @@ -19,6 +27,26 @@ "zh": "🇨🇳 中文", "en": "🇺🇸 English", }, + "English": { + "zh": "🇺🇸 英文", + "en": "🇺🇸 English", + }, + "Simplified Chinese": { + "zh": "🇨🇳 中文", + "en": "🇨🇳 Simplified Chinese", + }, + "PASS_HISTORY": { + "zh": "历史记录", + "en": "Chat history", + }, + "FOLLOW_UP": { + "zh": "后续提问", + "en": "Follow-up question", + }, + "LONG_TEXT": { + "zh": "长文本合并", + "en": "Long text merge", + }, "message_think": { "zh": "`思考中💭`", "en": "`thinking💭`",