forked from JPierr3/bigdateros-whatsappbot-python
-
Notifications
You must be signed in to change notification settings - Fork 0
/
services.py
303 lines (268 loc) · 9.69 KB
/
services.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
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
import requests
import sett
import json
import time
def obtener_Mensaje_whatsapp(message):
if 'type' not in message :
text = 'mensaje no reconocido'
return text
typeMessage = message['type']
if typeMessage == 'text':
text = message['text']['body']
elif typeMessage == 'button':
text = message['button']['text']
elif typeMessage == 'interactive' and message['interactive']['type'] == 'list_reply':
text = message['interactive']['list_reply']['title']
elif typeMessage == 'interactive' and message['interactive']['type'] == 'button_reply':
text = message['interactive']['button_reply']['title']
else:
text = 'mensaje no procesado'
return text
def enviar_Mensaje_whatsapp(data):
try:
whatsapp_token = sett.whatsapp_token
whatsapp_url = sett.whatsapp_url
headers = {'Content-Type': 'application/json',
'Authorization': 'Bearer ' + whatsapp_token}
print("se envia ", data)
response = requests.post(whatsapp_url,
headers=headers,
data=data)
if response.status_code == 200:
return 'mensaje enviado', 200
else:
return 'error al enviar mensaje', response.status_code
except Exception as e:
return e,403
def text_Message(number,text):
data = json.dumps(
{
"messaging_product": "whatsapp",
"recipient_type": "individual",
"to": number,
"type": "text",
"text": {
"body": text
}
}
)
return data
def buttonReply_Message(number, options, body, footer, sedd,messageId):
buttons = []
for i, option in enumerate(options):
buttons.append(
{
"type": "reply",
"reply": {
"id": sedd + "_btn_" + str(i+1),
"title": option
}
}
)
data = json.dumps(
{
"messaging_product": "whatsapp",
"recipient_type": "individual",
"to": number,
"type": "interactive",
"interactive": {
"type": "button",
"body": {
"text": body
},
"footer": {
"text": footer
},
"action": {
"buttons": buttons
}
}
}
)
return data
def listReply_Message(number, options, body, footer, sedd,messageId):
rows = []
for i, option in enumerate(options):
rows.append(
{
"id": sedd + "_row_" + str(i+1),
"title": option,
"description": ""
}
)
data = json.dumps(
{
"messaging_product": "whatsapp",
"recipient_type": "individual",
"to": number,
"type": "interactive",
"interactive": {
"type": "list",
"body": {
"text": body
},
"footer": {
"text": footer
},
"action": {
"button": "Ver Opciones",
"sections": [
{
"title": "Secciones",
"rows": rows
}
]
}
}
}
)
return data
def document_Message(number, url, caption, filename):
data = json.dumps(
{
"messaging_product": "whatsapp",
"recipient_type": "individual",
"to": number,
"type": "document",
"document": {
"link": url,
"caption": caption,
"filename": filename
}
}
)
return data
def sticker_Message(number, sticker_id):
data = json.dumps(
{
"messaging_product": "whatsapp",
"recipient_type": "individual",
"to": number,
"type": "sticker",
"sticker": {
"id": sticker_id
}
}
)
return data
def get_media_id(media_name , media_type):
media_id = ""
if media_type == "sticker":
media_id = sett.stickers.get(media_name, None)
#elif media_type == "image":
# media_id = sett.images.get(media_name, None)
#elif media_type == "video":
# media_id = sett.videos.get(media_name, None)
#elif media_type == "audio":
# media_id = sett.audio.get(media_name, None)
return media_id
def replyReaction_Message(number, messageId, emoji):
data = json.dumps(
{
"messaging_product": "whatsapp",
"recipient_type": "individual",
"to": number,
"type": "reaction",
"reaction": {
"message_id": messageId,
"emoji": emoji
}
}
)
return data
def replyText_Message(number, messageId, text):
data = json.dumps(
{
"messaging_product": "whatsapp",
"recipient_type": "individual",
"to": number,
"context": { "message_id": messageId },
"type": "text",
"text": {
"body": text
}
}
)
return data
def markRead_Message(messageId):
data = json.dumps(
{
"messaging_product": "whatsapp",
"status": "read",
"message_id": messageId
}
)
return data
def administrar_chatbot(text,number, messageId, name):
text = text.lower() #mensaje que envio el usuario
list = []
print("mensaje del usuario: ",text)
markRead = markRead_Message(messageId)
list.append(markRead)
time.sleep(2)
if "hola" in text:
body = "¡Hola! 👋 Bienvenido a Bigdateros. ¿Cómo podemos ayudarte hoy?"
footer = "Equipo Bigdateros"
options = ["✅ servicios", "📅 agendar cita"]
replyButtonData = buttonReply_Message(number, options, body, footer, "sed1",messageId)
replyReaction = replyReaction_Message(number, messageId, "🫡")
list.append(replyReaction)
list.append(replyButtonData)
elif "servicios" in text:
body = "Tenemos varias áreas de consulta para elegir. ¿Cuál de estos servicios te gustaría explorar?"
footer = "Equipo Bigdateros"
options = ["Analítica Avanzada", "Migración Cloud", "Inteligencia de Negocio"]
listReplyData = listReply_Message(number, options, body, footer, "sed2",messageId)
sticker = sticker_Message(number, get_media_id("perro_traje", "sticker"))
list.append(listReplyData)
list.append(sticker)
elif "inteligencia de negocio" in text:
body = "Buenísima elección. ¿Te gustaría que te enviara un documento PDF con una introducción a nuestros métodos de Inteligencia de Negocio?"
footer = "Equipo Bigdateros"
options = ["✅ Sí, envía el PDF.", "⛔ No, gracias"]
replyButtonData = buttonReply_Message(number, options, body, footer, "sed3",messageId)
list.append(replyButtonData)
elif "sí, envía el pdf" in text:
sticker = sticker_Message(number, get_media_id("pelfet", "sticker"))
textMessage = text_Message(number,"Genial, por favor espera un momento.")
enviar_Mensaje_whatsapp(sticker)
enviar_Mensaje_whatsapp(textMessage)
time.sleep(3)
document = document_Message(number, sett.document_url, "Listo 👍🏻", "Inteligencia de Negocio.pdf")
enviar_Mensaje_whatsapp(document)
time.sleep(3)
body = "¿Te gustaría programar una reunión con uno de nuestros especialistas para discutir estos servicios más a fondo?"
footer = "Equipo Bigdateros"
options = ["✅ Sí, agenda reunión", "No, gracias." ]
replyButtonData = buttonReply_Message(number, options, body, footer, "sed4",messageId)
list.append(replyButtonData)
elif "sí, agenda reunión" in text :
body = "Estupendo. Por favor, selecciona una fecha y hora para la reunión:"
footer = "Equipo Bigdateros"
options = ["📅 10: mañana 10:00 AM", "📅 7 de junio, 2:00 PM", "📅 8 de junio, 4:00 PM"]
listReply = listReply_Message(number, options, body, footer, "sed5",messageId)
list.append(listReply)
elif "7 de junio, 2:00 pm" in text:
body = "Excelente, has seleccionado la reunión para el 7 de junio a las 2:00 PM. Te enviaré un recordatorio un día antes. ¿Necesitas ayuda con algo más hoy?"
footer = "Equipo Bigdateros"
options = ["✅ Sí, por favor", "❌ No, gracias."]
buttonReply = buttonReply_Message(number, options, body, footer, "sed6",messageId)
list.append(buttonReply)
elif "no, gracias." in text:
textMessage = text_Message(number,"Perfecto! No dudes en contactarnos si tienes más preguntas. Recuerda que también ofrecemos material gratuito para la comunidad. ¡Hasta luego! 😊")
list.append(textMessage)
else :
data = text_Message(number,"Lo siento, no entendí lo que dijiste. ¿Quieres que te ayude con alguna de estas opciones?")
list.append(data)
for item in list:
enviar_Mensaje_whatsapp(item)
#al parecer para mexico, whatsapp agrega 521 como prefijo en lugar de 52,
# este codigo soluciona ese inconveniente.
def replace_start(s):
number = s[3:]
if s.startswith("521"):
return "52" + number
elif s.startswith("549"):
return "54" + number
else:
return s