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)
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)
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)
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 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
def _send_single_result(employees): response = MessagingResponse() employee = employees[0] employee_data = '\n'.join([employee.full_name, employee.phone_number, employee.email]) message = Message() message.append(Body(employee_data)) message.append(Media(employee.image_url)) return str(response.append(message))
def 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)
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)
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)
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
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)
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
def get_blacklisted_response(request): """Analyze the incoming Twilio request to determine whether or not to reject services. We'll only reject services if the user requesting service is on our blacklist. :param obj request: The Django HttpRequest object to analyze. :rtype: HttpResponse. :returns: HttpResponse if the user requesting services is blacklisted, None otherwise. """ try: # get the `From` data from the request's payload. # Only supporting GET and POST. data = request.GET if request.method == 'GET' else request.POST frm = data['From'] caller = Caller.objects.get(phone_number=frm) if caller.blacklisted: twilio_request = decompose(request) if twilio_request.type == 'voice': r = VoiceResponse() r.reject() else: # SMS does not allow to selectively reject SMS. # So, we respond with nothing, and twilio does not forward # the message back to the sender. r = Message() return HttpResponse(str(r), content_type='application/xml') except Exception: pass return None
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
def test_blacklist_works(self): with override_settings(DEBUG=False): request = self.factory.post( self.str_uri, {'From': str(self.blocked_caller.phone_number)}) response = str_view(request) r = Message() self.assertEqual( response.content, str(r).encode('utf-8'), ) with override_settings(DEBUG=True): request = self.factory.post( self.str_uri, {'From': str(self.blocked_caller.phone_number)}) response = str_view(request) r = Message() self.assertEqual( response.content, str(r).encode('utf-8'), ) with override_settings(DEBUG=False): request = self.factory.post( self.verb_uri, { 'From': str(self.blocked_caller.phone_number), 'callsid': 'some-call-sid', }) response = verb_view(request) r = VoiceResponse() r.reject() self.assertEqual( response.content, str(r).encode('utf-8'), ) with override_settings(DEBUG=True): request = self.factory.post( self.verb_uri, { 'From': str(self.blocked_caller.phone_number), 'callsid': 'some-call-sid', }) response = verb_view(request) r = VoiceResponse() r.reject() self.assertEqual( response.content, str(r).encode('utf-8'), )
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 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)
def post(self, *args, **kwargs): question = self.get_argument('Body') from_num = self.get_argument('From') if from_num not in self.sessions: print('New Session @ %s' % from_num) self.sessions[from_num] = {'engine': self, 'entries': []} session = self.sessions[from_num] # Make engine request res = session['engine'].engine.transaction('autosubmitmode', 'autosubmitwaittime', entry=question) print(res) try: # set up active close timer if res.get('autosubmitmode') == 'true' and session.get( 'timer', 0) is not None: session['timer'] = 10 # int(res['autosubmitwaittime']) else: session['timer'] = None except KeyError: print(res) exit() # grab answer text/parts answer = res['text'] # keep convo history session['entries'].append((question, answer)) response = MessagingResponse() for part in answer: message = Message() message.body(str(part)) response.append(message) self.write(str(response)) # store session self.sessions[from_num] = session
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.lower().startswith("limit="): self.limit = int(body[len("limit="):]) rstring = "Setting Alert Limit to {0} degrees {1}".format( self.limit, os.environ["ALERT_LOCAL"]) else: rstring = "Respond with message starting with `limit=` to set an alert!" message.body(rstring) response.append(message) return str(response)
def httpWebHooktoTwilioURL(event, context): print(event) #To have event come up in cloudwatchLogs numMedia = int(event['body']['NumMedia']) if (numMedia == 1): if (event['body']['MediaContentType0'] == 'image/jpeg'): image_url = event['body']['MediaUrl0'] filename = os.path.join( os.getcwd(), Path("../../tmp/{}.jpg".format(event['body']['MessageSid']))) retrieveContent = requests.get(image_url, stream=True) if retrieveContent.status_code == 200: retrieveContent.raw.decode_content = True #Required to ensure file size is not zero with open(filename, 'wb') as f: #writing into file shutil.copyfileobj(retrieveContent.raw, f) with open(filename, 'rb') as image: rekogResponse = rekogClient.recognize_celebrities( Image={'Bytes': image.read()}) print(rekogResponse) bodyContent = "{} celebrities found".format( len(rekogResponse['CelebrityFaces'])) if (len(rekogResponse['CelebrityFaces']) > 0): for celeb in rekogResponse['CelebrityFaces']: bodyContent += "{} {} : {}% match confidence".format( os.linesep, celeb['Name'], celeb['MatchConfidence']) else: bodyContent = "Image type is not JPEG or PNG. Please send only one of these." elif (numMedia > 1): bodyContent = "Please only send one image at a time " elif (numMedia == 0): bodyContent = "Hi, please attach a JPEG or PNG image for facial recognition of celebrities." try: #translator = Translator() response = MessagingResponse() message = Message() #message.body(translator.translate(event['body']['Body'],dest='hi').text) # Pre-tested on googletrans message.body(bodyContent) response.append(message) return response.to_xml() except: return "An Error has occured. Please contact support."
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 respond_sms(): #resp = twilio.twiml.Response() resp = MessagingResponse() body = request.form['Body'] blob = TextBlob(body) message = Message() #resp.message("Thanks for your query --- James Bond the 007") #return str(resp) try: number = int(str(blob)) message.body( "Thanks - You entered number " + str(blob) + ". Your guess is " + str(abs(32 - number)) + " away from the correct answer: 32. We will let you know if your guess is one of the 10 closest very soon. - CHARLES" ) #message.body('Republic of China') #message.media('http://s580789446.onlinehome.us/calligraphy/images/2009-4.JPG') resp.append(message) return str(resp) except: return "Unexpected Error! Please enter only integer from 0 to 60."
def test_black_list_works_class_view(self): with override_settings(DEBUG=False): request = self.factory.post( self.str_class_uri, {'From': str(self.blocked_caller.phone_number)}) response = StrView.as_view()(request) r = Message() self.assertEqual( response.content, str(r).encode('utf-8'), ) with override_settings(DEBUG=True): request = self.factory.post( self.str_class_uri, {'From': str(self.blocked_caller.phone_number)}) response = StrView.as_view()(request) r = Message() self.assertEqual( response.content, str(r).encode('utf-8'), )
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
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 hello_monkey(): """Respond to incoming calls with a simple text message.""" resp = MessagingResponse() msg = Message()\ .body("Hello, Mobile Monkey")\ .media("https://demo.twilio.com/owl.png") resp.append(msg) return str(resp) if __name__ == "__main__": app.run(debug=True)
def sms_reply(): """Respond to incoming calls with a simple text message.""" # Fetch the message start=time.time() msg = request.form.get('Body') phone_no=request.form.get('From') # Create reply reply,opt=fetch_reply(msg,phone_no) if opt==1: resp = MessagingResponse() resp.message(reply) else: # resp = MessagingResponse(to=phone_no) # resp.message("Showing the news") resp = MessagingResponse() print(reply) for i in reply: article=Message() article.body(i['title']+"("+i['releasedAt']+") Link: "+i['link']) # article.media(i['img']) resp.append(article) print(time.time()-start) return str(resp)
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)
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)
def convert_to_twilio(text_message): """Convert a message to a Twilio MessagingResponse by doing image substitution. :param text_message: The message, as text, where IMAGE(name.png) represents the image name.png. :returns A MessagingResponse. """ resp = MessagingResponse() if not text_message: return resp twilio_message = Message() start_ind = 0 for match in finditer(IMG_REGEX, text_message): match_start, match_end = match.span() twilio_message.body(text_message[start_ind:match_start].strip()) twilio_message.media(url_for('image', name=match.group(1))) start_ind = match_end twilio_message.body(text_message[start_ind:]) resp.append(twilio_message) return resp
def test_blacklist_works(self): with override_settings(DEBUG=False): request = self.factory.post(self.str_uri, {'From': str(self.blocked_caller.phone_number)}) response = str_view(request) r = Message() self.assertEqual( response.content, str(r).encode('utf-8'), ) with override_settings(DEBUG=True): request = self.factory.post(self.str_uri, {'From': str(self.blocked_caller.phone_number)}) response = str_view(request) r = Message() self.assertEqual( response.content, str(r).encode('utf-8'), ) with override_settings(DEBUG=False): request = self.factory.post(self.verb_uri, {'From': str(self.blocked_caller.phone_number), 'callsid': 'some-call-sid', }) response = verb_view(request) r = VoiceResponse() r.reject() self.assertEqual( response.content, str(r).encode('utf-8'), ) with override_settings(DEBUG=True): request = self.factory.post(self.verb_uri, {'From': str(self.blocked_caller.phone_number), 'callsid': 'some-call-sid', }) response = verb_view(request) r = VoiceResponse() r.reject() self.assertEqual( response.content, str(r).encode('utf-8'), )
from twilio.twiml.messaging_response import Body, Message, Redirect, MessagingResponse response = MessagingResponse() message = Message() message.body('Hello World!') response.append(message) response.redirect('https://demo.twilio.com/sms/welcome') print(response)
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)
from twilio.twiml.messaging_response import Body, Media, Message, MessagingResponse response = MessagingResponse() message = Message() message.body('Store Location: 123 Easy St.') message.media('https://demo.twilio.com/owl.png') response.append(message) print(response)