Beispiel #1
0
def send_sms_to_slack(body):
    data = urllib.parse.parse_qs(str(body))
    from_number = data['From'][0]
    sms_message = data['Body'][0]
    try:
        slack_client.chat_postMessage(
            # channel='#hack-time',
            channel='#q-and-a',
            blocks=[{
                "type": "header",
                "text": {
                    "type": "plain_text",
                    "text": ":phone: Text message",
                    "emoji": True
                }
            }, {
                "type": "section",
                "text": {
                    "type": "mrkdwn",
                    "text": f"*From*: {from_number}"
                }
            }, {
                "type": "section",
                "text": {
                    "type": "mrkdwn",
                    "text": sms_message
                }
            }])
        response_to_twilio = MessagingResponse()
        return {
            "statusCode": 200,
            "headers": {
                "Content-Type": "text/html"
            },
            "body": response_to_twilio.to_xml()
        }
    except SlackApiError as e:
        # You will get a SlackApiError if "ok" is False
        # str like 'invalid_auth', 'channel_not_found'
        assert e.response["error"]
        response_to_twilio = MessagingResponse()
        return {
            "statusCode": 500,
            "headers": {
                "Content-Type": "text/html"
            },
            "body": response_to_twilio.to_xml()
        }
Beispiel #2
0
def webhook(request):
    response = MessagingResponse()
    if request.method == "POST":
        message = request.POST.get("Body")
        print(message)
        response.message('You said: ' + message)
    return HttpResponse(response.to_xml(), content_type='text/xml')
Beispiel #3
0
    def unsubscribe(self, request):
        """
        Unsubscribe a recipient. This is a webhook triggered by Twilio.
        """

        log.info(request.data)

        try:
            raw_number = self.request.data.get("Body")
            phone_number = phonenumbers.parse(raw_number, "AU")
        except Exception as exception:
            # Could not pass received number from twilio
            log.exception(exception)
            return Response(status=status.HTTP_404_NOT_FOUND)

        try:
            recipient = Recipient.objects.get(phone_number=phone_number)
        except Recipient.DoesNotExist:
            log.exception("Recipient does not exist")
            return Response(status=status.HTTP_404_NOT_FOUND)

        recipient.unsubscribed = True
        recipient.save()

        # Start our response
        response = MessagingResponse()

        # Add a message
        response.message("Unsubscribed! Sorry to see you go")

        return HttpResponse(response.to_xml(), content_type="text/xml")
Beispiel #4
0
def send_incoming_message():
    from_number = request.form['From']
    sms_message = request.form['Body']
    message = f"Text message from {from_number}: {sms_message}"
    slack_message = slack_client.chat_postMessage(
        channel='#-ops-2fa-notifications', text=message, icon_emoji=':robot_face:')
    response = MessagingResponse()
    return Response(response.to_xml(), mimetype="text/html"), 200
Beispiel #5
0
    def get_response(self, message, **kwargs):
        response = MessagingResponse()

        response_text = self.get_response_text()
        if response_text:
            response.message(response_text)

        response = HttpResponse(response.to_xml(), content_type='application/xml')
        return response
Beispiel #6
0
def webhook(request):
    response = MessagingResponse()
    pprint(request.POST)
    if request.method == "POST":
        message = request.POST.get("Body")
        print({'text': message})
        rasa_response = requests.post("http://localhost:5005/model/parse", json={'text': message})
        pprint(rasa_response.text)
        response.message('You said: ' + message)
    return HttpResponse(response.to_xml(), content_type='text/xml')
Beispiel #7
0
def webhook(request):
    response = MessagingResponse()
    if request.method == "POST":
        number = request.POST.get("WaId")
        message = request.POST.get("Body")

        if not check_user_exist(number):
            msg = temp_register_user(request.POST)
            response.message(msg)
            return HttpResponse(response.to_xml(), content_type='text/xml')

        else:
            pass

        media = request.POST.get("MediaUrl0")
        print(request.POST)
        response.message(
            'Next procedure and user controls are under development,\nyou said: '
            + message)
    return HttpResponse(response.to_xml(), content_type='text/xml')
