Python slacker.Error() Examples

The following are 13 code examples of slacker.Error(). 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. You may also want to check out all available functions/classes of the module slacker , or try the search function .
Example #1
Source File: reaction.py    From pyconjpbot with MIT License 6 votes vote down vote up
def _react(message, emojis):
    """
    指定された emoji を reaction で返す
    """
    if isinstance(emojis, str):
        # tuple に変換する
        emojis = (emojis, )
    for emoji in emojis:
        try:
            message.react(emoji)
        except Error as error:
            # 同じリアクションをすると例外が発生するので、無視する
            if error.args[0] == 'already_reacted':
                pass
            else:
                raise 
Example #2
Source File: __init__.py    From aioslacker with MIT License 6 votes vote down vote up
def post(self, data):
        if not self.url:
            raise slacker.Error('URL for incoming webhook is undefined')

        _request = self.session.request(
            'POST',
            self.url,
            data=data,
            timeout=None,
        )

        _response = None

        try:
            with async_timeout.timeout(self.timeout, loop=self.loop):
                _response = yield from _request

            _response.raise_for_status()

            _json = yield from _response.json()
        finally:
            if _response is not None:
                yield from _response.release()

        return _json 
Example #3
Source File: cli.py    From slack-cleaner with MIT License 6 votes vote down vote up
def remove_files(time_range, user_id=None, types=None, channel_id=None):
  # Setup time range for query
  oldest = time_range.start_ts
  latest = time_range.end_ts
  page = 1

  if user_id == -1:
    user_id = None

  has_more = True
  while has_more:
    res = slack.files.list(user=user_id, ts_from=oldest, ts_to=latest,
                           channel=channel_id,
                           types=types, page=page).body

    if not res['ok']:
      logger.error('Error occurred on Slack\'s API:')
      pp.pprint(res)
      sys.exit(1)

    files = res['files']
    current_page = res['paging']['page']
    total_pages = res['paging']['pages']
    has_more = current_page < total_pages
    page = current_page + 1

    for f in files:
      if not should_delete_item(f):
        continue
      # Delete user file
      delete_file(f)

    if args.rate_limit:
      time.sleep(args.rate_limit) 
Example #4
Source File: auth.py    From em-slack-tableflip with MIT License 6 votes vote down vote up
def validate_token(token):
    """Validate token and retrieves info from Slack API."""
    # Set auth object
    auth = Auth(token)

    try:
        # Make request
        result = auth.test()

    except Error as err:
        report_event(str(err), {
            'token': token
        })
        abort(400)

    # Check for errors
    if not result.successful:
        report_event('token_invalid', {
            'token': token,
            'result': result.__dict__
        })
        abort(400)

    # Return user info
    return result.body 
Example #5
Source File: slack.py    From foremast with Apache License 2.0 5 votes vote down vote up
def post_slack_message(message=None, channel=None, username=None, icon_emoji=None):
    """Format the message and post to the appropriate slack channel.

    Args:
        message (str): Message to post to slack
        channel (str): Desired channel. Must start with #

    """
    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) 
Example #6
Source File: __init__.py    From slacker_log_handler with Apache License 2.0 5 votes vote down vote up
def emit(self, record):
        message = self.build_msg(record)

        if self.ping_users and record.levelno >= self.ping_level:
            for user in self.ping_users:
                message = '<@%s> %s' % (user, message)

        if self.stack_trace:
            trace = self.build_trace(record, fallback=message)
            attachments = json.dumps([trace])
        else:
            attachments = None

        try:
            self.slacker.chat.post_message(
                text=message,
                channel=self.channel,
                username=self.username,
                icon_url=self.icon_url,
                icon_emoji=self.icon_emoji,
                attachments=attachments,
            )
        except slacker.Error as e:
            if self.fail_silent:
                pass
            else:
                raise e 
Example #7
Source File: slack.py    From slack-cli with MIT License 5 votes vote down vote up
def save_token(user_token, team=None):
    # Always test token before saving
    try:
        client().api.test()
    except slacker.Error:
        raise errors.SlackCliError("Invalid Slack token: '{}'".format(user_token))

    # Get team
    try:
        team = team or client().team.info().body["team"]["domain"]
    except slacker.Error as e:
        message = e.args[0]
        if e.args[0] == "missing_scope":
            message = (
                "Missing scope on token {}. This token requires the 'team:read' scope."
            ).format(user_token)
        raise errors.SlackCliError(message)

    # Save token
    try:
        token.save(user_token, team)
    except errors.ConfigSaveError as e:
        sys.stderr.write("❌ ")
        sys.stderr.write(e.args[0])
        sys.stderr.write("\n")
        sys.stderr.write(
            "⚠️ Could not save token to disk. You will have to configure the Slack"
            " token again next time you run slack-cli.\n"
        ) 
