AUXteam commited on
Commit
1be4e49
·
verified ·
1 Parent(s): d074942

Upload folder using huggingface_hub

Browse files
Files changed (2) hide show
  1. frontend.py +48 -25
  2. src/app.ts +44 -14
frontend.py CHANGED
@@ -22,18 +22,22 @@ def update_ui():
22
  if not status:
23
  return "Backend Offline", "Waiting for Node.js to start...", ""
24
 
25
- msg = f"WhatsApp Status: {status['whatsappStatus']}\nConnected: {status['connected']}\nReady: {status['ready']}"
26
 
27
- qr_text = ""
28
  try:
29
  qr_r = requests.get(f"{NODE_URL}/qr-data", timeout=1)
30
  if qr_r.status_code == 200:
31
- qr_text = qr_r.json()['ascii']
 
 
 
 
 
 
32
  except:
33
  pass
34
 
35
- qr_html = f"<html><body style='background:white;color:black;padding:10px;display:flex;justify-content:center;'><pre style='font-size:6px;line-height:1;margin:0;'>{qr_text}</pre></body></html>" if qr_text else "No QR code generated yet."
36
-
37
  logs = "\n".join(status.get('logs', []))
38
 
39
  return msg, qr_html, logs
@@ -41,7 +45,7 @@ def update_ui():
41
  def trigger_init():
42
  try:
43
  requests.post(f"{NODE_URL}/init")
44
- return "Initialization triggered."
45
  except Exception as e:
46
  return f"Error: {str(e)}"
47
 
@@ -53,30 +57,49 @@ def send_poll(number, title, options):
53
  except Exception as e:
54
  return {"error": str(e)}
55
 
56
- with gr.Blocks(title="WPPConnect") as demo:
57
- gr.Markdown("# 🤖 WPPConnect Control Panel")
 
 
 
 
 
 
 
58
 
59
  with gr.Row():
60
- with gr.Column():
61
- status_text = gr.Label(label="System Status")
62
- init_btn = gr.Button("🚀 Start/Retry WhatsApp", variant="primary")
63
- with gr.Column():
64
- qr_display = gr.HTML(label="WhatsApp QR Code")
65
-
66
- with gr.Tab("Send Poll"):
67
- poll_number = gr.Textbox(label="Phone Number (with country code)")
68
- poll_title = gr.Textbox(label="Poll Question")
69
- poll_options = gr.Textbox(label="Options (comma separated)")
70
- poll_send = gr.Button("Send Poll")
71
- poll_output = gr.JSON(label="Result")
72
 
73
- with gr.Accordion("System Logs", open=False):
74
- log_display = gr.Code(label="Logs", language="markdown", lines=10)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
75
 
76
- init_btn.click(trigger_init, outputs=status_text)
77
- poll_send.click(send_poll, inputs=[poll_number, poll_title, poll_options], outputs=poll_output)
 
 
78
 
79
- demo.load(update_ui, outputs=[status_text, qr_display, log_display], every=5)
 
80
 
81
  if __name__ == "__main__":
82
  demo.launch(server_name="0.0.0.0", server_port=7860)
 
22
  if not status:
23
  return "Backend Offline", "Waiting for Node.js to start...", ""
24
 
25
+ msg = f"Status: {status['whatsappStatus']}\nConnected: {status['connected']}\nReady: {status['ready']}"
26
 
27
+ qr_html = "No QR code generated yet."
28
  try:
29
  qr_r = requests.get(f"{NODE_URL}/qr-data", timeout=1)
30
  if qr_r.status_code == 200:
31
+ qr_data = qr_r.json()
32
+ qr_html = f\"\"\"
33
+ <div style='background:white; color:black; padding:20px; display:flex; flex-direction:column; align-items:center;'>
34
+ <pre style='font-size:7px; line-height:1; margin:0; font-family:monospace;'>{qr_data['ascii']}</pre>
35
+ <p style='margin-top:10px; font-weight:bold;'>Scan this code with your phone</p>
36
+ </div>
37
+ \"\"\"
38
  except:
39
  pass
40
 
 
 
41
  logs = "\n".join(status.get('logs', []))
42
 
43
  return msg, qr_html, logs
 
45
  def trigger_init():
46
  try:
47
  requests.post(f"{NODE_URL}/init")
48
+ return "Initialization requested. Please wait 30-60 seconds and check logs."
49
  except Exception as e:
50
  return f"Error: {str(e)}"
51
 
 
57
  except Exception as e:
58
  return {"error": str(e)}
59
 
