Thanks to visit codestin.com
Credit goes to github.com

Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
76 changes: 76 additions & 0 deletions hd
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
const { default: makeWASocket, useSingleFileAuthState, DisconnectReason } = require("@whiskeysockets/baileys")
const { Configuration, OpenAIApi } = require("openai")
const { Boom } = require("@hapi/boom")

const { state, saveState } = useSingleFileAuthState('./auth_info.json')

// Your OpenAI API key here
const OPENAI_API_KEY = 'YOUR_OPENAI_API_KEY_HERE'

const openai = new OpenAIApi(new Configuration({
apiKey: OPENAI_API_KEY
}))

async function askAI(prompt) {
try {
const res = await openai.createChatCompletion({
model: "gpt-3.5-turbo",
messages: [{ role: "user", content: prompt }],
})
return res.data.choices[0].message.content
} catch (err) {
console.error("❌ OpenAI Error:", err.message)
return "Oops! I'm having some trouble thinking right now. Please try again later."
}
}

async function startBot() {
const sock = makeWASocket({
auth: state,
printQRInTerminal: true
})

sock.ev.on("creds.update", saveState)

// Track chats we already greeted
const greetedChats = new Set()

sock.ev.on("messages.upsert", async ({ messages }) => {
const msg = messages[0]
if (!msg.message || msg.key.fromMe) return

const from = msg.key.remoteJid
const text = msg.message.conversation || msg.message.extendedTextMessage?.text

if (text) {
if (!greetedChats.has(from)) {
// Send friendly welcome message once per chat session
await sock.sendMessage(from, { text: `👋 Hi! I’m Thamari Maposa, your friendly AI assistant. How can I help you today? 😊` })
greetedChats.add(from)
return
}

console.log(`📩 Message from ${from}: ${text}`)

// Ask AI and get friendly reply
let reply = await askAI(text)

// Make reply more friendly by adding bot name
reply = `🤖 Thamari Maposa says: ${reply}`

await sock.sendMessage(from, { text: reply })
}
})

sock.ev.on("connection.update", (update) => {
const { connection, lastDisconnect } = update
if (connection === 'close') {
const shouldReconnect = (lastDisconnect.error = Boom)?.output?.statusCode !== DisconnectReason.loggedOut
if (shouldReconnect) startBot()
} else if (connection === 'open') {
console.log("✅ Thamari Maposa is connected to WhatsApp")
}
})
}

startBot()