Пример #1
0
def _handle_slackout(bot, event, command):
    if "_slack_no_repeat" in dir(event) and event._slack_no_repeat:
        return
    """forward messages to slack over webhook"""

    slack_sink = bot.get_config_option('slack')

    if isinstance(slack_sink, list):
        for sinkConfig in slack_sink:

            try:
                slackkey = sinkConfig["key"]
                channel = sinkConfig["channel"]
                convlist = sinkConfig["synced_conversations"]

                if event.conv_id in convlist:
                    fullname = event.user.full_name
                    response = yield from bot._client.getentitybyid(
                        [event.user_id.chat_id])
                    try:
                        photo_url = "http:" + response.entities[
                            0].properties.photo_url
                    except Exception as e:
                        print("Slack: Could not pull avatar for {}".format(
                            fullname))

                    client = SlackClient(slackkey)
                    client.chat_post_message(channel,
                                             event.text,
                                             username=fullname,
                                             icon_url=photo_url)
            except Exception as e:
                print(
                    "Could not handle slackout with key {} between {} and {}. is config.json properly configured?"
                    .format(slackkey, channel, convlist))
Пример #2
0
def _handle_slackout(bot, event, command):
    """forward messages to slack over webhook"""

    slack_sink = bot.get_config_option('slack')

    if isinstance(slack_sink, list):
        for sinkConfig in slack_sink:

            try:
                slackkey = sinkConfig["key"]
                channel = sinkConfig["channel"]
                convlist = sinkConfig["synced_conversations"]

                if event.conv_id in convlist:
                    fullname = event.user.full_name
                    response = yield from bot._client.getentitybyid(
                        [event.user_id.chat_id])
                    try:
                        photo_url = "http:" + response['entity'][0][
                            'properties']['photo_url']
                    except Exception as e:
                        print("Slack: Could not pull avatar for {}".format(
                            fullname))

                    client = SlackClient(slackkey)
                    client.chat_post_message(channel,
                                             event.text,
                                             username=fullname,
                                             icon_url=photo_url)
            except Exception as e:
                print(
                    "Could not handle slackout, is config.json properly configured?"
                )
Пример #3
0
def postOnSlack(channel, botName, message, access_token, log_type):
	slackMessage = ""
	channel = "#%s"%channel
	
	if (time.time() - exeptionHandlingModule.EHM_SLACK_POST_TIME) > 1:
		if log_type == exeptionHandlingModule.EHM_LOG:
			slackMessage = slackMessage + "[ %s - Log ] :information_source: \n"%exeptionHandlingModule.EHM_APP_NAME
			slackMessage = slackMessage + "```Message: %s \nEHM Code: %s ```"%(message, exeptionHandlingModule.EHM_LOG)
		elif log_type == exeptionHandlingModule.EHM_EXCEPTION_CRITICAL:
			slackMessage = slackMessage + "[ %s - CRITICAL ERROR ] :no_entry: \n"%exeptionHandlingModule.EHM_APP_NAME
			slackMessage = slackMessage + "```Message: %s \nEHM Code: %s ```"%(message, exeptionHandlingModule.EHM_LOG)
		elif log_type == exeptionHandlingModule.EHM_EXCEPTION_WARNING:
			slackMessage = slackMessage + "[ %s - WARNING ] :warning: \n"%exeptionHandlingModule.EHM_APP_NAME
			slackMessage = slackMessage + "```Message: %s \nEHM Code: %s ```"%(message, exeptionHandlingModule.EHM_LOG)
		elif log_type == exeptionHandlingModule.EHM_EXCEPTION_IGNORABLE:
			slackMessage = slackMessage + "[ %s - IGNORABLE ERROR ] :heavy_exclamation_mark: \n"%exeptionHandlingModule.EHM_APP_NAME
			slackMessage = slackMessage + "```Message: %s \nEHM Code: %s ```"%(message, exeptionHandlingModule.EHM_LOG)
		try:
			token = access_token
			client = SlackClient(token)
			client.chat_post_message(channel, slackMessage, username=botName)
			exeptionHandlingModule.EHM_SLACK_POST_TIME = time.time()
		except Exception, e:
			print "[ EHM ERROR ] while posting message to slack: %s"%e
			ehmlog("[ EHM ERROR ] while posting message to slack: %s"%e)
Пример #4
0
def _handle_slackout(bot, event, command):
    """forward messages to slack over webhook"""

    slack_sink = bot.get_config_option('slack')

    if isinstance(slack_sink, list):
        for sinkConfig in slack_sink:

            try:
                slackkey = sinkConfig["key"]
                channel = sinkConfig["channel"]
                convlist = sinkConfig["synced_conversations"]

                if event.conv_id in convlist:
                    fullname = event.user.full_name
                    response = yield from bot._client.getentitybyid([event.user_id.chat_id])
                    try:
                       photo_url = "http:" + response.entities[0].properties.photo_url
                    except Exception as e:
                        print("Slack: Could not pull avatar for {}".format(fullname))

                    client = SlackClient(slackkey)
                    client.chat_post_message(channel, event.text, username=fullname, icon_url=photo_url)
            except Exception as e:
                print("Could not handle slackout with key {} between {} and {}. is config.json properly configured?".format(slackkey,channel,convlist))
Пример #5
0
class SlackSender(Module):
    def configure(self):
        self.client = SlackClient('YOUR_SLACK_API_TOKEN_HERE')
        self.current_run = None

    def process(self, blob):
        data = blob['CHData']
        data_io = StringIO(data)

        preamble = DAQPreamble(file_obj=data_io)
        print(ctime())
        print(preamble)

        event = DAQEvent(file_obj=data_io)
        print("Run: {0}".format(event.header.run))
        print("Time Slice: {0}".format(event.header.time_slice))

        if not self.current_run == event.header.run:
            self.current_run = event.header.run
            self.client.chat_post_message(
                "#du2-live",
                "Run #{0} has started!".format(event.header.run),
                username="******"
            )

        return blob
Пример #6
0
def notify_results(results, credentials):
    try:
        if 'slack' in credentials and 'SLACK_TOKEN' in credentials['slack']:
            SLACK_TOKEN = credentials['slack']['SLACK_TOKEN']
            SLACK_CHANNEL = credentials['slack']['SLACK_CHANNEL']
            SLACK_USERNAME = credentials['slack']['SLACK_USERNAME']

            client = SlackClient(SLACK_TOKEN)


            message_output = "Score %s for Test of \"%s\"\n\n"%(results['set'].get_score(), results['site'].title)

            message_output += "Full Report: %s\n\n"%(results['report_url'])

            # for message in results['messages']['success']:
            #     message_output += (message+'\n\n')
            # for message in results['messages']['error']:
            #     message_output += (message+'\n\n')
            # for message in results['messages']['warning']:
            #     message_output += (message+'\n\n')
            # for message in results['messages']['info']:
            #     message_output += (message+'\n\n')


            stripped = stripHtmlTags(message_output)
            client.chat_post_message(SLACK_CHANNEL, stripped, username=SLACK_USERNAME)
        else:
            logger.warn("Warning: Slack API credentials not supplied.")
    except Exception:
        logger.error("Error sending notification to Slack: %s"%(traceback.format_exc()))
Пример #7
0
class SlackNotifier(Notifier):
    def __init__(self, token, channel):
        self.slack = SlackClient(token)
        self.channel = channel

    def post_message(self, bot_name='SoftLayer Nofitier', as_user=True, **kwargs):
        type = kwargs.get('type')
        account = kwargs.get('account')
        update = kwargs.get('update')
        update_date = kwargs.get('update_date')
        href = kwargs.get('href')
        id = kwargs.get('id')
        color = kwargs.get('color')

        attachments = dict()
        attachments['thumb_url'] = 'https://pbs.twimg.com/profile_images/969317315/CLEAN_sl-logo_400x400.jpg'
        attachments['color'] = kwargs.get('color')

        attachments['title'] = 'Notification of UPDATE: %s %s under %s' % (
            type, id, account)
        attachments['title_link'] = href
        attachments['text'] = 'Update Date: %s\nUpdate Content:%s' % (
            update_date, update)

        logging.debug('Slack message: %s' % str(attachments))
        self.slack.chat_post_message(self.channel,
                                     '',
                                     username=bot_name,
                                     as_user=as_user,
                                     attachments=json.JSONEncoder().encode([attachments]))
Пример #8
0
class Slackchat:
    def __init__(self):
        settings = sublime.load_settings("SubSlack.sublime-settings")
        token = settings.get("token")
        self.bot = settings.get("bot_name")
        self.room = "#%s" % settings.get("default_chat")
        self.client = SlackClient(token)

    def post(self, text):
        self.client.chat_post_message(self.room, text, username=self.bot)
Пример #9
0
class Slackchat:
    def __init__(self):
        settings = sublime.load_settings("SubSlack.sublime-settings")
        token = settings.get('token')
        self.bot = settings.get('bot_name')
        self.room = '#%s' % settings.get('default_chat')
        self.client = SlackClient(token)

    def post(self, text):
        self.client.chat_post_message(self.room, text, username=self.bot)
Пример #10
0
 def send_general(text):
     if settings.SLACK_ENABLED:
         connection = SlackClient(settings.SLACK_TOKEN)
         try:
             connection.chat_post_message(
                 settings.SLACK_TEST_CHANNEL if settings.SLACK_TEST else settings.SLACK_GENERAL_CHANNEL, text,
                 username=settings.SLACK_BOT, parse='full', unfurl_links='true')
             return True
         except:
             pass
     return False
Пример #11
0
def talk_to_slack():
    # this function sends the same output of the files to slack
    get_last_data()
    token_dir = os.path.expanduser("~/.packages/conf/conf.txt")
    client = None
    if os.path.exists(token_dir):
        with open(token_dir, "r") as fp:
            client = SlackClient(fp.readlines()[0].strip())
    with open(LOG_FILE_DIR, "a+") as fp:
        fp.write(last_data + "\n")
    if client is not None:
        client.chat_post_message("#mail-tracker-notif", last_data, username="******")
    sys.exit(0)
Пример #12
0
 def send_kill(kill_id):
     if settings.SLACK_ENABLED:
         connection = SlackClient(settings.SLACK_TOKEN)
         try:
             connection.chat_post_message(
                 settings.SLACK_TEST_CHANNEL if settings.SLACK_TEST else settings.SLACK_KILL_CHANNEL,
                 "https://zkillboard.com/kill/" + str(kill_id) + "/",
                 username=settings.SLACK_BOT,
                 parse='full',
                 unfurl_links='true')
             return True
         except:
             pass
     return False
Пример #13
0
def talk_to_slack():
    # this function sends the same output of the files to slack
    get_last_data()
    token_dir = os.path.expanduser('~/.packages/conf/conf.txt')
    client = None
    if os.path.exists(token_dir):
        with open(token_dir, 'r') as fp:
            client = SlackClient(fp.readlines()[0].strip())
    with open(LOG_FILE_DIR, 'a+') as fp:
        fp.write(last_data + '\n')
    if client is not None:
        client.chat_post_message('#mail-tracker-notif',
                                 last_data,
                                 username='******')
    sys.exit(0)
Пример #14
0
    def post(self, request):
        serializer = SlackChatSerializer(data=request.data)
        client = SlackClient(
            'xoxp-4254176702-8269771440-11734785028-c59bdd6fab')
        if serializer.is_valid():
            try:
                message_construct = serializer.data['message_construct']
                chat_message = client.chat_post_message('#help',
                                                        message_construct,
                                                        username='******')
                content = {'data': chat_message}
                return Response(content)

            except ObjectDoesNotExist:
                raise Http404
