def _parse_msg_with_attach(self, message: BeautifulSoup) -> Message: """Turn image and link attachment posts to Messages.""" attrs = json.loads(message['data-store']) name = attrs['name'] img_hdr = message.find_all('img') if img_hdr: fpath = img_hdr[0]['src'] msg = message.find("div", {"data-sigil": "message-text"}) attrs = json.loads(msg['data-store']) timestamp = self._conv_datetime(attrs['timestamp']) return Message(name, '', timestamp, True, True, fpath) else: msg = message.find("div", {"data-sigil": "message-text"}) attrs = json.loads(msg['data-store']) timestamp = self._conv_datetime(attrs['timestamp']) try: link_store = message.find("a", {"data-sigil": "MLinkshim"}) link = json.loads(link_store['data-store'])['dest_uri'] except TypeError: # These seem to be unique each time? # I think they're some kind of FB share thing # Most of the time it's a URL to facebook CDN so it's not # like there is any useful info here anyways link = '' return Message(name, '', timestamp, True, False, link)
def end_votes(database, roomId): room_data = get_room(database, roomId) max_count = 0 suspectIdList = [] is_execution = False for i in room_data.players: count = sum(vote.targetId == i.userId for vote in room_data.votes) if count > max_count: max_count = count suspectIdList.clear() suspectIdList.append(i.userId) elif count == max_count: suspectIdList.append(i.userId) max_count = ceil(max_count) players_left = sum( players.status == 'alive' for players in room_data.players) # print(max_count, ceil(players_left/2)) if max_count >= ceil(players_left/2): for i in room_data.players: if i.userId == suspectIdList[0]: i.status = 'dead' room_data.votes.clear() room_data.gameMessages.append( Message('Execution', i.name + ' was hanged. Votes: ' + str(max_count) + ' Players left: ' + str(players_left - 1))) room_data.observerMessages.append( Message('Execution', i.name + ' was hanged. Votes: ' + str(max_count) + ' Players left: ' + str(players_left - 1))) is_execution = True mafia_left = sum(players.status == 'alive' and players.role == 'mafia' for players in room_data.players) players_left = sum( players.status == 'alive' for players in room_data.players) is_game_over = evaluate_win(room_data, players_left, mafia_left) if not is_game_over and is_execution: room_data.votes.clear() return True if not is_game_over and not is_execution: room_data.votes.clear() room_data.gameMessages.append( Message('Execution', 'Not enough votes, no one was hanged.')) room_data.observerMessages.append( Message('Execution', 'Not enough votes, no one was hanged.')) return False if is_game_over: return True
def heal_action(database, roomId, name, targetId): room_data = get_room(database, roomId) for i in room_data.players: if i.userId == targetId and i.status == 'alive': # set targets room_data.targets.healTarget = targetId # transition to detective phase room_data.phase = 'detective' room_data.gameMessages.append( Message('Detective Phase', 'Detective pick someone to check')) room_data.observerMessages.append( Message('Doctor Action', name + " healed " + i.name)) return True return False
def night_start_write(database, roomId): room_data = get_room(database, roomId) if len(room_data.votes) > 0: return False room_data.night += 1 room_data.phase = 'mafia' room_data.gameMessages.append( Message("Night " + str(room_data.night), "The night has begun!")) room_data.gameMessages.append( Message("Mafia Phase", "Mafia pick someone to kill")) # observer messages room_data.observerMessages.append( Message("Night " + str(room_data.night), "The night has begun!")) return True
def kill_action(database, roomId, name, targetId): room_data = get_room(database, roomId) for i in room_data.players: if i.userId == targetId and i.status == 'alive': # set targets room_data.targets.killTarget = targetId # transition to doctor phase room_data.phase = 'doctor' room_data.gameMessages.append( Message('Doctor Phase', 'Doctor pick someone to heal')) room_data.observerMessages.append( Message('Mafia Action', name + " killed " + i.name)) return True return False
def send_message(message, recipient): usr = current_user.social_id if current_user.is_mentor: convo = Conversation.query.filter_by(mentor=usr, mentee=recipient).first() else: convo = Conversation.query.filter_by(mentee=usr, mentor=recipient).first() if convo is None: print('conversation not found') return timestamp = datetime.now() other_nick = User.query.filter_by(social_id=recipient).first() other_nick = other_nick.social_id print('message sent by {} to {} at {}: {}'.format(current_user.social_id, other_nick, timestamp, message)) message = Message(sent=timestamp, owner=usr, recipient=recipient, contents=message) db.session.add(message) db.session.commit() sio.emit('message', { 'sent': str(timestamp), 'owner': usr, 'recipient': recipient, 'contents': message.contents }, room=recipient)
def enqueue(self, type, src, dst): dbsession = self.Dbsession() new_message = Message(type, src, dst) dbsession.add(new_message) dbsession.commit() dbsession.close() pass
def admin_send(): global Num SenderId = request.values.get('SenderId') #发送人学号 Sender = request.values.get('Sender') #发送人 recipient = request.values.get('recipient') #接收人 recipientId = request.values.get('recipientId') #接收人学号 message = request.values.get('message') #留言信息 # print(SenderId, Sender, recipient, recipientId, message) NewRecipient = Student.query.filter_by(id=recipientId).first() db.session.close() user=Student.query.filter_by(id=SenderId).first() db.session.close() # print(NewRecipient.password) if user: try: if recipient == NewRecipient.username: Message1 = Message(Num=str(Num),SenderId=SenderId, Sender=Sender, recipient=recipient, recipientId=recipientId, message=message) db.session.add(Message1) db.session.commit() db.session.close() print("发送成功") Num=Num+1 return render_template('index.html', message='发送成功',user=user) else: print("发送失败") return render_template('index.html', message='请检查姓名和学号是否正确',user=user) except AttributeError: return render_template('index.html', message='请检查姓名和学号是否正确', user=user) else: return render_template('index.html', message='请检查姓名和学号是否正确', user=user)
def insert_messages(messages): from database import DBSession, Message, User for message in messages: new_msg = Message(id=message.msgid, link='https://t.me/c/{}/{}'.format( LINK_ID, message.msgid), text=message.message, video='', photo='', audio='', voice='', type='text', category='', from_id=message.senderid, date=message.date) session = DBSession() session.add(new_msg) if not message.userexist: new_user = User(id=message.senderid, fullname=message.sender, username='', update_time=datetime.now()) session.add(new_user) session.commit() session.close()
def insert_messages(messages): from database import DBSession, Message, User for index, message in enumerate(messages): new_msg = Message(id=-index, link='', text='{}: {}'.format(message.sender, message.message), video='', photo='', audio='', voice='', type='text', category='', from_id=0, date=message.date) session = DBSession() session.add(new_msg) session.commit() session.close() deafult_user = User(id=0, fullname='历史聊天记录', username='******', update_time=datetime.now()) session = DBSession() session.add(deafult_user) session.commit() session.close()
def echo_controller(request): data = request.get('data') session = Session() message = Message(data=data) session.add(message) session.commit() session.close() return make_response(request, 200, data)
def write_new_room(database, numMafia): targets = Targets("", "", "") new_room = Room( generateGameRoomKey(), int(numMafia), 0, [], targets, "pre-game", "pre-game", True, uuid.uuid4().hex, [], [Message("Waiting for players", "Waiting for players")], [Message("Waiting for players", "Waiting for players")] ) database.append(new_room) return database, new_room
def detect_action(database, roomId, name, targetId): room_data = get_room(database, roomId) deathId = None if room_data.targets.killTarget != room_data.targets.healTarget: deathId = room_data.targets.killTarget # evaluate death for i in room_data.players: if i.userId == deathId: i.status = 'dead' room_data.gameMessages.append( Message('Night End', i.name + ' was killed')) # evaluate win players_left = sum( players.status == 'alive' for players in room_data.players) mafia_left = sum(players.status == 'alive' and players.role == 'mafia' for players in room_data.players) is_game_over = evaluate_win(room_data, players_left, mafia_left) if not is_game_over: for i in room_data.players: if i.userId == targetId and i.status == 'alive': # set targets for x in room_data.players: if x.userId == targetId: x.checked = True # transition to detective phase if deathId is None: room_data.gameMessages.append( Message('Night End', 'The victim was healed')) room_data.targets = Targets('', '', '') room_data.phase = 'voting' room_data.gameMessages.append( Message('Voting Phase', 'The night is over! Who is the mafia?')) room_data.observerMessages.append( Message('Detective Action', name + " checked " + i.name)) return True return False return True
def phase_shift(database, roomId): room_data = get_room(database, roomId) if room_data.phase == 'mafia': room_data.phase = 'doctor' room_data.gameMessages.append( Message('Doctor Phase', 'Doctor pick someone to heal')) return True elif room_data.phase == 'doctor': room_data.phase = 'detective' room_data.gameMessages.append( Message('Detective Phase', 'Detective pick someone to check')) return True elif room_data.phase == 'detective': deathId = None if room_data.targets.killTarget != room_data.targets.healTarget: deathId = room_data.targets.killTarget # evaluate death for i in room_data.players: if i.userId == deathId: i.status = 'dead' room_data.gameMessages.append( Message('Night End', i.name + ' was killed')) if deathId is None: room_data.gameMessages.append( Message('Night End', 'The victim was healed')) # evaluate win players_left = sum( players.status == 'alive' for players in room_data.players) mafia_left = sum(players.status == 'alive' and players.role == 'mafia' for players in room_data.players) is_game_over = evaluate_win(room_data, players_left, mafia_left) if is_game_over: return True room_data.targets = Targets('', '', '') room_data.phase = 'voting' room_data.gameMessages.append( Message('Voting Phase', 'The night is over! Who is the mafia?')) return True return False
def evaluate_win(room_data, players_left, num_mafia): num_civs = players_left - num_mafia print(num_civs, num_mafia) if num_civs <= num_mafia: room_data.status = 'ended' room_data.phase = 'ended' room_data.gameMessages.append( Message('Game Over', 'All the villagers were brutally executed by the Mafia.')) room_data.observerMessages.append( Message('Game Over', 'All the villagers were brutally executed by the Mafia.')) return True if num_mafia == 0: room_data.status = 'ended' room_data.phase = 'ended' room_data.gameMessages.append( Message('Game Over', 'The villagers weeded out all the Mafia.')) room_data.observerMessages.append( Message('Game Over', 'The villagers weeded out all the Mafia.')) return True
def create_test_room(): players = [ Player('alan', '12354', 'mafia', 'alive', False), Player('noob1', '42314', 'civilian', 'alive', False), Player('noob2', '22222', 'civilian', 'alive', False), Player('noob3', '33333', 'civilian', 'alive', False), Player('noob4', '44444', 'civilian', 'alive', False) ] targets = Targets('', '', '') gameMessages = [Message('Pre-Game', 'Waiting for players...')] observerMessages = [ Message('Pre-Game', 'Waiting for players...'), Message('Observer Message', 'Testing...') ] room = Room('0001', 2, 0, players, targets, 'pre-game', 'pre-game', True, '55555', [], gameMessages, observerMessages) database.append(room) LOG.info('Test room created..')
def add_message(time, sender, message): if len(get_message_log()) > 9990: least_recent = db.session.query(func.min(Message.time)) db.session.delete(least_recent) db.session.commit() message = Message(time=time, sender=sender, message=message) db.session.add(message) db.session.commit()
def new_message(conversation_id, text): print('new_message:' + text) print(conversation_id) conversation = Conversation.query.get(conversation_id) new_message = Message(text=text, conversation=conversation, user_id=session['user_id']) db.session.add(new_message) db.session.commit() emit('new_message', (conversation_id, new_message.lean()), room=conversation.id)
def cmd_xmpp_send(*args): """send a Jabber message""" if len(args) < 1: print "Usage: ardj xmpp-send \"message text\" [recipient_jid]" exit(1) recipient = None if len(args) > 1: recipient = args[1].decode("utf-8") from database import Message, commit Message(message=args[0].decode("utf-8"), re=recipient).put() commit()
def game_start_write(database, roomId): # shuffle the roles and assign them roles = [] room_data = get_room(database, roomId) if len(room_data.players)/2 <= room_data.numMafia: return False for i in range(0, room_data.numMafia): roles.append('mafia') roles.append('doctor') roles.append('detective') civilians = len(room_data.players) - room_data.numMafia - 2 for i in range(0, civilians): roles.append('civilian') random.shuffle(roles) count = 0 for i in room_data.players: i.role = roles[count] count += 1 room_data.night += 1 room_data.status = 'in-progress' room_data.phase = 'mafia' # game messages room_data.gameMessages.append( Message("Game Start", "Room is no longer accepting new players")) room_data.gameMessages.append( Message("Night " + str(room_data.night), "The night has begun!")) room_data.gameMessages.append( Message("Mafia Phase", "Mafia pick someone to kill")) # observer messages room_data.observerMessages.append( Message("Night " + str(room_data.night), "The night has begun!")) return True
def save_message_info(session, content_type, date, message): user = None for i in session.query(User.id): user = i saved_message = Message(user=user, content_type=content_type, date=date) if content_type == "Text": save_text_info(session, message.json['text'], message.json['entities'][0]['length'], message.json['entities'][0]['type']) elif 'caption' in message.json: save_text_info(session, message.json['caption'], len(message.json['caption']), "caption") session.add(saved_message) session.commit()
def _parse_admin_message(self, message: BeautifulSoup) -> Optional[Message]: """Read an 'admin' message and converts to a Message. An 'admin' message is one which is sent by Facebook instead of a user. A typical example is 'PersonX added PersonY to the chat' """ try: data = message.findAll("span", {"class": "fcg"})[0] except IndexError: # Not sure what these are, but they don't seem important... return None return Message('Admin', data.text, self._prev_msg.date)
def insert_messages(chat_id, messages): fail_count = 0 fail_messages = [] success_count = 0 for message in messages: if 'from_id' not in message: continue elif 'user' not in message['from_id']: continue insert_user_or_do_nothing(message['from_id'][4:], message['from'], message['from']) if isinstance(message['text'], list): msg_text = '' for obj in message['text']: if isinstance(obj, dict): msg_text += obj['text'] else: msg_text += obj else: msg_text = message['text'] if msg_text == '': msg_text == '[其他消息]' message_date = datetime.strptime(message['date'], '%Y-%m-%dT%H:%M:%S') new_msg = Message(id=message['id'], link='https://t.me/c/{}/{}'.format( chat_id, message['id']), text=msg_text, video='', photo='', audio='', voice='', type='text', category='', from_id=message['from_id'][4:], from_chat=chat_id, date=message_date) session = DBSession() try: session.add(new_msg) session.commit() success_count += 1 except Exception as e: print(e) fail_count += 1 fail_messages.append(str(message)) session.close() return success_count, fail_count, fail_messages
def vote(database, roomId, userId, targetId): room_data = get_room(database, roomId) name = None # get name for i in room_data.players: if i.userId == userId: name = i.name for i in room_data.votes: if i.userId == userId: # already voted return False for i in room_data.players: if i.userId == targetId: room_data.votes.append(Vote(userId, targetId, i.name)) room_data.gameMessages.append( Message('Vote', name + ' voted ' + i.name)) room_data.observerMessages.append( Message('Vote', name + ' voted ' + i.name)) return True return False
def insert_message(msg_id, msg_text, msg_video, msg_photo, msg_audio, msg_voice, msg_type, from_id, date): new_msg = Message(id=msg_id, text=msg_text, video=msg_video, photo=msg_photo, audio=msg_audio, voice=msg_voice, type=msg_type, category='', from_id=from_id, date=date) session = DBSession() session.add(new_msg) session.commit() session.close()
def new_message(message, user, branch_id, index): """ Creates a new message in a branch. The index is its posistion in the chat window. The user is the owner of this message Returns True if the message was created sucsesfully fals if not. """ branch_object = Branch.query.filter_by(id=branch_id).first() if branch_object is not None: message_object = Message(index, message, user, branch_id) db.session.add(message_object) branch_object.message.append(message_object) db.session.commit() return True else: return False
def write_message(): user = get_current_user() if not user: return jsonify({"message": "You have to login or register"}) new_message_data = request.get_json() receiver = new_message_data['receiver'] message = new_message_data['message'] subject = new_message_data['subject'] if str(receiver) == user.user_id: return jsonify({'message': 'You cannot write letters to yourself'}) existing_receiver = db.query(User).filter_by(user_id=receiver).first() if not existing_receiver: return jsonify({'message': 'There is no such receiver in the system'}) if len(message) == 0: return jsonify(({ 'message': 'You have to write something in your message' })) new_message = Message(sender=user.user_id, receiver=receiver, message=message, subject=subject) db.add(new_message) db.commit() message_result = db.query(Message).filter_by(sender=user.user_id).first() return jsonify({ 'message': { 'message_id': message_result.message_id, 'sender': message_result.sender, 'receiver': message_result.receiver, 'message': message_result.message, 'subject': message_result.subject, 'create_date': message_result.create_date, 'read': message_result.read } })
def add_message(): m_body = json.loads(request.data) user_id1 = m_body.get('user_id1') user_id2 = m_body.get('user_id2') chat = Chat.query.filter_by(user_id1=user_id1, user_id2=user_id2).first() if chat is None: chat = Chat.query.filter_by(user_id1=user_id2, user_id2=user_id1).first() if chat is not None: message = Message( sender_id = m_body.get('sender_id'), text = m_body.get('text'), chat_id = chat.id, ) chat.history.append(message) db.session.add(message) db.session.commit() return json.dumps({'success': True, 'data': message.brief()}), 200 return json.dumps({'success': False, 'error': 'CHAT NOT FOUND!'}), 404
def _parse_message(self, message: BeautifulSoup) -> Optional[Message]: """Read and converts HTML data into a Message.""" try: attrs = json.loads(message['data-store']) except KeyError: return self._parse_admin_message(message) if attrs['has_attachment']: return self._parse_msg_with_attach(message) else: name = attrs['name'] msg = message.find("div", {"data-sigil": "message-text"}) text = msg.span.text attrs = json.loads(msg['data-store']) timestamp = self._conv_datetime(attrs['timestamp']) new_msg = Message(name, text, timestamp, False) self._prev_msg = new_msg return new_msg
def check_inbox(): # with db_session: msg_list = select(m.id for m in Message)[:20] blacklist = select(b.name for b in Banneduser)[:20] msgs = reddit.inbox.messages(limit=100) for msg in msgs: if msg.id not in msg_list: print(msg.body + ' not in list') Message(id=msg.id) if msg.author.name in blacklist: if msg.body == start: delete(m for m in Message if m.id == msg.id) msg.reply(started) elif msg.body == stop: msg.reply(already_stopped) else: if msg.body == start: msg.reply(started) elif msg.body == stop: Banneduser(name=msg.author.name) msg.reply(stopped)