Cara menggunakan javascript wa

Kali ini saya akan share cara membuat WhatsApp API dengan NodeJs tanpa scraping ke web. ada apa. com dan tanpa harus daftar terlebih dahulu ke whatsapp business dan dapatkan kredensial api dan tunggu sangat lama untuk diterima

Nah, ada satu library atau package yang sangat berguna dan memudahkan hidup kita tanpa harus repot mengorek web itu sendiri. Apa itu?

Apa itu menggores?

Pengikisan web adalah proses mengekstraksi data dari situs web. Salah satu contoh pengikisan web adalah menyalin daftar kontak dari direktori web

Pengikisan Web. Panduan dan Teknik

Bagi Anda pemilik toko online, mungkin banyak sekali data yang perlu Anda kumpulkan untuk kebutuhan bisnis Anda...

www. dewa web. com

Oke langsung saja kita mulai

Instalasi

Buat proyek baru dengan perintah
$ mkdir whatsapp-api && cd whatsapp-api
$npm init -y
$ sentuh server. js

setelah berhasil membuat project dan membuat file server. js, lalu instal paket yang kami sebutkan di atas

$ benang tambahkan whatsapp-web. js

Proses instalasi akan memakan waktu lama karena paket ini berisi dalang yang mendownload chromium

pedroslopez/whatsapp-web. js

Klien API WhatsApp yang terhubung melalui aplikasi browser Web WhatsApp Ini menggunakan Puppeteer untuk menjalankan contoh nyata dari…

github. com

CATATAN. Saya tidak dapat menjamin Anda tidak akan diblokir dengan menggunakan metode ini, meskipun cara ini berhasil untuk saya. WhatsApp tidak mengizinkan bot atau klien tidak resmi di platform mereka, jadi ini tidak boleh dianggap sepenuhnya aman

lari temanku, lari...

kami suka benang…

Mulailah membuat

Kami memerlukan beberapa dependensi lagi untuk menjalankan aplikasi kami

$ benang tambahkan soket ekspres. io kode qr http

Pada berkas paket. json isi bagian script dengan start, seperti kode berikut

Kemudian, isi server. js dengan kode berikut

server. js

Buat file indeks. html
$ sentuh indeks. html
Kemudian isi kode berikut

indeks. htmlJalankan kode

Jalankan aplikasi kita dengan perintah
$ benang mulai

mulai aplikasi

Selanjutnya buka http. // localhost. 8000 dan PINDAI Kode QR yang muncul

indeks. htmlPengujian mengirim pesan

Kita tes dulu, dengan mengirim pesan ke nomor yang baru kita scan. KARENA KAMI TULIS PESANAN JIKA PESAN SAMA DENGAN. ping, lalu kirim. ping oke

jika berhasil akan ada balasan otomatis yaitu pong

Pengujian API di tukang pos

Selanjutnya kita akan menguji API Endpoint yang telah kita buat di postman

http. // localhost. 8000/kirim

tukang pos

Jika berhasil maka akan muncul objek respon, dengan pesan “Pesan terkirim”

Perlu DIPERHATIKAN bahwa angka yang dimasukkan harus dimulai dengan 62, dan c ditambahkan di belakangnya. kita

Selanjutnya

Kemudian kita tinggal mengembangkan APInya lagi, misalnya mengirim gambar, file, dll. Jelajahi sendiri paket whatsapp-web Anda. js di sini

Baileys tidak memerlukan Selenium atau browser lain untuk berinteraksi dengan WhatsApp Web, ia melakukannya secara langsung menggunakan WebSocket. Tidak menjalankan Selenium dan Chromium menghemat setengah gig ram. /

Baileys mendukung interaksi dengan versi multi-perangkat dan web WhatsApp

Terima kasih kepada @pokeraujo yang telah menuliskan pengamatannya tentang cara kerja WhatsApp Multi-Device. Terima kasih juga kepada @Sigalor yang telah menulis pengamatannya tentang cara kerja WhatsApp Web dan terima kasih kepada @Rhymen atas implementasinya

Baileys aman untuk tipe, dapat diperluas, dan mudah digunakan. Jika Anda memerlukan lebih banyak fungsionalitas daripada yang disediakan, sangat mudah untuk menulis ekstensi. Lebih lanjut tentang ini

Jika Anda tertarik untuk membuat bot WhatsApp, Anda mungkin ingin melihat WhatsAppInfoBot dan bot sebenarnya yang dibuat dengannya, Messcat

Baca dokumennya di sini Bergabunglah dengan Perselisihan di sini

Contoh

Periksa & jalankan contoh. ts untuk melihat contoh penggunaan perpustakaan. Skrip mencakup kasus penggunaan yang paling umum. Untuk menjalankan skrip contoh, unduh atau klon repo lalu ketik yang berikut di terminal

  1. const conn = makeWASocket({
        ...otherOpts,
        // can use Windows, Ubuntu here too
        browser: Browsers.macOS('Desktop'),
        syncFullHistory: true
    })
    _3
  2. const conn = makeWASocket({
        ...otherOpts,
        // can use Windows, Ubuntu here too
        browser: Browsers.macOS('Desktop'),
        syncFullHistory: true
    })
    _4
  3. const conn = makeWASocket({
        ...otherOpts,
        // can use Windows, Ubuntu here too
        browser: Browsers.macOS('Desktop'),
        syncFullHistory: true
    })
    5

Install

Gunakan versi stabil

yarn add @adiwajshing/baileys

Gunakan versi edge (tidak ada jaminan stabilitas, tetapi perbaikan + fitur terbaru)

yarn add github:adiwajshing/baileys
_

Kemudian impor kode Anda menggunakan

import makeWASocket from '@adiwajshing/baileys'

Tes Satuan

MELAKUKAN

Menghubungkan

import makeWASocket, { DisconnectReason } from '@adiwajshing/baileys'
import { Boom } from '@hapi/boom'

async function connectToWhatsApp () {
    const sock = makeWASocket({
        // can provide additional config here
        printQRInTerminal: true
    })
    sock.ev.on('connection.update', (update) => {
        const { connection, lastDisconnect } = update
        if(connection === 'close') {
            const shouldReconnect = (lastDisconnect.error as Boom)?.output?.statusCode !== DisconnectReason.loggedOut
            console.log('connection closed due to ', lastDisconnect.error, ', reconnecting ', shouldReconnect)
            // reconnect if not logged out
            if(shouldReconnect) {
                connectToWhatsApp()
            }
        } else if(connection === 'open') {
            console.log('opened connection')
        }
    })
    sock.ev.on('messages.upsert', m => {
        console.log(JSON.stringify(m, undefined, 2))

        console.log('replying to', m.messages[0].key.remoteJid)
        await sock.sendMessage(m.messages[0].key.remoteJid!, { text: 'Hello there!' })
    })
}
// run in main file
connectToWhatsApp()
_

Jika koneksi berhasil, Anda akan melihat kode QR tercetak di layar terminal Anda, pindai dengan WhatsApp di ponsel Anda dan Anda akan masuk

Catatan. instal

const conn = makeWASocket({
    ...otherOpts,
    // can use Windows, Ubuntu here too
    browser: Browsers.macOS('Desktop'),
    syncFullHistory: true
})
6 menggunakan
const conn = makeWASocket({
    ...otherOpts,
    // can use Windows, Ubuntu here too
    browser: Browsers.macOS('Desktop'),
    syncFullHistory: true
})
7 untuk mencetak otomatis QR ke terminal

Catatan. kode untuk mendukung WA Web versi lawas (pra multi-perangkat) telah dihapus di v5. Hanya koneksi multi-perangkat standar yang sekarang didukung. Ini dilakukan karena WA tampaknya benar-benar kehilangan dukungan untuk versi lawas

Konfigurasi Koneksi

Anda dapat mengonfigurasi koneksi dengan mengirimkan objek

const conn = makeWASocket({
    ...otherOpts,
    // can use Windows, Ubuntu here too
    browser: Browsers.macOS('Desktop'),
    syncFullHistory: true
})
8

Keseluruhan struktur

const conn = makeWASocket({
    ...otherOpts,
    // can use Windows, Ubuntu here too
    browser: Browsers.macOS('Desktop'),
    syncFullHistory: true
})
_8 disebutkan di sini dengan nilai default

type SocketConfig = {
    /** the WS url to connect to WA */
    waWebSocketUrl: string | URL
    /** Fails the connection if the socket times out in this interval */
	connectTimeoutMs: number
    /** Default timeout for queries, undefined for no timeout */
    defaultQueryTimeoutMs: number | undefined
    /** ping-pong interval for WS connection */
    keepAliveIntervalMs: number
    /** proxy agent */
	agent?: Agent
    /** pino logger */
	logger: Logger
    /** version to connect with */
    version: WAVersion
    /** override browser config */
	browser: WABrowserDescription
	/** agent used for fetch requests -- uploading/downloading media */
	fetchAgent?: Agent
    /** should the QR be printed in the terminal */
    printQRInTerminal: boolean
    /** should events be emitted for actions done by this socket connection */
    emitOwnEvents: boolean
    /** provide a cache to store media, so does not have to be re-uploaded */
    mediaCache?: NodeCache
    /** custom upload hosts to upload media to */
    customUploadHosts: MediaConnInfo['hosts']
    /** time to wait between sending new retry requests */
    retryRequestDelayMs: number
    /** time to wait for the generation of the next QR in ms */
    qrTimeout?: number;
    /** provide an auth state object to maintain the auth state */
    auth: AuthenticationState
    /** manage history processing with this control; by default will sync up everything */
    shouldSyncHistoryMessage: (msg: proto.Message.IHistorySyncNotification) => boolean
    /** transaction capability options for SignalKeyStore */
    transactionOpts: TransactionCapabilityOptions
    /** provide a cache to store a user's device list */
    userDevicesCache?: NodeCache
    /** marks the client as online whenever the socket successfully connects */
    markOnlineOnConnect: boolean
    /**
     * map to store the retry counts for failed messages;
     * used to determine whether to retry a message or not */
    msgRetryCounterMap?: MessageRetryMap
    /** width for link preview images */
    linkPreviewImageThumbnailWidth: number
    /** Should Baileys ask the phone for full history, will be received async */
    syncFullHistory: boolean
    /** Should baileys fire init queries automatically, default true */
    fireInitQueries: boolean
    /**
     * generate a high quality link preview,
     * entails uploading the jpegThumbnail to WA
     * */
    generateHighQualityLinkPreview: boolean

    /** options for axios */
    options: AxiosRequestConfig<any>
    /**
     * fetch a message from your store
     * implement this so that messages failed to send (solves the "this message can take a while" issue) can be retried
     * */
    getMessage: (key: proto.IMessageKey) => Promise<proto.IMessage | undefined>
}

Meniru aplikasi Desktop, bukan web

  1. Baileys, secara default, mengemulasi sesi web chrome
  2. Jika Anda ingin meniru koneksi desktop (dan menerima lebih banyak riwayat pesan), tambahkan ini ke konfigurasi Socket Anda

    const conn = makeWASocket({
        ...otherOpts,
        // can use Windows, Ubuntu here too
        browser: Browsers.macOS('Desktop'),
        syncFullHistory: true
    })

Menyimpan & Memulihkan Sesi

Anda jelas tidak ingin terus memindai kode QR setiap kali ingin terhubung

Jadi, Anda dapat memuat kredensial untuk masuk kembali

