Python slackclient.SlackClient() Examples

The following are 30 code examples of slackclient.SlackClient(). 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 slackclient , or try the search function .
Example #1
Source File: base.py    From bender with MIT License 6 votes vote down vote up
def __init__(self, **kwargs):
        self.slack_client = SlackClient(kwargs.get("slack_token"))
        self.bot = kwargs.get("bot_name")
        self.channel = kwargs.get("channel")
        self.grammar = kwargs.get("grammar")
        self.version = kwargs.get("version")
        self.working_dir = kwargs.get("working_dir")
        self.slack_unread = kwargs.get("slack_unread")
        self.users = self._call_api("users.list", presence=0)
        self.mention = kwargs.get("mention")
        if self.mention:
            self.bot_id = self._filter(self.users['members'], "id", "name", self.bot)
            fail_unless(self.bot_id, "Unable to find bot name '{}'".format(self.bot))
        if not self.grammar and not self.mention:
            fail_unless(False, "At least one parameter is required 'grammar', 'mention'.")

        self.channel_id, self.channel_type = self._get_channel_group_info()
        fail_unless(self.channel_id, "Unable to find channel/group '{}'".format(self.channel)) 
Example #2
Source File: logger.py    From pytorch-asr with GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, env="main"):
        super().__init__()
        self.env = env
        self.slack_token = os.getenv("SLACK_API_TOKEN")
        self.slack_user = os.getenv("SLACK_API_USER")
        if self.slack_token is None or self.slack_user is None:
            raise KeyError

        from slackclient import SlackClient
        self.sc = SlackClient(self.slack_token)

        # getting user id
        ans = self.sc.api_call("users.list")
        users = [u['id'] for u in ans['members'] if u['name'] == self.slack_user]
        # open DM channel to the users
        ans = self.sc.api_call("conversations.open", users=users)
        self.channel = ans['channel']['id'] 
Example #3
Source File: vthunting.py    From vthunting with MIT License 6 votes vote down vote up
def send_slack_report(report):
    sc = SlackClient(SLACK_BOT_TOKEN)
    if sc.rtm_connect(with_team_state=False):
        sc.api_call(
            "chat.postMessage",
            icon_emoji=SLACK_EMOJI,
            username=SLACK_BOT_NAME,
            channel=SLACK_CHANNEL,
            text=report
        )
        print("[*] Report have been sent to your Slack channel!")

    else:
        print("[!] Connection failed! Exception traceback printed above.")
        sys.exit()


# Posting to a Telegram channel 
Example #4
Source File: slack.py    From oncall with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def main(config):
    slack_config = config.get('slack')
    if not slack_config:
        logger.error('slack config not found!')
        return

    oauth_access_token = slack_config.get('oauth_access_token')
    if not oauth_access_token:
        logger.error('slack oauth_access_token not found!')
        return

    slack_client = SlackClient(oauth_access_token)
    sync_cycle = config['user_sync'].get('cycle', 60 * 60)

    while True:
        start = time.time()
        sync_action(slack_client)
        duration = time.time() - start
        logger.info('Slack user sync finished, took %ss, sleep for %ss.',
                    duration, sync_cycle - duration)
        sleep(sync_cycle - duration) 
Example #5
Source File: notifications.py    From reapsaw with Apache License 2.0 6 votes vote down vote up
def main():
    """Entrypoint for execution script"""
    args = parse_args()
    token = args.token
    rp = ReportPortalService(args.reportportal, token)
    try:
        launch_id, response = rp.get_launch_info_by_number(args.reportportal_project, args.reportportal_scan, 1)
        message = get_launch_info_msg(args.reportportal, args.reportportal_project, launch_id, response)

        if 'page' in response and response['page']['totalPages'] > 1:
            second_launch_id, second_launch_response = rp.get_launch_info_by_number(args.reportportal_project,
                                                                                    args.reportportal_scan, 2)
            message += "\n" + get_compare_launches_msg(response["content"][0], second_launch_response["content"][0])

        sc = SlackClient(args.slack_token)

        if sc.rtm_connect():
            send_slack_message(sc, channel=args.slack_channel, message=message)
            logger.info("Notification was sent.")
        else:
            logger.critical("Unable to connect to Slack.")
    except Exception as ex:
        print("Error occurred: [{}] {}".format(type(ex), ex))
    finally:
        rp.close_session() 
