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

如何实现Bot处理日志消息并响应反应提取[User]变量

解决Discord Bot日志消息处理与反应监听问题

一、提取日志消息中的用户名

针对固定格式的日志消息,可通过字符串分割或正则表达式提取Username:后的内容:

方法1:字符串分割

# 从日志消息对象中获取内容
log_content = message.content
# 按行拆分内容
for line in log_content.split('\n'):
    if line.startswith('Username:'):
        # 分割冒号并去除前后空格,得到用户名
        username = line.split(':', 1)[1].strip()
        break

方法2:正则表达式(更精准)

import re

log_content = message.content
# 匹配Username: 后的所有内容
match = re.search(r'Username:\s*(.*)', log_content)
if match:
    username = match.group(1)

二、监听指定频道的消息反应

推荐使用on_reaction_add事件监听反应,这样能覆盖所有符合条件的消息:

完整示例代码

import discord
from discord.ext import commands
import re

# 初始化Bot,按需调整前缀和Intents
client = commands.Bot(command_prefix='!', intents=discord.Intents.all())

# 替换为你要监听的频道ID
TARGET_CHANNEL_ID = 1234567890

@client.event
async def on_ready():
    print(f'已登录:{client.user}')

@client.event
async def on_reaction_add(reaction, user):
    # 忽略Bot自身的反应
    if user.bot:
        return
    # 检查消息是否在目标频道
    if reaction.message.channel.id != TARGET_CHANNEL_ID:
        return
    
    # 提取用户名
    match = re.search(r'Username:\s*(.*)', reaction.message.content)
    if not match:
        # 非目标格式日志,直接返回
        return
    username = match.group(1)
    
    # 这里执行你的业务操作,比如通知、记录等
    await reaction.message.channel.send(f'已处理用户 {username} 的库存日志')

# 替换为你的Bot Token
client.run('YOUR_BOT_TOKEN')

若需在on_message中等待单条消息的反应

如果只针对刚发送的日志消息等待反应,可使用wait_for:

import asyncio

@client.event
async def on_message(message):
    # 仅处理目标频道的日志消息
    if message.channel.id != TARGET_CHANNEL_ID or not message.content.startswith('Username:'):
        await client.process_commands(message)
        return
    
    # 提取用户名
    match = re.search(r'Username:\s*(.*)', message.content)
    if not match:
        await client.process_commands(message)
        return
    username = match.group(1)
    
    # 等待用户添加反应,超时1小时
    try:
        reaction, reactor = await client.wait_for(
            'reaction_add',
            timeout=3600,
            check=lambda r, u: r.message.id == message.id and not u.bot
        )
    except asyncio.TimeoutError:
        await message.channel.send('超时未收到反应,取消处理')
        return
    
    # 执行后续操作
    await message.channel.send(f'{reactor.name} 对 {username} 的日志做出反应,已完成处理')
    
    await client.process_commands(message)

注意事项

  • 确保Bot开启了message_content、reactions、members等必要Intents,否则无法正常监听消息和反应。
  • 可根据实际日志格式调整正则表达式,适配特殊字符或格式变化。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 12:24:45