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

如何实现discord.py机器人与服务器两名成员交互并存储指定回复

Discord机器人:仅存储指定提示用户的回复

核心需求

机器人向两位指定用户发送DM提示「Please enter a number:」,仅收集这两位用户的回复并存储,用于后续业务处理。

实现思路

  • 维护一个等待回复用户字典,记录哪些用户当前处于待回复状态;
  • 发送提示时,将目标用户ID加入该字典;
  • 监听私聊消息,判断发送者是否在等待列表中,若是则存储回复并移除等待状态。

完整代码示例(基于discord.py v2.x)

import discord
from discord.ext import commands

# 初始化机器人,开启消息内容读取权限
intents = discord.Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix="!", intents=intents)

# 存储待回复用户:键为用户ID,值标记提示类型(支持多场景扩展)
waiting_for_replies = {}
# 存储收集到的回复:键为用户ID,值为回复内容
user_responses = {}

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

async def send_prompt(user_ids):
    """给指定用户发送提示并标记待回复状态"""
    prompt = "Please enter a number:"
    for user_id in user_ids:
        try:
            user = await bot.fetch_user(user_id)
            await user.send(prompt)
            waiting_for_replies[user_id] = "number_input"
            print(f"已向用户{user_id}发送提示")
        except discord.NotFound:
            print(f"无法找到用户ID:{user_id}")

@bot.event
async def on_message(message):
    # 忽略机器人自身消息
    if message.author == bot.user:
        return
    # 仅处理私聊消息
    if isinstance(message.channel, discord.DMChannel):
        user_id = message.author.id
        # 判断用户是否处于待回复状态
        if user_id in waiting_for_replies:
            # 存储回复内容
            user_responses[user_id] = message.content.strip()
            # 移除待回复标记,避免重复收集
            del waiting_for_replies[user_id]
            await message.author.send(f"已收到你的回复:{message.content}")
            # 若两位用户都已回复,触发后续业务处理
            if len(user_responses) == 2:
                await process_responses()
    # 必须调用此方法,否则命令无法正常执行
    await bot.process_commands(message)

async def process_responses():
    """处理收集到的所有回复"""
    print("=== 回复收集完成,开始处理 ===")
    for user_id, reply in user_responses.items():
        print(f"用户[{user_id}]:{reply}")
    # 在这里添加你的业务逻辑,比如计算、存储到数据库等
    # 处理完成后清空存储,以便下次收集
    user_responses.clear()

# 示例命令:触发发送提示给两位用户(可按需修改触发方式)
@bot.command()
async def start(ctx, user1: int, user2: int):
    await send_prompt([user1, user2])
    await ctx.send("已向指定用户发送提示,请等待回复")

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

关键说明

  • 权限配置:必须在Discord开发者门户开启「Message Content Intent」权限,否则机器人无法读取消息内容;
  • 精准控制:通过waiting_for_replies字典确保仅收集目标用户的回复,避免无关消息干扰;
  • 扩展性:如果有多种提示场景,可以通过字典的值区分不同提示类型,实现多场景回复收集;
  • 后续处理:当两位用户都完成回复后,自动触发process_responses执行你的业务逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 17:20:26