def test_text(self):
        r = MessagingResponse()
        r.append('No tags!')

        assert_equal(
            self.strip(r),
            '<?xml version="1.0" encoding="UTF-8"?><Response>No tags!</Response>'
        )
Beispiel #2
0
    def test_redirect(self):
        r = MessagingResponse()
        r.redirect(url='example.com')

        assert_equal(
            self.strip(r),
            '<?xml version="1.0" encoding="UTF-8"?><Response><Redirect>example.com</Redirect></Response>'
        )
Beispiel #3
0
    def test_body(self):
        r = MessagingResponse()
        r.message('Hello')

        assert_equal(
            self.strip(r),
            '<?xml version="1.0" encoding="UTF-8"?><Response><Message>Hello</Message></Response>'
        )
def sms_reply():
    """Respond to incoming calls with a simple text message."""
    # Start our TwiML response
    resp = MessagingResponse()

    # Add a message
    resp.message("The Robots are coming! Head for the hills!")

    return str(resp)
Beispiel #5
0
    def test_nested_body(self):
        b = Body('Hello World')

        r = MessagingResponse()
        r.append(b)

        assert_equal(
            self.strip(r),
            '<?xml version="1.0" encoding="UTF-8"?><Response><Body>Hello World</Body></Response>'
        )
Beispiel #6
0
def respond_sms():
   response = MessagingResponse()
   
   # This is old logic which used a suid executable. 
   # process = subprocess.Popen(["/opt/lbearl/bin/c_sms", "-o"], stdout=subprocess.PIPE)
   # stdout = process.communicate()[0]
   # response.message(stdout.decode('utf-8'))
   temp_data = open("/opt/lbearl/temp.txt", "r")
   response.message(temp_data.read().decode('utf-8'))
   return unicode(response)
def _send_single_result(employees):
    response = MessagingResponse()
    employee = employees[0]
    employee_data = '\n'.join([employee.full_name,
                               employee.phone_number,
                               employee.email])
    message = Message()
    message.append(Body(employee_data))
    message.append(Media(employee.image_url))
    return str(response.append(message))
def _send_multiple_results(employees):
    names = [employee.full_name for employee in employees]
    session['choices'] = names
    response = MessagingResponse()
    message = ["We found multiple people, reply with:"]
    for i, name in enumerate(names, 1):
        message.append("%s for %s" % (i, name))
    message.append("Or start over")
    response.message('\n'.join(message))
    return str(response)
Beispiel #9
0
    def test_nested_body_media(self):
        b = Body('Hello World')
        m = Media('hey.jpg')

        r = MessagingResponse()
        r.append(b)
        r.append(m)

        assert_equal(
            self.strip(r),
            '<?xml version="1.0" encoding="UTF-8"?><Response><Body>Hello World</Body><Media>hey.jpg</Media></Response>'
        )
def hello_monkey():
    """Respond to incoming calls with a simple text message."""

    resp = MessagingResponse()
    msg = Message()\
        .body("Hello, Mobile Monkey")\
        .media("https://demo.twilio.com/owl.png")
    resp.append(msg)

    return str(resp)

    if __name__ == "__main__":
        app.run(debug=True)
def sms_survey():
    response = MessagingResponse()

    survey = Survey.query.first()
    if survey_error(survey, response.message):
        return str(response)

    if 'question_id' in session:
        response.redirect(url_for('answer',
                                  question_id=session['question_id']))
    else:
        welcome_user(survey, response.message)
        redirect_to_first_question(response, survey)
    return str(response)
def sms_reply():
    """Respond to incoming calls with a MMS message."""
    # Start our TwiML response
    resp = MessagingResponse()

    # Add a text message
    msg = resp.message("The Robots are coming! Head for the hills!")

    # Add a picture message
    msg.media(
        "https://farm8.staticflickr.com/7090/6941316406_80b4d6d50e_z_d.jpg"
    )

    return str(resp)
def incoming_sms():
    """Send a dynamic reply to an incoming text message"""
    # Get the message the user sent our Twilio number
    body = request.values.get('Body', None)

    # Start our TwiML response
    resp = MessagingResponse()

    # Determine the right reply for this message
    if body == 'hello':
        resp.message("Hi!")
    elif body == 'bye':
        resp.message("Goodbye")

    return str(resp)
def hello_monkey():
    """Respond and greet the caller by name."""
    # Try adding your own number to this list!
    callers = {
        "+14158675309": "Curious George",
        "+14158675310": "Boots",
        "+14158675311": "Virgil",
    }
    from_number = request.values.get('From', None)
    message = callers[from_number] if from_number in callers else "Monkey"

    resp = MessagingResponse()
    resp.message("{}, thanks for the message!".format(message))

    return str(resp)
Beispiel #15
0
def incoming_sms(request):
    """ Changes worker activity and returns a confirmation """
    client = Client(ACCOUNT_SID, AUTH_TOKEN)
    activity = 'Idle' if request.POST['Body'].lower().strip() == 'on' else 'Offline'
    activity_sid = WORKSPACE_INFO.activities[activity].sid
    worker_sid = WORKSPACE_INFO.workers[request.POST['From']]
    workspace_sid = WORKSPACE_INFO.workspace_sid

    client.workspaces(workspace_sid)\
          .workers(worker_sid)\
          .update(activity_sid=activity_sid)

    resp = MessagingResponse()
    message = 'Your status has changed to ' + activity
    resp.message(message)
    return HttpResponse(resp)
Beispiel #16
0
def sms(request):
    """
    Handle all incoming messages from Twilio.

    This is the start of the message processing pipeline.
    """
    logger.info('Received new sms')
    r = MessagingResponse()
    msg = InboundSms(request.POST)
    msg.start_bg_tasks()

    config = SiteConfiguration.get_solo()
    if msg.reply and not config.disable_all_replies:
        logger.info('Add reply (%s) to response', msg.reply)
        r.message(msg.reply)

    logger.info('Return response to Twilio')
    return HttpResponse(str(r), content_type='application/xml')
def construct_message(labels, face_annotations, logos):
    """Build up the response from the labels found"""

    # We'll use this to construct our response
    response_text = PRETEXT
    label_desc = ""
    pos_labels = ['very likely', 'likely', 'possibly']

    # Go through labels and turn them into text of the response
    for i in range(len(labels)):

        # We've got an answer! Let's tell them about it
        label_desc += '\nScore is %s for %s' % (labels[i]['score'],
                                                labels[i]['description'])

    for i in range(len(logos)):
        label_desc += '\nLogo score is %s for %s' % (logos[i]['score'],
                                                logos[i]['description'])

    joy, anger, sorrow, surprise = extract_sentiment(face_annotations)

    for i in range(len(pos_labels)):
        if joy[i] > 0:
            label_desc += '\nWe found %s people who are ' \
                '%s experiencing joy' % (joy[i], pos_labels[i])
        if anger[i] > 0:
            label_desc += '\nWe found %s people who are ' \
                '%s experiencing anger' % (anger[i], pos_labels[i])
        if sorrow[i] > 0:
            label_desc += '\nWe found %s people who are ' \
                '%s experiencing sorrow' \
                % (sorrow[i], pos_labels[i])
        if surprise[i] > 0:
            label_desc += '\nWe found %s people who are ' \
                '%s experiencing surprise' \
                % (surprise[i], pos_labels[i])

    # Add the prefix
    if not label_desc:
        label_desc = " No labels found."
    response_text += label_desc
    resp = MessagingResponse()
    resp.message(response_text)
    return resp
def hello_monkey():
    """Respond with the number of text messages sent between two parties."""

    counter = session.get('counter', 0)

    # increment the counter
    counter += 1

    # Save the new counter value in the session
    session['counter'] = counter

    to_number = request.values.get('To')
    from_number = request.values.get('From', None)
    name = callers[from_number] if from_number in callers else "Monkey"

    message = "{} has messaged {} {} times".format(name, to_number, counter)

    resp = MessagingResponse()
    resp.message(body=message)

    return str(resp)
    def text_mixed(self):
        r = MessagingResponse()
        r.append('before')
        r.append(Body('Content'))
        r.append('after')

        assert_equal(
            self.strip(r),
            '<?xml version="1.0" encoding="UTF-8"?><Response>before<Body>Content</Body>after</Response>'
        )
Beispiel #20
0
def sms(request, message, to=None, sender=None, action=None, method='POST',
        status_callback=None):
    """
    NOTE: Now deprecated, please use message() instead
    See: http://www.twilio.com/docs/api/twiml/sms

    Usage::

        # urls.py
        urlpatterns = patterns('',
            # ...
            url(r'^sms/$', 'django_twilio.views.sms', {
                'message': 'Hello, world!'
            }),
            # ...
        )
    """
    r = MessagingResponse()
    r.message(body=message, to=to, sender=sender, method='POST', action=action,
              status_callback=status_callback)
    return r
Beispiel #21
0
def tw_handle_incoming_closed(sms_message):
    """handle incoming sms messages"""
    #get and format the phone number from which msg was received
    phone = sms_message["From"][2:]

    #phone numbers are now stored as 9char strings, stripping all dashes,dots, etc
    #phone_number = '-'.join([phone[:3], phone[3:6], phone[6:]])

    #set up the response
    resp = MessagingResponse()

    #Find the user associated with this phone number
    incoming_coach = match_coach_by_phone(phone)

    #if the phone number does not match our db
    if incoming_coach is None:
        resp.message("The Reading Coach: Your phone number does not match our database.")
        return str(resp)

    #otherwise, send the message about the program end
    resp.message("The Reading Coach: The 2018 Summer Reading Program has ended")
    return str(resp)
    def test_mixed(self):
        r = MessagingResponse()

        r.append('before')
        r.add_child('Child').append('content')
        r.append('after')

        assert_equal(
            self.strip(r),
            '<?xml version="1.0" encoding="UTF-8"?><Response>before<Child>content</Child>after</Response>'
        )
def receive_message():
    """Run a label request on an image received from Twilio"""

    resp = MessagingResponse()

    attachments = int(request.values.get('NumMedia', 0))
    if not attachments:
        response_text = "No media attachments found."
        resp.message(response_text)
        return str(resp)

    # Process media attachments
    for i in range(attachments):

        media_content_type = request.values.get('MediaContentType%i' % i, None)

        # First, check to see if we can use the attachment
        if media_content_type in ACCEPTABLE_FILE_TYPES:

            # get the image
            media_url = request.values.get('MediaUrl%i' % i, None)
            image = requests.get(media_url).content

            # Query the API
            labels, face_annotations, logos = get_labels(image)
            logging.info("got labels %s", str(labels))
            # We're only looking at the first image
            break
        else:
            response_text = "We are not able to process this type of attachment."
            resp.message(response_text)
            return str(resp)

    # Construct the response
    resp = construct_message(labels, face_annotations, logos)
    return str(resp)
Beispiel #24
0
def message(request, message, to=None, sender=None, action=None,
            methods='POST', media=None, status_callback=None):
    """
    See: https://www.twilio.com/docs/api/twiml/sms/message

    Usage::

        # urls.py
        urlpatterns = patterns('',
            # ...
            url(r'^sms/$', 'django_twilio.views.message', {
                'message': 'Hello, world!',
                'media': 'http://fullpath.com/my_image.png'
            }),
            # ...
        )
    """

    r = MessagingResponse()
    r.message(body=message, to=to, sender=sender, method='POST',
              action=action, statusCallback=status_callback,
              media=media)

    return r
def hello():
    """Respond with the number of text messages sent between two parties."""
    # Increment the counter
    counter = session.get('counter', 0)
    counter += 1

    # Save the new counter value in the session
    session['counter'] = counter

    from_number = request.values.get('From')
    if from_number in callers:
        name = callers[from_number]
    else:
        name = "Friend"

    # Build our reply
    message = '{} has messaged {} {} times.' \
        .format(name, request.values.get('To'), counter)

    # Put it in a TwiML response
    resp = MessagingResponse()
    resp.message(message)

    return str(resp)
