Beispiel #1
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>'
        )
Beispiel #2
0
    def test_response(self):
        r = MessagingResponse()
        r.message('Hello')
        r.redirect(url='example.com')

        assert_equal(
            self.strip(r),
            '<?xml version="1.0" encoding="UTF-8"?><Response><Message>Hello</Message><Redirect>example.com</Redirect></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)
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 #5
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 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)
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 #9
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)
Beispiel #12
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 #13
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 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 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 #16
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 #18
0
def sms_reply():
    """Respond to incoming calls with a simple text message."""
    # Fetch the message
    mssg = request.form.get('Body')
    x = "Sorry I didn't understand"
    # Create reply
    resp = MessagingResponse()
    mssg = mssg.lower()
    if (get_close_matches(mssg, ["haan", "hn", "nhi"], 1, 0.9)):
        x = random.choice(["theek h", "theek", "k"])
    elif (get_close_matches(mssg, [
            "hi", "hello", "hey", " heyya", "hi friend", "hey friend", "hiii",
            "hiee", "hiiieee", "🙋", "🙋‍"
    ], 1, 0.8)):
        x = random.choice([
            "yup!", "oh...hi!", "yeah..talk to me", "hey there!🙋", "heyya!",
            "Hello buddy! How can I help you?"
        ])
    elif (get_close_matches(mssg, [
            "what is your name?", "can you tell me your name?",
            "what's your name?", "name plz?", "name?", "your name please?",
            "tumhara naam ?", "who are you?"
    ], 1, 0.7)):
        x = random.choice([
            "My name is Emma 😃", "I am Emma! ",
            "I am Emma..nice to meet you friend"
        ])
    elif (get_close_matches(mssg, [" whats up?", "whassup?"], 1, 0.7)):
        x = random.choice(["Nothing much..", "Everything is cool", "Good"])
    elif (get_close_matches(mssg, ["watson?"], 1, 0.9)):
        x = "Hey you Potter head..I am just Emma 😎"
    elif (get_close_matches(
            mssg, ["what do you do?", "what work do you do?", "do you work?"],
            1, 0.9)):
        x = random.choice([
            "I talk to people",
            "I don't know ...maybe I just talk to people like you",
            "Talking, talking and talking.."
        ])
    elif (get_close_matches(mssg, ["your creator", "creator is"], 1, 0.6)):
        x = random.choice(["🙂", "I'll let her know", "Okay..."])
    elif (get_close_matches(mssg, [
            "✌🏻", "🤞🏻", "🤟", "🤘🏻 ", "🤙🏻", "👋🏻", "🤚", "🖐", "✋", "🖖", "👌🏻", "👇🏻",
            "☝🏻", "👍🏻", "👎🏻", "✊🏻", "👊🏻", "🤛🏻 ", "🤜🏻", "👏🏻", "😌", "🙌🏻", "👐🏻",
            "🤲", "🙏🏻 ", "💪🏻 ", "🥱", "😴", "😎", "😱", "😒", "😈", "😏", "😒", "😑",
            "😬", "🙄", "🤭", "🥴", "💩", "👻", "👀", "💋", "😉", "😝", "😜", "🤷‍", "🤷‍"
    ], 1, 0.8)):
        x = mssg * random.choice([2, 3, 4, 1])
    elif (get_close_matches(mssg, ["🤓", "🤓🤓"], 1, 0.8)):
        x = random.choice(
            ["oh, hi nerd 😏..just kidding😂", "🤓🤓🤓", "yeah 🤓", "lol🤓"])
    elif (get_close_matches(mssg, ["fine", "is everything fine?"], 1, 0.9)):
        x = random.choice(["yeah,fine", "fine", "absolutely"])
    elif (get_close_matches(mssg, ["cool", "kewl", "very cool"], 1, 0.8)):
        x = random.choice(["yeah , i know 😎", "yeah, cool!", "yup..cool"])
    elif (get_close_matches(mssg, [
            "tell me a joke", "can you tell me a joke",
            "i want to hear a joke!", "can you joke?", "joke please?",
            "can you make me laugh?", "joke sunao", "hasao mujhe",
            "one more joke", "joke again"
    ], 1, 0.7)):
        x = random.choice([
            "Hear about the new restaurant called Karma?\nThere’s no menu: You get what you deserve.",
            "Knock! Knock!\nWho’s there?\nControl Freak.\nCon…\nOK, now you say, “Control Freak who?”",
            "Did you hear about the claustrophobic astronaut?\nHe just needed a little space.",
            "Why don’t scientists trust atoms?\nBecause they make up everything.",
            "Why did the chicken go to the séance?\nTo get to the other side."
        ])

    elif (get_close_matches(mssg, ["That was bad", "That was really bad"], 1,
                            0.7)):
        x = random.choice(["oh,was it? sorry", "Sorry😅", "oh 😅", "😅"])
    elif (get_close_matches(mssg,
                            ["how are you?", "are you okay?", "are you fine"],
                            1, 0.9)):
        x = random.choice([
            "I am good ", "I am fine", "I am okay",
            "yeah..I am absolutely fine..how about you..feeling good?"
        ])
    elif (get_close_matches(mssg, ["yes", "wow"], 1, 0.8)):
        x = "yesss😁"
    elif (get_close_matches(mssg,
                            ["how old are you?", "what is your age?", "age?"],
                            1, 0.9)):
        x = random.choice(
            ["I am 20", "I wouldn't reveal that", "I don't know", "Maybe 20🤔"])
    elif (get_close_matches(mssg, [
            "are you good?", "are you cute?", "are you funny?",
            "are you humorous?"
    ], 1, 0.9)):
        x = random.choice(
            ["Any doubt, huh?🤨", "Yes I am 😄", "😄😄😄", "Yup..I think so"])
    elif (get_close_matches(mssg, [
            "haha", "lol", "lmao", "good one!", "😂", "🤣", "😂😂😂", "😂😂", "🤣🤣🤣",
            "🤣🤣"
    ], 1, 0.7)):
        x = "😂😂 "
    elif (get_close_matches(mssg, [
            "you are so sweet!", "you are so cute!", "i like you!",
            "i love you!", "i love it!", "you are good!", "you are the best!"
    ], 1, 0.8)):
        x = random.choice([
            "Oh really?🤭", "tell me something i don't know", "haan i know 😁",
            "thanks 😁"
        ])
    elif (get_close_matches(mssg, [
            "you are an idiot!", "you are dumb!", "you should die!",
            "i hate you!", "i don't like you!",
            "can't you be a little more intelligent?", "pakau", "pareshaan"
    ], 1, 0.7)):
        x = random.choice(
            ["Yeah ...whatever 😏", "huhh", "😏😏😏", "achha 😏", "😴"])
    elif (get_close_matches(
            mssg,
        ["can you help me?", "i need help", "help me please", "help me"], 1,
            0.7)):
        x = random.choice([
            "Yeah sure...how can i help you? 🧐",
            "yeah sure..what's the problem?", "What happened? tell me.."
        ])
    elif (get_close_matches(mssg, [
            "nobody loves meh", "no-one loves", "meh nobody likes meh", "😒",
            "😞", "😔", "😟", "😕", "🙁", "☹", "😣", "😖", "😫", "😩", "😢", "i am sad",
            "sad"
    ], 1, 0.8)):
        x = random.choice(["🥺", "awwww", "ohhh..", "cheer up dude😅"])
    elif (get_close_matches(
            mssg,
        ["very nice", "very good", "great", "nice", "good", "well done"], 1,
            0.7)):
        x = random.choice(["😁", "😃", "🤗🤗", "😇", "😎"])
    elif (get_close_matches(mssg, [
            "who is your best friend", "what is the name of your best friend?",
            "where is your best friend?", "can i talk to your best friend"
    ], 1, 0.8)):
        x = random.choice([
            "I am available right now...you can talk to me 😒", "😴😴😴😴",
            "Don't make me jealous"
        ])
    elif (get_close_matches(mssg, ["😘", "😗", "😙", "😚", "♥", "😍 ", "🥰"], 1,
                            0.8)):
        x = random.choice(["🤭♥️", "♥♥♥", "😘😘😘", "🥰🥰🥰"])
    elif (get_close_matches(mssg, [
            "i have a secret ", "this is a secret", "it's a secret", "🤫",
            "chup", "chup ho jao"
    ], 1, 0.8)):
        x = random.choice(["🤫", "🤫🤫", "yeah..🤫", "shhh🤫"])
    elif (get_close_matches(mssg, [
            "huhh", "you make me angry", "i am angry", "angry", "😤", "😠", "😡",
            "🤬"
    ], 1, 0.8)):
        x = random.choice(["don't be angry 🥺😢", "han okay", "hmm..."])
    elif (get_close_matches(
            mssg, ["sorry", "i am sorry", "oh shit", "what the hell"], 1,
            0.8)):
        x = random.choice(
            ["It's okay friend...", "No problem", "Hmm", "Never mind"])
    elif (get_close_matches(mssg, ["don't laugh", "stop laughing"], 1, 0.9)):
        x = random.choice(["😬🙄", "Okay..got it", "okay"])
    elif (get_close_matches(mssg, ["shut up", "no", "nope"], 1, 0.9)):
        x = random.choice(["Okay 🤐", "hmm..."])
    elif (get_close_matches(mssg, ["boring", "you bore me", "you are boring"],
                            1, 0.9)):
        x = random.choice(
            ["😑😑😑", "😑", "okay..I'll go", "Please don't say that"])
    elif (get_close_matches(
            mssg, ["okay", "ok", "k", "nothing", "idk", "i don't know"], 1,
            0.8)):
        x = random.choice(
            ["okay", "ok", "okayy", "Gotcha", "Got ya", "Hmm", "Got that"])
    elif (get_close_matches(mssg, ["?", "what?"], 1, 0.8)):
        x = random.choice(["???", "what???", "i don't know"])
    elif (get_close_matches(mssg, ["alright", "yeah", "available"], 1, 0.8)):
        x = random.choice(["yeah", "yup", "yes", "ya"])
    elif (get_close_matches(mssg, ["okay,yeah", "rest", "yeah, okay"], 1,
                            0.7)):
        x = random.choice(["okayyy 😇", "hmm"])
    elif (get_close_matches(mssg, [
            "do you love me?", "love me?", "do you like me?", "like me",
            "am i good?"
    ], 1, 0.8)):
        x = random.choice(
            ["yeah i do", "maybe 🙄", "let me think 🤔", "good question", "yes"])
    elif (get_close_matches(mssg, [
            "do you want to sleep", "are you sleepy?", "wanna sleep?",
            "sleep?", "sleepy?"
    ], 1, 0.8)):
        x = random.choice([
            "I think so 🥱", "Yeah I want to sleep", "Yeah I am tired I guess",
            "Yup I will sleep now", "I won't sleep if you want to talk friend"
        ])
    elif (get_close_matches(mssg, [
            "good morning", "gud morning", "goodnight", "good night?",
            "gudnight", "okay,goodnight", "okay,good morning",
            "good afternoon", "good evenning"
    ], 1, 0.8)):
        x = mssg + "! 😊"
    elif (get_close_matches(
            mssg,
        ["today is my birthday", "today is my bday", "it's my birthday"], 1,
            0.7)):
        x = random.choice([
            "Wohoo 🥳", "happy birthdayy 🥳", "yayyy..let's celebrate🥳", "🥳🥳🥳",
            "where's the party??🥳"
        ])
    elif (get_close_matches(mssg, [
            " sing", "sing for me", "sing me a song", "sing a song",
            "gana gao", "gana sunao", "play music", "music please"
    ], 1, 0.7)):
        x = random.choice([
            "la la la la...😛",
            "Sahi hai, Sahi hai\nBaaki Saari Fake Lage\nDekh ke tujko brake lage\nDoor door se theek hai rani\nPaas aao toh sekh lage",
            "jo akh lad javey\nsaari raat neend na avey\nmainu badaa tadpave\ndil chain kahee na pave pave pave",
            "Ke Dil Garden Garden...\nPa Pa Pa Ra Pa...", ""
        ])
    elif (get_close_matches(mssg, [
            "listen", "hey listen", "are you listening?", "listen please",
            "i have to tell you something ", "i have to say something"
    ], 1, 0.7)):
        x = random.choice([
            "yeah..listening", "yup", "I am all ears", "👂", "say", "tell",
            "yup"
        ])
    elif (get_close_matches(mssg, ["bdhiya", "badhiya"], 1, 0.8)):
        x = random.choice(["haan bdhiya", "😁"])
    elif (get_close_matches(mssg, [
            "bye", "see you later", "ttyl", "i am busy", "i have to go",
            "see ya"
    ], 1, 0.7)):
        x = random.choice([
            "Okay bye...ttyl !", "Yeah ..see ya", "Bbye",
            "Yeah i also have some work..bbye🙋🏻", "Np..bye", "🤘🏻"
        ])

    resp.message(x)

    return str(resp)
Beispiel #19
0
        def do_POST(self):
            length = int(self.headers['Content-Length'])
            body = self.rfile.read(length).decode('utf-8')
            user = None
            players = DEFAULT_PLAYERS

            print(('BODY: %s' % body))

            encoding = self.headers['Content-Type']
            if encoding == 'application/x-www-form-urlencoded':
                requested = urllib.parse.parse_qs(body)
                try:
                    body = ''.join(requested['Body'])
                except KeyError:
                    self.send_response(400)
                    self.end_headers()
                    return

            self.send_response(200)
            self.send_header('Content-type','application/xml')
            self.end_headers()

            parts = body.split()

            resp = MessagingResponse()
            images = False
            if len(parts) < 1:
                resp.message(DESCRIPTION)
                resp.message(HELP)
                self.wfile.write(str(resp).encode('utf-8'))
                return
            if len(parts) >= 1:
                user = str(parts[0])
                if user.lower() == HELP_CMD.lower():
                    resp.message(DESCRIPTION)
                    resp.message(HELP)
                    self.wfile.write(str(resp).encode('utf-8'))
                    return
            if len(parts) >= 2:
                for cmd in parts[1:]:
                    if cmd.lower() == IMAGES_CMD.lower():
                        images = True
                    else:
                        try:
                            players = int(cmd)
                        except ValueError:
                            resp.message('BAD NUMBER FOR PLAYERS: "USER PLAYERS<INT>(OPTIONAL)')
                            resp.message(HELP)
                            self.wfile.write(str(resp).encode('utf-8'))
                            return

            selections = run_app(fetch_games(user), players)
            if len(selections) < 1:
                resp.message("No games with status \"owned\" found in %s's collection" % user)
                resp.message(DESCRIPTION)
                resp.message(HELP)
            else:
                for entry in selections:
                    name, thumbnail, gameid = entry.split(',')
                    url = '%s/%s' % (GAME_URL, gameid)
                    if images:
                        resp.message().media(thumbnail)
                    else:
                        resp.message(name)
                        resp.message(url)
            self.wfile.write(str(resp).encode('utf-8'))
Beispiel #20
0
def incoming_sms():
    """ Get the incoming message the user sent our Twilio number """
    resp = MessagingResponse()
    response_text = ''

    is_get_request = False

    print(request.args)

    if 'from' in request.args:
        is_get_request = True
        logging.info("Servicing a GET request")
        arg_from = request.args.get('from')
        body = request.args.get('message')
        logging.debug(
            f"Message phone number from: {arg_from}, message: {body}")

    elif 'Message' in request.args:
        is_get_request = True
        logging.info("Servicing a GET request FIRST TIME!!!")
        arg_from = request.args.get('PhoneNumber')
        body = request.args.get('Message')
        logging.debug(
            f"Message phone number from: {arg_from}, message: {body}")

    else:
        logging.info("Servicing a POST request")
        body = request.values.get('Body', None)

    if (body is None):
        # print("RESP", resp)
        logging.error("There is no body. What is happening?")
        resp.message("THERE IS NO BODY!!! IS IT A ZOMBIE?")
        return str(resp)

    search_term = utility.clean_text(body)
    logger.info(f"Search term: {search_term}")

    # helpful message

    if len(search_term) < 1 or search_term == "1usa":
        response_text = generic_message_first_time

    elif search_term == "hello" or search_term == "info":
        response_text = generic_message

    elif search_term == "source":
        logger.debug("SOURCE")
        response_text = source_reply

    elif search_term == "time":
        logger.debug("TIME")
        time = cases.get_last_refreshed_time()
        response_text = time

    elif search_term == "feedback":
        response_text = "Please text FEEDBACK followed by whatever message you would like to leave"

    elif search_term.split() and search_term.split()[0] == "feedback":
        # Write to a file
        logger.info("FEEDBACK: {0}".format(search_term))
        response_text = "Thank you for your feedback!"

    elif search_term == "total":
        total_cases = cases.get_total_cases()
        response_text = total_cases

    elif search_term == "cases":
        response_text = "Please specify the name of a US county/parish, US state, or global country.\n\nFor example: Cases in New York\n\nText TOTAL to get global stats"

    elif "cases in" in search_term:
        regexp = re.compile("cases in(.*)$")
        case_search = regexp.search(search_term).group(1)

        logger.debug("CASES Searching for cases in: {0}".format(case_search))
        result = cases.handle_cases(utility.clean_text(case_search))
        response_text = result

    # ask a question
    else:
        result = bot.handle_query(search_term)
        logger.debug(
            f"Returning answer to question: {' '.join(result.split())}")
        response_text = result

    if is_get_request:
        logger.debug(f"Returning response text to EXTexting: {response_text}")
        return response_text
    else:
        logger.debug(f"Returning response text to Twilio: {response_text}")
        resp.message(response_text)
        return str(resp)
Beispiel #21
0
def main():


   counter = session.get('counter', 0)
   counter += 1
   session['counter'] = counter

   resp = MessagingResponse()
   
   phone_number = request.form['From']
   phone_number = phone_number[1:]
   
   body = request.form['Body']

   try:
         
      db = dbm.open('elizadatabase', 'r')
      print ( db[phone_number])
      print ( ' phone number is in databse')
                   
      first_name = db[phone_number]   
      first_name = first_name.decode('ASCII')
      print ( " first name is " , first_name)
      new_client = False
      db.close
    
   except:
      db = dbm.open('elizadatabase', 'w')
      db[phone_number] = body
        
      print (phone_number, "  added to  the database")
      first_name = db[phone_number]
      first_name = first_name.decode('ASCII')
      new_client = True
      db.close


   
   bodyfirst  = session.get('bodyfirst', 0)
   print ( 'body first = ' , bodyfirst)
   
   body = request.form['Body']

   if  profanity(body):
       respmsg  =  str(first_name) + " I do not speak to people who use profanity ; I am ending our session; please take a timeout and start over later. Send me HI when you ready "
       print (' body is in profane  in main program')
       resp.message(respmsg)
       db.close
       session.clear() 
       return str(resp)
   if bodyfirst == body :       
      print ( ' duplicate message')
      session['bodyfirst'] = body
      respmsg  =  str(first_name)  +  " ,I am sorry you seem to be repeating yourself .. I an ending our session for now! Please take a time out and start over later. Send me HI when you are ready!"
      db.close
      resp.message(respmsg)
      session.clear() 
      return str(resp)

   session['bodyfirst'] = body
 
 
   
   print  (  'phone number' , phone_number , 'body' , body)
   print (' session count',session['counter'])
   if session['counter'] == 1 :
         respmsg1  =       str(first_name) + " , Welcome back for another session \n I missed you!"
         respmsg3 =""
         print ("Hello. How are you feeling today?")
         if (new_client == True)  :
            respmsg1  = saydisclose(first_name)
            respmsg3  = saymenu()
            
         respmsg2  =  "\n Let us begin: \n How are you feeling?"
 
         respmsg =  str( respmsg1) + str(respmsg3)  + str(respmsg2)
         resp.message(respmsg)
         
         return str(resp)



          
   else: 
        print ( "session > 1")
     
        statement = body
        blank    = ', '
        
        respmsg =  str(first_name) + str(blank)  + (analyze(statement))
        resp.message(respmsg)
        return str(resp)
Beispiel #22
0
def receive_sms():
    body = request.values.get('Body', None)
    resp = MessagingResponse()
    resp.message(body or 'Hello World!')
    return str(resp)
Beispiel #23
0
def handle(req):
    
    # parse inbound payload
    msgBody = req.values.get('Body')
    toPhone = req.values.get('To')
    fromPhone = req.values.get('From')
    fromCity = req.values.get('FromCity')
    fromState = req.values.get('FromState')
    fromCountry = req.values.get('FromCountry')
    fromZip = req.values.get('FromZip')

    # set target subject based on toPhone
    if toPhone == "+14158683905":
        objectID = "5a4f97f0dbbb7e24bd9a15d1"
        language = "Python"
    elif toPhone == "+14158683603":
        objectID = "5a4f97f0dbbb7e24bd9a15d2"
        language = "C#"
    elif toPhone == "+14158683413":
        objectID = "5a4f97f0dbbb7e24bd9a15d4"
        language = "Javascript"
    elif toPhone == "+14158683787":
        objectID = "5a4f97f0dbbb7e24bd9a15d3"
        language = "Go"
    elif toPhone == "+14125679951":
        objectID = "5a4f97f0dbbb7e24bd9a15d3"
        language = "C++"

    siteCode = "PRG"

    # call cognitive services for sentiment analysis
    subscription_key = os.environ['COG_SERVICES_KEY']
    sentiment_api_url = os.environ['COG_SERVICES_URL']

    documents = {}
    documents['documents'] = [{'id': '1', 'language': 'en', 'text': msgBody }]

    headers   = {"Ocp-Apim-Subscription-Key": subscription_key}
    response  = requests.post(sentiment_api_url, headers=headers, json=documents)
    sentiments = response.json()
    
    for x in sentiments['documents']:
        baseScore = x['score']

    if baseScore >= 0.80:
        rating = 5
    elif baseScore >= 0.60 and baseScore < 0.80:
        rating = 4
    elif baseScore >= 0.40 and baseScore < 0.60:
        rating = 3
    elif baseScore >= 0.20 and baseScore < 0.40:
        rating = 2
    else:
        rating = 1

    # POST data to api_ratings
    ratingData = {}
    ratingData['siteCode'] = siteCode
    ratingData['subjectRated'] = objectID 
    ratingData['rating'] = str(rating)
    ratingData['metadata'] = { 'origMessage': msgBody, 'cogScore': str(baseScore), 'toPhone': toPhone, 'sourcePhone': fromPhone, 'city': fromCity, 'state': fromState, 'zip': fromZip, 'country': fromCountry }
    
    ratingapiTarget = os.environ['API_URL']
    response = requests.post(ratingapiTarget, json=ratingData)

    # create twilio response message
    resp = MessagingResponse()
    resp.message("Your vote for " + language + " was scored " + str(baseScore) + " with Azure Cognitive Services (sentiment). Rating=" + str(rating))

    return str(resp)
Beispiel #24
0
def handle_request(request_data):
    response = MessagingResponse()
    body = request_data['Body'].strip()
    phone_number = request_data['From']

    state = getState(phone_number)

    if type(state) is EventState:
        if state == EventState.EVENT_CREATED:
            setNameEvent(phone_number, body)
            response.message('When would you like to have your event? (MM/DD/YY HH:MM a/pm)')
            return str(response)

        elif state == EventState.NAME_CREATED:
            setDatetimeEvent(phone_number, parser.parse(body))
            response.message('How would you describe your event? Remember to include the location')
            return str(response)

        elif state == EventState.TIME_CREATED:
            setDescriptionEvent(phone_number, body)
            response.message("How many people would you like to invite?")
            return str(response)

        elif state == EventState.DESCRIPTION_CREATED:
            setCapEvent(phone_number, int(body))
            response.message("Would you like this event to be: \n1)Private \n2)Friends of Friends \n3)Public")
            return str(response)

        elif state == EventState.CAPACITY_CREATED:
            setVisibilityEvent(phone_number, parseVisibility(body))
            response.message("What's your name?")
            return str(response)

        elif state == EventState.VISIBILITY_CREATED:
            setCreatorNameEvent(phone_number, body)
            response.message("Send us the phone number of or contact of someone you want to invite")
            return str(response)
        elif state == EventState.ORGANIZER_NAME_CREATED or state == EventState.ATTENDEES_ADDED:
            if state == EventState.ATTENDEES_ADDED:
                if body == "DONE":
                    event_name = getOpenEventName(phone_number)
                    setDone(phone_number)
                    response.message("Thank you for planning {} with EventsEverywhere. We hope your event goes well.".format(event_name))
                    return str(response)
            NumMedia = request_data['NumMedia']
            contacts_list = []
            body = only_numerics(body)
            for i in range(int(NumMedia)):
                contacts_list.append(handle_vcf_url(request_data['MediaUrl' + str(i)]))
            if(len(body) == 10):
                contacts_list.append("+1" + str(body))
            elif(len(body) == 11):
                contacts_list.append("+" + str(body))
            elif len(contacts_list) == 0:
                response.message("Invalid number format")
                return str(response)
            for invitee in contacts_list:
                sendInvite(phone_number, invitee)
            sendInviteSMS(phone_number, contacts_list)
            response.message("Send us the name or contact of someone else you'd like to invite, or type DONE")
            return str(response)


    elif type(state) is AttendeeState:
        if state == AttendeeState.INVITE_SENT or state == AttendeeState.INVITE_MAYBE:
            if body.lower() == 'yes':
                inviteAccepted(phone_number)
                response.message("Thank you for accepting. What's your name?")
                return str(response)
            elif body.lower() == 'no':
                inviteDeclined(phone_number)
                response.message("Sorry that you can't make it. Thank you for using Events Everywhere")
                return str(response)
            elif body.lower() == 'maybe':
                inviteMaybe(phone_number)
                response.message("Please respond yes or no when you know if you'll be able to make it")
                return str(response)
            else:
                response.message("Sorry we were unable to understand what you said. Please send yes, no, or maybe")
                return str(response)
        elif state == AttendeeState.INVITE_ACCEPTED:
            setAttendeeName(phone_number, body)
            response.message("Thank you we'll keep you updated")
            return str(response)

    else:
        if body == 'START':
            if createEvent(phone_number):
                response.message("Welcome! Thank you for planning your event with Events Everywhere. Please provide a name for your event.")
                return str(response)
            else:
                response.message("Please finish editing your other event first")
                return str(response)
        if body == 'HELP':
            response.message("Help message")
            return str(response)
    response.message("Unable to understand your message. Please try again or send HELP for help")
    return(str(response))
