我尝试为电报制作机器人,并使用telegram-node-bot。我在服务器上卸载我的机器人,现在进行一些修复并重新加载它。在我的控制台之后,我收到电报API错误消息,我无法向被禁止或阻止我的机器人的用户发送消息。如果我尝试发送这样的消息,我可以很容易地发现这个错误:
for(var i=0;i<users.length;i++){
let uid = users[i].chatid;
tg.api.sendMessage(uid, "Hello, world!")
.catch(function(err) {
console.log('err = '+JSON.stringify(err))
console.log('uid = '+uid) // undefined
})
}
在输出中会产生如下结果:
err = {"_code":403,"_description":"Forbidden: bot was blocked by the user"}
而且......这不要让我什么都不做因为uid
仍然未定义,我不能对这个错误做任何事情。如何将uid
传递给此捕获?
答案 0 :(得分:1)
您可以尝试以下方法:
const Fail = function(detail)=>{this.detail=detail;};
Promise.all(
users.map(
user =>
tg.api.sendMessage(user.chatid, "Hello, world!")
.then(
undefined,//do not handle resolve, do that later
err => new fail([err,user])
)
)
)
.then(
results => {
const sucesses = results.filter(result=>(result&&result.constructor)!==Fail);
const failures = results.filter(result=>(result&&result.constructor)===Fail);
console.log("all chats completed ,"+failures.length+" failed");
console.log(
"failure details:"
);
failures.forEach(
fail=>{
cosnt [reason,user] = fail.detail;
console.log("failed because:",reason,"for user:",user.chatid);
}
)
}
);
如果您需要更多帮助,请与我们联系。
您的代码无效的原因:
由于您的代码实际上没有显示任何问题,我必须猜测其中一个用户没有chatid,或者您正在使用var uid
或其他任何东西。
let
绑定的范围在for / while / if块中,但var
绑定在一个函数范围内(如果在函数外部则为全局绑定)。
我在这里使用let
绑定并看到它输出预期结果:
var i = -1,numbers=[1,2,3,4,5],promises=[];
while(++i<5){
let number = numbers[i]; // using let, should work as expected
console.log("in in the while loop",number);
promises.push(Promise.resolve("")
.then(
_=>console.log("In resolved promise number is now:",number)
)
);
}
console.log("after while loop",i);
Promise.all(promises)
.then(x=>console.log("all promises resolved"))
这使用var
绑定,因此您获得“意外”结果
var i = -1,numbers=[1,2,3,4,5],promises=[];
while(++i<5){
var number = numbers[i]; // using var, should have "unexpected" results
console.log("in in the while loop",number);
promises.push(Promise.resolve("")
.then(
_=>console.log("In resolved promise number is now (should be 5)",number)
)
);
}
console.log("after while loop",i);
Promise.all(promises)
.then(x=>console.log("all promises resolved"))