import makeWASocket, { BufferJSON, useMultiFileAuthState } from '@adiwajshing/baileys'
import * as fs from 'fs'

// utility function to help save the auth state in a single folder
// this function serves as a good guide to help write auth & key states for SQL/no-SQL databases, which I would recommend in any production grade system
const { state, saveCreds } = await useMultiFileAuthState('auth_info_baileys')
// will use the given state to connect
// so if valid credentials are available -- it'll connect without QR
const conn = makeWASocket({ auth: state }) 
// this will be called as soon as the credentials are updated
conn.ev.on ('creds.update', saveCreds)

Catatan. Saat pesan diterima/dikirim, karena sesi sinyal perlu diperbarui, kunci autentikasi (

import makeWASocket, { BufferJSON, useMultiFileAuthState } from '@adiwajshing/baileys'
import * as fs from 'fs'

// utility function to help save the auth state in a single folder
// this function serves as a good guide to help write auth & key states for SQL/no-SQL databases, which I would recommend in any production grade system
const { state, saveCreds } = await useMultiFileAuthState('auth_info_baileys')
// will use the given state to connect
// so if valid credentials are available -- it'll connect without QR
const conn = makeWASocket({ auth: state }) 
// this will be called as soon as the credentials are updated
conn.ev.on ('creds.update', saveCreds)
0) akan diperbarui. Setiap kali itu terjadi, Anda harus menyimpan kunci yang diperbarui (
import makeWASocket, { BufferJSON, useMultiFileAuthState } from '@adiwajshing/baileys'
import * as fs from 'fs'

// utility function to help save the auth state in a single folder
// this function serves as a good guide to help write auth & key states for SQL/no-SQL databases, which I would recommend in any production grade system
const { state, saveCreds } = await useMultiFileAuthState('auth_info_baileys')
// will use the given state to connect
// so if valid credentials are available -- it'll connect without QR
const conn = makeWASocket({ auth: state }) 
// this will be called as soon as the credentials are updated
conn.ev.on ('creds.update', saveCreds)
1 disebut). Tidak melakukannya akan mencegah pesan Anda mencapai penerima & menyebabkan konsekuensi tak terduga lainnya. Fungsi
import makeWASocket, { BufferJSON, useMultiFileAuthState } from '@adiwajshing/baileys'
import * as fs from 'fs'

// utility function to help save the auth state in a single folder
// this function serves as a good guide to help write auth & key states for SQL/no-SQL databases, which I would recommend in any production grade system
const { state, saveCreds } = await useMultiFileAuthState('auth_info_baileys')
// will use the given state to connect
// so if valid credentials are available -- it'll connect without QR
const conn = makeWASocket({ auth: state }) 
// this will be called as soon as the credentials are updated
conn.ev.on ('creds.update', saveCreds)
_2 secara otomatis menanganinya, tetapi untuk penerapan serius lainnya -- Anda harus sangat berhati-hati dengan manajemen status kunci

Mendengarkan Pembaruan Koneksi

Baileys sekarang mengaktifkan

import makeWASocket, { BufferJSON, useMultiFileAuthState } from '@adiwajshing/baileys'
import * as fs from 'fs'

// utility function to help save the auth state in a single folder
// this function serves as a good guide to help write auth & key states for SQL/no-SQL databases, which I would recommend in any production grade system
const { state, saveCreds } = await useMultiFileAuthState('auth_info_baileys')
// will use the given state to connect
// so if valid credentials are available -- it'll connect without QR
const conn = makeWASocket({ auth: state }) 
// this will be called as soon as the credentials are updated
conn.ev.on ('creds.update', saveCreds)
_3 untuk memberi tahu Anda bahwa ada sesuatu yang diperbarui dalam koneksi tersebut. Data ini memiliki struktur sebagai berikut

type ConnectionState = {
	/** connection is now open, connecting or closed */
	connection: WAConnectionState
	/** the error that caused the connection to close */
	lastDisconnect?: {
		error: Error
		date: Date
	}
	/** is this a new login */
	isNewLogin?: boolean
	/** the current QR code */
	qr?: string
	/** has the device received all pending notifications while it was offline */
	receivedPendingNotifications?: boolean 
}

Catatan. ini juga menawarkan pembaruan apa pun pada QR

Menangani Acara

Baileys menggunakan sintaks EventEmitter untuk acara. Semuanya diketik dengan baik, jadi Anda seharusnya tidak memiliki masalah dengan editor Intellisense seperti VS Code

Acara diketik seperti yang disebutkan di sini

export type BaileysEventMap = {
    /** connection state has been updated -- WS closed, opened, connecting etc. */
	'connection.update': Partial<ConnectionState>
    /** credentials updated -- some metadata, keys or something */
    'creds.update': Partial<AuthenticationCreds>
    /** history sync, everything is reverse chronologically sorted */
    'messaging-history.set': {
        chats: Chat[]
        contacts: Contact[]
        messages: WAMessage[]
        isLatest: boolean
    }
    /** upsert chats */
    'chats.upsert': Chat[]
    /** update the given chats */
    'chats.update': Partial<Chat>[]
    /** delete chats with given ID */
    'chats.delete': string[]
    /** presence of contact in a chat updated */
    'presence.update': { id: string, presences: { [participant: string]: PresenceData } }

    'contacts.upsert': Contact[]
    'contacts.update': Partial<Contact>[]

    'messages.delete': { keys: WAMessageKey[] } | { jid: string, all: true }
    'messages.update': WAMessageUpdate[]
    'messages.media-update': { key: WAMessageKey, media?: { ciphertext: Uint8Array, iv: Uint8Array }, error?: Boom }[]
    /**
     * add/update the given messages. If they were received while the connection was online,
     * the update will have type: "notify"
     *  */
    'messages.upsert': { messages: WAMessage[], type: MessageUpsertType }
    /** message was reacted to. If reaction was removed -- then "reaction.text" will be falsey */
    'messages.reaction': { key: WAMessageKey, reaction: proto.IReaction }[]

    'message-receipt.update': MessageUserReceiptUpdate[]

    'groups.upsert': GroupMetadata[]
    'groups.update': Partial<GroupMetadata>[]
    /** apply an action to participants in a group */
    'group-participants.update': { id: string, participants: string[], action: ParticipantAction }

    'blocklist.set': { blocklist: string[] }
    'blocklist.update': { blocklist: string[], type: 'add' | 'remove' }
    /** Receive an update on a call, including when the call was received, rejected, accepted */
    'call': WACallEvent[]
}

Anda dapat mendengarkan acara ini seperti ini

const sock = makeWASocket()
sock.ev.on('messages.upsert', ({ messages }) => {
    console.log('got messages', messages)
})

Menerapkan Penyimpanan Data

Baileys tidak dilengkapi dengan penyimpanan de facto untuk obrolan, kontak, atau pesan. Namun, implementasi dalam memori yang sederhana telah disediakan. Toko mendengarkan pembaruan obrolan, pesan baru, pembaruan pesan, dll. , untuk selalu memiliki versi data terbaru

Ini dapat digunakan sebagai berikut

yarn add github:adiwajshing/baileys
_0

Toko juga menyediakan beberapa fungsi sederhana seperti

import makeWASocket, { BufferJSON, useMultiFileAuthState } from '@adiwajshing/baileys'
import * as fs from 'fs'

// utility function to help save the auth state in a single folder
// this function serves as a good guide to help write auth & key states for SQL/no-SQL databases, which I would recommend in any production grade system
const { state, saveCreds } = await useMultiFileAuthState('auth_info_baileys')
// will use the given state to connect
// so if valid credentials are available -- it'll connect without QR
const conn = makeWASocket({ auth: state }) 
// this will be called as soon as the credentials are updated
conn.ev.on ('creds.update', saveCreds)
4 yang memanfaatkan toko untuk mempercepat pengambilan data

Catatan. Saya sangat merekomendasikan membangun penyimpanan data Anda sendiri terutama untuk koneksi MD, karena menyimpan seluruh riwayat obrolan seseorang di memori adalah pemborosan RAM yang mengerikan

Mengirim Pesan

Kirim semua jenis pesan dengan satu fungsi

Pesan Non-Media

yarn add github:adiwajshing/baileys
_1

Mengirim pesan dengan pratinjau tautan

  1. Secara default, WA MD tidak memiliki pembuatan tautan saat dikirim dari web
  2. Baileys memiliki fungsi untuk menghasilkan konten untuk pratinjau tautan ini
  3. Untuk mengaktifkan penggunaan fungsi ini, tambahkan
    import makeWASocket, { BufferJSON, useMultiFileAuthState } from '@adiwajshing/baileys'
    import * as fs from 'fs'
    
    // utility function to help save the auth state in a single folder
    // this function serves as a good guide to help write auth & key states for SQL/no-SQL databases, which I would recommend in any production grade system
    const { state, saveCreds } = await useMultiFileAuthState('auth_info_baileys')
    // will use the given state to connect
    // so if valid credentials are available -- it'll connect without QR
    const conn = makeWASocket({ auth: state }) 
    // this will be called as soon as the credentials are updated
    conn.ev.on ('creds.update', saveCreds)
    5 sebagai ketergantungan proyek Anda dengan
    import makeWASocket, { BufferJSON, useMultiFileAuthState } from '@adiwajshing/baileys'
    import * as fs from 'fs'
    
    // utility function to help save the auth state in a single folder
    // this function serves as a good guide to help write auth & key states for SQL/no-SQL databases, which I would recommend in any production grade system
    const { state, saveCreds } = await useMultiFileAuthState('auth_info_baileys')
    // will use the given state to connect
    // so if valid credentials are available -- it'll connect without QR
    const conn = makeWASocket({ auth: state }) 
    // this will be called as soon as the credentials are updated
    conn.ev.on ('creds.update', saveCreds)
    6
  4. Kirim tautan

yarn add github:adiwajshing/baileys
_2

Pesan Media

Mengirim media (video, stiker, gambar) lebih mudah dan efisien dari sebelumnya

  • Anda dapat menentukan buffer, url lokal, atau bahkan url jarak jauh
  • Saat menentukan url media, Baileys tidak pernah memuat seluruh buffer ke dalam memori;

yarn add github:adiwajshing/baileys
_3

