Giter Club home page Giter Club logo

valve-server-query's Introduction

Buy Me A Coffee Discord PayPal

This module allows you to:

  • Easily make queries to servers running valve games
  • Make queries to valve master servers
  • Use a remote console to control your server remotely

Links

An implementation of valve protocols

const { Server, RCON, MasterServer } = require('@fabricio-191/valve-server-query');

Some of the games where it works with are:

  • Counter-Strike
  • Counter-Strike: Global Offensive
  • Garry's Mod
  • Half-Life
  • Team Fortress 2
  • Day of Defeat
  • The ship

Examples

Server

const server = new Server({
  ip: '0.0.0.0',
  port: 27015,
  timeout: 3000,
});

const info = await server.getInfo();
console.log(info);

const players = await server.getPlayers();
console.log(players);

const rules = await server.getRules();
console.log(rules);

console.log(server.lastPing);

Master Server

const servers = await MasterServer({
  quantity: 1000,
  region: 'US_EAST',
  timeout: 3000,
});

//servers is an array if 'ip:port' strings, see the docs
console.log(servers);

RCON

const rcon = await RCON({
  ip: '0.0.0.0',
  port: 27015, //RCON port
  password: 'your RCON password'
});

rcon.on('disconnect', async (reason) => {
  console.log('disconnected', reason);
  try{
    await rcon.reconnect();
  }catch(e){
    console.log('reconnect failed', e.message);
  }
});

rcon.on('passwordChanged', async () => {
  const password = await getNewPasswordSomehow();
  try{
    await rcon.authenticate(password);
  }catch(e){
    console.error('Failed to authenticate with new password', e.message);
  }
});

const response = await rcon.exec('sv_gravity 1000');

valve-server-query's People

Contributors

fabricio-191 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

valve-server-query's Issues

Timing out on server that is online

Hey, I'm running into an issue while working on a discord integration for the gmod server npcsv-- for whatever reason, despite the server being online and listening (nmap confirms) at the port and ip I'm checking, I still get a response timeout. IP is us1.npcs.gg, port is currently set to default. Here's my code:

const fs = require("fs");
const { Server } = require("@fabricio-191/valve-server-query");
const { Client, Intents, MessageEmbed } = require("discord.js");

const DELAY = 1000;
const TARGET_CHANNEL = "773333968858251268";
class StatusEmbed extends MessageEmbed {
  constructor(data) {
    if (!data.offline) {
      super({
        type: "rich",
        title: `us1.npcs.gg status`,
        description: "",
        color: 0x00ffff,
        fields: [
          {
            name: `Status`,
            value: "Online",
            inline: true,
          },
          {
            name: `Players`,
            value: data.players,
            inline: true,
          },
          {
            name: `Map`,
            value: data.map,
            inline: true,
          },
          {
            name: `Uptime`,
            value: data.time,
            inline: true,
          },
        ],
      });
    } else {
      super({
        type: "rich",
        title: `us1.npcs.gg status`,
        description: "",
        color: 0x00ffff,
        fields: [
          {
            name: `Status`,
            value: "Offline",
            inline: true,
          },
        ],
      });
    }
  }
}

async function start() {
  try {
    const client = new Client({
      intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES],
    });
    client.once("ready", onReady);
    client.on("error", (e) => {
      console.error(`Error: ${e}`);
    });
    client.login(fs.readFileSync("token.txt").toString().replace(/\s/g, ""));
    function onReady() {
      let uptime = 0;
      console.log("Ready!");
      const channel = client.channels.cache.get(TARGET_CHANNEL);
      setInterval(async () => {
        try {
          console.log("Getting data");
          const server = await Server({
            ip: "135.148.136.143",
          });
          const info = await server.getInfo();
          const embed = new StatusEmbed({
            players: `${info.players.online}/${info.players.max}`,
            map: info.map,
            uptime: `${Math.floor(uptime / 1000 / 60 / 60)}:${
              Math.floor(uptime / 1000 / 60) % 60
            }`,
          });
          uptime += DELAY;
          channel.send(embed);
        } catch (e) {
          const embed = new StatusEmbed({ offline: true });
          uptime = 0;
          channel.send(embed);
          console.error(e);
        }
      }, DELAY);
    }
  } catch (e) {
    console.error("Error: " + e);
    start();
  }
}
start();

and here's the logs:

Ready!
Getting data
Getting data
Getting data
Getting data
Getting data
Getting data
Error: Response timeout.
    at /home/oranderr/code/miscjs/discintegration/node_modules/@fabricio-191/valve-server-query/lib/main/connection.js:132:62
    at new Promise (<anonymous>)
    at Connection.awaitResponse (/home/oranderr/code/miscjs/discintegration/node_modules/@fabricio-191/valve-server-query/lib/main/connection.js:118:10)
    at Connection.query (/home/oranderr/code/miscjs/discintegration/node_modules/@fabricio-191/valve-server-query/lib/main/connection.js:153:21)
    at processTicksAndRejections (node:internal/process/task_queues:96:5)
    at async _getInfo (/home/oranderr/code/miscjs/discintegration/node_modules/@fabricio-191/valve-server-query/lib/main/server.js:174:15)
    at async init (/home/oranderr/code/miscjs/discintegration/node_modules/@fabricio-191/valve-server-query/lib/main/server.js:140:15)
    at async Timeout._onTimeout (/home/oranderr/code/miscjs/discintegration/index.js:73:26)
^C

Any idea what might be happening?

Wrong type declaration for Server in index.d.ts

Hello and first of all thank you for this package.

When trying to build my project I get the following error:

error TS2694: Namespace '"@fabricio-191/valve-server-query". Server' has no exported member 'Data'.
280  export function Server(data?: Server.Data): Promise<Server>;
                                          ~~~~

Found 1 error in node_modules/@fabricio-191/valve-server-query/typings/index.d.ts:280

I am using your npm-package version 4.1.7 with typescript 4.9.4.
I think the type declaration in typings/index.d.ts for the parameter of the Server function is wrong:

// Causing an error
export function Server(data?: Server.Data): Promise<Server>;

The Data Interface in line 207 of typings/index.d.ts is in the MasterServer namespace and not in the Server namespace. But I think for this Server-Function the Options interface in the Server namespace should be used, shouldn't it? When changing the type declaration to Server.Options the build works:

// Works
export function Server(data?: Server.Options): Promise<Server>;

Could you please check if you have the same problem and update the index.d.ts with the correct type?

Thanks in advance!

compiling with tsc

It is presently impossible to cleanly compile in typescript with this library as there are quite a few typescript errors, pasted below:

node_modules/@fabricio-191/valve-server-query/typings/index.d.ts:7:19 - error TS2395: Individual declarations in merged declaration 'Server' must be all exported or all local.