Beispiel #26
0
def sms():
    counter = session.get('counter', 0)
    work_flow = session.get('work_flow', [])
    counter += 1
    session['counter'] = counter
    resp = MessagingResponse()

    print counter
    if counter == 1:
        #resp = MessagingResponse()
        number = request.form['From']
        city, state = getCityLocation(number)
        print "counter is 1"
        resp.message(
            'Hello There! Welcome to Virtual Doc. Hope the weather is great at '
            + city + ' ' + state +
            '. If you know your disease press 1 or else press 2')
        return str(resp)
    elif counter == 2:
        #work_flow = []
        message_body = request.form['Body']
        print "counter is 2"
        if message_body == '1':
            resp.message(
                "Tell me your disease and I will give you the medication")
            work_flow.append(1)
        else:
            work_flow.append(2)
            resp.message(
                "Let me diagnose you! Let's get a bit more specific. \n Press 1 if you have you any discomfort in your chest. \n Press 2 if you have any body pain. \n Press 3 if you are experiencing pain in your head."
            )
        session['work_flow'] = work_flow
        print work_flow
        return str(resp)
    elif counter == 3:
        #work_flow.append(2)
        if work_flow[-1] == 2:
            message_body = request.form['Body']
            if message_body == '1':
                work_flow.append(1)
                print 'Inside 1'
                resp.message(
                    "Don't worry I'll solve your problem, just answer the below questions with a number between 0 to 5. With 5 being severe. \n 1) Severity of Acid Flux? \n 2) Difficulty to swallow \n 3) Severity of wheezing \n 4) Severity of rapid breathing \n 5) Severity of restlessness \n 6) Severity of panic \n Keep a space between each value. Ex - 5 1 0 0"
                )
            elif message_body == '2':
                work_flow.append(2)
                resp.message(
                    "Don't worry I'll solve your problem, just answer the below questions with a number between 0 to 5. With 5 being severe. \n 1) Severity of Running Nose? \n 2) Severity of tiredness \n 3) Severity of Vomiting \n 4) Severity of muscle soreness \n 5) Severity of getting chills \n 6) Severity of body temperature \n 7) Severity of nauseous \n Keep a space between each value. Ex - 5 1 0 0"
                )
                print 'Inside 2'
            else:
                work_flow.append(3)
                resp.message(
                    "Don't worry I'll solve your problem, just answer the below questions with a number between 0 to 5. With 5 being severe. \n 1) Severity of pain on one side of your head \n 2) Is the pain intense? - 0 for No or 1 for Yes \n 3) Is the pain mild? - 0 for No or 1 for Yes \n 4) Severity of pain on all parts of your head \n Keep a space between each value. Ex - 5 1 0 0"
                )
                print 'Inside 3'
        else:
            message_body = request.form['Body']
            drug_name_store_price_map = getDrugStoresAndPrice(message_body)
            #print drug_name_store_price_map
            final_str = ''
            for each_drug in drug_name_store_price_map.keys():
                store_name, price = drug_name_store_price_map[each_drug]
                make_str = each_drug + ': '
                new_str = ''
                for i in range(0, 4):  #len(store_name)
                    new_str += store_name[i] + ' : ' + price[i] + ", "
                make_str += new_str
                final_str += make_str + ", "
            print(final_str)
            #resp = MessagingResponse()
            resp.message('Drugs that you can use ' + final_str + " " +
                         str(counter))
            #session.close()
        session['work_flow'] = work_flow
        print work_flow
        return str(resp)
    elif counter == 4 and len(work_flow) == 2:
        message_body = request.form['Body']
        print(message_body)
        message_body = message_body.split(" ")
        if work_flow[-1] == 1:
            test_list = [
                message_body[0], message_body[1], message_body[2],
                message_body[3], message_body[4], message_body[5], 0, 0, 0, 0,
                0, 0, 0, 0, 0, 0, 0
            ]
        elif work_flow[-1] == 2:
            test_list = [
                0, 0, 0, 0, 0, 0, message_body[0], message_body[1],
                message_body[2], message_body[3], message_body[4],
                message_body[5], message_body[6], 0, 0, 0, 0
            ]
        else:
            test_list = [
                0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, message_body[0],
                message_body[1], message_body[2], message_body[3]
            ]
        disease = getDisease(test_list)
        print disease
        drug_name_store_price_map = getDrugStoresAndPrice(disease)
        #print drug_name_store_price_map
        final_str = ''
        for each_drug in drug_name_store_price_map.keys():
            store_name, price = drug_name_store_price_map[each_drug]
            make_str = each_drug + ': '
            new_str = ''
            for i in range(0, 4):  #len(store_name)
                new_str += store_name[i] + ' : ' + price[i] + ", "
            make_str += new_str
            final_str += make_str + ", "
        print(final_str)
        #resp = MessagingResponse()
        resp.message('Oh Shit! You have ' + disease +
                     '. Drugs that you can use ' + final_str + " " +
                     str(counter))
        #resp.message('')
        return str(resp)
    else:
        session['counter'] = 0
        counter = 0
        session['work_flow'] = []
        resp.message('Bye')
        #session.close()
        return str(resp)
Beispiel #27
0
def bot():
    # print("AccountSid: "+request.values.get('AccountSid', ''))
    print("From: " + request.values.get('From', ''))
    # print("Date: "+request.values.get('dateCreated', ''))
    # print("AccountSid: "+request.values.get('Sid', ''))
    # print("ErrorMessage: "+request.values.get('ErrorMessage', ''))
    # print("Content: "+request.values.get('Body', ''))

    customermobno = request.values.get('From', '')
    start_index = customermobno.index('+')
    end_index = len(customermobno)
    # print("Incoming From : Start: {0} End: {1} ".format(start_index, end_index))

    incoming_msg = request.values.get('Body', '').lower()
    resp = MessagingResponse()
    msg = resp.message()
    greetings = """===============================================================
*เฎตเฎฃเฎ•เฏเฎ•เฎฎเฏ เฎฎเฎคเฏเฎฐเฏˆ เฎฎเฎ•เฏเฎ•เฎณเฏ‡*
เฎ‡เฎคเฏ เฎ’เฎฐเฏ เฎคเฎพเฎฉเฎฟเฎฏเฎ™เฏเฎ•เฎฟ เฎŠเฎŸเฎพเฎŸเฏเฎฎเฏ เฎšเฏ‡เฎตเฏˆ
*_เฎฎเฏเฎ•เฏเฎ•เฎฟเฎฏ เฎ…เฎฑเฎฟเฎตเฎฟเฎชเฏเฎชเฏ_*: 
เฎฎเฎฐเฏเฎคเฏเฎคเฏเฎตเฎฎเฏ, เฎคเฏ€ เฎฎเฎฑเฏเฎฑเฏเฎฎเฏ เฎ•เฏŠเฎฐเฏ‹เฎฉเฎพ เฎ…เฎตเฎšเฎฐ เฎคเฏ‡เฎตเฏˆเฎ•เฎณเฏเฎ•เฏเฎ•เฏ
เฎ…เฎฐเฎšเฏ เฎŽเฎฃเฏเฎ•เฎณเฏˆ เฎคเฏŠเฎŸเฎฐเฏเฎชเฏ เฎ•เฏŠเฎณเฏเฎณเฎตเฏเฎฎเฏ.

เฎฎเฎฑเฏเฎฑ เฎ‡เฎคเฎฐ เฎšเฏ‡เฎตเฏˆเฎ•เฎณเฏเฎ•เฏเฎ•เฏ เฎชเฎฟเฎฉเฏ เฎตเฎฐเฏเฎฎเฏ เฎชเฎŸเฏเฎŸเฎฟเฎฏเฎฒเฎฟเฎฒเฏ เฎ‡เฎฐเฏเฎจเฏเฎคเฏ เฎคเฏ‡เฎฐเฏเฎตเฏ เฎšเฏ†เฎฏเฏเฎ•,

*Welcome people of Madurai*
This is an automated whatsapp chat bot
*_Warning_*: 
Please call government helpline numbers if you have
Medical, Fire or Corona related Emergency.

For other support kindly select from below choice,
===============================================================
*1* เฎ‰เฎฃเฎตเฏ, เฎ•เฎพเฎฏเฏเฎ•เฎฑเฎฟ, เฎชเฎดเฎ™เฏเฎ•เฎณเฏ, เฎฎเฎณเฎฟเฎ•เฏˆ เฎคเฏ‡เฎตเฏˆเฎ•เฎณเฏ / Food, Groceries
*2* เฎฎเฎฐเฏเฎคเฏเฎคเฏเฎต เฎคเฏ‡เฎตเฏˆเฎ•เฎณเฏ [ เฎ‡เฎฐเฎคเฏเฎคเฎฎเฏ, เฎฎเฎฐเฏเฎจเฏเฎคเฏเฎ•เฎณเฏ ] / Medical Supplies
*3* เฎ•เฏเฎŸเฎฟ เฎจเฏ€เฎฐเฏ เฎคเฏ‡เฎตเฏˆเฎ•เฎณเฏ / Drinking Water Requirements
*4* เฎฎเฎฟเฎฉเฏ เฎชเฏเฎ•เฎพเฎฐเฏ / Electricity Complaints
*5* เฎšเฏเฎ•เฎพเฎคเฎพเฎฐ เฎ•เฏเฎฑเฏˆเฎ•เฎณเฏ / Sanitation Needs
*6* เฎ…เฎตเฎšเฎฐ เฎชเฎฏเฎฃ เฎ•เฏ‹เฎฐเฎฟเฎ•เฏเฎ•เฏˆ / Emergency Travel Requests
*7* เฎคเฎ™เฏเฎ•เฎณเฏ เฎ•เฏ‹เฎฐเฎฟเฎ•เฏเฎ•เฏˆเฎฏเฎฟเฎฉเฏ เฎจเฎฟเฎฒเฏˆ / Status of the Requests
*8* เฎคเฎฉเฏเฎฉเฎพเฎฐเฏเฎตเฎฒเฎฐเฏเฎ•เฎณเฎพเฎ• เฎชเฎฃเฎฟเฎฏเฎพเฎฑเฏเฎฑ เฎตเฎฟเฎฐเฏเฎชเฏเฎชเฎฎเฏ / Volunteer Registration
*9* เฎŽเฎ™เฏเฎ•เฎณเฏˆ เฎคเฏŠเฎŸเฎฐเฏเฎชเฏเฎ•เฏŠเฎณเฏเฎณ / Contact Us

เฎคเฎพเฎ™เฏเฎ•เฎณเฏ เฎตเฎฟเฎฐเฏเฎฎเฏเฎชเฏเฎฎเฏ เฎšเฏ‡เฎตเฏˆเฎ•เฏเฎ•เฏ เฎจเฎฟเฎ•เฎฐเฎพเฎฉ เฎŽเฎฃเฏเฎฃเฏˆ เฎ‰เฎณเฏเฎณเฏ€เฎŸเฏ เฎšเฏ†เฎฏเฏเฎ•.
_เฎ‰เฎคเฎพเฎฐเฎฃเฎคเฏเฎคเฎฟเฎฑเฏเฎ•เฏ_ เฎฎเฎฟเฎฉเฏ เฎชเฏเฎ•เฎพเฎฐเฏเฎ•เฏเฎ•เฏ เฎŽเฎฃเฏ 4 เฎ…เฎดเฏเฎคเฏเฎคเฎตเฏเฎฎเฏ

Kindly enter the number which corresponds to the needed support
_Example_: Press 4 if you want support in Electricity Complaints
===============================================================
"""
    requestreceived = """เฎคเฎ™เฏเฎ•เฎณเฏ เฎ•เฏ‹เฎฐเฎฟเฎ•เฏเฎ•เฏˆ เฎชเฎคเฎฟเฎฏเฎชเฏเฎชเฎŸเฏเฎŸเฎคเฏ 
Your request is received"""
    inprogress = """เฎ‡เฎจเฏเฎค เฎตเฎšเฎคเฎฟ เฎ•เฎŸเฏเฎŸเฏเฎฎเฎพเฎฉเฎคเฏเฎคเฎฟเฎฒเฏ เฎ‰เฎณเฏเฎณเฎคเฏเฎคเฏ 
This feature is in progress"""
    volunteerregistration = """เฎคเฎ™เฏเฎ•เฎณเฏ เฎ†เฎฐเฏเฎตเฎคเฏเฎคเฎฟเฎฑเฏเฎ•เฏ เฎจเฎฉเฏเฎฑเฎฟ! เฎตเฎฟเฎฐเฏˆเฎตเฎฟเฎฒเฏ เฎ‰เฎ™เฏเฎ•เฏˆเฎณเฏˆ เฎคเฏŠเฎŸเฎฐเฏเฎชเฏ เฎ•เฏŠเฎณเฏเฎตเฏ‹เฎฎเฏ 
Thank you for your interest! You will hear from us shortly"""
    aboutus = """เฎฎเฎคเฏเฎฐเฏˆ เฎคเฎฉเฏเฎฉเฎพเฎฐเฏเฎตเฏ เฎšเฏ‡เฎตเฏˆเฎ•เฎณเฏ
Madurai Voluntary Services
+91 8220287172 / +91 8758410258
เฎฎเฏ†เฎฉเฏเฎชเฏŠเฎฑเฎฟเฎฏเฎพเฎณเฎฐเฏ เฎคเฏŠเฎŸเฎฐเฏเฎชเฏ  / Developer Contact: 
+91 9943634523"""
    if incoming_msg.strip().isdigit():
        if int(incoming_msg.strip()) >= 1 and int(incoming_msg.strip()) <= 6:
            msg.body(requestreceived)
            update_db(customermobno, int(incoming_msg.strip()))
        if int(incoming_msg.strip()) == 7:
            msg.body(inprogress)
            update_db(customermobno, 7)
        if int(incoming_msg.strip()) == 8:
            msg.body(volunteerregistration)
            update_db(customermobno, 8)
        if '9' == incoming_msg:
            msg.body(aboutus)
        if int(incoming_msg.strip()) >= 10:
            msg.body(greetings)
    else:
        msg.body(greetings)

    return str(resp)