Catatan

  • import makeWASocket, { BufferJSON, useMultiFileAuthState } from '@adiwajshing/baileys'
    import * as fs from 'fs'
    
    // utility function to help save the auth state in a single folder
    // this function serves as a good guide to help write auth & key states for SQL/no-SQL databases, which I would recommend in any production grade system
    const { state, saveCreds } = await useMultiFileAuthState('auth_info_baileys')
    // will use the given state to connect
    // so if valid credentials are available -- it'll connect without QR
    const conn = makeWASocket({ auth: state }) 
    // this will be called as soon as the credentials are updated
    conn.ev.on ('creds.update', saveCreds)
    7 adalah ID WhatsApp orang atau grup yang Anda kirimi pesan
    • Itu harus dalam format
      import makeWASocket, { BufferJSON, useMultiFileAuthState } from '@adiwajshing/baileys'
      import * as fs from 'fs'
      
      // utility function to help save the auth state in a single folder
      // this function serves as a good guide to help write auth & key states for SQL/no-SQL databases, which I would recommend in any production grade system
      const { state, saveCreds } = await useMultiFileAuthState('auth_info_baileys')
      // will use the given state to connect
      // so if valid credentials are available -- it'll connect without QR
      const conn = makeWASocket({ auth: state }) 
      // this will be called as soon as the credentials are updated
      conn.ev.on ('creds.update', saveCreds)
      8
      • Contoh untuk orang.
        import makeWASocket, { BufferJSON, useMultiFileAuthState } from '@adiwajshing/baileys'
        import * as fs from 'fs'
        
        // utility function to help save the auth state in a single folder
        // this function serves as a good guide to help write auth & key states for SQL/no-SQL databases, which I would recommend in any production grade system
        const { state, saveCreds } = await useMultiFileAuthState('auth_info_baileys')
        // will use the given state to connect
        // so if valid credentials are available -- it'll connect without QR
        const conn = makeWASocket({ auth: state }) 
        // this will be called as soon as the credentials are updated
        conn.ev.on ('creds.update', saveCreds)
        _9
      • Untuk grup, harus dalam format
        type ConnectionState = {
        	/** connection is now open, connecting or closed */
        	connection: WAConnectionState
        	/** the error that caused the connection to close */
        	lastDisconnect?: {
        		error: Error
        		date: Date
        	}
        	/** is this a new login */
        	isNewLogin?: boolean
        	/** the current QR code */
        	qr?: string
        	/** has the device received all pending notifications while it was offline */
        	receivedPendingNotifications?: boolean 
        }
        0
    • Untuk daftar siaran, ini adalah
      type ConnectionState = {
      	/** connection is now open, connecting or closed */
      	connection: WAConnectionState
      	/** the error that caused the connection to close */
      	lastDisconnect?: {
      		error: Error
      		date: Date
      	}
      	/** is this a new login */
      	isNewLogin?: boolean
      	/** the current QR code */
      	qr?: string
      	/** has the device received all pending notifications while it was offline */
      	receivedPendingNotifications?: boolean 
      }
      1
    • Untuk cerita, IDnya adalah
      type ConnectionState = {
      	/** connection is now open, connecting or closed */
      	connection: WAConnectionState
      	/** the error that caused the connection to close */
      	lastDisconnect?: {
      		error: Error
      		date: Date
      	}
      	/** is this a new login */
      	isNewLogin?: boolean
      	/** the current QR code */
      	qr?: string
      	/** has the device received all pending notifications while it was offline */
      	receivedPendingNotifications?: boolean 
      }
      2
  • Untuk pesan media, thumbnail dapat dibuat secara otomatis untuk gambar & stiker asalkan Anda menambahkan
    type ConnectionState = {
    	/** connection is now open, connecting or closed */
    	connection: WAConnectionState
    	/** the error that caused the connection to close */
    	lastDisconnect?: {
    		error: Error
    		date: Date
    	}
    	/** is this a new login */
    	isNewLogin?: boolean
    	/** the current QR code */
    	qr?: string
    	/** has the device received all pending notifications while it was offline */
    	receivedPendingNotifications?: boolean 
    }
    3 atau
    type ConnectionState = {
    	/** connection is now open, connecting or closed */
    	connection: WAConnectionState
    	/** the error that caused the connection to close */
    	lastDisconnect?: {
    		error: Error
    		date: Date
    	}
    	/** is this a new login */
    	isNewLogin?: boolean
    	/** the current QR code */
    	qr?: string
    	/** has the device received all pending notifications while it was offline */
    	receivedPendingNotifications?: boolean 
    }
    4 sebagai dependensi dalam proyek Anda menggunakan
    type ConnectionState = {
    	/** connection is now open, connecting or closed */
    	connection: WAConnectionState
    	/** the error that caused the connection to close */
    	lastDisconnect?: {
    		error: Error
    		date: Date
    	}
    	/** is this a new login */
    	isNewLogin?: boolean
    	/** the current QR code */
    	qr?: string
    	/** has the device received all pending notifications while it was offline */
    	receivedPendingNotifications?: boolean 
    }
    5 atau
    type ConnectionState = {
    	/** connection is now open, connecting or closed */
    	connection: WAConnectionState
    	/** the error that caused the connection to close */
    	lastDisconnect?: {
    		error: Error
    		date: Date
    	}
    	/** is this a new login */
    	isNewLogin?: boolean
    	/** the current QR code */
    	qr?: string
    	/** has the device received all pending notifications while it was offline */
    	receivedPendingNotifications?: boolean 
    }
    6. Thumbnail untuk video juga dapat dibuat secara otomatis, meskipun Anda harus menginstal
    type ConnectionState = {
    	/** connection is now open, connecting or closed */
    	connection: WAConnectionState
    	/** the error that caused the connection to close */
    	lastDisconnect?: {
    		error: Error
    		date: Date
    	}
    	/** is this a new login */
    	isNewLogin?: boolean
    	/** the current QR code */
    	qr?: string
    	/** has the device received all pending notifications while it was offline */
    	receivedPendingNotifications?: boolean 
    }
    7 di sistem Anda
  • MiscGenerationOptions. beberapa info tambahan tentang pesan tersebut. Itu dapat memiliki nilai opsional berikut

    yarn add github:adiwajshing/baileys
    
    _4

Meneruskan Pesan

yarn add github:adiwajshing/baileys
_5

Membaca Pesan

Satu set kunci pesan harus secara eksplisit ditandai baca sekarang. Di multi-perangkat, Anda tidak dapat menandai seluruh "obrolan" sebagai telah dibaca dengan Baileys Web. Ini berarti Anda harus melacak pesan yang belum dibaca

yarn add github:adiwajshing/baileys
_6

ID pesan adalah pengidentifikasi unik dari pesan yang Anda tandai sebagai telah dibaca. Pada

type ConnectionState = {
	/** connection is now open, connecting or closed */
	connection: WAConnectionState
	/** the error that caused the connection to close */
	lastDisconnect?: {
		error: Error
		date: Date
	}
	/** is this a new login */
	isNewLogin?: boolean
	/** the current QR code */
	qr?: string
	/** has the device received all pending notifications while it was offline */
	receivedPendingNotifications?: boolean 
}
_8,
type ConnectionState = {
	/** connection is now open, connecting or closed */
	connection: WAConnectionState
	/** the error that caused the connection to close */
	lastDisconnect?: {
		error: Error
		date: Date
	}
	/** is this a new login */
	isNewLogin?: boolean
	/** the current QR code */
	qr?: string
	/** has the device received all pending notifications while it was offline */
	receivedPendingNotifications?: boolean 
}
9 dapat diakses menggunakan
export type BaileysEventMap = {
    /** connection state has been updated -- WS closed, opened, connecting etc. */
	'connection.update': Partial<ConnectionState>
    /** credentials updated -- some metadata, keys or something */
    'creds.update': Partial<AuthenticationCreds>
    /** history sync, everything is reverse chronologically sorted */
    'messaging-history.set': {
        chats: Chat[]
        contacts: Contact[]
        messages: WAMessage[]
        isLatest: boolean
    }
    /** upsert chats */
    'chats.upsert': Chat[]
    /** update the given chats */
    'chats.update': Partial<Chat>[]
    /** delete chats with given ID */
    'chats.delete': string[]
    /** presence of contact in a chat updated */
    'presence.update': { id: string, presences: { [participant: string]: PresenceData } }

    'contacts.upsert': Contact[]
    'contacts.update': Partial<Contact>[]

    'messages.delete': { keys: WAMessageKey[] } | { jid: string, all: true }
    'messages.update': WAMessageUpdate[]
    'messages.media-update': { key: WAMessageKey, media?: { ciphertext: Uint8Array, iv: Uint8Array }, error?: Boom }[]
    /**
     * add/update the given messages. If they were received while the connection was online,
     * the update will have type: "notify"
     *  */
    'messages.upsert': { messages: WAMessage[], type: MessageUpsertType }
    /** message was reacted to. If reaction was removed -- then "reaction.text" will be falsey */
    'messages.reaction': { key: WAMessageKey, reaction: proto.IReaction }[]

    'message-receipt.update': MessageUserReceiptUpdate[]

    'groups.upsert': GroupMetadata[]
    'groups.update': Partial<GroupMetadata>[]
    /** apply an action to participants in a group */
    'group-participants.update': { id: string, participants: string[], action: ParticipantAction }

    'blocklist.set': { blocklist: string[] }
    'blocklist.update': { blocklist: string[], type: 'add' | 'remove' }
    /** Receive an update on a call, including when the call was received, rejected, accepted */
    'call': WACallEvent[]
}
0

Perbarui Kehadiran

yarn add github:adiwajshing/baileys
_7

Ini memungkinkan orang/grup dengan

import makeWASocket, { BufferJSON, useMultiFileAuthState } from '@adiwajshing/baileys'
import * as fs from 'fs'

// utility function to help save the auth state in a single folder
// this function serves as a good guide to help write auth & key states for SQL/no-SQL databases, which I would recommend in any production grade system
const { state, saveCreds } = await useMultiFileAuthState('auth_info_baileys')
// will use the given state to connect
// so if valid credentials are available -- it'll connect without QR
const conn = makeWASocket({ auth: state }) 
// this will be called as soon as the credentials are updated
conn.ev.on ('creds.update', saveCreds)
_7 mengetahui apakah Anda sedang online, offline, mengetik, dll

export type BaileysEventMap = {
    /** connection state has been updated -- WS closed, opened, connecting etc. */
	'connection.update': Partial<ConnectionState>
    /** credentials updated -- some metadata, keys or something */
    'creds.update': Partial<AuthenticationCreds>
    /** history sync, everything is reverse chronologically sorted */
    'messaging-history.set': {
        chats: Chat[]
        contacts: Contact[]
        messages: WAMessage[]
        isLatest: boolean
    }
    /** upsert chats */
    'chats.upsert': Chat[]
    /** update the given chats */
    'chats.update': Partial<Chat>[]
    /** delete chats with given ID */
    'chats.delete': string[]
    /** presence of contact in a chat updated */
    'presence.update': { id: string, presences: { [participant: string]: PresenceData } }

    'contacts.upsert': Contact[]
    'contacts.update': Partial<Contact>[]

    'messages.delete': { keys: WAMessageKey[] } | { jid: string, all: true }
    'messages.update': WAMessageUpdate[]
    'messages.media-update': { key: WAMessageKey, media?: { ciphertext: Uint8Array, iv: Uint8Array }, error?: Boom }[]
    /**
     * add/update the given messages. If they were received while the connection was online,
     * the update will have type: "notify"
     *  */
    'messages.upsert': { messages: WAMessage[], type: MessageUpsertType }
    /** message was reacted to. If reaction was removed -- then "reaction.text" will be falsey */
    'messages.reaction': { key: WAMessageKey, reaction: proto.IReaction }[]

    'message-receipt.update': MessageUserReceiptUpdate[]

    'groups.upsert': GroupMetadata[]
    'groups.update': Partial<GroupMetadata>[]
    /** apply an action to participants in a group */
    'group-participants.update': { id: string, participants: string[], action: ParticipantAction }

    'blocklist.set': { blocklist: string[] }
    'blocklist.update': { blocklist: string[], type: 'add' | 'remove' }
    /** Receive an update on a call, including when the call was received, rejected, accepted */
    'call': WACallEvent[]
}
_2 dapat menjadi salah satu dari berikut ini

yarn add github:adiwajshing/baileys
_8

Kehadiran berakhir setelah sekitar 10 detik

Catatan. Di WhatsApp versi multi-perangkat -- jika klien desktop aktif, WA tidak mengirimkan pemberitahuan push ke perangkat. Jika Anda ingin menerima pemberitahuan tersebut -- tandai klien Baileys Anda offline menggunakan

