Skip to content

Instantly share code, notes, and snippets.

@markis
Last active August 29, 2015 14:23
Show Gist options
  • Save markis/43f7d433104b1713560b to your computer and use it in GitHub Desktop.
Save markis/43f7d433104b1713560b to your computer and use it in GitHub Desktop.
Script to monitor twitter and post to hipchat
#!/usr/bin/env python
import httplib, json
try:
from configparser import ConfigParser
except ImportError:
from ConfigParser import ConfigParser # ver. < 3.0
# config and globals
tweetMessages = []
configFileName = "config.ini"
config = ConfigParser()
config.read(configFileName)
# get tweets that match the search criteria
headers = {
"Content-type": "application/x-www-form-urlencoded;charset=UTF-8",
"Authorization": "Basic " + config.get("twitter", "auth")
}
httpServ = httplib.HTTPSConnection("api.twitter.com")
httpServ.connect()
httpServ.request("POST", "/oauth2/token", "grant_type=client_credentials", headers)
response = httpServ.getresponse()
if response.status == httplib.OK:
tokenObj = json.loads(response.read())
headers = {
"Authorization": "Bearer " + tokenObj["access_token"]
}
httpServ.request("GET", "/1.1/search/tweets.json" + config.get("twitter", "url"), None, headers)
response = httpServ.getresponse()
if response.status == httplib.OK:
tweets = json.loads(response.read())
config.set("twitter", "url", tweets["search_metadata"]["refresh_url"])
with open(configFileName, "w+") as dataFile:
config.write(dataFile)
for status in tweets["statuses"]:
text = status["text"]
if text.startswith("RT") == False:
screenName = status["user"]["screen_name"]
name = status["user"]["name"]
tweetUrl = "https://twitter.com/" + screenName + "/status/" + status["id_str"]
message = "%(text)s<br /><br />-%(name)s (@%(screenName)s) <br /><a href='%(tweetUrl)s'>%(tweetUrl)s</a>" % locals()
tweetMessages.append(message)
httpServ.close()
# post the tweets to hipchat
for tweetMsg in tweetMessages:
url = "/v2/room/" + config.get("hipchat", "room") + "/notification?auth_token=" + config.get("hipchat", "token")
headers = {
"Content-type": "application/json"
}
message = {
"notify": config.getboolean("hipchat", "notify"),
"message": tweetMsg,
"color": "yellow"
}
httpServ = httplib.HTTPSConnection("api.hipchat.com")
httpServ.connect()
httpServ.request("POST", url, json.dumps(message), headers)
response = httpServ.getresponse()
httpServ.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment