Giter Site home page Giter Site logo

node-screeps-api's Introduction

Screeps API

This is a nodejs API for the game Screeps

JavaScript Style Guide License Version Downloads CircleCI

npm

Notice on authentication

As of 12/29/2017 Screeps now uses auth tokens obtained via your screeps account settings. User/pass auth will stop working February 1, 2018! Screeps Announcement

CLI Usage

As of 1.7.0, a small CLI program (screeps-api) is included.

Server config is specified via a .screeps.yml file conforming to the Unified Credentials File format

screeps-api

  Usage:  [options] [command]

  Options:

    -V, --version                output the version number
    --server <server>            Server config to use (default: main)
    -h, --help                   output usage information

  Commands:

    raw <cmd> [args...]          Execute raw API call
    memory [options] [path]      Get Memory contents
    segment [options] <segment>  Get segment contents. Use 'all' to get all)
    download [options]           Download code
    upload [options] <files...>  Upload code

API Usage

As of 1.0, all functions return Promises

const { ScreepsAPI } = require('screeps-api');
const fs = require('fs');

// Supports @tedivm's [Unified Credentials File format](https://github.com/screepers/screepers-standards/blob/34bd4e6e5c8250fa0794d915d9f78d3c45326076/SS3-Unified_Credentials_File.md) (Pending [screepers-standard PR #8](https://github.com/screepers/screepers-standards/pull/8))
const api = await ScreepsAPI.fromConfig('main', 'appName')
// This loads the server config 'main' and the configs section 'appName' if it exists
// config section can be accessed like this:
// If making a CLI app, its suggested to have a `--server` argument for selection
console.log(api.appConfig.myConfigVar)

// All options are optional
const api = new ScreepsAPI({
  token: 'Your Token from Account/Auth Tokens'
  protocol: 'https',
  hostname: 'screeps.com',
  port: 443,
  path: '/' // Do no include '/api', it will be added automatically
});

// You can overwrite parameters if needed
api.auth('[email protected]','notMyPass',{
  protocol: 'https',
  hostname: 'screeps.com',
  port: 443,
  path: '/' // Do no include '/api', it will be added automatically
})

// If you want to point to the screeps PTR (Public Test Realm),
// you can set the 'path' option to '/ptr' and it will work fine.

// Dump Memory
api.memory.get()
  .then(memory => {
    fs.writeFileSync('memory.json', JSON.stringify(memory))
  })
  .catch(err => console.error(err));


// Dump Memory Path
api.memory.get('rooms.W0N0')
  .then(memory => {
    fs.writeFileSync('memory.rooms.W0N0.json', JSON.stringify(memory))
  })
  .catch(err => console.error(err));

// Get user info
api.me().then((user)=>console.log(user))

// Socket API

api.socket.connect()
// Events have the structure of:
// {
//   channel: 'room',
//   id: 'E3N3', // Only on certain events
//   data: { ... }
// }
api.socket.on('connected',()=>{
	// Do stuff after connected
})
api.socket.on('auth',(event)=>{
	event.data.status contains either 'ok' or 'failed'
	// Do stuff after auth
})

// Events: (Not a complete list)
// connected disconnected message auth time protocol package subscribe unsubscribe console

// Subscribtions can be queued even before the socket connects or auths,
// although you may want to subscribe from the connected or auth callback to better handle reconnects

api.socket.subscribe('console')
api.socket.on('console',(event)=>{
	event.data.messages.log // List of console.log output for tick
})


// Starting in 1.0, you can also pass a handler straight to subscribe!
api.socket.subscribe('console', (event)=>{
	event.data.messages.log // List of console.log output for tick
})

// More common examples
api.socket.subscribe('cpu',(event)=>console.log('cpu',event.data))
api.code.get('default').then(data=>console.log('code',data))
api.code.set('default',{
	main: 'module.exports.loop = function(){ ... }'
})
api.socket.subscribe('memory/stats',(event)=>{
	console.log('stats',event.data)
})
api.socket.subscribe('memory/rooms.E0N0',(event)=>{
	console.log('E0N0 Memory',event.data)
})

