NodeJS DiscordJS DiscordAPIError[50013]

edqdpe6u  于 12个月前  发布在  Node.js
关注(0)|答案(1)|浏览(130)

我想发送一条消息到一个通道,这里是我的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);
  }
}

字符串
我的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);
  }
}


这是错误信息

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'
}


我所有的代码woked罚款昨天,所以我不知道为什么有一个错误(我没有添加任何权限,这里是我用来邀请机器人https://discord.com/api/oauth2/authorize?client_id=1172365624790499388&permissions=137439464512&scope=bot的链接
当我在main函数中使用函数sendNotif()时,错误不会发生。
我使用nodejs版本16.16.0和discord.js版本^14.14.1
编辑:现在似乎工作,但我不做任何事情,所以idk

0yg35tkg

0yg35tkg1#

这不是代码的问题,而是机器人托管的服务器的问题。
我的意思是:
从错误消息中可以清楚地看到,机器人没有发送消息的权限(或者在那里正在做什么,我没有完全弄清楚)。

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

字符串
403状态也表明了这一点
第一个月
1.检查机器人的权限。很有可能机器人根本没有向该通道发送消息的权限
1.检查频道ID。也有可能是你的ID出错了,因此机器人没有真相。

相关问题