Exemplo n.º 1
0
 def post(self):
   logging.info('request params: %s', self.request.params)
   full_command_text = slack.get_request_text(self.request)
   command_runner = commands.CommandRunner(request=self.request)
   slack_response = command_runner.run(full_command_text)
   response_url = slack.get_response_url(self.request)
   slack.send_message(slack_response, webhook=response_url)
Exemplo n.º 2
0
def main():
    logging.basicConfig(
        level=logging.DEBUG,
        format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
    logging.getLogger('selenium.webdriver.remote.remote_connection').setLevel(
        logging.WARNING)

    time_start = time.time()
    driver = init_driver()
    res = parse_match_results(driver)

    match_reports = persistence.load_match_reports()
    report_matches = filter_almost_finished_draws(list(res.values()),
                                                  match_reports)

    persistence.save_match_reports(match_reports)

    if report_matches:
        logging.info('Sending message to Slack')
        newline = "\n"
        message = f'*Zápasy splňující podmínky:*\n\n' \
                  f'{newline.join(["  • "+str(report_match) for report_match in report_matches])}'
        slack.send_message(message)
    else:
        logging.info('Nothing to send')

    time_duration = time.time() - time_start
    logging.info(f'Took {time_duration:.2f} seconds')
    logging.info(f'All live matches: {res}')
    logging.info(f'Filtered matches: {report_matches}')
Exemplo n.º 3
0
def post():

    NAMESPACE = os.getenv('NAMESPACE', 'platform-ci')

    MAPNAME = 'upload-service-valid-topics'
    headers = request.headers
    data = request.get_data(as_text=True)
    payload = request.json

    Updater = ConfigMapUpdater(MAPNAME,
                               NAMESPACE,
                               'platform-mq',
                               'topics/topics.json',
                               rawdata=True)

    newMap = Updater.github_pr(headers, data, payload)

    if not newMap.get('msg'):
        if Updater.update_configMap(newMap):
            logger.info('ConfigMap updated')
            slack.send_message("Updated valid-topics config in %s" % NAMESPACE)
            return json.dumps({'msg': 'Config Map Updated'})
        else:
            return json.dumps(
                {'msg': 'Something went wrong. Config map not updated'})
            logger.error('configMap not updated')
    else:
        return json.dumps({'msg': newMap.get('msg')})
Exemplo n.º 4
0
def handle(response, context):
  todaysQuietTime = getTodaysQuiteTime(getSoup(env.getDailyBiblePath()))
  todaysQuietTimeSoon = getTodaysQuiteTime(getSoup(env.getDailyBiblePath(), 'soon'))

  daily_bible_qt_table = dynamodb.get_daily_bible_qt_table()
  dynamodb.insert_daily_bible_qt(daily_bible_qt_table, todaysQuietTime, todaysQuietTimeSoon)

  slack.send_message(env.getChannelId(), '%s' % (todaysQuietTime))
  slack.send_message(env.getChannelId(), '%s' % (todaysQuietTimeSoon))

  return { 'status': 200 }
def extractVerses(start, end, scriptures):
    result = list()
    regex = re.compile(r'(\d+)')
    for i in range(int(start), int(end) + 1):
        for target in scriptures:
            data = regex.search(target)
            if data:
                if int(data.group(1)) == i:
                    result.append(target)
            else:
                slack.send_message(env.getChannelId(),
                                   '%s' % ("%d NONE Data" % (i)))

    return result
def arrangementMainText(subTitles, scriptures):
    result = list()
    regex = re.compile(r'(\d+)~(\d+)')
    for target in subTitles:
        target.rstrip()
        result.append(target)
        result.append('\n')
        data = regex.search(target)
        if data:
            result.extend(
                extractVerses(data.group(1), data.group(2), scriptures))
            result.append('\n')
        else:
            slack.send_message(env.getChannelId(),
                               '%s' % ('arrangementMainText Error'))

    return result
Exemplo n.º 7
0
def handle(response, context):
    options = webdriver.ChromeOptions()
    options.add_argument("--headless")
    options.add_argument("--disable-gpu")
    options.add_argument("--window-size=1280x1696")
    options.add_argument("--disable-application-cache")
    options.add_argument("--disable-infobars")
    options.add_argument("--no-sandbox")
    options.add_argument("--hide-scrollbars")
    options.add_argument("--enable-logging")
    options.add_argument("--log-level=0")
    options.add_argument("--v=99")
    options.add_argument("--single-process")
    options.add_argument("--ignore-certificate-errors")
    options.add_argument("--homedir=/tmp")
    options.binary_location = "./bin/headless_chromium"

    driver = webdriver.Chrome("./bin/chromedriver", chrome_options=options)
    driver.implicitly_wait(3)
    driver.get(env.getLivingLifePath())
    sleep(3)
    driver.implicitly_wait(3)
    driver.find_element_by_xpath(
        '//*[@id="project_detail"]/div[2]/ul/ul/li[3]/a').click()
    sleep(3)

    html = driver.page_source
    soup = BeautifulSoup(html, 'html.parser')

    driver.close()

    todaysWord = getTodaysWord(soup)
    todaysCommentary = getTodaysCommentary(soup)

    living_life_qt_table = dynamodb.get_living_life_qt_table()

    dynamodb.insert_living_life_qt(living_life_qt_table, todaysWord,
                                   todaysCommentary)

    slack.send_message(env.getChannelId(), '%s' % (todaysWord))
    slack.send_message(env.getChannelId(), '%s' % (todaysCommentary))

    return {'status': 200}
Exemplo n.º 8
0
def logout(c, environ):
    form = timecard.get_data(environ)
    plain = b"plain" in form

    content = [] if plain else timecard.html_begin()
    status = 200
    headers = []

    if auth.verify_auth(c, environ):
        if "name" in form:
            username = form['name'][0]

            c.execute("SELECT uid, logged_in, last_login FROM users WHERE UPPER(name)=?", (username.upper(),))
            rows = c.fetchall()
            if len(rows) != 1:
                status = 400
                content += ["User not found: " + username]
            else:
                uid = int(rows[0][0])
                if rows[0][1] == 0:  # User is not logged in
                    status = 400
                    content += ["Can't log out user because user is not logged in!"]
                else:
                    c.execute(
                        "INSERT INTO sessions(uid, begin_time, end_time) VALUES (?, ?, datetime('now', 'localtime'))",
                        (int(uid), rows[0][2]))
                    c.execute("UPDATE users SET logged_in=0 WHERE uid=?", (uid,))

                    slack.send_message("{} has signed out".format(username))

                    # Redirect
                    status = 303
                headers += [timecard.get_location_header("/app/manage")]
        else:
            status = 400
            content += ["No name specified"]
    else:
        status = 401
        if plain:
            content += ["Not logged in/Session not valid"]
        else:
            content += ["<a href='/login.html'>Please login</a>"]
    return status, content + ([] if plain else timecard.html_end()), headers
Exemplo n.º 9
0
def send_to_p2p():
    """
    Saves the SVG of a chart as a blurb in P2P
    """
    app.logger.debug("sending to P2P")

    # We should be POSTing
    if request.method in ["POST", "PUT"]:
        # Pull the data from the latest POST request
        app.logger.debug("attempting to post")
        data = request.form

        try:
            app.logger.debug("try. trying hard.")
            created, obj = update_or_create_chartblurb(data)

            content = {
                "message": "Updated in P2P",
                "created": created,
                "p2p_blurb": obj,
            }

            # print data.get('source', None)
            slug = data['slug']

            # Only send to Slack if this is coming from Chartbuilder
            if data['source'] == 'chartbuilder':
                msg = slack.prep_slack_message(slug, created)
                slack.send_message(msg)

            app.logger.debug("Created object in P2P!")
            return slug

        except Exception as e:
            app.logger.debug("Exception!")
            # Return the exception if it fails
            content = {"message": str(e)}
            r = jsonify(content)
            r.status_code = 500
            return r

    return "Sending to p2p!"
Exemplo n.º 10
0
def handle_event_callback(event: dict):
    try:
        event_type = event['type']
    except KeyError:
        raise HTTPException(status_code=HTTP_400_BAD_REQUEST,
                            detail="Missing event type")

    if event_type == "app_mention":
        event = SlackAppMentionEvent(**event)
        logger.debug("Received app mention: {e}".format(e=event))
        user = slack.users_info(event.user)
        slack.send_message(
            event.channel,
            "Hello @{name}".format(name=user['profile']['display_name']))
        return {"message": "ok"}
    else:
        logger.error("Cannot handle event: {e}".format(e=event))
        raise HTTPException(
            status_code=HTTP_400_BAD_REQUEST,
            detail="Unhandled event type: {et}".format(et=event_wrapper.type))
Exemplo n.º 11
0
def send_slack_message():
    slug = request.args.get("slug")
    if slug:
        msg = slack.prep_slack_message(slug)
    else:
        msg = slack.prep_slack_message("la-g-chart-test")

    r = slack.send_message(msg)

    if r is True:
        return "Slack message sent!"
    else:
        return "Error sending Slack message"
Exemplo n.º 12
0
def incoming_sms():
    resp = MessagingResponse()
    resp_message = ""

    if request.method == 'POST':
        message_body = request.values.get('Body', None)
        message_body = message_body.encode('utf8')

        if message_body.upper() == 'IDEA':
            resp_message = "Welcome! We're excited bout your idea! Let's get started. Please type your EID and begin with 'EID: '"

        elif "EID: " in message_body.upper():

            message = message_body.split()

            employee_id = str(message[1])

            query = "SELECT * FROM Employee WHERE EMPLID='" + employee_id + "'"
            cursor = conn.cursor()
            cursor.execute(query)
            user = cursor.fetchall()
            cursor.close()

            C["cookie_emplid"] = employee_id

            if (len(user) == 1):
                resp_message = "Thanks! From 1-5, how urgent is your idea? 1 being the least urgent."
            else:
                resp_message = "Please enter a valid Blue Apron ID."

        elif message_body in urgency:
            C["cookie_urgency"] = int(message_body)
            resp_message = "Got it. In a sentence, please describe your idea. 'My idea is...'"

        elif "MY IDEA IS" in message_body.upper():
            C["cookie_idea"] = message_body
            resp_message = "Last part: How did you come up with your idea and why is it worth pursuing? 'I came up with this idea because...'"

        elif "I CAME UP WITH THIS IDEA BECAUSE" in message_body.upper():
            C["cookie_why"] = message_body
            resp_message = "Thank you for using Matter Bot. Please send 'Done' when you're finished and have a great day!"

        else:
            # Find department of the employee
            cursor_one = conn.cursor()
            dept_query = "SELECT department FROM Employee WHERE EMPLID ='" + C[
                "cookie_emplid"].value + "'"
            cursor_one.execute(dept_query)
            dept = cursor_one.fetchone()
            cursor_one.close()

            # Find current ticket reviewer
            cursor_three = conn.cursor()
            reviewer_query = "SELECT EMPLID FROM Employee WHERE department ='" + dept[
                'department'].encode('utf8') + "' AND title = 'MANAGER'"
            cursor_three.execute(reviewer_query)
            reviewer = cursor_three.fetchone()
            cursor_three.close()

            # storing the ticket into the DB
            cursor_two = conn.cursor()
            query = 'INSERT INTO ticket (idea, why, urgency, date_created, person_in_charge) VALUES (%s, %s, %s, %s, %s);'
            time = datetime.now()
            cursor_two.execute(
                query,
                (C["cookie_idea"].value, C["cookie_why"].value,
                 int(C["cookie_urgency"].value), time, reviewer['EMPLID']))
            conn.commit()
            cursor_two.close()

            # getting the tracking id to insert to google sheets later
            cursor_four = conn.cursor()
            trackingNo_query = "SELECT ticket_id FROM ticket WHERE IDEA ='" + C[
                "cookie_idea"].value + "'"
            cursor_four.execute(trackingNo_query)
            trackingNo = cursor_four.fetchone()
            cursor_four.close()

            # insert into google sheets
            insert(C["cookie_emplid"].value, C["cookie_urgency"].value,
                   C["cookie_idea"].value, C["cookie_why"].value,
                   trackingNo['ticket_id'])

            # slack integration
            channel_id = findDept(dept["department"])

            # find person name
            cursor_five = conn.cursor()
            emp_query = "SELECT employee_name FROM Employee WHERE EMPLID ='" + C[
                "cookie_emplid"].value + "'"
            cursor_five.execute(emp_query)
            emp_name = cursor_five.fetchone()
            cursor_five.close()

            # sending message to slack
            send_message(channel_id, "Department " + channel_id,
                         C["cookie_emplid"].value,
                         int(C["cookie_urgency"].value),
                         emp_name["employee_name"], C["cookie_idea"].value,
                         C["cookie_why"].value)

    resp.message(resp_message)
    return str(resp)
Exemplo n.º 13
0
import sys
import re

import slack
#from auditGitHubLog

slack.send_message('vulnerability found')
Exemplo n.º 14
0
 def get(self):
   command_runner = commands.CommandRunner()
   slack_response = command_runner.daily(None)
   slack.send_message(slack_response)
   return self.response.write(slack_response)
Exemplo n.º 15
0
def handle(response, context):
    if response:
        content = response['content']
        user_key = response['user_key']

        if content == kw.getTodaysQTMainTitle():
            user_table = dynamodb.get_user_table()
            user_data = dynamodb.query_target_user(user_table, user_key)

            if user_data:
                if const.KEY_USER_ADMIN in user_data:
                    admin = user_data[const.KEY_USER_ADMIN]
                    if admin == 'TRUE':
                        return answer.getAdmin()

                admission = user_data[const.KEY_USER_ADMISSION]
                if admission == 'TRUE':
                    return answer.getQTChoice()
                else:
                    return answer.getDisapprovedUserCase()
            else:
                return answer.getUnappliedUserCase()

        elif content == kw.getAdminFunction():
            return answer.getAdminMode()

        elif content == kw.getLLQTMainTitle():
            return answer.getLLQTChoice()

        elif content == kw.getDBQTMainTitle():
            return answer.getDBQTChoice()

        elif content == kw.getLLQTSubTitle():
            living_life_qt_table = dynamodb.get_living_life_qt_table()
            data = dynamodb.query_living_life_qt(living_life_qt_table)
            if data is None:
                return answer.getLLQT(data)
            else:
                return answer.getLLQT(data[const.KEY_LIVING_LIFE_DATA])

        elif content == kw.getLLQTCommentary():
            living_life_qt_table = dynamodb.get_living_life_qt_table()
            data = dynamodb.query_living_life_qt(living_life_qt_table)
            if data is None:
                return answer.getLLQT(data)
            else:
                return answer.getLLQT(data[const.KEY_LIVING_LIFE_COMM])

        elif content == kw.getDBQTBasicTitle():
            daily_bible_qt_table = dynamodb.get_daily_bible_qt_table()
            data = dynamodb.query_daily_bible_qt(daily_bible_qt_table)
            if data is None:
                return answer.getDBQT(data)
            else:
                return answer.getDBQT(data[const.KEY_DAILY_BIBLE_DATA])

        elif content == kw.getDBQTSoonTitle():
            daily_bible_qt_table = dynamodb.get_daily_bible_qt_table()
            data = dynamodb.query_daily_bible_qt(daily_bible_qt_table)
            return answer.getDBQT(data[const.KEY_DAILY_BIBLE_SOON])

        elif content == kw.getHome():
            return answer.getMain()

        elif content == kw.getApply():
            return answer.getApplyManual()

        elif content == kw.getChangeUserState():
            return answer.getUserStateChangeMode()

        elif content == kw.getWaitList():
            user_table = dynamodb.get_user_table()
            waitList = dynamodb.query_wait_user(user_table)
            if waitList is not None:
                userList = list()
                for target in waitList:
                    userList.append(target[const.KEY_USER_KEY] + ' : ' +
                                    target[const.KEY_USER_INFO] + '\n')
                waitString = '\n'.join(userList)
                return answer.getWaitUserList(waitString)
            else:
                return answer.getWaitUserList(None)
        elif content == kw.getApproveList():
            user_table = dynamodb.get_user_table()
            approveList = dynamodb.query_approve_user(user_table)
            if approveList is not None:
                userList = list()
                for target in approveList:
                    userList.append(target[const.KEY_USER_KEY] + ' : ' +
                                    target[const.KEY_USER_INFO] + '\n')
                approveString = '\n'.join(userList)
                return answer.getApproveUserList(approveString)
            else:
                return answer.getApproveUserList(None)
        else:
            user_table = dynamodb.get_user_table()
            user_data = dynamodb.query_target_user(user_table, user_key)

            if user_data:
                if const.KEY_USER_ADMIN in user_data:
                    admin = user_data[const.KEY_USER_ADMIN]
                    if admin == 'TRUE':
                        target_user_data = dynamodb.query_target_user(
                            user_table, content)
                        if target_user_data:
                            admission = target_user_data[
                                const.KEY_USER_ADMISSION]
                            if admission == 'FALSE':
                                dynamodb.update_user(user_table, content,
                                                     'TRUE')
                                return answer.getUserStateChangeResult(
                                    content + ' : FALSE -> TRUE')
                            else:
                                dynamodb.update_user(user_table, content,
                                                     'FALSE')
                                return answer.getUserStateChangeResult(
                                    content + ' : TRUE -> FALSE')
                        else:
                            return answer.getEnterIncorrectlyWord()
                else:
                    return answer.getWrongAccess()
            else:
                dynamodb.insert_user(user_table, user_key, content)
                slack.send_message(os.environ['CHANNEL_ID'],
                                   '%s : %s' % (user_key, content))
                return answer.getApplyQuietTime()

    return {'status': 200}
Exemplo n.º 16
0
 def send_message(self, message, user_id, attachments=[]):
     return send_message(message, user_id, attachments=attachments)