如何使用 Discord 机器人向 Discord 用户发送消息

问题描述 投票:0回答:1

我知道有一些类似的问题,但方法最近已更新,而且我发现文档不寻常。

所以我想知道我需要什么意图通过 Discord 机器人向 Discord 用户发送消息,并且仅依靠内部触发器来运行代码,以便函数调用而不是 Discord 服务器上的事件。

这是我目前为止的一个粗略想法:

  const { Client, GatewayIntentBits } = require('discord.js');

  const client = new Client({ intents: [GatewayIntentBits.DIRECT_MESSAGES] });
  
  // Cut the code out starting from here 
  async function sendMessage(page, messageURL){
  
    const userID = '644643045622415366'; 
    
    await client.login('asdfafasddfq234123421235sdgergafaesfsa');
    
    const user = await client.users.fetch (userID);
    

    await user.send (messageURL);
      

  
  
  }

这些方法中的大多数都被抽象为单独的函数,其中 try catch 块只是一个例子

我尝试了不同的组合和发送消息的方法,但似乎没有任何效果。

任何耐心将不胜感激,因为我是新手,我只是试图将不同文章中的内容拼凑在一起

automation discord.js bots
1个回答
0
投票

当您尝试私下向用户发送消息时,您确实需要使用

DirectMessages
意图。这是发送消息的整个代码的样子

const { Client, GatewayIntentBits } = require('discord.js');

const client = new Client({ 
    intents: [GatewayIntentBits.DirectMessages /* Add other intents here */],
});

// Function for sending the message
async function sendMessage() {
    const userID = '123456789';
    const user = await client.users.fetch(userID);
    await user.send('hello world').catch(() => console.log("User does not accept DM's")); // Add the catch to check whether or not the bot can send DM's to the user
}
© www.soinside.com 2019 - 2024. All rights reserved.