Skip to content

Commit

Permalink
feat: add support for remote session storage using mongoDB
Browse files Browse the repository at this point in the history
  • Loading branch information
Zain-ul-din committed Sep 6, 2024
1 parent 4fb8bb7 commit 3163c79
Show file tree
Hide file tree
Showing 6 changed files with 291 additions and 47 deletions.
3 changes: 2 additions & 1 deletion .env.example
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
OPENAI_API_KEY=ADD_YOUR_KEY
DREAMSTUDIO_API_KEY=ADD_YOUR_KEY
GEMINI_API_KEY=ADD_YOUR_KEY
HF_TOKEN=HUGGING_FACE_TOKEN
HF_TOKEN=HUGGING_FACE_TOKEN
MONGO_URL=YOUR_MONGO_DB_URL
2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@
"@types/qrcode-terminal": "^0.12.0",
"@whiskeysockets/baileys": "^6.7.7",
"dotenv": "^16.0.3",
"mongo-baileys": "^1.0.1",
"mongodb": "^6.8.0",
"openai": "^4.56.0",
"ora": "3.2.0",
"qrcode-terminal": "^0.12.0",
Expand Down
8 changes: 7 additions & 1 deletion src/lib/baileys/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,15 @@ import { Boom } from '@hapi/boom';
import * as fs from 'fs';
import path from 'path';
import { messagesHandler } from './handlers/messages';
import { useMongoDBAuthState } from 'mongo-baileys';
import { ENV } from '../env';
import { connectToMongoDB } from '../mongo-db';

export async function connectToWhatsApp() {
const { state, saveCreds } = await useMultiFileAuthState('auth_info_baileys');
const { state, saveCreds } =
ENV.MONGO_URL !== undefined
? await useMongoDBAuthState((await connectToMongoDB()).collection as any)
: await useMultiFileAuthState('auth_info_baileys');
const sock = makeWASocket({ printQRInTerminal: true, auth: state });

sock.ev.on('connection.update', async (update) => {
Expand Down
3 changes: 2 additions & 1 deletion src/lib/env.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,5 +7,6 @@ export const ENV = {
openAIKey: process.env.OPENAI_API_KEY,
dreamStudioKey: process.env.DREAMSTUDIO_API_KEY,
geminiKey: process.env.GEMINI_API_KEY,
HFKey: process.env.HF_TOKEN
HFKey: process.env.HF_TOKEN,
MONGO_URL: process.env.MONGO_URL
};
16 changes: 16 additions & 0 deletions src/lib/mongo-db/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { MongoClient } from 'mongodb';
import { ENV } from '../env';
import { AuthenticationCreds } from '@whiskeysockets/baileys';

interface AuthDocument extends Document {
_id: string;
creds?: AuthenticationCreds;
}

export async function connectToMongoDB() {
const client = new MongoClient(ENV.MONGO_URL || '');
await client.connect();
const db = client.db('whatsappAIBot');
const collection = db.collection<AuthDocument>('authState');
return { client, collection };
}
Loading

0 comments on commit 3163c79

Please sign in to comment.