如何避免Telegram Bot调用sendMediaGroup时触发429错误
Telegram 批量媒体发送的超时逻辑修复
需求背景
- 群组内发送限制:每分钟最多20条消息,
sendMediaGroup中的每个媒体块会被算作一条独立消息 dl.imgs最多包含4个媒体块,每个块最多9张图片(也可能只有1个块甚至1张图)- 预期发送逻辑:
- 前两个块间隔5秒发送
- 第三个块在第二个块发送后延迟60秒再发送
- 第四个块在第三个块发送后间隔5秒发送
- 以此规避429请求超限错误
原代码问题
你当前的代码对setTimeout的延迟计算逻辑有误,导致发送时间不符合预期:
let interval = chatType === 'private' ? 1000 : 5000; let it = 0; dl.imgs.forEach(function (el, index) { it += interval * index; if (index===2) it += 60000; setTimeout(function () { console.log(`part #${index+1}; size=${el.length}; timeout=${it}`) bot.sendMediaGroup(chatId, el, { reply_to_message_id: userMsgId, disable_notification: true, allow_sending_without_reply: true }).catch((err) => { console.log(err.code); console.log(err.response.body); }); }, it); });
问题出在it += interval * index的计算方式:
- 这种方式会让每个块的延迟基于index的倍数累加,而非在上一个块的发送时间基础上顺延
- 第三个块的额外60秒延迟叠加错误,导致整体发送时间线偏离预期
修复后的代码
let interval = chatType === 'private' ? 1000 : 5000; let it = 0; dl.imgs.forEach(function (el, index) { // 用当前的it值设置超时,发送当前媒体块 setTimeout(function () { console.log(`part #${index+1}; size=${el.length}; timeout=${it}`); bot.sendMediaGroup(chatId, el, { reply_to_message_id: userMsgId, disable_notification: true, allow_sending_without_reply: true }).catch((err) => { console.log(err.code); console.log(err.response.body); }); }, it); // 计算下一个块的延迟时间 if (index === 1) { // 第二个块发送后,额外增加60秒延迟 it += 60000; } // 每个块之间的基础间隔 it += interval; });
逻辑说明
- 初始
it为0,第一个块立即发送 - 第一个块发送后,
it累加基础间隔(5秒),第二个块在5秒后发送 - 第二个块发送后,先累加60秒延迟,再累加基础间隔,第三个块在
5+60=65秒后发送 - 第三个块发送后,累加基础间隔,第四个块在
65+5=70秒后发送 - 完全符合你需要的发送时间线,有效规避群组发送限制
内容的提问来源于stack exchange,提问作者Bohdan
相关产品推荐
相关产品推荐

