Beispiel #1
0
def create_slack_client(token):
    slack_client = SlackClient(token)
    if not slack_client.rtm_connect():
        raise Exception('Cannot connect to Slack')
    clients.slack = slack_client
    tokens.slack = token
    return slack_client
Beispiel #2
0
def handle_event(event: dict, channel: str, channel_id: str, message: str,
                 sc: SlackClient, logger: logging.Logger) -> None:
    pretty_event = pformat(event)
    logger.debug(f"Event received:\n{pretty_event}")

    subtype = event.get('subtype')
    user = event.get('user')

    if subtype in ('group_join', 'channel_join') and user:

        # We will use the event's channel ID to send a response and refer to
        # users by their display_name in accordance with new guidelines.
        # https://api.slack.com/changelog/2017-09-the-one-about-usernames
        event_channel_id = event.get('channel')
        user_profile = event.get('user_profile')
        username = user_profile.get('display_name')
        user_mention = f"<@{user}>"
        message = message.replace('{user}', user_mention)

        if event_channel_id == channel_id:
            try:
                sc.rtm_send_message(event_channel_id, message)
                logger.info(f"Welcomed {username} to #{channel}")
            except AttributeError:
                logger.error(f"Couldn't send message to #{channel}")
Beispiel #3
0
def slack():
	logs.write("In slack function in new thread", 'working')
	sc = SlackClient(token)
	if sc.rtm_connect():
		logs.write("Connected to rtm socket", 'success')
    	while True:
    		time.sleep(0.1)
        	message=sc.rtm_read()
        	if message!=[]:
        		if message[0].keys()[0]=='text':
        			command=message[0].values()[0]
        			logs.write(command,'working')
        			try:
        				command=json.loads(command)
        			except ValueError:
        				command=[{'type':'command'},{'devices':'all'},{'action':"{0}".format(command)}]
        			commandtype=command[0]
        			devices=command[1]
        			action=command[2]
        			if devices.values()[0]=='all' or devices.values()[0]=="XPS":
	        			logs.write("Checking local W.I.L.L server", 'trying')
	        			answer=requests.get('http://127.0.0.1:5000/?context=command&command={0}'.format(action.values()[0])).text
	        			print sc.api_call( "chat.postMessage", channel="#w_i_l_l", text="{0}".format(answer), username='******')
	else:
		logs.write("Connection Failed, invalid token?", 'error')
Beispiel #4
0
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
Beispiel #5
0
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='******',
        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'
            }
        ]
    )
Beispiel #6
0
class SlackMediator(object):
    def __init__(self, token):
        self.token = token
        self.slack_client = SlackClient(self.token)
        self.time_keeper = _TimeKeeper()

    def time_keeping(self):
        self.time_keeper.reset()
        return iter(self.time_keeper)

    def wait(self):
        self.time_keeper.wait()

    def read(self):
        return self.slack_client.rtm_read()

    def send(self, output, wait_itr):
        channel_id, message = output
        channel = self.find_channel(channel_id)
        if channel is not None and message is not None:
            next(wait_itr)
            channel.send_message(message)

    def ping(self):
        return self.slack_client.server.ping()

    def find_channel(self, name):
        return self.slack_client.server.channels.find(name)

    def connect(self):
        """Convenience method that creates Server instance"""
        logger.info("connect to slack ..")
        self.slack_client.rtm_connect()
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.")
Beispiel #8
0
def sendSlackAlert(token, channel, username, *args):
	sc = SlackClient(token)
	sc.api_call(
		"chat.postMessage", 
		channel=str(channel), 
		text=args[0] + "\n",
		username=str(username))
Beispiel #9
0
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
    )
Beispiel #10
0
class Output(cowrie.core.output.Output):

    def __init__(self):
        self.slack_channel = CONFIG.get('output_slack', 'channel')
        self.slack_token = CONFIG.get('output_slack', 'token')
        cowrie.core.output.Output.__init__(self)

    def start(self):
        pass

    def stop(self):
        pass

    def write(self, logentry):
        for i in list(logentry.keys()):
            # Remove twisted 15 legacy keys
            if i.startswith('log_'):
                del logentry[i]

        self.sc = SlackClient(self.slack_token)
        self.sc.api_call(
            "chat.postMessage",
            channel=self.slack_channel,
            text="%s %s" % (time.strftime('%Y-%m-%d %H:%M:%S'), json.dumps(logentry, indent=4, sort_keys=True))
        )
Beispiel #11
0
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
def slack_upload(fname, title=None, channel=CONF['alerts_channel'],
                 token=SLACK_BOT_TOKEN):
    """Upload a file to a channel

    Args:
        fname (str): Filepath
        title (str, optional): Title of the file. Defaults to fname
        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

    Returns:
        dict: Slack response object
    """
    if title is None:
        title = os.path.basename(fname)
    slack_client = SlackClient(token)
    response = slack_client.api_call(
        "files.upload",
        channels=channel,
        filename=fname,
        file=open(fname, 'rb'),
        title=title
        )

    return response
Beispiel #13
0
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))
Beispiel #14
0
def slack_notifier(slack_token, secret_conf_path, server, user, password, build_url):
    branches = run_command("git branch")
    branch_name_reg = re.search("\* (.*)", branches)
    branch_name = branch_name_reg.group(1)

    if branch_name == 'master':
        print_color("Starting Slack notifications about instances", LOG_COLORS.GREEN)
        attachments, integrations_counter = get_attachments(secret_conf_path, server, user, password, build_url)

        sc = SlackClient(slack_token)
        sc.api_call(
            "chat.postMessage",
            channel="devops-events",
            username="******",
            as_user="******",
            attachments=attachments,
            text="You have {0} instances configurations".format(integrations_counter)
        )

        sc.api_call(
            "chat.postMessage",
            channel="content-lab-tests",
            username="******",
            as_user="******",
            attachments=attachments,
            text="You have {0} instances configurations".format(integrations_counter)
        )
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
Beispiel #16
0
def marcopolo_bot():
    # Insert API token from Slack
    # My token was disabled as soon as I uploaded it to Git, another token must be generated 
    token = 'xoxb-55268990450-WzfkM0A5ufihTTElZ8k6sC33'
    # Creating the slackclient object/instance 
    sc = SlackClient(token)
    # Connect to Slack
    if sc.rtm_connect():
        
        while True:
            # Read latest messages as long as connected to Slack
            rtm_responses = sc.rtm_read()
            # Check every instance of potential response and check for text response 
            for rtm_response in rtm_responses:
                if 'text' in rtm_response:
                    # If response is found as 'marco', call API function to respond with 'polo'
                    if rtm_response['text'] == 'marco':
                        sc.api_call(
                            "chat.postMessage", channel="marco-polo", text="polo",
                            username='******', icon_emoji=':robot_face:'
                        )
            
            time.sleep(1)

    else:
        quit()
Beispiel #17
0
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)
Beispiel #18
0
class SlackAPI(object):
    def __init__(self, token, username="******"):
        self.client = SlackClient(token)
        self._all_channels = self._get_channels()
        self.username = username

    def _get_channels(self):
        res = self.client.api_call("channels.list")
        _channels = json.loads(res.decode())
        _parsed_channels = _channels.get("channels", None)
        if _parsed_channels is None:
            raise Exception("Could not get Slack channels. Are you sure your token is correct?")
        return _parsed_channels

    def get_channels(self, reload_channels=False):
        if not self._all_channels or reload_channels:
            self._all_channels = self._get_channels()
        return self._all_channels

    def channel_name_to_id(self, channel_name):
        for channel in self._all_channels:
            if channel["name"] == channel_name:
                return channel["id"]
        raise ChannelNotFoundError("Channel {} not in the list of available channels".format(channel_name))

    def bulk_message(self, message, post_to=[]):
        for channel in post_to:
            if not channel.startswith("@"):
                channel = self.channel_name_to_id(channel)
            logging.debug("Posting message to {}".format(channel))
            self.client.api_call("chat.postMessage", text=message, channel=channel, username=self.username)
        return True