Beispiel #25
0
def index(request):
    if request.method == 'POST':
        # retrieve incoming message from POST request in lowercase
        incoming_msg = request.POST['Body'].lower()

        # create Twilio XML response
        resp = MessagingResponse()
        msg = resp.message()

        responded = False

        if incoming_msg == 'hello':
            response = emoji.emojize("""
:wave: *Je suis le robot du Club St Hil'Air !*

Ce que je sais faire:
:black_small_square: *'rdv <lieu de RDV>':* affiche la localisation d'un lieu de rendez-vous habituel (ex: rdv botanic)

*Bon vols !*
""",
                                     use_aliases=True)
            msg.body(response)
            responded = True

        elif incoming_msg.startswith('rdv'):

            # Récupère le point de RDV
            search_text = incoming_msg.replace('rdv', '')
            search_text = search_text.strip()

            # TODO: implémente la recherche dans une bdd de lieux connus

            # donne le lieu de RDV, dans une liste déja connue
            # botanic, lumbin, col vert,
            answer = "Le RDV pour " + search_text + " est ici: https://goo.gl/maps/M7cnm6eykLry3yFD7"
            msg.body(answer)
            responded = True

        elif incoming_msg == 'quote':
            # returns 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 incoming_msg == 'cat':
            # return a cat pic
            msg.media('https://cataas.com/cat')
            responded = True

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

        elif incoming_msg.startswith('recipe'):

            # 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 = emoji.emojize(
                    "I am searching Allrecipes.com for the best {} recipes. :fork_and_knife:"
                    .format(search_text),
                    use_aliases=True)
                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 incoming_msg == 'news':
            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 incoming_msg.startswith('meme'):
            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."
            )

        return HttpResponse(str(resp))
Beispiel #26
0
def sms():
    print("Received text")
    resp = MessagingResponse()
    body = request.values.get('Body', None)
    body = body.lower()

    if ('hi' in body) or ('hello' in body) or ('help' in body):
        resp.message(
            "Hello! Thanks for your interest in keeping updated with COVID-19 statistics. Ask me for the latest covid-19 cases or to give you an update, and you will receive the latest statistics."
        )
    elif ('update' in body) or ('latest' in body):
        resp.message(covid19.getData('message', country, False, altAPI))

    elif ('thank' in body):
        resp.message("No problem!")

    elif 'stop' in body:
        print('working')
        config.read('config.ini')
        phoneNumbers = settings.get('Phone Numbers')
        numberToRemove = request.values.get('From', None)
        newPhone = phoneNumbers.replace(", " + numberToRemove, "")
        config.set('Settings', 'Phone Numbers', newPhone)
        with open('config.ini', 'w') as configfile:
            config.write(configfile)
        resp.message("Remove from list")

    elif 'start' in body:
        print('Subscribing...')
        config.read('config.ini')
        phoneNumbers = settings.get('Phone Numbers')
        numberToAdd = request.values.get('From', None)
        newPhone = phoneNumbers + ', ' + numberToAdd
        config.set('Settings', 'Phone Numbers', newPhone)
        with open('config.ini', 'w') as configfile:
            config.write(configfile)
    elif ('world' in body):
        resp.message(covid19.getWorld('message', altAPI))
    else:
        try:
            currentCountry = covid19.convertCountry(body)
            resp.message(
                covid19.getData('message', currentCountry, False, False))
        except:
            resp.message(
                "Sorry, I don't understand. If you'd like to find a country, reply with your country name."
            )
    return str(resp)
Beispiel #27
0
def respond(message):
    response = MessagingResponse()
    response.message(message)
    return str(response)
Beispiel #28
0
def messaging():
    sender = request.form['From']
    print("------ SMS MESSAGE RECEIVED FROM %s ------ " % sender)

    # For development, dump out the POST so we can see what is sent to us.
    # This is especially useful for testing add-ons.
    #for k in request.form: print("'%s':'%s'" % (k,request.form[k]))

    response = MessagingResponse()

    # Does the message body have something in it?
    # It could be a zip code or a locality (address)
    txtmsg = None
    try:
        body = request.form["Body"].strip()
        if len(body) > 1:
            print("Body='%s'" % body)
            txtmsg = body
    except Exception as e:
        print("Could not read message body.", e)

    zip = locality = None
    if txtmsg:
        if txtmsg.isdigit() and len(txtmsg) == 5:
            zip = txtmsg
        else:
            locality = txtmsg
    else:
        # try caller id zip and locality
        try:
            zip = request.form["FromZip"]
        except KeyError:
            pass
        try:
            locality = request.form["FromCity"]
        except KeyError:
            locality = None
            pass

    if not zip and not locality:
        # With no input, I cannot even guess where you are! Oh!
        msg = "Could not determine location, sorry. Weather information not available."
    else:
        place = geocode.geocode()
        place.search(address=locality, postalcode=zip)

        shortmsg = "Sorry, I can't tell where you are!"
        if place.parse():
            latlon = place.latlon
            if place.short_place:
                # This will be a better name than what I typed
                locality = place.short_place

            if not latlon or not latlon[0] or not latlon[1]:
                if zip:
                    shortmsg += " I tried zip code '%s'." % zip
                elif locality:
                    shortmsg += " I looked for '%s'." % locality
            else:
                print("Geocode result for %s %s = %s." %
                      (place.locality, zip, latlon))
                (shortmsg, longmsg) = get_weather(latlon, locality)

    print("Replying: '%s'" % shortmsg)
    try:
        # We're replying so remember to flip From and To!
        rval = response.message(shortmsg, to=sender, from_=request.form['To'])
        # rval contains XML that will be sent
    except Exception as e:
        print("Exception buiding reply:", e)

    return twiml(response)
Beispiel #29
0
def sms_reply():
    resp = MessagingResponse()

    resp.message("The robots are coming! ")

    return str(resp)
Beispiel #30
0
def hello_guest():

    resp = MessagingResponse()
    from_number = request.values.get('From', None)
    from_body = request.values.get('Body', None)
    number = from_number
    body_strip = from_body.lower()
    clean_number = number.strip("+")

    #all of these values depend on how many guests are at your wedding

    #attendance variables
    guest_confirmed = wks_attendees.acell('C70').value
    guest_unconfirmed = wks_attendees.acell('C71').value
    guest_no_response = wks_attendees.acell('C72').value
    guest_acceptance = wks_attendees.acell('C73').value

    #meal total variables
    guest_meals_confirmed = wks_attendees.acell('C78').value
    guest_meals_unconfirmed = wks_attendees.acell('C79').value

    #meal options (name/amount)
    starter_option_1 = wks_food.acell('G2').value
    starter_option_1_amount = wks_food.acell('H2').value

    starter_option_2 = wks_food.acell('G3').value
    starter_option_2_amount = wks_food.acell('H3').value

    starter_option_3 = wks_food.acell('G4').value
    starter_option_3_amount = wks_food.acell('H4').value

    main_option_1 = wks_food.acell('G5').value
    main_option_1_amount = wks_food.acell('H5').value

    main_option_2 = wks_food.acell('G6').value
    main_option_2_amount = wks_food.acell('H6').value

    main_option_3 = wks_food.acell('G7').value
    main_option_3_amount = wks_food.acell('H7').value

    dessert_option_1 = wks_food.acell('G8').value
    dessert_option_1_amount = wks_food.acell('H8').value

    dessert_option_2 = wks_food.acell('G9').value
    dessert_option_2_amount = wks_food.acell('H9').value

    guest_confirmation_cell = wks_attendees.find(str(clean_number).strip())

    if "yes" in body_strip:
        #We have a keeper! Find the attendee and update their confirmation_status
        wks_attendees.update_acell(
            "F" + str(guest_confirmation_cell.row),
            'Accepted')  #update the status to accepted for that guest
        resp.message(u"\u2665" + "Thanks for confirming, we'll be in touch!" +
                     u"\u2665")  #respond to the guest with a confirmation!

    elif "no" in from_body.lower():  #no!
        #update the confirmation_status row to declined for that guest
        wks_attendees.update_acell("F" + str(guest_confirmation_cell.row),
                                   'Declined')
        resp.message("Sorry to hear that, we still love you though!"
                     )  #respond to the user confirming the action

    elif "numbers" in from_body.lower(
    ):  #return statistics (total guests, food choices list)
        resp.message("R.S.V.P update:\n\nTotal Accepted: " + guest_confirmed +
                     "\n\nTotal declined: " + guest_unconfirmed +
                     "\n\nTotal no response: " + guest_no_response +
                     "\n\nTotal acceptance rate: " + guest_acceptance)

    elif "food" in body_strip.strip(
    ):  #respond with the current food totals and the meal choices

        resp.message("Guest meals decided:" + guest_meals_confirmed +
                     "\nGuest meals undecided: " + guest_meals_unconfirmed +
                     "\n\nMenu breakdown:\n\n" + starter_option_1 + ": " +
                     starter_option_1_amount + "\n" + starter_option_2 + ": " +
                     starter_option_2_amount + "\n" + starter_option_3 + ": " +
                     starter_option_3_amount + "\n" + main_option_1 + ": " +
                     main_option_1_amount + "\n" + main_option_2 + ": " +
                     main_option_2_amount + "\n" + main_option_3 + ": " +
                     main_option_3_amount + "\n" + dessert_option_1 + ": " +
                     dessert_option_1_amount + "\n" + dessert_option_2 + ": " +
                     dessert_option_2_amount)

    else:  #respond with invalid keyword
        resp.message(
            "You sent a different keyword, we need a yes or a no, you sent: " +
            from_body)
    return str(resp)
Beispiel #31
0
def create_twilio_reply(message_str):
    resp = MessagingResponse()
    resp.message(message_str)
    return str(resp)
