最简单的方法是在您的 Java 应用程序将请求的节点中执行 API。
例如,您将设置一个侦听端口 3000 的服务器。如果在此端口(例如 your-ip:3000/members)上向您的机器人发送请求,您将使用成员列表进行响应。
您必须在同一个应用程序中设置机器人和(假设您使用http)http 服务器。
创建一个服务器,用你的令牌记录你的机器人:
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”进行响应。