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

如何用discord.py实现带动态目标的情绪触发回复机器人?

Discord.py 情绪触发回复机器人实现方案

需求说明

在名为#textchannel的频道中,当用户发送形如「(关切) 杰克」或「(愤怒)杰克」的消息时,机器人从对应情绪的预设回复列表中随机选一条,替换消息中的目标名称后发送:

  • 关切类回复示例:「没事的,[目标名称]」「[目标名称],你还好吗?」
  • 愤怒类回复示例:「去你的[目标名称]」「[目标名称]你搞什么鬼」「[目标名称]哈哈」

完整代码实现

import discord
from discord.ext import commands
import random
import re

# 初始化机器人,开启所需权限
bot = commands.Bot(command_prefix='!', intents=discord.Intents.all())

# 情绪与对应回复的映射字典
emotion_responses = {
    "关切": [
        "没事的,{target}",
        "{target},你还好吗?",
        "{target},别担心啦"
    ],
    "愤怒": [
        "去你的{target}",
        "{target}你搞什么鬼",
        "{target}哈哈"
    ]
}

# 指定要监听的目标频道名称
TARGET_CHANNEL = "textchannel"

@bot.event
async def on_ready():
    print(f'机器人已登录:{bot.user}')

@bot.event
async def on_message(message):
    # 忽略机器人自身发送的消息
    if message.author == bot.user:
        return
    
    # 仅处理目标频道的消息
    if message.channel.name != TARGET_CHANNEL:
        return
    
    # 正则匹配消息格式:(情绪标签) + 可选空格 + 目标名称
    match_result = re.match(r'\((.*?)\)\s*(.*)', message.content)
    if match_result:
        emotion_tag = match_result.group(1)
        target_name = match_result.group(2)
        
        # 匹配到预设情绪则随机发送对应回复
        if emotion_tag in emotion_responses:
            selected_reply = random.choice(emotion_responses[emotion_tag])
            await message.channel.send(selected_reply.format(target=target_name))
    
    # 必须调用此方法,否则机器人命令功能会失效
    await bot.process_commands(message)

# 替换为你的机器人Token
bot.run('YOUR_BOT_TOKEN')

使用说明

  1. 安装依赖:执行pip install discord.py安装所需库
  2. 配置Token:前往Discord开发者平台获取机器人Token,替换代码中的YOUR_BOT_TOKEN
  3. 扩展情绪:若需添加更多情绪类型,直接在emotion_responses字典中新增键值对,格式为"情绪标签": ["回复内容1", "回复内容2"]
  4. 格式调整:当前正则支持标签与名称间有无空格的情况,若需修改消息匹配规则,可调整re.match中的正则表达式

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 04:50:25