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

如何使用discord.py实现机器人提取用户消息中的指定内容?

用discord.py提取消息中的特定内容

当然可以实现,核心是通过正则表达式匹配消息中的目标内容,结合discord.py的消息监听功能完成回复。下面是针对你给出的print('hello')案例的具体实现方案:

实现步骤与代码示例

  1. 导入所需模块:discord.py 和 正则表达式模块re
  2. 监听用户消息,用正则匹配括号内的单引号包裹内容
  3. 提取匹配到的内容并回复用户

完整代码示例:

import discord
import re
from discord.ext import commands

# 初始化机器人,设置命令前缀(可自定义)
bot = commands.Bot(command_prefix='!', intents=discord.Intents.all())

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

@bot.event
async def on_message(message):
    # 忽略机器人自身消息,避免循环回复
    if message.author == bot.user:
        return
    
    # 正则规则:匹配print('内容')格式,捕获单引号内的文本
    pattern = r"print\('(.*?)'\)"
    match = re.search(pattern, message.content)
    
    if match:
        # 提取捕获到的目标内容
        target_content = match.group(1)
        await message.channel.send(target_content)
    
    # 保留命令处理逻辑,否则自定义命令会失效
    await bot.process_commands(message)

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

扩展优化建议

  • 如果要支持双引号格式(比如print("hello")),可修改正则规则为r"print\(['\"](.*?)['\"]\)",同时兼容单双引号
  • 若需匹配更通用的括号内容(不局限于print),可调整正则为r"\('(.*?)'\)"或r"\((.*?)\)"(根据需求决定是否保留引号)
  • 确保在Discord开发者门户的Bot设置中开启message_content权限,否则机器人无法读取用户消息

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 13:42:23