def post(postid=None): isError = False error = "" curr_loc = database.get_location(postid) print curr_loc curr_comments = database.get_comments(postid) if request.method == "GET": if 'username' in session: user = database.get_user(session['username']); return render_template("post.html", location=curr_loc,get_timestamp=get_timestamp, comments=curr_comments, get_votes=database.get_votes_pst,postid=postid,session=session,user=user) return render_template("post.html", location=curr_loc,get_timestamp=get_timestamp, comments=curr_comments, get_votes=database.get_votes_pst,postid=postid,session=session) else: if 'username' in session: user=database.get_user(session['username']); rated() postid = postid if "content" in request.form: content = request.form['content'] if content == "": error = "You didn't write anything!" isError=True return render_template("post.html", error=error, isError=isError, location=curr_loc, get_timestamp=get_timestamp, comments=curr_comments, get_votes=database.get_votes, postid=postid, session=session, user=user) elif "username" in session: author = session['username'] user = database.get_user(author) database.add_comment(None, content, postid, author) users.update( user, {'$push':{'comments':postid}} ) #return redirect(url_for("post",postid=postid,session=session)) #return redirect(url_for("post",postid=postid)) return redirect(url_for("post",postid=postid,session=session, isError=isError, error=error))
def run_main_reddit_loop(): global praw, database, upload_timer #Main loop the listens to new comments on some subreddit for c in praw.helpers.comment_stream(r, subreddit): if check_condition(c): if not database.did_reply_comment(c.id): submission = r.get_submission(submission_id=c.permalink) flat_comments = praw.helpers.flatten_tree(submission.comments) already_commented = False for comment in flat_comments: if str(comment.author) == secret_keys.reddit_username: database.add_comment(c.id) database.add_thread(c.link_id, c.link_url, '') already_commented = True break if not already_commented: bot_action(c) if (time.time() - upload_timer) > upload_timeout: upload_timer = time.time() print "Trying to send a comment" try: reddit_comment, msg = upload_queue[0] print reddit_comment.permalink, msg reddit_comment.reply(msg) upload_queue.pop() except: pass for msg in r.get_unread(limit=None): if msg.new and len(msg.context) == 0: handle_private_msg(msg)
def test_get_comment(session, note, user): """ test getting comment """ add_comment(session, "hi", note, user) comment = session.query(Comment).filter_by(body="hi").one() comment2 = get_comment(session, comment.id, note, user) assert comment.body == comment2.body
def parse_get_request(get_parameters): """Парсит строку с парамаетрами GET запроса""" get_params = parse_qs(get_parameters) current_page = 1 error_message = '' if get_params.get("page"): current_page = int(get_params.get("page")[0]) else: if get_params.get("comment"): if get_params.get("firstname"): if get_params.get("lastname"): valid_email = True if get_params.get("email"): valid_email = validate_email(get_params.get("email")[0]) if valid_email: commentator_name = get_params.get("firstname")[0] comment = get_params.get("comment")[0] database.add_comment(comment, commentator_name) else: error_message = 'Error invalid email' else: error_message = 'Error empty lastname' else: error_message = 'Error empty name' else: error_message = "Error empty comment" return current_page, error_message
def run_main_reddit_loop(): global praw,database,upload_timer #Main loop the listens to new comments on some subreddit for c in praw.helpers.comment_stream(r, subreddit): if check_condition(c): if not database.did_reply_comment(c.id): submission = r.get_submission(submission_id=c.permalink) flat_comments = praw.helpers.flatten_tree(submission.comments) already_commented = False for comment in flat_comments: if str(comment.author) == secret_keys.reddit_username: database.add_comment(c.id) database.add_thread(c.link_id,c.link_url,'') already_commented = True break if not already_commented: bot_action(c) if (time.time() - upload_timer) > upload_timeout : upload_timer = time.time() print "Trying to send a comment" try: reddit_comment,msg = upload_queue[0] print reddit_comment.permalink,msg reddit_comment.reply(msg) upload_queue.pop() except: pass for msg in r.get_unread(limit=None): if msg.new and len(msg.context) == 0: handle_private_msg(msg)
def process_comment(comment): """Processes a comment, and decides how to update the repostitory. Args: comment: The comment to process. """ report_processing_func = None fetched_comment = db.get_comment(comment.id, comment.ticker) if fetched_comment == None: # Comment doesn't exist in database, create new. comment.set_compound(sa.performsentimentanalysis(comment.body)) db.add_comment(comment) # Since comment did not previously exist, add it to daily report and calculate new averages. def add_comment_to_report(daily_report): daily_report.add_comment(comment) report_processing_func = add_comment_to_report else: change_in_score = comment.score - fetched_comment.score if change_in_score == 0: # No change in score, return. return # Comment exists in database and score has changed, update. db.update_comment(comment) # Comment already exists, so it has been previously used in daily report calculations, we only want to change overall score of the report. def update_report_score(daily_report): daily_report.add_to_score(change_in_score) report_processing_func = update_report_score process_comment_into_daily_report(comment, report_processing_func)
def handle_private_msg(msg, verbose=True): if database.did_reply_comment(msg.id): return urls = re.findall( 'http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', msg.body) for url in urls: print 'URL from msg: ', url uploaded_colorized_image_url = colorize_and_upload_from_url(url) if len(uploaded_colorized_image_url ) == 0 or 'already_colorized' in uploaded_colorized_image_url: msg.mark_as_read() print 'From Private msg :: There was an error while trying to colorize and upload the photo , %s', url return '' msg_to_send = 'Hi I\'m colorizebot. I was trained to color b&w photos (not comics or rgb photos! Please do not abuse me :{}).\n\n This is my attempt to color your image, here you go : %s \n\n This is still a **beta-bot**. If you called the bot and didn\'t get a response, pm us and help us make it better. \n\n [For full explanation about this bot\'s procedure](http://whatimade.today/our-frst-reddit-bot-coloring-b-2/) | [code](https://github.com/dannyvai/reddit_crawlers/tree/master/redditBotColorize)' % ( uploaded_colorized_image_url) try: res = msg.reply(msg_to_send) msg.mark_as_read() database.add_comment(msg.id) except: traceback.print_exc()
def picture(urluser=None, urltitle=None): picture = get_picture(urluser, urltitle) if not picture: return redirect(url_for('user', urluser=urluser)) if request.method == 'POST': if not logged_in(): return redirect(url_for('login')) username = get_user()['username'] author = urluser date_uploaded = urltitle date_added = get_time(time.time()) message = request.form['message'] database.add_comment(username, author, date_uploaded, date_added, message) app.logger.info(username + ' posted a comment on /' + urluser + '/' + urltitle) return redirect(url_for('picture', urluser=urluser, urltitle=urltitle)) comments = get_comments(urluser, urltitle) favourites = [] if logged_in(): fav = get_favourites(get_user()['username']) if fav: for f in fav: favourites.append(f['author'] + f['date_uploaded']) return render_template('picture.html', pagetitle=urltitle, user=get_user(), picture=picture, comments=comments, favourites=favourites)
def bot_action(c, verbose=True): if not database.did_reply_thread(c.link_id): img_url = c.link_url uploaded_colorized_image_url = colorize_and_upload_from_url(img_url) if len(uploaded_colorized_image_url) == 0: print 'From bot action :: There was an error while trying to colorize and upload the photo , %s' % img_url return '' #Reply to the one who summned the bot elif 'already_colorized' in uploaded_colorized_image_url: msg = 'Hi I\'m colorizebot. I was trained to color b&w photos (not comics or rgb photos! Please do not abuse me :{}).\n\n Your photo seems to be already colored, Please try uploading another photo. \n\n This is still a **beta-bot**. If you called the bot and didn\'t get a response, pm us and help us make it better. \n\n [For full explanation about this bot\'s procedure](http://whatimade.today/our-frst-reddit-bot-coloring-b-2/) | [code](https://github.com/dannyvai/reddit_crawlers/tree/master/redditBotColorize)' else: msg = 'Hi I\'m colorizebot. I was trained to color b&w photos (not comics or rgb photos! Please do not abuse me :{}).\n\n This is my attempt to color your image, here you go : %s \n\n This is still a **beta-bot**. If you called the bot and didn\'t get a response, pm us and help us make it better. \n\n [For full explanation about this bot\'s procedure](http://whatimade.today/our-frst-reddit-bot-coloring-b-2/) | [code](https://github.com/dannyvai/reddit_crawlers/tree/master/redditBotColorize)' % ( uploaded_colorized_image_url) else: uploaded_colorized_image_url = image_downloader.get_secret_image_url() msg = 'Hi I\'m colorizebot. \n\n It seems this photo has been requested to be colorized already. Here\'s something else instead: %s \n\n [For full explanation about this bot\'s procedure](http://whatimade.today/our-frst-reddit-bot-coloring-b-2/) | [code](https://github.com/dannyvai/reddit_crawlers/tree/master/redditBotColorize)' % ( uploaded_colorized_image_url) try: res = c.reply(msg) database.add_thread(c.link_id, c.link_url, uploaded_colorized_image_url) database.add_comment(c.id) except: upload_queue.append((c, msg)) traceback.print_exc()
def test_delete_comment(session, note, user): """ test deleting comment """ add_comment(session, "bye", note, user) comment = session.query(Comment).filter_by(body="bye").one() delete_comment(session, comment.id, note, user) count = session.query(Comment).count() assert count == 0
def create_comment(note_id): """ Controller for adding comments """ note = get_note(g.session, note_id, current_user) form = request.form body = form["body"] add_comment(g.session, body, note, current_user) return redirect(url_for("view_note", note_id=note_id))
async def create_comment(request, id): comment = { 'post_id': id, 'content': request.form.get('comment'), 'create_at': datetime.now() } db.add_comment(comment) return redirect(app.url_for('post', id=id))
def story(): if request.method=="POST": if request.form["button"]=="comment": comment=str(request.form["comments"]) title=str(request.form["title"]) database.add_comment(title,comment) return render_template("story.html",title=title,comments=database.get_comments(title)) if request.form["button"]=="go back": return redirect(url_for("index"))
def test_add_comment(session, note, user): """ test adding comment """ commentbody = "Wow comments wow" add_comment(session, commentbody, note, user) comment = session.query(Comment).filter_by(owner_id=user.id).one() commentcount = session.query(Comment).filter_by(owner_id=user.id).count() assert commentcount == 1 assert comment.body == commentbody
def add_lesson(self): global day count = 0 for i in db.get_lessons(day): if i != '': count += 1 if count == 9: return text, ok = QInputDialog.getText(self, 'Урок', 'Введите название урока') if ok: db.add_schedule(day, str(text)) db.add_homework(db.take_lesson(day)) db.add_comment(db.take_lesson(day)) lessons = db.get_lessons(day) for i in range(9): self.table.setItem(i, 0, QTableWidgetItem(lessons.pop()))
def handle_private_msg(msg,verbose=True): if database.did_reply_comment(msg.id): return urls = re.findall('http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', msg.body) for url in urls: print 'URL from msg: ',url uploaded_colorized_image_url = colorize_and_upload_from_url(url) if len(uploaded_colorized_image_url) == 0 or 'already_colorized' in uploaded_colorized_image_url: msg.mark_as_read() print 'From Private msg :: There was an error while trying to colorize and upload the photo , %s',url return '' msg_to_send = 'Hi I\'m colorizebot. I was trained to color b&w photos (not comics or rgb photos! Please do not abuse me :{}).\n\n This is my attempt to color your image, here you go : %s \n\n This is still a **beta-bot**. If you called the bot and didn\'t get a response, pm us and help us make it better. \n\n [For full explanation about this bot\'s procedure](http://whatimade.today/our-frst-reddit-bot-coloring-b-2/) | [code](https://github.com/dannyvai/reddit_crawlers/tree/master/redditBotColorize)'%(uploaded_colorized_image_url) try: res = msg.reply(msg_to_send) msg.mark_as_read() database.add_comment(msg.id) except: traceback.print_exc()
def application(environ, start_response): status = '200 OK' page = read_html_page() current_page = 1 error_message = '' if environ['QUERY_STRING'] != "": get_params = parse_qs(environ['QUERY_STRING']) if get_params.get("page"): current_page = int(get_params.get("page")[0]) else: if get_params.get("comment"): if get_params.get("firstname"): if get_params.get("lastname"): valid_email = True if get_params.get("email"): valid_email = validate_email(get_params.get("email")[0]) if valid_email: commentator_name = get_params.get("firstname")[0] comment = get_params.get("comment")[0] database.add_comment(comment, commentator_name) else: error_message = 'Error invalid email' else: error_message = 'Error empty lastname' else: error_message = 'Error empty name' else: error_message = "Error empty comment" comments = database.get_comments() page = comment_page.add_comments_page(page, comments, current_page, error_message) response_headers = [ ('Content-type', 'text/html'), ('Content-Length', str(len(page)))] start_response(status, response_headers) return [page]
def submit_review(project_id, review_id): token = request.headers.get('X-USR-TOKEN') if token is None: abort(403) if not request.json: return jsonify(STATUS_REQ_JSON) if not common.check_sha1(project_id): return jsonify(STATUS_BAD_REQUEST) comment = request.json.get('comment') commit_labels = request.json.get('commitLabels') if not comment and not commit_labels: return jsonify(STATUS_BAD_REQUEST) if comment: database.add_comment(review_id, comment, token) commit2labels = dict() new_labels = [] for label in commit_labels: commit_id = label.get('commitId') if not commit_id: return jsonify(STATUS_BAD_REQUEST) if commit_id not in commit2labels: commit2labels[commit_id] = [] label_id = label.get('labelId') if label_id: commit2labels[commit_id].append(label_id) continue label_name = label.get('labelName') if label_name: label_id = database.add_label(label_name, 'Customized', token) new_labels.append({'label': {'id': label_id, 'name': label_name}}) commit2labels[commit_id].append(label_id) continue return jsonify(STATUS_BAD_REQUEST) for commit_id, label_ids in commit2labels.items(): database.add_review(comparison_id=review_id, commit_id=commit_id, label_ids=label_ids, token=token) return jsonify({'status': 0, 'data': new_labels})
def bot_action(c, verbose=True): if not database.did_reply_thread(c.link_id): img_url = c.link_url uploaded_colorized_image_url = colorize_and_upload_from_url(img_url) if len(uploaded_colorized_image_url) == 0: print 'From bot action :: There was an error while trying to colorize and upload the photo , %s' % img_url return '' #Reply to the one who summned the bot msg = 'Hi I\'m colorizebot. I was trained to color b&w photos (not comics or rgb photos! Please do not abuse me :{}).\n\n This is my attempt to color your image, here you go : %s \n\n This is still a **beta-bot**. If you called the bot and didn\'t get a response, pm us and help us make it better. \n\n [For full explanation about this bot\'s procedure](http://whatimade.today/our-frst-reddit-bot-coloring-b-2/) | [code](https://github.com/dannyvai/reddit_crawlers/tree/master/redditBotColorize)'%(uploaded_colorized_image_url) else: uploaded_colorized_image_url = image_downloader.get_secret_image_url() msg = 'Hi I\'m colorizebot. \n\n IIt seems this photo has been requested to be colorized already. Here\'s something else instead: %s \n\n [For full explanation about this bot\'s procedure](http://whatimade.today/our-frst-reddit-bot-coloring-b-2/) | [code](https://github.com/dannyvai/reddit_crawlers/tree/master/redditBotColorize)'%(uploaded_colorized_image_url) try: res = c.reply(msg) database.add_thread(c.link_id,c.link_url,uploaded_colorized_image_url) database.add_comment(c.id) except: upload_queue.append((c,msg)) traceback.print_exc()
def test_cascades_work(session, user, note): """ make sure all things related to a note are deleted when a note is deleted """ user2 = create_user(session, "dafdsfas", "dfadsfdsaf") add_permission(session, PermissionType.READ, user2, note, triggered_by=user) add_comment(session, "fdsa", note, user) create_rating(session, user, note, 5) delete_note(session, note.id, user) permissioncheck = ( session.query(NotePermission) .filter_by(user_id=user2.id, note_id=note.id) .first() ) ratingcheck = ( session.query(Rating).filter_by(owner_id=user.id, note_id=note.id).first() ) commentcheck = ( session.query(Comment).filter_by(owner_id=user.id, note_id=note.id).first() ) assert permissioncheck is None assert ratingcheck is None assert commentcheck is None
def add_comment(user, idea_id, comment_text): db.add_comment(user, idea_id, comment_text) return jsonify({"response": ["Success"]})
def add_comment(user, idea_id, comment_text): db.add_comment(user, idea_id, comment_text) return {"response": "Success"}
def add_comment(image_id): print 'Entering send_image function' user_id = session['user_id'] comment = request.form['comment'] status = app_data.add_comment(user_id, image_id, comment) return redirect(url_for('display_details', image_id=image_id))
def test_get_comments(self): database.add_story("new story") database.add_comment("new story","comment one") database.add_comment("new story","comment one") comments=database.get_comments("new story") self.assertEqual(["comment one","comment one"],comments)
def test_add_comment(self): database.add_story("new story") database.add_comment("new story","comment one") database.add_comment("new story","comment two") self.assertEqual(2,len(database.get_comments("new story")))
def recette(recipe_id = None): if recipe_id and request.method != 'POST': app.logger.debug('Recipe ID' + str(recipe_id)) recipe = get_recipe(recipe_id) if not recipe: app.logger.debug('404 NOT FOUND') abort(404) app.logger.debug(recipe['name']) return render_template('recette.html', recipe = recipe) elif recipe_id and request.method == 'POST' and "_method" not in request.form.keys(): app.logger.debug(request.form) new_comment = { "author": request.form['author'], "date": date.today().strftime("%d-%m-%Y"), "content": request.form['content'] } app.logger.debug(new_comment) add_comment(recipe_id, new_comment) recipe = get_recipe(recipe_id) if not recipe: app.logger.debug('404 NOT FOUND') abort(404) app.logger.debug(recipe['comments']) return render_template('recette.html', recipe = recipe, add = True) elif recipe_id and (("_method" in request.form.keys() and request.form['_method'] == 'PUT') or request.method == 'PUT'): app.logger.debug(request.form) if len(request.form['old_date']) > 10: new_date = request.form['old_date'][:10] + " (modifié le " + date.today().strftime("%d-%m-%Y") + ")" elif len(request.form['old_date']) == 10: new_date = request.form['old_date'] + " (modifié le " + date.today().strftime("%d-%m-%Y") + ")" edited_comment = { "author": request.form['author'], "date": new_date, "content": request.form['new_content'] } edit_comment(recipe_id, edited_comment, request.form['old_date'], request.form['old_content']) recipe = get_recipe(recipe_id) if not recipe: app.logger.debug('404 NOT FOUND') abort(404) return render_template('recette.html', recipe = recipe, edit = True) elif recipe_id and (("_method" in request.form.keys() and request.form['_method'] == 'DELETE') or request.method == 'DELETE'): app.logger.debug(request.form) deleted_comment = { "author": request.form['author'], "date": request.form['date'], "content": request.form['content'] } delete_comment(recipe_id, deleted_comment) recipe = get_recipe(recipe_id) if not recipe: app.logger.debug('404 NOT FOUND') abort(404) return render_template('recette.html', recipe = recipe, delete = True) app.logger.debug('404 NOT FOUND') abort(404)