예제 #1
0
def handle_bot_queries(request):
    resp = MessagingResponse()
    message = Message()
    brain_response = controller.handle_whatsapp_user_input(request)
    message.body(brain_response)
    resp.append(message)
    return resp
예제 #2
0
def sms_reply():
    msg = request.form.get('Body')
    sender = request.form.get('From')
    # The reply object
    resp = MessagingResponse()

    #Calling function to generate reply
    rec_reply = fetch_reply(msg, sender)

    # If a simple string is returned print that string
    if type(rec_reply) == str:
        message = Message()
        message.body(rec_reply)
        resp.append(message)
        return str(resp)

    # If 2 objects (string and url are returned append the media to message and send)
    for row in rec_reply:
        message = Message()
        link = requests.get('http://tinyurl.com/api-create.php?url={}'.format(
            row['link'])).content.decode('utf-8')
        message.body("{}\n{}".format(row['title'], link))
        if row['media']:
            message.media(row['media'])
        resp.append(message)
    return str(resp)
예제 #3
0
def get_random_band_info():
    url = '{}/band/random'.format(api_base_urls['metal_api'])
    params = {'api_key': api_keys['metal_api']}

    # Make the request to the metal API.
    # Convert the response JSON to a dictionary we can work with.
    response = requests.get(url, params).json()

    # Grab the relevant data from the JSON response.
    name = response['data']['band_name']
    photo = response['data']['photo']
    genre = response['data']['details']['genre']
    country = response['data']['details']['country of origin']

    # Create a TwiML response object for a Twilio SMS response.
    response = MessagingResponse()
    message = Message()

    # Write out the body of the text message.
    message.body('Check out this {} band from {} named {}'.format(
        genre, country, name))

    # Add the band's photo to the message. This is just a URL to an image.
    message.media(photo)

    # Add our message object to the TwiML response and return the object.
    response.append(message)
    return response
예제 #4
0
def sms_reply():
    """Respond to incoming calls with a simple text message."""

    # G_Drive connection 
    db_connection = DB.get_connection()

    reply = str()
    # Fetch the message
    req = request.form
    msg = str(req.get('Body')).lower()
    sender = req.get('WaId')

    # Process the response to a given message
    try:
        reply = RM.process_response(msg, sender, db_connection)
    except DB.APIError:
        reply = 'Server bussy...\n Please wait 2 minutes after new request'
    del db_connection

    # Create reply
    resp = MessagingResponse()
    message1 = Message()
    message1.body(reply)
    # message1.media('https://demo.twilio.com/owl.png')

    resp.append(message1)
    return str(resp)
예제 #5
0
    def InBoundMessageResponse(self):
        # Get text message body from POST request
        body = request.values.get('Body', None)
        print("Received Message: %s" % str(body))

        # Craft Twilio Response
        response = MessagingResponse()
        message = Message()
        rstring = None

        if body == None:
            print("No Body!!! Error")
            return render_template('twilio_response.html')

        if body.lower().startswith("limit="):
            self.floor = None
            self.limit = int(body[len("limit="):])
            rstring = "Setting Temp Limit to {0} degrees {1}".format(
                self.limit, os.environ["ALERT_LOCAL"])
        elif body.lower().startswith("floor="):
            self.limit = None
            self.floor = int(body[len("floor="):])
            rstring = "Setting Temp Floor to {0} degrees {1}".format(
                self.floor, os.environ["ALERT_LOCAL"])
        elif body.lower().startswith("disable"):
            rstring = "Disabling Alerts!"
            self.limit = None
            self.floor = None
        else:
            rstring = "Respond with message starting with `limit=/floor=/stop`, to set an alert!"
        message.body(rstring)
        response.append(message)

        return str(response)
def bot():
    req = request.values
    sender = request.values.get('From', '')
    message_id = request.values.get('SmsSid', '')

    resp = MessagingResponse()
    msg_txt = Message()
    msg_audio = Message()

    message, msg_type = read_message(req, message_id)

    response = requests.post('http://localhost:5005/webhooks/rest/webhook',
                             json={
                                 'sender': sender,
                                 'message': message,
                                 'type': msg_type
                             })
    bot_resp = response.json()

    text, audio = send_message(bot_resp, message_id)
    msg_txt.body(text)
    resp.append(msg_txt)
    if audio:
        msg_audio.media('{}/{}'.format(NGROK_URL, audio))
        resp.append(msg_audio)

    return str(resp)
