Git Product home page Git Product logo

node-scratch-client's Introduction

node-scratch-client

This package is a nodejs promise-based client to connect with the Scratch web and cloud servers. This package is based off https://github.com/trumank/scratch-api which the developer has discontinued.

Full project manipulation:

// Import the module with:
const scratch = require("node-scratch-client");

// Initiate client
const Client = new scratch.Client({
  username: "griffpatch",
  password: "SecurePassword1"
});

// Login
Client.login().then(() => {
  // Fetch project information
  Client.getProject(10128407).then(project => {
    project.postComment("Turning off comments..");

    project.turnOffCommenting();
  });
});

Cloud server connection:

const scratch = require("node-scratch-client");

const Client = new scratch.Client({
  username: "ceebeee",
  password: "SecurePassword2"
});

Client.login().then(() => {
  let cloud = Client.session.createCloudSession(281983597);

  cloud.connect().then(() => {
    cloud.on("set", variable => {
      console.log("Variable changed to " + variable.value);
    });
  });
});

node-scratch-client's People

Contributors

dependabot[bot] avatar edqx avatar

Stargazers

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

Watchers

 avatar  avatar  avatar

node-scratch-client's Issues

Cloud bug

Sometimes when trying to connect to the cloud like this:

Client.login().then(() => {
  let cloud = Client.session.createCloudSession(548738926);
  cloud.connect().then(() => {
    console.log("Successfully connected to cloud!");
    cloud.on("set", variable => {
      console.log("Cloud variable", variable.name, "set to", variable.value);
    });
  });
});

The following error appears:

undefined:2
{"method":"set","project_id":"548862682","name":"☁ CloudService response","value":"2410100100050202100307010909100703003819142363351915632419173523"}
^

SyntaxError: Unexpected token { in JSON at position 86
    at JSON.parse (<anonymous>)
    at WebSocket.<anonymous> (/home/runner/dictionary/node_modules/node-scratch-client/src/Struct/CloudSession.js:87:25)
    at WebSocket.emit (events.js:314:20)
    at WebSocket.EventEmitter.emit (domain.js:483:12)
    at Receiver.receiverOnMessage (/home/runner/dictionary/node_modules/node-scratch-client/node_modules/ws/lib/websocket.js:789:20)
    at Receiver.emit (events.js:314:20)
    at Receiver.EventEmitter.emit (domain.js:483:12)
    at Receiver.dataMessage (/home/runner/dictionary/node_modules/node-scratch-client/node_modules/ws/lib/receiver.js:422:14)
    at /home/runner/dictionary/node_modules/node-scratch-client/node_modules/ws/lib/receiver.js:379:23
    at /home/runner/dictionary/node_modules/node-scratch-client/node_modules/ws/lib/permessage-deflate.js:298:9

This is because sometimes the API sends multiple objects at once in a single string, like so:

`{"method":"set","project_id":"548862682","name":"☁ CloudService request","value":"0"}
{"method":"set","project_id":"548862682","name":"☁ CloudService response","value":"2410100100050202100307010909100703003819142363351915632419173523"}`

The way to solve this is simple. Separate the string by line to make an array of chunks, and run the code for every one of them, replacing the function on line 85 in src/Struct/CloudSession.js with this:

connection.on("message", function (chunks) {
  let chunksArr = chunks.split("\n");
  for (let i = 0; i < chunksArr.length; i++) {
    let chunk = chunksArr[i];
    if (!chunk) {
      continue;
    }
    let json = JSON.parse(chunk);

    _this._client._debugLog("CloudData: Received message: " + json);

    if (json.method === "set") {
      _this._variables[json.name]  = new CloudVariable(_this._client, {
        name: json.name,
        value: json.value
      });

      _this.emit("set", _this._variables[json.name]);
    } else {
      _this._client._debugLog("CloudData: Method not supported: " + json.method);
    }
  }
});

Projects.getComments() not working

(node:566) UnhandledPromiseRejectionWarning: TypeError: JSON.parse(...).map is not a function
at /home/runner/Amber-Studios/node_modules/node-scratch-client/src/Struct/Project.js:298:45
at processTicksAndRejections (internal/process/task_queues.js:97:5) is the given error

Cannot set cloud variables

I cannot set a cloud variable using this. The error I get is

(node:4069) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'set' of undefined
    at CloudSession.setVariable (/rbd/pnpm-volume/e38efa70-1bc7-452e-891e-f660e6a03dfd/node_modules/.registry.npmjs.org/node-scratch-client/1.3.7/node_modules/node-scratch-client/src/Struct/CloudSession.js:35:27)
at cloud.connect.then (/app/server.js:41:9)
(node:4069) 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(). (rejection id: 1)
(node:4069) [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.```
code:```js
const config = require("./config.json");
const scratch = require("node-scratch-client");

const Client = new scratch.Client({
  username: config.username,
  password: config.password
});

Client.login().then(() => {
  let cloud = Client.session.createCloudSession(221003966);

  cloud.connect().then(() => {
    cloud.on("set", variable => {
      console.log("Variable \""+variable.name+"\" changed to " + variable.value);
        
    });
  cloud.setVariable('☁ Test', 'Test')//seting her. ☁ Test exists
  });
});```

Error when running

image

code:
const scratch = require("node-scratch-client");
// const fetch = require("node-fetch"); Commented out to improve loading times. Uncomment if needed.

console.log("Successfully initialized external server components")
console.log("Establishing connection to scratch...")

// Session validation
const Client = new scratch.Client({
username: ,
password: ,
});

// Setup
const projectID = '582530103';

console.log("Connection to servers established!")

// Session start and event loop
Client.login().then(() => {
let cloud = Client.session.createCloudSession(projectID);

cloud.connect().then(() => {
    cloud.on("set", variable => {
        console.log(variable)
        //console.log("Variable changed to " + variable.value);
    });
});

});

Problem with User.get functions

The User.getCurating({"fetchAll" : true}), User.getFavorited({"fetchAll" : true}), and User.getFollowers({"fetchAll" : true}) all return shared projects.

Comments API changed

Now the comments API on Scratch has changed and using Project.getComments() will not work. However, comments can still be accessed via https://scratch.mit.edu/site-api/comments/project/<project id>/, even though the response is in HTML. Maybe an XML parser could be used to convert this to JSON.

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.