You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Discord机器人系统提示末尾添加用户名(非命令场景)

解决方法

核心问题分析

你之前的错误在于:get_messages函数的第三个参数传入的是消息内容字符串,但你试图在函数里把它当成Discord的Message对象调用message.author.name,这会导致逻辑失效甚至报错。实际上调用get_messages时,你已经把message.author.name作为第二个参数recipient传入了,直接用这个参数即可实现需求。

修改后的代码实现

1. 调整get_messages函数逻辑

将Discord用户名直接拼接在系统提示末尾:

def get_messages(sender, recipient, message_content):
    sender = sender.lower()
    sender_role = "assistant" if sender == "assistant" else "user"
    role = recipient.lower() if sender == "assistant" else sender
    user = get_user(role)
    personality = user['personality'] if user else config["global_personality"]
    bot_context = config["system_context"]
    
    # 把用户名添加到系统提示的末尾
    system_content = f"{bot_context} Имя человека, который с тобой общается - {recipient}"
    system_role = {"role": "system", "content": system_content}
    
    prefix = personality if sender_role == 'user' else ''
    add_message({"role": sender_role, "content": f"{prefix}, {message_content}" if prefix else message_content})
    return [
        system_role,
        *[{"role": obj['role'], "content": obj['content']} for obj in history]
    ]

2. 修正generate_response中的调用参数

将函数参数名改为message_content避免混淆(可选,但能提升代码可读性):

async def generate_response(message):
    try:
        if message.author == bot.user:
            return
        def call_openai_api():
            logger.info('Звоню на Апишник')
            return openai.ChatCompletion.create(
                model=config["model"],
                # 明确传入消息内容,与函数参数对应
                messages=get_messages('assistant', message.author.name, message.content),
                temperature=0.7
            )
        await bot.change_presence(activity=discord.Activity(type=discord.ActivityType.listening, name="a " + message.author.name))
        async with message.channel.typing():
            logger.info(message.author.name + ": " + message.content)
            response = await bot.loop.run_in_executor(None, call_openai_api)
            content = response['choices'][0]['message']['content']
            await message.reply(content)
            # 同样修正这里的调用参数
            get_messages('assistant', message.author.name, content)
            logger.info("Assistant: " + content)
            logger.info("Токены: " + str(response["usage"]["total_tokens"]))
        await bot.change_presence(activity=discord.Activity(type=discord.ActivityType.watching, name=config["presence"]))
    except Exception as e:
        await message.reply(config["error_message"])
        await bot.change_presence(activity=discord.Activity(type=discord.ActivityType.watching, name=config["presence"]))
        logging.error(f"Ошибка генерации: {e}", exc_info=True)

关键说明

  • 系统消息的用户名拼接直接复用了已传入的recipient参数,无需在async def外部获取Message对象
  • 修正了函数参数名混淆的问题,避免后续维护时出现类似错误

内容的提问来源于stack exchange,提问作者therealend

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.10 17:43:13