def ask_message(self, user): """ Function that runs in a Thread to keep asking the host for the message to send. :param user: host username to include as sender :return: response message """ print "=======================" print "| HOST CHAT |" print "=======================" while True: text = raw_input("Write the message: ") if "#" not in text: to = raw_input("Receiver: ") data = Message(user, to, text).to_dict() response = self.send(data) else: data = Message(user, None, text, 'b').to_dict() response = self.send(data) if response["status"] == -1: print "" print response["msg"] print ""
def handleMessage(tag: Tag, chat: Chat, prev_tag: Tag = None): if not prev_tag: txt = tag.find('div', attrs={'class': 'text'}) reply_to = tag.find('div', attrs={'class': 'reply_to_details'}) fromUser = tag.find('div', attrs={ 'class': 'from_name' }).getText().strip() chat.push( Message( int(tag.get('id').replace('message', '')), chat.extractUserAndBotNameFromMessage(fromUser) if chat.isAViaBotMessage(fromUser) else (fromUser, None), txt.getText().strip() if txt else None, tag.find('div', attrs={ 'class': 'pull_right date details' }).get('title'), int(reply_to.a.get('href')) if reply_to else None)) chat.updateUserRecords(fromUser, int(tag.get('id').replace('message', ''))) else: txt = prev_tag.find('div', attrs={'class': 'text'}) fromUser = prev_tag.find('div', attrs={ 'class': 'from_name' }).getText().strip() chat.push( Message( int(tag.get('id').replace('message', '')), chat.extractUserAndBotNameFromMessage(fromUser) if chat.isAViaBotMessage(fromUser) else (fromUser, None), txt.getText().strip() if txt else None, tag.find('div', attrs={ 'class': 'pull_right date details' }).get('title'))) chat.updateUserRecords(fromUser, int(tag.get('id').replace('message', '')))
def parseMessagesFromFile(filePath, limit=0, startDate=None, endDate=None): messages = [] senders = set([]) if startDate: startDate = datetime.strptime(startDate, Message.DATE_FORMAT) if endDate: endDate = datetime.strptime(endDate, Message.DATE_FORMAT) try: with open(filePath, 'r', encoding="utf8") as f: for line in f: date, time, sender, text = line.split(' ', 3) if startDate or endDate: thisDate = datetime.strptime(date, Message.DATE_FORMAT) if (not startDate or thisDate >= startDate) and ( not endDate or thisDate <= endDate): messages.append( Message(date, time, sender, text.strip())) else: messages.append(Message(date, time, sender, text.strip())) senders.add(sender) if limit != 0 and len(messages) >= limit: break except IOError: logger.warning("No such file: " + filePath) return messages, senders
def twil(): client = TwilioRestClient(ACCOUNT_SID, AUTH_TOKEN) from_ = request.form.get("From", WEI_HAN) body = request.form.get("Body", default="") picture = request.form.get("MediaUrl{1}", default="") message_id = request.form.get("MessageSid", default="") log = "IN: MessageSid = {}, From = {}, Body = {}".format(message_id, from_, body) logging.info(log) message = Message(From=from_, To=SERVER_NUMBER, Body=body, id=message_id) message.put() ''' Pass message into action builder.''' response_list = [] try: response_list = CommandHandler.handler(message) except (CommandError, DbError, TeamError, MeError, TargetError, TimeError,\ ReplyError) as message: logging.exception("Error {}".format(message.message)) response_num_list = [from_] response = "[ERR] {}".format(message.message) response_list = [(response_num_list, response)] except: logging.exception("Unknown Error") response_num_list = [from_] response = "[ERR] Unknown Error" response_list = [(response_num_list, response)] for response_num_list, response in response_list: for response_number in response_num_list: logging.info("Making message {} for {} with num_list {}".format(response, response_number, response_num_list)) '''Make message''' outgoing_message = Message(From=SERVER_NUMBER, To=response_number, Body=response) outgoing_message.put() logging.info(response) '''Send message''' client.messages.create( to=response_number, from_=SERVER_NUMBER, body=response) logging.info(response) return "Welcome to SAMSU assassins. The site is up and working.\
async def process_command(self, command): """ Process a command from the user. """ self.log.info(f"process_command({command=})") try: # Get input args = command.split(' ') # Do input if args[0] == 'hero': hero_name = args[1] args = args[2:] self.log.info(f"hero command {hero_name=}, {args=}") hero = next( filter(lambda h: h.name == hero_name, self.gamestate.heroes), None) if not hero: raise Complaint(Message('nosuchhero', hero_name)) if args[0] == 'play': # Forces card into a lower case string to prevent capitalization issues with input card = args[1].lower() await self.play_card(hero, card) elif args[0] == 'discard': card = args[1].lower() await self.discard_card(hero, card) elif args[0] == 'draw': await self.draw_card(hero) else: raise Complaint(Message('error', 'invalidcommand')) # TODO: Add hero abilities else: raise Complaint(Message('error', 'invalidcommand')) # break out when all enemies isded if self.gamestate.door_deck.is_defeated: await self.emit(Message('state', 'won')) except (Complaint, Exception) as e: if isinstance(e, Complaint): await self.emit(e.msg) else: await self.emit(Message('error', str(e)))
def new_slack_msg(self): rtm_client = self.slack_helper.create_rtm_client() if rtm_client.rtm_connect(): while True: try: rtv = rtm_client.rtm_read() if len(rtv) != 0: logger.debug(rtv[0]) if not rtv[0].get('subtype') and rtv[0].get( 'type') == 'message': # compose a message gid = rtv[0].get('channel') content = rtv[0].get('text') dest, type = self.get_src_id_and_type_from_sessions( gid) if dest is False: logger.warn('dest is false ' + str(gid)) message = Message(type, gid, None, dest, content) self.mq_pub( json.loads( json.dumps(message, default=lambda o: o.__dict__))) time.sleep(1) except Exception as e: logger.warn(e) rtm_client.rtm_connect() else: logger.error('rtm_client cant connect')
def spy(): logging.info("Spy cron") client = TwilioRestClient(ACCOUNT_SID, AUTH_TOKEN) ''' Get all ALIVE spies ''' alive_spies = Player.query(Player.role == "SPY").fetch() logging.info("Alive Spies:") logging.info(alive_spies) ''' For each spy, make and send hint ''' for spy in alive_spies: if spy.state == "DEAD": continue response = Player.spy_hint(spy) msg = Message(From=SERVER_NUMBER, To=spy.key.id(), Body=response) msg.put() client.messages.create( to=spy.key.id(), from_=SERVER_NUMBER, body=response) logging.info("SPY CRON: completed send to {}".format(alive_spies)) return "Ok"
def send_message(): """ Sends message to user :param sent_by :param sent_to :param message_body :param from_admin :return: """ sent_by = request.form.get('sent_by') sent_to = request.form.get('sent_to') message_body = request.form.get('message_body') from_admin = True if request.form.get('from_admin') == 'True' else False listing_id = request.form.get('listing_id') new_message = Message(sent_by=sent_by, sent_to=sent_to, message_body=message_body, from_admin=from_admin, timestamp=datetime.datetime.now(), listing_id=listing_id) db.session.add(new_message) db.session.commit() return jsonify({ 'message_id': new_message.message_id, 'timestamp': new_message.timestamp })
def handle_send_message_event(data): timestamp = datetime.now().strftime('%H:%M') # unpack the delivered json object try: input_data = json.load(data) message_object = input_data['child'] username = message_object['username'] room = message_object['room'] content = message_object['message'] except: socketio.emit(500) # log that a message was sent app.logger.info("{} to {} @ {}: {}".format(username, room, timestamp, content)) # create a new message object with a json accordingly new_message = Message(username, room, content, timestamp) new_message_json = new_message.get_json() # put this new message in the database and send it out save_message(new_message) socketio.emit(new_message_json)
def register(): request.get_json(force=True) request_json = request.json name = escape(request_json.get('name')) email = request_json.get('email') message = escape(request_json.get('message')) try: new_message = Message(name=name, email=email, message=message) db.session.add(new_message) db.session.commit() message_mail = MessageMail( 'Portfolio Contato', recipients=[os.environ.get('EMAIL_TO')], body=message, ) mail.send(message_mail) data = {'status': 'success'} except Exception as error: return {'error': str(error)}, 500 return jsonify(data), 201
def on_join_rooms(message): uid_from = message['uid_from'] room_from = message['room_from'] join_room(room_from) joined_rooms = rooms() app.logger.error('{}--join_room--{}--joined_rooms_is---{}'.format(uid_from, room_from, joined_rooms)) text = message['text'] msg_type = message['type'] is_send_to_server = message['is_send_to_server'] time_client = message['time_client'] room_to = message['room_to'] message = Message(text, msg_type, is_send_to_server, time_client, room_from, room_to, uid_from, uid_from) message.save() message_id = message.id app.logger.error('message_id-{}--{}--saved to db'.format(message_id, message.text)) if room_from in joined_rooms: update_sid_uid_map(sid=request.sid, uid=uid_from) add_online_uids(uid_from) data = { 'id': message_id, 'text': 'join_room_ok', 'room_from': room_from, 'type': MESSAGE_TYPE.MESSAGE_ACK.value, 'uid_from': uid_from, } async_emit_msg.delay('join_room', data, broadcast=True)
async def draw_card(self, hero): """ Make the given hero draw a card. """ self.log.info(f'draw_card({hero=})') card = hero.draw_card() await self.emit(Message('draw', [hero, card]))
def load_message(self, messagelist): message = Message() message.send = messagelist[0] message.text = messagelist[1] message.timestamp = messagelist[2] message.uuid = messagelist[3] message.seq = messagelist[4] return message
async def discard_card(self, hero, card): """ Move the given card to the discard pile. """ self.log.info(f'discard_card({hero=}, {card=})') hero.discard(card) await self.emit(Message('discard', [hero, card]))
def __parse_plain_message_block( blockchain_message_block: BlockchainMessageBlock, timestamp: int, compression_algorithm: CompressionAlgorithm, encoding: Encoding) -> Message: public_key_algorithm = Constants.PUBLIC_KEY_ALGORITHM() message_block_as_bytes = blockchain_message_block.data byte_index = Constants.FLAGS_LENGTH signature_length = public_key_algorithm.signature_length() signature = message_block_as_bytes[byte_index:byte_index + signature_length] byte_index += signature_length message_content = message_block_as_bytes[:Constants. FLAGS_LENGTH] # flags message_content += message_block_as_bytes[byte_index:] compressed_data = message_block_as_bytes[byte_index:] decompressed_data = Compressor.decompress( algorithm=compression_algorithm, data=compressed_data) byte_index = 0 message_type_bytes = decompressed_data[byte_index:byte_index + Constants.MESSAGE_TYPE_LENGTH] byte_index += Constants.MESSAGE_TYPE_LENGTH message_type_value = struct.unpack('!B', message_type_bytes)[0] message_type = MessageType(message_type_value) public_key_length = public_key_algorithm.get_public_key_class( ).key_length() sender_bytes = decompressed_data[byte_index:byte_index + public_key_length] byte_index += public_key_length sender = public_key_algorithm.get_public_key_class().parse( sender_bytes) nonce_timestamp = GeneralUtils.decode_unix_timestamp( decompressed_data[byte_index:byte_index + Constants.TIMESTAMP_LENGTH]) byte_index += Constants.TIMESTAMP_LENGTH message_bytes = decompressed_data[byte_index:] encoding_str = Encoding.get_str(encoding) message = message_bytes.decode(encoding_str) MessageBlockParser.__check_signature(message=message_content, public_key=sender, signature=signature) return Message(block_hash=blockchain_message_block.block_hash, sender=sender, message_type=message_type, message=message, timestamp=timestamp, nonce_timestamp=nonce_timestamp)
def handle_message(data): app.logger.info('received message: %s', data) app.logger.info('message %s', data.get('message')) data = data.get('message') message = Message(data.get('username'), data.get('message')) message.save() # app.logger.info("test %s", data.message) emit('add_message', 'message recu')
def _process_message(self, ch, method, properties, message): print(f'A new message was received: {message}') msg_type = ['incoming', 'outgoing'] storage = BigQuery() message = Message(f'1', '1', random.choice(msg_type), message.decode('utf-8')) storage.insert_message(message) print('message send at ', datetime.utcnow())
def test_clean(self): peer1 = ConversationPeer( peer=User(user_key=UserPK(user_id='stub', platform=UserPK.PLATFORM_TELEGRAM), username='******'), assigned_profile=PersonProfile(sentences=['stub profile'])) peer2 = ConversationPeer( peer=Bot(token='stub', bot_name='Dummy'), assigned_profile=PersonProfile(sentences=['stub profile 2'])) peers = [peer1, peer2] for p in peers: p.peer.save(cascade=True) p.assigned_profile.save(cascade=True) n_msg = 10 start_time = datetime.now() end_time = start_time + timedelta(hours=n_msg - 1) msgs = list( map( lambda x: Message(msg_id=x, text=str(x), sender=peers[x % 2].peer, time=start_time + timedelta(hours=x)), range(10))) test_conv = Conversation(conversation_id=1) test_conv.participant1 = peers[0] test_conv.participant2 = peers[1] with self.assertRaises(mongoengine.ValidationError): test_conv.save() test_conv.participant1 = None test_conv.participant2 = None test_conv.messages = msgs with self.assertRaises(mongoengine.ValidationError): test_conv.save() test_conv.participant1 = peers[0] test_conv.participant2 = peers[1] raised = False error_msg = '' try: test_conv.save() except Exception as e: raised = True error_msg = 'Unexpected exception: {}'.format(e) self.assertFalse(raised, error_msg) self.assertEqual(test_conv.start_time, start_time) self.assertEqual(test_conv.end_time, end_time)
def on_pubmsg(self, conn, event): """ archive public message """ session = self.sessionmaker() message = Message(user=event.source.split("!")[0], message=event.arguments[0].strip()) session.add(message) session.commit() print(event.type, event.source, event.target, event.arguments)
def read_block(path): __block = [] for filename in listdir(path): with open(join(path, filename)) as f: lines = f.readlines() __subject = np.array(map(int, lines[0].strip().split(' ')[1:])) __text = np.array(map(int, lines[2].strip().split(' '))) __type = __message_type_from_filename(filename) __block.append(Message(__subject, __text, __type)) return __block
def on_disconnect(): sid = request.sid uid = get_uid_with_sid(sid) remove_online_uids(uid) user = UserModel.find_by_id(uid) print('Client disconnected--{}--{}--{}'.format(sid, uid, user.to_json())) message = Message('disconnect_broadcast', MESSAGE_TYPE.MESSAGE_BROADCAST.value, False, int(round(time.time() * 1000)), user.room_private, user.room_private, uid, uid) message.save() async_emit_msg.delay('disconnect_broadcast', message.to_json(), broadcast=True)
def discard(self, card): """ Method to remove a card from the hero's hand """ # Checks if the card is held by the hero if self.get_card_from_hand(card): # If it is a valid card to remove, remove it self.hand.remove(card) else: raise Complaint(Message('error', 'nocard'))
def send(self, acquisitions): self.acquisitions = acquisitions if self.client is None: self.client = MQTTClient() self.client.connect_mqtt() if self.encryption is None: self.encryption = Encryption() for acquisition in acquisitions: message = Message(acquisition) jsonMessage = self.JSONConverter(message) self.client.publish(self.encryption.encrypt(jsonMessage))
def on_message(message): uid_from = message['uid_from'] room_from = message['room_from'] text = message['text'] msg_type = message['type'] is_send_to_server = message['is_send_to_server'] time_client = message['time_client'] room_to = message['room_to'] message = Message(text, msg_type, is_send_to_server, time_client, room_from, room_to, uid_from, uid_from) message.save() message_id = message.id app.logger.error('message_id-{}--{}--saved to db '.format(message_id, message.text)) async_emit_msg.delay('message', message.to_json(), room=room_to)
def parse(self, itemizer): print "Fetch messages from channel {}".format([self.channel_id]) response = self.slacker.channels.history(self.channel_id, count=config.MESSAGES_LIMIT) messages = response.body["messages"] for message in messages: if "subtype" in message or message["type"] != "message": continue is_bot = config.MY_BOT_ID == message["user"] t = datetime.fromtimestamp(float(message["ts"])) msg = Message(is_bot, t, message["text"]) itemizer.parse_message(msg)
def find_by_recipient(cursor, recipient_username): sql = "SELECT id, from_user, to_user, context, created_at FROM messages WHERE to_user=%s" ret = [] cursor.execute(sql, (recipient_username, )) for row in cursor.fetchall(): loaded_message = Message() loaded_message._id = row[0] loaded_message.from_user = row[1] loaded_message.to_user = row[2] loaded_message.context = row[3] loaded_message.created_at = row[4] ret.append(loaded_message) return ret
def check(self, website: Website) -> Message: # TODO support headers (auth, content-type etc); try: r = requests.get(url=website.url, timeout=self.timeout) regexp_check_passed: bool = False regexp_checked: bool = False if website.regexp: regexp_check_passed = self.regex_check.check( regexp=website.regexp, content=r.text) regexp_checked = True return Message(url=website.url, status=r.status_code, response_time_micro=r.elapsed.microseconds, regexp_checked=regexp_checked, regexp_passed=regexp_check_passed) except (RequestException, Exception) as e: return Message(url=website.url, status=None, response_time_micro=None, regexp_checked=False, regexp_passed=False)
def credit(): root = Tkinter.Tk() root.geometry('800x600') root.title('对公信贷系统') root.option_add("*Font", "helvetica -12") login = Login(master=root) login.pack() #p = PeopleInformationToplevel() people = People(master=root) message = Message(master=root) applys = Apply(master=root) panel_manager = PanelManager(login, people, message, applys) root.mainloop()
def message_event_handler(**payload): logger.debug(f"payload : {payload}") data = payload['data'] sub_type = data.get('subtype', None) if sub_type is not None: return web_client = payload['web_client'] rtm_client = payload['rtm_client'] if 'text' in data: message = Message(data) is_mention, message.bot_id = check_mention(message.text) commands = message.parse_message(is_mention) logger.debug(f"message {commands}") _parse_command(web_client, message, commands)
def save_messages(messages, is_thread): nonlocal count for msg in messages: Message(None, msg["ts"], channel_id, msg.get('user', None), msg.get('bot_id', None), msg.get('subtype', None), msg["text"], msg.get('icons', {}).get('image_64', None), msg.get('username', None), msg.get('thread_ts', None), is_thread).save() count += 1 if 'thread_ts' in msg and not is_thread: data, cursor = conversation.replies( token, channel_id, msg['thread_ts']) save_messages(data, True)