Giter Club home page Giter Club logo

booru's Introduction

booru

A node package to search boorus

CircleCI npm GitHub Typescript typings

Features

  • Search 15 different boorus (check sites.json)
  • Normalizes all received data into Post objects that are consistent no matter which booru you use
  • Access to the raw data received from the booru as well (transformed from XML to JSON, if applicable)
  • Alias support for boorus (sb for safebooru.org)
  • Promises
  • Types (using Typescript)
  • Choose the amount of images to get
  • Random support for all sites, using order:random on sites that support it and using custom code on those that don't
  • Coming soon(-ish): Support for more than just searching

Installation

npm add booru
# or
yarn add booru

Usage

const Booru = require('booru')

Booru.search('safebooru', ['glaceon'], { limit: 3, random: true }).then(
  posts => {
    for (let post of posts) console.log(post.fileUrl, post.postView)
  },
)

// or (using alias support and creating boorus)
const sb = Booru.forSite('sb')

sb.search(['cat', 'dog'], { limit: 2 })

See example.js for more examples


Docs

Available here: https://booru.js.org

Web support

booru was built for Node.js, and is only officially supported for Node.js. Issues relating to web are fine, although support might be limited.

It's possible to use booru on the web using webpack (or similar), although your experience may vary. Some websites don't have the proper CORS headers, meaning that API requests to those sites from a browser will fail! This is not an issue I can fix in the package, and requires either that booru to add proper support themselves or for you to find a workaround for CORS.

FAQ

What are the properties of a Post?

The basic structure of a Post object looks like:

Post {
  data: {/*...*/},                       // The raw data from the booru
  fileUrl: 'https://aaaa.com/img.jpg',    // The direct link to the image, ready to post
  id: '124125',                           // The image ID, as a string
  tags: ['cat', 'cute'],                  // The tags, split into an Array
  score: 5,                               // The score as a Number
  source: 'https://ex.com/aaa.png',       // Source of the image, if supplied
  rating: 's',                            // Rating of the image
  createdAt: Date,                        // The `Date` this image was created at
  postView: 'https://booru.ex/show/12345' // A URL to the post
}

s: 'Safe' q: 'Questionable' e: 'Explicit' u: 'Unrated'

Derpibooru has Safe, Suggestive, Questionable, Explicit, although Suggestive will be shown as q in <Post>.rating

Can I contribute?

Sure! Just fork this repo, push your changes, and then make a PR.

I'll accept PR based on what they do and code style (Not super strict about it, but it's best if it roughly follows the rest of the code)

Why?

Why not?

License?

It's MIT


Contributors

BobbyWibowo

Change from request-promise-native to snek-fetch

rubikscraft

Add 2 new boorus (furry.booru.org/realbooru.com)
Various Derpibooru fixes

Favna

Add TypeScript declarations
Improve TypeScript port
Various other small fixes

negezor

Add missing type information

iguessthislldo

Copy tags argument so it's not modified


booru's People

Contributors

atorasuunva avatar bobbywibowo avatar favna avatar iguessthislldo avatar negezor avatar respektive avatar slayerduck avatar youliao 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

Watchers

 avatar  avatar  avatar  avatar  avatar

booru's Issues

Cannot assign to read only property 'random'

After updating from 2.0.3 to 2.0.4, I receive an error whenever trying to do a search. Tested with both Gelbooru and Safebooru and both throw the same error. Issue is resolved upon rolling back to 2.0.3.

[2019-12-18 22:18:49]: ERROR Unhandled rejection: TypeError: Cannot assign to read only property 'random' of object '[object Object]'

Code below is from the discord.js project that I noticed the issue in.

  const booru = require("booru");
  var site = (! ["dm","group"].includes(message.channel.type) ? (message.channel.nsfw ? "gb" : "sb") : "sb");
  var taglist = args.join(" ");
  var tagarray = taglist.split(", ");
  for (var i=0;i<tagarray.length;i++) {
    tagarray[i] = tagarray[i].replace(/\s/g, "_");
  }
  if (site == "gb") tagarray.push("-webm", "-mp4");
  var img = await booru.search(site, tagarray, {limit: 1, random: true});
  if (!img[0]) {
    message.channel.send("No results found.");
    client.logger.warn(`No results found for tags: ${tagarray.join(", ")}`);
    return;
  }
  const embed = {"embed": {
    "title": `${site == "gb" ? "Gelbooru" : "Safebooru"} #${img[0].id}`,
    "url": `https://${site == "sb" ? "safebooru.org" : "gelbooru.com"}/index.php?page=post&s=view&id=${img[0].id}`,
    "color": client.colorInt(site == "sb" ? "#84a8b9" : "#006ffa"),
    "image": {"url": img[0].file_url},
    "footer": {"text":`Score: ${img[0].score}`}
  }};
  client.logger.log(`${site == "gb" ? "Gelbooru" : "Safebooru"} #${img[0].id} found for tags: ${tagarray.join(", ")}`);
  message.channel.send(embed);

