You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

如何在Discord机器人的-dm命令中使用用户ID替代@提及用户

Solution: Modify -dm Command to Use User IDs Instead of Mentions

Absolutely! You can absolutely tweak your -dm command to support user IDs (and even keep mention support as a fallback if you want) to avoid pinging users. This is a straightforward change using Discord.js's client.users.fetch() method, which lets you retrieve users by their unique ID without triggering a ping.

Modified Code

const Discord = require('discord.js')
module.exports = {
 name: 'dm',
 description: 'DMs a user via mention or User ID',
 // Mark execute as async to use await for user fetching
 async execute(client, msg, args) {
  // Keep admin permission check unchanged
  if(!msg.member.permissions.has("ADMINISTRATOR")) return msg.channel.send("You cannot do that!")
  
  let targetUser;
  const userId = args[0];

  // First attempt: Fetch user by ID from the first argument
  if (userId) {
    try {
      // Fetch user by ID (works even if they're not in the current server)
      targetUser = await client.users.fetch(userId);
    } catch (error) {
      // If ID is invalid, fall back to checking for a mentioned user
      targetUser = msg.mentions.users.first();
    }
  } else {
    // No ID provided, use mention as fallback
    targetUser = msg.mentions.users.first();
  }

  // Handle case where no valid user was found
  if(!targetUser) return msg.channel.send("That user ID is invalid, or no user was mentioned!")

  // Extract message content (skip first argument which is ID/mention)
  const str = args.slice(1).join(" ")
  if (!str) return msg.channel.send("You need to provide a message to send!") // Prevent empty DMs

  try {
    // Send the DM to the target user
    await targetUser.send(str)
    msg.channel.send("Message sent to the user!")

    // Log the DM with enhanced details
    const dmLogger = new Discord.MessageEmbed()
    .setTitle("DM Sent")
    .setColor("RANDOM")
    .addField("MESSAGE SENT BY", msg.author.tag)
    .addField("MESSAGE SENT TO", `${targetUser.tag} (ID: ${targetUser.id})`) // Include ID for traceability
    .addField("MESSAGE CONTENT", str)
    .setTimestamp()
    client.channels.cache.get('CENSORED_2.0').send(dmLogger)
  } catch (error) {
    // Handle cases where DM fails (user has DMs disabled, blocked bot, etc.)
    msg.channel.send("Failed to send the message—this user may have DMs disabled or blocked the bot.")
    console.error("DM send error:", error)
  }
 }
}

Key Changes Explained

  • ID-first priority: The command now tries to use the first argument as a user ID first. If that fails (invalid ID), it falls back to checking for a mentioned user.
  • client.users.fetch(): This method retrieves a user object using their ID, even if they aren't in the same server as the command is run in (works for any valid Discord user ID the bot can access).
  • Async/await support: Marked the execute function as async to handle the asynchronous fetch() call properly.
  • Improved error handling: Added try/catch blocks to handle invalid IDs and failed DM attempts (like when a user has DMs disabled).
  • Empty message check: Added a guard clause to prevent sending blank DMs.
  • Enhanced logging: Included the user's ID in the log embed for better traceability.

Usage Examples

  • Using User ID (no ping): -dm 123456789012345678 Hey there!
  • Using Mention (still works as fallback): -dm @Omega Hello!

This approach eliminates unwanted pings when using the ID method, which should resolve the annoyance your users mentioned while keeping the command flexible.

内容的提问来源于stack exchange,提问作者Omega

火山引擎 最新活动