Beispiel #28
0
def respond(message):
    response = MessagingResponse()
    response.message(message)
    return str(response)
Beispiel #29
0
def sms_reply():
    """Respond to incoming calls with a simple text message."""
    # Fetch the message
    msg = request.form.get('Body')
    # Create reply
    resp = MessagingResponse()
    response = MessagingResponse()
    message = Message()
    #resp.message("You said: {}".format(msg))
    if msg == "1":
        resp.message("Your  A/c XXXXXXX2138 on 02/02/2020 .Avl Bal Rs " +
                     str(data[m - 1, n - 1]))
    if msg == "2":
        message.body('Expenditure Categorisation')
        message.media('https://cc70f734.ngrok.io/as1.png')
        response.append(message)
        return str(response)
    if msg == "3":
        message.body('Atms near me')
        message.media('https://cc70f734.ngrok.io/atms.png')
        response.append(message)
        return str(response)
    if msg == "4":
        resp.message(
            "Standard Chartered Bank Personal Loan Details" +
            "Loan available for both salaried and self-employed professionals. Borrowers within the age group of 23 and 58 years."
            +
            "Loan amount of minimum โ‚น 1 Lakh to โ‚น 30 Lakh. Standard Chartered personal loan rate of interest is in the range of 10.99% to 19.00%."
        )
    if msg == "5":
        resp.message("you opted option 5")
    if msg == "6":
        message.body('transaction history')
        message.media('https://cc70f734.ngrok.io/transition.png')
        response.append(message)
        return str(response)
    if msg == "Options":
        resp.message(
            "Transaction History:\n1-Balance Enquiry\n2-Expenditure Categorisation\n3-ATM Near Me\n4-Loan Details\n5-Balance Analysis\n6-Transaction History"
        )
    return str(resp)
def sms_reply():
    resp = MessagingResponse()
    resp.messages("I'm great too!")
    return str(resp)
def _send_not_found():
    response = MessagingResponse()
    response.message(NOT_FOUND_MESSAGE)
    return str(response)
Beispiel #32
0
from twilio.twiml.messaging_response import Body, Message, Redirect, MessagingResponse

response = MessagingResponse()
message = Message()
message.body('Hello World!')
response.append(message)
response.redirect('https://demo.twilio.com/sms/welcome')

print(response)
Beispiel #33
0
 def process_response(self, req, resp, resource, req_succeeded):
     '''Post-request middleware to turn the response into twilio's XML format'''
     twil_resp = MessagingResponse()
     twil_resp.message(resp.body)
     resp.body = str(twil_resp)
Beispiel #34
0
async def handle_incoming(request):
    form = await request.post()
    message_sid = form['MessageSid']
    from_number = form['From']
    num_media = int(form.get('NumMedia', 0))
    message = form.get('Body', None)

    session = request.app['session']()
    user = User.get_or_create_user(session, from_number)

    def log(message='', event=None, **kwargs):
        extra = {
            'user_id': user.id,
            'tc_status': user.tc_status,
            'message_sid': message_sid
        }
        if event is not None:
            extra[event] = True
        extra.update(kwargs)
        logger.info(message, extra=extra)

    log('Received message', event='received_message')

    if num_media > 0:
        media_files = [(form.get("MediaUrl{}".format(i), ''),
                        form.get("MediaContentType{}".format(i), ''))
                       for i in range(0, num_media)]
        for media_url, _ in media_files:
            # TODO upload pictures to google cloud storage and delete from twilio servers
            picture = Picture(source_url=media_url,
                              create_time=datetime.now(),
                              message_sid=message_sid)
            print(media_url)
            session.add(picture)
            user.add_pending(picture)

    session.commit()

    worker_loop = request.app['worker']['loop']
    response = None

    if user.tc_status is TCStatus.NOTHING:

        log('New user, sending terms and conditions', 'send_tc')
        response = config.TC_AGREEMENT_TEXT
        user.tc_status = TCStatus.SENT
    elif user.tc_status is TCStatus.SENT:

        if message is not None:
            if message.upper() == 'YES':
                log('Agreed to terms and conditions', 'tc_agreed')
                user.tc_status = TCStatus.AGREED
                response = 'Thank you for agreeing to the terms and conditions.'
                if len(user.pending) > 0:
                    response += " Processing your {} picture(s) now".format(
                        len(user.pending))
                    asyncio.run_coroutine_threadsafe(
                        process_pictures(session, user.pending), worker_loop)
                    # await process_pictures(session, user.pending)
                else:
                    response += " You can now send me pictures to convert"
        else:
            log('Remind to agree to terms and conditions', 'tc_remind')
            response = 'You must agree to the terms and conditions by responding YES before continuing.'
            if len(user.pending) > 0:
                response += " You have {} pictures pending".format(
                    len(user.pending))
            response = ' '.join(response)
    else:

        assert user.tc_status is TCStatus.AGREED
        if num_media > 0:
            log('Received new pictures',
                'more_pictures',
                num_new_pictures=num_media)
            response = "Got it! Hard at work processing {} more /picture(s) for you!".format(
                num_media)
            asyncio.run_coroutine_threadsafe(
                process_pictures(session, user.pending), worker_loop)
            # await process_pictures(session, user.pending)

    session.commit()

    if not response:
        response = "Sorry, I didn't understand that!"
    mesg_resp = MessagingResponse()
    mesg_resp.message(response)
    return Response(text=str(mesg_resp), content_type='text/xml')
Beispiel #35
0
def sms_reply():
    resp = MessagingResponse()
    resp.message("I do not love you")

    return str(resp)
from twilio.twiml.messaging_response import Message, MessagingResponse

response = MessagingResponse()
response.message(
    'Store Location: 123 Easy St.', action='/SmsHandler.php', method='POST'
)

print(response)
Beispiel #37
0
def timet():
    count = 0
    while (True):
        days = [
            "monday.txt", "tuesday.txt", "wednesday.txt", "thursday.txt",
            "friday.txt", "saturday.txt", "sunday.txt"
        ]
        d = datetime.datetime.today().weekday()

        account_sid = "ACb8d91a3df5c33396b226bb1cee1b85b5"
        auth_token = "93456d7a03cbd46568978f47aed90011"

        mobile_number = [
            "+919936284777",
        ]
        for i in mobile_number:
            f = open('days/' + days[d], 'r')
            client = Client(account_sid, auth_token)
            message = client.messages.create(from_='whatsapp:+14155238886',
                                             body=f.read(),
                                             to='whatsapp:' + i)
            f.close()
        f.close()
        count += 1
        if count == 5:
            break
        time.sleep(5)

    reply = ""
    days = [
        "monday.txt", "tuesday.txt", "wednesday.txt", "thursday.txt",
        "friday.txt", "saturday.txt", "sunday.txt"
    ]
    d = datetime.datetime.today().weekday()
    f = open('days/' + days[d], 'r')
    body = request.values.get('Body', None)
    if 'update' in body.lower():
        reply = f.read()
        f.close()

    elif 'broadcast' in body.lower():
        msg = "Broadcast from " + str(request.values.get(
            'From', None))[-13:] + ":\n" + body[10:]
        account_sid = "ACb8d91a3df5c33396b226bb1cee1b85b5"
        auth_token = "93456d7a03cbd46568978f47aed90011"

        mobile_number = [
            "+919936284777", "+919260972911", "+919755761191", "+917448009954",
            "+917004727387"
        ]
        for i in mobile_number:
            f = open('days/' + days[d], 'r')
            client = Client(account_sid, auth_token)
            message = client.messages.create(from_='whatsapp:+14155238886',
                                             body=msg,
                                             to='whatsapp:' + i)
        f.close()
        reply = "Message broadcasted."

    else:
        reply = "Have a good day!"

    resp = MessagingResponse()
    resp.message(reply)
    return str(resp)
Beispiel #38
0
def sms():
    rVal = ""
    msg = request.form['Body']
    try:
        incomingMsgBody = utils.parseIncomingMessage(msg)
    except ValueError:
        incomingMsgBody = Utils.IncomingMessageStruct(
            reqType=sInfo.ERROR,
            error=
            "Please use fewer symbols in your query. Take out one of these 9: ['<', '>', '@', '#', '%', '^', '&', '*', ';', '/']"
        )
    msgResp = MessagingResponse()
    reqType = incomingMsgBody.reqType
    error = False

    if incomingMsgBody.error is None:
        if incomingMsgBody.reqType == sInfo.GOOGLE_SEARCH:
            try:
                gRes = resGen.get_search_result(incomingMsgBody.googleQuery)

                if len(gRes) == 0:
                    rVal = "Please refine your query. Use proper english. No results were found."
                    error = True
                else:
                    r = "%s%s" % (incomingMsgBody.googleQuery,
                                  sInfo.resultOutterDelim)
                    for result in gRes:
                        currString = "%s%s%s" % (result.description,
                                                 sInfo.resultInnerDelim,
                                                 sInfo.resultOutterDelim)
                        r = r + currString
                    rVal = r
            except:
                rVal = "Error made  by me. Please contact me. Error: Search Library not working"
                error = True
        elif incomingMsgBody.reqType == sInfo.TRANSLATION:
            try:
                if incomingMsgBody.transTo is not None and incomingMsgBody.transText is not None:
                    tRes = resGen.get_translation(
                        _tolang=incomingMsgBody.transTo,
                        _fromlang=incomingMsgBody.transFrom,
                        text=incomingMsgBody.transText)
                    if tRes.error is None:
                        rVal = "%s%s%s%s%s%s%s" % (
                            utils.lang(tRes.fromLang), sInfo.resultInnerDelim,
                            utils.lang(tRes.toLang), sInfo.resultInnerDelim,
                            tRes.fromText, sInfo.resultInnerDelim, tRes.toText)
                    else:
                        rVal = tRes.error
                        error = True
                else:
                    rVal = "Error made  by me. Please contact me. Error: TO AND TEXT IN TRANS NONE"
                    error = True
            except:
                rVal = "Error made  by me. Please contact me. Error: Translation Library not working"
                error = True
        elif incomingMsgBody.reqType == sInfo.DIRECTIONS:
            try:
                if incomingMsgBody.dirTo is not None and incomingMsgBody.dirFrom is not None:
                    dRes = resGen.get_directions(_from=incomingMsgBody.dirFrom,
                                                 _to=incomingMsgBody.dirTo,
                                                 _mode=incomingMsgBody.dirMode)
                    if dRes[0].error is None:
                        rVal = dRes
                    else:
                        rVal = dRes[0].error
                        error = True
                else:
                    rVal = "Error made  by me. Please contact me. Error: TO AND FROM IN DIR NONE"
            except:
                rVal = "Error made  by me. Please contact me. Error: Directions Library not working"
                error = True
        elif incomingMsgBody.reqType == sInfo.SPORTS:
            try:
                if incomingMsgBody.sportSport is not None and incomingMsgBody.sportHome is not None and incomingMsgBody.sportAway is not None:
                    sRes = resGen.get_sport_update(
                        incomingMsgBody.sportSport,
                        [incomingMsgBody.sportHome, incomingMsgBody.sportAway])
                    if sRes.error is None:
                        rVal = "%s%s%s%s%s%s%s%s" % (
                            sRes.home_team, sInfo.resultInnerDelim,
                            sRes.away_team, sInfo.resultInnerDelim,
                            sRes.home_score, sInfo.resultInnerDelim,
                            sRes.away_score, sInfo.resultOutterDelim)
                    else:
                        rVal = sRes.error
                        error = True
                else:
                    rVal = "Error made  by me. Please contact me. Error: TO AND FROM IN DIR NONE"
                    error = True
            except:
                rVal = "Error made  by me. Please contact me. Error: Sports Library not working"
                error = True
    else:
        rVal = incomingMsgBody.error
        error = True

    if isinstance(rVal, list):
        if not error:
            r = "%s%s%s%s" % (incomingMsgBody.dirFrom, sInfo.resultInnerDelim,
                              incomingMsgBody.dirTo, sInfo.resultOutterDelim)
            for i in range(len(rVal)):
                dir = rVal[i]
                # The return string must have at least 1 resultInnerDelim and 1 resultOutterDelim. It will follow the general format of
                # [REQTYPE][TEXT 1][RESULTOUTTERDELIM]...[TEXT N][RESULTOUTTERDELIM]
                # Each TEXT has format [INFO 1][RESULTINNERDELIM]...[INFO N][RESULTINNERDELIM]

                currString = "%s%s%s%s%s%s" % (
                    dir.distance, sInfo.resultInnerDelim, dir.time,
                    sInfo.resultInnerDelim, dir.instruction,
                    sInfo.resultOutterDelim)
                r = r + currString

            msgResp.message(str(reqType) + '' + r)
        else:
            msgResp.message(str(sInfo.ERROR) + '' + rVal)
    else:
        if not error:
            msgResp.message(str(reqType) + '' + str(rVal))
        else:
            msgResp.message(str(sInfo.ERROR) + '' + str(rVal))

    return str(msgResp)
