Search code examples
javascriptnode.jsdiscord.js

DiscordJS DiscordAPIError[50013]


I want to send a message to a channel here is my index.js

const json = require('./jsonEdit.js');
const discordBot = require('./discordBot.js')
const youtubeAPI = require('./youtubeAPI.js')
const server = require('./httpServer.js')
let intervalId = 0 

let link = ''

const main = async () => {
  var config = json.readJsonFile('./config.json');
  try {
    result = await json.updateData('./config.json', await youtubeAPI.getChannelIDByUrl(config.YOUTUBE_CHANNEL_LINK));
    config = result.config
  } catch (error) {
    console.error('Error updating config:', error);
    config = null
  }
  if(config == null) {
    return
  }
  await discordBot.start(json)
  await server.start(json)
  intervalId = setInterval(() => aprilFool(json), 1000); // Check every second, adjust as needed
  process(json)
  setInterval(() => process(json), config.INTERVAL);
}

main()


async function process(json) { 
  let res = await youtubeAPI.isInLive(json)
  var config = json.readJsonFile('./config.json');
  if(res != null) {
    link = config.MESSAGE.replace("${liveVideoLink}",res.liveLink)
    try {
      discordBot.sendNotif(config.DISCORD_ANNONCE_CHANNEL_ID, link);
      console.log("Message sent successfully");
    } catch (error) {
      console.error("Error sending message:", error);
    }
  }
}

function aprilFool(json) {
  var config = json.readJsonFile('./config.json');
  // Specify the date and time when you want the function to run
  const currentYear = new Date().getUTCFullYear();
  const targetDate = new Date(`${currentYear}-04-01T17:05:00`); // Change this to your desired date and time
  const currentDate = new Date();
  if (currentDate.getDay == targetDate.getDate && currentDate.getHours == targetDate.getHours) {
    // Call your function
    discordBot.sendNotif(config.DISCORD_ANNONCE_CHANNEL_ID, config.MESSAGE.replace("${liveVideoLink}", "<https://www.youtube.com/watch?v=dQw4w9WgXcQ>"))

    // Clear the interval after the function is executed
    clearInterval(intervalId);
  }
}

my discordBot.js

const Discord = require("discord.js");
const reg = require('./regex.js')

var running = false

const client = new Discord.Client(
    {
      intents: [
        Discord.GatewayIntentBits.Guilds,
        Discord.GatewayIntentBits.GuildMessages,
        Discord.GatewayIntentBits.MessageContent
      ],
      disableEveryone: false
    }
);

exports.start = async (json) => {
    let config = json.readJsonFile('./config.json');
    return new Promise((resolve) => {

        var regArr = [ 
            { regExp : reg.generateRegexForSuffixes(reg.generateWordVariations("quoi")), reply : "feur" },
            { regExp : reg.generateRegexForSuffixes(reg.generateWordVariations("feur")), reply : "ouge" }
        ]

        client.login(config.TOKEN);
    
        client.on('ready', () => {
            console.log(`Logged in as ${client.user.tag}!`);
            running = true;
            resolve(); // Resolve the promise when running becomes true
        });
  
        client.on("messageCreate", (message) => {
            if(message.author.bot) {
                return
            }
            for (let index = 0; index < regArr.length; index++) {
                const element = regArr[index];
                if(element.regExp.test(message.content)) {
                    console.log(`replyed : ${element.reply}`)
                    message.reply(element.reply)
                    break
                }
            }
        })
    
        // Periodically check the condition and resolve the promise if running is true
        const checkRunning = () => {
            if (running) {
                resolve();
            } else {
                setTimeout(checkRunning, 1000); // Check again after 1 second
            }
        };
        checkRunning();
    });
}

exports.sendNotif = (channelId, message) => {
  try {
    client.channels.cache.get(channelId).send(message)
    console.log("Message sent successfully");
  } catch (error) {
    console.error("Error sending message:", error);
  }
}

and here is the error message

D:\Dev\VisualStudioCode\MutaTeam\Bot Muta live\node_modules\@discordjs\rest\dist\index.js:722
      throw new DiscordAPIError(data, "code" in data ? data.code : data.error, status, method, url, requestData);
            ^

DiscordAPIError[50013]: Missing Permissions
    at handleErrors (D:\Dev\VisualStudioCode\MutaTeam\Bot Muta live\node_modules\@discordjs\rest\dist\index.js:722:13)
    at processTicksAndRejections (node:internal/process/task_queues:96:5)
    at async SequentialHandler.runRequest (D:\Dev\VisualStudioCode\MutaTeam\Bot Muta live\node_modules\@discordjs\rest\dist\index.js:1120:23)
    at async SequentialHandler.queueRequest (D:\Dev\VisualStudioCode\MutaTeam\Bot Muta live\node_modules\@discordjs\rest\dist\index.js:953:14)
    at async _REST.request (D:\Dev\VisualStudioCode\MutaTeam\Bot Muta live\node_modules\@discordjs\rest\dist\index.js:1266:22)
    at async NewsChannel.send (D:\Dev\VisualStudioCode\MutaTeam\Bot Muta live\node_modules\discord.js\src\structures\interfaces\TextBasedChannel.js:155:15) {
  requestBody: {
    files: [],
    json: {
      content: 'La Muta Team est en live ! Venez les regarder juste https://www.youtube.com/watch?v=ycXvX9hcljk.',
      tts: false,
      nonce: undefined,
      embeds: undefined,
      components: undefined,
      username: undefined,
      avatar_url: undefined,
      allowed_mentions: undefined,
      flags: undefined,
      message_reference: undefined,
      attachments: undefined,
      sticker_ids: undefined,
      thread_name: undefined
    }
  },
  rawError: { message: 'Missing Permissions', code: 50013 },
  code: 50013,
  status: 403,
  method: 'POST',
  url: 'https://discord.com/api/v10/channels/974116558219645008/messages'
}

all my code woked fine yesterday so i don't know why is there an error (i don't add any permission and here is the link i used to invite the bot https://discord.com/api/oauth2/authorize?client_id=1172365624790499388&permissions=137439464512&scope=bot

the error doesn't occure when i use the function sendNotif() in the main function.

I use nodejs version 16.16.0 and discord.js version ^14.14.1

Edit : Seems to work now but i don't do anything so idk


Solution

  • This is not really a problem with the code, but with the server on which the bot is hosted.

    What I mean:
    It is clear from the error message that the bot does not have the rights to send a message (or what is being done there, I did not quite figure it out).

    rawError: { message: 'Missing Permissions', code: 50013 },
    

    This is also indicated by the 403 status

    status: 403

    1. Check the rights of the bot. It is quite possible that the bot simply does not have the rights to send messages to that channel

    2. Check the Channel ID. It is also possible that you made a mistake with the id and therefore the bot does not have the truth