当前位置: 首页>>代码示例>>Python>>正文


Python slackclient.SlackClient方法代码示例

本文整理汇总了Python中slackclient.SlackClient方法的典型用法代码示例。如果您正苦于以下问题:Python slackclient.SlackClient方法的具体用法?Python slackclient.SlackClient怎么用?Python slackclient.SlackClient使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在slackclient的用法示例。


在下文中一共展示了slackclient.SlackClient方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: slackMsg

# 需要导入模块: import slackclient [as 别名]
# 或者: from slackclient import SlackClient [as 别名]
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
    ) 
开发者ID:supthunder,项目名称:premeStock,代码行数:21,代码来源:monitor.py

示例2: __init__

# 需要导入模块: import slackclient [as 别名]
# 或者: from slackclient import SlackClient [as 别名]
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)) 
开发者ID:ahelal,项目名称:bender,代码行数:20,代码来源:base.py

示例3: __init__

# 需要导入模块: import slackclient [as 别名]
# 或者: from slackclient import SlackClient [as 别名]
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 = {} 
开发者ID:slackapi,项目名称:Slack-Python-Onboarding-Tutorial,代码行数:25,代码来源:bot.py

示例4: send_slack_message

# 需要导入模块: import slackclient [as 别名]
# 或者: from slackclient import SlackClient [as 别名]
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)) 
开发者ID:lil-lab,项目名称:atis,代码行数:21,代码来源:run.py

示例5: do_scrape

# 需要导入模块: import slackclient [as 别名]
# 或者: from slackclient import SlackClient [as 别名]
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) 
开发者ID:VikParuchuri,项目名称:apartment-finder,代码行数:20,代码来源:scraper.py

示例6: send_slack_report

# 需要导入模块: import slackclient [as 别名]
# 或者: from slackclient import SlackClient [as 别名]
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 
开发者ID:fr0gger,项目名称:vthunting,代码行数:20,代码来源:vthunting.py

示例7: __init__

# 需要导入模块: import slackclient [as 别名]
# 或者: from slackclient import SlackClient [as 别名]
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'] 
开发者ID:jinserk,项目名称:pytorch-asr,代码行数:19,代码来源:logger.py

示例8: main

# 需要导入模块: import slackclient [as 别名]
# 或者: from slackclient import SlackClient [as 别名]
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) 
开发者ID:linkedin,项目名称:oncall,代码行数:23,代码来源:slack.py

示例9: main

# 需要导入模块: import slackclient [as 别名]
# 或者: from slackclient import SlackClient [as 别名]
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() 
开发者ID:dowjones,项目名称:reapsaw,代码行数:27,代码来源:notifications.py

示例10: __init__

# 需要导入模块: import slackclient [as 别名]
# 或者: from slackclient import SlackClient [as 别名]
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) 
开发者ID:ltworf,项目名称:localslackirc,代码行数:18,代码来源:slack.py

示例11: _api_call

# 需要导入模块: import slackclient [as 别名]
# 或者: from slackclient import SlackClient [as 别名]
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 
开发者ID:dropbox,项目名称:securitybot,代码行数:22,代码来源:slack.py

示例12: __init__

# 需要导入模块: import slackclient [as 别名]
# 或者: from slackclient import SlackClient [as 别名]
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") 
开发者ID:OpenToAllCTF,项目名称:OTA-Challenge-Bot,代码行数:19,代码来源:slack_wrapper.py

示例13: __init__

# 需要导入模块: import slackclient [as 别名]
# 或者: from slackclient import SlackClient [as 别名]
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 = [] 
开发者ID:slackapi,项目名称:python-rtmbot,代码行数:24,代码来源:core.py

示例14: __init__

# 需要导入模块: import slackclient [as 别名]
# 或者: from slackclient import SlackClient [as 别名]
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,
        } 
开发者ID:airflow-plugins,项目名称:pandora-plugin,代码行数:23,代码来源:general_notification_hook.py

示例15: __init__

# 需要导入模块: import slackclient [as 别名]
# 或者: from slackclient import SlackClient [as 别名]
def __init__(self, baseplate, token, actor_urn, reconnect=True,
                 *args, **kwargs):
        """Initializes RtmBot

        Args:
            baseplate (Legobot.Lego): The parent Pykka actor.
                Typically passed in fromLegobot.Connectors.Slack.Slack
            token (string): Slack API token
            actor_urn (string): URN of Pykka actor launching RtmBot
            *args: Variable length argument list.
            **kwargs: Arbitrary keyword arguments.

        Returns:
            Returns an instance of RtmBot which connects to Slack.
        """
        self.baseplate = baseplate
        self.token = token
        self.last_ping = 0
        self.actor_urn = actor_urn
        self.reconnect = reconnect
        self.auto_reconnect = True
        # 'event':'method'
        self.supported_events = {'message': self.on_message}
        self.user_map = {}
        self.slack_client = SlackClient(self.token)
        self.get_channels()
        self.get_users()
        threading.Thread.__init__(self) 
开发者ID:Legobot,项目名称:Legobot,代码行数:30,代码来源:Slack.py


注:本文中的slackclient.SlackClient方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。