Example #6
Source File: slack.py    From localslackirc with GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, token: str, cookie: Optional[str], previous_status: Optional[bytes]) -> None:
        self.client = SlackClient(token, cookie)
        self._usercache: Dict[str, User] = {}
        self._usermapcache: Dict[str, User] = {}
        self._usermapcache_keys: List[str]
        self._imcache: Dict[str, str] = {}
        self._channelscache: List[Channel] = []
        self._get_members_cache: Dict[str, Set[str]] = {}
        self._get_members_cache_cursor: Dict[str, Optional[str]] = {}
        self._internalevents: List[SlackEvent] = []
        self._sent_by_self: Set[float] = set()
        self.login_info: Optional[LoginInfo] = None
        if previous_status is None:
            self._status = SlackStatus()
        else:
            self._status = load(json.loads(previous_status), SlackStatus) 
Example #7
Source File: scraper.py    From apartment-finder with MIT License 6 votes vote down vote up
def do_scrape():
    """
    Runs the craigslist scraper, and posts data to slack.
    """

    # Create a slack client.
    sc = SlackClient(settings.SLACK_TOKEN)

    # Get all the results from craigslist.
    all_results = []
    for area in settings.AREAS:
        all_results += scrape_area(area)

    print("{}: Got {} results".format(time.ctime(), len(all_results)))

    # Post each result to slack.
    for result in all_results:
        post_listing_to_slack(sc, result) 
Example #8
Source File: slack.py    From securitybot with Apache License 2.0 6 votes vote down vote up
def _api_call(self, method, **kwargs):
        # type: (str, **Any) -> Dict[str, Any]
        '''
        Performs a _validated_ Slack API call. After performing a normal API
        call using SlackClient, validate that the call returned 'ok'. If not,
        log and error.

        Args:
            method (str): The API endpoint to call.
            **kwargs: Any arguments to pass on to the request.
        Returns:
            (dict): Parsed JSON from the response.
        '''
        response = self._slack.api_call(method, **kwargs)
        if not ('ok' in response and response['ok']):
            if kwargs:
                logging.error('Bad Slack API request on {} with {}'.format(method, kwargs))
            else:
                logging.error('Bad Slack API request on {}'.format(method))
        return response 
Example #9
Source File: slack_wrapper.py    From OTA-Challenge-Bot with MIT License 6 votes vote down vote up
def __init__(self, api_key):
        """
        SlackWrapper constructor.
        Connect to the real-time messaging API and
        load the bot's login data.
        """
        self.api_key = api_key
        self.client = SlackClient(self.api_key)
        self.connected = self.client.rtm_connect(auto_reconnect=True)
        self.server = None
        self.username = None
        self.user_id = None

        if self.connected:
            self.server = self.client.server
            self.username = self.server.username
            self.user_id = self.server.login_data.get("self").get("id") 
Example #10
Source File: run.py    From atis with MIT License 6 votes vote down vote up
def send_slack_message(username, message, channel):
    """Sends a message to your Slack channel.

    Input:
        username (str): Username to send from.
        message (str): The message to send.
        channel (str): Channel to send the message to.
    """
    token = ''  # TODO: put your Slack token here.
    try:
        client = SlackClient(token)
        client.api_call(
            'chat.postMessage',
            channel=channel,
            text=message,
            username=username,
            icon_emoji=':robot_face:')
    except SlackClientError as error:
        print("Couldn't send slack message with exception " + str(error)) 
Example #11
Source File: core.py    From python-rtmbot with MIT License 6 votes vote down vote up
def __init__(self, name=None, slack_client=None, plugin_config=None):
        '''
        A plugin in initialized with:
            - name (str)
            - slack_client - a connected instance of SlackClient - can be used to make API
                calls within the plugins
            - plugin config (dict) - (from the yaml config)
                Values in config:
                - DEBUG (bool) - this will be overridden if debug is set in config for this plugin
        '''
        if name is None:
            self.name = type(self).__name__
        else:
            self.name = name
        if plugin_config is None:
            self.plugin_config = {}
        else:
            self.plugin_config = plugin_config
        self.slack_client = slack_client
        self.jobs = []
        self.debug = self.plugin_config.get('DEBUG', False)
        self.outputs = [] 
