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

How to show number of registered users in Laravel based on usertype?

i'm trying to display data from the database in the admin dashboard i used this: <?php use Illuminate\Support\Facades\DB; $users = DB::table('users')->count(); echo $users; ?> and i have successfully get the correct data from the database but what if i want to display a specific data for example in this user table there is "usertype" that specify if the user is normal user or admin i want to user the same code above but to display a specific usertype i tried this: <?php use Illuminate\Support\Facades\DB; $users = DB::table('users')->count()->WHERE usertype =admin; echo $users; ?> but it didn't work, what am i doing wrong? source https://stackoverflow.com/questions/68199726/how-to-show-number-of-registered-users-in-laravel-based-on-usertype

Why is my reports service not connecting?

I am trying to pull some data from a Postgres database using Node.js and node-postures but I can't figure out why my service isn't connecting. my routes/index.js file: const express = require('express'); const router = express.Router(); const ordersCountController = require('../controllers/ordersCountController'); const ordersController = require('../controllers/ordersController'); const weeklyReportsController = require('../controllers/weeklyReportsController'); router.get('/orders_count', ordersCountController); router.get('/orders', ordersController); router.get('/weekly_reports', weeklyReportsController); module.exports = router; My controllers/weeklyReportsController.js file: const weeklyReportsService = require('../services/weeklyReportsService'); const weeklyReportsController = async (req, res) => { try { const data = await weeklyReportsService; res.json({data}) console...

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...