Discord机器人运行命令时停止指令实现及循环、数量指令开发求助
Discord 机器人命令停止、循环、数量控制实现方案
核心思路
通过状态标记位管控 spam 任务的运行状态,停止命令仅需修改对应标记位即可中断执行,同时扩展参数支持循环和指定发送数量。
完整实现代码
import asyncio import discord from discord.ext import commands # 初始化机器人,替换为你自己的命令前缀,同时开启消息内容意图 intents = discord.Intents.default() intents.message_content = True client = commands.Bot(command_prefix='!', intents=intents) # 存储每个服务器的spam运行状态,key为服务器ID,value为运行标记 spam_running = {} @client.command() async def startspam(ctx, message=None, count: int = -1): # count默认-1为无限循环,传入正整数则发送指定次数 if not message: await ctx.send("请指定要发送的内容,示例:!startspam 测试内容 10") return # 标记当前服务器spam任务启动 spam_running[ctx.guild.id] = True sent_count = 0 while spam_running.get(ctx.guild.id, False): # 达到指定发送次数则自动停止 if count != -1 and sent_count >= count: break await ctx.send(message) sent_count += 1 # 加1秒延时避免触发Discord消息发送频率限制,可按需调整 await asyncio.sleep(1) # 循环结束后重置状态 spam_running[ctx.guild.id] = False await ctx.send(f"spam任务已结束,共发送{sent_count}条消息") @client.command() async def stopspam(ctx): # 直接修改运行标记即可停止当前服务器的spam任务 spam_running[ctx.guild.id] = False await ctx.send('stopping...') await ctx.send('Stopped!') # 替换为你的机器人Token启动 client.run("你的机器人Token")
功能说明
- 运行中停止:每次发送消息前都会检查当前服务器的运行标记,执行
!stopspam修改标记后,循环会在下一次判断时直接终止 - 循环命令:不传入count参数时默认无限循环发送,例如
!startspam 测试内容 - 数量命令:传入第三个数字参数即可指定发送次数,例如
!startspam 测试内容 5就会自动发5条后停止
内容的提问来源于stack exchange,提问作者ItsAidenGaming
相关产品推荐
相关产品推荐