Beispiel #39
0
from flask import Flask, request, jsonify, make_response
from twilio.twiml.messaging_response import MessagingResponse
import Utils
from ResultGeneration import ResultGen as res
import json

app = Flask(__name__)

sInfo = Utils.SharedInfo()
resp = MessagingResponse()
resGen = res()
utils = Utils.Utils()


@app.route('/sms', methods=['POST', 'GET'])
def sms():
    rVal = ""
    msg = request.form['Body']
    try:
        incomingMsgBody = utils.parseIncomingMessage(msg)
    except ValueError:
        incomingMsgBody = Utils.IncomingMessageStruct(
            reqType=sInfo.ERROR,
            error=
            "Please use fewer symbols in your query. Take out one of these 9: ['<', '>', '@', '#', '%', '^', '&', '*', ';', '/']"
        )
    msgResp = MessagingResponse()
    reqType = incomingMsgBody.reqType
    error = False

    if incomingMsgBody.error is None:
Beispiel #40
0
 def post(cls) -> Response:
     message_body = request.form['Body']
     response = MessagingResponse()
     response.message('the')
     return Response(response)
Beispiel #41
0
def sms_welcome_message():
    resp = MessagingResponse()
    resp.message(str(const.WELCOME_MESSAGE))
    return str(resp)
Beispiel #42
0
def whatsApp_portal(request):

	lang = "EN" # change to BN . Dont use translate if lang = EN
	try:
		if request.method == 'POST':
			incoming_msg = request.POST['Body'].lower()
			aadhar = incoming_msg[1:]
			resp = MessagingResponse()
			msg = resp.message()
			#msg1 = resp.message()
			#msg2 = resp.message()

			responded = False
			try:
				#quote = "booo"
				#msg.body(quote)
				dos = Dosage.objects.get(matchedaadhar=aadhar)
				res = Register.objects.get(fullaadhar=aadhar)
				quote = "Your next dosage date and details are"
				if res.lang_pref == 'Hindi':
					lang = "HI"
				if res.lang_pref == 'Bengali':
					lang = "BN"
				if incoming_msg[0] == '1' and lang != "EN":
					responded = True
					translator= Translator(to_lang=lang)
					translation = translator.translate(quote)
					quote1 = str(dos.dosage_date)
					quotet2 = dos.dosage_details
					quote2 = translator.translate(quotet2)
					quote3 = ": "
					quote4 = " "
					quote5 = translator.translate("Dosage date")
					quote6 = translator.translate("Dosage details")
					msg.body(translation+quote3+quote4+quote5+quote3+quote1+quote4+quote6+quote3+quote2)
				elif incoming_msg[0] == '1' and lang == "EN":
					responded = True
					#translator= Translator(to_lang=lang)
					#translation = translator.translate(quote)
					quote1 = str(dos.dosage_date)
					quote2 = dos.dosage_details
					#quote2 = translator.translate(quotet2)
					quote3 = ": "
					quote4 = " "
					quote5 = "Dosage date"
					quote6 = "Dosage details"
					msg.body(quote+quote3+quote4+quote5+quote3+quote1+quote4+quote6+quote3+quote2)

				if incoming_msg[0] == '2' and lang != "EN":
					upcoming = Event.objects.order_by('day')
					dt = datetime.date.today()
					responded = True
		        #dates = Event.objects.order_by('day')
					for up in upcoming:
						if dt.strftime('%B') == up.day.strftime('%B'):
							translator= Translator(to_lang=lang)
							quote = str(up.day)
							quotet = up.notes
							quote1 = translator.translate(quotet)
							quotet2 = str(up.start_time)
							quote2 = translator.translate(quotet2)
							quote3 = str(up.end_time)
							quote4 = " "
							#quote8 = '/n'
							msg.body(quote1 +quote4+ quote+quote4+ quote2+quote4 + quote3 )
				elif incoming_msg[0] == '2' and lang == "EN":
					#if incoming_msg[0] == '2' and lang != "EN":
					upcoming = Event.objects.order_by('day')
					dt = datetime.date.today()
					responded = True
			        #dates = Event.objects.order_by('day')
					for up in upcoming:
						if dt.strftime('%B') == up.day.strftime('%B'):
								#translator= Translator(to_lang=lang)
							quote = str(up.day)								#quote1 = up.notes
								#quote1 = translator.translate(quotet)
							quote1 = up.notes
							quote2 = str(up.start_time)
								#quote2 = translator.translate(quotet2)
							quote3 = str(up.end_time)
							quote4 = " "
								#quote8 = '/n'
							msg.body(quote1 +quote4+ quote+quote4+ quote2+quote4 + quote3 )

				if incoming_msg[0] == '3' and lang != "EN":
					translator= Translator(to_lang=lang)
					quotet1 = "Available dates for checkup "
					quote1 = translator.translate(quotet1)
					responded = True
					#msg.body(quotet1)
					try:
						absentees_checkup = Event.objects.filter(notes="checkup for absentees")
						msg.body(quote1)

						for a in absentees_checkup:
							quote2 = str(a.day)
							msg.body(quote2)
					except Event.DoesNotExist:
						quotet3 = 'No dates available for checkup'
						quote3 = translator.translate(quotet3)
						msg.body(quote3)

				elif incoming_msg[0] == '3' and lang == "EN":
					#translator= Translator(to_lang=lang)
					quote1 = "Available dates for checkup "
					#quote1 = translator.translate(quotet1)
					responded = True
					#msg.body(quotet1)
					try:
						absentees_checkup = Event.objects.filter(notes="checkup for absentees")
						msg.body(quote1)

						for a in absentees_checkup:
							quote2 = str(a.day)
							msg.body(quote2)
					except Event.DoesNotExist:
						quote3 = 'No dates available for checkup'
						#quote3 = translator.translate(quotet3)
						msg.body(quote3)

				if incoming_msg[0] != '2' and incoming_msg[0] != '1' and incoming_msg[0] != '3' and lang != "EN":
					quote = 'Wrong input. Type 1 with your aadhar to get dosage details and 2 with your aadhar for events.'
					translator= Translator(to_lang=lang)
					translation = translator.translate(quote)
					responded = True
					msg.body(translation)
				elif incoming_msg[0] != '2' and incoming_msg[0] != '1' and incoming_msg[0] != '3' and lang == "EN":
					quote = 'Wrong input. Type 1 with your aadhar to get dosage details and 2 with your aadhar for events.'
					translator= Translator(to_lang=lang)
					responded = True
					translation = translator.translate(quote)
					msg.body(translation)








			except Dosage.DoesNotExist:
				try:
					inc = incoming_msg[10:]
					dos = Dosage.objects.get(matchedaadhar=inc)
					res = Register.objects.get(fullaadhar=inc)
					search = Event.objects.filter(notes="checkup for absentees")
					responded = True
					#lang = "EN"
					if res.lang_pref == 'Hindi':
						lang = "HI"
					if res.lang_pref == 'Bengali':
						lang = "BN"
					if res.lang_pref == 'English':
						done = 0
						#translator= Translator(to_lang=lang)
						#fixed = ""
						for d in search:
							if str(d.day) == incoming_msg[0:10]:
								#fixed = Event.objects.get(day=d.day)
								done = 1
								#break
						#translator= Translator(to_lang=lang)
							if done == 1:
								dos.dosage_date = d.day
								dos.save()
								quote = 'Your checkup date has been set.'
								quote2 = str(d.day)
								quote3 = str(d.start_time)
								quote4 = str(d.end_time)
								quote5 = " "
						#translator= Translator(to_lang=lang)
								#translation = translator.translate(quote)
								#msg.body(translation+quote2)
								msg.body(quote+quote5+quote2+quote5+quote3+quote5+quote4)
								break

						if done == 0:
							quote = 'This date is not available for checkup.'
							#translation = translator.translate(quote)
							msg.body(quote)
					else:
						done = 0
						translator= Translator(to_lang=lang)
						#fixed = ""
						for d in search:
							if str(d.day) == incoming_msg[0:10]:
								#fixed = Event.objects.get(day=d.day)
								done = 1
								#break
						#translator= Translator(to_lang=lang)
							if done == 1:
								dos.dosage_date = d.day
								dos.save()
								quote = 'Your checkup date has been set.'
								quote2 = str(d.day)
								quote3 = str(d.start_time)
								quote4 = str(d.end_time)
								quote5 = " "

						#translator= Translator(to_lang=lang)
								translation = translator.translate(quote)
								#msg.body(translation+quote2)
								msg.body(translation+quote5+quote2+quote5+quote3+quote5+quote4)
								break

						if done == 0:
							quote = 'This date is not available for checkup.'
							translation = translator.translate(quote)
							msg.body(translation)



				except Dosage.DoesNotExist:
					responded = True
					quote = " Type 1 with aadhar number to get dosage details, 2 with aadhar number to get event details, 3 with aadhar to get checkup dates and <date><aadhar number> to reschedule dosage date"
					msg.body(quote)

				#quote = 'Enter aadhar number correctly.Type 1 with your aadhar(1<aadhar>) to get dosage details and 2 with your aadhar(2<aadhar>) for events. '
				#translator= Translator(to_lang=lang)
				#translation = translator.translate(quote)
				#responded = True
				#msg.body(quote)










			if not responded:
				quote = 'Wrong input. Type 1 for list of upcoming events and type your aadhar number to get dosage details'
				translator= Translator(to_lang=lang)
				translation = translator.translate(quote)
				msg.body(translation)
				#quote = 'Wrong input. Type 1 for list of upcoming events and type your aadhar number to get dosage details'
				#translator= Translator(to_lang="BN")
				#translation = translator.translate(quote)
				#msg1.body(translation)
				#quote = 'Wrong input. Type 1 for list of upcoming events and type your aadhar number to get dosage details'
				#translator= Translator(to_lang=lang)
				#translation = translator.translate(quote)
				#msg2.body(quote)
			#retu##rn str(resp)
			return HttpResponse(str(resp))
		else:
			return HttpResponse("No")
	except Exception as e:
		trace_back = traceback.format_exc()
		message = str(e) + " " + str(trace_back)
		return HttpResponse(message)