Recomendation - switch from Snekfetch to node-fetch

Honestly... it's a tough story to explain. Snekfetch was made by a developer on the DiscordJS library and through that it got the most usage but starting v4.X it got a lot of issues and DiscordJS ended up switching to Node-Fetch instead. You can read the full story on this PR.

Anyway to the point, now that DiscordJS has dropped usage of Snekfetch the usage base for the lib has dropped enormously with it and now when installing booru through yarn it will even tell users to switch to node-fetch:

yarn install v1.10.1
info No lockfile found.
[1/5] Validating package.json...
[2/5] Resolving packages...
warning booru > [email protected]: use node-fetch instead
warning [email protected]: use node-fetch instead
[3/5] Fetching packages...
[4/5] Linking dependencies..

I personally made the jump from snekfetch to node-fetch a while ago for my Discord bot and while I have to admit it was quite an undertaking due to the different code structure it uses, it wasn't all too bad and I suppose that for a lib such as Booru it would take at most 2-3 hours if not less (depending on how quickly you can grasp the way node-fetch works)

Move to full OOP

Essentially rewrite the whole thing to make it more easily extensible in terms of supporting different boorus, with the final goal of adding more functionality than just searching boorus (Things like fetching the comments or allowing for login use to favorite pics or whatever.)

Backwards compatibility will still remain in some form, but might be removed in later releases so don't depend on it.

If you have any questions/comments/suggestions reply to this issue and I'll get back to you.

A very basic schema of what is going to happen is here:

  • index.js // just requires/exports the required things

    • Booru()
      => returns an object with
      • .search(site, [tags...], {limit, random})
      • [~] .postView(site, id) BooruImages Posts have a .postView prop now!
    • new Booru(site, {options})
    • .resolveSite(site/alias)
      => {site details}
    • .sites
      => {all sites}
    • .commonfy()
      => Do nothing, add <Post>.common getter to images/posts instead
  • src/

    • new Post

      • Constructor, params => data:Object, booru:IBooru
      • .common, get that replicates old .commonfy() function
    • Utils

      • .jsonfy([images])
      • .shuffle([arr])
      • .randInt(min, max)
      • .resolveSite(site/alias)
    • Constants

      • .sites
      • .BooruError
      • .userAgent
      • .searchURI(site, tags, limit) => http://${site}${sites[site].api}${(sites[site].tagQuery) ? sites[site].tagQuery : 'tags'}=${tags.join('+')}&limit=${limit}
    • sites.json

  • src/booru

    • new Booru // (Abstract Class), you shouldn't need to use this directly
      • Constructor, params (site, [credentials])
      • .search([tags...], {limit, random})
      • .postView(id)
      • .site
    • new JSONBooru : Booru // Class for the default boorus
    • new XMLBooru : Booru
    • new Derpibooru : Booru // They have weird randomization logic & api
    • 'Other boorus with specific things'?

Also coming is better JSDoc, for better intellisense :)

Yeah intellisense!

Received HTTP 422 from booru: 'PostQuery::TagLimitError'

Hello! It's me, again c:

I got this error while trying to get 1 post from danbooru with tags: angel, white_hair, rating:safe
image

await Booru.search(site, tag, { limit: 1, random: true }).then(posts => posts[0])

I guess isn't your issue, is it API, but anyway, can you recommend something or do with this?

"Cannot set property: 'file_url' of undefined"

Whenever I try searching on gelbooru, it always says "This function should only recieve images: TypeError: Cannot set property 'file_url' of undefined" whenever I try logging the file url, i've even tried the example code to make sure I wasn't just being dumb, am I still being dumb or is there something wrong?

Pagination?

Is it possible to specify page parameter for request (for example, &pid=2 for gelbooru)?

Return artist(s) & character(s)

I think it'd be nice if the data object also returned the artist(s) and character(s) like shown in the image below
img

Right now it returns an owner which I assume is the uploader, but personally I think it's more relevant to get the artist(s) and character(s). Would also be very useful, at least for my project but I'm sure other's could make use of that as well 😄

