GithubHelp home page GithubHelp logo

sleeplessone1917 / lemmy-bot Goto Github PK

View Code? Open in Web Editor NEW
88.0 2.0 10.0 455 KB

A bot library for Lemmy, the fediverse link aggregator.

Home Page: https://www.npmjs.com/package/lemmy-bot

License: GNU Affero General Public License v3.0

TypeScript 99.63% Dockerfile 0.37%
bot bots fediverse fediverse-bot lemmy lemmy-bot typescript typescript-library

lemmy-bot's Introduction

License Dependencies up to date Github stars npm version Last commit Issues Open pull requests Downloads per month Typescript
Lemmy logo

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

Features

  • Respond to different events that happen in lemmy, such as posts, comments, and modlog actions
  • Perform actions on a schedule
  • Supports most actions a regular Lemmy account can make, including moderator and admin actions

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:

  • minutesBeforeRetryConnection: If the bot's connection closes, the bot will wait this many minutes before opening another connection and trying again. Default value is 5. If you don't want the bot to attempt to reconnect, pass in false.
  • secondsBetweenPolls: Number of seconds between HTTP requests the bot will make to check for items to handle. Default value is 30.
  • minutesUntilReprocess: If the bot can to potentially handle the same item more than once (e.g. polling posts by top day every minute and replying to any with more than 25 points), minutesUntilReprocess specifies how many minutes must pass until an item is valid for reprocessing. If this value is undefined, items will not be reprocessed at all. Default value is undefined. Note: It is possible that an item that is valid for reprocessing will not be handled again. Taking the example from before and polling every day instead of every minute, a post from the day before that is valid for reprocessing might not show up in the current day's top posts.

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:

  • handle: Function to run to handle an item. Acccepts the item being handled as an argument.
  • secondsBetweenPolls: Does the same thing as the one from connection. Any value provided will override the value set in connection for handling items of a given type.
  • minutesUntilReprocess: Does the same thing as the one from connection. Any value provided will override the value set in connection for handling items of a given type.

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:

  • botActions: Different actions the bot can perform. More on bot actions in the bot actions sections.
  • preventReprocess: Call if the item being handled should not be handled again, even if minutesUntilReprocess is set.
  • reprocess: Mark the item being handled as able to be reprocessed, even if minutesUntilReprocess is not set.
  • item (property name varies depending on handler): The item being handled.

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

  • comment: Handle function has commentView in the argument object. Handler options also accept sort property of type CommentSortType.
  • post: Handle function has postView in the argument object. Handler options also accept sort property of type SortType.
  • privateMessage: Handle function has messageView in the argument object.
  • comment: Handle function has commentView in the argument object.
  • registrationApplication: Handle function has applicationView in the argument object.
  • mention: Handle function has mentionView in the argument object.
  • reply: Handle function has replyView in the argument object.
  • commentReport: Handle function has reportView in the argument object.
  • postReport: Handle function has reportView in the argument object.
  • privateMessageReport: Handle function has reportView in the argument object.
  • modRemovePost: Handle function has removedPostView in the argument object.
  • modLockPost: Handle function has lockedPostView in the argument object.
  • modFeaturePost: Handle function has featurePostView in the argument object.
  • modRemoveComment: Handle function has removedCommentView in the argument object.
  • modRemoveCommunity: Handle function has removedCommunityView in the argument object.
  • modBanFromCommunity: Handle function has banView in the argument object.
  • modAddModToCommunity: Handle function has modAddedToCommunityView in the argument object.
  • modTransferCommunity: Handle function has modTransferredToCommunityView in the argument object.
  • modAddAdmin: Handle function has addedAdminView in the argument object.
  • modBanFromSite: Handle function has banView in the argument object.

federation