60
+ def send_message(number, message):
61
+ try:
62
+ r = requests.post(f"{NODE_URL}/send-message", json={"telnumber": number, "message": message})
63
+ return r.json()
64
+ except Exception as e:
65
+ return {"error": str(e)}
66
+
67
+ with gr.Blocks(theme=gr.themes.Soft()) as demo:
68
+ gr.Markdown("# 🤖 WPPConnect WhatsApp Dashboard")
69
 
70
  with gr.Row():
71
+ with gr.Column(scale=1):
72
+ status_display = gr.Label(label="System Status")
73
+ init_btn = gr.Button("🚀 Start WhatsApp Session", variant="primary")
74
+ refresh_btn = gr.Button("🔄 Force Refresh UI")
 
 
 
 
 
 
 
 
75
 
76
+ with gr.Column(scale=2):
77
+ qr_display = gr.HTML(label="WhatsApp QR Code", value="Waiting for initialization...")
78
+
79
+ with gr.Tabs():
80
+ with gr.TabItem("💬 Send Message"):
81
+ msg_num = gr.Textbox(label="Phone Number", placeholder="e.g. 5511999999999")
82
+ msg_txt = gr.Textbox(label="Message", lines=3)
83
+ msg_btn = gr.Button("Send Text")
84
+ msg_out = gr.JSON(label="Result")
85
+
86
+ with gr.TabItem("📊 Send Poll"):
87
+ poll_num = gr.Textbox(label="Phone Number")
88
+ poll_title = gr.Textbox(label="Question")
89
+ poll_opts = gr.Textbox(label="Options", placeholder="Option 1, Option 2, Option 3")
90
+ poll_btn = gr.Button("Send Poll")
91
+ poll_out = gr.JSON(label="Result")
92
+
93
+ with gr.Accordion("📋 System Logs", open=True):
94
+ log_display = gr.Textbox(label="Recent logs", lines=10, interactive=False)
95
 
96
+ init_btn.click(trigger_init, outputs=status_display)
97
+ refresh_btn.click(update_ui, outputs=[status_display, qr_display, log_display])
98
+ msg_btn.click(send_message, inputs=[msg_num, msg_txt], outputs=msg_out)
99
+ poll_btn.click(send_poll, inputs=[poll_num, poll_title, poll_opts], outputs=poll_out)
100
 
101
+ # Auto-refresh every 5 seconds
102
+ demo.load(update_ui, outputs=[status_display, qr_display, log_display], every=5)
103
 
104
  if __name__ == "__main__":
105
  demo.launch(server_name="0.0.0.0", server_port=7860)
src/app.ts CHANGED
@@ -1,22 +1,29 @@
1
  import express from 'express';
2
  import * as wppconnect from './index';
3
- import fs from 'fs';
4
  import path from 'path';
 
 
 
 
 
 
5
 
6
  const app = express();
7
  const port = process.env.NODE_PORT || 3000;
8
 
9
  let whatsappClient: wppconnect.Whatsapp | null = null;
10
- let lastQR: { ascii: string } | null = null;
11
- let statusMsg: string = 'Offline';
12
  let appLogs: string[] = [];
13
  let isReady = false;
 
14
 
15
  const log = (msg: string) => {
16
  const entry = `${new Date().toISOString()} - ${msg}`;
17
  console.log(entry);
18
  appLogs.push(entry);
19
- if (appLogs.length > 100) appLogs.shift();
20
  };
21
 
22
  app.use(express.json());
@@ -38,33 +45,48 @@ app.get('/qr-data', (req, res) => {
38
  });
39
 
40
  app.post('/init', (req, res) => {
41
- log('Manual init triggered');
42
  startWPP();
43
  res.json({ success: true });
44
  });
45
 
 
 
 
 
 
 
 
 
 
46
  app.post('/send-poll', async (req, res) => {
47
  const { telnumber, name, choices } = req.body;
48
  if (!whatsappClient || !isReady) return res.status(503).json({ error: 'WhatsApp not ready' });
49
  try {
50
  const result = await whatsappClient.sendPollMessage(`${telnumber}@c.us`, name, choices);
51
  res.json({ success: true, result });
52
- } catch (e) {
53
- log('Poll Error: ' + e.message);
54
- res.status(500).json({ error: e.message });
55
- }
56
  });
57
 
