Handle messages from browser.
553030
def on_websocket_message(message: str) -> None:
    """"""
    msgs = json.loads(message)
    for msg in msgs:
        if not isinstance(msg, dict):
            logger.error('Invalid WS message format: {}'.format(message))
            continue
        _type = msg.get('type')
        if _type == 'log':
            log_handler(msg['level'], msg['message'])
        elif _type == 'event':
            event_handler(msg['event'])
        elif _type == 'response':
            response_handler(msg)
        else:
            raise ValueError('Unkown message type: {}'.format(message))
558603
def handle_msg(self, c, e):
        """"""

        if e.type not in ['authenticate', 'error', 'join', 'part', 'quit']:
            nick = e.source.nick
        else:
            nick = e.source

        if e.arguments is None:
            msg = ""
        else:
            msg = " ".join(e.arguments).strip()

        # Send the response to private messages to the sending nick.
        target = nick if e.type == 'privmsg' else e.target

        def send(msg, mtype='privmsg', target=target, ignore_length=False):
            self.send(target, self.connection.real_nickname, msg, mtype, ignore_length)

        if e.type in [
                'account', 'authenticate', 'bannedfromchan', 'cap', 'ctcpreply', 'error', 'featurelist', 'nosuchnick', 'nick', 'nicknameinuse',
                'privnotice', 'welcome', 'whospcrpl'
        ]:
            self.handle_event(msg, send, c, e)
            return

        # ignore empty messages
        if not msg and e.type != 'join':
            return

        self.do_log(target, nick, msg, e.type)

        if e.type == 'mode':
            self.do_mode(target, msg, nick, send)
            return

        if e.type == 'join':
            self.handle_join(c, e, target, send)
            return

        if e.type == 'part':
            if nick == c.real_nickname:
                send("Parted channel %s" % target, target=self.config['core']['ctrlchan'])
            return

        if e.type == 'kick':
            self.handle_kick(c, e, target, send)
            return

        if e.target == self.config['core']['ctrlchan'] and self.is_admin(None, nick):
            control.handle_ctrlchan(self, msg, nick, send)

        if self.is_ignored(nick) and not self.is_admin(None, nick):
            return

        self.handle_hooks(send, nick, target, e, msg)

        # We only process hooks for notices, not commands.
        if e.type == 'pubnotice':
            return

        msg = misc.get_cmdchar(self.config, c, msg, e.type)
        cmd_name, cmdargs = self.get_cmd(msg)

        if registry.command_registry.is_registered(cmd_name):
            self.run_cmd(send, nick, target, cmd_name, cmdargs, e)
        # special commands
        elif cmd_name == 'reload':
            with self.db.session_scope() as session:
                if session.query(orm.Permissions).filter(orm.Permissions.nick == nick).count():
                    send("Aye Aye Capt'n")
1032814
def send_message(message, params, site, logger):
    """"""
    client.capture(
        'Message',
        message=message,
        params=tuple(params),
        data={
            'site': site,
            'logger': logger,
        },
    )
591591
def listen():
        """"""
        msg = MSG()
        ctypes.windll.user32.GetMessageA(ctypes.byref(msg), 0, 0, 0)
385349
def handleStatus(self, version, status, message):
        """"""

        self.status = status
        self.message = message
1043230
def handle_message(message)
      begin
        message = decode_message message
      rescue InvalidMessageError => ex
        Logger.crash("couldn't decode message", ex)
        return
      end

      begin
        message.dispatch
      rescue => ex
        Logger.crash("message dispatch failed", ex)
      end
    end
483466
function handle(msg) {
  log.debug('handling msg', msg)
  var to = msg.to,
    intent = msg.intent;
  if (to && intent) {
    var reply;
    // try JSON or JSON.input as input
    try {
      reply = _.get(lib_js[to], intent)(msg)
    } catch (err) {
      try {
        reply = _.get(lib_js[to], intent)(msg.input)
      } catch (deepErr) {
        log.debug('js handle fails.', deepErr)
      }
    } finally {
      // try JSON or made-JSON output
      reply = correctReply(reply, msg)
      log.debug('reply', reply)
      if (reply.to) {
        client.emit('pass', reply)
      }
    }
  }
}
961559
async function handleMessagePing(state, msgObj) {

    /**
     * when there are no listener, we do nothing
     */
    if (!state.messagesCallback) return;

    let messages;
    if (!msgObj) {
        // get all
        messages = await getAllMessages(state.channelName, state.paths);
    } else {
        // get single message
        messages = [
            getSingleMessage(state.channelName, msgObj, state.paths)
        ];
    }

    const useMessages = messages
        .filter(msgObj => _filterMessage(msgObj, state))
        .sort((msgObjA, msgObjB) => msgObjA.time - msgObjB.time); // sort by time


    // if no listener or message, so not do anything
    if (!useMessages.length || !state.messagesCallback) return;

    // read contents
    await Promise.all(
        useMessages
        .map(
            msgObj => readMessage(msgObj).then(content => msgObj.content = content)
        )
    );

    useMessages.forEach(msgObj => {
        state.emittedMessagesIds.add(msgObj.token);

        if (state.messagesCallback) {
            // emit to subscribers
            state.messagesCallback(msgObj.content.data);
        }
    });
}
249881
def handle(self, msg):
        """"""
        debug_msg = ': {!r}'.format(msg) if self.debug else ''
        log.debug('request: %d bytes%s', len(msg), debug_msg)
        buf = io.BytesIO(msg)
        code, = util.recv(buf, '>B')
        if code not in self.methods:
            log.warning('Unsupported command: %s (%d)', msg_name(code), code)
            return failure()

        method = self.methods[code]
        log.debug('calling %s()', method.__name__)
        reply = method(buf=buf)
        debug_reply = ': {!r}'.format(reply) if self.debug else ''
        log.debug('reply: %d bytes%s', len(reply), debug_reply)
        return reply