export type BaileysEventMap = {
    /** connection state has been updated -- WS closed, opened, connecting etc. */
	'connection.update': Partial<ConnectionState>
    /** credentials updated -- some metadata, keys or something */
    'creds.update': Partial<AuthenticationCreds>
    /** history sync, everything is reverse chronologically sorted */
    'messaging-history.set': {
        chats: Chat[]
        contacts: Contact[]
        messages: WAMessage[]
        isLatest: boolean
    }
    /** upsert chats */
    'chats.upsert': Chat[]
    /** update the given chats */
    'chats.update': Partial<Chat>[]
    /** delete chats with given ID */
    'chats.delete': string[]
    /** presence of contact in a chat updated */
    'presence.update': { id: string, presences: { [participant: string]: PresenceData } }

    'contacts.upsert': Contact[]
    'contacts.update': Partial<Contact>[]

    'messages.delete': { keys: WAMessageKey[] } | { jid: string, all: true }
    'messages.update': WAMessageUpdate[]
    'messages.media-update': { key: WAMessageKey, media?: { ciphertext: Uint8Array, iv: Uint8Array }, error?: Boom }[]
    /**
     * add/update the given messages. If they were received while the connection was online,
     * the update will have type: "notify"
     *  */
    'messages.upsert': { messages: WAMessage[], type: MessageUpsertType }
    /** message was reacted to. If reaction was removed -- then "reaction.text" will be falsey */
    'messages.reaction': { key: WAMessageKey, reaction: proto.IReaction }[]

    'message-receipt.update': MessageUserReceiptUpdate[]

    'groups.upsert': GroupMetadata[]
    'groups.update': Partial<GroupMetadata>[]
    /** apply an action to participants in a group */
    'group-participants.update': { id: string, participants: string[], action: ParticipantAction }

    'blocklist.set': { blocklist: string[] }
    'blocklist.update': { blocklist: string[], type: 'add' | 'remove' }
    /** Receive an update on a call, including when the call was received, rejected, accepted */
    'call': WACallEvent[]
}
3

Mengunduh Pesan Media

Jika Anda ingin menyimpan media yang Anda terima

yarn add github:adiwajshing/baileys
_9

Catatan. WhatsApp secara otomatis menghapus media lama dari server mereka. Agar perangkat dapat mengakses media tersebut -- pengunggahan ulang diperlukan oleh perangkat lain yang memilikinya. Ini dapat dicapai dengan menggunakan

import makeWASocket from '@adiwajshing/baileys'
0

Menghapus Pesan

import makeWASocket from '@adiwajshing/baileys'
1

Catatan. menghapus untuk diri sendiri didukung melalui

export type BaileysEventMap = {
    /** connection state has been updated -- WS closed, opened, connecting etc. */
	'connection.update': Partial<ConnectionState>
    /** credentials updated -- some metadata, keys or something */
    'creds.update': Partial<AuthenticationCreds>
    /** history sync, everything is reverse chronologically sorted */
    'messaging-history.set': {
        chats: Chat[]
        contacts: Contact[]
        messages: WAMessage[]
        isLatest: boolean
    }
    /** upsert chats */
    'chats.upsert': Chat[]
    /** update the given chats */
    'chats.update': Partial<Chat>[]
    /** delete chats with given ID */
    'chats.delete': string[]
    /** presence of contact in a chat updated */
    'presence.update': { id: string, presences: { [participant: string]: PresenceData } }

    'contacts.upsert': Contact[]
    'contacts.update': Partial<Contact>[]

    'messages.delete': { keys: WAMessageKey[] } | { jid: string, all: true }
    'messages.update': WAMessageUpdate[]
    'messages.media-update': { key: WAMessageKey, media?: { ciphertext: Uint8Array, iv: Uint8Array }, error?: Boom }[]
    /**
     * add/update the given messages. If they were received while the connection was online,
     * the update will have type: "notify"
     *  */
    'messages.upsert': { messages: WAMessage[], type: MessageUpsertType }
    /** message was reacted to. If reaction was removed -- then "reaction.text" will be falsey */
    'messages.reaction': { key: WAMessageKey, reaction: proto.IReaction }[]

    'message-receipt.update': MessageUserReceiptUpdate[]

    'groups.upsert': GroupMetadata[]
    'groups.update': Partial<GroupMetadata>[]
    /** apply an action to participants in a group */
    'group-participants.update': { id: string, participants: string[], action: ParticipantAction }

    'blocklist.set': { blocklist: string[] }
    'blocklist.update': { blocklist: string[], type: 'add' | 'remove' }
    /** Receive an update on a call, including when the call was received, rejected, accepted */
    'call': WACallEvent[]
}
4 (bagian selanjutnya)

Memodifikasi Obrolan

WA menggunakan bentuk komunikasi terenkripsi untuk mengirim pembaruan obrolan/aplikasi. Ini sebagian besar telah diterapkan dan Anda dapat mengirim pembaruan berikut

  • Arsipkan obrolan

    import makeWASocket from '@adiwajshing/baileys'
    2

  • Membisukan/mengaktifkan obrolan

    import makeWASocket from '@adiwajshing/baileys'
    _3

  • Tandai obrolan telah dibaca/belum dibaca

    import makeWASocket from '@adiwajshing/baileys'
    _4

  • Hapus pesan untuk saya

    import makeWASocket from '@adiwajshing/baileys'
    5

  • Hapus obrolan

    import makeWASocket from '@adiwajshing/baileys'
    _6

  • Sematkan/lepas sematkan obrolan

    import makeWASocket from '@adiwajshing/baileys'
    _7

Catatan. jika Anda mengacaukan salah satu pembaruan Anda, WA dapat mengeluarkan Anda dari semua perangkat Anda dan Anda harus masuk lagi

Pesan Menghilang

import makeWASocket from '@adiwajshing/baileys'
_8

Lain-lain

  • Untuk memeriksa apakah ID yang diberikan ada di WhatsApp

    import makeWASocket from '@adiwajshing/baileys'
    _9

  • Untuk menanyakan riwayat obrolan di grup atau dengan seseorang TODO, jika memungkinkan
  • Untuk mendapatkan status seseorang

    import makeWASocket, { DisconnectReason } from '@adiwajshing/baileys'
    import { Boom } from '@hapi/boom'
    
    async function connectToWhatsApp () {
        const sock = makeWASocket({
            // can provide additional config here
            printQRInTerminal: true
        })
        sock.ev.on('connection.update', (update) => {
            const { connection, lastDisconnect } = update
            if(connection === 'close') {
                const shouldReconnect = (lastDisconnect.error as Boom)?.output?.statusCode !== DisconnectReason.loggedOut
                console.log('connection closed due to ', lastDisconnect.error, ', reconnecting ', shouldReconnect)
                // reconnect if not logged out
                if(shouldReconnect) {
                    connectToWhatsApp()
                }
            } else if(connection === 'open') {
                console.log('opened connection')
            }
        })
        sock.ev.on('messages.upsert', m => {
            console.log(JSON.stringify(m, undefined, 2))
    
            console.log('replying to', m.messages[0].key.remoteJid)
            await sock.sendMessage(m.messages[0].key.remoteJid!, { text: 'Hello there!' })
        })
    }
    // run in main file
    connectToWhatsApp()
    _0

  • Untuk mengubah status profil Anda

    import makeWASocket, { DisconnectReason } from '@adiwajshing/baileys'
    import { Boom } from '@hapi/boom'
    
    async function connectToWhatsApp () {
        const sock = makeWASocket({
            // can provide additional config here
            printQRInTerminal: true
        })
        sock.ev.on('connection.update', (update) => {
            const { connection, lastDisconnect } = update
            if(connection === 'close') {
                const shouldReconnect = (lastDisconnect.error as Boom)?.output?.statusCode !== DisconnectReason.loggedOut
                console.log('connection closed due to ', lastDisconnect.error, ', reconnecting ', shouldReconnect)
                // reconnect if not logged out
                if(shouldReconnect) {
                    connectToWhatsApp()
                }
            } else if(connection === 'open') {
                console.log('opened connection')
            }
        })
        sock.ev.on('messages.upsert', m => {
            console.log(JSON.stringify(m, undefined, 2))
    
            console.log('replying to', m.messages[0].key.remoteJid)
            await sock.sendMessage(m.messages[0].key.remoteJid!, { text: 'Hello there!' })
        })
    }
    // run in main file
    connectToWhatsApp()
    _1

  • Untuk mengubah nama profil Anda

    import makeWASocket, { DisconnectReason } from '@adiwajshing/baileys'
    import { Boom } from '@hapi/boom'
    
    async function connectToWhatsApp () {
        const sock = makeWASocket({
            // can provide additional config here
            printQRInTerminal: true
        })
        sock.ev.on('connection.update', (update) => {
            const { connection, lastDisconnect } = update
            if(connection === 'close') {
                const shouldReconnect = (lastDisconnect.error as Boom)?.output?.statusCode !== DisconnectReason.loggedOut
                console.log('connection closed due to ', lastDisconnect.error, ', reconnecting ', shouldReconnect)
                // reconnect if not logged out
                if(shouldReconnect) {
                    connectToWhatsApp()
                }
            } else if(connection === 'open') {
                console.log('opened connection')
            }
        })
        sock.ev.on('messages.upsert', m => {
            console.log(JSON.stringify(m, undefined, 2))
    
            console.log('replying to', m.messages[0].key.remoteJid)
            await sock.sendMessage(m.messages[0].key.remoteJid!, { text: 'Hello there!' })
        })
    }
    // run in main file
    connectToWhatsApp()
    _2

  • Untuk mendapatkan gambar tampilan dari beberapa orang/kelompok

    import makeWASocket, { DisconnectReason } from '@adiwajshing/baileys'
    import { Boom } from '@hapi/boom'
    
    async function connectToWhatsApp () {
        const sock = makeWASocket({
            // can provide additional config here
            printQRInTerminal: true
        })
        sock.ev.on('connection.update', (update) => {
            const { connection, lastDisconnect } = update
            if(connection === 'close') {
                const shouldReconnect = (lastDisconnect.error as Boom)?.output?.statusCode !== DisconnectReason.loggedOut
                console.log('connection closed due to ', lastDisconnect.error, ', reconnecting ', shouldReconnect)
                // reconnect if not logged out
                if(shouldReconnect) {
                    connectToWhatsApp()
                }
            } else if(connection === 'open') {
                console.log('opened connection')
            }
        })
        sock.ev.on('messages.upsert', m => {
            console.log(JSON.stringify(m, undefined, 2))
    
            console.log('replying to', m.messages[0].key.remoteJid)
            await sock.sendMessage(m.messages[0].key.remoteJid!, { text: 'Hello there!' })
        })
    }
    // run in main file
    connectToWhatsApp()
    _3

  • Untuk mengubah gambar tampilan Anda atau grup

    import makeWASocket, { DisconnectReason } from '@adiwajshing/baileys'
    import { Boom } from '@hapi/boom'
    
    async function connectToWhatsApp () {
        const sock = makeWASocket({
            // can provide additional config here
            printQRInTerminal: true
        })
        sock.ev.on('connection.update', (update) => {
            const { connection, lastDisconnect } = update
            if(connection === 'close') {
                const shouldReconnect = (lastDisconnect.error as Boom)?.output?.statusCode !== DisconnectReason.loggedOut
                console.log('connection closed due to ', lastDisconnect.error, ', reconnecting ', shouldReconnect)
                // reconnect if not logged out
                if(shouldReconnect) {
                    connectToWhatsApp()
                }
            } else if(connection === 'open') {
                console.log('opened connection')
            }
        })
        sock.ev.on('messages.upsert', m => {
            console.log(JSON.stringify(m, undefined, 2))
    
            console.log('replying to', m.messages[0].key.remoteJid)
            await sock.sendMessage(m.messages[0].key.remoteJid!, { text: 'Hello there!' })
        })
    }
    // run in main file
    connectToWhatsApp()
    _4

  • Untuk mendapatkan kehadiran seseorang (jika mereka sedang mengetik atau online)

    import makeWASocket, { DisconnectReason } from '@adiwajshing/baileys'
    import { Boom } from '@hapi/boom'
    
    async function connectToWhatsApp () {
        const sock = makeWASocket({
            // can provide additional config here
            printQRInTerminal: true
        })
        sock.ev.on('connection.update', (update) => {
            const { connection, lastDisconnect } = update
            if(connection === 'close') {
                const shouldReconnect = (lastDisconnect.error as Boom)?.output?.statusCode !== DisconnectReason.loggedOut
                console.log('connection closed due to ', lastDisconnect.error, ', reconnecting ', shouldReconnect)
                // reconnect if not logged out
                if(shouldReconnect) {
                    connectToWhatsApp()
                }
            } else if(connection === 'open') {
                console.log('opened connection')
            }
        })
        sock.ev.on('messages.upsert', m => {
            console.log(JSON.stringify(m, undefined, 2))
    
            console.log('replying to', m.messages[0].key.remoteJid)
            await sock.sendMessage(m.messages[0].key.remoteJid!, { text: 'Hello there!' })
        })
    }
    // run in main file
    connectToWhatsApp()
    _5

  • Untuk memblokir atau membuka blokir pengguna

    import makeWASocket, { DisconnectReason } from '@adiwajshing/baileys'
    import { Boom } from '@hapi/boom'
    
    async function connectToWhatsApp () {
        const sock = makeWASocket({
            // can provide additional config here
            printQRInTerminal: true
        })
        sock.ev.on('connection.update', (update) => {
            const { connection, lastDisconnect } = update
            if(connection === 'close') {
                const shouldReconnect = (lastDisconnect.error as Boom)?.output?.statusCode !== DisconnectReason.loggedOut
                console.log('connection closed due to ', lastDisconnect.error, ', reconnecting ', shouldReconnect)
                // reconnect if not logged out
                if(shouldReconnect) {
                    connectToWhatsApp()
                }
            } else if(connection === 'open') {
                console.log('opened connection')
            }
        })
        sock.ev.on('messages.upsert', m => {
            console.log(JSON.stringify(m, undefined, 2))
    
            console.log('replying to', m.messages[0].key.remoteJid)
            await sock.sendMessage(m.messages[0].key.remoteJid!, { text: 'Hello there!' })
        })
    }
    // run in main file
    connectToWhatsApp()
    _6

  • Untuk mendapatkan profil bisnis, seperti deskripsi atau kategori

    import makeWASocket, { DisconnectReason } from '@adiwajshing/baileys'
    import { Boom } from '@hapi/boom'
    
    async function connectToWhatsApp () {
        const sock = makeWASocket({
            // can provide additional config here
            printQRInTerminal: true
        })
        sock.ev.on('connection.update', (update) => {
            const { connection, lastDisconnect } = update
            if(connection === 'close') {
                const shouldReconnect = (lastDisconnect.error as Boom)?.output?.statusCode !== DisconnectReason.loggedOut
                console.log('connection closed due to ', lastDisconnect.error, ', reconnecting ', shouldReconnect)
                // reconnect if not logged out
                if(shouldReconnect) {
                    connectToWhatsApp()
                }
            } else if(connection === 'open') {
                console.log('opened connection')
            }
        })
        sock.ev.on('messages.upsert', m => {
            console.log(JSON.stringify(m, undefined, 2))
    
            console.log('replying to', m.messages[0].key.remoteJid)
            await sock.sendMessage(m.messages[0].key.remoteJid!, { text: 'Hello there!' })
        })
    }
    // run in main file
    connectToWhatsApp()
    _7