Example #12
Source File: general_notification_hook.py    From pandora-plugin with Apache License 2.0 6 votes vote down vote up
def __init__(self, args):
        """
        GeneralNotificationHook constructor.
        :param args: kv pairs of configs
        :type args: dict
        """
        super(GeneralNotificationHook, self).__init__(args)

        self.subject_fail = self.create_subject_message('Failure')
        self.subject_success = self.create_subject_message('Success')
        self.message_slack_fail = self.create_slack_message('Failure')
        self.message_slack_success = self.create_slack_message('Success')
        self.args = args
        self.sc = SlackClient(args['slack_api_token'])
        self.slack_api_params = {
            'channel': args['slack_channel'],
            'username': args['slack_bot'],
            'text': self.message_slack_fail,
            'icon_url': args['slack_avatar_icon_url'],
            'attachments': None,
        } 
Example #13
Source File: monitor.py    From premeStock with MIT License 6 votes vote down vote up
def slackMsg(item,color,link, size):
    # line 101

    if slack_token == "":
        return
    sc = SlackClient(slack_token)

    text = item+"\n"
    text += color+'\n'
    text += size.title()+'\n'
    text += link+'\n'
    text += "Restock!"+'\n'
    text += str(datetime.utcnow().strftime('%H:%M:%S.%f')[:-3])

    sc.api_call(
      "chat.postMessage",
      channel="#test",
      text=text
    ) 
Example #14
Source File: bot.py    From Slack-Python-Onboarding-Tutorial with MIT License 6 votes vote down vote up
def __init__(self):
        super(Bot, self).__init__()
        self.name = "pythonboardingbot"
        self.emoji = ":robot_face:"
        # When we instantiate a new bot object, we can access the app
        # credentials we set earlier in our local development environment.
        self.oauth = {"client_id": os.environ.get("CLIENT_ID"),
                      "client_secret": os.environ.get("CLIENT_SECRET"),
                      # Scopes provide and limit permissions to what our app
                      # can access. It's important to use the most restricted
                      # scope that your app will need.
                      "scope": "bot"}
        self.verification = os.environ.get("VERIFICATION_TOKEN")

        # NOTE: Python-slack requires a client connection to generate
        # an OAuth token. We can connect to the client without authenticating
        # by passing an empty string as a token and then reinstantiating the
        # client with a valid OAuth token once we have one.
        self.client = SlackClient("")
        # We'll use this dictionary to store the state of each message object.
        # In a production environment you'll likely want to store this more
        # persistently in  a database.
        self.messages = {} 
Example #15
Source File: bot.py    From bot with MIT License 5 votes vote down vote up
def __init__(self, token, rasa_nlu):
		logging.basicConfig(level=logging.INFO, format='%(asctime)s %(message)s')

		self.sc = SlackClient(token)
		self.rasa_nlu = rasa_nlu 
Example #16
Source File: slack_bot.py    From MozDef with Mozilla Public License 2.0 5 votes vote down vote up
def __init__(self, api_key, channels, bot_name, notify_welcome):
        self.slack_client = SlackClient(api_key)
        self.channels = channels
        self.bot_name = bot_name
        self.notify_welcome = notify_welcome
        self.load_commands() 
Example #17
Source File: slkmsg.py    From sci-pype with Apache License 2.0 5 votes vote down vote up
def post_message_to_slack(self, channel, message, debug=False):

        slack_response  = {}

        try:

            # SlackHQ Repository for integrating with the Slack API:
            # https://github.com/slackhq/python-slackclient         
            import slackclient

            slack = slackclient.SlackClient(self.m_slack_token)

            slack_response = slack.api_call("chat.postMessage", channel=channel, text=message, username=self.m_bot_name, as_user=True)

            if "error" in slack_response:
                print "\nERROR: Slack API call had an error(" + str(slack_response["error"]) + ")\n"

        except Exception, e:
            err_msg = "Failed to post message to slack with Ex(" + str(e) + ") SlackResponse(" + str(slack_response) + ")"
            print "ERROR: " + str(err_msg)
        # end of try/ex

    # end of post_message_to_slack


# end of SlkMsg 
Example #18
Source File: bot.py    From PantherBot with Mozilla Public License 2.0 5 votes vote down vote up
def create_slack_client(self, token):
        self.SLACK_CLIENT = SlackClient(token)

    # Returns a list of channel IDs searched for by name 
