Node.js中如何设置间隔/超时解决Discord发送频率限制问题
Discord发送速率限制问题解决
错误信息
Error: 'The write action you are performing on the channel has hit the write rate limit.'
问题描述
我用Node.js写了个简单的index.js脚本,借助discord-autosender库读取文本文件内容循环发送,但就算用递增循环逐个调用发送方法,结果还是一次性发完,触发了Discord的发送速率限制导致报错。想问问怎么降低循环发送的速率?用setInterval或者setTimeout可行吗?具体该怎么配置?
原代码示例
const autosend = require("discord-autosender") const fs = require("fs"); function send(){ var channelID = "" var tokenID = "" const data = fs.readFileSync('mr_robot.txt', 'UTF-8'); const lines = data.split(/\r?\n/); for (let l_indx = 0; l_indx < lines.length; l_indx++) { var message = lines[l_indx]; autosend.Post(message, channelID, tokenID) } } send();
文本文件内容(Mr.Robot.txt)
A dog of that house shall move me to stand. I will take the wall of any man or maid of Montague’s. That shows thee a weak slave, for the weakest goes to the wall. ’Tis true, and therefore women, being the weaker vessels, are ever thrust to the wall. Therefore I will push Montague’s men from the wall and thrust his maids to the wall. The quarrel is between our masters and us their men.
解决方案
你的问题核心是同步循环会一次性发起所有发送请求,discord-autosender的Post是异步操作,但同步循环不会等待前一个请求完成就触发下一个,瞬间请求量超过Discord的速率限制。用setTimeout或异步循环(结合Promise)都能解决,下面是两种可行方案:
方案1:用setTimeout设置递增延迟
给每条消息设置按顺序递增的延迟,确保发送操作分散执行:
const autosend = require("discord-autosender") const fs = require("fs"); function send(){ var channelID = "" var tokenID = "" const data = fs.readFileSync('mr_robot.txt', 'UTF-8'); const lines = data.split(/\r?\n/); const sendDelay = 2000; // 每条消息间隔2秒,可根据限制调整 lines.forEach((message, index) => { // 跳过空行 if (!message.trim()) return; setTimeout(() => { autosend.Post(message, channelID, tokenID) .catch(err => console.error(`发送失败: ${err}`)); }, index * sendDelay); }) } send();
方案2:异步循环+await(更可靠)
如果需要确保前一条消息发送完成后再发下一条(避免网络延迟导致的请求叠加),用async/await结合自定义延迟函数:
const autosend = require("discord-autosender") const fs = require("fs"); // 自定义延迟函数 function delay(ms) { return new Promise(resolve => setTimeout(resolve, ms)); } async function send(){ var channelID = "" var tokenID = "" const data = fs.readFileSync('mr_robot.txt', 'UTF-8'); const lines = data.split(/\r?\n/); const interval = 2000; // 间隔2秒 for (let idx = 0; idx < lines.length; idx++) { const message = lines[idx]; if (!message.trim()) continue; try { await autosend.Post(message, channelID, tokenID); console.log(`第${idx+1}条消息发送成功`); } catch (err) { console.error(`第${idx+1}条消息发送失败:`, err); } // 最后一条消息无需延迟 if (idx !== lines.length - 1) { await delay(interval); } } } send();
关键注意点
- 延迟时间可根据Discord限制调整:普通用户频道限制为每5秒最多5条消息,1-2秒的间隔完全安全;机器人账号限制更宽松,但仍建议保留合理间隔。
- 必须添加错误捕获,避免单条消息发送失败导致整个脚本中断。
- 跳过空行可减少无效请求,降低触发限制的概率。
内容的提问来源于stack exchange,提问作者Glen Sale
相关产品推荐
相关产品推荐

