Git Product home page Git Product logo

masto.js's Introduction

Masto.js

Universal Mastodon API client for JavaScript

npm

Q&A | Examples | Read the Docs | Releases

Features

  • 🌎 Universal: Works in Node.js, browsers, and Deno
  • πŸ“¦ Lightweight: Less runtime codes, 6kB+ minified and gzipped
  • πŸ“š TypeScript: Written in TypeScript, and provides type definitions
  • πŸ§ͺ Tested: 100% test coverage using a real Mastodon server
  • πŸ€“ Maintained: Actively maintained by a Fediverse lover since 2018

Migration Guides

Who's using Masto.js?

Quick Start

In this quick start, we'll look at how to create a simple Mastodon bot that publishes a post using Masto.js.

First, you must install Node.js and npm in your environment. Follow the npm official guide for the setup, and proceed to the next step. Alternatively, you can use yarn, pnpm, or other package managers to install Masto.js.

The minimal required version of dependencies is as follows:

  • Node.js: >= 18.x
  • npm: >= 9.x
  • TypeScript (optional peer dependency): >= 5.0.0

If you successfully installed Node.js and npm, create your first Masto.js project with the following command. Assume you're using a POSIX-compatible operating system.

Create a directory and initialise your project.

npm init --yes
npm pkg set type=module

Make sure a package.json file is created in your project directory. Then install Masto.js using npm

npm install masto

Now you successfully initialised your project for developing a Mastodon bot. Next, you need to create an application to obtain an access token required to access your account.

Go to your settings page, open Development, and click the New Application button to obtain your personal access token.

A screenshot from "New application" page from a setting page of Mastodon. It contains three input fields "Application name" "Application website" and "Redirect URI" and checkboxes named "Scopes".

You need to fill out Application name, but rest of the fields can be left as defaults. What you need to select for Scopes is depending on your bot's ability, but you can access most of the functionality by granting read and write. See OAuth Scopes documentation for further information.

Once you have created an application, save Your access token securely. This string is required to access your account through Masto.js.

Then you're almost there! Create a file named index.js inside your project directory and add the following code. This is an example which will post a status from your account.

import { createRestAPIClient } from "masto";

const masto = createRestAPIClient({
  url: process.env.URL,
  accessToken: process.env.TOKEN,
});

const status = await masto.v1.statuses.create({
  status: "Hello from #mastojs!",
});

console.log(status.url);

Finally, run the program with the following command. Replace {URL} with your instance's URL such as https://mastodon.social, and {TOKEN} to your access token that you obtained in the previous section.

URL={URL} TOKEN={TOKEN} node ./index.js

You can learn about other available features in the documentation. You may also want to refer examples to see more examples. Of course, you can ask questions in the Discussions if you have any.

Enjoy your Mastodon development with Masto.js!

Contribution

See CONTRIBUTING.md

License

Masto.js is distributed under the MIT license

masto.js's People

Contributors

343max avatar assaf avatar ayoayco avatar chdorner avatar dahlia avatar danielroe avatar darnfish avatar dependabot-preview[bot] avatar dependabot[bot] avatar fadookie avatar hakatashi avatar jacksonsamuel42 avatar jasonbyrne avatar johnythecarrot avatar josephkreydt avatar kkoyung avatar kytta avatar lostfictions avatar neet avatar semantic-release-bot avatar shinigami92 avatar shuuji3 avatar simon-he95 avatar supersonichub1 avatar sxzz avatar teabroker avatar thewalruzz avatar webfansplz 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  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

masto.js's Issues

error TS2304: Cannot find name 'Omit'.

Hello :)

Thanks for maintaining this module so frequently to keep up with Mastodon's evolution.

I guess this is related to #60 but not sure how.

I'm trying to build a small bot to post images on a Mastodon account. I'm using version 2.4.0 of the module, and when trying to build my script with typescript, I get the error above in clients/masto/params.d.ts

Here's my tsconfig :

{
	"compilerOptions": {
		// Target latest version of ECMAScript.
		"target": "esNext",
		"module": "commonjs",
		// Search under node_modules for non-relative imports.
		"moduleResolution": "node",
		// Enable strictest settings like strictNullChecks & noImplicitAny.
		// true is better but requires a global refactoring.
		"strict": false,
		// Disallow features that require cross-file information for emit.
		"isolatedModules": true,
		// Import non-ES modules as default imports.
		"esModuleInterop": true,
		// Import constants from JSON (locales).
		"resolveJsonModule": true,
		"sourceMap": true,
		"outDir": "dist/",
		"pretty": true,
		"removeComments": true,
		"downlevelIteration": true,
		"listFiles": true,
		"listEmittedFiles": true,
		"noUnusedParameters": true,
		"noUnusedLocals": true
	},
	"include": [
		"src"
	],
}

