Skip to content

Commit

Permalink
Merge pull request joshnewlan#2 from cclauss/patch-1
Browse files Browse the repository at this point in the history
Create AUTH once and then reuse
  • Loading branch information
joshnewlan committed May 28, 2016
2 parents 6d01b0a + 45bab2f commit 1befb16
Showing 1 changed file with 31 additions and 33 deletions.
64 changes: 31 additions & 33 deletions say_my_name.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,12 @@
import requests
from requests.auth import HTTPBasicAuth
import time
import json
import requests
import subprocess
import time

requests.packages.urllib3.disable_warnings()

SPLUNK_URL = 'https://localhost:8089'
CREDS = ('username','password')
AUTH = requests.auth.HTTPBasicAuth('username', 'password')

# Hipchat creds and my user id
hipchat_url = "https://hipchat.company.com"
Expand All @@ -18,22 +17,23 @@

# Check for mentions within the last minute
name_search = ("""search index=say_what sourcetype=_json """
"""minutes=*{}* earliest=-1m@s""".format(name))
"""minutes=*{}* earliest=-1m@s""".format(name))

# Get everything that was said in the last minute
minutes_search = ("""search index=say_what sourcetype=_json """
"""minutes=* earliest=-1m@s| sort _time| fields minutes""")


def start_splunk_search(search_string):
try:
r = requests.post(
'%s/services/search/jobs' % SPLUNK_URL,
data={"search": search_string},
auth=HTTPBasicAuth(*CREDS),
'%s/services/search/jobs' % SPLUNK_URL,
data={"search": search_string},
auth=AUTH,
verify=False,
params={'output_mode': 'json'})
except Exception, e:
print e
except Exception as e:
print(e)

sid = r.json()['sid']
return sid
Expand All @@ -42,12 +42,12 @@ def start_splunk_search(search_string):
def search_results(sid):
done = False
print "Searching Splunk"
while done == False:
while not done:
status = requests.get(
'%s/services/search/jobs/%s' % (SPLUNK_URL, sid),
auth=HTTPBasicAuth(*CREDS),
verify=False,
params={'output_mode': 'json'})
'%s/services/search/jobs/%s' % (SPLUNK_URL, sid),
auth=AUTH,
verify=False,
params={'output_mode': 'json'})

done = status.json()['entry'][0]['content']['isDone']
time.sleep(1)
Expand All @@ -56,17 +56,17 @@ def search_results(sid):
return result_count


def get_results(sid,result_count):
def get_results(sid, result_count):
events = []
offset = 0

while result_count > len(events):
offset = len(events)
results = requests.get(
'%s/services/search/jobs/%s/results/' % (SPLUNK_URL, sid),
auth=HTTPBasicAuth(*CREDS),
'%s/services/search/jobs/%s/results/' % (SPLUNK_URL, sid),
auth=AUTH,
verify=False,
params={'output_mode': 'json', 'count': 0, 'f': 'minutes','offset': offset})
params={'output_mode': 'json', 'count': 0, 'f': 'minutes', 'offset': offset})

more_events = [row['minutes'].encode('utf-8') for row in results.json()['results']]
events += more_events
Expand All @@ -81,18 +81,16 @@ def splunk_search(search_string):
return events


def notify(user_id,auth_token,message):
def notify(user_id, auth_token, message):
# Send the conversation context to yourself on hipchat
data = {
'message': message,
'notify': True,
'message_format': 'text'
}

data = json.dumps(data)

r = requests.post('{}/v2/user/{}/message'.format(hipchat_url,user_id),
data=data,
r = requests.post('{}/v2/user/{}/message'.format(hipchat_url, user_id),
data=json.dumps(data),
headers = {
'content-type': 'application/json',
"Authorization": "Bearer {}".format(auth_token)
Expand All @@ -103,27 +101,27 @@ def notify(user_id,auth_token,message):
def muted():
# Play the "Sorry, I was on mute" audio file.
audio_file = "./Muted.m4a"
# This works on my macbook,
# This works on my macbook,
# change the command line tool to another one if on a different OS
audio_output = subprocess.call(["afplay", audio_file])


while True:
mentioned = splunk_search(name_search)
if len(mentioned) == 0:
if not mentioned:
time.sleep(1)
continue
mention_time = time.time()
print "You were mentioned!"
minutes = splunk_search(minutes_search)
print("You were mentioned!")
minutes = "\n".join(splunk_search(minutes_search))
try:
minutes = "\n".join(minutes)
notify(hipchat_user_id,hipchat_auth_token,minutes)
notify(hipchat_user_id, hipchat_auth_token, minutes)
except Exception as e:
print e
print(e)

while int(time.time() - mention_time) < 15:
time.sleep(1)

muted()
# Wait another minute before checking for name mentions
time.sleep(60)

0 comments on commit 1befb16

Please sign in to comment.