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

Confusion between commands.Bot and discord.Client | Which one should I use?

Whenever you look at YouTube tutorials or code from this website there is a real variation. Some developers use client = discord.Client(intents=intents) while the others use bot = commands.Bot(command_prefix="something", intents=intents) . Now I know slightly about the difference but I get errors from different places from my code when I use either of them and its confusing. Especially since there has a few changes over the years in discord.py it is hard to find the real difference. I tried sticking to discord.Client then I found that there are more features in commands.Bot . Then I found errors when using commands.Bot . An example of this is: When I try to use commands.Bot client = commands.Bot(command_prefix=">",intents=intents) async def load(): for filename in os.listdir("./Cogs"): if filename.endswith(".py"): client.load_extension(f"Cogs.{filename[:-3]}") The above doesnt giveany response from my Cogs ...

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