Tentu saja, ganti

export type BaileysEventMap = {
    /** connection state has been updated -- WS closed, opened, connecting etc. */
	'connection.update': Partial<ConnectionState>
    /** credentials updated -- some metadata, keys or something */
    'creds.update': Partial<AuthenticationCreds>
    /** history sync, everything is reverse chronologically sorted */
    'messaging-history.set': {
        chats: Chat[]
        contacts: Contact[]
        messages: WAMessage[]
        isLatest: boolean
    }
    /** upsert chats */
    'chats.upsert': Chat[]
    /** update the given chats */
    'chats.update': Partial<Chat>[]
    /** delete chats with given ID */
    'chats.delete': string[]
    /** presence of contact in a chat updated */
    'presence.update': { id: string, presences: { [participant: string]: PresenceData } }

    'contacts.upsert': Contact[]
    'contacts.update': Partial<Contact>[]

    'messages.delete': { keys: WAMessageKey[] } | { jid: string, all: true }
    'messages.update': WAMessageUpdate[]
    'messages.media-update': { key: WAMessageKey, media?: { ciphertext: Uint8Array, iv: Uint8Array }, error?: Boom }[]
    /**
     * add/update the given messages. If they were received while the connection was online,
     * the update will have type: "notify"
     *  */
    'messages.upsert': { messages: WAMessage[], type: MessageUpsertType }
    /** message was reacted to. If reaction was removed -- then "reaction.text" will be falsey */
    'messages.reaction': { key: WAMessageKey, reaction: proto.IReaction }[]

    'message-receipt.update': MessageUserReceiptUpdate[]

    'groups.upsert': GroupMetadata[]
    'groups.update': Partial<GroupMetadata>[]
    /** apply an action to participants in a group */
    'group-participants.update': { id: string, participants: string[], action: ParticipantAction }

    'blocklist.set': { blocklist: string[] }
    'blocklist.update': { blocklist: string[], type: 'add' | 'remove' }
    /** Receive an update on a call, including when the call was received, rejected, accepted */
    'call': WACallEvent[]
}
_5 dengan ID yang sebenarnya

