imageboard
v0.11.5
Published
An easy uniform wrapper over the popular imageboards' API
Downloads
330
Maintainers
Readme
imageboard
Provides easy programmatic access to the popular imageboards.
Supported imageboard engines:
makaba —
2ch.hk
's proprietary engine.4chan —
4chan.org
's proprietary engine.vichan — An open-source
4chan
-compatible engine running on PHP/MySQL whose development started in 2012. The codebase has seen various maintainers take over and then leave off over the years, but as of late 2023, it seems like it's still being maintained and receiving new features.lainchan — a fork of
vichan
that adds a bit of features. Is no longer in development since 2023.OpenIB (formerly infinity) — A 2013 fork of
vichan
engine with the goal of supporting an "infinite" amount of user-managed boards as opposed to a finite set of predefined boards. No longer maintained since 2018.lynxchan — An alternative engine Node.js/MongoDB whose development started in 2015. Rather than mimicking any existing engine, it set off on its own path and ended up becoming a popular choice (of its time) provided that there's really not much else to choose from. Some choices made by the author are questionable and the overall approach doesn't look professional to me. For example, the engine has a bunch of quite obvious but easily-fixable issues that the author refuses to recognize and has no interest in fixing. The author's demeanor, in general, is somewhat controversial and not to everyone's liking.
jschan — An alternative engine written in Node.js/MongoDB whose development started in 2019. Isn't really adopted by anyone, perhaps because there haven't been any new imageboards since its development has started. Compared to
lynxchan
, purely from a technical perspective, it looks much more professional and mature, and the author is a well-known developer.
Originally created as part of the anychan
imageboard GUI.
Details on each imageboard engine API
Features
- (optional) Parses comments HTML markup into
Content
JSON structures. - (optional) Automatically generates shortened "previews" for long comments.
- (optional) Automatically inserts quotes in replying comments.
- (optional) Automatically builds a tree of replies: each comment has a list of "in-reply-to" comments and a list of "replying" comments.
- (optional) Automatically generates thread title when it's missing.
- (not on all imageboards) Provides the API to:
- Create threads
- Post comments
- Report comments
- Request and solve a CAPTCHA
- Log In / Log Out
Install
npm install imageboard --save
Example
P.S. The full source code for this example can be found in test/test.js
file.
Create a new folder and cd
into it.
This example will be using 4chan.org
as a data source.
Create a file called fourChan.js
and paste the following code into it.
import Imageboard from 'imageboard/node'
export default Imageboard('4chan')
Next, create an index.js
file and paste the following code into it. The code prints the first ten of 4chan.org
boards:
import fourChan from './fourChan.js'
// Prints the first 10 boards.
fourChan.getBoards().then(({ boards }) => {
const boardsList = boards.slice(0, 10).map(({
id,
title,
category,
description
}) => {
return `* [${category}] /${id}/ — ${title} — ${description}`
})
console.log(boardsList.join('\n'))
})
The output:
* [Creative] /3/ — 3DCG — "/3/ - 3DCG" is 4chan's board for 3D modeling and imagery.
* [Japanese Culture] /a/ — Anime & Manga — "/a/ - Anime & Manga" is 4chan's imageboard dedicated to the discussion of Japanese animation and manga.
* [Other] /adv/ — Advice — "/adv/ - Advice" is 4chan's board for giving and receiving advice.
... the other boards ...
Now, add the code that prints the first five threads on 4chan.org
/a/
board:
import { getCommentText } from 'imageboard'
// Prints the first five threads on `/a/` board.
fourChan.getThreads({
boardId: 'a'
}).then(({ threads, board }) => {
const threadsList = threads.slice(0, 5).map(({
id,
title,
createdAt,
commentsCount,
attachmentsCount,
comments
}) => {
return [
`#${id}`,
createdAt,
title,
getCommentText(comments[0]) || '(empty)',
`${commentsCount} comments, ${attachmentsCount} attachments`
].join('\n\n')
})
console.log(threadsList.join('\n\n~~~~~~~~~~~~~~~~~~~~~~~~~\n\n'))
})
The output:
#193605320
Wed Sep 25 2019 20:48:54 GMT+0300 (Moscow Standard Time)
Facebook announces Horizon, a VR massive-multiplayer world
DATABASE DATABASE JUST LIVING IN THE DATABE WO-OH
12 comments, 5 attachments
~~~~~~~~~~~~~~~~~~~~~~~~~
... the other threads ...
Now, add the code that prints the first five comments of a certain thread:
import { getCommentText } from 'imageboard'
// Prints the first five comments of thread #193605320 on `/a/` board.
fourChan.getThread({
boardId: 'a',
threadId: 193605320
}).then(({ thread, board }) => {
const commentsList = thread.comments.slice(0, 5).map((comment) => {
const {
id,
title,
createdAt,
replies,
attachments
} = comment
const parts = []
parts.push(`#${id}`)
parts.push(createdAt)
if (title) {
parts.push(title)
}
parts.push(getCommentText(comment) || '(empty)')
if (attachments) {
parts.push(`${attachments.length} attachments`)
}
if (title && replies) {
parts.push(`${replies.length} replies`)
}
return parts.join('\n\n')
})
console.log(commentsList.join('\n\n~~~~~~~~~~~~~~~~~~~~~~~~~\n\n'))
})
The output:
#193605320
Wed Sep 25 2019 20:48:54 GMT+0300 (Moscow Standard Time)
Facebook announces Horizon, a VR massive-multiplayer world
DATABASE DATABASE JUST LIVING IN THE DATABE WO-OH
1 attachments
3 replies
~~~~~~~~~~~~~~~~~~~~~~~~~
#193605743
Wed Sep 25 2019 21:02:00 GMT+0300 (Moscow Standard Time)
«DATABASE DATABASE JUST LIVING IN THE DATABE WO-OH»
Fuck you OP I saw horizon and now I am mad that it’s bait
~~~~~~~~~~~~~~~~~~~~~~~~~~
... the other comments ...
API
Imageboard(idOrConfig, options)
The default exported function. Creates a new imageboard
instance.
There're three different exports:
imageboard
— The default (envirnoment-agnostic) one. Requires specifying a customsendHttpRequest
parameter.imageboard/browser
— The one that can be used in a web browser. Has a web-browser-specificsendHttpRequest
function "built in".imageboard/node
— The one that can be used in Node.js. Has a Node.js-specificsendHttpRequest
function "built in".
import Imageboard from 'imageboard/node'
const fourChan = Imageboard('4chan', options)
If the imageboard is supported by this library out-of-the-box, such imageboard's id
can be passed as the first argument:
"2ch"
"27chan"
"4chan"
"8ch"
(8kun.top)"94chan"
"alogs.space"
"arisuchan"
"bandada"
"diochan"
"endchan"
"heolcafe"
"jakparty.soy"
"junkuchan"
"kohlchan"
"lainchan"
"leftypol"
"niuchan"
"ptchan"
"smugloli"
"tahtach"
"tvchan"
"vecchiochan"
"wizardchan"
"zzzchan"
Otherwise, i.e. when the imageboard is not supported by the library out-of-the-box, the first argument should be an imageboard config
object.
None of the imageboards (4chan.org
, 8kun.top
, 2ch.hk
, etc) allow calling their API from other websites in a web browser: they're all configured to block Cross-Origin Resource Sharing (CORS), so a CORS proxy is required in order for a third party website to be able to query their API.
To bypass CORS limitations, the request()
function would have to call fetch()
not with the original imageboard URL like https://imageboard.net/boards.json
directly but rather with a "proxied" URL like https://my-cors-proxy-address.net/?url=${encodeURIComponent('https://imageboard.net/boards.json')}
.
Available options
:
commentUrl?: string
— A template to use when formatting theurl
property oftype: "post-link"
s (links to other comments) in parsed comments'content
. Is"/{boardId}/{threadId}#{commentId}"
by default.threadUrl?: string
— A template to use when formatting theurl
property oftype: "post-link"
s (links to threads) in parsed comments'content
. Is"/{boardId}/{threadId}"
by default.messages?: Messages
— "Messages" ("strings", "labels") used when parsing commentscontent
. See Messages.commentLengthLimit?: number
— Anumber
telling the maximum comment length (in "points" which can be thought of as "characters and character equivalents for non-text content") upon exceeding which a preview is generated for a comment (ascomment.contentPreview
).useRelativeUrls?: boolean
— Determines whether to use relative or absolute URLs for attachments. Relative URLs are for the cases when an imageboard is temporarily hosted on an alternative domain and so all attachments are too meaning that the default imageboard domain name shouldn't be present in attachment URLs. Isfalse
by default.
parseContent?: boolean
— Istrue
by default. Can be set tofalse
to skip parsing comment HTML intoContent
. The rationale is that when there're 500-some comments in a thread parsing all of them up-front can take up to a second on a modern desktop CPU which results in subpar user experience. By deferring parsing comments' HTML an application could first only parse the first N comments' HTML and only as the user starts scrolling would it proceed to parsing the next comments. Or maybe a developer wants to use their own HTML parser or even render comments' HTML as is. IfparseContent
is set tofalse
then each non-empty comment will have theircontent
being the original unmodified HTML string. In such casesthread.title
won't be autogenerated when it's missing.addParseContent?: boolean
— Passtrue
to add a.parseContent()
method and a.createContentPreview()
method to each comment. This could be used in scenarios whenparseContent: false
option is passed, for example, to only parse comments as they become visible on screen as the user scrolls rather than parsing all the comments in a thread up-front. When passingaddParseContent: true
option, also passexpandReplies: true
option, otherwise.parseContent()
won't go up the chain of quoted comments.The
.parseContent()
function receives an optional object containing the parameters for the function:getCommentById(id): comment?
— Returns acomment
by anid
. This parameter should only be passed if some of thecomment
objects of athread
might have been replaced by the application (for whatever reason) since the time of receiving the originalthread
object.- Why might an application choose to replace some of the
thread
'scomment
s? An example would be refreshing thethread
by first fetching a newthread2
object and then updating the list of the comments in the originalthread
with the new comments from the newly fetchedthread2
. But in that case, some of the older comments' replies count (.replies.length
) might've changed, so those older comments'.replies
lists should be updated, and then those older comments should be re-rendered in order to reflect the updated replies count. And re-rendering a comment when using React framework would mean simply replacing thosecomment
objects with copies of themselves, which is called updating their "object reference".
- Why might an application choose to replace some of the
When
addParseContent: true
option is passed, each comment will also have a.hasContentBeenParsed()
function that can be used to find out whether the comment's content has been parsed.When
addParseContent: true
option is passed, each comment will also have an.onContentChange()
function that should be called whenever thecomment
's perceived.content
changes for any reason. An example would be marking acomment
as "hidden": in that case, the application might decide to update of that comment's replies by replacing their quotes of this comment with ">Hidden comment" placeholder text.The
.onContentChange()
function receives an optional object containing the parameters for the function:getCommentById(id): comment?
— Returns acomment
by anid
. This parameter should only be passed if some of thecomment
objects of athread
might have been replaced by the application (for whatever reason) since the time of receiving the originalthread
object. See the notes on.parseContent()
'sgetCommentById
parameter for an example on why might an application choose to replace some of thecomment
objects in some scenarios.
expandReplies?: boolean
— Everycomment
has optional properties:comment.replyIds[]
andcomment.inReplyToIds[]
. IfexpandReplies: true
parameter is passed, it will add additional optional properties on everycomment
:comment.replies[]
andcomment.inReplyTo[]
that're arrays ofComment
s rather than arrays of justComment.id
s. By default,expandReplies: false
is used to prevent JSON circular structure: this way a whole thread could be serialized into a*.json
file.getPostLinkProperties?: (comment?: Comment) => object
— Returns an object all properties of which will be added to thepost-link
object. Thecomment
argument will beundefined
if the comment was removed.getPostLinkText?: (postLink: object) => string?
— A function that can be used to define the textcontent
ofpost-link
s. It should return either a text for apost-link
, orundefined
, in which case it's simply ignored. An example of how it might be used:
// The application might choose to display `post-link`s to all
// "hidden" comments as links with "Hidden comment" text inside.
getPostLinkText(postLink) {
// If the `post` has not been removed.
// If the application has marked the post as "hidden".
if (postLink.meta.postIsHidden) {
return "Hidden comment"
}
}
// Returns additional `post-link` properties.
// These properties don't get refreshed in `comment.onContentChange()`.
getPostLinkProperties(comment) {
return {
// Whether the application has marked the `comment` object as "hidden".
postIsHidden: comment.hidden
}
}
getSetCookieHeaders?: ({ headers }) => string[]
— Returns a list ofSet-Cookie
header values for an HTTP response. The default implementation just returnsheaders.getSetCookie()
, but a developer could supply their own implementation, for example, to work around web browsers' limitations as they don't exposeset-cookie
response header.When parsing comments, it automatically generates quotes when a comment references another comment in the same thread. The options for generating such quotes are:
generatedQuoteMaxLength?: number
— The maximum length of an auto-generated quote. This is an approximate value.generatedQuoteMinFitFactor: number?
— Sets the minimum preferrable length of an auto-generated quote atgeneratedQuoteMinFitFactor * generatedQuoteMaxLength
.generatedQuoteMaxFitFactor: number?
— Sets the maximum preferrable length of an auto-generated quote atgeneratedQuoteMaxFitFactor * generatedQuoteMaxLength
.generatedQuoteGetCharactersCountPenaltyForLineBreak?: ({ textBefore: string }) => number
— Returns the character count equivalent for a "line break" (\n
) character. The idea is to "tax" multi-line texts when trimming by max length. By default, having\n
characters in text is not penalized in any way and those characters aren't counted.minimizeGeneratedPostLinkBlockQuotes?: boolean
— One can passtrue
to indicate that auto-generated quotes are minimized by default until the user expands them manually. This would mean that auto-generated quotes shouldn't be accounted for when calculating the total length of a comment when creating a shorter "preview" for it in case it exceeds the maxum preferred length.
imageboard
methods
supportsFeature(feature: string)
Tells whether the imageboard supports a certain feature.
feature
argument could be one of:
"getBoards"
"getTopBoards"
"findBoards"
"getThread.withLatestComments"
"getThreads.sortByRatingDesc"
"findThreads"
"findComments"
"findComments.boardId"
— IffindComments()
supports searching for comments across all threads of a given board."findComments.threadId"
— IffindComments()
supports searching for comments in a given thread."rateComment"
"reportComment"
"createThread"
"updateThread"
"createComment"
"updateComment"
"createBlockBypass"
"getCaptcha"
"logIn"
"logIn.tokenPassword"
"logOut"
Returns:
true
if the feature is supported by the imageboard.false
otherwise.
getBoards()
Fetches a list of boards on an imageboard.
Returns an object with properties:
boards
— a list of Boards
For some imageboards, the list could be huge. For example, 8ch.net (8kun.top)
has about 20,000
boards, and to get just the "top 20 boards" one could use getTopBoards()
function instead.
getTopBoards()
Fetches a list of "top" boards on an imageboard.
Returns an object with properties:
boards
— a list of Boards
For example, 8ch.net (8kun.top)
has about 20,000
boards, so getTopBoards()
returns just the "top 20 boards" while getBoards()
returns all 20,000
boards.
This function is only supported if supportsFeature('getTopBoards')
returns true
.
For example, 8ch.net (8kun.top)
has about 20,000
boards, so supportsFeature('getTopBoards')
returns true
for that specific imageboard and getTopBoards()
returns just the "top 20 boards".
findBoards()
Searches for a (non-full) list of boards matching a search query
. For example, if an imageboard supports creating "user boards", and there're a lot of them, then getBoards()
should return just the most popular ones, and to discover all other boards, searching by a query should be used.
Parameters object:
search: string
— Search query. Could be an empty string.
Returns an object with properties:
boards
— a list of Boards
This function isn't currently implemented in any of the supported imageboard engines. To see if a given imageboard supports this function, use supportsFeature('findBoards')
function.
getThreads()
Fetches a list of threads on a board.
Parameters object:
boardId: string
— Board ID.withLatestComments?: boolean
— Passtrue
to get latest comments for each thread. Latest comments are added asthread.latestComments[]
, but not necessarily for all threads in the list, because the result might differ depending on the imageboard engine. For example,4chan
provides latest comments for all threads in the list as part of its "get threads list" API response, while other imageboard engines don't — which is lame — and so the latest comments have to somehow be fetched separately by, for example, going through the "pages" of threads on a board. When doing so, somethreads
might not get theirlatestComments[]
at all, resulting inthread.latestComments[]
beingundefined
. That might happen for different reasons. One reason is that the list of threads on a board changes between the individual "read page" requests, so some threads might get lost in this space-time gap. Another reason is that it wouldn't be practical to go through all of the "pages" because that'd put unnecessary load on the server, and that's whenwithLatestCommentsMaxPages
parameter comes into effect.comments[]
will be an array of a single element — the "root" comment of the thread.latestComments[]
will not include the "root" comment of the thread.
withLatestCommentsMaxPages?: number
— The maximum number of threads list "pages" to fetch in order to get the latest comments for each thread. When the engine doesn't provide the latest comments for each thread as part of its generic "get threads list" API response, the latest comments are fetched by going through every "page" of threads on a board. Therefore, to get the latest comments for all threads on a board, the code has to fetch all "pages", of which there may be many (for example, 10). At the same time, usually imageboards warn the user of the "max one API request per second" rate limit (which, of course, isn't actually imposed). So the code decides to play it safe and defaults to fetching just the first "page" of threads to get just those threads' latest comments, and doesn't set the latest comments for the rest of the threads. A developer may specify a larger count of "pages" to be fetched. It would be safe to specify "over the top" (larger than actual) pages count because the code will just discard all "Not found" errors. All pages are fetched simultaneously for better UX due to shorter loading time, so consider web browser limits for the maximum number of concurrent HTTP requests when setting this parameter to a high number.commentLengthLimitForWithLatestComments?: number
— Same ascommentLengthLimit
but forthread.latestComments
.sortBy?: string
— Could be used to sort the list of threads by something. For example,makaba
engine supportssortBy: "rating-desc"
.Any other properties here will override the corresponding properties of the
options
object that was passed to theImageboard()
function when creating an imageboard instance.defaultAuthorName?: string
— Ifboard
object is available and has aboard.features.defaultAuthorName
property, it could be passed here to parse the default author name as an empty one.
Returns an object with properties:
findThreads()
Searches for a (non-full) list of threads on a given board matching a search query
.
Parameters object:
boardId: string
— Board IDsearch: string
— Search query. Could be an empty string.Any other properties here will override the corresponding properties of the
options
object that was passed to theImageboard()
function when creating an imageboard instance.defaultAuthorName?: string
— Ifboard
object is available and has aboard.features.defaultAuthorName
property, it could be passed here to parse the default author name as an empty one.
Returns an object with properties:
This function isn't currently implemented in any of the supported imageboard engines. To see if a given imageboard supports this function, use supportsFeature('findThreads')
function.
getThread()
Fetches a thread.
Parameters object:
boardId: string
— Board ID.threadId: number
— Thread ID.archived?: boolean
— (optional) Passtrue
when requesting an archived thread. This flag is not required in any way, but, formakaba
engine, it reduces the number of HTTP Requests from 2 to 1 because in that case it doesn't have to attempt to read the thread by a non-"archived" URL (which returns404 Not Found
) before attempting to read it by an "archived" URL.afterCommentId?: number
— (optional) (experimental) Could be used to only fetch comments after a certain comment.afterCommentNumber?: number
— (optional) (experimental) Could be used to only fetch comments after a certain comments count (counting from the first comment in the thread).Any other properties here will override the corresponding properties of the
options
object that was passed to theImageboard()
function when creating an imageboard instance.defaultAuthorName?: string
— Ifboard
object is available and has aboard.features.defaultAuthorName
property, it could be passed here to parse the default author name as an empty one.
Returns an object with properties:
findComments()
Searches for a (non-full) list of comments in a given thread matching a search query
.
Parameters object:
boardId: string
— Board ID.threadId?: number
— Thread ID. If not specified then searches across all threads on the board.search: string
— Search query. Could be an empty string.
Returns an object with properties:
This function isn't currently implemented in any of the supported imageboard engines. To see if a given imageboard supports this function, use supportsFeature('findComments')
function.
rateComment()
Some imageboards (like 2ch.hk
) allow upvoting or downvoting threads and comments on certain boards (like /po/
litics on 2ch.hk
).
Parameters object:
boardId: string
— Board ID.threadId: number
— Thread ID.commentId: number
— Comment ID.up: boolean
— Upvote or downvote.
Returns:
true
— The vote has been accepted.false
— The vote has not been accepted. For example, if the user has already voted.
createThread()
Creates a new thread on a board.
Parameters object:
boardId: string
— Board ID.accessToken?: string
— If the user is authenticated, put anaccessToken
here to bypass CAPTCHA.authorEmail?: string
— Comment author email.authorName?: string
— Comment author name.attachments?: File[]
— Attachments.title?: string
— Comment title (subject).content?: string
— Comment content (text).makaba
-specific properties:authorIsThreadAuthor?: boolean
— "Comment author is the thread author" flag.authorIconId?: number | string
— Comment author icon ID.tags?: string[]
— Thread tags.captchaType?: string
— CAPTCHA type. Possible values:"2chcaptcha"
.captchaId?: string
— CAPTCHA ID.captchaSolution?: string
— CAPTCHA solution.
Returns an object:
id: number
— Thread ID
updateThread()
Updates a thread.
Parameters object:
boardId: string
— Board ID.threadId: number
— Thread ID.- Same other properties as in
createThread()
This function isn't currently implemented in any of the supported imageboard engines. To see if a given imageboard supports this function, use supportsFeature('updateThread')
function.
createComment()
Creates a new comment in a thread.
Parameters object:
boardId: string
— Board ID.threadId: number
— Thread ID.accessToken?: string
— If the user is authenticated, put anaccessToken
here to bypass CAPTCHA.authorEmail?: string
— Comment author email.authorName?: string
— Comment author name.attachments?: File[]
— Attachments.title?: string
— Comment title (subject).content?: string
— Comment content (text).makaba
-specific properties:authorIsThreadAuthor?: boolean
— "Comment author is the thread author" flag.authorIconId?: number | string
— Comment author icon ID.captchaType?: string
— CAPTCHA type. Possible values:"2chcaptcha"
.captchaId?: string
— CAPTCHA ID.captchaSolution?: string
— CAPTCHA solution.
Returns an object:
id: number
— Comment ID
updateComment()
Updates a comment.
Parameters object:
boardId: string
— Board ID.threadId: number
— Thread ID.commentId: number
— Comment ID.- Same other properties as in
createComment()
This function isn't currently implemented in any of the supported imageboard engines. To see if a given imageboard supports this function, use supportsFeature('updateComment')
function.
getCaptcha()
Requests a CAPTCHA,
Parameters object:
boardId?: string
— Board ID.threadId?: number
— Thread ID, if posting a comment in a thread.
Returns an object:
captcha: object
:id: string
— CAPTCHAid
, can be used to get CAPTCHA image URL.type: string
— CAPTCHA type. Possible values:"text"
.challengeType: string
— CAPTCHA type. Possible values:"image"
,"image-slider"
.characterSet?: string
— A name of a character set for a"text"
CAPTCHA solution. For example,"numeric"
or"russian"
.expiresAt: Date
— CAPTCHA expiration date.image: object
— CAPTCHA image:type: string
— image mime-type.url: string
— image URL. May be relative or absolute.width: number
— image width.height: number
— image height.
backgroundImage?: object
—"image-slider"
CAPTCHA background image:type: string
— image mime-type.url: string
— image URL. May be relative or absolute.width: number
— image width.height: number
— image height.
canRequestNewCaptchaAt?: Date
— When the user is allowed to request a new CAPTCHA.
createBlockBypass()
Engines such as jschan
or lynxchan
introduce a concept of a "block bypass". A "block bypass" is a token that allows its owner to "bypass" a "block" that the server may have imposed on them. Such a "block" could block the user from posting comments or threads or submitting reports.
In order to prevent spam, users are untrusted by default, and are required to solve a CAPTCHA.
Offtopic: Although in the modern age of AI development automatically solving CAPTCHAs has become an easy task, so I'd personally advise utilizing other means of spam prevention. For example, kohlchan.net
requires a user to provide a "Proof-of-Work" in a form of a result of a lengthy computation. And popular imageboards like 4chan.org
or 2ch.hk
provide their users an option to bypass CAPTCHA by purchasing a "pass" which could be considered a "Proof-of-Stake".
This createBlockBypass()
method issues a new "block bypass" token.
Parameters object:
captchaId: string
— Captcha ID.captchaSolution: string
— Captcha solution.
Returns an object:
token: string
— "Block bypass" token.expiresAt: date
— The date when the "block bypass" token expires.
logIn()
Performs a login.
Parameters object:
token: string
— Login token. For example,4chan
calls them "passes".tokenPassword?: string
— Login token password. For example,4chan
uses them (it calls it a "PIN").
Returns an object:
accessToken?: string
— Access token.
logOut()
Performs a logout.
No parameters.
Returns undefined
.
reportComment()
Reports a comment or a thread.
Parameters object:
boardId: string
— Board ID.threadId: number
— Thread ID.commentId: number
— Comment ID.accessToken?: string
— If the user is authenticated, put anaccessToken
here to bypass CAPTCHA.content?: string
— Report content. Is used inmakaba
engine.reasonId?: number | string
— Report reason ID. Is used in4chan
engine.legalViolationReasonId?: number
— Report reason ID (31
) in case of a violation of United States law. NoreasonId
should be passed. Is only used in4chan
engine.captchaId?: string
— CAPTCHA ID. Is used in4chan
engine.captchaSolution?: string
— CAPTCHA solution. Is used in4chan
engine.
Returns undefined
.
Miscellaneous API
The following functions are exported for "advanced" use cases. In other words, they're being used in anychan
and that's the reason why they're exported.
getConfig(id: string): object?
Returns an imageboard config by its id
. Example: getConfig("4chan")
.
Can be used in cases when an application for whatever reasons needs to know the imageboard info defined in the *.json
file, such as domain
, engine
, etc.
getCommentText(comment: Comment, options: object?): string?
Generates a textual representation of Comment's content
. This is just a getPostText()
function re-exported from social-components
for convenience.
Is used in the examples in this document.
Available options
(optional argument):
messages: Messages?
— (optional) "Messages" ("strings", "labels") used when generating text fromcontent
. See Messages.skipPostQuoteBlocks: boolean?
— (optional) Set totrue
to skip all "block" (not "inline") "comment quotes" (quotes citing a particular comment).skipGeneratedPostQuoteBlocks: boolean?
— (optional) Set totrue
to skip all "block" (not "inline") autogenerated "comment quotes" (autogenerated quotes citing a particular comment).
sortThreadsWithPinnedOnTop(threads: Thread[]): Thread[]
Sorts a list of threads so that pinned
ones are on top according to their pinnedOrder
.
createHttpRequestFunction()
Creates a custom sendHttpRequest()
function that could be passed when creating an Imageboard()
using the default export from the imageboard
package.
See HTTP request function of this document for more details.
supportsFeature()
Tells if the feature is supported by the imageboard. See the docs for the instance method supportsFeature(feature)
of Imageboard
.
Arguments:
imageboardIdOrConfig
— Imageboard ID string or configuration object.feature
— Feature name.
Returns:
true
if the feature is supported by the imageboardfalse
otherwise
Models
Board
See Board.md
or ./types/index.d.ts
.
Thread
See Thread.md
or ./types/index.d.ts
.
Comment
See Comment.md
or ./types/index.d.ts
.
Content
Each comment could have a content
property, which is optional. The content
could be simple text or it could be "rich"-formatted text in which case it uses some kind of a "markup" language like Markdown or HTML.
In order to convert that "markup" language into a Content
structure, the comment's content
has to be "parsed". This package does that by default. To turn off the automatic parsing feature, pass parseContent: false
parameter.
When parsing a comment's content
, if commentLengthLimit
parameter was passed, it will automatically create a contentPreview
if content
surpasses the commentLengthLimit
. One could also use a comment.createContentPreview({ maxLength })
method to create a preview of a content
with a custom maxLength
limit.
Attachment
An attachment can be a:
Picture
attachment
Embedded Link Attachments
This library doesn't parse links to YouTube/Twitter/etc inside comments. Instead, this type of functionality is offloaded to a separate library. For example, anychan
uses loadResourceLinks()
and expandStandaloneAttachmentLinks()
from social-components
library when rendering comments to load YouTube/Twitter/etc links and embed the attachments directly in comments.
Messages
Sometimes an optional messages
object can be passed to define "messages" ("strings", "labels") used when parsing comments content
.
Messages used for setting the content of comment links:
{
...,
comment: {
default: "Comment",
deleted: "Deleted comment",
external: "Comment from another thread"
},
thread: {
default: "Thread"
}
}
Messages used when generating content
text (autogenerated quotes, autogenerated thread title):
{
...,
textContent: {
... // See the "Messages" section in the readme of `social-components` package.
}
}
See ./types/Messages.d.ts
for the most up-to-date description of the Messages
structure.
Adding a new imageboard
Follow the instructions in docs/add-new-imageboard.md
.
Adding a new engine
Follow the instructions in docs/add-new-engine.md
.
HTTP request function
When importing Imageboard
function from imageboard
package directly rather than from a sub-package like imageboard/browser
or imageboard/node
, one would have to supply a sendHttpRequest()
parameter:
sendHttpRequest()
— (required) Sends HTTP requests to an imageboard's API.
parameters
argument:method: string
— HTTP request method, in upper case.url: string
— HTTP request URL.body?: object
—POST
request body JSON object.headers?: object
— HTTP request headers, with header names in lower case.cookies?: object
— HTTP request cookies.
- Returns a
Promise
:- When successful, the
Promise
should resolve to an object:url: string
— HTTP request URL. If there were any redirects in the process, this should be the final URL that it got redrected to.status: number
— HTTP response status.responseText?: string
— HTTP response text. Can be omitted if there's no response content.headers: object
— HTTP response headers. For example, theheaders
property of afetch()
response
. Must be an object having functions:.get(headerName: string)
— Returns the value of an HTTP response header..getSetCookie()
— Returns a list ofset-cookie
header values in HTTP response.
- Otherwise, in case of an error, the
Promise
should reject with anError
instance having optional properties:url: string
— HTTP request URL. If there were any redirects in the process, this should be the final URL that it got redrected to.status: number
— HTTP response status.responseText?: string
— HTTP response text. Can be omitted if there's no response content.headers: object
— HTTP response headers. For example, theheaders
property of afetch()
response
. Must be an object having functions:.get(headerName: string)
— Returns the value of an HTTP response header..getSetCookie()
— Returns a list ofset-cookie
header values in HTTP response.
- When successful, the
await sendHttpRequest({
method: "GET",
url: "https://8kun.top/boards.json"
}) === {
url: "https://8kun.top/boards.json",
status: 200,
headers: {},
responseText: "[
{ "uri": "b", "title": "Random" },
...
]"
}
Because the response could be in different forms:
application/json
text/html
text/plain
, when something weird happens like the server being down.
So it's not always JSON, and having a response
parameter be sometimes of this type and sometimes of that type wouldn't be considered a professional approach.
status
andurl
are used when reading archived threads on2ch.hk
imageboard. When requesting an archived thread on2ch.hk
, it always redirects with a302
status to a URL that looks like/boardId/arch/yyyy-mm-dd/res/threadId.json
. As one can see, there's thearchivedAt
date in that final "redirect-to" URL, and it's nowhere else to be read. So this library has to have the access to the final URL after any redirects.headers
are used when parsing an imageboard API's response to a "log in" request: this library attempts to read the authentication cookie value from that response in order to return it to the application code.
An appropriate sendHttpRequest()
function could be created using the exported createHttpRequestFunction()
function:
import { createHttpRequestFunction } from 'imageboard'
const sendHttpRequest = createHttpRequestFunction({
fetch,
FormData
})
Required parameters of createHttpRequestFunction()
:
Optional parameters of createHttpRequestFunction()
:
setHeaders({ headers })
— Sets any custom HTTP request headers.attachCookiesInWebBrowser({ cookies, headers })
— Attaches any custom cookies to HTTP request when running in a web browser environment.getRequestUrl({ url })
— Transforms HTTP request URL in any arbitrary way.getResponseStatus({ status, headers })
— Returns any custom HTTP response status.getFinalUrlFromResponse({ url, headers })
— Returns any custom "final" URL for HTTP response.mode
— Overrides themode
parameter of thefetch()
function.credentials
— Overrides thecredentials
parameter of thefetch()
function.redirect
— Overrides theredirect
parameter of thefetch()
function. The default is"manual"
.
Imageboards API
4chan
4chan.org
API (with examples)4chan.org
API (brief official docs)- The "leaked" source code from 2014 (may be outdated in some parts).
vichan
vichan
engine was originally a fork of Tinyboard
engine having more features. In November 2017, vichan
engine was put in "no longer being maintained" state, although later, around 2022, a group of volunteers seems to have picked up the development from the former maintainer.
Chans running on vichan
:
lainchan.org
— Runs on a custom fork ofvichan
calledlainchan
infinity
infinity is a vichan
fork permitting users to create their own boards (hence the name). As of April 2017, infinity
engine is no longer being maintained. OpenIB is a security-focused fork of the infinity
engine which is no longer being maintained too.
Chans running on infinity
:
makaba
The only imageboard running on makaba
engine is currently 2ch.hk
.
lynxchan
lynxchan
seems to be the only still-being-maintained imageboard engine left. Has JSON API and POST API.
Chans running on lynxchan
:
jschan
jschan is an alternative engine written in Node.js/MongoDB whose development started in 2019. Isn't really adopted by anyone, perhaps because there haven't been any new imageboards since its development has started. Compared to lynxchan
, purely from a technical perspective, it looks much more professional and mature.
Chans running on jschan
:
Known issues
There're some limitations for imageboards running on lynxchan
engine (for example, kohlchan.net
) due to the lack of support for several features in that engine.
There're some smaller limitations for jschan
engine.
There're some very minor limitations for the infinity
/OpenIB
engine due to the lack of support for several very minor features in that engine.
There're some very minor bugs for 2ch.hk
caused by its makaba
engine.
Testing
Unit tests:
npm run build
npm test
Real-world tests:
npm run build
npm run test-chan [chan-id]
GitHub
On March 9th, 2020, GitHub, Inc. silently banned my account (erasing all my repos, issues and comments) without any notice or explanation. Because of that, all source codes had to be promptly moved to GitLab. The GitHub repo is now only used as a backup (you can star the repo there too), and the primary repo is now the GitLab one. Issues can be reported in any repo.