58
  async function startWPP() {
 
 
59
  statusMsg = 'Initializing...';
60
  log('Starting WPPConnect...');
61
 
 
 
 
 
 
 
62
  try {
63
  whatsappClient = await wppconnect.create({
64
  session: 'hf-session',
65
- catchQR: (b64, ascii) => {
66
- lastQR = { ascii };
67
  statusMsg = 'Waiting for scan';
 
68
  },
69
  statusFind: (status) => {
70
  statusMsg = status;
@@ -75,19 +97,27 @@ async function startWPP() {
75
  useChrome: false,
76
  puppeteerOptions: {
77
  executablePath: '/usr/bin/chromium',
78
- args: ['--no-sandbox', '--disable-setuid-sandbox', '--disable-dev-shm-usage', '--disable-gpu'],
 
 
 
 
 
 
79
  },
80
  autoClose: 0,
81
  updatesLog: false,
82
  waitForLogin: false,
83
  });
84
- log('Client Created');
 
85
  } catch (e) {
86
  log('Init Error: ' + e.message);
87
  statusMsg = 'Error: ' + e.message;
 
88
  }
89
  }
90
 
91
  app.listen(port, () => {
92
- log(`Node Backend started on port ${port}`);
93
  });
 
1
  import express from 'express';
2
  import * as wppconnect from './index';
3
+ import dns from 'dns';
4
  import path from 'path';
5
+ import fs from 'fs';
6
+
7
+ // Attempt to use public DNS
8
+ try {
9
+ dns.setServers(['1.1.1.1', '8.8.8.8']);
10
+ } catch (e) {}
11
 
12
  const app = express();
13
  const port = process.env.NODE_PORT || 3000;
14
 
15
  let whatsappClient: wppconnect.Whatsapp | null = null;
16
+ let lastQR: { ascii: string, base64: string } | null = null;
17
+ let statusMsg: string = 'Disconnected';
18
  let appLogs: string[] = [];
19
  let isReady = false;
20
+ let isInitializing = false;
21
 
22
  const log = (msg: string) => {
23
  const entry = `${new Date().toISOString()} - ${msg}`;
24
  console.log(entry);
25
  appLogs.push(entry);
26
+ if (appLogs.length > 200) appLogs.shift();
27
  };
28
 
29
  app.use(express.json());
 
45
  });
46
 
47
  app.post('/init', (req, res) => {
48
+ if (isInitializing) return res.json({ success: false, message: 'Already initializing' });
49
  startWPP();
50
  res.json({ success: true });
51
  });
52
 
53
+ app.post('/send-message', async (req, res) => {
54
+ const { telnumber, message } = req.body;
55
+ if (!whatsappClient || !isReady) return res.status(503).json({ error: 'WhatsApp not ready' });
56
+ try {
57
+ const result = await whatsappClient.sendText(`${telnumber}@c.us`, message);
58
+ res.json({ success: true, result });
59
+ } catch (e) { res.status(500).json({ error: e.message }); }
60
+ });
61
+
62
  app.post('/send-poll', async (req, res) => {
63
  const { telnumber, name, choices } = req.body;
64
  if (!whatsappClient || !isReady) return res.status(503).json({ error: 'WhatsApp not ready' });
65
  try {
66
  const result = await whatsappClient.sendPollMessage(`${telnumber}@c.us`, name, choices);
67
  res.json({ success: true, result });
68
+ } catch (e) { res.status(500).json({ error: e.message }); }
 
 
 
69
  });
70
 
71
  async function startWPP() {
72
+ if (isInitializing) return;
73
+ isInitializing = true;
74
  statusMsg = 'Initializing...';
75
  log('Starting WPPConnect...');
76
 
77
+ // Cleanup tokens
78
+ try {
79
+ const tokensDir = path.join(process.cwd(), 'tokens');
80
+ if (fs.existsSync(tokensDir)) fs.rmSync(tokensDir, { recursive: true, force: true });
81
+ } catch (e) {}
82
+
83
  try {
84
  whatsappClient = await wppconnect.create({
85
  session: 'hf-session',
86
+ catchQR: (base64, ascii) => {
87
+ lastQR = { base64, ascii };
88
  statusMsg = 'Waiting for scan';
89
+ log('QR generated');
90
  },
91
  statusFind: (status) => {
92
  statusMsg = status;
 
97
  useChrome: false,
98
  puppeteerOptions: {
99
  executablePath: '/usr/bin/chromium',
100
+ args: [
101
+ '--no-sandbox',
102
+ '--disable-setuid-sandbox',
103
+ '--disable-dev-shm-usage',
104
+ '--disable-gpu',
105
+ '--dns-servers=1.1.1.1,8.8.8.8'
106
+ ],
107
  },
108
  autoClose: 0,
109
  updatesLog: false,
110
  waitForLogin: false,
111
  });
112
+ log('Client object created');
113
+ isInitializing = false;
114
  } catch (e) {
115
  log('Init Error: ' + e.message);
116
  statusMsg = 'Error: ' + e.message;
117
+ isInitializing = false;
118
  }
119
  }
120
 
121
  app.listen(port, () => {
122
+ log(`Node Backend on port ${port}`);
123
  });