Grup

  • Untuk membuat grup

    import makeWASocket, { DisconnectReason } from '@adiwajshing/baileys'
    import { Boom } from '@hapi/boom'
    
    async function connectToWhatsApp () {
        const sock = makeWASocket({
            // can provide additional config here
            printQRInTerminal: true
        })
        sock.ev.on('connection.update', (update) => {
            const { connection, lastDisconnect } = update
            if(connection === 'close') {
                const shouldReconnect = (lastDisconnect.error as Boom)?.output?.statusCode !== DisconnectReason.loggedOut
                console.log('connection closed due to ', lastDisconnect.error, ', reconnecting ', shouldReconnect)
                // reconnect if not logged out
                if(shouldReconnect) {
                    connectToWhatsApp()
                }
            } else if(connection === 'open') {
                console.log('opened connection')
            }
        })
        sock.ev.on('messages.upsert', m => {
            console.log(JSON.stringify(m, undefined, 2))
    
            console.log('replying to', m.messages[0].key.remoteJid)
            await sock.sendMessage(m.messages[0].key.remoteJid!, { text: 'Hello there!' })
        })
    }
    // run in main file
    connectToWhatsApp()
    _8

  • Untuk menambah/menghapus orang ke grup atau menurunkan/mempromosikan orang

    import makeWASocket, { DisconnectReason } from '@adiwajshing/baileys'
    import { Boom } from '@hapi/boom'
    
    async function connectToWhatsApp () {
        const sock = makeWASocket({
            // can provide additional config here
            printQRInTerminal: true
        })
        sock.ev.on('connection.update', (update) => {
            const { connection, lastDisconnect } = update
            if(connection === 'close') {
                const shouldReconnect = (lastDisconnect.error as Boom)?.output?.statusCode !== DisconnectReason.loggedOut
                console.log('connection closed due to ', lastDisconnect.error, ', reconnecting ', shouldReconnect)
                // reconnect if not logged out
                if(shouldReconnect) {
                    connectToWhatsApp()
                }
            } else if(connection === 'open') {
                console.log('opened connection')
            }
        })
        sock.ev.on('messages.upsert', m => {
            console.log(JSON.stringify(m, undefined, 2))
    
            console.log('replying to', m.messages[0].key.remoteJid)
            await sock.sendMessage(m.messages[0].key.remoteJid!, { text: 'Hello there!' })
        })
    }
    // run in main file
    connectToWhatsApp()
    _9

  • Untuk mengubah topik grup

    type SocketConfig = {
        /** the WS url to connect to WA */
        waWebSocketUrl: string | URL
        /** Fails the connection if the socket times out in this interval */
    	connectTimeoutMs: number
        /** Default timeout for queries, undefined for no timeout */
        defaultQueryTimeoutMs: number | undefined
        /** ping-pong interval for WS connection */
        keepAliveIntervalMs: number
        /** proxy agent */
    	agent?: Agent
        /** pino logger */
    	logger: Logger
        /** version to connect with */
        version: WAVersion
        /** override browser config */
    	browser: WABrowserDescription
    	/** agent used for fetch requests -- uploading/downloading media */
    	fetchAgent?: Agent
        /** should the QR be printed in the terminal */
        printQRInTerminal: boolean
        /** should events be emitted for actions done by this socket connection */
        emitOwnEvents: boolean
        /** provide a cache to store media, so does not have to be re-uploaded */
        mediaCache?: NodeCache
        /** custom upload hosts to upload media to */
        customUploadHosts: MediaConnInfo['hosts']
        /** time to wait between sending new retry requests */
        retryRequestDelayMs: number
        /** time to wait for the generation of the next QR in ms */
        qrTimeout?: number;
        /** provide an auth state object to maintain the auth state */
        auth: AuthenticationState
        /** manage history processing with this control; by default will sync up everything */
        shouldSyncHistoryMessage: (msg: proto.Message.IHistorySyncNotification) => boolean
        /** transaction capability options for SignalKeyStore */
        transactionOpts: TransactionCapabilityOptions
        /** provide a cache to store a user's device list */
        userDevicesCache?: NodeCache
        /** marks the client as online whenever the socket successfully connects */
        markOnlineOnConnect: boolean
        /**
         * map to store the retry counts for failed messages;
         * used to determine whether to retry a message or not */
        msgRetryCounterMap?: MessageRetryMap
        /** width for link preview images */
        linkPreviewImageThumbnailWidth: number
        /** Should Baileys ask the phone for full history, will be received async */
        syncFullHistory: boolean
        /** Should baileys fire init queries automatically, default true */
        fireInitQueries: boolean
        /**
         * generate a high quality link preview,
         * entails uploading the jpegThumbnail to WA
         * */
        generateHighQualityLinkPreview: boolean
    
        /** options for axios */
        options: AxiosRequestConfig<any>
        /**
         * fetch a message from your store
         * implement this so that messages failed to send (solves the "this message can take a while" issue) can be retried
         * */
        getMessage: (key: proto.IMessageKey) => Promise<proto.IMessage | undefined>
    }
    _0

  • Untuk mengubah deskripsi grup

    type SocketConfig = {
        /** the WS url to connect to WA */
        waWebSocketUrl: string | URL
        /** Fails the connection if the socket times out in this interval */
    	connectTimeoutMs: number
        /** Default timeout for queries, undefined for no timeout */
        defaultQueryTimeoutMs: number | undefined
        /** ping-pong interval for WS connection */
        keepAliveIntervalMs: number
        /** proxy agent */
    	agent?: Agent
        /** pino logger */
    	logger: Logger
        /** version to connect with */
        version: WAVersion
        /** override browser config */
    	browser: WABrowserDescription
    	/** agent used for fetch requests -- uploading/downloading media */
    	fetchAgent?: Agent
        /** should the QR be printed in the terminal */
        printQRInTerminal: boolean
        /** should events be emitted for actions done by this socket connection */
        emitOwnEvents: boolean
        /** provide a cache to store media, so does not have to be re-uploaded */
        mediaCache?: NodeCache
        /** custom upload hosts to upload media to */
        customUploadHosts: MediaConnInfo['hosts']
        /** time to wait between sending new retry requests */
        retryRequestDelayMs: number
        /** time to wait for the generation of the next QR in ms */
        qrTimeout?: number;
        /** provide an auth state object to maintain the auth state */
        auth: AuthenticationState
        /** manage history processing with this control; by default will sync up everything */
        shouldSyncHistoryMessage: (msg: proto.Message.IHistorySyncNotification) => boolean
        /** transaction capability options for SignalKeyStore */
        transactionOpts: TransactionCapabilityOptions
        /** provide a cache to store a user's device list */
        userDevicesCache?: NodeCache
        /** marks the client as online whenever the socket successfully connects */
        markOnlineOnConnect: boolean
        /**
         * map to store the retry counts for failed messages;
         * used to determine whether to retry a message or not */
        msgRetryCounterMap?: MessageRetryMap
        /** width for link preview images */
        linkPreviewImageThumbnailWidth: number
        /** Should Baileys ask the phone for full history, will be received async */
        syncFullHistory: boolean
        /** Should baileys fire init queries automatically, default true */
        fireInitQueries: boolean
        /**
         * generate a high quality link preview,
         * entails uploading the jpegThumbnail to WA
         * */
        generateHighQualityLinkPreview: boolean
    
        /** options for axios */
        options: AxiosRequestConfig<any>
        /**
         * fetch a message from your store
         * implement this so that messages failed to send (solves the "this message can take a while" issue) can be retried
         * */
        getMessage: (key: proto.IMessageKey) => Promise<proto.IMessage | undefined>
    }
    _1

  • Untuk mengubah pengaturan grup

    type SocketConfig = {
        /** the WS url to connect to WA */
        waWebSocketUrl: string | URL
        /** Fails the connection if the socket times out in this interval */
    	connectTimeoutMs: number
        /** Default timeout for queries, undefined for no timeout */
        defaultQueryTimeoutMs: number | undefined
        /** ping-pong interval for WS connection */
        keepAliveIntervalMs: number
        /** proxy agent */
    	agent?: Agent
        /** pino logger */
    	logger: Logger
        /** version to connect with */
        version: WAVersion
        /** override browser config */
    	browser: WABrowserDescription
    	/** agent used for fetch requests -- uploading/downloading media */
    	fetchAgent?: Agent
        /** should the QR be printed in the terminal */
        printQRInTerminal: boolean
        /** should events be emitted for actions done by this socket connection */
        emitOwnEvents: boolean
        /** provide a cache to store media, so does not have to be re-uploaded */
        mediaCache?: NodeCache
        /** custom upload hosts to upload media to */
        customUploadHosts: MediaConnInfo['hosts']
        /** time to wait between sending new retry requests */
        retryRequestDelayMs: number
        /** time to wait for the generation of the next QR in ms */
        qrTimeout?: number;
        /** provide an auth state object to maintain the auth state */
        auth: AuthenticationState
        /** manage history processing with this control; by default will sync up everything */
        shouldSyncHistoryMessage: (msg: proto.Message.IHistorySyncNotification) => boolean
        /** transaction capability options for SignalKeyStore */
        transactionOpts: TransactionCapabilityOptions
        /** provide a cache to store a user's device list */
        userDevicesCache?: NodeCache
        /** marks the client as online whenever the socket successfully connects */
        markOnlineOnConnect: boolean
        /**
         * map to store the retry counts for failed messages;
         * used to determine whether to retry a message or not */
        msgRetryCounterMap?: MessageRetryMap
        /** width for link preview images */
        linkPreviewImageThumbnailWidth: number
        /** Should Baileys ask the phone for full history, will be received async */
        syncFullHistory: boolean
        /** Should baileys fire init queries automatically, default true */
        fireInitQueries: boolean
        /**
         * generate a high quality link preview,
         * entails uploading the jpegThumbnail to WA
         * */
        generateHighQualityLinkPreview: boolean
    
        /** options for axios */
        options: AxiosRequestConfig<any>
        /**
         * fetch a message from your store
         * implement this so that messages failed to send (solves the "this message can take a while" issue) can be retried
         * */
        getMessage: (key: proto.IMessageKey) => Promise<proto.IMessage | undefined>
    }
    _2

  • Untuk keluar dari grup

    type SocketConfig = {
        /** the WS url to connect to WA */
        waWebSocketUrl: string | URL
        /** Fails the connection if the socket times out in this interval */
    	connectTimeoutMs: number
        /** Default timeout for queries, undefined for no timeout */
        defaultQueryTimeoutMs: number | undefined
        /** ping-pong interval for WS connection */
        keepAliveIntervalMs: number
        /** proxy agent */
    	agent?: Agent
        /** pino logger */
    	logger: Logger
        /** version to connect with */
        version: WAVersion
        /** override browser config */
    	browser: WABrowserDescription
    	/** agent used for fetch requests -- uploading/downloading media */
    	fetchAgent?: Agent
        /** should the QR be printed in the terminal */
        printQRInTerminal: boolean
        /** should events be emitted for actions done by this socket connection */
        emitOwnEvents: boolean
        /** provide a cache to store media, so does not have to be re-uploaded */
        mediaCache?: NodeCache
        /** custom upload hosts to upload media to */
        customUploadHosts: MediaConnInfo['hosts']
        /** time to wait between sending new retry requests */
        retryRequestDelayMs: number
        /** time to wait for the generation of the next QR in ms */
        qrTimeout?: number;
        /** provide an auth state object to maintain the auth state */
        auth: AuthenticationState
        /** manage history processing with this control; by default will sync up everything */
        shouldSyncHistoryMessage: (msg: proto.Message.IHistorySyncNotification) => boolean
        /** transaction capability options for SignalKeyStore */
        transactionOpts: TransactionCapabilityOptions
        /** provide a cache to store a user's device list */
        userDevicesCache?: NodeCache
        /** marks the client as online whenever the socket successfully connects */
        markOnlineOnConnect: boolean
        /**
         * map to store the retry counts for failed messages;
         * used to determine whether to retry a message or not */
        msgRetryCounterMap?: MessageRetryMap
        /** width for link preview images */
        linkPreviewImageThumbnailWidth: number
        /** Should Baileys ask the phone for full history, will be received async */
        syncFullHistory: boolean
        /** Should baileys fire init queries automatically, default true */
        fireInitQueries: boolean
        /**
         * generate a high quality link preview,
         * entails uploading the jpegThumbnail to WA
         * */
        generateHighQualityLinkPreview: boolean
    
        /** options for axios */
        options: AxiosRequestConfig<any>
        /**
         * fetch a message from your store
         * implement this so that messages failed to send (solves the "this message can take a while" issue) can be retried
         * */
        getMessage: (key: proto.IMessageKey) => Promise<proto.IMessage | undefined>
    }
    _3

  • Untuk mendapatkan kode undangan untuk grup

    type SocketConfig = {
        /** the WS url to connect to WA */
        waWebSocketUrl: string | URL
        /** Fails the connection if the socket times out in this interval */
    	connectTimeoutMs: number
        /** Default timeout for queries, undefined for no timeout */
        defaultQueryTimeoutMs: number | undefined
        /** ping-pong interval for WS connection */
        keepAliveIntervalMs: number
        /** proxy agent */
    	agent?: Agent
        /** pino logger */
    	logger: Logger
        /** version to connect with */
        version: WAVersion
        /** override browser config */
    	browser: WABrowserDescription
    	/** agent used for fetch requests -- uploading/downloading media */
    	fetchAgent?: Agent
        /** should the QR be printed in the terminal */
        printQRInTerminal: boolean
        /** should events be emitted for actions done by this socket connection */
        emitOwnEvents: boolean
        /** provide a cache to store media, so does not have to be re-uploaded */
        mediaCache?: NodeCache
        /** custom upload hosts to upload media to */
        customUploadHosts: MediaConnInfo['hosts']
        /** time to wait between sending new retry requests */
        retryRequestDelayMs: number
        /** time to wait for the generation of the next QR in ms */
        qrTimeout?: number;
        /** provide an auth state object to maintain the auth state */
        auth: AuthenticationState
        /** manage history processing with this control; by default will sync up everything */
        shouldSyncHistoryMessage: (msg: proto.Message.IHistorySyncNotification) => boolean
        /** transaction capability options for SignalKeyStore */
        transactionOpts: TransactionCapabilityOptions
        /** provide a cache to store a user's device list */
        userDevicesCache?: NodeCache
        /** marks the client as online whenever the socket successfully connects */
        markOnlineOnConnect: boolean
        /**
         * map to store the retry counts for failed messages;
         * used to determine whether to retry a message or not */
        msgRetryCounterMap?: MessageRetryMap
        /** width for link preview images */
        linkPreviewImageThumbnailWidth: number
        /** Should Baileys ask the phone for full history, will be received async */
        syncFullHistory: boolean
        /** Should baileys fire init queries automatically, default true */
        fireInitQueries: boolean
        /**
         * generate a high quality link preview,
         * entails uploading the jpegThumbnail to WA
         * */
        generateHighQualityLinkPreview: boolean
    
        /** options for axios */
        options: AxiosRequestConfig<any>
        /**
         * fetch a message from your store
         * implement this so that messages failed to send (solves the "this message can take a while" issue) can be retried
         * */
        getMessage: (key: proto.IMessageKey) => Promise<proto.IMessage | undefined>
    }
    _4

  • Untuk mencabut kode invite di grup

    type SocketConfig = {
        /** the WS url to connect to WA */
        waWebSocketUrl: string | URL
        /** Fails the connection if the socket times out in this interval */
    	connectTimeoutMs: number
        /** Default timeout for queries, undefined for no timeout */
        defaultQueryTimeoutMs: number | undefined
        /** ping-pong interval for WS connection */
        keepAliveIntervalMs: number
        /** proxy agent */
    	agent?: Agent
        /** pino logger */
    	logger: Logger
        /** version to connect with */
        version: WAVersion
        /** override browser config */
    	browser: WABrowserDescription
    	/** agent used for fetch requests -- uploading/downloading media */
    	fetchAgent?: Agent
        /** should the QR be printed in the terminal */
        printQRInTerminal: boolean
        /** should events be emitted for actions done by this socket connection */
        emitOwnEvents: boolean
        /** provide a cache to store media, so does not have to be re-uploaded */
        mediaCache?: NodeCache
        /** custom upload hosts to upload media to */
        customUploadHosts: MediaConnInfo['hosts']
        /** time to wait between sending new retry requests */
        retryRequestDelayMs: number
        /** time to wait for the generation of the next QR in ms */
        qrTimeout?: number;
        /** provide an auth state object to maintain the auth state */
        auth: AuthenticationState
        /** manage history processing with this control; by default will sync up everything */
        shouldSyncHistoryMessage: (msg: proto.Message.IHistorySyncNotification) => boolean
        /** transaction capability options for SignalKeyStore */
        transactionOpts: TransactionCapabilityOptions
        /** provide a cache to store a user's device list */
        userDevicesCache?: NodeCache
        /** marks the client as online whenever the socket successfully connects */
        markOnlineOnConnect: boolean
        /**
         * map to store the retry counts for failed messages;
         * used to determine whether to retry a message or not */
        msgRetryCounterMap?: MessageRetryMap
        /** width for link preview images */
        linkPreviewImageThumbnailWidth: number
        /** Should Baileys ask the phone for full history, will be received async */
        syncFullHistory: boolean
        /** Should baileys fire init queries automatically, default true */
        fireInitQueries: boolean
        /**
         * generate a high quality link preview,
         * entails uploading the jpegThumbnail to WA
         * */
        generateHighQualityLinkPreview: boolean
    
        /** options for axios */
        options: AxiosRequestConfig<any>
        /**
         * fetch a message from your store
         * implement this so that messages failed to send (solves the "this message can take a while" issue) can be retried
         * */
        getMessage: (key: proto.IMessageKey) => Promise<proto.IMessage | undefined>
    }
    _5

  • Untuk menanyakan metadata grup

    type SocketConfig = {
        /** the WS url to connect to WA */
        waWebSocketUrl: string | URL
        /** Fails the connection if the socket times out in this interval */
    	connectTimeoutMs: number
        /** Default timeout for queries, undefined for no timeout */
        defaultQueryTimeoutMs: number | undefined
        /** ping-pong interval for WS connection */
        keepAliveIntervalMs: number
        /** proxy agent */
    	agent?: Agent
        /** pino logger */
    	logger: Logger
        /** version to connect with */
        version: WAVersion
        /** override browser config */
    	browser: WABrowserDescription
    	/** agent used for fetch requests -- uploading/downloading media */
    	fetchAgent?: Agent
        /** should the QR be printed in the terminal */
        printQRInTerminal: boolean
        /** should events be emitted for actions done by this socket connection */
        emitOwnEvents: boolean
        /** provide a cache to store media, so does not have to be re-uploaded */
        mediaCache?: NodeCache
        /** custom upload hosts to upload media to */
        customUploadHosts: MediaConnInfo['hosts']
        /** time to wait between sending new retry requests */
        retryRequestDelayMs: number
        /** time to wait for the generation of the next QR in ms */
        qrTimeout?: number;
        /** provide an auth state object to maintain the auth state */
        auth: AuthenticationState
        /** manage history processing with this control; by default will sync up everything */
        shouldSyncHistoryMessage: (msg: proto.Message.IHistorySyncNotification) => boolean
        /** transaction capability options for SignalKeyStore */
        transactionOpts: TransactionCapabilityOptions
        /** provide a cache to store a user's device list */
        userDevicesCache?: NodeCache
        /** marks the client as online whenever the socket successfully connects */
        markOnlineOnConnect: boolean
        /**
         * map to store the retry counts for failed messages;
         * used to determine whether to retry a message or not */
        msgRetryCounterMap?: MessageRetryMap
        /** width for link preview images */
        linkPreviewImageThumbnailWidth: number
        /** Should Baileys ask the phone for full history, will be received async */
        syncFullHistory: boolean
        /** Should baileys fire init queries automatically, default true */
        fireInitQueries: boolean
        /**
         * generate a high quality link preview,
         * entails uploading the jpegThumbnail to WA
         * */
        generateHighQualityLinkPreview: boolean
    
        /** options for axios */
        options: AxiosRequestConfig<any>
        /**
         * fetch a message from your store
         * implement this so that messages failed to send (solves the "this message can take a while" issue) can be retried
         * */
        getMessage: (key: proto.IMessageKey) => Promise<proto.IMessage | undefined>
    }
    _6

  • Untuk bergabung dengan grup menggunakan kode undangan

    type SocketConfig = {
        /** the WS url to connect to WA */
        waWebSocketUrl: string | URL
        /** Fails the connection if the socket times out in this interval */
    	connectTimeoutMs: number
        /** Default timeout for queries, undefined for no timeout */
        defaultQueryTimeoutMs: number | undefined
        /** ping-pong interval for WS connection */
        keepAliveIntervalMs: number
        /** proxy agent */
    	agent?: Agent
        /** pino logger */
    	logger: Logger
        /** version to connect with */
        version: WAVersion
        /** override browser config */
    	browser: WABrowserDescription
    	/** agent used for fetch requests -- uploading/downloading media */
    	fetchAgent?: Agent
        /** should the QR be printed in the terminal */
        printQRInTerminal: boolean
        /** should events be emitted for actions done by this socket connection */
        emitOwnEvents: boolean
        /** provide a cache to store media, so does not have to be re-uploaded */
        mediaCache?: NodeCache
        /** custom upload hosts to upload media to */
        customUploadHosts: MediaConnInfo['hosts']
        /** time to wait between sending new retry requests */
        retryRequestDelayMs: number
        /** time to wait for the generation of the next QR in ms */
        qrTimeout?: number;
        /** provide an auth state object to maintain the auth state */
        auth: AuthenticationState
        /** manage history processing with this control; by default will sync up everything */
        shouldSyncHistoryMessage: (msg: proto.Message.IHistorySyncNotification) => boolean
        /** transaction capability options for SignalKeyStore */
        transactionOpts: TransactionCapabilityOptions
        /** provide a cache to store a user's device list */
        userDevicesCache?: NodeCache
        /** marks the client as online whenever the socket successfully connects */
        markOnlineOnConnect: boolean
        /**
         * map to store the retry counts for failed messages;
         * used to determine whether to retry a message or not */
        msgRetryCounterMap?: MessageRetryMap
        /** width for link preview images */
        linkPreviewImageThumbnailWidth: number
        /** Should Baileys ask the phone for full history, will be received async */
        syncFullHistory: boolean
        /** Should baileys fire init queries automatically, default true */
        fireInitQueries: boolean
        /**
         * generate a high quality link preview,
         * entails uploading the jpegThumbnail to WA
         * */
        generateHighQualityLinkPreview: boolean
    
        /** options for axios */
        options: AxiosRequestConfig<any>
        /**
         * fetch a message from your store
         * implement this so that messages failed to send (solves the "this message can take a while" issue) can be retried
         * */
        getMessage: (key: proto.IMessageKey) => Promise<proto.IMessage | undefined>
    }
    _7

    Tentu saja, ganti
    export type BaileysEventMap = {
        /** connection state has been updated -- WS closed, opened, connecting etc. */
    	'connection.update': Partial<ConnectionState>
        /** credentials updated -- some metadata, keys or something */
        'creds.update': Partial<AuthenticationCreds>
        /** history sync, everything is reverse chronologically sorted */
        'messaging-history.set': {
            chats: Chat[]
            contacts: Contact[]
            messages: WAMessage[]
            isLatest: boolean
        }
        /** upsert chats */
        'chats.upsert': Chat[]
        /** update the given chats */
        'chats.update': Partial<Chat>[]
        /** delete chats with given ID */
        'chats.delete': string[]
        /** presence of contact in a chat updated */
        'presence.update': { id: string, presences: { [participant: string]: PresenceData } }
    
        'contacts.upsert': Contact[]
        'contacts.update': Partial<Contact>[]
    
        'messages.delete': { keys: WAMessageKey[] } | { jid: string, all: true }
        'messages.update': WAMessageUpdate[]
        'messages.media-update': { key: WAMessageKey, media?: { ciphertext: Uint8Array, iv: Uint8Array }, error?: Boom }[]
        /**
         * add/update the given messages. If they were received while the connection was online,
         * the update will have type: "notify"
         *  */
        'messages.upsert': { messages: WAMessage[], type: MessageUpsertType }
        /** message was reacted to. If reaction was removed -- then "reaction.text" will be falsey */
        'messages.reaction': { key: WAMessageKey, reaction: proto.IReaction }[]
    
        'message-receipt.update': MessageUserReceiptUpdate[]
    
        'groups.upsert': GroupMetadata[]
        'groups.update': Partial<GroupMetadata>[]
        /** apply an action to participants in a group */
        'group-participants.update': { id: string, participants: string[], action: ParticipantAction }
    
        'blocklist.set': { blocklist: string[] }
        'blocklist.update': { blocklist: string[], type: 'add' | 'remove' }
        /** Receive an update on a call, including when the call was received, rejected, accepted */
        'call': WACallEvent[]
    }
    _6 dengan kode undangan
  • Untuk mendapatkan info grup dengan kode undangan

    type SocketConfig = {
        /** the WS url to connect to WA */
        waWebSocketUrl: string | URL
        /** Fails the connection if the socket times out in this interval */
    	connectTimeoutMs: number
        /** Default timeout for queries, undefined for no timeout */
        defaultQueryTimeoutMs: number | undefined
        /** ping-pong interval for WS connection */
        keepAliveIntervalMs: number
        /** proxy agent */
    	agent?: Agent
        /** pino logger */
    	logger: Logger
        /** version to connect with */
        version: WAVersion
        /** override browser config */
    	browser: WABrowserDescription
    	/** agent used for fetch requests -- uploading/downloading media */
    	fetchAgent?: Agent
        /** should the QR be printed in the terminal */
        printQRInTerminal: boolean
        /** should events be emitted for actions done by this socket connection */
        emitOwnEvents: boolean
        /** provide a cache to store media, so does not have to be re-uploaded */
        mediaCache?: NodeCache
        /** custom upload hosts to upload media to */
        customUploadHosts: MediaConnInfo['hosts']
        /** time to wait between sending new retry requests */
        retryRequestDelayMs: number
        /** time to wait for the generation of the next QR in ms */
        qrTimeout?: number;
        /** provide an auth state object to maintain the auth state */
        auth: AuthenticationState
        /** manage history processing with this control; by default will sync up everything */
        shouldSyncHistoryMessage: (msg: proto.Message.IHistorySyncNotification) => boolean
        /** transaction capability options for SignalKeyStore */
        transactionOpts: TransactionCapabilityOptions
        /** provide a cache to store a user's device list */
        userDevicesCache?: NodeCache
        /** marks the client as online whenever the socket successfully connects */
        markOnlineOnConnect: boolean
        /**
         * map to store the retry counts for failed messages;
         * used to determine whether to retry a message or not */
        msgRetryCounterMap?: MessageRetryMap
        /** width for link preview images */
        linkPreviewImageThumbnailWidth: number
        /** Should Baileys ask the phone for full history, will be received async */
        syncFullHistory: boolean
        /** Should baileys fire init queries automatically, default true */
        fireInitQueries: boolean
        /**
         * generate a high quality link preview,
         * entails uploading the jpegThumbnail to WA
         * */
        generateHighQualityLinkPreview: boolean
    
        /** options for axios */
        options: AxiosRequestConfig<any>
        /**
         * fetch a message from your store
         * implement this so that messages failed to send (solves the "this message can take a while" issue) can be retried
         * */
        getMessage: (key: proto.IMessageKey) => Promise<proto.IMessage | undefined>
    }
    _8

  • Untuk bergabung dengan grup menggunakan groupInviteMessage

    type SocketConfig = {
        /** the WS url to connect to WA */
        waWebSocketUrl: string | URL
        /** Fails the connection if the socket times out in this interval */
    	connectTimeoutMs: number
        /** Default timeout for queries, undefined for no timeout */
        defaultQueryTimeoutMs: number | undefined
        /** ping-pong interval for WS connection */
        keepAliveIntervalMs: number
        /** proxy agent */
    	agent?: Agent
        /** pino logger */
    	logger: Logger
        /** version to connect with */
        version: WAVersion
        /** override browser config */
    	browser: WABrowserDescription
    	/** agent used for fetch requests -- uploading/downloading media */
    	fetchAgent?: Agent
        /** should the QR be printed in the terminal */
        printQRInTerminal: boolean
        /** should events be emitted for actions done by this socket connection */
        emitOwnEvents: boolean
        /** provide a cache to store media, so does not have to be re-uploaded */
        mediaCache?: NodeCache
        /** custom upload hosts to upload media to */
        customUploadHosts: MediaConnInfo['hosts']
        /** time to wait between sending new retry requests */
        retryRequestDelayMs: number
        /** time to wait for the generation of the next QR in ms */
        qrTimeout?: number;
        /** provide an auth state object to maintain the auth state */
        auth: AuthenticationState
        /** manage history processing with this control; by default will sync up everything */
        shouldSyncHistoryMessage: (msg: proto.Message.IHistorySyncNotification) => boolean
        /** transaction capability options for SignalKeyStore */
        transactionOpts: TransactionCapabilityOptions
        /** provide a cache to store a user's device list */
        userDevicesCache?: NodeCache
        /** marks the client as online whenever the socket successfully connects */
        markOnlineOnConnect: boolean
        /**
         * map to store the retry counts for failed messages;
         * used to determine whether to retry a message or not */
        msgRetryCounterMap?: MessageRetryMap
        /** width for link preview images */
        linkPreviewImageThumbnailWidth: number
        /** Should Baileys ask the phone for full history, will be received async */
        syncFullHistory: boolean
        /** Should baileys fire init queries automatically, default true */
        fireInitQueries: boolean
        /**
         * generate a high quality link preview,
         * entails uploading the jpegThumbnail to WA
         * */
        generateHighQualityLinkPreview: boolean
    
        /** options for axios */
        options: AxiosRequestConfig<any>
        /**
         * fetch a message from your store
         * implement this so that messages failed to send (solves the "this message can take a while" issue) can be retried
         * */
        getMessage: (key: proto.IMessageKey) => Promise<proto.IMessage | undefined>
    }
    _9

    Tentu saja, ganti
    export type BaileysEventMap = {
        /** connection state has been updated -- WS closed, opened, connecting etc. */
    	'connection.update': Partial<ConnectionState>
        /** credentials updated -- some metadata, keys or something */
        'creds.update': Partial<AuthenticationCreds>
        /** history sync, everything is reverse chronologically sorted */
        'messaging-history.set': {
            chats: Chat[]
            contacts: Contact[]
            messages: WAMessage[]
            isLatest: boolean
        }
        /** upsert chats */
        'chats.upsert': Chat[]
        /** update the given chats */
        'chats.update': Partial<Chat>[]
        /** delete chats with given ID */
        'chats.delete': string[]
        /** presence of contact in a chat updated */
        'presence.update': { id: string, presences: { [participant: string]: PresenceData } }
    
        'contacts.upsert': Contact[]
        'contacts.update': Partial<Contact>[]
    
        'messages.delete': { keys: WAMessageKey[] } | { jid: string, all: true }
        'messages.update': WAMessageUpdate[]
        'messages.media-update': { key: WAMessageKey, media?: { ciphertext: Uint8Array, iv: Uint8Array }, error?: Boom }[]
        /**
         * add/update the given messages. If they were received while the connection was online,
         * the update will have type: "notify"
         *  */
        'messages.upsert': { messages: WAMessage[], type: MessageUpsertType }
        /** message was reacted to. If reaction was removed -- then "reaction.text" will be falsey */
        'messages.reaction': { key: WAMessageKey, reaction: proto.IReaction }[]
    
        'message-receipt.update': MessageUserReceiptUpdate[]
    
        'groups.upsert': GroupMetadata[]
        'groups.update': Partial<GroupMetadata>[]
        /** apply an action to participants in a group */
        'group-participants.update': { id: string, participants: string[], action: ParticipantAction }
    
        'blocklist.set': { blocklist: string[] }
        'blocklist.update': { blocklist: string[], type: 'add' | 'remove' }
        /** Receive an update on a call, including when the call was received, rejected, accepted */
        'call': WACallEvent[]
    }
    _6 dengan kode undangan

