Exemplo n.º 1
0
def init(user_token=None, team=None):
    """
    This function must be called prior to any use of the Slack API.
    """
    user_token = user_token or token.load(team=team)

    # Always test token
    try:
        slacker.Slacker(user_token).api.test()
    except slacker.Error:
        raise errors.InvalidSlackToken(user_token)

    # Initialize slacker client globally
    Slacker.INSTANCE = slacker.Slacker(user_token)

    # Save token
    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 'dnd:info' scope."
        raise errors.InvalidSlackToken(message)

    token.save(user_token, team)
Exemplo n.º 2
0
    def __init__(self,
                 token,
                 timeout=None,
                 bot_icon=None,
                 bot_emoji=None,
                 connect=True,
                 rtm_start_args=None):
        self.token = token
        self.bot_icon = bot_icon
        self.bot_emoji = bot_emoji
        self.username = None
        self.domain = None
        self.login_data = None
        self.websocket = None
        self.users = {}
        self.channels = {}
        self.connected = False
        self.rtm_start_args = rtm_start_args

        if timeout is None:
            self.webapi = slacker.Slacker(self.token)
        else:
            self.webapi = slacker.Slacker(self.token, timeout=timeout)

        if connect:
            self.rtm_connect()
Exemplo n.º 3
0
def deferred_process_album_details(album_id, channel='', slack_token=None):
    try:
        album, artist, url = bandcamp.scrape_bandcamp_album_details_from_id(
            album_id)
        albums_model.add_to_albums(album_id,
                                   artist,
                                   album,
                                   url,
                                   channel=channel)
        deferred_process_album_cover.delay(album_id)
        deferred_process_album_tags.delay(album_id)
    except DatabaseError as e:
        print(f'[db]: failed to add album details for {album_id}')
        print(f'[db]: {e}')
        if channel and slack_token:
            slacker.Slacker(slack_token) \
                .chat \
                .post_message(f'{channel}', f':red_circle: failed to add album details')
    except (TypeError, ValueError):
        pass
    else:
        print(f'[scraper]: processed album details for {album_id}')
        if channel and slack_token:
            slacker.Slacker(slack_token) \
                .chat \
                .post_message(f'{channel}',
                              f':full_moon_with_face: processed album details for "*{album}*" by *{artist}*')
Exemplo n.º 4
0
def _handle_remove(
        team,  # type: SlackWorkspaceEmojiWatcher
        event,  # type: typing.Dict
):  # type: (...) -> slacker.Response
    emoji_names = event.get(
        'names', [])  # type: typing.Optional[typing.List[typing.Text]]

    if not isinstance(emoji_names, list):
        raise RequestPayloadValidationError(
            message=gettext(_UNRECOGNIZED_JSON_BODY_ERR +
                            ' (unrecognized event names)'), )

    if not emoji_names:
        return None

    too_many = len(emoji_names) > _EMOJIS_MAX_LEN
    emoji_names = emoji_names[:_EMOJIS_MAX_LEN]

    if any((not isinstance(emoji_name, str) for emoji_name in emoji_names[:_EMOJIS_MAX_LEN])) \
            or any((len(emoji_name) > _EMOJI_NAME_MAX_LEN for emoji_name in emoji_names)):
        raise RequestPayloadValidationError(
            message=gettext(_UNRECOGNIZED_JSON_BODY_ERR +
                            ' (unrecognized event names)'), )

    return slacker.Slacker(team.access_token).chat.post_message(
        team.channel_id,
        html.escape(
            gettext('removed {}{}').format(
                ', '.join('`:{}:`'.format(name)
                          for name in emoji_names[:_EMOJIS_MAX_LEN]),
                '...' if too_many else '')),
        as_user=_as_user(team),
        icon_emoji=_icon_emoji(team),
    )
def main(args):
    now = time.time()
    oldest, latest = timerange(now, args.daysback)
    print('Running on %s' % format_day(now))
    print('Digesting messages between %s and %s' %
          (format_time(oldest), format_time(latest)))

    reactions = args.conf['slack']['reactions']
    joins_leaves = args.conf['slack']['joins_leaves']
    print('Include reactions: %s' % reactions)
    print('Include joins: %s' % joins_leaves)

    slack = slacker.Slacker(args.conf['slack']['token'])
    channels, sendTo = filter_channels(slack, args.conf)
    users = get_usernames(slack)

    digests = get_digests(objectify(args.conf['slack']), slack, channels,
                          users, oldest, latest)
    for channel, digest in digests.items():
        if digest and sendTo[channel]:
            sendto = sendTo[channel]
            if not args.dryrun:
                send_digest(args.conf, channel, sendto, digest, oldest)
            else:
                print(channel, sendto, len(digest))
