See https://api.slack.com/rtm.
960687
public WebSocket rtm(HttpUrl url, WebSocketListener listener) {
    return httpClient.newWebSocket(new Request.Builder()
        .url(url)
        .build(), listener);
  }
1172068
def post_slack_message(message=None, channel=None, username=None, icon_emoji=None):
    
    LOG.debug('Slack Channel: %s\nSlack Message: %s', channel, message)
    slack = slacker.Slacker(SLACK_TOKEN)
    try:
        slack.chat.post_message(channel=channel, text=message, username=username, icon_emoji=icon_emoji)
        LOG.info('Message posted to %s', channel)
    except slacker.Error:
        LOG.info("error posted message to %s", channel)
635595
def slack_user(request, api_data):
    
    if request.user.is_anonymous:
        return request, api_data

    data = deepcopy(api_data)

    slacker, _ = SlackUser.objects.get_or_create(slacker=request.user)
    slacker.access_token = data.pop('access_token')
    slacker.extras = data
    slacker.save()

    messages.add_message(request, messages.SUCCESS, 'Your account has been successfully updated with '
                                                    'Slack. You can share your messages within your slack '
                                                    'domain.')

    return request, api_data
853649
def get_pmt(self, dom_id, channel_id):
        """"""
        du, floor, _ = self.doms[dom_id]
        pmt = self.pmts[self._pmt_index_by_omkey[(du, floor, channel_id)]]
        return pmt
1212170
def seek(self, time):
        
        res = librtmp.RTMP_SendSeek(self.client.rtmp, time)

        if res < 1:
            raise RTMPError("Failed to seek")
637099
function SlackRtmOut(n) {
    RED.nodes.createNode(this, n);

    var node = this;
    this.client = n.client;
    this.clientNode = RED.nodes.getNode(this.client);

    node.status(statuses.disconnected);

    if (node.client) {
      SetConfigNodeConnectionListeners(node);

      node.on("input", function(msg) {
        SlackDebug("slack-rtm-out incomiming message", msg);

        /**
         * message, presence_sub, presence_query, ping, and typing.
         */
        var method = msg.topic;
        var options = msg.payload;

        if (
          !method ||
          typeof method !== "string" ||
          !method instanceof String
        ) {
          node.error("invalid msg.topic");
          return null;
        }

        /**
         * Try to help with common use case, set channel based on lookup if starts with @ or #
         */
        if (
          method == "message" &&
          (options.channel[0] == "@" || options.channel[0] == "#")
        ) {
          var channel = node.clientNode.findChannelByName(options.channel);
          if (channel && channel.id) {
            options.channel = channel.id;
          }
        }

        /**
         * special handling for simple use-case
         */
        if (method[0] == "@" || method[0] == "#") {
          var channel = node.clientNode.findChannelByName(method);
          if (!channel || !channel.id) {
            node.error("invalid channel: " + method);
            return null;
          }
          method = "message";
          options = {
            text: msg.payload,
            channel: channel.id
          };
        }

        /**
         * custom per-method logic
         */
        switch (method) {
          case "message":
            // force text to be a string
            options.text = ValueToString(options.text);
            break;
        }

        /**
         * something seems to block when it's not message events
         * keeping a hard-coded list for now until the 'bug' is squashed
         *
         * https://github.com/slackapi/node-slack-sdk/issues/706
         *
         * There's only 5 (public) writable events on RTM: message,
         * presence_sub, presence_query, ping, and typing.
         *
         * The only two that expect responses are message and ping.
         */
        var awaitReply = false;
        switch (method) {
          case "message":
          case "ping":
            awaitReply = true;
            break;
          case "presence_sub":
          case "presence_query":
          case "typing":
            awaitReply = false;
            break;
          default:
            /**
             * go ahead and let invalid methods await so a negative/error
             * response is returned
             */
            awaitReply = true;
            break;
        }

        node.status(statuses.sending);
        msg.slackState = node.clientNode.state;

        SlackDebug("slack-rtm-out call", method, options);
        node.clientNode.rtmClient
          .addOutgoingEvent(awaitReply, method, options)
          .then(res => {
            /**
             * mock a response for methods which return nothing
             * ie: everything but message and ping
             */
            if (typeof res === "undefined") {
              res = {
                ok: true,
                type: method
              };
            }

            SlackDebug("slack-rtm-out call response", res);
            msg.payload = res;
            node.send(msg);
            node.status(statuses.connected);
          })
          .catch(e => {
            SlackDebug("slack-rtm-out error response", e.data);
            msg.payload = e.data;
            node.send(msg);
            node.status(statuses.connected);
          });
      });
    } else {
      node.status(statuses.misconfigured);
    }
  }