Beispiel #8
0
def incoming_whatsapp_message_handler(**kwargs):
    """This is a webhook called by Twilio when a WhatsApp message is received.
	"""
    args = frappe._dict(kwargs)
    incoming_message_callback(args)
    resp = MessagingResponse()

    # Add a message
    resp.message(frappe.db.get_single_value('Twilio Settings',
                                            'reply_message'))
    return Response(resp.to_xml(), mimetype='text/xml')
Beispiel #9
0
def process_request_data(data):
    resp = MessagingResponse()
    if int(data['NumMedia']) > 0 and 'image' in data.get('MediaContentType0'):
        response = requests.get(data['MediaUrl0'])
        imag_file = io.BytesIO(response.content)
        image = check_if_image_exists_and_is_rumor(imag_file)
        content_type = _('Image')
        resp.message(get_response_message(image, content_type))
    if data['Body']:
        text = check_text(data['Body'])
        content_type = _('text')
        resp.message(get_response_message(text, content_type))
    return resp.to_xml()
Beispiel #10
0
def webhook(request):
    response = MessagingResponse()
    if request.method == "POST":
        lat, lon = request.POST.get('Latitude'), request.POST.get('Longitude')
        if lat and lon:
            weather_response = get_weather(lat, lon,
                                           settings.OPEN_WEATHER_API_KEY)
            message_body = generate_weather_message(weather_response)
            response.message(message_body)
        else:
            response.message("Send your location")

    return HttpResponse(response.to_xml(), content_type='text/xml')
Beispiel #11
0
    def post(self, request, format=None):
        data = request.data
        resp = MessagingResponse()

        from_number = data.get("From", None)
        msg_id = data.get("MessageSid", None)

        if not from_number:
            return HttpResponse()
        if not msg_id:
            return HttpResponse()

        from_number, _ = PhoneNumber.objects.get_or_create(number=from_number)
        params = {
            "twilio_message_id": msg_id,
            "data": data,
            "phone_number": from_number
        }
        msg = ReceivedMessage(**params)
        msg.save()

        if msg_id.startswith("SM"):
            resp.message(body=RECEIVED_SMS)
            return HttpResponse(resp.to_xml(), content_type="application/xml")

        num_media_items = int(data.get("NumMedia", 0))
        media_resources = []
        for num in range(num_media_items):
            content_type = data.get(f"MediaContentType{num}")
            url = data.get(f"MediaUrl{num}")
            item = MediaResource(resource_url=url,
                                 content_type=content_type,
                                 phone_number=from_number)
            media_resources.append(item)

        MediaResource.objects.bulk_create(media_resources)
        resp.message(body=f"Received {num_media_items} picture(s)! Thank you!")
        return HttpResponse(resp.to_xml(), content_type="application/xml")
Beispiel #12
0
def sms_response(request):
    body = request.POST.get('Body', '')
    print(body)
    if re.match(r'^query\s\d+', body, re.IGNORECASE) is not None:
        r = get_product_details(body)
        return HttpResponse(r.to_xml(), content_type='text/xml')
    elif re.match(r'^query\sall', body, re.IGNORECASE):
        r = MessagingResponse()
        products = ProductDetail.queryset.values_list('id', 'name', 'price', 'url')
        r.message(str([i for i in products]))
        return HttpResponse(r.to_xml(), content_type='text/xml')
    elif re.match(r'^buy\s\d', body, re.IGNORECASE):
        id = re.findall(r'\d.*', body, re.IGNORECASE)[0]
        product = ProductDetail.queryset.filter(id=id)[0]
        print(Product.url)
        add_and_checkout(product.url)
