首页 > 解决方案 > 已解决:使用 ID 对特定用户进行 DMing

问题描述

我经历了其他问题试图找到答案并得出以下代码:

let Prayer = message.member.user.tag;
bot.users.cache.get("my_id").send("My goddess, " + Prayer + " has sent you a prayer!");

但是,我收到此错误:

TypeError: Cannot read property 'send' of undefined

我不知道它为什么这么说,因为它也适用于其他人。有人能帮我吗?

编辑:

现在是新代码

const Discord = require("discord.js");
const bot = new Discord.Client();
let Prayer = message.member.user.tag;
async function SendingPray() {
      message.reply("Test3");
      const Yuuki = await bot.users.fetch('715912580127785060');
      message.reply("Test4");
      console.log(Yuuki);
      message.reply("Test5");
      Yuuki.send("Testing");
      message.reply("Test6");
};
SendingPray();
message.reply("your pray has been sent. The goddess will read your pray and decide your fate!");

它到达了Test3,但之后Test 4 不会出现,Yuuki 也不会被记录。

结果:特别感谢@Karizma 和我一起解决这个问题!

在 index.js 的结尾必须说

module.exports = bot;

而pray.js(使用命令处理程序)具有以下代码:

module.exports = {
    name: 'pray',
    description: 'Pray to the goddess!',
    usage: '[command name]',
    execute(message, args){
        const Discord = require("discord.js");
        const { Client } = require('discord.js');
        const bot = require("path_to_index.js")
        const token = require("path_to_your_token");
        bot.login(token.login_token);
        //token_login is how I stored my token to login the bot
        let Prayer = message.member.user.tag;
            async function SendingPray() {
                const Yuuki = await bot.users.fetch('ID_wanted').catch(err => {
                    console.error(err);
                    //means the user id is invalid
                });
                Yuuki.send("My goddess, " + Prayer + " has sent you a pray!").catch(console.error);
            };
            SendingPray();
        message.reply("your pray has been sent. The goddess will read your pray and decide your fate!");
    }
}

问题是无法通过在 7-9 中添加代码通过新文件重新定义机器人时获取 ID,直接返回 index.js

标签: javascriptdiscord.js

解决方案


由于您正在获取用户,因此您必须调用.catch该方法以防它失败

async function SendingPray() {
      message.reply("Test3");
      const Yuuki = await bot.users.fetch('715912580127785060').catch(err => {
          console.error(err);
          //means the user id is invalid
      });
      message.reply("Test4");
      console.log(Yuuki);
      message.reply("Test5");
      Yuuki.send("Testing");
      message.reply("Test6");
};

我已经在 discord 上测试了 id,它似乎是无效的。


推荐阅读