Exemplo n.º 6
0
def deferred_attribute_album_url(album_id, slack_token):
    try:
        album = albums_model.get_album_details(album_id)
        album_url = album.album_url
        slack = slacker.Slacker(slack_token)
        response = slack.search.all(album_url)
        if response.successful:
            for match in response.body['messages']['matches']:
                user = match['user']
                if user:
                    albums_model.add_user_to_album(album_id, user)
                    print(f'[scraper]: added {user} to {album_id}')
                elif 'previous' in match and album_url in match['previous'][
                        'text']:
                    albums_model.add_user_to_album(album_id,
                                                   match['previous']['user'])
                    print(
                        f'[scraper]: added {match["previous"]["user"]} to {album_id}'
                    )
                elif 'previous2' in match and album_url in match['previous2'][
                        'text']:
                    albums_model.add_user_to_album(album_id,
                                                   match['previous2']['user'])
                    print(
                        f'[scraper]: added {match["previous2"]["user"]} to {album_id}'
                    )
    except (DatabaseError, KeyError) as e:
        print('[db]: failed to attribute users to album')
        print(f'[db]: {e}')
Exemplo n.º 7
0
Arquivo: mann.py Projeto: dheavy/mann
 def __set_slack_logger(self):
     if not hasattr(self, 'slacker'):
         try:
             self.slacker = slacker.Slacker(
                 self.config.get('slack', {}).get('key', ''))
         except Exception as e:
             self.file(e, error=True)
Exemplo n.º 8
0
    def __init__(self,
                 api_key,
                 channel,
                 stack_trace=True,
                 username=None,
                 icon_url=None,
                 icon_emoji=None,
                 fail_silent=False,
                 link_names=True):
        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
        self.channel = channel
        self.link_names = link_names

        if not (self.channel.startswith('#') or self.channel.startswith('@')):
            raise ValueError(
                'Invalid channel "{}". '
                'It must start with "#" for a channel or "@" for a private message.'
                .format(self.channel))
Exemplo n.º 9
0
    def __init__(self,
                 debug=False,
                 verbose=False,
                 slackbot_injected=None,
                 slacker_injected=None):
        self.debug = debug
        self.verbose = verbose
        self.config = config.Config()
        slackbot_token = os.getenv(self.config.slackbot_api_token_env_varname)
        api_token = os.getenv(self.config.api_token_env_varname)

        self.slackbot = slackbot_injected or slackbot.Slackbot(
            config.SLACK_NAME, token=slackbot_token)

        self.logger = logging.getLogger(__name__)
        utils.set_up_logger(self.logger,
                            log_level_env_var='DESTALINATOR_LOG_LEVEL',
                            log_to_slack_env_var='DESTALINATOR_LOG_TO_CHANNEL',
                            log_channel=self.config.log_channel,
                            slackbot=self.slackbot)

        self.destalinator_activated = False
        if os.getenv(self.config.destalinator_activated_env_varname):
            self.destalinator_activated = True
        self.logger.debug("destalinator_activated is %s",
                          self.destalinator_activated)

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

        self.ds = destalinator.Destalinator(
            slacker=self.slacker,
            slackbot=self.slackbot,
            activated=self.destalinator_activated,
            logger=self.logger)
Exemplo n.º 10
0
def issue_flex_day(self, note=None, user_id=None):
    '''
    issues a flex day for the current day

    ###Args:
    - **note**:optional string to add to the note field
    - **user_id**: optional, if supplied, only issue flex day to this user
    '''

    if user_id:
        users = Profile.objects.filter(pk=user_id)
    else:
        users = Profile.objects.filter(is_active=True)

    today = arrow.utcnow().date()

    slack = slacker.Slacker(os.environ.get("LUCILLE_BOT_TOKEN"))

    for user in users:
        # issue flex day
        flex_day, created = DayOff.objects.get_or_create(
            user=user,
            date=today,
            type='flex',
            amount=1,
            note="Automatically issued from 'issue_flex_day'. {}".format(note),
        )

        logger.info("Flex day added for %s on %s", user, today)
        slack.chat.post_message(
            user.slack_user,
            ":bowtie: added a *{}*. {}".format(flex_day, note),
            as_user=True,
        )