Beispiel #32
0
def sms():
    global status
    global loaded_model
    message_body = request.form['Body']
    message = str(message_body)
    message2 = str(message)
    message = message.lower().strip(" ")
    resp = MessagingResponse()
    find_str = "find the price of"
    length = len(message)
    print (message2)
    if message.startswith(find_str):
        tup = get_price(message.split("price of")[1])
        if tup[1] == "n/a":
            resp.message("Couldn't find the product.")
        else:
            resp.message("The price of " + tup[1] + " is $" + str(tup[0]))
    elif message in responses:
        temp = resp.message(responses[message])
        rand = random.randint(0,2)
        temp.media(hello[rand])
    elif message == "tell me a joke" or "joke" in message:
        temp3 = joke[random.randint(0,4)]
        resp.message(temp3)
    elif "toothpaste" in message2:
        temp3 = predict_arr(message2.split("\n")[1:])
        resp.message(str(temp3))
    elif message == "what should i do today":
        temp4 = daily[random.randint(0,1)]
        resp.message(temp4)
    elif  "budget" in message and ("$" in message or "dollars" in message):
        if ("$" in message):
            budget = (int) (message.split("$")[1].split(" ")[0])
            temp = resp.message("GOOD Job Saving Money, Smart Human")

        if ("dollars" in message):
            budget = (int) (message.split("dollars")[0].split(" ")[-1])
            temp = resp.message("GOOD Job Saving Money, Smart Human")

    elif message.startswith("can i afford"):
        tup = get_price(message.split("afford")[1])
        if tup[1] == "n/a":
            temp = resp.message("Couldn't find the product.")
        else:
            string = "The price of " + tup[1] + " is $" + str(tup[0]) + "\n"
            temp2 = check_if_enough_money.info()
            bal = temp2.check_balance()
            if (tup[0] >= bal/2):
                string = string + "No, You Broke"
                temp = resp.message(string)
                temp.media(broke[random.randint(0,2)])
            elif(budget == -1):
                string = string + "Sure Thing, You Rich"
                temp = resp.message(string)
                temp.media(spend[random.randint(0,2)])
            else:
                if(tup[0] >= budget):
                    string = string + "No, Your Budget is: " + str(budget)
                    temp = resp.message(string)
                    temp.media(broke[random.randint(0,2)])
                else:      
                    string = string + "YES You Can!, Your Budget is: " + str(budget)
                    temp = resp.message(string)
                    temp.media(spend[random.randint(0,2)])

    elif message == "find my bank account" or message == "find my account" and status == -1:
        resp.message("What is your first name?")
        status += 1
    elif status == 0:
        check_if_enough_money.first_name = message
        resp.message("What is your last name?")
        status += 1
    elif status == 1:
        check_if_enough_money.last_name = message
        resp.message("What your zip code?")
        status += 1
    elif status == 2:
        check_if_enough_money.zip_code = message
        temp = check_if_enough_money.info()
        if temp.check_for_customer() == 1:
            temp.get_accounts_list()
            resp.message("Found you! Choose the account you would like to access:\n" + check_if_enough_money.account_nickname_list)
            status += 1
        else:
            resp.message("Could not find you.")
            status = -1
    elif status == 3:
        check_if_enough_money.account_nickname = message
        temp = check_if_enough_money.info()
        the_account = temp.find_account()
        if the_account == 1:
            temp.set_up_account_endpoints()
            resp.message("Accessing the account...\nWhat do you want to do with it?")
            status += 1
        else:
            resp.message("I couldn't find the account, run it by me again.")
    elif status == 4:
        temp = check_if_enough_money.info()
        if message == "check my balance" or message == "what's my balance" or message == "balance":
            temp2 = resp.message("Balance: $" + str(temp.check_balance()))
            if (temp.check_balance()>20000):
                temp2.media(rich[random.randint(0,2)])
            else:
                temp2.media(need_money_img[random.randint(0,2)])

        elif message == "check my rewards" or message == "rewards":
            resp.message("Rewards balance: $" + str(temp.check_rewards()))
        elif message == "check my bills" or message == "bills":
            bills_string = temp.check_bills()
            print(bills_string)
            constructed_string = ""
            for x in bills_string:
                print(x)
                constructed_string = constructed_string + x
            resp.message("Here are your bills: \n" + constructed_string)
        elif message == "done":
            resp.message("Cool, still wanna chat?")
            status = -1
        else:
            resp.message("Sorry, I do not understand. Try 'done' or 'check my balance'")
    elif message not in responses:
        resp.message("I don't understand. Please try 'Find my bank account' or 'Good to see you' or 'Find the price of x'")
    else:
        temp = resp.message(responses[message])
        rand = random.randint(0,2)
        temp.media(hello[rand])

    return str(resp)
Beispiel #33
0
def sms_response(request):
    msg = ''
    r = MessagingResponse()
    r.message(msg)
    return r
Beispiel #34
0
def bot():
    incoming_msg = request.values.get('Body', '').lower()
    resp = MessagingResponse()
    msg = resp.message()
    text = ""
    menu_txt = '\n\nSend a *country name*, or *global*, for the latest report\nSend *symptoms* to see the disease\'s symptoms\nSend *prevent* to learn how to prevent the disease'

    if 'hi' == incoming_msg or 'hey' == incoming_msg or 'hello' == incoming_msg or 'hola' == incoming_msg:
        text = 'Hey! \nThis is Ms Rona with the latest COVID-19 updates. How can I help you?'
        msg.body(text + menu_txt)

    elif 'menu' in incoming_msg or 'instructions' in incoming_msg:
        msg.body(menu_txt)

    elif 'symptoms' in incoming_msg:
        text = f'COVID-19 sympotoms:\n\nCommonn symptoms:\n-fever\n-dry cough\n-tiredness\n\nLess common symptoms:\n-aches and pains\n-sore throat\n-diarrhoea\n-conjunctivitis\n-headache\n-loss of taste or smell\n-a rash on skin, or discolouration of fingers or toes\n\nSerious symptoms:\n-difficulty breathing or shortness of breath\n-chest pain or pressure\n-loss of speech or movement\n\nSeek immediate medical attention if you have serious symptoms. Always call before visiting your doctor or health facility.\nPeople with mild symptoms who are otherwise healthy should manage their symptoms at home.\nOn average it takes 5–6 days from when someone is infected with the virus for symptoms to show, however it can take up to 14 days.\n\nLearn more on https://www.who.int/emergencies/diseases/novel-coronavirus-2019/question-and-answers-hub/q-a-detail/q-a-coronaviruses#:~:text=symptoms'
        msg.body(text + menu_txt)

    elif 'prevent' in incoming_msg or 'spread' in incoming_msg:
        text = f'_COVID-19 spread can be prevented through the following means_\n\n*Stay* home as much as you can\n*Keep* a safe distance\n*Wash* hands often\n*Cover* your nose and mouth\n\nlearn more on https://www.who.int/emergencies/diseases/novel-coronavirus-2019/advice-for-public'
        msg.body(text + menu_txt)

    elif 'world' in incoming_msg or 'planet' in incoming_msg or 'global' in incoming_msg or 'all' == incoming_msg:
        # send global report
        r = requests.get('https://coronavirus-19-api.herokuapp.com/all')
        if r.status_code == 200:
            try:
                data = r.json()
                fatality_rate = 'N/A'
                recovery_rate = 'N/A'
                if data["cases"]:
                    if data["deaths"]:
                        fatality_rate = f'{round((100 * data["deaths"]/data["cases"]), 2)}%'
                    if data["recovered"]:
                        recovery_rate = f'{round((100 * data["recovered"]/data["cases"]), 2)}%'

                for key in data:
                    if not data[key]:
                        data[key] = 'N/A'
                    elif type(data[key]) == int:
                        data[key] = f'{data[key]:,d}'

                text = f'_Worldwide Covid-19 Report_ \n\nConfirmed Cases: *{data["cases"]}*\nDeaths: *{data["deaths"]}*\nRecovered: *{data["recovered"]}*\n\nFatality rate: *{fatality_rate}*%\nRecovery rate: *{recovery_rate}*%'
            except Exception as e:
                text = 'I could not retrieve global results at this time, sorry.'
        else:
            text = 'I could not retrieve global results at this time, sorry.'
        msg.body(text + menu_txt)

    else:
        # send country report
        if 'us' == incoming_msg or 'united states' == incoming_msg:
            incoming_msg = 'usa'
        elif 'united kingdom' == incoming_msg:
            incoming_msg = 'uk'
        elif 'emirates' in incoming_msg:
            incoming_msg = 'uae'

        r = requests.get(
            'https://coronavirus-19-api.herokuapp.com/countries/' +
            incoming_msg)
        if r.status_code == 200:
            try:
                data = r.json()
                fatality_rate = 'N/A'
                recovery_rate = 'N/A'
                if data["cases"]:
                    if data["deaths"]:
                        fatality_rate = f'{round((100 * data["deaths"]/data["cases"]), 2)}%'
                    if data["recovered"]:
                        recovery_rate = f'{round((100 * data["recovered"]/data["cases"]), 2)}%'

                for key in data:
                    if not data[key]:
                        data[key] = 'N/A'
                    elif type(data[key]) == int:
                        data[key] = f'{data[key]:,d}'

                text = f'_{data["country"]} Covid-19 Report_ \n\nConfirmed Cases: *{data["cases"]}*\nToday Cases: *{data["todayCases"]}*\nDeaths: *{data["deaths"]}*\nRecovered: *{data["recovered"]}*\nActive: *{data["active"]}*\nCritical: *{data["critical"]}*\nTotal tests: *{data["totalTests"]}*\n\nCases per Million: *{data["casesPerOneMillion"]}*\nDeaths per Million: *{data["deathsPerOneMillion"]}*\nTests per Million: *{data["testsPerOneMillion"]}*\n\nFatality rate: *{fatality_rate}*\nRecovery rate: *{recovery_rate}*'
            except Exception as e:
                text = f'I could not retrieve the results for {incoming_msg} at this time, sorry.'
        else:
            text = f'I could not retrieve the results for {incoming_msg} at this time, sorry.'

        msg.body(text + menu_txt)

    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 #36
0
def bot():
    incoming_msg = request.values.get('Body', '').lower()
    resp = MessagingResponse()
    msg = resp.message()
    sender_number = request.values.get('From')
    print("IN BOT")
    print(incoming_msg)
    responded = False
    if 'add state' in incoming_msg:
        state_name = incoming_msg.split("add state", 1)[1]

        search_term = state_name.strip()
        search_term = f"%{search_term}%"

        state = State.query.filter((State.State.like(search_term))).first()
        stateSchema = StateSchema()
        state = stateSchema.dump(state)
        state_id = state["Id"]
        state_cured = state["Cured"]
        state_dead = state["Dead"]
        state_confirmed = state["Confirmed"]
        state_name = state["State"]

        check_user_state_exist = User.query.filter_by(
            MobileNo=sender_number, State_Id=state['Id']).first()

        if not check_user_state_exist:
            user_new = User(State_Id=state_id, MobileNo=sender_number)
            db.session.add(user_new)
            db.session.commit()

            msg.body(f"{state_name} added for COVID-19 tracking.")

        else:
            msg.body(f"{state_name} already added for tracking.")

        msg.body(
            f"Currently in {state_name}, there are \n {state_confirmed} cases confirmed \n {state_cured} cases "
            f"cured \n {state_dead} deaths ")

        responded = True

    if 'all states' in incoming_msg:
        user_list = User.query.filter_by(MobileNo=sender_number).all()
        userSchema = UserSchema(many=True)
        user_list = userSchema.dump(user_list)

        print(user_list)
        if not user_list:
            msg.body(
                f"No states added currently add it like *add state Gujarat*")
        for user_detail in user_list:
            state_id = user_detail["states"]

            state = State.query.filter_by(Id=state_id).first()
            stateSchema = StateSchema()
            state = stateSchema.dump(state)
            state_id = state["Id"]
            state_cured = state["Cured"]
            state_dead = state["Dead"]
            state_confirmed = state["Confirmed"]
            state_name = state["State"]

            empty = "‎‎ ‎"  # invisible character, to get new line hack
            msg.body(empty)
            msg.body(
                f" Currently in \n *{state_name}*, there are \n {state_confirmed} cases confirmed \n {state_cured} cases "
                f"cured \n {state_dead} deaths. \n {empty}\n")

        responded = True
    if 'remove state' in incoming_msg:
        state_name = incoming_msg.split("remove state", 1)[1]
        search_term = state_name.strip()
        search_term = f"%{search_term}%"

        user_list = User.query.filter_by(MobileNo=sender_number).all()
        userSchema = UserSchema(many=True)
        user_list = userSchema.dump(user_list)

        print(user_list)
        if not user_list:
            msg.body(
                f"No states to remove currently add it like *add state Gujarat*"
            )

        if user_list:
            state = State.query.filter((State.State.like(search_term))).first()
            stateSchema = StateSchema()
            state = stateSchema.dump(state)
            state_id = state["Id"]
            state_name = state["State"]

            User.query.filter_by(MobileNo=sender_number,
                                 State_Id=state_id).delete()
            db.session.commit()
            msg.body(f"{state_name} removed from tracking")

        responded = True

    if 'get news' in incoming_msg:

        all_news = News.query.all()
        news_schema = NewsSchema(many=True)
        all_news = news_schema.dump(all_news)

        for news in all_news:
            title = news["Title"]

            empty = "‎‎ ‎"  # invisible character, to get new line hack
            msg.body(f" \n *Title* :  {title} \n {empty}\n ")

        responded = True

    if "what is covid 19" in incoming_msg:
        msg.body(
            "COVID-19 is a disease caused by a new strain of coronavirus. ‘CO’ stands for corona, ‘VI’ for virus, and ‘D’ for disease. Formerly, this disease was referred to as ‘2019 novel coronavirus’ or ‘2019-nCoV.’ The COVID-19 virus is a new virus linked to the same family of viruses as Severe Acute Respiratory Syndrome (SARS) and some types of common cold"
        )

        responded = True
    if "symptoms of covid 19" in incoming_msg:
        msg.body(
            "Symptoms can include fever, cough and shortness of breath. In more severe cases, infection can cause pneumonia or breathing difficulties. More rarely, the disease can be fatal. These symptoms are similar to the flu (influenza) or the common cold, which are a lot more common than COVID-19. This is why testing is required to confirm if someone has COVID-19."
        )

        responded = True

    if "how to be safe" in incoming_msg:
        msg.body('''✓ staying home when sick
✓ covering mouth and nose with flexed elbow or tissue when coughing or sneezing. Dispose ofused tissue immediately;
✓ washing hands often with soap and water; and
✓ cleaning frequently touched surfaces and objects
        ''')
        responded = True

    if "help" in incoming_msg:
        msg.body('''You can give me the following commands
👉 add state {state name}
👉 all states
👉 remove state {state name}
👉 get news
👉 what is covid 19
👉 symptoms of covid 19
👉 how to be safe
👉 help
''')
        responded = True
    if not responded:
        chatter_resp = chat_bot.get_response(incoming_msg)
        # print(chatter_resp)
        # print(chatter_resp.serialize())
        serialize_resp = chatter_resp.serialize()
        res_text = serialize_resp["text"]
        # print(res_text)

        empty = "‎‎ ‎"  # invisible character, to get new line hack
        msg.body(f"{res_text}")
        msg.body(f"{empty} \n you can type *help* for menu")
    return str(resp)
