logger

Self-hosted WhatsApp logger us...
Log | Files | Refs | README | LICENSE

commit 0f05beebb36f4276c818e2e1f585c670817506e2
parent 6b58ce04847b63d0282dedeb06a6160eec8f0830
Author: Amit Dutta <amitdutta4255@gmail.com>
Date:   Mon, 16 Feb 2026 17:02:08 +0530

restart

Diffstat:
DData/Procfile | 3---
DData/message_log.json | 20--------------------
DMain.py | 104-------------------------------------------------------------------------------
DProcfile | 3---
DRequirements.txt | 18------------------
Dai.py | 32--------------------------------
Dindex.js | 118-------------------------------------------------------------------------------
Dpackage.json | 20--------------------
8 files changed, 0 insertions(+), 318 deletions(-)

diff --git a/Data/Procfile b/Data/Procfile @@ -1,2 +0,0 @@ -web: python Main.py -bot: node index.js- \ No newline at end of file diff --git a/Data/message_log.json b/Data/message_log.json @@ -1,19 +0,0 @@ -[ - { - "timestamp": "2025-09-26 17:05:34", - "sender": "917439454418@s.whatsapp.net", - "content": "Hi" - }, - { - "id": "AC3E680C66B7EE67BECDB0DEE33982D1", - "timestamp": "2025-09-26 17:10:19", - "sender": "917439454418@s.whatsapp.net", - "content": "Hello" - }, - { - "id": "ACCDB6B50D89550C3C30F11493C69537", - "timestamp": "2025-09-26 17:10:46", - "sender": "917439454418@s.whatsapp.net", - "content": "How are you?" - } -]- \ No newline at end of file diff --git a/Main.py b/Main.py @@ -1,104 +0,0 @@ -import os -import json -from datetime import datetime -from flask import Flask, request, jsonify, render_template_string - -# Initialize a Flask web application -app = Flask(__name__) - -# Define the log file path -log_dir = "Data" -log_file = os.path.join(log_dir, "message_log.json") - -# Ensure the Data directory exists -if not os.path.exists(log_dir): - os.makedirs(log_dir) - -# Ensure the log file exists and is a valid JSON array -if not os.path.exists(log_file) or os.path.getsize(log_file) == 0: - with open(log_file, "w", encoding='utf-8') as f: - f.write("[]") - -def log_message(sender_id, message_content): - """ - Logs a new message to a JSON file. - Each message is stored with a timestamp, sender ID, and content. - """ - timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S") - message_entry = { - "timestamp": timestamp, - "sender": sender_id, - "content": message_content - } - - # Read existing log or create a new one - try: - with open(log_file, "r", encoding='utf-8') as f: - log_data = json.load(f) - except (FileNotFoundError, json.JSONDecodeError): - log_data = [] - - # Append the new message entry and save - log_data.append(message_entry) - with open(log_file, "w", encoding='utf-8') as f: - json.dump(log_data, f, indent=4) - print(f"Logged message from {sender_id}") - -@app.route("/health", methods=["GET"]) -def health_check(): - """ - Provides a simple health check endpoint. - Returns a 200 OK status for services like UptimeRobot. - """ - return "OK", 200 - -@app.route("/logs", methods=["GET"]) -def show_logs(): - """ - Displays all logged messages in a human-readable format. - """ - try: - with open(log_file, "r", encoding='utf-8') as f: - log_data = json.load(f) - except FileNotFoundError: - return render_template_string("<h1>No messages have been logged yet.</h1>") - except json.JSONDecodeError: - return render_template_string("<h1>No messages have been logged yet.</h1>") - - if not log_data: - return render_template_string("<h1>No messages have been logged yet.</h1>") - - # Create an HTML-formatted string for display - log_html = "<h1>Recorded Messages</h1>" - for entry in log_data: - log_html += f""" - <div style="border: 1px solid #ccc; margin: 10px; padding: 10px; border-radius: 8px;"> - <strong>Timestamp:</strong> {entry['timestamp']}<br> - <strong>From:</strong> {entry['sender']}<br> - <p><strong>Message:</strong><br>{entry['content']}</p> - </div> - """ - return render_template_string(log_html) - -@app.route("/save_message", methods=["POST"]) -def save_message(): - """ - Endpoint to receive messages from the Node.js client and log them. - """ - try: - data = request.json - sender = data.get("sender") - query = data.get("query") - - if not sender or not query: - return jsonify({"error": "Missing sender or query"}), 400 - - log_message(sender, query) - return jsonify({"status": "success", "message": "Message logged successfully"}), 200 - - except Exception as e: - return jsonify({"error": str(e)}), 500 - -# Run the Flask app on a local server -if __name__ == "__main__": - app.run(host='0.0.0.0', port=5000) diff --git a/Procfile b/Procfile @@ -1,2 +0,0 @@ -web: python Main.py -bot: node index.js- \ No newline at end of file diff --git a/Requirements.txt b/Requirements.txt @@ -1,18 +0,0 @@ -python-dotenv -groq -elevenlabs -appopener -pywhatkit -bs4 -pillow -rich -requests -keyboard -cohere -googlesearch-python -selenium -mtranslate -pygame -edge-tts -PyQt5 -webdriver-manager diff --git a/ai.py b/ai.py @@ -1,32 +0,0 @@ -import sys -import requests -import json -import shutil -import os - -# Fix encoding for emojis/unicode output -sys.stdout.reconfigure(encoding='utf-8') - -if len(sys.argv) < 3: - print("No query or sender provided.") - sys.exit() - -query = sys.argv[1] -sender = sys.argv[2] - -try: - # Send the message data to the Python logging server - payload = { - "sender": sender, - "query": query - } - - response = requests.post("http://localhost:5000/save_message", json=payload) - response.raise_for_status() # Raise an exception for bad status codes (4xx or 5xx) - - print("✅ Message successfully sent to logging server.") - -except requests.exceptions.RequestException as e: - print(f"❌ Error sending message to logging server: {e}") -except Exception as e: - print(f"❌ An unexpected error occurred: {e}") diff --git a/index.js b/index.js @@ -1,118 +0,0 @@ -import makeWASocket, { - makeCacheableSignalKeyStore, - useMultiFileAuthState, - DisconnectReason, - fetchLatestBaileysVersion -} from "@whiskeysockets/baileys"; -import { Boom } from "@hapi/boom"; -import pino from "pino"; -import { execFile } from "child_process"; -import qrcode from "qrcode-terminal"; -import fs from "fs"; - -// Initialize a silent logger for Baileys -const logger = pino().child({ level: "silent" }); - -// Define the path for the authentication credentials -const authPath = "./baileys_auth_info"; - -// Function to run the Python script -const runPythonScript = (text, sender, senderName) => { - // Execute the Python script "ai.py" to handle the message. - execFile('python', ['ai.py', text, sender, senderName], (error, stdout, stderr) => { - if (error) { - console.error("❌ Python Error:", error.message); - return; - } - if (stderr) { - console.error("⚠️ Python stderr:", stderr); - return; - } - console.log("🐍 Python stdout:", stdout); - }); -}; - -// Main function to start the bot -const startSock = async () => { - // Check if the auth directory exists, otherwise create it - if (!fs.existsSync(authPath)) { - fs.mkdirSync(authPath); - } - - const { state, saveCreds } = await useMultiFileAuthState(authPath); - - // Fetch the latest compatible version of WhatsApp Web - const { version } = await fetchLatestBaileysVersion(); - console.log(`Using WhatsApp version: ${version.join('.')}`); - - const sock = makeWASocket({ - version, - logger, - auth: { - creds: state.creds, - keys: makeCacheableSignalKeyStore(state.keys, logger.child({ level: 'silent' })), - }, - browser: ["WhatsApp Bot", "Chrome", "1.0.0"], // This is a fake browser ID - patchMessageBeforeSending: (message) => { - const requiresPatch = !!( - message.buttonsMessage || - message.listMessage - ); - if (requiresPatch) { - message = { - viewOnceMessage: { - message: { - ...message, - }, - }, - }; - } - return message; - }, - }); - - // Save credentials when they are updated - sock.ev.on("creds.update", saveCreds); - - // Handle connection state changes - sock.ev.on("connection.update", (update) => { - const { connection, lastDisconnect, qr } = update; - if (qr) { - console.log("Scan the QR code to connect:"); - qrcode.generate(qr, { small: true }); - } - if (connection === "close") { - const reason = new Boom(lastDisconnect?.error)?.output?.statusCode; - if (reason === DisconnectReason.loggedOut) { - console.log("Logged out. Deleting auth directory and trying again."); - fs.rmSync(authPath, { recursive: true, force: true }); - startSock(); - } else { - console.log("Connection closed. Reconnecting..."); - startSock(); - } - } else if (connection === "open") { - console.log("✅ Baileys bot is ready and running!"); - } - }); - - // Listen for incoming messages - sock.ev.on("messages.upsert", async ({ messages, type }) => { - if (type === "notify") { - const msg = messages[0]; - if (!msg.message || msg.key.fromMe) return; - - const sender = msg.key.remoteJid; - const senderName = msg.pushName || sender; - const text = msg.message.conversation || msg.message.extendedTextMessage?.text; - - if (text) { - console.log(`📥 From ${senderName} (${sender}): ${text}`); - runPythonScript(text, sender, senderName); - } - } - }); -}; - -// Start the bot -startSock(); diff --git a/package.json b/package.json @@ -1,20 +0,0 @@ -{ - "name": "whatsapptracking", - "version": "1.0.0", - "description": "A simple WhatsApp message logger.", - "main": "index.js", - "type": "module", - "scripts": { - "start": "node index.js" - }, - "keywords": [], - "author": "", - "license": "ISC", - "dependencies": { - "@hapi/boom": "^10.0.1", - "@whiskeysockets/baileys": "^6.7.2", - "package.json": "^2.0.1", - "pino": "^8.1.0", - "qrcode-terminal": "^0.12.0" - } -}
© notamitgamer • Site Built: 2026-07-21 13:58:23 UTC • git-mirror commit: 1037f62 [view raw info]
Originally created with stagit • modified by notamitgamer
Forked from github.com/notamitgamer/git-mirror