Did I do something wrong? Hope you can help.

Unable to upload media attachments

It appears that uploading media attachments is broken. I get the below error with both my own code and the original example form inside the project.

(node:19274) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'name' of null
    at FormData._getContentDisposition (/mnt/dev/bot/node_modules/form-data/lib/form_data.js:226:40)
    at FormData._multiPartHeader (/mnt/dev/bot/node_modules/form-data/lib/form_data.js:177:33)
    at FormData.append (/mnt/dev/bot/node_modules/form-data/lib/form_data.js:70:21)
    at createFormData (/mnt/dev/bot/node_modules/masto/dist/index.js:1:4494)
    at /mnt/dev/bot/node_modules/masto/dist/index.js:1:4447
    at Array.forEach (<anonymous>)
    at createFormData (/mnt/dev/bot/node_modules/masto/dist/index.js:1:4409)
    at /mnt/dev/bot/node_modules/masto/dist/index.js:1:4447
    at Array.forEach (<anonymous>)
    at createFormData (/mnt/dev/bot/node_modules/masto/dist/index.js:1:4409)
(node:19274) 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:19274) [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.```

no way to handle streaming api websocket connections errors

With current stream method there is no way to know about underlying websocket connection errors and handle them when necessary.

Returning an event emitter decorating WebSocketConnection (or directly the WebSocketConnection event emitter) would allow to do that.

What do you think about something like (stream: string, recieved: (message: {event: string, payload: any}) => void): Promise<WebSocketConnection> instead of current stream: string, recieved: (message: {event: string, payload: any}) => void) ?

Typing for argument of .next()

const timeline = masto.fetchPublicTimeline();

timeline.next();                 // OK
timeline.next({ reset: true });  // OK 
timeline.next(['foo', 'bar'])    // Should be an error, but allowed...

Fix Filter entity

Type of Filter[β€˜id’] requires update since it has been outdated

Iterable timeline function

e.g.

async () => {
  for await (statuses of fetchTimeline('public')) {
    statuses // Mastodon.Status[]
  }
}

Can't fetch

import Mastodon from '@lagunehq/core'

const masto = new Mastodon({
    url: 'https://eldritch.cafe',
    streamingUrl: 'wss://eldritch.cafe',
    token: 'xxx',
})

fetch()

async function fetch() {
    for await (const stats of masto.fetchHomeTimeline()) {
        console.log(stats)
    }
}
UnhandledPromiseRejectionWarning: TypeError: Symbol.asyncIterator is not defined.
at __asyncGenerator (xxx/node_modules/@lagunehq/core/dist/client/Mastodon.js:63:38)

Note: Streams works well

Use Gaxios (or some other HTTP wrapper)

I use Axios as an HTTP client on this project, but I feel it's not well-maintained, and obsolete since it's implemented by XMLHttpRequest not Fetch API.

So I'm planning to try some other HTTP wrapper such as Gaxios which is a package that is compatible with Axios written in TypeScript, maintained by Google.

I'm also having a look at ky, node-fetch (or just window.fetch on browsers), but both are written in pure JS and I can't say they both are strictly typed.

Refs

Search is incorrect

According to this, client.search() does a POST against the search endpoint, when it needs to be a GET.

Also, for us over in TypeScript-land, the V argument doesn't seem to be filling properly.

Use ts builtin `Omit`

Remove simplytyped's Omit and use builtin one that has been added in the newer version.

Cannot update source of credential

Cannot update source of credential by Masto.updateCredential because it is impossible to send nested object through multipart/form-data.
So keys have to be encoded like a[b][c]

Use ESLint

Change the linting tool to ESlint instead of TSLint, since TSLint has been deprecated

Edit I've also noticed some of the extended rules are warning errors but I would change linter to ESLint rather than fix the errors.

Type undefined and null in entities correctly

Mastodon (rails) doesn’t have a difference between null and undefined in rest api, in other words, there’s 2 ways of returning β€œNone” value. So the entities have to check null and undefined strictly with union operators.

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.