本文整理汇总了Python中slackclient.SlackClient类的典型用法代码示例。如果您正苦于以下问题:Python SlackClient类的具体用法?Python SlackClient怎么用?Python SlackClient使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了SlackClient类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: get_slack_users
def get_slack_users():
'''Gets all users from slack and returns a list of users, each as a dictionary'''
sc = SlackClient(TOKEN)
members = sc.api_call("users.list")['members']
slack_users = []
for member in members:
slack_id = member['id']
slack_deleted = member['deleted']
slack_name = member['name']
slack_status = member['status']
slack_first_name = member['profile']['first_name']
slack_last_name = member['profile']['last_name']
slack_real_name = member['profile']['real_name']
slack_real_name_normalized = member['profile']['real_name_normalized']
slack_email = member['profile']['email']
slack_user = {'slack_id': slack_id,
'slack_deleted': slack_deleted,
'slack_name': slack_name,
'slack_status': slack_status,
'slack_first_name': slack_first_name,
'slack_last_name': slack_last_name,
'slack_real_name': slack_real_name,
'slack_real_name_normalized': slack_real_name_normalized,
'slack_email': slack_email}
slack_users.append(slack_user)
return slack_users
示例2: __init__
class Slack:
def __init__(self, config, token_file):
self.disabled = True
try:
from slackclient import SlackClient
except:
return
try:
self.channel = config['channel']
self.method = config['method']
self.username = config['username']
self.emoji = config['emoji']
except (TypeError, KeyError) as e:
return
try:
with open(token_file) as stoken:
r = stoken.readlines()
slack_token = ''.join(r).strip()
self.client = SlackClient(slack_token)
except IOError:
return
self.disabled = False
def api_call(self, text):
if not self.disabled:
self.client.api_call(self.method, channel=self.channel,
username=self.username, icon_emoji=self.emoji, text=text)
print ("Your current configuration for slack notifications is deprecated! Please switch to latest configuration.")
示例3: _register_deployment
def _register_deployment():
branch = local('git rev-parse --abbrev-ref HEAD', capture=True)
author = local('git log -1 --pretty=format:"%an"', capture=True)
commit = local('git log -1 --pretty=format:"%B"', capture=True)
git_url = f'https://github.com/CDE-UNIBE/qcat/tree/{branch}'
sc = SlackClient(settings.SLACK_TOKEN)
sc.api_call(
'chat.postMessage',
channel='server-info',
username='Deploy bot',
text=f'Branch "{branch}" deployed: {git_url}',
attachments=[
{
'pretext': f'Great success!',
'title': commit,
'title_link': git_url,
'fields': [
{
'title': 'Branch',
'value': 'develop',
'short': False
},
{
'title': 'Author',
'value': author,
'short': False
}
],
'image_url': 'https://qcat.wocat.net/static/assets/favicons/favicon-32x32.png'
}
]
)
示例4: __init__
class Utils:
def __init__(self):
self.sc = SlackClient(token)
def send(self, chan, message):
"""Print to chat function using the slackclient api"""
self.sc.api_call("chat.postMessage", channel = chan, text = "`" + message + "`", icon_emoji=':robot_face:')
def whisper(self, message):
return message
def is_empty_input(param, self):
"""Check parameters to see if it is empty"""
param = request.args.get("text")
if param is None:
self.help()
return True
return False
def is_user_online(self, username):
"""Grats the user_ID (U123456789) via username"""
data = self.sc.api_call("users.list", presence='1')
try:
for key in data['members']:
if key['name'] == username:
return key['presence']
except:
pass
return None
示例5: send_message
def send_message(channel, message, username):
slack_token = os.environ.get('SLACK_API_TOKEN')
client = SlackClient(slack_token)
client.api_call(
'chat.postMessage',
channel=channel, text=message, username=username
)
示例6: slack_post
def slack_post(message, channel=CONF['alerts_channel'],
token=SLACK_BOT_TOKEN):
"""Post a message to a channel
Args:
message (str): Message to post
channel (str): Channel id. Defaults to alerts_channel specified in
private.yml
token (str): Token to use with SlackClient. Defaults to bot_token
specified in private.yml
"""
LOGGER.debug("Posting to slack")
slack_client = SlackClient(token)
response = slack_client.api_call(
"chat.postMessage",
as_user=True,
channel=channel,
text=message
)
if response['ok']:
LOGGER.info('Posted succesfully')
else:
LOGGER.error('Unable to post, response: %s', response)
return
示例7: RtmBot
class RtmBot(object):
def __init__(self, token):
self.last_ping = 0
self.token = token
self.bot_plugins = []
self.slack_client = None
self.exit = False
def connect(self):
"""Convenience method that creates Server instance"""
self.slack_client = SlackClient(self.token)
self.slack_client.rtm_connect()
def start(self):
self.connect()
self.load_plugins()
while True and not self.exit:
for reply in self.slack_client.rtm_read():
self.input(reply)
self.crons()
self.output()
self.autoping()
time.sleep(.1)
def autoping(self):
#hardcode the interval to 3 seconds
now = int(time.time())
if now > self.last_ping + 3:
self.slack_client.server.ping()
self.last_ping = now
def input(self, data):
if "type" in data:
function_name = "process_" + data["type"]
dbg("got {}".format(function_name))
for plugin in self.bot_plugins:
plugin.register_jobs()
plugin.do(function_name, data)
def output(self):
for plugin in self.bot_plugins:
if plugin.name == 'robbie':
self.exit = plugin.exit
limiter = False
for output in plugin.do_output():
channel = self.slack_client.server.channels.find(output[0])
if channel != None and output[1] != None:
if limiter == True:
time.sleep(.1)
limiter = False
message = output[1].encode('utf-8','ignore')
channel.send_message("{}".format(message))
limiter = True
def crons(self):
for plugin in self.bot_plugins:
plugin.do_jobs()
def load_plugins(self):
for plugin in glob.glob(directory+'/plugins/*'):
sys.path.insert(0, plugin)
sys.path.insert(0, directory+'/plugins/')
for plugin in glob.glob(directory+'/plugins/*.py') + glob.glob(directory+'/plugins/*/*.py'):
logging.info(plugin)
name = plugin.split('/')[-1][:-3]
# try:
self.bot_plugins.append(Plugin(name))
示例8: SlackThread
class SlackThread(threading.Thread):
def __init__(self, queue, config):
super(SlackThread, self).__init__()
self.daemon = True
self.queue = queue
self._config = config
self.conn = None
def run(self):
try:
print 'Connecting to slack'
self.conn = SlackClient(self._config['token'])
if not self.conn.rtm_connect():
return
self.parseLoginData(self.conn.server.login_data)
print 'Connected to slack'
self.conn.server.websocket.sock.setblocking(True)
while True:
for event in self.conn.rtm_read():
self.queue.put({'type': 'slack.event', 'data': event})
except Exception as e:
print 'SLACK RUNLOOP ERROR: %s' % e
self.conn = None
def parseLoginData(self, loginData):
for user in loginData.get('users', []):
if user.get('deleted', False):
continue
if user.get('is_bot', False):
continue
self.queue.put({'type': 'slack.join', 'data': {'id': user['id'], 'name': user['name']}})
示例9: SlackROS
class SlackROS():
# Must have __init__(self) function for a class, similar to a C++ class constructor.
def __init__(self):
# Get the ~private namespace parameters from command line or launch file.
self.token = rospy.get_param('~token', 'xoxp-123456789')
self.channel = rospy.get_param('~channel', 'G1234567Q')
self.username = rospy.get_param('~username', 'ros-bot')
# Create a publisher for our custom message.
pub = rospy.Publisher('from_slack_to_ros', String, queue_size=10)
rospy.Subscriber("from_ros_to_slack", String, self.callback)
# Create the slack client
self.sc = SlackClient(self.token)
if self.sc.rtm_connect():
# Main while loop.
while not rospy.is_shutdown():
for reply in self.sc.rtm_read():
if "type" in reply and "user" in reply:
#print reply
if reply["type"] == "message" and reply["channel"] == self.channel:
pub.publish(reply["text"])
# Sleep for a while before publishing new messages. Division is so rate != period.
rospy.sleep(2.0)
def callback(self, data):
self.sc.api_call(
"chat.postMessage", channel=self.channel, text=data.data,
username=self.username, icon_emoji=':robot_face:'
)
示例10: check
def check(self):
sc = SlackClient(self.config["bot"]["token"])
history = sc.api_call("channels.history", channel=self.config["bot"]["channel"], oldest=self.lastcheck )
botname = "%s" % self.config["bot"]["name"]
#sometimes there are no messages!
if "messages" in history:
for message in history["messages"]:
if botname in message["text"]:
timestamp = message["ts"]
command = message["text"].split(" ")
if command[1] == self.config["hostname"]:
if command[2] == "df":
self._action_df()
self._set_lastcheck(timestamp)
elif command[2] == "mem":
self._action_mem()
self._set_lastcheck(timestamp)
elif command[2] == "top":
self._action_top()
self._set_lastcheck(timestamp)
else:
self._send_message("I don't know what this action is '%s'. Supported actions: df, mem, top" % command[2])
sc.api_call("chat.postMessage", as_user="true:", channel=self.config["bot"]["channel"], text="I don't know what this action is '%s'. Supported actions: df, mem, top" % command[2])
self._set_lastcheck(timestamp)
elif command[1] == "rollcall":
self._send_message("%s on %s reporting in" % (self.config["bot"]["name"], self.config["hostname"]))
示例11: main
def main(args):
global sc
for i in range(NUM_WORKERS):
t = threading.Thread(target=worker)
t.daemon = True
t.start()
for n in range(NUM_TRY):
sc = SlackClient(TOKEN)
if sc.rtm_connect():
while True:
try:
records = sc.rtm_read()
except:
print "接続が切断されました。再接続します。試行回数: %d" % (n + 1)
break
for record in records:
if "file" in record:
fileinfo = record["file"]["id"]
filedata = sc.api_call("files.info", file=fileinfo)
if fileinfo not in memo:
q.put(filedata["file"])
memo.append(fileinfo)
time.sleep(WAIT_TIME)
else:
print "接続に失敗しました。TOKENが間違っていませんか?"
time.sleep(60)
示例12: post_message
def post_message(self):
sc = SlackClient(self.token)
print sc.api_call("api.test")
sc.api_call(
"chat.postMessage", channel="#general", text="Hello from Python! :tada:",
username=self.username, as_user="false", icon_emoji=':robot_face:'
)
示例13: bot
def bot():
try:
slack_client = SlackClient(token=config["slack"]["token"])
slack_client.rtm_connect()
bot_info = json.loads(slack_client.api_call("auth.test").decode("utf-8"))
last_ping = 0
cache_emoji_list(slack_client)
while True:
last_ping = autoping(slack_client, last_ping)
process_queued_responses(slack_client)
for event in slack_client.rtm_read():
print(event)
event_type = event.get("type")
if event_type == "message":
process_message_event(slack_client, bot_info, event)
time.sleep(0.1)
except KeyboardInterrupt:
sys.exit(0)
示例14: main
def main(self):
token = os.environ.get("SLACK_TOKEN")
slack_client = SlackClient(token)
if slack_client.rtm_connect():
while True:
new_evts = slack_client.rtm_read()
for evt in new_evts:
#print evt
if 'type' in evt:
if str(evt["type"]) == "message" and "text" in evt:
# this is where the logic for the human input text is placed.
# we also get more information from the JSON
keyword = True
channel = evt['channel']
response = evt['text']
print response
elif 'reply_to' in evt:
#this is where the logic for the chat bot is placed.
slack_client.rtm_send_message('This is where the messages will go', 'Hello World')
else:
print "Failed."
示例15: TachikomaFrontend
class TachikomaFrontend(pykka.ThreadingActor, CoreListener):
def new_slack_client(self):
self.sc = SlackClient(self.slackToken)
if not self.sc.rtm_connect():
raise Exception("Bad Slack token?")
logger.info("New Slack client started")
def __init__(self, config, core):
super(TachikomaFrontend, self).__init__()
self.daemon = True
self.slackToken = config['tachikoma']['slack_token'],
self.core = core
self.new_slack_client()
thread.start_new_thread(self.doSlack, ())
def doSlackRead(self, last_track_told):
try:
items = self.sc.rtm_read()
except Exception, e:
logger.info("Exception from Slack: %r", e)
time.sleep(1)
self.new_slack_client()
return last_track_told
logger.debug("info %r", items)
if items != []:
try:
current_track = self.core.playback.get_current_track().get(3)
except pykka.Timeout, e:
logger.warning("Failure to get current track: %r", e)
current_track = None
return self.doSlackLoop(last_track_told, current_track, items)