Skip to content

Commit

Permalink
✨ Feature: Add feature: Support calculating the next reset time based…
Browse files Browse the repository at this point in the history
… on each user's last question time, instead of resetting all users at the same time.
  • Loading branch information
yym68686 committed Oct 26, 2024
1 parent 5d5f9a7 commit adf2d71
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 10 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ The following is a list of environment variables related to the bot's core setti
| SYSTEMPROMPT | Specify system prompt, the system prompt is a string, for example: `SYSTEMPROMPT=You are ChatGPT, a large language model trained by OpenAI. Respond conversationally`. The default is `None`. The setting of the system prompt is only effective when `CHAT_MODE` is `global`. When `CHAT_MODE` is `multiusers`, the system prompt environment variable will not modify any user's system prompt regardless of its value, because users do not want their set system to be changed to a global system prompt. | No |
| LANGUAGE | Specifies the default language displayed by the bot, including button display language and dialogue language. The default is `English`. Currently, it only supports setting to the following four languages: `English`, `Simplified Chinese`, `Traditional Chinese`, `Russian`. You can also use the `/info` command to set the display language after the bot is deployed. | No |
| CONFIG_DIR | Specify storage user profile folder. CONFIG_DIR is the folder for storing user configurations. Each time the bot starts, it reads the configurations from the CONFIG_DIR folder, so users won't lose their previous settings every time they restart. you can achieve configuration persistence by mounting folders using the `-v` parameter when deploying locally with Docker. Default is `user_configs`. | No |
| RESET_TIME | Specifies how many seconds the bot resets the chat history once. Every RESET_TIME seconds, the bot will reset the chat history for all users except the admin list. The default value is `3600` seconds, and the minimum value is `60` seconds. | No |
| RESET_TIME | Specifies how many seconds the bot resets the chat history. Every RESET_TIME seconds, the bot will reset the chat history for all users except the admin list. The reset time for each user is different, calculated based on the last question time of each user to determine the next reset time. It is not all users resetting at the same time. The default value is `3600` seconds, and the minimum value is `60` seconds. | No |

The following is a list of environment variables related to robot preferences. Preferences can also be set after the robot is started by using the `/info` command and clicking the `Preferences` button:

Expand Down
2 changes: 1 addition & 1 deletion README_CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ ChatGPT Telegram 机器人是一个强大的 Telegram 机器人,可以使用
| SYSTEMPROMPT | 指定系统提示,系统提示是字符串,例如:`SYSTEMPROMPT=You are ChatGPT, a large language model trained by OpenAI. Respond conversationally`。默认是 `None`。系统提示的设置仅在 `CHAT_MODE``global` 时,系统提示的设置才会有效。当 `CHAT_MODE``multiusers` 时,系统提示的环境变量无论是任何值都不会修改任何用户的系统提示,因为用户不希望自己设置的系统系统被修改为全局系统提示。 ||
| LANGUAGE | 指定机器人显示的默认语言,包括按钮显示语言和对话语言。默认是 `English`。目前仅支持设置为下面四种语言:`English``Simplified Chinese``Traditional Chinese``Russian`。同时也可以在机器人部署后使用 `/info` 命令设置显示语言 ||
| CONFIG_DIR | 指定存储用户配置文件夹。CONFIG_DIR 是用于存储用户配置的文件夹。每次机器人启动时,它都会从 CONFIG_DIR 文件夹读取配置,因此用户每次重新启动时不会丢失之前的设置。您可以在本地使用 Docker 部署时,通过使用 `-v` 参数挂载文件夹来实现配置持久化。默认值是 `user_configs`||
| RESET_TIME | 指定机器人每隔多少秒重置一次聊天历史记录,每隔 RESET_TIME 秒,机器人会重置一次除了管理员列表外所有用户的聊天历史记录。默认值是 `3600` 秒,最小值是 `60` 秒。 ||
| RESET_TIME | 指定机器人每隔多少秒重置一次聊天历史记录,每隔 RESET_TIME 秒,机器人会重置除了管理员列表外所有用户的聊天历史记录,每个用户重置时间不一样,根据每个用户最后的提问时间来计算下一次重置时间。而不是所有用户在同一时间重置。默认值是 `3600` 秒,最小值是 `60` 秒。 ||

以下是与机器人偏好设置相关的环境变量列表,偏好设置也可以通过机器人启动后使用 `/info` 命令,点击 `偏好设置` 按钮来设置:

Expand Down
40 changes: 32 additions & 8 deletions bot.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@
from telegram.constants import ChatAction
from telegram import BotCommand, InlineKeyboardMarkup, InlineQueryResultArticle, InputTextMessageContent, Update, ReplyKeyboardMarkup, KeyboardButton, ReplyKeyboardRemove
from telegram.ext import CommandHandler, MessageHandler, ApplicationBuilder, filters, CallbackQueryHandler, Application, AIORateLimiter, InlineQueryHandler, ContextTypes
from datetime import timedelta

import asyncio
lock = asyncio.Lock()
Expand Down Expand Up @@ -84,6 +85,17 @@ async def command_bot(update, context, language=None, prompt=translator_prompt,
stop_event.clear()
message, rawtext, image_url, chatid, messageid, reply_to_message_text, update_message, message_thread_id, convo_id, file_url, reply_to_message_file_content, voice_text = await GetMesageInfo(update, context)

# 移除已存在的任务(如果有)
remove_job_if_exists(convo_id, context)

# 添加新的定时任务
context.job_queue.run_once(
scheduled_function,
when=timedelta(seconds=RESET_TIME),
chat_id=chatid,
name=convo_id
)

if has_command == False or len(context.args) > 0:
if has_command:
message = ' '.join(context.args)
Expand Down Expand Up @@ -592,11 +604,26 @@ async def inlinequery(update: Update, context) -> None:
await update.inline_query.answer(results)

async def scheduled_function(context: ContextTypes.DEFAULT_TYPE) -> None:
"""这个函数将每RESET_TIME秒执行一次"""
for chat_id in Users.users.keys():
if config.ADMIN_LIST and chat_id in config.ADMIN_LIST:
continue
reset_ENGINE(chat_id)
"""这个函数将在RESET_TIME秒后执行一次,重置特定用户的对话"""
job = context.job
chat_id = job.chat_id

if config.ADMIN_LIST and chat_id in config.ADMIN_LIST:
return

reset_ENGINE(chat_id)

# 任务执行完毕后自动移除
remove_job_if_exists(str(chat_id), context)

def remove_job_if_exists(name: str, context: ContextTypes.DEFAULT_TYPE) -> bool:
"""如果存在,则移除指定名称的任务"""
current_jobs = context.job_queue.get_jobs_by_name(name)
if not current_jobs:
return False
for job in current_jobs:
job.schedule_removal()
return True

# 定义一个全局变量来存储 chatid
target_convo_id = None
Expand Down Expand Up @@ -787,9 +814,6 @@ async def post_init(application: Application) -> None:
application.add_handler(MessageHandler(filters.COMMAND, unknown))
application.add_error_handler(error)

job_queue = application.job_queue
job_queue.run_repeating(scheduled_function, interval=RESET_TIME, first=1)

if WEB_HOOK:
print("WEB_HOOK:", WEB_HOOK)
application.run_webhook("0.0.0.0", PORT, webhook_url=WEB_HOOK)
Expand Down

0 comments on commit adf2d71

Please sign in to comment.