Quantcast
Channel: Active questions tagged youtube-api - Stack Overflow
Viewing all articles
Browse latest Browse all 3638

Optimizing Youtube-api calls

$
0
0

I am using discord.js running in Node.js to create a Discord bot that checks if a YouTube channel has a new video on it. I'm using the API to perform these checks every half an hour. Before the day ends, my API calls run out, and I can no longer check, resulting in a large JSON error response.

In my code, it fetches the information and stores it in a database. When it checks the YouTube channel again, if the video is new, it records it in the database and publishes the video.

> const { Client, EmbedBuilder } = require("discord.js");> const axios = require("axios");> require("dotenv").config();> const key = process.env.youtube;> const channelAnnouncement = "1144157374773473403";> > const channelIds = [>   "UCZ-yZV4JKOewGZAJSqs2V0w", // Por um punhado de dados.>   "UCF1BfG8XJb9m6g96vn76G6A", // variedados>   "UCCkIJHK5KYpWb58YyAqTWKg", // GURPS na veia>   "UC4-7okrLZK2sfwINnqZNVog", // Chris Normand>   "UCRhm02S_o1oktdjfj6JTlTA" // n sei se eu quero isso....> Adicione mais IDs de canal conforme necessário> ];> > const Video = require("../schema/youtubeSchema");> > async function youtube(client) {> try {> for (const channelId of channelIds) {> const video = await getLatestVideo(channelId);> > Extrair informações do vídeo> const videoTitle = video.snippet.title;> const videoUrl = `https://www.youtube.com/watch?v=${video.id.videoId}`;> const channelTitle = video.snippet.channelTitle;> const videoDescription = video.snippet.description; // Adicionando descrição do vídeo> const channelThumbnail = video.snippet.thumbnails.default.url; // Miniatura do canal> const videoThumbnail => video.snippet.thumbnails.maxres?.url ||> video.snippet.thumbnails.high?.url ||> video.snippet.thumbnails.medium?.url ||> video.snippet.thumbnails.default.url;> > Verificar se o vídeo já existe na base de dados> const existingVideo = await Video.findOne({ videoUrl });> > if (!existingVideo) {> Se não existir, adicione-o à base de dados> const newVideo = new Video({> videoTitle,> videoUrl,> channelTitle,> videoThumbnail,> videoDescription,> channelThumbnail,>         });> await newVideo.save();> console.log(" 💡 Novo vídeo adicionado à base de dados:");> console.log("Nome do Canal:", channelTitle);> const embed = new EmbedBuilder(); // Certifique-se de que está usando a classe EmbedBuilder corretamente> embed>           .setColor(0x5506ce)>           .setDescription(`${videoDescription}`)>           .setThumbnail(`${channelThumbnail}`)>           .setURL(`${videoUrl}`)>           .setTitle(`${videoTitle}`)>           .setImage(`${videoThumbnail}`);> > Enviar a mensagem para o canal de anúncios> const channel = client.channels.cache.get(channelAnnouncement);> > channel.send({ embeds: [embed] }).catch((error) => {> console.error("⛔ Erro ao enviar embed:", error);>         });> console.log("💡 Vídeo enviado.");> else {> Se já existir, compare o título para verificar se o vídeo é diferente> if (existingVideo.videoTitle !== videoTitle) {> Atualize o vídeo na base de dados> existingVideo.videoTitle = videoTitle;> existingVideo.save();> else {> console.log(> Vídeo já existe na base de dados e não foi alterado.">           );>         }>       }>     }> catch (error) {> console.error("⛔ Erro na função principal:", error);>   }> }> > async function getLatestVideo(channelId) {> const url = `https://www.googleapis.com/youtube/v3/search?key=${key}&channelId=${channelId}&part=snippet,id&order=date&maxResults=1`;> const response = await axios.get(url);> const latestVideo = response.data.items[0];> return latestVideo;> }> > module.exports = {> youtube,> };> > the timer is in the main.j triggering in 30 minutes cycle. My questions are:1- Is there a way to optimize and use the API more effectively to perform more checks throughout the day?2- When the JSON error is returned, how can I do it in a way that makes it easier to read the error content?

Viewing all articles
Browse latest Browse all 3638

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>