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 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 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(): # 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 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 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 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 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 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)
data = r.json() #print data message_directions.body(route_parser.extract_path((data))) response.append(message_directions) #print(str(data)) #print str(response) #static image image_request = requests.get("https://dev.virtualearth.net/REST/v1/Imagery/Map/Road/Routes?wp.0="+from_text+"&wp.1="+dest_text+"&key=AmAugBLaNYZ5kK48nDsSyH2IkXZTMgLdevV0cwJkIohl5A4hitqxiCmKhDAAq7cr") # print(image_request.text) name = ''.join(random.sample(string.ascii_lowercase, 10)) + ".jpg" with open("img/"+name, 'wb') as out_file: out_file.write(image_request.content) # message_mapImage.body('Image of the route') message_mapImage.media("http://159.65.68.139:5000/uploads/{}".format(name)) response.append(message_mapImage) #res1 = str(response) #print res1 return str(response) elif body == "1": response = MessagingResponse() message = Message() message.body("Okay! From where?") response.append(message) with open('somefile.txt', 'a') 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("\n"+"dest") f.close() return str(response)
from twilio.twiml.messaging_response import Body, Media, Message, MessagingResponse response = MessagingResponse() message = Message() message.body('Hello friend') 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)
def sms_reply(): stationsOld = set([ "North Springs", "Sandy Springs", "Dunwoody", "Medical Center", "Buckhead", "Lindbergh Center", "Arts Center", "Midtown", "North Avenue", "Civic Center", "Peachtree Center", "Five Points", "Garnett", "West End", "Oakland City", "Lakewood/Ft. McPherson", "East Point", "College Park", "Airport", "Doraville", "Chamblee", "Brookhaven/Oglethorpe", "Lenox", "Lindbergh Center", "Arts Center", "Midtown", "North Avenue", "Civic Center", "Peachtree Center", "Five Points", "Garnett", "West End", "Oakland City", "Lakewood/Ft. McPherson", "East Point", "College Park", "Airport", "Bankhead", "Ashby", "Vine City", "Dome/GWCC/Philips Arena/CNN Center", "Five Points", "Georgia State", "King Memorial", "Inman Park/Reynoldstown", "Edgewood/Candler Park", "Hamilton E. Holmes", "West Lake", "Ashby", "Vine City", "Dome/GWCC/Philips Arena/CNN Center", "Five Points", "Georgia State", "King Memorial", "Inman Park/Reynoldstown", "Edgewood/Candler Park", "East Lake", "Decatur", "Avondale", "Kensington", "Indian Creek" ]) stationsOld = list(stationsOld) stations = [] for i in stationsOld: i = i.lower() stations.append(i) # Take 1: Old SDK SMS - passed # resp = MessagingResponse() # resp.message("Hi, I'm MARTAN from mAlerts, here to give you your best rider experience!") # return str(resp) # Take 2: Simpler SMS - passed # response = MessagingResponse() # response.message("Hi, I'm MARTAN from mAlerts.") # return str(response) # Take 3: MMS - passed # response = MessagingResponse() # message = Message() # request_body = request.values.get("Body", None) # message.body("Hi, I'm Martan from mAlerts. If you need to refer to the MARTA map, I gotchu. You texted me: " + request_body) # message.media("http://www.itsmarta.com/images/train-stations-map.jpg") # response.append(message) # return str(response) response = MessagingResponse() message = Message() request_body = request.values.get("Body", None) lower_request_body = request_body.lower() stripped_request_body = lower_request_body.strip(",.!?/&-:;@'...") bodyArray = stripped_request_body.split(" ") waysToSayHi = [ "hi", "hello", "hell", "howdy", "hh", "bonjour", "aloha", "hallo", "halo", "hey", "wassup", "wessup", "what is up", "whats up", "what's up", "hi there", "hithere", "yo", "sup" ] # checks to see if hi or similar is in text for hi in waysToSayHi: if hi in bodyArray: message.body( "Hi, I'm Martan from mAlerts! Please text me an origin and a destination. For example: 'Doraville to Midtown'. Or if you want to see a full MARTA map, text me 'map'." ) response.append(message) return str(response) # if text says "map" if "map" in bodyArray: message.body("Here's the MARTA map!") message.media("http://www.itsmarta.com/images/train-stations-map.jpg") response.append(message) return str(response) # if text says "<station> to <station>"" elif ("to" in bodyArray): toIndex = bodyArray.index("to") origin = ' '.join(bodyArray[0:toIndex]) destination = ' '.join(bodyArray[toIndex + 1:]) stationsDict = getStationsDict() keys = stationsDict.keys() originFinalKeyList = get_close_matches(origin.lower(), keys, 1) destinationFinalKeyList = get_close_matches(destination.lower(), keys, 1) # if text contains "to" but does not contain valid station names if (len(originFinalKeyList) == 0 or len(destinationFinalKeyList) == 0): message.body( "Hmm, you didn't use the right format... Please text me a valid origin and a destination. For example: Doraville to Midtown" ) response.append(message) return str(response) originFinalKey = originFinalKeyList[0] destinationFinalKey = destinationFinalKeyList[0] finalOrigin = stationsDict[originFinalKey] finalDestination = stationsDict[destinationFinalKey] output = "Cool. So you're going from " + finalOrigin + " to " + finalDestination + "." route = findRoute(finalOrigin, finalDestination) counter = 0 for leg in route: if counter == 0: output += " Take the " else: output += " Then take the " if len(leg["lines"]) == 1: output += min(leg["lines"]).name + " line " elif len(leg["lines"]) == 2: output += min(leg["lines"]).name + " or " + max( leg["lines"]).name + " lines " output += leg["direction"].name + "BOUND to " output += leg["destination"] + " station." counter += 1 message.body(output) response.append(message) return str(response) # if text says something invalid else: message.body( "Hey, it looks like you said something that's not valid! Just send me a hello or your origin and destination stations. For example: 'Doraville to Midtown'." ) response.append(message) return str(response)
def _main(): # get data income_msg = request.form.get('Body') trasmisor = request.form.get('From') number = trasmisor.split(':')[1] #data = json.loads(request.data) #number = data['number'] #income_msg = data['message'] # get session if not exist session equal 0 user_id = session.get('user_id', 0) lang = session.get('lang', 'en') # if session exist send to NLP if user_id != 0: # Noise removal income_msg = str(normalize(income_msg)) flag = 0 for x in exit_terms: if x in income_msg: message = logout.logout() flag = 1 break if not (flag): if 'menu' in income_msg: message = ("{}\n".format( palabras[lang].get("menu_select"))) message += flow_menu() flag = 1 if not (flag): for x in help_terms: if x in income_msg: message = flow_help() flag = 1 break if not (flag): flows = { "contacts": flow_contact, "memories": flow_memory, "language": change_lang, "phrases": chatbot } flow = session.get('thread', 'phrases') func = flows.get(flow) message = func(income_msg) # if not send to login else: message = login.login(number) response = MessagingResponse() msg = Message() if message[0] == 'media': msg.media(message[1]) else: msg.body(message) response.append(msg) # response #resp = MessagingResponse() # resp.message(message)g # return str(resp) return str(response)
def sms(): message_body = request.form['Body'].lower() resp = MessagingResponse() reply_message = Message() registered = session.get("registered", False) zip_c = session.get("zip_c", "30322") if registered: loc = Location(zip_c) wu = WU(wu_key, loc) if "zipchange" in message_body.lower(): nums = [int(i) for i in message_body.split() if i.isdigit()] if len(nums): zip_code = str(nums[0]) try: temp_loc = Location(zip_code) session["zip_c"] = zip_code reply_text = "Your zip code has been changed to {} - {}, {}.".format( zip_code, temp_loc.city, temp_loc.state) except KeyError: reply_text = "The zip code provided was not valid." else: reply_text = "The correct syntax for this command is zipchange (zip code here)." else: if len(message_body.split()) == 1: if "commands" in message_body: reply_text = ( "Available commands include:\n\n" "alerts - See a list of weather alerts for the set area.\n\n" "conditions - See current weather conditions for the set area.\n\n" "radar - View a live weather radar image for the set area. This command has a delay.\n\n" "zipchange - Change the zip code of the selected area.\n\n" "details - View details about this service.\n\n" "credit - View information about Weather Underground, the weather data provider." ) elif "alerts" in message_body: try: reply_text = wu.get_alerts() except RequestException: reply_text = "Weather alerts could not be found at this time, please try again later." elif "conditions" in message_body: try: reply_text = wu.get_conditions() except RequestException: reply_text = "The weather conditions could not be found at this time, please try again later." elif "radar" in message_body: try: file_name = wu.get_animation() uploader.upload("Images/" + file_name + ".gif", public_id=file_name) c_url = cloudinary.utils.cloudinary_url(file_name)[0] reply_message.media(c_url) reply_text = "{}, {} Radar".format(loc.city, loc.state) except HTTPError: reply_text = "The radar imagery could not be found at this time, please try again later." elif "details" in message_body: reply_text = ( "This service was created by Josh McFarlin in Python. " "This service is a proof of concept, and is not intended for lifesaving uses. " "Messaging and data rates may apply.\n\nhttp://JoshMcFarlin.me/" ) elif "credit" in message_body: reply_text = "All weather data is provided by Weather Underground." reply_message.media( "https://icons.wxug.com/logos/PNG/wundergroundLogo_4c_rev.png" ) else: reply_text = 'Please reply with a valid command, type "commands" to view a list of commands.' else: reply_text = "Please only use one command at a time." else: if message_body.isdigit(): session["registered"] = True session["zip_c"] = message_body reply_text = 'Thanks for registering! Type "commands" to view a list of commands.' else: reply_text = "Welcome. In order to subscribe to weather updates, please reply with a zip code." reply_message.body(reply_text) resp.append(reply_message) return str(resp)