Реализация Faceit API в Node.js - PullRequest
0 голосов
/ 18 июня 2020

Я всего лишь студент, и сейчас я застрял в разработке команды для моего Twitch Bot. Это команда! Player, которая берет информацию об игре из внешнего API (FACEIT) и редактирует ее в чате. В некоторых случаях он работает, но когда игра продолжается, в оболочке питания появляется код ошибки. Я знаю, что означает код 404, но не знаю, как его исправить. Надеюсь, вы поможете мне исправить ошибку. Документация из API: https://developers.faceit.com/docs/auth/api-keys Facit- js npm: https://github.com/philliplakis/faceit-js

Это ошибка от powershell:

(node:18676) UnhandledPromiseRejectionWarning: Error: Request failed with status code 404
at createError (C:\....Downloads\twitch_bot\twitch_bot\node_modules\axios\lib\core\createError.js:16:15)
at settle (C:\.....Downloads\twitch_bot\twitch_bot\node_modules\axios\lib\core\settle.js:17:12)
at IncomingMessage.handleStreamEnd (C:\....\Downloads\twitch_bot\twitch_bot\node_modules\axios\lib\adapters\http.js:236:11)
at IncomingMessage.emit (events.js:327:22)
at endReadableNT (_stream_readable.js:1224:12)
at processTicksAndRejections (internal/process/task_queues.js:84:21)
(Use node --trace-warnings ... to show where the warning was created) (node:18676) 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: 2) (node:18676) [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.

А это код:

// Requirements
const tmi = require('tmi.js');
const fitlib = require('faceit-js');
const fs = require('fs');

// FACEIT API
const FACEIT_API_KEY = `2ff592a9-2f9b-48b9-b176-12db474ba5e0`;
const FaceIT = new fitlib(FACEIT_API_KEY);
console.log("Testing FACEIT key...");
FaceIT.account().then(data => console.log(data));

// Define configuration options
const opts = {
  identity: {
    username: '4bierborvier',
    password: 'oauth:zbsggyj2o0md3ahd8ue8579p9da27t',
  },
  channels: [
    '4biervorvier'
  ]
};
// Create a client with our options
const client = new tmi.client(opts);

// Register our event handlers (defined below)
client.on('message', onMessageHandler);
client.on('connected', onConnectedHandler);

// Connect to Twitch:
client.connect();

// Called every time a message comes in
function onMessageHandler (target, context, msg, self) {
  console.log("* Received message: " + msg);
  if (self) { return; } // Ignore messages from the bot

  // Remove whitespace from chat message
  const commandName = msg.trim();

  // If the command is known, let's execute it
  if (commandName === '!dice') {
    const num = rollDice();
    client.say(target, `You rolled a ${num}`);
    console.log(`* Executed ${commandName} command`);
  } 
  else if (commandName === '!player') {
    const gid = fs.readFileSync("./gameid.txt").toString().trim();
    if(gid === "null")
      client.say(target, `No game started.`);
    else {
      try {
        
      FaceIT.matches(gid, true)
        .then(data => {
          let players = [];
          for(let i in data.rounds[0].teams) {
            let team = data.rounds[0].teams[i];
            for (let ib in team.players) {
              let player = team.players[ib];
              players.push(player.nickname);
            }

          }
          client.say(target, `Players in match: ${players.join(", ")}`);
        });
        } catch (error) {
          console.log(err);
        }
    }
    console.log(`* Executed ${commandName} command`);
  } 
  else {
    console.log(`* Unknown command ${commandName}`);
  }
}
// Function called when the "dice" command is issued
function rollDice () {
  const sides = 6;
  return Math.floor(Math.random() * sides) + 1;
}
// Called every time the bot connects to Twitch chat
function onConnectedHandler (addr, port) {
  console.log(`* Connected to ${addr}:${port}`);
}

К сожалению, нет форума, где я мог бы задать ваш вопрос, поэтому запишите его здесь. Я знаю, что это не тот человек.

...