Beispiel #13
0
def enqueue():
    body = request.values.get('Body')
    track = search(body)
    if not track:
        abort(400)

    me = spotify.v1.me.fetch()
    playlist = spotify.v1.users.get(me.id).playlists.get(PLAYLIST_ID).fetch()
    playlist.tracks.add([track.uri])

    artists = [artist.name for artist in track.artists]

    mr = MessagingResponse()
    mr.message(body='Added {} by {} to the playlist!'.format(
        track.name, ' & '.join(artists)))
    return mr.to_xml()
Beispiel #14
0
 def post(self, request):
     msg = request.POST.get('Body')
     user = request.POST.get("From")[-10:]
     conversation, created = Conversation.objects.get_or_create(sender=user)
     if not conversation.selections:
         conversation.selections = []
     response, last, selection, language = generate_response(
         msg, conversation.last_selection, conversation.selections,
         conversation.language)
     conversation.message = response
     conversation.last_selection = last
     conversation.selections = selection
     conversation.language = language
     conversation.save()
     resp = MessagingResponse()
     resp.message(response)
     return HttpResponse(resp.to_xml(), content_type='text/xml')
def httpWebHooktoTwilioURL(event, context):
    print(event)  #To have event come up in cloudwatchLogs
    numMedia = int(event['body']['NumMedia'])
    if (numMedia == 1):
        if (event['body']['MediaContentType0'] == 'image/jpeg'):
            image_url = event['body']['MediaUrl0']
            filename = os.path.join(
                os.getcwd(),
                Path("../../tmp/{}.jpg".format(event['body']['MessageSid'])))
            retrieveContent = requests.get(image_url, stream=True)
            if retrieveContent.status_code == 200:
                retrieveContent.raw.decode_content = True  #Required to ensure file size is not zero
                with open(filename, 'wb') as f:  #writing into file
                    shutil.copyfileobj(retrieveContent.raw, f)

            with open(filename, 'rb') as image:
                rekogResponse = rekogClient.recognize_celebrities(
                    Image={'Bytes': image.read()})
            print(rekogResponse)
            bodyContent = "{} celebrities found".format(
                len(rekogResponse['CelebrityFaces']))
            if (len(rekogResponse['CelebrityFaces']) > 0):
                for celeb in rekogResponse['CelebrityFaces']:
                    bodyContent += "{}    {} : {}% match confidence".format(
                        os.linesep, celeb['Name'], celeb['MatchConfidence'])
        else:
            bodyContent = "Image type is not JPEG or PNG. Please send only one of these."
    elif (numMedia > 1):
        bodyContent = "Please only send one image at a time "
    elif (numMedia == 0):
        bodyContent = "Hi, please attach a JPEG or PNG image for facial recognition of celebrities."
    try:
        #translator = Translator()
        response = MessagingResponse()
        message = Message()
        #message.body(translator.translate(event['body']['Body'],dest='hi').text) # Pre-tested on googletrans
        message.body(bodyContent)
        response.append(message)
        return response.to_xml()
    except:
        return "An Error has occured. Please contact support."
Beispiel #16
0
def Webhook(request):
    global tube_file_url
    global search_name
    global num

    response = MessagingResponse()
    msg = response.message()
    if request.method == "POST":
        message = request.POST.get("Body")
        try:
            int(message)
            num = int(message)
            results = YoutubeSearch(search_name, max_results=10).to_dict()
            num = num - 1
            result = results[num]['url_suffix']
            tube_file_url = result.replace("/watch?v=", "")
            msg.body("")  #Domain Name

        except ValueError:
            mess_to_string = str(message)
            string_verification = False

            for url in YoutubeUrl.objects.all():
                if mess_to_string.startswith(url.verification_url):
                    tube_file_url = mess_to_string.replace(
                        url.verification_url, "")
                    msg.body("")  #Domain Name
                    string_verification = True
                    break

            if string_verification == False:
                results = YoutubeSearch(message, max_results=10).to_dict()
                search_name = message
                for index in range(10):
                    result = results[index]['title']
                    msg.body('--\n{0} {1}\n--'.format(index + 1, result))

    return HttpResponse(response.to_xml(), content_type='text/xml')
