-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathwebhook.py
More file actions
71 lines (57 loc) · 2.43 KB
/
webhook.py
File metadata and controls
71 lines (57 loc) · 2.43 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
import os
from flask import Flask, request, jsonify
from dotenv import load_dotenv
import sys
# Load environment variables from a .env file
load_dotenv()
# This is a good way to handle local module imports
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
from wa_cp_flask.bot_handler import handle_incoming_whatsapp
app = Flask(__name__)
# Load the Verify Token from environment variables
VERIFY_TOKEN = os.getenv("VERIFY_TOKEN")
# It's a good practice to check if the token is set
if not VERIFY_TOKEN:
raise ValueError("VERIFY_TOKEN is not set in the environment variables.")
@app.route('/')
def index():
"""A simple route to confirm the server is running."""
print("SUCCESS: Root route '/' was accessed.")
return "Flask server is running!", 200
@app.route('/webhook', methods=['GET', 'POST'])
def webhook():
if request.method == 'GET':
# --- Webhook Verification ---
mode = request.args.get('hub.mode')
token = request.args.get('hub.verify_token')
challenge = request.args.get('hub.challenge')
print(f"Using VERIFY_TOKEN: {VERIFY_TOKEN, token}")
if mode == 'subscribe' and token == VERIFY_TOKEN:
print("WEBHOOK_VERIFIED")
return challenge, 200
else:
print("VERIFICATION_FAILED")
return "Verification token mismatch", 403
if request.method == 'POST':
# --- Handle Incoming Messages ---
data = request.json
# Log the entire payload for debugging purposes
app.logger.info("Received webhook data: %s", data)
try:
# It's crucial to wrap this in a try-except block
# to ensure you always return a 200 OK to Meta.
handle_incoming_whatsapp(data)
except Exception as e:
# Log the error for debugging
app.logger.error(f"Error handling webhook: {e}")
# Still return a 200 OK, but you can log the error
# Meta doesn't care about the response body, only the status code.
return jsonify(status="error", message=str(e)), 200
# If everything went well, return a success status.
return jsonify(status="ok"), 200
# If the request method is not GET or POST
return "Method not allowed", 405
if __name__ == '__main__':
# Use os.getenv to make the port configurable
port = int(os.getenv('PORT', 3000))
app.run(port=port, debug=True)