Daftar Siaran & Cerita

Catatan. pesan saat ini tidak dapat dikirim ke daftar siaran dari versi MD

  • Anda dapat mengirim pesan ke daftar siaran dengan cara yang sama seperti mengirim pesan ke grup & obrolan individual
  • Saat ini, WA Web tidak mendukung pembuatan daftar siaran, tetapi Anda masih dapat menghapusnya
  • ID siaran dalam format
    export type BaileysEventMap = {
        /** connection state has been updated -- WS closed, opened, connecting etc. */
    	'connection.update': Partial<ConnectionState>
        /** credentials updated -- some metadata, keys or something */
        'creds.update': Partial<AuthenticationCreds>
        /** history sync, everything is reverse chronologically sorted */
        'messaging-history.set': {
            chats: Chat[]
            contacts: Contact[]
            messages: WAMessage[]
            isLatest: boolean
        }
        /** upsert chats */
        'chats.upsert': Chat[]
        /** update the given chats */
        'chats.update': Partial<Chat>[]
        /** delete chats with given ID */
        'chats.delete': string[]
        /** presence of contact in a chat updated */
        'presence.update': { id: string, presences: { [participant: string]: PresenceData } }
    
        'contacts.upsert': Contact[]
        'contacts.update': Partial<Contact>[]
    
        'messages.delete': { keys: WAMessageKey[] } | { jid: string, all: true }
        'messages.update': WAMessageUpdate[]
        'messages.media-update': { key: WAMessageKey, media?: { ciphertext: Uint8Array, iv: Uint8Array }, error?: Boom }[]
        /**
         * add/update the given messages. If they were received while the connection was online,
         * the update will have type: "notify"
         *  */
        'messages.upsert': { messages: WAMessage[], type: MessageUpsertType }
        /** message was reacted to. If reaction was removed -- then "reaction.text" will be falsey */
        'messages.reaction': { key: WAMessageKey, reaction: proto.IReaction }[]
    
        'message-receipt.update': MessageUserReceiptUpdate[]
    
        'groups.upsert': GroupMetadata[]
        'groups.update': Partial<GroupMetadata>[]
        /** apply an action to participants in a group */
        'group-participants.update': { id: string, participants: string[], action: ParticipantAction }
    
        'blocklist.set': { blocklist: string[] }
        'blocklist.update': { blocklist: string[], type: 'add' | 'remove' }
        /** Receive an update on a call, including when the call was received, rejected, accepted */
        'call': WACallEvent[]
    }
    8
  • Untuk menanyakan penerima & nama daftar siaran

    const conn = makeWASocket({
        ...otherOpts,
        // can use Windows, Ubuntu here too
        browser: Browsers.macOS('Desktop'),
        syncFullHistory: true
    })
    0

