Home > Back-end >  Trying to get the username of the user that runs the ping command and log it
Trying to get the username of the user that runs the ping command and log it

Time:12-25

const TOKEN = "mybotstoken";
const CLIENT_ID = "mybotsclientid";

const { REST, Routes } = require('discord.js');

const commands = [
  {
    name: 'ping',
    description: 'Replies with Pong!',
  },
];

const rest = new REST({ version: '10' }).setToken(TOKEN);

(async () => {
  try {
    console.log('Started refreshing application (/) commands.');

    await rest.put(Routes.applicationCommands(CLIENT_ID), { body: commands });

    console.log('Successfully reloaded application (/) commands.');
  } catch (error) {
    console.error(error);
  }
})();

const { Client, GatewayIntentBits } = require('discord.js');
const client = new Client({ intents: [GatewayIntentBits.Guilds] });

client.on('ready', () => {
  console.log(`Logged in as ${client.user.tag}!`);
});

client.on('interactionCreate', async interaction => {
  if (!interaction.isChatInputCommand()) return;

  if (interaction.commandName === 'ping') {
    const user = interaction.author;

    const username = user.username;
    console.log(`Got a ping execute request from: ${username}`);

    await interaction.reply('Pong!');
    console.log(`Execute succesful`);
  }
});

client.login(TOKEN);

What's wrong with this code?

I'm getting the error: TypeError: Cannot read properties of undefined (reading 'username')

CodePudding user response:

It's because there is no interaction.author. You probably thought that it's like message.author. There is an interaction.user or an interaction.member, so you can use the former if you want to get the author's username:

const username = interaction.user.username;
  • Related