Issue with sending automatic replies in Discord bot for breaking news updates
Tags: webdev, node, discord, automation
Published: 2023-05-30 18:45:00

Automated Replies In Discord.js is Not Working As Expected

I'm working on a Discord bot using the Discord.js library in Node.js, and I'm facing an issue with the automatic replies functionality. The bot is designed to fetch breaking news from a website every few seconds and send it to a specific channel in a Discord server. However, the automatic replies for breaking news updates are not working as expected.

Here's an overview of the functionality:

The bot fetches breaking news from a website using Axios and Cheerio. The fetched breaking news is stored in an array. There is a specific channel in a Discord server where the bot is supposed to send the breaking news updates automatically. The bot uses the message.reply method to send the breaking news updates as replies in the channel. The bot is able to receive commands and respond appropriately, such as when a user sends a message with the content "news", the bot fetches the breaking news from the array and sends it as replies in the channel. However, the issue arises when trying to send the breaking news updates automatically every 10 seconds. The expected behavior is for the bot to send the breaking news updates using the message.reply method in the specific channel. But no automatic replies are being sent by the bot, even though all other parts of the code are working fine.

I've confirmed that the target channel ID is correct and the bot has the necessary permissions (including sending messages) in that channel. I've also tested other parts of the code, such as fetching breaking news and responding to user commands, and they work without any issues.

I'm using the latest version of Discord.js and have checked the documentation and examples, but I couldn't find a solution to this issue. I suspect there might be a problem with the implementation of the setInterval function or the usage of message.reply within it. I've included the relevant portions of my code below for reference:
`const axios = require('axios');
const cheerio = require('cheerio');
const express = require('express');
const cron = require('node-cron');

const { Client, GatewayIntentBits } = require('discord.js');

const bot = new Client({
  intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildMessages, GatewayIntentBits.MessageContent],
});
const app = express();
const port = process.env.PORT || 5000;
const url = 'URL I can not mention because of privacy agreement';

let breakingNews = [];
let promptNews = [];
let targetGuildId = null;



const fetchData = async () => {
  try {
    const res = await axios.get(url);

    const data = cheerio.load(res.data);
    let updatedBreakingNews = [];
    let updatedPromptNews = [];

    // Scrape breaking news section
    const breakingNewsElement1 = data('#fusion-app > div.high-impact-vertstyles__StickyHighImpactLayoutWrapperStyled-cuy9q8-1.hPdtnJ > div.layout-container > div > main > div > section:nth-child(2) > div > div.leaderboard > div > div:nth-child(2) > div > div > div:nth-child(2)');
    const breakingNewsElement2 = data('#fusion-app > div.high-impact-vertstyles__StickyHighImpactLayoutWrapperStyled-cuy9q8-1.hPdtnJ > div.layout-container > div > main > div > section:nth-child(2) > div > div.leaderboard > div > div:nth-child(2) > div > div > div.side-cover-cardstyles__SideCoverCardWrapper-sc-1nd3s5z-0.drWEWC');
    const breakingNewsElement3 = data('#fusion-app > div.high-impact-vertstyles__StickyHighImpactLayoutWrapperStyled-cuy9q8-1.hPdtnJ > div.layout-container > div > main > div > section:nth-child(2) > div > div.leaderboard > div > div:nth-child(2) > div > div > div:nth-child(4)');
    const breakingNewsElement4 = data('#fusion-app > div.high-impact-vertstyles__StickyHighImpactLayoutWrapperStyled-cuy9q8-1.hPdtnJ > div.layout-container > div > main > div > section:nth-child(2) > div > div.leaderboard > div > div:nth-child(2) > div > div > div:nth-child(5)');

    const breakingNewsElements = [breakingNewsElement1, breakingNewsElement2, breakingNewsElement3, breakingNewsElement4];

    breakingNewsElements.forEach((breakingNewsElement) => {
      breakingNewsElement.each((i, e) => {
        const title = data(e).text().trim();
        const link = data(e).find('a').attr('href');
        updatedBreakingNews.push({ title, link });
      });
    });

    // Scrape prompt news section
    const promptNewsElement = data('#fusion-app > div.high-impact-vertstyles__StickyHighImpactLayoutWrapperStyled-cuy9q8-1.hPdtnJ > div.layout-container > div > main > div > section:nth-child(2) > div > div.leaderboard > div > div:nth-child(2) > div > div > div.featured-cardstyles__FeaturedCardWrapper-caozbq-2.gtlGpD');
    promptNewsElement.each((i, e) => {
      const title = data(e).text().trim();
      const link = data(e).find('a').attr('href');
      updatedPromptNews.push({ title, link });
    });

    breakingNews = updatedBreakingNews;
    promptNews = updatedPromptNews;
  } catch (e) {
    console.log(e);
  }
};

// Fetch data initially
fetchData();

app.get('/breaking-news', (req, res) => {
  res.send(breakingNews);
});

app.get('/prompt-news', (req, res) => {
  res.send(promptNews);
});

app.listen(port, () => console.log('Server started'));

bot.on('ready', () => {
  console.log(`Logged in as ${bot.user.tag}`);
});

bot.on('messageCreate', async (message) => {
  if (message.content.toLowerCase() === 'news' && !targetGuildId) {
    targetGuildId = message.guildId;
    message.reply({ content: 'This server will receive automatic news updates.' });
  }

  if (message.content.toLowerCase() === 'stop news' && message.guildId === targetGuildId) {
    targetGuildId = null;
    message.reply({ content: 'Automatic news updates have been stopped for this server.' });
  }

  if (message.content.toLowerCase() === 'news' && message.guildId === targetGuildId) {
    try {
      const response = await axios.get('http://localhost:5000/breaking-news');
      const newsData = response.data.map((breakingNewsItem) => `${breakingNewsItem.title}\n${url}${breakingNewsItem.link}`);
      newsData.forEach((data) => {
        message.reply({ content: `Latest news highlights:\n\n${data}` });
      });
    } catch (error) {
      console.error(error);
      message.reply('An error occurred while fetching the news highlights.');
    }
  }
});

// Function to send prompt news as automated replies
// Function to send prompt news as automated replies
const sendPromptNews = async () => {
  if (targetGuildId) {
    const guild = bot.guilds.cache.get(targetGuildId);
    if (guild) {
      const channel = guild.channels.cache.find((channel) => channel.type === 'text' && channel.id === '1111638079103574159');
      if (channel) {
        try {
          const response = await axios.get('http://localhost:5000/prompt-news');
          const newsData = response.data.map((promptNewsItem) => `${promptNewsItem.title}\n${url}${promptNewsItem.link}`);
          newsData.forEach((data) => {
            channel.send(`Breaking Automatic News:\n\n${data}`);
          });
        } catch (error) {
          console.error(error);
          channel.send('An error occurred while fetching the news highlights.');
        }
      }
    }
  }
};

// Schedule the automatic prompt news every 10 seconds
cron.schedule('*/10 * * * * *', () => {
  sendPromptNews();
});




bot.login('my bot token');`
I tried everything but failed anyone please help!