1
- const whatsapp = require ( 'whatsapp-web.js' ) ;
1
+ const { Client } = require ( 'whatsapp-web.js' ) ;
2
2
const qrcode = require ( 'qrcode-terminal' ) ;
3
3
const fs = require ( 'fs' ) ;
4
4
const path = require ( 'path' ) ;
5
5
6
6
const FILE_NAME = 'session.json' ;
7
7
8
- class Session extends whatsapp . Client {
8
+ /**
9
+ * Starting point for interacting with the WhatsApp Web API.
10
+ * @param {string } SESSION_FILE_PATH - Path to `session.json` file.
11
+ * @see https://docs.wwebjs.dev/Client.html
12
+ * @extends {Client }
13
+ */
14
+ class Session extends Client {
9
15
constructor ( ) {
10
16
super ( {
11
17
puppeteer : {
@@ -16,22 +22,36 @@ class Session extends whatsapp.Client {
16
22
this . SESSION_FILE_PATH = path . join ( __dirname , FILE_NAME ) ;
17
23
}
18
24
25
+ /**
26
+ * Checks if the `session.json` file already exists.
27
+ * @returns {boolean } - `True` if exists, `False` if not.
28
+ */
19
29
get exists ( ) {
20
30
return fs . existsSync ( this . SESSION_FILE_PATH ) ;
21
31
}
22
32
33
+ /**
34
+ * Throws the QR-Code to authenticate the session. When the QR-Code is read, the session file is written.
35
+ */
23
36
create ( ) {
24
37
this . on ( 'qr' , ( qr ) => {
25
38
qrcode . generate ( qr , { small : true } ) ;
26
39
} ) ;
27
40
this . on ( 'authenticated' , this . save ) ;
28
41
}
29
42
43
+ /**
44
+ * Writes the session in a .json file (`this.SESSION_FILE_PATH`)
45
+ * @param {object } session - The session file returned in the authentication.
46
+ */
30
47
save ( session ) {
31
48
fs . writeFileSync ( this . SESSION_FILE_PATH , JSON . stringify ( session ) ) ;
32
49
console . log ( '⚠ The current session has been saved ⚠' ) ;
33
50
}
34
51
52
+ /**
53
+ * Loads the saved session file.
54
+ */
35
55
load ( ) {
36
56
if ( ! this . exists ) {
37
57
throw Error ( `session data does not exist in ${ this . SESSION_FILE_PATH } ` ) ;
@@ -44,6 +64,9 @@ class Session extends whatsapp.Client {
44
64
console . log ( '⚠ The previous session was loaded ⚠' ) ;
45
65
}
46
66
67
+ /**
68
+ * Starts the session.
69
+ */
47
70
start ( ) {
48
71
this . on ( 'ready' , ( ) => {
49
72
console . log ( 'Client is ready!' ) ;
0 commit comments