我正在为Discord做一个机器人(使用youtube api进行音乐播放),他在我们实现的所有功能中都做得很好,问题只在于当我调用播放列表功能或播放功能以及我们调用的音乐时必须播放或添加到队列中被阻止。我为此做了很多工作,并且找到了检测这些错误的方法,但是,有时它有用,有时却没有。如果我这样做,则可以处理某些音乐,例如交流/直流播放列表,而不能用于独立民谣播放列表中的一种音乐,但是如果我做了一些改动,则可以适用于独立民谣播放列表,但不会t表示交流/直流播放列表。我很紧张!
好的,这是我的代码存在问题的功能:
OBS:问题仅在于我验证regionRestriction和允许的数组的部分。问题是我不知道如何用promises正确地做事,变量bool / bool2在输入函数next()或next2()之前没有得到正确的值。并再次输入该函数,但是“抛出新错误”会停止我的程序的运行。当我调用pesquisarTime函数时,我正在尝试捕捉,并且当我捕捉到一些错误时,我只是再次抛出了这个错误,并执行了“ throw new Error(err)”,因为在播放功能中,我再次捕捉到了这个错误,最后在不和谐聊天中显示错误消息。请帮我解决这个问题!
async function pesquisarTime(idp, titlep){
let linkYoutube = "https://www.googleapis.com/youtube/v3/videos?id=" + idp + "&part=contentDetails&key=" + config.ytapi;
let response = await fetch(linkYoutube);
if(response == undefined || response == null){
throw new Error("Vídeo \"" + titlep + "\" inválido!");
}
let info = await response.json();
let regionRestriction = "";
let allowed = "";
let bool;
let bool2;
let x = 0;
let x2 = 0;
try{
regionRestriction = info.items[0].contentDetails.regionRestriction.blocked;
//console.log("regionRestriction = " + regionRestriction);
}catch(err){
}
try{
allowed = info.items[0].contentDetails.regionRestriction.allowed;
//console.log("allowed = " + allowed);
}catch(err){
}
if(regionRestriction != undefined && regionRestriction.length > 0){
bool = new Promise(function(resolve){
for(x = 0; x < regionRestriction.length; x++){
if(regionRestriction[x] == "BR"){
x = regionRestriction.length;
console.log("resolve region = true");
resolve(true);
}
else{
if(x == regionRestriction.length - 1){
console.log("resolve region = false");
resolve(false);
}
}
}
}).then(next(bool));
}
if(allowed != undefined && allowed.length > 0){
bool2 = new Promise(function(resolve){
for(x2 = 0; x2 < allowed.length; x2++){
if(allowed[x2] == "BR"){
x2 = allowed.length;
console.log("resolve allowed = false");
resolve(false);
}
else{
if(x2 == allowed.length - 1){
console.log("resolve allowed = true");
resolve(true);
}
}
}
}).then(next2(bool2));
}
function next(result){
if(result){
console.log("bool region = true fiii");
Promise.resolve();
throw new Error("Vídeo \"" + titlep + "\" bloqueado na sua região!");
}
}
function next2(result){
if(result){
console.log("bool2 allowed = true fiiii");
Promise.resolve();
throw new Error("Vídeo \"" + titlep + "\" Bloqueado!");
}
}
let durationp = info.items[0].contentDetails.duration.replace("PT", "");
durationp = consertarTempo(durationp);
durationp = calibrar(durationp);
return durationp;
}