当前位置: 首页>>代码示例>>Python>>正文


Python slacker.Error方法代码示例

本文整理汇总了Python中slacker.Error方法的典型用法代码示例。如果您正苦于以下问题:Python slacker.Error方法的具体用法?Python slacker.Error怎么用?Python slacker.Error使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在slacker的用法示例。


在下文中一共展示了slacker.Error方法的13个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: _react

# 需要导入模块: import slacker [as 别名]
# 或者: from slacker import Error [as 别名]
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 
开发者ID:pyconjp,项目名称:pyconjpbot,代码行数:18,代码来源:reaction.py

示例2: post

# 需要导入模块: import slacker [as 别名]
# 或者: from slacker import Error [as 别名]
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 
开发者ID:aio-libs,项目名称:aioslacker,代码行数:27,代码来源:__init__.py

示例3: validate_token

# 需要导入模块: import slacker [as 别名]
# 或者: from slacker import Error [as 别名]
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 
开发者ID:ErinMorelli,项目名称:em-slack-tableflip,代码行数:27,代码来源:auth.py

示例4: post_slack_message

# 需要导入模块: import slacker [as 别名]
# 或者: from slacker import Error [as 别名]
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) 
开发者ID:foremast,项目名称:foremast,代码行数:17,代码来源:slack.py

示例5: emit

# 需要导入模块: import slacker [as 别名]
# 或者: from slacker import Error [as 别名]
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 
开发者ID:mathiasose,项目名称:slacker_log_handler,代码行数:29,代码来源:__init__.py

示例6: save_token

# 需要导入模块: import slacker [as 别名]
# 或者: from slacker import Error [as 别名]
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"
        ) 
开发者ID:regisb,项目名称:slack-cli,代码行数:31,代码来源:slack.py

示例7: __init__

# 需要导入模块: import slacker [as 别名]
# 或者: from slacker import Error [as 别名]
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() 
开发者ID:alexwlchan,项目名称:backup-slack,代码行数:12,代码来源:backup_slack.py

示例8: clean_replies

# 需要导入模块: import slacker [as 别名]
# 或者: from slacker import Error [as 别名]
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) 
开发者ID:sgratzl,项目名称:slack-cleaner,代码行数:14,代码来源:cli.py

示例9: remove_files

# 需要导入模块: import slacker [as 别名]
# 或者: from slacker import Error [as 别名]
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) 
开发者ID:sgratzl,项目名称:slack-cleaner,代码行数:36,代码来源:cli.py

示例10: get_token

# 需要导入模块: import slacker [as 别名]
# 或者: from slacker import Error [as 别名]
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'] 
开发者ID:ErinMorelli,项目名称:em-slack-tableflip,代码行数:37,代码来源:auth.py

示例11: is_valid_token

# 需要导入模块: import slacker [as 别名]
# 或者: from slacker import Error [as 别名]
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 
开发者ID:ErinMorelli,项目名称:em-slack-tableflip,代码行数:28,代码来源:flipper.py

示例12: send_flip

# 需要导入模块: import slacker [as 别名]
# 或者: from slacker import Error [as 别名]
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 
开发者ID:ErinMorelli,项目名称:em-slack-tableflip,代码行数:31,代码来源:flipper.py

示例13: __request

# 需要导入模块: import slacker [as 别名]
# 或者: from slacker import Error [as 别名]
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 
开发者ID:aio-libs,项目名称:aioslacker,代码行数:53,代码来源:__init__.py


注:本文中的slacker.Error方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。