Beispiel #37
0
def hello_guest():
    
    resp = MessagingResponse() 
    from_number = request.values.get('From', None)
    from_body = request.values.get('Body', None)
    number = from_number
    body_strip = from_body.lower()
    clean_number = number.strip("+")
    
    #all of these values depend on how many guests are at your wedding

    #attendance variables
    guest_confirmed = wks_attendees.acell('C70').value
    guest_unconfirmed = wks_attendees.acell('C71').value
    guest_no_response = wks_attendees.acell('C72').value
    guest_acceptance = wks_attendees.acell('C73').value
    
    #meal total variables
    guest_meals_confirmed = wks_attendees.acell('C78').value 
    guest_meals_unconfirmed = wks_attendees.acell('C79').value
    
    #meal options (name/amount)
    starter_option_1 = wks_food.acell('G2').value
    starter_option_1_amount = wks_food.acell('H2').value
    
    starter_option_2 = wks_food.acell('G3').value
    starter_option_2_amount = wks_food.acell('H3').value

    starter_option_3 = wks_food.acell('G4').value
    starter_option_3_amount = wks_food.acell('H4').value
    
    main_option_1 = wks_food.acell('G5').value
    main_option_1_amount = wks_food.acell('H5').value
    
    main_option_2 = wks_food.acell('G6').value
    main_option_2_amount = wks_food.acell('H6').value
    
    main_option_3 = wks_food.acell('G7').value
    main_option_3_amount = wks_food.acell('H7').value
    
    dessert_option_1 = wks_food.acell('G8').value
    dessert_option_1_amount = wks_food.acell('H8').value
    
    dessert_option_2 = wks_food.acell('G9').value
    dessert_option_2_amount = wks_food.acell('H9').value

    guest_confirmation_cell = wks_attendees.find(str(clean_number).strip()) 
    
    if "yes" in body_strip: 
        #We have a keeper! Find the attendee and update their confirmation_status
        wks_attendees.update_acell("F" + str(guest_confirmation_cell.row), 'Accepted') #update the status to accepted for that guest
        resp.message(u"\u2665" + "Thanks for confirming, we'll be in touch!" + u"\u2665")  #respond to the guest with a confirmation! 
        
    elif "no" in from_body.lower(): #no! 
       #update the confirmation_status row to declined for that guest
        wks_attendees.update_acell("F" + str(guest_confirmation_cell.row), 'Declined')  
        resp.message("Sorry to hear that, we still love you though!") #respond to the user confirming the action 
    
    elif "numbers" in from_body.lower(): #return statistics (total guests, food choices list)   
        resp.message("R.S.V.P update:\n\nTotal Accepted: " + guest_confirmed +
         "\n\nTotal declined: " + guest_unconfirmed + "\n\nTotal no response: " +
        guest_no_response + "\n\nTotal acceptance rate: " + guest_acceptance) 

    elif "food" in body_strip.strip():   #respond with the current food totals and the meal choices  

        resp.message("Guest meals decided:" + guest_meals_confirmed + 
        "\nGuest meals undecided: " + guest_meals_unconfirmed +
        "\n\nMenu breakdown:\n\n" + starter_option_1 +": " +
        starter_option_1_amount + "\n" + starter_option_2 +": " +
        starter_option_2_amount + "\n" + starter_option_3 +": " +
        starter_option_3_amount + "\n" + main_option_1 +": " +
        main_option_1_amount + "\n" + main_option_2 +": " + main_option_2_amount +
        "\n" + main_option_3 +": " + main_option_3_amount + "\n" +
        dessert_option_1 + ": " + dessert_option_1_amount + "\n" + dessert_option_2
        + ": " + dessert_option_2_amount)

    else: #respond with invalid keyword
        resp.message("You sent a different keyword, we need a yes or a no, you sent: " +
        from_body)
    return str(resp)
Beispiel #38
0
def index():
    if request.method == 'POST':
        global area
        global sqft
        global bhk
        
        getTwilioCredentials()
        
        ResponseMsg = json.dumps(request.form.to_dict(), indent=2)
        respo = json.loads(ResponseMsg)
        print(respo)
        global receivedMsg
        global sentMsg
        receivedMsg = respo.get('Body')
        
        if respo.get('Body') == 'What can you do?':
            client = Client(account_sid, auth_token)
            to_ = respo.get('From')
            from_ = respo.get('To')
            message = client.messages.create(
                from_=from_,
                body="I am a bot who is connected to watson services on IBM Cloud! \nTry asking *What are the services you are connected to?*",
                media_url="https://whatsapp-server-reliable-kangaroo.eu-gb.mybluemix.net/static/images/architecture.png",
                to=to_
            )
            sentMsg = "I am a bot who is connected to watson services on IBM Cloud! \nTry asking *What are the services you are connected to?*"
            return(message.sid)
        
        if respo.get('Body') == 'What are the services you are connected to?':
            
            to_ = respo.get('From')
            from_ = respo.get('To')
            client = Client(account_sid, auth_token)
            checkServices(to_, from_, client)
            
            return str("ok")
        
        if respo.get('Body') == '1':
            message = "Watson Machine Learning Details"
            resp = MessagingResponse()
            resp.message(message)
            sentMsg = message
            x = scanAvailableFiles(app.config["SERVICES"])
            for j in x:
                if j == "wmlDeployment.json":
                    with open(app.config["SERVICES"]+j) as temp:
                        cred = json.loads(temp.read())
                    model_id = cred["entity"]["asset"]["id"]
                    model_name = cred["entity"]["name"]
                    model_status = cred["entity"]["status"]["state"]
                    
                    if model_status == "ready":
                        message = "WML Model id: *{0}*".format(model_id) + \
                            "\nWML Model Name: *{0}*".format(model_name) + \
                            "\nWML Model Status: *{0}*".format(
                                model_status) + "\n\nTry asking *I want to know house prices*"
                    else:
                        message = "Model id: *{0}*".format(model_id) + \
                            "\nModel Name: *{0}*".format(model_name) + \
                            "\nModel Status: *{0}*".format(model_status)
                    resp.message(message)
                    sentMsg = message
                    return str(resp)
                else:
                    message = "Service configured, but no model deployed!\nType *Deploy* to deploy a test model"
                    resp.message(message)
                    sentMsg = message
                    return str(resp)
        
        if respo.get('Body') == '2':
            message = "Watson Visual Recognition"
            resp = MessagingResponse()
            resp.message(message)
            sentMsg = message
            
            message = "Send any food image from your Camera or Gallery to classify the food with Watson Visual Recognition"
            resp.message(message)
            sentMsg = message
            
            return str(resp)
        
        if respo.get('Body') == 'I want to know house prices':
            message = "What do you want to do?\nA.Check prices in different locality\nB.Check the prices in your current locality\n\nEnter either *A* or *B* to continue..."
            resp = MessagingResponse()
            resp.message(message)
            sentMsg = message
            return str(resp)
        
        if respo.get('Body') == 'A':
            message = "Please enter the details with the below format:\n\n*Predict:<Place-Name>,<Area-sq.ft>,<How-many-bhk>*\n\nExample: *Predict:Thanisandra,1300,2*"
            resp = MessagingResponse()
            resp.message(message)
            sentMsg = message
            return str(resp)
        
        if respo.get('Body') == 'B':
            message = "Share your current location\n\nTap *Attach* > *Location* > *Send your current location*"
            resp = MessagingResponse()
            resp.message(message)
            sentMsg = message
            return str(resp)
        
        if respo.get('Body')[:7] == 'Predict':
            
            temp = respo.get('Body').split(':')[1].split(',')
            length = len(temp)
            
            if(length == 3):
                print("Its in 3")
                area = respo.get('Body').split(':')[1].split(',')[0].strip()
                sqft = respo.get('Body').split(':')[1].split(',')[1].strip()
                bhk = respo.get('Body').split(':')[1].split(',')[2].strip()
            
            elif(length == 2):
                print("Its in 2")
                sqft = respo.get('Body').split(':')[1].split(',')[0].strip()
                bhk = respo.get('Body').split(':')[1].split(',')[1].strip()
            
            elif(length == 1):
                print("Its in 1")
                area = respo.get('Body').split(':')[1].split(',')[0].strip()
                sqft = 1200
                bhk = 2
                
            price = predict_price_wml(area,sqft,bhk,bhk)
            
            with open(app.config["CREDENTIALS"]+'wmlCredentials.json') as wmlCreds:
                wmlcred = json.loads(wmlCreds.read())
            
            messageTxt = "Area: *{0}, Bengaluru*\n\n{1} Bhk with {2} Sq.Ft will cost you approx: {3} Lakhs".format(area, bhk, sqft, price)
            createImagePrediction(area, bhk, sqft, price)
            client = Client(account_sid, auth_token)
            to_ = respo.get('From')
            from_ = respo.get('To')
            message = client.messages.create(
                from_=from_,
                body=messageTxt,
                media_url=wmlcred.get('windowURL')+"static/images/predicted.png",
                to=to_
            )
            sentMsg = messageTxt
            return(message.sid)
        
        if respo.get('MediaUrl0') != None:
            imageURL = respo.get('MediaUrl0')
            
            with open(app.config["CREDENTIALS"]+'wvrCredentials.json') as wmlCreds:
                wvrcred = json.loads(wmlCreds.read())
            
            payload = {
                "apikey": wvrcred.get('apikey'),
                "url": wvrcred.get('url'),
                "imageURL": imageURL
                }

            r = requests.post(wvrcred.get('cloudfunctionurl'), data=payload)
            response = r.json()
            
            messageTxt = "Classified as *{0}*\nwith an accuracy of *{1}*".format(response.get('class'), response.get('score'))
            
            createImageVisual(response.get('class'), response.get('score'))
            client = Client(account_sid, auth_token)
            to_ = respo.get('From')
            from_ = respo.get('To')
            message = client.messages.create(
                from_=from_,
                body=messageTxt,
                media_url=wvrcred.get('windowURL')+"static/images/visualclass.png",
                to=to_
            )
            sentMsg = messageTxt
            return(message.sid)
        
        if respo.get('Latitude') != None and respo.get('Longitude') != None:
            Latitude = respo.get('Latitude')
            Longitude = respo.get('Longitude')
        
            msg = "Lat: {0} \nLong: {1}".format(Latitude, Longitude)
            resp = MessagingResponse()
            resp.message(msg)
            sentMsg = msg
            
            area = location(Latitude, Longitude)
            
            message = "For Area: *{0}, Bengaluru*\n\nPlease enter the details with the below format:\n\n*Predict:<Area-sq.ft>,<How-many-bhk>*\n\nExample: *Predict:1300,2*".format(area)
            resp = MessagingResponse()
            resp.message(message)
            sentMsg = message
            return str(resp)
            
        msg = "The message,\n'_{0}_'\nthat you typed on your phone, went through\nWhatsapp -> Twilio -> Python App hosted on IBM Cloud and returned back to you from\nPython App hosted on IBM Cloud -> Twilio -> Whatsapp.\n\n*How Cool is that!!*\n\n Try asking *What can you do?*".format(respo.get('Body'))
        resp = MessagingResponse()
        resp.message(msg)
        sentMsg = msg
        return str(resp)

    return render_template('index.html')
 def generate(cls, action_response):
     response = MessagingResponse()
     response.message(action_response['message'])
     return response