521111
def team_integrationLogs(self, **kwargs) -> SlackResponse:
        """"""
        self._validate_xoxp_token()
        return self.api_call("team.integrationLogs", http_verb="GET", params=kwargs)
474906
function SlackRtmIn(n) {
    RED.nodes.createNode(this, n);

    var node = this;
    this.client = n.client;
    this.events = n.events;
    this.clientNode = RED.nodes.getNode(this.client);

    var eventNames;
    if (this.events) {
      eventNames = this.events
        .replace(/[\s]+/g, "")
        .split(",")
        .filter(Boolean);
    }

    node.status(statuses.disconnected);

    if (node.client) {
      SetConfigNodeConnectionListeners(node);

      node.clientNode.rtmClient.on("slack_event", (eventType, event) => {
        /**
         * responses to websocket commands come over the without an eventType
         */
        if (eventType === undefined) {
          eventType = "ws_response";
          event.type = eventType;
        }

        /**
         * ignore non-subscribed events
         * 
         * Since the message events are bound to the same object as connection
         * events this feature has been implemented in this fashion vs directly
         * subscribing to prevent stupid (ie: someone setting a value of
         * 'connected' or the like) in node properties. Crude but effective.
         * 
         * It also decouples the feature from the semantics of the client.
         */
        if (this.events && eventNames.length > 0) {
          if (
            !(
              eventNames.includes(event.type) ||
              (event.subtype &&
                eventNames.includes(`${event.type}::${event.subtype}`))
            )
          ) {
            return null;
          }
        }

        /**
         * pong: triggered in response to a ping keep-alive
         *
         * hello: triggered on connect
         *
         * ws_response: triggered after data has been sent over the ws
         *
         * channel_marked: triggered when the bot user has 'read' a channel
         *
         * desktop_notification: triggered when the bot user is @mentioned or
         * otherwise would receive an alert
         *
         * pretty sure nobody is interested in the below
         * note that ws_response is sent on the output side of the output node
         * so receiving it here is double processing
         */
        if (eventType == "pong" || eventType == "ws_response") {
          return null;
        }

        SlackDebug("slack-rtm-in incoming event", event);
        var msg = {};
        msg.payload = node.clientNode.dressResponseMessage(event);
        msg.slackState = node.clientNode.state;
        node.send(msg);
      });
    } else {
      node.status(statuses.misconfigured);
    }
  }
1011868
def post_slack():
    """"""
    try:
        token = os.environ['SLACK_TOKEN']
        slack = Slacker(token)

        obj = slack.chat.post_message('#general', 'Hello fellow slackers!')
        print(obj.successful, obj.__dict__['body']['channel'], obj.__dict__[
            'body']['ts'])
    except KeyError as ex:
        print('Environment variable %s not set.' % str(ex))
543176
def post_message(self):
        
        message = get_template(template_file='slack/pipeline-prepare-ran.j2', info=self.info)
        channel = '#deployments-prod'
        post_slack_message(message=message, channel=channel, username='pipeline-bot', icon_emoji=':gear:')