Пример #15
0
def _handle_slackout(bot, event, command):
    if "_slack_no_repeat" in dir(event) and event._slack_no_repeat:
        return

    """forward messages to slack over webhook"""

    slack_sink = bot.get_config_option('slack')

    if isinstance(slack_sink, list):
        for sinkConfig in slack_sink:

            try:
                slackkey = sinkConfig["key"]
                channel = sinkConfig["channel"]
                convlist = sinkConfig["synced_conversations"]

                if event.conv_id in convlist:
                    fullname = event.user.full_name
                    response = yield from bot._client.getentitybyid([event.user_id.chat_id])
                    try:
                        photo_url = "http:" + \
                            response.entities[0].properties.photo_url
                    except Exception as e:
                        logger.exception(
                            "FAILED to acquire photo_url for {}".format(fullname))
                        photo_url = None

                    try:
                        client = SlackClient(slackkey, verify=True)
                    except TypeError:
                        client = SlackClient(slackkey)

                    slack_api_params = {'username': fullname,
                                        'icon_url': photo_url}

                    if "link_names" not in sinkConfig or sinkConfig["link_names"]:
                        logger.debug("slack api link_names is active")
                        slack_api_params["link_names"] = 1

                    if bot.conversations.catalog[event.conv_id]["history"] or "otr_privacy" not in sinkConfig or not sinkConfig["otr_privacy"]:
                        client.chat_post_message(
                            channel, event.text, **slack_api_params)

            except Exception as e:
                logger.exception("Could not handle slackout with key {} between {} and {}."
                                 " Is config.json properly configured?".format(slackkey,
                                                                               channel,
                                                                               convlist))
Пример #16
0
class Logger:

    def __init__(self, verbosity=1, reporting=1):
        '''
        Logger util for relevant data and errors.

        Args:
            verbosity: 0 silences logger in console, 1 prints output.
                Logging to file is active at any level.
            reporting: 0 silences reporting, 1 logs into logfile,
                2 sends Slack message only,
                3 sends email only,
                4 sends both Slack and email messages.
                Both 2, 3 and 4 also print to logfile.
        '''
        self.verbosity = verbosity
        self.reporting = reporting

        self.__setup_file_logging()

        try:
            self.email = smtplib.SMTP(
                settings.EMAIL_SMTP_SERVER, settings.EMAIL_SMTP_PORT
            )
        except gaierror, e:
            self.__error_to_file(e)

        self.slack = SlackClient(settings.SLACK_API_KEY)
Пример #17
0
def slackusers(bot, event, *args):
    slack_sink = bot.get_config_option('slack')
    if isinstance(slack_sink, list):
        for sinkConfig in slack_sink:
            slackkey = sinkConfig["key"]
            channel = sinkConfig["channel"]
            convlist = sinkConfig["synced_conversations"]

            if event.conv_id in convlist:
                try:
                    client = SlackClient(slackkey, verify=True)
                except TypeError:
                    client = SlackClient(slackkey)

                chan_id = client.channel_name_to_id(channel)
                slack_api_params = {'channel': chan_id}
                info = client._make_request('channels.info', slack_api_params)
                msg =  "Slack channel {}: {}".format(info['channel']['name'],
                                                       info['channel']['topic']['value'])
                users = {}
                for uid in info['channel']['members']:
                    slack_api_params = {'user': uid}
                    user = client._make_request('users.info', slack_api_params)
                    if user["ok"] and user['user']:
                        username = user['user']['name']
                        realname = user['user'].get('real_name', "No real name")
                        users[username] = realname

                msg += "\n{} members:".format(len(users))

                for username, realname in sorted(users.items()):
                    msg += "\n  {}: {}".format(username, realname)

                yield from bot.coro_send_message(event.conv, msg)
def main(argv=sys.argv):
    import getopt
    short_args = "hp:e:at:c:"
    long_args = [
        "help",
        "program=",
        "event=",
        "any",
        "token="
        "channel=",
        ]
    arguments = argv[1:]
    try:
        opts, args = getopt.getopt(arguments, short_args, long_args)
    except:
        usage()

    programs = []
    events = []
    any = False
    channel = ''
    token = ''

    for option, value in opts:

        if option in ('-h', '--help'):
            usage()

        if option in ('-p', '--program'):
            programs.append(value)

        if option in ('-e', '--event'):
            events.append(value)

        if option in ('-a', '--any'):
            any = True

        if option in ('-t', '--token'):
            token = value

        if option in ('-c', '--channel'):
            channel = value

    if not events:
        events = config.events.keys()

    if 'SUPERVISOR_SERVER_URL' not in os.environ:
        sys.stderr.write('slack must be run as a supervisor event '
                         'listener\n')
        sys.stderr.flush()
        return

    sys.stderr.flush()
    slackClient = SlackClient(token)

    prog = SlackNotifier(slackClient, programs, any, events, channel)
    prog.runforever()
Пример #19
0
def _slack_send(bot, sinkConfig, message, chat_id, passthru):

    _response = yield from bot._client.get_entity_by_id(
        hangups.hangouts_pb2.GetEntityByIdRequest(
            request_header = bot._client.get_request_header(),
            batch_lookup_spec = [
                hangups.hangouts_pb2.EntityLookupSpec(
                    gaia_id = chat_id )]))

    try:
        photo_url = "http:" + _response.entity[0].properties.photo_url
    except Exception as e:
        logger.exception("FAILED to acquire photo_url for {}".format(fullname))
        photo_url = None

    if "original_request" in passthru:
        message = passthru["original_request"]["message"]
        if isinstance(passthru["original_request"]["user"], str):
            fullname = passthru["original_request"]["user"]
        else:
            fullname = _response.entity[0].properties.display_name;

    try:
        try:
            client = SlackClient(sinkConfig["key"], verify=True)
        except TypeError:
            client = SlackClient(sinkConfig["key"])

        slack_api_params = { 'username': fullname,
                             'icon_url': photo_url }

        if "link_names" not in sinkConfig or sinkConfig["link_names"]:
            logger.debug("slack api link_names is active")
            slack_api_params["link_names"] = 1

        client.chat_post_message(sinkConfig["channel"],  message, **slack_api_params)
    except Exception as e:
        logger.exception( "Could not handle slackout with key {} between {} and {}. "
                          "Is config.json properly configured?".format( slackkey,
                                                                        channel ))
 def process_flow(self, data, jenkins_master):
     build_status = data.get('build').get('status')
     if build_status != 'FAILURE':
         self.log.debug('This flow will not be processed')
         return
     
     build_number = data.get('build').get('number')
     build = self.jenkins_master[data.get('name')].get_build(int(build_number))
     build_name = build.name
     console = build.get_console()
     lines = console.split('\n')
     line_number = len(lines)
     index = 0
     failed_jobs = {}
     while index < line_number:
         if lines[index].startswith('[Result] FAILURE'):
             job_name = lines[index - 1].lstrip('[Job Name]').lstrip().rstrip('\n')
             url = lines[index + 1].lstrip('[URL]').lstrip().rstrip('\n')
             failed_jobs[job_name] = url
         index = index + 1
         
     full_url = data.get('build').get('full_url')
     
     if len(failed_jobs) == 0:
         msg = '<%s|%s> failed' % (full_url, build_name)
     else:
         failed_jobs_msg = ''
         for name in failed_jobs:
             failed_jobs_msg = ' '.join([failed_jobs_msg, '<%s|%s>' % (failed_jobs[name], name)])
         msg = '<%s|%s> failed at %s' % (full_url, build_name, failed_jobs_msg)
     
     self.log.debug('Slack message: %s' % msg)
     
     slack_token = self.config['slack']['token']
     slack_botname = self.config['slack']['name']
     slack_channel = self.config['slack']['channel']
     
     slack = SlackClient(slack_token)
        
     slack.chat_post_message(slack_channel, msg, username=slack_botname, mrkdwn=True)
Пример #21
0
class ChatClient():
    def __init__(self, token, user, send_to):
        self.client = SlackClient(token)
        self.user = user
        self.send_to = send_to

    def _send_msg(self, msg):
        self.client.chat_post_message(self.send_to, msg, username=self.user)

    def allow_airline(self, airline, iata):
        self._send_msg("Airline '%s (%s)' allowed in search" % (airline, iata))

    def disable_airline(self, airline, iata, reason):
        self._send_msg("Airline '%s (%s)' disabled in search because: %s" %
                       (airline, iata, reason))

    def start_scraping(self, airline, iata):
        self._send_msg("Scraping of airline '%s (%s)' started" %
                       (airline, iata))

    def stop_scraping(self, airline, iata, reason):
        self._send_msg("Scraping of airline '%s (%s)' stopped because: %s" %
                       (airline, iata, reason))

    def start_automat(self, airline, iata):
        self._send_msg("Automat for airline '%s (%s)' started" %
                       (airline, iata))

    def stop_automat(self, airline, iata, reason):
        self._send_msg("Automat for airline '%s (%s)' stopped because: %s" %
                       (airline, iata, reason))

    def saving_deactivated(self, iata):
        self._send_msg("Saving results to DB deactivated for airline '%s' " %
                       (iata))

    def saving_activated(self, iata):
        self._send_msg("Saving results to DB activated for airline '%s' " %
                       (iata))
Пример #22
0
    def __init__(self, connect=True):
        # Lets get set up
        botPass = {}
        if botData.token_id:
            self.client = SlackClient(botData.token_id)
        if connect is True:
            req = self.client._make_request('rtm.start', {})
            socket_url = req['url']
            self.ws = websocket.WebSocket()
            self.ws.connect(socket_url)
        else:
            self.ws = websocket.WebSocket()

        # Compile regex triggers and url regex
        self.triggers = {}
        for key, val in self.hooks.iteritems():
            self.triggers[key] = re.compile(val)

        self.urlChecker = re.compile(self.urlFixer)

        # For Python 2.x
        self.html_parser = HTMLParser.HTMLParser()