Beispiel #43
0
def sms_reply():
    resp = MessagingResponse()

    incoming_message_body = request.values.get('Body')
    print("Full incoming message body:", incoming_message_body)

    # Parsing for coordinates similar to 33ยฐ46โ€ฒ45โ€ณ N  94ยฐ23โ€ฒ24โ€ณ W

    latitude_full = incoming_message_body.split(" ")[0]
    if (incoming_message_body.split(" ")[1] == "N"):
        latitude_normalizer = float(1)
    else:
        latitude_normalizer = float(-1)
    longitude_full = incoming_message_body.split(" ")[3]
    if (incoming_message_body.split(" ")[4] == "E"):
        longitude_normalizer = float(1)
    else:
        longitude_normalizer = float(-1)
    print("Parsed values:", latitude_full, longitude_full)

    latitude_full = latitude_full.replace("ยฐ", " ")
    latitude_full = latitude_full.replace("โ€ฒ", " ")
    latitude_full = latitude_full.replace("โ€ณ", " ")

    longitude_full = longitude_full.replace("ยฐ", " ")
    longitude_full = longitude_full.replace("โ€ฒ", " ")
    longitude_full = longitude_full.replace("โ€ณ", " ")
    print("New parsed values:", latitude_full, longitude_full)

    latitude_degree = float(latitude_full.split(" ")[0])
    latitude_minute = float(latitude_full.split(" ")[1])
    latitude_second = float(latitude_full.split(" ")[2])
    longitude_degree = float(longitude_full.split(" ")[0])
    longitude_minute = float(longitude_full.split(" ")[1])
    longitude_second = float(longitude_full.split(" ")[2])

    latitude_decimal = latitude_normalizer * float(latitude_degree +
                                                   (latitude_minute / 60) +
                                                   (latitude_second / 3600))
    longitude_decimal = longitude_normalizer * float(longitude_degree +
                                                     (longitude_minute / 60) +
                                                     (longitude_second / 3600))
    print("Calculated coordinates", latitude_decimal, longitude_decimal)

    sun_api_response = requests.get('https://api.sunrise-sunset.org/json',
                                    params={
                                        'lat': latitude_decimal,
                                        'lng': longitude_decimal,
                                        'date': 'today'
                                    })
    print(sun_api_response.json()["status"])

    # {"status": "OK", "results": {
    # "day_length": "14:20:48",
    # "sunset": "12:52:12 AM",
    # "civil_twilight_end": "1:21:03 AM",
    # "nautical_twilight_end": "1:56:34 AM",
    # "astronomical_twilight_end": "2:35:19 AM"}}
    # "astronomical_twilight_begin": "8:48:17 AM",
    # "nautical_twilight_begin": "9:27:02 AM",
    # "civil_twilight_begin": "10:02:33 AM",
    # "sunrise": "10:31:24 AM",
    # "solar_noon": "5:41:48 PM",

    sun_data = sun_api_response.json()
    time_format = '%H:%M:%S %p'
    sunrise_time = datetime.strptime(sun_data['results']['sunrise'],
                                     time_format)
    sunset_time = datetime.strptime(sun_data['results']['sunset'], time_format)
    civil_twilight_end_time = datetime.strptime(
        sun_data['results']['civil_twilight_end'], time_format)

    # FIXME Incorrectly parsing time values (AM/PM not going correctly for sunrise time)
    # TODO convert from UTC to local
    # sunset_time = sunset_time.replace(tzinfo='UTC')
    # civil_twilight_end_time = civil_twilight_end_time.replace(tzinfo='UTC')
    # sunset_time = sunset_time.astimezone('America/New_York')
    # civil_twilight_end_time = civil_twilight_end_time.astimezone('America/New_York')

    tdelta = civil_twilight_end_time - sunset_time
    print(type(tdelta))
    print(type(sunset_time))
    # print(tdelta.strftime(time_format))
    print(sun_data['results']['sunset'], sunset_time.strftime(time_format))
    print(sun_data['results']['civil_twilight_end'],
          civil_twilight_end_time.strftime(time_format))

    golden_hour_start_time = sunset_time - tdelta
    golden_hour_end_time = sunset_time + (4.0 / 6.0) * tdelta

    print(type(golden_hour_start_time))
    print(golden_hour_start_time.strftime(time_format))
    print(type(golden_hour_end_time))
    print(golden_hour_end_time.strftime(time_format))

    # TODO Use Google Maps API timezone to determine time
    # Use time difference between civil twilight and sunset to determine golden hour offset

    resp.message("Golder Hour is from " +
                 golden_hour_start_time.strftime(time_format) + " UTC to " +
                 golden_hour_end_time.strftime(time_format) +
                 " UTC with sunset at " + sunset_time.strftime(time_format) +
                 " UTC")
    return str(resp)
Beispiel #44
0
def whatsapp_reply():
    """
    Respond to basic message on whatsapp
  """
    msg = request.form.get('Body')

    # Start out response
    resp = MessagingResponse()

    greeting_list = [
        "hey", "good morning", "good evening", 'g\'day', "good morrow",
        "hello", "hi", "sup"
    ]
    joke_list = ["bored", "joke", "laugh"]
    meme = ["meme", "funny picture", "bored", "boring"]
    status = [
        'how are you', 'whats up', 'what\'s up', 'howdy', 'what\'s new',
        'how are you doing', 'how are you coping'
    ]
    sad_response = [
        'bad', "not well", "stressed", "angry", "sad", "pissed off", "nervous"
    ]
    good_response = ['good', 'awesome', 'great', 'happy', 'relieved']

    #Myths
    if (any(keywords in msg.lower() for keywords in MYTHS)):
        msg = resp.message("Wawa-wee-wa ๐Ÿค–. Myth busting activated.").media(
            myth_busters(msg))
    #Greetings
    elif (any(keywords in msg.lower() for keywords in greeting_list)):
        msg = resp.message(wawa_tell_welcome())
    #Answer
    elif (any(keywords in msg.lower() for keywords in status)):
        msg = resp.message("I am good! How are you today?")
    #Sad response
    elif (any(keywords in msg.lower() for keywords in sad_response)):
        msg = resp.message(
            "Aww! It will get better with time. Ask me for a *joke* or *meme*, I want to cheer you up!"
        ).media('https://wawaweewabot.herokuapp.com/upload/WawaLove.png')
    #Good response
    elif (any(keywords in msg.lower() for keywords in good_response)):
        msg = resp.message("Great to hear that!")
    #Meme
    elif (any(keywords in msg.lower() for keywords in meme)):
        # image, message = wawa_get_meme()
        # if (image == "" or message == ""):
        index = randint(1, 26)
        image, message = 'https://wawaweewabot.herokuapp.com/uploads/{}'.format(
            index) + '.JPG', "Here is your meme!"
        msg = resp.message(message).media(image)
    #Joke
    elif (any(joke in msg.lower() for joke in joke_list)):
        msg = resp.message(wawa_tell_joke())
    #Update
    elif ("update" in msg.lower()):
        country = msg[7:]
        msg = resp.message(covid_api(country))
    #Instructions
    elif ("instructions" in msg.lower() or "help" in msg.lower()):
        msg = resp.message(wawa_tell_instructions())
    #Emergency Number
    elif ("emergency" in msg.lower()):
        country = msg[10:]
        print(country)
        msg = resp.message(wawa_get_emergency(country))
    #Reccomendations
    elif ("who" in msg.lower() or "recommendations" in msg.lower()
          or "world health organisation" in msg.lower()):
        msg = resp.message(wawa_tell_who_recommendations())
    #Symptoms
    elif ('symptoms' in msg.lower() or "unwell" in msg.lower()):
        msg = resp.message(wawa_get_symptoms())
    #Default message
    else:
        msg = resp.message(
            """Sorry I did not catch that. Ask me for *help* to obtain my vocabulary. 

Or *emergency [your country]* if you need it.""")

    return str(resp)
Beispiel #45
0
def bot():
    covid19 = COVID19Py.COVID19(data_source="jhu")
    incoming_msg = request.values.get('Body', '').lower()
    resp = MessagingResponse()
    msg = resp.message()
    body = '\n' + 'Invalid command, Please try again or type COVID for list of commands'
    if 'covid' in incoming_msg:
        body = '\n' + "Welcome to SMSCovid" + '\n' + "Available Commands: " + '\n' + "global" + '\n' + "country rank - <confirmed,deaths>" + '\n' + "2 Digit Country Name <IN,US,AU,...>" + '\n' + "<County>,US - <default - 1,county index, all>"
        msg.body(body)
        print(body)
        responded = True
    elif 'global' in incoming_msg:
        location = covid19.getLatest()
        body = '\n' + 'location: ' + 'global' + '\n' + 'confirmed: ' + "{:,}".format(
            location['confirmed']) + '\n' + 'deaths: ' + "{:,}".format(
            location['deaths']) + '\n' + 'recovered: ' + "{:,}".format(location['recovered'])
        msg.body(body)
        responded = True
    elif 'country rank - confirmed' in incoming_msg:
        location = covid19.getLocations(rank_by='confirmed')
        countryarr = []
        for i in range(10):
            countryarr.append(location[i])
        body = '\n' + 'Top Countries Leading by Confirmed Cases:' + '\n'
        for j in range(10):
            body += countryarr[j]['country'] + ' ' + countryarr[j]['country_code'] + '\n'
        msg.body(body)
        responded = True
    elif 'country rank - deaths' in incoming_msg:
        location = covid19.getLocations(rank_by='deaths')
        countryarr = []
        for i in range(10):
            countryarr.append(location[i])
        body = '\n' + 'Top Countries Leading by Deaths:' + '\n'
        for j in range(10):
            body += countryarr[j]['country'] + ' ' + countryarr[j]['country_code'] + '\n'
        msg.body(body)
        responded = True
    elif 'us' in incoming_msg:
        if ',' in incoming_msg:
            county = incoming_msg.split(', ')
            newcounty = county[0].replace(' county', '')
            covid191 = COVID19Py.COVID19(data_source="csbs")
            location = covid191.getLocations()
            indexcounty = []
            indexanswer = []
            # print(county)
            # print(newcounty)
            for index in range(3006):
                # print("Current county: " + location[index]['county'] + "County inputted: " + newcounty)
                if (location[index]['county'].lower() == newcounty):
                    # print("found it")
                    # print(index)
                    indexcounty.append(index)
            number = [int(i) for i in incoming_msg.split() if i.isdigit()]
            if (len(indexcounty) == 0):
                body = '\n' + 'Invalid County name, please try again'
                msg.body(body)
                responded = True
            else:
                for index in indexcounty:
                    print(location[index])
                    indexanswer.append('Location: ' + location[index]['county'] + ' County, ' + location[index][
                        'province'] + '\n' + 'Confirmed: ' + "{:,}".format(
                        location[index]['latest']['confirmed']) + '\n' + 'Deaths: ' + "{:,}".format(
                        location[index]['latest']['deaths']) + '\n' + 'recovered: ' + "{:,}".format(
                        location[index]['latest']['recovered']) + '\n')
                if 'all' in incoming_msg:
                    for index in range(len(indexanswer)):
                        if (index == 0):
                            body = '\n' + indexanswer[0]
                        else:
                            body += indexanswer[index]
                    msg.body(body)
                    responded = True
                elif len(number) == 1:
                    if (len(number) < len(indexcounty)):
                        try:
                            body = '\n' + indexanswer[number[0] - 1]
                        except:
                            body = '\n' + 'Index out of range: Please try again'
                        msg.body(body)
                        responded = True
                    else:
                        body = '\n' + 'Index out of range: Please try again'
                        msg.body(body)
                        responded = True
                elif len(number) == 0:
                    body = '\n' + indexanswer[0]
                    msg.body(body)
                    responded = True
                else:
                    body = '\n' + 'Invalid format: Please try again'
                    msg.body(body)
                    responded = True
        else:
            try:
                location = covid19.getLocationByCountryCode(incoming_msg, timelines=True)
                print(location[0])
                body = '\n' + 'location: ' + location[0]['country'] + '\n' + 'country population: ' + "{:,}".format(
                    location[0]['country_population']) + '\n' 'confirmed: ' + "{:,}".format(
                    location[0]['latest']['confirmed']) + '\n' + 'deaths: ' + "{:,}".format(
                    location[0]['latest']['deaths']) + '\n' + 'recovered: ' + "{:,}".format(
                    location[0]['latest']['recovered'])
            except:
                body = '\n' + 'Invalid command format: Please try again'
            msg.body(body)
            responded = True
    elif (len(incoming_msg) == 2):
        try:
            location = covid19.getLocationByCountryCode(incoming_msg, timelines=True)
            print(location[0])
            body = '\n' + 'location: ' + location[0]['country'] + '\n' + 'country population: ' + "{:,}".format(
                location[0]['country_population']) + '\n' 'confirmed: ' + "{:,}".format(
                location[0]['latest']['confirmed']) + '\n' + 'deaths: ' + "{:,}".format(
                location[0]['latest']['deaths']) + '\n' + 'recovered: ' + "{:,}".format(
                location[0]['latest']['recovered'])
        except:
            body = '\n' + 'Invalid country name: Please try again'
        msg.body(body)
        responded = True
    else:
        msg.body(body)
        responded = True
    return str(resp)
def sms_twiml(question):
    response = MessagingResponse()
    response.message(question.content)
    response.message(SMS_INSTRUCTIONS[question.kind])
    return str(response)
Beispiel #47
0
def tw_handle_incoming(sms_message):
    """handle incoming sms messages"""
    #get and format the phone number from which msg was received
    phone = sms_message["From"][2:]

    print sms_message
    #phone numbers are now stored as 9char strings, dots and dashes stripped
    #phone_number = '-'.join([phone[:3], phone[3:6], phone[6:]])

    #get and format the message received
    received_message = sms_message["Body"]

    #set up the response
    resp = MessagingResponse()

    #initialize some variables
    remaining_words = []
    possible_names = set()
    log_minutes = False
    minutes = None
    first_name = None

    #look for Log or log, a string of digits and all other words may be names
    for word in received_message.split():
        if word == "log" or word == "Log" or word == "LOG":
            log_minutes = True
        elif word.isdigit() and minutes is None:
            minutes = word
        else:
            remaining_words.append(word)
            possible_names.add(word.lower())

    #Find the user associated with this phone number
    incoming_coach = match_coach_by_phone(phone)

    #if the phone number does not match our db
    if incoming_coach is None:
        resp.message("The Reading Coach: Your phone number does not match our database.")
        return str(resp)

    #if the string "log" is not in the body of the message
    if not log_minutes:
        resp.message("The Reading Coach: not a proper log command. Try again? Example: log 10 {}".format(incoming_coach.readers[0].first_name))
        return str(resp)

    for reader in incoming_coach.readers:
        #check to see if the name occurs in the possible_names set
        if reader.first_name.lower() in possible_names:
            #if so, set first_name and remove that value from the remaining words list
            first_name = reader.first_name
            for single_word in remaining_words:
                if single_word.lower() == first_name.lower():
                    remaining_words.remove(single_word)
            reader_id = reader.reader_id

    #do we have a reader?
    if not first_name:
        resp.message("The Reading Coach: Reader's name not found. Try again? Example: log 10 {}".format(incoming_coach.readers[0].first_name))
        return str(resp)

    #do we have some digit data to assign to minutes?
    if not minutes:
        resp.message("The Reading Coach: number of minutes not found. Try again? Example: log 10 {}".format(incoming_coach.readers[0].first_name))
        return str(resp)

    #we need a date and time
    date = None
    title = ' '.join(remaining_words)

    #Here's where we add log to the database
    add_logentry_to_db(reader_id, minutes, title, date)

    #All elements found, success message
    resp.message("The Reading Coach: You have successfully logged {} min for {}".format(minutes, first_name))
    return str(resp)
Beispiel #48
0
def sms():

    message_body = request.form['Body'].lower()
    resp = MessagingResponse()
    reply_message = Message()

    registered = session.get("registered", False)
    zip_c = session.get("zip_c", "30322")

    if registered:
        loc = Location(zip_c)
        wu = WU(wu_key, loc)

        if "zipchange" in message_body.lower():
            nums = [int(i) for i in message_body.split() if i.isdigit()]
            if len(nums):
                zip_code = str(nums[0])
                try:
                    temp_loc = Location(zip_code)
                    session["zip_c"] = zip_code
                    reply_text = "Your zip code has been changed to {} - {}, {}.".format(
                        zip_code, temp_loc.city, temp_loc.state)
                except KeyError:
                    reply_text = "The zip code provided was not valid."
            else:
                reply_text = "The correct syntax for this command is zipchange (zip code here)."
        else:
            if len(message_body.split()) == 1:
                if "commands" in message_body:
                    reply_text = (
                        "Available commands include:\n\n"
                        "alerts - See a list of weather alerts for the set area.\n\n"
                        "conditions - See current weather conditions for the set area.\n\n"
                        "radar - View a live weather radar image for the set area. This command has a delay.\n\n"
                        "zipchange - Change the zip code of the selected area.\n\n"
                        "details - View details about this service.\n\n"
                        "credit - View information about Weather Underground, the weather data provider."
                    )
                elif "alerts" in message_body:
                    try:
                        reply_text = wu.get_alerts()
                    except RequestException:
                        reply_text = "Weather alerts could not be found at this time, please try again later."
                elif "conditions" in message_body:
                    try:
                        reply_text = wu.get_conditions()
                    except RequestException:
                        reply_text = "The weather conditions could not be found at this time, please try again later."
                elif "radar" in message_body:
                    try:
                        file_name = wu.get_animation()
                        uploader.upload("Images/" + file_name + ".gif",
                                        public_id=file_name)
                        c_url = cloudinary.utils.cloudinary_url(file_name)[0]
                        reply_message.media(c_url)
                        reply_text = "{}, {} Radar".format(loc.city, loc.state)
                    except HTTPError:
                        reply_text = "The radar imagery could not be found at this time, please try again later."
                elif "details" in message_body:
                    reply_text = (
                        "This service was created by Josh McFarlin in Python. "
                        "This service is a proof of concept, and is not intended for lifesaving uses. "
                        "Messaging and data rates may apply.\n\nhttp://JoshMcFarlin.me/"
                    )
                elif "credit" in message_body:
                    reply_text = "All weather data is provided by Weather Underground."
                    reply_message.media(
                        "https://icons.wxug.com/logos/PNG/wundergroundLogo_4c_rev.png"
                    )
                else:
                    reply_text = 'Please reply with a valid command, type "commands" to view a list of commands.'
            else:
                reply_text = "Please only use one command at a time."
    else:
        if message_body.isdigit():
            session["registered"] = True
            session["zip_c"] = message_body
            reply_text = 'Thanks for registering! Type "commands" to view a list of commands.'
        else:
            reply_text = "Welcome. In order to subscribe to weather updates, please reply with a zip code."

    reply_message.body(reply_text)
    resp.append(reply_message)
    return str(resp)
Beispiel #49
0
def sms_search_main_text_reply(title, hint):
    info = be.search_main_text(title, hint)
    response = compile_results(title, hint, info, False)
    resp = MessagingResponse()
    resp.message(str(response))
    return str(resp)
Beispiel #50
0
def parse_data_into_dict():
    #make dictionary: key = stat, value=column of Excel spreadsheet (column B is avg minutes played)
    stat_dict = {
        "age": "B",
        "gp": "C",
        "w": "D",
        "l": "E",
        "min": "F",
        "pts": "G",
        "fgm": "H",
        "fga": "I",
        "fg%": "J",
        "3pm": "K",
        "3pa": "L",
        "ftm": "M",
        "fta": "N",
        "ft%": "O",
        "oreb": "P",
        "dreb": "Q",
        "reb": "R",
        "ast": "S",
        "tov": "T",
        "stl": "U",
        "blk": "V",
        "pf": "W",
        "dd2": "X",
        "td3": "Y"
    }
    excel_file = 'nba_stats_one_sheet.xlsx'
    typo_msg = "send first and last name(s), stat, or check for typos!"
    stat_msg = "Type 1-2 players' names(first + last, players separated by a space), then a stat(GP,W,L,MIN,PTS,FG%,3P%,FT%,REB,AST,STL,BLK)"
    msg = request.form['Body'].lower()
    list_of_stats = []
    list_of_players = []
    wb = load_workbook(excel_file)
    reg_season = True  # set boolean, will change depending on user input
    if msg == "play":
        ret = MessagingResponse().message(
            "type \'a\' for regular season or \'b\' for playoffs")
    elif msg == 'a' or msg == 'b':
        ret = MessagingResponse().message(statmsg)
    else:
        if reg_season:  # playoffs or regular season, take your pick!!
            ws = wb[wb.sheetnames[0]]  #first sheet
        else:  #playoffs (texted 'b'), second sheet
            ws = wb[wb.sheetnames[1]]
        player_and_stat = msg.split()  #split
        if len(player_and_stat) == 3:  # 1 player
            full_name = player_and_stat[0] + " " + player_and_stat[1]
            stat = player_and_stat[2]
            for row in range(1, ws.max_row + 1):  #need +1 to get last row!
                for col in "A":  #A gets players for texted season
                    cell_name = "{}{}".format(col, row)
                    list_of_players.append(ws[cell_name].value.lower())
                for col in stat_dict[stat]:  #pts
                    cell_name = "{}{}".format(col, row)
                    list_of_stats.append(ws[cell_name].value)
            player_stat_map = dict(zip(list_of_players, list_of_stats))
            if full_name in player_stat_map.keys():
                ret = MessagingResponse().message(
                    full_name + " averaged " + str(stat) + " of: " +
                    str(player_stat_map[full_name]))
            else:
                ret = MessagingResponse().message(typomsg)
        elif len(player_and_stat) == 5:  #2 players
            player1 = player_and_stat[0] + " " + player_and_stat[1]
            player2 = player_and_stat[2] + " " + player_and_stat[3]
            stat = player_and_stat[4]
            for row in range(1, ws.max_row + 1):  #need +1 to get last row!
                for col in "A":  #A gets players for texted season
                    cell_name = "{}{}".format(col, row)
                    list_of_players.append(ws[cell_name].value.lower())
                for col in stat_dict[
                        stat]:  # gets column of whatever statistic
                    cell_name = "{}{}".format(col, row)
                    list_of_stats.append(ws[cell_name].value)
            player_stat_map = dict(zip(list_of_players, list_of_stats))
            if player1 in player_stat_map.keys(
            ) and player2 in player_stat_map.keys():
                if player_stat_map[player1] > player_stat_map[player2]:
                    ret = MessagingResponse().message(
                        player1 + " 's total regular season " + stat +
                        " were " + str(player_stat_map[player1]) +
                        ", higher than " + player2 + "\'s " +
                        str(player_stat_map[player2]))
                else:
                    ret = MessagingResponse().message(
                        player2 + " 's total regular season " + stat + " " +
                        str(player_stat_map[player2]) + ", higher than " +
                        player1 + "\'s " + str(player_stat_map[player1]))
            else:  #check
                ret = MessagingResponse().message(typomsg)
        else:  #idk how many players
            ret = MessagingResponse().message(typomsg)
    return str(ret)
Beispiel #51
0
def sms_response(request):
    resp = MessagingResponse()
    resp.message('Check this out')

    return HttpResponse(str(resp))
Beispiel #52
0
def sms_search_infobox_reply(title, query):
    resp = MessagingResponse()
    info = be.check_sidebar(title, query)
    response = compile_results(title, query, info, True)
    resp.message(str(response))
    return str(resp)
from twilio.twiml.messaging_response import Body, Media, Message, MessagingResponse

response = MessagingResponse()
message = Message()
message.body('Hello Jenny')
message.media('https://demo.twilio.com/owl.png')
response.append(message)

print(response)
Beispiel #54
0
def sms_get_query_reply():
    resp = MessagingResponse()
    resp.message(str(const.QUERY_MESSAGE))
    return str(resp)
Beispiel #55
0
def sms_goodbye_message():
    resp = MessagingResponse()
    resp.message(str(const.GOODBYE_MESSAGE))
    return str(resp)
