handle a message and return an gif
2110
def on_message(msg, server):
    """"""
    text = msg.get("text", "")
    match = re.findall(r"!gif (.*)", text)
    if not match:
        return

    res = gif(match[0])
    if not res:
        return

    attachment = {
        "fallback": match[0],
        "title": match[0],
        "title_link": res,
        "image_url": res
    }
    server.slack.post_message(
        msg['channel'],
        '',
        as_user=server.slack.username,
        attachments=json.dumps([attachment]))
555674
function handleEvent(event) {
  if (event.replyToken && event.replyToken.match(/^(.)\1*$/)) {
    return console.log("Test hook recieved: " + JSON.stringify(event.message));
  }

  switch (event.type) {
    case 'message':
      const message = event.message;
      switch (message.type) {
        case 'text':
          return handleText(message, event.replyToken, event.source);
        case 'image':
          return handleImage(message, event.replyToken);
        case 'video':
          return handleVideo(message, event.replyToken);
        case 'audio':
          return handleAudio(message, event.replyToken);
        case 'location':
          return handleLocation(message, event.replyToken);
        case 'sticker':
          return handleSticker(message, event.replyToken);
        default:
          throw new Error(`Unknown message: ${JSON.stringify(message)}`);
      }

    case 'follow':
      return replyText(event.replyToken, 'Got followed event');

    case 'unfollow':
      return console.log(`Unfollowed this bot: ${JSON.stringify(event)}`);

    case 'join':
      return replyText(event.replyToken, `Joined ${event.source.type}`);

    case 'leave':
      return console.log(`Left: ${JSON.stringify(event)}`);

    case 'postback':
      let data = event.postback.data;
      if (data === 'DATE' || data === 'TIME' || data === 'DATETIME') {
        data += `(${JSON.stringify(event.postback.params)})`;
      }
      return replyText(event.replyToken, `Got postback: ${data}`);

    case 'beacon':
      return replyText(event.replyToken, `Got beacon: ${event.beacon.hwid}`);

    default:
      throw new Error(`Unknown event: ${JSON.stringify(event)}`);
  }
}
1360875
async def on_message(message):
    

    # Simplify message info
    server = message.server
    author = message.author
    channel = message.channel
    content = message.content

    data = datatools.get_data()

    if not data["discord"]["servers"][server.id][_data.modulename]["activated"]:
        return

    # Only reply to server messages and don't reply to myself
    if server is not None and author != channel.server.me:
        # Commands section
        prefix = data["discord"]["servers"][server.id]["prefix"]
        if content.startswith(prefix):
            # Parse message
            package = content.split(" ")
            command = package[0][len(prefix):]
            args = package[1:]
            arg = ' '.join(args)

            # Commands
            if command == 'hex':
                await client.send_typing(channel)

                # Parse message
                hex_strs = api_hexconvert.convert_hex_value(arg)
                # Create embed UI
                if len(hex_strs) > 0:
                    for hex_str in hex_strs:
                        image_url = convert_hex_to_url(hex_str)
                        embed = ui_embed.success(channel, image_url, hex_str)
                        await embed.send()
                else:
                    embed = ui_embed.fail_api(channel)
                    await embed.send()
        else:
            # Parse message
            hex_strs = api_hexconvert.convert_hex_value(content)
            # Create embed UI
            if len(hex_strs) > 0:
                for hex_str in hex_strs:
                    await client.send_typing(channel)
                    image_url = convert_hex_to_url(hex_str)
                    embed = ui_embed.success(channel, image_url, hex_str)
                    await embed.send()
1179592
def handle_message(self, data):
        
        msg = json.loads(data)
        print("Dev server message: {}".format(msg))
        handler_name = 'do_{}'.format(msg['type'])
        if hasattr(self, handler_name):
            handler = getattr(self, handler_name)
            result = handler(msg)
            return {'ok': True, 'result': result}
        else:
            err = "Warning: Unhandled message: {}".format(msg)
            print(err)
            return {'ok': False, 'message': err}
365556
def process_message(self,msg,sock):
    ""
    command=msg[0]
    try: f={'GET':self.get,'SET':self.set,'SUBSCRIBE':self.sub,'PUBLISH':self.pub,
      'PING':self.ping,'GETSET':self.getset,'EXPIRE':self.expire,'DEL':self.delete}[command]
    except KeyError: print msg; raise
    args=msg[1:]
    try: return f(sock,*args) if command in self.SOCK_COMMANDS else f(*args)
    except Exception as e:
      print e
      print msg
      return '-ERROR\r\n'