예제 #7
0
def sms_reply():
    # Fetch the message
    msg = request.form.get('Body')
    sender = request.form.get('From')

    # Create reply
    resp = MessagingResponse()
    recieved_obj = fetch_reply(msg, sender)

    # If the recieved object is from get_weather()
    if isinstance(recieved_obj[0], str):
        message = Message()
        message.body(recieved_obj[0])
        message.media(recieved_obj[1])
        resp.append(message)
        return str(resp)

    # If the recieved object is from get_news()
    for row in recieved_obj:
        message = Message()
        link = requests.get('http://tinyurl.com/api-create.php?url={}'.format(
            row['link'])).content.decode('utf-8')
        message.body("{}\n{}".format(row['title'], link))
        if row['media']:
            message.media(row['media'])
        resp.append(message)
    return str(resp)
예제 #8
0
def inbound_sms():
    """
    Function that receives an SMS and returns necessary information
    """
    response = MessagingResponse()
    # Get the SMS message from the request
    inbound_message = request.form.get("Body")

    # Parse the response based on new lines or period,
    # Returns a list of arguments
    message = parse_inbound(inbound_message)

    # Convert message arguments to be url ready
    ready_message = convert_spaces(message)

    # Create API call
    # Only for Meme related calls
    if len(ready_message) < 3:
        for i in range(3 - len(ready_message)):
            ready_message.append("")
    meme_url = "/Users/Jennie/Desktop/text_meme/testing/marked_image.png"

    # Responds with the meme with the img 
    msg = Message().body("Here is your {} meme".format(message[0])).media(meme_url)
    response.append(msg)

    return Response(str(response), mimetype="application/xml"), 200
예제 #9
0
파일: app.py 프로젝트: ruinanwang/ratchat
def address():
    response = MessagingResponse()
    message = Message()
    user_input = request.values.get('Body', None).replace('\n', ' ')
    user_input_test = user_input.replace(' ', '')
    lat, lon, address = geocoder.geocode(user_input)

    if user_input_test.upper() == 'YES' and 'address' in session:
        db.execute(
            config.db_credentials, config.update_address,
            (session['address'], None, None, None, 0, session['row_id']))
        session['counter'] = 2
        message.body(prompts.options)
    elif user_input_test.isnumeric() or user_input_test.isalpha() or (
            not user_input_test[0].isnumeric()):
        message.body(prompts.partial_address)
    elif lat != None and lon != None and address != None:
        db.execute(config.db_credentials, config.update_address,
                   (user_input, address, lat, lon, 1, session['row_id']))
        session['counter'] = 2
        message.body(prompts.options)
    else:
        session['address'] = user_input
        message.body(prompts.address_error)

    response.append(message)
    return str(response)
예제 #10
0
def sendmsgresp(num, msg):
    if (num != ''):
        response = MessagingResponse()
        message = Message(to=num, from_=config.smsGatewayNumber, body=msg)
        response.append(message)
        response.redirect('https://demo.twilio.com/welcome/sms/')
        print(response)
예제 #11
0
def pro_response():
    # Increment the counter
    counter = session.get('counter', 0)
    counter += 1

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

    response = MessagingResponse()
    message = Message()

    from_number = request.values.get('From')
    from_body = request.values.get('Body')

    if not from_body:
        from_body = 'web form'

    if session['counter'] >= 7:
        message.body(None)
    else:
        message_body = message_response(from_number, from_body)
        message.body(message_body[0])

    response.append(message)

    if message_body[0]:
        return str(response)
    else:
        return '', 204
    def test_text(self):
        r = MessagingResponse()
        r.append('No tags!')

        assert_equal(
            self.strip(r),
            '<?xml version="1.0" encoding="UTF-8"?><Response>No tags!</Response>'
        )
    def test_text(self):
        r = MessagingResponse()
        r.append('No tags!')

        assert_equal(
            self.strip(r),
            '<?xml version="1.0" encoding="UTF-8"?><Response>No tags!</Response>'
        )
예제 #14
0
def post_message_media_webhook():
    """Respond to incoming messages with a MessageResponse instance."""
    # Start our response
    resp = MessagingResponse()
    message = Message()
    message.media(special_pic_two)
    message.body('_Spam_ is, therefore _I_ am.')
    resp.append(message)
    return str(resp)