Beispiel #56
0
def send_sms_response():
    """
    Responds to an incoming message with a custom SMS response from the trained
    intents within DialogFlow
    ::returns sms response as a string
    """
    INBOUND_MESSAGE = request.form.get('Body').lower().strip()

    resp = MessagingResponse()
    menu_resp = responses.sms_responses()
    logger.info(INBOUND_MESSAGE)

    try:
        if INBOUND_MESSAGE:
            dialogflow_response = \
            smart_message.detect_intent_response(INBOUND_MESSAGE)
            resp.message(dialogflow_response)
            logger.info(f'{resp}')
            return str(resp)
    except:
        """
        If the DialogFlow API times out or fails to return a valid response,
        the code within the except block will run to maintain response 
        continuity.
        """
        # Save the new counter value in the session
        cookie = session['counter'] = set_session_response()

        # Use the body of the user's text message to create a new TextBlob object.
        text_blob = TextBlob(INBOUND_MESSAGE)

        # Get sentiment of the user's statement.
        # >>> sentiment = text_blob.sentiment
        # >>> sentiment.polarity
        # 0.0
        sentiment = text_blob.sentiment

        if ('who' in INBOUND_MESSAGE) and ('advisor' in INBOUND_MESSAGE):
            resp.message(menu_resp['who_is_advisor'])
            resp.message(menu_resp['major'])
            logger.info(f'{resp}')
            return str(resp)
        if INBOUND_MESSAGE != None:
            if find_isss_advisor() == 'Nina':
                resp.message(menu_resp['nina'])
                return str(resp)
            elif find_isss_advisor() == 'Nathan':
                resp.message(menu_resp['nathan'])
                return str(resp)
            elif find_isss_advisor() == 'Marcella':
                resp.message(menu_resp['marcella'])
                return str(resp)
            elif find_isss_advisor() is 'Cynthia':
                resp.message(menu_resp['cynthia'])
                return str(resp)
        if ('appointment' in INBOUND_MESSAGE) or ('advisor'
                                                  in INBOUND_MESSAGE):
            resp.message(menu_resp['appt'])
            logger.info(f'{resp}')
            return str(resp)
        elif ('how' in INBOUND_MESSAGE) \
            and ('opt' not in INBOUND_MESSAGE) \
            and ('workshop' not in INBOUND_MESSAGE) \
            and ('leave' not in INBOUND_MESSAGE) \
            and ('unit' not in INBOUND_MESSAGE) \
            and ('transfer' not in INBOUND_MESSAGE) \
            and ('absence' not in INBOUND_MESSAGE) \
            and ('apply' not in INBOUND_MESSAGE) \
            and ('itin' not in INBOUND_MESSAGE) \
            and ('taxes' not in INBOUND_MESSAGE) \
            and ('extension' not in INBOUND_MESSAGE) \
            and ('internship' not in INBOUND_MESSAGE) \
            and ('social' not in INBOUND_MESSAGE) \
            and ('class' not in INBOUND_MESSAGE) \
            and ('travel' not in INBOUND_MESSAGE) \
            and ('ssn' not in INBOUND_MESSAGE) \
            and ('visa' not in INBOUND_MESSAGE) \
            and ('credit' not in INBOUND_MESSAGE) \
            and ('extend' not in INBOUND_MESSAGE) \
            or ('ready' in INBOUND_MESSAGE):
            resp.message(menu_resp['contact_isss'])
            resp.message((menu_resp['processing_time']))
            logger.info(f'{resp}')
            return str(resp)
        elif ('when' in INBOUND_MESSAGE) \
            and ('opt' not in INBOUND_MESSAGE) \
            and ('workshop' not in INBOUND_MESSAGE) \
            and ('leave' not in INBOUND_MESSAGE) \
            and ('transfer' not in INBOUND_MESSAGE) \
            and ('absence' not in INBOUND_MESSAGE) \
            and ('apply' not in INBOUND_MESSAGE) \
            and ('itin' not in INBOUND_MESSAGE) \
            and ('taxes' not in INBOUND_MESSAGE) \
            or ('ready' in INBOUND_MESSAGE):
            resp.message(menu_resp['contact_isss'])
            resp.message((menu_resp['processing_time']))
            logger.info(f'{resp}')
            return str(resp)
        elif 'transfer' in INBOUND_MESSAGE:
            resp.message(menu_resp['transfer'])
            logger.info(f'{resp}')
            return str(resp)
        elif 'call' in INBOUND_MESSAGE:
            resp.message(menu_resp['call'])
            logger.info(f'{resp}')
            return str(resp)
        elif 'email' in INBOUND_MESSAGE:
            resp.message(menu_resp['email'])
            logger.info(f'{resp}')
            return str(resp)
        elif ('workshop' in INBOUND_MESSAGE) and ('opt' in INBOUND_MESSAGE):
            resp.message(menu_resp['workshop'])
            logger.info(f'{resp}')
            return str(resp)
        elif ('workshop' in INBOUND_MESSAGE) and ('tax' in INBOUND_MESSAGE):
            resp.message(menu_resp['workshop'])
            logger.info(f'{resp}')
            return str(resp)
        elif ('workshop' in INBOUND_MESSAGE):
            resp.message(menu_resp['workshop'])
            logger.info(f'{resp}')
            return str(resp)
        elif ('tax' in INBOUND_MESSAGE) or ('taxes' in INBOUND_MESSAGE) \
            or ('itin' in INBOUND_MESSAGE):
            resp.message(menu_resp['taxes'])
            logger.info(f'{resp}')
            return str(resp)
        elif ('visa' in INBOUND_MESSAGE) and ('apply' not in INBOUND_MESSAGE) \
            and ('letter' not in INBOUND_MESSAGE):
            resp.message(menu_resp['visa'])
            logger.info(f'{resp}')
            return str(resp)
        elif ('opt' in INBOUND_MESSAGE) and ('travel' in INBOUND_MESSAGE):
            resp.message(menu_resp['opt_travel'])
            logger.info(f'{resp}')
            return str(resp)
        elif ('travel' in INBOUND_MESSAGE) and ('apply' not in INBOUND_MESSAGE) \
            and ('request' not in INBOUND_MESSAGE):
            resp.message(menu_resp['travel_1'])
            resp.message(menu_resp['travel_2'])
            resp.message(menu_resp['travel_3'])
            logger.info(f'{resp}')
            return str(resp)
        elif ('how' in INBOUND_MESSAGE) and ('credit' in INBOUND_MESSAGE) \
            or ('full time' in INBOUND_MESSAGE) or ('credit' in INBOUND_MESSAGE) \
            or ('unit' in INBOUND_MESSAGE):
            resp.message(menu_resp['full_time'])
            resp.message(menu_resp['full_time_reminder'])
            logger.info(f'{resp}')
            return str(resp)
        elif ('opt' in INBOUND_MESSAGE) and \
            ('how' in INBOUND_MESSAGE) and ('apply' not in INBOUND_MESSAGE):
            resp.message(menu_resp['opt_processing_time'])
            logger.info(f'{resp}')
            return str(resp)
        elif ('opt' in INBOUND_MESSAGE) and \
            ('how' in INBOUND_MESSAGE) and ('apply' in INBOUND_MESSAGE):
            resp.message(menu_resp['how_opt_apply'])
            resp.message(menu_resp['register_workshop'])
            logger.info(f'{resp}')
            return str(resp)
        elif ('when' in INBOUND_MESSAGE) and \
            ('opt' in INBOUND_MESSAGE) and ('apply' in INBOUND_MESSAGE):
            resp.message(menu_resp['opt_apply'])
            logger.info(f'{resp}')
            return str(resp)
        elif ('when' in INBOUND_MESSAGE) and ('opt' in INBOUND_MESSAGE):
            resp.message(menu_resp['opt_processing_time'])
            logger.info(f'{resp}')
            return str(resp)
        elif ('opt' in INBOUND_MESSAGE) and ('apply' not in INBOUND_MESSAGE):
            resp.message(menu_resp['opt'])
            logger.info(f'{resp}')
            return str(resp)
        elif ('cpt' in INBOUND_MESSAGE) and ('apply' not in INBOUND_MESSAGE):
            resp.message(menu_resp['cpt'])
            logger.info(f'{resp}')
            return str(resp)
        elif ('intern' in INBOUND_MESSAGE) or ('work' in INBOUND_MESSAGE) \
            or ('off campus' in INBOUND_MESSAGE) or ('job' in INBOUND_MESSAGE) \
            or ('extern' in INBOUND_MESSAGE) or \
            ('employment' in INBOUND_MESSAGE):
            resp.message(menu_resp['employment'])
            logger.info(f'{resp}')
            return str(resp)
        elif ('ssn' in INBOUND_MESSAGE) or \
            ('social security' in INBOUND_MESSAGE) \
            or ('financial aid' in INBOUND_MESSAGE):
            resp.message(menu_resp['gen_student_life'])
            logger.info(f'{resp}')
            return str(resp)
        elif ('extension' in INBOUND_MESSAGE) or ('extend' in INBOUND_MESSAGE):
            resp.message(menu_resp['p_extension_1'])
            resp.message(menu_resp['p_extension_2'])
            resp.message(menu_resp['p_extension_3'])
            logger.info(f'{resp}')
            return str(resp)
        elif ('rcl' in INBOUND_MESSAGE) and ('apply' not in INBOUND_MESSAGE) \
            or ('reduced' in INBOUND_MESSAGE) \
            or ('reduced course load' in INBOUND_MESSAGE):
            resp.message(menu_resp['rcl'])
            resp.message(menu_resp['rcl_link'])
            resp.message(menu_resp['full_time_reminder'])
            logger.info(f'{resp}')
            return str(resp)
        elif ('leave of absence' in INBOUND_MESSAGE) \
            or ('loa' in INBOUND_MESSAGE) or ('leave' in INBOUND_MESSAGE) \
            or ('withdraw' in INBOUND_MESSAGE):
            resp.message(menu_resp['loa_wd'])
            logger.info(f'{resp}')
            return str(resp)
        elif ('apply' in INBOUND_MESSAGE) or ('travel' in INBOUND_MESSAGE) \
            or ('cpt' in INBOUND_MESSAGE) or ('letter' in INBOUND_MESSAGE) \
            or ('request' in INBOUND_MESSAGE) or ('i20' in INBOUND_MESSAGE) \
            or ('i-20' in INBOUND_MESSAGE) or ('rcl' in INBOUND_MESSAGE) \
            or ('reduced course load' in INBOUND_MESSAGE):
            resp.message(menu_resp['isss_request'])
            resp.message(menu_resp['disclaimer'])
            logger.info(f'{resp}')
            return str(resp)
        elif ('class' in INBOUND_MESSAGE) or ('course' in INBOUND_MESSAGE) \
            or ('drop' in INBOUND_MESSAGE):
            resp.message(menu_resp['academic'])
            resp.message(menu_resp['full_time_reminder'])
            logger.info(f'{resp}')
            return str(resp)
        elif ('hello' in INBOUND_MESSAGE) or ('hey' in INBOUND_MESSAGE) \
            or ('hi' in INBOUND_MESSAGE):
            resp.message(menu_resp['menu'])
            logger.info(f'{resp}')
            return str(resp)
        elif 'isss' in INBOUND_MESSAGE:
            resp.message(menu_resp['isss'])
            logger.info(f'{resp}')
            return str(resp)
        elif 'website' in INBOUND_MESSAGE:
            resp.message(menu_resp['website'])
            logger.info(f'{resp}')
            return str(resp)
        elif 'menu' in INBOUND_MESSAGE:
            resp.message(menu_resp['menu'])
            logger.info(f'{resp}')
            return str(resp)

        # If the polarity of the sentiment is greater than zero, the statement is
        # positive.  Highest positivity is 1.0
        elif sentiment.polarity > 0:
            resp.message(menu_resp['sentiment_resp1'])
            return str(resp)

        # If the polarity of the sentiment is less than zero, the statement is
        # negative.  Lowest negativity is -1.0.
        elif sentiment.polarity < 0:
            resp.message(menu_resp['sentiment_resp2'])
            resp.message(menu_resp['menu'])
            logger.info(f'{resp}')
            return str(resp)

        # If the polarity is 0.0, TextBlob was unable to determine the sentiment
        # of the statement.  In this case, we'll return a neutral response in turn.
        elif INBOUND_MESSAGE != None and cookie <= 1:
            cookie += 1
            resp.message(menu_resp['sentiment_resp3'])
            return str(resp)
        else:
            resp.message((menu_resp['renew_session']))
            session['counter'] = 0
            return str(resp)