Baileys ditulis dengan mempertimbangkan fungsionalitas khusus. Alih-alih membagi proyek & menulis ulang bagian dalamnya, Anda cukup menulis ekstensi Anda sendiri

Pertama, aktifkan pencatatan pesan tidak tertangani dari WhatsApp dengan pengaturan

const conn = makeWASocket({
    ...otherOpts,
    // can use Windows, Ubuntu here too
    browser: Browsers.macOS('Desktop'),
    syncFullHistory: true
})
_1

Ini akan memungkinkan Anda untuk melihat semua jenis pesan yang dikirim WhatsApp di konsol

Beberapa contoh

  1. Fungsionalitas untuk melacak persentase baterai ponsel Anda. Anda mengaktifkan logging dan Anda akan melihat pesan tentang baterai Anda muncul di konsol.

    export type BaileysEventMap = {
        /** connection state has been updated -- WS closed, opened, connecting etc. */
    	'connection.update': Partial<ConnectionState>
        /** credentials updated -- some metadata, keys or something */
        'creds.update': Partial<AuthenticationCreds>
        /** history sync, everything is reverse chronologically sorted */
        'messaging-history.set': {
            chats: Chat[]
            contacts: Contact[]
            messages: WAMessage[]
            isLatest: boolean
        }
        /** upsert chats */
        'chats.upsert': Chat[]
        /** update the given chats */
        'chats.update': Partial<Chat>[]
        /** delete chats with given ID */
        'chats.delete': string[]
        /** presence of contact in a chat updated */
        'presence.update': { id: string, presences: { [participant: string]: PresenceData } }
    
        'contacts.upsert': Contact[]
        'contacts.update': Partial<Contact>[]
    
        'messages.delete': { keys: WAMessageKey[] } | { jid: string, all: true }
        'messages.update': WAMessageUpdate[]
        'messages.media-update': { key: WAMessageKey, media?: { ciphertext: Uint8Array, iv: Uint8Array }, error?: Boom }[]
        /**
         * add/update the given messages. If they were received while the connection was online,
         * the update will have type: "notify"
         *  */
        'messages.upsert': { messages: WAMessage[], type: MessageUpsertType }
        /** message was reacted to. If reaction was removed -- then "reaction.text" will be falsey */
        'messages.reaction': { key: WAMessageKey, reaction: proto.IReaction }[]
    
        'message-receipt.update': MessageUserReceiptUpdate[]
    
        'groups.upsert': GroupMetadata[]
        'groups.update': Partial<GroupMetadata>[]
        /** apply an action to participants in a group */
        'group-participants.update': { id: string, participants: string[], action: ParticipantAction }
    
        'blocklist.set': { blocklist: string[] }
        'blocklist.update': { blocklist: string[], type: 'add' | 'remove' }
        /** Receive an update on a call, including when the call was received, rejected, accepted */
        'call': WACallEvent[]
    }
    _9

    "Bingkai" adalah pesan yang diterima, ia memiliki tiga komponen

    • const sock = makeWASocket()
      sock.ev.on('messages.upsert', ({ messages }) => {
          console.log('got messages', messages)
      })
      0 -- tentang apa bingkai ini (mis. pesan akan memiliki "pesan")
    • const sock = makeWASocket()
      sock.ev.on('messages.upsert', ({ messages }) => {
          console.log('got messages', messages)
      })
      1 -- pasangan kunci-nilai string dengan beberapa metadata (biasanya berisi ID pesan)
    • const sock = makeWASocket()
      sock.ev.on('messages.upsert', ({ messages }) => {
          console.log('got messages', messages)
      })
      2 -- data sebenarnya (mis. node pesan akan memiliki konten pesan aktual di dalamnya)
    • baca lebih lanjut tentang format ini di sini

    Anda dapat mendaftarkan panggilan balik untuk suatu acara menggunakan yang berikut ini

    const conn = makeWASocket({
        ...otherOpts,
        // can use Windows, Ubuntu here too
        browser: Browsers.macOS('Desktop'),
        syncFullHistory: true
    })
    _2

Catatan

Perpustakaan ini awalnya merupakan proyek untuk CS-2362 di Universitas Ashoka dan sama sekali tidak berafiliasi dengan WhatsApp. Gunakan atas kebijaksanaan Anda sendiri. Jangan spam orang dengan ini