def create_message(sender_id, content, channel_id): new_message = Message(sender=sender_id, content=content, channel=channel_id) db.session.add(new_message) db.session.commit() return new_message.serialize()
def create_message_to_channel(user_id, channel_id, content): new_message = Message(user_id=user_id, channel_id=channel_id, content=content) db.session.add(new_message) db.session.commit() return new_message.serialize()
async def create_message(self, ctx): user = ctx.user ws = ctx.extensions.get('ws') snowflake = ctx.services.get('snowflake') websocket = ctx.services.get('websocket') try: channel = Channel.nodes.first_or_none(uid=kwargs['url_data']['channel.id']) except KeyError: raise web.HTTPBadRequest() if not channel: raise web.HTTPBadRequest() board = channel.board_parent.single() role_uid = board.subscribers.relationship(user).role role = Role.nodes.first_or_none(uid=role_uid) if not role: raise web.HTTPBadRequest() if (role.permissions & 8 == 8) or (role.permissions & 2048 == 2048): message_data = ctx.sent_data content = message_data['content'] if content == '': raise web.HTTPBadRequest() new_message = Message(uid=await snowflake(), content=content) new_message.save() new_message.author.connect(user) new_message.channel.connect(channel) await ws.event(EventType.MESSAGE_CREATE, board.subscribers, message=new_message) return ctx.respond(jsonify(new_message))
def get_chat_messages_data(game_id: int, oldest_id: int, newest_id: int, newer_messages: bool): older_message = Message.get_or_none((Message.game == game_id) & (Message.id < oldest_id)) has_older_message = older_message is not None MESSAGE_LIMIT = 20 if newer_messages: messages = Message.select().where((Message.game == game_id) & (Message.id > newest_id)).order_by(-Message.id)\ .limit(MESSAGE_LIMIT).execute() else: messages = Message.select().where((Message.game == game_id) & (Message.id < oldest_id)).order_by(-Message.id)\ .limit(MESSAGE_LIMIT).execute() # Note: oldest_id and newest_id could be -1 when frontend has no messages at all if len(messages): # Needed for when newer_messages is False oldest_id_in_query = messages[0].id has_older_message = Message.get_or_none( (Message.game == game_id) & (Message.id < oldest_id_in_query)) has_older_message = has_older_message is not None reversed_messages = [ messages[len(messages) - i - 1] for i in range(len(messages)) ] return reversed_messages, has_older_message
def group_chat(id_=None): form = MessageForm() if request.method == 'POST': content = form.data.content send2 = form.data.send2 send2user = User.get_or_404(id=send2) message = Message(create_by=current_user.id, content=content, send2=send2) message.save() msgs = Message.objects(send2=id_) return render_template('/group_chat.html', msgs=msgs, form=form)
def create_message(chat_id, body): message = Message(timestamp=datetime.datetime.now(), content=body.get("content"), sender_id=body.get("sender_id"), chat_id=chat_id) chat = Chat.query.filter_by(id=chat_id).first() sender = User.query.filter_by(id=body.get("sender_id")).first() if sender not in chat.users: return None for user in chat.users: if user is not sender: user.messages_received.append(message) db.session.add(message) db.session.commit() return message.serialize()
def send_message_to_group(sender_id, group_id, message): sender = User.query.filter_by(id=sender_id).first() group = Group.query.filter_by(id=group_id).first() if sender is None or group is None or sender not in group.members: return None new_message = Message( sender_id=sender_id, group_id=group_id, message=message ) db.session.add(new_message) db.session.commit() return new_message.serialize()
def send_message(roomname): ''' Send a message ''' message = request.json["message"] if "username" not in message and \ "roomname" not in message and \ "content" not in message and \ "timestamp" not in message: abort(UNPROCESSABLE_ENTITY_ERROR) elif message["roomname"] not in cached_rooms or \ message["username"] not in cached_users: abort(NOT_FOUND_ERROR) elif message["username"] not in cached_rooms[message["roomname"]]: abort(UNAUTHORIZED_ERROR) else: # Well formed message, send it! timestamp = datetime.fromtimestamp(message["timestamp"]) this_offset = room_offsets[message["roomname"]] + 1 sent_message = Message(offset=this_offset, roomname=message["roomname"], username=message["username"], content=message["content"], timestamp=timestamp) print( f'Trying to send message {message} and the offset is {room_offsets[message["roomname"]]}' ) if not db.send_message(sent_message): abort(INTERNAL_SERVER_ERROR) else: # Successfully saved the message to the db room_offsets[message["roomname"]] = this_offset cached_messages[message["roomname"]].append(sent_message) return jsonify({'status': 200}) # What to send back here?
def my_timeline(): user = get_session_user() assert user is not None messages = Message.select().where( Message.user == user ) return object_list('my_messages.html', messages, 'message_list')
def act_sendMessage(data): userId = dbi.getXbyY('User', 'sid', data['sid']).id msgTime = misc.generateTimeForTest() if misc.TEST_MODE else math.trunc( time.time()) text = data['text'] dbi.add(Message(userId, text, msgTime)) return {'result': 'ok'}
def post_message_to_group(user_id, group_id): group = Group.query.filter_by(id=group_id).first() if group is None: return json.dumps({ "success": False, "error": "Group not found..." }), 404 post_body = json.loads(request.data) message = Message(user_id=user_id, group_id=group_id, description=post_body.get("description")) db.session.add(message) db.session.commit() return json.dumps({ 'success': True, 'data': message.serialize_group() }), 201
def _log_msg(text, source, update, state=None, chat_id=None): chat_id = chat_id or update.effective_chat.id msg = Message(msg=text, source=source, chat_id=chat_id, state=state, server_time=datetime.utcnow()) Database().insert(msg)
def create_message_with_file(file): a = AlfaCV(file) messages = a.get_messages() bulk_list = [] for message in messages: parser = ParserMessage(message) bulk_list.append( Message(card=parser.get_card(), balance=parser.get_balance(), amount=parser.get_amount(), currency=parser.get_currency(), date=parser.get_date(), body=parser.text)) Message.bulk_create(bulk_list)
def private_timeline(): # the private timeline exemplifies the use of a subquery -- we are asking for # messages where the person who created the message is someone the current # user is following. these messages are then ordered newest-first. user = get_session_user() assert user is not None messages = Message.select().where( Message.user << user.following() ) return object_list('private_messages.html', messages, 'message_list')
def score_message(hug_token, message_id: hug.types.number, score: hug.types.number): try: msg = Message.get(Message.token == Token.get(Token.token == hug_token), Message.id == message_id, Message.reply_to != None) Score.create(message=msg, value=score) return {"status": "ok"} except Message.DoesNotExist: raise HTTPError(HTTP_404) except peewee.IntegrityError: raise HTTPError(HTTP_409)
def setUp(self): super().setUp() with db.atomic() as txn: self.game = Game.create( name='Game', starting_cash=10000.00, shareable_link='aaaabbbbccccdddd', shareable_code='aaaa', ends_at=(datetime.utcnow().replace(tzinfo=pytz.utc) + timedelta(days=7)).isoformat()) profile = Profile.create(username='******', hashed_password='******') GameProfile.create(game=self.game, profile=profile, cash=-1.0) Message.create( game=self.game.id, profile=profile.id, content="first message", # use default value for created_on ) self.token = AuthToken.create(profile=profile, token='thevalidtoken').token
def show_db_message_table(): # creating HTML table from dict messages = {} query = Message.select().dicts() msg_id = 0 for row in query: messages[msg_id] = row msg_id += 1 df = pd.DataFrame(data=messages) df = df.fillna(' ').T resp = df.to_html() return resp
def add_message(from_user, to_user, content): f_user = session.query(User.name).filter_by(name=from_user).first()[0] t_user = session.query(User.name).filter_by(name=to_user).first()[0] if f_user and t_user: new_message = Message(from_user=f_user, to_user=t_user, content=content) session.add(new_message) session.commit() print('************ insert successful ************') return True
def __init__(self, resources): self._mutex = threading.RLock() logging.info('Starting logging thread') self._object = resources.object self._resources = resources db = self._resources.getDbManager() self._log = Log(db) self._message = Message(db) self._plc = self._resources.plcManager self._position = self._resources.plcManager.getPositionHelper() self._period = resources.config.getLoggingTime() self._altitude = None self._start()
def message(): if request.method == 'POST': if request.form.get('name') and request.form.get('message_content'): message = Message( ip_address=request.remote_addr, date_time=datetime.utcnow().isoformat(), name=request.form['name'], content=request.form['message_content'] ) db.session.add(message) db.session.commit() return jsonMessages()
def add_message_to_assignment(class_id, assign_id): post_body = json.loads(request.data) single_class = Class.query.filter_by(id=class_id).first() assignment = Assignment.query.filter_by(id=assign_id).first() user = User.query.filter_by(username=post_body.get('username')).first() if single_class is None: return json.dumps({'success': False, 'error': 'Class not found'}), 404 elif assignment is None: return json.dumps({ 'success': False, 'error': 'Assignment not found' }), 404 message = Message(message=post_body.get('message', ''), username=post_body.get('username', 'anonymous'), name=post_body.get('name', 'anonymous'), time=post_body.get('time', '2000-01-01T00:00:00'), assignment_id=assign_id) if user is not None: user.classes.append(single_class) user.assignments.append(assignment) assignment.messages.append(message) db.session.add(message) db.session.commit() return json.dumps({'success': True, 'data': message.serialize()}), 200
def create(): if request.method == 'GET': return render_template('create.html') content = request.form.get('content') if not content: flash('Please input message') return redirect(url_for('create')) user = get_session_user() assert user is not None message = Message.create( user=user, content=content, pub_date=datetime.datetime.now() ) flash('Your message has been created') return redirect(url_for('user_detail', username=user.username))
def contact(): error, success = False, False if request.method == 'POST': name = request.form['name'] email = request.form['email'] message = request.form['message'] date = datetime.now().__str__() try: new_message = Message(name=name, email=email, message=message, date=date) session.add(new_message) session.commit() success = True except: error = True return render_template('contact.html', error=error, success=success)
def main(): Session = sessionmaker(bind=engine) session = Session() r = re.compile( '^(?P<sender>[\w-]+)>([^:]+)::(?P<recipient>[^:]+):(?P<body>[^{]*){?(.*)$' ) while True: try: s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((settings.APRS_IS_HOST, settings.APRS_IS_PORT)) s.sendall('user %s pass %s\n' % (settings.CALLSIGN, doHash(settings.CALLSIGN))) try: f = s.makefile() for l in f: print l, m = r.match(l) if not m: continue sender = m.group('sender').strip() recipient = m.group('recipient').strip() body = m.group('body').strip() session.add( Message(sender=sender, recipient=recipient, body=body)) try: session.commit() except DataError as e: print 'ERROR:', e except KeyboardInterrupt: raise finally: f.close() except KeyboardInterrupt: break finally: s.shutdown(socket.SHUT_RDWR) s.close()
def create_chat_message(profile_id, game_id, message): try: int(profile_id) int(game_id) assert len(message) > 0 except: raise BadRequest("Invalid parameters to create chat message") message = Message.create( game=game_id, profile=profile_id, content=message, # use default value for created_on ) game = Game.get_or_none(Game.id == game_id) if game is not None: print("Broadcaseting to game") broadcast_in_a_game(game, 'chat', '', False) return message
async def on_message(self, message): if message.author == self.user: return if config.get( 'channels-whitelist') and message.channel.name not in strip( config.get('channels-whitelist').split(',')): return if config.get('channels-blacklist') and message.channel.name in strip( config.get('channels-blacklist').split(',')): return content = message.content mentions = message.mentions bot_mention = lambda user: not user.bot if all(mentions, bot_mention): return if message.author.bot: return if len(message.attachments) > 0: return r = s.query(Message).filter( Message.message.ilike(content)).one_or_none() if r: channel = message.channel await message.delete() await channel.say( '{0} Your message has been deleted as an identical message has been sent already.' .format(author.mention)) else: db_entry = Message(username=message.author.name, message=content) s.add(db_entry) s.commit()
def process_question(message): return Message.create(token=message.token, content='Reply to: ' + message.content, reply_to=message)
def save_massage(self, user_id, message): mes = Message(user_id, message) session.add(mes) session.commit()
def send_message(hug_token, message: hug.types.text): msg = Message.create(content=message, token=Token.get(Token.token == hug_token)) return model_to_dict(chatbot.process_question(msg))
from alfa_cv import AlfaCV from parser_message import ParserMessage from db import Message a = AlfaCV('history.jpg') messages = a.get_messages() bulk_list = [] for message in messages: parser = ParserMessage(message) bulk_list.append( Message(card=parser.get_card(), balance=parser.get_balance(), amount=parser.get_amount(), currency=parser.get_currency(), date=parser.get_date(), body=parser.text)) Message.bulk_create(bulk_list)
def create(self, content): m = Message(content=content) super().create(m)
class LogThread(object): """ Separate thread for logging stuff. It starts to log in separate thread as new instance will be done or _start() method will be called Timer could be stopped be calling stop() method. """ def __init__(self, resources): self._mutex = threading.RLock() logging.info('Starting logging thread') self._object = resources.object self._resources = resources db = self._resources.getDbManager() self._log = Log(db) self._message = Message(db) self._plc = self._resources.plcManager self._position = self._resources.plcManager.getPositionHelper() self._period = resources.config.getLoggingTime() self._altitude = None self._start() def _start(self): """ Starts timer to run, function is looped by itself. Should be interrupted by calling timer.cancel() in other case it will become a daemon """ if self._plc.isSwitchedOn(): self._doWork() self._timer = threading.Timer(self._period, self._start) self._timer.start() def stop(self): """ Thread safe method for stopping timer. It will finish as soon as timer thread stops working and thread will be closed""" with self._mutex: self._timer.cancel() self._timer.join() def _doWork(self): """ All logging stuff performs here. This method is calling by logging thread """ with self._mutex: if self._resources.plcManager.isConnected(): self._log.setStarId(self._getStarId()) self._log.setMsgId(self._getMsgId()) self._log.setCurrentRaDec(*self._getCurrentRaDec()) self._log.setCurrentFocus(self._getCurrentFocus()) self._log.setTemperature(*self._getTemperature()) self._log.setAlarmStatus(self._getAlarmStatus()) self._log.setCurrentAltitude(self._getAltitude()) self._log.writeToLog() def force(self): with self._mutex: self._timer.cancel() self._timer.join() self._start() def updatePeriod(self, time): """ Update logging period, period in seconds """ self._period = time def _getStarId(self): """ return selected object id from controller, if object is not selected return None """ object = self._resources.object return object.getId() def _getMsgId(self): """ for getting current message last stored message is used """ id = self._message.getLastId() return id def _getCurrentRaDec(self): """ current telescope positions are taken directly from plc """ return self._position.getCurrentPosition() def _getAltitude(self): if self._object.selected(): alt, az = self._object.getHorizontalPosition() return alt.real def _getCurrentFocus(self): """ current telescope positions are taken directly from plc """ focus = self._position.getFocus() return focus def _getTemperature(self): """ current dome and telescope temperatures """ return self._plc.getModeHelper().readTemperatures() def _getAlarmStatus(self): """ alarm status as a alarm codes separated by ',' """ return self._plc.readAlarmStatus()
def add_message_record(source, text, sent, body): logger.info('adding new record to Message table [from:{}, text:{}]'.format(source, text)) message = Message.create(source=source, text=text, sent=sent, body=body) message.save()
def receive_message(hug_token, after_msg_id: hug.types.number): token = Token.get(Token.token == hug_token) return Message.select().where(Message.token == token, Message.reply_to != None, Message.id > after_msg_id).dicts()
def public_timeline(): # simply display all messages, newest first messages = Message.select() return object_list('public_messages.html', messages, 'message_list')
def read_messages(driver, queue, **params): page_number = 1 messages_on_page = 10 messages = {} while True: driver.get('%s?t=0&order=DESC&page=%d' % (Player.PAGES['MESSAGES'], page_number)) time.sleep(2) unread_messages = Player._parse_message_table(driver) for i in unread_messages: messages.update({ i[1]: { 'header': i[2], 'from_id': i[3], 'from_name': i[4], 'date_time': i[5] } }) if len(unread_messages) < messages_on_page: break page_number += 1 for travian_id, message_params in messages.items(): driver.get('%s?id=%d' % (Player.PAGES['MESSAGES'], travian_id)) time.sleep(2) try: body = driver.find_element_by_xpath("//div[@id='message']") except NoSuchElementException: logging.error('Cant read message mody id=%d' % travian_id) return queue body = body.text message_params['body'] = body if messages: logging.info('%d New messages!' % len(messages)) for travian_id, message_params in messages.items(): Message.create_new( travian_id, message_params['from_id'], message_params['from_name'], message_params['header'], message_params['body'], message_params['date_time'], ) need_def_messages = Message.get_need_def_messages() if need_def_messages: try: server_time = driver.find_element_by_xpath( "//div[@id='servertime']/span") except NoSuchElementException: logging.error('Cant define servertime') return queue h, m, s = server_time.text.split(':') h = Player._to_int(h) m = Player._to_int(m) s = Player._to_int(s) now = datetime.now() year, month, day = now.year, now.month, now.day now = datetime(year, month, day, h, m, s) for need_def_message in need_def_messages: if need_def_message.valid_def_message() is False: logging.warning( 'Someone in message travian_id = %s whant def.' % need_def_message.travian_id) continue params = need_def_message.get_def_params() if params is None: continue return queue x, y, atack_time = params atack_timedelta = atack_time - now if atack_timedelta.total_seconds() < 0: logging.warning('Passed atack. Message travian_id = %s' % need_def_message.travian_id) need_def_message.readed() continue helpers = get_help(x, y, atack_timedelta) if 'Dictator' in helpers: helpers.remove('Dictator') attention_message = ''' ########################################## Внимание! Наша деревня [x|y]({x}|{y})[/x|y] атакована. Атака будет совершена в {atack_time}. Всем кто успевает. Необходимо выслать деф на данные координаты. p.s. Всем удачи! И не забывайте выслать кроп для своих войск. ########################################## '''.format(x=x, y=y, atack_time=str(atack_time)) head = 'Нужен ДЕФ' if helpers: # We can write only for 25 peoples. counter = 0 to_helpers = [] for helper in helpers: counter += 1 to_helpers.append(helper) if counter == 24: Player.write_message(driver, to_helpers, head, attention_message) counter = 0 to_helpers = [] if to_helpers: Player.write_message(driver, to_helpers, head, attention_message) head = 'RE: %s' % need_def_message.header if helpers: attention_message = ''' ########################################## Игроки, которые могут оперативно прислать помощь оповещены. ########################################## ''' dictator_message = ''' ########################################## Наша деревня [x|y]({x}|{y})[/x|y] атакована. Атака будет совершена в {atack_time}. Игроки, которые могут помочь проинформированы: {helpers} ########################################## '''.format(x=x, y=y, atack_time=str(atack_time), helpers='\n'.join(helpers)) else: attention_message = ''' ########################################## Нет игроков, готовых оперативно помочь. ########################################## ''' dictator_message = ''' ########################################## Наша деревня [x|y]({x}|{y})[/x|y] атакована. Атака будет совершена в {atack_time}. Нет игроков, готовых оперативно помочь. ########################################## '''.format(x=x, y=y, atack_time=str(atack_time)) Player.write_message(driver, need_def_message.from_name, head, attention_message) Player.write_message( driver, 'Dictator', 'На деревню (%s, %s) будет совершено нападение' % (x, y), dictator_message) need_def_message.readed() return queue