Exemplo n.º 11
0
    def __init__(self, api_key, channel, stack_trace=True, username='******', 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)
Exemplo n.º 12
0
 def send_slack_message(self, output):
     print('sending slack message')
     slack = slacker.Slacker(self.secrets['i3']['slack']['token'])
     slack.chat.post_message(self.channel,
                             output,
                             username=self.name,
                             icon_url=self.pic)
Exemplo n.º 13
0
    def __init__(self, token, verbose=False, request_pause_period=0.5):
        self.slack = slacker.Slacker(token)
        self.verbose = verbose

        self.request_pause_period = 0.5

        self._invite_link = None
Exemplo n.º 14
0
def connect(api_token=None):
    if api_token is None:
        import slackbot_settings as ss
        api_token = ss.API_TOKEN

    herm = slacker.Slacker(api_token)

    return herm
Exemplo n.º 15
0
    def __init__(self, team_token=None, bot_token=None):
        '''
        Creates the necessary slacker sessions, using env vars if kwargs are not supplied
        '''
        self._logger = get_task_logger(__name__)

        self._logger.info("Created Slack Service instance")

        if bot_token is None: bot_token = os.environ.get("SLACK_APP_BOT_TOKEN")
        if team_token is None:
            team_token = os.environ.get("SLACK_APP_TEAM_TOKEN")

        self._slack_bot = slacker.Slacker(bot_token)
        self._slack_team = slacker.Slacker(team_token)

        # get user info for the slack bot
        self._bot_info = self._slack_bot.auth.test().body
Exemplo n.º 16
0
Arquivo: slack.py Projeto: zc/cimaa
 def __init__(self, config):
     self.token = config['token']
     self.channel = config.get('channel') or 'general'
     self.target = config.get('target') or ''
     if not self.channel[0] == '#':
         self.channel = '#' + self.channel
     self.name = 'cimaa'
     self.slack = slacker.Slacker(self.token)
def post_msg_to_slack(slack_secrets, message_otd, channel_otd):
    """ use Kip's slackbot to post whatever given message to a specific channel in Chez Dungeness """
    with open(slack_secrets) as f:
        creds = json.load(f)
    token = creds["botuserOAuthAccessToken"]
    slack = slacker.Slacker(token)
    # Send a message to #general channel
    slack.chat.post_message(channel_otd, message_otd)
Exemplo n.º 18
0
    def __init__(self, token):
        self.slack = slacker.Slacker(token=token)  # todo set retry limit here

        # Check the token is valid
        try:
            self.slack.auth.test()
        except slacker.Error:
            raise AuthenticationError('Unable to authenticate API token.')
Exemplo n.º 19
0
def get_client(token: str,
               session: Optional[Session] = None) -> slacker.Slacker:
    if not token:
        raise Exception(f'No token was provided')
    if not token.startswith('xoxp-'):
        raise Exception(
            f'The provided token is invalid since it not a user token, please use a user token instead'
        )
    return slacker.Slacker(token, session=session)
Exemplo n.º 20
0
 def __init__(self, *args, **kwargs):
     self.websocket_options = kwargs.pop("websocket_options", {})
     self.websocket_options.setdefault("timeout", 5.0)
     self.reconnect_options = kwargs.pop("reconnect_options", {})
     self.reconnect_options.setdefault("retry", 5)
     self.reconnect_options.setdefault("delay", 15.0)
     super(SlackClient, self).__init__(*args, **kwargs)
     self.session = requests.session()
     self.webapi = slacker.Slacker(self.token, session=self.session)
Exemplo n.º 21
0
 def send_message(self, channel, message, attachments=None):
     slacker.Slacker(self.token).chat.post_message(
         channel,
         message,
         username=self.username,
         icon_url=self.bot_icon,
         icon_emoji=self.bot_emoji,
         attachments=attachments,
         as_user=True)