Options for handling federated instances. Can be one of:

  • 'local': Only handle items on the bot's local instance. This is the default setting.
  • 'all': Handle items on any instance, both local and federated.
  • object with the following properties:
    • allowList: List of instances the bot is allowed to handle items from.
    • blockList: List of instances the bot is not allowed to handle ites from.

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:

  • instance: Domain name of the instance to allow/block from.
  • communities: List of community names on the instance that should be allowed/blocked.

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:

  • cronExpression: String expression that controls when the task runs. See node-cron for valid expression syntax.
  • doTask: Run the task. Takes bot actions as an argument.
  • timezone: String stating the timezone the schedule should be in. See here for supported timezones.
  • runAtStart: Boolean value for whether or not the task should be run immediately. Defaults to false.

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

  • getCommunity(form: GetCommunity): Retrieves community. the request form can accept either a community ID or a community name. If you are doing the latter, use "{community name}@{instance}" to get results more reliably.
  • getPersonDetails(form: GetPersonDetails): Gets details about a person, including posts and comments they made and communities the moderate.
  • getPost(form: GetPost): Retrieve a post based on its ID.
  • getComment(form: GetComment): Retrieve a comment based on its ID.
  • getParentOfComment(form: Comment): Retrieves the parent of a comment. Accepts a comment object, which is returned from handlers that deal with comments (e.g. comment handler, mention handler, reply handler, etc.). Returns an object with the following properties:
    • type "post" or "comment" When type is "post":
    • post: GetPostResponse When type is "comment":
    • comment: CommentResponse
  • isCommunityMod(form: {community: Community, person: Person}): Returns whether or not a person is a moderator of a given community.

Regular account

  • createComment(form: CreateComment): Create a comment. Accepts an object with the following properties:
    • content string
    • post_id number
    • parent_id optional number
    • language_id optional number
  • reportComment(form: ReportComment): Report a comment. Accepts an object with the following properties:
    • comment_id number
    • reason string
  • reportPost(form: ReportPost): Report a post. Accepts an object with the following properties:
    • post_id number
    • reason string
  • votePost(form: VotePost): Vote on a post. Accepts an object with the following properties:
    • post_id number
    • vote Vote
  • voteComment(form: VoteComment): Vote on a comment. Accepts an object with the following properties:
    • comment_id number
    • vote Vote
  • createPost(form: CreatePost): Create a post. form has the following properties:
    • name string
    • url optional string
    • body optional string
    • nsfw optional boolean
    • language_id optional number
    • community_id number
    • honeypot optional string
  • sendPrivateMessage(form: SendPrivateMessage): Send a private message to a user. Accepts an object with the following properties:
    • recipient_id number
    • content string
  • reportPrivateMessage(form: ReportPrivateMessage): Report a private message. Accepts an object with the following properties:
    • privateMessage_id number
    • reason string
  • uploadImage(image: Buffer): Upload an image to pictrs. Returns a promise with an UploadImageResponse.
  • resolveObject(form: ResolveObject): Resolves an object on a remote instance. Use this to federate with communities that aren't showing up on your local instance yet. Note: If passing in a string, make sure it is in the format "!'community name'@'instance domain'".
  • followCommunity(form: FollowCommunity): Subscribe to a community.
  • editPost(form: EditPost): Edit a post that was made previously by the bot. The form argument has the following properties:
    • post_id number
    • name optional string
    • url optional string
    • body optional string
    • nsfw optional boolean
    • language_id optional number
  • editComment(form: EditComment): Edit a comment previously made by the bot. The form argument has the following properties:
    • comment_id number
    • content optional string
    • language_id optional number
  • listMedia(form: ListMedia): List all media that was posted by the bot. The form argument is optional and has the following properties:
    • page: number
    • limit: number
  • hidePost(form: HidePost): Hide posta so they don't show up in your feed. The form argument has the following properties:
    • postIds: number[]
    • hide: boolean

Community moderator

  • banFromCommunity(form: BanFromCommunity): Ban or unban a user from a community. Accepts an object with the following properties:
    • community_id number
    • person_id number
    • ban boolean
    • expires optional number
    • reason optional string
    • remove_data optional boolean
  • removePost(form: RemovePost): Remove a post. Accepts an object with the following properties:
    • post_id number
    • removed boolean
    • reason optional string
  • distinguishComment(form: DistinguishComment): Pin a comment to the top of a comment thread. Accepts an object with the following properties:
    • comment_id number
    • distinguished boolean
  • removeComment(form: RemoveComment): Remove a comment. Accepts an object with the following properties:
    • comment_id number
    • removed boolean
    • reason optional string
  • resolveCommentReport(form: ResolveCommentReport): Resolve a comment report. Accepts an object with the following properties:
    • report_id number
    • resolved boolean
  • resolvePostReport(form: ResolvePostReport): Resolve a post report. Accepts an object with the following properties:
    • report_id number
    • resolved boolean
  • resolveMessageReport(form: ResolvePrivateMessageReport): Resolve a private message report. Accepts an object with the following propertied:
    • report_id number
    • resolved boolean
  • featurePost(form: FeaturePost): Feature a post. Accepts an object with the following properties:
    • post_id number
    • feature_type: PostFeatureType
    • featured: boolean
  • lockPost(postId: number, locked: boolean): Lock/unlock a post. Accepts an object with the following properties:
    • pst_id number
    • locked boolean

Admin

  • getCommentVotes(form: ListCommentLikes): Show who voted on a comment, and what their vote is. Accepts an object with the following properties:
    • comment_id number
    • page optional number
    • limit optional number
  • getPostVotes(form: ListPostLikes): Show who voted on a post, and what their vote is. Accepts an object with the following properties:
    • post_id number
    • page optional number
    • limit optional number
  • banFromSite(form: BanFromSite): Ban or unban a user from the instance. Accepts an object with the following properties:
    • person_id number
    • ban number
    • expires optional number
    • reason optional string
    • remove_data optional boolean
  • approveRegistrationApplication(form: ApproveRegistrationApplication): Approve the creation of an account. Accepts an object with the following properties:
    • id number
    • approve boolean
    • deny_reason optional string
  • listAllMedia(form: ListMedia): List all media that has been posted on the instance. Optionally accepts an object with the following properties:
    • page: number
    • limit: number

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.

lemmy-bot's People

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

Watchers

 avatar  avatar

lemmy-bot's Issues

[Feature request] Optional flag to disable logs

immagine

I don't really like having my logs spammed by the library's activity, I'd prefer handling my own logging in my app, only for the operations where I deem it necessary.

I propose creating an additional, optional flag in the new LemmyBot() constructor to disable the output of logs from the library.

If @SleeplessOne1917 likes the idea I could also implement such a feature myself and submit a PR for it.

SQLITE_BUSY: database is locked

Some weird database issues..

Error: SQLITE_BUSY: database is locked
--> in Statement#run({ '$id': 42368, '$reprocessTime': null }, [Function (anonymous)])
    at Database.<anonymous> (/app/node_modules/.pnpm/[email protected]/node_modules/sqlite3/lib/sqlite3.js:76:19)
    at Database.<anonymous> (/app/node_modules/.pnpm/[email protected]/node_modules/sqlite3/lib/sqlite3.js:20:19)
    at <anonymous> (/app/node_modules/.pnpm/github.com+SleeplessOne1917+lemmy-bot@6ed4abbf3e6c343e60ecffa94059b51eae8afbb5_i365mkdgu5davuyz74udnrlrka/node_modules/lemmy-bot/dist/db.js:57:8)
    at new Promise (<anonymous>)
    at upsert (/app/node_modules/.pnpm/github.com+SleeplessOne1917+lemmy-bot@6ed4abbf3e6c343e60ecffa94059b51eae8afbb5_i365mkdgu5davuyz74udnrlrka/node_modules/lemmy-bot/dist/db.js:56:58)
    at <anonymous> (/app/node_modules/.pnpm/github.com+SleeplessOne1917+lemmy-bot@6ed4abbf3e6c343e60ecffa94059b51eae8afbb5_i365mkdgu5davuyz74udnrlrka/node_modules/lemmy-bot/dist/db.js:75:114)
    at Generator.next (<anonymous>)
    at <anonymous> (/app/node_modules/.pnpm/github.com+SleeplessOne1917+lemmy-bot@6ed4abbf3e6c343e60ecffa94059b51eae8afbb5_i365mkdgu5davuyz74udnrlrka/node_modules/lemmy-bot/dist/db.js:8:71) {
  errno: 5,
  code: 'SQLITE_BUSY',
  __augmented: true
}

Sometimes bot fails to start

Sometimes I'll start a script and it'll give me this error and exits. It'd be nice if it could gracefully handle this error.

