AUXteam commited on
Commit
87ab1e4
Β·
verified Β·
1 Parent(s): 6dfbc12

Upload folder using huggingface_hub

Browse files
Files changed (2) hide show
  1. frontend.py +42 -25
  2. src/app.ts +23 -11
frontend.py CHANGED
@@ -20,20 +20,21 @@ def get_status():
20
  def update_ui():
21
  status = get_status()
22
  if not status:
23
- return "Backend Offline", "Waiting for Node.js to start...", "No logs available"
24
 
25
- msg = f"Status: {status.get('whatsappStatus', 'Unknown')}\nConnected: {status.get('connected')}\nReady: {status.get('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
  ascii_qr = qr_data['ascii']
33
  qr_html = f"""
34
- <div style='background:white; color:black; padding:20px; display:flex; flex-direction:column; align-items:center;'>
35
- <pre style='font-size:7px; line-height:1; margin:0; font-family:monospace;'>{ascii_qr}</pre>
36
- <p style='margin-top:10px; font-weight:bold;'>Scan this code with your phone</p>
 
37
  </div>
38
  """
39
  except:
@@ -45,8 +46,8 @@ def update_ui():
45
 
46
  def trigger_init():
47
  try:
48
- r = requests.post(f"{NODE_URL}/init")
49
- return "Initialization requested. Click 'Refresh' in a few seconds."
50
  except Exception as e:
51
  return f"Error: {str(e)}"
52
 
@@ -58,35 +59,51 @@ def send_poll(number, title, options):
58
  except Exception as e:
59
  return {"error": str(e)}
60
 
 
 
 
 
 
 
 
61
  with gr.Blocks(theme=gr.themes.Default()) as demo:
62
- gr.Markdown("# πŸ€– WPPConnect WhatsApp Control")
63
 
64
  with gr.Row():
65
  with gr.Column(scale=1):
66
- status_display = gr.Textbox(label="System Status", lines=3)
67
- init_btn = gr.Button("πŸš€ Start/Retry WhatsApp", variant="primary")
68
- refresh_btn = gr.Button("πŸ”„ Refresh Status/QR")
 
69
  with gr.Column(scale=2):
70
  qr_display = gr.HTML(label="QR Code")
71
 
72
- with gr.Tab("Send Poll"):
73
- poll_num = gr.Textbox(label="Phone Number (e.g. 5511999999999)")
74
- poll_title = gr.Textbox(label="Question")
75
- poll_opts = gr.Textbox(label="Options (comma separated)")
76
- poll_send = gr.Button("Send Poll")
77
- poll_output = gr.JSON(label="Result")
 
 
 
 
 
 
 
 
 
78
 
79
- log_display = gr.Code(label="Internal Logs", language="markdown")
 
80
 
81
  init_btn.click(trigger_init, outputs=status_display)
82
  refresh_btn.click(update_ui, outputs=[status_display, qr_display, log_display])
83
- poll_send.click(send_poll, inputs=[poll_num, poll_title, poll_opts], outputs=poll_output)
 
84
 
85
- # Try to use every if Gradio version is new enough, otherwise fallback
86
- try:
87
- demo.load(update_ui, outputs=[status_display, qr_display, log_display], every=10)
88
- except:
89
- demo.load(update_ui, outputs=[status_display, qr_display, log_display])
90
 
91
  if __name__ == "__main__":
92
  demo.launch(server_name="0.0.0.0", server_port=7860)
 
20
  def update_ui():
21
  status = get_status()
22
  if not status:
23
+ return "Backend Offline", "Waiting for Node.js...", ""
24
 
25
+ msg = f"Status: {status.get('whatsappStatus', 'Unknown')}\nConnected: {status.get('connected', False)}\nReady: {status.get('ready', False)}"
26
 
27
+ qr_html = "No QR code available yet. Click 'Start WhatsApp Session'."
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
  ascii_qr = qr_data['ascii']
33
  qr_html = f"""
34
+ <div style='background:white; color:black; padding:15px; display:flex; flex-direction:column; align-items:center; border-radius:8px;'>
35
+ <h3 style='margin:0 0 10px 0;'>WhatsApp QR Code</h3>
36
+ <pre style='font-size:7px; line-height:1; margin:0; font-family:monospace; font-weight:bold;'>{ascii_qr}</pre>
37
+ <p style='margin-top:10px; font-size:12px;'>Scan this with your WhatsApp mobile app</p>
38
  </div>
39
  """
40
  except:
 
46
 
47
  def trigger_init():
48
  try:
49
+ requests.post(f"{NODE_URL}/init")
50
+ return "Initialization triggered. Waiting for QR..."
51
  except Exception as e:
52
  return f"Error: {str(e)}"
53
 
 
59
  except Exception as e:
60
  return {"error": str(e)}
61
 
62
+ def send_message(number, message):
63
+ try:
64
+ r = requests.post(f"{NODE_URL}/send-message", json={"telnumber": number, "message": message})
65
+ return r.json()
66
+ except Exception as e:
67
+ return {"error": str(e)}
68
+
69
  with gr.Blocks(theme=gr.themes.Default()) as demo:
70
+ gr.Markdown("# πŸ€– WPPConnect WhatsApp Control Panel")
71
 
72
  with gr.Row():
73
  with gr.Column(scale=1):
74
+ status_display = gr.Textbox(label="System Status", lines=3, interactive=False)
75
+ init_btn = gr.Button("πŸš€ Start WhatsApp Session", variant="primary")
76
+ refresh_btn = gr.Button("πŸ”„ Refresh Status")
77
+
78
  with gr.Column(scale=2):
79
  qr_display = gr.HTML(label="QR Code")
80
 
81
+ with gr.Tabs():
82
+ with gr.TabItem("πŸ’¬ Send Message"):
83
+ with gr.Row():
84
+ msg_num = gr.Textbox(label="Phone Number", placeholder="e.g. 5511999999999")
85
+ msg_txt = gr.Textbox(label="Message", lines=2)
86
+ msg_btn = gr.Button("Send Text", variant="secondary")
87
+ msg_out = gr.JSON(label="Result")
88
+
89
+ with gr.TabItem("πŸ“Š Send Poll"):
90
+ with gr.Row():
91
+ poll_num = gr.Textbox(label="Phone Number")
92
+ poll_title = gr.Textbox(label="Poll Question")
93
+ poll_opts = gr.Textbox(label="Choices (comma separated)", placeholder="Yes, No, Maybe")
94
+ poll_btn = gr.Button("Send Poll", variant="secondary")
95
+ poll_out = gr.JSON(label="Result")
96
 
97
+ with gr.Accordion("πŸ“‹ System Logs", open=False):
98
+ log_display = gr.Code(label="Recent logs", lines=10, language="markdown")
99
 
100
  init_btn.click(trigger_init, outputs=status_display)
101
  refresh_btn.click(update_ui, outputs=[status_display, qr_display, log_display])
102
+ msg_btn.click(send_message, inputs=[msg_num, msg_txt], outputs=msg_out)
103
+ poll_btn.click(send_poll, inputs=[poll_num, poll_title, poll_opts], outputs=poll_out)
104
 
105
+ # Auto-refresh UI on load
106
+ demo.load(update_ui, outputs=[status_display, qr_display, log_display])
 
 
 
107
 
108
  if __name__ == "__main__":
109
  demo.launch(server_name="0.0.0.0", server_port=7860)
src/app.ts CHANGED
@@ -1,13 +1,9 @@
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;
@@ -23,7 +19,7 @@ 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());
@@ -74,7 +70,23 @@ async function startWPP() {
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 });
@@ -82,7 +94,7 @@ async function startWPP() {
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';
@@ -102,14 +114,14 @@ async function startWPP() {
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);
 
1
  import express from 'express';
2
  import * as wppconnect from './index';
3
  import dns from 'dns';
4
+ import { Resolver } from 'dns';
5
  import fs from 'fs';
6
+ import path from 'path';
 
 
 
 
7
 
8
  const app = express();
9
  const port = process.env.NODE_PORT || 3000;
 
19
  const entry = `${new Date().toISOString()} - ${msg}`;
20
  console.log(entry);
21
  appLogs.push(entry);
22
+ if (appLogs.length > 100) appLogs.shift();
23
  };
24
 
25
  app.use(express.json());
 
70
  statusMsg = 'Initializing...';
71
  log('Starting WPPConnect...');
72
 
73
+ // Try to get IP for web.whatsapp.com manually
74
+ let waIP = '157.240.22.60'; // Default fallback
75
+ try {
76
+ const resolver = new Resolver();
77
+ resolver.setServers(['8.8.8.8', '1.1.1.1']);
78
+ const addrs = await new Promise<string[]>((resolve, reject) => {
79
+ resolver.resolve4('web.whatsapp.com', (err, addresses) => err ? reject(err) : resolve(addresses));
80
+ });
81
+ if (addrs && addrs.length > 0) {
82
+ waIP = addrs[0];
83
+ log(`Resolved web.whatsapp.com to ${waIP}`);
84
+ }
85
+ } catch (e) {
86
+ log(`DNS check failed, using fallback IP ${waIP}`);
87
+ }
88
+
89
+ // Cleanup tokens to avoid locks
90
  try {
91
  const tokensDir = path.join(process.cwd(), 'tokens');
92
  if (fs.existsSync(tokensDir)) fs.rmSync(tokensDir, { recursive: true, force: true });
 
94
 
95
  try {
96
  whatsappClient = await wppconnect.create({
97
+ session: 'hf-session-' + Date.now(),
98
  catchQR: (base64, ascii) => {
99
  lastQR = { base64, ascii };
100
  statusMsg = 'Waiting for scan';
 
114
  '--disable-setuid-sandbox',
115
  '--disable-dev-shm-usage',
116
  '--disable-gpu',
117
+ `--host-resolver-rules=MAP web.whatsapp.com ${waIP}`,
118
  ],
119
  },
120
  autoClose: 0,
121
  updatesLog: false,
122
  waitForLogin: false,
123
  });
124
+ log('Client ready');
125
  isInitializing = false;
126
  } catch (e) {
127
  log('Init Error: ' + e.message);