Booru is not a constructor?

so here's my code.

const Booru = require('booru') // load the fucking uhh
const sb = new Booru("sb")
const Discord = require('discord.js'); // make discord actually need discord.js
const client = new Discord.Client(); // make bot do a fucking exist
const prefix = "#"; // prefix what the fuck else to say
const version = "3.1 alpha";
const botname = "MSPABot";
const hostsys = "Debian 10 using Windows 10 Home"
const imgsfw = sb.search(['homestuck'])

client.on("message", (message) => {
// Exit and stop if it's not there
if (!message.content.startsWith(prefix)) return;

if (message.content.startsWith(prefix + "imgtest")) {
message.channel.send(botname + " " + version + " " + hostsys + "\n" + imgsfw[0].postView);
} else
if (message.content.startsWith(prefix + "foo")) {
message.channel.send("bar!");
}
});

client.login("mmm im not putting the token on git ;)");

every run though i get the following:

/home/saiko/MSPABot/main.js:2
const sb = new Booru("sb")
^

TypeError: Booru is not a constructor

clearly booru is a constructor. what

Extra tag/Number of tags

I'm working on a discord bot using discord.js and node.js.
One of my command code can be seen here: https://pastebin.com/bptJySts

What the command is supposed to do is generate two danbooru images based on the tags provided in 'args', which is an array. However, when I attempt to use the Booru.search, args seems to gain an extra order:random value, which interferes with the search since it adds an extra unneeded value. Is there something wrong with how I'm using the command?

Video

Hi how do i make it return mp4 or webp instead of images?

Issues regarding gelbooru API changes

Hello, I would like to know if you could add more security to the package regarding API changes that could occur.
Let me explain, I am using this package in one of my application and that change was breaking my whole application when the search function was used. It caused a lot of downtime since I had to restard my application clusters manually.

Thanks.

BooruError: Failed to execute 'fetch' on 'Window': Illegal invocation

Not sure if this is an issue on my end, but I get the above error when running

export const getLinks = (): AppThunk => dispatch => { 

  Booru.search('safebooru', ['glaceon'], { limit: 3, random: true })
    .then((posts: BooruPost[]) => {
      let arr = posts.map((p: BooruPost) => {
        return p.fileUrl;
      });
      dispatch(populate(arr));
    }).catch((err: any) => {
      console.error("whomp whomp  " + err)
    });

};

Also, I'm using this in a react, redux web app if that is relevant.

Gelbooru limits anonymous usage now

The limit seems to be pretty low. Anytime I try to search on gelbooru I get an error saying Search error: We have exceeded maximum queries per day for anonymous usage. Yukkuri Shiteitte ne! :<. This can be avoided by setting the api_key and uesr_id URL parameters, which i currently do in a bit of a hacky way, by editing the api search url. In the future the credentials param on the BooruClass should probably be used.

Tags query encoding is wrong

The newest version changes the way tags are encoded. It used to encode the individual tags and concatenate them with + symbols. Now it's encoding the entire string of tags including the + symbols.
E.g. it used to be like this:
https://gelbooru.com/index.php?page=dapi&s=post&q=index&json=1&tags=izumi_konata+-rating%3Aexplicit+-rating%3Aquestionable
and it now turned into:
https://gelbooru.com/index.php?page=dapi&s=post&q=index&json=1&tags=izumi_konata%2B-rating%253Aexplicit%2B-rating%253Aquestionable
This breaks at least the gelbooru api, didn't test for other sites.

Could not find a declaration file for module 'node-fetch'

Error

node_modules/booru/dist/Constants.d.ts:1:29 - error TS7016: Could not find a declaration file for module 'node-fetch'. '../node_modules/node-fetch/lib/index.js' implicitly has an 'any' type.
  Try `npm i --save-dev @types/node-fetch` if it exists or add a new declaration (.d.ts) file containing `declare module 'node-fetch';`

1 import { RequestInit } from 'node-fetch';
                              ~~~~~~~~~~~~

[17:32:57] Found 1 error. Watching for file changes.

package.json

{
  "devDependencies": {
     "@types/node-fetch": "^3.0.3"
  }
}

site issue

image
the bot was working fine but recently its been showing me this error, the error gets fixed when switched to other sites
heres my code:
const Booru = require('booru');
module.exports = {
name: 'rule34',

async execute(message, args1, Discord){ 
  
    const posts = await Booru.search('rule34', args1, {limit:3, random: true})

return console.log(posts[0].fileUrl)

}}