Beispiel #19
0
    def connect(self, inLegalSlack):
        """
        Connects to the Slack Real Time Messaging (RTM) API.
        """
        if inLegalSlack:
            self.client = SlackClient(self.human_token)
        else:
            self.client = SlackClient(self.bot_token)
        self.client.rtm_connect()
        self.username = self.client.server.username

        response = self.client.api_call(method="im.list").decode("utf-8")
        response = json.loads(response)
        # debug
        directIDList = []
        for imObj in response["ims"]:
            directIDList.append(imObj["id"])
        self.directChannelList = directIDList

        userObjects = self.client.api_call(method="users.list").decode("utf-8") # list all users in slack w/API call
        userObjects = json.loads(userObjects)

        if userObjects["ok"]:
            for user in userObjects["members"]:
                self.conversationList.append(Conversation(user["name"], user["id"]))
Beispiel #20
0
class BasicSlackClient:
    """
    Basic slack client.git
    """
    def __init__(self, token: str, default_channel: str, default_username: str):
        """
        Constructor.
        :param token: authentication tocken from BasicSlackClient
        """
        self._default_channel = default_channel
        self._default_username = default_username
        self._slack_client = SlackClient(token)

    def post(self, message: str, channel: str=None, username: str=None):
        """
        Post the given message to the given channel as the given username.
        :param message: the message to post
        :param channel: the channel to post to
        :param username: the username to post as
        """
        if channel is None:
            channel = self._default_channel
        if username is None:
            username = self._default_username

        self._slack_client.api_call(_SLACK_CLIENT_POST_MESSAGE, channel=channel, text=message, username=username)
def postNotification(token, channelID, service, calendar, timePeriod):

    events = []
    message = ""
    sc = SlackClient(token)

    if timePeriod == "today":
        events = get_todays_events(token, channelID, service, calendar)
    elif timePeriod == "this week":
        events = get_weeks_events(token, channelID, service, calendar)
    elif timePeriod == "this month":
        events = get_months_events(token, channelID,service, calendar)

    if not events:
        period = "*_No events scheduled for " + timePeriod + " :sleepy:  _*\n"
    for event in events:
        period = "*_Here are the events happening " + timePeriod + "  :smile: _*\n"
        period = period.encode('utf-8')
        start_date = dateutil.parser.parse(event['start'].get('dateTime'))
        start_date = start_date.strftime("%A, %B %d %Y @ %I:%M %p")
        end_date = dateutil.parser.parse(event['end'].get('dateTime'))
        end_date = end_date.strftime("%A, %B %d %Y @ %I:%M %p")
        message += "\n - " + "*" + event['summary'] + "*" + "\n"+ start_date + " to " + end_date + "\n" + "*Where:* " + event['location'] + "\n" + "*Description:* " + event['description'] + "\n" + event['htmlLink'] + "\n"
        message = message.encode('utf-8')
        
    sc.api_call("chat.postMessage",username="******",channel=channelID,text=period + message)
Beispiel #22
0
def router():

    _logger = get_logger(__name__)
    if request.form.get("token") == os.environ.get("SLACK_WEBHOOK_SECRET"):

        # Get info from incoming request
        channel_id = request.form.get("channel_id")
        user = request.form.get("user_name")
        message = request.form.get("text")
        _logger.info("Incoming message from {0} on {1}: {2}".format(channel_id, user, message))

        # Parse and route
        try:
            response = parse_message(message, user)
        except Exception as e:
            response = fail(e, user)
        slack_client = SlackClient(os.environ.get("SLACK_TOKEN"))
        slack_client.api_call(
            "chat.postMessage",
            channel=channel_id,
            username='******',
            icon_emoji=':sausage:',
            **response
        )

    return Response(), 200
Beispiel #23
0
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']}})
Beispiel #24
0
 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="******", 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"]))    
Beispiel #25
0
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)
Beispiel #26
0
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)
Beispiel #27
0
 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="******", icon_emoji=':robot_face:'
     )
Beispiel #28
0
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:'
	)
Beispiel #29
0
    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."
    def call(self, method, api_params):
        sc = SlackClient(self.token)
        rc = sc.api_call(method, **api_params)

        if not rc['ok']:
            msg = "Slack API call failed ({})".format(rc['error'])
            raise AirflowException(msg)
Beispiel #31
0
import os
import time
import re
from slackclient import SlackClient

# instantiate Slack client
slack_client = SlackClient("xoxb-293862340119-kmqFvNoEefpiPJ9AWsqZUnRh")
# starterbot's user ID in Slack: value is assigned after the bot starts up
starterbot_id = None

# constants
RTM_READ_DELAY = 1  # 1 second delay between reading from RTM
EXAMPLE_COMMAND = "do"
MENTION_REGEX = "^<@(|[WU].+)>(.*)"


def parse_bot_commands(slack_events):
    """
        Parses a list of events coming from the Slack RTM API to find bot commands.
        If a bot command is found, this function returns a tuple of command and channel.
        If its not found, then this function returns None, None.
    """
    for event in slack_events:
        if event["type"] == "message" and not "subtype" in event:
            user_id, message = parse_direct_mention(event["text"])
            if user_id == starterbot_id:
                return message, event["channel"]
    return None, None


def parse_direct_mention(message_text):
Beispiel #32
0
class SlackBot():
    """master slack client that remains alive for the duration of the script.  subsidiary connections to SlackClient are made on each connection drop or error"""
    def __init__(self, config):

        self.config = config
        self.token = self.config['api_key']
        self.slack_client = None
        self.name = self.config['bot_name']
        self.slack_user_id = None
        self.direct_message_channels = None
        self.channel_id = None
        self.channel_name = None
        self.master = self.config['master']

        self.plugins = self.config.get('plugins', 'plugins').split('\n')
        logger.info("Plugins installed: " + str(self.plugins))

        self.last_ping = 0
        self.reconnects = 0
        self.error_count = 0
        self.run_time = 0
        self.run_time_total = 0
        self.first_time = True
        self.auth_check = True
        self.errors = []
        self.ping_frequency = 15

    def test_connection(self, verbose=True):
        """tests whether the device is connected to the internet"""

        connected = False
        retries = 0
        while connected == False:
            if verbose:
                logger.info("Testing internet connection...")

            try:
                socket.create_connection(("www.google.com", 80))
                if verbose:
                    logger.info("internet working")
                connected = True
                return True

            except (socket.gaierror, socket.error):
                logger.error("Internet connection down - retrying " +
                             str(retries))
                error = utils.ConnectionDrop(self, "internet down")
                retries += 1
                time.sleep((1 + retries))

    def generate_client(self):
        """creates an instance of SlackClient for each connection"""

        if self.test_connection():
            self.reconnects += 1
            logger.info("Generating slack_client")

            # check token is valid

            self.slack_client = SlackClient(self.token)

            if self.auth_check:
                self.auth_check = False
                if self.slack_client.api_call(
                        "auth.test", token=self.token).get('ok') == False:
                    logger.error("key not recognised")
                    sys.exit("Invalid key.. exiting")

            logger.info("Token valid - SlackClient generated " +
                        str(self.slack_client))
            logger.info("Connecting to RTM...")

            #test RTM connection

            try:
                self.slack_client.rtm_connect()
                logger.info("Connected to RTM")
                self.run_time = 0

            except Exception as e:
                logger.error("Error in RTM connection: " + str(e))
                logger.warning("Exiting script...")
                sys.exit(1)

            logger.info("Getting user & channel IDs")

            #get list of users, channels and direct message channels

            channel_list = self.slack_client.api_call("channels.list")

            self.direct_message_channels = self.slack_client.api_call(
                "im.list")

            user_list = self.slack_client.api_call("users.list")

            for channel in channel_list.get('channels'):
                if channel.get('is_member'):
                    self.channel_id = str(channel.get('id'))
                    self.channel_name = str(channel.get('name'))

            for user in user_list.get('members'):
                if user.get('name') == self.name:
                    self.slack_user_id = user.get('id')

            logger.info("Bot ID:  " + str(self.slack_user_id) +
                        " Channel ID: " + str(self.channel_id) + "/ " +
                        str(self.channel_name))

    def say(self, text_message):
        """simple function to post a message to the bot's channel"""

        try:
            self.slack_client.api_call("chat.postMessage",
                                       channel=self.channel_id,
                                       text=str(text_message),
                                       as_user=True)

        except (websocket.WebSocketConnectionClosedException,
                socket.error) as e:

            error = utils.ConnectionDrop(self, "chat connection error")

    def autoping(self):
        """pings the slack server as set by the Bot"""

        now = int(time.time())
        if now > self.last_ping + self.ping_frequency:
            self.slack_client.server.ping()
            self.last_ping = now

    def load_plugin(self, name):
        """loads the plugin for the process method"""

        plugin = __import__("plugin_%s" % name)
        return plugin

    def call_plugin(self, name, message):

        plugin = self.load_plugin(name)
        plugin.plugin_main(message, self)

    def process(self):
        """checks for connection errors, reads the RTM firehose and parses messages"""

        self.run_time += 1
        self.run_time_total += 1

        try:
            messages = self.slack_client.rtm_read()
            self.error_count = 0

            if self.first_time:
                self.say("Bot ID:" + str(self.slack_user_id) + " is awake")
                self.first_time = False

            if self.errors:
                drop_period = int(time.time()) - self.errors[0].timestamp
                self.say("I was offline for " + str(drop_period) + " secs.  " +
                         str(len(self.errors)) + "errors.")
                logger.debug("Offline for " + str(drop_period) + " secs")
                self.errors = []

        except websocket.WebSocketConnectionClosedException:

            error = utils.ConnectionDrop(self, "websocket drop")
            self.generate_client()
            return

        except socket.error:

            error = utils.ConnectionDrop(self, "Socket error")
            time.sleep(5)
            self.error_count += 1

            if self.error_count > 5:
                self.generate_client()
            return

        #checks the message stream

        for message in messages:
            #print (message)

            if message['type'] == 'presence_change':
                if message['presence'] == 'active':
                    time.sleep(.5)
                    self.say(
                        lex.response('greetings') + " " + str(self.master))

            if 'text' in message:
                if message['text'].startswith(
                        "<@%s>" % self.slack_user_id
                ) or 'text' in message and message['text'].startswith(
                        "<!%s>" % 'everyone'):

                    #if user issues a command, run through through all plugins

                    message_text = message['text']
                    for plugin in self.plugins:
                        self.call_plugin(plugin, message_text)

        self.autoping()
