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

Discord.py开发问题:如何实现spam命令收到stopspam关键词后停止刷屏

问题原因

  • 第一版代码逻辑顺序错误:while Spamcheck 是死循环,代码会一直卡在循环发送消息的步骤,永远不会执行后面的停止监听逻辑;同时调用字符串小写方法时漏了括号,lower要写成lower()才会返回小写处理后的内容,判断逻辑永远不会生效。
  • 第二版代码变量作用域错误:Spamcheck是spampls函数内的局部变量,stopspam命令里修改的是自己函数内的同名局部变量,完全不会影响到spampls里的运行状态。

正确实现方案

我们可以用bot实例的全局属性存储运行状态,跨命令共享状态,同时加发送间隔避免触发Discord速率限制:

import asyncio
from discord.ext import commands

# 初始化bot实例后先定义全局状态,用于控制spam任务
bot = commands.Bot(command_prefix='!', intents=your_intents) # 替换成你自己的intents配置
bot.spam_running = False
bot.spam_author_id = None

@commands.has_role("Bot Developer")
@bot.command()
async def spampls(ctx):
    # 避免重复触发多个spam任务
    if bot.spam_running:
        await ctx.send("已有正在运行的刷屏任务,请先发送!stopspam停止")
        return
    bot.spam_running = True
    bot.spam_author_id = ctx.author.id
    await ctx.send('请输入你想要刷屏的内容:')
    
    def check(m):
        return m.author.id == ctx.author.id and m.channel == ctx.channel
    # 等待用户输入要刷屏的内容
    input_msg = await bot.wait_for('message', check=check)
    spam_content = input_msg.content
    
    while bot.spam_running:
        await ctx.send(spam_content)
        # 必须加发送间隔,否则会触发Discord反垃圾机制,严重会导致机器人账号被封禁
        await asyncio.sleep(1) # 可自行调整间隔时长,单位为秒

@bot.command()
@commands.has_role("Bot Developer")
async def stopspam(ctx):
    # 仅触发spam任务的用户有权限停止
    if not bot.spam_running or ctx.author.id != bot.spam_author_id:
        await ctx.send("当前无运行中的刷屏任务,或你没有停止权限")
        return
    bot.spam_running = False
    bot.spam_author_id = None
    await ctx.send("已停止刷屏")

注意事项

  • 需要在Discord开发者后台的机器人设置里开启Message Content Intent,否则机器人无法读取消息内容,监听和命令都会失效。
  • 如果需要支持多服务器同时运行不同的spam任务,可以把状态存储改成字典格式,用服务器ID作为key区分不同任务。
  • 不建议把发送间隔调得太短,避免触发Discord官方的限流或封禁。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 14:36:03