### Handle Connection State and QR Code Source: https://context7.com/whiskeysockets/baileyscsharp/llms.txt Handles connection state updates, displays QR codes for initial pairing, and manages reconnection logic. Ensure you have the QRCoder library installed for QR code generation. ```csharp using BaileysCSharp.Core.Types; using BaileysCSharp.Exceptions; using QRCoder; private static void OnConnectionUpdate(object? sender, ConnectionState state) { // Display QR code in the terminal on first login if (state.QR != null) { var qrGenerator = new QRCodeGenerator(); var qrData = qrGenerator.CreateQrCode(state.QR, QRCodeGenerator.ECCLevel.L); var ascii = new AsciiQRCode(qrData); Console.WriteLine(ascii.GetGraphic(1)); Console.WriteLine("Scan the QR code with WhatsApp on your phone."); return; } if (state.Connection == WAConnectionState.Open) { Console.WriteLine("Connected to WhatsApp!"); } if (state.Connection == WAConnectionState.Close) { // Reconnect unless the session was explicitly logged out if (state.LastDisconnect?.Error is Boom boom && boom.Data?.StatusCode != (int)DisconnectReason.LoggedOut) { Console.WriteLine($"Disconnected ({boom.Message}), reconnecting …"); Thread.Sleep(2000); socket.MakeSocket(); } else { Console.WriteLine("Logged out. Delete creds.json and restart to re-pair."); } } } ``` -------------------------------- ### Create and connect a socket Source: https://context7.com/whiskeysockets/baileyscsharp/llms.txt Instantiates the full socket stack, handles WebSocket lifecycle events, performs the Noise protocol handshake, and starts the keep-alive thread. This must be called after authentication is configured. ```APIDOC ## Create and connect a socket — `WASocket` / `MakeSocket()` ### Description Instantiates the full socket stack, wires up all WebSocket lifecycle events, performs the Noise protocol handshake, and starts the keep-alive thread. Must be called after `SocketConfig.Auth` is set. ### Method Signature `WASocket(SocketConfig config)` `socket.MakeSocket()` ### Usage Example ```csharp using BaileysCSharp.Core.Sockets; using BaileysCSharp.Core.Models; using BaileysCSharp.Core.Logging; var config = new SocketConfig { SessionName = "my-session", Logger = { Level = LogLevel.Info }, MarkOnlineOnConnect = true, FireInitQueries = true, // fetch privacy settings & props on connect Auth = new AuthenticationState { Creds = authentication, Keys = keys } // Assuming 'authentication' and 'keys' are already initialized }; var socket = new WASocket(config); // Wire up events before connecting socket.EV.Connection.Update += OnConnectionUpdate; socket.EV.Auth.Update += OnAuthUpdate; socket.EV.Message.Upsert += OnMessageUpsert; // Connect — non-blocking; events arrive asynchronously socket.MakeSocket(); Console.ReadLine(); // keep the process alive // Graceful shutdown socket.Dispose(); ``` ``` -------------------------------- ### Create and Connect WASocket - BaileysCSharp Source: https://context7.com/whiskeysockets/baileyscsharp/llms.txt Instantiates the full socket stack, wires up WebSocket events, performs the Noise protocol handshake, and starts the keep-alive thread. Must be called after SocketConfig.Auth is set. Events are handled asynchronously. ```csharp using BaileysCSharp.Core.Sockets; using BaileysCSharp.Core.Models; using BaileysCSharp.Core.Logging; var config = new SocketConfig { SessionName = "my-session", Logger = { Level = LogLevel.Info }, MarkOnlineOnConnect = true, FireInitQueries = true, // fetch privacy settings & props on connect Auth = new AuthenticationState { Creds = authentication, Keys = keys } }; var socket = new WASocket(config); // Wire up events before connecting socket.EV.Connection.Update += OnConnectionUpdate; socket.EV.Auth.Update += OnAuthUpdate; socket.EV.Message.Upsert += OnMessageUpsert; // Connect — non-blocking; events arrive asynchronously socket.MakeSocket(); Console.ReadLine(); // keep the process alive // Graceful shutdown socket.Dispose(); ``` -------------------------------- ### Manage WhatsApp Newsletters (Channels) Source: https://context7.com/whiskeysockets/baileyscsharp/llms.txt Perform operations related to WhatsApp Channels, including creation, updating name and description, getting admin count, sending messages, following/unfollowing, muting/unmuting, querying recommendations, and deleting channels. ```csharp // Create a new channel var channel = await socket.NewsletterCreate("My Dev Channel"); Console.WriteLine($"Channel ID: {channel.Id}"); // Update name and description await socket.NewsletterUpdateName(channel.Id, "My Dev Channel – Official"); await socket.NewsletterUpdateDescription(channel.Id, "Daily C# tips and tricks"); // Get admin count var adminCount = await socket.NewsletterAdminCount(channel.Id); Console.WriteLine($"Admins: {adminCount}"); // Send a text message to the channel await socket.SendNewsletterMessage(channel.Id, new NewsletterTextMessage { Text = "Hello, subscribers!" }); // Follow / unfollow / mute / unmute await socket.NewsletterFollow(channel.Id); await socket.NewsletterMute(channel.Id); await socket.NewsletterUnMute(channel.Id); await socket.NewsletterUnFollow(channel.Id); // Query recommended newsletters var recommended = await socket.QueryRecommendedNewsletters(); foreach (var item in recommended?.Newsletters ?? []) { Console.WriteLine($"{item.ThreadMetadata?.Name}: {item.ThreadMetadata?.SubscriberCount} subscribers"); } // Delete the channel await socket.NewsletterDelete(channel.Id); ``` -------------------------------- ### Retrieve Profile Picture URL Source: https://context7.com/whiskeysockets/baileyscsharp/llms.txt Get the CDN URL for a contact's or group's profile picture. Supports fetching both a preview thumbnail and the full-resolution image. ```csharp using BaileysCSharp.Core.Types; // Preview thumbnail (default) var previewUrl = await socket.ProfilePictureUrl("15551234567@s.whatsapp.net"); // Full-resolution image var fullUrl = await socket.ProfilePictureUrl( "15551234567@s.whatsapp.net", ProfilePictureUrlType.Image ); if (fullUrl != null) { var bytes = await new HttpClient().GetByteArrayAsync(fullUrl); File.WriteAllBytes("avatar.jpg", bytes); } ``` -------------------------------- ### Initialize Authentication Credentials - BaileysCSharp Source: https://context7.com/whiskeysockets/baileyscsharp/llms.txt Generates cryptographic material for a new WhatsApp Web session or loads existing credentials. Use this when no persisted credentials exist. A file-backed Signal key store is provided. ```csharp using BaileysCSharp.Core.Helper; using BaileysCSharp.Core.Models; using BaileysCSharp.Core.NoSQL; var config = new SocketConfig { SessionName = "my-session", // determines the cache folder name }; var credsFile = Path.Join(config.CacheRoot, "creds.json"); // Load existing credentials, or create new ones AuthenticationCreds authentication; if (File.Exists(credsFile)) { authentication = AuthenticationCreds.Deserialize(File.ReadAllText(credsFile)); Console.WriteLine("Loaded existing credentials"); } else { authentication = AuthenticationUtils.InitAuthCreds(); Console.WriteLine("Created fresh credentials – QR scan required"); } // File-backed Signal key store (session keys, pre-keys, sender keys …) BaseKeyStore keys = new FileKeyStore(config.CacheRoot); config.Auth = new AuthenticationState { Creds = authentication, Keys = keys }; ``` -------------------------------- ### `FileKeyStore` — file-backed Signal key storage Source: https://context7.com/whiskeysockets/baileyscsharp/llms.txt Persists Signal pre-keys, session keys, and sender-key state to the local filesystem. ```APIDOC ## FileKeyStore ### Description Provides a file-backed storage mechanism for Signal protocol keys, including pre-keys, session keys, and sender-key state. Keys are organized into named subdirectories under a specified cache root directory. ### Usage Instantiate `FileKeyStore` with a path to a writable directory. The socket stack automatically uses this store for key persistence. You can also interact with the store directly to inspect or manually set key values. ### Methods - `FileKeyStore(string cacheRoot)`: Constructor to initialize the store with a root directory path. - `Get(string id)`: Retrieves a single key record of type `T` by its ID. - `Get(IEnumerable ids)`: Retrieves multiple key records of type `T` by a collection of IDs. - `Set(string id, T value)`: Sets a key record of type `T` with the given ID and value. ### Request Example ```csharp using BaileysCSharp.Core.NoSQL; // Instantiate pointing at a writable directory var store = new FileKeyStore("/var/myapp/session-keys"); // Keys are read/written automatically by the socket stack. // You can also read them directly for inspection: var sessionRecord = store.Get("15551234567.0"); Console.WriteLine(sessionRecord != null ? "Session exists" : "No session yet"); // Set a value manually (advanced use) store.Set("120363@g.us", senderKeyRecord); // Retrieve multiple keys in one call var ids = new List { "15551234567.0", "15559876543.0" }; var sessions = store.Get(ids); Console.WriteLine($"Loaded {sessions.Count} sessions"); ``` ### Response - `Get` methods return the requested key records or null/empty collections if not found. - `Set` methods do not return a value upon successful operation. ``` -------------------------------- ### Initialize authentication credentials Source: https://context7.com/whiskeysockets/baileyscsharp/llms.txt Generates cryptographic material for a new WhatsApp Web session or loads existing credentials. This is a prerequisite for establishing a connection. ```APIDOC ## Initialize authentication credentials — `AuthenticationUtils.InitAuthCreds()` ### Description Generates all cryptographic material (noise keys, identity key, signed pre-key, registration ID, ADV secret) needed for a fresh WhatsApp Web session. Call this only when no persisted credentials exist; otherwise, deserialize saved credentials from disk. ### Method Signature `AuthenticationUtils.InitAuthCreds()` ### Usage Example ```csharp using BaileysCSharp.Core.Helper; using BaileysCSharp.Core.Models; using BaileysCSharp.Core.NoSQL; var config = new SocketConfig { SessionName = "my-session", // determines the cache folder name }; var credsFile = Path.Join(config.CacheRoot, "creds.json"); // Load existing credentials, or create new ones AuthenticationCreds authentication; if (File.Exists(credsFile)) { authentication = AuthenticationCreds.Deserialize(File.ReadAllText(credsFile)); Console.WriteLine("Loaded existing credentials"); } else { authentication = AuthenticationUtils.InitAuthCreds(); Console.WriteLine("Created fresh credentials – QR scan required"); } // File-backed Signal key store (session keys, pre-keys, sender keys …) BaseKeyStore keys = new FileKeyStore(config.CacheRoot); config.Auth = new AuthenticationState { Creds = authentication, Keys = keys }; ``` ``` -------------------------------- ### File-Backed Signal Key Storage Source: https://context7.com/whiskeysockets/baileyscsharp/llms.txt Utilize `FileKeyStore` for persisting Signal pre-keys, session keys, and sender-key state to the local filesystem. Keys are organized into subdirectories under a specified cache root. This store is automatically used by the socket stack, but keys can also be read or set manually for inspection or advanced use. ```csharp using BaileysCSharp.Core.NoSQL; // Instantiate pointing at a writable directory var store = new FileKeyStore("/var/myapp/session-keys"); // Keys are read/written automatically by the socket stack. // You can also read them directly for inspection: var sessionRecord = store.Get("15551234567.0"); Console.WriteLine(sessionRecord != null ? "Session exists" : "No session yet"); // Set a value manually (advanced use) store.Set("120363@g.us", senderKeyRecord); // Retrieve multiple keys in one call var ids = new List { "15551234567.0", "15559876543.0" }; var sessions = store.Get(ids); Console.WriteLine($"Loaded {sessions.Count} sessions"); ``` -------------------------------- ### Send Media Messages (Image, Audio, Video, Document) Source: https://context7.com/whiskeysockets/baileyscsharp/llms.txt Sends various media types including images, audio (voice notes), videos, and documents. Accepts any readable stream and auto-generates thumbnails. Ensure media files exist at the specified paths. ```csharp using BaileysCSharp.Core.Models.Sending.Media; var recipient = "15551234567@s.whatsapp.net"; // --- Image --- await socket.SendMessage(recipient, new ImageMessageContent { Image = File.OpenRead("photo.jpg"), Caption = "Check out this picture!" }); // --- Audio (voice note) --- await socket.SendMessage(recipient, new AudioMessageContent { Audio = File.OpenRead("voice.ogg"), Ptt = true // true = voice-note UI, false = music player }); // --- Video (or animated GIF) --- await socket.SendMessage(recipient, new VideoMessageContent { Video = File.OpenRead("clip.mp4"), Caption = "Funny clip", GifPlayback = false }); // --- Document --- await socket.SendMessage(recipient, new DocumentMessageContent { Document = File.OpenRead("report.pdf"), FileName = "Q1-Report.pdf", Mimetype = "application/pdf" }); ``` -------------------------------- ### Manage presence and subscribe to updates Source: https://context7.com/whiskeysockets/baileyscsharp/llms.txt Broadcasts presence status (online, offline, typing, recording) and subscribes to a contact's presence. Also includes an event handler for receiving presence updates. ```csharp using BaileysCSharp.Core.Types; // Broadcast typing indicator to a chat socket.SendPresenceUpdate(WAPresence.Composing, "15551234567@s.whatsapp.net"); // Broadcast recording indicator socket.SendPresenceUpdate(WAPresence.Recording, "15551234567@s.whatsapp.net"); // Mark yourself as available globally socket.SendPresenceUpdate(WAPresence.Available); // Subscribe to a contact's presence (tcToken obtained from contact data) socket.PresenceSubscribe("15551234567@s.whatsapp.net", tcToken); // Receive presence events socket.EV.Pressence.Update += (sender, model) => { foreach (var (participant, data) in model.Presences) { Console.WriteLine($"{participant}: {data.LastKnownPresence} (last seen: {data.LastSeen})"); } }; ``` -------------------------------- ### Handle connection state and QR code — EV.Connection.Update Source: https://context7.com/whiskeysockets/baileyscsharp/llms.txt This event handler manages the connection state with WhatsApp. It displays a QR code for initial pairing, indicates when the connection is open, and handles disconnections, including automatic reconnection logic. ```APIDOC ## EV.Connection.Update ### Description Handles the connection state updates from the WhatsApp service. This includes displaying QR codes for pairing, notifying when the connection is open, and managing disconnections with automatic reconnection attempts. ### Event Handler `OnConnectionUpdate(object? sender, ConnectionState state)` ### Usage This event is triggered by the `BaileysCSharp` library to inform the application about changes in the connection status. ### Example ```csharp private static void OnConnectionUpdate(object? sender, ConnectionState state) { // Display QR code in the terminal on first login if (state.QR != null) { // QR code generation and display logic here Console.WriteLine("Scan the QR code with WhatsApp on your phone."); return; } if (state.Connection == WAConnectionState.Open) { Console.WriteLine("Connected to WhatsApp!"); } if (state.Connection == WAConnectionState.Close) { // Reconnect logic here Console.WriteLine("Disconnected, reconnecting …"); Thread.Sleep(2000); socket.MakeSocket(); } } ``` ``` -------------------------------- ### Presence updates Source: https://context7.com/whiskeysockets/baileyscsharp/llms.txt Broadcast your own presence and subscribe to the presence of any contact using `SendPresenceUpdate`, `PresenceSubscribe`, and `EV.Pressence.Update`. ```APIDOC ## Presence updates — `SendPresenceUpdate` / `PresenceSubscribe` / `EV.Pressence.Update` ### Description Broadcast your own presence (online/offline/typing/recording) and subscribe to the presence of any contact. ### Methods - `SendPresenceUpdate` - `PresenceSubscribe` - `EV.Pressence.Update` (Event) ### Parameters #### SendPresenceUpdate - **presence** (WAPresence) - Required - The presence status to broadcast (e.g., Composing, Recording, Available). - **toJid** (string) - Optional - The JID of the contact to send the presence update to. If not provided, it's broadcast globally. #### PresenceSubscribe - **jid** (string) - Required - The JID of the contact to subscribe to. - **tcToken** (string) - Required - The tcToken obtained from contact data for subscription. ``` -------------------------------- ### Download incoming media Source: https://context7.com/whiskeysockets/baileyscsharp/llms.txt Decrypts and downloads any media attached to an incoming `WebMessageInfo` using `DownloadMediaMessage`. ```APIDOC ## Download incoming media — `DownloadMediaMessage` ### Description Decrypts and downloads any media attached to an incoming `WebMessageInfo`. Returns the raw bytes, MIME type, and filename (for documents). ### Method `DownloadMediaMessage` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **msg.Message** (WebMessageInfo) - Required - The message containing the media. ``` -------------------------------- ### Persist Credentials Source: https://context7.com/whiskeysockets/baileyscsharp/llms.txt Saves authentication credentials to a file whenever they are updated. It's crucial to serialize and save immediately to prevent session loss. Use a lock to ensure thread-safe writing. ```csharp private static void OnAuthUpdate(object? sender, AuthenticationCreds creds) { var path = Path.Join(socket.SocketConfig.CacheRoot, "creds.json"); // Serialize is thread-safe; use a lock when writing from multiple threads lock (locker) { File.WriteAllText(path, AuthenticationCreds.Serialize(creds)); } Console.WriteLine("Credentials saved."); } ``` -------------------------------- ### Check WhatsApp registration — `OnWhatsApp` Source: https://context7.com/whiskeysockets/baileyscsharp/llms.txt Verify whether one or more phone numbers have a WhatsApp account before sending. ```APIDOC ## OnWhatsApp ### Description Verify whether one or more phone numbers have a WhatsApp account before sending. ### Method `OnWhatsApp` ### Parameters - `phoneNumbers` (params string[]) - Required - One or more phone numbers to check. ### Request Example ```csharp var results = await socket.OnWhatsApp("+15551234567", "+447911123456"); foreach (var r in results) { Console.WriteLine($"{r.Jid}: exists={r.Exists}, business={r.IsBusiness}"); } ``` ### Response - `results` (IEnumerable) - A collection of results, each indicating if a number exists on WhatsApp and if it's a business account. ``` -------------------------------- ### Group management Source: https://context7.com/whiskeysockets/baileyscsharp/llms.txt Provides full CRUD operations over WhatsApp groups, including creation, participant management, and settings updates. ```APIDOC ## Group management — `GroupCreate`, `GroupParticipantsUpdate`, `GroupMetaData`, etc. ### Description Full CRUD over WhatsApp groups: create, update subject/description, manage participants, invite codes, disappearing messages, and admin settings. ### Methods - `GroupCreate` - `GroupMetaData` - `GroupParticipantsUpdate` - `GroupUpdateSubject` - `GroupUpdateDescription` - `GroupToggleEphemeral` - `GroupInviteCode` - `GroupAcceptInvite` - `GroupLeave` ### Parameters #### GroupCreate - **subject** (string) - Required - The subject of the group. - **participants** (List) - Optional - A list of participant JIDs to add initially. #### GroupMetaData - **jid** (string) - Required - The JID of the group. #### GroupParticipantsUpdate - **jid** (string) - Required - The JID of the group. - **participants** (List) - Required - A list of participant JIDs to update. - **action** (ParticipantAction) - Required - The action to perform (Add, Remove, Promote, Demote). #### GroupUpdateSubject - **jid** (string) - Required - The JID of the group. - **subject** (string) - Required - The new subject of the group. #### GroupUpdateDescription - **jid** (string) - Required - The JID of the group. - **description** (string) - Required - The new description of the group. #### GroupToggleEphemeral - **jid** (string) - Required - The JID of the group. - **duration** (int) - Required - The duration in seconds for disappearing messages. #### GroupInviteCode - **jid** (string) - Required - The JID of the group. #### GroupAcceptInvite - **code** (string) - Required - The invite code of the group. #### GroupLeave - **jid** (string) - Required - The JID of the group. ``` -------------------------------- ### Group management operations Source: https://context7.com/whiskeysockets/baileyscsharp/llms.txt Provides full CRUD operations for WhatsApp groups, including creation, metadata fetching, participant updates, subject/description changes, and invite link management. ```csharp // Create a group with two initial participants var group = await socket.GroupCreate( "Team Alpha", ["15551111111@s.whatsapp.net", "15552222222@s.whatsapp.net"] ); Console.WriteLine($"Group created: {group.ID}"); // Fetch metadata for an existing group var meta = await socket.GroupMetaData("120363000000000001@g.us"); Console.WriteLine($"Group: {meta.Subject}, members: {meta.Size}"); // Add a participant await socket.GroupParticipantsUpdate( group.ID, ["15553333333@s.whatsapp.net"], ParticipantAction.Add ); // Promote to admin await socket.GroupParticipantsUpdate(group.ID, ["15553333333@s.whatsapp.net"], ParticipantAction.Promote); // Update subject and description await socket.GroupUpdateSubject(group.ID, "Team Alpha – Q2"); await socket.GroupUpdateDescription(group.ID, "All things Q2 planning"); // Enable disappearing messages (7 days) await socket.GroupToggleEphemeral(group.ID, 7 * 24 * 60 * 60); // Generate and retrieve invite link var code = await socket.GroupInviteCode(group.ID); Console.WriteLine($"Invite: https://chat.whatsapp.com/{code}"); // Accept an invite by code await socket.GroupAcceptInvite(code); // Leave the group await socket.GroupLeave(group.ID); ``` -------------------------------- ### Check WhatsApp Registration Status Source: https://context7.com/whiskeysockets/baileyscsharp/llms.txt Verify if one or more phone numbers are registered on WhatsApp before sending messages. The output indicates if the number exists and if it's a business account. ```csharp var results = await socket.OnWhatsApp("+15551234567", "+447911123456"); foreach (var r in results) { Console.WriteLine($"{r.Jid}: exists={r.Exists}, business={r.IsBusiness}"); } // Output: // 15551234567@s.whatsapp.net: exists=True, business=False // 447911123456@s.whatsapp.net: exists=True, business=True ``` -------------------------------- ### Send media messages — SendMessage with media content types Source: https://context7.com/whiskeysockets/baileyscsharp/llms.txt Enables sending various media types including images, audio, video, and documents. The library handles media uploading and thumbnail generation automatically. ```APIDOC ## SendMessage with Media Content Types ### Description Sends media messages such as images, audio, video, and documents. The library automatically handles the upload of media to WhatsApp's servers and generates necessary previews or thumbnails. ### Method `SendMessage(string recipientJid, MediaMessageContent message)` ### Parameters - **recipientJid** (string) - The WhatsApp JID of the recipient. - **message** (MediaMessageContent) - An object representing the media message. Specific types include `ImageMessageContent`, `AudioMessageContent`, `VideoMessageContent`, and `DocumentMessageContent`. - **ImageMessageContent**: - **Image** (Stream) - The image file stream. - **Caption** (string) - Optional caption for the image. - **AudioMessageContent**: - **Audio** (Stream) - The audio file stream. - **Ptt** (bool) - Whether to send as a voice note (true) or regular audio (false). - **VideoMessageContent**: - **Video** (Stream) - The video file stream. - **Caption** (string) - Optional caption for the video. - **GifPlayback** (bool) - Whether to play as a GIF. - **DocumentMessageContent**: - **Document** (Stream) - The document file stream. - **FileName** (string) - The name of the document file. - **Mimetype** (string) - The MIME type of the document. ### Request Example ```csharp var recipient = "15551234567@s.whatsapp.net"; // Image await socket.SendMessage(recipient, new ImageMessageContent { Image = File.OpenRead("photo.jpg"), Caption = "Check out this picture!" }); // Audio (voice note) await socket.SendMessage(recipient, new AudioMessageContent { Audio = File.OpenRead("voice.ogg"), Ptt = true }); // Video await socket.SendMessage(recipient, new VideoMessageContent { Video = File.OpenRead("clip.mp4"), Caption = "Funny clip", GifPlayback = false }); // Document await socket.SendMessage(recipient, new DocumentMessageContent { Document = File.OpenRead("report.pdf"), FileName = "Q1-Report.pdf", Mimetype = "application/pdf" }); ``` ### Response - **sent** (MessageSendResult?) - An object containing the key information of the sent message, or null if sending failed. ``` -------------------------------- ### Download incoming media messages Source: https://context7.com/whiskeysockets/baileyscsharp/llms.txt Decrypts and downloads media attached to an incoming message. Handles images, audio, and documents, saving them to files. ```csharp private static async void OnMessageUpsert(object? sender, MessageEventModel e) { if (e.Type != MessageEventType.Notify) return; // skip history sync foreach (var msg in e.Messages) { if (msg.Message == null) continue; if (msg.Message.ImageMessage != null) { var media = await socket.DownloadMediaMessage(msg.Message); var ext = MimeTypeUtils.GetExtension(media.MimeType); // "jpg" File.WriteAllBytes($"received_{msg.Key.Id}.{ext}", media.Data); } if (msg.Message.AudioMessage != null) { var media = await socket.DownloadMediaMessage(msg.Message); File.WriteAllBytes($"audio.{MimeTypeUtils.GetExtension(media.MimeType)}", media.Data); } if (msg.Message.DocumentMessage != null) { var media = await socket.DownloadMediaMessage(msg.Message); File.WriteAllBytes(media.FileName, media.Data); } } } ``` -------------------------------- ### Send Contact and Location Messages Source: https://context7.com/whiskeysockets/baileyscsharp/llms.txt Sends contact cards with details like name, number, and organization, or shares a location pin using latitude and longitude coordinates. ```csharp using BaileysCSharp.Core.Models.Sending.NonMedia; var recipient = "15551234567@s.whatsapp.net"; // Contact card await socket.SendMessage(recipient, new ContactMessageContent { Contact = new ContactShareModel { FullName = "Jane Doe", ContactNumber = "15559876543", Organization = "Acme Corp" } }); // Location pin (Eiffel Tower) await socket.SendMessage(recipient, new LocationMessageContent { Location = new Proto.Message.Types.LocationMessage { DegreesLatitude = 48.858221, DegreesLongitude = 2.294466 } }); ``` -------------------------------- ### Newsletter (Channel) management Source: https://context7.com/whiskeysockets/baileyscsharp/llms.txt Create, follow, update, and post to WhatsApp Channels (Newsletters). ```APIDOC ## Newsletter Management ### Description Manage WhatsApp Channels (Newsletters), including creation, updates, posting messages, and subscription actions. ### Methods - `NewsletterCreate(string name)`: Creates a new channel with the given name. - `NewsletterUpdateName(string channelId, string name)`: Updates the name of an existing channel. - `NewsletterUpdateDescription(string channelId, string description)`: Updates the description of an existing channel. - `NewsletterAdminCount(string channelId)`: Retrieves the number of administrators for a channel. - `SendNewsletterMessage(string channelId, object message)`: Sends a message to a channel. The message object type depends on the message content (e.g., `NewsletterTextMessage`). - `NewsletterFollow(string channelId)`: Follows a channel. - `NewsletterUnFollow(string channelId)`: Unfollows a channel. - `NewsletterMute(string channelId)`: Mutes notifications for a channel. - `NewsletterUnMute(string channelId)`: Unmutes notifications for a channel. - `QueryRecommendedNewsletters()`: Retrieves a list of recommended newsletters. - `NewsletterDelete(string channelId)`: Deletes a channel. ### Request Example ```csharp // Create a new channel var channel = await socket.NewsletterCreate("My Dev Channel"); Console.WriteLine($"Channel ID: {channel.Id}"); // Update name and description await socket.NewsletterUpdateName(channel.Id, "My Dev Channel – Official"); await socket.NewsletterUpdateDescription(channel.Id, "Daily C# tips and tricks"); // Get admin count var adminCount = await socket.NewsletterAdminCount(channel.Id); Console.WriteLine($"Admins: {adminCount}"); // Send a text message to the channel await socket.SendNewsletterMessage(channel.Id, new NewsletterTextMessage { Text = "Hello, subscribers!" }); // Follow / unfollow / mute / unmute await socket.NewsletterFollow(channel.Id); await socket.NewsletterMute(channel.Id); await socket.NewsletterUnMute(channel.Id); await socket.NewsletterUnFollow(channel.Id); // Query recommended newsletters var recommended = await socket.QueryRecommendedNewsletters(); foreach (var item in recommended?.Newsletters ?? []) { Console.WriteLine($"{item.ThreadMetadata?.Name}: {item.ThreadMetadata?.SubscriberCount} subscribers"); } // Delete the channel await socket.NewsletterDelete(channel.Id); ``` ### Response Responses vary depending on the method called. For example, `NewsletterCreate` returns a `Channel` object, while `NewsletterAdminCount` returns an integer. ``` -------------------------------- ### Send a text message — SendMessage with TextMessageContent Source: https://context7.com/whiskeysockets/baileyscsharp/llms.txt Allows sending plain text messages to individual users or groups. It supports message quoting (replies) and mentions by specifying participant JIDs. ```APIDOC ## SendMessage with TextMessageContent ### Description Sends a plain text message to a specified recipient (user or group). This method supports replying to existing messages by including `ContextInfo` and mentioning participants in group chats. ### Method `SendMessage(string recipientJid, TextMessageContent message)` ### Parameters - **recipientJid** (string) - The WhatsApp JID of the recipient (e.g., "15551234567@s.whatsapp.net" or "120363000000000001@g.us"). - **message** (TextMessageContent) - An object containing the text content and optional context for the message. - **Text** (string) - The content of the message. - **Mentions** (List) - Optional. A list of JIDs to mention in the message. - **ContextInfo** (Proto.ContextInfo) - Optional. Information for quoting a previous message. ### Request Example ```csharp // Plain text var sent = await socket.SendMessage( "15551234567@s.whatsapp.net", new TextMessageContent { Text = "Hello from BaileysCSharp!" } ); // Reply (quote) an existing message var reply = await socket.SendMessage( "15551234567@s.whatsapp.net", new TextMessageContent { Text = "This is a reply", ContextInfo = new Proto.ContextInfo { QuotedMessage = originalMsg.Message } } ); // Mention participants in a group var mention = await socket.SendMessage( "120363000000000001@g.us", new TextMessageContent { Text = "Hey @15551234567, check this out!", Mentions = ["15551234567@s.whatsapp.net"] } ); ``` ### Response - **sent** (MessageSendResult?) - An object containing the key information of the sent message, or null if sending failed. ``` -------------------------------- ### Persist credentials — EV.Auth.Update Source: https://context7.com/whiskeysockets/baileyscsharp/llms.txt This event fires whenever the authentication credentials are changed. It is crucial for saving the session state to prevent data loss, especially after successful pairing or updates to pre-key information. ```APIDOC ## EV.Auth.Update ### Description Fired whenever the credential object is mutated. This event is essential for persisting session data, ensuring that the application can resume without re-authentication. ### Event Handler `OnAuthUpdate(object? sender, AuthenticationCreds creds)` ### Usage Implement this handler to serialize and save the `AuthenticationCreds` object to a persistent storage, such as a file. ### Example ```csharp private static void OnAuthUpdate(object? sender, AuthenticationCreds creds) { var path = Path.Join(socket.SocketConfig.CacheRoot, "creds.json"); // Serialize is thread-safe; use a lock when writing from multiple threads lock (locker) { File.WriteAllText(path, AuthenticationCreds.Serialize(creds)); } Console.WriteLine("Credentials saved."); } ``` ``` -------------------------------- ### Send contact and location messages Source: https://context7.com/whiskeysockets/baileyscsharp/llms.txt Provides functionality to send contact cards (vCards) and geographical location pins. ```APIDOC ## Send Contact and Location Messages ### Description Sends contact information as a vCard or shares a specific geographical location via a map pin. ### Method `SendMessage(string recipientJid, MessageContent message)` ### Parameters - **recipientJid** (string) - The WhatsApp JID of the recipient. - **message** (MessageContent) - An object representing the message content. This can be either `ContactMessageContent` or `LocationMessageContent`. - **ContactMessageContent**: - **Contact** (ContactShareModel) - An object containing the contact details. - **FullName** (string) - The full name of the contact. - **ContactNumber** (string) - The phone number of the contact. - **Organization** (string) - Optional organization name. - **LocationMessageContent**: - **Location** (Proto.Message.Types.LocationMessage) - An object containing location coordinates. - **DegreesLatitude** (double) - The latitude in degrees. - **DegreesLongitude** (double) - The longitude in degrees. ### Request Example ```csharp var recipient = "15551234567@s.whatsapp.net"; // Contact card await socket.SendMessage(recipient, new ContactMessageContent { Contact = new ContactShareModel { FullName = "Jane Doe", ContactNumber = "15559876543", Organization = "Acme Corp" } }); // Location pin (Eiffel Tower) await socket.SendMessage(recipient, new LocationMessageContent { Location = new Proto.Message.Types.LocationMessage { DegreesLatitude = 48.858221, DegreesLongitude = 2.294466 } }); ``` ### Response - **sent** (MessageSendResult?) - An object containing the key information of the sent message, or null if sending failed. ``` -------------------------------- ### React to a message Source: https://context7.com/whiskeysockets/baileyscsharp/llms.txt Sends or removes an emoji reaction on any existing message using `SendMessage` with `ReactMessageContent`. ```APIDOC ## React to a message — `SendMessage` with `ReactMessageContent` ### Description Sends or removes an emoji reaction on any existing message. ### Method `SendMessage` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **msg.Key.RemoteJid** (string) - Required - The remote JID of the chat. - **ReactMessageContent** (object) - Required - Content for the reaction. - **Key** (MessageKey) - Required - The key of the message to react to. - **ReactText** (string) - Required - The emoji reaction text. An empty string removes the reaction. ``` -------------------------------- ### React to a message with emoji Source: https://context7.com/whiskeysockets/baileyscsharp/llms.txt Sends or removes an emoji reaction on any existing message. Use an empty string for ReactText to remove a reaction. ```csharp using BaileysCSharp.Core.Models.Sending.NonMedia; // Add a heart reaction await socket.SendMessage( msg.Key.RemoteJid, new ReactMessageContent { Key = msg.Key, ReactText = "❤️" // empty string removes the reaction } ); ``` -------------------------------- ### Privacy settings Source: https://context7.com/whiskeysockets/baileyscsharp/llms.txt Programmatically update all WhatsApp privacy controls including last seen, profile picture, read receipts, and online status. ```APIDOC ## Privacy settings — `UpdateLastSeenPrivacy`, `UpdateOnlinePrivacy`, `UpdateProfilePicturePrivacy`, etc. ### Description Programmatically update all WhatsApp privacy controls. ### Methods - `UpdateLastSeenPrivacy` - `UpdateProfilePicturePrivacy` - `UpdateReadReceiptsPrivacy` - `UpdateOnlinePrivacy` - `UpdateDefaultDisappearingMode` ### Parameters #### UpdateLastSeenPrivacy - **value** (WAPrivacyValue) - Required - The privacy setting for last seen (e.g., All, Contacts, MyContacts, None). #### UpdateProfilePicturePrivacy - **value** (WAPrivacyValue) - Required - The privacy setting for profile picture. #### UpdateReadReceiptsPrivacy - **value** (WAReadReceiptsValue) - Required - The privacy setting for read receipts (e.g., All, Contacts, None). #### UpdateOnlinePrivacy - **value** (WAPrivacyOnlineValue) - Required - The privacy setting for online status (e.g., Match_Last_Seen, Everyone, Close_Friends, Close_Friends_Except, Contacts, Contacts_Except, None). #### UpdateDefaultDisappearingMode - **duration** (int) - Required - The default duration in seconds for disappearing messages in new chats. ``` -------------------------------- ### Profile picture URL — `ProfilePictureUrl` Source: https://context7.com/whiskeysockets/baileyscsharp/llms.txt Retrieve the CDN URL of a contact's or group's profile picture. ```APIDOC ## ProfilePictureUrl ### Description Retrieve the CDN URL of a contact's or group's profile picture. ### Method `ProfilePictureUrl` ### Parameters - `jid` (string) - Required - The JID of the contact or group. - `type` (ProfilePictureUrlType) - Optional - The type of picture to retrieve (Thumbnail or Image). Defaults to Thumbnail. ### Request Example ```csharp // Preview thumbnail (default) var previewUrl = await socket.ProfilePictureUrl("15551234567@s.whatsapp.net"); // Full-resolution image var fullUrl = await socket.ProfilePictureUrl( "15551234567@s.whatsapp.net", ProfilePictureUrlType.Image ); if (fullUrl != null) { var bytes = await new HttpClient().GetByteArrayAsync(fullUrl); File.WriteAllBytes("avatar.jpg", bytes); } ``` ### Response - `url` (string) - The CDN URL of the profile picture, or null if not found. ``` -------------------------------- ### Update WhatsApp privacy settings Source: https://context7.com/whiskeysockets/baileyscsharp/llms.txt Programmatically updates various WhatsApp privacy controls, including last seen, profile picture visibility, read receipts, online status, and default disappearing message timer. ```csharp using BaileysCSharp.Core.Types; // "Last seen" visible only to contacts socket.UpdateLastSeenPrivacy(WAPrivacyValue.Contacts); // Profile picture visible to everyone socket.UpdateProfilePicturePrivacy(WAPrivacyValue.All); // Read receipts off socket.UpdateReadReceiptsPrivacy(WAReadReceiptsValue.None); // Online status hidden from everyone socket.UpdateOnlinePrivacy(WAPrivacyOnlineValue.Match_Last_Seen); // Default disappearing message timer for new chats (24 hours) await socket.UpdateDefaultDisappearingMode(24 * 60 * 60); ``` -------------------------------- ### Send Text Message Source: https://context7.com/whiskeysockets/baileyscsharp/llms.txt Sends plain text messages to a recipient. Supports replying to existing messages by quoting them and mentioning participants in group chats. ```csharp using BaileysCSharp.Core.Models.Sending.NonMedia; // Plain text var sent = await socket.SendMessage( "15551234567@s.whatsapp.net", new TextMessageContent { Text = "Hello from BaileysCSharp!" } ); Console.WriteLine($"Sent message id: {sent?.Key.Id}"); // Reply (quote) an existing message var reply = await socket.SendMessage( "15551234567@s.whatsapp.net", new TextMessageContent { Text = "This is a reply", ContextInfo = new Proto.ContextInfo { QuotedMessage = originalMsg.Message } } ); // Mention participants in a group var mention = await socket.SendMessage( "120363000000000001@g.us", new TextMessageContent { Text = "Hey @15551234567, check this out!", Mentions = ["15551234567@s.whatsapp.net"] } ); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.