如何将Discord Youtube通知程序更改为仅在if语句为true时发布

如何将Discord Youtube通知程序更改为仅在if语句为true时发布,discord,discord.js,Discord,Discord.js,您好,我正在使用此repo获取频道发布新视频时的通知,这个机器人工作得很好,我对此没有任何抱怨,但我想改变一下它的工作方式,但我不能很好地理解代码,所以我试着通过改变一些东西来测试它,但没有任何效果,所以简言之,我试着做的和正在尝试做的是 修复代码,使其仅在视频标题以某个特定单词(如ex“Hello”)开头时发布最新视频,或者如果视频的标签是ex.#Hello,则发布最新视频,如果没有此帖子,则什么都没有 这是github repo中bot的index.js const config = req

您好,我正在使用此repo获取频道发布新视频时的通知,这个机器人工作得很好,我对此没有任何抱怨,但我想改变一下它的工作方式,但我不能很好地理解代码,所以我试着通过改变一些东西来测试它,但没有任何效果,所以简言之,我试着做的和正在尝试做的是

修复代码,使其仅在视频标题以某个特定单词(如ex“Hello”)开头时发布最新视频,或者如果视频的标签是ex.#Hello,则发布最新视频,如果没有此帖子,则什么都没有

这是github repo中bot的index.js

const config = require("./config.json"),
Discord = require("discord.js"),
Parser = require("rss-parser"),
parser = new Parser(),
Youtube = require("simple-youtube-api"),
youtube = new Youtube(config.youtubeKey);

const startAt = Date.now();
const lastVideos = {};

const client = new Discord.Client();
client.login(config.token).catch(console.log);

client.on("ready", () => {
    console.log(`[!] Ready to listen ${config.youtubers.length} youtubers!`);
    check();
    setInterval(check, 20*1000);
});

/**
 * Format a date to a readable string
 * @param {Date} date The date to format 
 */
function formatDate(date) {
    let monthNames = [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ];
    let day = date.getDate(), month = date.getMonth(), year = date.getFullYear();
    return `${day} ${monthNames[parseInt(month, 10)]} ${year}`;
}

/**
 * Call a rss url to get the last video of a youtuber
 * @param {string} youtubeChannelName The name of the youtube channel
 * @param {string} rssURL The rss url to call to get the videos of the youtuber
 * @returns The last video of the youtuber
 */
async function getLastVideo(youtubeChannelName, rssURL){
    console.log(`[${youtubeChannelName}]  | Getting videos...`);
    let content = await parser.parseURL(rssURL);
    console.log(`[${youtubeChannelName}]  | ${content.items.length} videos found`);
    let tLastVideos = content.items.sort((a, b) => {
        let aPubDate = new Date(a.pubDate || 0).getTime();
        let bPubDate = new Date(b.pubDate || 0).getTime();
        return bPubDate - aPubDate;
    });
    console.log(`[${youtubeChannelName}]  | The last video is "${tLastVideos[0] ? tLastVideos[0].title : "err"}"`);
    return tLastVideos[0];
}

/**
 * Check if there is a new video from the youtube channel
 * @param {string} youtubeChannelName The name of the youtube channel to check
 * @param {string} rssURL The rss url to call to get the videos of the youtuber
 * @returns The video || null
 */
async function checkVideos(youtubeChannelName, rssURL){
    console.log(`[${youtubeChannelName}] | Get the last video..`);
    let lastVideo = await getLastVideo(youtubeChannelName, rssURL);
    // If there isn't any video in the youtube channel, return
    if(!lastVideo) return console.log("[ERR] | No video found for "+lastVideo);
    // If the date of the last uploaded video is older than the date of the bot starts, return 
    if(new Date(lastVideo.pubDate).getTime() < startAt) return console.log(`[${youtubeChannelName}] | Last video was uploaded before the bot starts`);
    let lastSavedVideo = lastVideos[youtubeChannelName];
    // If the last video is the same as the last saved, return
    if(lastSavedVideo && (lastSavedVideo.id === lastVideo.id)) return console.log(`[${youtubeChannelName}] | Last video is the same as the last saved`);
    return lastVideo;
}

/**
 * Get the youtube channel id from an url
 * @param {string} url The URL of the youtube channel
 * @returns The channel ID || null
 */
function getYoutubeChannelIdFromURL(url) {
    let id = null;
    url = url.replace(/(>|<)/gi, "").split(/(\/channel\/|\/user\/)/);
    if(url[2]) {
      id = url[2].split(/[^0-9a-z_-]/i)[0];
    }
    return id;
}

/**
 * Get infos for a youtube channel
 * @param {string} name The name of the youtube channel or an url
 * @returns The channel info || null
 */
async function getYoutubeChannelInfos(name){
    console.log(`[${name.length >= 10 ? name.slice(0, 10)+"..." : name}] | Resolving channel infos...`);
    let channel = null;
    /* Try to search by ID */
    let id = getYoutubeChannelIdFromURL(name);
    if(id){
        channel = await youtube.getChannelByID(id);
    }
    if(!channel){
        /* Try to search by name */
        let channels = await youtube.searchChannels(name);
        if(channels.length > 0){
            channel = channels[0];
        }
    }
    console.log(`[${name.length >= 10 ? name.slice(0, 10)+"..." : name}] | Title of the resolved channel: ${channel.raw ? channel.raw.snippet.title : "err"}`);
    return channel;
}

/**
 * Check for new videos
 */