Beispiel #33
0
from slackclient import SlackClient
from settings import SLACK_TOKEN, SLACK_CHANNEL, CLUSTER_NAME

sc = SlackClient(SLACK_TOKEN)

NORMAL_COLOR = '#36a64f'
WARNING_COLOR = '#FFFF00'
ERROR_COLOR = '#FF0000'

ALERTS_COLORS = {
    'Normal': NORMAL_COLOR,
    'Warning': WARNING_COLOR,
}


def get_slack_msg_color(event_type):
    return ALERTS_COLORS.get(event_type, ERROR_COLOR)


def send_alert(event_type, url, description, status, response_time):
    attachment = {
        "fallback":
        description,
        "color":
        get_slack_msg_color(event_type),
        "title":
        description,
        "title_link":
        url,
        "fields": [{
            "title": "URL",
Beispiel #34
0
class Bot(object):
    """ Instanciates a Bot object to handle Slack onboarding interactions."""
    def __init__(self):
        super(Bot, self).__init__()
        self.name = "come_back_here"
        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": "users.profile:read"
        }
        self.oauth
        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 envrionment you'll likely want to store this more
        # persistantly in  a database.
        self.messages = {}

    def auth(self, code):
        """
        Authenticate with OAuth and assign correct scopes.
        Save a dictionary of authed team information in memory on the bot
        object.

        Parameters
        ----------
        code : str
            temporary authorization code sent by Slack to be exchanged for an
            OAuth token

        """
        # After the user has authorized this app for use in their Slack team,
        # Slack returns a temporary authorization code that we'll exchange for
        # an OAuth token using the oauth.access endpoint
        auth_response = self.client.api_call(
            "oauth.access",
            client_id=self.oauth["client_id"],
            client_secret=self.oauth["client_secret"],
            code=code)
        # To keep track of authorized teams and their associated OAuth tokens,
        # we will save the team ID and bot tokens to the global
        # authed_teams object
        team_id = auth_response["team_id"]
        authed_teams[team_id] = {"bot_token": auth_response["access_token"]}
        # Then we'll reconnect to the Slack Client with the correct team's
        # bot token
        self.client = SlackClient(authed_teams[team_id]["bot_token"])

    def bring_back_user(self, user_id, channel, token):
        """
        Create and send an onboarding welcome message to new users. Save the
        time stamp of this message on the message object for updating in the
        future.

        Parameters
        ----------
        team_id : str
            id of the Slack team associated with the incoming event
        user_id : str
            id of the Slack user associated with the incoming event

        """
        # We'll use the message object's method to create the attachments that
        # we'll want to add to our Slack message. This method will also save
        # the attachments on the message object which we're accessing in the
        # API call below through the message object's `attachments` attribute.
        text = "Hey... get back here <@" + str(user_id) + ">"
        self.client.api_call("chat.postMessage",
                             channel=channel,
                             token=token,
                             username=self.name,
                             icon_emoji=self.emoji,
                             text=text)
        self.client.api_call("channels.invite",
                             token=token,
                             channel=channel,
                             user=user_id)
Beispiel #35
0
 def create_slack_client(self, token):
     self.SLACK_CLIENT = SlackClient(token)
Beispiel #36
0
class Bot(object):
    admin_env_string = os.environ['PB_ADMIN']
    ADMIN = admin_env_string.split(',')

    # Set the name for the logger
    # Add custom log handler to logger

    EMOJI_LIST = ["party-parrot", "venezuela-parrot", "star2", "fiesta-parrot", "wasfi_dust", "dab"]
    GENERAL_CHANNEL = ""
    TTPB = "talk-to-pantherbot"
    VERSION = "2.1.0"

    def __init__(self, token, bot_name=""):
        self.SLACK_CLIENT = None
        self.BOT_NAME = bot_name
        self.BOT_ICON_URL = "http://i.imgur.com/QKaLCX7.png"
        self.USER_LIST = None
        self.POLLING_LIST = dict()
        self.WEBSOCKET = None
        self.THREADS = []
        self.COMMANDS_LIST = commands
        
        self.pb_cooldown = True
        # self.check_in_thread_ts

        self.create_slack_client(token)

    def create_slack_client(self, token):
        self.SLACK_CLIENT = SlackClient(token)

    # Returns a list of channel IDs searched for by name
    def channels_to_ids(self, channel_names):
        pub_channels = self.SLACK_CLIENT.api_call(
            "channels.list",
            exclude_archived=1
        )
        pri_channels = self.SLACK_CLIENT.api_call(
            "groups.list",
            exclude_archived=1
        )
        list_of_channels = []
        for channel in pub_channels["channels"]:
            for num in range(0, len(channel_names)):
                if channel["name"].lower() == channel_names[num].lower():
                    list_of_channels.append(channel["id"])
        # Same as above
        for channel in pri_channels["groups"]:
            for num in range(0, len(channel_names)):
                if channel["name"].lower() == channel_names[num].lower():
                    list_of_channels.append(channel["id"])
        return list_of_channels

    # Send Message
    # Sends a message to the specified channel (looks up by channel name, unless is_id is True)
    def send_msg(self, channel, text, is_id=False, thread_ts=None):
        if is_id:
            channel_id = channel
        else:
            channel_id = self.channels_to_ids([channel])[0]
        if thread_ts is not None:
            response_json = self.SLACK_CLIENT.api_call(
                "chat.postMessage",
                channel=channel_id,
                text=text,
                username=self.BOT_NAME,
                icon_url=self.BOT_ICON_URL,
                thread_ts=thread_ts
            )
        else:
            response_json = self.SLACK_CLIENT.api_call(
                "chat.postMessage",
                channel=channel_id,
                text=text,
                username=self.BOT_NAME,
                icon_url=self.BOT_ICON_URL
            )
        logger.info("Message sent: ")
        return response_json

    def emoji_reaction(self, channel, ts, emoji):
        self.SLACK_CLIENT.api_call(
            "reactions.add",
            name=emoji,
            channel=channel,
            timestamp=ts
        )
        logger.info("Reaction posted: " + emoji)

    def close(self):
        self.WEBSOCKET.keep_running = False
        logger.info("Closing Websocket...")
Beispiel #37
0
class Bot(object):
    """ Instanciates a Bot object to handle Slack onboarding interactions."""
    def __init__(self):
        super(Bot, self).__init__()
        self.name = "SouthwestCheckin"
        # 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": key.client_id,
        #               "client_secret": key.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 = key.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(key.bot_token)
        # We'll use this dictionary to store the state of each message object.
        # In a production envrionment you'll likely want to store this more
        # persistantly in  a database.
        self.messages = {}


    def open_dm(self, user_id):
        """
        Open a DM to send a welcome message when a 'team_join' event is
        recieved from Slack.
        Parameters
        ----------
        user_id : str
            id of the Slack user associated with the 'team_join' event
        Returns
        ----------
        dm_id : str
            id of the DM channel opened by this method
        """

        new_dm = self.client.api_call("im.open",
                                      user=user_id)
        dm_id = new_dm["channel"]["id"]
        return dm_id

    def onboarding_message(self, team_id, user_id):
        """
        Create and send an onboarding welcome message to new users. Save the
        time stamp of this message on the message object for updating in the
        future.
        Parameters
        ----------
        team_id : str
            id of the Slack team associated with the incoming event
        user_id : str
            id of the Slack user associated with the incoming event
        """
        # We've imported a Message class from `message.py` that we can use
        # to create message objects for each onboarding message we send to a
        # user. We can use these objects to keep track of the progress each
        # user on each team has made getting through our onboarding tutorial.

        # First, we'll check to see if there's already messages our bot knows
        # of for the team id we've got.
        if self.messages.get(team_id):
            # Then we'll update the message dictionary with a key for the
            # user id we've recieved and a value of a new message object
            self.messages[team_id].update({user_id: message.Message()})
        else:
            # If there aren't any message for that team, we'll add a dictionary
            # of messages for that team id on our Bot's messages attribute
            # and we'll add the first message object to the dictionary with
            # the user's id as a key for easy access later.
            self.messages[team_id] = {user_id: message.Message()}
        message_obj = self.messages[team_id][user_id]
        # Then we'll set that message object's channel attribute to the DM
        # of the user we'll communicate with
        message_obj.channel = self.open_dm(user_id)
        # We'll use the message object's method to create the attachments that
        # we'll want to add to our Slack message. This method will also save
        # the attachments on the message object which we're accessing in the
        # API call below through the message object's `attachments` attribute.
        message_obj.create_attachments()
        post_message = self.client.api_call("chat.postMessage",
                                            channel=message_obj.channel,
                                            username=self.name,
                                            icon_emoji=self.emoji,
                                            text=message_obj.text,
                                            attachments=message_obj.attachments
                                            )
        timestamp = post_message["ts"]
        # We'll save the timestamp of the message we've just posted on the
        # message object which we'll use to update the message after a user
        # has completed an onboarding task.
        message_obj.timestamp = timestamp

    def checkin_instructions(self, team_id, user_id):
        """
        Create and send an onboarding welcome message to new users. Save the
        time stamp of this message on the message object for updating in the
        future.
        Parameters
        ----------
        team_id : str
            id of the Slack team associated with the incoming event
        user_id : str
            id of the Slack user associated with the incoming event
        """
        # We've imported a Message class from `message.py` that we can use
        # to create message objects for each onboarding message we send to a
        # user. We can use these objects to keep track of the progress each
        # user on each team has made getting through our onboarding tutorial.

        # First, we'll check to see if there's already messages our bot knows
        # of for the team id we've got.
        if self.messages.get(team_id):
            # Then we'll update the message dictionary with a key for the
            # user id we've recieved and a value of a new message object
            self.messages[team_id].update({user_id: message.Message()})
        else:
            # If there aren't any message for that team, we'll add a dictionary
            # of messages for that team id on our Bot's messages attribute
            # and we'll add the first message object to the dictionary with
            # the user's id as a key for easy access later.
            self.messages[team_id] = {user_id: message.Message()}
        message_obj = self.messages[team_id][user_id]
        # Then we'll set that message object's channel attribute to the DM
        # of the user we'll communicate with
        message_obj.channel = self.open_dm(user_id)
        # We'll use the message object's method to create the attachments that
        # we'll want to add to our Slack message. This method will also save
        # the attachments on the message object which we're accessing in the
        # API call below through the message object's `attachments` attribute.

        post_message = self.client.api_call("chat.postMessage",
                                            channel=message_obj.channel,
                                            username=self.name,
                                            #icon_emoji=self.emoji,
                                            text=message_obj.text,
                                            #attachments=message_obj.attachments
                                            )

        timestamp = post_message["ts"]
        # We'll save the timestamp of the message we've just posted on the
        # message object which we'll use to update the message after a user
        # has completed an onboarding task.
        message_obj.timestamp = timestamp

    def pass_checkin(self, conf_number, firstname, lastname, user_id, team_id):
        # TODO: Pass variables to checkin.py
        # TODO: Store checkins and associate to user id so user can ask what are scheduled
        print('Running pass_checkin')
        print("Checkin {} {} {} for {} on team {}".format(conf_number, firstname, lastname, user_id, team_id))
        #TODO Use subprocess instead of os.system
        #subprocess.call(['python', 'checkin.py', '%s %s %s %s %s']) % (conf_number, firstname, lastname, user_id, team_id)
        os.system("python3 checkin.py {} {} {} {} {}".format(conf_number, firstname, lastname, user_id, team_id))
    def checkin_initial(self, team_id, user_id, conf_number, firstname, lastname):
        """
        Create and send an onboarding welcome message to new users. Save the
        time stamp of this message on the message object for updating in the
        future.
        Parameters
        ----------
        team_id : str
            id of the Slack team associated with the incoming event
        user_id : str
            id of the Slack user associated with the incoming event
        """
        # We've imported a Message class from `message.py` that we can use
        # to create message objects for each onboarding message we send to a
        # user. We can use these objects to keep track of the progress each
        # user on each team has made getting through our onboarding tutorial.

        # First, we'll check to see if there's already messages our bot knows
        # of for the team id we've got.
        if self.messages.get(team_id):
            # Then we'll update the message dictionary with a key for the
            # user id we've recieved and a value of a new message object
            self.messages[team_id].update({user_id: message.Message()})
        else:
            # If there aren't any message for that team, we'll add a dictionary
            # of messages for that team id on our Bot's messages attribute
            # and we'll add the first message object to the dictionary with
            # the user's id as a key for easy access later.
            self.messages[team_id] = {user_id: message.Message()}
        message_obj = self.messages[team_id][user_id]
        # Then we'll set that message object's channel attribute to the DM
        # of the user we'll communicate with
        message_obj.channel = self.open_dm(user_id)
        # We'll use the message object's method to create the attachments that
        # we'll want to add to our Slack message. This method will also save
        # the attachments on the message object which we're accessing in the
        # API call below through the message object's `attachments` attribute.

        post_message = self.client.api_call("chat.postMessage",
                                            channel=message_obj.channel,
                                            username=self.name,
                                            #icon_emoji=self.emoji,
                                            text="Got it, processing check in for: *" + firstname + " " + lastname +
                                            "* on confirmation number *" + conf_number + "*",
                                            #attachments=message_obj.attachments
                                            )
        print('Sending ' + conf_number, firstname, lastname, user_id, team_id)
        self.pass_checkin(conf_number, firstname, lastname, user_id, team_id)
        timestamp = post_message["ts"]
        # We'll save the timestamp of the message we've just posted on the
        # message object which we'll use to update the message after a user
        # has completed an onboarding task.
        message_obj.timestamp = timestamp

    def checkin_response(self, team_id, user_id, message_text):
        #TODO clean up all this
        """
        Creating response ability for checkin.py
        Parameters
        ----------
        team_id : str
            id of the Slack team associated with the incoming event
        user_id : str
            id of the Slack user associated with the incoming event
        message_text : str
            text for bot to respond with
        """
        # We've imported a Message class from `message.py` that we can use
        # to create message objects for each onboarding message we send to a
        # user. We can use these objects to keep track of the progress each
        # user on each team has made getting through our onboarding tutorial.

        # First, we'll check to see if there's already messages our bot knows
        # of for the team id we've got.
        if self.messages.get(team_id):
            # Then we'll update the message dictionary with a key for the
            # user id we've recieved and a value of a new message object
            self.messages[team_id].update({user_id: message.Message()})
        else:
            # If there aren't any message for that team, we'll add a dictionary
            # of messages for that team id on our Bot's messages attribute
            # and we'll add the first message object to the dictionary with
            # the user's id as a key for easy access later.
            self.messages[team_id] = {user_id: message.Message()}
        message_obj = self.messages[team_id][user_id]
        # Then we'll set that message object's channel attribute to the DM
        # of the user we'll communicate with
        message_obj.channel = self.open_dm(user_id)
        # We'll use the message object's method to create the attachments that
        # we'll want to add to our Slack message. This method will also save
        # the attachments on the message object which we're accessing in the
        # API call below through the message object's `attachments` attribute.

        post_message = self.client.api_call("chat.postMessage",
                                            channel=message_obj.channel,
                                            username=self.name,
                                            #icon_emoji=self.emoji,
                                            text=message_text,
                                            #attachments=message_obj.attachments
                                            )

        timestamp = post_message["ts"]
        # We'll save the timestamp of the message we've just posted on the
        # message object which we'll use to update the message after a user
        # has completed an onboarding task.
        message_obj.timestamp = timestamp
    def update_emoji(self, team_id, user_id):
        """
        Update onboarding welcome message after recieving a "reaction_added"
        event from Slack. Update timestamp for welcome message.
        Parameters
        ----------
        team_id : str
            id of the Slack team associated with the incoming event
        user_id : str
            id of the Slack user associated with the incoming event
        """
        # These updated attachments use markdown and emoji to mark the
        # onboarding task as complete
        completed_attachments = {"text": ":white_check_mark: "
                                         "~*Add an emoji reaction to this "
                                         "message*~ :thinking_face:",
                                 "color": "#439FE0"}
        # Grab the message object we want to update by team id and user id
        message_obj = self.messages[team_id].get(user_id)
        # Update the message's attachments by switching in incomplete
        # attachment with the completed one above.
        message_obj.emoji_attachment.update(completed_attachments)
        # Update the message in Slack
        post_message = self.client.api_call("chat.update",
                                            channel=message_obj.channel,
                                            ts=message_obj.timestamp,
                                            text=message_obj.text,
                                            attachments=message_obj.attachments
                                            )
        # Update the timestamp saved on the message object
        message_obj.timestamp = post_message["ts"]

    def update_pin(self, team_id, user_id):
        """
        Update onboarding welcome message after recieving a "pin_added"
        event from Slack. Update timestamp for welcome message.
        Parameters
        ----------
        team_id : str
            id of the Slack team associated with the incoming event
        user_id : str
            id of the Slack user associated with the incoming event
        """
        # These updated attachments use markdown and emoji to mark the
        # onboarding task as complete
        completed_attachments = {"text": ":white_check_mark: "
                                         "~*Pin this message*~ "
                                         ":round_pushpin:",
                                 "color": "#439FE0"}
        # Grab the message object we want to update by team id and user id
        message_obj = self.messages[team_id].get(user_id)
        # Update the message's attachments by switching in incomplete
        # attachment with the completed one above.
        message_obj.pin_attachment.update(completed_attachments)
        # Update the message in Slack
        post_message = self.client.api_call("chat.update",
                                            channel=message_obj.channel,
                                            ts=message_obj.timestamp,
                                            text=message_obj.text,
                                            attachments=message_obj.attachments
                                            )
        # Update the timestamp saved on the message object
        message_obj.timestamp = post_message["ts"]

    def update_share(self, team_id, user_id):
        """
        Update onboarding welcome message after recieving a "message" event
        with an "is_share" attachment from Slack. Update timestamp for
        welcome message.
        Parameters
        ----------
        team_id : str
            id of the Slack team associated with the incoming event
        user_id : str
            id of the Slack user associated with the incoming event
        """
        # These updated attachments use markdown and emoji to mark the
        # onboarding task as complete
        completed_attachments = {"text": ":white_check_mark: "
                                         "~*Share this Message*~ "
                                         ":mailbox_with_mail:",
                                 "color": "#439FE0"}
        # Grab the message object we want to update by team id and user id
        message_obj = self.messages[team_id].get(user_id)
        # Update the message's attachments by switching in incomplete
        # attachment with the completed one above.
        message_obj.share_attachment.update(completed_attachments)
        # Update the message in Slack
        post_message = self.client.api_call("chat.update",
                                            channel=message_obj.channel,
                                            ts=message_obj.timestamp,
                                            text=message_obj.text,
                                            attachments=message_obj.attachments
                                            )
        # Update the timestamp saved on the message object
        message_obj.timestamp = post_message["ts"]
Beispiel #38
0
import logging
import os
import pickle
import re
import sys

from slackclient import SlackClient

botuser = os.environ.get('SLACK_KARMA_BOTUSER')
token = os.environ.get('SLACK_KARMA_TOKEN')
if not botuser or not token:
    print('Make sure you set SLACK_KARMA_BOTUSER and SLACK_KARMA_TOKEN in env')
    sys.exit(1)

KARMA_BOT = botuser
SLACK_CLIENT = SlackClient(token)

MAX_POINTS = 5

# the first +/- is merely signaling, start counting (regex capture)
# from second +/- onwards, so bob++ adds 1 point, bob+++ = +2, etc
KARMA_ACTION = re.compile(r'(?:^| )(\S{2,}?)\s?[\+\-]([\+\-]+)')
IS_USER = re.compile(r'^<@[^>]+>$')

USERNAME_CACHE = {}
KARMA_CACHE = 'data'

logging.basicConfig(
    level=logging.DEBUG,
    format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s',  # noqa E501
    datefmt='%m-%d %H:%M',
Beispiel #39
0
import os
import time

from slackclient import SlackClient
from commands import *

# Gather all exported tokens
access_token = os.getenv("SERVER_TOKEN")
BOT_ID = os.environ.get("BOT_ID")

AT_BOT = "<@" + BOT_ID + ">"

# instantiate Slack Clients
SLACK_TOKEN = os.environ.get('SLACK_BOT_TOKEN')
slack_client = SlackClient(SLACK_TOKEN)


def handle_command(command, channel):
    """
        Receives commands directed at the bot and determines if they
        are valid commands. If so, then acts on the commands. If not,
        returns back what it needs for clarification.
    """
    response = "Sorry didn't catch that :("

    if command.startswith(DEFAULT_COMMAND):
        response = greeting()

    elif command.startswith(HELP_COMMAND):
        response = help()
import os
from slackclient import SlackClient

SLACK_TOKEN='insert-here-slack-token'

slack_client = SlackClient(SLACK_TOKEN)




def send_message(channel_id, message):
    slack_client.api_call(
        "chat.postMessage",
        channel=channel_id,
        text=message,
        username='******',
        icon_emoji=':space_invader:'
    )
    

if __name__ == '__main__':
    send_message('test_python', "Hello World!")
Beispiel #41
0
    return profile.pop("first_name")


def processIncomingEvent(client, event):
    if commande == "SOF":
        text = text.replace("SOF", "")
        print text
        print requests.get(
            'https://api.stackexchange.com/2.2/search?order=desc&sort=activity&intitle='
            + text + '&site=stackoverflow').text
        sendMessage(
            event.pop("channel"), "Hello " + getfirstNameByID(userID) +
            ", que puis-je faire pour vous ? :tada:")


sc1 = SlackClient(token1)

slack1 = Slack(sc1)
sc2 = SlackClient(token2)
slack2 = Slack(sc2)
listeQuestions = []
waitingForAnswer = []
currentTS = time.time()
if slack1.connect() and slack2.connect():

    listClients = [slack1, slack2]
    while True:
        for client in listClients:
            data = client.fetch()
            for event in data:
                print event
Beispiel #42
0
from lxml import html
import requests
page = requests.get('http://smittenicecream.com/menu/')

tree = html.fromstring(page.content)

flavors = tree.xpath("//span[@class='name']/span/text()")
message = '\n'.join(flavors)

print 'Flavors:', flavors

from slackclient import SlackClient

token = 'xoxb-23465111906-LUJJs8YHOSmpKgf6JU4dMLEC'
sc = SlackClient(token)

print sc.api_call("api.test")
print sc.api_call("channels.info", channel="1234567890")
print sc.api_call("chat.postMessage",
                  channel="#general",
                  text=message,
                  username='******',
                  icon_emoji=':robot_face:')
Beispiel #43
0
if __name__ == "__main__":

  parser = argparse.ArgumentParser(
    formatter_class=argparse.RawDescriptionHelpFormatter,
    description='''
This script posts a message into a slack channel.
Sample commands:
post.py mychannel "This is a message."
''',
    epilog='''''' )
  parser.add_argument('channel', type=str, nargs=1,
                   help='Channel to post to')
  parser.add_argument('message', type=str, nargs=1,
                   help='Message to post')
  args = parser.parse_args()

  config = ConfigParser.RawConfigParser()
  config.read('creds.cfg')
  
  token = config.get("Slack","token")

  client = SlackClient(token)
  client.rtm_connect()

  try:
    post(client, args.channel[0], args.message[0])
  except Exception as e:
    sys.exit("Error: %s" % e.message)

Beispiel #44
0
import os
import time
from slackclient import SlackClient

# randoBot's ID as an env. variable
BOT_ID = os.environ.get("BOT_ID")

# constants
AT_BOT = "<@" + BOT_ID + ">"
EXAMPLE_COMMAND = "do"

# instantiate Slack & Twilio clients
slack_client = SlackClient(os.environ.get('SLACK_BOT_TOKEN'))


def handle_command(command, channel):
    """
		Receives commands directed at the bot and determines if they are valid commands. If so, then acts on the commands. If not, returns back what it needs for clarification.
	"""
    response = "oooohhhh yeeaaahhh brother get ready for some PICKEMS!!! I'M GONNA TAKE YOU DOWN, NICK!!"
    if command.startswith(EXAMPLE_COMMAND):
        response = "Sure... write some more nerd code, then I can do that, dummy!"
    slack_client.api_call("chat.postMessage",
                          channel=channel,
                          text=response,
                          as_user=True)


def parse_slack_output(slack_rtm_output):
    """
		The Slack Real Time Messaging API is an events firehose. this parsing function returns None unless a message is directed at the bot, based on its ID.
Beispiel #45
0
 def connect(self):
     """Convenience method that creates Server instance"""
     self.slack_client = SlackClient(self.token)
     self.slack_client.rtm_connect()
Beispiel #46
0
    async def on_ready():
        if bot._intro_displayed:
            return
        bot._intro_displayed = True

        owner_cog = bot.get_cog('Owner')
        total_cogs = len(owner_cog._list_cogs())
        users = len(set(bot.get_all_members()))
        servers = len(bot.servers)
        channels = len([c for c in bot.get_all_channels()])

        login_time = datetime.datetime.utcnow() - bot.uptime
        login_time = login_time.seconds + login_time.microseconds / 1E6

        print("Login successful. ({}ms)\n".format(login_time))

        owner = await set_bot_owner()

        settings.bot_user = str(bot.user)
        settings.save_settings()

        print("--------------------------")
        print("Red Magician - Discord Bot")
        print("--------------------------")
        print(str(bot.user))
        print("\nConnected to:")
        print("{} servers".format(servers))
        print("{} channels".format(channels))
        print("{} users\n".format(users))
        prefix_label = 'Prefix'
        if len(bot.settings.prefixes) > 1:
            prefix_label += 'es'
        print("{}: {}".format(prefix_label, " ".join(bot.settings.prefixes)))
        print("Owner: {}".format(owner))
        print("{}/{} active cogs with {} commands".format(
            len(bot.cogs), total_cogs, len(bot.commands)))
        print("--------------------------")

        if bot.settings.token and not bot.settings.self_bot:
            print("\nUse this url to bring your bot to a server:")
            url = await get_oauth_url()
            bot.oauth_url = url
            print(url)

        print("\ndealien's Server: https://discord.gg/SN4TvHJ")
        if str(os.environ.get("IS_HEROKU")) == "True":
            herokustatus = True
        else:
            herokustatus = False

        fields = [{
            "title": "Heroku Deployed",
            "value": str(herokustatus),
            "short": True
        }]
        fields.append({
            "title": prefix_label,
            "value": "{}".format(" ".join(bot.settings.prefixes)),
            "short": True
        })
        fields.append({
            "title":
            "Cogs",
            "value":
            "{}/{} active cogs with {} commands".format(
                len(bot.cogs), total_cogs, len(bot.commands)),
            "short":
            True
        })
        fields.append({
            "title": "Active Cogs",
            "value": "{}".format(", ".join(bot.cogs)),
            "short": False
        })
        slackattachments = [{
            "fallback":
            "Red DiscordBot Initialized",
            "color":
            "good",
            "title":
            "Bot Initialized",
            "title_link":
            "https://github.com/dealien/Red-Magician",
            "text":
            "*Servers:* {}, *Channels:* {}, *Users:* {}".format(
                servers, channels, users),
            "fields":
            fields,
            "footer":
            str(bot.user),
            "footer_icon":
            "https://cdn.discordapp.com/app-icons/349363592627486740/eacdbc4e9c80e0db0e1160db529d45a4.png",
            "ts":
            datetime.datetime.now().timestamp()
        }]
        # print(slackattachments)
        SlackClient(settings.slack_token).api_call(
            "chat.postMessage",
            channel=settings.slack_channel,
            attachments=slackattachments,
            mrkdwn=True,
            as_user=False,
            username=str(settings.bot_user).split("#", 1)[0],
            icon_url=
            "https://cdn.discordapp.com/app-icons/349363592627486740/eacdbc4e9c80e0db0e1160db529d45a4.png"
        )
        print("Slack message sent")

        await bot.get_cog('Owner').disable_commands()
Beispiel #47
0
    def __init__(self, token):
        history_length = 20
        summary_frequency = 5
        summary_countdown = summary_frequency
        self.s = requests.Session()
        self.tea = TextEmotionAnalyzer(outputMode="json")
        self.token = token
        sc = SlackClient(token)
        self.history = bot_history(history_length)
        channel = "#dancewithdeanna"
        if sc.rtm_connect():
            while True:
                new_evts = sc.rtm_read()
                for evt in new_evts:
                    if len(evt) != 0:
                        if evt.has_key('text') and not evt.has_key('subtype'):
                            print evt['text']
                            top_emotion = self.analyse(evt['text'],
                                                       evt['user'],
                                                       evt['channel'])
                            if top_emotion is None:
                                print "top emotion is None"
                                continue
                            print top_emotion["docEmotions"]

                            if top_emotion["docEmotions"].has_key('anger'):
                                print sc.api_call(
                                    'chat.postMessage',
                                    channel=channel,
                                    text='Calm down!',
                                    username='******',
                                    icon_emoji=':woman::skin-tone-2:',
                                    as_user='******')
                            elif top_emotion["docEmotions"].has_key('fear'):
                                print sc.api_call(
                                    'chat.postMessage',
                                    channel=channel,
                                    text='Dont worry!',
                                    username='******',
                                    icon_emoji=':woman::skin-tone-2:',
                                    as_user='******')
                            elif top_emotion["docEmotions"].has_key('joy'):
                                print sc.api_call(
                                    'chat.postMessage',
                                    channel=channel,
                                    text='Yay!',
                                    username='******',
                                    icon_emoji=':woman::skin-tone-2:',
                                    as_user='******')
                            elif top_emotion["docEmotions"].has_key('sadness'):
                                print sc.api_call(
                                    'chat.postMessage',
                                    channel=channel,
                                    text='*hugs*!',
                                    username='******',
                                    icon_emoji=':woman::skin-tone-2:',
                                    as_user='******')
                            elif top_emotion["docEmotions"].has_key('disgust'):
                                print sc.api_call(
                                    'chat.postMessage',
                                    channel=channel,
                                    text='Gross!',
                                    username='******',
                                    icon_emoji=':woman::skin-tone-2:',
                                    as_user='******')

                            if (summary_countdown >= 0):
                                summary_countdown -= 1
                            else:
                                print_summary(self.history)
                    time.sleep(1)
        else:
            print "Connection Failed, invalid token?"
import time
import re
from operator import itemgetter
from slackclient import SlackClient
import conf
from tweepy import API
from tweepy import OAuthHandler
import json
import schedule

# instantiate Slack client
slack_client = SlackClient(conf.SLACK_BOT_TOKEN)
# starterbot's user ID in Slack: value is assigned after the bot starts up
starterbot_id = None

# constants
RTM_READ_DELAY = 1  # 1 second delay between reading from RTM
EXAMPLE_COMMAND = "topsy"
MENTION_REGEX = "^<@(|[WU].+?)>(.*)"

auth = OAuthHandler(conf.CONSUMER_KEY, conf.CONSUMER_SECRET)
auth.set_access_token(conf.ACCESS_TOKEN, conf.ACCESS_SECRET)
api = API(auth)


def call_top(sched='True'):
    top_tweets = api.trends_place(1)
    new_tweets = json.dumps(top_tweets, indent=4, sort_keys=True)
    new_tweets = json.loads(new_tweets)
    tweet_dict = new_tweets[0]
Beispiel #49
0
# log quote

import syslog
import sqlite3
import re
import os
import time
import datetime
import sys
import traceback
from daemonize import Daemonize
from slackclient import SlackClient

# Setting up the RTM API
from prodtoken import token
sc = SlackClient(token)
avatar = ":metro-robo:"

# Setting up the Web API
#import json
#import requests
#url = "https://hooks.slack.com/services/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"
#headers={'Content-Type': 'application/json'}

###################################################################### Vars
testmode = False

pid = "/tmp/sassist.pid"
app = "assistant"
nickname = "Métro"
dump = "#dump"
import os
import time
from slackclient import SlackClient
from app.services.corpus_callosum import CorpusCallosum

token = os.environ['SLACK_TOKEN']
sc = SlackClient(token)

if sc.rtm_connect():
    while True:
        events = sc.rtm_read()
        for event in events:
            # Narowing down event types
            # Make sure there's a channel to respond back, there is text, the event type is of message
            # And most importantly to avoid loop, verify if wasn't a bot who sent the message, in which case
            # Matilda would just be forever talking to herself
            if ('channel' in event and 'bot_id' not in event and 'text' in event and event.get('type') == 'message'):
                cc = CorpusCallosum(event);
                
else:
    print ("Connection Failed, invalid token?")
Beispiel #51
0
class Checkbot:
    def __init__(self):
        self.redis = StrictRedis(host=REDIS_HOST, port=REDIS_PORT, password=REDIS_PASSWORD)
        self.slack = SlackClient(SLACK_API_TOKEN)

    def hmart(self):
        form = {
            'custno': HMART_NUMBER,
            'lastname': HMART_NAME,
            'zipcode': HMART_ZIP,
        }

        logger.info(f'checking points for {form}')

        response = requests.post(HMART_POINTS_URL, data=form)
        data = response.json()
        points = data['tpldata'][0]['point']
        date = data['tpldata'][0]['trdate']

        logger.info(f'{points} points as of {date}')

        cached = self.redis.get(HMART_POINTS_KEY)
        is_point_change = int(points) != int(cached) if cached else False

        if not cached or is_point_change:
            logger.info('current points differ from cached points')

            self.redis.set(HMART_POINTS_KEY, points)

            # TODO: include difference between old and new totals in message?
            self.message(f'{points} Hmart points as of {date}')

    def ez(self):
        base_url = 'https://www.ezdrivema.com'
        session = requests.Session()
        session.headers.update({
            'User-Agent': (
                'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_0) AppleWebKit/537.36 (KHTML, like Gecko) '
                'Chrome/69.0.3497.100 Safari/537.36'
            )
        })

        login_url = f'{base_url}/ezpassmalogin'
        response = session.get(login_url)
        logger.info(f'{login_url} get {response.status_code}')

        soup = BeautifulSoup(response.text, 'html.parser')

        with open('forms/login.json') as f:
            form = json.load(f)

        form['__RequestVerificationToken'] = soup.find('input', {'name': '__RequestVerificationToken'}).get('value')
        form['__VIEWSTATE'] = soup.find(id='__VIEWSTATE').get('value')
        form['__EVENTVALIDATION'] = soup.find(id='__EVENTVALIDATION').get('value')
        form['dnn$ctr689$View$txtUserName'] = EZ_USERNAME
        form['dnn$ctr689$View$txtPassword'] = EZ_PASSWORD

        response = session.post(login_url, data=form)
        logger.info(f'{login_url} post {response.status_code}')

        soup = BeautifulSoup(response.text, 'html.parser')
        balance = soup.find(id='dnn_ctr670_ucAccountSummaryMassDot_lblBalance').text
        logger.info(f'balance {balance}')

        cached = self.redis.get(EZ_BALANCE_KEY)
        cached = cached.decode('utf-8') if cached else None
        is_balance_change = balance != cached if cached else False

        if not cached or is_balance_change:
            logger.info('current balance differs from cached balance')

            self.redis.set(EZ_BALANCE_KEY, balance)

            self.message(f'E-ZPass balance is {balance}')
        else:
            logger.info('balance unchanged, exiting')
            return

        tx_url = f'{base_url}/ezpassviewtransactions'
        response = session.get(tx_url)
        logger.info(f'{tx_url} get {response.status_code}')

        soup = BeautifulSoup(response.text, 'html.parser')

        with open('forms/tx.json') as f:
            form = json.load(f)

        form['__RequestVerificationToken'] = soup.find('input', {'name': '__RequestVerificationToken'}).get('value')
        form['__VIEWSTATE'] = soup.find(id='__VIEWSTATE').get('value')
        form['__EVENTVALIDATION'] = soup.find(id='__EVENTVALIDATION').get('value')

        yesterday = datetime.now() - timedelta(days=1)
        yesterday = yesterday.strftime('%m/%d/%Y')
        form['dnn$ctr1180$ucMassDotTcoreTransaction$ucBaseTcoreTransaction$txtStartDate'] = yesterday
        form['dnn$ctr1180$ucMassDotTcoreTransaction$ucBaseTcoreTransaction$txtEndDate'] = yesterday

        response = session.post(tx_url, data=form, timeout=10)
        logger.info(f'{tx_url} post {response.status_code}')

        soup = BeautifulSoup(response.text, 'html.parser')
        table = soup.find(id='dnn_ctr1180_ucMassDotTcoreTransaction_ucBaseTcoreTransaction_AccountGridView')
        rows = table.find_all('tr')

        if len(rows) == 1:
            logger.info('no transactions found')
            return

        header = rows.pop(0)  # noqa: F841
        total = rows.pop()

        dollars = total.find_all('td')[-1].text
        if dollars.startswith('('):
            stripped = dollars.strip('()')
            dollars = f'-{stripped}'

        msg = f'found {len(rows)} transactions totaling {dollars}'
        logger.info(msg)
        self.message(msg)

        for row in rows:
            cells = row.find_all('td')
            tx_type = cells[2].text.lower().strip()

            if 'toll' in tx_type:
                toll_ts = cells[1].get_text(' ')
                toll_loc = cells[6].text
                toll_dollars = cells[8].text.strip('()')

                msg = f'{tx_type} {toll_dollars} at {toll_loc} {toll_ts}'
                logger.info(msg)
                self.message(msg)
            elif 'replenish' in tx_type:
                replenish_ts = cells[0].text
                replenish_dollars = cells[8].text

                msg = f'{tx_type} {replenish_dollars} on {replenish_ts}'
                logger.info(msg)
                self.message(msg)

    def message(self, message):
        self.slack.api_call(
            'chat.postMessage',
            channel=SLACK_CHANNEL,
            text=message,
        )
Beispiel #52
0
import unirest
import numpy as np
import pandas as pd
from pandas.io.json import json_normalize
# starterbot's ID as an environment variable
#export BOT_ID='U4AK5FZTP'
#export SLACK_BOT_TOKEN='xoxb-146651543941-V78nlhngwrirtcf8mSbMPkZM'
#channel_id='C3S7PP03A'
BOT_ID = os.environ.get("BOT_ID")

# constants
AT_BOT = "<@" + BOT_ID + ">"
EXAMPLE_COMMAND = "do"

# instantiate Slack client
slack_client = SlackClient(os.environ.get('SLACK_BOT_TOKEN'))

def image_predictions():
       app = ClarifaiApp("vRFXZQ1VC4WEBnurtH1XiehfUL7DgZoV4oMHcX7n", "DFzeuPqmt0T3UoMODZiCX904IV84SYOHXz0gkdTO")
       model = app.models.get('food-items-v1.0')
       image=app.inputs.create_image_from_filename("/home/aashay/a.jpg")
       predictions=model.predict([image])
       return predictions


def list_channels():
    channels_call = slack_client.api_call("channels.list")
    if channels_call['ok']:
        print channels_call['channels']
        return channels_call['channels']
    return None
Beispiel #53
0
 def execute(self, **kwargs):
     sc = SlackClient(self.token)
     sc.api_call(self.method, **self.params)
Beispiel #54
0
 def __init__(self):
     self.redis = StrictRedis(host=REDIS_HOST, port=REDIS_PORT, password=REDIS_PASSWORD)
     self.slack = SlackClient(SLACK_API_TOKEN)
Beispiel #55
0
import os
import time
from datetime import datetime

from slackclient import SlackClient

slack_token = os.environ["SLACK_API_TOKEN"]
SLACK_WEBHOOK_SECRET = os.environ.get('SLACK_WEBHOOK_SECRET')
sc = SlackClient(slack_token)

# [{'type': 'message',
# 'channel': 'C4H2ZJVUK',
# 'user': '******', 'text': 'hello test bot',
# 'ts': '1489331005.529033', 'source_team': 'T4H2ZJVA7', 'team': 'T4H2ZJVA7'}]

# [{'text': 'Testing :tada:', 'username': '******',
# 'bot_id': 'B4H33G00K', 'type': 'message', 'subtype': 'bot_message',
# 'team': 'T4H2ZJVA7', 'channel': 'C4H2ZJVUK', 'event_ts': '1489330956.526758', 'ts': '1489330956.526758'}]


def rtm_loop(start_time):
    while True:
        events = sc.rtm_read()
        for e in events:
            print(e)
            e_type = e.get('type')
            is_bot = bool(e.get('bot_id'))
            new_message = e.get('ts') and float(e['ts']) > start_time
            e_text = e.get('text')
            parrot_rmt_messages(e_text, e_type, is_bot, new_message)
        time.sleep(1)
Beispiel #56
0
import os
import sys
from slackclient import SlackClient

BOT_NAME = 'portfolio'

TOKEN = os.environ.get('SLACK_BOT_TOKEN')
BOT_ID = os.environ.get('BOT_ID')

if __name__ == "__main__":
    if TOKEN is None:
        TOKEN = sys.argv[1]
    if BOT_ID is None:
        BOT_ID = sys.argv[2]

    slack_client = SlackClient(sys.argv[1])
    api_call = slack_client.api_call("users.list")
    if api_call.get('ok'):
        # retrieve all users so we can find our bot
        users = api_call.get('members')
        for user in users:
            if 'name' in user and user.get('name') == BOT_NAME:
                print("Bot ID for '" + user['name'] + "' is " + user.get('id'))
    else:
        print("could not find bot user with the name " + BOT_NAME)
Beispiel #57
0
class Bot(object):
    def __init__(self, key, codeword='iamgod'):
        self.slack_client = SlackClient(key)
        self.bot_name = "chocbot"
        self.bot_id = self.get_bot_id()
        print('My ID is:', self.bot_id)
        self.codeword = codeword

        self.scoreboard = Scoreboard()
        self.nominators = Scoreboard('Nominators')

        if self.bot_id is None:
            exit("Error, could not find " + self.bot_name)

        self.restore_state()

        self.event = Event(self)
        self.listen()

    def get_bot_id(self):
        api_call = self.slack_client.api_call("users.list")
        if api_call.get('ok'):
            # retrieve all users so we can find our bot
            users = api_call.get('members')
            for user in users:
                if 'name' in user and user.get('name') == self.bot_name:
                    return "<@" + user.get('id') + ">"

            return None

    def get_user_name(self, userid):
        api_call = self.slack_client.api_call("users.list")
        if api_call.get('ok'):
            # retrieve all users so we can find our bot
            users = api_call.get('members')
            for user in users:
                if 'name' in user and user.get('id') == userid:
                    return user.get('name')

        return None

    def listen(self):
        if self.slack_client.rtm_connect(with_team_state=False):
            print("Successfully connected, listening for commands")
            while True:
                self.event.wait_for_event()
                time.sleep(1)
        else:
            exit("Error, Connection Failed")

    def send_message(self, channel, message):
        #sends a message to the noted channel
        self.slack_client.api_call("chat.postMessage",
                                   channel=channel,
                                   text=message,
                                   as_user=True)

    def save_state(self, filename='bot_state.pkl'):
        #dumps the state out to an appropriate file
        try:
            state = {
                'scoreboard': self.scoreboard,
                'nominators': self.nominators
            }
            pickle.dump(state, open(filename, 'wb'))
        except:
            print('Count not save state. Is the location writeable?')

    def restore_state(self, filename='bot_state.pkl'):
        try:
            state = pickle.load(open(filename, 'rb'))
            self.scoreboard = state['scoreboard']
            self.nominators = state['nominators']
            print('Restored state from save file.')
        except:
            print('Save file not found')
Beispiel #58
0
except ImportError as e:
    print(e)
    plt = None

import requests
from slackclient import SlackClient

VELOCITY = 13
SHOOTOUT = 0.6
OVERTIME = 0.8

LOGGER = logging.getLogger(__name__)
LOGGER.setLevel(logging.DEBUG)

SLACK_CLIENT_ID = os.environ.get('SLACK_CLIENT_ID')
SLACK_CLIENT = SlackClient(SLACK_CLIENT_ID)
IMGUR_CLIENT_ID = os.environ.get('IMGUR_CLIENT_ID')
CSV_ID = "11HKFGPgWCA3g8auTNNSqVtyKk6WBuV7UeRYarVTBHvk"


class Team:
    """
    Model to hold ELO histories of each team
    """
    def __init__(self, name, color, emoji):
        self.name = name
        self.history = [1500]
        self.color = color
        self.emoji = emoji

    @property
Beispiel #59
0
from slackbot.bot import Bot
from slackbot.bot import respond_to
from slackclient import SlackClient
from slackbot_settings import API_TOKEN
import re
from scholar_script import ScholarQuerier, ScholarSettings, SearchScholarQuery

sc = SlackClient(API_TOKEN)


def scholar_wrapper():
    querier = ScholarQuerier()
    settings = ScholarSettings()
    querier.apply_settings(settings)

    query = SearchScholarQuery()

    return (querier, query)


@respond_to('doi (.*)')
def doi(message, something):
    message.reply('Try this link: {}'.format("http://dx.doi.org/" + something))


@respond_to('who cited (.*)')
def cited_by(message, something):
    querier, query = scholar_wrapper()
    query.set_words(something)

    querier.send_query(query)
Beispiel #60
0
from slackclient import SlackClient
from firebase import firebase

firebase = firebase.FirebaseApplication(
    'https://slackbotadventures.firebaseio.com/', None)

# starterbot's ID as an environment variable
BOT_ID = os.environ.get("BOT_ID")
BOT_ID = 'U4AA1UYN7'

# constants
AT_BOT = "<@" + BOT_ID + ">"
EXAMPLE_COMMAND = "do"

# instantiate Slack & Twilio clients
slack_client = SlackClient(os.environ.get('SLACK_BOT_TOKEN'))
slack_client = SlackClient('xoxb-146341984755-1fYi3Oau3Cx262xcxP3Tzzp0')


def handle_command(command, channel, user):
    """
        Receives commands directed at the bot and determines if they
        are valid commands. If so, then acts on the commands. If not,
        returns back what it needs for clarification.
    """
    response = "Not sure what you mean. Use the *" + EXAMPLE_COMMAND + \
               "* command with numbers, delimited by spaces."
    if command.startswith("get"):
        name = command.split(" ")
        parsed = '/'
        for part in name: