Fastwa Documentation

website·Indexed 31 days ago

https://docs.fastwa.org/

An open source framework for building applications with WhatsApp integration. Features include controllers for message handling, event listening with @On() decorators, pipes for data transformation, guards for authorization, and a schedule module via @fastwa/schedule.

Tokens
3.5K
Snippets
23
Records
31
Agent score
49%

What's inside Fastwa

  1. Overview of the Fastwa framework

    Fastwa is an open-source framework designed for building efficient and scalable WhatsApp applications. It is built on top of the Baileys library but maintains compatibility with a wide range of other libraries, enabling the use of various third-party plugins. A key feature of Fastwa is the ability to use TypeScript decorators on Baileys, which simplifies the codebase and improves overall readability.
  2. Implement data transformation and validation using Pipes

    A pipe in Fastwa is a class that implements the PipeTransform interface. Pipes are used for two primary purposes:

    1. Transformation: Converting input data into a desired format (e.g., converting a string to an integer).
    2. Validation: Evaluating input data; if the data is valid, it passes through unchanged; otherwise, the pipe throws an exception.
  3. Connect a FastWA application to WhatsApp

    To connect your application to WhatsApp, use the WAFactory.create method to initialize the app and then call app.listen() to start the connection process. You can enable printQrInTerminal to display the QR code for authentication directly in the console.
    import { WAFactory } from '@fastwa/core';
    
    async function connectToWhatsapp() {
      const app = await WAFactory.create(AppModule, {
        printQrInTerminal: true
      });
    
      await app.listen();
    }
    
    connectToWhatsapp();
  4. Persist WhatsApp sessions using the file system

    To avoid scanning the QR code on every restart, use useMultiFileAuthState from @whiskeysockets/baileys. This function saves the authentication state to a specified local folder. Pass the resulting state and saveCreds function into the WAFactory.create configuration.
    import { 
      fetchLatestBaileysVersion, 
      useMultiFileAuthState 
    } from '@whiskeysockets/baileys';
    import { WAFactory } from '@fastwa/core';
    
    async function connectToWhatsapp() {
      // Save auth state in the './sessions' folder
      const { state, saveCreds } = await useMultiFileAuthState('./sessions');
    
      const app = await WAFactory.create(AppModule, {
        auth: state,
        printQRInTerminal: true,
        saveCreds
      });
    
      await app.listen();
    }
    
    connectToWhatsapp();
  5. Send media messages (images, video, stickers)

    To send media, return an object specifying the media type (e.g., image) and the source. FastWA supports buffers, local URLs, and remote URLs. When using a URL, the media is encrypted as a readable stream rather than loading the entire buffer into memory, improving efficiency.
    return {
      image: { url: './cat.jpeg' },
      caption: "Look this cat",
    }
  6. Create a basic command controller

    The most common way to respond to a message in FastWA is by using a controller method decorated with @Command. Returning a value from this method acknowledges the interaction and sends that value as a response message.
    @Controller()
    export class AppController {
      @Command('ping')
      ping() {
        return 'Pong!';
      }
    }
  7. Format WhatsApp messages using @fastwa/builders

    The @fastwa/builders package provides utility functions to format strings into the various styles supported by WhatsApp. These functions wrap the provided string in the specific characters required by the WhatsApp protocol to render bold, italic, strikethrough, or monospace text.
    import { bold, italic, strikethrough, monospace } from '@fastwa/builders';
    
    const message = bold('This is bold'); // Returns *This is bold*
    const slanted = italic('This is italic'); // Returns _This is italic_
    const crossed = strikethrough('This is crossed'); // Returns ~This is crossed~
    const code = monospace('This is monospace'); // Returns ```This is monospace```
  8. Create a message controller in Fastwa

    Controllers in Fastwa handle incoming messages and return replies. They are implemented using classes and decorators, which provide the necessary metadata for Fastwa to map interactions to the correct controller.

    There are two ways to handle replies:

    1. Standard (Recommended): Return a JavaScript primitive (e.g., a string) directly from the handler method. Fastwa automatically sends this value as the reply.
    2. Platform-specific: Use the native socket instance to call specific reply methods (e.g., sock.sendMessage()). This is useful for advanced interactions that require native API access.
  9. Mark messages as read

    In multi-device environments, you must mark specific message keys as read individually rather than marking an entire chat. Use sock.readMessages() and pass an array of message keys. Each key must include the message id, the remoteJid, and the participant.
    const key = {
      id: 'AHASHH123123AHGA',
      remoteJid: '1234-123@g.us',
      participant: '912121232@s.whatsapp.net'
    }
    
    // Pass multiple keys to read multiple messages
    await sock.readMessages([key])
  10. Create commands with dynamic segments

    Dynamic commands allow you to handle variable data in a command path when the exact segment names are not known ahead of time. To define a dynamic segment, prefix the parameter name with a colon (e.g., :id or :name). These segments act as variables that are replaced with actual values at runtime based on the user's message.
    // Example of a command with a dynamic segment ':name'
    @Command('/hello :name')
    async getHello(@Args('name') name: string) {
      return `Hello, ${name}.`;
    }
  11. Implement custom database-backed session storage

    For better scalability and security, you can implement a custom auth state handler that stores session data in a database instead of JSON files. This requires creating a state object with get and set methods that interact with your database or ORM, and a saveCreds function to persist the main credentials.
    import { initAuthCreds } from "@whiskeysockets/baileys"
    
    export async function useDatabaseAuthState() {
      const creds = initAuthCreds();
    
      const state = {
        creds,
        keys: {
          async get<T extends keyof SignalDataTypeMap>(types: T, ids: string[]) {
            // TODO: Implement database retrieval (e.g., credsRepository.findOne())
            return credsRepository.findOne();
          },
          async set(data: SignalDataSet) {
            // TODO: Implement database update/insert (e.g., credsRepository.upsert())
            credsRepository.upsert();
          }
        }
      }
    
      const saveCreds = () => credsRepository.save(creds)
    
      return {
        state,
        saveCreds
      }
    }
  12. Install Fastwa system requirements

    To run Fastwa, your system must meet the following requirements: Node.js version 16.8 or later. Supported operating systems include macOS, Windows (including WSL), and Linux.