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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 17:37:41