Skip to content

Commit

Permalink
Merge pull request #4 from Debanjan-San/main
Browse files Browse the repository at this point in the history
Updated the index.js
  • Loading branch information
well300 authored Apr 23, 2024
2 parents 8dbe584 + f7162c1 commit dfa94a4
Show file tree
Hide file tree
Showing 5 changed files with 187 additions and 4,443 deletions.
3 changes: 3 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
CHATGPT_API_URL=https://ultimetron.guruapi.tech/gpt4
DALLE_API_URL=https://api.maher-zubair.tech/ai/photoleap
PREFIX=/
189 changes: 49 additions & 140 deletions index.js
Original file line number Diff line number Diff line change
@@ -1,147 +1,56 @@
import { makeWASocket } from '@whiskeysockets/baileys';
import pino from 'pino';
import axios from 'axios';
import dotenv from 'dotenv';

dotenv.config();

const CHATGPT_API_URL = process.env.CHATGPT_API_URL;
const DALLE_API_URL = process.env.DALLE_API_URL;

const logger = pino({ level: 'silent' });

const client = makeWASocket({
logger: logger
});

client.ev.on('conn', async (status) => {
logger.info('📱 Scan the QR code below to log in:');
logger.info(status.qrCode);
});

client.ev.on('open', () => {
logger.info('✅ Authentication complete');
});

client.ev.on('message-new', async (message) => {
const sender = message.key.remoteJid;
const messageContent = message.message.conversation;

logger.info(`👤 From: ${sender}`);
logger.info(`💬 Message: ${messageContent}`);

// Handle message content and respond accordingly
// Example:
if (messageContent.startsWith('/dalle')) {
const text = messageContent.replace('/dalle', '').trim();
try {
const imageBase64 = await getDALLEImage(text);

if (imageBase64) {
const media = {
key: {
fromMe: true,
participant: '[email protected]',
remoteJid: sender
},
message: {
imageMessage: {
url: `data:image/jpeg;base64,${imageBase64}`,
mimetype: 'image/jpeg',
caption: 'DALL·E generated image'
}
}
};

logger.info('📸 Sending DALL·E generated image');
client.interface.send('sendMessage', { ...media });
} else {
throw new Error('Failed to generate DALL·E image');
import ws from '@whiskeysockets/baileys'
const { default: makeWASocket, DisconnectReason, useMultiFileAuthState, fetchLatestBaileysVersion } = ws
import { remove } from 'fs-extra'
import { serialize } from './lib/waClient.js'
import * as dotenv from 'dotenv'
import axios from 'axios'
import P from 'pino'
import { Boom } from '@hapi/boom'

dotenv.config()

const start = async () => {
const { state, saveCreds } = await useMultiFileAuthState("session")
const client = makeWASocket({
version: (await fetchLatestBaileysVersion()).version,
auth: state,
logger: P({ level: 'silent' }),
printQRInTerminal: true
})

//connection updates
client.ev.on('connection.update', async (update) => {
const { connection, lastDisconnect } = update
if (update.qr) console.log(`Scan the QR code!!`)
if (connection === 'close') {
const { statusCode } = new Boom(lastDisconnect?.error).output
if (statusCode !== DisconnectReason.loggedOut) setTimeout(() => start(), 3000)
else {
console.log('Disconnected :"(')
await remove("session")
console.log('Starting...')
setTimeout(() => start(), 3000)
}
} catch (dalleError) {
logger.error(`❌ ${dalleError.message}`);
client.interface.send('sendMessage', {
key: {
fromMe: true,
participant: '[email protected]',
remoteJid: sender
},
message: {
conversation: '❌ Failed to generate DALL·E image'
}
});
}
} else {
const response = await getChatGPTResponse(messageContent);
const emojiResponse = addEmojis(response);

logger.info(`✉️ Response: ${emojiResponse}`);
client.interface.send('sendMessage', {
key: {
fromMe: true,
participant: '[email protected]',
remoteJid: sender
},
message: {
conversation: emojiResponse
}
});
}
});

async function getChatGPTResponse(text) {
try {
const response = await axios.get(`${CHATGPT_API_URL}?prompt=${encodeURIComponent(text)}`);
if (response.data.status) {
return response.data.result;
} else {
throw new Error(`API error: ${response.data.result}`);
if (connection === 'connecting') console.log('Connecting to WhatsApp!!')
if (connection === 'open') console.log('Connected to WhatsApp')

})
client.ev.on('messages.upsert', async ({ messages, type }) => {
if (type !== 'notify') return
const M = serialize(JSON.parse(JSON.stringify(messages[0])), client)
if (M.quoted?.participant) M.mentions.push(M.quoted.participant)
console.log(M.body)
if (
M.mentions.includes(client.user.id.split(':')[0] + '@s.whatsapp.net')
) {
const text = await axios.get(`https://oni-chan-unique-api.vercel.app/gpt4?text=${M.body}`)
M.reply(text.data.result)
}
} catch (error) {
logger.error(`❌ Error calling ChatGPT API: ${error.message}`);
throw new Error('Error calling ChatGPT API');
}
}

async function getDALLEImage(text) {
try {
const response = await axios.get(`${DALLE_API_URL}?text=${encodeURIComponent(text)}`, { responseType: 'arraybuffer' });
const data = Buffer.from(response.data, 'binary').toString('base64');
return data;
} catch (error) {
logger.error(`❌ Error calling DALL·E API: ${error.message}`);
throw new Error('Error calling DALL·E API');
}
}

function addEmojis(response) {
// Add emojis based on conditions or keywords in the response
let emojiResponse = '*🤖 Response:* ' + response;

if (response.toLowerCase().includes('hello')) {
emojiResponse += ' 👋';
} else if (response.toLowerCase().includes('thank you')) {
emojiResponse += ' 🙏';
} else if (response.toLowerCase().includes('good morning')) {
emojiResponse += ' 🌅';
} else if (response.toLowerCase().includes('good night')) {
emojiResponse += ' 🌃';
} else if (response.toLowerCase().includes('good evening')) {
emojiResponse += ' 🌆';
} else if (response.toLowerCase().includes('good afternoon')) {
emojiResponse += ' ☀️';
} else if (response.toLowerCase().includes('good day')) {
emojiResponse += ' 🌤️';
}

return emojiResponse;
}

async function main() {
await client.connect();
})
client.ev.on('creds.update', saveCreds)
}

main().catch((error) => {
logger.error(`❗️ ${error.message}`);
process.exit(1);
});
start()
115 changes: 115 additions & 0 deletions lib/waClient.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
import { getContentType, jidDecode } from '@whiskeysockets/baileys'

export const decodeJid = (jid) => {
const { user, server } = jidDecode(jid) || {}
return user && server ? `${user}@${server}`.trim() : jid
}

export const serialize = (messages, client) => {
if (messages.key) {
messages.id = messages.key.id
messages.isSelf = messages.key.fromMe
messages.from = decodeJid(messages.key.remoteJid)
messages.isGroup = messages.from.endsWith('@g.us')
messages.sender = messages.isGroup
? decodeJid(messages.key.participant)
: messages.isSelf
? decodeJid(client.user.id)
: messages.from
}
if (messages.message) {
messages.type = getContentType(messages.message)
if (messages.type === 'ephemeralMessage') {
messages.message = messages.message[messages.type].message
const tipe = Object.keys(messages.message)[0]
messages.type = tipe
if (tipe === 'viewOnceMessageV2') {
messages.message = messages.message[messages.type].message
messages.type = getContentType(messages.message)
}
}
if (messages.type === 'viewOnceMessageV2') {
messages.message = messages.message[messages.type].message
messages.type = getContentType(messages.message)
}
messages.messageTypes = (type) => ['videoMessage', 'imageMessage'].includes(type)
try {
const quoted = messages.message[messages.type]?.contextInfo
if (quoted.quotedMessage['ephemeralMessage']) {
const tipe = Object.keys(quoted.quotedMessage.ephemeralMessage.message)[0]
if (tipe === 'viewOnceMessageV2') {
messages.quoted = {
type: 'view_once',
stanzaId: quoted.stanzaId,
participant: decodeJid(quoted.participant),
message: quoted.quotedMessage.ephemeralMessage.message.viewOnceMessage.message
}
} else {
messages.quoted = {
type: 'ephemeral',
stanzaId: quoted.stanzaId,
participant: decodeJid(quoted.participant),
message: quoted.quotedMessage.ephemeralMessage.message
}
}
} else if (quoted.quotedMessage['viewOnceMessageV2']) {
messages.quoted = {
type: 'view_once',
stanzaId: quoted.stanzaId,
participant: decodeJid(quoted.participant),
message: quoted.quotedMessage.viewOnceMessage.message
}
} else {
messages.quoted = {
type: 'normal',
stanzaId: quoted.stanzaId,
participant: decodeJid(quoted.participant),
message: quoted.quotedMessage
}
}
messages.quoted.isSelf = messages.quoted.participant === decodeJid(client.user.id)
messages.quoted.mtype = Object.keys(messages.quoted.message).filter(
(v) => v.includes('Message') || v.includes('conversation')
)[0]
messages.quoted.text =
messages.quoted.message[messages.quoted.mtype]?.text ||
messages.quoted.message[messages.quoted.mtype]?.description ||
messages.quoted.message[messages.quoted.mtype]?.caption ||
messages.quoted.message[messages.quoted.mtype]?.hydratedTemplate?.hydratedContentText ||
messages.quoted.message[messages.quoted.mtype] ||
''
messages.quoted.key = {
id: messages.quoted.stanzaId,
fromMe: messages.quoted.isSelf,
remoteJid: messages.from
}
messages.quoted.download = () => downloadMedia(messages.quoted.message)
} catch {
messages.quoted = null
}
messages.body =
messages.message?.conversation ||
messages.message?.[messages.type]?.text ||
messages.message?.[messages.type]?.caption ||
(messages.type === 'listResponseMessage' &&
messages.message?.[messages.type]?.singleSelectReply?.selectedRowId) ||
(messages.type === 'buttonsResponseMessage' && messages.message?.[messages.type]?.selectedButtonId) ||
(messages.type === 'templateButtonReplyMessage' && messages.message?.[messages.type]?.selectedId) ||
''
messages.reply = (text) =>
client.sendMessage(
messages.from,
{
text
},
{
quoted: messages
}
)
messages.mentions = []
if (messages.quoted?.participant) messages.mentions.push(messages.quoted.participant)
const array = messages?.message?.[messages.type]?.contextInfo?.mentionedJid || []
messages.mentions.push(...array.filter(Boolean))
}
return messages
}
Loading

0 comments on commit dfa94a4

Please sign in to comment.