7 declare namespace Server {
                    ~~~~~~

node_modules/@fabricio-191/valve-server-query/typings/index.d.ts:163:19 - error TS2395: Individual declarations in merged declaration 'MasterServer' must be all exported or all local.

163 declare namespace MasterServer {
                      ~~~~~~~~~~~~

node_modules/@fabricio-191/valve-server-query/typings/index.d.ts:269:1 - error TS1046: Top-level declarations in .d.ts files must start with either a 'declare' or 'export' modifier.

269 class Server{
    ~~~~~

node_modules/@fabricio-191/valve-server-query/typings/index.d.ts:269:7 - error TS2395: Individual declarations in merged declaration 'Server' must be all exported or all local.

269 class Server{
          ~~~~~~

node_modules/@fabricio-191/valve-server-query/typings/index.d.ts:303:17 - error TS2395: Individual declarations in merged declaration 'Server' must be all exported or all local.

303 export function Server(data: Server.Data): Promise<Server>;
                    ~~~~~~

node_modules/@fabricio-191/valve-server-query/typings/index.d.ts:307:17 - error TS2395: Individual declarations in merged declaration 'MasterServer' must be all exported or all local.

307 export function MasterServer(data?: MasterServer.Data): Promise<address[]>;
                    ~~~~~~~~~~~~


Found 6 errors.

the only fix so far is to skip libchecking:

{
  "compilerOptions": {
    "skipLibCheck": true
  },
}

This however is an ugly fix, but it works.

Error when trying to retrieve player infos

Hi, i was making a discord bot with this library to check my server's stats but when I try to get the players informations with server.getPlayers(), I get this error :

                if(stringEndIndex === -1) throw new Error('string not terminated');
                                                ^

Error: string not terminated
    at BufferParser.string (C:\Users\mrxet\Desktop\Bot\Yoh\node_modules\@fabricio-191\valve-server-query\lib\utils\parsers.js:93:35)
    at Object.playersInfo (C:\Users\mrxet\Desktop\Bot\Yoh\node_modules\@fabricio-191\valve-server-query\lib\utils\parsers.js:230:17)
    at Server.getPlayers (C:\Users\mrxet\Desktop\Bot\Yoh\node_modules\@fabricio-191\valve-server-query\lib\main\server.js:68:18)
    at async C:\Users\mrxet\Desktop\Bot\Yoh\src\events\ready.js:45:27

Here's my code :

client.on("ready", async () => {

  const server = await Server({
    ip: "IP",
    port: 27015,
    timeout: 5000,
  });

  console.log(await server.getPlayers());

}); 

rcon.destroy() causes an error

Hello,

I am using your RCON implementation to connect to a Squad Server and execute a command to receive the next map. The connection works perfectly fine and I am able to receive the RCON response.
But if I use rcon.destroy() to close the RCON connection I receive an error.

This is a small code example that will result in the error:

import ServerQuery from "@fabricio-191/valve-server-query";

console.log("Connecting via RCON...");

const rcon = await ServerQuery.RCON({
   ip: "127.0.0.1",
   port: 12345,
   password: "xxxxxxxxxxxx",
 });

console.log("Connected.");

const response = await rcon.exec("ShowNextMap");
console.log(`RCON-Response: ${response}`);

console.log("Destroying the connection...");
rcon.destroy();

This is the output of the above code with the thrown error:

Connecting via RCON...
Connected.
RCON-Response: Next level is Al Basrah, layer is Al Basrah Invasion v1
Destroying the connection...
C:\path\@fabricio-191\valve-server-query\lib\main\RCON.js:188
                this.connection.client.removeAllListeners();
                         ^
TypeError: Cannot read properties of undefined (reading 'removeAllListeners')

Could you please check if you can reproduce the same error or am I doing something wrong in the above code?

Thanks in advance!

SyntaxError: The requested module '@fabricio-191/valve-server-query' does not provide an export named 'MasterServer'

Problem:

import { MasterServer } from '@fabricio-191/valve-server-query';
         ^

SyntaxError: The requested module '@fabricio-191/valve-server-query' does not provide an export named 'MasterServer'
    at ModuleJob._instantiate (node:internal/modules/esm/module_job:122:21)
    at async ModuleJob.run (node:internal/modules/esm/module_job:188:5)

Node.js v20.0.0

src/app.ts

import { MasterServer } from '@fabricio-191/valve-server-query';

(async () => {
    const servers = await MasterServer({
        quantity: 1000,
        region: 'US_EAST',
        timeout: 3000,
    });

    console.log(servers);
})();

package.json

{
  "type": "module",
  "module": "esnext",
  "scripts": {
    "build": "tsc",
    "start:js": "node build/app.js",
    "start": "tsx src/app.ts",
    "watch": "tsx watch src/app.ts"
  },
  "dependencies": {
    "@fabricio-191/valve-server-query": "^4.1.9"
  },
  "devDependencies": {
    "@tsconfig/node20": "^1.0.0",
    "@types/node": "^18.16.1",
    "tsx": "^3.12.6",
    "typescript": "^5.0.4"
  }
}

tsconfig.json

{
  "extends": "@tsconfig/node20/tsconfig.json",
  "compilerOptions": {
    "rootDir": "./src",
    "baseUrl": "./src",
    "sourceMap": true,
    "outDir": "build",
  }
}

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.