### Initialize @skyware/labeler Setup
Source: https://github.com/skyware-js/web/blob/main/src/content/guides/labeler/introduction/getting-started.mdx
This command initializes the Bluesky account as a labeler. It guides the user through logging in, providing the labeler server URL (must be HTTPS), and then sends a confirmation code to the user's email. A signing key is generated if not provided, which is crucial for operating the labeler.
```shell
npx @skyware/labeler setup
```
--------------------------------
### Initialize and Start Labeler Server
Source: https://github.com/skyware-js/web/blob/main/src/content/guides/labeler/introduction/getting-started.mdx
Initializes the LabelerServer with DID and signing key, then starts the server on a given port. Includes basic error handling for server startup. Requires environment variables LABELER_DID and SIGNING_KEY.
```typescript
if (!process.env.LABELER_DID || !process.env.SIGNING_KEY) throw "";
// ---cut---
import { LabelerServer } from "@skyware/labeler";
const server = new LabelerServer({
did: process.env.LABELER_DID,
signingKey: process.env.SIGNING_KEY
});
server.start(14831, (error) => {
if (error) {
console.error("Failed to start server:", error);
} else {
console.log("Labeler server running on port 14831");
}
});
```
--------------------------------
### Install Dependencies and Start Dev Server (Bash)
Source: https://context7.com/skyware-js/web/llms.txt
Installs project dependencies, pulls source repositories, and starts the development server. Requires git and pnpm.
```bash
# Clone and setup the project
git clone https://github.com/skyware-js/web.git
cd web
# Install dependencies
pnpm install
# Pull source repositories
pnpm pull
# Start development server at http://localhost:4321
pnpm dev
```
--------------------------------
### Initialize and Start Jetstream
Source: https://github.com/skyware-js/web/blob/main/src/content/guides/jetstream/introduction/getting-started.mdx
Initializes the Jetstream class and starts listening for events. The Jetstream class accepts configuration options for desired collections, DIDs, cursor, and endpoint. The start() method initiates the connection and event stream.
```typescript
import { Jetstream } from "@skyware/jetstream";
const jetstream = new Jetstream();
jetstream.start();
```
--------------------------------
### Post a Message to Bluesky
Source: https://github.com/skyware-js/web/blob/main/src/content/guides/bot/introduction/getting-started.mdx
This snippet shows how to create and publish a simple text post to Bluesky using the @skyware/bot package. It assumes the bot has already been initialized and logged in.
```typescript
declare const bot: import("@skyware/bot").Bot;
// ---cut---
const post = await bot.post({
text: "hello, sky!"
});
console.log(post.uri);
```
--------------------------------
### Initialize Firehose Client
Source: https://github.com/skyware-js/web/blob/main/src/content/guides/firehose/introduction/getting-started.mdx
Initializes the Firehose client. The Firehose class can optionally take a Relay URL and an options object for cursor management and setCursorInterval.
```typescript
import { Firehose } from "@skyware/firehose";
const firehose = new Firehose();
```
--------------------------------
### Render Guide Pages in Astro (TypeScript)
Source: https://context7.com/skyware-js/web/llms.txt
Fetches and renders guide content within an Astro page. It demonstrates how to get a guide entry, render its content, and optionally override default HTML elements with custom components for styling.
```typescript
// Fetch and render guide content
const guide = await getEntry("guides", "bot/introduction/getting-started");
const { Content } = await guide.render();
// Render with custom components
// Generate metadata
const meta = generateMeta(module, guide);
// Returns: {
// title: "Getting Started | @skyware/bot",
// description: "Learn how to create your first bot",
// ogImage: "/og/bot.png"
// }
```
--------------------------------
### Initialize and Run Labeler Server and Bot - TypeScript
Source: https://github.com/skyware-js/web/blob/main/src/content/guides/labeler/introduction/automated-labeling.mdx
Initializes the LabelerServer and Bot from the @skyware/labeler and @skyware/bot packages. It starts the server on a specified port and logs in the bot using environment variables for credentials. This is the foundational setup for the labeling functionality.
```typescript
if (!process.env.LABELER_DID || !process.env.LABELER_PASSWORD || !process.env.SIGNING_KEY) throw "";
// ---cut---
import { LabelerServer } from "@skyware/labeler";
import { Bot } from "@skyware/bot";
const server = new LabelerServer({
did: process.env.LABELER_DID,
signingKey: process.env.SIGNING_KEY,
});
server.start(14831, (error) => {
if (error) {
console.error("Failed to start: ", error);
} else {
console.log("Listening on port 14831");
}
});
const bot = new Bot();
await bot.login({
identifier: process.env.LABELER_DID,
password: process.env.LABELER_PASSWORD,
});
```
--------------------------------
### Load Environment Variables for Bot Credentials
Source: https://github.com/skyware-js/web/blob/main/src/content/guides/bot/introduction/getting-started.mdx
This snippet demonstrates how to use the 'dotenv' package to load Bluesky bot credentials (username and password) from a .env file. It ensures that these environment variables are present before proceeding with bot initialization.
```typescript
import { Bot } from "@skyware/bot";
if (!process.env.BSKY_USERNAME || !process.env.BSKY_PASSWORD) throw "";
// ---cut---
const bot = new Bot();
await bot.login({
identifier: process.env.BSKY_USERNAME,
password: process.env.BSKY_PASSWORD,
});
```
--------------------------------
### Create a Label using Labeler Server
Source: https://github.com/skyware-js/web/blob/main/src/content/guides/labeler/introduction/getting-started.mdx
Demonstrates how to create a new label for a given URI or DID using the LabelerServer. The 'uri' can point to a record or an account's DID, and 'val' specifies the label identifier.
```typescript
declare const server: import("@skyware/labeler").LabelerServer;
// ---cut---
await server.createLabel({
// If you're labeling a record, this should be an at:// URI pointing to the record.
// If you're labeling an account, this should be the account's DID.
uri: "did:plc:427uaandx74txvzakxthrjwu",
// Assuming you've previously defined a label with the identifier "cool-cat".
val: "cool-cat",
});
```
--------------------------------
### Configure Guide Collections in JSON
Source: https://context7.com/skyware-js/web/llms.txt
Configuration file in JSON format that maps repository packages (e.g., '@skyware/bot') to collections of guides. It organizes guides into categories and lists individual guide slugs.
```json
{
"guides": {
"@skyware/bot": [
{
"category": "Introduction",
"guides": [
"bot/introduction/getting-started",
"bot/introduction/listening-to-events",
"global/glossary"
]
},
{
"category": "Advanced Posting",
"guides": [
"bot/advanced-posting/rich-text",
"bot/advanced-posting/embeds-and-images"
]
}
]
}
}
```
--------------------------------
### Handle Commit Events with Firehose
Source: https://github.com/skyware-js/web/blob/main/src/content/guides/firehose/introduction/getting-started.mdx
Listens for 'commit' events from the Firehose relay. It iterates through operations within a commit, logs the URI for each operation, and provides access to record details for create and update actions.
```typescript
declare const firehose: import("@skyware/firehose").Firehose;
// ---// ---
firehose.on("commit", (message) => {
for (const op of message.ops) {
const uri = "at://" + message.repo + "/" + op.path;
console.log("URI:", uri);
}
});
```
--------------------------------
### Add a New Label with @skyware/labeler
Source: https://github.com/skyware-js/web/blob/main/src/content/guides/labeler/introduction/getting-started.mdx
This command allows you to add a new label to your labeler configuration. You will be prompted to provide a unique identifier, user-facing name, description, and settings related to adult content, label severity, content hiding, and default subscriber settings.
```shell
npx @skyware/labeler label add
```
--------------------------------
### Handle New Posts with onCreate
Source: https://github.com/skyware-js/web/blob/main/src/content/guides/jetstream/introduction/getting-started.mdx
Subscribes to new record creation events for a specific collection, such as 'app.bsky.feed.post'. When a new post is created, the provided callback function is executed, logging the post's text. This demonstrates filtered event handling.
```typescript
declare const jetstream: import("@skyware/jetstream").Jetstream;
// ---
jetstream.onCreate("app.bsky.feed.post", (event) => {
console.log("New post:", event.commit.record.text)
});
```
--------------------------------
### Clear @skyware/labeler Database
Source: https://github.com/skyware-js/web/blob/main/src/content/guides/labeler/introduction/getting-started.mdx
This command is used to clear the database associated with a labeler account. It is recommended to run this command after deleting the database file if you no longer intend to use that account as a labeler, effectively returning it to a regular account.
```shell
npx @skyware/labeler clear
```
--------------------------------
### Handle All Commits with on
Source: https://github.com/skyware-js/web/blob/main/src/content/guides/jetstream/introduction/getting-started.mdx
Listens for all 'commit' events, regardless of the collection. The callback function checks the commit operation type (Create, Update, Delete) and logs relevant information like the collection, record, or rkey. This provides a comprehensive view of repository changes.
```typescript
declare const jetstream: import("@skyware/jetstream").Jetstream;
// ---
import { CommitType } from "@skyware/jetstream";
// Listen for all commits, regardless of collection
jetstream.on("commit", (event) => {
if (event.commit.operation === CommitType.Create) {
console.log("create in ", event.commit.collection, event.commit.record);
} else if (event.commit.operation === CommitType.Update) {
console.log("update in", event.commit.collection, event.commit.rkey);
} else if (event.commit.operation === CommitType.Delete) {
console.log("delete in", event.commit.collection, event.commit.rkey);
}
});
```
--------------------------------
### Handle Account and Identity Updates with on
Source: https://github.com/skyware-js/web/blob/main/src/content/guides/jetstream/introduction/getting-started.mdx
Subscribes to 'account' and 'identity' events emitted by Jetstream. The 'account' event handler logs the account status changes, while the 'identity' event handler logs the updated DID. These are broader events indicating changes to user accounts.
```typescript
declare const jetstream: import("@skyware/jetstream").Jetstream;
// ---
// Listen for account status updates
jetstream.on("account", (event) => {
console.log("account update", event.account.status)
});
// Listen for identity updates
jetstream.on("identity", (event) => {
console.log("identity update", event.identity.did)
});
```
--------------------------------
### Install Skyware Labeler and Bot Packages
Source: https://github.com/skyware-js/web/blob/main/src/content/guides/labeler/introduction/automated-labeling.mdx
Installs the necessary Skyware packages for labeler and bot functionalities using npm. These packages are essential for implementing automated labeling features.
```sh
npm install @skyware/labeler @skyware/bot
```
--------------------------------
### Negate a Label using Labeler Server
Source: https://github.com/skyware-js/web/blob/main/src/content/guides/labeler/introduction/getting-started.mdx
Shows how to remove or negate a previously applied label by setting the 'neg' property to true when calling createLabel. This is used to undo a label on a URI or DID.
```typescript
declare const server: import("@skyware/labeler").LabelerServer;
// ---cut---
await server.createLabel({
uri: "did:plc:427uaandx74txvzakxthrjwu",
val: "cool-cat",
neg: true
});
```
--------------------------------
### AT URI Examples
Source: https://github.com/skyware-js/web/blob/main/src/content/guides/global/glossary.mdx
Illustrates the structure of AT URIs, which are unique identifiers for records within a user's repository. AT URIs can include a user identifier (DID or domain), collection name, and record key.
```text
at://did:plc:ragtjsm2j2vknwkz3zp4oxrd/app.bsky.feed.post/3jvz2442yt32g
at://pfrazee.com/app.bsky.feed.post/3jvz2442yt32g
at://pfrazee.com
```
--------------------------------
### Generate Page Metadata for API and Guides (TypeScript)
Source: https://context7.com/skyware-js/web/llms.txt
Utility function to generate SEO metadata (title, description, OG image) for both API documentation (using TypeDoc reflections) and hand-written MDX guides. It combines information from code reflections and Astro content entries.
```typescript
import { generateMeta } from "./lib/util/generateMeta";
import type { DeclarationReflection } from "typedoc";
import type { CollectionEntry } from "astro:content";
// For API documentation
const reflection: DeclarationReflection = /* ... */;
const meta = generateMeta(reflection);
// Returns: {
// title: "Bot | @skyware/bot",
// description: "A class for creating Bluesky bots",
// ogImage: "/og/bot.png"
// }
// For guide pages
const guide: CollectionEntry<"guides"> = await getEntry("guides", "bot/introduction/getting-started");
const meta = generateMeta(reflection, guide);
// Returns: {
// title: "Getting Started | @skyware/bot",
// description: "Learn how to create your first Bluesky bot",
// ogImage: "/og/bot.png"
// }
```
--------------------------------
### Define Astro Content Collection for Guides (TypeScript)
Source: https://context7.com/skyware-js/web/llms.txt
Defines a content collection in Astro for managing guide documentation. It specifies the schema for guide entries, including required 'title' and 'description' fields.
```typescript
// src/content/config.ts
import { defineCollection, z } from "astro:content";
const guidesCollection = defineCollection({
type: "content",
schema: z.object({
title: z.string(),
description: z.string()
}),
});
export const collections = { guides: guidesCollection };
```
--------------------------------
### Get or Create Conversation for Members - TypeScript
Source: https://github.com/skyware-js/web/blob/main/src/content/guides/bot/introduction/chatting-with-users.mdx
Retrieves an existing conversation with specified members or creates a new one if it doesn't exist. This is the first step to initiating a chat with a user, requiring a 'Bot' instance.
```typescript
import { Bot } from "@skyware/bot";
declare const bot: Bot;
const conversation = await bot.getConversationForMembers(["did:plc:ith6w2xyj2qy3rcvmlsem6fz"]);
```
--------------------------------
### Reply to Messages with Sender and Conversation Info (TypeScript)
Source: https://github.com/skyware-js/web/blob/main/src/content/guides/bot/introduction/chatting-with-users.mdx
Extends the message handling to retrieve sender and conversation details, enabling a reply to the sender. It uses `message.getSender()` and `message.getConversation()` to get references to the sender's profile and the conversation context. Handles cases where conversation resolution might fail. Requires the bot to be initialized with `emitChatEvents: true`.
```typescript
import { Bot, type ChatMessage } from "@skyware/bot";
declare const bot: Bot;
// ---cut---
bot.on("message", async (message: ChatMessage) => {
const sender = await message.getSender();
console.log(`Received message from @${sender.handle}: ${message.text}`);
const conversation = await message.getConversation();
if (conversation) {
// It may not always be possible to resolve the conversation the message was sent in!
await conversation.sendMessage({ text: "Hey there, " + sender.displayName + "!" });
}
});
```
--------------------------------
### Generating Sidebar Navigation Structure
Source: https://context7.com/skyware-js/web/llms.txt
Generates a structured sidebar navigation data object from a module reflection. The output includes organized lists for modules, guides, documentation sections (classes, functions, types, enums, variables), and the module reflection itself.
```typescript
import { generateSidebar } from "./components/layout/Sidebar.astro";
import { DeclarationReflection, ReflectionKind } from "typedoc";
// Generate sidebar data structure
const module: DeclarationReflection = /* module reflection */;
const sidebar = await generateSidebar(module);
// Structure returned:
// {
// modules: [{ name: "@skyware/bot", url: "docs/bot" }],
// guides: [
// {
// category: "Introduction",
// entries: [
// { slug: "bot/introduction/getting-started", data: { title: "...", description: "..." } }
// ]
// }
// ],
// docs: {
// classes: [{ name: "Bot", url: "docs/bot/classes/Bot", reflection: {...} }],
// functions: [...],
// types: [...],
// enums: [...],
// variables: [...]
// },
// module: reflection
// }
```
--------------------------------
### Get Chat Messages - TypeScript
Source: https://github.com/skyware-js/web/blob/main/src/content/guides/bot/introduction/chatting-with-users.mdx
Retrieves chat history for a given conversation. This method returns an array of message objects (ChatMessage or DeletedChatMessage) and a cursor for pagination. It allows fetching up to 100 messages at a time.
```typescript
import { Conversation } from "@skyware/bot";
declare const conversation: Conversation;
const { cursor, messages } = await conversation.getMessages();
// You'll only receive up to 100 messages at a time — you can use the cursor to fetch messages further into the past!
const { messages: moreMessages } = await conversation.getMessages(cursor);
```
--------------------------------
### Build and Preview Production Site (Bash)
Source: https://context7.com/skyware-js/web/llms.txt
Builds the static site for production deployment and provides a way to preview the built site locally.
```bash
# Pull latest repos and build static site
pnpm build
# Preview production build
pnpm preview
```
--------------------------------
### Complete Skyware Labeler and Bot Implementation - TypeScript
Source: https://github.com/skyware-js/web/blob/main/src/content/guides/labeler/introduction/automated-labeling.mdx
This is the complete, consolidated TypeScript code for running the Skyware Labeler server and bot. It includes initializing the server, logging in the bot, defining a mapping for post-to-label assignments, and handling 'like' events to apply labels to user accounts. Ensure all environment variables and AT URIs are correctly configured.
```typescript
if (!process.env.LABELER_DID || !process.env.LABELER_PASSWORD || !process.env.SIGNING_KEY) throw "";
// ---cut---
import { LabelerServer } from "@skyware/labeler";
import { Bot, Post } from "@skyware/bot";
const server = new LabelerServer({
did: process.env.LABELER_DID,
signingKey: process.env.SIGNING_KEY,
});
server.start(14831, (error) => {
if (error) {
console.error("Failed to start: ", error);
} else {
console.log("Listening on port 14831");
}
});
const bot = new Bot();
await bot.login({
identifier: process.env.LABELER_DID,
password: process.env.LABELER_PASSWORD,
});
const postsToLabels: Record = {
"at://did:.../app.bsky.feed.post/f1234": "fire",
"at://did:.../app.bsky.feed.post/w3456": "water",
"at://did:.../app.bsky.feed.post/a5678": "air",
"at://did:.../app.bsky.feed.post/e7890": "earth",
}
bot.on("like", async ({ subject, user }) => {
if (subject instanceof Post) {
const label = postsToLabels[subject.uri];
if (label) {
await user.labelAccount([label]);
}
}
});
```
--------------------------------
### Create Posts for Labeling with Skyware Bot
Source: https://github.com/skyware-js/web/blob/main/src/content/guides/labeler/introduction/automated-labeling.mdx
Creates a main post and several reply posts (e.g., 'Fire!', 'Water!') using the Skyware Bot. The `post` method creates the initial post, and its `reply` method generates subsequent posts, returning their AT URIs for later use. Threadgate is used to restrict replies.
```ts
if (!process.env.LABELER_DID || !process.env.LABELER_PASSWORD || !process.env.SIGNING_KEY) throw "";
// ---cut---
import { Bot } from "@skyware/bot";
const bot = new Bot();
await bot.login({
identifier: process.env.LABELER_DID,
password: process.env.LABELER_PASSWORD,
});
const post = await bot.post({ text: "Like the replies to this post to receive labels.", threadgate: { allowLists: [] } });
const firePost = await post.reply({ text: "Fire!" });
const waterPost = await post.reply({ text: "Water!"});
const airPost = await post.reply({ text: "Air!" });
const earthPost = await post.reply({ text: "Earth!" });
console.log(
`Fire: ${firePost.uri}\n`,
`Water: ${waterPost.uri}\n`,
`Air: ${airPost.uri}\n`,
`Earth: ${earthPost.uri}\n`,
);
// Fire: at://did:.../app.bsky.feed.post/...
// Water: at://did:.../app.bsky.feed.post/...
// Air: at://did:.../app.bsky.feed.post/...
// Earth: at://did:.../app.bsky.feed.post/...
```
--------------------------------
### TypeDoc Application Bootstrap (TypeScript)
Source: https://context7.com/skyware-js/web/llms.txt
Initializes a TypeDoc application instance, configuring it to process packages and extract documentation. It sets entry points and filters to exclude external, internal, private, and protected members.
```typescript
import {
Application,
ReflectionKind,
} from "typedoc";
import {
externalSymbolLinkMappings,
} from "../lib/util/resolveUrl";
const app = await Application.bootstrap({
entryPointStrategy: "packages",
entryPoints: ["packages/*"],
excludeExternals: true,
excludeInternal: true,
excludePrivate: true,
excludeProtected: true,
externalSymbolLinkMappings,
});
const project = await app.convert();
const modules = project.getChildrenByKind(ReflectionKind.Module);
```
--------------------------------
### Configure Skyware Labeler Environment Variables
Source: https://github.com/skyware-js/web/blob/main/src/content/guides/labeler/introduction/automated-labeling.mdx
Sets up environment variables required for the Skyware labeler to authenticate and operate. These include the labeler's DID, password, and signing key, typically loaded using the dotenv package.
```env
LABELER_DID=did:...
LABELER_PASSWORD=...
SIGNING_KEY=...
```
--------------------------------
### Configure Astro Site and Redirects (TypeScript)
Source: https://context7.com/skyware-js/web/llms.txt
Configuration file for Astro, defining the site's base URL and setting up permanent redirects for older documentation paths to new locations. It also lists integrated plugins like Tailwind CSS, React, MDX, and Sitemap.
```typescript
// astro.config.ts
export default defineConfig({
site: "https://skyware.js.org",
redirects: {
"/docs/bot": "/guides/bot/introduction/getting-started",
"/docs/firehose": "/guides/firehose/introduction/getting-started",
"/docs/labeler": "/guides/labeler/introduction/getting-started",
"/docs/jetstream": "/guides/jetstream/introduction/getting-started",
},
integrations: [tailwind(), react(), mdx(), sitemap()],
});
```
--------------------------------
### Rendering Class Documentation with Astro Templates
Source: https://context7.com/skyware-js/web/llms.txt
Selects appropriate Astro templates (ClassPage, FunctionPage, TypePage, etc.) based on the ReflectionKind. It also extracts and sorts constructor, properties, accessors, and methods for rendering.
```typescript
// Template selection based on reflection kind
import ClassPage from "../templates/ClassPage.astro";
import FunctionPage from "../templates/FunctionPage.astro";
import TypePage from "../templates/TypePage.astro";
const DocsTemplates: Partial> = {
[ReflectionKind.Class]: ClassPage,
[ReflectionKind.Interface]: TypePage,
[ReflectionKind.TypeAlias]: TypePage,
[ReflectionKind.Enum]: EnumPage,
[ReflectionKind.Function]: FunctionPage,
[ReflectionKind.Variable]: VariablePage,
};
// ClassPage renders constructor, properties, accessors, methods
const ctor = reflection.getChildrenByKind(ReflectionKind.Constructor)[0];
const properties = sort(
reflection.getChildrenByKind(ReflectionKind.VariableOrProperty)
.filter(reflectionShouldBeRendered)
);
const methods = sort(
reflection.getChildrenByKind(ReflectionKind.Method)
.filter(method =>
reflectionShouldBeRendered(method) &&
method.signatures?.some(reflectionShouldBeRendered)
)
);
```
--------------------------------
### Build Basic Rich Text Post
Source: https://github.com/skyware-js/web/blob/main/src/content/guides/bot/advanced-posting/rich-text.mdx
Demonstrates constructing a rich text string using the RichText builder. It includes adding text, a hyperlink, and a hashtag, then posting it using the bot. The Bot#post method accepts either RichText objects or plain strings.
```typescript
import { RichText, Bot } from "@skyware/bot";
declare const bot: Bot;
// ---cut---
const richText = new RichText()
.addText("Hey, check out this library: ")
.addLink("skyware.js.org", "https://skyware.js.org")
.addText("! ")
.addTag("#atdev");
await bot.post({ text: richText })
```
--------------------------------
### Apply Labels Based on Liked Post - TypeScript
Source: https://github.com/skyware-js/web/blob/main/src/content/guides/labeler/introduction/automated-labeling.mdx
Enhances the 'like' event handler to apply specific labels to a user's account based on the AT URI of the liked post. It uses a predefined mapping of post URIs to labels and calls the `user.labelAccount` method. Ensure the AT URIs in the `postsToLabels` object are accurate.
```typescript
declare const server: import("@skyware/labeler").LabelerServer;
declare const bot: import("@skyware/bot").Bot;
import { Post } from "@skyware/bot";
// ---cut---
const postsToLabels: Record = {
"at://did:.../app.bsky.feed.post/f1234": "fire",
"at://did:.../app.bsky.feed.post/w3456": "water",
"at://did:.../app.bsky.feed.post/a5678": "air",
"at://did:.../app.bsky.feed.post/e7890": "earth",
}
bot.on("like", async ({ subject, user }) => {
if (subject instanceof Post) {
const label = postsToLabels[subject.uri];
if (label) {
await user.labelAccount([label]);
}
}
});
```
--------------------------------
### Listen for Likes and Log Post URI - TypeScript
Source: https://github.com/skyware-js/web/blob/main/src/content/guides/labeler/introduction/automated-labeling.mdx
Extends the bot functionality to listen for 'like' events. When a like occurs, it checks if the subject of the like is an instance of the Post class and logs the AT URI of the post to the console. This snippet demonstrates event handling for likes.
```typescript
declare const bot: import("@skyware/bot").Bot;
// ---cut---
// Modify your import to include the Post class
import { Bot, Post } from "@skyware/bot";
// ...
bot.on("like", async ({ subject, user }) => {
if (subject instanceof Post) {
console.log(subject.uri);
}
});
```
--------------------------------
### Initialize Bot for Chat Events (TypeScript)
Source: https://github.com/skyware-js/web/blob/main/src/content/guides/bot/introduction/chatting-with-users.mdx
Initializes the Skyware bot with the `emitChatEvents` option set to `true`. This is a prerequisite for receiving and processing incoming chat messages. No external dependencies are required beyond the `@skyware/bot` library.
```typescript
import { Bot } from "@skyware/bot";
// ---cut---
const bot = new Bot({ emitChatEvents: true });
```
--------------------------------
### Listen for Bot Events (TypeScript)
Source: https://github.com/skyware-js/web/blob/main/src/content/guides/bot/introduction/listening-to-events.mdx
This snippet demonstrates how to listen for a 'reply' event on a Skyware JS bot instance. When a reply is received, the bot automatically likes the reply and sends a confirmation message. This showcases the basic usage of the `bot.on()` method for handling user interactions.
```typescript
declare const bot: import("@skyware/bot").Bot;
// ---cut---
bot.on("reply", async (reply) => {
await reply.like();
await reply.reply({ text: "Thanks for the reply!" });
})
```
--------------------------------
### Generate Static Paths for Documentation Pages (TypeScript)
Source: https://context7.com/skyware-js/web/llms.txt
Generates static paths for Astro pages based on TypeDoc reflections. It iterates through modules and their children, filtering and resolving URLs for renderable reflection types (classes, interfaces, etc.).
```typescript
// From src/pages/[...path].astro
export async function getStaticPaths(): Promise {
const app = await Application.bootstrap({
entryPointStrategy: "packages",
entryPoints: ["packages/*"],
});
const project = await app.convert();
const modules = project.getChildrenByKind(ReflectionKind.Module);
const pages: GetStaticPathsResult = [];
for (const module of modules) {
for (const reflection of module.children || []) {
if (!reflectionShouldBeRendered(reflection)) continue;
let path = resolveReflectionUrl(reflection);
if (path?.startsWith("/")) path = path.slice(1);
if (reflection.kindOf([
ReflectionKind.Class,
ReflectionKind.Interface,
ReflectionKind.TypeAlias,
ReflectionKind.Enum,
ReflectionKind.Function,
ReflectionKind.Variable,
])) {
pages.push({ params: { path }, props: { reflection } });
}
}
}
return pages;
}
```
--------------------------------
### Handle Incoming Messages (TypeScript)
Source: https://github.com/skyware-js/web/blob/main/src/content/guides/bot/introduction/chatting-with-users.mdx
Sets up an event listener for the 'message' event on the Skyware bot. This function is called whenever a new chat message is received. It logs the message text to the console. Requires the bot to be initialized with `emitChatEvents: true`.
```typescript
import { Bot, type ChatMessage } from "@skyware/bot";
declare const bot: Bot;
// ---cut---
bot.on("message", async (message: ChatMessage) => {
console.log(`Received message: ${message.text}`);
});
```
--------------------------------
### Map Reflection Kinds to URL Categories (TypeScript)
Source: https://context7.com/skyware-js/web/llms.txt
Maps TypeDoc reflection kinds (e.g., Class, Interface) to corresponding URL categories for documentation. This helps in organizing and routing API documentation pages based on the type of code element.
```typescript
// Map reflection kinds to URL categories
export const UrlCategories: Partial> = {
[ReflectionKind.Class]: "classes",
[ReflectionKind.Interface]: "types",
[ReflectionKind.TypeAlias]: "types",
[ReflectionKind.Function]: "functions",
[ReflectionKind.Variable]: "variables",
[ReflectionKind.Enum]: "enums",
};
// Generate category URL
const category = UrlCategories[reflection.kind];
const url = `/docs/${repoName}/${category}/${reflection.name}`;
// Example: "/docs/bot/classes/Bot"
```
--------------------------------
### Configuring Shiki Highlighter with Twoslash Transformer in Astro
Source: https://context7.com/skyware-js/web/llms.txt
Configures the Shiki code highlighter within Astro's markdown settings to use the Twoslash transformer. This enables features like type inference previews and custom markdown rendering within tooltips.
```typescript
// astro.config.ts
import { transformerTwoslash } from "@shikijs/twoslash";
import { defineConfig } from "astro/config";
export default defineConfig({
markdown: {
shikiConfig: {
theme: "catppuccin-mocha",
transformers: [
transformerTwoslash({
rendererRich: {
renderMarkdown: renderMarkdownInTwoslashHover,
renderMarkdownInline: renderMarkdownInTwoslashHover,
},
twoslashOptions: {
compilerOptions: {
module: 199, // nodenext
moduleResolution: 99 // nodenext
}
}
}),
],
wrap: true,
},
},
});
```
--------------------------------
### Import RichText Class
Source: https://github.com/skyware-js/web/blob/main/src/content/guides/bot/advanced-posting/rich-text.mdx
This snippet shows how to import the RichText class from the @skyware/bot package, which is the first step in creating rich text posts.
```typescript
import { RichText } from "@skyware/bot";
```
--------------------------------
### Rendering Code with Type Inference using Twoslash
Source: https://context7.com/skyware-js/web/llms.txt
Renders code snippets with syntax highlighting and type inference previews using the `renderCode` function and Shiki highlighter configured with Twoslash. Supports both full code blocks and inline code rendering.
```typescript
import { renderCode, highlighter } from "./lib/rendering/renderMarkdown";
// Render code with Twoslash type hovers
const code = `
import { Bot } from "@skyware/bot";
const bot = new Bot();
await bot.login({ identifier: "user", password: "pass" });
`;
const rendered = renderCode(code, { twoslash: true, inline: false });
// Outputs syntax-highlighted code with hover previews showing inferred types
// Render inline code
const inlineCode = renderCode("bot.login()", { twoslash: false, inline: true });
```
--------------------------------
### Pull Source Repositories (Bash)
Source: https://context7.com/skyware-js/web/llms.txt
Pulls all configured repositories from config.json. Supports an overwrite flag to force updates.
```bash
# Pull all configured repositories from config.json
pnpm pull
# Force overwrite local changes
pnpm pull --overwrite
```
--------------------------------
### Add Mention to Rich Text Post
Source: https://github.com/skyware-js/web/blob/main/src/content/guides/bot/advanced-posting/rich-text.mdx
Shows how to add a user mention to a rich text post using the `.addMention` method. This requires the user's handle and DID. The `Bot#post` method is used to send the post.
```typescript
import { RichText, Bot } from "@skyware/bot";
declare const bot: Bot;
// ---cut---
const richText = new RichText()
.addText("Hey, ")
.addMention("@skyware.js.org", "did:plc:ith6w2xyj2qy3rcvmlsem6fz")
.addText("!");
await bot.post({ text: richText })
```
--------------------------------
### Post with Manually Provided Facets
Source: https://github.com/skyware-js/web/blob/main/src/content/guides/bot/advanced-posting/rich-text.mdx
Demonstrates how to manually provide facets for a post, which bypasses automatic text parsing. This is useful for replicating facets from another post. The `Bot#post` method is used.
```typescript
import { Post, Bot } from "@skyware/bot";
declare const bot: Bot;
declare const otherPost: Post;
// ---cut---
await bot.post({ text: otherPost.text, facets: otherPost.facets });
```
--------------------------------
### Configure Algolia DocSearch Component (TypeScript)
Source: https://context7.com/skyware-js/web/llms.txt
Integrates Algolia DocSearch into a React component within an Astro project. It requires the application ID, API key, and index name for DocSearch configuration.
```typescript
// src/components/layout/DocSearch.tsx
import { DocSearch } from "@docsearch/react";
```
--------------------------------
### Search Component with Platform Detection (TypeScript)
Source: https://context7.com/skyware-js/web/llms.txt
A React component that displays a search button and dynamically adjusts the keyboard shortcut modifier (Command ⌘ for Mac/iOS, Control ⌃ for others) based on the user's platform detected via `navigator.platform`.
```typescript
import { useEffect, useState } from "react";
export function Search() {
const [modifier, setModifier] = useState("⌃");
useEffect(() => {
setModifier(/(Mac|iPhone|iPod|iPad)/i.test(navigator.platform) ? "⌘" : "⌃");
}, []);
return (
);
}
```
--------------------------------
### List Bot Conversations - TypeScript
Source: https://github.com/skyware-js/web/blob/main/src/content/guides/bot/introduction/chatting-with-users.mdx
Fetches a list of conversations the bot is currently participating in. The method supports pagination using a cursor to retrieve older conversations. It returns a list of conversation objects and a cursor for subsequent calls.
```typescript
import { Bot } from "@skyware/bot";
declare const bot: Bot;
const { cursor, conversations } = await bot.listConversations();
// The method only returns 100 conversations at a time — use the cursor to fetch more conversations
const { conversations: moreConversations } = await bot.listConversations({ cursor });
```
--------------------------------
### Resolve URLs and Link External Symbols (TypeScript)
Source: https://context7.com/skyware-js/web/llms.txt
Provides utility functions to resolve URLs for TypeDoc reflections and source code, and maps external symbols to their documentation links. Useful for cross-linking within generated documentation.
```typescript
import { resolveReflectionUrl, resolveTypeUrl, resolveSourceUrl } from "./lib/util/resolveUrl";
import { DeclarationReflection } from "typedoc";
// Resolve URL for a class/function/type
const reflection: DeclarationReflection = /* ... */;
const url = resolveReflectionUrl(reflection);
// Returns: "/docs/bot/classes/Bot"
// Resolve GitHub source URL
const sourceUrl = resolveSourceUrl(reflection);
// Returns: "https://github.com/skyware-js/bot/blob/main/src/Bot.ts#L42"
// Link external types
const externalSymbolLinkMappings = {
global: {
Promise: "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise",
},
"@atcute/client": {
"XRPC": "https://github.com/mary-ext/atcute/tree/trunk/packages/core/client",
},
};
```
--------------------------------
### StrongRef Object
Source: https://github.com/skyware-js/web/blob/main/src/content/guides/global/glossary.mdx
Represents a StrongRef, an immutable reference to a record within the AT Protocol. It combines both the AT URI and the CID of the record for integrity verification.
```javascript
{
"uri": "string",
"cid": "string"
}
```
--------------------------------
### Embed Images in a Post (TypeScript)
Source: https://github.com/skyware-js/web/blob/main/src/content/guides/bot/advanced-posting/embeds-and-images.mdx
This code shows how to embed up to four images within a post using the `images` property. Each image object requires `data` (a URL or image data) and an `alt` text for accessibility. This feature enhances posts with visual content.
```typescript
declare const bot: import("@skyware/bot").Bot;
// ---cut---
await bot.post({
text: "Check out this image!",
images: [
{
data: "https://http.cat/images/418.jpg",
alt: "A cat in a teapot, with the caption '418 I'm a teapot'",
},
],
});
```
--------------------------------
### Embed an External Link in a Post (TypeScript)
Source: https://github.com/skyware-js/web/blob/main/src/content/guides/bot/advanced-posting/embeds-and-images.mdx
This snippet illustrates embedding external links into a post using the `external` property. It accepts a URL string, which the platform can then format as an embed with a title, description, and preview image. This is useful for sharing content from other websites.
```typescript
declare const bot: import("@skyware/bot").Bot;
// ---cut---
await bot.post({
text: "Check out this link!",
external: "https://skyware.js.org"
});
```
--------------------------------
### Rendering Markdown Comments with Typedoc
Source: https://context7.com/skyware-js/web/llms.txt
Processes and renders markdown comments, including code blocks and links, using `renderMarkdown` and `parseMarkdown` from `./lib/rendering/renderMarkdown`. It supports parsing markdown strings into structured comment display parts.
```typescript
import { renderMarkdown, parseMarkdown } from "./lib/rendering/renderMarkdown";
import { CommentDisplayPart } from "typedoc";
// Parse markdown with code blocks and links
const parts: CommentDisplayPart[] = [
{ kind: "text", text: "Creates a new `Bot` instance. See [docs](/docs) for details." },
{ kind: "code", text: "const bot = new Bot();" }
];
const rendered = renderMarkdown(parts);
// Outputs React nodes with syntax highlighting, links, and Twoslash hovers
// Parse markdown string
const parsed = parseMarkdown("Use `Bot.login()` to [authenticate](https://example.com)");
// Returns:
// [
// { text: "Use " },
// { text: "Bot.login()", code: true, inline: true },
// { text: " to " },
// { text: "authenticate", url: "https://example.com" }
// ]
```
--------------------------------
### DID Document Structure
Source: https://github.com/skyware-js/web/blob/main/src/content/guides/global/glossary.mdx
Defines the expected structure of a DID document, which contains identity information for DIDs. Key fields include the DID itself, alternative identifiers, verification methods, and associated services.
```json
{
"id": "string",
"alsoKnownAs": ["string"],
"verificationMethods": {},
"services": {}
}
```
--------------------------------
### Send and Read Messages via Profile - TypeScript
Source: https://github.com/skyware-js/web/blob/main/src/content/guides/bot/introduction/chatting-with-users.mdx
Allows sending and reading messages directly using a 'Profile' object, bypassing the need for a 'Conversation' object. This is useful if you already have the user's profile information.
```typescript
import { Profile } from "@skyware/bot";
declare const profile: Profile;
await profile.sendMessage({ text: "Hello, world!" });
const { messages } = await profile.getMessages();
```
--------------------------------
### Add Hyperlink to Rich Text Post
Source: https://github.com/skyware-js/web/blob/main/src/content/guides/bot/advanced-posting/rich-text.mdx
Illustrates using the `.addLink` method to create a hyperlink within a rich text post. This method takes the link text and the URL as parameters. The post is then sent via `Bot#post`.
```typescript
import { RichText, Bot } from "@skyware/bot";
declare const bot: Bot;
// ---cut---
const richText = new RichText()
.addText("Hey, check out ")
.addLink("Skyware", "https://skyware.js.org")
.addText("!");
await bot.post({ text: richText })
```
--------------------------------
### Embed a Post in a Post (TypeScript)
Source: https://github.com/skyware-js/web/blob/main/src/content/guides/bot/advanced-posting/embeds-and-images.mdx
This snippet demonstrates how to embed a previously created post within a new post. It utilizes the `quoted` property, which accepts a post object or an object with `uri` and `cid`. This allows for referencing and displaying other posts directly.
```typescript
declare const bot: import("@skyware/bot").Bot;
// ---cut---
const post = await bot.getPost(
"at://did:plc:ragtjsm2j2vknwkz3zp4oxrd/app.bsky.feed.post/3jvz2442yt32g"
);
await bot.post({
text: "Check out this post!",
quoted: post,
});
```
--------------------------------
### Send Rich Text Message - TypeScript
Source: https://github.com/skyware-js/web/blob/main/src/content/guides/bot/introduction/chatting-with-users.mdx
Sends a formatted message containing links and mentions using the RichText class. This method allows for more complex message structures than plain text. It requires a 'Conversation' object and a 'RichText' instance.
```typescript
import { Conversation } from "@skyware/bot";
declare const conversation: Conversation;
import { RichText } from "@skyware/bot";
await conversation.sendMessage({
text: new RichText().addText("I love ").addLink("Skyware", "https://skyware.js.org").addText("!")
});
```
--------------------------------
### Configure Bot for Jetstream Event Strategy (TypeScript)
Source: https://github.com/skyware-js/web/blob/main/src/content/guides/bot/introduction/listening-to-events.mdx
This snippet shows how to configure a Skyware JS bot to use the Jetstream strategy for event listening. This involves setting the `strategy` option to `EventStrategy.Jetstream` within `eventEmitterOptions`, enabling real-time event updates via a WebSocket connection instead of polling. This is suitable for bots requiring immediate event processing.
```typescript
import { Bot, EventStrategy } from "@skyware/bot";
const bot = new Bot({
eventEmitterOptions: {
strategy: EventStrategy.Jetstream
}
});
```
--------------------------------
### Set Incoming Chat Preference - TypeScript
Source: https://github.com/skyware-js/web/blob/main/src/content/guides/bot/introduction/chatting-with-users.mdx
Configures whether the bot receives messages from any user, only followed users, or no users. This function call affects the bot's ability to receive new chat messages. It requires the 'Bot' and 'IncomingChatPreference' modules from '@skyware/bot'.
```typescript
import { Bot, IncomingChatPreference } from "@skyware/bot";
const bot = new Bot();
await bot.setChatPreference(IncomingChatPreference.All);
```
--------------------------------
### Send Text Message - TypeScript
Source: https://github.com/skyware-js/web/blob/main/src/content/guides/bot/introduction/chatting-with-users.mdx
Sends a plain text message to a user within a conversation. This requires a 'Conversation' object and a message object containing the 'text' property.
```typescript
import { Conversation } from "@skyware/bot";
declare const conversation: Conversation;
await conversation.sendMessage({ text: "Hello, world!" });
```
--------------------------------
### Configure Bot Polling Interval (TypeScript)
Source: https://github.com/skyware-js/web/blob/main/src/content/guides/bot/introduction/listening-to-events.mdx
This code configures the polling interval for event listeners in a Skyware JS bot. By setting `pollingInterval` within `eventEmitterOptions`, you can control how frequently the bot checks for new events, helping to manage rate limits and optimize performance. The default is 5 seconds.
```typescript
// @noErrors: 2741
import { Bot } from "@skyware/bot";
// ---cut---
const bot = new Bot({
eventEmitterOptions: {
pollingInterval: 10 // Poll every 10 seconds
}
});
```
--------------------------------
### Disable Automatic Facet Detection
Source: https://github.com/skyware-js/web/blob/main/src/content/guides/bot/advanced-posting/rich-text.mdx
Shows how to disable Skyware's automatic facet detection for a post by passing `{ resolveFacets: false }` as an option to the `Bot#post` method. This ensures that no automatic mentions or hashtags are parsed from the text.
```typescript
declare const bot: import("@skyware/bot").Bot;
// ---cut---
await bot.post({
text: "i love the @protocol"
}, { resolveFacets: false });
```
--------------------------------
### Rendering TypeScript Types with Typedoc
Source: https://context7.com/skyware-js/web/llms.txt
Renders various TypeScript types, including union types (e.g., string | number | null), reference types with links to definitions, and complex intersection types. It utilizes the `renderType` function from `./lib/rendering/renderType`.
```typescript
import { renderType } from "./lib/rendering/renderType";
import { UnionType, IntersectionType, ReferenceType } from "typedoc";
// Render union types: string | number | null
const unionType = new UnionType([stringType, numberType, nullType]);
const rendered = renderType(unionType);
// Output: string | number | null
// Render reference types with links
const referenceType = new ReferenceType("Bot", reflection);
const rendered = renderType(referenceType);
// Output: Bot
// Render complex types
const complexType = {
type: "intersection",
types: [
{ type: "reference", name: "BaseOptions" },
{ type: "object", properties: [/* ... */] }
]
};
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.