130892
function Message(options, body) {
  Stream.call(this);

  if (options || body)
    this.bind(options, body);

}
666827
def handle_message(self, stream, header, payload):
        '''
        
        '''
        try:
            try:
                payload = self._decode_payload(payload)
            except Exception:
                stream.write(salt.transport.frame.frame_msg('bad load', header=header))
                raise tornado.gen.Return()

            # TODO helper functions to normalize payload?
            if not isinstance(payload, dict) or not isinstance(payload.get('load'), dict):
                yield stream.write(salt.transport.frame.frame_msg(
                    'payload and load must be a dict', header=header))
                raise tornado.gen.Return()

            try:
                id_ = payload['load'].get('id', '')
                if str('\0') in id_:
                    log.error('Payload contains an id with a null byte: %s', payload)
                    stream.send(self.serial.dumps('bad load: id contains a null byte'))
                    raise tornado.gen.Return()
            except TypeError:
                log.error('Payload contains non-string id: %s', payload)
                stream.send(self.serial.dumps('bad load: id {0} is not a string'.format(id_)))
                raise tornado.gen.Return()

            # intercept the "_auth" commands, since the main daemon shouldn't know
            # anything about our key auth
            if payload['enc'] == 'clear' and payload.get('load', {}).get('cmd') == '_auth':
                yield stream.write(salt.transport.frame.frame_msg(
                    self._auth(payload['load']), header=header))
                raise tornado.gen.Return()

            # TODO: test
            try:
                ret, req_opts = yield self.payload_handler(payload)
            except Exception as e:
                # always attempt to return an error to the minion
                stream.write('Some exception handling minion payload')
                log.error('Some exception handling a payload from minion', exc_info=True)
                stream.close()
                raise tornado.gen.Return()

            req_fun = req_opts.get('fun', 'send')
            if req_fun == 'send_clear':
                stream.write(salt.transport.frame.frame_msg(ret, header=header))
            elif req_fun == 'send':
                stream.write(salt.transport.frame.frame_msg(self.crypticle.dumps(ret), header=header))
            elif req_fun == 'send_private':
                stream.write(salt.transport.frame.frame_msg(self._encrypt_private(ret,
                                                             req_opts['key'],
                                                             req_opts['tgt'],
                                                             ), header=header))
            else:
                log.error('Unknown req_fun %s', req_fun)
                # always attempt to return an error to the minion
                stream.write('Server-side exception handling payload')
                stream.close()
        except tornado.gen.Return:
            raise
        except StreamClosedError:
            # Stream was closed. This could happen if the remote side
            # closed the connection on its end (eg in a timeout or shutdown
            # situation).
            log.error('Connection was unexpectedly closed', exc_info=True)
        except Exception as exc:  # pylint: disable=broad-except
            # Absorb any other exceptions
            log.error('Unexpected exception occurred: %s', exc, exc_info=True)

        raise tornado.gen.Return()
1294770
def handle_request(self, msgtype, msgid, method, args, kwargs):
        """"""
        response = None
        error = None
        exception = None

        try:
            response = self.dispatch.call(method, args, kwargs)
        except Exception as e:
            error = (e.__class__.__name__, str(e))
            exception = e

        if isinstance(response, Deferred):
            response.add_callback(self.send_response, msgid)
            response.add_errback(self.send_error, msgid)
        else:
            if exception is None:
                self.send_response(msgid, response)
            else:
                self.send_error(msgid, exception)
514067
def message(self, to, subject, text):
        """"""
        return self.compose(to, subject, text)
217686
def show_message(self, message, timeout=0):
        """"""
        self.main.statusBar().showMessage(message, timeout)
696697
protected function processGif()
    {
        ob_start();
        imagegif($this->image->getCore());
        $this->image->mime = image_type_to_mime_type(IMAGETYPE_GIF);
        $buffer = ob_get_contents();
        ob_end_clean();

        return $buffer;
    }
679224
def handle_stream(self, message):
        
        logging.debug("handle_stream(...)")

        event = Event()
        for line in message.strip().splitlines():
            (field, value) = line.split(":", 1)
            field = field.strip()

            if field == "event":
                event.name = value.lstrip()
            elif field == "data":
                value = value.lstrip()
                if event.data is None:
                    event.data = value
                else:
                    event.data = "%s\n%s" % (event.data, value)
            elif field == "id":
                event.id = value.lstrip()
                self.last_event_id = event.id
            elif field == "retry":
                try:
                    self.retry_timeout = int(value)
                    event.retry = self.retry_timeout
                    logging.info("timeout reset: %s" % (value,))
                except ValueError:
                    pass
            elif field == "":
                logging.debug("received comment: %s" % (value,))
            else:
                raise Exception("Unknown field !")
        self.events.append(event)
