Bot
The Bot object is the main component of the library. It is used to register event handlers, and provides the entry point of the bot—the fetch() method to be connected to the HTTP server.
BotKit also exposes the bot actor's standard ActivityPub collections. The JSON-LD responses of the outbox and followers collections include the FEP-5711 inverse properties outboxOf and followersOf.
TIP
A bot created by createBot() occupies its whole server. Since BotKit 0.5.0, a single server can also host multiple bots; see the Instance concept document.
Instantiation
You can instantiate a Bot instance by calling the createBot() function:
import { createBot } from "@fedify/botkit";
import { MemoryKvStore } from "@fedify/fedify";
const bot = createBot<void>({
username: "my_bot",
kv: new MemoryKvStore(),
});It takes a type parameter TContextData which is the type of the Fedify context data. Usually, you don't have to mind this type parameter and can just use void as shown in the example above, unless you are familiar with Fedify and want to use the context data.
It takes a CreateBotOptions object with the following required properties:
username
The username of the bot actor. This is used to be a part of the bot's fediverse handle. For example, if the username is my_bot, the bot's handle will be @my_bot@your-domain.
TIP
Although it is not recommended, you can change the username after you have once deployed your bot. However, in practice, as people would be confused about the username change, it is recommended to stick with one good username forever.
kv
The key–value store to be used by the bot. There are several drivers available. See also the related section of the Fedify docs.
During local development, you probably want to use the MemoryKvStore, which stores data in memory.
On production, you probably want to use one of the following drivers:
DenoKvStore(Deno only)RedisKvStorePostgresKvStore
Or if you want to implement your own custom key–value store, that is also possible!
Additional options
There are other options to customize your Bot instance:
repository
The repository (data access object) to be used by the bot. It is used to store and retrieve data from the bot's database.
By default, it uses the KvRepository with the key–value store specified in the kv option.
For more information, see the Repository section.
If you want to use a SQL-backed repository directly instead of KvRepository, BotKit also provides concrete repository packages such as SqliteRepository and PostgresRepository.
~CreateBotOptions.federationOptions
Selected options for the underlying Fedify federation. These include private network access for local integration tests, queued-delivery circuit breaking, OpenTelemetry providers, and HTTP Signature negotiation. See Federation infrastructure options for the complete list and safety notes. The same options are available to createInstance().
identifier
The internal identifier of the bot actor. It is used for the URI of the bot actor, which is the unique identifier of ActivityPub objects.
By default, it is just a "bot".
CAUTION
Unlike username, the identifier must not be changed after once your bot is deployed. If you change the identifier of your bot, other fediverse software will not recognize your bot as the existing one but it will be practically another distinct actor.
class
The type of the bot actor. It can be either Application or Service.
Service by default.
NOTE
Since BotKit is a framework for creating bots, it does not support Person or Group or Organization.
name
The display name of the bot. It can be changed after the bot is federated.
If you change it after deployment and want followers to notice the change immediately, call Session.republishProfile().
summary
The description of the bot. It will be displayed in the bio field of the profile. It can be changed after the bot is federated.
Note that it does not take a string, but a Text object. See also the Text chapter.
If you change it after deployment and want followers to notice the change immediately, call Session.republishProfile().
icon
The avatar URL of the bot. It can be changed after the bot is federated.
NOTE
BotKit does not perform any modifications (cropping or resampling) on the avatar image. The image as it is will be used. If you want to adjust the avatar image so that it looks fine on the most fediverse platforms, you need to change the image file itself.
If you change it after deployment and want followers to notice the change immediately, call Session.republishProfile().
image
The header image URL of the bot. It can be changed after the bot is federated.
NOTE
BotKit does not perform any modifications (cropping or resampling) on the header image. The image as it is will be used. If you want to adjust the header image so that it looks fine on the most fediverse platforms, you need to change the image file itself.
If you change it after deployment and want followers to notice the change immediately, call Session.republishProfile().
properties
The custom properties of the bot. Usually you would like to put some metadata about the bot like the website URL, the source code repository URL, etc. here. Note that the property names should be human-readable and property values are of the Text type (see also the Text chapter):
import { createBot, link, mention } from "@fedify/botkit";
const bot = createBot<void>({
// Omitted other options for brevity
properties: {
Website: link("https://botkit.fedify.dev/"),
Repository: link("https://github.com/fedify-dev/botkit"),
Creator: mention("@hongminhee@hollo.social"),
},
});It can be changed after the bot is federated.
~CreateBotOptions.aliases
Available since BotKit 0.6.0.
The actor URIs of other accounts representing the same bot, published in its ActivityPub alsoKnownAs property. This allows an existing account to move its followers to the bot. Values must be URL objects containing actor URIs, rather than handles or profile page URLs. BotKit publishes these URIs without resolving them.
The default is an empty array. You can read the configured list through Bot.aliases or Session.bot.aliases. To change it on a static bot, update the configuration and redeploy. See Moving an existing account to a bot for the migration steps.
followerPolicy
How to handle incoming follow requests. Possible values are:
"accept"(default)- Automatically accept all incoming follow requests.
"reject"- Automatically reject all incoming follow requests.
"manual"- Require manual handling of incoming follow requests. You can manually
accept()orreject()in theBot.onFollowevent handler.
It can be changed after the bot is federated.
TIP
This behavior can be overridden by manually invoking FollowRequest.accept() or FollowRequest.reject() in the Bot.onFollow event handler.
quotePolicy
Who can quote messages published by the bot by default. BotKit serializes the policy into each outgoing message and uses it as the fallback for older stored messages that do not have a quote policy yet.
The shorthand values are:
"public"(default)- Accept every quote request automatically.
"followers"- Accept quote requests from followers automatically.
"manual"- Leave every quote request pending for the
Bot.onQuoteRequestevent handler. "nobody"- Reject every quote request except the bot's own requests.
You can also use the full two-axis policy object:
import { createBot } from "@fedify/botkit";
const bot = createBot({
username: "mybot",
name: "My Bot",
kv,
quotePolicy: {
automatic: "followers",
manual: "public",
},
});This accepts followers automatically and sends other quote requests to Bot.onQuoteRequest for manual moderation. A publish call can override the default with Session.publish()'s quotePolicy option.
queue
The message queue for handling incoming and outgoing activities. If omitted, incoming activities are processed immediately, and outgoing activities are sent immediately.
There are several drivers available. See also the related section of the Fedify docs.
During local development, you probably want to use the InProcessMessageQueue, which processes messages in the same process.
On production, you probably want to use one of the following drivers:
Or if you want to implement your own custom message queue, that is also possible!
NOTE
Although it can be unset for local development, in production, we highly recommend to configure the queue to make your bot performant and scalable.
software
The metadata about the bot server. It is used for the NodeInfo protocol. It consists of the following properties:
name(required)The canonical name of the bot software. This must comply with pattern
/^[a-z0-9-]+$/, i.e., it must consist of Latin lowercase letters, digits, and hyphens.version(required)The version of the bot software. It should be a string:
import {createBot} from "@fedify/botkit"; constbot=createBot<void>({ // Omitted other options for brevitysoftware: {name: "my-bot",version: "1.0.0", } });repository(optional)The
URLof the source code repository of the bot software.homepage(optional)the
URLof the homepage of the bot software.
behindProxy
Whether to trust X-Forwarded-* headers. If the bot is behind an L7 reverse proxy (e.g., nginx, Caddy), you should turn it on.
Turned off by default.
TIP
During local development, if you use tunneling services like fedify tunnel, ngrok, Tailscale Funnel, etc., you should turn it on. These tunneling services practically act as an L7 reverse proxy.
pages
The options for the web pages of the bot.
BotKit serves a bot's profile, posts, and follower list with a quiet, modern design that foregrounds the bot's own identity. The whole look is driven by a single accent color, adapts to light and dark automatically, and needs no build step or external CDN: the stylesheet and fonts are bundled with the package. See the design language document for the full system.
colorThe accent color of the bot's pages. It tints links, the follow button, and small highlights, and is used as the theme color for browser chrome. The default color is
"green".Here's the list of available colors:
"amber""azure""blue""cyan""fuchsia""green"(default)"grey""indigo""jade""lime""orange""pink""pumpkin""purple""red""sand""slate""violet""yellow""zinc"
The accent values are taken from the Colors section of the Pico CSS docs, so each name looks the same as it does there.
themeThis option is available since BotKit 0.5.0.
The color scheme of the web pages:
"auto"(the default) follows the visitor's operating system preference, while"light"and"dark"force a fixed scheme.cssCustom CSS injected after BotKit's own stylesheet, so it can override any of the design system's tokens or rules. It should be a string of CSS code. For example,
:root { --bk-radius: 6px; }gives the pages squarer corners.
Moving an existing account to a bot
Available since BotKit 0.6.0.
You can move followers from an existing account on Mastodon or another server that supports account migration with Move to a BotKit bot. Only followers move: posts, accounts you follow, and other account data are not transferred.
First, find the old account's actor URI. It is the id in its ActivityPub actor document, which may differ from its profile page URL. For example, a Mastodon account @mybot@old.example normally has the actor URI https://old.example/users/mybot, while its profile page is https://old.example/@mybot. Do not put the handle or the profile page URL in aliases: migration checks compare actor URIs exactly.
To find the URI without guessing the server's URL scheme, query the old account's WebFinger endpoint:
curl 'https://old.example/.well-known/webfinger?resource=acct:mybot@old.example'In the response's links, find the rel: "self" link whose type is application/activity+json or application/ld+json with the ActivityStreams profile. Fetch its href with an ActivityPub Accept header, and use the returned actor document's id:
curl -H 'Accept: application/activity+json' \
'https://old.example/users/mybot'Configure and deploy the new bot with that URI in aliases:
import { createBot } from "@fedify/botkit";
import { MemoryKvStore } from "@fedify/fedify";
const bot = createBot<void>({
username: "mybot",
kv: new MemoryKvStore(),
aliases: [new URL("https://old.example/users/mybot")],
});
export default bot;This example uses an in-memory store; use persistent storage for a production bot.
Once the bot is publicly reachable, fetch its actor document and confirm that alsoKnownAs contains the old actor URI. You can find the new actor URI through the bot's WebFinger endpoint using the same procedure above. Mastodon refuses to start the move until the target advertises this alias.
Then sign in to the old Mastodon account. Under Settings → Account → Moving to a different account, choose the migration option, enter the new bot's handle (for example, @mybot@new.example), and confirm the move. Keep the old server online while it sends the migration notifications. The bot receives ordinary follow requests from servers that support migration; followers may arrive gradually.
The default followerPolicy: "accept" accepts these requests automatically. With "manual", accept them in the onFollow handler. A "reject" policy rejects them unless your handler accepts them first. Check the bot's availability and follow policy before starting: Mastodon imposes a migration cooldown, so you cannot recover by immediately repeating the move.
Aliases can be added to a bot that is already federated by updating its configuration and redeploying. On a multi-bot instance, set BotProfile.aliases on each static bot or in the profile returned by a dynamic group's dispatcher. Later requests for a dynamic bot use the aliases returned by its dispatcher. See Mastodon's migration guide for details about the old account's settings and restrictions.
Running the bot
After you have instantiated a Bot object, you need to connect it to the HTTP server to run it. The Bot object comply with the fetch() API, so you can serve it with the deno serve command on Deno or the srvx CLI on Node.js. Both run the same export default bot entry.
Deno
For example, if you have a Bot object named bot, and export it as a default export:
import { createBot } from "@fedify/botkit";
const bot = createBot<void>({
// Omitted other options for brevity
});
export default bot; You can run the following command to expose the bot to the fediverse:
deno serve -A ./bot.tsThen, it will show the following message:
deno serve: Listening on http://0.0.0.0:8000/And your bot will be available at http://localhost:8000/.
TIP
You can change the listening port by specifying the --port option:
deno serve -A --port=3000 ./bot.tsNode.js
On Node.js, export the bot as a default export exactly as on Deno:
import { createBot } from "@fedify/botkit";
const bot = createBot<void>({
// Omitted other options for brevity
});
export default bot; Then serve it with the srvx CLI, which runs a fetch handler on Node.js with no glue code. It executes the TypeScript entry directly, so there is no build step:
npx srvx serve --port 8000 --entry ./bot.tspnpx srvx serve --port 8000 --entry ./bot.tsyarn dlx srvx serve --port 8000 --entry ./bot.tsYour bot will be available at http://localhost:8000/. The CLI listens on port 3000 unless you pass --port. When you run the bot in production, add --prod to turn off watch mode and debug output.
Exposing the bot to the public internet
During local development, you probably want to use a tunneling service like fedify tunnel, ngrok, Tailscale Funnel, etc. to expose your bot to the public internet so that other fediverse servers can interact with your bot.
In such a case, you should turn on the behindProxy option to trust X-Forwarded-* headers from the tunneling service and recognize the public hostname of the server.
It is recommended to have an environment variable to control the behindProxy option so that you can easily switch between local development and production:
import { createBot } from "@fedify/botkit";
const BEHIND_PROXY =
Deno.env.get("BEHIND_PROXY")?.trim()?.toLowerCase() === "true";
const bot = createBot<void>({
// Omitted other options for brevity
behindProxy: BEHIND_PROXY,
});import { createBot } from "@fedify/botkit";
const BEHIND_PROXY =
process.env.BEHIND_PROXY?.trim()?.toLowerCase() === "true";
const bot = createBot<void>({
// Omitted other options for brevity
behindProxy: BEHIND_PROXY,
});Then, you can use the following command to run the bot with the BEHIND_PROXY environment variable set to true:
BEHIND_PROXY=true deno serve -A --port 8000 ./bot.tsBEHIND_PROXY=true npx srvx serve --port 8000 --entry ./bot.tsThen, you can use the tunneling service to expose your bot to the public internet, for example, with fedify tunnel:[1]
fedify tunnel 8000The above command will show a temporary public hostname that your bot can be accessed from the fediverse:[2]
✔ Your local server at 8000 is now publicly accessible:
https://8eba96f5416581.lhr.life/
Press ^C to close the tunnel.You need to install the
fedifycommand first. There are multiple ways to install it. ↩︎The hostname will be different in your case. ↩︎