generated at
送られた画像ファイルをオウム返しする
メッセージに添付ファイルがあるか調べ、画像だったら埋め込みに画像URLを入れて送信するというもの
message.attachments.first() で添付ファイルを取得している。無かったら undefined が返ってくる。
if (!file) return で添付ファイルが無かった場合は無視している。
if (!file.height && !file.width) return は画像ファイルであるかを調べている。
MessageAttachmentクラスにある height width は添付ファイルが画像である場合に number が入るのでそれを利用している。
画像ファイルでない場合、 height width には null が入っている。
message.channel.send({ embeds: [{ image: { url: file.url } }] }) で埋め込みに添付ファイルのURLを入れて送信
注意:Discord APIにファイルの種類を判別する方法がなくて、画像か動画のときだけあるheightとかを使っているだけなので、これだけだと動画にも反応してしまう

js
const Discord = require('discord.js') const client = new Discord.Client({ intents: // ... }) client.on('messageCreate', message => { const file = message.attachments.first() if (!file) return // 添付ファイルがなかったらスルー if (!file.height && !file.width) return // 画像じゃなかったらスルー return message.channel.send({ embeds: [{ image: { url: file.url } }] }) }) client.login('Your token.')

MessageAttachment#contentType にはmimeが格納されている。
image で始まっていれば画像であると判断してよいだろう。
js
const Discord = require('discord.js') const client = new Discord.Client( { intents: Discord.Intents.FLAGS.GUILD_MESSAGES|Discord.Intents.FLAGS.GUILDS } ) client.on('messageCreate', message => { const file = message.attachments.first() if (!file) return // 添付ファイルがなかったらスルー if (!file.height && !file.width) return if (!file.contentType?.startsWith("image")) return return message.channel.send({ embeds: [{ image: { url: file.url } }] }) }) client.login('Your token.')

関連