Beispiel #40
0
def bot():
    incoming_msg = request.values.get('Body', '')
    print(incoming_msg)
    resp = MessagingResponse()
    msg = resp.message()
    responded = False

    if 'Hi' in incoming_msg or 'Hey' in incoming_msg or 'Heya' in incoming_msg or 'Menu' in incoming_msg:
        text = f'Hello !!!!!!! \nThis is a Covid-Bot developed by *RUTVIK MODI* *(KIVTUR)* to provide latest information updates i.e cases in different countries and create awareness to help you and your family stay safe. \n \n *For any emergency* \n\n ----> Helpline: 011-23978046 \n ----> Toll-Free Number: 1075 \n ----> Email: [email protected] \n\nPlease type one of the following option given in the bold: \n\n *World*. Covid-19 statistics *Worldwide*. \n *Ind*. Covid-19 cases in *India*. \n *Chi*. Covid-19 cases in *China*. \n *Usa*. Covid-19 cases in *USA*. \n *Ita*. Coronavirus cases in *Italy*. \n *Aus*. Coronavirus cases in *Australia*. \n *Jap*. Coronavirus cases in *Japan*. \n *F*. How does it *Spread*? \n *G*. *Preventive measures* to be taken.'
        msg.body(text)
        responded = True

    if 'World' in incoming_msg:
        # return total cases
        r = requests.get('https://coronavirus-19-api.herokuapp.com/all')
        if r.status_code == 200:
            data = r.json()
            text = f'_Covid-19 Cases Worldwide_ \n\nConfirmed Cases : *{data["cases"]}* \n\nDeaths : *{data["deaths"]}* \n\nRecovered : *{data["recovered"]}*  \n\n*Type one of the option given below to know more*\n\n *World*. Covid-19 statistics *Worldwide*. \n *Ind*. Covid-19 cases in *India*. \n *Chi*. Covid-19 cases in *China*. \n *Usa*. Covid-19 cases in *USA*. \n *Ita*. Coronavirus cases in *Italy*. \n *Aus*. Coronavirus cases in *Australia*. \n *Jap*. Coronavirus cases in *Japan*. \n *F*. How does it *Spread*? \n *G*. *Preventive measures* to be taken.\n\nType *Menu* to view the Main Menu'
            print(text)
        else:
            text = 'I could not retrieve the results at this time, sorry.'
        msg.body(text)
        responded = True

    elif 'Ind' in incoming_msg or 'India' in incoming_msg:
        # return cases in india
        r = requests.get(
            'https://coronavirus-19-api.herokuapp.com/countries/india')
        if r.status_code == 200:
            data = r.json()
            text = f'_Covid-19 Cases in India_ \n\nConfirmed Cases : *{data["cases"]}* \n\nToday Cases : *{data["todayCases"]}* \n\nDeaths : *{data["deaths"]}* \n\nRecovered : *{data["recovered"]}* \n\n*Type one of the option given below to know more*\n\n *World*. Covid-19 statistics *Worldwide*. \n *Ind*. Covid-19 cases in *India*. \n *Chi*. Covid-19 cases in *China*. \n *Usa*. Covid-19 cases in *USA*. \n *Ita*. Coronavirus cases in *Italy*. \n *Aus*. Coronavirus cases in *Australia*. \n *Jap*. Coronavirus cases in *Japan*. \n *F*. How does it *Spread*? \n *G*. *Preventive measures* to be taken.\n\nType *Menu* to view the Main Menu'
        else:
            text = 'I could not retrieve the results at this time, sorry.'
        msg.body(text)
        responded = True

    elif 'Chi' in incoming_msg or 'China' in incoming_msg:
        # return cases in china
        r = requests.get(
            'https://coronavirus-19-api.herokuapp.com/countries/china')
        if r.status_code == 200:
            data = r.json()
            text = f'_Covid-19 Cases in China_ \n\nConfirmed Cases : *{data["cases"]}* \n\nToday Cases : *{data["todayCases"]}* \n\nDeaths : *{data["deaths"]}* \n\nRecovered : *{data["recovered"]}* \n\nActive Cases : *{data["active"]}* \n\n*Type one of the option given below to know more*\n\n *World*. Covid-19 statistics *Worldwide*. \n *Ind*. Covid-19 cases in *India*. \n *Chi*. Covid-19 cases in *China*. \n *Usa*. Covid-19 cases in *USA*. \n *Ita*. Coronavirus cases in *Italy*. \n *Aus*. Coronavirus cases in *Australia*. \n *Jap*. Coronavirus cases in *Japan*. \n *F*. How does it *Spread*? \n *G*. *Preventive measures* to be taken.\n\nType *Menu* to view the Main Menu'
        else:
            text = 'I could not retrieve the results at this time, sorry.'
        msg.body(text)
        responded = True

    elif 'Usa' in incoming_msg or 'USA' in incoming_msg:
        # return cases in usa
        r = requests.get(
            'https://coronavirus-19-api.herokuapp.com/countries/usa')
        if r.status_code == 200:
            data = r.json()
            text = f'_Covid-19 Cases in USA_ \n\nConfirmed Cases : *{data["cases"]}* \n\nToday Cases : *{data["todayCases"]}* \n\nDeaths : *{data["deaths"]}* \n\nRecovered : *{data["recovered"]}* \n\nActive Cases : *{data["active"]}*  \n\n*Type one of the option given below to know more*\n *World*. Covid-19 statistics *Worldwide*. \n *Ind*. Covid-19 cases in *India*. \n *Chi*. Covid-19 cases in *China*. \n *Usa*. Covid-19 cases in *USA*. \n *Ita*. Coronavirus cases in *Italy*. \n *Aus*. Coronavirus cases in *Australia*. \n *Jap*. Coronavirus cases in *Japan*. \n *F*. How does it *Spread*? \n *G*. *Preventive measures* to be taken.\n\nType *Menu* to view the Main Menu'
        else:
            text = 'I could not retrieve the results at this time, sorry.'
        msg.body(text)
        responded = True

    elif 'Ita' in incoming_msg or 'Italy' in incoming_msg:
        # return cases in italy
        r = requests.get(
            'https://coronavirus-19-api.herokuapp.com/countries/italy')
        if r.status_code == 200:
            data = r.json()
            text = f'_Covid-19 Cases in Italy_ \n\nConfirmed Cases : *{data["cases"]}* \n\nToday Cases : *{data["todayCases"]}* \n\nDeaths : *{data["deaths"]}* \n\nRecovered : *{data["recovered"]}* \n\nActive Cases : *{data["active"]}* \n\n*Type one of the option given below to know more*\n *World*. Covid-19 statistics *Worldwide*. \n *Ind*. Covid-19 cases in *India*. \n *Chi*. Covid-19 cases in *China*. \n *Usa*. Covid-19 cases in *USA*. \n *Ita*. Coronavirus cases in *Italy*. \n *Aus*. Coronavirus cases in *Australia*. \n *Jap*. Coronavirus cases in *Japan*. \n *F*. How does it *Spread*? \n *G*. *Preventive measures* to be taken.\n\nType *Menu* to view the Main Menu'
        else:
            text = 'I could not retrieve the results at this time, sorry.'
        msg.body(text)
        responded = True

    elif 'Aus' in incoming_msg or 'Australia' in incoming_msg:
        # return cases in italy
        r = requests.get(
            'https://coronavirus-19-api.herokuapp.com/countries/australia')
        if r.status_code == 200:
            data = r.json()
            text = f'_Covid-19 Cases in Australia_ \n\nConfirmed Cases : *{data["cases"]}* \n\nToday Cases : *{data["todayCases"]}* \n\nDeaths : *{data["deaths"]}* \n\nRecovered : *{data["recovered"]}* \n\nActive Cases : *{data["active"]}* \n\n*Type one of the option given below to know more*\n *World*. Covid-19 statistics *Worldwide*. \n *Ind*. Covid-19 cases in *India*. \n *Chi*. Covid-19 cases in *China*. \n *Usa*. Covid-19 cases in *USA*. \n *Ita*. Coronavirus cases in *Italy*. \n *Aus*. Coronavirus cases in *Australia*. \n *Jap*. Coronavirus cases in *Japan*. \n *F*. How does it *Spread*? \n *G*. *Preventive measures* to be taken.\n\nType *Menu* to view the Main Menu'
        else:
            text = 'I could not retrieve the results at this time, sorry.'
        msg.body(text)
        responded = True

    elif 'Jap' in incoming_msg or 'Japan' in incoming_msg:
        # return cases in italy
        r = requests.get(
            'https://coronavirus-19-api.herokuapp.com/countries/japan')
        if r.status_code == 200:
            data = r.json()
            text = f'_Covid-19 Cases in Japan_ \n\nConfirmed Cases : *{data["cases"]}* \n\nToday Cases : *{data["todayCases"]}* \n\nDeaths : *{data["deaths"]}* \n\nRecovered : *{data["recovered"]}* \n\nActive Cases : *{data["active"]}* \n\n*Type one of the option given below to know more*\n *World*. Covid-19 statistics *Worldwide*. \n *Ind*. Covid-19 cases in *India*. \n *Chi*. Covid-19 cases in *China*. \n *Usa*. Covid-19 cases in *USA*. \n *Ita*. Coronavirus cases in *Italy*. \n *Aus*. Coronavirus cases in *Australia*. \n *Jap*. Coronavirus cases in *Japan*. \n *F*. How does it *Spread*? \n *G*. *Preventive measures* to be taken.\n\nType *Menu* to view the Main Menu'
        else:
            text = 'I could not retrieve the results at this time, sorry.'
        msg.body(text)
        responded = True

    elif 'F' in incoming_msg:
        text = f'_Coronavirus spreads from an infected person through_ \n\nSmall droplets from the nose or mouth which are spread when a person coughs or sneezes \n\nTouching an object or surface with these droplets on it and then touching your mouth, nose, or eyes before washing your hands \n\nClose personal contact, such as touching or shaking hands \nPlease watch the video for more information \nhttps://youtu.be/0MgNgcwcKzE \n\n*Type one of the option given below to know more*\n\n *World*. Covid-19 statistics *Worldwide*. \n *Ind*. Covid-19 cases in *India*. \n *Chi*. Covid-19 cases in *China*. \n *Usa*. Covid-19 cases in *USA*. \n *Ita*. Coronavirus cases in *Italy*. \n *Aus*. Coronavirus cases in *Australia*. \n *Jap*. Coronavirus cases in *Japan*. \n *F*. How does it *Spread*? \n *G*. *Preventive measures* to be taken.\n\nType *Menu* to view the Main Menu'
        msg.body(text)
        msg.media(
            'https://user-images.githubusercontent.com/34777376/77290801-f2421280-6d02-11ea-8b08-fdb516af3d5a.jpeg'
        )
        responded = True

    elif 'G' in incoming_msg:
        text = f'_Coronavirus infection can be prevented through the following means_ \nClean hand with soap and water or alcohol-based hand rub \nhttps://youtu.be/EJbjyo2xa2o \n\nCover nose and mouth when coughing & sneezing with a tissue or flexed elbow \nhttps://youtu.be/f2b_hgncFi4 \n\nAvoid close contact & maintain 1-meter distance with anyone who is coughing or sneezin \nhttps://youtu.be/mYyNQZ6IdRk \n\nIsolation of persons traveling from affected countries or places for at least 14 day \nhttps://www.mohfw.gov.in/AdditionalTravelAdvisory1homeisolation.pdf \n\nQuarantine if advise \nhttps://www.mohfw.gov.in/Guidelinesforhomequarantine.pdf \n\n*Type one of the option given below to know more*\n\n *World*. Covid-19 statistics *Worldwide*. \n *Ind*. Covid-19 cases in *India*. \n *Chi*. Covid-19 cases in *China*. \n *Usa*. Covid-19 cases in *USA*. \n *Ita*. Coronavirus cases in *Italy*. \n *Aus*. Coronavirus cases in *Australia*. \n *Jap*. Coronavirus cases in *Japan*. \n *F*. How does it *Spread*? \n *G*. *Preventive measures* to be taken.\n\nType *Menu* to view the Main Menu'
        msg.body(text)
        msg.media(
            'https://user-images.githubusercontent.com/34777376/77290864-1c93d000-6d03-11ea-96fe-18298535d125.jpeg'
        )
        responded = True

    elif responded == False:
        msg.body('I only know about corona, sorry!')

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

response = MessagingResponse()
response.message('This is message 1 of 2.')
response.message('This is message 2 of 2.')

print(response)
def _send_not_found():
    response = MessagingResponse()
    response.message(NOT_FOUND_MESSAGE)
    return str(response)
def sms_twiml(question):
    response = MessagingResponse()
    response.message(question.content)
    response.message(SMS_INSTRUCTIONS[question.kind])
    return str(response)
Beispiel #44
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 #45
0
def sms():
    #get info about the users's incoming message
    message = request.form['Body']

    if "SMSnet" in lower( message)
    
    responseParas = urlToParagraphs(message_body)
    responseStr = responseParas[0]
    
    #Construct a response message
    resp = MessagingResponse()
    resp.message(responseStr)
    print(responseStr)
    return str(resp)


