Python slacker.Slacker() Examples

The following are 30 code examples of slacker.Slacker(). 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: slack.py    From slack-cli with MIT License 6 votes vote down vote up
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) 
Example #2
Source File: gadmin.py    From pyconjpbot with MIT License 6 votes vote down vote up
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) 
Example #3
Source File: module.py    From opsbro with MIT License 6 votes vote down vote up
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) 
Example #4
Source File: module.py    From opsbro with MIT License 6 votes vote down vote up
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) 
Example #5
Source File: module.py    From opsbro with MIT License 6 votes vote down vote up
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) 
Example #6
Source File: list.py    From slacker with Apache License 2.0 6 votes vote down vote up
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)) 
Example #7
Source File: iam-notify-slack.py    From aws-iam-slack-notifer with MIT License 6 votes vote down vote up
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 
Example #8
Source File: master_post.py    From CodeScraper with MIT License 6 votes vote down vote up
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()) 
Example #9
Source File: master_post.py    From CodeScraper with MIT License 6 votes vote down vote up
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
#    ) 
Example #10
Source File: events.py    From devopsloft with GNU General Public License v3.0 6 votes vote down vote up
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) 
Example #11
Source File: __init__.py    From slacker-cli with MIT License 5 votes vote down vote up
def post_message(
    token, channel, message, name, as_user, icon, as_slackbot, team, **kwargs
):
    if as_slackbot:
        post_message_as_slackbot(team, token, channel, message)
    else:
        slack = Slacker(token)
        slack.chat.post_message(
            channel, message, username=name, as_user=as_user, icon_emoji=icon, **kwargs
        ) 
Example #12
Source File: slack.py    From slack-cli with MIT License 5 votes vote down vote up
def client():
    return Slacker.instance() 
Example #13
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 #14
Source File: slack_auto_export.py    From slack-auto-export with MIT License 5 votes vote down vote up
def __init__(self, token, verbose=False):
        self.slack = slacker.Slacker(token)
        self.verbose = verbose 
Example #15
Source File: core.py    From butterfield with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(self, token, daemons=None, **kwargs):

        self.slack = Slacker(token)
        self.uuid = hashlib.sha1(token.encode("utf-8")).hexdigest()

        self.handlers = defaultdict(list)
        self.daemons = daemons or []
        self.environment = None
        self.params = kwargs 
Example #16
Source File: utils.py    From slack_bot with MIT License 5 votes vote down vote up
def upload_image(canvas_or_url, image_type, app=None, filename=None,
                 tmp_dir=None, deleted=False):
    here = os.path.abspath(os.path.dirname(__file__))
    if tmp_dir is None:
        tmp_dir = os.path.join(here, 'data')
    match = CANVAS_REGEX.search(canvas_or_url)
    if match:
        imgstr = match.group(1)
        if filename is None:
            filename = os.path.join(tmp_dir, '{}.png'.format(imgstr[:20]))
        output = open(filename, 'wb')
        output.write(imgstr.decode('base64'))
        output.close()
    else:
        r = requests.get(canvas_or_url, stream=True)
        if filename is None:
            filename = canvas_or_url.rsplit('/', 1)[1]
        with open(filename, 'wb') as f:
            r.raw.decode_content = True
            shutil.copyfileobj(r.raw, f)

    if image_type == 'thumb':
        image_type = 'thumb_360'
    if app is None:
        token = 'xoxp-4231087425-4231087427-4463321974-03a74ae'
    else:
        token = app.config.get('SLACK_CHAT_TOKEN')
    slack = Slacker(token)
    ret = slack.files.upload(filename)
    if deleted:
        os.remove(filename)
    try:
        return ret.body['file'][image_type]
    except KeyError:
        return ret.body['file']['url'] 
Example #17
Source File: __init__.py    From slacker-cli with MIT License 5 votes vote down vote up
def get_im_id(token, username):
    slack = Slacker(token)
    members = slack.users.list().body["members"]
    user_id = get_item_id_by_name(members, username)
    ims = slack.im.list().body["ims"]
    return get_item_by_key_value(ims, key="user", value=user_id).get("id") 
Example #18
Source File: __init__.py    From slacker-cli with MIT License 5 votes vote down vote up
def get_channel_id(token, channel_name):
    slack = Slacker(token)
    channels = slack.channels.list().body["channels"]
    return get_item_id_by_name(channels, channel_name) 
Example #19
Source File: __init__.py    From slacker-cli with MIT License 5 votes vote down vote up
def upload_file(token, channel_name, file_name):
    """ upload file to a channel """

    slack = Slacker(token)

    slack.files.upload(file_name, channels=channel_name) 
Example #20
Source File: slack.py    From AutoTriageBot with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def postMessage(message: str, channel: str=config.channel, attachments: List=[]) -> Optional[Mapping]:
    """ Post a message to the specified slack channel """
    if secrets.slackOauth:
        slack = Slacker(secrets.slackOauth)
        if channel:
            resp = slack.chat.post_message(channel, message, attachments=attachments)
            return resp.body
    return None 
Example #21
Source File: executor.py    From destalinator with Apache License 2.0 5 votes vote down vote up
def __init__(self, slackbot_injected=None, slacker_injected=None):
        self.slackbot = slackbot_injected or slackbot.Slackbot(self.config.slack_name, token=self.config.sb_token)
        set_up_slack_logger(self.slackbot)

        self.logger.debug("activated is %s", self.config.activated)

        self.slacker = slacker_injected or slacker.Slacker(self.config.slack_name, token=self.config.api_token)

        self.ds = destalinator.Destalinator(slacker=self.slacker,
                                            slackbot=self.slackbot,
                                            activated=self.config.activated) 
