Fetch all im channels to determine direct message to the bot.

@param slackToken slack token which you get from slack for the integration you create
@param limit number of channels to fetch in one call
@param nextCursor cursor for the next call
359017
private void getImChannels(String slackToken, int limit, String nextCursor) {
        try {
            Event event = restTemplate.getForEntity(slackApiEndpoints.getImListApi(), Event.class,
                    slackToken, limit, nextCursor).getBody();
            imChannelIds.addAll(Arrays.stream(event.getIms()).map(Channel::getId).collect(Collectors.toList()));
            if (event.getResponseMetadata() != null &&
                    !StringUtils.isEmpty(event.getResponseMetadata().getNextCursor())) {
                Thread.sleep(5000L); // sleep because its a tier 2 api which allows only 20 calls per minute
                getImChannels(slackToken, limit, event.getResponseMetadata().getNextCursor());
            }
        } catch (Exception e) {
            logger.error("Error fetching im channels for the bot: ", e);
        }
    }
10600
private void nextToken(StreamTokenizer tokenizer) throws IOException {
    tokenizer.nextToken();
    if((tokenizer.ttype == '\'') || (tokenizer.ttype == '"')) {
      tokenizer.ttype = StreamTokenizer.TT_WORD;
    }
    else if((tokenizer.ttype == StreamTokenizer.TT_WORD) && (tokenizer.sval.equals("?"))) {
      tokenizer.ttype = '?';
    }
    if(LOG.isDebugging()) {
      if(tokenizer.ttype == StreamTokenizer.TT_NUMBER) {
        LOG.debug("token: " + tokenizer.nval);
      }
      else if(tokenizer.ttype == StreamTokenizer.TT_WORD) {
        LOG.debug("token: " + tokenizer.sval);
      }
      else if(tokenizer.ttype == StreamTokenizer.TT_EOF) {
        LOG.debug("token: EOF");
      }
      else if(tokenizer.ttype == StreamTokenizer.TT_EOL) {
        LOG.debug("token: EOL");
      }
      else {
        LOG.debug("token type: " + tokenizer.ttype);
      }
    }
  }
1084467
private final void nextToken()
  {

    if (m_queueMark < m_ops.getTokenQueueSize())
    {
      m_token = (String) m_ops.m_tokenQueue.elementAt(m_queueMark++);
      m_tokenChar = m_token.charAt(0);
    }
    else
    {
      m_token = null;
      m_tokenChar = 0;
    }
  }
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 ''
253780
function getAdjacentCommentTokensFromCursor(cursor) {
    const tokens = [];
    let currentToken = cursor.getOneToken();

    while (currentToken && astUtils.isCommentToken(currentToken)) {
        tokens.push(currentToken);
        currentToken = cursor.getOneToken();
    }

    return tokens;
}
164148
public void queryMessagesFromServer(int limit, final AVIMMessagesQueryCallback callback) {
    queryMessagesFromServer(null, 0, limit, null, 0, new AVIMMessagesQueryCallback() {
      @Override
      public void done(List<AVIMMessage> messages, AVIMException e) {
        if (null == e) {
          if (AVIMOptions.getGlobalOptions().isMessageQueryCacheEnabled()) {
            processContinuousMessages(messages);
          }
          callback.internalDone(messages, null);
        } else {
          callback.internalDone(null, e);
        }
      }
    });
  }
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)
976105
def add_token_with_limits(
            self,
            token_address: TokenAddress,
            channel_participant_deposit_limit: TokenAmount,
            token_network_deposit_limit: TokenAmount,
    ) -> Address:
        
        return self._add_token(
            token_address=token_address,
            additional_arguments={
                '_channel_participant_deposit_limit': channel_participant_deposit_limit,
                '_token_network_deposit_limit': token_network_deposit_limit,
            },
        )
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
818037
function Slack(opts, debug) {
  if (!(this instanceof Slack)) return new Slack(opts);
  this.opts = opts;
  this.debug = debug;

  /**
   * Do everything.
   */

  this.import = function *() {
    try {
      console.log('Starting import');
      yield this.tokens();
      console.log('Got tokens');
      yield this.login();
      console.log('Logged in');
    } catch (e) {
      console.log('Uh oh! ' + e);
      throw e;
    }
    console.log('Getting emoji page');
    var emojiList = '';
    var aliasList = '';
    for (var i = 0; i < Object.keys(this.opts.emojis).length; i++) {
      var e = this.opts.emojis[i];
      if (e.src) {
        var uploadRes = yield this.upload(e.name, e.src);
        emojiList += ' :' + e.name + ':';
      }
      if (e.aliases) {
        for (var n = 0; n < e.aliases.length; n++) {
          yield this.alias(e.name, e.aliases[n]);
          aliasList += ' :' + e.aliases[n] + ':';
        }
      }
    }
    console.log('Uploaded emojis:' + emojiList);
    console.log('Uploaded emoji aliases:' + aliasList);
    return 'Success';
  };

  /**
   * Get login page (aka credentials).
   */

  this.tokens = function *() {
    var opts = this.opts;
    opts.jar = opts.jar || { _jar: { store: { idx: {} } } };
    var load = {
      url: opts.url + loginFormPath,
      headers: headers,
      jar: opts.jar,
      method: 'GET'
    };
    var res = yield request(load);
    var $ = cheerio.load(res[0].body);
    if (this.debug) write($('title').text(), $.html());
    opts.formData = {
      signin: $('#signin_form input[name="signin"]').attr('value'),
      redir: $('#signin_form input[name="redir"]').attr('value'),
      crumb: $('#signin_form input[name="crumb"]').attr('value'),
      remember: 'on',
      email: opts.email,
      password: opts.password
    };
    if (!opts.formData.signin && !opts.formData.redir && !opts.formData.crumb) throw new Error('Login error: could not get login form for ' + opts.url);
    return this.opts = opts;
  };

  /**
   * Log into Slack and populate cookies.
   */

  this.login = function *() {
    var opts = this.opts;
    var load = {
      url: opts.url + loginFormPath,
      headers: headers,
      jar: opts.jar,
      method: 'POST',
      followAllRedirects: true,
      formData: opts.formData
    };
    var res = yield request(load);
    if(res[0].body.indexOf("Sorry, you entered an incorrect email address or password.") != -1){
      throw new Error('Login error: incorrect username / password');
    }

    if(res[0].body.indexOf("Enter your authentication code") != -1){

      var $ = cheerio.load(res[0].body);

      var inputs = $("form input")

      var formData = {};

      inputs.each(function(i,v){
        formData[v.attribs.name] = v.attribs.value;
      })

      user_2fa_code = yield ask('2FA Code: ', isPassword, 'A password (as defined by this script) needs to have at least one character (not including you).');
      formData["2fa_code"] = user_2fa_code

      delete formData[undefined]
      delete formData['input']

      var load_2fa = {
        url: opts.url + "/",
        headers: headers,
        jar: opts.jar,
        method: 'POST',
        followAllRedirects: true,
        formData: formData
      };
      res = yield request(load_2fa);
    }

    //TODO: it may be necessary in the future to replace this with a user-supplied token
    var match = apiTokenRegex.exec(res[0].body);
    if (!match || !match[1]) {
      throw new Error('Application Error: unable to find api token on login page');
    }
    opts.apiToken = match[1];

    return this.opts = opts;
  };

  /**
   * Upload the emoji.
   */

  this.upload = function *(name, emoji) {
    console.log('Uploading %s with %s', name, emoji);
    return new Promise(function(resolve, reject, notify) {
      var opts = this.opts;
      var r = req({
        url: opts.url + emojiAddEndpoint,
        headers: headers,
        method: 'POST',
        jar: opts.jar,
        followAllRedirects: true
      }, function(err, res, body) {
        if (err || !body) return reject(err);
        resolve(body);
      });
      var form = r.form();
      form.append('name', name);
      form.append('mode', 'data');
      form.append('image', req(emoji));
      form.append('token', opts.apiToken);
    }.bind(this));
  };

  this.alias = function *(name, alias) {
    console.log('Aliasing %s to %s', alias, name);
    return new Promise(function(resolve, reject, notify) {
      var opts = this.opts;
      var r = req({
        url: opts.url + emojiAddEndpoint,
      headers: {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36'},
        method: 'POST',
        jar: opts.jar,
        followAllRedirects: true
      }, function(err, res, body) {
        if (err || !body) return reject(err);
        resolve(body);
      });
      var form = r.form();
      form.append('name', alias);
      form.append('mode', 'alias');
      form.append('alias', name);
      form.append('token', opts.apiToken);
    }.bind(this));
  };
}
803370
def join(self, channel_name):
        
        self.params.update({
            'name': channel_name,
            })
        return FromUrl('https://slack.com/api/channels.join', self._requests)(data=self.params).post()
178815
def get_dm_channel(self, userid):
        '''
        '''

        dm_open = self.slack_client.api_call('im.open', user=userid)
        return dm_open['channel']['id']
691999
public void queryMessages(final int limit, final AVIMMessagesQueryCallback callback) {
    if (limit <= 0 || limit > 1000) {
      if (callback != null) {
        callback.internalDone(null, new AVException(new IllegalArgumentException(
                "limit should be in [1, 1000]")));
      }
    }
    // 如果屏蔽了本地缓存则全部走网络
    if (!AVIMOptions.getGlobalOptions().isMessageQueryCacheEnabled()) {
      queryMessagesFromServer(null, 0, limit, null, 0, new AVIMMessagesQueryCallback() {

        @Override
        public void done(List<AVIMMessage> messages, AVIMException e) {
          if (callback != null) {
            if (e != null) {
              callback.internalDone(e);
            } else {
              callback.internalDone(messages, null);
            }
          }
        }
      });
      return;
    }
    if (!AppConfiguration.getGlobalNetworkingDetector().isConnected()) {
      queryMessagesFromCache(null, 0, limit, callback);
    } else {
      // 选择最后一条有 breakpoint 为 false 的消息做截断，因为是 true 的话，会造成两次查询。
      // 在 queryMessages 还是遇到 breakpoint，再次查询了
      long cacheMessageCount = storage.getMessageCount(conversationId);
      long toTimestamp = 0;
      String toMsgId = null;
      // 如果本地的缓存的量都不够的情况下，应该要去服务器查询，以免第一次查询的时候出现limit跟返回值不一致让用户认为聊天记录已经到头的问题
      if (cacheMessageCount >= limit) {
        final AVIMMessage latestMessage =
                storage.getLatestMessageWithBreakpoint(conversationId, false);

        if (latestMessage != null) {
          toMsgId = latestMessage.getMessageId();
          toTimestamp = latestMessage.getTimestamp();
        }
      }

      // 去服务器查询最新消息，看是否在其它终端产生过消息。为省流量，服务器会截断至 toMsgId 、toTimestamp
      queryMessagesFromServer(null, 0, limit, toMsgId, toTimestamp,
              new AVIMMessagesQueryCallback() {
                @Override
                public void done(List<AVIMMessage> messages, AVIMException e) {
                  if (e != null) {
                    // 如果遇到本地错误或者网络错误，直接返回缓存数据
                    if (e.getCode() == AVIMException.TIMEOUT || e.getCode() == 0 || e.getCode() == 3000) {
                      queryMessagesFromCache(null, 0, limit, callback);
                    } else {
                      if (callback != null) {
                        callback.internalDone(e);
                      }
                    }
                  } else {
                    if (null == messages || messages.size() < 1) {
                      // 这种情况就说明我们的本地消息缓存是最新的
                    } else {
                      /*
                       * 1.messages.size()<=limit && messages.contains(latestMessage)
                       * 这种情况就说明在本地客户端退出后，该用户在其他客户端也产生了聊天记录而没有缓存到本地来,且产生了小于一页的聊天记录
                       * 2.messages==limit && !messages.contains(latestMessage)
                       * 这种情况就说明在本地客户端退出后，该用户在其他客户端也产生了聊天记录而没有缓存到本地来,且产生了大于一页的聊天记录
                       */

                      processContinuousMessages(messages);
                    }
                    queryMessagesFromCache(null, 0, limit, callback);
                  }
                }
              });
    }
  }
533676
public SequenceLabel getNextToken() {
    if (this.nextToken == null) {
      try {
        this.nextToken = this.jlexer.yylex();
      } catch (final IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    }
    final SequenceLabel result = this.nextToken;
    this.nextToken = null;
    if (result == null) {
      throw new NoSuchElementException();
    }
    return result;
  }
285000
public final void handleTextMessage(WebSocketSession session, TextMessage textMessage) {
        ObjectMapper mapper = new ObjectMapper();
        logger.debug("Response from Slack: {}", textMessage.getPayload());
        try {
            Event event = mapper.readValue(textMessage.getPayload(), Event.class);
            if (event.getType() != null) {
                if (event.getType().equalsIgnoreCase(EventType.IM_OPEN.name())
                        || event.getType().equalsIgnoreCase(EventType.IM_CREATED.name())) {
                    if (event.getChannelId() != null) {
                        slackService.addImChannelId(event.getChannelId());
                    } else if (event.getChannel() != null) {
                        slackService.addImChannelId(event.getChannel().getId());
                    }
                } else if (event.getType().equalsIgnoreCase(EventType.MESSAGE.name())) {
                    if (event.getText() != null && event.getText().contains(slackService.getCurrentUser().getId())) { // direct mention
                        event.setType(EventType.DIRECT_MENTION.name());
                    } else if (slackService.getImChannelIds().contains(event.getChannelId())) { // direct message
                        event.setType(EventType.DIRECT_MESSAGE.name());
                    }
                } else if (event.getType().equalsIgnoreCase(EventType.HELLO.name())) {
                    pingAtRegularIntervals(session);
                }
            } else { // slack does not send any TYPE for acknowledgement messages
                event.setType(EventType.ACK.name());
            }

            if (isConversationOn(event)) {
                invokeChainedMethod(session, event);
            } else {
                invokeMethods(session, event);
            }
        } catch (Exception e) {
            logger.error("Error handling response from Slack: {} \nException: ", textMessage.getPayload(), e);
        }
    }
1300948
def history(self, channel_name, **kwargs):
        
        channel_id = self.get_channel_id(channel_name)
        self.params.update({'channel': channel_id})
        if kwargs:
            self.params.update(kwargs)
        return FromUrl('https://slack.com/api/channels.history', self._requests)(data=self.params).get()
332003
def conversations_invite(
        self, *, channel: str, users: List[str], **kwargs
    ) -> SlackResponse:
        
        self._validate_xoxp_token()
        kwargs.update({"channel": channel, "users": users})
        return self.api_call("conversations.invite", json=kwargs)