### Quick Start: Basic AppService Setup Source: https://github.com/matrix-org/matrix-appservice-node/blob/develop/_autodocs/README.md This snippet demonstrates how to generate a registration file, create an AppService instance, listen for room messages, handle user queries, and start the server. ```typescript import { AppService, AppServiceRegistration } from "matrix-appservice"; // Generate registration const reg = new AppServiceRegistration("http://localhost:8010"); reg.setId("my-bot"); reg.setHomeserverToken(AppServiceRegistration.generateToken()); reg.setAppServiceToken(AppServiceRegistration.generateToken()); reg.setSenderLocalpart("bot"); reg.addRegexPattern("users", "@bot_.+", true); reg.outputAsYaml("registration.yaml"); // Create appservice const as = new AppService({ homeserverToken: reg.getHomeserverToken() }); // Listen for events as.on("type:m.room.message", (event) => { console.log(`Message: ${event.content.body}`); }); // Handle queries as.onUserQuery = async (userId) => { // Validate or create user }; // Start server await as.listen(8010, "localhost", 50); ``` -------------------------------- ### User Query Endpoint Example Source: https://github.com/matrix-org/matrix-appservice-node/blob/develop/_autodocs/endpoints.md Example GET request to query if an appservice can handle a specific user ID. Requires an access token. ```http GET /_matrix/app/v1/users/@bot:example.com?access_token=secret123 ``` -------------------------------- ### Complete AppServiceRegistration Example Source: https://github.com/matrix-org/matrix-appservice-node/blob/develop/_autodocs/api-reference/AppServiceRegistration.md This snippet shows a complete example of creating and configuring an AppServiceRegistration object, including setting required fields, defining protocols and namespaces, and outputting the registration to a YAML file. ```typescript const reg = new AppServiceRegistration("http://localhost:8010"); // Set required fields reg.setId("irc-bridge"); reg.setHomeserverToken(AppServiceRegistration.generateToken()); reg.setAppServiceToken(AppServiceRegistration.generateToken()); reg.setSenderLocalpart("ircbot"); // Configure protocols and namespaces reg.setProtocols(["irc"]); reg.addRegexPattern("users", "@irc_.+", true); // Exclusive reg.addRegexPattern("aliases", "#irc_.+", true); // Optional: enable ephemeral events reg.pushEphemeral = true; // Disable rate limiting for this service reg.setRateLimited(false); // Write to file for homeserver configuration reg.outputAsYaml("registration.yaml"); ``` -------------------------------- ### Initialize AppService Source: https://github.com/matrix-org/matrix-appservice-node/blob/develop/_autodocs/INDEX.md Create and start an AppService instance. Ensure the homeserver token is correctly configured. ```typescript const as = new AppService({ homeserverToken: "token" }); as.listen(8010, "0.0.0.0", 50); ``` -------------------------------- ### Start AppService Server Source: https://github.com/matrix-org/matrix-appservice-node/blob/develop/_autodocs/api-reference/AppService.md Starts the HTTP server listening on the specified port. Supports both HTTP and HTTPS via environment variables. Use a callback for immediate feedback or omit it to receive a Promise. ```typescript await appService.listen(8010, "localhost", 50); ``` ```typescript appService.listen(8010, "localhost", 50, () => { console.log("Server listening on port 8010"); }); ``` ```bash # MATRIX_AS_TLS_KEY=/path/to/key.pem MATRIX_AS_TLS_CERT=/path/to/cert.pem node app.js ``` -------------------------------- ### AppServiceOutput Example and YAML Output Source: https://github.com/matrix-org/matrix-appservice-node/blob/develop/_autodocs/types.md Shows a complete example of an AppServiceOutput object and how to use it to create and output a registration file in YAML format. This is useful for configuring app services. ```typescript const output: AppServiceOutput = { id: "my-appservice", url: "http://localhost:8010", hs_token: "secret123", as_token: "secret456", sender_localpart: "bot", rate_limited: false, protocols: ["irc"], "de.sorunome.msc2409.push_ephemeral": true, namespaces: { users: [ { regex: "@irc_.+", exclusive: true }, { regex: "@bridge_.+", exclusive: false } ], aliases: [ { regex: "#irc_.+", exclusive: true } ] } }; // Write to YAML const reg = AppServiceRegistration.fromObject(output); reg.outputAsYaml("registration.yaml"); ``` -------------------------------- ### Synapse Homeserver Configuration Source: https://github.com/matrix-org/matrix-appservice-node/blob/develop/_autodocs/configuration.md Example configuration for Synapse to load an app service registration file. ```yaml app_service_config_files: - /path/to/registration.yaml ``` -------------------------------- ### listen Source: https://github.com/matrix-org/matrix-appservice-node/blob/develop/_autodocs/api-reference/AppService.md Starts the HTTP server listening on the specified port. Supports both HTTP and HTTPS via environment variables. ```APIDOC ## listen ### Description Starts the HTTP server listening on the specified port. Supports both HTTP and HTTPS via environment variables. ### Method Signature ```typescript listen( port: number, hostname: string, backlog: number, callback?: () => void ): Promise | void ``` ### Parameters #### Path Parameters * None #### Query Parameters * None #### Request Body * None ### Parameters Table | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| | port | number | Yes | — | TCP port to listen on | | hostname | string | Yes | — | Hostname or IP address to bind to | | backlog | number | Yes | — | Maximum length of pending connections queue | | callback | function | No | — | Callback invoked when server is listening; omit to get a Promise | ### Returns `Promise` if no callback provided; `void` if callback is provided. ### Throws Error if both TLS environment variables are not defined together or if files do not exist. ### Environment Variables - `MATRIX_AS_TLS_KEY` — Path to TLS private key file (enables HTTPS) - `MATRIX_AS_TLS_CERT` — Path to TLS certificate file (enables HTTPS) ### Example ```typescript // Using Promise await appService.listen(8010, "localhost", 50); // Using callback appService.listen(8010, "localhost", 50, () => { console.log("Server listening on port 8010"); }); // HTTPS (set environment variables first) // MATRIX_AS_TLS_KEY=/path/to/key.pem MATRIX_AS_TLS_CERT=/path/to/cert.pem node app.js ``` ``` -------------------------------- ### Transaction Request Example Source: https://github.com/matrix-org/matrix-appservice-node/blob/develop/_autodocs/endpoints.md An example of a PUT request to the transaction endpoint, including both regular message events and ephemeral receipt events. ```json PUT /_matrix/app/v1/transactions/abc123?access_token=secret123 { "events": [ { "type": "m.room.message", "event_id": "$event1", "room_id": "!room:example.com", "sender": "@user:example.com", "origin_server_ts": 1234567890, "content": { "msgtype": "m.text", "body": "Hello, world!" } } ], "ephemeral": [ { "type": "m.receipt", "content": { "!room:example.com": { "m.read": { "@user:example.com": { "ts": 1234567890 } } } } } ] } ``` -------------------------------- ### Create and Configure a Basic AppService Source: https://github.com/matrix-org/matrix-appservice-node/blob/develop/_autodocs/INDEX.md This snippet demonstrates how to initialize an AppService, configure its registration details, and set up basic event listeners. Ensure you have the 'matrix-appservice' library installed. ```typescript import { AppService, AppServiceRegistration } from "matrix-appservice"; // Create and configure registration const reg = new AppServiceRegistration("http://localhost:8010"); reg.setId("my-bot"); reg.setHomeserverToken(AppServiceRegistration.generateToken()); reg.setAppServiceToken(AppServiceRegistration.generateToken()); reg.setSenderLocalpart("bot"); reg.addRegexPattern("users", "@bot_.+", true); reg.outputAsYaml("registration.yaml"); // Create appservice const appService = new AppService({ homeserverToken: reg.getHomeserverToken() }); // Handle messages appService.on("type:m.room.message", (event) => { console.log(`[${event.room_id}] ${event.sender}: ${event.content.body}`); }); // Start server appService.listen(8010, "localhost", 50, () => { console.log("Appservice listening on port 8010"); }); ``` -------------------------------- ### Room Alias Query Endpoint Example Source: https://github.com/matrix-org/matrix-appservice-node/blob/develop/_autodocs/endpoints.md Example GET request to query if an appservice can handle a specific room alias. The '#' character in the alias is URL-encoded. ```http GET /_matrix/app/v1/rooms/%23irc_general:example.com?access_token=secret123 ``` -------------------------------- ### Create a Matrix AppService Instance Source: https://github.com/matrix-org/matrix-appservice-node/blob/develop/_autodocs/00-START-HERE.md Instantiate an AppService with your homeserver token. Listen for specific event types and start the server to handle incoming requests. ```typescript const as = new AppService({ homeserverToken: "secret123" }); // Listen for events as.on("type:m.room.message", (event) => { console.log(`Message: ${event.content.body}`); }); // Start server await as.listen(8010, "localhost", 50); ``` -------------------------------- ### AppService Initialization with Homeserver Token Source: https://github.com/matrix-org/matrix-appservice-node/blob/develop/_autodocs/endpoints.md Example of initializing the AppService with a homeserver token. This token is required for authenticating with Matrix specification endpoints. ```typescript const as = new AppService({ homeserverToken: "my-secret-token-xyz" }); ``` -------------------------------- ### RegexObj Example Usage Source: https://github.com/matrix-org/matrix-appservice-node/blob/develop/_autodocs/types.md Demonstrates how to create an instance of the RegexObj interface. This is useful for defining custom namespace matching rules. ```typescript const regexObj: RegexObj = { regex: "@irc_.+", exclusive: true }; ``` -------------------------------- ### Initialize and Listen with AppService Source: https://github.com/matrix-org/matrix-appservice-node/blob/develop/_autodocs/INDEX.md Instantiate the AppService class with a homeserver token, define handlers for user queries and specific event types, and start the HTTP server on a given port and host. ```typescript const appService = new AppService({ homeserverToken: "secret123" }); appService.onUserQuery = async (userId) => { // Handle user queries }; appService.on("type:m.room.message", (event) => { console.log("Message:", event.content.body); }); appService.listen(8010, "localhost", 50); ``` -------------------------------- ### Complete AppService Registration Example Source: https://github.com/matrix-org/matrix-appservice-node/blob/develop/_autodocs/configuration.md This snippet demonstrates how to create, configure, and output a complete AppService registration file in YAML format. It covers setting required fields, optional parameters like protocols and rate limiting, and defining namespace patterns for users, rooms, and aliases. Finally, it shows how to use the generated registration details to initialize the AppService. ```typescript import { AppService, AppServiceRegistration } from "matrix-appservice"; // Create registration const reg = new AppServiceRegistration("http://localhost:8010"); // Set required fields reg.setId("irc-bridge"); reg.setHomeserverToken(AppServiceRegistration.generateToken()); reg.setAppServiceToken(AppServiceRegistration.generateToken()); reg.setSenderLocalpart("ircbot"); // Set optional fields reg.setProtocols(["irc"]); reg.setRateLimited(false); reg.pushEphemeral = true; // Add namespace patterns reg.addRegexPattern("users", "@irc_.+", true); // Exclusive: only this AS handles these users reg.addRegexPattern("users", "@bridge_.+", false); // Non-exclusive: others can match too reg.addRegexPattern("aliases", "#irc_.+", true); reg.addRegexPattern("rooms", "!irc_.+", true); // Write to file reg.outputAsYaml("registration.yaml"); // Use in AppService const appService = new AppService({ homeserverToken: reg.getHomeserverToken() }); ``` -------------------------------- ### Listen for Matrix Events and User Queries Source: https://github.com/matrix-org/matrix-appservice-node/blob/develop/README.md This snippet demonstrates how to start an application service and listen for incoming Matrix events, specifically 'm.room.message'. It also shows how to handle user queries and alias queries. ```javascript import { AppService, AppserviceHttpError } from "matrix-appservice"; // listening const as = new AppService({ homeserverToken: "abcd653bac492087d3c87" }); as.on("type:m.room.message", (event) => { // handle the incoming message }); as.onUserQuery = function(userId, callback) { // handle the incoming user query then respond console.log("RECV %s", userId); /* // if this userId cannot be created, or if some error // conditions occur, throw AppserviceHttpError exception. // The underlying appservice code will send the HTTP status, // Matrix errorcode and error message back as a response. if (userCreationOrQueryFailed) { throw new AppserviceHttpError( { errcode: "M_FORBIDDEN", error: "User query or creation failed.", }, 403, // Forbidden, or an appropriate HTTP status ) } */ callback(); }; // can also do this as a promise as.onAliasQuery = async function(alias) { console.log("RECV %s", alias); }; as.listen(8010); ``` -------------------------------- ### Get Namespaces Output Source: https://github.com/matrix-org/matrix-appservice-node/blob/develop/_autodocs/types.md Retrieves the structured namespaces configuration from a registration object. ```typescript const output = registration.getOutput(); // output.namespaces = { // users: [{ regex: "@irc_.+", exclusive: true }], // rooms: [{ regex: "!irc_.+", exclusive: true }], // aliases: [{ regex: "#irc_.+", exclusive: true }] // } ``` -------------------------------- ### Handle User Queries for User Creation Source: https://github.com/matrix-org/matrix-appservice-node/blob/develop/_autodocs/INDEX.md Implement the `onUserQuery` handler to manage user creation requests. This example shows how to validate a user ID and throw an error if creation is not permitted. ```typescript appService.onUserQuery = async (userId) => { if (!isValidUser(userId)) { throw new AppserviceHttpError( { errcode: "M_FORBIDDEN", error: "User creation not allowed" }, 403 ); } // Create user or verify existence }; ``` -------------------------------- ### setId / getId Source: https://github.com/matrix-org/matrix-appservice-node/blob/develop/_autodocs/api-reference/AppServiceRegistration.md Sets or gets the unique ID for the application service. This ID must be unique across the homeserver and should never change after initial setup. ```APIDOC ## setId / getId ### Description Sets or gets the unique appservice ID. Must be unique across the homeserver and never change. ### Method - `setId(id: string): void` - `getId(): string | null` ### Parameters #### setId - **id** (string) - Required - The unique ID for the appservice. ### Example ```typescript registration.setId("my-irc-bridge"); console.log(registration.getId()); // "my-irc-bridge" ``` ``` -------------------------------- ### AppService Event Handler Implementation Source: https://github.com/matrix-org/matrix-appservice-node/blob/develop/_autodocs/endpoints.md Example code demonstrating how to listen for and handle specific event types emitted by the appservice, including room messages and receipts. ```typescript appService.on("type:m.room.message", (event) => { console.log(`Message in ${event.room_id}: ${event.content.body}`); }); appService.on("ephemeral_type:m.receipt", (event) => { console.log("User read a message:", event.content); }); ``` -------------------------------- ### Handle User Queries in AppService Source: https://github.com/matrix-org/matrix-appservice-node/blob/develop/_autodocs/00-START-HERE.md Implement logic to handle user queries. This example shows how to check if a user exists and throw an error if not found, returning a 404 status. ```typescript // User queries as.onUserQuery = async (userId) => { if (!userExists(userId)) { throw new AppserviceHttpError( { errcode: "M_NOT_FOUND", error: "User not found" }, 404 ); } }; ``` -------------------------------- ### User Query Handler with Error Handling Source: https://github.com/matrix-org/matrix-appservice-node/blob/develop/_autodocs/api-reference/AppserviceHttpError.md Example of a user query handler that throws an AppserviceHttpError if the user is not found or disabled. ```typescript appService.onUserQuery = async (userId) => { const user = await database.getUser(userId); if (!user) { throw new AppserviceHttpError( { errcode: "M_NOT_FOUND", error: `User ${userId} not found` }, 404 ); } if (user.disabled) { throw new AppserviceHttpError( { errcode: "M_FORBIDDEN", error: "User account is disabled" }, 403 ); } // If no error is thrown, the handler succeeds }; ``` -------------------------------- ### Handle Alias Queries in AppService Source: https://github.com/matrix-org/matrix-appservice-node/blob/develop/_autodocs/00-START-HERE.md Implement logic to handle alias queries. This example demonstrates checking for alias existence and returning a 404 error if the alias is not found. ```typescript // Alias queries as.onAliasQuery = async (alias) => { if (!aliasExists(alias)) { throw new AppserviceHttpError( { errcode: "M_NOT_FOUND", error: "Alias not found" }, 404 ); } }; ``` -------------------------------- ### Set and Get Protocols Source: https://github.com/matrix-org/matrix-appservice-node/blob/develop/_autodocs/api-reference/AppServiceRegistration.md Use `setProtocols` to specify the list of third-party protocols handled by the appservice. `getProtocols` retrieves this list. ```typescript setProtocols(protocols: string[]): void getProtocols(): string[] | null ``` ```typescript registration.setProtocols(["irc", "gitter"]); console.log(registration.getProtocols()); // ["irc", "gitter"] ``` -------------------------------- ### Successful Query Response Source: https://github.com/matrix-org/matrix-appservice-node/blob/develop/_autodocs/errors.md This is an example of a successful query response, indicating that the request was processed without errors. ```http HTTP/1.1 200 OK Content-Type: application/json {} ``` -------------------------------- ### Example of Throwing AppserviceHttpError in Handler Source: https://github.com/matrix-org/matrix-appservice-node/blob/develop/_autodocs/errors.md Shows how to throw an AppserviceHttpError within an AppService handler, such as onUserQuery, to indicate a permission denial. ```typescript appService.onUserQuery = async (userId) => { if (!isAllowedUser(userId)) { throw new AppserviceHttpError( { errcode: "M_FORBIDDEN", error: "User creation not allowed" }, 403 ); } }; ``` -------------------------------- ### Alias Query Handler with Error Handling Source: https://github.com/matrix-org/matrix-appservice-node/blob/develop/_autodocs/api-reference/AppserviceHttpError.md Example of an alias query handler that throws an AppserviceHttpError if the alias is not found or the channel is not joinable. ```typescript appService.onAliasQuery = async (alias) => { const room = await irc.getRoomForAlias(alias); if (!room) { throw new AppserviceHttpError( { errcode: "M_NOT_FOUND", error: `No IRC channel for ${alias}` }, 404 ); } if (!room.joinable) { throw new AppserviceHttpError( { errcode: "M_FORBIDDEN", error: "Channel is not joinable" }, 403 ); } }; ``` -------------------------------- ### Set and Get App Service URL Source: https://github.com/matrix-org/matrix-appservice-node/blob/develop/_autodocs/api-reference/AppServiceRegistration.md Use `setAppServiceUrl` to specify the URL where the homeserver can reach this appservice. `getAppServiceUrl` retrieves this URL. ```typescript setAppServiceUrl(url: string): void getAppServiceUrl(): string | null ``` ```typescript registration.setAppServiceUrl("http://example.com:8010"); console.log(registration.getAppServiceUrl()); // "http://example.com:8010" ``` -------------------------------- ### Handling Transient Failures with Retries Source: https://github.com/matrix-org/matrix-appservice-node/blob/develop/_autodocs/errors.md This example demonstrates a strategy for handling transient database errors by implementing a retry mechanism with exponential backoff. If all retries fail, it throws an AppserviceHttpError indicating unavailability. ```typescript appService.onUserQuery = async (userId) => { let lastError; // Retry on transient failures for (let i = 0; i < 3; i++) { try { return await database.getUser(userId); } catch (error) { lastError = error; if (i < 2) { await new Promise(r => setTimeout(r, 100 * (i + 1))); } } } throw new AppserviceHttpError( { errcode: "M_UNKNOWN", error: "Database unavailable" }, 500 ); }; ``` -------------------------------- ### Set and Get Homeserver Token Source: https://github.com/matrix-org/matrix-appservice-node/blob/develop/_autodocs/api-reference/AppServiceRegistration.md Use `setHomeserverToken` to set the token the homeserver uses for authenticating requests to the appservice. `getHomeserverToken` retrieves this token. ```typescript setHomeserverToken(token: string): void getHomeserverToken(): string | null ``` ```typescript registration.setHomeserverToken(AppServiceRegistration.generateToken()); ``` -------------------------------- ### 403 Forbidden (Invalid Token) Response Example Source: https://github.com/matrix-org/matrix-appservice-node/blob/develop/_autodocs/errors.md This JSON structure represents a 403 Forbidden error due to an invalid access token. Ensure your homeserver is using the correct token and update it via setHomeserverToken() if necessary. ```json { "errcode": "M_FORBIDDEN", "error": "Bad token supplied" } ``` -------------------------------- ### Set and Get App Service Token Source: https://github.com/matrix-org/matrix-appservice-node/blob/develop/_autodocs/api-reference/AppServiceRegistration.md Use `setAppServiceToken` to set the token the appservice uses for authenticating requests to the homeserver. `getAppServiceToken` retrieves this token. ```typescript setAppServiceToken(token: string): void getAppServiceToken(): string | null ``` ```typescript registration.setAppServiceToken(AppServiceRegistration.generateToken()); ``` -------------------------------- ### Listen for Specific Event Type Source: https://github.com/matrix-org/matrix-appservice-node/blob/develop/_autodocs/api-reference/AppService.md Capture events of a particular type by prefixing the event type with 'type:'. For example, to listen for room messages, use 'type:m.room.message'. ```typescript appService.on("type:m.room.message", (event: Record) => {}) ``` ```typescript appService.on("type:m.room.message", (event) => { console.log("Message:", event.content.body); }); ``` ```typescript appService.on("type:m.room.member", (event) => { console.log("Membership change:", event.state_key); }); ``` -------------------------------- ### Distinguishing Between Alias Query Error Conditions Source: https://github.com/matrix-org/matrix-appservice-node/blob/develop/_autodocs/errors.md This example shows how to differentiate between various error conditions (syntax, not found, forbidden) when handling alias queries. It throws specific AppserviceHttpError instances with appropriate errcodes and status codes. ```typescript appService.onAliasQuery = async (alias) => { if (!alias.match(/^#.+$/)) { // Syntax error — invalid format throw new AppserviceHttpError( { errcode: "M_INVALID_PARAM", error: "Invalid alias format" }, 400 ); } const room = await findRoom(alias); if (!room) { // Semantic error — doesn't exist throw new AppserviceHttpError( { errcode: "M_NOT_FOUND", error: "Alias not found" }, 404 ); } if (room.archived) { // Policy error — exists but access denied throw new AppserviceHttpError( { errcode: "M_FORBIDDEN", error: "Room is archived" }, 403 ); } }; ``` -------------------------------- ### Set and Get Rate Limiting Status Source: https://github.com/matrix-org/matrix-appservice-node/blob/develop/_autodocs/api-reference/AppServiceRegistration.md Use `setRateLimited` to control whether the homeserver applies rate limiting to this appservice. `isRateLimited` checks the current status. The default is `true`. ```typescript setRateLimited(isRateLimited: boolean): void isRateLimited(): boolean ``` ```typescript registration.setRateLimited(false); // Disable rate limiting console.log(registration.isRateLimited()); // false ``` -------------------------------- ### Listen on a Different Port Source: https://github.com/matrix-org/matrix-appservice-node/blob/develop/_autodocs/configuration.md Change the port the AppService listens on by closing the existing listener and calling `listen()` again with the new port and host configuration. Ensure the previous listener is properly closed before starting a new one. ```typescript await appService.close(); appService.listen(9010, "0.0.0.0", 50); ``` -------------------------------- ### Enable HTTPS/TLS Configuration Source: https://github.com/matrix-org/matrix-appservice-node/blob/develop/_autodocs/configuration.md Set the MATRIX_AS_TLS_KEY and MATRIX_AS_TLS_CERT environment variables to enable HTTPS. Both files must exist, be readable, and contain valid PEM-formatted key and certificate. ```bash export MATRIX_AS_TLS_KEY=/etc/appservice/key.pem export MATRIX_AS_TLS_CERT=/etc/appservice/cert.pem node app.js ``` -------------------------------- ### Project File Organization Source: https://github.com/matrix-org/matrix-appservice-node/blob/develop/_autodocs/00-START-HERE.md Illustrates the directory structure for the matrix-appservice-node project, showing the location of key documentation files. ```markdown output/ ├── 00-START-HERE.md ← You are here ├── README.md ← Navigation guide ├── MANIFEST.md ← What's documented ├── INDEX.md ← Complete overview ├── types.md ← Type definitions ├── endpoints.md ← HTTP API spec ├── errors.md ← Error reference ├── configuration.md ← Config options └── api-reference/ ├── AppService.md ← Main class ├── AppServiceRegistration.md ← Registration └── AppserviceHttpError.md ← Errors ``` -------------------------------- ### outputAsYaml Source: https://github.com/matrix-org/matrix-appservice-node/blob/develop/_autodocs/api-reference/AppServiceRegistration.md Writes the registration to a YAML file, which is the standard format for homeserver configuration. Requires essential registration fields to be set. ```APIDOC ## outputAsYaml ### Description Writes the registration to a YAML file. This is the standard format for homeserver configuration. ### Method `outputAsYaml(filename: string): void` ### Parameters #### Path Parameters - **filename** (string) - Required - Path to write the YAML file to ### Throws Error if required fields are missing, or if file write fails. ### Example ```typescript registration.setId("my-appservice"); registration.setHomeserverToken(AppServiceRegistration.generateToken()); registration.setAppServiceToken(AppServiceRegistration.generateToken()); registration.setSenderLocalpart("bot"); registration.setAppServiceUrl("http://localhost:8010"); registration.outputAsYaml("registration.yaml"); // Writes: // id: my-appservice // url: http://localhost:8010 // hs_token: ... // as_token: ... // sender_localpart: bot ``` ``` -------------------------------- ### setAppServiceUrl / getAppServiceUrl Source: https://github.com/matrix-org/matrix-appservice-node/blob/develop/_autodocs/api-reference/AppServiceRegistration.md Sets or gets the URL where the homeserver can reach this appservice. This is crucial for establishing communication between the homeserver and the application service. ```APIDOC ## setAppServiceUrl / getAppServiceUrl ### Description Sets or gets the URL where the homeserver can reach this appservice. ### Method - `setAppServiceUrl(url: string): void` - `getAppServiceUrl(): string | null` ### Parameters #### setAppServiceUrl - **url** (string) - Required - The URL of the appservice. ### Example ```typescript registration.setAppServiceUrl("http://example.com:8010"); console.log(registration.getAppServiceUrl()); // "http://example.com:8010" ``` ``` -------------------------------- ### Common Error Codes Source: https://github.com/matrix-org/matrix-appservice-node/blob/develop/_autodocs/api-reference/AppserviceHttpError.md Provides examples for common Matrix error codes (M_FORBIDDEN, M_NOT_FOUND, M_INVALID_PARAM, M_UNKNOWN) when used with AppserviceHttpError. ```APIDOC ## Common Error Codes ### M_FORBIDDEN (403) User creation or alias resolution is forbidden due to a policy or permission constraint. ```typescript throw new AppserviceHttpError( { errcode: "M_FORBIDDEN", error: "Policy violation" }, 403 ); ``` ### M_NOT_FOUND (404) A queried user or alias does not exist. ```typescript throw new AppserviceHttpError( { errcode: "M_NOT_FOUND", error: "User not found" }, 404 ); ``` ### M_INVALID_PARAM (400) A parameter in the query is invalid or malformed. ```typescript throw new AppserviceHttpError( { errcode: "M_INVALID_PARAM", error: "Invalid user ID format" }, 400 ); ``` ### M_UNKNOWN (500) A generic error occurred. ```typescript throw new AppserviceHttpError( { errcode: "M_UNKNOWN", error: "Internal server error" }, 500 ); ``` ``` -------------------------------- ### onUserQuery Source: https://github.com/matrix-org/matrix-appservice-node/blob/develop/_autodocs/api-reference/AppService.md Override this method to handle user creation/query requests from the homeserver. ```APIDOC ## onUserQuery ### Description Override this method to handle user creation/query requests from the homeserver. ### Method Signature ```typescript onUserQuery(userId: string, callback: () => void): PromiseLike | null ``` ### Parameters #### Path Parameters * None #### Query Parameters * None #### Request Body * None ### Parameters Table | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| | userId | string | Yes | — | The user ID being queried (e.g., "@user:example.com") | | callback | function | Yes | — | Call this when the query is complete (deprecated; use Promise return instead) | ### Returns Promise that resolves when complete, or `null` if using callback. ### Throws `AppserviceHttpError` to reject a query with a specific HTTP status and Matrix error code. ### Example ```typescript // Using Promise (recommended) appService.onUserQuery = async (userId) => { console.log("Query for user:", userId); // Create the user in your backend if (!canCreateUser(userId)) { throw new AppserviceHttpError( { errcode: "M_FORBIDDEN", error: "User creation failed" }, 403 ); } }; // Using callback (deprecated) appService.onUserQuery = (userId, callback) => { console.log("Query for user:", userId); callback(); }; ``` ``` -------------------------------- ### Handle User Queries Source: https://github.com/matrix-org/matrix-appservice-node/blob/develop/_autodocs/api-reference/AppService.md Override this method to handle user creation/query requests from the homeserver. The Promise-based approach is recommended. Throw an AppserviceHttpError to reject a query. ```typescript appService.onUserQuery = async (userId) => { console.log("Query for user:", userId); // Create the user in your backend if (!canCreateUser(userId)) { throw new AppserviceHttpError( { errcode: "M_FORBIDDEN", error: "User creation failed" }, 403 ); } }; ``` ```typescript appService.onUserQuery = (userId, callback) => { console.log("Query for user:", userId); callback(); }; ``` -------------------------------- ### Generate App Service Registration File Source: https://github.com/matrix-org/matrix-appservice-node/blob/develop/README.md Use this snippet to create a registration file for your application service. It sets essential details like URLs, tokens, and user patterns. The output is saved to 'registration.yaml'. ```javascript const { AppServiceRegistration } = require("matrix-appservice"); // creating registration files const reg = new AppServiceRegistration(); reg.setAppServiceUrl("http://localhost:8010"); reg.setHomeserverToken(AppServiceRegistration.generateToken()); reg.setAppServiceToken(AppServiceRegistration.generateToken()); reg.setSenderLocalpart("example-appservice"); reg.addRegexPattern("users", "@.*", true); reg.setProtocols(["exampleservice"]); // For 3PID lookups reg.setId("example-service"); reg.outputAsYaml("registration.yaml"); ``` -------------------------------- ### Health Check Endpoint Source: https://github.com/matrix-org/matrix-appservice-node/blob/develop/_autodocs/endpoints.md A simple GET endpoint used to verify the application service is running. It is typically used by infrastructure for monitoring. ```http GET /health ``` -------------------------------- ### User Query Handler Error Response Source: https://github.com/matrix-org/matrix-appservice-node/blob/develop/_autodocs/endpoints.md Example error response when the user query handler throws an AppserviceHttpError, returning the error as-is. ```json { "errcode": "M_NOT_FOUND", "error": "User not found", "message": "M_NOT_FOUND: User not found" } ``` -------------------------------- ### AppService Constructor with Options Source: https://github.com/matrix-org/matrix-appservice-node/blob/develop/_autodocs/configuration.md Instantiate the AppService with a configuration object. The homeserverToken is required for authentication, and httpMaxSizeBytes can be set to control request body size. ```typescript import { AppService } from "matrix-appservice"; const appService = new AppService({ homeserverToken: "your-secret-token-here", httpMaxSizeBytes: 10000000 // 10 MB }); ``` -------------------------------- ### setAppServiceToken / getAppServiceToken Source: https://github.com/matrix-org/matrix-appservice-node/blob/develop/_autodocs/api-reference/AppServiceRegistration.md Sets or gets the authentication token that the application service uses when making requests to the homeserver. This token is used for appservice-to-homeserver authentication. ```APIDOC ## setAppServiceToken / getAppServiceToken ### Description Sets or gets the token the appservice uses to authenticate requests to the homeserver. ### Method - `setAppServiceToken(token: string): void` - `getAppServiceToken(): string | null` ### Parameters #### setAppServiceToken - **token** (string) - Required - The appservice authentication token. ### Example ```typescript registration.setAppServiceToken(AppServiceRegistration.generateToken()); ``` ``` -------------------------------- ### setHomeserverToken / getHomeserverToken Source: https://github.com/matrix-org/matrix-appservice-node/blob/develop/_autodocs/api-reference/AppServiceRegistration.md Sets or gets the authentication token that the homeserver uses when making requests to the application service. This token ensures secure communication. ```APIDOC ## setHomeserverToken / getHomeserverToken ### Description Sets or gets the token the homeserver uses to authenticate requests to the appservice. ### Method - `setHomeserverToken(token: string): void` - `getHomeserverToken(): string | null` ### Parameters #### setHomeserverToken - **token** (string) - Required - The homeserver authentication token. ### Example ```typescript registration.setHomeserverToken(AppServiceRegistration.generateToken()); ``` ``` -------------------------------- ### AppServiceRegistration Constructor Source: https://github.com/matrix-org/matrix-appservice-node/blob/develop/_autodocs/api-reference/AppServiceRegistration.md Creates a new application service registration with a specified homeserver URL. ```APIDOC ## AppServiceRegistration Constructor ### Description Creates a new application service registration. ### Parameters #### Path Parameters - **url** (string | null) - Required - Base URL where the homeserver can reach this appservice (e.g., "http://localhost:8010") ### Request Example ```typescript import { AppServiceRegistration } from "matrix-appservice"; const registration = new AppServiceRegistration("http://localhost:8010"); ``` ``` -------------------------------- ### AppService Constructor Source: https://github.com/matrix-org/matrix-appservice-node/blob/develop/_autodocs/api-reference/AppService.md Initializes a new instance of the AppService. This constructor is used to set up the application service to receive events and queries from a Matrix homeserver via HTTP. ```APIDOC ## AppService Constructor ### Description Creates a new application service instance with HTTP event handling. This is used to configure the connection and communication parameters between the application service and the Matrix homeserver. ### Method ```typescript constructor(config: { homeserverToken: string; httpMaxSizeBytes?: number }) ``` ### Parameters #### Config Object - **config** (object) - Required - Configuration object for the AppService. - **homeserverToken** (string) - Required - The token the homeserver uses to authenticate requests to this service. - **httpMaxSizeBytes** (number) - Optional - The maximum size in bytes for incoming HTTP requests. Defaults to 5000000 (5 MB). ### Throws - Error if `homeserverToken` is not provided. ### Example ```typescript import { AppService } from "matrix-appservice"; const appService = new AppService({ homeserverToken: "your-secret-token-here", httpMaxSizeBytes: 10000000 // 10 MB }); ``` ``` -------------------------------- ### Create and Output AppService Registration Source: https://github.com/matrix-org/matrix-appservice-node/blob/develop/_autodocs/INDEX.md Create an AppServiceRegistration instance, set essential identifiers and tokens, define namespace patterns for users and aliases, and output the configuration to a YAML file. ```typescript const reg = new AppServiceRegistration("http://localhost:8010"); reg.setId("my-appservice"); reg.setHomeserverToken(AppServiceRegistration.generateToken()); reg.setAppServiceToken(AppServiceRegistration.generateToken()); reg.setSenderLocalpart("bot"); reg.addRegexPattern("users", "@bot_.+", true); reg.addRegexPattern("aliases", "#bot_.+", true); reg.outputAsYaml("registration.yaml"); ``` -------------------------------- ### Close AppService Server Source: https://github.com/matrix-org/matrix-appservice-node/blob/develop/_autodocs/api-reference/AppService.md Closes the HTTP server. Returns a Promise that resolves when the server is fully closed. Ensure the server has been started before calling this method. ```typescript await appService.close(); ``` -------------------------------- ### Set and Get Sender Localpart Source: https://github.com/matrix-org/matrix-appservice-node/blob/develop/_autodocs/api-reference/AppServiceRegistration.md Use `setSenderLocalpart` to define the local part of the appservice's user ID. `getSenderLocalpart` retrieves this local part. ```typescript setSenderLocalpart(localpart: string): void getSenderLocalpart(): string | null ``` ```typescript registration.setSenderLocalpart("bot"); console.log(registration.getSenderLocalpart()); // "bot" ``` -------------------------------- ### Generate AppService Registration File Source: https://github.com/matrix-org/matrix-appservice-node/blob/develop/_autodocs/00-START-HERE.md Create a registration file for your AppService. This includes setting IDs, tokens, sender localpart, and user ID regex patterns. The output can be saved as a YAML file. ```typescript const reg = new AppServiceRegistration("http://localhost:8010"); reg.setId("my-bot"); reg.setHomeserverToken(AppServiceRegistration.generateToken()); reg.setAppServiceToken(AppServiceRegistration.generateToken()); reg.setSenderLocalpart("bot"); reg.addRegexPattern("users", "@bot_.+", true); reg.outputAsYaml("registration.yaml"); ``` -------------------------------- ### Create New AppServiceRegistration Source: https://github.com/matrix-org/matrix-appservice-node/blob/develop/_autodocs/api-reference/AppServiceRegistration.md Instantiates a new AppServiceRegistration object. Provide the base URL for your homeserver to reach the appservice. ```typescript import { AppServiceRegistration } from "matrix-appservice"; const registration = new AppServiceRegistration("http://localhost:8010"); ``` -------------------------------- ### expressApp Source: https://github.com/matrix-org/matrix-appservice-node/blob/develop/_autodocs/api-reference/AppService.md Returns the underlying Express application instance for adding custom routes. ```APIDOC ## expressApp ### Description Returns the underlying Express application instance for adding custom routes. ### Method Signature ```typescript get expressApp(): Application ``` ### Parameters * None ### Returns Express `Application` instance. ### Example ```typescript // Add a custom health check endpoint appService.expressApp.get("/custom-health", (req, res) => { res.json({ status: "ok" }); }); ``` ``` -------------------------------- ### Room Alias Query Handler Error Response Source: https://github.com/matrix-org/matrix-appservice-node/blob/develop/_autodocs/endpoints.md Example error response when the room alias query handler throws an error, returning the error message. ```json { "errcode": "M_NOT_FOUND", "error": "Alias not found" } ``` -------------------------------- ### Create AppService Registration Source: https://github.com/matrix-org/matrix-appservice-node/blob/develop/_autodocs/INDEX.md Generate a registration file for the appservice. Ensure all required tokens and details are set. ```typescript const reg = new AppServiceRegistration("http://localhost:8010"); reg.setId("id"); reg.setHomeserverToken(token); reg.setAppServiceToken(token); reg.setSenderLocalpart("bot"); reg.outputAsYaml("reg.yaml"); ``` -------------------------------- ### Set and Get App Service ID Source: https://github.com/matrix-org/matrix-appservice-node/blob/develop/_autodocs/api-reference/AppServiceRegistration.md Use `setId` to set a unique appservice ID, which must never change. `getId` retrieves the current ID. ```typescript setId(id: string): void getId(): string | null ``` ```typescript registration.setId("my-irc-bridge"); console.log(registration.getId()); // "my-irc-bridge" ``` -------------------------------- ### Configure Logging Source: https://github.com/matrix-org/matrix-appservice-node/blob/develop/_autodocs/configuration.md Set up custom logging by subscribing to the `http-log` event emitted by the AppService. Logged lines automatically redact access tokens, enhancing security. ```typescript appService.on("http-log", (line) => { // Send to your logging system logger.info(line); }); ``` -------------------------------- ### Import Core AppService Modules Source: https://github.com/matrix-org/matrix-appservice-node/blob/develop/_autodocs/INDEX.md Import the main modules required for building a Matrix appservice. ```typescript import { AppService, AppServiceRegistration, AppserviceHttpError } from "matrix-appservice"; ``` -------------------------------- ### setSenderLocalpart / getSenderLocalpart Source: https://github.com/matrix-org/matrix-appservice-node/blob/develop/_autodocs/api-reference/AppServiceRegistration.md Sets or gets the local part of the application service's own user ID. This is the part before the '@' symbol in a Matrix ID (e.g., 'bot' in '@bot:example.com'). ```APIDOC ## setSenderLocalpart / getSenderLocalpart ### Description Sets or gets the local part of the appservice's own user ID (e.g., "bot" in "@bot:example.com"). ### Method - `setSenderLocalpart(localpart: string): void` - `getSenderLocalpart(): string | null` ### Parameters #### setSenderLocalpart - **localpart** (string) - Required - The local part of the appservice's user ID. ### Example ```typescript registration.setSenderLocalpart("bot"); console.log(registration.getSenderLocalpart()); // "bot" ``` ``` -------------------------------- ### Write AppServiceRegistration to YAML File Source: https://github.com/matrix-org/matrix-appservice-node/blob/develop/_autodocs/api-reference/AppServiceRegistration.md Writes the registration to a YAML file, the standard format for homeserver configuration. Ensure all required fields are set before calling this method. ```typescript registration.setId("my-appservice"); registration.setHomeserverToken(AppServiceRegistration.generateToken()); registration.setAppServiceToken(AppServiceRegistration.generateToken()); registration.setSenderLocalpart("bot"); registration.setAppServiceUrl("http://localhost:8010"); registration.outputAsYaml("registration.yaml"); // Writes: // id: my-appservice // url: http://localhost:8010 // hs_token: ... // as_token: ... // sender_localpart: bot ``` -------------------------------- ### Listen for Any Event Source: https://github.com/matrix-org/matrix-appservice-node/blob/develop/_autodocs/api-reference/AppService.md Use this to capture all events pushed to the appservice from the homeserver. The event object follows the Matrix application service transaction format. ```typescript appService.on("event", (event: Record) => {}) ``` ```typescript appService.on("event", (event) => { console.log("Event type:", event.type); console.log("Event ID:", event.event_id); console.log("Room ID:", event.room_id); }); ``` -------------------------------- ### Listen for Specific Ephemeral Event Type Source: https://github.com/matrix-org/matrix-appservice-node/blob/develop/_autodocs/api-reference/AppService.md Capture specific types of ephemeral events by prefixing the event type with 'ephemeral_type:'. For example, use 'ephemeral_type:m.receipt' for receipt events. ```typescript appService.on("ephemeral_type:m.receipt", (event: Record) => {}) ``` ```typescript appService.on("ephemeral_type:m.receipt", (event) => { console.log("Receipt event:", event); }); ``` ```typescript appService.on("ephemeral_type:m.typing", (event) => { console.log("Typing notification:", event); }); ``` -------------------------------- ### getOutput Source: https://github.com/matrix-org/matrix-appservice-node/blob/develop/_autodocs/api-reference/AppServiceRegistration.md Returns the registration as a serializable object, typically for writing to YAML. Includes core fields and optional protocol/namespace configurations. ```APIDOC ## getOutput ### Description Returns the registration as a serializable object (typically for writing to YAML). ### Method `getOutput(): AppServiceOutput` ### Returns `AppServiceOutput` object with keys: `id`, `url`, `hs_token`, `as_token`, `sender_localpart`, plus optional `protocols`, `namespaces`, `rate_limited`, and `de.sorunome.msc2409.push_ephemeral`. ### Throws Error if required fields (`id`, `hs_token`, `as_token`, `sender_localpart`) are missing. ### Example ```typescript const output = registration.getOutput(); console.log(JSON.stringify(output, null, 2)); // { // "id": "my-service", // "url": "http://localhost:8010", // "hs_token": "...", // "as_token": "...", // "sender_localpart": "bot" // } ``` ``` -------------------------------- ### AppService Constructor Source: https://github.com/matrix-org/matrix-appservice-node/blob/develop/_autodocs/api-reference/AppService.md Initializes a new AppService instance. Requires a homeserverToken for authentication and optionally accepts httpMaxSizeBytes to limit incoming request sizes. ```typescript import { AppService } from "matrix-appservice"; const appService = new AppService({ homeserverToken: "your-secret-token-here", httpMaxSizeBytes: 10000000 // 10 MB }); ``` -------------------------------- ### AppServiceRegistration Class Methods Source: https://github.com/matrix-org/matrix-appservice-node/blob/develop/_autodocs/INDEX.md Methods for managing and configuring the appservice registration details. ```APIDOC ## AppServiceRegistration Class ### Description Manages registration configuration for the appservice. ### Methods - `setId(id)`: Set unique appservice identifier. - `setAppServiceUrl(url)`: Set the appservice URL. - `setHomeserverToken(token)`: Set homeserver authentication token. - `setAppServiceToken(token)`: Set appservice authentication token. - `setSenderLocalpart(localpart)`: Set bot user local part. - `setProtocols(protocols)`: Set third-party protocols. - `addRegexPattern(type, regex, exclusive)`: Register namespace patterns. - `outputAsYaml(filename)`: Write registration to YAML file. ### Static Methods - `generateToken()`: Generate a cryptographically-strong token. - `fromObject(obj)`: Load registration from object. ### Example ```typescript const reg = new AppServiceRegistration("http://localhost:8010"); reg.setId("my-appservice"); reg.setHomeserverToken(AppServiceRegistration.generateToken()); reg.setAppServiceToken(AppServiceRegistration.generateToken()); reg.setSenderLocalpart("bot"); reg.addRegexPattern("users", "@bot_.+", true); reg.addRegexPattern("aliases", "#bot_.+", true); reg.outputAsYaml("registration.yaml"); ``` ``` -------------------------------- ### Get AppServiceRegistration as Serializable Object Source: https://github.com/matrix-org/matrix-appservice-node/blob/develop/_autodocs/api-reference/AppServiceRegistration.md Returns the registration as a serializable object, typically for writing to YAML. Ensure required fields like id, hs_token, as_token, and sender_localpart are set before calling. ```typescript const output = registration.getOutput(); console.log(JSON.stringify(output, null, 2)); // { // "id": "my-service", // "url": "http://localhost:8010", // "hs_token": "...", // "as_token": "...", // "sender_localpart": "bot" // } ``` -------------------------------- ### Handle User Queries Source: https://github.com/matrix-org/matrix-appservice-node/blob/develop/_autodocs/INDEX.md Implement logic to respond to user queries asynchronously. This function should return data or throw an error. ```typescript as.onUserQuery = async (userId) => { // Return or throw error }; ``` -------------------------------- ### Listen to Ephemeral Events Source: https://github.com/matrix-org/matrix-appservice-node/blob/develop/_autodocs/INDEX.md Enable ephemeral event listening in your registration and use the `appService.on` method to handle events like receipts and typing notifications. Ensure `reg.pushEphemeral = true;` is set in your registration. ```typescript // Enable in registration reg.pushEphemeral = true; // Listen for receipts appService.on("ephemeral_type:m.receipt", (event) => { console.log("User read a message"); }); // Listen for typing appService.on("ephemeral_type:m.typing", (event) => { console.log("User is typing"); }); ``` -------------------------------- ### 500 Internal Server Error (Unhandled Exception) Response Example Source: https://github.com/matrix-org/matrix-appservice-node/blob/develop/_autodocs/errors.md This JSON structure indicates a 500 Internal Server Error caused by an unhandled exception in a handler. The error message will be populated from the exception. ```json { "errcode": "M_UNKNOWN", "message": "" } ``` -------------------------------- ### Define Namespaces Configuration Source: https://github.com/matrix-org/matrix-appservice-node/blob/develop/_autodocs/types.md Defines the structure for organizing user, room, and alias ID patterns in application service registrations. ```typescript interface Namespaces { users?: RegexObj[]; // User ID patterns rooms?: RegexObj[]; // Room ID patterns aliases?: RegexObj[]; // Room alias patterns } ``` -------------------------------- ### Enable HTTPS for AppService Source: https://github.com/matrix-org/matrix-appservice-node/blob/develop/_autodocs/INDEX.md Configure HTTPS for your AppService by setting the `MATRIX_AS_TLS_KEY` and `MATRIX_AS_TLS_CERT` environment variables before running your Node.js application. ```bash export MATRIX_AS_TLS_KEY=/etc/appservice/key.pem export MATRIX_AS_TLS_CERT=/etc/appservice/cert.pem node app.js ```