【问题标题】:Connecting Discord node.js bot to an external Java client将 Discord node.js 机器人连接到外部 Java 客户端
【发布时间】:2018-12-29 00:32:42
【问题描述】:

我有一个用于我的 discord 服务器的机器人,我使用 discord.js 在 Node.js 中编写;其托管 24/7。 我正在用 Java 编写一个客户端,我想连接到机器人,这样我就可以从我的服务器中提取成员并将它们显示在我的应用程序中。 有点像在网页上嵌入 twitter 提要。

如果不将第二个机器人连接到我的服务器,我将如何做到这一点。 如果有帮助,我有我的机器人令牌吗?

【问题讨论】:

  • 在 nodejs 服务器上打开一些端口并使用 Java 连接到该端口。也许像 socket.io 或者只是简单的 http 请求
  • 我正在使用 glitch.com 来编写我的机器人,并使用 uptimerobot.com 来保持它的活力。而且我的机器人正在侦听端口 3000。我将能够连接到那些使用 Java 的人?
  • 我认为您需要自己的服务器。
  • 我在这个主题上找不到任何东西。我已将 socket.io 添加到我的机器人中,现在我正在尝试 java 中的 http 请求。
  • 我找到了这个stackoverflow.com/questions/36923974/http-node-js-java-api,但我不确定它是否正确

标签: javascript java node.js discord discord.js


【解决方案1】:

最简单的方法是在您的 Java 应用程序将请求的节点中执行 API。

例如,您将设置一个侦听端口 3000 的服务器。如果在此端口(例如 your-ip:3000/members)上向您的机器人发送请求,您将使用成员列表进行响应。

您必须在同一个应用程序中设置机器人和(假设您使用httphttp 服务器。

创建一个服务器,用你的令牌记录你的机器人:

const Discord = require("discord.js");
const client = new Discord.Client();
const config = require("./config.json");

const http = require('http');

const hostname = '127.0.0.1';
const port = 3000;

const server = http.createServer((req, res) => {
  respondToRequest(req, res);
});

server.listen(port, hostname, () => {
  console.log(`Server running at http://${hostname}:${port}/`);
});


// client action
client.on("message", respondToMessage);
client.login(config.token);
console.log("bot is starting");

然后处理你要处理的事件。 这是我为处理 gitlab 请求所做的示例

function respondToRequest (request, response){
  let res = "";
  if ("x-gitlab-event" in request["headers"]){ // check if the request is correct
    let body = "";
    request.on('data', function(chunk){ // read the request
      body += chunk;
    });
    request.on('end', function(){
      try {
    createEmbedMessage(request, JSON.parse(body));
    res = "Hook ok\n"; // here is the response sent to gitlab
    response.writeHead(200, {"Content-Type": "text/plain"}); 
    response.end(res);
      } catch (e){
    console.log("JSON invalid: ", e);
    response.writeHead(400, {"Content-Type": "text/plain"}); 
    response.end("NO\n");
      }
    });
  } else {
    res = "link to git\n";
    response.writeHead(200, {"Content-Type": "text/plain"}); 
    response.end(res);
  }
}

它检查请求是否正确(以避免响应任何类型的请求),然后读取请求正文并使用它在 Discord 中写入嵌入消息。然后它使用简单的“Hook ok”消息响应请求。
您需要获取所需的成员列表(一般或特定),然后将其作为答案发送,例如以 JSON 格式发送,而不是使用“Hook ok”进行响应。

【讨论】:

    猜你喜欢
    • 2022-01-23
    • 2011-03-03
    • 2020-12-08
    • 1970-01-01
    • 1970-01-01
    • 2020-02-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多