Last active
January 29, 2016 15:34
-
-
Save howyi/c3fcf9e88029d35c3930 to your computer and use it in GitHub Desktop.
UserStreamToSlack.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python2.7 | |
#-*- coding:utf-8 -*- | |
import tweepy | |
from tweepy.streaming import StreamListener | |
from tweepy import Stream | |
import sys | |
import urllib2 | |
import slackweb | |
import requests.packages.urllib3 | |
requests.packages.urllib3.disable_warnings() | |
TWITTER_CONSUMER_KEY = "hoge" | |
TWITTER_CONSUMER_SECRET = "hoge" | |
TWITTER_ACCESS_TOKEN = "hoge" | |
TWITTER_ACCESS_TOKEN_SECRET = "hoge" | |
slack = slackweb.Slack(url="https://hooks.slack.com/services/hogehogehogehoge") | |
auth = tweepy.OAuthHandler(TWITTER_CONSUMER_KEY, TWITTER_CONSUMER_SECRET) | |
auth.set_access_token(TWITTER_ACCESS_TOKEN, TWITTER_ACCESS_TOKEN_SECRET) | |
api = tweepy.API(auth_handler=auth) | |
me = api.me().screen_name | |
def send_to_slack(status): | |
text = status.text.encode('utf-8') | |
if ('extended_entities' in status._json.keys()): | |
replace = '' | |
link = '' | |
for item in status.extended_entities['media']: | |
replace = item['url'].encode('utf-8') | |
link = link + ' ' + item['media_url_https'].encode('utf-8') | |
text = text.replace(replace,link) | |
slack.notify(channel="hoge",text=text, username=status.author.name.encode('utf-8'), icon_url=status.author.profile_image_url_https.encode('utf-8')) | |
class streamListener(StreamListener): #StreamingAPI | |
try: | |
def on_status(self, status): | |
if not hasattr(status, 'retweeted_status'): | |
send_to_slack(status) | |
else: | |
send_to_slack(status.retweeted_status) | |
def on_error(self, status): | |
print status | |
except: | |
if __name__ == '__main__': | |
l = streamListener() | |
stream = Stream(auth, l) | |
stream.userstream() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment