hfgghfg commited on
Commit
bfbb431
·
verified ·
1 Parent(s): 0da6704

Upload index.js with huggingface_hub

Browse files
Files changed (1) hide show
  1. index.js +42 -118
index.js CHANGED
@@ -10,6 +10,7 @@ import dotenv from 'dotenv';
10
  import { fileURLToPath } from 'url';
11
  import { dirname, join } from 'path';
12
  import { readFileSync, existsSync, mkdirSync } from 'fs';
 
13
 
14
  // Load .env
15
  const __filename = fileURLToPath(import.meta.url);
@@ -24,9 +25,6 @@ app.use(express.json());
24
  // Configuration
25
  // ====================================
26
  const ADMIN_PHONE = process.env.ADMIN_PHONE || '201108279642';
27
- const OPENROUTER_API_KEY = process.env.VITE_OPENROUTER_API_KEY;
28
- const AI_MODEL = 'amazon/nova-lite-v1';
29
- // Hugging Face Spaces REQUIRE port 7860
30
  const PORT = 7860;
31
 
32
  // ====================================
@@ -35,7 +33,7 @@ const PORT = 7860;
35
  let isClientReady = false;
36
  let qrCodeData = null;
37
  let initializationRetries = 0;
38
- const MAX_RETRIES = 5;
39
 
40
  const client = new Client({
41
  authStrategy: new LocalAuth({
@@ -53,7 +51,10 @@ const client = new Client({
53
  '--no-zygote',
54
  '--disable-gpu',
55
  '--disable-extensions',
56
- '--disable-software-rasterizer'
 
 
 
57
  ]
58
  }
59
  });
@@ -61,7 +62,7 @@ const client = new Client({
61
  // QR Code Event
62
  client.on('qr', (qr) => {
63
  qrCodeData = qr;
64
- console.log('\n📱 QR Code Generated. Scan it to connect.\n');
65
  qrcode.generate(qr, { small: true });
66
  });
67
 
@@ -69,102 +70,53 @@ client.on('qr', (qr) => {
69
  client.on('ready', () => {
70
  isClientReady = true;
71
  qrCodeData = null;
72
- initializationRetries = 0;
73
  console.log('\n✅ WhatsApp Client is Ready!');
74
  });
75
 
76
- // Authentication Success
77
- client.on('authenticated', () => {
78
- console.log('🔐 Authenticated successfully!');
79
- });
80
-
81
- // Auth Failure
82
- client.on('auth_failure', (msg) => {
83
- console.error('❌ Authentication failure:', msg);
84
- });
85
-
86
  // Disconnected Event
87
  client.on('disconnected', (reason) => {
88
  isClientReady = false;
89
  console.log('❌ Disconnected:', reason);
90
- setTimeout(() => {
91
- console.log('🔄 Re-initializing...');
92
- initializeClient();
93
- }, 5000);
94
  });
95
 
96
  // ====================================
97
- // Initialization Logic with Retry
98
  // ====================================
 
 
 
 
 
 
 
 
 
 
 
 
 
 
99
  async function initializeClient() {
100
- try {
101
- // Ensure session directory exists
102
- const sessionPath = join(__dirname, 'whatsapp-session');
103
- if (!existsSync(sessionPath)) {
104
- mkdirSync(sessionPath, { recursive: true });
105
- }
 
 
106
 
 
107
  console.log('⏳ Initializing WhatsApp Client...');
108
  await client.initialize();
109
  } catch (error) {
110
  console.error('❌ Initialization Error:', error.message);
111
-
112
  if (initializationRetries < MAX_RETRIES) {
113
  initializationRetries++;
114
- const delay = 10000 * initializationRetries;
115
- console.log(`🔄 Retry ${initializationRetries}/${MAX_RETRIES} in ${delay/1000}s...`);
116
- setTimeout(initializeClient, delay);
117
- } else {
118
- console.error('💥 Max retries reached. Please check internet connection or logs.');
119
- }
120
- }
121
- }
122
-
123
- // ====================================
124
- // AI Message Generator
125
- // ====================================
126
- async function generateAIMessage(eventType, data) {
127
- if (!OPENROUTER_API_KEY) {
128
- return generateDefaultMessage(eventType, data);
129
- }
130
-
131
- const prompt = `أنت مساعد ذكي لنظام 7STAR CRM. اكتب رسالة واتساب قصيرة ومنسقة بالإيموجي للحدث التالي:
132
- نوع الحدث: ${eventType}
133
- البيانات: ${JSON.stringify(data, null, 2)}
134
- القواعد: اكتب بالعربية، استخدم إيموجي، اجعلها مختصرة، لا تستخدم Markdown، أضف توقيع "✨ 7STAR CRM"`;
135
-
136
- try {
137
- const response = await fetch('https://openrouter.ai/api/v1/chat/completions', {
138
- method: 'POST',
139
- headers: {
140
- 'Authorization': `Bearer ${OPENROUTER_API_KEY}`,
141
- 'Content-Type': 'application/json'
142
- },
143
- body: JSON.stringify({
144
- model: AI_MODEL,
145
- messages: [{ role: 'user', content: prompt }],
146
- temperature: 0.7,
147
- max_tokens: 500
148
- })
149
- });
150
-
151
- const result = await response.json();
152
- if (result.choices && result.choices[0]?.message?.content) {
153
- return result.choices[0].message.content.trim();
154
  }
155
- } catch (error) {
156
- console.error('❌ AI Error:', error.message);
157
  }
158
-
159
- return generateDefaultMessage(eventType, data);
160
- }
161
-
162
- function generateDefaultMessage(eventType, data) {
163
- const templates = {
164
- new_order: `🛒 طلب جديد!\n👤 العميل: ${data.customer_name || 'غير محدد'}\n💰 المبلغ: ${data.total_amount || 0} ج.م\n✨ 7STAR CRM`,
165
- custom: data.message || 'إشعار من 7STAR CRM'
166
- };
167
- return templates[eventType] || templates.custom;
168
  }
169
 
170
  // ====================================
@@ -172,62 +124,34 @@ function generateDefaultMessage(eventType, data) {
172
  // ====================================
173
 
174
  app.get('/', (req, res) => {
175
- res.send('<h1>7STAR WhatsApp Server is Running</h1><p>Go to <a href="/qr">/qr</a> to scan.</p>');
176
  });
177
 
178
  app.get('/status', (req, res) => {
179
- res.json({
180
- connected: isClientReady,
181
- qrCode: !!qrCodeData,
182
- adminPhone: ADMIN_PHONE
183
- });
184
  });
185
 
186
  app.get('/qr', (req, res) => {
187
- if (isClientReady) {
188
- res.send('<h1>✅ WhatsApp Connected!</h1>');
189
- return;
190
- }
191
- if (!qrCodeData) {
192
- res.send('<h1>⏳ Initializing... Please refresh in 10 seconds.</h1><meta http-equiv="refresh" content="10">');
193
- return;
194
- }
195
  const qrImageUrl = `https://api.qrserver.com/v1/create-qr-code/?size=300x300&data=${encodeURIComponent(qrCodeData)}`;
196
- res.send(`
197
- <div style="text-align:center;font-family:sans-serif;padding:50px;">
198
- <h1>📱 Scan QR Code</h1>
199
- <img src="${qrImageUrl}" style="border:10px solid white;box-shadow:0 0 20px rgba(0,0,0,0.1);margin:20px;">
200
- <p>Open WhatsApp > Linked Devices > Link a Device</p>
201
- <meta http-equiv="refresh" content="30">
202
- </div>
203
- `);
204
  });
205
 
206
  app.post('/send', async (req, res) => {
207
  try {
208
  const { phone, message } = req.body;
209
- if (!message) return res.status(400).json({ error: 'message is required' });
210
- if (!isClientReady) return res.status(503).json({ error: 'WhatsApp not connected' });
211
-
212
- const targetPhone = phone || ADMIN_PHONE;
213
- const chatId = `${targetPhone.replace('+', '')}@c.us`;
214
  await client.sendMessage(chatId, message);
215
-
216
- res.json({ success: true, message: 'Sent successfully' });
217
  } catch (error) {
218
  res.status(500).json({ error: error.message });
219
  }
220
  });
221
 
222
- // ====================================
223
- // Start Server
224
- // ====================================
225
  app.listen(PORT, '0.0.0.0', () => {
226
- console.log('\n========================================');
227
- console.log(' 🚀 7STAR WhatsApp Server');
228
- console.log('========================================\n');
229
  console.log(`📡 Server running on port: ${PORT}`);
230
-
231
- // Start WhatsApp
232
  initializeClient();
233
  });
 
10
  import { fileURLToPath } from 'url';
11
  import { dirname, join } from 'path';
12
  import { readFileSync, existsSync, mkdirSync } from 'fs';
13
+ import dns from 'dns';
14
 
15
  // Load .env
16
  const __filename = fileURLToPath(import.meta.url);
 
25
  // Configuration
26
  // ====================================
27
  const ADMIN_PHONE = process.env.ADMIN_PHONE || '201108279642';
 
 
 
28
  const PORT = 7860;
29
 
30
  // ====================================
 
33
  let isClientReady = false;
34
  let qrCodeData = null;
35
  let initializationRetries = 0;
36
+ const MAX_RETRIES = 10;
37
 
38
  const client = new Client({
39
  authStrategy: new LocalAuth({
 
51
  '--no-zygote',
52
  '--disable-gpu',
53
  '--disable-extensions',
54
+ '--disable-software-rasterizer',
55
+ '--proxy-server="direct://"',
56
+ '--proxy-bypass-list=*',
57
+ '--dns-prefetch-disable'
58
  ]
59
  }
60
  });
 
62
  // QR Code Event
63
  client.on('qr', (qr) => {
64
  qrCodeData = qr;
65
+ console.log('\n📱 QR Code Generated.');
66
  qrcode.generate(qr, { small: true });
67
  });
68
 
 
70
  client.on('ready', () => {
71
  isClientReady = true;
72
  qrCodeData = null;
 
73
  console.log('\n✅ WhatsApp Client is Ready!');
74
  });
75
 
 
 
 
 
 
 
 
 
 
 
76
  // Disconnected Event
77
  client.on('disconnected', (reason) => {
78
  isClientReady = false;
79
  console.log('❌ Disconnected:', reason);
80
+ setTimeout(initializeClient, 5000);
 
 
 
81
  });
82
 
83
  // ====================================
84
+ // Connectivity Check & Initialization
85
  // ====================================
86
+ async function checkConnectivity() {
87
+ return new Promise((resolve) => {
88
+ dns.lookup('web.whatsapp.com', (err) => {
89
+ if (err) {
90
+ console.error('🌐 DNS Lookup Failed for web.whatsapp.com');
91
+ resolve(false);
92
+ } else {
93
+ console.log('🌐 DNS Lookup Success!');
94
+ resolve(true);
95
+ }
96
+ });
97
+ });
98
+ }
99
+
100
  async function initializeClient() {
101
+ const hasInternet = await checkConnectivity();
102
+
103
+ if (!hasInternet && initializationRetries < MAX_RETRIES) {
104
+ initializationRetries++;
105
+ console.log(`⏳ Waiting for network... Retry ${initializationRetries}/${MAX_RETRIES}`);
106
+ setTimeout(initializeClient, 10000);
107
+ return;
108
+ }
109
 
110
+ try {
111
  console.log('⏳ Initializing WhatsApp Client...');
112
  await client.initialize();
113
  } catch (error) {
114
  console.error('❌ Initialization Error:', error.message);
 
115
  if (initializationRetries < MAX_RETRIES) {
116
  initializationRetries++;
117
+ setTimeout(initializeClient, 15000);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
118
  }
 
 
119
  }
 
 
 
 
 
 
 
 
 
 
120
  }
121
 
122
  // ====================================
 
124
  // ====================================
125
 
126
  app.get('/', (req, res) => {
127
+ res.send('<h1>7STAR WhatsApp Server</h1><p><a href="/qr">View QR Code</a></p>');
128
  });
129
 
130
  app.get('/status', (req, res) => {
131
+ res.json({ connected: isClientReady, qrCode: !!qrCodeData });
 
 
 
 
132
  });
133
 
134
  app.get('/qr', (req, res) => {
135
+ if (isClientReady) return res.send('<h1>✅ Connected!</h1>');
136
+ if (!qrCodeData) return res.send('<h1>⏳ Initializing... Refresh in 10s</h1><meta http-equiv="refresh" content="10">');
137
+
 
 
 
 
 
138
  const qrImageUrl = `https://api.qrserver.com/v1/create-qr-code/?size=300x300&data=${encodeURIComponent(qrCodeData)}`;
139
+ res.send(`<div style="text-align:center;padding:50px;"><h1>📱 Scan QR</h1><img src="${qrImageUrl}"><meta http-equiv="refresh" content="30"></div>`);
 
 
 
 
 
 
 
140
  });
141
 
142
  app.post('/send', async (req, res) => {
143
  try {
144
  const { phone, message } = req.body;
145
+ if (!isClientReady) return res.status(503).json({ error: 'Not connected' });
146
+ const chatId = `${(phone || ADMIN_PHONE).replace('+', '')}@c.us`;
 
 
 
147
  await client.sendMessage(chatId, message);
148
+ res.json({ success: true });
 
149
  } catch (error) {
150
  res.status(500).json({ error: error.message });
151
  }
152
  });
153
 
 
 
 
154
  app.listen(PORT, '0.0.0.0', () => {
 
 
 
155
  console.log(`📡 Server running on port: ${PORT}`);
 
 
156
  initializeClient();
157
  });