-
Notifications
You must be signed in to change notification settings - Fork 38
/
index.js
116 lines (101 loc) · 2.61 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
const { WAConnection, MessageType } = require("@adiwajshing/baileys")
const fs = require("fs")
const http = require("http")
const qrcode = require("qrcode")
const express = require("express")
const socketIO = require("socket.io")
const port = 8000 || process.env.PORT
const wa = new WAConnection()
const app = express()
const server = http.createServer(app)
const io = socketIO(server)
wa.connectOptions.alwaysUseTakeover = false
app.use(express.json())
app.use(express.urlencoded({
extended: true
}))
app.use("/assets", express.static(__dirname + "/client/assets"))
app.get("/", (req, res) => {
res.sendFile("./client/server.html", {
root: __dirname
})
})
app.get("/client", (req, res) => {
res.sendFile("./client/index.html", {
root: __dirname
})
})
io.on("connection", async socket => {
socket.emit("log", "Connecting...")
wa.on("qr", qr => {
qrcode.toDataURL(qr, (err, url) => {
socket.emit("qr", url)
socket.emit("log", "QR Code received, please scan!")
})
})
wa.on("open", res => {
socket.emit("qrstatus", "./assets/check.svg")
socket.emit("log", "WhatsApp terhubung!")
socket.emit("log", res)
})
wa.on("close", res => {
socket.emit("log", "WhatsApp terputus!")
socket.emit("log", res)
})
// wa.on('chat-update', async chat => {
// if (chat.hasNewMessage) {
// const m = chat.messages.all()[0]
// console.log(m)
// if (!m.key.fromMe) {
// await wa.sendMessage (m.key.remoteJid, 'masih nub, belum tau apa apa (人 •͈ᴗ•͈)', MessageType.text)
// }
// }
// })
switch (wa.state) {
case "close":
await wa.connect()
break
case "open":
socket.emit("qrstatus", "./assets/check.svg")
socket.emit("log", "WhatsApp terhubung!")
break
default:
socket.emit("log", wa.state)
}
})
app.post('/send-message', async (req, res) => {
const message = req.body.message
const number = req.body.number
if (wa.state === "open") {
const exists = await wa.isOnWhatsApp(number)
if (exists) {
wa.sendMessage(exists.jid, message, MessageType.text)
.then(result => {
res.status(200).json({
status: true,
response: result
})
})
.catch(err => {
res.status(500).json({
status: false,
response: err
})
})
} else {
res.status(500).json({
status: false,
response: `Nomor ${number} tidak terdaftar.`
})
}
} else {
res.status(500).json({
status: false,
response: `WhatsApp belum terhubung.`
})
}
})
server.listen(port, () => {
console.log(`Server berjalan di http://localhost:${port}`)
console.log(`Aplikasi Client di http://localhost:${port}/client`)
})