I'm connecting to lemmy.world as my instance, which has weird connectivity issues. I'm wondering if the ws is timing out and actorId isn't getting set properly. If so, it would be nice if it could attempt to reconnect.

Log:

> ts-node src/main.ts

Connected to Lemmy Instance
Initializing DB
Logging in
Marking account as bot account
Subscribing to communities
/node_modules/lemmy-bot/dist/helpers.js:55
const extractInstanceFromActorId = (actorId) => actorId.match(/https?:\/\/(.*)\/(?:c|u)\/.*/)[1];
                                                                                             ^
TypeError: Cannot read properties of null (reading '1')
    at extractInstanceFromActorId (/node_modules/lemmy-bot/dist/helpers.js:55:94)
    at LemmyBot.<anonymous> (/node_modules/lemmy-bot/dist/bot.js:804:90)
    at Generator.next (<anonymous>)
    at /node_modules/lemmy-bot/dist/bot.js:8:71
    at new Promise (<anonymous>)
    at __awaiter (/node_modules/lemmy-bot/dist/bot.js:4:12)
    at WebSocketConnection.<anonymous> (/node_modules/lemmy-bot/dist/bot.js:449:51)
    at WebSocketConnection.emit (node:events:513:28)
    at WebSocketConnection.emit (node:domain:489:12)
    at WebSocketConnection.processFrame (/node_modules/websocket/lib/WebSocketConnection.js:554:26)
    at /node_modules/websocket/lib/WebSocketConnection.js:323:40
    at processTicksAndRejections (node:internal/process/task_queues:77:11)

Spam of logging in and other stuff

grafik

The exception is there too but it was big data comming up. But the "Loggin in ..... Subscribing...." is annoying me and it spams the console at start

Get Community (and Instance) Info/Sidebar

Hi,

Can a feature be added to get the source text of a communities' (and instances') sidebar? I would like to be able to limit where my bot is run and allowing instance and community owners to set specific markdown in the sidebar seems like the easiest way to do this.

Thanks!

Add a dryrun mode for development

I've been doing some development on a bot, and I don't want to post my in-progress threads to a live, production lemmy instance. I'd prefer to be able to set the bot to be in "dry run" mode, and only log to the console the actions it would have taken on the production instance

The new option would be used as follows

const bot = new LemmyBot.LemmyBot({
  enableLogs: true,
  dryRun: true
});

Database init fails on first/second try

Works fine in memory, on disk tends to take one or two start attempts for it to finish initialisation.

