首页 > 解决方案 > 如何获取附件的链接 Discord.js

问题描述

嘿,所以我正在尝试获取不和谐图像的链接但是当我尝试时,它会吐出错误:

    (node:248) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'url' of undefined
    at Object.module.exports.run (C:\Users\nafiu\OneDrive\Desktop\Bots\Glitchz Bot\commands\rankbackground.js:11:123)
    at Client.<anonymous> (C:\Users\nafiu\OneDrive\Desktop\Bots\Glitchz Bot\events\message.js:24:37)
    at processTicksAndRejections (internal/process/task_queues.js:93:5)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:248) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:248) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

这是我的代码:

let fs = require("fs");
const Discord = require("discord.js");
const { Client, MessageAttachment, MessageEmbed } = require("discord.js");
const RankBackgroundModel = require('../models/rankbackground')

module.exports.run = async (client, message, args) => {
    
    const Attachment = (message.attachments).array();
    if(!Attachment) return message.reply('You Didnt Upload a Image to make it your custom rank background')

    const doc = await RankBackgroundModel.findOneAndUpdate({ id: message.author.id }, { $set: { Background: Attachment[0].url} }, {new: true});
    return message.reply('Sucsessfuly Set Rank Background to' + Attachment[0].url)
}

module.exports.help = {
  name: "rankbackground"
}

标签: javascriptnode.jsdiscorddiscord.jsattachment

解决方案


如果您至少上传一个附件,您的代码就可以工作,但我假设您没有上传任何附件。

您收到错误的原因Attachment是空的(因此Attachemnt[0]未定义),因为以下 if 语句失败:

if(!Attachment) return message.reply('You Didnt Upload a Image to make it your custom rank background')

这是因为[]or {}(空数组/对象) 是thruthy.


您的代码将不得不检查数组的大小。如果为 0,则邮件中没有附件。

let fs = require("fs");
const Discord = require("discord.js");
const { Client, MessageAttachment, MessageEmbed } = require("discord.js");
const RankBackgroundModel = require("../models/rankbackground");

module.exports.run = async (client, message, args) => {
    const Attachment = message.attachments.array();
    if (Attachment.length === 0) return message.reply("You Didnt Upload a Image to make it your custom rank background");

    const doc = await RankBackgroundModel.findOneAndUpdate({ id: message.author.id }, { $set: { Background: Attachment[0].url } }, { new: true });
    return message.reply("Sucsessfuly Set Rank Background to" + Attachment[0].url);
};

module.exports.help = {
    name: "rankbackground",
};

推荐阅读