如何在DSharp-button中循环替换机器人消息?实现无硬编码交互
解决方案:循环实现按钮文本切换
直接用循环代替重复的硬编码逻辑,既不用声明多个result变量,也能灵活处理任意数量的文本切换。优化后的代码如下:
[Command("test_button")] public async Task But(CommandContext ctx) { // 初始化带按钮的消息 var buttonMsg = await ctx.RespondAsync(m => m .WithContent("初始文本") .AddComponents(new DiscordButtonComponent(ButtonStyle.Primary, "button-one", "点击切换"))); // 要切换的文本集合,可随时扩展 var textList = new string[] { "textAAA", "textBBB", "textCCC" }; // 循环遍历每个文本项 foreach (var text in textList) { // 等待指定按钮的点击事件,过滤掉其他按钮/用户 var buttonResult = await buttonMsg.WaitForButtonAsync( btn => btn.Id == "button-one", timeout: TimeSpan.FromMinutes(5)); // 可设置超时时间 // 如果超时或没有有效交互,退出循环 if (!buttonResult.IsSuccess) break; // 回复Discord的交互,避免超时警告 await buttonResult.Result.Interaction.CreateResponseAsync( InteractionResponseType.DeferredMessageUpdate).ConfigureAwait(false); // 修改消息内容为当前文本 await buttonMsg.ModifyAsync(m => m.WithContent(text)).ConfigureAwait(false); } // 循环结束后可以禁用按钮(可选) await buttonMsg.ModifyAsync(m => m.Components = new ComponentBuilder() .WithButton("已结束", "button-one", ButtonStyle.Secondary, disabled: true) .Build()).ConfigureAwait(false); }
关键优化点:
- 循环复用变量:用
foreach遍历文本集合,每次循环复用buttonResult变量,不用重复声明result1/result2。 - 交互过滤:
WaitForButtonAsync里加了按钮ID的过滤条件,确保只响应目标按钮的点击,避免其他交互干扰。 - 超时处理:添加了超时参数,防止用户长时间不操作导致任务挂起。
- 可扩展性:只要修改
textList数组,就能新增/删除切换文本,完全不用改循环逻辑。
如果需要无限循环切换文本直到用户触发退出,可以改用while循环:
int currentIndex = 0; bool isRunning = true; while (isRunning) { var buttonResult = await buttonMsg.WaitForButtonAsync(btn => btn.Id == "button-one"); if (!buttonResult.IsSuccess) { isRunning = false; break; } await buttonResult.Result.Interaction.CreateResponseAsync(InteractionResponseType.DeferredMessageUpdate).ConfigureAwait(false); await buttonMsg.ModifyAsync(m => m.WithContent(textList[currentIndex])).ConfigureAwait(false); // 索引循环,到末尾回到开头 currentIndex = (currentIndex + 1) % textList.Length; }
内容的提问来源于stack exchange,提问作者Ishimi Anderson
相关产品推荐
相关产品推荐

