【问题标题】:Permission Error Handler - Bot Crashes how to use try catch properly权限错误处理程序 - Bot 崩溃如何正确使用 try catch
【发布时间】:2020-08-28 04:43:28
【问题描述】:

我想要它,因此我的机器人只能在授予权限的特定频道中发送嵌入,但如果用户在未授予权限的频道中发送消息,机器人将停止工作并切断。我正在尝试使它起作用,因此即使抛出错误它也会继续工作,我得到的错误是“UnhandledPromiseRejectionWarning: DiscordAPIError: Missing Permissions - 我希望能够忽略这个错误。

function catchErr (err, emessage, a){
console.log("Someone tried to use the embed in the");}




    let args = message.content.slice(PREFIX.length).split(' ');

    switch(args[0]){
        case 'discordbot ':
            try {
            const discordbot = new Discord.MessageEmbed()
            .setTitle('My Discord Bot*')
            .addFields(
                { name: 'Test Bot:', value: 'Test' },
            message.channel.send(discordbot );
        } catch (err) {
            catchErr(err, message);
        }

【问题讨论】:

    标签: discord.js


    【解决方案1】:

    .send 返回一个Promise,如果你想捕获错误,你可以选择Promise.catch 或使用async / await(这需要你的顶级函数是异步的)

    // Using Promise.catch
    const catchErr = err => {
      console.log(err)
    }
    
    message.channel.send(embed).catch(catchErr)
    
    // Using async / await
    try {
      await message.channel.send(embed)
    } catch(err) {
      catchErr(err)
    }
    

    【讨论】:

      【解决方案2】:
      function sendMessage(message,content){
              const permissions = message.channel.permissionsFor(message.client.user);
              if (permissions.has("SEND_MESSAGES")){
                  if(content){
                      message.channel.send(content);
                  }
              }
              else{
                  console.log("[ERR] no msg perms")
                  message.author.send("I can't send messages on this channel or guild!, Try another channel or contact the server staff to check bot's permissions.");
              }
          }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-04-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多