예제 #15
0
def hello_monkey():
    """
    Respond to incoming calls with a simple text message
    """

    resp = MessagingResponse()
    msg = Message().body("Hello, Mobile Monkey").media("https://demo.twilio.com/owl.png")
    resp.append(msg)
    return str(resp)
    def test_nested_body(self):
        b = Body('Hello World')

        r = MessagingResponse()
        r.append(b)

        assert_equal(
            self.strip(r),
            '<?xml version="1.0" encoding="UTF-8"?><Response><Body>Hello World</Body></Response>'
        )
예제 #17
0
    def test_nested_body(self):
        b = Body('Hello World')

        r = MessagingResponse()
        r.append(b)

        assert_equal(
            self.strip(r),
            '<?xml version="1.0" encoding="UTF-8"?><Response><Body>Hello World</Body></Response>'
        )
    def test_mixed(self):
        r = MessagingResponse()

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

        assert_equal(
            self.strip(r),
            '<?xml version="1.0" encoding="UTF-8"?><Response>before<Child>content</Child>after</Response>'
        )
    def test_mixed(self):
        r = MessagingResponse()

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

        assert_equal(
            self.strip(r),
            '<?xml version="1.0" encoding="UTF-8"?><Response>before<Child>content</Child>after</Response>'
        )
예제 #20
0
    def test_nested_body_media(self):
        b = Body('Hello World')
        m = Media('hey.jpg')

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

        assert_equal(
            self.strip(r),
            '<?xml version="1.0" encoding="UTF-8"?><Response><Body>Hello World</Body><Media>hey.jpg</Media></Response>'
        )
예제 #21
0
def hello_monkey():
    """Respond to incoming texts with a simple text message and store said text in a database."""
    content = request.values.get('Body', None)
    feedback = Feedback(content)
    db.session.add(feedback)
    db.session.commit()
    random_media_url = random.choice(gif_media_urls)
    resp = MessagingResponse()
    msg = Message().body('Thank you for your feedback! - Gen').media(
        random_media_url)
    resp.append(msg)
    return str(resp)
    def test_nested_body_media(self):
        b = Body('Hello World')
        m = Media('hey.jpg')

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

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

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

    return str(resp)

    if __name__ == "__main__":
        app.run(debug=True)
def hello_monkey():
    """Respond to incoming calls with a simple text message."""

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

    return str(resp)

    if __name__ == "__main__":
        app.run(debug=True)
예제 #25
0
def handle_sms():
    user = request.form['From']
    receivedText = request.form['Body']
    resp = MessagingResponse()
    if receivedText == 'gbx':
        gbxData = gbx()
        msg = Message().body(gbxData['Customer Reviews'] + "   " +
                             gbxData['Amazon Launchpad'])
        resp.append(msg)
        return str(resp)
    else:
        msg = Message().body('wrong text bro. try again.')
        resp.append(msg)
        return str(resp)
예제 #26
0
파일: app.py 프로젝트: ruinanwang/ratchat
def options():
    response = MessagingResponse()
    message = Message()
    user_input = request.values.get('Body',
                                    None).replace(' ', '').replace('\n',
                                                                   '').upper()

    if user_input == 'A':
        db.execute(config.db_credentials, config.update_sighting,
                   ('sighting', 'outside', 'alive', 1, session['row_id']))
        session.clear()
        message.body(prompts.done)
    elif user_input == 'B':
        db.execute(config.db_credentials, config.update_sighting,
                   ('sighting', 'inside', 'alive', 1, session['row_id']))
        session.clear()
        message.body(prompts.done)
    elif user_input == 'C':
        db.execute(config.db_credentials, config.update_sighting,
                   ('sighting', 'outside', 'dead', 1, session['row_id']))
        session.clear()
        message.body(prompts.done)
    elif user_input == 'D':
        db.execute(config.db_credentials, config.update_sighting,
                   ('sighting', 'inside', 'dead', 1, session['row_id']))
        session.clear()
        message.body(prompts.done)
    elif user_input == 'E':
        db.execute(config.db_credentials, config.update_evidence,
                   ('evidence', 'chewed', 1, session['row_id']))
        session.clear()
        message.body(prompts.done)
    elif user_input == 'F':
        db.execute(config.db_credentials, config.update_evidence,
                   ('evidence', 'droppings', 1, session['row_id']))
        session.clear()
        message.body(prompts.done)
    elif user_input == 'G':
        db.execute(config.db_credentials, config.update_evidence,
                   ('evidence', 'hole', 1, session['row_id']))
        session.clear()
        message.body(prompts.done)
    else:
        db.execute(config.db_credentials, config.update_evidence,
                   (user_input, None, 0, session['row_id']))
        message.body(prompts.option_error)

    response.append(message)
    return str(response)