Gelbooru search doesn't work for tags with special characters

I noticed that on the newest version tags like 6+girls don't works anymore even after escaping the special characters using the encodeURIComponent() function.

On top of that it seems like that tags like :3 or :d that usually work fine break after encoding them. This was not the case before.

Search available tags

Unless the documentation is incomplete or I'm blind, there doesn't appear to be a way to search for tags by partial strings?
For example, searching "opp" would return a list of tags that contain "opp", such as "oppai". This would be very helpful.

Also, a simple "most popular" list of tags to serve as an introduction would be nice.
More info here: https://gelbooru.com/index.php?page=wiki&s=view&id=18780
under "Tag List"

Common returning undefined

When using "common.file_url" is returning the following error

TypeError: Cannot read property 'file_url' of undefined

Always finds the same image

No matter the site used, it always returns the exact same image. Instead of this behaviour it should randomly pick an image from the site. My code right now is:

 if (msg.content.startsWith(delimiter + "r34")) {
            if (msg.channel.id !== "263731711714525194" && msg.channel.id !== "217745836094783488") {
                msg.reply("NSFW commands can only be used in <#263731711714525194> and <#217745836094783488>");
                return;
            }

            let rule34Tags = msg.content.slice(5).split(" ");
            if (rule34Tags[0] === '') {
                msg.reply("Please provide tags to search for");
                return;
            }

            booru.search("r34", rule34Tags, 2)
                .then(booru.commonfy)
                .then(images => {
                    //Log the direct link to each image 
                    for (let image of images) {
                        msg.channel.sendMessage(`Score: ${image.common.score}\nImage: ${image.common.file_url}`);
                    }
                })
                .catch(err => {
                    if (err.name === 'booruError') {
                        msg.reply("Something went wrong! Try contacting <@112001393140723712>");
                        console.log(err.message);
                    } else {
                        console.log(err);
                    }
                })
        }

Help me booru is broken

Broken

