def get(self): """ Determine whether the user correctly spelled the key word during her wakeup call. For instance, 'W-A-L-R-U-S' is correct. """ digits = self.request.get('Digits') the_number = self.request.get('To') try: the_user = User.all().filter('phone_number =', the_number).fetch(1)[0] except IndexError: return 'FAIL' stop = (digits == chars_to_digits('stop')) correct = (digits == chars_to_digits(TODAYS_KEYWORD['word'])) call_record = Call(user=the_user, correct_response=correct) call_record.put() if correct: res = YOU_SPELLED_THE_WALRUS else: if stop: the_user.delete() res = UNSUBSCRIBE else: res = THATS_NOT_HOW_YOU_SPELL_WALRUS % { 'keyword': TODAYS_KEYWORD['word'], 'domain': WALRUS_DOMAIN } return self.return_XML(res)
def add_call(cid, cdir, cstate, timestamp, name, login): remote = User(login=login, name=name) call_ob = Call(cid, cdir, cstate, timestamp, remote) call_ob._ipc = app.ipc app.add_call(call_ob) app.emit("call.add", call_ob)
def manage_add_edit_call(self, product, api_id=None): edit, count, title = False, 1, "Add API Call" api_settings = g.db.api_settings.find_one() found_product = self.retrieve_product(product) if type(found_product) is str: flash("Product not found, please check the URL and try again") return redirect("/") if api_id: found_call = self.retrieve_api_call(found_product, api_id) if not found_call: flash("API Call was not found", "error") return redirect("/%s/manage/api" % product) title = "Edit API Call" edit = True post_url = "/%s/manage/api/edit/%s" % (product, api_id) form, count = helper.generate_edit_call_form(found_product, found_call, api_id) else: post_url = "/%s/manage/api/add" % product form = helper.add_fields_to_form(count) for i in range(count): temp = getattr(form, "variable_%i" % i) temp.form.id_value.data = i form.verb.choices = [(verb.get("name"), verb.get("name")) for verb in api_settings.get("verbs")] form.group.choices = helper.generate_group_choices(found_product) form.product.data = product if request.method == "POST" and form.validate_on_submit(): api_call = Call(request.form.to_dict()) api_call.variables = helper.get_vars_for_call(list(request.form.iterlists())) if api_id: getattr(g.db, found_product.db_name).update({"_id": ObjectId(api_id)}, {"$set": api_call.__dict__}) flash("API Call was successfully updated", "success") else: try: getattr(g.db, found_product.db_name).insert(api_call.__dict__) flash("API Call was added successfully", "success") except: flash( "There was an issue storing the API Call. Check " "the product and ensure the db_name is specified", "error", ) return redirect("/%s/manage/api" % product) else: if request.method == "POST": flash("Form validation error, please check the " "form and try again", "error") return render_template( "manage/manage_call_add_edit.html", title=title, form=form, count=count, edit=edit, post_url=post_url, cancel_return="/%s/manage/api" % product, )
def twilio_call(request): # if request.method is not 'GET': # return HttpResponse(status=400) account_sid = secrets.TWILIO_ACCOUNT_SID # Your Account SID from www.twilio.com/console auth_token = secrets.TWILIO_ACCOUNT_SECRET # Your Auth Token from www.twilio.com/console required = ['name', 'npeople', 'datetime', 'resid', 'cusphone', 'lang'] for req in required: if req not in request.GET: return JSONResponse(status=400) name = request.GET.get('name') num_people = request.GET.get('npeople') timestamp = request.GET.get('datetime') jptz = pytz.timezone('Asia/Tokyo') dt = datetime.datetime.fromtimestamp(float(timestamp), tz=jptz) shopid = request.GET.get('resid') if request.GET.get('lang') == "ja": language = Call.JAPANESE else: language = Call.ENGLISH cus_phone = request.GET.get('cusphone') shop_info = Venue.objects.get(pk = shopid) #res_phone = shop_info.phone res_phone = secrets.TEST_PHONE res_name = shop_info.name call_info = Call() call_info.name = name call_info.num_people = num_people call_info.date_time = dt call_info.res_phone = res_phone call_info.cus_phone = cus_phone call_info.language_opt = language call_info.res_name = res_name call_info.save() # After save, I have this id. pk = call_info.pk # Make request to Twilio. url = "http://tjr.tonny.me/reservation/" + str(pk) + '/' client = TwilioRestClient(account_sid, auth_token) try: call = client.calls.create(url=url, to=res_phone, from_=secrets.TWILIO_PHONE, status_callback="http://tjr.tonny.me/callingstatus/" + str(pk) + '/', status_callback_method="POST", ) except TwilioRestException as e: print(e) serializer = CallSerializer(call_info) return JSONResponse(serializer.data)
def twilio_call(request): # if request.method is not 'GET': # return HttpResponse(status=400) account_sid = "AC9fd29fc278859337de38574c25843043" # Your Account SID from www.twilio.com/console auth_token = "22388542078a89a05e264409a2ef0055" # Your Auth Token from www.twilio.com/console required = ['name', 'npeople', 'datetime', 'resid', 'cusphone', 'lang'] for req in required: if req not in request.GET: return JSONResponse(status=400) name = request.GET.get('name') num_people = request.GET.get('npeople') timestamp = request.GET.get('datetime') jptz = pytz.timezone('Asia/Tokyo') dt = datetime.datetime.fromtimestamp(float(timestamp), tz=jptz) shopid = request.GET.get('resid') if request.GET.get('lang') == "ja": language = Call.JAPANESE else: language = Call.ENGLISH cus_phone = request.GET.get('cusphone') shop_info = Venue.objects.get(pk = shopid) #res_phone = shop_info.phone res_phone = "+819071931989" res_name = shop_info.name call_info = Call() call_info.name = name call_info.num_people = num_people call_info.date_time = dt call_info.res_phone = res_phone call_info.cus_phone = cus_phone call_info.language_opt = language call_info.res_name = res_name call_info.save() # After save, I have this id. pk = call_info.pk # Make request to Twilio. url = "http://47.88.212.198:8000/reservation/" + str(pk) + '/' client = TwilioRestClient(account_sid, auth_token) try: call = client.calls.create(url=url, to=res_phone, from_="+81345304650") except TwilioRestException as e: print(e) serializer = CallSerializer(call_info) return JSONResponse(serializer.data)
def create(): form = RegistrationForm() if form.validate() is False: return render_template('calls/new.html', form=form) else: call = Call() call.title = form.title.data call.link = form.link.data call.active = 0 db.session.add(call) db.session.commit() message = u'Muito obrigado! sua Chamada foi submetida com sucesso!' flash(message, 'success') return redirect(url_for('calls.admin'))
def retrieve_api_call(self, product, api_id): temp_call = getattr(g.db, product.db_name).find_one( {'_id': ObjectId(api_id)}) if temp_call: return Call(temp_call) return temp_call
def init_call(self, mobile_number): call_url = self.initiate_call_urlformat.format(sid=self.sid) flow_url = self.flow_urlformat.format(flow_id=self.flow_id) #TODO create a call object. add the id to the CustomField. save the call object props = self.init_props() post_data = { 'From': int(mobile_number), 'CallerId': self.caller_id, 'Url': flow_url, 'TimeLimit': self.time_limit, 'TimeOut': self.time_out, 'CallType': self.call_type, 'StatusCallback': reverse(self.ServiceCallEndView.get_name()), 'CustomField': json.dumps(props), } r = requests.post(call_url, auth=(self.sid, self.token), data=post_data) response_data = json.loads(r.text) call_sid = response_data['Call']['Sid'] call = Call(exotel_call_id=call_sid) call.state = json.dumps(self.init_state()) call.props = json.dumps(self.init_props()) call.save() #return {"id": call.id, "exotel_id": call_sid} return {"exotel_id": call_sid}
def generate_call(self, bill_start_day): """ 根据指定的日期, 获取指定的通话记录 :param bill_start_day: :return: """ call = json.loads(Call.objects(mobile=self.phone, time__gte=bill_start_day).to_json()) for item in call: del item["_id"] del item["task_id"] del item["mobile"] return call
def parse_metadata(self, metadata, stack): if self.indent is None: self.indent = metadata.indent if metadata.indent < self.indent: self.close(metadata, stack) return match = regex_jump.match(metadata.line) if match: label = match["label"] jump = Jump(label, metadata) self.context.add_child(jump) return match = regex_call.match(metadata.line) if match: label = match["label"] call = Call(label, metadata) self.context.add_child(call) return match = regex_script.match(metadata.line) if match: script_code = match["script"] script = Script(script_code, metadata) self.context.add_child(script) return match = regex_condition.match(metadata.line) if match: parser = ConditionParser(self, metadata) stack.push(parser) stack.parse_metadata(metadata) return match = regex_menu.match(metadata.line) if match: parser = MenuParser(self, metadata) stack.push(parser) return match = regex_python_block.match(metadata.line) if match: parser = PythonScriptParser(self, metadata) stack.push(parser) return self.context.add_child(Text(metadata.line, metadata))
def init_call(self, mobile_number): call_url = self.initiate_call_urlformat.format(sid=self.sid) flow_url = self.flow_urlformat.format(flow_id=self.flow_id) #TODO create a call object. add the id to the CustomField. save the call object props = self.init_props() post_data = { 'From' : int(mobile_number), 'CallerId' : self.caller_id, 'Url' : flow_url, 'TimeLimit' : self.time_limit, 'TimeOut' : self.time_out, 'CallType' : self.call_type, 'StatusCallback' : reverse(self.ServiceCallEndView.get_name()), 'CustomField' : json.dumps(props), } r = requests.post(call_url, auth=(self.sid, self.token), data=post_data) response_data = json.loads(r.text) call_sid = response_data['Call']['Sid'] call = Call(exotel_call_id = call_sid) call.state = json.dumps(self.init_state()) call.props = json.dumps(self.init_props()) call.save() #return {"id": call.id, "exotel_id": call_sid} return {"exotel_id": call_sid}
def create_call(payload): body = request.get_json() if not body: abort(400, 'Request body is missing.') if body.get('question') is None: abort(400, '"question" is required in the request body.') # Create a new record c = Call( question=body.get('question'), description=body.get('description', ''), topics=[get_topic(name=t) for t in body.get('topics', [])] ) try: c.insert() call_id = c.id except Exception: abort(422, 'Database error: Insertion failed.') return jsonify({ 'success': True, 'message': 'Call record has been created successfully.', 'id': call_id }), 201
def sendMailCall(call): #TODO: fix template message = mail.EmailMessage(sender="MercatoLibero <*****@*****.**>", subject="Nuova chiamata") users = User.query().fetch() to = "" for user in users: to += user.email + ";" message.to = to path = os.path.join(os.path.dirname(__file__), 'templates', 'mail_call.html') calls_open = Call.query(Call.status == "OPEN").fetch() open = [e.to_dict() for e in calls_open] params = dict(call=call.to_dict(), open=open) res = template.render(path, params) message.html = res message.send()
def post(self): # we need to create the id before, GAE is slow at this ids = Call.allocate_ids(size=1) user = self.user call = Call(id=ids[0]) call.player = self.request.get('giocatore') call.called_by = user.key call.put() # deffer the task # sendMailCall(call) deferred.defer(sendMailCall, call=call) # redirect to Offer self.redirect(self.uri_for('offer', call=call.key.urlsafe()))
def _handle_create(self, e): '''Handle channel create events by building local `Session` and `Call` objects for state tracking. ''' uuid = e.getHeader('Unique-ID') self.log.debug("channel created for session '{}'".format(uuid)) # Record the newly activated session # TODO: pass con as weakref? con = self._tx_con if not self._shared else None sess = Session(event=e, con=con) sess.cid = self.get_id(e, 'default') # note the start time and current load # TODO: move this to Session __init__?? sess.create_time = get_event_time(e) # Use our special Xheader to try and associate sessions into calls # (assumes that x-headers are forwarded by the proxy/B2BUA) call_uuid = e.getHeader('variable_{}'.format(self.call_corr_xheader)) # If that fails then try using the freeswitch 'variable_call_uuid' # (only works if bridging takes place locally) if call_uuid is None: call_uuid = e.getHeader(self.call_corr_var) # could be 'None' if not call_uuid: self.log.warn("Unable to associate session '{}' into calls" .format(sess.uuid)) # associate sessions into a call # (i.e. set the relevant sessions to reference each other) if call_uuid in self.calls: call = self.calls[call_uuid] self.log.debug("session '{}' is bridged to call '{}'".format( uuid, call.uuid)) # append this session to the call's set call.sessions.append(sess) else: # this sess is not yet tracked so use its id as the 'call' id call = Call(call_uuid, sess) self.calls[call_uuid] = call self.log.debug("call created for session '{}'".format(call_uuid)) sess.call = call self.sessions[uuid] = sess return True, sess
def answer(): print "entered /answer" if request.method == 'POST': try: print "request call status:" print >> sys.stderr, str(request.form['CallStatus']) #create call object c= Call( timeAnswered = datetime.datetime.now(), direction = request.form['Direction'], callFrom = request.form['From'], billRate = float(request.form['BillRate']), cn = request.form['CallerName'], callTo = request.form['To'], callUUID = str(request.form['CallUUID']), #callStatus = request.form['CallStatus'], callState = 'ringing', ) #make a new sCall object print "about to save" c.save() #create state machine daddy = CallStateMachDaddy(c.callUUID) print "created daddy" daddy.e_answer() print "invoked state machine" if daddy.callXMLBuffer: r = daddy.callXMLBuffer daddy.callXMLBuffer = '' print "checked callXMLBuffer" print "type c = "+str(type(c)) print "type daddy = " +str(type(daddy)) c.callDaddyPickle = pickle.dumps(daddy) print "stuffed callDaddyPickle" c.save() #send response to Plivo cloud. output = "Plivo Call RESTXML Response => %s" % r print >> sys.stderr, output return render_template('response_template.xml', response=r) except: print "exception in /answer" print >> sys.stderr, str(sys.exc_info()[0]) # These write the nature of the error print >> sys.stderr, str(sys.exc_info()[1]) else: print >> sys.stderr, "Received GET request to /answer." return "Received GET request to /answer."
def callsv2(): if not request.args or not request.args['key'] or request.args['key'] != IOS_API_KEY: abort(401) if request.method == "POST": if not request.json or not 'google_places_id' in request.json or not 'name' in request.json or not 'vicinity' in request.json: abort(400) call = Call(google_places_id=request.json['google_places_id'], name=request.json['name'], vicinity=request.json['vicinity']) if 'ios_device_id' in request.json: call.populate(ios_device_id=request.json['ios_device_id']) try: call.put() return jsonify(call.to_dict()) except CapabilityDisabledError: abort(400)
def schedule_call(day, hour, client): """ Schedules a call between client and their coach on the specified datetime """ try: # first, delete all existing calls for this month # we are in sqlite so we can't use YEAR and MONTH functions... :( for match in db.session.query(Call).filter(Call.client_id == client.id).all(): if match.timeslot.year == day.year and match.timeslot.month == day.month: db.session.delete(match) db.session.commit() except Exception: LOGGER.exception('Failed to delete existing calls') db.session.rollback() # now, add the schedule timeslot = arrow.get(day).replace(hour=CALL_HOURS[hour]).datetime call = Call.create( timeslot=timeslot, client_id=client.id, coach_id=client.coach_id) db.session.add(call) db.session.commit()
def receive_call(request, template=None, form_class=ReceiveCallForm): if request.method == 'POST': fields = request.POST else: fields = request.GET form = form_class(fields) context = {} user = None if form.is_valid(): profile = None try: fragment_type = CallFragment.OUTBOUND_WELCOME_UNKNOWN_USER profile = ApplicantProfile.objects.get(mobile_number=form.cleaned_data['From']) user = profile.user call = Call(applicant=profile, outbound=False, call_sid=form.cleaned_data['CallSid'], phone_number=form.cleaned_data['From'], call_type=INBOUND_CHECK_JOBS) call.save() fragment_type = CallFragment.OUTBOUND_WELCOME_KNOWN_USER except ApplicantProfile.DoesNotExist: call = Call(outbound=False, call_sid=form.cleaned_data['CallSid'], phone_number=form.cleaned_data['From'], call_type=INBOUND_CHECK_JOBS) call.save() fragment = CallFragment(call=call, outbound=True, fragment_type=fragment_type) fragment.save() context['user'] = user return render_to_response(template, context, context_instance=RequestContext(request))
def sendMailResult(): # TODO: test this message = mail.EmailMessage(sender="MercatoLibero <*****@*****.**>", subject="Risultati") users = User.query().fetch() to = "" for user in users: to += user.email + ";" message.to = to calls_open = Call.query(Call.status == "OPEN").fetch() status = Config.query().get() if not status: status = Config() status.is_open = True status.put() if len(calls_open) > 0: path = os.path.join(os.path.dirname(__file__), 'templates', 'mail_results.html') params = dict(open=[e.to_dict() for e in calls_open]) res = template.render(path, params) for o in calls_open: o.status = "CLOSED" o.put() message.html = res message.send()
def manage_add_edit_call(self, product, api_id=None): edit, count, title = False, 1, 'Add API Call' api_settings = g.db.api_settings.find_one() found_product = self.retrieve_product(product) if type(found_product) is str: flash('Product not found, please check the URL and try again') return redirect('/') if api_id: found_call = self.retrieve_api_call(found_product, api_id) if not found_call: flash('API Call was not found', 'error') return redirect('/%s/manage/api' % product) title = 'Edit API Call' edit = True post_url = "/%s/manage/api/edit/%s" % (product, api_id) form, count = helper.generate_edit_call_form( found_product, found_call, api_id ) else: post_url = "/%s/manage/api/add" % product form = helper.add_fields_to_form(count) for i in range(count): temp = getattr(form, 'variable_%i' % i) temp.form.id_value.data = i form.verb.choices = [ (verb.get('name'), verb.get('name')) for verb in api_settings.get('verbs') ] form.group.choices = helper.generate_group_choices(found_product) form.product.data = product if request.method == 'POST' and form.validate_on_submit(): api_call = Call(request.form.to_dict()) api_call.variables = helper.get_vars_for_call( list(request.form.iterlists()) ) if api_id: getattr(g.db, found_product.db_name).update( { '_id': ObjectId(api_id) }, { '$set': api_call.__dict__ } ) flash('API Call was successfully updated', 'success') else: try: getattr(g.db, found_product.db_name).insert( api_call.__dict__ ) flash('API Call was added successfully', 'success') except: flash( 'There was an issue storing the API Call. Check ' 'the product and ensure the db_name is specified', 'error' ) return redirect('/%s/manage/api' % product) else: if request.method == 'POST': flash( 'Form validation error, please check the ' 'form and try again', 'error' ) return render_template( 'manage/manage_call_add_edit.html', title=title, form=form, count=count, edit=edit, post_url=post_url, cancel_return='/%s/manage/api' % product, )
def get(self): calls_open = Call.query(Call.status == "OPEN").fetch() calls_past = Call.query(Call.status == "CLOSED").fetch() template_values = dict(open=[e.to_dict(self.user) for e in calls_open], past=[e.to_dict() for e in calls_past], is_open=is_open_or_close()) self.render_template('index.html', template_values)
def twilio_call(request): # if request.method is not 'GET': # return HttpResponse(status=400) account_sid = secrets.TWILIO_ACCOUNT_SID # Your Account SID from www.twilio.com/console auth_token = secrets.TWILIO_ACCOUNT_SECRET # Your Auth Token from www.twilio.com/console required = ['name', 'npeople', 'datetime', 'resid', 'cusphone', 'lang'] for req in required: if req not in request.GET: return JSONResponse(status=400) name = request.GET.get('name') num_people = request.GET.get('npeople') timestamp = request.GET.get('datetime') jptz = pytz.timezone('Asia/Tokyo') dt = datetime.datetime.fromtimestamp(float(timestamp), tz=jptz) shopid = request.GET.get('resid') if request.GET.get('lang') == "ja": language = Call.JAPANESE else: language = Call.ENGLISH cus_phone = request.GET.get('cusphone') shop_info = Venue.objects.get(pk=shopid) #res_phone = shop_info.phone res_phone = secrets.TEST_PHONE res_name = shop_info.name call_info = Call() call_info.name = name call_info.num_people = num_people call_info.date_time = dt call_info.res_phone = res_phone call_info.cus_phone = cus_phone call_info.language_opt = language call_info.res_name = res_name call_info.save() # After save, I have this id. pk = call_info.pk # Make request to Twilio. url = "http://tjr.tonny.me/reservation/" + str(pk) + '/' client = TwilioRestClient(account_sid, auth_token) try: call = client.calls.create( url=url, to=res_phone, from_=secrets.TWILIO_PHONE, status_callback="http://tjr.tonny.me/callingstatus/" + str(pk) + '/', status_callback_method="POST", ) except TwilioRestException as e: print(e) serializer = CallSerializer(call_info) return JSONResponse(serializer.data)
def manage_add_edit_call(self, product, api_id=None): edit, count, title = False, 1, 'Add API Call' api_settings = g.db.api_settings.find_one() found_product = self.retrieve_product(product) if type(found_product) is str: flash('Product not found, please check the URL and try again') return redirect('/') if api_id: found_call = self.retrieve_api_call(found_product, api_id) if not found_call: flash('API Call was not found', 'error') return redirect('/%s/manage/api' % product) title = 'Edit API Call' edit = True post_url = "/%s/manage/api/edit/%s" % (product, api_id) form, count = helper.generate_edit_call_form( found_product, found_call, api_id) else: post_url = "/%s/manage/api/add" % product form = helper.add_fields_to_form(count) for i in range(count): temp = getattr(form, 'variable_%i' % i) temp.form.id_value.data = i form.verb.choices = [(verb.get('name'), verb.get('name')) for verb in api_settings.get('verbs')] form.group.choices = helper.generate_group_choices(found_product) form.product.data = product if request.method == 'POST' and form.validate_on_submit(): api_call = Call(request.form.to_dict()) api_call.variables = helper.get_vars_for_call( list(request.form.iterlists())) if api_id: getattr(g.db, found_product.db_name).update( {'_id': ObjectId(api_id)}, {'$set': api_call.__dict__}) flash('API Call was successfully updated', 'success') else: try: getattr(g.db, found_product.db_name).insert(api_call.__dict__) flash('API Call was added successfully', 'success') except Exception: flash( 'There was an issue storing the API Call. Check ' 'the product and ensure the db_name is specified', 'error') return redirect('/%s/manage/api' % product) else: if request.method == 'POST': flash( 'Form validation error, please check the ' 'form and try again', 'error') return render_template( 'manage/manage_call_add_edit.html', title=title, form=form, count=count, edit=edit, post_url=post_url, cancel_return='/%s/manage/api' % product, )