Exemplo n.º 22
0
def init(user_token=None, team=None):
    """
    This function must be called prior to any use of the Slack API.
    """
    user_token = user_token or token.load(team=team)

    # Always test token
    try:
        slacker.Slacker(user_token).api.test()
    except slacker.Error:
        sys.stderr.write("Invalid Slack token: '{}'".format(user_token))
        sys.exit(1)

    # Initialize slacker client globally
    Slacker.INSTANCE = slacker.Slacker(user_token)

    # Save token
    team = team or client().team.info().body["team"]["domain"]
    token.save(user_token, team)
Exemplo n.º 23
0
    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()
Exemplo n.º 24
0
    def slackpost(self, status):
        if self.slack_token:
            slack = slacker.Slacker(self.slack_token)

            message = {
                'channel': settings.SLACK_CHANNEL['name'],
                'username': settings.SLACK_USERNAME,
                'text': '',
            }

            cve_sync_status = 'In-sync'
            if self.is_cve_updated():
                cve_sync_status = 'Out-of-sync'
                status = 1

            # POST to Slack
            if status == 0 or status == 1:
                # Success or Warning
                response = slack.files.upload(
                    self.output_file,
                    title='Association Results',
                    filename='results.txt',
                    channels=[settings.SLACK_CHANNEL['id']])

                color = 'good'

                if status == 1:
                    color = 'warning'

                fields = list()
                fields.append({
                    'title': 'Outcome',
                    'value': 'Success',
                    'short': True
                })
                fields.append({
                    'title': 'CVE Sync. Status',
                    'value': cve_sync_status,
                    'short': True
                })

                message['attachments'] = json.dumps([{
                    'fallback': 'Attack Surface Nightly Run',
                    'title': 'Attack Surface Nightly Run',
                    'color': color,
                    'fields': fields
                }])

                slack.chat.post_message(**message)
            elif status == 2:
                # Error
                print('[SLACK] Error')
                pass
        else:
            print('Slack API token was not appropirately initialized')
Exemplo n.º 25
0
 def __init__(self, api_key: str, channel: str, username: str = DEFAULT_USERNAME,
              emoji: str = DEFAULT_EMOJI, ping_users: Optional[List[str]] = None,
              **kwargs: Any):
     super().__init__(**kwargs)
     self.api_key = str(api_key)
     self.channel = self._parse_channel(channel)
     self.username = self._parse_username(username)
     self.emoji = self._parse_emoji(emoji)
     self.ping_users = self._parse_ping_users(ping_users)
     self._user_cache = dict()  # type: Dict[str, str]
     self._slacker = slacker.Slacker(api_key)
Exemplo n.º 26
0
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
Exemplo n.º 27
0
    def _init_connection(self):
        self.slack = slacker.Slacker(self.apikey)
        try:
            r = self.slack.channels.list()
        except slacker.Error as e:
            if e.message == 'invalid_auth':
                raise SlackardFatalError('Invalid API key')
            raise
        except Exception as e:
            raise SlackardNonFatalError(e.message)

        c_map = {c['name']: c['id'] for c in r.body['channels']}
        self.chan_id = c_map[self.channel]
Exemplo n.º 28
0
    def __init__(self, debug=False, verbose=False):
        self.debug = debug
        self.verbose = verbose
        self.config = config.Config()
        slackbot_token = os.getenv(self.config.slackbot_api_token_env_varname)
        api_token = os.getenv(self.config.api_token_env_varname)

        self.sb = slackbot.Slackbot(config.SLACK_NAME, token=slackbot_token)

        self.slacker = slacker.Slacker(config.SLACK_NAME, token=api_token)

        self.ds = destalinator.Destalinator(slacker=self.slacker,
                                            slackbot=self.sb)
Exemplo n.º 29
0
    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)
def main(args):
    slack_up = False
    while not slack_up:
        list_of_proc = [psutil.Process(p).name() for p in psutil.pids()]
        slack_up = "slack.exe" in list_of_proc
        time.sleep(10)
    twitch_tracker.stream_status = get_followed_streamers()
    bot_key = csv_to_dict(
        "C:\\Users\\User\\Documents\\PythonScripts\\config.csv",
        "slack")["key"]
    twitch_tracker.slack_bot = slacker.Slacker(bot_key)
    twitch_tracker.sched_obj = sched.scheduler(time.time, time.sleep)
    ping_streams()