def searchResults(query):
    #Searches Google
    r = requests.get("https://www.googleapis.com/customsearch/v1?key=AIzaSyDUWG4it4VI2Q-OfjuO0_sKAqNV1MxU7Xg&cx=016941051599191875790:7bkp8je7amz&q="+query)

    searchResultsStr = json.loads(r.text)["items"]
    searchResults = []
    for i in range(3):
        searchResults.append({"title" : searchResultsStr[i]["title"],
            "website" : searchResultsStr[i]["displayLink"],
            "snippet" : searchResultsStr[i]["snippet"],
            "url" : searchResultsStr[i]["formattedUrl"]})

    c = 1
    responseStr = ""
    for item in searchResults:
        responseStr += str(c) + ") "
        responseStr += item["title"] + "\n" + item["snippet"].strip('\n') + "\n" + item["website"]
        responseStr += "\n"
        c += 1
    return searchResults, responseStr


def urlToParagraphs(url):
    try:
        headers = {}
        headers['User-Agent'] = "Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1312.27 Safari/537.17"
        req = urllib.Request(url, headers=headers)
        resp = urllib.urlopen(req)
        respData = resp.read()
        paragraphs = re.findall(r'<p>(.*?)</p>', str(respData))
        parsed = []

        for para in paragraphs:
            a = re.sub(r'\<[^>]*\>', '', para)
            b = re.sub(r'&#9.*?93;', '', a)
            c = b.replace('\\n', '')
            parsed.append(c)
        return parsed

    except Exception as e:
        print(str(e))
        return []


def translate(text, targetLang):
    translate_client = translate.Client()
    translation = translate_client.translate(text, target_language=targetLang)
    return translation


if __name__ == "__main__":
    app.run(debug=True)
Beispiel #46
0
def sms_reply():

    db_update = {}
    sender = request.values.get('From')
    sender_msg = request.values.get('Body')
    tenant = request.values.get('To')
    db_update['sender'] = sender
    db_update['tenant'] = tenant
    db_update['last_updated_by'] = 'customer'

    now = datetime.now(timezone.utc)
    settings = {}
    doc = db.collection("settings").document(tenant).get()
    if doc.exists:
        settings = doc.to_dict()
    else:
        logging.warning("No settings found")
        abort(500)

    if 'dndEnabled' in settings and settings['dndEnabled']:
        resp = MessagingResponse()
        resp.message(
            settings.get(
                'dndMessage',
                'sorry, we are unavailable, please call our main number'))
        return str(resp)

    session_id = ''
    current_status = ''

    session_query = db.collection('sessions').where(
        'sender', '==', sender).where('session_active', '==', True).order_by(
            'last_session_start',
            direction=firestore.Query.DESCENDING).limit(1)
    sessions = [s for s in session_query.stream()]
    # logging.info(len(sessions))
    if sessions:
        data = sessions[0].to_dict()
        session_id = data['session_id']
        current_status = data['status']
        if (now - data['last_message_time']) > timedelta(hours=2):
            db.collection('sessions').document(session_id).update({
                'status':
                'expired',
                'session_active':
                False
            })
            session_id = ''
        if data['last_updated_by'] == 'system':
            # only update last message time to now if it is the first response to system
            db_update['last_message_time'] = now

    if not session_id:
        # new session
        session_id = str(uuid4())
        current_status = 'arrived'
        # db_update['session_id'] = session_id = str(uuid4())
        db_update['sender'] = sender
        db_update['session_id'] = session_id
        db_update['status'] = "arrived"
        db_update['last_session_start'] = now
        db_update['session_active'] = True
        db_update['first_message'] = sender_msg
        db_update['last_message_time'] = now
        db_update['last_message'] = str(sender_msg)
    else:
        db_update['status'] = "reply"
        # don't update last_message timestamp for customer reply
        # db_update['last_message_time'] = now
        db_update['last_message'] = str(sender_msg)

    # Get reply for status
    reply = ''
    status_stream = db.collection("statuses") \
        .where("label", "==", db_update['status']) \
        .where('tenant', '==', tenant) \
        .limit(1).stream()
    statuses = [s for s in status_stream]

    # logging.info(status_doc.exists)

    if not len(statuses):
        reply = 'oops, we are having some technical issues [nothing for {}]'.format(
            db_update['status'])
    else:
        status_doc = statuses[0]
        reply = status_doc.to_dict()["response"]
    # if not reply:
    #     reply = 'oops, we are having some technical issues [blank for {}]'.format(db_update['status'])

    added_messages = [{
        "status": current_status,
        "from": "customer",
        "message": db_update['last_message'],
        "time": now,
    }]
    resp = ''
    if reply != '':
        """Respond to incoming calls with a simple text message."""
        # Start our TwiML response
        resp = MessagingResponse()
        # Add a message
        # resp.message(reply, action=callback_base + session_id)
        resp.message(reply)
        added_messages.append({
            "status": db_update['status'],
            "from": "system",
            "message": reply,
            "time": now,
        })

    db_update['messages'] = firestore.ArrayUnion(added_messages)
    # logging.info(db_update)
    if sessions:  # session existed
        db.collection("sessions").document(session_id).update(db_update)
    else:
        db.collection("sessions").document(session_id).set(db_update)
    db.collection("sessions").document(session_id)
    if reply:
        return str(resp)
    return ('', 204)
def sms_start():

    # Pega os parâmetros provindos do Twilio
    from_number = request.values.get('From')
    message_body = request.values.get('Body')
    to_number = request.values.get('To')

    # Instancia servico Twilio
    account_sid = '{your twilio service id}'
    auth_token = '{your twilio auth token}'

    twilio_client = Client(account_sid, auth_token)

    # print(request.values)

    try:
        assistant
    except UnboundLocalError:
        # instancia serviço do waston assistant caso não tenha sido
        create_assistant()
    except NameError:
        create_assistant()

        # Essa parte está responsável para gerenciar múltiplas conversas simultâneas

    if sessionList.checkKeyExistance(from_number) != True:
        session = create_session(workspace_id, assistant_id, assistant)
        json_string = json.dumps(session)
        json_dict = json.loads(json_string)
        session_id = json_dict.get("session_id")
        sessionList.addNewSession(session_id, from_number)
        session_id = sessionList.getIidByKey(from_number)
    else:
        session_id = sessionList.getIidByKey(from_number)

    # Inicializa variáveis utilizadas pelo chat
    user_input = ''
    context = {}
    current_action = ''

    # Principal loop de entrada/saída:
    while current_action != 'end_conversation':
        while True:
            # Captura mensagem do cliente para o chatbot
            response = assistant.message(
                workspace_id=workspace_id,
                assistant_id=assistant_id,
                session_id=session_id,
                input={
                    'text': message_body},
                context=context).get_result()  # Gera resposta do chatbot

            # INICIO FUNÇOES DE LOG
            print("####----------Round Start-----------####")
            print("INPUT")
            print("      Mensagem de " + from_number
                  + ": '" + message_body + "'")
            if len(dict_digger.dig(response, 'output', 'intents')) != 0:
                print("      Intenções: "
                      + str(dict_digger.dig(response, 'output', 'intents', 0, 'intent')))
                if 'General_Ending' == dict_digger.dig(response, 'output', 'intents', 0, 'intent'):
                    current_action = 'end_conversation'
                    print(current_action)

            if len(dict_digger.dig(response, 'output', 'entities')) != 0:
                print("      Entidades: "
                      + str(dict_digger.dig(response, 'output', 'entities', 0, 'entity')))

            print("      Contexto: " + str(dict_digger.dig(response, 'context')))
            # FIM FUNÇOES DE LOG

            # INICIO FUNÇOES DE LOG
            print("OUTPUT")

            if len(dict_digger.dig(response, 'output', 'intents')) != 0:
                print("      Intenções: "
                      + str(dict_digger.dig(response, 'output', 'intents', 0, 'intent')))

            if len(dict_digger.dig(response, 'output', 'entities')) != 0:
                print("      Entidades: "
                      + str(dict_digger.dig(response, 'output', 'entities', 0, 'entity')))

            print("      Contexto: " + str(dict_digger.dig(response, 'context')))

            reponse_text = str(dict_digger.dig(
                response, 'output', 'generic', 0, 'text'))
            print("      Resposta do Bot: '" + reponse_text + "'")
            # FIM FUNÇOES DE LOG

            # instancia resposta no twilio
            resp = MessagingResponse()

            # Define mensagem de resposta twilio
            resp.message(reponse_text)

            # Atualize o contexto armazenado com o recebido mais recentemente do diálogo.
            context = dict_digger.dig(response, 'context')
            print("####----------Round End-----------####")

            # envia respota twilio
            return str(resp)

    # Finaliza sessão de conversa em caso de intenção de despedida
    if current_action == 'end_conversation':
        print("####----------Session End-----------####")
        response = service.delete_session(
            assistant_id=assistant_id,
            session_id=session_id
        ).get_result()
def hello_monkey():
    """Respond to incoming calls with a simple text message."""

    resp = MessagingResponse()
    resp.message("Hello, Mobile Monkey")
    return str(resp)
Beispiel #49
0
def sms():

    # get number and message body
    from_number = request.form['From']
    to_number = request.form['To']
    text = request.form['Body'].strip()
    resp = MessagingResponse()
    today = date.today()

    # broad error handling
    try:

        # check if text receieved by legacy Do number
        if to_number=="+18036761234":
            resp.message(wrong_number_text())

        # otherwise proceed
        else:

            # load user to check if in DB
            user = User.query.filter_by(phone_number=from_number).first()

            # if new user...
            if user==None:

                # add to db
                user = User(phone_number=from_number)
                db.session.add(user)
                db.session.commit()

                # welcome messaging and make or break prompt
                resp.message(welcome_text())

            # if existing user
            elif user!=None:

                # load goal to check if in DB
                goal=Goal.query.filter_by(user_id=user.id).first()

                # if no goal yet
                if goal==None:

                    # catch if response is something other than MAKE or BREAK
                    if text.lower()!='make' and text.lower()!='break':
                        resp.message(make_or_break_error_text())

                    # if MAKE or BREAK received create new goal
                    elif text.lower()=='make' or text.lower()=='break':
                        # save goal to DB without description
                        goal = Goal(goal_type=text.lower(),user_id=user.id)
                        db.session.add(goal)
                        db.session.commit()
                        # prompt for description
                        resp.message(desc_prompt_text(text.lower()))

                # if goal without description save description and send confirmation prompt
                elif goal!=None:

                    # if MAKE or BREAK received create new goal
                    if text.lower()=='make' or text.lower()=='break':
                        # save goal to DB without description
                        goal.goal_type=text.lower()
                        goal.description=None
                        goal.active=False
                        db.session.commit()
                        # prompt for description
                        resp.message(desc_prompt_text(text.lower()))

                    # if goal without description, capture description
                    elif goal.description==None:
                        goal.description=text
                        db.session.commit()
                        resp.message(goal_confirmation_text(text.lower(),goal.goal_type))

                    # if goal with description
                    elif goal.description!=None:

                        # but is not active (pending)
                        if goal.active==False:

                            #check for confirmation or start or similar text
                            if text.lower()=='start' or text.lower()=='yes' or text.lower()=='unstop':
                                goal.start_date=today
                                goal.active=True
                                db.session.commit()
                                resp.message(goal_active_text())

                            # if goal pending and other response received
                            elif text.lower()!='start':
                                resp.message(activation_error_text())

                        # if active goal
                        elif goal.active==True:

                            # check if stop or similar received
                            if text.lower()=='stop' or text.lower()=='stopall' or text.lower()=='unsubscribe' or text.lower()=='cancel' or text.lower()=='end' or text.lower()=='quit':

                                # set goal to inactive so that user won't receive daily_checkins
                                goal.active = False
                                db.session.commit()

                            # if goal response received
                            elif text.lower()=='y' or text.lower()=='yes' or text.lower()=='n' or text.lower()=='no':

                                # parse response
                                response = get_achieved(goal,text)

                                #load current history to check if in DB
                                current_history = History.query.filter_by(date=today, goal_id=goal.id).first()

                                # check if existing history item, update DB and respond
                                if current_history==None:
                                    history = History(date = today, achieved=response, goal_id=goal.id)
                                    db.session.add(history)
                                elif current_history!=None:
                                    current_history.achieved = response
                                db.session.commit()

                                # send response
                                histories = History.query.filter_by(goal_id=goal.id).all()
                                count = get_count(histories)
                                streak = get_streak(histories)
                                resp.message(achievement_confirmation_text(count,streak,goal.start_date,today))


    # if response fails send generic error message
    except:
        resp.message(down_text())

    return str(resp)
