将Discord node.js机器人连接到外部Java客户端

时间:2018-07-20 16:30:58

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

我有一个我的Discord服务器的机器人,该机器人是我使用discord.js在Node.js中编写的;其托管24/7。 我正在用Java编写一个要连接到机器人的客户端,以便可以从服务器中提取成员并将其显示在应用程序中。 有点像您在网页上嵌入Twitter提要的方式。

在不将第二个机器人连接到服务器的情况下,我该怎么做。 我有我的机器人令牌吗?

1 个答案:

答案 0 :(得分:0)

最简单的方法是在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”消息响应请求。
而不是用“ Hook ok”进行响应,您需要获取所需成员(常规或特定)的列表,然后将其作为答案发送,例如以JSON格式。