Skip to content

Instantly share code, notes, and snippets.

@starch0
Created March 1, 2024 20:24
Show Gist options
  • Save starch0/adbb63c65429264b1f8b83606637b89c to your computer and use it in GitHub Desktop.
Save starch0/adbb63c65429264b1f8b83606637b89c to your computer and use it in GitHub Desktop.
NodeJS, Whatsappweb, qrcode, express
const axios = require('axios')
const qrcode = require('qrcode-terminal')
const { Client, LocalAuth} = require('whatsapp-web.js')
require('dotenv').config()
const OpenAI = require('openai')
const express = require('express')
const app = express()
const openai = new OpenAI({
apiKey: process.env.wlOpenKey,
})
const client = new Client({
authStrategy: new LocalAuth()
})
client.on('qr', (qr) => {
console.log(qr)
qrcode.generate(qr, { small: true })
})
client.on('message', async (message) => {
console.log(`${message.from} disse: ${message.body}`)
})
client.on('message', async (message) => {
const userInput = message.body
const chatCompletion = await openai.chat.completions.create({
model: 'gpt-3.5-turbo',
prompt: `User: ${userInput}\nAI:`,
})
const aiResponse = chatCompletion.choices[0].text
const recipientNumber = '+xxxxxxxxxxx'
await sendToWhatsapp(recipientNumber, aiResponse)
res.json({ aiResponse })
console.log(`msg: ${message.body}, de: ${message.from}`)
})
async function sendToWhatsapp(number, message) {
const chat = await client.getChatById(number + '@c.us')
await chat.sendMessage(message)
}
client.on('ready', () => {
console.log('🔥')
})
client.initialize()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment