TypeScript client library for WAHA (WhatsApp HTTP API) - Unofficial
✨ This library is fully auto-generated and maintained by GitHub Copilot
npm install waha-api-client-ts
import { WAHAClient } from 'waha-api-client-ts';
// Initialize client with default configuration
const client = new WAHAClient({
baseURL: 'https://your-waha-instance.com',
apiKey: 'your-api-key',
session: 'default',
timeout: 30000,
retryAttempts: 3,
retryDelay: 1000,
});
// Send a text message
await client.sendText({
chatId: '1234567890@c.us',
text: 'Hello from WAHA!',
});
When initializing the client, you can set default values:
const client = new WAHAClient({
baseURL: 'https://your-waha-instance.com', // Required: Your WAHA API base URL
apiKey: 'your-api-key', // Optional: API key for authentication
session: 'default', // Optional: Default session name (default: 'default')
timeout: 30000, // Optional: Request timeout in ms (default: 30000)
retryAttempts: 3, // Optional: Number of retry attempts (default: 3)
retryDelay: 1000, // Optional: Delay between retries in ms (default: 1000)
});
You can override configuration for individual API calls:
await client.sendText({
chatId: '1234567890@c.us',
text: 'Hello!',
config: {
session: 'custom-session', // Override session for this request
timeout: 60000, // Override timeout for this request
retryAttempts: 5, // Override retry attempts
retryDelay: 2000, // Override retry delay
},
});
To prevent your WhatsApp account from being blocked, it's recommended to check if a number is registered on WhatsApp before sending messages. This library provides "safe send" methods that automatically implement WhatsApp's anti-blocking best practices.
When you send messages to numbers that don't exist on WhatsApp, it can lead to your account being flagged or blocked. Safe send methods help prevent this by implementing the following anti-blocking measures:
These methods return null if the number doesn't exist, preventing failed delivery attempts that could flag your account.
Delay Timings:
All safe send methods follow the same pattern: they check the number status first, then send only if the number exists.
safeSendText() - Safe version of sendText()safeSendImage() - Safe version of sendImage()safeSendFile() - Safe version of sendFile()safeSendVoice() - Safe version of sendVoice()safeSendVideo() - Safe version of sendVideo()safeSendLocation() - Safe version of sendLocation()safeSendContactVcard() - Safe version of sendContactVcard()safeSendLinkPreview() - Safe version of sendLinkPreview()safeSendButtons() - Safe version of sendButtons()safeSendList() - Safe version of sendList()safeSendPoll() - Safe version of sendPoll()When you call a safe send method, the following sequence occurs automatically:
This mimics human behavior and significantly reduces the risk of being flagged as a bot or spam account.
// Safe send text message with anti-blocking measures
const result = await client.safeSendText({
chatId: '1234567890@c.us',
text: 'Hello! How are you?',
});
if (result === null) {
console.log('Number does not exist on WhatsApp - message not sent');
} else {
console.log('Message sent successfully with anti-blocking measures:', result);
}
// Safe send image with anti-blocking measures
const imageResult = await client.safeSendImage({
chatId: '1234567890@c.us',
file: 'https://example.com/image.jpg',
caption: 'Check this out!',
});
if (imageResult === null) {
console.log('Number does not exist on WhatsApp - image not sent');
} else {
console.log('Image sent successfully:', imageResult);
}
// Safe send file with anti-blocking measures
const fileResult = await client.safeSendFile({
chatId: '1234567890@c.us',
file: 'https://example.com/document.pdf',
filename: 'document.pdf',
caption: 'Important document',
});
if (fileResult === null) {
console.log('Number does not exist on WhatsApp - file not sent');
} else {
console.log('File sent successfully:', fileResult);
}
Following WhatsApp's guidelines to avoid getting blocked:
✅ DO:
❌ DON'T:
Use Safe Send when:
Use Regular Send when:
This client implements all 147 WAHA API endpoints organized into the following categories:
getQR() - Get QR code for pairingrequestCode() - Request authentication codegetSessions() - Get all sessionsgetSession() - Get session infocreateSession() - Create new sessionupdateSession() - Update session configdeleteSession() - Delete sessionstartSession() / startSessionAlt() - Start sessionstopSession() / stopSessionAlt() - Stop sessionlogoutSession() / logoutSessionBulk() - Logout sessionrestartSession() - Restart sessiongetSessionMe() - Get session "me" infogetProfile() - Get my profilesetProfileName() - Set profile namesetProfileStatus() - Set profile statussetProfilePicture() - Set profile picturedeleteProfilePicture() - Delete profile picturesendText() / sendTextAlt() / sendTextGet() - Send text messagesendImage() / sendImageAlt() - Send imagesendFile() / sendFileAlt() - Send filesendVoice() - Send voice messagesendVideo() - Send videosendButtons() - Send buttonssendList() - Send list messagesendPoll() - Send pollsendPollVote() - Vote in pollsendLocation() - Send locationsendContactVcard() - Send contact vCardsendLinkPreview() - Send link with previewsendLinkCustomPreview() - Send link with custom previewforwardMessage() - Forward messagereply() - Reply to messagereplyButton() - Reply to buttonsendSeen() - Mark as seenstartTyping() - Start typing indicatorstopTyping() - Stop typing indicatorreaction() - React to messagestar() - Star/unstar messagegetMessages() / getMessagesAlt() - Get messagescheckNumberStatus() - Check if number is on WhatsAppgetChats() - Get all chatsgetChatsOverview() - Get chats overviewcreateChatsOverview() - Create chats overviewdeleteChat() - Delete chatgetChatPicture() - Get chat picturegetMessage() - Get specific messagedeleteMessage() - Delete messageeditMessage() - Edit messagedeleteAllMessages() - Delete all messagesreadMessages() - Mark messages as readpinMessage() - Pin messageunpinMessage() - Unpin messagearchiveChat() - Archive chatunarchiveChat() - Unarchive chatmarkChatUnread() - Mark chat as unreadgetChannels() - Get all channelscreateChannel() - Create channelgetChannel() - Get channel by IDdeleteChannel() - Delete channelgetChannelMessagesPreview() - Get messages previewfollowChannel() - Follow channelunfollowChannel() - Unfollow channelmuteChannel() - Mute channelunmuteChannel() - Unmute channelsearchChannelsByView() - Search channels by viewsearchChannelsByText() - Search channels by textgetChannelSearchViews() - Get search viewsgetChannelSearchCountries() - Get search countriesgetChannelSearchCategories() - Get search categoriespostTextStatus() - Post text statuspostImageStatus() - Post image statuspostVoiceStatus() - Post voice statuspostVideoStatus() - Post video statusdeleteStatus() - Delete statusgetNewMessageId() - Get new message IDgetLabels() - Get all labelscreateLabel() - Create labelupdateLabel() - Update labeldeleteLabel() - Delete labelgetChatLabels() - Get labels for chatsetChatLabels() - Set labels for chatgetChatsByLabel() - Get chats by labelgetAllContacts() - Get all contactsgetContact() - Get contact infocheckContactExists() - Check if contact existsgetContactAbout() - Get contact aboutgetContactProfilePicture() - Get contact profile pictureblockContact() - Block contactunblockContact() - Unblock contactupdateContact() - Update contactgetLids() - Get LIDsgetLidsCount() - Get LIDs countgetLid() - Get LID by IDgetLidByPhone() - Get LID by phonecreateGroup() - Create groupgetGroups() - Get all groupsgetGroup() - Get group by IDdeleteGroup() - Delete groupgetGroupsCount() - Get groups countrefreshGroups() - Refresh groupsgetGroupJoinInfo() - Get group join infojoinGroup() - Join groupleaveGroup() - Leave groupgetGroupPicture() - Get group picturesetGroupPicture() - Set group picturedeleteGroupPicture() - Delete group picturesetGroupDescription() - Set group descriptionsetGroupSubject() - Set group subjectgetGroupInfoAdminOnly() - Get info admin only settingsetGroupInfoAdminOnly() - Set info admin onlygetGroupMessagesAdminOnly() - Get messages admin only settingsetGroupMessagesAdminOnly() - Set messages admin onlygetGroupInviteCode() - Get invite coderevokeGroupInviteCode() - Revoke invite codegetGroupParticipants() - Get participantsaddGroupParticipants() - Add participantsremoveGroupParticipants() - Remove participantspromoteGroupParticipant() - Promote to admindemoteGroupParticipant() - Demote from adminsetPresence() - Set presencegetAllPresence() - Get all presence infogetPresence() - Get presence for chatsubscribePresence() - Subscribe to presenceping() - Ping endpointhealth() - Health checkgetVersion() - Get API versiongetServerVersion() - Get server versiongetServerEnvironment() - Get server environmentgetServerStatus() - Get server statusstopServer() - Stop servergetHeapSnapshot() - Get heap snapshotgetBrowserTrace() - Get browser traceconvertToVoice() - Convert audio to voice formatconvertVideo() - Convert videotakeScreenshot() - Take screenshotsendEvent() - Send eventgetApps() - Get all appscreateApp() - Create appgetApp() - Get app by IDupdateApp() - Update appdeleteApp() - Delete appgetChatwootLocales() - Get Chatwoot localesawait client.sendText({
chatId: '1234567890@c.us',
text: 'Hello, World!',
reply_to: 'message-id', // Optional: Reply to a specific message
config: { ... }, // Optional: Override config
});
await client.sendImage({
chatId: '1234567890@c.us',
file: 'https://example.com/image.jpg', // URL or base64
caption: 'Check this out!', // Optional
reply_to: 'message-id', // Optional
config: { ... }, // Optional
});
await client.sendFile({
chatId: '1234567890@c.us',
file: 'https://example.com/document.pdf',
filename: 'document.pdf', // Optional
caption: 'Important document', // Optional
reply_to: 'message-id', // Optional
config: { ... }, // Optional
});
// Create a group
const groupResponse = await client.createGroup({
name: 'My Group',
participants: ['1234567890@c.us', '0987654321@c.us']
});
// Add participants (use the group ID from the response)
const groupId = 'group-id@g.us'; // Extract from response
await client.addGroupParticipants(groupId, {
participants: ['1111111111@c.us']
});
// Promote to admin
await client.promoteGroupParticipant(groupId, {
participants: ['1234567890@c.us']
});
const session = await client.getSession({
session: 'custom-session', // Optional: Override session
});
const session = await client.startSession({
session: 'new-session', // Optional: Override session to start
});
await client.stopSession({
session: 'session-to-stop', // Optional: Override session
});
const sessions = await client.getSessions();
const chats = await client.getChats({
session: 'custom-session', // Optional: Override session
});
const messages = await client.getMessages('1234567890@c.us', {
session: 'custom-session', // Optional: Override session
});
const status = await client.checkNumberStatus('1234567890', {
session: 'custom-session', // Optional: Override session
});
console.log(status.exists); // true if number is on WhatsApp
You can work with multiple WhatsApp sessions using the same client:
const client = new WAHAClient({
baseURL: 'https://your-waha-instance.com',
apiKey: 'your-api-key',
session: 'default',
});
// Send from default session
await client.sendText({
chatId: '1234567890@c.us',
text: 'From default session',
});
// Send from a different session
await client.sendText({
chatId: '1234567890@c.us',
text: 'From custom session',
config: { session: 'session-2' },
});
Adjust retry behavior for specific operations:
// For a critical message that needs more retries
await client.sendText({
chatId: '1234567890@c.us',
text: 'Important message',
config: {
retryAttempts: 10,
retryDelay: 5000,
},
});
// For a quick operation with no retries
await client.sendText({
chatId: '1234567890@c.us',
text: 'Quick message',
config: {
retryAttempts: 0,
},
});
try {
await client.sendText({
chatId: '1234567890@c.us',
text: 'Hello!',
});
} catch (error) {
console.error('Failed to send message:', error);
}
The library exports TypeScript types for all configurations and responses:
import type {
WAHAConfig,
RequestConfig,
SendTextParams,
SendImageParams,
SendFileParams,
SessionInfo,
ChatInfo,
MessageInfo,
APIResponse,
} from 'waha-api-client-ts';
See src/example.ts for code examples and src/demo.ts for a complete feature demonstration.
To run the demo:
npm install
npx tsx src/demo.ts
Once deployed, the API documentation will be available at:
https://myusp.github.io/waha-api-client-ts/You can also generate documentation locally:
npm run docs
# Documentation will be generated in the ./docs directory
ISC
Contributions are welcome! Please feel free to submit a Pull Request.
This is an unofficial client library for WAHA API. It is not affiliated with or endorsed by the WAHA project.
USE AT YOUR OWN RISK: This software is provided "as is" without warranty of any kind, either expressed or implied. The authors and contributors are not responsible for any damages, data loss, account bans, or other issues that may arise from using this library. You are solely responsible for ensuring your use complies with WhatsApp's Terms of Service and applicable laws. By using this library, you acknowledge and accept all risks associated with automated messaging and API usage.