Python get messages
60 Python code examples are found related to "
get messages".
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
Example 1
Source File: slacker.py From destalinator with Apache License 2.0 | 6 votes |
def get_messages_in_time_range(self, oldest, cid, latest=None): assert cid in self.channels_by_id, "Unknown channel ID {}".format(cid) cname = self.channels_by_id[cid] messages = [] done = False while not done: murl = self.url + "channels.history?oldest={}&token={}&channel={}".format(oldest, self.token, cid) if latest: murl += "&latest={}".format(latest) else: murl += "&latest={}".format(int(time.time())) payload = self.get_with_retry_to_json(murl) messages += payload['messages'] if payload['has_more'] is False: done = True continue ts = [float(x['ts']) for x in messages] earliest = min(ts) latest = earliest messages.sort(key=lambda x: float(x['ts'])) for message in messages: message['channel'] = cname return messages
Example 2
Source File: destalinator.py From destalinator with Apache License 2.0 | 6 votes |
def get_messages(self, channel_name, days): """Return `days` worth of messages for channel `channel_name`. Caches messages per channel & days.""" oldest = self.now - days * 86400 cid = self.slacker.get_channelid(channel_name) if oldest in self.cache.get(cid, {}): self.logger.debug("Returning %s cached messages for #%s over %s days", len(self.cache[cid][oldest]), channel_name, days) return self.cache[cid][oldest] messages = self.slacker.get_messages_in_time_range(oldest, cid) self.logger.debug("Fetched %s messages for #%s over %s days", len(messages), channel_name, days) messages = [x for x in messages if x.get("subtype") is None or x.get("subtype") in self.config.included_subtypes] self.logger.debug("Filtered down to %s messages based on included_subtypes: %s", len(messages), ", ".join(self.config.included_subtypes)) if cid not in self.cache: self.cache[cid] = {} self.cache[cid][oldest] = messages return messages
Example 3
Source File: tf_bag.py From tf_bag with GNU Lesser General Public License v3.0 | 6 votes |
def getMessagesInTimeRange(self, min_time=None, max_time=None): """ Returns all messages in the time range between two given ROS times :param min_time: the lower end of the desired time range (if None, the bag recording start time) :param max_time: the upper end of the desired time range (if None, the bag recording end time) :return: an iterator over the messages in the time range """ import genpy if min_time is None: min_time = -float('inf') elif type(min_time) in (genpy.rostime.Time, rospy.rostime.Time): min_time = min_time.to_nsec() if max_time is None: max_time = float('inf') elif type(max_time) in (genpy.rostime.Time, rospy.rostime.Time): max_time = max_time.to_nsec() if max_time < min_time: raise ValueError('the minimum time should be lesser than the maximum time!') indices_in_range = np.where(np.logical_and(min_time < self.tf_times, self.tf_times < max_time)) ret = (self.tf_messages[i] for i in indices_in_range[0]) return ret
Example 4
Source File: message_factory.py From Serverless-Deep-Learning-with-TensorFlow-and-AWS-Lambda with MIT License | 6 votes |
def GetMessages(file_protos): """Builds a dictionary of all the messages available in a set of files. Args: file_protos: Iterable of FileDescriptorProto to build messages out of. Returns: A dictionary mapping proto names to the message classes. This will include any dependent messages as well as any messages defined in the same file as a specified message. """ # The cpp implementation of the protocol buffer library requires to add the # message in topological order of the dependency graph. file_by_name = {file_proto.name: file_proto for file_proto in file_protos} def _AddFile(file_proto): for dependency in file_proto.dependency: if dependency in file_by_name: # Remove from elements to be visited, in order to cut cycles. _AddFile(file_by_name.pop(dependency)) _FACTORY.pool.Add(file_proto) while file_by_name: _AddFile(file_by_name.popitem()[1]) return _FACTORY.GetMessages([file_proto.name for file_proto in file_protos])
Example 5
Source File: dht_msg.py From pyp2p with MIT License | 6 votes |
def get_messages(self): result = [] if self.has_messages(): while not self.protocol.messages_received.empty(): result.append(self.protocol.messages_received.get()) # Run handlers on messages. old_handlers = set() for received in result: for handler in self.message_handlers: expiry = handler( self, received ) if expiry == -1: old_handlers.add(handler) # Expire old handlers. for handler in old_handlers: self.message_handlers.remove(handler) return result return result
Example 6
Source File: storage.py From luci-py with Apache License 2.0 | 6 votes |
def get_latest_messages_async(config_sets, path, message_factory): """Reads latest config files as a text-formatted protobuf message. |message_factory| is a function that creates a message. Typically the message type itself. Values found in the retrieved config file are merged into the return value of the factory. Returns: A mapping {config_set: message}. A message is empty if the file does not exist. """ configs = yield get_latest_configs_async(config_sets, path) def to_msg(text): msg = message_factory() if text: text_format.Merge(text, msg) return msg raise ndb.Return({ cs: to_msg(text) for cs, (_, _, _, text) in configs.items() })
Example 7
Source File: forms.py From djangocms-spa with MIT License | 6 votes |
def get_form_state_and_messages_dict(self): data_dict = { 'state': { 'error': bool(self.errors) } } error_messages = [] if self.errors and self.show_general_error_message: error_messages.append(str(self.default_validation_error)) non_field_errors = self.errors.get(ALL_FIELDS) if non_field_errors: error_messages.extend(non_field_errors) if error_messages: data_dict['messages'] = { 'error': error_messages } return data_dict
Example 8
Source File: _extractors.py From flakehell with MIT License | 6 votes |
def get_messages(code: str, content: str) -> Dict[str, str]: root = ast.parse(content) CollectStrings._strings = [] collector = CollectStrings() collector.visit(root) messages = dict() for message in collector._strings: message_code, _, message_text = message.partition(' ') if not message_text: continue if not REX_CODE.match(message_code): continue if code and not message_code.startswith(code): continue messages[message_code] = message_text return messages
Example 9
Source File: task.py From pyvivado with MIT License | 6 votes |
def get_messages(self, ignore_strings=config.default_ignore_strings): ''' Get any messages that the process wrote to it's output. and work out what type of message they were (e.g. ERROR, INFO...). Args: `ignore_strings`: Is a list of strings which when present in messages we ignore. ''' messages = [] out_lines = (self.get_stdout(), self.get_stderr()) for lines in out_lines: for line in lines: ignore_line = False for ignore_string in ignore_strings: if ignore_string in line: ignore_line = True if not ignore_line: for mt, logger_function in self.MESSAGE_MAPPING.items(): if line.startswith(mt): messages.append((mt, line[len(mt)+1:-1])) return messages
Example 10
Source File: irc.py From CuckooSploit with GNU General Public License v3.0 | 6 votes |
def getClientMessages(self, buf): """Get irc client commands of tcp streams. @buf: list of messages @return: dictionary of the client messages """ try: self._unpack(buf) except Exception: return None entry_cc = [] for msg in self._messages: if msg["type"] == "client": entry_cc.append(msg) return entry_cc
Example 11
Source File: irc.py From CuckooSploit with GNU General Public License v3.0 | 6 votes |
def getServerMessages(self, buf): """Get irc server commands of tcp streams. @buf: list of messages @return: dictionary of server messages """ try: self._unpack(buf) except Exception: return None entry_sc = [] for msg in self._messages: if msg["type"] == "server": entry_sc.append(msg) return entry_sc
Example 12
Source File: irc.py From CuckooSploit with GNU General Public License v3.0 | 6 votes |
def getServerMessagesFilter(self, buf, filters): """Get irc server commands of tcp streams. @buf: list of messages @return: dictionary of server messages filtered """ try: self._unpack(buf) except Exception: return None entry_sc = [] for msg in self._messages: if msg["type"] == "server" and msg["command"] not in filters: entry_sc.append(msg) return entry_sc
Example 13
Source File: irc.py From CuckooSploit with GNU General Public License v3.0 | 6 votes |
def getClientMessagesFilter(self, buf, filters): """Get irc client commands of tcp streams. @buf: list of messages @return: dictionary of the client messages filtered """ try: self._unpack(buf) except Exception: return None entry_cc = [] for msg in self._messages: if msg["type"] == "client" and msg["command"] not in filters: entry_cc.append(msg) return entry_cc
Example 14
Source File: messages.py From freelancer-sdk-python with GNU Lesser General Public License v3.0 | 6 votes |
def get_messages(session, query, limit=10, offset=0): """ Get one or more messages """ query['limit'] = limit query['offset'] = offset # GET /api/messages/0.1/messages response = make_get_request(session, 'messages', params_data=query) json_data = response.json() if response.status_code == 200: return json_data['result'] else: raise MessagesNotFoundException( message=json_data['message'], error_code=json_data['error_code'], request_id=json_data['request_id'] )
Example 15
Source File: retrieve_msgs.py From groupme_stats with MIT License | 6 votes |
def getMessages(group_id, direct_msgs, before_id=None, since_id=None): """ Given the group_id and the message_id, retrieves 20 messages Params: before_id: take the 20 messages before this message_id since_id: take the 20 messages after this message_id (maybe) """ params = {} if before_id is not None: params['before_id'] = str(before_id) if since_id is not None: params['since_id'] = str(since_id) try: if direct_msgs: params['other_user_id'] = group_id msgs = get(requests.get(URL + '/direct_messages' + TOKEN, params=params)) else: msgs = get(requests.get(URL + '/groups/' + group_id + '/messages' + TOKEN, params=params)) except ValueError: return [] return msgs
Example 16
Source File: recipe-577637.py From code with MIT License | 6 votes |
def get_messages(self): # Schedule method for one second from now. self.after(1000, self.get_messages) # Get a list of new files. files = set(os.listdir(HOLD)) diff = files - self.__dirlist self.__dirlist = files # Load each new message. messages = [] for name in diff: path = os.path.join(HOLD, name) try: with open(path) as file: user, clock, message = self.load_message(file) messages.append((user, float(clock), message)) except: # Print any error for debugging purposes. traceback.print_exc() os.remove(path) # Sort the messages according to time and display them. messages.sort(key=lambda m: m[1]) for m in messages: self.display_message(m[0], m[2])
Example 17
Source File: sqs_wrapper.py From mycroft with MIT License | 6 votes |
def get_messages_from_queue(self): """ Fetches messages from the sqs queue of name passed in during this object's construction. Does not handle exceptions from Boto. :rtype: a list of SQS message or None """ try: msgs = self._queue.get_messages( num_messages=self._num_messages_to_fetch, wait_time_seconds=self._wait_time_secs) return msgs except (BotoClientError, BotoServerError): log_exception( "Boto exception in fetching messages from SQS, for queue name:" + self._queue.id) raise
Example 18
Source File: fastproto.py From orisi with MIT License | 6 votes |
def getMessages(): url = 'http://hub.orisi.org/?format=json' r = tryForever(requests.get, url) data = json.loads(r.text) decoded_results = [] for req in data['results']: try: decoded_body = decode_data(req['body']) req['body'] = decoded_body if not verify(req['body'], req['signature'], req['source']): logging.warning('fastcast: bad signature for frame: %r; ignoring' % req['frame_id']) continue req['source'] = re.sub(r'\n','',req['source']) decoded_results.append(req) except: logging.warning('fastcast: problem decoding frame: %r; ignoring' % req['frame_id']) continue data['results'] = decoded_results return data
Example 19
Source File: wechat_history.py From wechat-history with MIT License | 6 votes |
def get_all_messages(account_info): starting_msg_url = construct_message_url(account_info, new=True) chunk = Chunk(starting_msg_url) messages = [] while chunk.errmsg == 'ok': # result is good, save the message list messages.extend(chunk.message_list) # loading more if chunk.can_msg_continue: offset = chunk.next_offset next_url = construct_message_url(account_info, next_offset=offset) chunk = Chunk(next_url) # nothing to load anymore, return the message else: return messages
Example 20
Source File: imessage.py From pymessage-lite with MIT License | 6 votes |
def get_messages_for_recipient(id): connection = _new_connection() c = connection.cursor() # The `message` table stores all exchanged iMessages. c.execute("SELECT * FROM `message` WHERE handle_id=" + str(id)) messages = [] for row in c: text = row[2] if text is None: continue date = datetime.datetime.fromtimestamp(row[15] + OSX_EPOCH) # Strip any special non-ASCII characters (e.g., the special character that is used as a placeholder for attachments such as files or images). encoded_text = text.encode('ascii', 'ignore') messages.append(Message(encoded_text, date)) connection.close() return messages
Example 21
Source File: api.py From matrixcli with GNU General Public License v3.0 | 6 votes |
def get_room_messages(self, room_id, token, direction, limit=10, to=None): """Perform GET /rooms/{roomId}/messages. Args: room_id (str): The room's id. token (str): The token to start returning events from. direction (str): The direction to return events from. One of: ["b", "f"]. limit (int): The maximum number of events to return. to (str): The token to stop returning events at. """ query = { "roomId": room_id, "from": token, "dir": direction, "limit": limit, } if to: query["to"] = to return self._send("GET", "/rooms/{}/messages".format(quote(room_id)), query_params=query, api_path="/_matrix/client/r0")
Example 22
Source File: qrlnode.py From QRL with MIT License | 6 votes |
def get_inbox_messages_by_address(self, address: bytes, item_per_page: int, page_number: int): if item_per_page == 0: return None transaction_hashes = self._load_inbox_message_transaction_hashes(address, item_per_page, page_number) response = qrl_pb2.GetTransactionsByAddressResp() for tx_hash in transaction_hashes: tx, block_number = self._chain_manager.get_tx_metadata(tx_hash) b = self.get_block_from_index(block_number) transaction_detail = qrl_pb2.GetTransactionResp(tx=tx.pbdata, confirmations=self.block_height - block_number + 1, block_number=block_number, block_header_hash=b.headerhash, timestamp=b.timestamp, addr_from=tx.addr_from) response.transactions_detail.extend([transaction_detail]) return response
Example 23
Source File: GooglePubSub.py From content with MIT License | 6 votes |
def get_messages_ids_and_max_publish_time(msgs): """ Get message IDs and max publish time from given pulled messages """ msg_ids = set() max_publish_time = None for msg in msgs: msg_ids.add(msg.get("messageId")) publish_time = msg.get("publishTime") if publish_time: publish_time = dateparser.parse(msg.get("publishTime")) if not max_publish_time: max_publish_time = publish_time else: max_publish_time = max(max_publish_time, publish_time) if max_publish_time: max_publish_time = convert_datetime_to_iso_str(max_publish_time) return msg_ids, max_publish_time
Example 24
Source File: EWSO365.py From content with MIT License | 6 votes |
def get_limited_number_of_messages_from_qs(qs, limit): """ Retrieve a limited number of messages from query search :param qs: query search to execute :param limit: limit on number of items to retrieve from search :return: list of exchangelib.Message """ count = 0 results = [] for item in qs: if count == limit: break if isinstance(item, Message): count += 1 results.append(item) return results
Example 25
Source File: symbol_database.py From botchallenge with MIT License | 6 votes |
def GetMessages(self, files): """Gets all the messages from a specified file. This will find and resolve dependencies, failing if they are not registered in the symbol database. Args: files: The file names to extract messages from. Returns: A dictionary mapping proto names to the message classes. This will include any dependent messages as well as any messages defined in the same file as a specified message. Raises: KeyError: if a file could not be found. """ result = {} for f in files: result.update(self._symbols_by_file[f]) return result
Example 26
Source File: cron_executor.py From reliable-task-scheduling-compute-engine-sample with Apache License 2.0 | 6 votes |
def get_messages(self): # You can fetch multiple messages with a single API call. batch_size = 1 # Create a POST body for the Pub/Sub request body = { # Setting ReturnImmediately to false instructs the API to wait # to collect the message up to the size of MaxEvents, or until # the timeout (approx 90s) 'returnImmediately': False, 'maxMessages': batch_size, } log.debug("pulling messages") resp = self.client.projects().subscriptions().pull( subscription=self.sub['name'], body=body).execute() if 'receivedMessages' in resp: log.debug("number msgs: %s" % len(resp.get('receivedMessages'))) self.lease_start = datetime.now() return resp.get('receivedMessages') else: return []
Example 27
Source File: helpers.py From annotated-py-projects with MIT License | 6 votes |
def get_flashed_messages(with_categories=False): """从 session 中拉取消息, 并返回. - 同一个请求, 调用本方法, 会返回相同的消息. - 默认方式, 只是直接返回 所有的消息. - with_categories参数有效时, 返回一个 元素为元组(category, message)的列表 Example usage: .. sourcecode:: html+jinja (模板文件示例) {% for category, msg in get_flashed_messages(with_categories=true) %} <p class=flash-{{ category }}>{{ msg }} {% endfor %} :param with_categories: set to `True` to also receive categories. """ flashes = _request_ctx_stack.top.flashes if flashes is None: _request_ctx_stack.top.flashes = flashes = session.pop('_flashes', []) if not with_categories: return [x[1] for x in flashes] return flashes
Example 28
Source File: structure_tools.py From message-analyser with MIT License | 6 votes |
def get_messages_per_timedelta(msgs, time_bin): """Gets lists of messages for each time interval with a given length. For example: time_bin is 7, so we will get lists of messages for each week between the first and last messages. Args: msgs (list of MyMessage objects): Messages. time_bin (int): The number of days in each bin (time interval). Returns: A dictionary such as: { day (datetime.date object): a list of messages within interval [day, day + time_bin) } """ start_d = msgs[0].date.date() current_date = start_d end_d = msgs[-1].date.date() res = dict() while current_date <= end_d: res[current_date] = [] current_date += relativedelta(days=time_bin) for msg in msgs: res[start_d + relativedelta(days=(msg.date.date() - start_d).days // time_bin * time_bin)].append(msg) return res
Example 29
Source File: structure_tools.py From message-analyser with MIT License | 6 votes |
def get_messages_per_minutes(msgs, minutes): """Gets lists of messages for each interval in minutes. Args: msgs (list of MyMessage objects): Messages. minutes (int): The number of minutes in one interval. Returns: A dictionary such as: { minute: list off all messages sent within interval [minute, minute + minutes). } """ res = {i: [] for i in range(0, 24 * 60, minutes)} for msg in msgs: res[(msg.date.hour * 60 + msg.date.minute) // minutes * minutes].append(msg) return res
Example 30
Source File: structure_tools.py From message-analyser with MIT License | 6 votes |
def get_messages_per_month(msgs): """Gets lists of messages for each month between the first and last message. Notes: Months keys are set to the first day of the month. Args: msgs (list of Mymessage objects): Messages. Returns: A dictionary such as: { month (datetime.date): list of messages within this month } """ res = dict() current_date = msgs[0].date.date().replace(day=1) end_d = msgs[-1].date.date().replace(day=1) while current_date <= end_d: res[current_date] = [] current_date += relativedelta(months=1) for msg in msgs: res[msg.date.date().replace(day=1)].append(msg) return res
Example 31
Source File: structure_tools.py From message-analyser with MIT License | 6 votes |
def get_messages_per_weekday(msgs): """Gets lists of messages for each day of the week (7 lists in a dictionary total). Args: msgs (list of MyMessage objects): Messages. Returns: A dictionary such as: { day_of_the_week (int 0-6): list off all messages sent on this day } """ res = {0: [], 1: [], 2: [], 3: [], 4: [], 5: [], 6: []} for msg in msgs: res[msg.date.weekday()].append(msg) # placing Sunday at the end of the week # turned out we don't need it... # for i in [0, 1, 2, 3, 4, 5]: # res[i], res[(i + 6) % 7] = res[(i + 6) % 7], res[i] return res
Example 32
Source File: structure_tools.py From message-analyser with MIT License | 6 votes |
def get_messages_per_week(msgs): """Gets lists of messages for each calendar week between the first and the last message. Args: msgs (list of Mymessage objects): Messages. Returns: A dictionary such as: { week (datetime.date): list of messages within this week } """ res = dict() current_date = msgs[0].date.date() end_d = msgs[-1].date.date() if current_date.weekday() != 0: current_date -= relativedelta(days=current_date.weekday()) while current_date <= end_d: res[current_date] = [] current_date += relativedelta(days=7) for msg in msgs: res[msg.date.date() - relativedelta(days=msg.date.date().weekday())].append(msg) return res
Example 33
Source File: structure_tools.py From message-analyser with MIT License | 6 votes |
def get_messages_per_day(msgs): """Gets lists of messages for each day between the first and the last message. Notes: Days are stored in a dictionary as integers (first day is 0, second is 1 etc). Args: msgs (list of MyMessage objects): Messages. Returns: A dictionary such as: { day (int): list of messages sent this day } """ current_date = msgs[0].date.date() end_d = msgs[-1].date.date() res = dict() one_day = relativedelta(days=1) while current_date <= end_d: res[current_date] = [] current_date += one_day for msg in msgs: res[msg.date.date()].append(msg) return res
Example 34
Source File: Wc.py From NotSoBot with MIT License | 6 votes |
def get_messages(self, channel, limit, user=None): msgs = None if channel in self.message_cache.keys(): msgs = self.message_cache[channel] if len(msgs) >= limit: msgs = msgs[:limit] else: before = msgs[-1] limit = limit-len(msgs) else: self.message_cache[channel] = [] before = None if not msgs: async for message in self.bot.logs_from(channel, limit=limit, before=before): self.message_cache[channel].append(message.content) msgs = self.message_cache[channel] if not len(msgs): return ['no messages found rip'] final = [] for msg in msgs: final.extend([*msg.split()]) return final
Example 35
Source File: structure_tools.py From message-analyser with MIT License | 6 votes |
def get_messages_per_hour(msgs): """Gets lists of messages for each hour of the day (total 24 lists). Args: msgs (list of MyMessage objects): Messages. Returns: A dictionary such as: { hour (string "%H:00"): list of messages sent this hour (for all days) } """ res = {hour: [] for hour in get_hours()} for msg in msgs: res[f"{msg.date.hour:02d}:00"].append(msg) return res
Example 36
Source File: channel_service_stub.py From python-compat-runtime with Apache License 2.0 | 6 votes |
def get_channel_messages(self, token): """Returns the pending messages for a given channel. Args: token: A string representing the channel. Note that this is the token returned by CreateChannel, not the client id. Returns: List of messages, or None if the channel doesn't exist. The messages are strings. """ self._log('Received request for messages for channel: ' + token) client_id = self.client_id_from_token(token) if client_id in self._connected_channel_messages: return self._connected_channel_messages[client_id] return None
Example 37
Source File: message_handlers.py From chat with Apache License 2.0 | 6 votes |
def get_messages(conversation_id, limit, before_time=None, before_message_id=None, after_time=None, after_message_id=None, order=None): if not Conversation.exists(conversation_id): raise ConversationNotFoundException() # use message id if given message id as the range condition, # otherwise use time as range condition # # thus if neither message id or time is given, this will return the # latest messages if before_message_id or after_message_id: if before_time or after_time: raise InvalidGetMessagesConditionArgumentException() return get_messages_by_message(conversation_id, limit, before_message_id, after_message_id, order) else: return get_messages_by_time(conversation_id, limit, before_time, after_time, order)
Example 38
Source File: basicmessage.py From indy-agent with Apache License 2.0 | 6 votes |
def get_messages(self, msg: Message) -> None: """ UI activated method requesting a list of messages exchanged with a given agent. :param msg: Message from the UI to get a list of message exchanged with a given DID: { '@type': AdminBasicMessage.GET_MESSAGES, 'with': 'CzznW3pTbFr2YqDCGWWf8x', # DID of other party with whom messages # have been exchanged } :return: None """ their_did = msg['with'] messages = await get_wallet_records(self.agent.wallet_handle, 'basicmessage', json.dumps({'their_did': their_did})) messages = sorted(messages, key=lambda n: n['sent_time'], reverse=True) await self.agent.send_admin_message( Message({ '@type': AdminBasicMessage.MESSAGES, 'with': their_did, 'messages': messages }) )
Example 39
Source File: cache.py From RPiNWR with GNU General Public License v3.0 | 6 votes |
def get_active_messages(self, when=None, event_pattern=None, here=True): """ :param when: the time for which to check effectiveness of the messages, default = the present time :param event_pattern: a regular expression to match the desired event codes. default = all. :param here: True to retrieve local messages, False to retrieve those for other locales """ if when is None: when = time.time() if event_pattern is None: event_pattern = re.compile(".*") elif not hasattr(event_pattern, 'match'): event_pattern = re.compile(event_pattern) l = list(filter(lambda m: m.is_effective(self.latlon, self.county_fips, here, when) and event_pattern.match( m.get_event_type()), self.__messages.values())) l.sort(key=functools.cmp_to_key(self.sorter)) return l
Example 40
Source File: _client6.py From python-libjuju with Apache License 2.0 | 6 votes |
def GetUpgradeSeriesMessages(self, params=None): ''' params : typing.Sequence[~UpgradeSeriesNotificationParam] Returns -> StringsResults ''' if params is not None and not isinstance(params, (bytes, str, list)): raise Exception("Expected params to be a Sequence, received: {}".format(type(params))) # map input types to rpc msg _params = dict() msg = dict(type='MachineManager', request='GetUpgradeSeriesMessages', version=6, params=_params) _params['params'] = params reply = await self.rpc(msg) return reply
Example 41
Source File: _client8.py From python-libjuju with Apache License 2.0 | 6 votes |
def GetLXDProfileUpgradeMessages(self, application=None, watcher_id=None): ''' application : Entity watcher_id : str Returns -> LXDProfileUpgradeMessagesResults ''' if application is not None and not isinstance(application, (dict, Entity)): raise Exception("Expected application to be a Entity, received: {}".format(type(application))) if watcher_id is not None and not isinstance(watcher_id, (bytes, str)): raise Exception("Expected watcher_id to be a str, received: {}".format(type(watcher_id))) # map input types to rpc msg _params = dict() msg = dict(type='Application', request='GetLXDProfileUpgradeMessages', version=8, params=_params) _params['application'] = application _params['watcher-id'] = watcher_id reply = await self.rpc(msg) return reply
Example 42
Source File: __init__.py From WebWhatsapp-Wrapper with MIT License | 6 votes |
def get_all_messages_in_chat( self, chat, include_me=False, include_notifications=False ): """ Fetches messages in chat :param include_me: Include user's messages :type include_me: bool or None :param include_notifications: Include events happening on chat :type include_notifications: bool or None :return: List of messages in chat :rtype: list[Message] """ message_objs = self.wapi_functions.getAllMessagesInChat( chat.id, include_me, include_notifications ) for message in message_objs: yield (factory_message(message, self))
Example 43
Source File: webapi.py From WebWhatsapp-Wrapper with MIT License | 6 votes |
def get_messages(chat_id): """Return all of the chat messages""" mark_seen = request.args.get("mark_seen", True) chat = g.driver.get_chat_from_id(chat_id) msgs = list(g.driver.get_all_messages_in_chat(chat)) for msg in msgs: print(msg.id) if mark_seen: for msg in msgs: try: msg.chat.send_seen() except: pass return jsonify(msgs)
Example 44
Source File: chat.py From WebWhatsapp-Wrapper with MIT License | 6 votes |
def get_unread_messages(self, include_me=False, include_notifications=False): """ I fetch unread messages. :param include_me: if user's messages are to be included :type include_me: bool :param include_notifications: if events happening on chat are to be included :type include_notifications: bool :return: list of unread messages :rtype: list """ return list( self.driver.get_unread_messages_in_chat( self.id, include_me, include_notifications ) ) # get_unread_messages()
Example 45
Source File: svc_usb.py From photoframe with GNU General Public License v3.0 | 6 votes |
def getMessages(self): # display a message indicating which storage device is being used or an error messing if no suitable storage device could be found if self.device and os.path.exists(self.baseDir): msgs = [ { 'level': 'SUCCESS', 'message': 'Storage device "%s" is connected' % self.device.getName(), 'link': None } ] msgs.extend(BaseService.getMessages(self)) else: msgs = [ { 'level': 'ERROR', 'message': 'No storage device could be found that contains the "/photoframe/"-directory! Try to reboot or manually mount the desired storage device to "%s"' % self.usbDir, 'link': None } ] return msgs
Example 46
Source File: mbox.py From prospector with GNU General Public License v3.0 | 6 votes |
def get_messages(self): """ Iterate through all messages in self.mbox_file """ messages = self.backend.fetch() for message in messages: data = message['data'] try: msg = Message(data['From'], data['Date'], data['Subject'], data['Message-ID'], data['References']) except: logger.warning('Malformed message found, skipping:\n%s', message['updated_on'], exc_info=True) msg = None # yield outside the try block to avoid capturing exceptions # that should terminate the loop instead if msg is not None: yield msg
Example 47
Source File: lambda_function.py From amazon-textract-serverless-large-scale-document-processing with Apache License 2.0 | 6 votes |
def getMessagesFromQueue(sqs, qUrl,): # Receive message from SQS queue response = sqs.receive_message( QueueUrl=qUrl, MaxNumberOfMessages=1, VisibilityTimeout=60 #14400 ) print('SQS Response Recieved:') print(response) if('Messages' in response): return response['Messages'] else: print("No messages in queue.") return None
Example 48
Source File: email_mirror.py From zulip with Apache License 2.0 | 6 votes |
def get_imap_messages() -> Generator[EmailMessage, None, None]: mbox = IMAP4_SSL(settings.EMAIL_GATEWAY_IMAP_SERVER, settings.EMAIL_GATEWAY_IMAP_PORT) mbox.login(settings.EMAIL_GATEWAY_LOGIN, settings.EMAIL_GATEWAY_PASSWORD) try: mbox.select(settings.EMAIL_GATEWAY_IMAP_FOLDER) try: status, num_ids_data = mbox.search(None, 'ALL') for message_id in num_ids_data[0].split(): status, msg_data = mbox.fetch(message_id, '(RFC822)') assert isinstance(msg_data[0], tuple) msg_as_bytes = msg_data[0][1] message = email.message_from_bytes(msg_as_bytes, policy=email.policy.default) assert isinstance(message, EmailMessage) # https://github.com/python/typeshed/issues/2417 yield message mbox.store(message_id, '+FLAGS', '\\Deleted') mbox.expunge() finally: mbox.close() finally: mbox.logout()
Example 49
Source File: python_examples.py From zulip with Apache License 2.0 | 6 votes |
def get_messages(client: Client) -> None: # {code_example|start} # Get the 100 last messages sent by "iago@zulip.com" to the stream "Verona" request: Dict[str, Any] = { 'anchor': 'newest', 'num_before': 100, 'num_after': 0, 'narrow': [{'operator': 'sender', 'operand': 'iago@zulip.com'}, {'operator': 'stream', 'operand': 'Verona'}], } result = client.get_messages(request) # {code_example|end} validate_against_openapi_schema(result, '/messages', 'get', '200') assert len(result['messages']) <= request['num_before']
Example 50
Source File: imap.py From imapfw with MIT License | 6 votes |
def getMessages(self, messages: Messages, attributes: FetchAttributes) -> Messages: self._debug("getMessages", repr(messages)) # (typ, [data, ...]) # e.g. ('OK', [b'1 (UID 1 FLAGS (\\Seen) INTERNALDATE "15-Nov-2015 # 00:00:46 +0100")', b'2 (UID 2 FLAGS () INTERNALDATE "15-Nov-2015 # 00:00:46 +0100")']) response = self.imap.uid('FETCH', messages.coalesceUIDs(), str(attributes)) self._debugResponse("getMessages", response) status, data = response if status == 'OK': for item in data: item = item.decode(ENCODING) uid = int(item[0]) #TODO: item must be of type MessageAttributes. messages.setAttributes(uid, item) return messages raise ImapCommandError(data)
Example 51
Source File: datastore.py From OpenBazaar-Server with MIT License | 6 votes |
def get_messages(self, guid, message_type, msgID=None, limit=20): """ Return all messages matching guid and message_type. """ if msgID == None: timestamp = 4294967295 else: timestamp = self.get_timestamp(msgID) conn = Database.connect_database(self.PATH) cursor = conn.cursor() cursor.execute('''SELECT guid, handle, pubkey, subject, messageType, message, timestamp, avatarHash, signature, outgoing, read, msgID FROM messages WHERE guid=? AND messageType=? AND timestamp<? ORDER BY timestamp DESC LIMIT 20''', (guid, message_type, timestamp)) ret = cursor.fetchall() conn.close() return ret
Example 52
Source File: restapi.py From OpenBazaar-Server with MIT License | 6 votes |
def get_chat_messages(self, request): start = request.args["start"][0] if "start" in request.args else None messages = self.db.messages.get_messages(request.args["guid"][0], "CHAT", start) message_list = [] for m in messages[::-1]: message_json = { "id": m[11], "guid": m[0], "handle": m[1], "message": m[5], "timestamp": m[6], "avatar_hash": m[7].encode("hex"), "outgoing": False if m[9] == 0 else True, "read": False if m[10] == 0 else True } message_list.append(message_json) request.setHeader('content-type', "application/json") request.write(json.dumps(sanitize_html(message_list), indent=4)) request.finish() return server.NOT_DONE_YET
Example 53
Source File: slack.py From securitybot with Apache License 2.0 | 6 votes |
def get_messages(self): # type () -> List[Dict[str, Any]] ''' Gets a list of all new messages received by the bot in direct messaging channels. That is, this function ignores all messages posted in group chats as the bot never interacts with those. Each message should have the following format, minimally: { "user": The unique ID of the user who sent a message. "text": The text of the received message. } ''' events = self._slack.rtm_read() messages = [e for e in events if e['type'] == 'message'] return [m for m in messages if 'user' in m and m['channel'].startswith('D')]
Example 54
Source File: __init__.py From rapidpro-python with BSD 3-Clause "New" or "Revised" License | 6 votes |
def get_messages(self, id=None, broadcast=None, contact=None, folder=None, label=None, before=None, after=None): """ Gets all matching messages :param id: message id :param broadcast: broadcast id :param contact: contact object or UUID :param folder: folder name :param label: message label name or UUID :param datetime before: created before :param datetime after: created after :return: message query """ params = self._build_params( id=id, broadcast=broadcast, contact=contact, folder=folder, label=label, before=before, after=after ) return self._get_query("messages", params, Message)
Example 55
Source File: ch08_listing_source.py From https---github.com-josiahcarlson-redis-in-action with MIT License | 6 votes |
def get_status_messages(conn, uid, timeline='home:', page=1, count=30):#A statuses = conn.zrevrange( #B '%s%s'%(timeline, uid), (page-1)*count, page*count-1) #B pipeline = conn.pipeline(True) for id in statuses: #C pipeline.hgetall('status:%s'%id) #C return filter(None, pipeline.execute()) #D # <end id="fetch-page"/> #A We will take an optional 'timeline' argument, as well as page size and status message counts #B Fetch the most recent status ids in the timeline #C Actually fetch the status messages themselves #D Filter will remove any 'missing' status messages that had been previously deleted #END # <start id="follow-user"/>
Example 56
Source File: run.py From fb-page-chat-download with GNU Affero General Public License v3.0 | 6 votes |
def get_messages(self, t): extra_params = (('&since=' + str(self.since)) if self.since else '') + (('&until=' + str(self.until)) if self.until else '') url = self.build_url('{}/messages?fields=from,created_time,message,shares,attachments&limit=400' + extra_params, t['id']) thread = self.scrape_thread(url, []) if thread: print( thread[0]['time'], t['id'].ljust(20), str(len(thread)).rjust(3) + ' from', unidecode.unidecode(t['participants']['data'][0]['name']) ) id_map = {p['id']: p['name'] for p in t['participants']['data']} for message in thread: message['from'] = id_map[message['from_id']] return [{ # 'page_id': t['participants']['data'][1]['id'], # 'page_name': t['participants']['data'][1]['name'], # 'user_id': t['participants']['data'][0]['id'], # 'user_name': t['participants']['data'][0]['name'], 'url': t['link'], }] + list(reversed(thread)) return []