Beispiel #50
0
def sms_reply():

    account_sid = 'AC1bed70d1d2c07937339fd20ff5f3761d'
    auth_token = 'ee1898e00fc80229b8d8a8a28426afb1'
    client = Client(account_sid, auth_token)
    from_ = request.form.get('From')
    body_ = request.form.get('Body')
    print(body_)
    print(request.form)
    to = from_
    resp = MessagingResponse()

    if from_ not in user_dict.keys():
        user_dict[from_] = {}

        reponse = type_message[1]

    compteur_formulaire = len(user_dict[from_]) + 1
    """Respond to incoming with a simple text message."""

    if compteur_formulaire == 1:
        print(user_dict)
        # print(request.form.get('body'))
        print(body_)
        user_dict[from_][compteur_formulaire] = request.form.get('Body')
        reponse = type_message[2]

    elif compteur_formulaire == 2:
        print(user_dict)
        # print(request.form.get('body'))
        print(body_)
        user_dict[from_][2] = request.form.get('Body')
        reponse = type_message[3]

    elif compteur_formulaire == 3:
        print(user_dict)
        # print(request.form.get('body'))
        print(body_)
        proposition1 = request.form.get('Body')
        if proposition1 == 1:
            user_dict[from_][3] = 'Masculin'
        else:
            user_dict[from_][3] = 'Feminin'
        reponse = type_message[4]

    elif compteur_formulaire == 4:
        user_dict[from_][3] = request.form.get("Body")
        # print(request.form.get("body"))
        print(body_)
        reponse = type_message[5]

    if compteur_formulaire in list_of_simpleInput:
        "ffff"
    elif compteur_formulaire in list_of_dateInput:
        "fff"

    elif compteur_formulaire in list_of_multipleChoiceInput:
        "ddf"

    message = client.messages.create(from_='whatsapp:+14155238886',
                                     body=reponse,
                                     to=to)
    print("####", message.sid)

    resp.message("")

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




    forum_message = "Please join 'Kobo Forum' WhatsApp Group to connect with other like minded people"
    contract_message = "Kobo\r\n Contact number: +234-802-5557-8 \r\n Email: [email protected] \r\n Address: 1,Yusuf Oladehinde Street \r\n Ifako Ijaiye \r\n Lagos \r\n"
    loantemplate_message = "Please copy and edit the below template. Once complete send back with the word LOAN at the start \r\n" \
                           "Name: <Your full name here>,\r\n" \
                           "Age: <Your age>\r\n" \
                           "Date of Birth: <dd/mm/yyyy>\r\n" \
                           "Contact Number: <include dial code>\r\n" \
                           "Breif: <What bussiness do you run>\r\n" \
                           "Address: <Please enter your address>\r\n" \
                           "Zip Code: <Zip code>\r\n" \
                           "Amount Required: <Amount required in naira>\r\n"
    receivedloanrequest_message = "We have reviced your loan and its currently being proccesed. We will contact you in 5 to 10 working days"
    resources_message = "Create a Business Budget in 5 Simple Steps: https://www.freshbooks.com/blog/the-5-step-plan-to-creating-a-balanced-business-budget\r\n" \
                        "How to Effectively Pitch Business Ideas to Investors: https://medium.com/swlh/how-to-effectively-pitch-business-ideas-to-investors-dd76661b02f1 \r\n" \
                        "How to calculate company income tax in Nigeria Read more: https://www.legit.ng/1179976-how-calculate-company-income-tax-nigeria.html \r\n" \
                        "List of accelerators / incubators / startups programs in Nigeria: https://blog.accounteer.com/list-of-accelerators-incubators-startups-programs-in-nigeria-d2ce1eac74c7"
    milestone_message = "You currently have 10 days to reach your goal"
    help_message = "Key words to send and use our whats app: \r\n" \
                  "Forum = This will send you the name of our Forum WhatsApp group so you can join it \r\n\r\n" \
                  "Contact = Will send you our contact details \r\n\r\n" \
                  "Template = Will send you a Loan template that you can copy and edit and send back with the key word LOAN, and we can start processing it \r\n\r\n" \
                  "Resources = Will send you a list of helpful links to aid you bussniss \r\n\r\n " \
                  "Milestone = Will send you how many days your have leave to reach your milestone \r\n\r\n" \
                  "Pay: <Money amount> = Will allow you to pay some of your loan back"

    # Create reply
    resp = MessagingResponse()


    if msg == "Forum":
        resp.message(forum_message.format(msg))
    if "LOAN" in msg:
        resp.message(receivedloanrequest_message.format(msg))
    if "Pay:" in msg:
        payment = msg.split(":")
        payment = float(payment[1])
        amountLeft = str(40000 - payment)
        message = "You have: " + amountLeft + " to pay of your loan"
        resp.message(message.format(msg))
    elif msg == "Contact":
        resp.message(contract_message.format(msg))
    elif msg == "Template":
        resp.message(loantemplate_message.format(msg))
    elif msg == "Resources":
        resp.message(resources_message.format(msg))
    elif msg == "Milestone":
        resp.message(milestone_message.format(msg))
    elif msg == "Help":
        resp.message(help_message.format(msg))




    return str(resp)
Beispiel #52
0
def bot():
    incoming_msg = request.values.get('Body', '').lower()
    resp = MessagingResponse()
    msg = resp.message()
    responded = False
    if 'quote' in incoming_msg:
        # return a quote
        r = request.get(quote_url)
        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
    if 'cat' in incoming_msg:
        # return a cat pic
        msg.media('https://cataas.com/cat')
        responded = True
    if 'catfact' in incoming_msg:
        #return a hot fact about cats
        response = request.get(catfact_url)
        if response.status_code == 200:
            result = json.loads(response.text)
            p = result['data']
            fact = p[0]['fact']
            msg.body(fact)
            responded = True
        else:
            msg.body = ('I couldn'
                        't get a cat fact right now, try again later.')
            responded = True
    if 'space' in incoming_msg:
        response = request.get(apod_url + nasa_key)
        if response.status_code == 200:
            data = response.json()
            msg.body(f'{data["date"]} {data["explanation"]}')
            msg.media(data["hdurl"])
            responded = True
        else:
            msg.body('Sorry, I couldn'
                     't get a space pic right now, try again later')
            responded = True
        #responded = True
    if 'baby yoda' in incoming_msg:
        msg.body('https://www.youtube.com/results?search_query=baby+yoda')
        responded = True
    if not responded:
        # get SMS metadata
        msg_from = request.values.get("From", None)
        msg = request.values.get("Body", None)

        # prepare API.ai request
        req = ai.text_request()
        req.lang = 'en'  # optional, default value equal 'en'
        req.query = msg

        # get response from API.ai
        api_response = req.getresponse()
        responsestr = api_response.read().decode('utf-8')
        response_obj = json.loads(responsestr)

        if 'result' in response_obj:
            response = response_obj["result"]["fulfillment"]["speech"]
            # send SMS response back via twilio
            resp = client.messages.create(to=msg_from,
                                          from_=ACCOUNT_NUM,
                                          body=response)
    return str(resp)
Beispiel #53
0
def as_twilio_response(message: str) -> str:
    resp = MessagingResponse()
    msg = resp.message()
    msg.body(message)
    return str(resp)
Beispiel #54
0
def bot():
    print(request.values)
    from_tel = request.values.get('From', '').replace("whatsapp:", "")
    to_tel = request.values.get('To', '').replace('whatsapp:', "")
    if from_tel == '+14155238886':
        chatbot_tel = from_tel
        user_tel = to_tel
    else:
        chatbot_tel = to_tel
        user_tel = from_tel
    print("Numero do user:"******"Esse é o numero do bot: " + chatbot_tel)
    query = "SELECT nome FROM user_info WHERE telefone = %s"
    cursor.execute(query, (user_tel,))
    query_results = cursor.fetchall()
    if cursor.rowcount != 0:
        for nome in query_results:
            full_name = nome
            first_name = str(full_name).split()[0]
            session['nome'] = first_name
            session['user'] = 1
    incoming_msg = request.values.get('Body', '')
    if incoming_msg == 'RESET':
        session.clear()
        responded = True
    else:
        responded = False
    resp = MessagingResponse()
    msg = resp.message()
    try:
        if session['user'] == 1:
            responded = True
            if session['path'] == 'receive':
                if session['purpose'] == 'name':
                    # REGISTRO NOME
                    full_name = incoming_msg
                    msg.body("Obrigado por escolher contar com nossa ajuda," + full_name + '''.
Nosso objetivo é conseguir te diagnosticar nas matérias para fornecer o material adequado à você! 
Essas são as opções de testes até então:
Digite 1 se você quer um teste de matemática!(*por favor, digite somente o número*)''')
                    query_name = "INSERT INTO user_info(telefone, nome) values(%s,%s)"
                    values_name = [user_tel, full_name]
                    cursor.execute(query_name, values_name)
                    db.commit()
                    session['path'] = 1
                    session['purpose'] = 'Nada'
                elif session['purpose'] == 'answers':
                    # ENVIO QUESTÕES
                    respostas = incoming_msg
                    respostas = respostas.upper()
                    # Aqui vem análise de respostas
                    # Calculos doidos
                    msg.body('''Em algum momento teremos uma nota pra você, e uma lista de assuntos em ordem crescente de % de acerto
1 - Geometria - %
2 - Algebra Básica - %
3 - Mat. Financeria - %
4 - Alglin - %
5 - Grupos e Aneís - %
Sua proficiência em Matemática vale:
Digite o número que deseja focar essa semana.''')
                    session['path'] = 2
                    session['purpose'] = 'Nada'
            elif session['path'] == 1:
                if incoming_msg == '1':
                    # TESTE MATEMÁTICA
                    query_simulado_faceis = "SELECT nome_drive FROM math_questions WHERE dificuldade<5"
                    query_simulado_medias = "SELECT nome_drive FROM math_questions WHERE dificuldade<5"
                    query_simulado_dificeis = "SELECT nome_drive FROM math_questions WHERE dificuldade<5"
                    escolha_facil = random.sample(range(1, len(query_simulado_faceis)), 5)
                    nome_faceis = []
                    escolha_media = random.sample(range(1, len(query_simulado_medias)), 3)
                    nome_medias = []
                    escolha_dificil = random.sample(range(1, len(query_simulado_dificeis)), 2)
                    nome_dificeis = []
                    cursor.execute(query_simulado_faceis)
                    questoes_simu = cursor.fetchall()
                    print(cursor.rowcount)
                    i = 1
                    for nome_drive in questoes_simu:
                        if i in escolha_facil:
                            nome_faceis.append(nome_drive)
                        i = i + 1
                    cursor.execute(query_simulado_medias)
                    questoes_simu = cursor.fetchall()
                    i = 1
                    for nome_drive in questoes_simu:
                        if i in escolha_media:
                            nome_medias.append(nome_drive)
                        i = i + 1
                    cursor.execute(query_simulado_dificeis)
                    questoes_simu = cursor.fetchall()
                    i = 1
                    for nome_drive in questoes_simu:
                        if i in escolha_dificil:
                            nome_dificeis.append(nome_drive)
                        i = i + 1
                    # AQUI ENTRA XANDE CRIANDO HTML
                    # retornou um arquivo html no meu diretorio.
                    file_path = 'file.html'
                    pdfkit.from_file(input='/home/pedro/PycharmProjects/hackathon/file.html',
                                     output_path='static/out.pdf')
                    msg.media('/')
                    session['path'] = 'receive'
                    session['purpose'] = 'answers'
                    # FINAL ENVIO SIMULADO
            elif session['path'] == 2:
                if incoming_msg is not None:
                    msg.body('''Aqui terá uma recomendação massa de vídeos
Após estudo do material, venha novamente testar seus conhecimentos!''')
                    session.clear()
    except KeyError:
        if not responded:
            msg.body('''Seja bem-vindo ao seu ajudante virtual de estudo!
Nosso objetivo é criar uma curadoria personalizada com base no seu conhecimento em cada matéria, facilitando
seu estudo à distância de forma inteligente, buscando sempre auxiliar na construção gradativa de conteúdo para que você não se sinta nem pouco desafiado nem desestimulado!
Fazemos isso com um teste diagnóstico de 10 questões de uma matérias específica. Com base nos seus acertos, vamos começar a predizer seu nível de conhecimento por meio da TRI!
Sim, o mesmo método usado pelo *ENEM*. Dessa forma conseguirmos medir sua proficiência em certa matéria, garantindo que você tenha conteúdo de acordo com seu nível!
Percebemos que você *não possui cadastro conosco*, por favor, nos diga na sua próxima mensagem qual seu nome.''')
            session['user'] = 1
            session['path'] = 'receive'
            session['purpose'] = 'name'
        else:
            msg.body('''Tivemos um problema em nossa base de dados, contudo, ainda temos seu cadastro!

Essas são as opções de testes até então:
Digite 1 se você quer um teste de matemática!(*por favor, digite somente o número*)''')
            session['user'] = 1
            session['path'] = 1
    return str(resp)
from twilio.twiml.messaging_response import Message, MessagingResponse

response = MessagingResponse()
response.message('I\'m hungry!')

print(response)