Endpoint documentation

Server endpoints are listed in the docs folder:

node-screeps-api's People

Contributors

alinanova21 avatar arcath avatar dependabot[bot] avatar domnomnom avatar ffmathy avatar gdborton avatar hiryus avatar pyrodogg avatar semperrabbit avatar systemparadox avatar tedivm avatar thmsndk avatar tprk77 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  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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

node-screeps-api's Issues

Cannot install in node 12, needs bufferutil 4.x

Installing on node12 results in build errors from bufferutil -> nan. Updating to [email protected] should fix it.

In file included from ../../nan/nan_new.h:189,
                 from ../../nan/nan.h:203,
                 from ../src/bufferutil.cc:7:
../../nan/nan_implementation_12_inl.h: In static member function ‘static Nan::imp::FactoryBase<v8::Function>::return_t Nan::imp::Factory<v8::Function>::New(Nan::FunctionCallback, v8::Local<v8::Value>)’:
../../nan/nan_implementation_12_inl.h:105:32: error: no matching function for call to ‘v8::Function::New(v8::Isolate*&, void (&)(const v8::FunctionCallbackInfo<v8::Value>&), v8::Local<v8::Object>&)’
                           , obj));

Is it possible to execute arbitrary commands using this API?

I'm planning to write a Google Function to:

  • Pull events (and clear the array) from Memory.events periodically
  • Post these events to a local database

Is it possible to retrieve Memory.events (it appears to be based on the docs) and then empty Memory.events (did spot this in Endpoints.md)

Thanks for your help

React.js Support + screeps-api npm package does not contain src folder

(1) I am trying to get this library working on a React.js App. The first issue I was facing is the problem with it not getting resolved because the package.json contains this in a line: "module": "src/index.js". I solved that by downloading this repository as a zip and copying the src folder into the screeps-api folder in my projects node_modules folder.

image

(2) Now I am facing the issue that your script turns my React.js App white as soon I try to import ScreepsAPI from the package. This implies there is a syntax error. Could you perhaps make this compatible with React.js? It happens as soon I try to import ScreepsAPI using import { ScreepsAPI } from 'screeps-api';.

I am using Vite.js for development. But should happen on React.js in general.

v1.0

forced dependency to get v1.0 because I wanted to play with it "screeps-api": "screepers/node-screeps-api#v1.0",

test console.js

const ScreepsAPI = require('screeps-api')
const creds = require('./creds')

const api = new ScreepsAPI(creds)
PS D:\Dropbox\git\screep.serfinity> node console
module.js:471
    throw err;
    ^

Error: Cannot find module './build/'
    at Function.Module._resolveFilename (module.js:469:15)
    at Function.Module._load (module.js:417:25)
    at Module.require (module.js:497:17)
    at require (internal/module.js:20:19)
    at Object.<anonymous> (D:\Dropbox\git\screep.serfinity\node_modules\screeps-api\index.js:1:80)
    at Module._compile (module.js:570:32)
    at Object.Module._extensions..js (module.js:579:10)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
    at Function.Module._load (module.js:438:3)

I understand it's not done, but just reporting

"[object Object]" returned when subscribing to memory

screepsApi.socket.subscribe('memory/stats',(event)=>{
    console.log('stats', JSON.stringify(event))
})

Results in

stats {"channel":"memory/stats","id":"57909b057d880b5773e95d25","type":"user","data":"[object Object]"}

I double checked that my memory indeed contains an object at that memory path, not this string.
Is this how it's returned from the screeps server or is node-screeps-api doing something weird?

axios needs updated

The current version of axios has a known moderate vulnerability, documented here. It's also grossly out of date, in general.

Reconnect goes mental if the connection is refused

  1. Start private server
  2. Create websocket connection with api.socket.connect()
  3. Stop the server

Reconnect goes mental:

  screepsapi:socket disconnected +695ms
  screepsapi:socket error Error: connect ECONNREFUSED 192.168.8.2:21025 +112ms
  screepsapi:socket disconnected +0ms
  screepsapi:socket reconnect 1/10 +1ms
  screepsapi:socket error Error: connect ECONNREFUSED 192.168.8.2:21025 +109ms
  screepsapi:socket disconnected +0ms
  screepsapi:socket reconnect 1/10 +0ms
  screepsapi:socket error Error: connect ECONNREFUSED 192.168.8.2:21025 +99ms
  screepsapi:socket disconnected +1ms
  screepsapi:socket reconnect 2/10 +0ms
  screepsapi:socket error Error: connect ECONNREFUSED 192.168.8.2:21025 +6ms
  screepsapi:socket disconnected +1ms
  screepsapi:socket reconnect 1/10 +0ms
  screepsapi:socket error Error: WebSocket was closed before the connection was established +104ms
  screepsapi:socket error Error: connect ECONNREFUSED 192.168.8.2:21025 +0ms
  screepsapi:socket disconnected +0ms
  screepsapi:socket disconnected +1ms
  screepsapi:socket reconnect 1/10 +0ms
  screepsapi:socket reconnect 1/10 +0ms

What's happening is that the socket close event is being fired immediately when the connection fails, which triggers another call to this.reconnect(), but it never checks to see if it's currently reconnecting and so retries immediately each time. Additionally, the close event fires before the disconnect event which cleans up the event listeners so the original reconnection "thread" often makes at least one retry before its listeners are killed, with each retry guaranteeing at least one extra connection attempt. It's not quite a fork bomb, but it slowly accumulates more simultanous connection attempts as time goes on.

I'm working on a PR to fix this but welcome any comments about how this should be fixed.

Path opt is being ignored

I've been trying this library to push code to the PTR, but the path option is being ignored.

I think I've located the bug in RawAPI.js, line 300. The url package is probably not working as intended since it is ignoring the relative path in the first parameter.

I think we can work around this issue appending the opts.path to the second parameter of the resolve function.

authentication errors

trying to integrate updating my badge into my deployment i ran into the following issue:

i wanted to integrate the badge update script in a way that it uses the screeps.json that is being used by the ts-starter rollup configuration. so my config looked something like this:

"pserver": {
    "email": "qnz",
    "password": "test",
    "protocol": "http",
    "hostname": "localhost",
    "port": 21025,
    "path": "/",
    "branch": "default"
  }}

i then authenticated using the pserver object that got parsed from json like so:

const api = new ScreepsAPI(cfg[dest]);
api.auth(cfg[dest].email, cfg[dest].password, cfg[dest]);

the auth would fail and everything else would be http401. api.__authed was undefined, api.opts were set correctly

__authed: undefined
opts: {"protocol":"http","hostname":"127.0.0.1","port":21025,"path":"/","email":"qnz","password":"test","branch":"default","secure":false,"pathname":"/","url":"http://127.0.0.1:21025/"}       
(node:388524) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 2): Error: Not Authorized

i got it working like this though:

const api = new ScreepsAPI(cfg[dest]);
api.auth(cfg[dest].email, cfg[dest].password, cfg[dest]);
const res = await api.raw.auth.signin(cfg[dest].email, cfg[dest].password);

the raw call somehow worked perfectly fine, and subsequent calls would work fine too. (the "OK." is the end of my script)

__authed: undefined
opts: {"protocol":"http","hostname":"127.0.0.1","port":21025,"path":"/","email":"qnz","password":"test","branch":"default","secure":false,"pathname":"/","url":"http://127.0.0.1:21025/"}       
OK.

im not quite sure whether this is a bug or whether i did something wrong, but i debugged this for a while and i suspect it is some weirdness in screeps-api (maybe its related to api.__authed staying undefined?). could not really find the cause sadly so im reporting it here

some version numbers:

  • screeps-api": "^1.9.1"
  • servers i tested this with were screeps-launcher v1.9.6 running screeps server 4.1.6 via http and s+2 via https

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.