async function check(){
    console.log("Checking...");
    config.youtubers.forEach(async (youtuber) => {
        console.log(`[${youtuber.length >= 10 ? youtuber.slice(0, 10)+"..." : youtuber}] | Start checking...`);
        let channelInfos = await getYoutubeChannelInfos(youtuber);
        if(!channelInfos) return console.log("[ERR] | Invalid youtuber provided: "+youtuber);
        let video = await checkVideos(channelInfos.raw.snippet.title, "https://www.youtube.com/feeds/videos.xml?channel_id="+channelInfos.id);
        if(!video) return console.log(`[${channelInfos.raw.snippet.title}] | No notification`);
        let channel = client.channels.get(config.channel);
        if(!channel) return console.log("[ERR] | Channel not found");
        channel.send(
            config.message
            .replace("{videoURL}", video.link)
            .replace("{videoAuthorName}", video.author)
            .replace("{videoTitle}", video.title)
            .replace("{videoPubDate}", formatDate(new Date(video.pubDate)))
        );
        console.log("Notification sent !");
        lastVideos[channelInfos.raw.snippet.title] = video;
    });
}

const config=require(“./config.json”),
Discord=require(“Discord.js”),
Parser=require(“rss解析器”),
parser=new parser(),
Youtube=require(“简单Youtube api”),
youtube=新的youtube(config.youtubeKey);
const startAt=Date.now();
const lastVideos={};
const client=new Discord.client();
client.login(config.token).catch(console.log);
client.on(“ready”,()=>{
log(`[!]准备好侦听${config.youtubers.length}youtubers!`);
检查();
设置间隔(检查,20*1000);
});
/**
*将日期格式化为可读字符串
*@param{Date}Date要格式化的日期
*/
函数格式日期(日期){
让monthNames=[“一月”、“二月”、“三月”、“四月”、“五月”、“六月”、“七月”、“八月”、“九月”、“十月”、“十一月”、“十二月”];
让day=date.getDate(),month=date.getMonth(),year=date.getFullYear();
返回`${day}${monthNames[parseInt(月,10)]}${year}`;
}
/**
*调用rss url以获取youtuber的最后一个视频
*@param{string}youtubeChannelName youtube频道的名称
*@param{string}rssURL调用rss url以获取youtuber的视频
*@返回YouTube的最后一段视频
*/
异步函数getLastVideo(youtubeChannelName,rssURL){
log(`[${youtubeChannelName}]|获取视频…`);
让content=wait parser.parseURL(rssURL);
log(`[${youtubeChannelName}]|${content.items.length}找到视频`);
让tLastVideos=content.items.sort((a,b)=>{
设aPubDate=newdate(a.pubDate | | 0).getTime();
设bPubDate=newdate(b.pubDate | | 0).getTime();
返回bPubDate-aPubDate;
});
console.log(`[${youtubeChannelName}]|最后一个视频是“${tLastVideos[0]?tLastVideos[0]。标题:“err”}`);
返回tLastVideos[0];
}
/**
*检查是否有来自youtube频道的新视频
*@param{string}youtubeChannelName要检查的youtube频道的名称
*@param{string}rssURL调用rss url以获取youtuber的视频
*@返回视频| |空
*/
异步函数检查视频(youtubeChannelName,rssURL){
log(`[${youtubeChannelName}]|获取最后一个视频..`);
让lastVideo=等待getLastVideo(youtubeChannelName,rssURL);
//如果youtube频道中没有任何视频,请返回
如果(!lastVideo)返回console.log(“[ERR]|找不到“+lastVideo”的视频);
//如果上次上载视频的日期早于bot启动的日期,则返回
if(新日期(lastVideo.pubDate).getTime()|=10?name.slice(0,10)+“…”:name}]|解析频道信息…`);
让通道=空;
/*尝试按ID搜索*/
让id=getYoutubeChannelIdFromURL(名称);
如果(id){
channel=wait youtube.getChannelByID(id);
}
如果(!通道){
/*尝试按名称搜索*/
let channels=wait youtube.searchChannels(名称);
如果(通道长度>0){
通道=通道[0];
}
}
console.log(`[${name.length>=10?name.slice(0,10)+“…”:name}]|已解析通道的标题:${channel.raw?channel.raw.snippet.Title:“err”}`);
返回通道;
}
/**
*查看新视频
*/
异步函数检查(){
控制台日志(“检查…”);
config.youtuber.forEach(异步(youtuber)=>{
console.log(`[${youtuber.length>=10?youtuber.slice(0,10)+“…”:youtuber}]|开始检查…`);
让channelInfos=等待getYoutubeChannelInfos(youtuber);
if(!channelInfos)返回console.log(“[ERR]”提供的youtuber无效:“+youtuber”);
let video=等待检查视频(channelInfos.raw.snippet.title,“https://www.youtube.com/feeds/videos.xml?channel_id=“+channelInfos.id);
if(!video)返回console.log(`[${channelInfos.raw.snippet.title}]|无通知`);
让channel=client.channels.get(config.channel);
if(!channel)返回console.log(“[ERR]| channel not found”);
频道发送(
config.message
.replace(“{videoURL}”,video.link)
.replace(“{videoAuthorName}”,video.author)
.replace(“{videoTitle}”,video.title)
.replace(“{videoPubDate}”,formatDate(新日期(video.pubDate)))
);
log(“已发送通知!”);
lastVideos[channelInfos.raw.snippet.title]=视频;
});
}
通过返回此

return tLastVideos[0] && tLastVideos[0].title.startsWith("HELLO") ? tLastVideos[0]: null;
现在,它检查标题是否以该字符串开始,并显示视频,对其进行测试,结果显示效果良好