예제 #27
0
def sms_reply():
    message_body = request.form['Body'].lower()

    if message_body in api_keywords:
        response = api_keywords[message_body]()
    else:
        response = MessagingResponse()
        message = Message()

        message.body(
            'Thanks for joining my demo! Questions? @Sagnewshreds or [email protected]'
        )
        response.append(message)

    return str(response)
예제 #28
0
def inbound_sms():
    """
    Function that receives an SMS and returns necessary information
    """
    account_sid = os.environ['account_sid']
    auth_token = os.environ['auth_token']

    client = Client(account_sid, auth_token)
    caller_ids = client.outgoing_caller_ids.list()

    response = MessagingResponse()
    # Get the SMS message from the request
    inbound_message = request.form.get("Body")

    # Gets the incoming SMS phone number
    inbound_number = request.form.get("From")
    number_list = [caller.phone_number for caller in caller_ids]
    if inbound_number not in number_list:
        msg = Message().body(
            "Looks like you havent signed up for TextMeme. You can sign up via this link: http://34.210.213.199/sign_up.html#/"
        )
    else:
        # Parse inbound message
        message = parse_inbound(inbound_message)
        meme = message[0]
        top = message[1]
        bot = message[2]

        # Spelling Error Check for Memes

        # Check for START command
        if "Start" == meme:
            msg = Message().body(
                "Welcome to TextMeme! To make a meme, text me the meme name and the top and bottom text you want, seperated by a period."
            )
        else:
            # Check if meme exists, if not let user know
            if meme not in open('meme_list').read():
                msg = Message().body(
                    "Having trouble? Text START to learn how to use or Check our our available memes here: INSERT"
                ).media("http://m.memegen.com/hxg2qb.jpg")
            else:
                # Responds with the meme with the img
                url = 'http://34.210.213.199:8080/api/v1/get_image/' + meme + ':' + top + ':' + bot
                msg = Message().body("Here is your meme").media(url)

    response.append(msg)
    return Response(str(response), mimetype="application/xml"), 200
예제 #29
0
def sms_reply():
    """Respond to incoming calls with a simple text message."""
    # Fetch the message
    print(request.form)
    msg = request.form.get('Body')
    sender = request.form.get('From')
    # Create reply
    resp = MessagingResponse()
    reply = fetch_reply(msg, sender)
    if isinstance(reply, str):
        resp.message(reply)
    elif isinstance(reply, tuple):
        resp.message(reply[0]).media(reply[1])
    else:
        for msg in list(map(lambda x: Message(x), reply)):
            resp.append(msg)
    return str(resp)
예제 #30
0
def inbound_sms():
    message_body = request.form['Body']
    resp = MessagingResponse()

    if message_body.isdigit():
        response_message = 'Taken {0} Martian solar days into the journey.' \
                           .format(message_body)
        photo_url = get_mars_photo_url(message_body)

        msg = Message().body(response_message).media(photo_url)
        resp.append(msg)
    else:
        msg = Message().body(
            'Text a number of solar days into the rover\'s journey.')
        resp.append(msg)

    return str(resp)
def BikelisttoSMS(bikelist: list) -> bool:
    """sample from https://www.twilio.com/docs/sms/twiml
    SAMPLE DOESNT WORK. NOT REQUIRED, USE SMSAdvanced Method"""

    for bike in bikelist:
        if bike[1]:
            messageData = "a new " + str(bike[1]) + " has appeared, Size M"
            print(messageData)

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

            print(response)
    return True
