imseldrith commited on
Commit
92b3530
·
verified ·
1 Parent(s): b59175c

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +64 -0
app.py ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from flask import Flask, request, jsonify
2
+ from dotenv import load_dotenv
3
+ import os
4
+ from helper.openai_api import chat_completion
5
+ from helper.messenger_api import send_message, set_typing_on, set_typing_off
6
+
7
+ load_dotenv()
8
+
9
+ app = Flask(__name__)
10
+
11
+ VERIFY_TOKEN = os.getenv('VERIFY_TOKEN')
12
+
13
+ @app.route('/', methods=['GET'])
14
+ def verify_webhook():
15
+ mode = request.args.get('hub.mode')
16
+ token = request.args.get('hub.verify_token')
17
+ challenge = request.args.get('hub.challenge')
18
+
19
+ if mode == 'subscribe' and token == VERIFY_TOKEN:
20
+ print('WEBHOOK_VERIFIED')
21
+ return challenge, 200
22
+ else:
23
+ return 'Forbidden', 403
24
+
25
+ @app.route('/webhook', methods=['POST'])
26
+ def handle_messages():
27
+ body = request.get_json()
28
+
29
+ if not body.get('entry') or not body['entry'][0].get('messaging'):
30
+ print('Invalid payload structure:', body)
31
+ return 'Invalid payload', 400
32
+
33
+ messaging_event = body['entry'][0]['messaging'][0]
34
+ sender_id = messaging_event['sender']['id']
35
+ message_text = messaging_event['message'].get('text')
36
+
37
+ if not sender_id or not message_text:
38
+ print('Missing sender ID or message text:', {'sender_id': sender_id, 'message_text': message_text})
39
+ return 'Invalid message', 400
40
+
41
+ set_typing_on(sender_id)
42
+
43
+ result = chat_completion(message_text)
44
+ print('Chat Completion Result:', result)
45
+
46
+ response_text = result.get('response', '')
47
+ try:
48
+ parsed_response = eval(response_text) # Caution: using eval() is dangerous, ensure the content is trusted
49
+ except:
50
+ parsed_response = response_text
51
+
52
+ if isinstance(parsed_response, dict):
53
+ msg = parsed_response.get('msg')
54
+ image_url = parsed_response.get('image_url')
55
+ send_message(sender_id, msg, image_url)
56
+ else:
57
+ send_message(sender_id, response_text)
58
+
59
+ set_typing_off(sender_id)
60
+ print(f'Message sent to {sender_id}: {parsed_response}')
61
+ return 'OK', 200
62
+
63
+ if __name__ == '__main__':
64
+ app.run(host="0.0.0.0", port=7860, debug=True)