Screenshot_2021-09-11-12-09-03-527_com android chrome
Screenshot_2021-09-11-12-09-10-781_com android chrome
![Screenshot_2021-09-11-12-09-16-591_com android chrome](https://user-images.githubusercontent.com/71258192/132944650-9862fe22-cbdd-47ff-8819-741123297776.jpg)

Cannot read property 'toString' of undefined, node_modules\booru\dist\structures\Post.js:1:1897

(node:13644) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'toString' of undefined
at new Post (C:\Users\user\Desktop\Makise-master\node_modules\booru\dist\structures\Post.js:1:1897)
at C:\Users\user\Desktop\Makise-master\node_modules\booru\dist\boorus\Booru.js:1:2125
at Array.map ()
at Booru.parseSearchResult (C:\Users\user\Desktop\Makise-master\node_modules\booru\dist\boorus\Booru.js:1:2118)
at Booru.search (C:\Users\user\Desktop\Makise-master\node_modules\booru\dist\boorus\Booru.js:1:865)
at runMicrotasks ()
at processTicksAndRejections (internal/process/task_queues.js:97:5)

this happens around 2 out of 10 times when I use the search function on danbooru, randomly

Tags are being encoded twice

It looks like the tags are being encoded twice, because tags like -rating:explicit should be -rating%3Aexplicit. Instead the tag used in the URL looks like this -rating%253Aexplicit which implies that the % symbol is being encoded which is in fact %25.

I believe this happens, because the function that's supposed to construct the query string is encoding the already encoded tags again, but I didn't have the time to confirm this yet.

Score does not counted

I seen this problem in 2.5.3 ver and also in 2.5.6 ver of library
Code example:

 let res = await BooruSearch(defaultSite.toLowerCase(), tags);
console.log(res.score);

So, if we check documentation, we can see that res.score must be score of post in Number type
Score even not only 0 everytime, he's also sometimes became to the null(in 2.5.3 ver, at least all time been 0)
console.log screenshot
Check this problem please

Cannot read property \'length\' of undefined (Sorry if this has been answered)

Sorry if this has been answered somewhere, I searched around and couldn't find anything, I understand alot in Javascript but I'm kind of new to it. I'm making a r34 function for my discord bot and I found this on npm, I tried this V what you see below, but no matter what I do to it, or even use the example provided the console spits this BooruError : "Cannot read property 'length' of undefined", I'm using discord.js if you wanted to know.

try {
const booruData = await booru.search('rule34.xxx', args, {
'limit': 1,
'random': true
}).then(booru.commonfy);

             if (booruData) {
               message.delete(200);

               return message.channel.send(`Score: ${booruData[0].common.score}\n Image: ${booruData[0].common.file_url}`);
            }

        return message.reply('⚠️ No juicy images found.');

} catch (BooruError) {
console.log(BooruError);
return message.reply('⚠️ No juicy images found.(err)');
}

Empty posts for all sites but sb

Code:

     module.exports = {
     name: 'fap',
    category: 'nsfw',
    description: 'Bot will post fap picture that you want',
    
    run: async (bot, message, args ) =>{
        const discord  = require('discord.js'); // bot stuff 
        
        const { RichEmbed } = require('discord.js'); 

        const Booru = require('booru')
        const { BooruError, sites } = require('booru')

        const site = 'rule34.xxx'
        const tags = [`${args[0]}`] //tags from msg's args

        await message.delete().catch (O_o=>{}); //delete msg that calls command


    if (message.channel.nsfw == true) // if  command called in nsfw channel than execute code  {

        const posts = await Booru.search(site, tags, {limit: 1, random: true});


        console.log(posts[0]);
        console.log(tags);

    /*
        console.log(`--------------------`)
        console.log(`Posting fap pic`)
        console.log(tags);
        console.log(posts[0].fileUrl);
        console.log(`--------------------`)

        
        const Embed = new discord.MessageEmbed()
	            .setColor('#d91c0b')
	            .setImage(`${posts[0].fileUrl}`)
                .setTimestamp()
                .setFooter(`Заказал: ${message.author.tag}`)

        message.channel.send(Embed);
    } else { 
        message.channel.send(':warning: You can't fap in public places')
    }
    */



Output:

undefined (empty posts[0] ?)
[ 'ahri' ] (tag)

And same issue for all sites, but safebooru.

rating:questionable not working for danbooru

rating:safe danbooru images work,
as do rating:questionable images for yande.re and konachan.com.
But this rating doesn't return anything for Danbooru specifically

My code if you believe it's on my end:

const BOORU = require('booru');


module.exports.run = async (bot,message,args) => {
    let site;
    let tag = args[1]
    let notPicked = false

    switch(args[0]) {
        case "dan":
          site = 'danbooru'
          break;
        case "yan":
          site = 'yande.re'
          break;
        case "kon":
          site = 'konachan.com'
          break;
        default:
            message.channel.send("Please pick a supported site :^)");
            notPicked = true
      }

      if(!notPicked){
        if(args[1] == "nsfw"){
            tag = args[2]

            if(tag == "guro" || tag == "loli" || tag == "despacito"){
                message.channel.send("https://www.betterhelp.com/");
            }
            else{
                if(message.channel.nsfw == true ){
                    rando = Math.floor(Math.random() * 5);
                    let rating = "rating:questionable";
                    
                    if (rando == 0){
                        rating = 'rating:explicit';
                    }

                    BOORU.search(site, [rating,tag], {random:true})
                    .then(
                        (images) => {
                            let index = Math.floor(Math.random() * images.length); // Select a random imagefrom images array
                            let image = images[index];
                            let url = image.common.file_url;
                            message.channel.send(url);
                        }
                    )
                    .catch(err => message.channel.send("Nothing turned up."));         
                }
                else{
                    message.channel.send("Go to a NSFW channel first :^)");
                }
            }
        }
        else{
            console.log(tag)
            
            BOORU.search(site, ['rating:safe',tag], {random:true})
            .then(
                (images) => {
                    let index = Math.floor(Math.random() * images.length); // Select a random imagefrom images array
                    let image = images[index];
                    let url = image.common.file_url;
                    console.log(url);
                    message.channel.send(url);
                }
            )
            .catch(err => message.channel.send("Nothing turned up."));
        }
    }
}

module.exports.info = {
    name: "Booru"
}

Danbooru seem to be only returning its source URL?

Did the site go even more gei or ...?

Example result after commonfy():

[ { id: 968062,
  created_at: '2011-08-04T04:14:03.724-04:00',
  uploader_id: 34945,
  score: 10,
  source: 'http://img01.pixiv.net/img/michael/20819382.jpg',
  last_comment_bumped_at: '2011-08-04T15:21:16.810-04:00',
  rating: 'e',
  image_width: 800,
  image_height: 1025,
  tag_string: '1girl apron apron_lift bad_id bad_pixiv_id black_hair blush brown_eyes censored fingering loli masturbation mika-shi naked_apron nude original pussy pussy_juice ribbon short_hair solo twintails',
  is_note_locked: false,
  fav_count: 7,
  last_noted_at: '2011-08-04T08:14:46.811-04:00',
  is_rating_locked: false,
  parent_id: null,
  has_children: false,
  approver_id: null,
  tag_count_general: 18,
  tag_count_artist: 1,
  tag_count_character: 0,
  tag_count_copyright: 1,
  file_size: 381008,
  is_status_locked: false,
  fav_string: 'fav:63434 fav:13038 fav:377489 fav:415533 fav:389227 fav:429003 fav:361142',
  pool_string: '',
  up_score: 6,
  down_score: 0,
  is_pending: false,
  is_flagged: false,
  is_deleted: false,
  tag_count: 22,
  updated_at: '2017-01-06T12:27:42.935-05:00',
  is_banned: false,
  pixiv_id: 20819382,
  last_commented_at: '2011-08-04T15:21:16.810-04:00',
  has_active_children: false,
  bit_flags: 0,
  tag_count_meta: 2,
  keeper_data: null,
  uploader_name: 'Monki',
  has_large: false,
  has_visible_children: false,
  children_ids: null,
  tag_string_general: '1girl apron apron_lift black_hair blush brown_eyes censored fingering loli masturbation naked_apron nude pussy pussy_juice ribbon short_hair solo twintails',
  tag_string_character: '',
  tag_string_copyright: 'original',
  tag_string_artist: 'mika-shi',
  tag_string_meta: 'bad_id bad_pixiv_id',
  common: 
   { file_url: 'http://img01.pixiv.net/img/michael/20819382.jpg',
     id: '968062',
     tags: [Array],
     score: 10,
     source: 'http://img01.pixiv.net/img/michael/20819382.jpg',
     rating: 'e' } } ]

Illegal invocation at Booru.search

i'm trying to do a frontend with react using booru, but every time i try to make the search, it gives the error:

Constants.js:24 Uncaught (in promise) BooruError: Failed to execute 'fetch' on 'Window': Illegal invocation at Booru.search (http://localhost:3000/static/js/0.chunk.js:543:13)

there is the code, sorry for some words being in portuguese:

import React from "react";
import { search } from "booru";
import "./Main.css";

export default function Main() {
  let tmpTags;
  let tags;
  let listOfLinks;
  let posts;

  async function handleSubmit() {
    tags = tmpTags.split();
    console.log(tags);
    listOfLinks = [];
    posts = await search("rule34", tags, {
      limit: 1,
      random: true
    });
    console.log(posts)
    for (let post of posts) {
      await listOfLinks.push(String(post.fileUrl));
    }
    console.log(tags);
  }

  return (
    <div className="main-container">
      <h1 className="titulo">Booru Pack Downloader</h1>
      <input
        className="barra-de-pesquisa"
        value={tmpTags}
        placeholder="Quais tags você quer pesquisar?"
        onChange={e => (tmpTags = e.target.value)}
      />
      <button className="botão-de-pesquisa" onClick={handleSubmit}>
        pesquisar
      </button>
    </div>
  );
}

Searching NSFW sites returns "this site is not supported

I'm currently working on a Discord bot and I wanted to add a "pics" command that would return pics based on inserted tags.
While SFW search is working fine (tested more than 10 times), every NSFW site search returns same 'BooruError'

Site not supported

Here I send all necessary files to reconstruct this problem (including purge/reload commands if you wanted to make testing it easier).
NSFWerror.zip
Thank you in advance.

Received HTTP 404 from booru?

Here's what the log says:

node:internal/process/promises:246
          triggerUncaughtException(err, true /* fromPromise */);
          ^

BooruError: Received HTTP 404 from booru: '{}'
    at Booru.doSearchRequest (C:\Users\dimas\Desktop\dimacbot\node_modules\booru\dist\boorus\Booru.js:1:1966)
    at processTicksAndRejections (node:internal/process/task_queues:96:5)
    at async Booru.search (C:\Users\dimas\Desktop\dimacbot\node_modules\booru\dist\boorus\Booru.js:1:841)

BTW, it's a Discord bot on a local machine. So i put this on the code instead:

const Booru = require('booru')

module.exports = {
    info: {
        name: "booru",
        description: "booru image scraper",
        cooldown: 30,
    },
    async execute(client, message, args, Discord) {
        const image_query = args.join(' ');
        if (!image_query) {
            message.channel.send("i'm very sorry, but i cannot find what you are looking for.")
        }
        Booru.search('yandere', image_query, { limit: 1, random: true })
        const booruEmbed = new Discord.MessageEmbed()
        .setColor('#990000')
        .setTitle('You want me to look for an image?')
        .setDescription("Here's what i have found according to what you have specified. I hope this result satisfies you.")
        .setThumbnail('https://media.discordapp.net/attachments/898563395807232061/899534056356724756/sketch-1634535999710.png?width=499&height=499')
        .setImage(Booru.search.url)
        .setFooter('Egg-Shaped Battle Maid', 'https://images-ext-2.discordapp.net/external/l7-PY5Kkvta4_p-sOE0ftwQCmJ9iAe72eMPSTczuWi0/%3Fsize%3D512/https/cdn.discordapp.com/avatars/897674562265817088/e36ef03370367a4b3cd51b864e9df392.png?width=499&height=499');
    
        message.channel.send(booruEmbed);
    }
} 

If it was impossible for Discord bots hosted locally to do this to begin with, please tell me.

What am I doing wrong?

I am trying to make a discord bot to get images off of danbooru, here is my code

if (message.content === '?nsfw' && message.channel.nsfw === true) { async function f() { let img = await dan.search(['a secret'], {limit: 1}) return message.channel.send(img[0].postView) }
There is nothing in the logs or in the discord channel.

Is there no callback for when a site returns no posts?

I've been pulling my hair out in clumps because the error callback (from the promise thing) .catch((err) => )isn't firing when a site does not return a result. How do I deal with that sort of error? I have not found any resources so far on the documentation site.

tags

is there a way to where it can pull the tags so it can be set as the description

blacklist tags

just a simple question
is there a feature to blacklist tags on this package?
if not, i already have my own way to block certain words on my discord bot code with just using if(message.content.includes(blacklist)).
but this method couldn't blacklist more than one tags without making the code incredibly messy.

edit: even if i blacklisted a word using that code, it could still return image tagged with something that i want to blacklist if the tags are specific enough.

TypeError: resolvedFetch is not a function

TypeError: resolvedFetch is not a function
    at Booru.doSearchRequest (<omitted>\node_modules\booru\dist\boorus\Booru.js:1:1639)
    at Booru.search (<omitted>\node_modules\booru\dist\boorus\Booru.js:1:821)
    at Object.search (<omitted>\node_modules\booru\dist\index.js:1:1555)
    at <omitted>\handlers\booru.js:23:21
    at new Promise (<anonymous>)
    at Object.<anonymous> (<omitted>\handlers\booru.js:22:16)
    at Generator.next (<anonymous>)
    at <omitted>\handlers\booru.js:8:71
    at new Promise (<anonymous>)
    at __awaiter (<omitted>\handlers\booru.js:4:12)
    at <omitted>\handlers\booru.js:21:64
    at node:electron/js2c/browser_init:201:579
    at Object.<anonymous> (node:electron/js2c/browser_init:165:10272)
    at Object.emit (node:events:394:28) {
  name: 'BooruError'
}

Booru version: 2.6.2
Node version: 14.15.0

Tried with any booru.
Before that, using v2.4.0, every NSFW boorus throws an error like this:

TypeError: Cannot read properties of undefined (reading 'split')
    at getTags (<omitted>\node_modules\booru\dist\structures\Post.js:1:810)
    at new Post (<omitted>\node_modules\booru\dist\structures\Post.js:1:1922)
    at <omitted>\node_modules\booru\dist\boorus\Booru.js:1:2386
    at Array.map (<anonymous>)
    at Booru.parseSearchResult (<omitted>\node_modules\booru\dist\boorus\Booru.js:1:2378)
    at Booru.search (<omitted>\node_modules\booru\dist\boorus\Booru.js:1:902)
    at processTicksAndRejections (node:internal/process/task_queues:96:5){
  name: 'BooruError'
}

While SFW boorus works normally.

Linux error

When I run this module on a Linux device it just crashes with this error code:

/home/pi/scraperv212/node_modules/booru/dist/Utils.js:1
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.compareArrays=exports.validateSearchParams=exports.randInt=exports.shuffle=exports.jsonfy=exports.resolveSite=void 0;const Constants_1=require("./Constants"),fast_xml_parser_1=require("fast-xml-parser");function resolveSite(t){if("string"!=typeof t)return null;t=t.toLowerCase();for(const r in Constants_1.sites)if(r===t||Constants_1.sites[r].domain===t||Constants_1.sites[r].aliases.includes(t))return r;return null}function jsonfy(t){if("object"==typeof t)return t;const r=(0,fast_xml_parser_1.parse)(t,{ignoreAttributes:!1,attributeNamePrefix:""});if(r.html||r["!doctype"]){const t=r.html||r["!doctype"]?.html,e=[];throw t.body.h1&&e.push(t.body.h1),t.body.p&&e.push(t.body.p["#text"]),new Constants_1.BooruError(`The Booru sent back an error: '${e.join(": ")}'`)}return r.posts.post?r.posts.post:r.posts.tag?Array.isArray(r.posts.tag)?r.posts.tag:[r.posts.tag]:[]}function shuffle(t){let r,e,o=t.length;for(;0!==o;)e=Math.floor(Math.random()*o),o-=1,r=t[o],t[o]=t[e],t[e]=r;return t}function randInt(t,r){return t=Math.ceil(t),r=Math.floor(r),Math.floor(Math.random()*(r-t+1))+t}function validateSearchParams(t,r){const e=resolveSite(t);if("number"!=typeof r&&(r=parseInt(r,10)),null===e)throw new Constants_1.BooruError("Site not supported");if("number"!=typeof r||Number.isNaN(r))throw new Constants_1.BooruError("`limit` should be an int");return{site:e,limit:r}}function compareArrays(t,r){return t.filter((t=>r.some((r=>t.toLowerCase()===r.toLowerCase()))))}exports.resolveSite=resolveSite,exports.jsonfy=jsonfy,exports.shuffle=shuffle,exports.randInt=randInt,exports.validateSearchParams=validateSearchParams,exports.compareArrays=compareArrays;
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           ^

SyntaxError: Unexpected token '.'
    at wrapSafe (internal/modules/cjs/loader.js:915:16)
    at Module._compile (internal/modules/cjs/loader.js:963:27)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1027:10)
    at Module.load (internal/modules/cjs/loader.js:863:32)
    at Function.Module._load (internal/modules/cjs/loader.js:708:14)
    at Module.require (internal/modules/cjs/loader.js:887:19)
    at require (internal/modules/cjs/helpers.js:74:18)
    at Object.<anonymous> (/home/pi/scraperv212/node_modules/booru/dist/boorus/Booru.js:1:290)
    at Module._compile (internal/modules/cjs/loader.js:999:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1027:10)
```.

This bug also affect any kind of linux terminal (ex. Windows Subsystem for Linux, etc.)
Any solutions?

[Support] How to filter results?

I want to filter the results in a search (I want that the search only shows images & gifs, not webm and other). How can I do that?

Optimize random a little

Instead of shuffling the entire array, just make it pick a random element.
Should be only ms quicker but hey every ms counts.

Console.log instance with 0.3.2?

Hi, first of all, thanks for the hard work on this!

Anyways, I just updated to 0.3.2 and every time I do a search it seems to be logging something to console. Even worse though, it only logs [object Object] and not anything useful.

Error on node-v11.9.0-win-x64

Failing to get images using const e9 = await Booru.search('e9', [tag]);.
Always returns this error:
TypeError: tags[i].toLowerCase is not a function at expandTags (E:\files\db indexing node js\@njs_api\node_modules\booru\src\Constants.js:85:37) at Object.module.exports.searchURI (E:\files\db indexing node js\@njs_api\node_modules\booru\src\Constants.js:68:9) at Booru._doSearchRequest (E:\files\db indexing node js\@njs_api\node_modules\booru\src\boorus\Booru.js:109:31) at Booru.search (E:\files\db indexing node js\@njs_api\node_modules\booru\src\boorus\Booru.js:75:17) at Function.search (E:\files\db indexing node js\@njs_api\node_modules\booru\index.js:77:28) at getImages (E:\files\db indexing node js\@njs_api\dscBot.js:244:28) at DCIE (E:\files\db indexing node js\@njs_api\dscBot.js:132:11) at Client.client.on.message (E:\files\db indexing node js\@njs_api\dscBot.js:32:7) at Client.emit (events.js:197:13) at MessageCreateHandler.handle (E:\files\db indexing node js\@njs_api\node_modules\discord.js\src\client\websocket\packets\handlers\MessageCreate.js:9:34)

I have also tested the same code on other versions of node js and it worked perfectly.
Sorry if this issue is already reported, but I havent been able to get it to work.

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.