Initializing DB
/home/bwachter/git/aard/lemmy-reddit-bot/node_modules/lemmy-bot/dist/db.js:43
const getRow = (db, id, table) => new Promise((resolve, reject) => {
                                  ^
Error: SQLITE_ERROR: no such table: posts
--> in Database#get('SELECT id, reprocessTime FROM posts WHERE id=?;', 54, [Function (anonymous)])
    at /home/bwachter/git/aard/lemmy-reddit-bot/node_modules/lemmy-bot/dist/db.js:44:8
    at new Promise (<anonymous>)
    at getRow (/home/bwachter/git/aard/lemmy-reddit-bot/node_modules/lemmy-bot/dist/db.js:43:35)
    at /home/bwachter/git/aard/lemmy-reddit-bot/node_modules/lemmy-bot/dist/db.js:74:88
    at Generator.next (<anonymous>)
    at /home/bwachter/git/aard/lemmy-reddit-bot/node_modules/lemmy-bot/dist/db.js:8:71
    at new Promise (<anonymous>)
    at __awaiter (/home/bwachter/git/aard/lemmy-reddit-bot/node_modules/lemmy-bot/dist/db.js:4:12)
    at get (/home/bwachter/git/aard/lemmy-reddit-bot/node_modules/lemmy-bot/dist/db.js:74:26)
    at get (/home/bwachter/git/aard/lemmy-reddit-bot/node_modules/lemmy-bot/dist/db.js:102:26)
    at LemmyBot.<anonymous> (/home/bwachter/git/aard/lemmy-reddit-bot/node_modules/lemmy-bot/dist/bot.js:988:35)
    at Generator.next (<anonymous>)
    at /home/bwachter/git/aard/lemmy-reddit-bot/node_modules/lemmy-bot/dist/bot.js:8:71
    at new Promise (<anonymous>)
    at __awaiter (/home/bwachter/git/aard/lemmy-reddit-bot/node_modules/lemmy-bot/dist/bot.js:4:12)
    at LemmyBot._LemmyBot_handleEntry (/home/bwachter/git/aard/lemmy-reddit-bot/node_modules/lemmy-bot/dist/bot.js:987:12)
    at LemmyBot.<anonymous> (/home/bwachter/git/aard/lemmy-reddit-bot/node_modules/lemmy-bot/dist/bot.js:505:129)
    at Generator.next (<anonymous>)
    at /home/bwachter/git/aard/lemmy-reddit-bot/node_modules/lemmy-bot/dist/bot.js:8:71
    at new Promise (<anonymous>)
    at __awaiter (/home/bwachter/git/aard/lemmy-reddit-bot/node_modules/lemmy-bot/dist/bot.js:4:12)
    at /home/bwachter/git/aard/lemmy-reddit-bot/node_modules/lemmy-bot/dist/bot.js:503:64
    at Array.map (<anonymous>)
    at LemmyBot.<anonymous> (/home/bwachter/git/aard/lemmy-reddit-bot/node_modules/lemmy-bot/dist/bot.js:503:46)
    at Generator.next (<anonymous>)
    at /home/bwachter/git/aard/lemmy-reddit-bot/node_modules/lemmy-bot/dist/bot.js:8:71
    at new Promise (<anonymous>) {
  errno: 1,
  code: 'SQLITE_ERROR',
  __augmented: true
}

First fetch works second not anymore

I created a bot and it didnt got any posts from my community. And after i debugged it. It fetches 1 time correctly but then it doesnt fetch it anymore.

  lemmyService.bot = new LemmyBot({
          instance: process.env.LEMMY_INSTANCE!,
          credentials: {
            username: process.env.LEMMY_USERNAME!,
            password: process.env.LEMMY_PW!,
          },
          connection: {
            minutesUntilReprocess: 1,
            secondsBetweenPolls: 30,
          },
          schedule: [],
          federation: "all",
          dbFile: "./lemmy.db",
          handlers: {
post: async ({
              botActions,
              postView,
              preventReprocess,
              reprocess,
            }) => {
        console.log("NEW POST")
                  });

It logs like in the initial start the first 30 posts and then i can wait like for 15 minutes nothing happens

Unable to run bot due to issues with the examples

Hi, wondering if you could help with where I'm going wrong.

I'm using the like me bot example, and getting the error "Expected 1 arguments, but got 2. (ts2554) on the Vote.Upvote lines and the same error on the SendPrivateMessage lines where the text is flagging the same error.

I'm really new to this so most likely an error with my setup but google has been no help in figuring this out.

Thanks

image

edit: on Lemmy 0.18 and using bot version 0.4

just sits at "user_already_exists"

Can't seem to get any further, it logs in, marks user as bot, and then just sits at user_already_exists

Not sure where the logs are dumped

Does not work on the new 0.18.0 update.

Hey! I haven't gotten my bot to work after updating the instance to Lemmy 0.18.0. Is this because they no longer are using websockets? If so, will this library update?

Invalid JSON response body when starting up

I've got a bot for lemmy.world and it has stopped working since they've upgraded to 0.18.1-rc.4
It fails at logging in:

Starting bot
Initializing DB
app listening at http://localhost:1234
logging in

D:\projects\lemmybot\node_modules\node-fetch\lib\index.js:273
                                return Body.Promise.reject(new FetchError(`invalid json response body at ${_this2.url} reason: ${err.message}`, 'invalid-json'));
                                                           ^
FetchError: invalid json response body at https://lemmy.world/api/v3/user/login reason: Unexpected token J in JSON at position 0
    at D:\projects\lemmybot\node_modules\node-fetch\lib\index.js:273:32
    at processTicksAndRejections (node:internal/process/task_queues:96:5) {
  type: 'invalid-json'
}

I've double checked, the account credentials I'm passing in are valid.

No editComment or editPost Bot Action?

I'm looking into making a bot that lets commenters vote on what genres apply to the story and then locks it and logs it into a database that will (probably) be web-accessible.
I, admittedly, have not worked on it at all yet, but I'm imagining the comment will be updated to reflect what genres have been accepted and (maybe) a link to find more like it.

If there's no way to edit a comment via this (or any other) library, then this project will be a non-starter and probably dropped before it's even started.

"Sending private message to user ID undefined"

function onPrivateMessage(res){
	console.log(res)
	res.botActions.sendPrivateMessage(res.messageView.private_message.creator_id, "holaa")
}

this prints Sending private message to user ID undefined and does not send anything

[bug] federation allowList does not seem to work

The allowList property of the federation option does not seem to be followed, and the bot will reply to all comments/posts on any federated community.
example:

federation: {
  allowList: [
    {
      instance: 'lemmy.world',
      communities: ['vexillology']
    },
    {
      instance: 'lemmy.antemeridiem.xyz',
      communities: ['vexillologyjerk']
    }
  ]
},

I am using lemmy-bot 0.3.9 from npm

Bot creates a 502 Error

grafik

It happens when the ratelimit is achieved, it happens every time on lemmy.world and i have my poll rate at 15 ( i tested at 120 ). But it will straight up 502 Gateway Error ( Sometimes /comment sometimes /posts ) and after few seconds the login will fail too because it gets tot the ratelimit too.

I would guess the requests between comments and posts are too fast and need a buffer between them ( just use the poll rate as buffer between calls )

Tried Lemmy Instance:
lemmy.world

getUserId and getCommunityId dont always find the user/community

Due to how getUserId and getCommunityId try to find the id (using the search), if the actual user or community doesnt show up in that then it cant be found by the query

For example if you try to look for the id of the community [email protected]. Doing a call to getCommunityId("git") then does an api call to https://programming.dev/api/v3/search?q=git&type_=Communities which does not have git as one of the options (instead its populated by other things that have git in the name)

"Removing comment ID undefined" but the ID is defined

to remove a comment I'm using

botActions.removeComment({
	reason: "Requested by user " + userName,
	removed: true,
	comment_id: parentId
});

with parentId defined, but it prints Removing comment ID undefined and does not remove the comment.

Program stops after some time with ETIMEDOUT error.

i created simple bot with posts and privateMessage handlers. After running for some time it closes with the following error:

node main.js    
Starting bot
Initializing DB
(node:89951) [DEP0040] DeprecationWarning: The `punycode` module is deprecated. Please use a userland alternative instead.
(Use `node --trace-deprecation ...` to show where the warning was created)
Logging in
Logged in

/home/dell/dbx-home/image_compare/node_modules/node-fetch/lib/index.js:1501
			reject(new FetchError(`request to ${request.url} failed, reason: ${err.message}`, 'system', err));
			       ^
FetchError: request to https://lemmy.world/api/v3/post/list?type_=Subscribed&auth=*censored*&sort=New failed, reason: 
    at ClientRequest.<anonymous> (/home/dell/dbx-home/image_compare/node_modules/node-fetch/lib/index.js:1501:11)
    at ClientRequest.emit (node:events:519:28)
    at TLSSocket.socketErrorListener (node:_http_client:495:9)
    at TLSSocket.emit (node:events:519:28)
    at emitErrorNT (node:internal/streams/destroy:169:8)
    at emitErrorCloseNT (node:internal/streams/destroy:128:3)
    at processTicksAndRejections (node:internal/process/task_queues:82:21)
    at runNextTicks (node:internal/process/task_queues:64:3)
    at listOnTimeout (node:internal/timers:540:9)
    at process.processTimers (node:internal/timers:514:7) {
  type: 'system',
  errno: 'ETIMEDOUT',
  code: 'ETIMEDOUT'
}

Node.js v21.5.0

It works for 20-30 mins before closing. One time it closed right after starting.

Detect if Post URL / Image / Title / Body changed?

I was wondering if Lemmy has any native ability to detect if a post was changed, and what was changed without having to store that information in an external database? If so, does lemmy-bot also have that functionality?

createComment does nothing?

I made that the bot automatically sends a message to a new post in a community. Everything works and the library replies with

"Replying to post ID 651474"

My Code:

      botActions.createComment({
                content: Config.autoComment.text,
                postId: postView.post.id,
              });

But nothing happens

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.