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 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 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(): """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 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 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 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)
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 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 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(): 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 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 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)
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
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 process_sms(): """Recieves incoming SMS from Twilio and responds with a link to compose a message""" phone_number = request.values.get('From', None) message = request.values.get('Body', None) resp = MessagingResponse() message = Message() valid_user = db.users.find_one({"phone_number": phone_number}) if valid_user is not None: token = secrets.token_urlsafe(8) db.tokens.insert_one( {"token": token, "phone_number": phone_number, "time": int(time.time())}) link = base_url + "/c/" + token message.body("Hey {}! Tap this link to send a secure message to {}. {}".format( valid_user['first_name'], doctor_name, link)) else: message.body("Hi! Your number wasn't recognized as belonging to a current patient. Please register at this link: {}/register/{}".format(base_url, phone_number)) resp.append(message) 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 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 receiveMessage(): body = request.values.get('Body', None) fromNumber = request.values.get('From', None) msgID = request.values.get('MessageSid', None) # Do sentiment analysis documents = {'documents': [{'id': '1', 'language': 'en', 'text': body}]} headers = {"Ocp-Apim-Subscription-Key": subscription_key} response = requests.post(sentiment_api_url, headers=headers, json=documents) sentiments = response.json() # Store user response with sentiment in mongodb sms = db.sms sms_data = { 'body': body, 'from': fromNumber, 'msgid': msgID, 'sentiments': sentiments["documents"][0]['score'] } sms.insert_one(sms_data) config = db.config.find_one() productType = config['productType'] firstName = config['firstName'] response = MessagingResponse() message = Message() for i in sentiments["documents"]: if i['score'] >= 0.5: message.body(config['positiveResponse'].replace( '<firstName>', firstName).replace('<productType>', productType)) else: message.body(config['negativeResponse'].replace( '<firstName>', firstName).replace('<productType>', productType)) response.append(message) return str(response)
def index(): body = request.values.get('Body', None) response = MessagingResponse() message = Message() if request.method == 'POST': try: country = pycountry.countries.lookup(body) r = requests.get(covid_status_by_country + country.alpha_2) json_data = r.json() message.body(f' In the {country.name} there are\ \n Total cases: {json_data["cases"]} \ \n Total deaths: {json_data["deaths"]} \ \n Total recovered: {json_data["recovered"]} ') response.append(message) return str(response) except LookupError: message.body('Please send a valid 2 digit country i.e. US') response.append(message) return str(response) if request.method == 'GET': return abort(404)
def register_globalgiving(event, context): log.info(event) response = MessagingResponse() message = Message() result = None reg = Registration(event) if reg.execute(): message.body("6782646400") else: message.body("resend") response.append(message) result = { "statusCode": 200, "headers": { "Content-Type": "application/xml" }, "body": str(response) } return result
def inbound_sms(): message_body = request.form['Body'] resp = MessagingResponse() if message_body.isdigit(): response_message = 'Taken {} Martian solar days into the journey.' \ .format(message_body) photo_url = get_mars_photo_url(message_body) print(photo_url) msg = Message() msg.body(response_message) msg.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 update_globalgiving(event, context): log.info(event) response = MessagingResponse() message = Message() result = None upd = Update(event) if upd.execute(): message.body("ack") else: message.body("resend") response.append(message) result = { "statusCode": 200, "headers": { "Content-Type": "application/xml" }, "body": str(response) } return result
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 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 sms_reply(): """Respond to incoming calls with a simple text message.""" # Fetch the message msg = request.form.get('Body') # Create reply resp = MessagingResponse() response = MessagingResponse() message = Message() #resp.message("You said: {}".format(msg)) if msg == "1": resp.message("Your A/c XXXXXXX2138 on 02/02/2020 .Avl Bal Rs " + str(data[m - 1, n - 1])) if msg == "2": message.body('Expenditure Categorisation') message.media('https://savyatam.github.io/sampleChatBot/myfig1.png') response.append(message) return str(response) if msg == "3": message.body('Atms near me') message.media('https://savyatam.github.io/sampleChatBot/atms.png') response.append(message) return str(response) if msg == "4": resp.message( "Standard Chartered Bank Personal Loan Details" + "Loan available for both salaried and self-employed professionals. Borrowers within the age group of 23 and 58 years." + "Loan amount of minimum ₹ 1 Lakh to ₹ 30 Lakh. Standard Chartered personal loan rate of interest is in the range of 10.99% to 19.00%." ) if msg == "5": message.body('Balance Analysis') message.media('https://savyatam.github.io/sampleChatBot/myfig.png') response.append(message) return str(response) if msg == "6": message.body('transaction history') message.media( 'https://savyatam.github.io/sampleChatBot/transition.png') response.append(message) return str(response) if msg == "Options": resp.message( "Transaction History:\n1-Balance Enquiry\n2-Expenditure Categorisation\n3-ATM Near Me\n4-Loan Details\n5-Balance Analysis\n6-Transaction History" ) return str(resp)
def sms(): session.permanent = True response = MessagingResponse() message = Message() counter = session.get('counter', 0) num_images = eval(request.values['NumMedia']) if not counter: if num_images != 0: if num_images > 1: message.body(prompts.too_many_images) response.append(message) return str(response) filename = request.values['MessageSid'] + '.jpg' filepath = config.image_directory + filename with open(filepath, 'wb') as f: image_url = request.values['MediaUrl0'] f.write(requests.get(image_url).content) db.execute(config.db_credentials, config.insert_report) session['row_id'] = db.get_row_id() db.execute(config.db_credentials, config.update_image, (filepath, session['row_id'])) session['counter'] = 1 message.body(prompts.address_image) else: db.execute(config.db_credentials, config.insert_report) session['row_id'] = db.get_row_id() session['counter'] = 1 message.body(prompts.address) response.append(message) return str(response) else: if counter == 1: response.redirect(url=url_for('address'), method='POST') return str(response) elif counter == 2: response.redirect(url=url_for('options'), method='POST') return str(response)
if request.form['NumMedia'] != '0': image1 = request.form['MediaUrl0'] the_url = "https://southcentralus.api.cognitive.microsoft.com/customvision/v1.1/Prediction/58efabf4-d519-417c-8f4f-5a4550cac311/url?iterationId=78a30fb3-ce3b-4858-afe6-be52a84ddcd1" res = requests.post(url = the_url, data=json.dumps({"Url":image1}), headers={'Content-Type': 'application/json',"Prediction-Key":"5dddbd7652e24ea99576c57ef9fb381a"}) location = parse_img.get_tag(res.json()) with open('somefile.txt', 'w+') as f: # Note that f has now been truncated to 0 bytes, so you'll only # be able to read data that you wrote earlier... f.write(location) f.close() response = MessagingResponse() message = Message() location = location + "\n" + "Would you like directions to this location? -> If yes, reply with 1" + "\n" + "Would you like to go somewhere from this place? -> If yes, reply with 2." message.body(location) response.append(message) return str(response) # return "dummy" else: # Start our response body = request.values.get('Body', None) body = body.lower() if "from" in body: body = body.lower() #from_text = re.search(r'from(.*?)to', body).group(1) #dest_text = body.split("to",1)[1] body1 = body.split("by",1)[0] grp = re.search(r'from(.*?)to',body1)
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)
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, Message, Redirect, MessagingResponse response = MessagingResponse() message = Message() message.body('Hello World!') response.append(message) response.redirect('https://demo.twilio.com/sms/welcome') print(response)