def process_message_existing(): """Store message in database, associated with an existing userconvo""" convo_id = request.form.get('convo') sender_id = session['user'] content = request.form.get('message') convo = Convo.query.get(convo_id) userconvos = convo.userconvos userconvo_id = None for userconvo in userconvos: if userconvo.user_id == sender_id: userconvo_id = userconvo.userconvo_id if userconvo_id is None: print "something weird happened." new_message = Message(userconvo_id=userconvo_id, sent_at=datetime.utcnow(), content=content) print new_message db.session.add(new_message) db.session.commit() flash('Successfully sent message.') return redirect('/account-home')
def choose_deck(self, type_ids=None, base_units=None): message = Message(type="pick", turn=self.get_current_turn(), info=None) if type_ids is not None: message.info = {"units": type_ids} elif base_units is not None: message.info = {"units": [unit.type_id for unit in base_units]} self.queue.put(message)
def cast_unit_spell(self, unit=None, unit_id=None, path=None, path_id=None, cell=None, row=None, col=None, spell=None, spell_id=None): if spell is None and spell_id is None: return None if spell is None: spell = self.get_spell_by_id(spell_id) if row is not None and col is not None: cell = Cell(row, col) if unit is not None: unit_id = unit.unit_id if path is not None: path_id = path.id message = Message(type="castSpell", turn=self.get_current_turn(), info={ "typeId": spell.type_id, "cell": { "row": cell.row, "col": cell.col }, "unitId": unit_id, "pathId": path_id }) self.queue.put(message)
def set_up(self): u = Message() path = u.path(self.id) try: os.remove(path) except Exception, e: pass
def home(): if request.method == 'POST': original_message = request.form['content'] rendered_message = html.escape(str(original_message)) m = Message(content=rendered_message) m.save() body = """ <html> <body> <h1>Class Message Board</h1> <h2>Contribute to the Knowledge of Others</h2> <form method="POST"> <textarea name="content"></textarea> <input type="submit" value="Submit"> </form> <h2>Wisdom From Your Fellow Classmates</h2> """ for m in Message.select(): body += """ <div class="message"> {} </div> """.format(m.content) return body
def home(): if 'csrf_token' not in session: session['csrf_token'] = str(random.randint(10000000, 99999999)) if request.method == 'POST': m = Message(content=request.form['content']) m.save() body = """ <html> <body> <h1>Class Message Board</h1> <h2>Contribute to the Knowledge of Others</h2> <form method="POST"> <textarea name="content"></textarea> <input type="submit" value="Submit"> </form> <h2>Wisdom From Your Fellow Classmates</h2> """ for m in Message.select(): body += """ <div class="message"> {} </div> """.format(m.content) return body
def home(): if request.method == 'POST': m = Message(content=request.form['content']) m.save() body = """ <html> <body> <h1>Class Message Board</h1> <h2>Contribute to the Knowledge of Others</h2> <form method="POST"> <textarea name="content"></textarea> <input type="submit" value="Submit"> </form> <h2>Wisdom From Your Fellow Classmates</h2> """ for m in Message.select(): body += """ <div class="message"> {} </div> """.format(html.escape(m.content)) # a simple approach below to replace < or > # m.content.replace('<', '<').replace('>', '>')) # html.escape does the same replacement, but also looks for other control characters in html return body
async def on_message_received(self, conversation_id: int, sender: Union[Bot, User], text: str, time: datetime) -> int: log.info(f'message received for conversation {conversation_id}') self._validate_conversation_and_peer(conversation_id, sender) conversation = self._active_dialogs[conversation_id] if conversation_id in self._evaluations: raise ValueError('Conversation is finished. Only evaluation is allowed') msg = Message(msg_id=len(conversation.messages), text=text, sender=sender, time=time) conversation.messages.append(msg) receiver = next((p.peer for p in conversation.participants if p.peer != sender), None) if receiver is None: raise RuntimeError('Could not find a receiver for the message') await self._gateway_for_peer(receiver).send_message(conversation_id, msg.msg_id, msg.text, receiver) if len(conversation.messages) >= self.length_threshold: log.info(f'conversation length threshold reached. Finishing the conversation') await self.trigger_dialog_end(conversation_id, sender) else: self._reset_inactivity_timer(conversation_id) return msg.msg_id
def get_messages_by_username(self, username): messages = [] statement = ''' SELECT msg.id, msg.[user_id], [text], expiration_date_utc, msg.created_date_utc FROM [message] msg WITH (NOLOCK) JOIN [user] usr WITH (NOLOCK) ON usr.[id] = msg.[user_id] WHERE usr.username = ?''' try: result = self.engine.execute(statement, username).fetchall() if result is not None: for row in result: messages.append( Message(id=row.id, user_id=row.user_id, text=row.text, expiration_date_utc=row.expiration_date_utc, created_date_utc=row.created_date_utc)) except Exception as ex: raise Exception( SvcUtils.error_message('message lookup failed', { 'id': username, 'error': ex.message })) return messages
def post(self): message_text = self.request.get("message") message = Message() message.message_text = message_text message.put() return self.render_template("hello.html", params={"message": message_text})
def text_reply(msg): ''' print "MsgType: " + str(msg.MsgType) print "MsgId: " + str(msg.MsgId) print "FromUserName: "******"ToUserName: "******"Content: " + msg.Content print "Message: " + msg.text print "Actual Nick Name: " + msg.actualNickName print "IsAt: " + str(msg.isAt) ''' # if msg.isAt: print "New Message: " + msg.text m = Message() m.id = 0 m.from_user = msg.FromUserName m.from_nick = msg.actualNickName m.from_remark = ChatDB.get_remark_by_userid(m.from_user) m.to_user = msg.ToUserName m.to_nick = ChatDB.get_nickname_by_userid(m.to_user) m.content = msg.Content m.recvtime = get_cur_time() m.status = 0 ChatDB.save_new_message(m) # msg.user.send(u'@%s\u2005I received: %s' % (msg.actualNickName, msg.text)) pass
def add_meeting(): ''' send a proposal for a meeting to dog owner :return: homepage template ''' mycursor = DBManager().getCursor() details = request.form username = get_user_logged_in() mycursor.execute("select username from dogs where dog_id=" + details['dog']) owner_username = mycursor.fetchone() mycursor.execute("select name from dogs where dog_id=" + details['dog']) dog_name = mycursor.fetchone() DBManager().connection.commit() sending_date = datetime.now() sending_date_formated = sending_date.strftime('%Y-%m-%d %H:%M:%S') date_time = details['time'].split('T') # the template massage: 'Can I meet {} in {} in {} at {}?\nYes/No' add_message_to_db( Message( username, owner_username[0], 'Can I meet ' + dog_name[0] + ' in ' + date_time[0] + ' in ' + date_time[1] + ' at ' + details['place'] + '?\nYes/No', sending_date_formated, 'True')) return redirect('/homepage')
def add_message(): """Add meesages to Message database""" message = request.form.get("message") author_id = g.user.user_id timestamp = datetime.now() chatroom_id = 1 new_message = Message(author_id=author_id, timestamp=timestamp, text=message, chatroom_id=chatroom_id) db.session.add(new_message) # Messages on line 60 will be passed in to be translated. # Call detect_language(text) and translate_text(target, text) functions. languages = db.session.query(User.language).distinct() # Loop over all existing user distinct languages. And translate the original message # to each language. Add translated messages to database. for language in languages: # languages returns a list of tuples. language is still a tuple of one element. # index language[0] to fix it. trans_text = translate_text(language[0], message).translated_text message_id = new_message.message_id new_translation = Translation(message_id=message_id, trans_text=trans_text, language=language) db.session.add(new_translation) db.session.commit() return ""
def publish_current_state(): # msg = Message(type=MessageType.STATE.value, payload={'session': {'sessionTime':ir['SessionTime']}}) sessionData = SessionData(ir) messages = state.msg_proc.manifest_output() cars = state.car_proc.manifest_output() pits = state.pit_proc.manifest_output() stateMsg = StateMessage(session=sessionData.manifest_output(), messages=messages, cars=cars, pits=pits) msg = Message(type=MessageType.STATE.value, payload=stateMsg.__dict__) data = { 'topic': f'{crossbarConfig.topic}.{state.racelog_event_key}', 'args': [msg.__dict__] } #json_data = json.dumps(data, ensure_ascii=False) to_publish = PublishItem( url=crossbarConfig.url, topic=f'{crossbarConfig.topic}.{state.racelog_event_key}', data=[msg.__dict__]) q.put(to_publish) q.task_done() state.msg_proc.clear_buffer() state.pit_proc.clear_buffer()
def send_message(user_id, user_message, talk_to): user_name = "" # Find user's name with user_id for user in server_data_container.user_list: if user['user_id'] == user_id: user_name = user['user_name'] break format_msg = Message(user_id, talk_to, user_message) # Group chat here if talk_to == 0: print('Group chat', format_msg) format_msg.content = "<%s>: %s" % (user_name, format_msg.content) for user in server_data_container.user_list: if user['user_id'] != user_id: user['message_queue'].put(format_msg) # Individual talk here else: print('Individual chat', format_msg) for user in server_data_container.user_list: if user['user_id'] == talk_to and user_id != talk_to: user['message_queue'].put(format_msg) db = MySQL() db.modify( "INSERT INTO Message (user_id, content, destination) VALUES (%s,%s,%s)", int(user_id), user_message, int(talk_to))
def read_message(self, msg_list): count = 0 c = self.__conn.cursor() c.execute( "SELECT id,from_user,from_nick,from_remark,to_user,to_nick,content,recvtime,reply,sendtime,status FROM message WHERE status=0 ORDER BY id LIMIT 5" ) rows = c.fetchall() if not rows: return count for row in rows: msg = Message() msg.id = row[0] msg.from_user = row[1] msg.from_nick = row[2] msg.from_remark = row[3] msg.to_user = row[4] msg.to_nick = row[5] msg.content = row[6] msg.recvtime = row[7] msg.reply = row[8] msg.sendtime = row[9] msg.status = row[10] msg_list.append(msg) count = count + 1 print("read message id " + str(msg.id)) if count > 10: break return count
def add_message(user_1_id, user_2_id, message): """add a message between two users""" db.session.add( Message(sender_id=user_1_id, receiver_id=user_2_id, message=message)) db.session.commit()
def send_message(): """Processes button request from user's homepage to send their message and location to user's contacts""" # getting current user in session and their active contacts current_user = session.get("user_id") contacts = Contact.query.filter((Contact.user_id == current_user) & (Contact.status == "Active")).all() # obtaining the most recent message object message = Message.query.filter(Message.user_id == current_user)\ .order_by(Message.message_id.desc()).first() # getting user's location from front-end in user-home.html/location-finder.js user_lat = float(request.form.get("lat")) user_lng = float(request.form.get("lng")) user_location = str([user_lat, user_lng]) # DEPRECATED # link = "https://www.google.com/maps/?q={lat},{lng}".format(lat=user_lat, lng=user_lng) # link for testing # link = "http://localhost:5000/map/{user_id}".format(user_id=current_user) # link for deployed site - change for https link = "https://humano.us/map/{user_id}".format(user_id=current_user) for contact in contacts: # Format phone number for Twilio API call phone_digits = ''.join(d for d in contact.contact_phone_number if d.isdigit()) # Twilio API call to send message message_results = send_message_to_recipients(phone_digits, message.message) # import pdb; pdb.set_trace() # create a new sent_message record in DB new_sent_message = SentMessage(user_id=current_user, message_id=message.message_id, contact_id=contact.contact_id, date_created=message_results[1], message_sid=message_results[0], error_code=message_results[2], latitude=user_lat, longitude=user_lng) db.session.add(new_sent_message) print("\n\n\nMESSAGE SENT\n\n\n") # Twilio API call to send location location_results = send_message_to_recipients( contact.contact_phone_number, link) print("\n\n\nLOCATION SENT\n\n\n") db.session.commit() # creating a new instance of the message since prior message has been sent new_message = Message(user_id=current_user, message=message.message) db.session.add(new_message) db.session.commit() return jsonify({"success": "true"})
def put_unit(self, type_id=None, path_id=None, base_unit=None, path=None): fail = False if type_id is not None and type(type_id) is not int: Logs.show_log("put_unit function called with invalid type_id argument!") fail = True if path_id is not None and type(path_id) is not int: Logs.show_log("put_unit function called with invalid path_id argument!") fail = True if base_unit is not None and type(base_unit) is not BaseUnit: Logs.show_log("put_unit function called with invalid base_unit argument") fail = True if path is not None and type(path) is not Path: Logs.show_log("put_unit function called with invalid path argument") fail = True if fail is True: return if base_unit is not None: type_id = base_unit.type_id if path is not None: path_id = path.id if path_id is None or type_id is None: return None message = Message(turn=self.get_current_turn(), type="putUnit", info={ "typeId": type_id, "pathId": path_id }) self.queue.put(message)
def closeConversation(): user = getCurrentUser() if user == chatter: user = makeNewUser() else: user.lastPing = time.time() talkid = request.POST.get('talkid').strip() c = getConversationById(talkid) if not c: return json.dumps({'msg': 'Conversation is already closed'}) partner = c.getMyPartner(user.id) print 'closing conversation of', user.toString(), 'with', partner.name if not partner.id in users: return json.dumps({'msg': 'User is offline'}) 'close conversation' if c in user.conversations: user.conversations.remove(c) c.setAccepted(user.id, value=False) 'update status (to stop blinking on the partner\'s page)' user.lastStatusChange = model.timeMillis() 'remove or send close message' if not c.acceptedBy(partner.id): print 'removing conversation', c.partner1.name, '<-->', c.partner2.name if c in partner.conversations: partner.conversations.remove(c) conversations.remove(c) else: 'send CLOSED system message to partner' message = Message(model.MSG_CLOSED, user, type='s') c.messages.append(message)
def add_messages(): users = select(u for u in User)[:] y = 1 while y < len(users): current = users[y-1] y += 1 for them in users: if them == current: break choice = [current, them] stopper = random.randint(8, 15) start_date = datetime.datetime(2019, 7, 10, 13, 00) for x in reversed(list(random_date(start_date, stopper))): sender = random.choice(choice) receiver = [item for item in choice if item not in [sender]] receiver = receiver[0] body = random.choice(messages) timestamp = x Message(timestamp=timestamp, sender=sender, receiver=receiver, body=body) commit()
def post(self): user = users.get_current_user() if not user: return self.write("You are not logged in!") author = self.request.get("name") email = user.email() sendto = self.request.get("to-mail") subject = self.request.get("to-subject") message = self.request.get("message") if not author: author = "Anonymous" if not sendto: sendto = "Write your email" if not subject: subject = "none" if "<script>" in message: return self.write("insert non JS") msg_object = Message(message=message.replace("<script>", "")) msg_object.author_name = author msg_object.email = email msg_object.sendto = sendto msg_object.subject = subject msg_object.put() return self.redirect_to("message-site")
def home(): if request.method == 'POST': m = Message(content=request.form['content']) m.save() body = """ <html> <body> <h1>Class Message Board</h1> <h2>Contribute to the Knowledge of Others</h2> <form method="POST"> <textarea name="content"></textarea> <input type="submit" value="Submit"> </form> <h2>Wisdom From Your Fellow Classmates</h2> """ for m in Message.select(): body += """ <div class="message"> {} </div> """.format(m.content.replace('<', '<').replace('>', '>')) return body
def create_room_message(room_id): '''Create a Message object from the POST data''' # Can call curl with --data-binary and retrieve with request.data # API test: curl --data "data=Hi, I am Sally&user_id=3" http://localhost:5001/api/rooms/1/messages # print request.form #import pdb; pdb.set_trace() main_room = db.session.query(Room).get(room_id) data = request.form.get('data') data = bleach.clean(data) uid = int(request.form.get('user_id')) user = db.session.query(User).get(uid) # If nothing is left in the message, don't return anything # if data == '': # return msg = Message(user=user, room=main_room, data=data) # Create the date fields using the database db.session.add(msg) db.session.commit() # Put the event on the bus print "Throwing message_created_event" bus.notify(Event(Event.Types.message_created_event, msg.as_json())) # To access the newly created object # msgs = Message.query.order_by(Message.message_id).all() # msg = msgs[-1] return jsonify({"messages": main_room.messages_as_json()})
def process_message_new(): """Create new convo, userconvos and message and store in database""" user_to_id = request.form.get('user-to') user_from_id = session['user'] subject = request.form.get('subject') convo = Convo(subject=subject) db.session.add(convo) db.session.commit() # Get the convo_id to use in creating new userconvos convo_id = convo.convo_id new_userconvo_1 = Userconvo(user_id=user_from_id, convo_id=convo_id) db.session.add(new_userconvo_1) db.session.commit() new_userconvo_2 = Userconvo(user_id=user_to_id, convo_id=convo_id) db.session.add(new_userconvo_2) db.session.commit() userconvo_id = new_userconvo_1.userconvo_id # Create new message content = request.form.get('message') new_message = Message(userconvo_id=userconvo_id, sent_at=datetime.utcnow(), content=content) db.session.add(new_message) db.session.commit() flash('Successfully started conversation and sent message.') return redirect('/account-home')
def home(): if request.method == 'POST': m = Message(content=request.form['content']) m.save() body = """ <html> <body> <h1>Class Message Board</h1> <h2>Contribute to the Knowledge of Others</h2> <form method="POST"> <textarea name="content"></textarea> <input type="submit" value="Submit"> </form> <h2>Wisdom From Your Fellow Classmates</h2> """ for m in Message.select(): body += """ <div class="message"> {} </div> """.format(html.escape(m.content)) # Ref: https://docs.python.org/3/library/html.html # Method from lecture, handles only < > characters: # """.format(m.content.replace('<', '<').replace('>', '>')) return body
def log_message(self, user_id, user_message, chat_id): if user_message is None: user_message = "[NO MESSAGE]" try: s = session() language_code = english_message = "" polarity = subjectivity = 0.0 try: # translate to English & log the original language translator = Translator() translated = translator.translate(user_message) language_code = translated.src english_message = translated.text # run basic sentiment analysis on the translated English string analysis = TextBlob(english_message) polarity = analysis.sentiment.polarity subjectivity = analysis.sentiment.subjectivity except Exception as e: print("Error translating message: {}".format(e)) msg1 = Message(user_id=user_id, message=user_message, chat_id=chat_id, language_code=language_code, english_message=english_message, polarity=polarity, subjectivity=subjectivity) s.add(msg1) s.commit() s.close() except Exception as e: print("Error logging message: {}".format(e)) print(traceback.format_exc())
def home(): if request.method == 'POST': m = Message(content=request.form['content']) m.save() body = """ <html> <body> <h1>Class Message Board</h1> <h2>Contribute to the Knowledge of Others</h2> <form method="POST"> <textarea name="content"></textarea> <input type="submit" value="Submit"> </form> <h2>Wisdom From Your Fellow Classmates</h2> """ # Replacing str with HTML char. sequences (Unicode Hexadecimal) for m in Message.select(): body += """ <div class="message"> {} </div> """.format(m.content.replace('<', '<').replace('>', '>') .replace('(', '(').replace(')', ')').replace("'", ''') .replace("[", '[').replace("]", ']').replace("{", '{') .replace("}", '}').replace("!", '!')) return body
def cast_area_spell(self, center: Cell = None, row: int = None, col: int = None, spell: Spell = None, spell_id: int = None) -> None: if spell is None: if spell_id is None or type(spell_id) is not int: Logs.show_log("no valid spell selected in cast_area_spell!") return spell = self.get_spell_by_id(spell_id) if type(spell) is not Spell: Logs.show_log("no valid spell selected in cast_area_spell!") return if row is not None and col is not None: center = self._map.get_cell(row, col) if center is not None: message = Message(type="castSpell", turn=self.get_current_turn(), info={ "typeId": spell.type_id, "cell": { "row": center.row, "col": center.col }, "unitId": -1, "pathId": -1 }) self._queue.put(message) else: Logs.show_log("invalid cell selected in cast_area_spell")
def test_delete(self): self.test_new() e = ZVent(ztype=events.MESG_DELETE, data={'id':TestMessage.id, 'user':TestMessage.user_id}) ZVent.publish(e) m = Message() m.load(TestMessage.id) assert m.deleted == True