@itznomo/baileys 0.0.0-stage โ 0.0.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/BUTTONS.md +153 -0
- package/Example/call-bot.mjs +38 -0
- package/Example/example.mjs +36 -0
- package/Example/full-bot-commands.mjs +319 -0
- package/Example/full-bot.mjs +77 -0
- package/LICENSE +21 -0
- package/README.md +543 -2
- package/WAProto/@dnuzi +1 -0
- package/WAProto/index.d.ts +15932 -0
- package/WAProto/index.js +113300 -0
- package/assets/banner.svg +17 -0
- package/assets/devider.svg +1 -0
- package/assets/features.svg +21 -0
- package/docs/CALLS.md +106 -0
- package/docs/FEATURES.md +1152 -0
- package/engine-requirements.js +19 -0
- package/index.d.ts +815 -0
- package/package.json +51 -4
- package/src/binary/wa-binary-constants.js +1300 -0
- package/src/binary/wa-binary.js +627 -0
- package/src/constants.js +147 -0
- package/src/defaults.js +106 -0
- package/src/foundation/ai-rich.js +654 -0
- package/src/foundation/audio-duration.js +470 -0
- package/src/foundation/audio-samples.js +250 -0
- package/src/foundation/boom.js +39 -0
- package/src/foundation/builders.js +851 -0
- package/src/foundation/cache.js +134 -0
- package/src/foundation/concurrency.js +69 -0
- package/src/foundation/curve25519.js +189 -0
- package/src/foundation/image-thumb.js +65 -0
- package/src/foundation/link-preview.js +278 -0
- package/src/foundation/logger.js +78 -0
- package/src/foundation/long.js +130 -0
- package/src/foundation/performance.js +385 -0
- package/src/foundation/protobuf-minimal.js +587 -0
- package/src/foundation/qrcode-terminal.js +273 -0
- package/src/foundation/sql-database.js +716 -0
- package/src/foundation/wa-crypto.js +47 -0
- package/src/foundation/zip.js +108 -0
- package/src/index.js +67 -0
- package/src/signal/libsignal.js +996 -0
- package/src/signal/signal-group.js +455 -0
- package/src/signal/signal-repository.js +635 -0
- package/src/socket/business-communities.js +811 -0
- package/src/socket/chats.js +702 -0
- package/src/socket/groups-newsletter.js +524 -0
- package/src/socket/messages-recv.js +1815 -0
- package/src/socket/messages-send.js +1526 -0
- package/src/socket/socket-builder.js +131 -0
- package/src/socket/socket-core.js +913 -0
- package/src/socket/usync.js +287 -0
- package/src/socket-client/native-websocket.js +344 -0
- package/src/socket-client/websocket-client.js +170 -0
- package/src/utils/auth-state-core.js +731 -0
- package/src/utils/auth-state-storage.js +594 -0
- package/src/utils/chat-sync.js +1046 -0
- package/src/utils/check-status.js +159 -0
- package/src/utils/cstoken.js +17 -0
- package/src/utils/media.js +807 -0
- package/src/utils/message-compose.js +1747 -0
- package/src/utils/message-processing.js +912 -0
- package/src/utils/modern-messages.js +435 -0
- package/src/utils/nomo-buttons.js +138 -0
- package/src/utils/nomo-commands.js +168 -0
- package/src/utils/spam-report-utils.js +136 -0
- package/src/utils/use-keyv-auth-state.js +307 -0
- package/src/utils/username.js +19 -0
- package/src/utils/wa-protocol-core.js +1227 -0
- package/src/voip/WaVoipCoordinator.js +158 -0
- package/src/voip/app-data/WaAppDataStream.js +193 -0
- package/src/voip/app-data/protocol.js +172 -0
- package/src/voip/auto.js +139 -0
- package/src/voip/bytes.js +63 -0
- package/src/voip/call/WaCallManager.js +442 -0
- package/src/voip/call/WaCallMediaSession.js +1727 -0
- package/src/voip/call/call-state.js +203 -0
- package/src/voip/crypto/encryption.js +13 -0
- package/src/voip/crypto/primitives.js +21 -0
- package/src/voip/crypto/rtcp.js +66 -0
- package/src/voip/crypto/srtp.js +180 -0
- package/src/voip/crypto/ssrc.js +15 -0
- package/src/voip/index.js +730 -0
- package/src/voip/media/WaAudioEngine.js +486 -0
- package/src/voip/media/WaVideoEngine.js +275 -0
- package/src/voip/media/audio-codec.js +0 -0
- package/src/voip/media/audio-reorder.js +107 -0
- package/src/voip/media/h264.js +246 -0
- package/src/voip/media/mlow-codec.js +465 -0
- package/src/voip/media/rtcp.js +68 -0
- package/src/voip/media/rtp.js +242 -0
- package/src/voip/protobuf.js +30 -0
- package/src/voip/relay/WaManualRelay.js +609 -0
- package/src/voip/relay/datachannel/pre-negotiated.js +25 -0
- package/src/voip/relay/dtls/aead.js +46 -0
- package/src/voip/relay/dtls/cert-builder.js +102 -0
- package/src/voip/relay/dtls/der.js +98 -0
- package/src/voip/relay/dtls/ecdhe.js +37 -0
- package/src/voip/relay/dtls/handshake-framing.js +100 -0
- package/src/voip/relay/dtls/handshake-messages.js +158 -0
- package/src/voip/relay/dtls/handshake.js +582 -0
- package/src/voip/relay/dtls/prf.js +39 -0
- package/src/voip/relay/dtls/record.js +56 -0
- package/src/voip/relay/relay-ack.js +141 -0
- package/src/voip/relay/sctp/association.js +434 -0
- package/src/voip/relay/sctp/crc32c.js +21 -0
- package/src/voip/relay/sctp/wire.js +226 -0
- package/src/voip/relay/stun.js +463 -0
- package/src/voip/shim/baileys-resolve.js +7 -0
- package/src/voip/shim/core.js +66 -0
- package/src/voip/shim/crypto.js +6 -0
- package/src/voip/shim/proto.js +10 -0
- package/src/voip/shim/protocol.js +130 -0
- package/src/voip/shim/transport.js +82 -0
- package/src/voip/shim/util.js +207 -0
- package/src/voip/signaling/bridge.js +102 -0
- package/src/voip/signaling/screen-share.js +60 -0
- package/src/voip/signaling/signaling.js +491 -0
- package/src/voip/types.js +69 -0
- package/src/voip/voip-deps.js +243 -0
- package/src/voip/voipClient.js +314 -0
- package/src/wam/wam-constants.js +22852 -0
- package/src/wam/wam.js +146 -0
- package/voip.d.ts +144 -0
package/BUTTONS.md
ADDED
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
# Buttons, lists and interactive messages
|
|
2
|
+
|
|
3
|
+
This fork adds sendable button messages on top of upstream Baileys. All of them go through the normal
|
|
4
|
+
`sock.sendMessage(jid, content)` call.
|
|
5
|
+
|
|
6
|
+
> WhatsApp decides what it renders. Button support for non-official clients changes on the server side without
|
|
7
|
+
> notice, so always test with a spare number first, and expect some message types to show up as plain text or
|
|
8
|
+
> "message not supported" on some app versions.
|
|
9
|
+
|
|
10
|
+
## Quick start
|
|
11
|
+
|
|
12
|
+
```js
|
|
13
|
+
import makeWASocket, { quickReplyButton, urlButton, copyButton, getButtonReply } from '@nomo/ballieys'
|
|
14
|
+
|
|
15
|
+
// native flow buttons (the modern ones)
|
|
16
|
+
await sock.sendMessage(jid, {
|
|
17
|
+
text: 'Welcome to the bot',
|
|
18
|
+
footer: 'Anuhas Bandara',
|
|
19
|
+
interactiveButtons: [
|
|
20
|
+
quickReplyButton('Menu', '.menu'),
|
|
21
|
+
quickReplyButton('Ping', '.ping'),
|
|
22
|
+
urlButton('Website', 'https://example.com'),
|
|
23
|
+
copyButton('Copy code', 'ABC-123')
|
|
24
|
+
]
|
|
25
|
+
})
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
## Message types
|
|
29
|
+
|
|
30
|
+
### 1. `interactiveButtons` (native flow)
|
|
31
|
+
|
|
32
|
+
| Field | Notes |
|
|
33
|
+
| --- | --- |
|
|
34
|
+
| `text` or `caption` | body text |
|
|
35
|
+
| `title`, `subtitle` | optional header text |
|
|
36
|
+
| `footer` | optional footer |
|
|
37
|
+
| `image`, `video`, `document` | optional media header (`document` also takes `mimetype`, `fileName`) |
|
|
38
|
+
| `interactiveButtons` | array of `{ name, buttonParamsJson }`, use the helpers below |
|
|
39
|
+
|
|
40
|
+
Helpers (all exported from the package root):
|
|
41
|
+
|
|
42
|
+
- `quickReplyButton(displayText, id)`
|
|
43
|
+
- `urlButton(displayText, url)`
|
|
44
|
+
- `copyButton(displayText, code)`
|
|
45
|
+
- `callButton(displayText, phoneNumber)`
|
|
46
|
+
- `singleSelectButton(title, sections)` for a drop-down list inside native flow
|
|
47
|
+
|
|
48
|
+
```js
|
|
49
|
+
await sock.sendMessage(jid, {
|
|
50
|
+
image: { url: './logo.jpg' },
|
|
51
|
+
caption: 'Pick a tool',
|
|
52
|
+
interactiveButtons: [
|
|
53
|
+
singleSelectButton('Open menu', [
|
|
54
|
+
{
|
|
55
|
+
title: 'Tools',
|
|
56
|
+
rows: [
|
|
57
|
+
{ id: '.sticker', title: 'Sticker', description: 'Image to sticker' },
|
|
58
|
+
{ id: '.song', title: 'Song', description: 'Download audio' }
|
|
59
|
+
]
|
|
60
|
+
}
|
|
61
|
+
])
|
|
62
|
+
]
|
|
63
|
+
})
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
### 2. `buttons` (classic quick reply)
|
|
67
|
+
|
|
68
|
+
```js
|
|
69
|
+
await sock.sendMessage(jid, {
|
|
70
|
+
text: 'Choose',
|
|
71
|
+
footer: 'footer',
|
|
72
|
+
buttons: [
|
|
73
|
+
{ buttonId: 'a', buttonText: { displayText: 'Option A' } },
|
|
74
|
+
{ buttonId: 'b', buttonText: { displayText: 'Option B' } }
|
|
75
|
+
]
|
|
76
|
+
})
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
Add `image`, `video` or `document` to put media in the header; `headerType` is picked for you.
|
|
80
|
+
|
|
81
|
+
### 3. `sections` (classic list)
|
|
82
|
+
|
|
83
|
+
```js
|
|
84
|
+
await sock.sendMessage(jid, {
|
|
85
|
+
text: 'Choose a command',
|
|
86
|
+
title: 'Menu',
|
|
87
|
+
buttonText: 'Open list',
|
|
88
|
+
footer: 'footer',
|
|
89
|
+
sections: [{ title: 'Tools', rows: [{ title: 'Ping', rowId: '.ping', description: 'Latency' }] }]
|
|
90
|
+
})
|
|
91
|
+
```
|
|
92
|
+
|
|
93
|
+
### 4. `cards` (carousel)
|
|
94
|
+
|
|
95
|
+
```js
|
|
96
|
+
await sock.sendMessage(jid, {
|
|
97
|
+
text: 'Our plans',
|
|
98
|
+
cards: [
|
|
99
|
+
{
|
|
100
|
+
image: { url: './basic.jpg' },
|
|
101
|
+
title: 'Basic',
|
|
102
|
+
body: 'For small groups',
|
|
103
|
+
footer: 'Free',
|
|
104
|
+
buttons: [quickReplyButton('Select', 'plan-basic')]
|
|
105
|
+
},
|
|
106
|
+
{
|
|
107
|
+
image: { url: './pro.jpg' },
|
|
108
|
+
title: 'Pro',
|
|
109
|
+
body: 'For big communities',
|
|
110
|
+
buttons: [urlButton('Buy', 'https://example.com/pro')]
|
|
111
|
+
}
|
|
112
|
+
]
|
|
113
|
+
})
|
|
114
|
+
```
|
|
115
|
+
|
|
116
|
+
## Reading what the user tapped
|
|
117
|
+
|
|
118
|
+
`getButtonReply` understands classic buttons, templates, lists and native flow replies:
|
|
119
|
+
|
|
120
|
+
```js
|
|
121
|
+
sock.ev.on('messages.upsert', async ({ messages }) => {
|
|
122
|
+
const msg = messages[0]
|
|
123
|
+
const reply = getButtonReply(msg)
|
|
124
|
+
if (reply) {
|
|
125
|
+
console.log(reply.kind, reply.id, reply.displayText)
|
|
126
|
+
// e.g. 'native_flow' '.menu' 'Menu'
|
|
127
|
+
}
|
|
128
|
+
})
|
|
129
|
+
```
|
|
130
|
+
|
|
131
|
+
The returned `id` is exactly what you passed as `id`, `buttonId` or `rowId`, so using your command text (`.menu`) as the
|
|
132
|
+
id lets you feed it straight into your command handler.
|
|
133
|
+
|
|
134
|
+
## Two ways to write buttons
|
|
135
|
+
|
|
136
|
+
Both work, use whichever you like:
|
|
137
|
+
|
|
138
|
+
```js
|
|
139
|
+
// nomo style (raw native flow buttons from the helpers)
|
|
140
|
+
await sock.sendMessage(jid, { text: 'Hi', interactiveButtons: [quickReplyButton('Menu', '.menu')] })
|
|
141
|
+
|
|
142
|
+
// compact style
|
|
143
|
+
await sock.sendMessage(jid, { text: 'Hi', nativeFlow: [{ text: 'Menu', id: '.menu' }, { text: 'Site', url: 'https://example.com' }] })
|
|
144
|
+
```
|
|
145
|
+
|
|
146
|
+
Carousel cards accept `buttons` / `body` (nomo style) or `nativeFlow` / `caption` (compact style).
|
|
147
|
+
Everything else in this package (widgets, AI rich, calls, payments, auth storage ...) is in `docs/FEATURES.md`.
|
|
148
|
+
|
|
149
|
+
## Where the code lives
|
|
150
|
+
|
|
151
|
+
- `src/utils/nomo-buttons.js`: helpers, `getButtonReply`, and `withNomoAliases` (the shape mapping).
|
|
152
|
+
- `src/utils/message-compose.js`: builds the actual button, list, native flow and carousel messages.
|
|
153
|
+
- `test/smoke.test.mjs`: offline checks for all of the above (`npm test`).
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import makeWASocket, { useMultiFileAuthState, DisconnectReason, createCommandRouter } from '../src/index.js'
|
|
2
|
+
import Voip from '../src/voip/index.js'
|
|
3
|
+
|
|
4
|
+
const start = async () => {
|
|
5
|
+
const { state, saveCreds } = await useMultiFileAuthState('./auth')
|
|
6
|
+
const sock = makeWASocket({ auth: state })
|
|
7
|
+
sock.ev.on('creds.update', saveCreds)
|
|
8
|
+
|
|
9
|
+
const bot = createCommandRouter(sock, { prefix: '.', owners: ['947XXXXXXXX'] })
|
|
10
|
+
let voip
|
|
11
|
+
|
|
12
|
+
bot.command('menu', ctx => bot.sendMenu(ctx.jid, { title: 'Call bot', text: 'Pick a command' }), { description: 'Show this menu' })
|
|
13
|
+
bot.command('callme', async ctx => {
|
|
14
|
+
const call = await voip.call(ctx.sender, ctx.args[0] || './song.mp3')
|
|
15
|
+
call.on('error', err => console.error(err))
|
|
16
|
+
}, { description: 'The bot calls you and plays music', category: 'Calls', cooldownMs: 30_000 })
|
|
17
|
+
bot.command('history', ctx => ctx.reply(voip.history.slice(-5).map(h => `${h.direction} ${h.peer} ${Math.round(h.durationMs / 1000)}s`).join('\n') || 'no calls yet'), {
|
|
18
|
+
description: 'Last 5 calls',
|
|
19
|
+
category: 'Calls',
|
|
20
|
+
ownerOnly: true
|
|
21
|
+
})
|
|
22
|
+
bot.attach()
|
|
23
|
+
|
|
24
|
+
sock.ev.on('connection.update', async ({ connection, lastDisconnect }) => {
|
|
25
|
+
if (connection === 'open') {
|
|
26
|
+
voip = new Voip(sock, { maxConcurrentCalls: 2, tmpDir: './tmp' })
|
|
27
|
+
await voip.autoAnswer({
|
|
28
|
+
media: './song.mp3',
|
|
29
|
+
delayMs: 2000,
|
|
30
|
+
onAnswer: (call, incoming) => console.log('answered', incoming.jid),
|
|
31
|
+
onError: err => console.error(err)
|
|
32
|
+
})
|
|
33
|
+
console.log('connected, auto answer is on')
|
|
34
|
+
}
|
|
35
|
+
if (connection === 'close' && lastDisconnect?.error?.output?.statusCode !== DisconnectReason.loggedOut) start()
|
|
36
|
+
})
|
|
37
|
+
}
|
|
38
|
+
start()
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import makeWASocket, { useMultiFileAuthState, DisconnectReason, quickReplyButton, urlButton, copyButton, singleSelectButton, getButtonReply } from '../src/index.js'
|
|
2
|
+
|
|
3
|
+
const start = async () => {
|
|
4
|
+
const { state, saveCreds } = await useMultiFileAuthState('./auth')
|
|
5
|
+
const sock = makeWASocket({ auth: state })
|
|
6
|
+
sock.ev.on('creds.update', saveCreds)
|
|
7
|
+
|
|
8
|
+
sock.ev.on('connection.update', ({ connection, lastDisconnect }) => {
|
|
9
|
+
if (connection === 'open') console.log('connected')
|
|
10
|
+
if (connection === 'close' && lastDisconnect?.error?.output?.statusCode !== DisconnectReason.loggedOut) start()
|
|
11
|
+
})
|
|
12
|
+
|
|
13
|
+
sock.ev.on('messages.upsert', async ({ messages }) => {
|
|
14
|
+
const msg = messages[0]
|
|
15
|
+
if (!msg?.message || msg.key.fromMe) return
|
|
16
|
+
const jid = msg.key.remoteJid
|
|
17
|
+
const reply = getButtonReply(msg)
|
|
18
|
+
const cmd = reply?.id || msg.message.conversation || msg.message.extendedTextMessage?.text || ''
|
|
19
|
+
|
|
20
|
+
if (cmd === '.menu') {
|
|
21
|
+
await sock.sendMessage(jid, {
|
|
22
|
+
text: 'Pick something',
|
|
23
|
+
footer: '@nomo/ballieys',
|
|
24
|
+
interactiveButtons: [
|
|
25
|
+
quickReplyButton('Ping', '.ping'),
|
|
26
|
+
urlButton('Website', 'https://example.com'),
|
|
27
|
+
copyButton('Copy code', 'ABC-123'),
|
|
28
|
+
singleSelectButton('More', [{ title: 'Tools', rows: [{ id: '.ping', title: 'Ping', description: 'Latency' }] }])
|
|
29
|
+
]
|
|
30
|
+
})
|
|
31
|
+
} else if (cmd === '.ping') {
|
|
32
|
+
await sock.sendMessage(jid, { text: 'pong' }, { quoted: msg })
|
|
33
|
+
}
|
|
34
|
+
})
|
|
35
|
+
}
|
|
36
|
+
start()
|
|
@@ -0,0 +1,319 @@
|
|
|
1
|
+
// All commands of the full example bot. Add, remove or rename commands here.
|
|
2
|
+
// Every command is `bot.command(names, handler, { description, category, ownerOnly, groupOnly, privateOnly, cooldownMs })`.
|
|
3
|
+
import { join, dirname } from 'node:path'
|
|
4
|
+
import { fileURLToPath } from 'node:url'
|
|
5
|
+
import { quickReplyButton, urlButton, copyButton, callButton, singleSelectButton, getContentType, extractMessageContent } from '../src/index.js'
|
|
6
|
+
|
|
7
|
+
const MEDIA_DIR = join(dirname(fileURLToPath(import.meta.url)), '..', 'Media')
|
|
8
|
+
const media = name => join(MEDIA_DIR, name)
|
|
9
|
+
|
|
10
|
+
const digits = value => String(value ?? '').split('@')[0].split(':')[0].replace(/\D/g, '')
|
|
11
|
+
const toJid = number => `${digits(number)}@s.whatsapp.net`
|
|
12
|
+
const formatDuration = ms => {
|
|
13
|
+
const s = Math.floor(ms / 1000)
|
|
14
|
+
return `${Math.floor(s / 86400)}d ${Math.floor((s % 86400) / 3600)}h ${Math.floor((s % 3600) / 60)}m ${s % 60}s`
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/** replied-to user, first @mention, or a phone number in the arguments */
|
|
18
|
+
const targetOf = ctx => {
|
|
19
|
+
const content = extractMessageContent(ctx.msg.message)
|
|
20
|
+
const info = content?.[getContentType(content)]?.contextInfo
|
|
21
|
+
if (info?.mentionedJid?.[0]) return info.mentionedJid[0]
|
|
22
|
+
if (info?.participant) return info.participant
|
|
23
|
+
// a number can be written with spaces: "94 77 XXX XXXX"
|
|
24
|
+
const number = []
|
|
25
|
+
for (const arg of ctx.args) {
|
|
26
|
+
if (!/^\+?[\d()-]+$/.test(arg)) break
|
|
27
|
+
number.push(arg)
|
|
28
|
+
}
|
|
29
|
+
return digits(number.join('')).length >= 8 ? toJid(number.join('')) : undefined
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
const isAdminOf = (metadata, jid) => {
|
|
33
|
+
const wanted = digits(jid)
|
|
34
|
+
return metadata.participants.some(p => p.admin && [p.id, p.lid, p.phoneNumber].some(id => digits(id) === wanted))
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* bot: the command router, deps: { sock, getVoip(), config: { botName, owners, prefix } }
|
|
39
|
+
* returns the state object (anti call / auto answer handles), handy for tests
|
|
40
|
+
*/
|
|
41
|
+
export const registerCommands = (bot, { sock, getVoip, config }) => {
|
|
42
|
+
const { botName = 'My Bot', owners = [], ownerEmail = 'anuhazdev@gmail.com' } = config
|
|
43
|
+
const prefix = bot.prefix
|
|
44
|
+
const startedAt = Date.now()
|
|
45
|
+
const state = { antiCall: null, autoAnswer: null }
|
|
46
|
+
|
|
47
|
+
const withGroupAdmin = handler => async ctx => {
|
|
48
|
+
const metadata = await sock.groupMetadata(ctx.jid)
|
|
49
|
+
if (!ctx.isOwner && !isAdminOf(metadata, ctx.sender)) return ctx.reply('Only group admins can use this command.')
|
|
50
|
+
return handler(ctx, metadata)
|
|
51
|
+
}
|
|
52
|
+
const needVoip = ctx => {
|
|
53
|
+
const voip = getVoip()
|
|
54
|
+
if (!voip) void ctx.reply('Calls are not ready yet, try again in a few seconds.')
|
|
55
|
+
return voip
|
|
56
|
+
}
|
|
57
|
+
const stopCallHandlers = async () => {
|
|
58
|
+
state.antiCall?.stop()
|
|
59
|
+
state.autoAnswer?.stop()
|
|
60
|
+
state.antiCall = state.autoAnswer = null
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
const menuText = () => {
|
|
64
|
+
const groups = new Map()
|
|
65
|
+
for (const { names, meta } of bot.commands) {
|
|
66
|
+
if (!meta.description || meta.hidden) continue
|
|
67
|
+
const tags = `${meta.ownerOnly ? ' (owner)' : ''}${meta.groupOnly ? ' (group)' : ''}`
|
|
68
|
+
const category = meta.category ?? 'Other'
|
|
69
|
+
if (!groups.has(category)) groups.set(category, [])
|
|
70
|
+
groups.get(category).push(`${prefix}${names[0]}${tags} - ${meta.description}`)
|
|
71
|
+
}
|
|
72
|
+
return [`*${botName}*`, ...[...groups].map(([category, rows]) => `\n*${category}*\n${rows.join('\n')}`)].join('\n')
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/* ------------------------------------------------------------------ Basic */
|
|
76
|
+
bot.command(['menu', 'help'], ctx => ctx.reply(menuText()), { description: 'Show every command', category: 'Basic' })
|
|
77
|
+
bot.command('menulist', ctx => bot.sendMenu(ctx.jid, { title: botName, text: 'Pick a command', footer: botName }), { description: 'Menu as a drop-down list', category: 'Basic' })
|
|
78
|
+
bot.command('ping', ctx => {
|
|
79
|
+
const sentAt = Number(ctx.msg.messageTimestamp) * 1000
|
|
80
|
+
return ctx.reply(Number.isFinite(sentAt) && sentAt > 0 ? `pong ${Math.max(0, Date.now() - sentAt)} ms` : 'pong')
|
|
81
|
+
}, { description: 'Check the bot is alive', category: 'Basic' })
|
|
82
|
+
bot.command('alive', ctx => ctx.reply({
|
|
83
|
+
text: `*${botName}* is online\nUptime: ${formatDuration(Date.now() - startedAt)}`,
|
|
84
|
+
footer: botName,
|
|
85
|
+
interactiveButtons: [quickReplyButton('Menu', `${prefix}menu`), quickReplyButton('Ping', `${prefix}ping`)]
|
|
86
|
+
}), { description: 'Status with buttons', category: 'Basic' })
|
|
87
|
+
bot.command('runtime', ctx => ctx.reply(`Running for ${formatDuration(Date.now() - startedAt)}`), { description: 'How long the bot has been running', category: 'Basic' })
|
|
88
|
+
bot.command('id', ctx => ctx.reply(`Chat: ${ctx.jid}\nYou: ${ctx.sender}`), { description: 'Show chat and sender ids', category: 'Basic' })
|
|
89
|
+
bot.command('owner', ctx => {
|
|
90
|
+
const name = `${botName} owner`
|
|
91
|
+
const number = owners.length ? digits(owners[0]) : ''
|
|
92
|
+
// the contact card carries the email, and the phone number only if one was configured
|
|
93
|
+
const vcard = ['BEGIN:VCARD', 'VERSION:3.0', `FN:${name}`, number && `TEL;type=CELL;waid=${number}:+${number}`, ownerEmail && `EMAIL;type=INTERNET:${ownerEmail}`, 'END:VCARD'].filter(Boolean).join('\n')
|
|
94
|
+
if (!number) return ctx.reply({ text: `*${name}*\nEmail: ${ownerEmail}`, footer: botName, interactiveButtons: [copyButton('Copy email', ownerEmail), urlButton('Send email', `mailto:${ownerEmail}`)] })
|
|
95
|
+
return sock.sendMessage(ctx.jid, { contacts: { displayName: name, contacts: [{ displayName: name, vcard }] } }, { quoted: ctx.msg })
|
|
96
|
+
}, { description: 'Send the owner contact (email)', category: 'Basic' })
|
|
97
|
+
|
|
98
|
+
/* ------------------------------------------------------------------ Buttons and lists */
|
|
99
|
+
bot.command('buttons', ctx => {
|
|
100
|
+
const buttons = [quickReplyButton('Ping', `${prefix}ping`), urlButton('Website', 'https://example.com'), copyButton('Copy code', 'ABC-123')]
|
|
101
|
+
if (owners.length) buttons.push(callButton('Call owner', `+${digits(owners[0])}`))
|
|
102
|
+
return ctx.reply({ text: 'Native flow buttons', footer: botName, interactiveButtons: buttons })
|
|
103
|
+
}, { description: 'Quick reply, link, copy and call buttons', category: 'Buttons' })
|
|
104
|
+
bot.command('classic', ctx => ctx.reply({
|
|
105
|
+
text: 'Classic buttons',
|
|
106
|
+
footer: botName,
|
|
107
|
+
buttons: [
|
|
108
|
+
{ buttonId: `${prefix}ping`, buttonText: { displayText: 'Ping' } },
|
|
109
|
+
{ buttonId: `${prefix}runtime`, buttonText: { displayText: 'Runtime' } }
|
|
110
|
+
]
|
|
111
|
+
}), { description: 'Classic reply buttons', category: 'Buttons' })
|
|
112
|
+
bot.command('list', ctx => ctx.reply({
|
|
113
|
+
text: 'Pick one',
|
|
114
|
+
title: 'Drop-down list',
|
|
115
|
+
footer: botName,
|
|
116
|
+
interactiveButtons: [singleSelectButton('Open list', [{
|
|
117
|
+
title: 'Basic',
|
|
118
|
+
rows: [
|
|
119
|
+
{ id: `${prefix}ping`, title: 'Ping', description: 'Latency' },
|
|
120
|
+
{ id: `${prefix}runtime`, title: 'Runtime', description: 'Uptime' },
|
|
121
|
+
{ id: `${prefix}menu`, title: 'Menu', description: 'All commands' }
|
|
122
|
+
]
|
|
123
|
+
}])]
|
|
124
|
+
}), { description: 'Drop-down list inside native flow', category: 'Buttons' })
|
|
125
|
+
bot.command('carousel', ctx => ctx.reply({
|
|
126
|
+
text: 'Swipe the cards',
|
|
127
|
+
footer: botName,
|
|
128
|
+
cards: [
|
|
129
|
+
{ image: { url: media('cat.jpeg') }, title: 'Cat', body: 'A cat photo', buttons: [quickReplyButton('Image', `${prefix}image`)] },
|
|
130
|
+
{ image: { url: media('meme.jpeg') }, title: 'Meme', body: 'A meme', buttons: [quickReplyButton('Viewonce', `${prefix}viewonce`)] },
|
|
131
|
+
{ image: { url: media('logo.png') }, title: 'Logo', body: 'The logo', buttons: [urlButton('Website', 'https://example.com')] }
|
|
132
|
+
]
|
|
133
|
+
}), { description: 'Carousel with image cards', category: 'Buttons' })
|
|
134
|
+
bot.command('widget', ctx => ctx.reply({
|
|
135
|
+
text: 'Widget demo',
|
|
136
|
+
footer: botName,
|
|
137
|
+
nativeFlow: [{ text: 'Menu', id: `${prefix}menu` }],
|
|
138
|
+
widget: {
|
|
139
|
+
align: 'center',
|
|
140
|
+
fallback: 'Widget cannot be loaded on this device',
|
|
141
|
+
items: [
|
|
142
|
+
{ text: `Welcome to ${botName}`, variant: 'title' },
|
|
143
|
+
{ text: 'This card is a widget (A2UI).', variant: 'body' },
|
|
144
|
+
{ divider: 'horizontal' },
|
|
145
|
+
{ choice: ['Red', 'Green', 'Blue'], label: 'Favorite color', variant: 'mutuallyExclusive', displayStyle: 'chips' },
|
|
146
|
+
{ slider: 100, min: 0, value: 50, label: 'Volume' },
|
|
147
|
+
{ button: 'Open website', url: 'https://example.com', variant: 'primary' }
|
|
148
|
+
]
|
|
149
|
+
}
|
|
150
|
+
}), { description: 'Widget with inputs and a button', category: 'Buttons' })
|
|
151
|
+
|
|
152
|
+
/* ------------------------------------------------------------------ Media */
|
|
153
|
+
const mediaCommand = (name, description, build) =>
|
|
154
|
+
bot.command(name, ctx => ctx.reply(build(ctx)), { description, category: 'Media', cooldownMs: 3000 })
|
|
155
|
+
mediaCommand('image', 'Send an image', () => ({ image: { url: media('cat.jpeg') }, caption: 'A cat' }))
|
|
156
|
+
mediaCommand('video', 'Send a video', () => ({ video: { url: media('ma_gif.mp4') }, caption: 'A short clip' }))
|
|
157
|
+
mediaCommand('gif', 'Send a gif', () => ({ video: { url: media('ma_gif.mp4') }, gifPlayback: true }))
|
|
158
|
+
mediaCommand('audio', 'Send an audio file', () => ({ audio: { url: media('sonata.mp3') }, mimetype: 'audio/mpeg' }))
|
|
159
|
+
mediaCommand('sticker', 'Send a sticker', () => ({ sticker: { url: media('octopus.webp') } }))
|
|
160
|
+
mediaCommand('doc', 'Send a document', () => ({ document: { url: media('cat.jpeg') }, mimetype: 'image/jpeg', fileName: 'cat.jpeg' }))
|
|
161
|
+
mediaCommand('viewonce', 'Send a view once image', () => ({ image: { url: media('meme.jpeg') }, caption: 'Only once', viewOnce: true }))
|
|
162
|
+
mediaCommand('album', 'Send an album', () => ({ album: [{ image: { url: media('cat.jpeg') } }, { image: { url: media('meme.jpeg') } }] }))
|
|
163
|
+
bot.command('pp', async ctx => {
|
|
164
|
+
const jid = targetOf(ctx) ?? ctx.sender
|
|
165
|
+
const url = await sock.profilePictureUrl(jid, 'image').catch(() => undefined)
|
|
166
|
+
return url ? ctx.reply({ image: { url }, caption: 'Profile picture' }) : ctx.reply('No profile picture (or it is private).')
|
|
167
|
+
}, { description: 'Profile picture of you, a reply or a mention', category: 'Media', cooldownMs: 5000 })
|
|
168
|
+
|
|
169
|
+
/* ------------------------------------------------------------------ Fun */
|
|
170
|
+
bot.command('poll', ctx => {
|
|
171
|
+
const [question, ...options] = ctx.args.join(' ').split('|').map(s => s.trim()).filter(Boolean)
|
|
172
|
+
if (!question || options.length < 2 || options.length > 12) return ctx.reply(`Usage: ${prefix}poll Question | Option 1 | Option 2 ... (2 to 12 options)`)
|
|
173
|
+
return sock.sendMessage(ctx.jid, { poll: { name: question, values: options, selectableCount: 1 } }, { quoted: ctx.msg })
|
|
174
|
+
}, { description: 'Make a poll: question | option | option', category: 'Fun', cooldownMs: 5000 })
|
|
175
|
+
bot.command('event', ctx => ctx.reply({
|
|
176
|
+
event: { name: ctx.args.join(' ') || 'Meetup', description: 'Created by the bot', startDate: new Date(Date.now() + 3600_000) }
|
|
177
|
+
}), { description: 'Event card that starts in one hour', category: 'Fun', cooldownMs: 5000 })
|
|
178
|
+
bot.command('location', ctx => ctx.reply({ location: { degreesLatitude: 6.9271, degreesLongitude: 79.8612, name: 'Colombo' } }), { description: 'Send a location', category: 'Fun' })
|
|
179
|
+
bot.command('react', ctx => sock.sendMessage(ctx.jid, { react: { text: ctx.args[0] || '๐', key: ctx.msg.key } }), { description: 'React to your message', category: 'Fun' })
|
|
180
|
+
bot.command('dice', ctx => ctx.reply(`๐ฒ ${1 + Math.floor(Math.random() * 6)}`), { description: 'Roll a dice', category: 'Fun' })
|
|
181
|
+
bot.command('coin', ctx => ctx.reply(Math.random() < 0.5 ? 'Heads' : 'Tails'), { description: 'Flip a coin', category: 'Fun' })
|
|
182
|
+
|
|
183
|
+
/* ------------------------------------------------------------------ AI rich */
|
|
184
|
+
bot.command('aitable', ctx => {
|
|
185
|
+
const rows = new Map()
|
|
186
|
+
for (const { names, meta } of bot.commands) if (meta.description && !meta.hidden) rows.set(meta.category ?? 'Other', (rows.get(meta.category ?? 'Other') ?? 0) + 1)
|
|
187
|
+
return sock.sendMessage(ctx.jid, {
|
|
188
|
+
aiRich: { title: botName, text: 'Commands per category', table: [['Category', 'Commands'], ...[...rows].map(([category, count]) => [category, String(count)])] }
|
|
189
|
+
}, { quoted: ctx.msg })
|
|
190
|
+
}, { description: 'AI rich message with a table', category: 'AI rich', cooldownMs: 5000 })
|
|
191
|
+
bot.command('aicode', ctx => sock.aiRich()
|
|
192
|
+
.setTitle(botName)
|
|
193
|
+
.addText('A code block in an AI rich message:')
|
|
194
|
+
.addCode('javascript', "console.log('Hello from the bot')")
|
|
195
|
+
.send(ctx.jid, { quoted: ctx.msg }), { description: 'AI rich message with a code block', category: 'AI rich', cooldownMs: 5000 })
|
|
196
|
+
|
|
197
|
+
/* ------------------------------------------------------------------ Group info and tools */
|
|
198
|
+
bot.command('groupinfo', async ctx => {
|
|
199
|
+
const metadata = await sock.groupMetadata(ctx.jid)
|
|
200
|
+
const admins = metadata.participants.filter(p => p.admin).length
|
|
201
|
+
const created = metadata.creation ? new Date(metadata.creation * 1000).toDateString() : 'unknown'
|
|
202
|
+
return ctx.reply(`*${metadata.subject}*\nMembers: ${metadata.participants.length}\nAdmins: ${admins}\nCreated: ${created}\n${metadata.desc ? `\n${metadata.desc}` : ''}`)
|
|
203
|
+
}, { description: 'Group name, members and admins', category: 'Group', groupOnly: true, cooldownMs: 5000 })
|
|
204
|
+
bot.command('tagall', withGroupAdmin((ctx, metadata) => {
|
|
205
|
+
const jids = metadata.participants.map(p => p.phoneNumber ?? p.id)
|
|
206
|
+
const note = ctx.args.join(' ') || 'Attention please'
|
|
207
|
+
return sock.sendMessage(ctx.jid, { text: `${note}\n\n${jids.map(jid => `@${digits(jid)}`).join(' ')}`, mentions: jids }, { quoted: ctx.msg })
|
|
208
|
+
}), { description: 'Mention everyone (admins, once a minute)', category: 'Group', groupOnly: true, cooldownMs: 60_000 })
|
|
209
|
+
|
|
210
|
+
/* ------------------------------------------------------------------ Group admin (the bot must be a group admin too) */
|
|
211
|
+
const memberAction = (name, action, description) =>
|
|
212
|
+
bot.command(name, withGroupAdmin(async (ctx) => {
|
|
213
|
+
const target = targetOf(ctx)
|
|
214
|
+
if (!target) return ctx.reply(`Reply to a user, @mention them or give a number: ${prefix}${name} 947XXXXXXXX`)
|
|
215
|
+
if (owners.map(digits).includes(digits(target)) && action !== 'add') return ctx.reply('The bot owner cannot be changed with this command.')
|
|
216
|
+
const result = await sock.groupParticipantsUpdate(ctx.jid, [target], action)
|
|
217
|
+
const status = result?.[0]?.status
|
|
218
|
+
return ctx.reply(!status || String(status) === '200' ? `Done: ${action} @${digits(target)}` : `WhatsApp answered ${status}. Is the bot a group admin?`)
|
|
219
|
+
}), { description, category: 'Group admin', groupOnly: true, cooldownMs: 2000 })
|
|
220
|
+
memberAction('kick', 'remove', 'Remove a member (reply, @mention or number)')
|
|
221
|
+
memberAction('add', 'add', 'Add a member by number')
|
|
222
|
+
memberAction('promote', 'promote', 'Make a member admin')
|
|
223
|
+
memberAction('demote', 'demote', 'Remove admin from a member')
|
|
224
|
+
bot.command('link', withGroupAdmin(async ctx => ctx.reply(`https://chat.whatsapp.com/${await sock.groupInviteCode(ctx.jid)}`)), { description: 'Group invite link', category: 'Group admin', groupOnly: true })
|
|
225
|
+
bot.command('revoke', withGroupAdmin(async ctx => { await sock.groupRevokeInvite(ctx.jid); return ctx.reply('Invite link reset.') }), { description: 'Reset the invite link', category: 'Group admin', groupOnly: true })
|
|
226
|
+
bot.command('gname', withGroupAdmin(async ctx => {
|
|
227
|
+
if (!ctx.args.length) return ctx.reply(`Usage: ${prefix}gname New name`)
|
|
228
|
+
await sock.groupUpdateSubject(ctx.jid, ctx.args.join(' '))
|
|
229
|
+
}), { description: 'Change the group name', category: 'Group admin', groupOnly: true })
|
|
230
|
+
bot.command('gdesc', withGroupAdmin(async ctx => {
|
|
231
|
+
await sock.groupUpdateDescription(ctx.jid, ctx.args.join(' ') || undefined)
|
|
232
|
+
}), { description: 'Change the group description', category: 'Group admin', groupOnly: true })
|
|
233
|
+
const settingCommand = (name, setting, description) =>
|
|
234
|
+
bot.command(name, withGroupAdmin(async ctx => { await sock.groupSettingUpdate(ctx.jid, setting); return ctx.reply(`Done: ${name}`) }), { description, category: 'Group admin', groupOnly: true })
|
|
235
|
+
settingCommand('mute', 'announcement', 'Only admins can send messages')
|
|
236
|
+
settingCommand('unmute', 'not_announcement', 'Everyone can send messages')
|
|
237
|
+
settingCommand('lock', 'locked', 'Only admins can edit group info')
|
|
238
|
+
settingCommand('unlock', 'unlocked', 'Everyone can edit group info')
|
|
239
|
+
|
|
240
|
+
/* ------------------------------------------------------------------ Calls */
|
|
241
|
+
bot.command('callme', async ctx => {
|
|
242
|
+
const voip = needVoip(ctx)
|
|
243
|
+
if (!voip) return
|
|
244
|
+
const call = await voip.call(ctx.sender, media('sonata.mp3'))
|
|
245
|
+
call.on('error', error => console.error('call error:', error.message))
|
|
246
|
+
return ctx.reply('Calling you now...')
|
|
247
|
+
}, { description: 'The bot calls you and plays music', category: 'Calls', privateOnly: true, cooldownMs: 60_000 })
|
|
248
|
+
bot.command('calls', ctx => {
|
|
249
|
+
const voip = needVoip(ctx)
|
|
250
|
+
if (!voip) return
|
|
251
|
+
const rows = voip.history.slice(-5).map(h => `${h.direction} ${h.peer} ${h.isVideo ? 'video' : 'audio'} ${Math.round((h.durationMs ?? 0) / 1000)}s`)
|
|
252
|
+
return ctx.reply(rows.join('\n') || 'No calls yet')
|
|
253
|
+
}, { description: 'Last 5 calls', category: 'Calls', ownerOnly: true })
|
|
254
|
+
bot.command('anticall', async ctx => {
|
|
255
|
+
const voip = needVoip(ctx)
|
|
256
|
+
if (!voip) return
|
|
257
|
+
const mode = ctx.args[0]?.toLowerCase()
|
|
258
|
+
if (mode === 'on') {
|
|
259
|
+
await stopCallHandlers()
|
|
260
|
+
state.antiCall = await voip.autoReject({ allow: owners, message: 'Calls are off. Please send a message.' })
|
|
261
|
+
return ctx.reply('Anti call is on. Incoming calls are rejected (owners are allowed).')
|
|
262
|
+
}
|
|
263
|
+
if (mode === 'off') { await stopCallHandlers(); return ctx.reply('Anti call is off.') }
|
|
264
|
+
return ctx.reply(`Usage: ${prefix}anticall on | off`)
|
|
265
|
+
}, { description: 'Reject incoming calls: on | off', category: 'Calls', ownerOnly: true })
|
|
266
|
+
bot.command('autoanswer', async ctx => {
|
|
267
|
+
const voip = needVoip(ctx)
|
|
268
|
+
if (!voip) return
|
|
269
|
+
const mode = ctx.args[0]?.toLowerCase()
|
|
270
|
+
if (mode === 'on') {
|
|
271
|
+
await stopCallHandlers()
|
|
272
|
+
const everyone = ctx.args[1]?.toLowerCase() === 'all'
|
|
273
|
+
state.autoAnswer = await voip.autoAnswer({ media: media('sonata.mp3'), delayMs: 2000, allow: everyone ? undefined : owners, onError: error => console.error('auto answer:', error.message) })
|
|
274
|
+
return ctx.reply(everyone ? 'Auto answer is on for EVERYONE. Anyone who calls hears the music.' : 'Auto answer is on for the owners only. Use "on all" for everyone.')
|
|
275
|
+
}
|
|
276
|
+
if (mode === 'off') { await stopCallHandlers(); return ctx.reply('Auto answer is off.') }
|
|
277
|
+
return ctx.reply(`Usage: ${prefix}autoanswer on [all] | off`)
|
|
278
|
+
}, { description: 'Answer calls with music: on [all] | off', category: 'Calls', ownerOnly: true })
|
|
279
|
+
|
|
280
|
+
/* ------------------------------------------------------------------ Owner */
|
|
281
|
+
const PRIVACY = {
|
|
282
|
+
lastseen: ['updateLastSeenPrivacy', ['all', 'contacts', 'contact_blacklist', 'none']],
|
|
283
|
+
online: ['updateOnlinePrivacy', ['all', 'match_last_seen']],
|
|
284
|
+
profile: ['updateProfilePicturePrivacy', ['all', 'contacts', 'contact_blacklist', 'none']],
|
|
285
|
+
status: ['updateStatusPrivacy', ['all', 'contacts', 'contact_blacklist', 'none']],
|
|
286
|
+
read: ['updateReadReceiptsPrivacy', ['all', 'none']],
|
|
287
|
+
groups: ['updateGroupsAddPrivacy', ['all', 'contacts', 'contact_blacklist']]
|
|
288
|
+
}
|
|
289
|
+
bot.command('privacy', async ctx => {
|
|
290
|
+
const [what, value] = ctx.args.map(a => a.toLowerCase())
|
|
291
|
+
const entry = PRIVACY[what]
|
|
292
|
+
if (!entry || !entry[1].includes(value)) return ctx.reply(Object.entries(PRIVACY).map(([k, [, values]]) => `${prefix}privacy ${k} ${values.join(' | ')}`).join('\n'))
|
|
293
|
+
await sock[entry[0]](value)
|
|
294
|
+
return ctx.reply(`Privacy ${what}: ${value}`)
|
|
295
|
+
}, { description: 'Change privacy: lastseen, online, profile, status, read, groups', category: 'Owner', ownerOnly: true })
|
|
296
|
+
for (const [name, action] of [['block', 'block'], ['unblock', 'unblock']]) {
|
|
297
|
+
bot.command(name, async ctx => {
|
|
298
|
+
const target = targetOf(ctx)
|
|
299
|
+
if (!target) return ctx.reply(`Reply to a user, @mention them or give a number: ${prefix}${name} 947XXXXXXXX`)
|
|
300
|
+
await sock.updateBlockStatus(target, action)
|
|
301
|
+
return ctx.reply(`Done: ${name} ${digits(target)}`)
|
|
302
|
+
}, { description: `${name[0].toUpperCase()}${name.slice(1)} a user`, category: 'Owner', ownerOnly: true })
|
|
303
|
+
}
|
|
304
|
+
bot.command('blocklist', async ctx => ctx.reply((await sock.fetchBlocklist()).map(jid => `+${digits(jid)}`).join('\n') || 'Nobody is blocked'), { description: 'Show blocked numbers', category: 'Owner', ownerOnly: true })
|
|
305
|
+
bot.command('bio', async ctx => { await sock.updateProfileStatus(ctx.args.join(' ')); return ctx.reply('Bio updated.') }, { description: 'Change the bot bio', category: 'Owner', ownerOnly: true })
|
|
306
|
+
bot.command('botname', async ctx => {
|
|
307
|
+
if (!ctx.args.length) return ctx.reply(`Usage: ${prefix}botname New name`)
|
|
308
|
+
await sock.updateProfileName(ctx.args.join(' '))
|
|
309
|
+
return ctx.reply('Name updated.')
|
|
310
|
+
}, { description: 'Change the bot profile name', category: 'Owner', ownerOnly: true })
|
|
311
|
+
bot.command('theme', async ctx => {
|
|
312
|
+
const THEMES = ['Default-Blue@Minimal', 'Emerald@Minimal', 'Pink@Minimal', 'Red@Minimal', 'Royal-Blue@Minimal', 'Tyrian-Purple@Minimal', 'WhatsApp-Green@Minimal']
|
|
313
|
+
if (!THEMES.includes(ctx.args[0])) return ctx.reply(`Themes:\n${THEMES.join('\n')}`)
|
|
314
|
+
await sock.setChatTheme(ctx.jid, ctx.args[0])
|
|
315
|
+
}, { description: 'Set the chat theme of this chat', category: 'Owner', ownerOnly: true })
|
|
316
|
+
bot.command('leave', async ctx => { await ctx.reply('Bye!'); await sock.groupLeave(ctx.jid) }, { description: 'Bot leaves this group', category: 'Owner', ownerOnly: true, groupOnly: true })
|
|
317
|
+
|
|
318
|
+
return state
|
|
319
|
+
}
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
// Full example bot: buttons, lists, carousel, widgets, media, polls, AI rich, group tools, calls and owner tools.
|
|
2
|
+
//
|
|
3
|
+
// node Example/full-bot.mjs (scan the QR code, no phone number needed)
|
|
4
|
+
// PHONE_NUMBER=947XXXXXXXX node Example/full-bot.mjs (pairing code instead of QR)
|
|
5
|
+
//
|
|
6
|
+
// Environment: OWNER_EMAIL (default anuhazdev@gmail.com), OWNER_NUMBER (optional, comma separated, needed for owner-only commands), PHONE_NUMBER, PREFIX (default .), BOT_NAME, SESSION_DIR (default ./auth)
|
|
7
|
+
// Needs ffmpeg (and ffprobe for calls) in PATH. Use a spare number first.
|
|
8
|
+
import makeWASocket, { useMultiFileAuthState, DisconnectReason, createCommandRouter, Browsers } from '../src/index.js'
|
|
9
|
+
import Voip from '../src/voip/index.js'
|
|
10
|
+
import { registerCommands } from './full-bot-commands.mjs'
|
|
11
|
+
|
|
12
|
+
const config = {
|
|
13
|
+
botName: process.env.BOT_NAME || 'My Bot',
|
|
14
|
+
prefix: process.env.PREFIX || '.',
|
|
15
|
+
ownerEmail: process.env.OWNER_EMAIL || 'anuhazdev@gmail.com',
|
|
16
|
+
owners: (process.env.OWNER_NUMBER || '').split(',').map(s => s.trim()).filter(Boolean),
|
|
17
|
+
phone: (process.env.PHONE_NUMBER || '').replace(/\D/g, ''),
|
|
18
|
+
session: process.env.SESSION_DIR || './auth'
|
|
19
|
+
}
|
|
20
|
+
if (!config.owners.length) console.warn('OWNER_NUMBER is not set, owner commands will answer "Owner only".')
|
|
21
|
+
|
|
22
|
+
const DENIED = {
|
|
23
|
+
owner_only: 'This command is for the bot owner.',
|
|
24
|
+
group_only: 'Use this command in a group.',
|
|
25
|
+
private_only: 'Use this command in a private chat.'
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
const start = async () => {
|
|
29
|
+
const { state, saveCreds } = await useMultiFileAuthState(config.session)
|
|
30
|
+
const sock = makeWASocket({
|
|
31
|
+
auth: state,
|
|
32
|
+
printQRInTerminal: !config.phone,
|
|
33
|
+
syncFullHistory: false,
|
|
34
|
+
markOnlineOnConnect: false,
|
|
35
|
+
browser: Browsers.ubuntu('Chrome')
|
|
36
|
+
})
|
|
37
|
+
sock.ev.on('creds.update', saveCreds)
|
|
38
|
+
|
|
39
|
+
let voip
|
|
40
|
+
const bot = createCommandRouter(sock, {
|
|
41
|
+
prefix: config.prefix,
|
|
42
|
+
owners: config.owners,
|
|
43
|
+
onDenied: (ctx, reason, waitMs) => ctx.reply(reason === 'cooldown' ? `Wait ${Math.ceil(waitMs / 1000)}s before using ${config.prefix}${ctx.command} again.` : DENIED[reason]),
|
|
44
|
+
onError: (error, ctx) => {
|
|
45
|
+
console.error(`command ${ctx.command} failed:`, error)
|
|
46
|
+
return ctx.reply(`Something went wrong: ${error?.message ?? error}`).catch(() => {})
|
|
47
|
+
}
|
|
48
|
+
})
|
|
49
|
+
registerCommands(bot, { sock, getVoip: () => voip, config })
|
|
50
|
+
bot.attach()
|
|
51
|
+
|
|
52
|
+
let pairingRequested = false
|
|
53
|
+
sock.ev.on('connection.update', async ({ connection, lastDisconnect, qr }) => {
|
|
54
|
+
if (qr && config.phone && !pairingRequested) {
|
|
55
|
+
pairingRequested = true
|
|
56
|
+
try {
|
|
57
|
+
console.log('Pairing code:', await sock.requestPairingCode(config.phone))
|
|
58
|
+
} catch (error) {
|
|
59
|
+
console.error('Could not request a pairing code:', error.message)
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
if (connection === 'open') {
|
|
63
|
+
voip = new Voip(sock, { maxConcurrentCalls: 2, tmpDir: './tmp' })
|
|
64
|
+
console.log('Connected as', sock.user?.id)
|
|
65
|
+
}
|
|
66
|
+
if (connection === 'close') {
|
|
67
|
+
voip = undefined
|
|
68
|
+
const code = lastDisconnect?.error?.output?.statusCode
|
|
69
|
+
if (code === DisconnectReason.loggedOut) return console.log(`Logged out. Delete ${config.session} and run again to link a new device.`)
|
|
70
|
+
if (code === DisconnectReason.connectionReplaced) return console.log('This session was opened somewhere else. Not reconnecting.')
|
|
71
|
+
console.log(`Connection closed (${code}), reconnecting...`)
|
|
72
|
+
setTimeout(start, 1000)
|
|
73
|
+
}
|
|
74
|
+
})
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
start()
|
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 # : ๐ต๐๐๐ !ยก </>
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|