Skip to main content

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

Via Active questions tagged javascript - Stack Overflow https://ift.tt/aVhrA5x

Comments

Popular posts from this blog

ValueError: X has 10 features, but LinearRegression is expecting 1 features as input

So, I am trying to predict the model but its throwing error like it has 10 features but it expacts only 1. So I am confused can anyone help me with it? more importantly its not working for me when my friend runs it. It works perfectly fine dose anyone know the reason about it? cv = KFold(n_splits = 10) all_loss = [] for i in range(9): # 1st for loop over polynomial orders poly_order = i X_train = make_polynomial(x, poly_order) loss_at_order = [] # initiate a set to collect loss for CV for train_index, test_index in cv.split(X_train): print('TRAIN:', train_index, 'TEST:', test_index) X_train_cv, X_test_cv = X_train[train_index], X_test[test_index] t_train_cv, t_test_cv = t[train_index], t[test_index] reg.fit(X_train_cv, t_train_cv) loss_at_order.append(np.mean((t_test_cv - reg.predict(X_test_cv))**2)) # collect loss at fold all_loss.append(np.mean(loss_at_order)) # collect loss at order plt.plot(np.log(al...

Sorting large arrays of big numeric stings

I was solving bigSorting() problem from hackerrank: Consider an array of numeric strings where each string is a positive number with anywhere from to digits. Sort the array's elements in non-decreasing, or ascending order of their integer values and return the sorted array. I know it works as follows: def bigSorting(unsorted): return sorted(unsorted, key=int) But I didnt guess this approach earlier. Initially I tried below: def bigSorting(unsorted): int_unsorted = [int(i) for i in unsorted] int_sorted = sorted(int_unsorted) return [str(i) for i in int_sorted] However, for some of the test cases, it was showing time limit exceeded. Why is it so? PS: I dont know exactly what those test cases were as hacker rank does not reveal all test cases. source https://stackoverflow.com/questions/73007397/sorting-large-arrays-of-big-numeric-stings

How to load Javascript with imported modules?

I am trying to import modules from tensorflowjs, and below is my code. test.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title </head> <body> <script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@2.0.0/dist/tf.min.js"></script> <script type="module" src="./test.js"></script> </body> </html> test.js import * as tf from "./node_modules/@tensorflow/tfjs"; import {loadGraphModel} from "./node_modules/@tensorflow/tfjs-converter"; const MODEL_URL = './model.json'; const model = await loadGraphModel(MODEL_URL); const cat = document.getElementById('cat'); model.execute(tf.browser.fromPixels(cat)); Besides, I run the server using python -m http.server in my command prompt(Windows 10), and this is the error prompt in the console log of my browser: Failed to loa...