Beispiel #17
0
def webhook(request):
    response = MessagingResponse()
    if request.method == "POST":

        lat, lon = request.POST.get('Latitude'), request.POST.get('Longitude')
        if lat and lon:
            response.message(
                "A Nurse has been assigned to your location,/n if this is a mistake say cancel!"
            )
            pusher_client = pusher.Pusher(
                app_id='yourappid',
                key='yourkey',
                secret='yoursecret',
                encryption_master_key_base64='<output from command above>',
                cluster='yourclustername',
                ssl=True)

            pusher_client.trigger('private-encrypted-my-channel', 'my-event',
                                  {'message': 'hello world'})

        else:
            response.message("Send your location")

    return HttpResponse(response.to_xml(), content_type='text/xml')
Beispiel #18
0
def webhook(request):
    response = MessagingResponse()

    def bye():
        message = f" Thank you for chatting with us...\n" \
                  f" Have a good day! \n"
        del (request.session['function'])
        response.message(message)

    def hi():
        message = f" * Hi*  \n" \
                  f" *Welcome to Stanview!* \n\n" \
                  f" 1>Fault follow up/ registration \n" \
                  f" 2>Account status enquiry \n" \
                  f" 3>Request to speak to an agent \n" \
                  f" 4>Exit \n"
        request.session['function'] = 'menu'
        response.message(message)

    def fault_menu():
        message = f" What would you like to do? \n" \
                  f" 1>Follow up \n" \
                  f" 2>Register \n" \
                  f" 0>Home \n"
        request.session['function'] = 'follow/register'
        response.message(message)

    def enquiry_menu():
        message = f" You have chosen account status enquiry \n" \
                  f" 0>Home \n"
        request.session['function'] = 'enquiry'
        response.message(message)

    def agent_menu():
        message = f" How do you wish to communicate with our agent? \n" \
                  f" 1>Website \n" \
                  f" 2>LiveChat \n" \
                  f" 3>Call \n" \
                  f" 0>Home \n"
        request.session['function'] = 'agent'
        response.message(message)

    def menu():
        body = request.POST.get("Body")
        if body == '1':
            fault_menu()
        elif body == '2':
            enquiry_menu()
        elif body == '3':
            agent_menu()
        elif body == '4':
            bye()
        else:
            hi()

    def follow_register():
        body = request.POST.get("Body")
        if body == '1':
            message = f" Please enter the fault number: \n"
            request.session['function'] = 'follow'
            response.message(message)
        elif body == '2':
            message = f" New Fault Registration \n" \
                      f" 0>Home \n"
            request.session['function'] = 'register_fault'
            response.message(message)
        elif body == '0':
            hi()
        else:
            fault_menu()

    def agent():
        body = request.POST.get("Body")
        if body == '1':
            message = f" Website is ...: \n"
            request.session['function'] = 'website'
            response.message(message)
        elif body == '2':
            message = f" Follow this link ... \n"
            request.session['function'] = 'live_chat'
            response.message(message)
        elif body == '3':
            message = f" 0777470333/ 0782384322 \n"
            request.session['function'] = 'call'
            response.message(message)
        elif body == '0':
            hi()
        else:
            agent_menu()

    if request.method == "POST":

        if request.session.get('function') == 'menu':
            menu()
        elif request.session.get('function') == 'follow/register':
            follow_register()
        elif request.session.get('function') == 'agent':
            agent()
        else:
            hi()

    return HttpResponse(response.to_xml(), content_type='text/xml')
