本文整理匯總了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
)
示例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))
示例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 = {}
示例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))
示例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)
示例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
示例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']
示例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)
示例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()
示例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)
示例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
示例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")
示例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 = []
示例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,
}
示例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)