Пример #23
0
def main():
    global LAST_UPDATE_ID

    parser = argparse.ArgumentParser(description=BOT_DESCRIPTION)
    parser.add_argument("--logfile",
                        type=str,
                        default='log',
                        help="Path to log file")
    parser.add_argument("--dbfile",
                        type=str,
                        default='proofspace.sqlite',
                        help="Path to sqlite DB file")
    args = parser.parse_args()

    botDB.bind('sqlite', args.dbfile, create_db=True)
    botDB.generate_mapping(create_tables=True)

    # TODO: use it
    logging.basicConfig(
        format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')

    http = urllib3.PoolManager(cert_reqs='CERT_REQUIRED',
                               ca_certs=certifi.where())

    telegram_token = open('.telegram_token').readline().strip()
    slack_token = open('.slack_token').readline().strip()
    bot = telegram.Bot(telegram_token)
    slackbot = SlackClient(slack_token)

    try:
        LAST_UPDATE_ID = bot.getUpdates()[-1].update_id
    except IndexError:
        LAST_UPDATE_ID = None

    while True:
        try:
            run(bot, args.logfile, slackbot)
        except telegram.TelegramError as error:
            print "TelegramError", error
            time.sleep(1)
        #except urllib2.URLError as error:
        #    print "URLError", error
        #    time.sleep(1)
        except:
            traceback.print_exc()
            try:
                bot.sendMessage(chat_id=CHAT_ID_ALARM, text=MESSAGE_ALARM)
            except:
                pass
            time.sleep(100)  # 100 seconds
Пример #24
0
def _handle_slackout(bot, event, command):
    if "_slack_no_repeat" in dir(event) and event._slack_no_repeat:
        return
    """forward messages to slack over webhook"""

    slack_sink = bot.get_config_option('slack')

    if isinstance(slack_sink, list):
        for sinkConfig in slack_sink:

            try:
                slackkey = sinkConfig["key"]
                channel = sinkConfig["channel"]
                convlist = sinkConfig["synced_conversations"]

                if event.conv_id in convlist:
                    fullname = event.user.full_name
                    response = yield from bot._client.getentitybyid(
                        [event.user_id.chat_id])
                    try:
                        photo_url = "http:" + response.entities[
                            0].properties.photo_url
                    except Exception as e:
                        logger.exception(
                            "FAILED to acquire photo_url for {}".format(
                                fullname))
                        photo_url = None

                    try:
                        client = SlackClient(slackkey, verify=True)
                    except TypeError:
                        client = SlackClient(slackkey)

                    slack_api_params = {
                        'username': fullname,
                        'icon_url': photo_url
                    }

                    if "link_names" not in sinkConfig or sinkConfig[
                            "link_names"]:
                        logger.debug("slack api link_names is active")
                        slack_api_params["link_names"] = 1

                    client.chat_post_message(channel, event.text,
                                             **slack_api_params)

            except Exception as e:
                logger.exception(
                    "Could not handle slackout with key {} between {} and {}."
                    " Is config.json properly configured?".format(
                        slackkey, channel, convlist))
Пример #25
0
    def __init__(self, connect=True):
        # Lets get set up
        botPass = {}
        if botData.token_id:
            self.client = SlackClient(botData.token_id)
        if connect is True:
            req         = self.client._make_request('rtm.start', {})
            socket_url  = req['url']
            self.ws     = websocket.WebSocket()
            self.ws.connect(socket_url)
        else:
            self.ws     = websocket.WebSocket()
            
        # Compile regex triggers and url regex
        self.triggers = {}
        for key, val in self.hooks.iteritems():
            self.triggers[key] = re.compile(val)

        self.urlChecker = re.compile(self.urlFixer)
        
        # For Python 2.x
        self.html_parser = HTMLParser.HTMLParser()
Пример #26
0
def _slack_send(bot, sinkConfig, message, chat_id, passthru):

    _response = yield from bot._client.get_entity_by_id(
        hangups.hangouts_pb2.GetEntityByIdRequest(
            request_header=bot._client.get_request_header(),
            batch_lookup_spec=[
                hangups.hangouts_pb2.EntityLookupSpec(gaia_id=chat_id)
            ]))

    try:
        photo_url = "http:" + _response.entity[0].properties.photo_url
    except Exception as e:
        logger.exception("FAILED to acquire photo_url for {}".format(fullname))
        photo_url = None

    if "original_request" in passthru:
        message = passthru["original_request"]["message"]
        if isinstance(passthru["original_request"]["user"], str):
            fullname = passthru["original_request"]["user"]
        else:
            fullname = _response.entity[0].properties.display_name

    try:
        try:
            client = SlackClient(sinkConfig["key"], verify=True)
        except TypeError:
            client = SlackClient(sinkConfig["key"])

        slack_api_params = {'username': fullname, 'icon_url': photo_url}

        if "link_names" not in sinkConfig or sinkConfig["link_names"]:
            logger.debug("slack api link_names is active")
            slack_api_params["link_names"] = 1

        client.chat_post_message(sinkConfig["channel"], message,
                                 **slack_api_params)
    except Exception as e:
        logger.exception(
            "Could not handle slackout with key {} between {} and {}. "
            "Is config.json properly configured?".format(slackkey, channel))
Пример #27
0
from pyslack import SlackClient
client = SlackClient('')
client.chat_post_message('#group3', "testing, testing...", username='******')

Пример #28
0
class SlackResponder(object):
    # Messages we understand and parse
    hooks = {
        "add": "^(\.add) \<\@([\w]+)\> ?(admin|superuser)?",
        "del": "^(\.del) \<\@([\w]+)\>",
        "hide": "^(\.hide) \<\@([\w]+)\>",
        "show": "^(\.show) \<\@([\w]+)\>",
        "twitter": "^(\.twitter) ([\w]+)$",
        "email": "^(\.email) \<mailto\:([\w+\.-@]+)|[\w+\.-@]+\>$",
        "image": "^(\.image) \<(.*)\>$",
        "name": "^(\.name) (.*)$",
        "balance": "^(\.balance) ([A-Za-z0-9]{25,36})$",
        "rate":
        "^(\.rate) ([\w]+) ?(usd|USD|eur|EUR|cny|CNY|cad|CAD|rub|RUB|btc|BTC)?",
        "status": "^(\.status) (.*)$",
        "undo": "^\.undo",
        "list": "^\.list",
        "regen": "^\.regen",
        "ping": "^\.ping",
        "whoami": "^\.whoami",
        "help": "^\.help",
        "lazy": "^\.lazy"
    }

    # User ability level
    userLevel = {"none": 0, "user": 1, "superuser": 2, "owner": 3}

    # Url regex
    urlFixer = "<(https?:\/\/[^>]+)>"

    def __init__(self, connect=True):
        # Lets get set up
        botPass = {}
        if botData.token_id:
            self.client = SlackClient(botData.token_id)
        if connect is True:
            req = self.client._make_request('rtm.start', {})
            socket_url = req['url']
            self.ws = websocket.WebSocket()
            self.ws.connect(socket_url)
        else:
            self.ws = websocket.WebSocket()

        # Compile regex triggers and url regex
        self.triggers = {}
        for key, val in self.hooks.iteritems():
            self.triggers[key] = re.compile(val)

        self.urlChecker = re.compile(self.urlFixer)

        # For Python 2.x
        self.html_parser = HTMLParser.HTMLParser()
        # For Python 3.x
        # self.html_parser = html.parser.HTMLParser()

    def SetupJson(self):
        logger = logging.getLogger("SlackBot")
        if os.path.isfile(botData.status_file):
            # It exists, lets read it in.
            status_in = open(botData.status_file, "r")
            data = status_in.read()
            status_in.close()
            self.botJson = simplejson.loads(data)
        else:
            # Starting over
            self.botJson = {
                "users": {},
                "updates": {},
                "undo": {},
                "admins": [],
                "superusers": [],
                "hidden": []
            }

        if botData.owner_id and botData.owner_id not in self.botJson[
                'superusers']:
            self.botJson['superusers'].append(botData.owner_id)
        if botData.owner_id and botData.owner_id not in self.botJson['users']:
            self.botJson['users'][botData.owner_id] = {}

        return

    def SaveJson(self):
        with open(botData.status_file, 'w') as status_out:
            json.dump(self.botJson, status_out)
            status_out.close()
        return

    def Parse(self, postData):
        ''' Parses a (should be) matching request of the bot
        : param postData: dict from the post sent to the bot from Slack
        : return: String containing response for the user:
        '''
        logger = logging.getLogger("SlackBot")
        logger.debug("User ID: " + postData['user_id'])

        # Verify Token
        if postData['token'] != botData.hook_token:
            logger.debug("Token from Slack does not match ours, ignoring.")
            return

        logger.debug("Looking through hooks for a match...")
        logger.debug("Got: " + str(postData['text']))
        for key, val in self.triggers.iteritems():
            test = self.triggers[key].match(postData['text'])
            if test:
                logger.debug("Got a match with: " + self.hooks[key])
                return self._Process(
                    postData, re.findall(self.triggers[key], postData['text']))
        # Still here? Very unlikely
        return "Huh?"

    def _Process(self, postData, matchText):
        logger = logging.getLogger("SlackBot")
        self.SetupJson()  # Needed for comparison checks
        # logger.debug(json.dumps(postData, indent=4))

        try:
            del postData['token'], postData['trigger_word'], postData[
                'team_id']
            del postData['channel_name'], postData['user_name']
        except:
            pass

        if postData['user_id'] == botData.owner_id:
            postData['uLevel'] = self.userLevel['owner']  # 3
        elif postData['user_id'] in self.botJson['superusers']:
            postData['uLevel'] = self.userLevel['superuser']  # 2
        elif postData['user_id'] in self.botJson['admins']:
            postData['uLevel'] = self.userLevel['user']  # 1
        else:
            postData['uLevel'] = self.userLevel['none']  # 0

        request = matchText[0]
        logger.debug("Request: " + str(request))

        if not isinstance(request, basestring):
            if len(request) >= 2:
                trigger = request[0]
                argument = request[1]
                logger.debug("Trigger: " + trigger)
                logger.debug("Argument: " + argument)
                # Third value for a user class (for .add)
                if trigger == ".add":
                    try:
                        userClass = request[2]
                    except:
                        userClass = "admin"
                elif trigger == ".del":
                    try:
                        if k[2].lower() in ("yes", "true", "t", "1"):
                            hideUser = True
                        else:
                            hideUser = False
                    except:
                        hideUser = False
                elif trigger == ".rate":
                    try:
                        rateType = request[2]
                    except:
                        rateType = "usd"

                forbidden = [
                    '.status', '.add', '.del', '.show', '.hide', '.name',
                    '.image', '.email', '.twitter', '.undo', '.regen'
                ]
                if trigger in forbidden and postData['uLevel'] < 1:
                    return "<@" + postData[
                        'user_id'] + ">: You are not an authorised user."

                # Status update?
                if trigger == ".status":
                    return self.PostStatusUpdate(postData, argument)
                # Is the owner trying to be added or deleted?
                elif trigger == ".add" or trigger == ".del":
                    if str(argument) == str(botData.owner_id):
                        return "<@" + postData[
                            'user_id'] + ">: Cannot perform actions on bot owner."
                    if trigger == ".add":
                        return self.PromoteUser(postData, argument, userClass)
                    elif trigger == ".del":  # Removes from either list
                        return self.DemoteUser(postData, argument, hideUser)
                # Show/hide condition?
                elif trigger == ".show" or trigger == ".hide":
                    if trigger == ".show":
                        return self.ShowUserPosts(postData, argument)
                    elif trigger == ".hide":
                        return self.HideUserPosts(postData, argument)
                # User details?
                elif trigger == ".name" or trigger == ".image" or trigger == ".email":
                    if trigger == ".name":
                        return self.UpdateUserInfo(postData, "name", argument)
                    elif trigger == ".email":
                        return self.UpdateUserInfo(postData, "email", argument)
                    elif trigger == ".image":
                        return self.UpdateUserInfo(postData, "image", argument)
                elif trigger == ".balance":
                    return "Balance for address " + argument + ": " + str(
                        self.GetBalance(argument)) + " SJCX"
                elif trigger == ".twitter":
                    self.SetupJson()
                    self.botJson['users'][
                        postData['user_id']]['twitter'] = argument
                    self.SaveJson()
                    return "<@" + postData[
                        'user_id'] + ">: Your twitter handle is now '" + argument + "'."
                elif trigger == ".rate":
                    return self.GetExRate(argument, rateType)
                else:
                    return "No response to give!"
        elif request == ".list":
            return self.AdminList(postData)
        elif request == ".undo":
            return self.UndoPost(postData)
        elif request == ".regen":
            return self.OutputTemplate(postData)
        elif request == ".ping":
            return "PONG!"
        elif request == ".whoami":
            return "Hello <@" + postData[
                'user_id'] + ">, your user id is " + postData['user_id'] + "."
        elif request == ".help":
            return self.HelpResponse()
        elif request == ".lazy":
            return self.FindLazyUsers()
        else:
            return "No response to give!"

    def HelpResponse(self):
        return textwrap.dedent("""
            Hello, I'm SlackBot. Standard commands you can use with me are:\n
            .add (username) <superuser> - Authorise a user to post status updates. Include 'superuser' to
            give them the power to add or remove other users from the authorised list.\n
            .del (username) - Revokes status updates from a user.\n
            .show (username) - Show posts from a user on the status page.\n
            .hide (username) - Hide posts from a user on the status page.\n
            .name (name) - Updates name shown for a user added to the bot.\n
            .image (url) - Updates the image shown for a user added to the bot.\n
            .email (address) - Updates name shown for a user added to the bot (not that this is shown normally).\n
            .twitter (name) - Updates the twitter address for a user from the default.\n
            .status (text) - Post a status update! Use whatever text you want, it will be used in the output.\n
            .undo - Didn't mean to post that last status update? This will return it to what you said last.\n
            .regen - Force regeneration of the status page from the template.\n
            .whoami - Tells you your user_id, should you wish to change any 'settings' :)\n
            .list - Lists bot users authorised to post status updates.\n
            .rate (coin) (currency) - Fetches exchange rates for coins at CoinMarketCap, uses the top 100
            coins they track, with USD, CAD, CNY, RUB and BTC as supported currencies.
            \n
            Enjoy!
            """)

    def PostStatusUpdate(self, user, text):
        ''' Creates a status update for a user, refreshes template.
        @param user: json dict representing the user data
        @param text: The status text the user wishes to post
        @return: String to send back to the user
        '''
        self.SetupJson()
        user['text'] = self.TextParser(text)
        user['ts'] = user['timestamp']
        del user['timestamp']
        self.botJson['updates'][user['user_id']] = user
        if user['user_id'] in self.botJson['undo']:
            old = self.botJson['updates'][user['user_id']]
            self.botJson['undo'][user['user_id']] = old  # Copy before replace
            self.botJson['updates'][
                user['user_id']] = user  # Update this user with latest post
        else:
            self.botJson['undo'][
                user['user_id']] = user  # Set them both to the same to start
            self.botJson['updates'][user['user_id']] = user
        self.SaveJson()
        self.OutputTemplate(user)
        return "<@" + user[
            'user_id'] + ">: Status update accepted, template updated."

    def TextParser(self, text):
        ''' Parses info from slack, e.g. urls '''
        logger = logging.getLogger("SlackBot")
        logger.debug("Looking for a URL match...'" + str(text) + "'")
        # Single
        for m in self.urlChecker.findall(text):
            text = text.replace(
                "<" + m + ">", "<a href=\\\"" + m + "\\\">" +
                self.html_parser.escape(m) + "</a>")

        return text

    def PromoteUser(self, user, subject, level):
        ''' Promotes a user to a higher level so they can post updates, or at
        superuser level they can promote other users to update posting level.
        @param user: json dict representing the user data
        @param subject: The user to act on
        @param level: int user level to promote to, 1=user, 2=superuser
        @return: String to send back to the user.
        '''
        logger = logging.getLogger("SlackBot")
        self.SetupJson()
        logger.debug(json.dumps(user, indent=4))
        response = ""
        if level == "superuser":
            if user['uLevel'] >= 3:
                if subject in self.botJson['superusers']:
                    return "<@" + user['user_id'] + ">: Action not needed."
                self.botJson['superusers'].append(subject)
                self.SaveJson()
                response += "<@" + user[
                    'user_id'] + ">: User <@" + subject + "> added to superusers.\n"
            else:
                return "<@" + user[
                    'user_id'] + ">: You are not authorised to add other superusers."
        else:
            if user['uLevel'] >= 2:
                if subject in self.botJson['admins']:
                    return "<@" + user['user_id'] + ">: Action not needed."
                self.botJson['admins'].append(subject)
                self.SaveJson()
                response += "<@" + user[
                    'user_id'] + ">: User <@" + subject + "> added to authorised users.\n"
            else:
                return "<@" + user[
                    'user_id'] + ">: You are not authorised to add other users."

        newUser = {}
        ''' Is the rtm api token set up? If not, complain at them.'''
        if not botData.token_id:
            self.botJson['users'][subject] = {}
            self.SaveJson()

            response += "<@" + subject + ">: I cannot access Slack to get your user info so you will need to enter it manually.\n"
            response += "I need your name, email and twitter details at minimum - I'll generate a gravatar address from your "
            response + "email unless you specify it as below.\n"
            response += "You can use the commands .name,.email and .twitter to update your details.\n"
            response += "You can also use .image to force your image to a direct url if Gravatar does not work with your email.\n"
            response += "Example: \".name Slack User\", \".email [email protected]\", \".image <url\", \".twitter tweeter\".\n"
            return response
        else:
            req = self.client._make_request('users.info', {'user': subject})
            logger.debug(json.dumps(req, indent=4))
            newUser['name'] = req['user']['profile']['real_name']
            newUser['image'] = req['user']['profile']['image_72']
            newUser['email'] = req['user']['profile']['email']
            newUser['twitter'] = "storjproject"
            self.botJson['users'][user['user_id']] = newUser
            self.SaveJson()

            response += "<@" + subject + ">: I have set up your profile with what I can gather immediately from Slack.\n"
            response += "If you want, you can use the commands .name,.email and .twitter to update your details.\n"
            response += "You can also use .image to force your image to a direct url if Gravatar does not work with your email.\n"
            response += "Example: \".name Slack User\", \".email [email protected]\", \".twitter tweeter\".\n"
            return response

    def DemoteUser(self, user, subject, hide):
        ''' Demotes a user so they won't be allowed to post updates. Optional hide posts.
        Doesn't matter what level they are, they're gone.
        @param user: json dict representing the user data
        @param subject: The user to act upon
        @param hide: Bool to hide posts by the user at the same time
        @return: String to send back to the user
        '''
        logger = logging.getLogger("SlackBot")
        self.SetupJson()
        if subject in self.botJson['admins']:
            logger.debug(self.botJson['admins'].index(subject))
            userIndex = self.botJson['admins'].index(subject)
            del self.botJson['admins'][userIndex]
            if subject in self.botJson['updates']:
                del self.botJson['updates'][subject]
            self.SaveJson()
            self.OutputTemplate(user)
            return "<@" + user[
                'user_id'] + ">: User <@" + subject + "> removed."
        elif subject in self.botJson['superusers']:
            logger.debug(self.botJson['superusers'].index(subject))
            userIndex = self.botJson['superusers'].index(subject)
            del self.botJson['superusers'][userIndex]
            if subject in self.botJson['updates']:
                self.botJson['updates'].remove(subject)
            self.SaveJson()
            self.OutputTemplate(user)
            return "<@" + user[
                'user_id'] + ">: User <@" + subject + "> removed."
        else:
            return "<@" + user['user_id'] + ">: Action not needed."

    def HideUserPosts(self, user, subject):
        ''' Hide posts by a user, refreshes template without that users posts.
        @param user: json dict representing the user data
        @param subject: The user to act upon
        @return: String to send back to the user
        '''
        self.SetupJson()
        if user['uLevel'] >= 1:
            if subject in self.botJson['hidden']:
                return "<@" + user['user_id'] + ">: Action not needed."
            self.botJson['hidden'].append(subject)
            self.SaveJson()
            self.OutputTemplate(user)
            return "<@" + user[
                'user_id'] + ">: Posts by <@" + subject + "> are now hidden.\nTemplate refreshed."

    def ShowUserPosts(self, user, subject):
        ''' Show posts by a user, refreshes template with that users posts.
        @param user: json dict representing the user data
        @param subject: The user to act upon
        @return: String to send back to the user
        '''
        self.SetupJson()
        if user['uLevel'] >= 1:
            if subject not in self.botJson['hidden']:
                return "<@" + user['user_id'] + ">: Action not needed."
            self.botJson['hidden'].remove(subject)
            self.SaveJson()
            self.OutputTemplate(user)
            return "<@" + user[
                'user_id'] + ">: Updates by <@" + subject + "> are now seen.\nTemplate refreshed."

    def UpdateUserInfo(self, user, userValue, text):
        ''' Update user information so status updates work properly.
        @param user: json dict representing the user data
        @param userValue: The user information to update
        @param text: The new value - a name, email address or image url.
        @return: String to send back to the user
        '''
        self.SetupJson()
        text = text.replace("'", "").replace("\\", "")  # Bit of anti-xss
        if user['user_id'] not in self.botJson['users']:
            self.botJson['users'][user['user_id']] = {}
        if userValue == "name":
            self.botJson['users'][user['user_id']]['name'] = text
            self.SaveJson()
            return "<@" + user[
                'user_id'] + ">: Your name has been updated.\nUse '.regen' to refresh the template."
        elif userValue == "email":
            if validate_email(text) == False:
                return "<@" + user['user_id'] + ">: Invalid email address."
            gravatar_url = "http://www.gravatar.com/avatar/" + hashlib.md5(
                text.lower()).hexdigest() + "?"
            gravatar_url += urllib.urlencode({
                'd': "http://storj.sdo-srv.com/storjlogo.jpg",
                's': "72"
            })
            self.botJson['users'][user['user_id']]['email'] = text
            self.botJson['users'][user['user_id']]['image'] = gravatar_url
            self.SaveJson()
            response = "<@" + user[
                'user_id'] + ">: Your email address has been updated.\nI also updated the image url "
            response += "with gravatar based on that email. If you would prefer to override that, use \".image <url>\" instead.\n"
            response += "Use \".regen\" to refresh the template."
            return response
        elif userValue == "image":
            self.botJson['users'][user['user_id']]['image'] = text
            self.SaveJson()
            return "<@" + user[
                'user_id'] + ">: Your image url has been updated.\nUse '.regen' to refresh the template."

    def UndoPost(self, user):
        ''' Undo a post a user has made.
        @param user: json dict representing the user data
        @return: String to send back to the user
        '''
        self.SetupJson()
        self.botJson['updates'][user['user_id']] = self.botJson['undo'][
            user['user_id']]
        self.SaveJson()
        self.OutputTemplate(user['user_id'])
        response = "<@" + user[
            'user_id'] + ">: I have undone your last update and refreshed the template."
        return response

    def AdminList(self, user):
        admins = []
        superusers = []
        self.SetupJson()
        for k in self.botJson['admins']:
            try:
                admins.append(self.botJson['users'][k]['name'])
            except:
                pass
        for k in self.botJson['superusers']:
            try:
                superusers.append(self.botJson['users'][k]['name'])
            except:
                pass

        adminList = ", ".join(admins)
        superList = ", ".join(superusers)
        return "Approved posters: " + adminList + "\n Administrators: " + superList

    def FindLazyUsers(self):
        logger = logging.getLogger("SlackBot")
        self.SetupJson()
        text = ""
        got_any = False

        lazyUsers = {'name': [], 'image': [], 'email': [], 'twitter': []}

        for key, val in self.botJson['users'].iteritems():
            if 'name' not in self.botJson['users'][key]:
                lazyUsers['name'].append(key)
                logger.debug("No name for " + str(key))
            if 'image' not in self.botJson['users'][key]:
                lazyUsers['image'].append(key)
                logger.debug("No image for " + str(key))
            if 'email' not in self.botJson['users'][key]:
                lazyUsers['email'].append(key)
                logger.debug("No email for " + str(key))
            if 'twitter' not in self.botJson['users'][key]:
                lazyUsers['twitter'].append(key)
                logger.debug("No name for " + str(key))

        for no_info in ['name', 'image', 'email', 'twitter']:
            if len(lazyUsers[no_info]) > 0:
                lazy = []
                text += "Users without " + no_info + " set: "
                for user_id in lazyUsers[no_info]:
                    lazy.append("<@" + str(user_id) + ">")
                text += ", ".join(lazy)
                text += "\n"
                got_any = True

        if got_any is True:
            return "Aha!\n" + text
        else:
            return "All users in my system have complete profiles!"

    def GetBalance(self, address):
        ''' Fetch user sjcx balance
        @param address: sjcx address
        @return: balance string
        '''
        test = requests.get(
            "http://api.blockscan.com/api2?module=address&action=balance&asset=SJCX&btc_address="
            + address).json()
        if test['status'] == "success":
            return test['data'][0]['balance']

    def GetExRate(self, currency, output):
        if not output:
            output = "usd"
        logger = logging.getLogger("SlackBot")
        url = "http://coinmarketcap-nexuist.rhcloud.com/api/" + currency.lower(
        ) + "/price"
        logger.debug("url: " + url)
        logger.debug("Currency: " + output)
        test = requests.get(url).json()
        if 'error' in test:
            return "Error: " + test['error']
        if 'e' in test[output]:
            test[output] = "%.10f" % float(test[output])
        return currency.upper() + "/" + output.upper() + ": " + test[
            output.lower()]

    def OutputTemplate(self, user):
        logger = logging.getLogger("SlackBot")
        logger.debug(user['user_id'] + " asked for a template refresh")
        self.SetupJson()
        # Two stages, the first is to order the user id by timestamp, then pull in order
        findLatest = {}
        findPosts = {}
        problems = False
        twUrl = "http://twitter.com/"

        for key, val in self.botJson['updates'].iteritems():
            findPosts[key] = self.botJson['updates'][key]['ts']

        findLatest = sorted(findPosts.items(), key=itemgetter(1), reverse=True)

        tdata = []
        for key, val in findLatest:
            user_id = self.botJson['updates'][key]['user_id']

            # Is this a hidden post?
            if user_id in self.botJson['hidden']:
                continue

            text = str(self.botJson['updates'][key]['text'].encode("utf-8"))
            text = text.replace("\"", "\\\"")
            logger.debug("Text to output: " + text)
            ts = self.botJson['updates'][key]['ts']
            ''' Reasons not to continue. We will mark a problem and skip. '''
            if 'name' not in self.botJson['users'][user_id]:
                problems = True
                continue
            if 'image' not in self.botJson['users'][user_id]:
                problems = True
                continue
            if 'twitter' not in self.botJson['users'][user_id]:
                problems = True
                continue
            if 'email' not in self.botJson['users'][user_id]:
                problems = True
                continue

            logger.debug(self.botJson['users'][user_id]['name'])
            tdata.append({
                "text":
                cgi.escape(text),  #self.html_parser.escape(text),
                "name":
                self.botJson['users'][user_id]['name'],
                "image":
                self.botJson['users'][user_id]['image'],
                "twitter":
                twUrl + str(self.botJson['users'][user_id]['twitter']),
                "email":
                self.botJson['users'][user_id]['email'],
                "ts":
                datetime.datetime.fromtimestamp(
                    float(ts)).strftime('%Y-%m-%d %H:%M:%S')
            })

        pt_loader = TemplateLoader(['html/'], auto_reload=True)
        template = pt_loader.load('index.template')
        with open(botData.output_file, 'w') as template_out:
            template_out.write(template(users=tdata))
            template_out.close()

        if problems is True:
            response = "<@" + user[
                'user_id'] + ">: There was a problem outputting the template, but I did what I can.\n"
            response += self.FindLazyUsers()
            return response
        else:
            return "<@" + user['user_id'] + ">: I have refreshed the template."
Пример #29
0
# https://api.slack.com/community
# https://api.slack.com/community#python
# v1 avec ce client :
# https://github.com/loisaidasam/pyslack
from pyslack import SlackClient

# https://api.slack.com/apps

botUserOAuthAccessToken = input("Bot User OAuth Access Token ? ")

print("Bot User OAuth Access Token : ", botUserOAuthAccessToken)

client = SlackClient(botUserOAuthAccessToken)

client.chat_post_message('#dev', "Hello ", username='******')
Пример #30
0
def notify(message):
    api = SlackClient(config.SLACK_API_KEY)
    channel = config.SLACK_CHANNEL
    username = config.SLACK_USERNAME
    api.chat_post_message(channel, message, username=username, as_user=False)
Пример #31
0
 def configure(self):
     self.client = SlackClient('YOUR_SLACK_API_TOKEN_HERE')
     self.current_run = None
Пример #32
0
import praw
import yaml
from pyslack import SlackClient

input = open("output.txt","r")

with open("config.yml", 'r') as ymlfile:
	cfg = yaml.load(ymlfile)

#importing config
apitoken = cfg['apitoken'] 
channel = cfg['channel']
username = cfg['redditusername']
password = cfg ['redditpassword']
#passing API token to pyslack
client = SlackClient(apitoken)

#init PRAW and login
r = praw.Reddit('NewfriendCatcher by hlprimm /u/ajisai v 1.0')
r.login(username,password,disable_warning=True)

#ghetto per-instance "database" until i figure yaml out
already_done = str(input.read()).split()

#keywords to search, need to pull these from the yaml too. 
tier1 = ['Looking to join', 'group of friends', 'new person']
tier2 = ['joining',"settlement","large city","small city","large town","small town","start"]

#don't change below plz
while True:
    print 'Checking for more newfriends...'
Пример #33
0
#!/usr/bin/env python

from pyslack import SlackClient
import requests
from BeautifulSoup import BeautifulSoup

slack_token = 'get-ur-own'
client = SlackClient(slack_token)
url = 'https://www.gfoodtrucks.com/kiosklanding/all'

r = requests.get(url)
soup = BeautifulSoup(r.content)
today = soup.find('div', {'id': 'tab_0'})
message = ''
for box in today.findAll('div', {'class': 'ordering_box'}):
  truck_name = box.find('strong').string
  truck_type = box.find('span').string
  message = message + truck_name.strip() + " : " + truck_type.strip() + '\n'

client.chat_post_message('#sfo', message, username='******')


Пример #34
0
* python 2.7.3 and above

"""
from pyslack import SlackClient
import ConfigParser
import time

# Get config information from ../Authentication/Slack.cfg

config = ConfigParser.RawConfigParser()
config.read("../Authentication/Slack.cfg")

__token__ = config.get("LogPoster", "token")

# User token from config file to generate
client = SlackClient(__token__)
__channel__ = "#logging-scripts"
__username__ = "Script Logger"

client.chat_post_message(__channel__, "Update-ComputerStatistics; Start time: 2:03", username=__username__)
time.sleep(2.5)
client.chat_post_message(__channel__, "Update-ComputerStatistics; End time: 2:05", username=__username__)
__username__ = "SQL Job Logger"
time.sleep(2.5)
client.chat_post_message(__channel__, "Repopulate CMDB Table; Start time: 2:05", username=__username__)
time.sleep(2.5)
client.chat_post_message(__channel__, "Repopulate CMDB Table; End time: 2:05", username=__username__)

raw_input()
__channel__ = "#logging-serverstats"
__username__ = "Statistics Logger"
Пример #35
0
 def __init__(self, token, channel):
     self.slack = SlackClient(token)
     self.channel = channel
Пример #36
0
 def __init__(self):
     settings = sublime.load_settings("SubSlack.sublime-settings")
     token = settings.get("token")
     self.bot = settings.get("bot_name")
     self.room = "#%s" % settings.get("default_chat")
     self.client = SlackClient(token)
Пример #37
0
#asterisk AMI login
server = "ASTRISKSERVERNAME"
port = 5038
username = "******"
secret = "PASSWORD"
extensions = {"SIP/200": "YOU", "SIP/201": "Someone else"}

log = logging.getLogger("server")

timeouttask = None
timeoutping = 5
timeoutloop = 120

slack_api_token = 'ENTERTOKEN'

client = SlackClient(slack_api_token)


def sendToSlack(msg):
    client.chat_post_message('#phone', msg, username='******')


class callMeFactory(AMIFactory):
    cbconnect = None

    def __init__(self):
        AMIFactory.__init__(self, username, secret)

    def connect(self):
        print 'connecting'
        df = self.login(server, port)
Пример #38
0
    async def _send_to_external_chat(self, config, event):
        conv_id = config["trigger"]
        relay_channels = config["config.json"][self.configkey]

        user = event.passthru["original_request"]["user"]
        message = event.passthru["original_request"]["message"]

        if not message:
            message = ""

        # XXX: rudimentary conversion of html to markdown
        message = re.sub(r"</?b>", "*", message)
        message = re.sub(r"</?i>", "_", message)
        message = re.sub(r"</?pre>", "`", message)

        bridge_user = self._get_user_details(user, { "event": event })

        try:
            client = SlackClient(config["config.json"]["key"], verify=True)
        except TypeError:
            client = SlackClient(config["config.json"]["key"])

        slack_api_params = { 'username': bridge_user["preferred_name"],
                             'icon_url': bridge_user["photo_url"] }

        if "link_names" not in config["config.json"] or config["config.json"]["link_names"]:
            slack_api_params["link_names"] = 1

        """XXX: deferred image sending

        this plugin leverages existing storage in hangouts - since there isn't a direct means
        to acquire the public url of a hangups-upload file we need to wait for other handlers to post
        the image in hangouts, which generates the public url, which we will send in a deferred post.

        handlers.image_uri_from() is packaged as a task to wait for an image link to be associated with
        an image id that this handler sees
        """

        if( "image_id" in event.passthru["original_request"]
                and event.passthru["original_request"]["image_id"] ):

            if( "conv_event" in event
                    and "attachments" in event.conv_event
                    and len(event.conv_event.attachments) == 1 ):

                message = "shared an image: {}".format(event.conv_event.attachments[0])
            else:
                # without attachments, create a deferred post until the public image url becomes available
                image_id = event.passthru["original_request"]["image_id"]

                loop = asyncio.get_event_loop()
                task = loop.create_task(
                    self.bot._handlers.image_uri_from(
                        image_id,
                        self._send_deferred_photo,
                        relay_channels,
                        client,
                        slack_api_params ))

        """standard message relay"""

        for relay_channel in relay_channels:
            client.chat_post_message(relay_channel,  message, **slack_api_params)
Пример #39
0
    def _send_to_external_chat(self, config, event):
        conv_id = config["trigger"]
        relay_channels = config["config.json"][self.configkey]

        user = event.passthru["original_request"]["user"]
        message = event.passthru["original_request"]["message"]

        if not message:
            message = ""

        # XXX: rudimentary conversion of html to markdown
        message = re.sub(r"</?b>", "*", message)
        message = re.sub(r"</?i>", "_", message)
        message = re.sub(r"</?pre>", "`", message)

        bridge_user = self._get_user_details(user, { "event": event })

        try:
            client = SlackClient(config["config.json"]["key"], verify=True)
        except TypeError:
            client = SlackClient(config["config.json"]["key"])

        slack_api_params = { 'username': bridge_user["preferred_name"],
                             'icon_url': bridge_user["photo_url"] }

        if "link_names" not in config["config.json"] or config["config.json"]["link_names"]:
            slack_api_params["link_names"] = 1

        """XXX: deferred image sending

        this plugin leverages existing storage in hangouts - since there isn't a direct means
        to acquire the public url of a hangups-upload file we need to wait for other handlers to post
        the image in hangouts, which generates the public url, which we will send in a deferred post.

        handlers.image_uri_from() is packaged as a task to wait for an image link to be associated with
        an image id that this handler sees
        """

        if( "image_id" in event.passthru["original_request"]
                and event.passthru["original_request"]["image_id"] ):

            if( "conv_event" in event
                    and "attachments" in event.conv_event
                    and len(event.conv_event.attachments) == 1 ):

                message = "shared an image: {}".format(event.conv_event.attachments[0])
            else:
                # without attachments, create a deferred post until the public image url becomes available
                image_id = event.passthru["original_request"]["image_id"]

                loop = asyncio.get_event_loop()
                task = loop.create_task(
                    self.bot._handlers.image_uri_from(
                        image_id,
                        self._send_deferred_photo,
                        relay_channels,
                        client,
                        slack_api_params ))

        """standard message relay"""

        for relay_channel in relay_channels:
            client.chat_post_message(relay_channel,  message, **slack_api_params)
Пример #40
0
wm = pyinotify.WatchManager()
mask = pyinotify.IN_CLOSE_WRITE

URL = 'http://elog.whatever.com'
LOGBOOK_PATH = '/usr/local/elog/logbooks'
BOTNAME = 'ELOG'
PREVIEW_LENGTH = 150
FALLBACK_DESTINATION = '#elog'
DESTINATIONS = {
    'Analysis': '#analysis',
    'Computing and Software': '#software',
    'Whatever': '@tgal',
    }

slack = SlackClient('YOUR-SLACK-API-TOKEN')


class ElogEntry(object):
    def __init__(self, logbook, msg_id=None):
        self.logbook = logbook
        self.id = msg_id
        self.header = {}
        self.content = ''

    @property
    def author(self):
        return self._lookup('Author')

    @property
    def type(self):
Пример #41
0
class SlackResponder(object):
    # Messages we understand and parse
    hooks = {
        "add":      "^(\.add) \<\@([\w]+)\> ?(admin|superuser)?",
        "del":      "^(\.del) \<\@([\w]+)\>",
        "hide":     "^(\.hide) \<\@([\w]+)\>",
        "show":     "^(\.show) \<\@([\w]+)\>",
        "twitter":  "^(\.twitter) ([\w]+)$",
        "email":    "^(\.email) \<mailto\:([\w+\.-@]+)|[\w+\.-@]+\>$",
        "image":    "^(\.image) \<(.*)\>$",
        "name":     "^(\.name) (.*)$",
        "balance":  "^(\.balance) ([A-Za-z0-9]{25,36})$",
        "rate":     "^(\.rate) ([\w]+) ?(usd|USD|eur|EUR|cny|CNY|cad|CAD|rub|RUB|btc|BTC)?",
        "status":   "^(\.status) (.*)$",
        "undo":     "^\.undo",
        "list":     "^\.list",
        "regen" :   "^\.regen",
        "ping":     "^\.ping",
        "whoami":   "^\.whoami",
        "help":     "^\.help",
        "lazy":     "^\.lazy"
    }
    
    # User ability level
    userLevel = {
        "none": 0,
        "user": 1,
        "superuser": 2,
        "owner": 3
    }


    # Url regex
    urlFixer = "<(https?:\/\/[^>]+)>"


    def __init__(self, connect=True):
        # Lets get set up
        botPass = {}
        if botData.token_id:
            self.client = SlackClient(botData.token_id)
        if connect is True:
            req         = self.client._make_request('rtm.start', {})
            socket_url  = req['url']
            self.ws     = websocket.WebSocket()
            self.ws.connect(socket_url)
        else:
            self.ws     = websocket.WebSocket()
            
        # Compile regex triggers and url regex
        self.triggers = {}
        for key, val in self.hooks.iteritems():
            self.triggers[key] = re.compile(val)

        self.urlChecker = re.compile(self.urlFixer)
        
        # For Python 2.x
        self.html_parser = HTMLParser.HTMLParser()
        # For Python 3.x
        # self.html_parser = html.parser.HTMLParser()


    def SetupJson(self):
        logger = logging.getLogger("SlackBot")
        if os.path.isfile(botData.status_file):
            # It exists, lets read it in.
            status_in = open(botData.status_file, "r")
            data      = status_in.read()
            status_in.close()
            self.botJson = simplejson.loads(data)
        else:
            # Starting over
            self.botJson = {
                "users": {},
                "updates": {},
                "undo": {},
                    "admins": [],
                    "superusers": [],
                    "hidden": []
            }

        if botData.owner_id and botData.owner_id not in self.botJson['superusers']:
            self.botJson['superusers'].append(botData.owner_id)
        if botData.owner_id and botData.owner_id not in self.botJson['users']:
            self.botJson['users'][botData.owner_id] = {}

        return

    def SaveJson(self):
        with open(botData.status_file, 'w') as status_out:
            json.dump(self.botJson, status_out)
            status_out.close()
        return

    def Parse(self, postData):
        ''' Parses a (should be) matching request of the bot
        : param postData: dict from the post sent to the bot from Slack
        : return: String containing response for the user:
        '''
        logger = logging.getLogger("SlackBot")
        logger.debug("User ID: " + postData['user_id'])

        # Verify Token
        if postData['token'] != botData.hook_token:
            logger.debug("Token from Slack does not match ours, ignoring.")
            return
            
        logger.debug("Looking through hooks for a match...")
        logger.debug("Got: " + str(postData['text']))
        for key, val in self.triggers.iteritems():
            test = self.triggers[key].match(postData['text'])
            if test:
                logger.debug("Got a match with: " + self.hooks[key])
                return self._Process(postData, re.findall(self.triggers[key], postData['text']))
        # Still here? Very unlikely
        return "Huh?"

    def _Process(self, postData, matchText):
        logger = logging.getLogger("SlackBot")
        self.SetupJson() # Needed for comparison checks
        # logger.debug(json.dumps(postData, indent=4))

        try:
            del postData['token'], postData['trigger_word'], postData['team_id']
            del postData['channel_name'], postData['user_name']
        except:
            pass

        if   postData['user_id'] == botData.owner_id:
            postData['uLevel'] = self.userLevel['owner'] # 3
        elif postData['user_id'] in self.botJson['superusers']:
            postData['uLevel'] = self.userLevel['superuser'] # 2
        elif postData['user_id'] in self.botJson['admins']:
            postData['uLevel'] = self.userLevel['user'] # 1
        else:
            postData['uLevel'] = self.userLevel['none'] # 0

        request = matchText[0]
        logger.debug("Request: " + str(request))

        if not isinstance(request, basestring):
            if len(request) >= 2:
                trigger  = request[0]
                argument = request[1]
                logger.debug("Trigger: " + trigger)
                logger.debug("Argument: " + argument)
                # Third value for a user class (for .add)
                if trigger == ".add":
                    try:
                        userClass = request[2]
                    except:
                        userClass = "admin"
                elif trigger == ".del":
                    try:
                        if k[2].lower() in ("yes", "true", "t", "1"):
                            hideUser = True
                        else:
                            hideUser = False
                    except:
                        hideUser = False
                elif trigger == ".rate":
                    try:
                        rateType = request[2]
                    except:
                        rateType = "usd"

                forbidden = ['.status','.add','.del','.show','.hide','.name',
                             '.image','.email','.twitter','.undo','.regen']
                if trigger in forbidden and postData['uLevel'] < 1:
                    return "<@" + postData['user_id'] + ">: You are not an authorised user."

                # Status update?
                if trigger == ".status":
                    return self.PostStatusUpdate(postData, argument)
                # Is the owner trying to be added or deleted?
                elif trigger == ".add" or trigger == ".del":
                    if str(argument) == str(botData.owner_id):
                        return "<@" + postData['user_id'] + ">: Cannot perform actions on bot owner."
                    if trigger == ".add":
                        return self.PromoteUser(postData, argument, userClass)
                    elif trigger == ".del": # Removes from either list
                        return self.DemoteUser(postData, argument, hideUser)
                # Show/hide condition?
                elif trigger == ".show" or trigger == ".hide":
                    if trigger == ".show":
                        return self.ShowUserPosts(postData, argument)
                    elif trigger == ".hide":
                        return self.HideUserPosts(postData, argument)
                # User details?
                elif trigger == ".name" or trigger == ".image" or trigger == ".email":
                    if trigger == ".name":
                        return self.UpdateUserInfo(postData, "name", argument)
                    elif trigger == ".email":
                        return self.UpdateUserInfo(postData, "email", argument)
                    elif trigger == ".image":
                        return self.UpdateUserInfo(postData, "image", argument)
                elif trigger == ".balance":
                    return "Balance for address " + argument + ": " + str(self.GetBalance(argument)) + " SJCX"
                elif trigger == ".twitter":
                    self.SetupJson()
                    self.botJson['users'][postData['user_id']]['twitter'] = argument
                    self.SaveJson()
                    return "<@" + postData['user_id'] + ">: Your twitter handle is now '" + argument + "'."
                elif trigger == ".rate":
                    return self.GetExRate(argument, rateType)
                else:
                    return "No response to give!"
        elif request == ".list":
            return self.AdminList(postData)
        elif request == ".undo":
            return self.UndoPost(postData)
        elif request == ".regen":
            return self.OutputTemplate(postData)
        elif request == ".ping":
            return "PONG!"
        elif request == ".whoami":
            return "Hello <@" + postData['user_id'] + ">, your user id is " + postData['user_id'] + "."
        elif request == ".help":
            return self.HelpResponse()
        elif request == ".lazy":
            return self.FindLazyUsers()
        else:
            return "No response to give!"


    def HelpResponse(self):
        return textwrap.dedent(
            """
            Hello, I'm SlackBot. Standard commands you can use with me are:\n
            .add (username) <superuser> - Authorise a user to post status updates. Include 'superuser' to
            give them the power to add or remove other users from the authorised list.\n
            .del (username) - Revokes status updates from a user.\n
            .show (username) - Show posts from a user on the status page.\n
            .hide (username) - Hide posts from a user on the status page.\n
            .name (name) - Updates name shown for a user added to the bot.\n
            .image (url) - Updates the image shown for a user added to the bot.\n
            .email (address) - Updates name shown for a user added to the bot (not that this is shown normally).\n
            .twitter (name) - Updates the twitter address for a user from the default.\n
            .status (text) - Post a status update! Use whatever text you want, it will be used in the output.\n
            .undo - Didn't mean to post that last status update? This will return it to what you said last.\n
            .regen - Force regeneration of the status page from the template.\n
            .whoami - Tells you your user_id, should you wish to change any 'settings' :)\n
            .list - Lists bot users authorised to post status updates.\n
            .rate (coin) (currency) - Fetches exchange rates for coins at CoinMarketCap, uses the top 100
            coins they track, with USD, CAD, CNY, RUB and BTC as supported currencies.
            \n
            Enjoy!
            """
        )

    def PostStatusUpdate(self, user, text):
        ''' Creates a status update for a user, refreshes template.
        @param user: json dict representing the user data
        @param text: The status text the user wishes to post
        @return: String to send back to the user
        '''
        self.SetupJson()
        user['text'] = self.TextParser(text)
        user['ts']   = user['timestamp']
        del user['timestamp']
        self.botJson['updates'][user['user_id']] = user
        if user['user_id'] in self.botJson['undo']:
            old = self.botJson['updates'][user['user_id']]
            self.botJson['undo'][user['user_id']] = old # Copy before replace
            self.botJson['updates'][user['user_id']] = user # Update this user with latest post
        else:
            self.botJson['undo'][user['user_id']] = user # Set them both to the same to start
            self.botJson['updates'][user['user_id']] = user
        self.SaveJson()
        self.OutputTemplate(user)
        return "<@" + user['user_id'] + ">: Status update accepted, template updated."


    def TextParser(self, text):
        ''' Parses info from slack, e.g. urls '''
        logger = logging.getLogger("SlackBot")
        logger.debug("Looking for a URL match...'" + str(text) + "'")
        # Single
        for m in self.urlChecker.findall(text):
            text = text.replace("<" + m + ">",
                                "<a href=\\\"" + m + "\\\">" + 
                                self.html_parser.escape(m) + "</a>")
        
        return text

    def PromoteUser(self, user, subject, level):
        ''' Promotes a user to a higher level so they can post updates, or at
        superuser level they can promote other users to update posting level.
        @param user: json dict representing the user data
        @param subject: The user to act on
        @param level: int user level to promote to, 1=user, 2=superuser
        @return: String to send back to the user.
        '''
        logger = logging.getLogger("SlackBot")
        self.SetupJson()
        logger.debug(json.dumps(user, indent=4))
        response = ""
        if level == "superuser":
            if user['uLevel'] >= 3:
                if subject in self.botJson['superusers']:
                    return "<@" + user['user_id'] + ">: Action not needed."
                self.botJson['superusers'].append(subject)
                self.SaveJson()
                response += "<@" + user['user_id'] + ">: User <@" + subject + "> added to superusers.\n"
            else:
                return "<@" + user['user_id'] + ">: You are not authorised to add other superusers."
        else:
            if user['uLevel'] >= 2:
                if subject in self.botJson['admins']:
                    return "<@" + user['user_id'] + ">: Action not needed."
                self.botJson['admins'].append(subject)
                self.SaveJson()
                response += "<@" + user['user_id'] + ">: User <@" + subject + "> added to authorised users.\n"
            else:
                return "<@" + user['user_id'] + ">: You are not authorised to add other users."

        newUser = {}
        ''' Is the rtm api token set up? If not, complain at them.'''
        if not botData.token_id:
            self.botJson['users'][subject] = {}
            self.SaveJson()
            
            response += "<@" + subject + ">: I cannot access Slack to get your user info so you will need to enter it manually.\n"
            response += "I need your name, email and twitter details at minimum - I'll generate a gravatar address from your "
            response + "email unless you specify it as below.\n"
            response += "You can use the commands .name,.email and .twitter to update your details.\n"
            response += "You can also use .image to force your image to a direct url if Gravatar does not work with your email.\n"
            response += "Example: \".name Slack User\", \".email [email protected]\", \".image <url\", \".twitter tweeter\".\n"
            return response
        else:
            req = self.client._make_request('users.info', {'user': subject})
            logger.debug(json.dumps(req, indent=4))
            newUser['name']    = req['user']['profile']['real_name']
            newUser['image']   = req['user']['profile']['image_72']
            newUser['email']   = req['user']['profile']['email']
            newUser['twitter'] = "storjproject"
            self.botJson['users'][user['user_id']] = newUser
            self.SaveJson()
        
            response += "<@" + subject + ">: I have set up your profile with what I can gather immediately from Slack.\n"
            response += "If you want, you can use the commands .name,.email and .twitter to update your details.\n"
            response += "You can also use .image to force your image to a direct url if Gravatar does not work with your email.\n"
            response += "Example: \".name Slack User\", \".email [email protected]\", \".twitter tweeter\".\n"
            return response


    def DemoteUser(self, user, subject, hide):
        ''' Demotes a user so they won't be allowed to post updates. Optional hide posts.
        Doesn't matter what level they are, they're gone.
        @param user: json dict representing the user data
        @param subject: The user to act upon
        @param hide: Bool to hide posts by the user at the same time
        @return: String to send back to the user
        '''
        logger = logging.getLogger("SlackBot")
        self.SetupJson()
        if subject in self.botJson['admins']:
            logger.debug(self.botJson['admins'].index(subject))
            userIndex = self.botJson['admins'].index(subject)
            del self.botJson['admins'][userIndex]
            if subject in self.botJson['updates']:
                del self.botJson['updates'][subject]
            self.SaveJson()
            self.OutputTemplate(user)
            return "<@" + user['user_id'] + ">: User <@" + subject + "> removed."
        elif subject in self.botJson['superusers']:
            logger.debug(self.botJson['superusers'].index(subject))
            userIndex = self.botJson['superusers'].index(subject)
            del self.botJson['superusers'][userIndex]
            if subject in self.botJson['updates']:
                self.botJson['updates'].remove(subject)
            self.SaveJson()
            self.OutputTemplate(user)
            return "<@" + user['user_id'] + ">: User <@" + subject + "> removed."
        else:
            return "<@" + user['user_id'] + ">: Action not needed."


    def HideUserPosts(self, user, subject):
        ''' Hide posts by a user, refreshes template without that users posts.
        @param user: json dict representing the user data
        @param subject: The user to act upon
        @return: String to send back to the user
        ''' 
        self.SetupJson()
        if user['uLevel'] >= 1:
            if subject in self.botJson['hidden']:
                return "<@" + user['user_id'] + ">: Action not needed."
            self.botJson['hidden'].append(subject)
            self.SaveJson()
            self.OutputTemplate(user)
            return "<@" + user['user_id'] + ">: Posts by <@" + subject + "> are now hidden.\nTemplate refreshed."

    
    def ShowUserPosts(self, user, subject):
        ''' Show posts by a user, refreshes template with that users posts.
        @param user: json dict representing the user data
        @param subject: The user to act upon
        @return: String to send back to the user
        '''
        self.SetupJson()
        if user['uLevel'] >= 1:
            if subject not in self.botJson['hidden']:
                return "<@" + user['user_id'] + ">: Action not needed."
            self.botJson['hidden'].remove(subject)
            self.SaveJson()
            self.OutputTemplate(user)
            return "<@" + user['user_id'] + ">: Updates by <@" + subject + "> are now seen.\nTemplate refreshed."


    def UpdateUserInfo(self, user, userValue, text):
        ''' Update user information so status updates work properly.
        @param user: json dict representing the user data
        @param userValue: The user information to update
        @param text: The new value - a name, email address or image url.
        @return: String to send back to the user
        '''
        self.SetupJson()
        text = text.replace("'", "").replace("\\", "") # Bit of anti-xss
        if user['user_id'] not in self.botJson['users']:
            self.botJson['users'][user['user_id']] = {}
        if userValue == "name":
            self.botJson['users'][user['user_id']]['name'] = text
            self.SaveJson()
            return "<@" + user['user_id'] + ">: Your name has been updated.\nUse '.regen' to refresh the template."
        elif userValue == "email":
            if validate_email(text) == False:
                return "<@" + user['user_id'] + ">: Invalid email address." 
            gravatar_url = "http://www.gravatar.com/avatar/" + hashlib.md5(text.lower()).hexdigest() + "?"
            gravatar_url += urllib.urlencode({'d':"http://storj.sdo-srv.com/storjlogo.jpg", 's':"72"})
            self.botJson['users'][user['user_id']]['email'] = text
            self.botJson['users'][user['user_id']]['image'] = gravatar_url
            self.SaveJson()
            response  = "<@" + user['user_id'] + ">: Your email address has been updated.\nI also updated the image url "
            response += "with gravatar based on that email. If you would prefer to override that, use \".image <url>\" instead.\n"
            response += "Use \".regen\" to refresh the template."
            return response
        elif userValue == "image":
            self.botJson['users'][user['user_id']]['image'] = text
            self.SaveJson()
            return "<@" + user['user_id'] + ">: Your image url has been updated.\nUse '.regen' to refresh the template."
    
        
    def UndoPost(self, user):
        ''' Undo a post a user has made.
        @param user: json dict representing the user data
        @return: String to send back to the user
        '''
        self.SetupJson()
        self.botJson['updates'][user['user_id']] = self.botJson['undo'][user['user_id']]
        self.SaveJson()
        self.OutputTemplate(user['user_id'])
        response = "<@" + user['user_id'] + ">: I have undone your last update and refreshed the template."
        return response

    def AdminList(self, user):
        admins = []
        superusers = []
        self.SetupJson()
        for k in self.botJson['admins']:
            try:
                admins.append(self.botJson['users'][k]['name'])
            except:
                pass
        for k in self.botJson['superusers']:
            try:
                superusers.append(self.botJson['users'][k]['name'])
            except:
                pass
            
        adminList = ", ".join(admins)
        superList = ", ".join(superusers)
        return "Approved posters: " + adminList + "\n Administrators: " + superList


    def FindLazyUsers(self):
        logger = logging.getLogger("SlackBot")
        self.SetupJson()
        text = ""
        got_any = False
        
        lazyUsers = {
            'name': [],
            'image': [],
            'email': [],
            'twitter': []
        }
        
        for key, val in self.botJson['users'].iteritems():
            if 'name' not in self.botJson['users'][key]:
                lazyUsers['name'].append(key)
                logger.debug("No name for " + str(key))
            if 'image' not in self.botJson['users'][key]:
                lazyUsers['image'].append(key)
                logger.debug("No image for " + str(key))
            if 'email' not in self.botJson['users'][key]:
                lazyUsers['email'].append(key)
                logger.debug("No email for " + str(key))
            if 'twitter' not in self.botJson['users'][key]:
                lazyUsers['twitter'].append(key)
                logger.debug("No name for " + str(key))
        
        for no_info in ['name', 'image', 'email', 'twitter']:
            if len(lazyUsers[no_info]) > 0:
                lazy = []
                text += "Users without " + no_info + " set: "
                for user_id in lazyUsers[no_info]:
                    lazy.append("<@" + str(user_id) + ">")
                text += ", ".join(lazy)
                text += "\n"
                got_any = True

        if got_any is True:
            return "Aha!\n" + text
        else:
            return "All users in my system have complete profiles!"

    def GetBalance(self, address):
        ''' Fetch user sjcx balance
        @param address: sjcx address
        @return: balance string
        '''
        test = requests.get("http://api.blockscan.com/api2?module=address&action=balance&asset=SJCX&btc_address=" + address).json()
        if test['status'] == "success":
            return test['data'][0]['balance']

    def GetExRate(self, currency, output):
        if not output:
            output = "usd"
        logger = logging.getLogger("SlackBot")
        url = "http://coinmarketcap-nexuist.rhcloud.com/api/" + currency.lower() + "/price"
        logger.debug("url: " + url)
        logger.debug("Currency: " + output)
        test = requests.get(url).json()
        if 'error' in test:
            return "Error: " + test['error']
        if 'e' in test[output]:
            test[output] = "%.10f" % float(test[output])
        return currency.upper() + "/" + output.upper() + ": " + test[output.lower()]


    def OutputTemplate(self, user):
        logger = logging.getLogger("SlackBot")
        logger.debug(user['user_id'] + " asked for a template refresh")
        self.SetupJson()
        # Two stages, the first is to order the user id by timestamp, then pull in order
        findLatest  = {}
        findPosts   = {}
        problems    = False
        twUrl       = "http://twitter.com/"
        
        for key, val in self.botJson['updates'].iteritems():
            findPosts[key] = self.botJson['updates'][key]['ts']
            
        findLatest = sorted(findPosts.items(), key=itemgetter(1), reverse=True)

        tdata = []
        for key, val in findLatest:
            user_id = self.botJson['updates'][key]['user_id']

            # Is this a hidden post?    
            if user_id in self.botJson['hidden']:
                continue
            
            text = str(self.botJson['updates'][key]['text'].encode("utf-8"))
            text = text.replace("\"", "\\\"")
            logger.debug("Text to output: " + text)
            ts   = self.botJson['updates'][key]['ts']
            ''' Reasons not to continue. We will mark a problem and skip. '''
            if 'name' not in self.botJson['users'][user_id]:
                problems = True
                continue
            if 'image' not in self.botJson['users'][user_id]:
                problems = True
                continue
            if 'twitter' not in self.botJson['users'][user_id]:
                problems = True
                continue
            if 'email' not in self.botJson['users'][user_id]:
                problems = True
                continue

            logger.debug(self.botJson['users'][user_id]['name'])
            tdata.append({
                "text": cgi.escape(text), #self.html_parser.escape(text),
                "name": self.botJson['users'][user_id]['name'],
                "image": self.botJson['users'][user_id]['image'],
                "twitter": twUrl + str(self.botJson['users'][user_id]['twitter']),
                "email": self.botJson['users'][user_id]['email'],
                "ts": datetime.datetime.fromtimestamp(float(ts)).strftime('%Y-%m-%d %H:%M:%S')
            })

        pt_loader = TemplateLoader(['html/'], auto_reload=True)
        template  = pt_loader.load('index.template')
        with open(botData.output_file, 'w') as template_out:
            template_out.write(template(users=tdata))
            template_out.close()
            
        if problems is True:
            response  = "<@" + user['user_id'] + ">: There was a problem outputting the template, but I did what I can.\n"
            response += self.FindLazyUsers()
            return response
        else:
            return "<@" + user['user_id'] + ">: I have refreshed the template."
Пример #42
0
import requests
import config
import json
from pymongo import MongoClient
from pyslack import SlackClient
from datetime import datetime

mongo = MongoClient(config.mongo_string)
db = mongo.slack
mongo_messages = db.messages

slack = SlackClient(config.token)

channels = slack.channel_listing('public_channel,private_channel')

mongo_docs = []

created_date = datetime.utcnow()
messagecount = 0
for channel in channels:
    messages = slack.message_listing(channel['id'])
    print(channel['name'] + ' ' + str(len(messages)))
    messagecount = messagecount + len(messages)
    for message in messages:
        doc = message
        ts = float(message['ts'])
        timestamp = int(ts)
        doc['channel'] = channel['name']
        doc['channelid'] = channel['id']
        doc['messagedate'] = datetime.utcfromtimestamp(timestamp).strftime(
            '%Y-%m-%d %H:%M:%S')
Пример #43
0
 def __init__(self):
     self.blacklist = ['http://Amazon.co.jp/', 'http://Amazon.co.jp']
     self.slack_client = SlackClient(self.slack_token)
Пример #44
0
 def __init__(self):
     settings = sublime.load_settings("SubSlack.sublime-settings")
     token = settings.get('token')
     self.bot = settings.get('bot_name')
     self.room = '#%s' % settings.get('default_chat')
     self.client = SlackClient(token)
Пример #45
0
    return sub_expire


# Main
salt_root = "/salt/"
pillar_filelist = []

for root, dirs, files in os.walk(salt_root):
    for f in files:
        if "/pillar/" in root:
            pillar_filelist.append(os.path.join(root, f))

report_data = extract_certs(pillar_filelist)

for entry in report_data:
    slack_client = SlackClient(slack_api_key)
    slack_message = ""
    subject = report_data[entry][0]
    expire_after = report_data[entry][1]

    if (expire_after - timedelta(days=30)) < datetime.now():
        slack_message = "*ACTION REQUIRED:* A certificate found in `{}`, with a subject of `{}`, is expired/will expire on *{}*.".format(
            entry, subject, expire_after)
    elif (expire_after - timedelta(days=60)) < datetime.now():
        slack_message = "*Warning:* A certificate found in `{}`, with a subject of `{}`, will expire on *{}*.".format(
            entry, subject, expire_after)
    if slack_message:
        slack_client.chat_post_message(slack_channel,
                                       slack_message,
                                       username=slack_username)
Пример #46
0
LOGBOOK_PATH = "/usr/local/elog/logbooks"
BOTNAME = "ELOG"
DEFAULT_DESTINATION = "#elog"
DESTINATIONS = {
    "Operations_IT": "#operations_it",
    "Operations_FR": "#operations_fr",
    #    'Qualification': '#elog',
    #    'DOM_Integration': '#elog',
    #    'DU_Integration': '#elog',
    #    'DAQ_Readout': '#elog',
    #    'Electronics': '#elog',
    #    'Analysis': '#elog',
    "Computing and Software": "#software",
}

slack = SlackClient("YOUR_SLACK_API_TOKEN_HERE")


class ElogEntry(object):
    def __init__(self, logbook, msg_id=None):
        self.logbook = logbook
        self.id = msg_id
        self.header = {}
        self.content = ""

    @property
    def author(self):
        return self._lookup("Author")

    @property
    def type(self):
Пример #47
0
class newsReporterBase:

    def __init__(self):
        self.blacklist = ['http://Amazon.co.jp/', 'http://Amazon.co.jp']
        self.slack_client = SlackClient(self.slack_token)

    def run(self):
        try:
            rows = self._summarise_rows()
            self._report_to_slack(rows, self.channel)
        except Exception as e:
            message = 'ニュースの更新に失敗しました: ' + str(e)
            self.slack_client.chat_post_message(
                self.channel, message, username=self.slackname
                )

    def _summarise_rows(self):
        target_time = self._calc_target_time()
        rows = self._request_urls(200, target_time)
        return self._select_keys(rows)

    def _calc_target_time(self):
        target_time = datetime.now() + timedelta(hours=-self.waybackhours)
        return int(target_time.strftime('%s'))

    def _request_urls(self, count, target_time):
        reporter = tl.urlReporter(**self.twitter_conf)
        rows = reporter.request_urls(
            count=count,
            target_time=target_time,
            **self.twlist_conf
            )
        return rows

    def _select_keys(self, rows):
        formed_row = (self._form_row(r) for r in rows
                      if r['url'] not in self.blacklist)
        return sorted(formed_row, key=lambda x: x['value'], reverse=True)

    def _form_row(self, row):
        favorite = max(row['favorite_counts'])
        retweet = max(row['retweet_counts'])
        return {
            'url': row['url'],
            'title': self._check_title(row['title']),
            'value': favorite + retweet
            }

    def _check_title(self, title):
        if title is None:
            return '[タイトルが取得できませんでした]'
        else:
            return title.strip()

    def _report_to_slack(self, rows, channel, threshold=0):
        filtered_rows = [r for r in rows if r['value'] >= threshold]
        message = self._form_message(filtered_rows)
        if len(message) <= 1800:
            self.slack_client.chat_post_message(
                channel, message, username=self.slackname
                )
        else:
            self._report_to_slack(filtered_rows, channel, threshold+1)

    def _form_message(self, rows):
        template = '>>>{body}'
        body = self._form_body(rows)
        message = template.format(body=body, domain=self.domain)
        return message

    def _form_body(self, rows):
        if len(rows) >= 1:
            return '\n\n'.join(self._form_each_row(**r) for r in rows)
        else:
            return '最新のツイートはありません'.format(self.domain)

    def _form_each_row(self, url, title, value):
        elems = self._pick_elems(url, title, value)
        return '\n'.join(elems)

    def _pick_elems(self, url, title, value):
        if value >= 1:
            return [self._make_stars(value), title, url]
        else:
            return [title, url]

    def _make_stars(self, value):
        if value >= 10:
            return ':star:×' + str(value)
        else:
            return ':star:' * value
Пример #48
0
def main():
    opts = parse_args()
    cfg = yaml.load(open(opts.config))

    # match Yaml options to commandline options
    try:
        if cfg['mail']['frommail'] != "":
            opts.frommail = cfg['mail']['frommail']
    except:
        pass
    try:
        if cfg['mail']['tomail'] != "":
            opts.tomail = cfg['mail']['tomail']
    except:
        pass
    try:
        if cfg['mail']['smtphost'] != "":
            opts.smtphost = cfg['mail']['smtphost']
    except:
        pass
    try:
        if cfg['mail']['smtpport'] != "":
            opts.smtpport = int(cfg['mail']['smtpport'])
    except:
        pass
    try:
        if cfg['mail']['usessl'] != "":
            opts.usessl = bool(cfg['mail']['usessl'])
    except:
        pass
    try:
        if cfg['mail']['username'] != "":
            opts.username = cfg['mail']['username']
    except:
        pass
    try:
        if cfg['mail']['password'] != "":
            opts.password = cfg['mail']['password']
    except:
        pass
    try:
        if cfg['interval'] != "":
            opts.interval = int(cfg['interval'])
    except:
        pass
    try:
        if cfg['update'] != "":
            opts.update = bool(cfg['update'])
    except:
        pass
    try:
        if cfg['queries'] != "":
            opts.queries = cfg['queries']
    except:
        pass
    try:
        if cfg['slackroom'] != "":
            opts.slackroom = cfg['slackroom']
    except:
        pass
    try:
        if cfg['slacktoken'] != "":
            opts.slacktoken = cfg['slacktoken']
    except:
        pass
    try:
        if cfg['slackuser'] != "":
            opts.slackuser = cfg['slackuser']
    except:
        pass
    try:
        if cfg['verbose'] != "":
            opts.verbose = bool(cfg['verbose'])
    except:
        pass

    # print debug info
    if opts.verbose:
        print("from mail: " + opts.frommail)
        print("to mail: " + str(opts.tomail))
        print("smtp host: " + opts.smtphost)
        print("smtp port: " + str(opts.smtpport))
        print("use ssl: " + str(opts.usessl))
        print("username: "******"interval: " + str(opts.interval))
        print("update: " + str(opts.update))
        print("queries: " + str(opts.queries))
        print("slack room: " + str(opts.slackroom))
        print("slack user: "******"Adding document: " + md['title'] + " (" + file['id'] + ")")
                        docs[file['id']] = None

            # Check that we are not getting too many documents
            if counter > 999:
                print("WARNING: Query returns too many documents, not tracking all docs: " + query)

        # Track if there where changes
        foundChanges = False

        # A mail message to send via mail
        mailMessageBody = ""

        # A message to be sent via slack
        slackMessageBody = ""

        # Iterate over the documents we monitor
        for doc,modifiedDate in docs.items():
            # Get information about the specified file.  This will throw
            # an exception if the file does not exist.
            md = gd.get_file_metadata(doc)

            if md['mimeType'] == 'application/vnd.google-apps.document':
                # Get some metadata for the file we track
                if modifiedDate is None:
                    modifiedDate=md['modifiedDate']
                title = md['title']
                try:
                    md['embedLink'] 
                except KeyError:
                    editLink = ""
                else:
                    editLink = md['embedLink'].replace('preview', 'edit')

                # Iterate over the revisions (from oldest to newest).
                lastRevModifiedDate=None
                for rev in gd.revisions(doc):
                    lastRevModifiedDate = rev['modifiedDate']
                if modifiedDate != lastRevModifiedDate:
                    foundChanges = True
                    if lastRevModifiedDate is None:
                        print("Need Edit access to: " + title + " (" + editLink + ")")
                        mailMessageBody += '<li><a href="' + editLink + '">' + title + ' (need edit access)</a></li>' + os.linesep
                        slackMessageBody += '<' + editLink + '|*' + title + ' (need edit access)*>' + os.linesep
                    else:
                        print("Document Change: " + title + " (" + editLink + ")")
                        mailMessageBody += '<li><a href="' + editLink + '">' + title + '</a></li>' + os.linesep
                        slackMessageBody += '<' + editLink + '|*' + title + '*>' + os.linesep
                    if lastRevModifiedDate is None:
                        docs[md['id']] = modifiedDate
                    else:
                        docs[md['id']] = lastRevModifiedDate

        # Write out the new files list and dates
        if opts.update and foundChanges:
            print("Updating file list")

            # write new file list
            f = open('myfilelist.py.new', 'w')
            f.write("docs={}\n")

            # Iterate over the documents we monitor
            for doc,modifiedDate in docs.items():
                if modifiedDate is not None:
               	    f.write('docs["' + doc + '"] = "' + modifiedDate + '"\n')
            f.close()

            # put new file in place
            os.rename('myfilelist.py.new', 'myfilelist.py')

        if opts.slackuser != "" and opts.slackroom != "" and opts.slacktoken != "" and slackMessageBody != "":
            print("Sending slack with changes")
            
            client = SlackClient(opts.slacktoken)
            client.chat_post_message("#" + opts.slackroom, ">>> The following documents have been changed since the last scan" + os.linesep + slackMessageBody, username=opts.slackuser)
            
        # Send a mail with the changes
        #
        # If you get: smtplib.SMTPAuthenticationError: (534... when using gmail
        #   you need to enable less secure access at https://www.google.com/settings/u/1/security/lesssecureapps
        #
        if opts.frommail != "" and mailMessageBody != "":
            print("Sending email with changes")

            finalMessageBody = "<html><head></head><body><ul>" + mailMessageBody + "</ul></body>"

            msg = MIMEText(finalMessageBody, 'html')
            msg['Subject'] = "The following documents have been changed since the last scan"
            msg['From'] = opts.frommail
            msg['To'] = ', '.join(opts.tomail)

            # Send the message via our own SMTP server, but don't include the
            # envelope header.
            if opts.usessl:
                s = smtplib.SMTP_SSL(opts.smtphost, opts.smtpport)
            else:
                s = smtplib.SMTP(opts.smtphost, opts.smtpport)
            s.ehlo()
            s.starttls()
            if opts.username != "":
                s.login(opts.username, opts.password)
            s.sendmail(opts.frommail, opts.tomail, msg.as_string())
            s.quit()

        # Bail out if we don't want to loop
        if opts.interval == 0:
            break
        else:
            time.sleep(opts.interval * 60)
Пример #49
0
from apscheduler.schedulers.background import BackgroundScheduler
from apscheduler.triggers.interval import IntervalTrigger
from flask import Flask, request, session, g, redirect, url_for, abort, \
     render_template, flash

from pyslack import SlackClient

# the number of days of inactivity after which we begin to decay
DECAY_AFTER = 3
SEGMENT = [98, 101, 110]
CLOSURE = [103, 105, 108, 98, 101, 114, 116]
ENCODING = [70, 111, 108, 108, 111, 119, 32, 109, 121, 32, 112, 111, 100, 99, 97, 115, 116, 33]

app = Flask(__name__)
scheduler = BackgroundScheduler()
slack_client = SlackClient(os.environ['SLACK_API_TOKEN'])

# Utility functions

def stdev(arr):
    if len(arr) < 2:
        raise ValueError("To calculate stdev, length ")
    mean = float(sum(arr)) / len(arr)
    deltas = [abs(a - mean)**2 for a in arr]
    return math.sqrt(float(sum(deltas)) / len(deltas))

def security_flag(segment, closure):
    return segment.lower() == ''.join([chr(x) for x in SEGMENT]) and closure.lower() == ''.join([chr(x) for x in CLOSURE])

def connect_db():
    rv = sqlite3.connect(app.config['DATABASE'])
Пример #50
0
 def __init__(self, token, user, send_to):
     self.client = SlackClient(token)
     self.user = user
     self.send_to = send_to
Пример #51
0
	v = np.array([list1[30] - list1[33],list2[30] - list2[33],list3[30] - list3[33]])
	return abs(np.cross(u,v)/np.linalg.norm(u))

if __name__ == '__main__':
	import sys, getopt
	fig3d = plt.figure()
	ax = fig3d.add_subplot(111,projection='3d')
	plt.ion()
	args, video_src = getopt.getopt(sys.argv[1:], '', ['face=', 'con=', 'tri='])
	try: video_src = video_src[0]
	except: video_src = 0
	args = dict(args)
	face_fn = args.get('--con', r"..\pyFaceTracker-0.1.1\external\FaceTracker\model\face.tracker")
	con_fn = args.get('--con', r"..\pyFaceTracker-0.1.1\external\FaceTracker\model\face.con")
	tri_fn  = args.get('--tri', r"..\pyFaceTracker-0.1.1\external\FaceTracker\model\face.tri")
	client = SlackClient('xoxp-2172260348-2172280558-2597830651-36a429')
	tracker = facetracker.FaceTracker(face_fn)
	conns = facetracker.LoadCon(con_fn)
	trigs = facetracker.LoadTri(tri_fn)
	cam = create_capture(video_src)
	tracker.setWindowSizes((7,))

	try:
		while True:
			ret, img = cam.read()
			gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
			#グレースケール画像のヒストグラムの均一化
			gray = cv2.equalizeHist(gray)
			if tracker.update(gray):
				obj3D = tracker.get3DShape()
				#drawMask(ax,obj3D)
Пример #52
0
from pyslack import SlackClient
import os

token = os.environ['SLACK_TOKEN']

if token == '':
    print('Could not get SLACK_TOKEN')
    exit(1)

client = SlackClient(token)
client.chat_post_message('#log',
                         "Posted from post.py: hello!",
                         username='******')