-
Notifications
You must be signed in to change notification settings - Fork 4
/
main.py
232 lines (194 loc) · 8.61 KB
/
main.py
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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
import os
import uvicorn
import logging
from sarufi import Sarufi
from heyoo import WhatsApp
from dotenv import load_dotenv
from fastapi import FastAPI,Response, Request, BackgroundTasks
# Initialize FastAPI App
app = FastAPI()
# Load .env file
load_dotenv(".env")
# Make sure all required environment variables are set
if os.getenv("WHATSAPP_TOKEN") is None:
raise ValueError("WHATSAPP_TOKEN not set")
if os.getenv("PHONE_NUMBER_ID") is None:
raise ValueError("PHONE_NUMBER_ID not set")
if os.getenv("SARUFI_API_KEY") is None:
raise ValueError("SARUFI_API_KEY not set")
if os.getenv("SARUFI_BOT_ID") is None:
raise ValueError("SARUFI_BOT_ID not set")
if os.getenv("VERIFY_TOKEN") is None:
raise ValueError("VERIFY_TOKEN not set")
messenger = WhatsApp(
os.getenv("WHATSAPP_TOKEN"), phone_number_id=os.getenv("PHONE_NUMBER_ID")
)
sarufi = Sarufi(api_key=os.getenv('SARUFI_API_KEY'))
chatbot = sarufi.get_bot(os.getenv("SARUFI_BOT_ID"))
VERIFY_TOKEN = os.getenv("VERIFY_TOKEN")
PORT=os.getenv("PORT",8000)
# Logging
logging.basicConfig(
level=logging.INFO, format="%(asctime)s - %(name)s - %(levelname)s - %(message)s"
)
# FUNCTIONS
def respond(mobile: str, message: str, message_type: str = "text")->None:
"""
Send message to user
"""
try:
response = sarufi.chat(
bot_id=os.getenv("SARUFI_BOT_ID"),
chat_id=mobile,
message=message,
message_type=message_type,
channel="whatsapp",
)
execute_actions(actions=response, mobile=mobile)
except Exception as error:
logging.error("Error in respond function: %s", error)
def execute_actions(actions: dict, mobile: str)->None:
if actions.get("actions"):
actions = reversed(actions.get("actions"))
for action in actions:
if action.get("send_message"):
message = action.get("send_message")
if isinstance(message, list):
message = "\n".join(message)
messenger.send_message(message=message, recipient_id=mobile)
elif action.get("send_reply_button"):
reply_button = action.get("send_reply_button")
messenger.send_reply_button(button=reply_button, recipient_id=mobile)
elif action.get("send_button"):
button=action.get("send_button")
messenger.send_button(button=button, recipient_id=mobile)
elif action.get("send_images"):
images=action.get("send_images")
send_medias(images,mobile,"images")
elif action.get("send_videos"):
videos=action.get("send_videos")
send_medias(videos,mobile,"videos")
elif action.get("send_audios"):
audios=action.get("send_audios")
send_medias(audios,mobile,"audios")
elif action.get("send_documents"):
documents=action.get("send_documents")
send_medias(documents,mobile,"documents")
elif action.get("send_stickers"):
stickers=action.get("send_stickers")
send_medias(stickers,mobile,"stickers")
logging.info("No response")
# send media
def send_medias(medias:dict,mobile:str ,type:str)->None:
for media in medias:
link=media.get("link")
caption=media.get("caption")
if type=="images":
messenger.send_image(image=link,recipient_id=mobile,caption=caption )
elif type =="videos":
messenger.send_video(video=link,recipient_id=mobile,caption=caption)
elif type == "audios":
messenger.send_document(document=link,recipient_id=mobile,caption=caption)
elif type=="stickers":
messenger.send_sticker(sticker=link,recipient_id=mobile)
elif type=="documents":
filename=link.split("/")[-1]
if "sarufi-media" in link:
filename_parts = filename.split('.')
extension = filename_parts[-1]
name=''.join(filename_parts[:-1])
if len(name)>11 and name[-11] == '-':
name = name[:-11]
filename = f'{name}.{extension}'
messenger.send_document(document=link,recipient_id=mobile,caption=caption, filename=filename)
else:
logging.error("Unrecognized type")
# WEBHOOK ROUTE
@app.get("/")
async def wehbook_verification(request: Request):
if request.query_params.get("hub.verify_token") == VERIFY_TOKEN:
content=request.query_params.get("hub.challenge")
logging.info("Verified webhook")
return Response(content=content, media_type="text/plain", status_code=200)
logging.error("Webhook Verification failed")
return "Invalid verification token"
@app.post("/")
async def webhook_handler(request: Request,tasks:BackgroundTasks):
# Handle Webhook Subscriptions
data = await request.json()
# logging.info("Received webhook data: %s", data)
changed_field = messenger.changed_field(data)
if changed_field == "messages":
new_message = messenger.is_message(data)
if new_message:
mobile = messenger.get_mobile(data)
name = messenger.get_name(data)
message_type = messenger.get_message_type(data)
logging.info(
f"New Message; sender:{mobile} name:{name} type:{message_type}"
)
# Mark message as read
message_id = messenger.get_message_id(data)
messenger.mark_as_read(message_id)
if message_type == "text":
message = messenger.get_message(data)
name = messenger.get_name(data)
logging.info("Message: %s", message)
# Background Task
tasks.add_task(respond,
message=message,
message_type=message_type,
mobile=mobile,
)
elif message_type == "interactive":
message_response = messenger.get_interactive_response(data)
intractive_type = message_response.get("type")
message_id = message_response[intractive_type]["id"]
message_text = message_response[intractive_type]["title"]
logging.info(f"Interactive Message; {message_id}: {message_text}")
# Background Task
tasks.add_task(respond,
message=message_id,
message_type=message_type,
mobile=mobile,
)
elif message_type == "location":
message_location = messenger.get_location(data)
message_latitude = message_location["latitude"]
message_longitude = message_location["longitude"]
logging.info("Location: %s, %s", message_latitude, message_longitude)
elif message_type == "image":
image = messenger.get_image(data)
image_id, mime_type = image["id"], image["mime_type"]
image_url = messenger.query_media_url(image_id)
image_filename = messenger.download_media(image_url, mime_type)
logging.info(f"{mobile} sent image {image_filename}")
elif message_type == "video":
video = messenger.get_video(data)
video_id, mime_type = video["id"], video["mime_type"]
video_url = messenger.query_media_url(video_id)
video_filename = messenger.download_media(video_url, mime_type)
logging.info(f"{mobile} sent video {video_filename}")
elif message_type == "audio":
audio = messenger.get_audio(data)
audio_id, mime_type = audio["id"], audio["mime_type"]
audio_url = messenger.query_media_url(audio_id)
audio_filename = messenger.download_media(audio_url, mime_type)
logging.info(f"{mobile} sent audio {audio_filename}")
elif message_type == "file":
file = messenger.get_file(data)
file_id, mime_type = file["id"], file["mime_type"]
file_url = messenger.query_media_url(file_id)
file_filename = messenger.download_media(file_url, mime_type)
logging.info(f"{mobile} sent file {file_filename}")
else:
print(f"{mobile} sent {message_type}\n{data}")
else:
delivery = messenger.get_delivery(data)
if delivery:
logging.info(f"Message : {delivery}")
else:
logging.info("No new message")
return "OK",200
if __name__ == "__main__":
uvicorn.run("main:app",port=PORT)