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

如何用Python开发可检测特定身份组并自动回复的Discord Bot

Python Discord Bot 触发式自动回复实现方案

前置准备

  • 确认你当前使用的Discord Python库为discord.py v2.x版本,安装命令:pip install discord.py==2.3.2
  • 前往Discord开发者平台的Bot管理页,开启以下Privileged Gateway Intents:
    • Server Members Intent
    • Message Content Intent
  • 邀请Bot进服时勾选以下权限:
    • View Channels
    • Send Messages
    • Read Message History

核心逻辑说明

discord.py没有内置has_role方法,但可以通过遍历消息发送者的身份组列表匹配目标身份组,实现逻辑复杂度很低,核心判断代码为:

# 判断发送者是否持有指定名称的身份组
has_target_role = any(role.name == "PlaysROR2" for role in message.author.roles)

如果需要更稳定的匹配(避免改角色名失效),可以替换为按角色ID匹配:any(role.id == 你的角色ID整数 for role in message.author.roles)

完整可运行代码示例

import discord
from discord.ext import commands

# 配置Bot意图,必须开启对应的权限开关
intents = discord.Intents.default()
intents.members = True
intents.message_content = True

# 初始化Bot,命令前缀可自定义,这里用!不影响消息监听逻辑
bot = commands.Bot(command_prefix="!", intents=intents)

# Bot启动完成的提示
@bot.event
async def on_ready():
    print(f"已登录为 {bot.user}")

# 监听所有消息事件
@bot.event
async def on_message(message):
    # 排除Bot自己发送的消息,避免循环触发
    if message.author.bot:
        return
    
    # 自定义配置区
    target_role_name = "PlaysROR2"
    trigger_keyword = "game"
    reply_content = "ROR2"

    # 核心判断逻辑
    # 1. 判断用户是否持有目标身份组
    has_role = any(role.name == target_role_name for role in message.author.roles)
    # 2. 判断消息是否包含触发关键词(当前为大小写不敏感匹配)
    has_keyword = trigger_keyword in message.content.lower()

    if has_role and has_keyword:
        await message.channel.send(reply_content)
    
    # 保留Bot的命令处理逻辑,后续添加其他命令不会冲突
    await bot.process_commands(message)

# 替换为你自己的Bot Token后运行
bot.run("你的Bot Token")

部署替换说明

你现有托管的Bot只需要把原有代码替换为上述代码,填入你自己的Bot Token后重启服务即可生效。

常见排查问题

  • 如果Bot无响应,优先检查开发者后台的Intent开关是否全部开启,邀请时权限是否勾选正确
  • 身份组名称大小写敏感,如果匹配失败可以打印[role.name for role in message.author.roles]核对角色名称是否正确
  • 关键词匹配默认大小写不敏感,如果需要严格匹配可以去掉.lower()方法

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 10:06:02