Example #8
Source File: backup_slack.py    From backup-slack with MIT License 5 votes vote down vote up
def __init__(self, token):
        self.slack = slacker.Slacker(token=token)

        # Check the token is valid
        try:
            self.slack.auth.test()
        except slacker.Error:
            raise AuthenticationError('Unable to authenticate API token.')

        self.usernames = self._fetch_user_mapping() 
Example #9
Source File: cli.py    From slack-cleaner with MIT License 5 votes vote down vote up
def clean_replies(channel_id, thread_ts, time_range, user_id=None, bot=False):
  def list_f(latest, oldest):
    try:
      return slack.conversations.replies(channel_id, thread_ts, latest=latest, oldest=oldest, limit=1000)
    except Error as e:
      if str(e) == 'thread_not_found':
        # make it as if there are no more messages
        return dict(ok=True, messages=[])
      raise e
    

  _clean_messages_impl(list_f, channel_id, time_range, user_id, bot, thread_ts) 
Example #10
Source File: auth.py    From em-slack-tableflip with MIT License 5 votes vote down vote up
def get_token(code, scope='user'):
    """Request a token from the Slack API."""
    # Set OAuth access object
    oauth = OAuth()

    # Setup return URL
    return_url = '{0}_url'.format(scope)

    try:
        # Attempt to make request
        result = oauth.access(
            client_id=PROJECT_INFO['client_id'],
            client_secret=PROJECT_INFO['client_secret'],
            redirect_uri=PROJECT_INFO[return_url],
            code=code
        )

    except Error as err:
        report_event('oauth_error', {
            'code': code,
            'return_url': return_url,
            'error': str(err)
        })
        abort(400)

    if not result.successful:
        report_event('oauth_unsuccessful', {
            'code': code,
            'return_url': return_url,
            'result': result.__dict__
        })
        abort(400)

    # Return token
    return result.body['access_token'] 
Example #11
Source File: flipper.py    From em-slack-tableflip with MIT License 5 votes vote down vote up
def is_valid_token(token):
    """Check that the user has a valid token."""
    # Set auth object
    auth = Auth(token)

    try:
        # Make request
        result = auth.test()

    except Error as err:
        # Check for auth errors
        stf.report_event(str(err), {
            'token': token
        })
        return False

    # Check for further errors
    if not result.successful:
        stf.report_event('token_invalid', {
            'token': token,
            'result': result.__dict__
        })
        return False

    # Return successful
    return True 
Example #12
Source File: flipper.py    From em-slack-tableflip with MIT License 5 votes vote down vote up
def send_flip(token, table, args):
    """Post the flip as the authenticated user in Slack."""
    # Set up chat object
    chat = Chat(token)

    try:
        # Attempt to post message
        chat.post_message(
            args['channel_id'],
            table,
            username=args['user_id'],
            as_user=True
        )

    except Error as err:
        stf.report_event(str(err), {
            'token': token,
            'table': table,
            'args': args
        })

        # Report if we got any errors
        return '{app} encountered an error: {error}'.format(
            app=stf.PROJECT_INFO['name_full'],
            error=str(err)
        )

    # Return without errors
    return None 
Example #13
Source File: __init__.py    From aioslacker with MIT License 4 votes vote down vote up
def __request(self, method, api, **kwargs):
        method = self.methods[method]

        kwargs.setdefault('params', {})
        kwargs.setdefault('timeout', None)

        if self.token:
            kwargs['params']['token'] = self.token

        kwargs['params'] = urlencode(kwargs['params'], doseq=True)

        if method == 'POST':
            files = kwargs.pop('files', None)

            if files is not None:
                data = kwargs.pop('data', {})

                _data = aiohttp.FormData()

                for k, v in files.items():
                    _data.add_field(k, open(v.name, 'rb'))

                for k, v in data.items():
                    if v is not None:
                        _data.add_field(k, str(v))

                kwargs['data'] = _data

        _url = slacker.API_BASE_URL.format(api=api)

        _request = self.session.request(method, _url, **kwargs)

        _response = None

        try:
            with async_timeout.timeout(self.timeout, loop=self.loop):
                _response = yield from _request

            _response.raise_for_status()

            text = yield from _response.text()
        finally:
            if _response is not None:
                yield from _response.release()

        response = Response(text)

        if not response.successful:
            raise Error(response.error)

        return response