def alice_skill(request): try: req_json = json.loads(request.body) except Exception: req_json = {'version': 1, 'session': 1} uid = req_json['session']['user_id'] cmd = req_json['request']['command'] if uid not in aliceSession: aliceSession[uid] = 0 response = { "version": req_json['version'], "session": req_json['session'], "response": { "end_session": True, 'text': 'Привет :D' } } if aliceSession[uid] == 0: # TODO: make it sound must better response['response']['text'] = 'Привет!' aliceSession[uid] += 1 elif aliceSession[uid] == 1: if len(cmd) < 20: response['response'][ 'text'] = 'Очень мало слов. Текст должен быть более 20 символов' else: Feedback(text=cmd).save() response['response']['text'] = 'Спасибо за отзыв!' response['response']['end_session'] = True aliceSession[uid] = aliceSession[uid] % 2 return JsonResponse(response, json_dumps_params={'ensure_ascii': False})
def test_feedback_product_name_str_test(self): test_feedback = Feedback(product_name="test", user_feedback="good", published_date="2020-05-06", ratings='4', upvote=1) self.assertEqual(str(test_feedback.product_name), "test")
def send_feedback_view(request): if request.method == "POST": sender_email = request.POST['email'] text = request.POST['text'] feedback = Feedback() feedback.sender_email = sender_email feedback.text = text feedback.save() return redirect('index')
def addfeedback(request): objlist = Feedback.objects.filter(sender_id=request.session["student"]) if request.method == "POST": obj = Feedback() obj.sender_id = request.session["student"] obj.feedback = request.POST.get("feedback") obj.f_date = datetime.date.today() obj.save() return render(request,'feedback/addfeedbackstud.html')
def giveFeedback(request): if request.method == 'POST': name = request.POST['name'] email = request.POST['email'] phone = request.POST['phone'] message = request.POST['message'] feed = Feedback(name=name, email=email, phone=phone, message=message) feed.save() return redirect('home')
def feedback(request): response = {} status = 200 feedback_message = request.POST["message"] new_feedback = Feedback() new_feedback.message = feedback_message if request.user.is_authenticated: new_feedback.owner = request.user new_feedback.save() return JsonResponse(response, status=status)
def feedback(request): status = 405 response = {} if request.is_ajax() and request.method == 'POST': status = 200 feedback_message = request.POST['message'] new_feedback = Feedback() new_feedback.message = feedback_message if request.user.is_authenticated: new_feedback.owner = request.user new_feedback.save() return JsonResponse(response, status=status)
def feedback(request): request.POST = json.loads(request.body.decode('utf-8')) #Each feedback should be no longer than 500 letters, or it will be truncated. feedback_info = request.POST['feedback'].strip()[:500] if len(feedback_info) == 0: return JsonResponse( get_json_dict(data={}, err_code=-1, message="Empty Feedback")) else: feedback = Feedback(feedback=feedback_info) feedback.save() return JsonResponse( get_json_dict(data={}, err_code=0, message="Feedback Success"))
def feedback(request): status = 405 if request.is_ajax() and request.method == 'POST': status = 200 feedback_message = request.POST['message'] feedback_owner = request.user new_feedback = Feedback() new_feedback.message = feedback_message if request.user.is_authenticated(): new_feedback.owner = request.user new_feedback.save() return HttpResponse(status=status)
def save(self): feedback = Feedback() feedback.save() for key, value in self.cleaned_data.items(): if not key.startswith("question_"): continue q_id = key.split("_")[1] question = Question.objects.get(id=q_id) response = Response(feedback=feedback, question=question) if question.qtype == 1: response.text = value elif question.qtype == 2: response.selected = value response.save()
def submit(): form = FeedbackForm(request.form) if form.validate_on_submit(): data = form.data feedback = Feedback(data['customer_name'], data['dealer'], data['rating'], data['comments']) db.session.add(feedback) db.session.commit() feedback.send_email() flash('Your feedback was succesfully submitted') return redirect(url_for('main.success')) else: flash(form.errors, 'error') return render_template('index.html', form=form)
def add(request): name = 'Kim' email = '*****@*****.**' comment = 'Hello' name = request.GET.get('name') email = request.GET.get('email') comment = request.GET.get('comment') fb = Feedback(name=name, email=email, comment=comment, createDate=datetime.now()) fb.save() return HttpResponse("<h1>Add!</h1>")
def feedback(request): if request.method == 'POST': data = parse_qs(request.POST.get('request')) print('data', data['name'], data['comment']) author = data['name'][0] if 'name' in data else None phone = data['cell'][0] if 'cell' in data else None content = data['comment'][0] if 'comment' in data else None if not (author and content): return JsonResponse({'message': 'Invalid data'}, status=400) Feedback(author=author, phone=phone, content=content).save() return JsonResponse({'message': 'Success'}) elif request.method == 'GET': feedbacks = Feedback.objects.all() socials = SocialSection.objects.all() output = [] categoires = Category.objects.all() for category in categoires: products = Product.objects.filter(categories=category) output.append({ 'name': category.name, 'slug': category.slug, 'is_show': category.is_show, }) shares = SharesSection.objects.all() content = { 'output': output, 'shares': shares, 'socials': socials, 'feedbacks': feedbacks } tempalte = 'page/feedback.html' return render(request, tempalte, content)
def feedback(): form = feedbackForm() if form.validate_on_submit(): record = Feedback.query.filter_by(customerName=form.customerName.data).first() if record is None: reqFeedback = Feedback(customerName=form.customerName.data, dealerName=form.dealerName.data, rating=form.ratingChoice.data, comments=form.comments.data) db.session.add(reqFeedback) db.session.commit() flash('Thank you for feedback!!', category='success') print(reqFeedback) sendMailOnSubmission(reqFeedback) return redirect(url_for('input.feedback')) else: flash('You have already provided your feedback. Thanks again!!', category='warning') return redirect(url_for('input.feedback')) return render_template('feedback.html', title='Feedback', form=form)
def home(request): #return HttpResponse('Home page') #return render(request,'homepage.html') courseCode = request.GET.get('code', '') request.session['q'] = [0, 0, 0, 0, 0, 0] # request.session['prn']=request.session['prn'] # request.session['courseCode']=request.session['courseCode'] feedbackObj = Feedback(prn=request.session['prn'], courseCode=courseCode, q1=request.session['q'][0], q2=request.session['q'][1], q3=request.session['q'][2], q4=request.session['q'][3], q5=request.session['q'][4], q6=request.session['q'][5]) feedbackObj.save() request.session['f_id'] = feedbackObj.id return render(request, 'index1.html')
def submitFeedback(request): d = {} try: if request.method == "POST": f = Feedback() f.email = request.POST['email'] f.username = request.POST['name'] f.message = request.POST['body'] f.save() deliverEmail("feedbacksubject.html", "feedbackmessage.html", {'f': f}, getAlumClubAdminEmail()) except: d['error'] = "oops........some problem at the server end" json = simplejson.dumps(d) return HttpResponse(json)
def post(self, request, format=None): text = request.POST['text'] if not text.strip(): return Response('Please enter a comment in the box.') client = request.user.client feedback = Feedback(client=client, text=text, date=datetime.now()) feedback.save() subject = "Feedback from %s %s" % (str(client), client.user.email) email_message = text send_queued_mail(subject, email_message, settings.SUPPORT_EMAIL, [settings.SUPPORT_EMAIL], reply_to=client.user.email) return Response(( "<img src='%s/healersource/img/hs_logo_stripe.png' style='float:left; margin-right: 8px;' />" "<p><strong><em>Thanks so much for your suggestions!</em></strong></p>" "<p>We're constantly working to make HealerSource the best possible experience for you, so your feedback is most appreciated. </p>" ) % settings.STATIC_URL)
def process(self, request): resp = Response() email = request.POST.get('email', None) from_page = request.POST.get('from_page', None) feedback = request.POST.get('feedback', None) if feedback is not None: f = Feedback(text=feedback) if email is not None: f.email = email if from_page is not None: try: f.from_page = Page.objects.get(pk=int(from_page)) except ValueError: return resp.set_error(ApiError.INCORRECT_POST_FIELD) except ObjectDoesNotExist: # id == 0 - Home Screen pass f.save() return resp.set_ok() else: return resp.set_error(ApiError.MISSING_POST_FIELD)
def create(self, validated_data): return Feedback(**validated_data)
def handle(self, *args, **options): event_name = options['event_name'][0] try: event = Event.objects.get(name=event_name) except Event.DoesNotExist: self.stdout.write('event does not exist') return if options['flush']: self.stdout.write('Removing all applicants in event %s...' % event_name) self.stdout.write('%s users in the database' % Applicant.objects.all().count()) applicants = Applicant.objects.filter(event__name=event_name) self.stdout.write('%s users in the event %s' % (applicants.count(), event_name)) applicants.delete() self.stdout.write('%s users left in the database' % Applicant.objects.all().count()) if options['applicants']: if not os.path.exists('tmp'): os.makedirs('tmp') with open(options['applicants'], 'rU') as csvfile: applicants = list(csv.reader(csvfile)) event = Event.objects.get_or_create( name=options['event_name'][0])[0] for applicant in applicants[1:]: self.add_applicant( { key: value for (key, value) in zip(applicants[0], applicant) }, event_name) if options['testing']: for _ in xrange(10): applicant = Applicant() applicant.first_name = randomString(10) applicant.last_name = randomString(10) applicant.high_school = '%s High School ' % randomString(8) applicant.hometown = randomString(7) applicant.hometown_state = random.choice(US_STATES)[0] applicant.gender = random.choice(['Mr.', 'Ms.']) applicant.event = event applicant.save() self.stdout.write('Created user %s' % applicant.get_full_name()) if options['feedback']: scholars = McUser.objects.all() applicants = Applicant.objects.all() for scholar in scholars: chance = random.random() / 3 for applicant in applicants: if random.random() < chance: try: f = Feedback.objects.get(scholar=scholar, applicant=applicant) except Feedback.DoesNotExist: f = Feedback(scholar=scholar, applicant=applicant) f.rating = random.choice([0, 1, 2, 3, 4, 5]) f.interest = random.choice([0, 1, 3, 4, 5]) f.comments = randomWords(random.randint(4, 15)) f.save() if options['pics']: for f in os.listdir('tmp'): f_split = f.split('.')[0].split(',') scholar_name = normalize_name('%s%s' % (f_split[1], f_split[0])) try: app = Applicant.objects.get(norm_name=scholar_name, event__name=event_name) except Applicant.DoesNotExist: self.stdout.write('Could not find user %s for pic %s' % (scholar_name, f)) continue extension = f.split('.')[-1] file_name = '%s,%s-fw.%s' % (app.last_name, app.first_name, extension) with open('tmp/%s' % f, 'rb') as img_file: app.actual_pic.save(file_name, File(img_file), save=True) app.save() self.stdout.write('Saved pic %s for %s' % (f, scholar_name))
def test_last_feedback_duration_attribute(self): self.feedback.duration = timedelta(hours=3) self.feedback.save() feedback = Feedback(subject=self.subject) feedback.save() self.assertEqual(feedback.duration, self.feedback.duration)
def save(self): user = self.context.get("request").user customer = user.customer if self.validated_data["feature_request_title"]: feature_request, created = FeatureRequest.objects.get_or_create( customer=customer, title=self.validated_data["feature_request_title"]) if created: tracking.feature_request_created(user, tracking.EVENT_SOURCE_CE) fr_id = feature_request.pk else: fr_id = self.validated_data["feature_request_id"] if self.validated_data["app_user_email"]: app_user, created = AppUser.objects.update_or_create( customer=customer, email=self.validated_data["app_user_email"], defaults={ "name": self.validated_data["app_user_name"], }, ) app_user_id = app_user.pk elif self.validated_data["app_user_name"]: try: app_user, created = AppUser.objects.update_or_create( customer=customer, name=self.validated_data["app_user_name"], email=None, ) except AppUser.MultipleObjectsReturned: app_user = AppUser.objects.filter( customer=customer, name=self.validated_data["app_user_name"], email=None, )[0] app_user_id = app_user.pk else: app_user_id = self.validated_data["app_user_id"] feedback = Feedback( customer=customer, created_by=user, user_id=app_user_id, feature_request_id=fr_id, problem=self.validated_data["problem"], solution="", # self.validated_data['solution'], source_url=self.validated_data["source_url"], feedback_type=self.validated_data["feedback_type"], ) feedback.save() total_created_by_user = Feedback.objects.filter( customer=customer, created_by=user).count() first_entry = total_created_by_user == 1 tracking.feedback_created(user.id, user.customer, feedback, tracking.EVENT_SOURCE_CE) OnboardingTask.objects.filter( customer=customer, task_type=OnboardingTask.TASK_CREATE_FEEDBACK_CE).update( completed=True, updated=timezone.now()) return {"id": feedback.pk, "first_entry": first_entry}
def save(self): user = self.context.get("request").user customer = user.customer fr_title = self.validated_data.get("feature_request_title", "") if fr_title: feature_request, created = FeatureRequest.objects.get_or_create( customer=customer, title__iexact=fr_title, defaults={ "title": fr_title, }) if created: tracking.feature_request_created(user, tracking.EVENT_SOURCE_API) fr_id = feature_request.pk else: fr_id = None email = self.validated_data.get("person_email", "") name = self.validated_data.get("person_name", "") if email: app_user, created = AppUser.objects.update_or_create( customer=customer, email__iexact=email, defaults={ "email": email, "name": name, }, ) app_user_id = app_user.pk elif name: app_user, created = AppUser.objects.get_or_create( customer=customer, name=name, defaults={ "email": email or None, }) app_user_id = app_user.pk else: app_user_id = None feedback = Feedback( customer=customer, created_by=user, user_id=app_user_id, feature_request_id=fr_id, problem=self.validated_data["problem"], source_url=self.validated_data.get("source_url", ""), feedback_type=self.validated_data["feedback_type"], state=self.validated_data["state"], source_username="******", ) feedback.save(override_auto_triage=True) for theme_name in self.validated_data.get("tags", list()): defaults = { "title": theme_name, } theme, created = Theme.objects.get_or_create( customer=user.customer, title__iexact=theme_name, defaults=defaults) feedback.themes.add(theme) tracking.feedback_created(user.id, user.customer, feedback, tracking.EVENT_SOURCE_API) return {"id": feedback.pk}
def slack_dialog(request): # noqa: C901 json_payload, slack_settings = validate_slack_request(request) # An error occured in validate_slack_response. So we return a 200 # and tell Slack to not retry. if slack_settings is None: response = HttpResponse(status=200) response["X-Slack-No-Retry"] = "1" return response customer = slack_settings.customer channel_id = json_payload["channel"]["id"] payload_type = json_payload["type"] headers = {"Content-Type": "application/json; charset=utf-8"} if payload_type == "block_actions": # Yes or No button has been clicked if json_payload["actions"][0]["text"]["text"] == "No": # "No" Button clicked - delete ephemeral message delete_ephemeral_message( json_payload["container"]["message_ts"], json_payload["response_url"], headers, ) else: # "Yes" button clicked - show dialog trigger_id = json_payload["trigger_id"] # message_ts is the pointer to the message we care about adding to Savio, NOT the timestamp # of the response to the Yes/No ephemeral message that just got POSTed message_ts = json_payload["actions"][0]["value"] # Get Message so we can display "problem" as a default in the Dialog's problem textarea message_url = "https://slack.com/api/channels.history" message_json = { "oldest": message_ts, "count": 1, "inclusive": True, "channel": channel_id, } headers = { "Content-Type": "application/x-www-form-urlencoded;", "Authorization": "Bearer " + slack_settings.slack_user_access_token, } response = requests.post(message_url, data=message_json, headers=headers) if not response.json()["ok"]: capture_message( f"Error getting Slack Message: message.json: {response.json()}. slack_settings_id: {slack_settings.id}." ) response = HttpResponse(status=200) response["X-Slack-No-Retry"] = "1" return response else: message = response.json()["messages"][0]["text"] dialog_json = get_dialog_json(trigger_id, "show_create_feedback_dialog", message_ts, message, customer) headers = { "Content-Type": "application/json; charset=utf-8", "Authorization": "Bearer " + slack_settings.slack_bot_token, } dialog_url = "https://slack.com/api/dialog.open" response = requests.post(dialog_url, data=json.dumps(dialog_json), headers=headers) if not response.json()["ok"]: capture_message( f"Error generating Slack dialog: response.json: {response.json()}. message: {message}. message_ts: {message_ts}. slack_settings_id: {slack_settings.id}" ) response = HttpResponse(status=200) response["X-Slack-No-Retry"] = "1" return response delete_ephemeral_message( json_payload["container"]["message_ts"], json_payload["response_url"], headers, ) else: # Dialog initiated by message action callback_id = json_payload["callback_id"] if callback_id == "show_create_feedback_dialog": if payload_type == "dialog_submission": # Saving a Posted Dialog slack_user_name = json_payload["user"]["name"] slack_user_id = json_payload["user"]["id"] problem = json_payload["submission"]["problem"] person = json_payload["submission"]["person"] new_person_email = json_payload["submission"][ "new_person_email"] feedback_from = json_payload["submission"]["feedback_from"] feature_request = json_payload["submission"]["feature_request"] response_url = json_payload["response_url"] # Validate submitted data errors = {"errors": []} if not problem: errors["errors"].append({ "name": "problem", "error": "Can't be blank. Please try again.", }) if not feedback_from: errors["errors"].append({ "name": "feedback_from", "error": "Can't be blank. Please try again.", }) if not (person or new_person_email): errors["errors"].append({ "name": "person", "error": "You need to select an existing or new person.", }) errors["errors"].append({ "name": "new_person_email", "error": "You need to select an existing or new person.", }) if len(errors["errors"]) > 0: capture_message( f"Invalid params submitted from Slack. problem: {problem}. person: {person}. feedback_from: {feedback_from}" ) return JsonResponse(errors) # To post to the Slack channel, we first need to get the permalink of the parent message. permalink_url = "https://slack.com/api/chat.getPermalink" shared_ts = json_payload["state"] # Add Auth header to headers. We don't need it for previous posts to response_url, but we do # post web API methods like chat.getPermalink headers[ "Authorization"] = "Bearer " + slack_settings.slack_bot_token permalink_params = { "channel": channel_id, "message_ts": shared_ts } permalink_response = requests.post(permalink_url, params=permalink_params, headers=headers).json() if not permalink_response["ok"]: params = { "text": "There was an error saving your feedback. Please try again.", } requests.post(response_url, data=json.dumps(params), headers=headers) capture_message( f"Invalid permalink from Slack. channel: {channel_id}. message timestamp: {shared_ts}. " ) return HttpResponse(status=406) message_permalink = permalink_response["permalink"] # Look up User. The user in Slack likely won't have a row in our users table. if slack_settings.slack_user_id == slack_user_id: u = slack_settings.user else: u = None # Are we creating a new person, or using an existing one? Figure it out. if person: use_person_id = person else: # handle case where email entered but user exists. try: user = AppUser.objects.get(email=new_person_email, customer_id=customer.id) except AppUser.DoesNotExist: user = AppUser.objects.create(email=new_person_email, customer_id=customer.id) use_person_id = user.id # Save feedback to DB feedback = Feedback( customer=customer, source_url=message_permalink, problem=problem, feedback_type=feedback_from, feature_request_id=feature_request, user_id=use_person_id, source_username=slack_user_name, created_by=u, ) feedback.save() if u: user_id = u.id else: user_id = f"Slack - {slack_user_id}" tracking.feedback_created(user_id, customer, feedback, tracking.EVENT_SOURCE_SLACK) # Then, we'll post a reply to the message as part of a thread post_message_url = "https://slack.com/api/chat.postMessage" now = datetime.datetime.now() unix_time = now.timestamp() savio_feedback_url = settings.HOST + feedback.get_absolute_url( ) date_string = ("<!date^" + repr(int(unix_time)) + "^{date} at {time}^" + savio_feedback_url + "|" + now.strftime("%b %d %Y at %I:%M %p") + ">") company_str = "" if feedback.user.company: company_str = f" @ {feedback.user.company.name}" fr_string = "None" if feedback.feature_request is not None: fr_url = settings.HOST + reverse( "feature-request-feedback-details", kwargs={"pk": feedback.feature_request.id}, ) fr_string = f"<{fr_url}|{feedback.feature_request.title}>" # This Code creates a payload to reply in a thread with the original message as the parent reply_json = { "channel": channel_id, "as_user": False, "link_names": True, "mrkdwn": True, "unfurl_links": True, "thread_ts": shared_ts, "blocks": [ { "type": "context", "elements": [ { "type": "mrkdwn", "text": f"@{slack_user_name} pushed this customer feedback to Savio on {date_string}:", }, ], }, { "type": "section", "text": { "type": "mrkdwn", "text": f"*From*\n{feedback.user.get_name_or_email()}{company_str} ({dict(feedback.TYPE_CHOICES)[feedback.feedback_type]})\n\n*Feedback*\n{problem}\n\n*Feature Request*\n{fr_string}", }, }, ], } # End Code posts a response to the Slack Channel with the message posted to Savio response = requests.post(post_message_url, data=json.dumps(reply_json), headers=headers) elif payload_type == "message_action": # Show a Dialog trigger_id = json_payload["trigger_id"] message = json_payload["message"]["text"] message_ts = json_payload["message_ts"] dialog_json = get_dialog_json(trigger_id, callback_id, message_ts, message, customer) headers = { "Content-Type": "application/json; charset=utf-8", "Authorization": "Bearer " + slack_settings.slack_bot_token, } dialog_url = "https://slack.com/api/dialog.open" response = requests.post(dialog_url, data=json.dumps(dialog_json), headers=headers) return Response(status=status.HTTP_200_OK)