SleeplessOne1917 / lemmy-bot

A bot library for Lemmy, the fediverse link aggregator.
https://www.npmjs.com/package/lemmy-bot
GNU Affero General Public License v3.0
91 stars 11 forks source link
bot bots fediverse fediverse-bot lemmy lemmy-bot typescript typescript-library
License Dependencies up to date Github stars npm version Last commit Issues Open pull requests Downloads per month Typescript
Lemmy logo

lemmy-bot

Library to make it easier to make bots for Lemmy, the fediverse forum/link aggregator.

Features

Installation

Note: This library only works with Node versions 18 and above.

Run

npm install lemmy-bot

or

yarn add lemmy-bot

or

pnpm install lemmy-bot

Lemmy Versions

For lemmy versions 0.17.x, use lemmy-bot 0.3.9 and lower.

For lemmy versions 0.18.x, use lemmy-bot 0.4.x.

For lemmy versions 0.19.x, use lemmy-bot 0.5.x or 0.6.x.

Documentation

LemmyBot

Create a bot by newing up a LemmyBot

import LemmyBot from 'lemmy-bot';

const bot = new LemmyBot({
  // Pass configuration options here
});

Calling bot.start() will start the bot. Calling bot.stop() will stop it.


LemmyBotOptions

What your bot does is determined by the options passed to the constructor. They are as follows:

credentials

Log in credentials for the bot. Accepts an object with username and password properties. If not provided, the bot can still poll the instance for items like posts, comments, and modlog actions, but it will not be able to perform actions that require an account.

instance REQUIRED

The Lemmy instance your bot will connect to. Only pass the domain name of the instance, e.g. if the bot is supposed to be on lemmy.ml, pass 'lemmy.ml', not 'https://lemmy.ml'.

connection

Options for the bot's connection. It is an object with the following properties:

handlers

Options that control what the bot does when encountering a certain item. The following is a simple example to show how handlers work:

import LemmyBot from 'lemmy-bot';

const bot = new LemmyBot({
  handlers: {
    post: (res) => {
      console.log(res.postView.post.name);
    }
  }
});

bot.start();

In the previous example, the bot polls the instance for posts and logs the name of each one.

Each handler can accept an object with the following properties:

Some handlers accept more options.

If using the default values for secondsBetweenPolling and minutesUntilReprocess, the handle function can be used instead of the object.

The handle function receives an object that has the following props as an argument:

The following are the properties that can be set on handlers:

federation

Options for handling federated instances. Can be one of:

A bot cannot set both a block list and an allow list. Entries allowList and blockList can either be strings or objects. If the entry is a string, all items on the instance named by the string will be allowed/blocked. If an object, it must have the following shape:

Note: If you want to limit checking on your local instance to only a few communities, do not pass local; instead, pass an object with an allowList with your local instance domain and desired communities.

schedule

Task object or list of task objects. Task objects have the following properties:

secure

If true, the bot will use HTTPS. If false, it will use HTTP. Default value is true.

dbFile

The bot tracks which items it has handled already in a SQLite database. Accepts a string path to the file to use a database: will create the file if it does not already exist. If this option is not specified, the bot will store the SQLite DB in memory. This can be useful during development, but it is recommended to use a file when running in production.

markAsBot

If true, the bot will automatically mark its own account as a bot. If false, make sure to remember to mark the bot's account as a bot in the account's settings.

Default value is true.

dryRun

If true, no network requests will be made to your lemmy instance. If false, the bot will contact the instance configured in instance. Use this in combination with enableLogs and without credentials when doing development or testing to avoid unwanted actions in production.

Default value is false.

enableLogs

If true, the bot will log every action it does to the console.

Default value is true.


Bot Actions

When handling an item or running a scheduled task, the bot will have access to several actions it can perform as an argument.

The actions are as follows, grouped by access level in ascending order:

No login required

Regular account

Community moderator

Admin

HTTP Client

If you need to use the lemmy client directly, the __httpClient__ property is available so you don't need add it to your project separately. For your convenience, you can also access this in paramaters for polled event handlers and scheduled tasks.

Running Your Bot

There are templates for docker and systemd in the templates folder to help you run your bot once you've made it.

Examples

Live Examples

Congratulator Bot

This bot will comment a cringy congratulations whenever a post on certain communities receives a score or 25 or more. Posts are valid to be handled after 10 minutes, but if a post ist congratulated it will no longer be eligible to be processed (due to preventReprocess being called). Posts that it's polling will be sorted by hot, and the bot will only be able to check posts in the shrek or tv communities on instance.xyz or the fediverse, cringe, and cooking communities on fediplace.ml.

import LemmyBot from 'lemmy-bot';

const bot = new LemmyBot({
  instance: 'instance.xyz',
  credentials: {
    username: 'CongratulatorBot',
    password: 'password'
  },
  connection: {
    minutesUntilReprocess: 10,
    secondsBetweenPolls: 120
  },
  dbFile: 'db.sqlite3',
  federation: {
    allowList: [
      {
        instance: 'instance.xyz',
        communities: ['shrek', 'tv']
      },
      {
        instance: 'fediplace.ml',
        communities: ['fediverse', 'cringe', 'cooking']
      }
    ]
  },
  handlers: {
    post: {
      sort: 'Hot',
      handle: ({
        postView: {
          counts: { score },
          post: { id }
        },
        botActions: { createComment },
        preventReprocess
      }) => {
        if (score > 25) {
          createComment({
            post_id: id,
            content:
              'WOW, 25+ score!?!?! Das a lot of score-arinos!!!!! Congratulations fedizen! :)'
          });
          preventReprocess();
        }
      }
    }
  }
});

bot.start();

Cringe username rejector

This bot will reject registration applications of anyone with a cringy username. The bot must have admin privileges to work.

import LemmyBot from 'lemmy-bot';

const cringeNameRegex = /(^(x|X)+.+(x|X)+$)|69|420/;

const bot = new LemmyBot({
  instance: 'instance.ml',
  credentials: {
    username: 'CringeRejector',
    password: 'password'
  },
  handlers: {
    registrationApplication: ({
      applicationView: {
        creator: { name },
        registration_application: { id }
      },
      botActions: { approveRegistrationApplication }
    }) => {
      if (cringeNameRegex.test(name)) {
        approveRegistrationApplication({
          id,
          deny_reason: 'No cringy usernames allowed',
          approve: false
        });
      }
    }
  }
});

bot.start();

Credits

Logo made by Andy Cuccaro (@andycuccaro) under the CC-BY-SA 4.0 license.