441952
async def handler(event):
    """"""
    query = urllib.parse.quote(event.pattern_match.group(1))
    await asyncio.wait([
        event.delete(),
        event.respond(SEARCH.format(query), reply_to=event.reply_to_msg_id)
    ])
23103
async def handler(self):
    ''''''
    self.ws = await websockets.connect(self.url, ssl=self.ssl)
    while self.ws:
      message = await self.ws.recv()
      for handle in self.on_message:
        if asyncio.iscoroutinefunction(handle):
          await handle(self, message)
        else:
          handle(self, message)
1351300
def handle_data(self, data):
        """"""
        # Only process the data when we are in an active a tag and have an URL.
        if not self.active_url:
            return

        # The visible text can have a final slash so strip it off
        if data.strip('/') == self.active_url:
            self.entries.append(self.active_url)
1119012
def help(self, message, plugin=None):
        """"""
        # help_data = self.load("help_files")
        selected_modules = help_modules = self.load("help_modules")

        self.say("Sure thing, %s." % message.sender.handle)

        help_text = "Here's what I know how to do:"
        if plugin and plugin in help_modules:
            help_text = "Here's what I know how to do about %s:" % plugin
            selected_modules = dict()
            selected_modules[plugin] = help_modules[plugin]

        for k in sorted(selected_modules, key=lambda x: x[0]):
            help_data = selected_modules[k]
            if help_data:
                help_text += "<br/><br/><b>%s</b>:" % k
                for line in help_data:
                    if line:
                        if ":" in line:
                            line = "&nbsp; <b>%s</b>%s" % (line[:line.find(":")], line[line.find(":"):])
                        help_text += "<br/> %s" % line

        self.say(help_text, html=True)
163387
def handle_message(self, msg):
        
        self._messages.append({
            'type': msg.category,
            'module': msg.module,
            'obj': msg.obj,
            'line': msg.line,
            'column': msg.column,
            'path': msg.path,
            'symbol': msg.symbol,
            'message': str(msg.msg) or '',
            'message-id': msg.msg_id,
        })
391055
def on_message(self, event):
        '''
        '''

        metadata = self._parse_metadata(event)
        message = Message(text=metadata['text'],
                          metadata=metadata).__dict__
        if message.get('text'):
            message['text'] = self.find_and_replace_userids(message['text'])
            message['text'] = self.find_and_replace_channel_refs(
                message['text']
            )
        return message
641049
def handle(self, message):
        '''
        '''

        logger.debug(message)
        if Utilities.isNotEmpty(message['metadata']['opts']):
            target = message['metadata']['opts']['target']
            thread = message['metadata']['opts'].get('thread')
            # pattern = re.compile('@([a-zA-Z0-9._-]+)')
            pattern = re.compile('^@([a-zA-Z0-9._-]+)|\s@([a-zA-Z0-9._-]+)')
            matches = re.findall(pattern, message['text'])
            matches = set(matches)
            logger.debug('MATCHES!!!!   {}'.format(matches))
            for match in matches:
                if isinstance(match, tuple):
                    if match[0] != '':
                        match = match[0]
                    else:
                        match = match[1]
                if not match.startswith('@'):
                    match = '@' + match
                message['text'] = message['text'].replace(
                    match,
                    '<{}>'.format(match)
                )

            pattern = re.compile('#([A-Za-z0-9-]+)')
            matches = re.findall(pattern, message['text'])
            matches = set(matches)
            for match in matches:
                channel_id = self.botThread.get_channel_id_by_name(match)
                if channel_id:
                    message['text'] = message['text'].replace(
                        '#' + match,
                        '<#{}|{}>'.format(
                            channel_id,
                            match
                        )
                    )

            if (message['text'].find('<<@') != -1
                    or message['text'].find('<<#') != -1):
                message['text'] = message['text'].replace('<<', '<')
                message['text'] = message['text'].replace('>>', '>')

            if target.startswith('U'):
                target = self.botThread.get_dm_channel(target)
            attachment = message['metadata']['opts'].get('attachment')
            if attachment:
                text = message['metadata']['opts'].get('fallback')
                attachment = self.build_attachment(
                    text, target, attachment, thread)
                self.botThread.post_attachment(attachment)
            else:
                self.botThread.slack_client.rtm_send_message(
                    target, message['text'], thread=thread)
740420
def on_message(self, message):
        """"""
        json_rpc = json.loads(message)
        logging.log(logging.DEBUG, json_rpc)

        if self.pool is None:
            self.pool = multiprocessing.Pool(processes=args.workers)

        # Spawn a process to protect the server against segfaults
        async = self.pool.apply_async(_worker_process, [json_rpc])
        try:
            result = async.get(timeout=args.timeout)
            error = 0
        except multiprocessing.TimeoutError:
            result = ("File format conversion timed out! This is due "
                      "either to a large input file or a segmentation "
                      "fault in the underlying open babel library.")
            error = 1
            self.pool.terminate()
            self.pool = multiprocessing.Pool(processes=args.workers)
        except Exception:
            result = traceback.format_exc()
            error = 1
        logging.log(logging.DEBUG, result)

        self.write_message(json.dumps({'result': result, 'error': error,
                                       'id': json_rpc['id']},
                                      separators=(',', ':')))