def create_message(room_id, player_id, content): try: message = Message(roomId=room_id, playerId=player_id, content=content) message.save() return message, "" except Exception as e: logger.error(e) return {}, "Failed to create message"
def send_message(username): current_user = User.get(session['user']) message_text = request.form['message'] current_date = datetime.now() new_message = Message(sender=current_user.username, recipient=username, text=message_text, creation_time=current_date) new_message.insert()
def __init__(self, bot, update, args=None): super().__init__(bot, update) self.user = current_user(update.callback_query.from_user) self.message = Message.get( Message.telegram_id == update.callback_query.message.message_id) self.callback_data = json.loads(update.callback_query.data) self._call_handler()
def test_get_msg(): headers = { 'Authorization': 'Bearer ' + pytest.users[3]["token"], 'Content-Type': 'text/plain' } with db_session: date = str( Message.select( lambda u: u.game.id == pytest.info['game']).first().date) date = date.replace(" ", "T") response = client.get(f"/games/{pytest.info['game']}/messages", headers=headers) assert response.status_code == 200 assert response.json() == { "data": [{ "content": "Hola Guachin", "date": date, "send_by": { "id": pytest.users[2]["user_id"], "username": "******", "useralias": "andres2" } }] } with db_session: game = Game.get(id=pytest.info['game']) game.started = False response = client.get(f"/games/{pytest.info['game']}/messages", headers=headers) assert response.status_code == 400 assert response.json() == {'detail': "Game is not started"} game.started = True
async def handler_new_message(event): """ Хендлер: запись в БД входящего сообщения из ТГ """ try: print(event.message.message) add_message_to_db(Message(**parse_message(event))) except Exception as ex: print(ex)
def post(self): data = request.get_json() message = Message(name=data['name'], body=data['body']) db.session.add(message) db.session.commit() response = jsonify(message_schema(message)) response.status_code = 201 return response
def __init__(self, bot, update, args=None): super().__init__(bot, update) self.user = current_user(update.message.from_user) self.message, _ = Message.get_or_create( text=self._get_message_text(), user=self.user) self.previous_markup = self.user.reply_markup_message if ((not self._is_full_page()) or (not self.previous_markup.exists()) or (not self.previous_markup.get().is_recent())): self._resend_message_with_markup()
def search_messages(self): tags = (Tag.select(Tag) .where(Tag.user == self.user) .where(Tag.title.in_(self.args))) messages = Message.get_by_tags(tags) messages = messages.paginate(1, paginate_by=SENDED_MESSAGES_PER_PAGE) self._send_reply_markup( 'Messages: ', pagination_keyboard(), json.dumps( ReplyMarkupMessage.search_params(self.args))) self._send_messages(messages)
def send_message(recipient): user = User.query.filter_by(username=recipient).first_or_404() form = MessageForm() if form.validate_on_submit(): msg = Message(author=current_user, recipient=user, body=form.message.data) db.session.add(msg) user.add_notification('unread_message_count', user.new_messages()) db.session.commit() flash('Your message has been sent', 'success') return redirect(url_for('users.user_profile', username=user.username)) return render_template('users/send_message.html', form=form, recipient=recipient)
async def write_message(msg_content: MessageM, game_id: int, user=Depends(manager)): with db_session: game = Game.get(id=game_id) current_player = Player.select(lambda p: user["id"] == p.user.id and p. game.id == game_id).first() if game is None: raise HTTPException(status_code=404, detail="Game not found") if not game.started: raise HTTPException(status_code=400, detail="Game is not started") Message(date=datetime.datetime.now(), content=msg_content.content, game=game_id, player=current_player) return {"detail": "the message was recorder successfully"}
def forge(count): from faker import Faker db.drop_all() db.create_all() fake = Faker() click.echo('Working...') for i in range(count): message = Message(name=fake.name(), body=fake.sentence(), timestamp=fake.date_time_this_year()) db.session.add(message) db.session.commit() click.echo('Created %d fake messages.' % count)
def get_sended_messages(self): tags = (Tag.select(Tag) .where(Tag.user == self.user) .where(Tag.title.in_(self.current_params['tags']))) messages = Message.get_by_tags(tags) if self.update.message.text == '<': page = self.current_params['page'] - 1 elif self.update.message.text == '>': page = self.current_params['page'] + 1 page = self._correct_page( page, self._max_page(messages, SENDED_MESSAGES_PER_PAGE)) messages = messages.paginate(page, paginate_by=SENDED_MESSAGES_PER_PAGE) self._send_reply_markup( self.update.message.chat_id, 'Messages: ', pagination_keyboard(), json.dumps(ReplyMarkupMessage.search_params(self.current_params['tags'], page))) self._send_messages(messages)
def add_messages(): u1 = User.query.filter_by(username="******").first() u2 = User.query.filter_by(username="******").first() u3 = User.query.filter_by(username="******").first() m1 = Message( created_by=u1.id, sent_to=u2.id, body="Could you sort out that scrolling issue?", created_on=datetime.now() - timedelta(hours=3, seconds=55), unread=False, ) m2 = Message( created_by=u1.id, sent_to=u2.id, body="Hmm maybe it's not such a big deal in the end?", created_on=datetime.now() - timedelta(hours=3, seconds=40), unread=False, ) m3 = Message( created_by=u2.id, sent_to=u1.id, body="On it, just have to finish off some other stuff.", created_on=datetime.now() - timedelta(hours=3, seconds=10), unread=False, ) m4 = Message( created_by=u2.id, sent_to=u3.id, body="Wanna get food soon?", created_on=datetime.now() - timedelta(hours=8, seconds=40), ) m5 = Message( created_by=u3.id, sent_to=u2.id, body="Yeah! Let's do burgers!", created_on=datetime.now() - timedelta(hours=8, seconds=25), ) m6 = Message( created_by=u3.id, sent_to=u1.id, body="Food?", created_on=datetime.now() - timedelta(hours=8, seconds=2), ) db.session.add_all([m1, m2, m3, m4, m5, m6]) db.session.commit()