Discord JS - пять миллионов игроков - PullRequest
0 голосов
/ 09 мая 2020

Я хочу создать бота, который будет отображать количество игроков от пяти минут в статусе, как я могу самым простым способом импортировать количество игроков с сервера? Мой сервер находится на VPS, а бот будет на другой машине, поэтому я не могу ссылаться на программу. Хорошего дня.

Ответы [ 3 ]

0 голосов
/ 09 мая 2020

Возвращает:

(node:15924) UnhandledPromiseRejectionWarning: DiscordAPIError: Cannot send an empty message
    at RequestHandler.execute (D:\discordBot5\node_modules\discord.js\src\rest\RequestHandler.js:170:25)
    at processTicksAndRejections (internal/process/task_queues.js:97:5) (node:15924) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1) (node:15924) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

Я заставил его работать с командой m! Gracze (im poli sh), и она возвращает эту ошибку, а не сервер отключен или что-то еще, только эта ошибка

Мой код:

const { token } = require('./config.json');
const ms = require('ms');
const fs = require('fs');
const { Client } = require('discord.js');
const bot = new Client;
const client =  new Client;
const Gamedig = require('gamedig');

bot.on("ready", () => {
    console.log(`Zalogowano do bota: ${bot.user.tag}`)

    bot.user.setActivity("| ✅ | Ładowanie...", {type: "PLAYING"});
    let activeNum = 0;

    setInterval(function() {
        var scount2 = bot.guilds.size
        var ucount = bot.users.size

        var currentdate = new Date();
        var dateTime = currentdate.getDate() + "/"
          + (currentdate.getMonth()+1)  + "/" 
          + currentdate.getFullYear() + " | "  
          + currentdate.getHours() + ":"  
          + currentdate.getMinutes() + ":" 
          + currentdate.getSeconds() + " !";

          if (activeNum === 0) {
            bot.user.setActivity(`| ✅ | Servery:  ${scount2}! `);
            activeNum = 1;
          }else if (activeNum === 1) {
            bot.user.setActivity(`| ✅ | Użytkownicy:  ${ucount}! `)
            activeNum = 2;
          }else if (activeNum === 2) {
            bot.user.setActivity(`| ✅ | Pomoc: m!pomoc`)
            activeNum = 3;
          }else if (activeNum === 3) {
            bot.user.setActivity(`| ✅ | Data: ${dateTime}`)
            activeNum = 4;
          }else if (activeNum === 4) {
            bot.user.setActivity(`| ✅ | Status: ✅!`)
            activeNum = 0;
          }
        }, 15 * 1000);




});

bot.on("message", async msg => {
    if (msg.author.bot) return;

    let prefixes = JSON.parse(fs.readFileSync("./prefixes.json", "utf8"));

    if(!prefixes[msg.guild.id]) {
      prefixes[msg.guild.id] = {
        prefixes: "m!"
      };
    }

    let prefix = prefixes[msg.guild.id].prefixes;

    const args = msg.content.split(" ");
    let command = msg.content.toLowerCase().split(" ")[0];
    command = command.slice(prefix.length)

    if (command === "gracze") {
        Gamedig.query({
            type: 'fivem',
            host: '178.33.45.164'
        }).then((gracze) => {
            msg.channel.send(gracze);
        }).catch((error) => {
            console.log("server is offline");
            msg.channel.send("Server jest offline")
        })

    }

})
0 голосов
/ 10 мая 2020
• 1000

Я сделал JavaScript AP для FiveM API. http://npmjs.com/package/fivem - На этой странице написано, как его использовать и реализовать!

Наслаждайтесь.

  • Фиксированная ссылка. Также там есть документы: D
0 голосов
/ 09 мая 2020

Вы можете использовать gamedig, это позволяет вам запрашивать разные типы игровых серверов, в том числе FiveM.

Вы можете установить его, используя npm i gamedig

Затем вы можете изменить и использовать этот пример:

const Gamedig = require('gamedig');
Gamedig.query({
    type: 'fivem',
    host: 'IP' // This needs to be a string
    port: port // This needs to be a number & is optional, unless you're not using the default port for that gameserver type
}).then((state) => {
    console.log(state); // You can use this output to get the player count.
}).catch((error) => {
    console.log("Server is offline");
});
...