本文整理汇总了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
示例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
示例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
示例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)
示例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
示例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"
)
示例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()
示例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)
示例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)
示例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']
示例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
示例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
示例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