From 679f9ac2fe53bf14f67391a3993958ab5278b2db Mon Sep 17 00:00:00 2001 From: "CHIH-HAO, CHUANG" Date: Fri, 24 Apr 2026 13:50:57 +0800 Subject: [PATCH] Make bot send message like a real human --- interaction/chat.py | 19 +++++++++++++------ llm/llm.py | 3 ++- utils/send_like_human.py | 20 ++++++++++++++++++++ 3 files changed, 35 insertions(+), 7 deletions(-) create mode 100644 utils/send_like_human.py diff --git a/interaction/chat.py b/interaction/chat.py index 059dea6..70a80f1 100644 --- a/interaction/chat.py +++ b/interaction/chat.py @@ -1,5 +1,7 @@ -from discord import Bot, Message +from discord import Bot, Message, TextChannel, Thread + from llm.llm import get_llm_service +from utils.send_like_human import send_like_human async def handle_chat(bot: Bot, message: Message) -> None: @@ -7,10 +9,10 @@ async def handle_chat(bot: Bot, message: Message) -> None: bot_user = bot.user if bot_user is None or bot_user == user or user.bot: - return + return None if bot_user not in message.mentions: - return + return None content = message.content for mention_user in message.mentions: @@ -25,17 +27,22 @@ async def handle_chat(bot: Bot, message: Message) -> None: llm_service = get_llm_service() except ValueError as e: await message.reply(f"聊天功能無法使用: {str(e)}") - return + return None except Exception as e: await message.reply(f"初始化聊天服務時發生錯誤: {str(e)}") - return + return None try: async with message.channel.typing(): response = await llm_service.process_message( message=message, ) - await message.reply(response, mention_author=False) + + if not isinstance(message.channel, (TextChannel, Thread)): + await message.reply("無法回覆訊息: 頻道類型不受支持") + return None + + await send_like_human(message.channel, response) except Exception as e: error_msg = f"抱歉,處理訊息時發生錯誤: {str(e)}" await message.reply(error_msg) diff --git a/llm/llm.py b/llm/llm.py index 2789c38..b136bfd 100644 --- a/llm/llm.py +++ b/llm/llm.py @@ -15,6 +15,7 @@ from db import get_db from repository.chat_repository import ChatRepository from tools import AVAILABLE_TOOLS +from utils.send_like_human import send_like_human from .config import OpenAIConfig from .filter import post_filter @@ -296,7 +297,7 @@ async def system_event_callback( content=response, ) - await text_channel.send(response) + await send_like_human(text_channel, response) # pylint: disable=invalid-name diff --git a/utils/send_like_human.py b/utils/send_like_human.py new file mode 100644 index 0000000..b7a9849 --- /dev/null +++ b/utils/send_like_human.py @@ -0,0 +1,20 @@ +from discord import TextChannel, Thread + +from asyncio import sleep as asleep +from random import random +from typing import Union + + +async def send_like_human( + channel: Union[TextChannel, Thread], + content: str +) -> None: + message_list = content.split("\n\n") + for i, msg in enumerate(message_list): + await channel.send(msg) + + if i >= len(message_list) - 1: + break + + async with channel.typing(): + await asleep(random() + 0.3)