Monday, January 31, 2022

[SOLVED] yt-search module causing CPU spikes

Issue

Any way to limit the amount of resources the module has/uses? When it spikes the CPU usage and a audio stream is currently playing the audio stops for a second. I am hosting the bot on AWS EC2 with 1 vCPU 1G RAM. Usually the bot uses about 2-3 CPU Utilization per stream but it spikes to about 60 Utilization when the yt-search is used. Here is a snip of the code:

if(ytdl.validateURL(args[0])){
    const song_info = await ytdl.getInfo(args[0]);
    song = {title: song_info.videoDetails.title, url: song_info.videoDetails.video_url};
} else{
    const video_finder = async(query) =>{
        const videoResult = await ytSearch(query);
        return (videoResult.videos.length > 1) ? videoResult.videos[0] : null;
    }
    const video = await video_finder(args.join(' '));
    if(video){
        song = {title: video.title, url: video.url}
    } else{
        return message.reply('Error finding vdieo.')
    }
}

The first if statement determines if the argument that defines the song is a link or a search term. If it isn't a URL then I use the yt-search module to get the first result and the title and URL of the result.


Solution

Ditched yt-search for youtube-sr. This new module doesn't spike the CPU and can be configured to only pull the first result.

if(ytdl.validateURL(args[0])){
    const song_info = await ytdl.getInfo(args[0]);
    song = {title: song_info.videoDetails.title, url: song_info.videoDetails.video_url};
} else{
    const video_finder = async(query) =>{
        const res = await ytSearch.search(query, {limit: 1, type: 'video'}).catch(e =>{});
        if(!res || !res[0]) return
        const videoResult = res[0];
        return (videoResult.title.length > 1) ? videoResult : null;
    }
    const video = await video_finder(args.join(' '));
    if(video){
        song = {title: video.title, url: video.url};
    } else{
        return message.reply('Error finding video.');
    }
}


Answered By - Liam Brewer
Answer Checked By - David Marino (WPSolving Volunteer)