npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

mastodon-api-v1

v1.1.6

Published

Mastodon API library with streaming support

Downloads

266

Readme

Mastodon API

NPM Downloads NPM Version code style

Mastodon API Client for node

Installing

yarn add mastodon-api-v1

OR

npm install --save mastodon-api-v1

Usage:

Authorization

For getting an access token, please take a look into examples/authorization.js.

For more information, please take a look on the wiki here and here.

The authorization process works as follows:

  1. Hit the /apps endpoint to create an OAuth application
  2. With the received client_id and client_secret get an authorization URL
  3. Get an access token by hitting the /oauth/token endpoint with the authorization code you got from the authorization page

Mastodon.createOAuthApp(url, clientName, scopes, redirectUri)

Makes a call to the /app endpoint to create an OAuth app. Returns the apps id, client_id and client_secret.

These values should be stored and used from now on. Ideally only call this once!

url

Optional. The base url of the Mastodon instance. Defaults to https://mastodon.social/api/v1/apps

clientName

Optional. Defaults to mastodon-node

scopes

Optional. Defines the scopes of your OAuth app whitespace seperated. Defaults to read write follow.

redirectUri

Optional. Defaults to urn:ietf:wg:oauth:2.0:oob. This will be used in a future call to Mastodon.getAuthorizationUrl(...), only the URL defined here can be used later to redirect the user. The default means no redirect (the code will be shown to the user).

Mastodon.getAuthorizationUrl(clientId, clientSecret, baseUrl, scope, redirectUri)

Returns an authorization url for users to authorize your application. clientId and clientSecret can be obtained by calling Mastodon.createOAuthApp(...) before.

clientId

Your client_id.

clientSecret

Your client_secret.

baseUrl

Optional. Defaults to https://mastodon.social.

scope

Optional. Defines the scopes of your OAuth app whitespace seperated. Defaults to read write follow.

redirectUri

Optional. Defaults to urn:ietf:wg:oauth:2.0:oob. If you specify your own URL, it will be called with a query parameter code.

Mastodon.getAccessToken(clientId, clientSecret, authorizationCode, baseUrl, redirectUri)

After authorizing your OAuth application via the authorization URL from Mastodon.getAuthorizationUrl(...) you'll get the authorization code on the website, which lets us obtain the access token we actually need.

clientId

Your client_id.

clientSecret

Your client_secret.

authorizationCode

The authorization code you should have got from the authorization page.

baseUrl

Optional. Defaults to https://mastodon.social.

redirectUri

Optional. Defaults to urn:ietf:wg:oauth:2.0:oob.

import Mastodon from 'mastodon-api-v1'

const M = new Mastodon({
  access_token: '...',
  timeout_ms: 60*1000,  // optional HTTP request timeout to apply to all requests.
  api_url: 'https://mastodon.social/api', // optional, defaults to https://mastodon.social/api/
})

node-mastodon API:

const M = new Mastodon(config)

Create a Mastodon instance that can be used to make requests to Mastodon's APIs.

If authenticating with user context, config should be an object of the form:

{
  access_token: '...'
}

APIs

Accounts:

Get Current Account:

await M.apis.account.verifyAccountCredentials()

Follow Account:

await M.apis.account.follow(accountId)

Parameters

  • accountId > String: AccountId to follow account

Unfollow Account:

await M.apis.account.unfollow(accountId)

Parameters

  • accountId > String: AccountId to unfollow account

Get Account by Id:

await M.apis.account.get(accountId)

Parameters

  • accountId > String: AccountId to get the details of

Get Account followers:

await M.apis.account.followers(accountId, limit, nextId)

Parameters

  • accountId > String: AccountId to get the followers of
  • limit > Number: Limit to get the followers. Max value is 80. Default is 10
  • nextId > String: Followers to get after the current list.

Get Account followings:

await M.apis.account.followings(accountId, limit, nextId) Parameters

  • accountId > String: AccountId to get the followers of
  • limit > Number: Limit to get the followers. Max value is 80. Default is 10
  • nextId > String: Followers to get after the current list.

Search Accounts:

await M.apis.account.search(query, start, limit, exactMatch, rawData)

Parameters

  • query > String: Search query e.g "Social"
  • start > Number: Starting index of the results
  • limit > Number: No of results to fetch
  • exactMatch > Boolean: Should return exact match.
  • rawData > Boolean: Return formatted or raw data.

Media

Upload Media:

await M.apis.media.upload(file, thumbnail, description, focus)

Upload Media V2:

await M.apis.media.uploadV2(file, thumbnail, description, focus)

Get Media:

await M.apis.media.get(mediaId)

Update Media:

await M.apis.media.upload(mediaId, thumbnail)

Status

Post Status:

await M.apis.status.create(message, mediaIds, inReplyToId)

Get Status:

await M.apis.status.get(statusId)

Delete Status:

await M.apis.status.remove(statusId)

Mark Favourite Status:

await M.apis.status.markFavourite(statusId)

Unmark Favourite Status:

await M.apis.status.unmarkFavourite(statusId)

Share Status:

await M.apis.status.share(statusId)

Update Status:

await M.apis.status.update(statusId, message, mediaIds)

Customizable APIs:

M.get(path, [params], callback)

GET any of the REST API endpoints.

path

The endpoint to hit.

params

(Optional) parameters for the request.

callback

function (err, data, response)

  • data is the parsed data received from Mastodon.
  • response is the http.IncomingMessage received from Mastodon.

M.post(path, [params], callback)

POST any of the REST API endpoints. Same usage as T.get().

M.stream(path, [params])

Returns a stream listener instance. See examples on how to use it.

M.getAuth()

Get the client's authentication tokens.

M.setAuth(tokens)

Update the client's authentication tokens.


Examples

Reading the home timeline

M.get('timelines/home', {}).then(resp => console.log(resp.data))

Upload an image and attach it to a tweet

M.post('media', { file: fs.createReadStream('path/to/image.png') }).then(resp => {
  const id = resp.data.id;
  M.post('statuses', { status: '#selfie', media_ids: [id] })
});

Stream home timeline

Read the API documentation.

const listener = M.stream('streaming/user')

listener.on('message', msg => console.log(msg))

listener.on('error', err => console.log(err))

Advanced

You may specify an array of trusted certificate fingerprints if you want to only trust a specific set of certificates. When an HTTP response is received, it is verified that the certificate was signed, and the peer certificate's fingerprint must be one of the values you specified. By default, the node.js trusted "root" CAs will be used.

eg.

const M = new Mastodon({
  access_token:         '...',
  trusted_cert_fingerprints: [
    '66:EA:47:62:D9:B1:4F:1A:AE:89:5F:68:BA:6B:8E:BB:F8:1D:BF:8E',
  ]
})

License

This software is a fork of twit and node-mastodon.

Thanks for your awesome work <3

(The MIT License)

Copyright (c) 2023 mystery-man

Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
'Software'), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.