예제 #32
0
def get_random_metal_band_info():
    url = 'http://em.wemakesites.net/band/random'
    params = {'api_key': api_keys['metal']}

    api_response = requests.get(url, params).json()
    name = api_response['data']['band_name']
    genre = api_response['data']['details']['genre']
    country = api_response['data']['details']['country of origin']
    photo = api_response['data']['photo']

    response = MessagingResponse()
    message = Message()
    message.body('Check out this {} band from {} named {}!'.format(
        genre, country, name))
    message.media(photo)
    response.append(message)

    return response
예제 #33
0
def message():
    received_text=request.values.get("Body")
    response = MessagingResponse()
    message = Message()
    sms_text = model.make_short_sentence(200)
    message.body(sms_text)
    # gif_url = get_giphy(
    #     person_name="Donald Trump", tweet=sms_text, gif_type="downsized_still"
    # )
    # message.media(gif_url)
    gif_url = get_giphy(
        person_name="Donald Trump", tweet=received_text, gif_type="downsized_still"
    )
    message.media(gif_url)

    response.append(message)

    return str(response)
예제 #34
0
def sms_reply():
    response = MessagingResponse()
    message = Message()
    message.body("Message Recieved. Help will be on the way")
    response.append(message)
    sms_message = request.form['Body']
    send_message, send_list = sms_message.split(":")
    sender = request.form['From']
    send_list = send_list.split(',')
    if isinstance(send_list, str):
        send_list = [send_list]
    for item in send_list:
        if item == '':
            send_list.remove('')
    if send_list != []:
        if Contact.query.filter_by(number=sender).first():
            modify_contact(sender, ','.join(send_list))
        else:
            create_contact(sender, ','.join(send_list))
    else:
        send_list = db.session.query(Contact).filter(
            Contact.number == request.form["From"]).first().contacts.split(',')
    try:
        State = request.form['FromState']
    except:
        State = False
    try:
        City = request.form['FromCity']
    except:
        City = False
    try:
        Country = request.form['FromCountry']
    except:
        Country = False
    if State and City and Country:
        full_message = send_message + ' from ' + City + ' ' + State + ', ' + Country + ' ' + sender
    else:
        full_message = send_message + ' ' + sender
    for contact_number in send_list:

        export_message = client.messages.create(to='+1' + contact_number,
                                                from_="+16467620371",
                                                body=full_message)
    return str(response)
예제 #35
0
def _send_single_result(employees):
    response = MessagingResponse()
    employee = employees[0]
    employee_data = '\n'.join([employee.full_name,
                               employee.phone_number,
                               employee.email])
    message = Message()
    message.append(Body(employee_data))
    message.append(Media(employee.image_url))
    return str(response.append(message))
예제 #36
0
def inbound_sms():
    """
    Function that receives an SMS and returns necessary information
    """
    response = MessagingResponse()
    # Get the SMS message from the request
    inbound_message = request.form.get("Body")

    # Parse the response based on new lines or period,
    # Returns a list of arguments
    message = parse_inbound(inbound_message)

    # Opens the image, determine width & height for font resizing
    imgFile = "images" + message[0] + ".jpg"
    img = Image.open(imageFile)
    W, H = img.size

    # Variables for message and font
    msg_top = message[1]
    fontsize = 1
    img_fraction = 0.75

    draw = ImageDraw.Draw(img)

    # Loop to determine fontsize
    font = ImageFont.truetype("/Library/Font/Impact.ttf", fontsize)
    while font.getsize(msg)[0] < img_fraction * img.size[0]:
        fontsize += 1
        font = ImageFont.truetype("/Library/Font/Impact.ttf", fontsize)

    # Draw the new meme with given fontsize
    w, h = draw.textsize(msg, font)
    draw.text(((W - w) / 2, 0), msg, font=font)
    draw = ImageDraw.Draw(img)

    img.save("temporary_image.png")

    # Responds with the meme with the img
    msg = Message().body("Here is your {} meme".format(
        message[0])).media("temporary_image.png")
    response.append(msg)

    return Response(str(response), mimetype="application/xml"), 200
    def text_mixed(self):
        r = MessagingResponse()
        r.append('before')
        r.append(Body('Content'))
        r.append('after')

        assert_equal(
            self.strip(r),
            '<?xml version="1.0" encoding="UTF-8"?><Response>before<Body>Content</Body>after</Response>'
        )
예제 #38
0
from twilio.twiml.messaging_response import Body, Media, Message, MessagingResponse

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

print(response)