Beispiel #19
0
def reply_to_sms_messages(request):
    r = MessagingResponse()
    from_ = request.POST['From']
    body = request.POST['Body'].strip()

    phone = from_.replace('+61', '0').strip()
    print(phone)

    orders = Order.objects.filter(phone1=phone, canceled=False, completed=False)#(completed=False).filter(Q(phone1=phone) | Q(phone2=phone))
    print(orders)

    # check for duplicate orders and flag them
    if len(orders) > 1:
        print('Duplicate orders')
        for order in orders:
            Message.objects.create(user=SYSTEM, phone=phone, text=body, sent=False, order=order)
            Flags.objects.create(order=order, acknowledged=False, text='Duplicate orders found with caller id - no action has been taken')

        r.message('Thank-you for your response. We will be in touch shortly.')
        return HttpResponse(r.to_xml(), content_type='text/xml')

    elif not orders:
        print('Order not found')
        Message.objects.create(user=SYSTEM, phone=phone, text=body, sent=False, order=None)
        return HttpResponse(r.to_xml(), content_type='text/xml')

    else:
        order = orders[0]

        # we're at the selecting preferred day stage
        if not order.preferred_day:
            print('Already set preferred day')
            Message.objects.create(user=SYSTEM, phone=phone, text=body, sent=False, order=order)
            if len(body) != 1:
                print('More than one character returned')
                Flags.objects.create(order=order, acknowledged=False,
                                     text='Unable to decode message reply')
                r.message('Thank-you for your response. We will be in touch shortly.')
                Message.objects.create(user=SYSTEM, phone=phone, text='Thank-you for your response. We will be in touch shortly.', sent=True, order=order)
                return HttpResponse(r.to_xml(), content_type='text/xml')
            else:
                try:
                    option = int(body)
                except ValueError:
                    print('Non numeric reply')
                    Flags.objects.create(order=order, acknowledged=False,
                                         text='Unable to decode message reply')
                    r.message('Thank-you for your response. We will be in touch shortly.')
                    Message.objects.create(user=SYSTEM, phone=phone,
                                           text='Thank-you for your response. We will be in touch shortly.', sent=True,
                                           order=order)
                    return HttpResponse(r.to_xml(), content_type='text/xml')

                index = 1
                days = {}
                zone = order.suburb.zone

                if zone.monday:
                    days[index] = 'Monday'
                    index += 1

                if zone.tuesday:
                    days[index] = 'Tuesday'
                    index += 1

                if zone.wednesday:
                    days[index] = 'Wednesday'
                    index += 1

                if zone.thursday:
                    days[index] = 'Thursday'
                    index += 1

                if zone.friday:
                    days[index] = 'Friday'
                    index += 1

                if zone.saturday:
                    days[index] = 'Saturday'
                    index += 1

                if zone.sunday:
                    days[index] = 'Sunday'
                    index += 1

                # -- valid response
                if option in days:
                    print('Found the correct day!!!')
                    order.preferred_day = days[option]
                    order.save()

                    r.message('Thank-you for indicating your preference for a {0} delivery. We will be in touch shortly to arrange a delivery date.'.format(days[option]))
                    Message.objects.create(user=SYSTEM, phone=phone,
                                           text='Thank-you for indicating your preference for a {0} delivery. We will be in touch shortly to arrange a delivery date.'.format(days[option]), sent=True,
                                           order=order)
                    return HttpResponse(r.to_xml(), content_type='text/xml')

                else:
                    print('Option selected is not an applicable day')
                    Flags.objects.create(order=order, acknowledged=False,
                                         text='Client selected an unavailable day')
                    r.message('Thank-you for your response. We will be in touch shortly.')
                    Message.objects.create(user=SYSTEM, phone=phone,
                                           text='Thank-you for your response. We will be in touch shortly.', sent=True,
                                           order=order)
                    return HttpResponse(r.to_xml(), content_type='text/xml')

        # -- stuff other than choosing a day
        else:
            Message.objects.create(user=SYSTEM, phone=phone, text=body, sent=False, order=order)
            Flags.objects.create(order=order, acknowledged=False,
                                 text='Client replied to unspecified prompt')

            return HttpResponse(r.to_xml(), content_type='text/xml')

    return HttpResponse(r.to_xml(), content_type='text/xml')



    # r.message('{0}\n{1}'.format(from_, body))
    # return HttpResponse(r.to_xml(), content_type='text/xml')
Beispiel #20
0
def twiml_error(text):
    response = MessagingResponse()
    response.message(text)
    return response.to_xml()