1191420
def run_forever(self):
        """"""
        res = self.slack.rtm.start()
        self.log.info("current channels: %s",
                      ','.join(c['name'] for c in res.body['channels']
                               if c['is_member']))
        self.id = res.body['self']['id']
        self.name = res.body['self']['name']
        self.my_mention = "<@%s>" % self.id

        self.ws = websocket.WebSocketApp(
            res.body['url'],
            on_message=self._on_message,
            on_error=self._on_error,
            on_close=self._on_close,
            on_open=self._on_open)
        self.prepare_connection(self.config)
        self.ws.run_forever()
577197
async def _incoming_from_rtm(
        self, url: str, bot_id: str
    ) -> AsyncIterator[events.Event]:
        
        async for data in self._rtm(url):
            event = events.Event.from_rtm(json.loads(data))
            if sansio.need_reconnect(event):
                break
            elif sansio.discard_event(event, bot_id):
                continue
            else:
                yield event
1123295
function( tmp, self ) {
      var _arg = self.options.validators.regExp[ tmp.arg ],
        _reg = new RegExp( _arg.pattern );
      return _reg.test( tmp.val ) || _arg.errorMessage;
    }
1145806
def slack_message():
    """"""
    # Incoming request format:
    # token=TOKEN
    # team_id=T0001
    # team_domain=example
    # channel_id=C12345
    # channel_name=test
    # user_id=U12345
    # user_name=Steve
    # command=/weather
    # text=94070

    # Verify Slack token lines up
    if request.form['token'] != SLACK_TOKEN:
        return ('Provided Slack token from message didn\'t match our server\'s Slack token. '
                'Please double check they are aligned', 403)

    # Extract our text and make a card
    text = request.form['text']
    user_name = request.form['user_name']
    # Pre-emptively extract channel name before taking actions (transaction-esque)
    channel_name = request.form['channel_name']
    card = make_trello_card(name='{text} ({user_name})'.format(text=text, user_name=user_name))

    # Send a message to Slack about our success
    # TODO: Escape our content
    send_slack_message(channel='#{channel_name}'.format(channel_name=channel_name),
                       text='Trello card "<{url}|{text}>" created by "{user_name}"'
                       .format(url=card.url, text=text, user_name=user_name))

    # Reply with nothing (as the external message does more)
    return ''
811573
def main():
    
    log = logging.getLogger(mod_logger + '.main')
    parser = argparse.ArgumentParser(description='This Python module allows '
                                                 'sending Slack messages.')
    parser.add_argument('-u', '--url', help='Slack webhook URL', required=True)
    parser.add_argument('-t', '--text', help='Text of the message', required=True)
    parser.add_argument('-n', '--channel', help='Slack channel', required=True)
    parser.add_argument('-i', '--icon', help='URL for the Slack icon', required=False)
    parser.add_argument('-c', '--color', help='Color of the Slack post', required=False)
    parser.add_argument('-a', '--attachment', help='Text for the Slack Attachment', required=False)
    parser.add_argument('-p', '--pretext', help='Pretext for the Slack attachment', required=False)
    args = parser.parse_args()

    # Create the SlackMessage object
    try:
        slack_msg = SlackMessage(args.url, channel=args.channel, icon_url=args.icon, text=args.text)
    except ValueError as e:
        msg = 'Unable to create slack message\n{ex}'.format(ex=e)
        log.error(msg)
        print(msg)
        return

    # If provided, create the SlackAttachment object
    if args.attachment:
        try:
            slack_att = SlackAttachment(fallback=args.attachment, color=args.color,
                                        pretext=args.pretext, text=args.attachment)
        except ValueError:
            _, ex, trace = sys.exc_info()
            log.error('Unable to create slack attachment\n{e}'.format(e=str(ex)))
            return
        slack_msg.add_attachment(slack_att)

    # Send Slack message
    try:
        slack_msg.send()
    except(TypeError, ValueError, IOError):
        _, ex, trace = sys.exc_info()
        log.error('Unable to send Slack message\n{e}'.format(e=str(ex)))
        return
    log.debug('Your message has been Slacked successfully!')