Beispiel #57
0
def bot():
    # add webhook logic here and return a response
    incoming_msg = request.values.get('Body', '').lower()
    resp = MessagingResponse()
    msg = resp.message()
    responded = False

    response1 = """
*Hi! I am the Quarantine Bot* ๐Ÿ‘‹
Let's be friends ๐Ÿ˜‰
You can give me the following commands:
~  *'quote'*: ```Hear an inspirational quote to start your day!```๐Ÿš€

~  *'cat'*:   Who doesn't love cat pictures? ๐Ÿˆ

~  *'dog'*:   Don't worry, we have dogs too! dog๐Ÿ•

~  *'meme'*:  The top memes of today, fresh from r/memes. ๐Ÿ‘ป

~  *'news'*:  Latest news from around the world. ๐Ÿ“ฐ

~  *'recipe'*:  Searches Allrecipes.com for the best recommended recipes. ๐Ÿด

~  *'recipe <query>'*:  Searches Allrecipes.com for the best recipes based on your query. ๐Ÿง™

~  *'get recipe'*:  Run this after the 'recipe' or 'recipe <query>' command to fetch your recipes! 

~  *'statistics <country>'*:  Show the latest COVID19 statistics for each country.

~  *'statistics <prefix>'*:  Show the latest COVID19 statistics for all countries starting with that prefix. 

~  *'developer'*:   Know the developer.
"""

    if re.search('h[ae]llo', incoming_msg
                 ):  # will find and match either hello or hallo in a message
        msg.body(response1)
        responded = True

    elif re.search('quote',
                   incoming_msg):  # will find and match quote in a sentence
        # return a quote
        r = requests.get('https://api.quotable.io/random')
        if r.status_code == 200:
            data = r.json()
            quote = f'{data["content"]} ({data["author"]})'
        else:
            quote = 'I could not retrieve a quote at this time, sorry.'
        msg.body(quote)
        responded = True

    elif re.search('cat|pic', incoming_msg):  # will find and match cat or pic
        # return a cat pic
        msg.media('https://cataas.com/cat')
        responded = True

    elif re.search('dog', incoming_msg):
        # return a dog pic
        r = requests.get('https://dog.ceo/api/breeds/image/random')
        data = r.json()
        msg.media(data['message'])
        responded = True

    elif re.search('recipe', incoming_msg):

        # search for recipe based on user input (if empty, return featured recipes)
        search_text = incoming_msg.replace('recipe', '')
        search_text = search_text.strip()

        data = json.dumps({'searchText': search_text})

        result = ''
        # updates the Apify task input with user's search query
        r = requests.put(
            'https://api.apify.com/v2/actor-tasks/o7PTf4BDcHhQbG7a2/input?token=qTt3H59g5qoWzesLWXeBKhsXu&ui=1',
            data=data,
            headers={"content-type": "application/json"})
        if r.status_code != 200:
            result = 'Sorry, I cannot search for recipes at this time.'

        # runs task to scrape Allrecipes for the top 5 search results
        r = requests.post(
            'https://api.apify.com/v2/actor-tasks/o7PTf4BDcHhQbG7a2/runs?token=qTt3H59g5qoWzesLWXeBKhsXu&ui=1'
        )
        if r.status_code != 201:
            result = 'Sorry, I cannot search Allrecipes.com at this time.'

        if not result:
            result = "I am searching Allrecipes.com for the best {} recipes.".format(
                search_text)

            result += "\nPlease wait for a few moments before typing 'get recipe' to get your recipes!"
        msg.body(result)
        responded = True

    elif incoming_msg == 'get recipe':
        # get the last run details
        r = requests.get(
            'https://api.apify.com/v2/actor-tasks/o7PTf4BDcHhQbG7a2/runs/last?token=qTt3H59g5qoWzesLWXeBKhsXu'
        )

        if r.status_code == 200:
            data = r.json()

            # check if last run has succeeded or is still running
            if data['data']['status'] == "RUNNING":
                result = 'Sorry, your previous query is still running.'
                result += "\nPlease wait for a few moments before typing 'get recipe' to get your recipes!"

            elif data['data']['status'] == "SUCCEEDED":

                # get the last run dataset items
                r = requests.get(
                    'https://api.apify.com/v2/actor-tasks/o7PTf4BDcHhQbG7a2/runs/last/dataset/items?token=qTt3H59g5qoWzesLWXeBKhsXu'
                )
                data = r.json()

                if data:
                    result = ''

                    for recipe_data in data:
                        url = recipe_data['url']
                        name = recipe_data['name']
                        rating = recipe_data['rating']
                        rating_count = recipe_data['ratingcount']
                        prep = recipe_data['prep']
                        cook = recipe_data['cook']
                        ready_in = recipe_data['ready in']
                        calories = recipe_data['calories']

                        result += """
*{}*
_{} calories_
Rating: {:.2f} ({} ratings)
Prep: {}
Cook: {}
Ready in: {}
Recipe: {}
""".format(name, calories, float(rating), rating_count, prep, cook, ready_in,
                        url)

                else:
                    result = 'Sorry, I could not find any results for {}'.format(
                        search_text)

            else:
                result = 'Sorry, your previous search query has failed. Please try searching again.'

        else:
            result = 'I cannot retrieve recipes at this time. Sorry!'

        msg.body(result)
        responded = True

    elif re.search(
            'news*',
            incoming_msg):  # will search and match new or news or newsssss
        r = requests.get(
            'https://newsapi.org/v2/top-headlines?sources=bbc-news,the-washington-post,the-wall-street-journal,cnn,fox-news,cnbc,abc-news,business-insider-uk,google-news-uk,independent&apiKey=3ff5909978da49b68997fd2a1e21fae8'
        )

        if r.status_code == 200:
            data = r.json()
            articles = data['articles'][:5]
            result = ''

            for article in articles:
                title = article['title']
                url = article['url']
                if 'Z' in article['publishedAt']:
                    published_at = datetime.datetime.strptime(
                        article['publishedAt'][:19], "%Y-%m-%dT%H:%M:%S")
                else:
                    published_at = datetime.datetime.strptime(
                        article['publishedAt'], "%Y-%m-%dT%H:%M:%S%z")
                result += """
*{}*
Read more: {}
_Published at {:02}/{:02}/{:02} {:02}:{:02}:{:02} UTC_
""".format(title, url, published_at.day, published_at.month, published_at.year,
                published_at.hour, published_at.minute, published_at.second)

        else:
            result = 'I cannot fetch news at this time. Sorry!'

        msg.body(result)
        responded = True

    elif incoming_msg.startswith('statistics'):
        # runs task to aggregate data from Apify Covid-19 public actors
        requests.post(
            'https://api.apify.com/v2/actor-tasks/5MjRnMQJNMQ8TybLD/run-sync?token=qTt3H59g5qoWzesLWXeBKhsXu&ui=1'
        )

        # get the last run dataset items
        r = requests.get(
            'https://api.apify.com/v2/actor-tasks/5MjRnMQJNMQ8TybLD/runs/last/dataset/items?token=qTt3H59g5qoWzesLWXeBKhsXu'
        )

        if r.status_code == 200:
            data = r.json()

            country = incoming_msg.replace('statistics', '')
            country = country.strip()
            country_data = list(
                filter(lambda x: x['country'].lower().startswith(country),
                       data))

            if country_data:
                result = ''

                for i in range(len(country_data)):
                    data_dict = country_data[i]
                    last_updated = datetime.datetime.strptime(
                        data_dict.get('lastUpdatedApify', None),
                        "%Y-%m-%dT%H:%M:%S.%fZ")

                    result += """
*Statistics for country {}*
Infected: {}
Tested: {}
Recovered: {}
Deceased: {}
Last updated: {:02}/{:02}/{:02} {:02}:{:02}:{:03} UTC
""".format(data_dict['country'], data_dict.get('infected', 'NA'),
                    data_dict.get('tested', 'NA'), data_dict.get('recovered', 'NA'),
                    data_dict.get('deceased', 'NA'), last_updated.day,
                    last_updated.month, last_updated.year, last_updated.hour,
                    last_updated.minute, last_updated.second)
            else:
                result = "Country not found. Sorry!"

        else:
            result = "I cannot retrieve statistics at this time. Sorry!"

        msg.body(result)
        responded = True

    elif re.search('memes*', incoming_msg):
        r = requests.get(
            'https://www.reddit.com/r/memes/top.json?limit=20?t=day',
            headers={'User-agent': 'your bot 0.1'})

        if r.status_code == 200:
            data = r.json()
            memes = data['data']['children']
            random_meme = random.choice(memes)
            meme_data = random_meme['data']
            title = meme_data['title']
            image = meme_data['url']

            msg.body(title)
            msg.media(image)

        else:
            msg.body('Sorry, I cannot retrieve memes at this time.')

        responded = True

        if not responded:
            msg.body(
                "Sorry, I don't understand. Send 'hello' for a list of commands."
            )

    if re.search('developer', incoming_msg):
        mess = """
        Guess its who!!๐Ÿ˜Ž
        Its your buddy Alex.๐Ÿฅณ
        
         More updates are coming soon..
         
         Report any error @ 0711521508
         
         Thank you very much!!๐Ÿ’–
        """
        msg.body(mess)
        responded = True

    if not responded:
        msg.body(response1)
    return str(resp)
Beispiel #58
0
def sms_reply():
    body = request.values.get('Body', '-')
    resp = MessagingResponse()
    resp.message(f'The Knative copy cat says: {body}')
    return str(resp)
Beispiel #59
0
def incoming_sms():
    """Send a dynamic reply to an incoming text message"""
    # Get the message the user sent our Twilio number
    body = request.values.get('Body', None)

    # Start our TwiML response
    resp = MessagingResponse()

    phone_number = request.values.get('From')

    if phone_number in user_info:
        if user_info[phone_number][-1] == 0:
            #check the validity of the state
            user_info[phone_number][0] = body
            resp.message(
                'How old are you? Selection from the age groups below:')
            resp.message('A. 3 to 17')
            resp.message('B. 18 to 30')
            resp.message('C. 31 to 64')
            resp.message('D. 65 and older')
            user_info[phone_number][-1] += 1
        elif user_info[phone_number][-1] == 1:
            #check the validity of the age
            user_info[phone_number][1] = body
            resp.message('What profession are you?')
            resp.message('Are you in Group A? (Yes / No)')
            resp.message(
                'Ambulatory health care \n Assisted living \n Developmental disability facility \n Fire protection services \n Home healthcare services Hospital '
                'worker \n Nursing/residential care \n Outpatient care \n Pharmacy/drug store \n Physician/health practitioner \n Police'
            )
            user_info[phone_number][-1] += 1
        elif user_info[phone_number][-1] == 2:
            #check the validity of the profession A
            user_info[phone_number][2] = body
            resp.message('Are you in Group B? (Yes / No)')
            resp.message(
                'Community relief services \n Cosmetic/beauty supply store \n Day care \n Dentistry \n Food/drink production or store \n Gas station \n Health/personal care store \n Homeless shelter \n Medical/diagnostic lab \n '
                'Optical goods store \n Medicine production \n Postal service \n Prison/Jail \n School teaching \n Transportation \n Warehousing/storage'
            )
            user_info[phone_number][-1] += 1
        elif user_info[phone_number][-1] == 3:
            #check the validity of the profession B
            user_info[phone_number][3] = body
            resp.message('Are you in Group C? (Yes / No)')
            resp.message(
                'Animal production/fishing \n Bars/Restaurants \n Clothing/accessories store \n Construction \n Credit intermediation \n Crop production \n '
                'Hardware \n Mining \n Oil/gas extraction \n Specialty trade contractors \n Transport equipment production \n Utilities \n Waste management'
            )

            user_info[phone_number][-1] += 1
        elif user_info[phone_number][-1] == 4:
            #check the validity of profession C
            user_info[phone_number][4] = body
            resp.message('What is your living situation?')
            resp.message(
                'A. Nursing home/residential care \n B. Home with more people than rooms \n C. Homeless shelter '
                '\n D. Prison/Jail \n E. Group home \n F. Rehab center \n G. None of these'
            )

            user_info[phone_number][-1] += 1
        elif user_info[phone_number][-1] == 5:
            #check the validity of the living condition
            user_info[phone_number][5] = body
            resp.message('Do you have any health conditions? (0 - 5)')
            resp.message(
                'A. Obesity \n B. COPD (Chronic obstructive pulmonary disease) \n C. Diabetes \n D. Heart disease \n E. Chronic kidney disease \n F. None of these'
            )
            user_info[phone_number][-1] += 1

        elif user_info[phone_number][-1] == 6:
            #check the validity of the health condition
            user_info[phone_number][6] = body
            resp.message('This is the end of the message.')
    else:

        resp.message(
            'Hi! Welcome to Vaccine Info Estimator, we are going to ask you a series of questions to determine '
            'your estimated date to receive the vaccine. What state are you in?'
        )
        current_counter = 0
        #[states, ages, workA, workB, workC, living, health]
        user_info[phone_number] = [
            None, None, None, None, None, None, None, current_counter
        ]


#----------------------------------------------------------------------------

    return str(resp)
Beispiel #60
0
def sms_reply():
    """Respond to incoming calls with a simple text message."""
    # Fetch the message
    msg = request.form.get('Body').lower()
    resp = MessagingResponse()

    if "hi" in msg or "hello" in msg:
        resp.message("Greetings Human! I am a weather bot!")
        resp.message(
            "To get the weather of the desired city type in \"weather in cityname\""
        )
        resp.message(
            "To get the weather in farenheit type in \"farenheit in cityname\""
        )

    if "weather" in msg:
        string1 = msg
        cty = string1.split("in ", 1)[1]
        resp.message("it's {} Celcius and {} in {}".format(
            getweather(cty), getdesc(cty), cty))

    if "farenheit" in msg:
        string1 = msg
        cty = string1.split("in ", 1)[1]
        number = getweather(cty)
        number = int(number)
        infarenheit = (number * 9 / 5) + 32
        resp.message("it's " + str(infarenheit) + " Farenheit and " +
                     getdesc(cty) + " in " + cty)

    if "bye" in msg:
        resp.message("Thank you for using the weather chatbot!")
        resp.message("Have a nice day!")

    return str(resp)