Example #22
Source File: mocks.py    From destalinator with Apache License 2.0 5 votes vote down vote up
def mocked_slacker_object(channels_list=None, users_list=None, messages_list=None, emoji_list=None):
    slacker_obj = slacker.Slacker(get_config().slack_name, token='token', init=False)

    slacker_obj.get_all_channel_objects = mock.MagicMock(return_value=channels_list or [])
    slacker_obj.get_channels()

    slacker_obj.get_all_user_objects = mock.MagicMock(return_value=users_list or [])
    slacker_obj.get_users()

    slacker_obj.get_messages_in_time_range = mock.MagicMock(return_value=messages_list or [])
    slacker_obj.get_emojis = mock.MagicMock(return_value=emoji_list or [])

    return slacker_obj 
Example #23
Source File: gmail2slack.py    From gmail2slack with MIT License 5 votes vote down vote up
def __init__(self, apikey):
        self.slack = Slacker(apikey) 
Example #24
Source File: slack.py    From slack-cli with MIT License 5 votes vote down vote up
def instance(cls):
        if cls.INSTANCE is None:
            # This is not supposed to happen
            raise ValueError("Slacker client token was not undefined")
        return cls.INSTANCE 
Example #25
Source File: __init__.py    From slacker_log_handler with Apache License 2.0 5 votes vote down vote up
def __init__(self, api_key, channel, stack_trace=True, username='Python logger', icon_url=None, icon_emoji=None,
                 fail_silent=False, ping_users=None, ping_level=None):
        Handler.__init__(self)
        self.formatter = NoStacktraceFormatter()

        self.stack_trace = stack_trace
        self.fail_silent = fail_silent

        self.slacker = slacker.Slacker(api_key)

        self.username = username
        self.icon_url = icon_url
        self.icon_emoji = icon_emoji if (icon_emoji or icon_url) else DEFAULT_EMOJI
        self.channel = channel
        if not self.channel.startswith('#') and not self.channel.startswith('@'):
            self.channel = '#' + self.channel

        self.ping_level = ping_level
        self.ping_users = []

        if ping_users:
            user_list = self.slacker.users.list().body['members']

            for ping_user in ping_users:
                ping_user = ping_user.lstrip('@')

                for user in user_list:
                    if user['name'] == ping_user:
                        self.ping_users.append(user['id'])
                        break
                else:
                    raise RuntimeError('User not found in Slack users list: %s' % ping_user) 
Example #26
Source File: __init__.py    From slouch with MIT License 5 votes vote down vote up
def __init__(self, slack_token, config):
        """
        Do not override this to perform implementation-specific setup;
        use :func:`prepare_bot` instead.

        No IO will be done until :func:`run_forever` is called (unless :func:`prepare_bot`
        is overridden to perform some).

        :param slack_token: a Slack api token.
        :param config: an arbitrary dictionary for implementation-specific configuration.
          The same object is stored as the `config` attribute and passed to prepare methods.
        """
        #: the same config dictionary passed to init.
        self.config = config
        self._current_message_id = 0

        #: a Logger (``logging.getLogger(__name__)``).
        self.log = logging.getLogger(__name__)

        # This doesn't perform IO.
        #: a `Slacker <https://github.com/os/slacker>`__ instance created with `slack_token`.
        self.slack = Slacker(slack_token)

        #: the bot's Slack id.
        #: Not available until :func:`prepare_connection`.
        self.id = None

        #: the bot's Slack name.
        #: Not available until :func:`prepare_connection`.
        self.name = None

        #: the bot's Slack mention, equal to ``<@%s> % self.id`` .
        #: Not available until :func:`prepare_connection`.
        self.my_mention = None

        #: a `WebSocketApp <https://github.com/liris/websocket-client>`__ instance.
        #: Not available until :func:`prepare_connection`.
        self.ws = None

        self.prepare_bot(self.config) 
Example #27
Source File: communication_utils.py    From seqr with GNU Affero General Public License v3.0 5 votes vote down vote up
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 
Example #28
Source File: post.py    From slacker with Apache License 2.0 5 votes vote down vote up
def post_slack():
    """Post slack message."""
    try:
        token = os.environ['SLACK_TOKEN']
        slack = Slacker(token)

        obj = slack.chat.post_message('#general', 'Hello fellow slackers!')
        print(obj.successful, obj.__dict__['body']['channel'], obj.__dict__[
            'body']['ts'])
    except KeyError as ex:
        print('Environment variable %s not set.' % str(ex)) 
Example #29
Source File: slack_export.py    From slack-export with MIT License 5 votes vote down vote up
def doTestAuth():
    testAuth = slack.auth.test().body
    teamName = testAuth['team']
    currentUser = testAuth['user']
    print(u"Successfully authenticated for team {0} and user {1} ".format(teamName, currentUser))
    return testAuth

# Since Slacker does not Cache.. populate some reused lists 
Example #30
Source File: slack.py    From openduty with MIT License 5 votes vote down vote up
def notify(self, notification):
        slack = Slacker(self.__config['apikey'])
        response = slack.chat.post_message(notification.user_to_notify.profile.slack_room_name, notification.message,
                                           username="Openduty", icon_url="https://slack.global.ssl.fastly.net/1937/img/services/pagerduty_48.png")
        if not response.error:
            print "Slack message sent"
        else:
            print "Failed to send Slack message"