本文整理汇总了Python中twython.Twython.show_status方法的典型用法代码示例。如果您正苦于以下问题:Python Twython.show_status方法的具体用法?Python Twython.show_status怎么用?Python Twython.show_status使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类twython.Twython
的用法示例。
在下文中一共展示了Twython.show_status方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: update_given_tweet
# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import show_status [as 别名]
def update_given_tweet(tweet_id):
twitter = Twython(
app_key=APP_KEY,
app_secret=APP_SECRET,
oauth_token=OAUTH_TOKEN,
oauth_token_secret=OAUTH_TOKEN_SECRET,
)
try:
status = twitter.show_status(id=tweet_id)
return status
except Exception as err:
# rotate_key()
print(err.msg)
if 'rate limit exceeded' in err.msg.lower() or 'max retries' in err.msg.lower():
rotate_key()
# twitter = Twython(
# app_key=APP_KEY,
# app_secret=APP_SECRET,
# oauth_token=OAUTH_TOKEN,
# oauth_token_secret=OAUTH_TOKEN_SECRET,
# )
traceback.print_tb(err.__traceback__)
return update_given_tweet(tweet_id)
traceback.print_tb(err.__traceback__)
return False
示例2: getRetweetCount
# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import show_status [as 别名]
def getRetweetCount(twe_id):
index=0
while (index <len(APP_KEYS)):
APP_KEY = APP_KEYS[index]
APP_SECRET = APP_SECRETS[index]
OAUTH_TOKEN = OAUTH_TOKENS[index]
OAUTH_TOKEN_SECRET = OAUTH_TOKEN_SECRETS[index]
try:
twitter = Twython (APP_KEY, APP_SECRET)
auth = twitter.get_authentication_tokens()
twitter = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET)
result = twitter.show_status(id=twe_id)
'''
#print result['user']['screen_name'] + " " + result['user']['description']
tweet['Usr_Screename'] = result['user']['screen_name']
tweet['Usr_Description'] = result['user']['description']
tweet['FavoriteCount'] = int(result['favorite_count'])
'''
return int(result['retweet_count'])
except Exception as e:
if "429 (Too Many Requests)" in str(e):
index += 1
print "App Exceeded: index = %d"%(index)
pass
elif "404 (Not Found)" in str(e):
return -1
elif "403 (Forbidden)" in str(e):
return -1
else:
print e
return ''
示例3: follow_and_retweet
# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import show_status [as 别名]
def follow_and_retweet(CONSUMER_KEY, CONSUMER_SECRET, ACCESS_KEY, ACCESS_SECRET, queue):
bot = Twython(CONSUMER_KEY, CONSUMER_SECRET, ACCESS_KEY, ACCESS_SECRET)
time_queue = Queue.Queue()
while True:
if not queue.empty():
tweet_id = queue.get()
print 'thread: removed tweet ' + tweet_id + ' from queue'
print 'thread: time queue size: ' + str(time_queue.qsize())
if not time_queue.empty():
time_of_post = time_queue.get()
if time_queue.qsize() > 13:
while time.time() - time_of_post < 60*15:
pass
else:
for i in range(time_queue.qsize()):
time_queue.put(time_of_post)
time_of_post = time_queue.get()
time_queue.put(time_of_post)
try:
tweet = bot.show_status(id = tweet_id)
bot.retweet(id = tweet_id)
text = "@" + tweet["user"]["screen_name"] + " " + "NO SOUP FOR YOU!"
bot.update_status(status=text, in_reply_to_status_id=tweet_id)
except TwythonError as e:
print e
time_queue.put(time.time())
示例4: __init__
# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import show_status [as 别名]
class SocialTrends:
def __init__(self, authors, title, urls):
self.authors = authors
self.title = title
self.urls = urls
# hackathon hack!
if not len(authors):
self.authors = [""]
if not len(urls):
self.urls = ["NOT_APPLICABLE_90125738943705"]
if (authors[0], title) in social_cache:
self.twitter_results = social_cache[(authors[0], title, urls[0])]['twitter']
return
social_cache[(self.authors[0], self.title, self.urls[0])] = {}
(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET) = KEYS.keys()
self.tw = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET)
self.twitter_results = ""
self.reddit_results = ""
def paper_tweets(self):
if self.twitter_results:
return self.twitter_results
#allnames = author.split() # possible author names
#lastname = allnames[len(allnames)-1]
tweets = []
trend_score = 0
# possible urls
for url in self.urls:
url = url.lstrip("http://").lstrip("https://").lstrip("www.")
results = self.tw.search(q=url, count=50)
if results['statuses']:
(new_tweets, rt_counts) = zip(*[(status['id'], status['retweet_count']) for status in results['statuses']])
tweets += new_tweets
trend_score += sum(rt_counts)
# search title + author
#TODO count retweets and use in ranking
for author in self.authors:
results = self.tw.search(q="\"" + self.title + "\" " + author, count=50)
if results['statuses']:
(new_tweets, rt_counts) = zip(*[(status['id'], status['retweet_count']) for status in results['statuses']])
tweets += new_tweets
trend_score += sum(rt_counts)
#TODO see if there are any new urls to check in results?
#TODO search author + title fragments
#TODO better scoring system please
trend_score += len(tweets)
#TODO ID top tweets
top_tweets = [(t, self.tw.show_status(id=t)) for t in tweets[:30]]
self.twitter_results = (trend_score, top_tweets)
social_cache[(self.authors[0], self.title, self.urls[0])]['twitter'] = self.twitter_results
pickle.dump(social_cache, open(PICKLE_FILE,'wb'))
return self.twitter_results
示例5: getFeatures
# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import show_status [as 别名]
def getFeatures(filename):
csvfile = pd.read_csv(filename) # Reading .csv files containing tweets.
tweet_ids = csvfile["id_str"] # Copying the 'id_str' attribute values to a item.
length = len(tweet_ids) # Getting the length of 'tweet_ids'.
df = DataFrame(d, index=[0]) # Creating a DataFrame
twitter = Twython(APP_KEY, APP_SECRET, oauth_version=2)
ACCESS_TOKEN = twitter.obtain_access_token()
twitter = Twython(APP_KEY, access_token=ACCESS_TOKEN)
# Generating Access Token
for i in range(0, length):
status = twitter.show_status(id=tweet_ids[i])
d["id"] = status["id_str"].encode("utf-8")
d["created_at"] = status["created_at"].encode("utf-8")
d["from_user"] = status["user"]["screen_name"].encode("utf-8")
d["followers_count"] = status["user"]["followers_count"]
d["friends_count"] = status["user"]["friends_count"]
d["statuses_count"] = status["user"]["statuses_count"]
d["verified"] = status["user"]["verified"]
d["location"] = 0 if (len(status["user"]["location"].encode("utf-8")) == 0) else 1
d["text"] = status["text"].encode("utf-8")
d["retweet_count"] = status["retweet_count"]
d["favorite_count"] = status["favorite_count"]
d["hashtag_count"] = len(status["entities"]["hashtags"])
d["url_count"] = len(status["entities"]["urls"])
d["mentions_count"] = len(status["entities"]["user_mentions"])
if len(status["entities"]["urls"]) > 0:
for x in range(0, len(status["entities"]["urls"])):
d["links"] += status["entities"]["urls"][x]["expanded_url"].encode("utf-8") + " "
df = df.append(d, ignore_index=True)
df.to_csv("NSamples.csv") # Saving file to disk
d["links"] = ""
print "\nAll Done!"
示例6: Questions
# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import show_status [as 别名]
class Questions(object):
def __init__(self, appKey, appKeySecret, accessToken, accessTokenSecret):
self.questions = {}
self.handle = Twython(app_key=appKey, app_secret=appKeySecret, oauth_token=accessToken, oauth_token_secret=accessTokenSecret)
self.handle.get_home_timeline()
print "Remaining API calls: ", self.handle.get_lastfunction_header('x-rate-limit-remaining')
def getTweet(self, tweetId):
status = self.handle.show_status(id=tweetId)
tweetText = self.unescape(status['text'])
tweetText = re.sub(r'([ \t]*[#]+[\w]+[ \t]*|[ \t]*[#]+[ \t]*|[ \t]+$|[ \t]*[@]\w+[ \t]*)', '', tweetText)
return tweetText
def exprValidator(self, tweetId):
text = self.getTweet(tweetId)
print "validation: " + text
if text[-1] in ['>', '<']:
text = text[:-1]
elif text[-2] in ['>','<','=','!']:
text = text[:-2]
else:
return False
try:
exec("r = " + text)
if r == None:
return False
return True
except:
return False
def refresh(self, channel):
search = self.handle.search(q=channel, count=25)
tweets = search['statuses']
for tweet in tweets:
# Not a retweet
if tweet['text'][:2] != 'RT' and self.exprValidator(tweet['id']):
#db.addTweetToDB(channel, tweet['id'])
# If channel exists
if channel in self.questions:
# If ID is not on the list
if tweet['id'] not in self.questions[channel]:
self.questions[channel].append(tweet['id'])
# Channel doesn't exist, create it
else:
self.questions[channel] = [ tweet['id'] ]
def unescape(self, text):
text = text.replace("<", "<")
text = text.replace(">", ">")
text = text.replace("&", "&")
return text
示例7: get_tweet
# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import show_status [as 别名]
def get_tweet(token_id, url):
soc_token = SocToken.query.get(token_id)
twitter = Twython(
SocConfig.TWITTER_KEY, SocConfig.TWITTER_SECRET, soc_token.user_token, soc_token.token_secret)
status_id = TwitterApi.parse_status_id(url)
tweet = twitter.show_status(
id=status_id, include_my_retweet='true', include_entities='false')
return tweet
示例8: get_info
# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import show_status [as 别名]
def get_info():
with open('tweet_dict') as file:
twitterdata=json.load(file)
index=0
num_checked = 0
rate_ex = 0
for tweet in twitterdata:
if index >= 3:
"Exceeded all app rate limits"
break
tweet_id = tweet['Tweet_ID']
APP_KEY = APP_KEYS[index]
APP_SECRET = APP_SECRETS[index]
OAUTH_TOKEN = OAUTH_TOKENS[index]
OAUTH_TOKEN_SECRET = OAUTH_TOKEN_SECRETS[index]
if (tweet['Usr_Screename']== None or tweet['Usr_Description']== None):
try:
twitter = Twython (APP_KEY, APP_SECRET)
auth = twitter.get_authentication_tokens()
twitter = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET)
result = twitter.show_status(id=tweet_id)
print result['user']['screen_name'] + " " + result['user']['description']
tweet['Usr_Screename'] = result['user']['screen_name']
tweet['Usr_Description'] = result['user']['description']
num_checked += 1
except Exception as e:
if "429 (Too Many Requests)" in str(e):
index += 1
elif "404 (Not Found)" in str(e):
print "404"
tweet['Usr_Screename'] = ""
tweet['Usr_Description'] = ""
print "403"
elif "403 (Forbidden)" in str(e):
tweet['Usr_Screename'] = ""
tweet['Usr_Description'] = ""
else:
print e
rate_ex += 1
if (num_checked == 0 and rate_ex ==0):
with open("tweet_dict_fully_checked",'w') as fout:
json.dump(twitterdata,fout)
else:
with open('tweet_dict','w') as fout:
json.dump(twitterdata,fout)
time.sleep(900)
get_info()
示例9: collect_tweets
# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import show_status [as 别名]
def collect_tweets(path_name):
emotion_sentiment_mapping = {"joy":"positive","sadness":"negative","anger":"negative","fear":"negative","disgust":"negative"}
try:
#connecting to MongoDB database
mongoObj = MongoClient()
#setting the MongoDB database
db = mongoObj["TwitterSentimentAnalysis"]
#setting the collection in the database for storing the Tweets
collection = db["emotion_labeled_tweets"]
except:
print "Could not connect to the MongoDb Database, recheck the connection and the database"
try:
fp = open(path_name)
except IOError:
print "Please provide the right path to the file named labeledTweetSentimentCorpus.csv"
request_count = 0
key_count = 0
auth_key = t_auth.keyList[key_count%11]
for entry in fp:
tweet_id = entry.rstrip().split(":")[0]
try:
tweet_sentiment = emotion_sentiment_mapping[entry.rstrip().split("::")[1].strip()]
except:
tweet_sentiment = ""
twitter = Twython(auth_key["APP_KEY"],auth_key["APP_SECRET"],auth_key["OAUTH_TOKEN"],auth_key["OAUTH_TOKEN_SECRET"])
if request_count == 1499:
request_count = 0
key_count += 1
auth_key = t_auth.keyList[key_count%11]
time.sleep(60)
try:
twitter_status = twitter.show_status(id = tweet_id)
twitter_status["sentiment_label"] = tweet_sentiment
language = twitter_status["lang"]
if language == "en" and tweet_sentiment:
collection.insert(twitter_status)
else:
pass
except TwythonError:
pass
request_count += 1
示例10: twitter_status
# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import show_status [as 别名]
def twitter_status(match, bot=None):
global token
id = match.group(2)
init(bot.config['api_keys']['twitter_key'], bot.config['api_keys']['twitter_secret'])
twitter = Twython(bot.config['api_keys']['twitter_key'], access_token=token)
result = twitter.show_status(id=id)
at_name = result['user']['screen_name']
full_name = result['user']['name']
tweet_text = http.unescape(result['text'].replace('\n', ' '))
return "\[email protected]" + at_name + " \x02(" + full_name + ") - " + tweet_text
示例11: main
# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import show_status [as 别名]
def main():
config = parse_config(args.config)
twitter = Twython(config['consumer_key'], config['consumer_secret'], config['access_token'], config['access_token_secret'])
if os.path.isdir(args.outputpath):
fin = codecs.open(args.id_list_file, 'r', 'utf-8')
for tweetid in fin:
tweetid = tweetid.strip()
if not (tweetid + '.txt') in os.listdir('args.outputpath'):
try:
tweet = twitter.show_status(id=tweetid)
fout = codecs.open(str(args.outputpath) + tweetid + '.txt', 'w', 'utf-8')
fout.write(tweet['text'])
fout.close()
except:
pass
fin.close()
else:
print 'The output directory does not exist !'
exit()
示例12: twitter_status
# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import show_status [as 别名]
def twitter_status(match, bot=None):
global token
result = {}
if match.group("user").lower() == "realdonaldtrump":
init(bot.config["api_keys"]["twitter_key"], bot.config["api_keys"]["twitter_secret"])
twitter = Twython(bot.config["api_keys"]["twitter_key"], access_token=token)
result = choice(twitter.get_user_timeline(screen_name="BadSonicFanArt"))
else:
id = match.group(2)
init(bot.config["api_keys"]["twitter_key"], bot.config["api_keys"]["twitter_secret"])
twitter = Twython(bot.config["api_keys"]["twitter_key"], access_token=token)
result = twitter.show_status(id=id)
at_name = result["user"]["screen_name"]
full_name = result["user"]["name"]
tweet_text = http.unescape(result["text"].replace("\n", " "))
return "\[email protected]" + at_name + " \x02(" + full_name + ") - " + tweet_text
示例13: HTMLParser
# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import show_status [as 别名]
class twitter:
_unescape = HTMLParser().unescape
rooms = []
def __init__(self, bot, config):
self.get_our_nick = bot.get_our_nick
auth = config.get("auth", [{}])[0]
self.twython = Twython(auth.get("app_key"), access_token=auth.get("access_token"))
for muc in config.get("muc", []):
room = muc.get("room")
if room is None:
log.error(_("Configuration error - room attribute of muc required."))
continue
self.rooms.append(room)
bot.add_event_handler("muc::{}::message".format(room), self.handle_message, threaded=True)
def shutdown(self, bot):
for room in self.rooms:
bot.del_event_handler("muc::{}::message".format(room), self.handle_message)
def handle_message(self, msg):
if msg["mucnick"] in ("", self.get_our_nick(msg["mucroom"])):
# Ignore system and own message in MUC
return
match = re.search("https?://(mobile\.)?twitter\.com/.*?/status/([0-9]+)", msg.get("body"))
if match is None:
# No twitter status
return
status_id = match.group(2)
try:
status = self.twython.show_status(id=status_id)
name = self._unescape(status["user"]["screen_name"])
status = self._unescape(status["text"])
except:
log.exception(_("Unexpected error while getting twitter status {}.").format(status_id))
return
msg.reply("@{}: {}".format(name, status)).send()
示例14: TuiterText
# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import show_status [as 别名]
class TuiterText(TextTriggerPlugin):
def __init__(self):
TextTriggerPlugin.__init__(self)
self.trigger = re.compile(
"""((http|https)://(twitter.com)/(([A-Za-z0-9_]{1,15})/"""\
"""status)/([\d]*))""",
re.IGNORECASE
)
tuiter_conf = self.get_configuration('plugins/tuiterText.yapsy-plugin',
[
{
"section" : "Auth",
"conf" : "app_key"
},
{
"section" : "Auth",
"conf" :"app_secret"
}
])
self.api = Twython(tuiter_conf.get("app_key"),
tuiter_conf.get("app_secret"))
def execute(self, ircMsg, userRole, regex_group):
m = IRCMessage()
m.channel = ircMsg.channel
r_group = regex_group[0]
status = self.api.show_status(id = r_group[-1])
author = r_group[-2]
m.msg = u"@{0}: {1}".format(author, status.get("text"))
m.user = ircMsg.user
return m
示例15: receive
# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import show_status [as 别名]
def receive(self):
dm_enable = self.param('receiving', 'dm')
ids = self.param('receiving', 'ids')
tweets = list()
user_timeline = list()
APP_KEY = self.param('receiving', 'key')
APP_SECRET = self.param('receiving', 'secret')
OAUTH_TOKEN = self.param('receiving', 'token')
OAUTH_TOKEN_SECRET = self.param('receiving', 'tsecret')
SCREEN_NAME = self.param('receiving', 'name')
twitter = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET)
try:
if dm_enable:
if len(ids) > 0:
for dm_id in ids:
dm = twitter.get_direct_message(id=dm_id)
user_timeline.append(dm)
else:
user_timeline = twitter.get_direct_messages()
else:
if len(ids) > 0:
for t_id in ids:
tweet = twitter.show_status({'id': t_id})
user_timeline.append(tweet)
else:
user_timeline = twitter.get_user_timeline(screen_name=SCREEN_NAME)
for x in user_timeline:
if 'text' in x:
tweets.append(x['text'])
except Exception as err:
raise ExfilChannel("Error retrieving tweets: {0}".format(err))
return tweets