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

Discord申请机器人重复发送Embed与感谢消息问题排查求助

解决Discord警察申请机器人重复发送消息的问题

问题描述

开发的Discord警察职位申请机器人修改后出现异常:用户完成申请问答流程后,机器人会向指定频道重复7次发送申请Embed,同时向用户的DM重复7次发送感谢消息。以下是出现问题的原代码:

import discord
import json
from discord.ext import commands
from discord.utils import get
import inspect
from discord import colour
from discord import user
from discord.ext import commands
from discord.ext.commands import Bot
bot = Bot("?")

intents = discord.Intents.all()
client = discord.Client(intents=intents)
#------------------------
channel_id = 1144768805499834409 # sends application to when it is done
token = "MY TOKEN"
# ------------------------
prefix = '?'
questions = {
    1: "What is your In-Game Name?",
    2: "Why do you want to be a police constable in BSRP",
    3: "In your own words,  what are your strengths and weaknesses? ",
    4: "What can you bring to the Metropolitan Police Service?",
    5: "Can you tell us a time you faced a difficult challenge and how you dealt with it?",
    6: "Where do you see yourself in 3 months time?",
    7: "What is your discord name and tag?"
}
max_questions = len(questions)
is_open = True

@client.event
async def on_message(message):
    global is_open
    if not message.content.startswith(prefix) or message.author.bot:
        return

    args = message.content[len(prefix):].split()
    command = args.pop(0).lower()

    if command == 'apply':
        if not is_open:
            await message.channel.send("Sorry, Applications are currently closed.")
            return
        user = await message.author.create_dm()
        await user.send("Hey! Welcome to your police Constable application! Your application has started. You have 3 minutes to complete it. Please rember to put lots of detail into youe respones and think about your answers")
        await message.channel.send("Application has been sent to your DM's, Please check for messages from BSRP Bot")
       
        application = {'userId': message.author.id}
        for i in range(1, max_questions+1):
            embed = discord.Embed(title=f'Question [{i}/{max_questions}]', description=questions[i],)
            await user.send(embed=embed)
            response = await client.wait_for('message', check=lambda m: m.author == message.author and m.channel == user, timeout=300)
            application[f'question{i}'] = response.content

        try:
            with open('applications.json', 'r') as f:
                data = json.load(f)
        except (FileNotFoundError, json.JSONDecodeError):
            data = []

        data.append(application)
        with open('applications.json', 'w') as f:
            json.dump(data, f)

        channel = client.get_channel(channel_id)
        embed = discord.Embed(title='Police Constable Application: ' + message.author.display_name)
        for i in range(1, max_questions+1):
            myval = f'{questions[i]}\n\n' + '_' + application[f'question{i}'] + '_'
            embed.add_field(name=f'Question {i}: ', value=myval, inline=True)
            await channel.send(embed=embed)
            await user.send('Thank you for applying! Your Application will now be reviewed! after it has been reviewed a member of the training team will contact you! Please do dont open support tickets unless it has been more then 48 hours since you applied. Best of luck!!')

    elif command == 'open' and message.author.guild_permissions.administrator:
        is_open = True
        await message.channel.send("Applications are now open.")

    elif command == 'close' and message.author.guild_permissions.administrator:
        is_open = False
        await message.channel.send("Applications are now closed.")


@client.event
async def on_ready():
    print(f"I'm Alive {bot.user}")

client.run(token)

Bug定位

问题出在构建申请Embed的for循环中:await channel.send(embed=embed)和await user.send(...)这两行代码被放在了循环内部。由于循环要执行7次(对应7个问题),每次循环都会发送一次消息,最终导致重复发送7次。

修复方案

将发送消息的代码移到循环外部,先完成所有Embed字段的添加,再执行一次发送操作。修复后的完整代码如下:

import discord
import json
from discord.ext import commands
from discord.utils import get
import inspect
from discord import colour
from discord import user
from discord.ext import commands
from discord.ext.commands import Bot
bot = Bot("?")

intents = discord.Intents.all()
client = discord.Client(intents=intents)
#------------------------
channel_id = 1144768805499834409 # sends application to when it is done
token = "MY TOKEN"
# ------------------------
prefix = '?'
questions = {
    1: "What is your In-Game Name?",
    2: "Why do you want to be a police constable in BSRP",
    3: "In your own words,  what are your strengths and weaknesses? ",
    4: "What can you bring to the Metropolitan Police Service?",
    5: "Can you tell us a time you faced a difficult challenge and how you dealt with it?",
    6: "Where do you see yourself in 3 months time?",
    7: "What is your discord name and tag?"
}
max_questions = len(questions)
is_open = True

@client.event
async def on_message(message):
    global is_open
    if not message.content.startswith(prefix) or message.author.bot:
        return

    args = message.content[len(prefix):].split()
    command = args.pop(0).lower()

    if command == 'apply':
        if not is_open:
            await message.channel.send("Sorry, Applications are currently closed.")
            return
        user = await message.author.create_dm()
        await user.send("Hey! Welcome to your police Constable application! Your application has started. You have 3 minutes to complete it. Please rember to put lots of detail into youe respones and think about your answers")
        await message.channel.send("Application has been sent to your DM's, Please check for messages from BSRP Bot")
       
        application = {'userId': message.author.id}
        for i in range(1, max_questions+1):
            embed = discord.Embed(title=f'Question [{i}/{max_questions}]', description=questions[i],)
            await user.send(embed=embed)
            response = await client.wait_for('message', check=lambda m: m.author == message.author and m.channel == user, timeout=300)
            application[f'question{i}'] = response.content

        try:
            with open('applications.json', 'r') as f:
                data = json.load(f)
        except (FileNotFoundError, json.JSONDecodeError):
            data = []

        data.append(application)
        with open('applications.json', 'w') as f:
            json.dump(data, f)

        channel = client.get_channel(channel_id)
        embed = discord.Embed(title='Police Constable Application: ' + message.author.display_name)
        # 先循环添加所有字段
        for i in range(1, max_questions+1):
            myval = f'{questions[i]}\n\n' + '_' + application[f'question{i}'] + '_'
            embed.add_field(name=f'Question {i}: ', value=myval, inline=True)
        # 字段添加完成后,仅发送一次Embed到指定频道
        await channel.send(embed=embed)
        # 仅发送一次感谢消息到用户DM
        await user.send('Thank you for applying! Your Application will now be reviewed! after it has been reviewed a member of the training team will contact you! Please do dont open support tickets unless it has been more then 48 hours since you applied. Best of luck!!')

    elif command == 'open' and message.author.guild_permissions.administrator:
        is_open = True
        await message.channel.send("Applications are now open.")

    elif command == 'close' and message.author.guild_permissions.administrator:
        is_open = False
        await message.channel.send("Applications are now closed.")


@client.event
async def on_ready():
    print(f"I'm Alive {bot.user}")

client.run(token)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 17:24:56