def chatroom_all(): messages = ndb.gql('SELECT * FROM ChatMessage ORDER BY timestamp') if request.method == 'POST': user, message, timestamp = request.form.get('name'), request.form.get('message'), datetime.datetime.now() chat_msg = ChatMessage(user=user, timestamp=timestamp, message=message) chat_msg.put() messages = ndb.gql('SELECT * FROM ChatMessage ORDER BY timestamp') return render_template('chatroom.html', messages=messages, vm_time=vm_start_time, mode='chatroom_all')
def save_chat_message(nick_name='', steam_id='', message=''): if not nick_name and not steam_id: nick_name = 'Server' steam_id = '0' ChatMessage.create( datetime=datetime.datetime.now(), player=get_player(nick_name, steam_id), message=message )
def next_move(): game = Game.current() last_state = GameState.get(game_id=game.id, seq=game.current_seq - 1) if last_state is None: GameState.insert( game_id=game.id, seq=0, black_captures=0, white_captures=0, illegal=json.dumps([]), board=json.dumps([[0] * 19] * 19), sgf=DEFAULT_SGF, ) return True top_moves = Vote.summary(game.id, game.current_seq) if not top_moves: return False top_move = top_moves[0].move result = call_gnugo( last_state.sgf, game.current_seq, top_move, ) next_state = parse_gnugo(result) next_state['black_captures'] += last_state['black_captures'] next_state['white_captures'] += last_state['white_captures'] GameState.insert(game_id=game.id, seq=game.current_seq, move=top_move, **next_state) Game.insert_or_update( keys=('id', ), id=game.id, current_seq=game.current_seq + 1, ) message = 'Move %d, %s plays %s.' % ( game.current_seq, game.current_seq % 2 and "Black" or "White", Pretty.pos(top_move), ) for room_id in (1, 2): ChatMessage.insert( room_id=room_id, user_id=0, message=message, ) signal_message(room_id, 'send')
def chatroom_time(): messages = ChatMessage.gql('WHERE timestamp > :fiveago ORDER BY timestamp', fiveago=datetime.datetime.now() - datetime.timedelta(minutes=2)) if request.method == 'POST': user, message, timestamp = request.form.get('name'), request.form.get('message'), datetime.datetime.now() chat_msg = ChatMessage(user=user, timestamp=timestamp, message=message) chat_msg.put() messages = ChatMessage.gql('WHERE timestamp > :fiveago ORDER BY timestamp', fiveago=datetime.datetime.now() - datetime.timedelta(minutes=2)) return render_template('chatroom.html', messages=messages, vm_time=vm_start_time, mode='chatroom_time')
def chatroom_all(): messages = ndb.gql('SELECT * FROM ChatMessage ORDER BY timestamp') if request.method == 'POST': user, message, timestamp = request.form.get('name'), request.form.get( 'message'), datetime.datetime.now() chat_msg = ChatMessage(user=user, timestamp=timestamp, message=message) chat_msg.put() messages = ndb.gql('SELECT * FROM ChatMessage ORDER BY timestamp') return render_template('chatroom.html', messages=messages, vm_time=vm_start_time, mode='chatroom_all')
def POST(self): room_id = web.ctx.game.player_color form = ChatForm() if not form.validates(): raise web.notfound(form.note) ChatMessage.insert( room_id=room_id, user_id=web.ctx.user.id, message=form.d.message, ) signal_message(room_id, 'send')
def DELETE(self): get_data = web.input(id=None) chat_id = int(get_data.id) msg = ChatMessage.get(id=chat_id) ChatMessage.update( ('id', ), id=chat_id, deleted=1, ) signal_message(msg.room_id, 'delete', id=chat_id) return "OK"
def DELETE(self): get_data = web.input(id=None) chat_id = int(get_data.id) msg = ChatMessage.get(id=chat_id) ChatMessage.update( ('id',), id=chat_id, deleted=1, ) signal_message(msg.room_id, 'delete', id=chat_id) return "OK"
def chat_new_message(request): print request chat_id = request.POST.get("chat_id") chat = Chat.objects.get(id=chat_id) chat_message = ChatMessage(chat=chat, user=request.user, date = datetime.now(), text=request.POST["text"]) chat_message.save() chat_users = ChatUserList.objects.filter(chat=chat_id) chat_messages = ChatMessage.objects.filter(chat=chat_id).order_by('date') return render(request, 'chat/messages.html', {'id': chat_id, 'chat_users': chat_users, 'chat_messages': chat_messages}) # @login_required # def messages(request): # context = {'messages' : Message.objects.filter(Q(user_from=request.user) | Q(user_to=request.user)).annotate(messages_to=Count('user_to')).order_by('-date')} # return render(request, 'user/messages.html', context) # # @login_required # def new_message(request): # message = Message(user_from=request.user, user_to='asd1', date = datetime.now(), text=request.POST["text"]) # print message # message.save() # return render(request, 'generic/.html', {'id': message.id, 'date': message.date, 'text': request.POST["text"]}) # class IndexView(generic.ListView): # template_name = 'index.html' # context_object_name = 'index' # # def get_queryset(self): # return Post.objects.order_by('date')[:5] # class DetailView(generic.DetailView): # model = Post # template_name = 'post/detail.html' # # class ListView(generic.ListView): # model = Post # template_name = 'post/list.html' # # def profile(request, user_id): # return HttpResponse(User.objects.user.get(user_id=user_id)) # # def post_list(request, user_id): # context = {'view_last_posts': Post.objects.filter(user_id=user_id).order_by('date')[:10]} # return render(request, 'SocialApp/post/list.html', context) # # def post_detail(request, post_id): # context = Post.objects.user.get(post_id=post_id) # return HttpResponse(request, 'SocialApp/post/detail.html', context) # # def post_save(request, post): # post.save()
def new_message(self, room_id, author, text): msg = ChatMessage() msg.author = author msg.room_id = room_id msg.text = text if not room_id in self._recent_messages_in_room: self._recent_messages_in_room[room_id] = deque() if len(self._recent_messages_in_room[room_id]) >= RECENT_MESSAGES_AMOUNT: self._recent_messages_in_room[room_id].popleft() self._recent_messages_in_room[room_id].append(msg) connection_manager.emit_for_room(room_id, 'chat_message', msg=msg.json_representation)
def add_messages(url): "add messages to db if they aren't added" session = Session() messages = get_current_messages(url) for message_elem in messages: message = ChatMessage() message.author = message_elem.find_element_by_id('author-name').text message.text = message_elem.find_element_by_id('message').text message.message_id = message_elem.get_attribute('id') message_exists = session.query(exists().where(ChatMessage.message_id == message.message_id)).scalar() if not message_exists: try: session.add(message) session.commit() print("{}: {}".format(message.author, message.text)) except: pass session.close()
def GET(self): get_data = web.input(last_id=0) last_id = int(get_data.last_id) room_id = web.ctx.game.player_color messages = [] delete_id = None if last_id == 0: messages = ChatMessage.load(room_id, last_id) else: action, kwargs = wait_for_message(room_id) #sleep up to 300 ms to prevent the thundering herd time.sleep(random.random() * .3) if action == 'send': messages = ChatMessage.load(room_id, last_id) elif action == 'delete': delete_id = kwargs['id'] deletable = is_admin() ChatRoom.set_online(room_id) online_users = [{ 'name': u[1], 'rating': Pretty.rating(u[2]), } for u in ChatRoom.get_online(room_id)] return json.dumps({ 'messages': list( reversed([{ 'id': x.id, 'name': x.name, 'rating': Pretty.rating(x.rating), 'message': x.message, 'deletable': deletable, } for x in messages])), 'online_users': online_users, 'refresh': False, 'delete_id': delete_id, })
def post(self): req = self.request msg = ChatMessage() msg.text = req("text") msg.unitfrom = Unit.get_by_id(req("fromid")) msg.unitto = Unit.get_by_id(req("toid")) msg.put()
def test_message_1(self): with self.app.test_request_context(): dt = datetime.now() message = ChatMessage(text='hello', date_created=dt) expect = { 'user': '******', 'text': 'hello', 'created_at': dt.isoformat(), } self.assertEqual( serializers.MessageSerializer(message).calc(), expect)
def addMsg(msgData): """ addMsg(msgData) Add new message and the user how sent to database. """ from_user = get_User(msgData['email']) session = DBSession() msg = ChatMessage(message=msgData['message'], user=from_user) session.add(msg) session.commit() session.close_all()
def GET(self): get_data = web.input(last_id=0) last_id = int(get_data.last_id) room_id = web.ctx.game.player_color messages = [] delete_id = None if last_id == 0: messages = ChatMessage.load(room_id, last_id) else: action, kwargs = wait_for_message(room_id) #sleep up to 300 ms to prevent the thundering herd time.sleep(random.random() * .3) if action == 'send': messages = ChatMessage.load(room_id, last_id) elif action == 'delete': delete_id = kwargs['id'] deletable = is_admin() ChatRoom.set_online(room_id) online_users = [{ 'name': u[1], 'rating': Pretty.rating(u[2]), } for u in ChatRoom.get_online(room_id)] return json.dumps({ 'messages': list(reversed([ { 'id': x.id, 'name': x.name, 'rating': Pretty.rating(x.rating), 'message': x.message, 'deletable': deletable, } for x in messages ])), 'online_users': online_users, 'refresh': False, 'delete_id': delete_id, })
def download_chat_messages(vod_id, timestamp, duration): api = TwitchAPI() vod = VOD.objects.get(id=vod_id) timestamp_offset = 0 while timestamp_offset < duration: timestamp_offset += 30 try: data = api.get_chat_messages(vod_id, timestamp + timestamp_offset) if data["data"]: for message in data["data"]: db_message = ChatMessage(id=message["id"], message=message["attributes"]["message"], timestamp=message["attributes"]["timestamp"], vod=vod) db_message.save() except: continue vod.all_messages_loaded = True vod.save()
def test_message_2(self): with self.app.test_request_context(): dt = datetime.now() config.SITE_URL = 'http://localhost' user = User(username='******', password='******') message = ChatMessage(text='http://localhost/someurl', date_created=dt, user=user) expect = { 'user': '******', 'text': '/someurl', 'link': 'http://localhost/someurl', 'created_at': dt.isoformat(), } self.assertEqual( serializers.MessageSerializer(message).calc(), expect)
def post_message(request): if request.method == "POST": cm = ChatMessage() cm.user = request.POST.get('user') cm.message = request.POST.get('message') if not cm.user or not cm.message: return HttpResponse("400 Bad Request You need to specify username and message") cm.date = datetime.datetime.now() cm.save() return json_response(request,'Success') else: return HttpResponse("405 Method Not Allowed")
def get(self): try: limit = int(request.args.get('limit', -1)) offset = int(request.args.get('offset', -1)) if limit < 0: limit = config.DEFAULT_COUNT_MESSAGES if offset < 0: offset = 0 except Exception as e: logger.error(e) raise APIException('wrong arguments') messages = ChatMessage.select()\ .where(ChatMessage.chat == None)\ .order_by(-ChatMessage.date_created)\ .offset(offset)\ .limit(limit) return { 'messages': [MessageSerializer(m).calc() for m in messages], }
def chatroom_time(): messages = ChatMessage.gql('WHERE timestamp > :fiveago ORDER BY timestamp', fiveago=datetime.datetime.now() - datetime.timedelta(minutes=2)) if request.method == 'POST': user, message, timestamp = request.form.get('name'), request.form.get( 'message'), datetime.datetime.now() chat_msg = ChatMessage(user=user, timestamp=timestamp, message=message) chat_msg.put() messages = ChatMessage.gql( 'WHERE timestamp > :fiveago ORDER BY timestamp', fiveago=datetime.datetime.now() - datetime.timedelta(minutes=2)) return render_template('chatroom.html', messages=messages, vm_time=vm_start_time, mode='chatroom_time')
def next_move(): game = Game.current() last_state = GameState.get( game_id=game.id, seq=game.current_seq - 1 ) if last_state is None: GameState.insert( game_id=game.id, seq=0, black_captures=0, white_captures=0, illegal=json.dumps([]), board=json.dumps([[0] * 19] * 19), sgf=DEFAULT_SGF, ) return True top_moves = Vote.summary(game.id, game.current_seq) if not top_moves: return False top_move = top_moves[0].move result = call_gnugo( last_state.sgf, game.current_seq, top_move, ) next_state = parse_gnugo(result) next_state['black_captures'] += last_state['black_captures'] next_state['white_captures'] += last_state['white_captures'] GameState.insert( game_id=game.id, seq=game.current_seq, move=top_move, **next_state ) Game.insert_or_update( keys=('id',), id=game.id, current_seq=game.current_seq + 1, ) message = 'Move %d, %s plays %s.' % ( game.current_seq, game.current_seq % 2 and "Black" or "White", Pretty.pos(top_move), ) for room_id in (1, 2): ChatMessage.insert( room_id=room_id, user_id=0, message=message, ) signal_message(room_id, 'send')
def post(self): message = ChatMessage.create(user=request.user, text=self.data['text']) result = {'message': MessageSerializer(message).calc()} send_ws(result, WS_CHAT_MESSAGE) return result