发送消息给特定用户?

时间:2019-03-02 00:56:17

标签: node.js discord discord.js

我试图让我的不和谐机器人每隔几个小时向我发送一条消息,所以我知道它仍在运行。

例如:
该机器人向我发送了“仍在运行!”每两个小时给我。

这是我尝试过的一些代码,但是没有用:

client.on("ready", () => {
  client.user.setActivity("a game.");

  if (timeout) {
    clearInterval(timeout);
  }
  timeout = setInterval(() => client.channels.get("<ID Retracted>").send("Still functioning!"), 7200000);
  console.log("READY");
});

这是我得到的错误:

Jump to /app/index.js:26
    timeout = setInterval(() => client.channels.get("<retracted id>").send("Still functioning!"), 7200000);
                                                                         ^

TypeError: Cannot read property 'send' of undefined
    at Timeout.setInterval [as _onTimeout] (/app/index.js:26:74)
    at ontimeout (timers.js:436:11)
    at tryOnTimeout (timers.js:300:5)
    at listOnTimeout (timers.js:263:5)
    at Timer.processTimers (timers.js:223:10)

2 个答案:

答案 0 :(得分:0)

首先使用var fetchedUser = client.fetchUser(userID)来获取用户,然后可以调用fetchedUser.createDM()为该用户创建并获取DM频道。
另外,dmChannel属性也可以工作,但是如果先前在漫游器和用户之间未创建DM通道,则它会返回null。

答案 1 :(得分:0)

要使DM自己仍在运行bot,可以使用此代码以指定的时间间隔使它成为DM。

首先,将您的用户ID存储为变量。对于此示例,我将其设置为 yourid

let yourid = client.users.get("your id")

然后为要运行的间隔创建一个函数,在此示例中,我将其命名为intervalFunc。

function intervalFunc() {
yourchannel.send("Im still running!")
}

最后但并非最不重要的一点是,按间隔运行该函数。

setInterval(intervalFunc, 40000)
})

最后,您将获得此代码。

const discord = require('discord.js');
    client.on("ready", () => {
      client.user.setActivity("a game.");
    let yourchannel = client.users.get("your id")
    function intervalFunc() {
    yourchannel.send("Im still running!")
    }
    setInterval(intervalFunc, 40000)
    })

要在特定的频道中发送消息,基本上是一样的,只有将users.get更改为channels.get。我将使用您的频道作为该频道的变量。

let yourchannel = client.channels.get("your id")

因此,最后您将获得此代码。

const discord = require('discord.js');
client.on("ready", () => {
  client.user.setActivity("a game.");
let yourchannel = client.channels.get("your id")
function intervalFunc() {
yourchannel.send("Im still running!")
}
setInterval(intervalFunc, 7200000)
})

这些方法之所以有效,是因为您已经知道要使用哪个频道或DM频道。因此,您可以获取它们各自的ID,并告诉漫游器以一定间隔发送您的消息。希望这会有所帮助!

相关问题