1203768
def _handle_message(self, opcode: int, data: bytes) -> "Optional[Future[None]]":
        """"""
        if self.client_terminated:
            return None

        if self._frame_compressed:
            assert self._decompressor is not None
            try:
                data = self._decompressor.decompress(data)
            except _DecompressTooLargeError:
                self.close(1009, "message too big after decompression")
                self._abort()
                return None

        if opcode == 0x1:
            # UTF-8 data
            self._message_bytes_in += len(data)
            try:
                decoded = data.decode("utf-8")
            except UnicodeDecodeError:
                self._abort()
                return None
            return self._run_callback(self.handler.on_message, decoded)
        elif opcode == 0x2:
            # Binary data
            self._message_bytes_in += len(data)
            return self._run_callback(self.handler.on_message, data)
        elif opcode == 0x8:
            # Close
            self.client_terminated = True
            if len(data) >= 2:
                self.close_code = struct.unpack(">H", data[:2])[0]
            if len(data) > 2:
                self.close_reason = to_unicode(data[2:])
            # Echo the received close code, if any (RFC 6455 section 5.5.1).
            self.close(self.close_code)
        elif opcode == 0x9:
            # Ping
            try:
                self._write_frame(True, 0xA, data)
            except StreamClosedError:
                self._abort()
            self._run_callback(self.handler.on_ping, data)
        elif opcode == 0xA:
            # Pong
            self.last_pong = IOLoop.current().time()
            return self._run_callback(self.handler.on_pong, data)
        else:
            self._abort()
        return None
710253
def handle_get(self):
        

        code = 400
        message, explain = BaseHTTPRequestHandler.responses[code]

        response = http_server.DEFAULT_ERROR_MESSAGE % \
            {
             'code' : code,
             'message' : message,
             'explain' : explain
            }
        response = response.encode('utf-8')
        print('Status: %d %s' % (code, message))
        print('Content-Type: %s' % http_server.DEFAULT_ERROR_CONTENT_TYPE)
        print('Content-Length: %d' % len(response))
        print()
        sys.stdout.flush()
        sys.stdout.buffer.write(response)
        sys.stdout.buffer.flush()
280244
function handleIncomingMessage(event, message, source) {
		var blocks = event.split(':'),
			id = blocks[2] || blocks[1];
		if (id in self.transactions && source in self.transactions[id]) {
			self.transactions[id][source].resolve([message, source]);
		}
	}
551388
def makeKVPost(request_message, server_url):
    
    # XXX: TESTME
    resp = fetchers.fetch(server_url, body=request_message.toURLEncoded())

    # Process response in separate function that can be shared by async code.
    return _httpResponseToMessage(resp, server_url)
1162883
def handle(send, msg, args):
    
    worker = args["handler"].workers
    result = worker.run_pool(get_urls, [msg])
    try:
        urls = result.get(5)
    except multiprocessing.TimeoutError:
        worker.restart_pool()
        send("Url regex timed out.", target=args["config"]["core"]["ctrlchan"])
        return
    for url in urls:
        # Prevent botloops
        if (args["db"].query(Urls).filter(Urls.url == url, Urls.time > datetime.now() - timedelta(seconds=10)).count() > 1):
            return

        if url.startswith("https://twitter.com"):
            tid = url.split("/")[-1]
            twitter_api = get_api(args["config"])
            status = twitter_api.GetStatus(tid)
            text = status.text.replace("\n", " / ")
            send("** {} (@{}) on Twitter: {}".format(status.user.name, status.user.screen_name, text))
            return

        imgkey = args["config"]["api"]["googleapikey"]
        title = urlutils.get_title(url, imgkey)

        shortkey = args["config"]["api"]["bitlykey"]
        short = urlutils.get_short(url, shortkey)

        last = args["db"].query(Urls).filter(Urls.url == url).order_by(Urls.time.desc()).first()
        if args["config"]["feature"].getboolean("linkread"):
            if last is not None:
                lasttime = last.time.strftime("%H:%M:%S on %Y-%m-%d")
                send("Url %s previously posted at %s by %s -- %s" % (short, lasttime, last.nick, title))
            else:
                send("** %s - %s" % (title, short))
        args["db"].add(Urls(url=url, title=title, nick=args["nick"], time=datetime.now()))