98865
def run_commands_from_slack_async(self, message_generator, fire_all, tag, control, interval=1):
        '''
        
        '''

        outstanding = {}  # set of job_id that we need to check for

        while True:
            log.trace('Sleeping for interval of %s', interval)
            time.sleep(interval)
            # Drain the slack messages, up to 10 messages at a clip
            count = 0
            for msg in message_generator:
                # The message_generator yields dicts.  Leave this loop
                # on a dict that looks like {'done': True} or when we've done it
                # 10 times without taking a break.
                log.trace('Got a message from the generator: %s', msg.keys())
                if count > 10:
                    log.warning('Breaking in getting messages because count is exceeded')
                    break
                if not msg:
                    count += 1
                    log.warning('Skipping an empty message.')
                    continue  # This one is a dud, get the next message
                if msg.get('done'):
                    log.trace('msg is done')
                    break
                if fire_all:
                    log.debug('Firing message to the bus with tag: %s', tag)
                    log.debug('%s %s', tag, msg)
                    self.fire('{0}/{1}'.format(tag, msg['message_data'].get('type')), msg)
                if control and (len(msg) > 1) and msg.get('cmdline'):
                    channel = self.sc.server.channels.find(msg['channel'])
                    jid = self.run_command_async(msg)
                    log.debug('Submitted a job and got jid: %s', jid)
                    outstanding[jid] = msg  # record so we can return messages to the caller
                    channel.send_message("@{}'s job is submitted as salt jid {}".format(msg['user_name'], jid))
                count += 1
            start_time = time.time()
            job_status = self.get_jobs_from_runner(outstanding.keys())  # dict of job_ids:results are returned
            log.trace('Getting %s jobs status took %s seconds', len(job_status), time.time() - start_time)
            for jid in job_status:
                result = job_status[jid]['data']
                function = job_status[jid]['function']
                if result:
                    log.debug('ret to send back is %s', result)
                    # formatting function?
                    this_job = outstanding[jid]
                    channel = self.sc.server.channels.find(this_job['channel'])
                    return_text = self.format_return_text(result, function)
                    return_prefix = "@{}'s job `{}` (id: {}) (target: {}) returned".format(
                        this_job['user_name'], this_job['cmdline'], jid, this_job['target'])
                    channel.send_message(return_prefix)
                    ts = time.time()
                    st = datetime.datetime.fromtimestamp(ts).strftime('%Y%m%d%H%M%S%f')
                    filename = 'salt-results-{0}.yaml'.format(st)
                    r = self.sc.api_call(
                        'files.upload', channels=channel.id, filename=filename,
                        content=return_text)
                    # Handle unicode return
                    log.debug('Got back %s via the slack client', r)
                    resp = salt.utils.yaml.safe_load(salt.utils.json.dumps(r))
                    if 'ok' in resp and resp['ok'] is False:
                        this_job['channel'].send_message('Error: {0}'.format(resp['error']))
                    del outstanding[jid]
378874
def rtm_handler(self, ws_message):
        
        message = json.loads(ws_message.data)
        if 'reply_to' in message:
            reply_to = message['reply_to']
            future = self.response_futures.pop(reply_to, None)
            if future is None:
                logger.error(f'This should not happen, received reply to unknown message! {message}')
                return None
            future.set_result(message)
            return None
        if 'type' not in message:
            logger.error(f'No idea what this could be {message}')
            return
        message_type = message['type']

        if hasattr(self, f'handle_{message_type}'):
            function = getattr(self, f'handle_{message_type}')
            return function(message)

        if message_type in self.SLACK_RTM_EVENTS:
            logger.debug(f'Unhandled {message_type}. {message}')
        else:
            logger.warning(f'Unknown {message_type}. {message}')
        return message