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 sms_send(request): response = MessagingResponse() if request.POST['To'] == settings.TWILIO_PHONE_NUMBER: response.redirect(reverse('sms:index')) return response try: result = \ SmsMessage.objects \ .filter(from_number=request.POST['To']) \ .filter(related_phone_number__number_type="ADV") \ .latest('date_created') response.message(request.POST['Body'], from_=result.related_phone_number.e164, to=request.POST['To']) except SmsMessage.DoesNotExist: response.message(request.POST['Body'], from_=PhoneNumber.objects.filter( number_type="ADV").latest('date_created').e164, to=request.POST['To']) save_sms_message.apply_async(args=[request.POST]) return response
def sms_signup(): response = MessagingResponse() signup_survey = Survey.query.first() if survey_error(signup_survey, response.message): return str(response) session['id'] = request.values['From'] if 'question_id' in session: # Retrieve the client's phone number and format it phone_number = "%2B" + request.values.get('From', None)[1:] # Retrieve the record id to check if the client registered before response_id = retrieve_prev_record(phone_number) # Redirect the response to the answer-saving url answer_url = url_for('main.answer', question_id=session['question_id'], record_id=response_id) response.redirect(url=answer_url) elif request.values.get('Body', None).strip() == 'SIGNUP': redirect_to_first_question(response, signup_survey) elif request.values.get('Body', None).strip() == 'MOVEUP': welcome_user(signup_survey, response.message) else: response.message(None) return str(response)
def redirect_twiml(question, recording): response = MessagingResponse() response.redirect(url=url_for('question', question_id=question.id, recording=recording), method='GET') return str(response)
def redirect_twiml(question): with open('questions.json', 'r') as f: survey = json.load(f) resp = MessagingResponse() resp.redirect(url=url_for('question', question_id=survey.index(question)), method='GET') return str(resp)
def next_question_redirect(question_id, survey_id): parameters = {'survey_id': survey_id, 'question_id': question_id} question_url = reverse('question', kwargs=parameters) twiml_response = MessagingResponse() twiml_response.redirect(url=question_url, method='GET') return HttpResponse(twiml_response)
def test_redirect(self): r = MessagingResponse() r.redirect(url='example.com') assert_equal( self.strip(r), '<?xml version="1.0" encoding="UTF-8"?><Response><Redirect>example.com</Redirect></Response>' )
def register(): resp = MessagingResponse() number = request.values.get('From') if not db.number_exists(number): resp.redirect(url=url_for('welcome')) return str(resp) else: resp.redirect(url=url_for('handle_text')) return str(resp)
def sms_ahoy_reply(): print( f'Incoming message from {request.values.get("From")}: {request.values.get("Body")}' ) # Here', we're generating TwiML using the Python helper library resp = MessagingResponse() # resp.message('TwilioQuest rules', action='/status_callback') resp.redirect('http://www.foo.com/nextInstructions') return str(resp)
def sms_onboard(): response = MessagingResponse() onboard = Onboard.query.first() if 'question_id' in session: response.redirect(url_for('answer', question_id=session['question_id'])) else: welcome_user(onboard, response.message) redirect_to_first_question(response, onboard) return str(response)
def sms_survey(): response = MessagingResponse() now = datetime.datetime.now() # Get the to/from numbers from the latest request from_num = request.values['From'] to_num = request.values['To'] # Get the message most recently sent from us messages = client.messages.list(from_=to_num, to=from_num, limit=1) message_text = messages[0].body # old code #survey = Survey.query.first() #if survey_error(survey, response.message): # return str(response) #if 'question_id' in session: # response.redirect(url_for('answer', # question_id=session['question_id'])) #else: # welcome_user(survey, response.message) # redirect_to_first_question(response, survey) #return str(response) # new code with 5 minute time limit, and reprompt reset if message_text == "Are you ready to take the COSC 102 survey? Please respond when you are ready to begin. You will have 5 minutes to complete the survey once you begin, but the survey should only take 1-2 minutes.": if 'question_id' in session: del session['question_id'] if 'start_time' in session: del session['start_time'] if 'question_id' in session: delta = now - session['start_time'] if delta.seconds > 300: del session['start_time'] del session['question_id'] response.message("The time to complete the survey has expired") else: response.redirect( url_for('answer', question_id=session['question_id'])) else: survey = Survey.query.first() if survey_error(survey, response.message): return str(response) welcome_user(survey, response.message) redirect_to_first_question(response, survey) return str(response)
def index(request): response = MessagingResponse() if "!deter" in request.POST['Body']: response.redirect(reverse('deterrence:deter')) elif "!new_deterrence" in request.POST['Body']: response.redirect(reverse('deterrence:new_deterrence')) else: response.message("I did not understand that command.", from_=request.POST['To'], to=request.POST['From']) return response
def sms_survey(): response = MessagingResponse() survey = Survey.query.first() if survey_error(survey, response.message): return str(response) if 'question_id' in session: response.redirect(url_for('answer', question_id=session['question_id'])) else: welcome_user(survey, response.message) redirect_to_first_question(response, survey) return str(response)
def sms(request): response = MessagingResponse() try: result = PhoneNumber.objects.get(e164=request.POST['To']) except PhoneNumber.DoesNotExist: result = None response.message(request.POST['To']) if result and result.related_sim: response.redirect(reverse('sims:sms_receive')) elif result and result.related_bot: process_bot_response.apply_async( args=[request.POST, result.related_bot.id]) return 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 sms_parse(): resp = MessagingResponse() resp.message("Message received") message_number = request.form['From'] message_body = request.form['Body'] response_str = None message_parser = Parser(message_body) book_now = message_parser.to_book_now() if book_now: send_response(message_number, 'trying to book') resp.redirect(os.environ['APP_URL']) booking_dt = message_parser.booking_time match_type = message_parser.game_type playing_time = message_parser.playing_time cas_user, cas_pw = get_tennis_creds() chromedriver_path = get_chromedriver_path() booker_args = [playing_time, match_type, cas_user, cas_pw, chromedriver_path, message_number, book_now] if book_now: booking_dt = pd.to_datetime('now') + pd.DateOffset(seconds=8) booking_dt = booking_dt.to_pydatetime() scheduler.add_job(run_booker, 'date', run_date=booking_dt, args=booker_args) logging.getLogger('apscheduler').setLevel(logging.DEBUG) else: if message_parser.booking_time: booking_dt = pd.to_datetime(booking_dt) booking_dt = booking_dt.to_pydatetime() scheduler.add_job(run_booker, 'date', run_date=booking_dt, args=booker_args) response_str = 'Scheduled to run on {} for {}'.format(booking_dt, playing_time) else: response_str = 'Error: needs to be in MM/DD/YYYY HH:MM PM/AM singles/doubles format' if response_str: send_response(message_number, response_str) return 'Finished'
def show_survey(request, pk): survey = Survey.objects.get(id=pk) request.session['current_survey_id'] = survey.id phone_number = request.POST[ 'From'] if 'From' in request.POST else request.GET['From'] new_responder = False try: responder = Responder.objects.get(phone_number=phone_number) except Responder.DoesNotExist: responder = Responder(phone_number=phone_number) responder.save() new_responder = True responder.surveys.add(survey) responder.active_survey = survey responder.save() first_question = survey.first_question first_question_ids = { 'survey_id': survey.id, 'question_id': first_question.id } first_question_url = reverse('textin:question', kwargs=first_question_ids) # If this is a new Responder, or an old Responder with missing data (email or name) that we want # them to complete if new_responder or (survey.complete_responder and not responder.complete()): responder_params = {'responder_id': responder.id} is_new_param = create_get_param_string({'new': new_responder}) new_responder_url = reverse('textin:process_responder', kwargs=responder_params) + \ is_new_param twiml_response = MessagingResponse() if survey.start_message: twiml_response.message(survey.start_message) twiml_response.redirect(new_responder_url, method='POST') return HttpResponse(twiml_response, content_type='application/xml') else: request.session['active_cookie'] = 'answering_question_id' return redirect(first_question_url)
def sms_survey(): response = MessagingResponse() now = datetime.datetime.now() # Get the to/from numbers from the latest request from_num = request.values['From'] to_num = request.values['To'] # Get the message most recently sent from us messages = client.messages.list(from_=to_num, to=from_num, limit=1) message_text = messages[0].body # new code with 5 minute time limit, and reprompt reset if message_text == survey_prompt: if 'instance_id' in session: del session['instance_id'] if 'question_id' in session: del session['question_id'] if 'start_time' in session: del session['start_time'] session['instance_id'] = messages[0].sid if 'question_id' in session: delta = now - session['start_time'] if delta.seconds > 300: del session['start_time'] del session['question_id'] del session['instance_id'] response.message("The time to complete the survey has expired") else: response.redirect( url_for('answer', question_id=session['question_id'])) else: survey = Survey.query.first() if survey_error(survey, response.message): return str(response) welcome_user(survey, response.message) redirect_to_first_question(response, survey) return str(response)
def index(request): response = MessagingResponse() base_uri = "{0}://{1}".format(request.scheme, request.get_host()) if "deter" in request.POST['Body']: response.redirect(reverse("deterrence:index")) elif "!new_ad" in request.POST['Body']: buy_new_phone_number.apply_async( args=[base_uri, request.POST, PhoneNumber.AD]) response.message("Buying new advertisement phone number...", from_=request.POST['To'], to=request.POST['From']) else: response.message("I did not understand that command.", from_=request.POST['To'], to=request.POST['From']) return response
def sms_send(request): response = MessagingResponse() if request.POST['To'] == settings.TWILIO_PHONE_NUMBER: response.redirect(reverse('sms:index')) return response try: check = PhoneNumber.objects.get(e164=request.POST['To']) response.message("[ERROR] Cannot send SMS as {0} is a " "Garfield number. " "Are you sure this number is correct?" "".format(check.e164), from_=request.POST['To'], to=request.POST['From']) return response except PhoneNumber.DoesNotExist: pass try: sim_sid = request.POST['From'].replace("sim:", "") result = \ SmsMessage.objects \ .filter(from_number=request.POST['To']) \ .filter(related_phone_number__number_type="ADV") \ .filter(related_phone_number__related_sim__sid=sim_sid) \ .latest('date_created') response.message(request.POST['Body'], from_=result.related_phone_number.e164, to=request.POST['To']) except SmsMessage.DoesNotExist: response.message(request.POST['Body'], from_=PhoneNumber.objects.filter( number_type="ADV").latest('date_created').e164, to=request.POST['To']) save_sms_message.apply_async(args=[request.POST]) return response
def sms_find_poll(): """Find poll from sms""" # Start our response resp = MessagingResponse() sms = request.values['Body'] poll = Poll.get_from_code(sms) # del session['short_code'] if 'short_code' in session: short_code = session['short_code'] poll = Poll.get_from_code(short_code) if poll.poll_type.multi_select: if sms[0].upper() == 'N': del session['short_code'] resp.message('Thank you for responding.') return str(resp) elif sms[0].upper() == 'Y': resp.redirect('/sms/' + short_code) else: resp.message('Please type "Y" for Yes or "N" for No.') resp.redirect('/sms/' + short_code + '/input') elif poll: resp.redirect('/sms/' + sms) else: resp.message('That poll does not exist') return str(resp)
def set_responder_attr(request, responder_id): responder = Responder.objects.get(id=responder_id) active_survey = responder.active_survey if request.method == 'GET': attr = request.session['responder_attr'] if getattr(responder, attr): if attr != Responder.USER_SET_ATTRS[-1]: phone_number = create_get_param_string({'From': request.GET['From']}) return redirect(reverse('textin:survey', kwargs={'pk': active_survey.id}) + \ phone_number) attr = Responder.USER_SET_ATTRS[Responder.USER_SET_ATTRS.index(attr) + 1] return HttpResponse(compose_response(ResponderStrings.get_responder_attr(attr))) elif request.method == 'POST': attr = request.session['responder_attr'] value = request.POST['Body'] print('responder id: ', responder.id) print('attr cookie: ', request.session['responder_attr']) print('value: ', value) print('usr response match: ', SurveyStrings.user_response_matches(value, 'skip')) if not SurveyStrings.user_response_matches(value, 'skip'): setattr(responder, request.session['responder_attr'], value) responder.save() if attr == Responder.USER_SET_ATTRS[-1]: del request.session['responder_attr'] phone_number = create_get_param_string({'From': request.POST['From']}) return redirect(reverse('textin:survey', kwargs={'pk': active_survey.id}) + \ phone_number) else: next_attr = Responder.USER_SET_ATTRS[Responder.USER_SET_ATTRS.index(attr) + 1] request.session['responder_attr'] = next_attr next_attr_url = reverse('textin:set_responder_attr', kwargs={'responder_id': responder.id}) twiml_response = MessagingResponse() twiml_response.redirect(next_attr_url, method='GET') return HttpResponse(twiml_response)
def show_survey(request, survey_id): survey = Survey.objects.get(id=survey_id) first_question = survey.first_question first_question_ids = { 'survey_id': survey.id, 'question_id': first_question.id } first_question_url = reverse('question', kwargs=first_question_ids) welcome = 'Hello and thank you for taking the %s survey' % survey.title if request.is_sms: twiml_response = MessagingResponse() twiml_response.message(welcome) twiml_response.redirect(first_question_url, method='GET') else: twiml_response = VoiceResponse() twiml_response.say(welcome) twiml_response.redirect(first_question_url, method='GET') return HttpResponse(twiml_response, content_type='application/xml')
def show_survey(request, survey_id): survey = Survey.objects.get(id=survey_id) first_question = survey.first_question first_question_ids = { 'survey_id': survey.id, 'question_id': first_question.id } first_question_url = reverse('question', kwargs=first_question_ids) welcome = 'Hello! Thank you for contacting Ivy Global United, the premier advocacy organization for surrogates. You are about to take the %s survey' % survey.title if request.is_sms: twiml_response = MessagingResponse() twiml_response.message(welcome) twiml_response.redirect(first_question_url, method='GET') else: twiml_response = VoiceResponse() twiml_response.say(welcome) twiml_response.redirect(first_question_url, method='GET') return HttpResponse(twiml_response, content_type='application/xml')
def handle_text(): resp = MessagingResponse() body = request.values['Body'] born = db.get_born_message() if born: resp.message(born[0]) return str(resp) elif request.values['Body'].startswith(BORN_PHRASE): resp.redirect(url=url_for('notify')) return str(resp) elif "remove" in body.lower(): number = request.values.get('From') db.remove_number(number) resp.message("You have been removed from the {} Notifier.".format( BABY_NICKNAME)) return str(resp) else: resp.message( "{} is not born yet. You'll be notified when that changes.".format( BABY_NICKNAME)) 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)
def show_survey(request, survey_id): survey = Survey.objects.get(id=survey_id) first_question = survey.first_question first_question_ids = { 'survey_id': survey.id, 'question_id': first_question.id } first_question_url = reverse('question', kwargs=first_question_ids) #welcome = 'Hi Alex, Welcome to the %s , You will be asked 3 questions, You will need to answer each question in max 10 seconds, Press # key when you have finished your answer' % survey.title c_name = request.GET.get("c_name") org_name = request.GET.get("org_name") if (c_name != None and c_name != 'None'): c_name = c_name else: c_name = 'candidate' if (org_name != None and org_name != 'None'): title = org_name else: title = survey.title welcome = 'Hi %s, Welcome to the %s , You will be asked 3 questions, You will need to answer each question in max 10 seconds, Press # key when you have finished your answer' % ( c_name, title) if request.is_sms: twiml_response = MessagingResponse() twiml_response.message(welcome) twiml_response.redirect(first_question_url, method='GET') else: twiml_response = VoiceResponse() twiml_response.say(welcome) twiml_response.redirect(first_question_url, method='GET') return HttpResponse(twiml_response, content_type='application/xml')
def incoming_sms(): resp = MessagingResponse() nowt = datetime.now body = str(request.values.get('Body', None)) num = request.values.get('From', None) num = phonenumbers.parse(num, None) num = phonenumbers.format_number(num, phonenumbers.PhoneNumberFormat.NATIONAL) command = body.lower().split()[0].replace(':', '') db = MySQL.Database('users') db.execute("SELECT * FROM information") # Responds with a list of actions users can take if command == "actions" or command == "action": resp.message( "List of commands:\n" "TIME: Reply 'time' followed by the time you'd like to receive your daily update. 'Time 8am' to get your " "update at 8:00am.\n" "LOCATION: To change your location respond to the number with 'location' followed by your new location. " "'Location Richmond, VA' (you may also use your zip code, address, or a nearby landmark).\n" "WEATHER: To get a current weather update reply to the number with 'weather'.\n" "You can respond to the number with feedback or to get in touch with Delaney Kassab at any time. Just " "reply with whatever you have to say!\n" "To stop receiving messages at any time just reply 'STOP'.") # Changes user's location elif command == "location": location = body.lower().replace('location', '') usr = db.usr(num, 'byPhone') usr.location = location w = darkskyreq.Weather(usr.location) if w.getcoords() is None: resp.message("We couldn't find that location. Please type \"location\" followed by a valid location.") else: address = w.getaddress() tz = w.getweather().timezone resp.message("Your new location has been set: " + address) db.execute("UPDATE information SET location = '%s' WHERE customer_id = %s" % (location, usr.customer_id)) db.execute("UPDATE information SET timezone = '%s' WHERE customer_id = %s" % (tz, usr.customer_id)) db.commit() # Sends current conditions to user elif command == "weather": usr = db.usr(num, 'byPhone') deliver.sendWeather(usr.customer_id) # Sign up a new user via sms signup elif command == 'weathermywardrobe' or 'question_id' in session: with open('questions.json', 'r') as f: survey = json.load(f) if 'question_id' in session: resp.redirect(url_for('answer', question_id=session['question_id'])) else: db.addnum(num) welcome_user(resp.message) redirect_to_first_question(resp, survey) # Changes the time the user receives the message elif command == "time": time = str(body.lower().replace('time', '').replace(' ', '')) usr = db.usr(num, 'byPhone') if 'a' in time or 'p' in time: if 'm' not in time: time += 'm' if ':' in time: try: t = datetime.strptime(time, "%I:%M%p") db.execute("UPDATE information SET usr_time = '%s' WHERE customer_id = %s" % ( t.strftime("%H:%M"), usr.customer_id)) resp.message(t.strftime("New time set for %I:%M%p")) except Exception as e: print(e) resp.message( "Oops, you may have misformatted your time. Please double check the time you sent and reply " "\"time \" followed by time you would like to set.") else: try: t = datetime.strptime(time, "%I%p") db.execute("UPDATE information SET usr_time = '%s' WHERE customer_id = %s" % ( t.strftime("%H:%M"), usr.customer_id)) resp.message(t.strftime("New time set for %I:%M%p")) except Exception as e: print(e) resp.message( "Oops, you may have misformatted your time. Please double check the time you sent and reply " "\"time \" followed by the time you would like to set.") else: resp.message("Make sure you include am or pm. Reply \"time \" followed by the time you would like to set.") db.commit() # if none of the above are true (there is no command), assumes the message is feedback and saves it to # logs/FeedbackLog.json. Also sends a message to me with the feedback, phone number, and first and last name. else: usr = db.usr(num, 'byPhone') msg = "New feedback from %s %s %s: %s" % (usr.first_name, usr.last_name, usr.phone, body) deliver.send('8049288208', msg) resp.message("Your feedback has been recorded. Thank you!") with open('logs/FeedbackLog.json', 'a', encoding='utf-8') as f: json.dump(msg, f, ensure_ascii=False, indent=4) f.write("\n") # logs everything sent to the number in logs/conversationLog.json with open('logs/conversationLog.json', 'a', encoding='utf-8') as f: conv = 'Message from %s at ' % (num) + nowt(pytz.timezone('America/New_York')).strftime( "%b %d at %I:%M%p: ") + body json.dump(conv, f, ensure_ascii=False, indent=4) f.write('\n') return str(resp)
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/welcome/sms/') print(response)
def redirect_twiml(question_id): response = MessagingResponse() response.redirect(url=url_for('main.question', question_id=question_id), method='GET') return str(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)