本文整理汇总了Python中slacker.Slacker方法的典型用法代码示例。如果您正苦于以下问题:Python slacker.Slacker方法的具体用法?Python slacker.Slacker怎么用?Python slacker.Slacker使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类slacker
的用法示例。
在下文中一共展示了slacker.Slacker方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _send_password_on_dm
# 需要导入模块: import slacker [as 别名]
# 或者: from slacker import Slacker [as 别名]
def _send_password_on_dm(message, email, password):
"""
ユーザーのパスワード文字列を DM でコマンドを実行したユーザーに送信する
:param email: ユーザーのメールアドレス
:param password: 生成されたパスワード文字列
"""
# ユーザーとのDMのチャンネルIDを取得
user = message._body['user']
slack = Slacker(settings.API_TOKEN)
result = slack.im.open(user)
dm_channel = result.body['channel']['id']
msg = 'ユーザー `{}` のパスワードは `{}` です'.format(email, password)
# DMチャンネルにメッセージを送信する
message._client.rtm_send_message(dm_channel, msg)
示例2: postNewPoCFound
# 需要导入模块: import slacker [as 别名]
# 或者: from slacker import Slacker [as 别名]
def postNewPoCFound(word, repos, channel):
url = 'https://github.com'
slack = Slacker(slackbot_settings.API_TOKEN)
try:
slack.chat.post_message(
channel,
'New Code Found about `' + word + '` at _github_',
as_user=True
)
message = ''
for r in repos:
message += url + '/' + r + '/\n'
slack.chat.post_message(
channel,
message,
as_user=True
)
except:
print("Could not send slack notification.")
print(traceback.format_exc())
示例3: postAnyData
# 需要导入模块: import slacker [as 别名]
# 或者: from slacker import Slacker [as 别名]
def postAnyData(word, channel):
slack = Slacker(slackbot_settings.API_TOKEN)
try:
slack.chat.post_message(
channel,
word,
as_user=True
)
except:
print("Could not send slack notification.")
print(traceback.format_exc())
#if __name__ == '__main__':
# slack = Slacker(slackbot_settings.API_TOKEN)
# slack.chat.post_message(
# 'bot_test',
# 'Hello. I\'m Master',
# as_user=True
# )
示例4: putSlack
# 需要导入模块: import slacker [as 别名]
# 或者: from slacker import Slacker [as 别名]
def putSlack(channel='sandbox', message='Hello World', event=None):
try:
sc = Slacker(loft_hvac.read_secret(path='secret/slack/apikey'))
response = sc.chat.post_message(
channel=channel,
text=message,
unfurl_links=True
)
if response.body['ok']:
print('success')
else:
print("Failed publishing to slack. Error: {0}"
.format(response['error']))
except Exception as e:
print(e)
示例5: send_to_slack
# 需要导入模块: import slacker [as 别名]
# 或者: from slacker import Slacker [as 别名]
def send_to_slack(message, attachment, channel, key):
status = True
print("sending slack message " + message)
emoji = ":closed_lock_with_key:"
if not channel.startswith('#'):
channel = '#' + channel
slack = Slacker(key)
slack.chat.post_message(
channel=channel,
text=message,
attachments=attachment,
as_user="false",
username="AWS IAM Notifier",
icon_emoji=emoji)
return status
示例6: list_slack
# 需要导入模块: import slacker [as 别名]
# 或者: from slacker import Slacker [as 别名]
def list_slack():
"""List channels & users in slack."""
try:
token = os.environ['SLACK_TOKEN']
slack = Slacker(token)
# Get channel list
response = slack.channels.list()
channels = response.body['channels']
for channel in channels:
print(channel['id'], channel['name'])
# if not channel['is_archived']:
# slack.channels.join(channel['name'])
print()
# Get users list
response = slack.users.list()
users = response.body['members']
for user in users:
if not user['deleted']:
print(user['id'], user['name'], user['is_admin'], user[
'is_owner'])
print()
except KeyError as ex:
print('Environment variable %s not set.' % str(ex))
示例7: init
# 需要导入模块: import slacker [as 别名]
# 或者: from slacker import Slacker [as 别名]
def init(user_token=None, team=None):
"""
This function must be called prior to any use of the Slack API.
"""
user_token = user_token
loaded_token = token.load(team=team)
must_save_token = False
if user_token:
if user_token != loaded_token:
must_save_token = True
else:
user_token = loaded_token
if not user_token:
user_token = token.ask(team=team)
must_save_token = True
# Initialize slacker client globally
Slacker.INSTANCE = slacker.Slacker(user_token)
if must_save_token:
save_token(user_token, team=team)
示例8: __send_slack_check
# 需要导入模块: import slacker [as 别名]
# 或者: from slacker import Slacker [as 别名]
def __send_slack_check(self, check):
token = self.__get_token()
if not token:
self.logger.error('[SLACK] token is not configured on the slack module. skipping slack messages.')
return
slack = Slacker(token)
# title = '{date_num} {time_secs} [node:`%s`][addr:`%s`] Check `%s` is going %s' % (gossiper.display_name, gossiper.addr, check['name'], check['state'])
content = check['output']
channel = self.get_parameter('channel')
colors = {'ok': 'good', 'warning': 'warning', 'critical': 'danger'}
node_name = '%s (%s)' % (gossiper.name, gossiper.addr)
if gossiper.display_name:
node_name = '%s [%s]' % (node_name, gossiper.display_name)
attachment = {"pretext": ' ', "text": content, 'color': colors.get(check['state'], '#764FA5'), 'author_name': node_name, 'footer': 'Send by OpsBro on %s' % node_name, 'ts': int(time.time())}
fields = [
{"title": "Node", "value": node_name, "short": True},
{"title": "Check", "value": check['name'], "short": True},
]
attachment['fields'] = fields
attachments = [attachment]
self.__do_send_message(slack, attachments, channel)
示例9: __send_slack_group
# 需要导入模块: import slacker [as 别名]
# 或者: from slacker import Slacker [as 别名]
def __send_slack_group(self, group, group_modification):
token = self.__get_token()
if not token:
self.logger.error('[SLACK] token is not configured on the slack module. skipping slack messages.')
return
slack = Slacker(token)
# title = '{date_num} {time_secs} [node:`%s`][addr:`%s`] Check `%s` is going %s' % (gossiper.display_name, gossiper.addr, check['name'], check['state'])
content = 'The group %s was %s' % (group, group_modification)
channel = self.get_parameter('channel')
colors = {'remove': 'danger', 'add': 'good'}
node_name = '%s (%s)' % (gossiper.name, gossiper.addr)
if gossiper.display_name:
node_name = '%s [%s]' % (node_name, gossiper.display_name)
attachment = {"pretext": ' ', "text": content, 'color': colors.get(group_modification, '#764FA5'), 'author_name': node_name, 'footer': 'Send by OpsBro on %s' % node_name, 'ts': int(time.time())}
fields = [
{"title": "Node", "value": node_name, "short": True},
{"title": "Group:%s" % group_modification, "value": group, "short": True},
]
attachment['fields'] = fields
attachments = [attachment]
self.__do_send_message(slack, attachments, channel)
示例10: __send_slack_compliance
# 需要导入模块: import slacker [as 别名]
# 或者: from slacker import Slacker [as 别名]
def __send_slack_compliance(self, compliance):
token = self.__get_token()
if not token:
self.logger.error('[SLACK] token is not configured on the slack module. skipping slack messages.')
return
slack = Slacker(token)
# title = '{date_num} {time_secs} [node:`%s`][addr:`%s`] Check `%s` is going %s' % (gossiper.display_name, gossiper.addr, check['name'], check['state'])
content = 'The compliance %s changed from %s to %s' % (compliance.get_name(), compliance.get_state(), compliance.get_old_state())
channel = self.get_parameter('channel')
state_color = COMPLIANCE_STATE_COLORS.get(compliance.get_state())
color = {'magenta': '#221220', 'green': 'good', 'cyan': '#cde6ff', 'red': 'danger', 'grey': '#cccccc'}.get(state_color, '#cccccc')
node_name = '%s (%s)' % (gossiper.name, gossiper.addr)
if gossiper.display_name:
node_name = '%s [%s]' % (node_name, gossiper.display_name)
attachment = {"pretext": ' ', "text": content, 'color': color, 'author_name': node_name, 'footer': 'Send by OpsBro on %s' % node_name, 'ts': int(time.time())}
fields = [
{"title": "Node", "value": node_name, "short": True},
{"title": "Compliance:%s" % compliance.get_name(), "value": compliance.get_state(), "short": True},
]
attachment['fields'] = fields
attachments = [attachment]
self.__do_send_message(slack, attachments, channel)
示例11: post_to_slack
# 需要导入模块: import slacker [as 别名]
# 或者: from slacker import Slacker [as 别名]
def post_to_slack(channel, message):
if not SLACK_TOKEN:
logger.info(message)
return None
slack = Slacker(SLACK_TOKEN)
response = slack.chat.post_message(
channel, message, as_user=False, icon_emoji=":beaker:", username="Beaker (engineering-minion)",
)
return response.raw
示例12: connect
# 需要导入模块: import slacker [as 别名]
# 或者: from slacker import Slacker [as 别名]
def connect(self):
logger.info("Connecting...")
self._slacker = Slacker(self._SLACK_BOT_TOKEN)
self._slackSocket = SlackSocket(self._SLACK_BOT_TOKEN, translate=False)
self._BOT_ID = self._slacker.auth.test().body["user_id"]
self._registrations = {} # our dictionary of event_types to a list of callbacks
logger.info(f"Connected. Set bot id to {self._BOT_ID} with name {self.helper_user_id_to_user_name(self._BOT_ID)}")
示例13: _is_admin
# 需要导入模块: import slacker [as 别名]
# 或者: from slacker import Slacker [as 别名]
def _is_admin(user):
"""
ユーザーがSlackのAdminかどうかを返す
:param user: SlackのユーザーID
"""
slack = Slacker(settings.API_TOKEN)
user_info = slack.users.info(user)
return user_info.body['user']['is_admin']
示例14: random_command
# 需要导入模块: import slacker [as 别名]
# 或者: from slacker import Slacker [as 别名]
def random_command(message, subcommand=None):
"""
チャンネルにいるメンバーからランダムに一人を選んで返す
- https://github.com/os/slacker
- https://api.slack.com/methods/channels.info
- https://api.slack.com/methods/users.getPresence
- https://api.slack.com/methods/users.info
"""
if subcommand == 'help':
botsend(message, '''- `$random`: チャンネルにいるメンバーからランダムに一人を選ぶ
- `$random active`: チャンネルにいるactiveなメンバーからランダムに一人を選ぶ
''')
return
# チャンネルのメンバー一覧を取得
channel = message.body['channel']
webapi = slacker.Slacker(settings.API_TOKEN)
cinfo = webapi.channels.info(channel)
members = cinfo.body['channel']['members']
# bot の id は除く
bot_id = message._client.login_data['self']['id']
members.remove(bot_id)
member_id = None
while not member_id:
# メンバー一覧からランダムに選んで返す
member_id = random.choice(members)
if subcommand == 'active':
# active が指定されている場合は presence を確認する
presence = webapi.users.get_presence(member_id)
if presence.body['presence'] == 'away':
members.remove(member_id)
member_id = None
user_info = webapi.users.info(member_id)
name = user_info.body['user']['name']
botsend(message, '{} さん、君に決めた!'.format(name))
示例15: _get_user_name
# 需要导入模块: import slacker [as 别名]
# 或者: from slacker import Slacker [as 别名]
def _get_user_name(user_id):
"""
指定された Slack の user_id に対応する username を返す
Slacker で users.list API を呼び出す
- https://github.com/os/slacker
- https://api.slack.com/methods/users.info
"""
webapi = slacker.Slacker(settings.API_TOKEN)
response = webapi.users.info(user_id)
if response.body['ok']:
return response.body['user']['name']
else:
return ''