Example #19
Source File: slack_bot.py    From usb-canary with GNU General Public License v3.0 5 votes vote down vote up
def setup(slack, channel):
    logging.debug('Setting up Slack Bot.')
    global slack_client
    slack_client = slackclient.SlackClient(slack['api_key'])
    logging.debug('\tSetting Slack API key.')
    logging.debug('\tSetting Slack channel name.')
    global channel_name
    channel_name = channel 
Example #20
Source File: slackRequestHandler.py    From LED-bot with MIT License 5 votes vote down vote up
def connect(self):
		self.slack_client = SlackClient(self.token)

		try:
			self.slack_client.rtm_connect()
			self.login_data = self.slack_client.server.login_data
			self.id = self.login_data["self"]["id"]
			self.name = self.login_data["self"]["name"]
			self.selector = re.compile("^<@"+self.id+">: (.*)")
		except Exception, e:
			print "failed to connect" 
Example #21
Source File: slack_api.py    From luigi-slack with MIT License 5 votes vote down vote up
def __init__(self, token, username='Luigi-slack Bot', as_user=False, use_private_channels=True):
        self.client = SlackClient(token)
        self._all_channels = self._get_channels(use_private_channels)
        self.username = username
        self.as_user = as_user 
Example #22
Source File: coffeeshop.py    From coffeeshop with MIT License 5 votes vote down vote up
def __init__(self, token = None):

        try:

            connection = SlackClient(token)
            

        except:

            raise NoSlacksForYou("Could not authenticate with this token") 
Example #23
Source File: coffeeshop.py    From coffeeshop with MIT License 5 votes vote down vote up
def __init__(self, token = None):

        try:

            connection = SlackClient(token)
            
        except:

            raise NoSlacksForYou("Could not authenticate with this token") 
Example #24
Source File: slack_server.py    From PyExfil with MIT License 5 votes vote down vote up
def _connect2Slack(self):
        self.slackObj = SlackClient(self.slackToken)

        if self.slackObj.api_call("api.test")['ok'] == True:
            sys.stdout.write("[+]\tConnected to Slack. API is valid!\n")
            return True

        else:
            sys.stderr.write("Unable to connect to slack. Maybe token is wrong?\n")
            sys.stderr.write("%s\n" % self.slackObj.api_call("api.test")['error'])
            sys.exit(1) 
Example #25
Source File: slack_client.py    From PyExfil with MIT License 5 votes vote down vote up
def _connect2Slack(self):
        self.slackObj = SlackClient(self.slackToken)

        if self.slackObj.api_call("api.test")['ok'] == True:
            sys.stdout.write("[+]\tConnected to Slack. API is valid!\n")
            return True

        else:
            sys.stderr.write("Unable to connect to slack. Maybe token is wrong?\n")
            sys.stderr.write("%s\n" % self.slackObj.api_call("api.test")['error'])
            sys.exit(1) 
Example #26
Source File: slack.py    From Arsenal with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, config):
        """
        Initialize the integration.
        """
        self.config = config
        self.timeout = config.get('TIMEOUT', 10)
        self.client = SlackClient(config.get('API_TOKEN')) 
Example #27
Source File: coffeeshop.py    From coffeeshop with MIT License 5 votes vote down vote up
def __init__(self, token = None):

        try:

            connection = SlackClient(token)
            
        except:

            raise NoSlacksForYou("Could not authenticate with this token") 
Example #28
Source File: slack.py    From securitybot with Apache License 2.0 5 votes vote down vote up
def __init__(self, username, token, icon_url):
        # type: (str, str, str) -> None
        '''
        Constructs the Slack API object using the bot's username, a Slack
        token, and a URL to what the bot's profile pic should be.
        '''
        self._username = username
        self._icon_url = icon_url

        self._slack = SlackClient(token)
        self._validate() 
Example #29
Source File: slack.py    From DET with MIT License 5 votes vote down vote up
def __init__(self, app, conf):
        global app_exfiltrate, config, sc
        sc = SlackClient(conf['api_token'])
        config = conf
        app.register_plugin('slack', {'send': send, 'listen': listen})
        app_exfiltrate = app 
Example #30
Source File: slack_common.py    From resilient-community-apps with MIT License 5 votes vote down vote up
def __init__(self, api_token):
        self.slack_client = SlackClient(api_token)
        self.channel = None
        self.warnings = []