ユーザーメニューを使ってavatarをembedに埋め込んで表示するサンプル
https://gyazo.com/b5aca85a56c83eb04c8f479fdf9d3ccd
code:js
const Discord = require("discord.js");
const client = new Discord.Client({
intents: 0
});
const GUILD_ID = "494780225280802817"; // command deployed to global if undefined
async function on_ready() {
await client.application.commands.set([
{
type: "USER",
name: "get user avatar"
}
], GUILD_ID);
}
const imageOptions = {
dynamic: true,
format: "webp",
size: 4096
};
/**
*
* @param {Discord.ContextMenuInteraction} interaction
*/
async function on_context_menu_interaction(interaction) {
const member = interaction.options.getMember("user");
const user = member.user;
const embeds = [
new Discord.MessageEmbed().setImage(user.displayAvatarURL(imageOptions)).setTitle(${user.username}(user))
];
const guildAvatarURL = member.avatarURL(imageOptions);
if(guildAvatarURL){
embeds.push(new Discord.MessageEmbed().setImage(guildAvatarURL).setTitle(${member.displayName}(guild)));
}
await interaction.reply({
embeds
});
}
/**
*
* @param {Discord.Interaction} interaction
*/
async function on_interaction(interaction) {
if (!interaction.isContextMenu()) {
return;
}
await on_context_menu_interaction(interaction);
}
client.on("ready", () => {
on_ready().catch(err => console.error(err));
});
client.on("interactionCreate", (interaction) => {
on_interaction(interaction).catch(err => console.error(err));
});
client.login("THE UNIQUE TOKEN");
解説
interaction.options.getUser("user")
選択されたユーザーあるいはメンバーのUserオブジェクトはこのように取得する
interaction.options.getMember("user")
このようにすることで、Guild内で実行されたならば、GuildMemberオブジェクトを取得することもできる
code:js
const {
Client,
GatewayIntentBits,
EmbedBuilder,
ContextMenuCommandBuilder,
ApplicationCommandType,
REST,
Routes
} = require("discord.js");
const client = new Client({
intents: [
//...
]
});
const token = process.env.token;
client.on("ready", async () => {
const rest = new REST({ version: '10' }).setToken(token);
await rest.put(
Routes.applicationCommands(client.user.id),
{
body: [
new ContextMenuCommandBuilder()
.setName("get user avatar")
.setType(ApplicationCommandType.User)
]
}
);
});
client.on("interactionCreate", (interaction) => {
if (interaction.isUserContextMenuCommand()){
if (interaction.commandName === "get user avatar"){
const user = interaction.options.getUser("user");
const avatarURL = user.displayAvatarURL(
{
dynamic: true,
format: "webp",
size: 4096
}
);
return interaction.reply({
embeds: [
new EmbedBuilder()
.setTitle(user.tag)
.setImage(avatarURL)
]
});
};
};
});
client.login(token);