discord.js批量发送用户DM报错处理 机器人运行中断问题求助
问题原因
discord.js的user.send()是异步方法,会返回Promise对象,你当前的写法没有等待Promise执行完成,同步的try/catch只能捕获同步抛出的错误,无法捕获异步Promise的rejection,所以报错会直接冒泡到全局导致进程终止。
修复方案
方案1:async/await配合try/catch(推荐)
把发送逻辑封装到异步函数中,用await等待发送操作完成,即可让try/catch正常捕获错误:
// 把发送逻辑封装到异步函数中 async function bulkSendDM() { for (let i = 0; i < arrayOfUsersIDs.length; i++) { const userId = arrayOfUsersIDs[i] const user = client.users.cache.get(userId) // 先判断用户是否存在,避免空值报错 if (!user) { console.log(`未找到ID为${userId}的用户,跳过`) continue } try { // 等待异步发送操作完成 await user.send('My Message') console.log(`已向用户${userId}发送消息`) } catch (error) { // 可根据错误码精准判断是私信权限问题 if (error.code === 50007) { console.log(`用户${userId}关闭了私信权限,跳过`) } else { console.log(`向用户${userId}发送消息失败:`, error.message) } } } } // 调用执行函数 bulkSendDM()
方案2:链式调用.catch()处理错误
如果不想改动外层逻辑,也可以直接给send方法挂载.catch()处理错误:
for (let i = 0; i < arrayOfUsersIDs.length; i++) { const userId = arrayOfUsersIDs[i] const user = client.users.cache.get(userId) if (!user) { console.log(`未找到ID为${userId}的用户,跳过`) continue } user.send('My Message') .then(() => console.log(`已向用户${userId}发送消息`)) .catch(error => { if (error.code === 50007) { console.log(`用户${userId}关闭了私信权限,跳过`) } else { console.log(`向用户${userId}发送消息失败:`, error.message) } }) }
注意事项
批量发送私信时建议添加适当的发送间隔,避免触发Discord的消息频率限制,导致账号被风控。
内容的提问来源于stack exchange,提问作者Elyas Behroozizade
相关产品推荐
相关产品推荐

