本文整理汇总了Python中twython.Twython方法的典型用法代码示例。如果您正苦于以下问题:Python twython.Twython方法的具体用法?Python twython.Twython怎么用?Python twython.Twython使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类twython
的用法示例。
在下文中一共展示了twython.Twython方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: add_access_token
# 需要导入模块: import twython [as 别名]
# 或者: from twython import Twython [as 别名]
def add_access_token(creds_file=None):
"""
For OAuth 2, retrieve an access token for an app and append it to a
credentials file.
"""
if creds_file is None:
path = os.path.dirname(__file__)
creds_file = os.path.join(path, 'credentials2.txt')
oauth2 = credsfromfile(creds_file=creds_file)
app_key = oauth2['app_key']
app_secret = oauth2['app_secret']
twitter = Twython(app_key, app_secret, oauth_version=2)
access_token = twitter.obtain_access_token()
tok = 'access_token={}\n'.format(access_token)
with open(creds_file, 'a') as infile:
print(tok, file=infile)
示例2: post_tweet
# 需要导入模块: import twython [as 别名]
# 或者: from twython import Twython [as 别名]
def post_tweet(message: str):
"""Post tweet message to account.
Parameters
----------
message: str
Message to post on Twitter.
"""
try:
twitter = Twython(TwitterAuth.consumer_key,
TwitterAuth.consumer_secret,
TwitterAuth.access_token,
TwitterAuth.access_token_secret)
twitter.update_status(status=message)
except TwythonError as e:
print(e)
示例3: get_available_trends
# 需要导入模块: import twython [as 别名]
# 或者: from twython import Twython [as 别名]
def get_available_trends():
"""
Returns the locations that Twitter has trending topic information for.
https://developer.twitter.com/en/docs/trends/locations-with-trending-topics/api-reference/get-trends-available
"""
twtr = Twython(**get_available_trends.get_auth_params())
available_trends = twtr.get_available_trends()
trends_df = pd.DataFrame(available_trends)
trends_df['code'] = [x['code'] for x in trends_df['placeType']]
trends_df['place_type'] = [x['name'] for x in trends_df['placeType']]
del trends_df['placeType']
trends_df = trends_df.sort_values(['country', 'place_type', 'name'])
trends_df = trends_df.reset_index(drop=True)
return trends_df
示例4: new_tweet
# 需要导入模块: import twython [as 别名]
# 或者: from twython import Twython [as 别名]
def new_tweet(filename=None, status=None):
"""Posts a new tweet.
Status are the initial conditions, video is attached.
To successfully post, a valid API key is needed to be stored in `api_key.txt`.
Args:
filename (string): name of the file containing video (without extension)
status (string): text which will be posted as Twitter status
"""
if filename is None:
filename, comment = create_content()
if status is None:
status = comment
with open("api_key.txt") as f:
api_data = f.readline().split(';')
twitter = Twython(*api_data)
video = open('./animations/{}.mp4'.format(filename), 'rb')
response = twitter.upload_video(media=video, media_type='video/mp4')
twitter.update_status(status=status, media_ids=[response['media_id']])
示例5: receive
# 需要导入模块: import twython [as 别名]
# 或者: from twython import Twython [as 别名]
def receive(self):
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)
user_timeline = twitter.get_user_timeline(screen_name=SCREEN_NAME, count=200, trim_user=True)
timeline = user_timeline
# TODO pagination
# while len(user_timeline) == 200:
# max_id = user_timeline[-1]['id'] + 1
# user_timeline = twitter.get_user_timeline(screen_name=SCREEN_NAME, count=200, trim_user=True, max_id=max_id)
# timeline.extend(user_timeline)
tweets = []
for x in reversed(timeline):
if 'text' in x:
tweets.append(x['text'].encode('utf-8'))
return tweets
示例6: __init__
# 需要导入模块: import twython [as 别名]
# 或者: from twython import Twython [as 别名]
def __init__(self, api_key, api_secret, log, client_args):
"""
:param api_key: The API KEY for a Twitter Developer App
:param api_secret: The API Secret for a Twitter Developer App.
Both of these values are used to acquire a OAuth2 Access Token,
:param log:
"""
self.log = log
self.twitter_auth = Twython(api_key, api_secret, oauth_version=2, client_args=client_args)
self.access_token = self.twitter_auth.obtain_access_token()
self.twitter = Twython(api_key, access_token=self.access_token, client_args=client_args)
log.debug("Access_Token is {}".format(self.access_token))
del api_secret, self.twitter_auth
log.info("Deleted API Secret")
示例7: tweet_search
# 需要导入模块: import twython [as 别名]
# 或者: from twython import Twython [as 别名]
def tweet_search(log, item, limit=50):
log.debug(" Searching twitter for %s", item)
check_twitter_config()
if len(item) > 500:
log.error(" Search string too long")
raise Exception("Search string too long: %d", len(item))
logging.captureWarnings(True)
old_level = log.getEffectiveLevel()
log.setLevel(logging.ERROR)
twitter = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET)
try:
result = twitter.search(q=item, count=limit)
except TwythonAuthError as e:
twitter_auth_issue(e)
raise
except:
raise
log.setLevel(old_level)
return result
示例8: check_relationship
# 需要导入模块: import twython [as 别名]
# 或者: from twython import Twython [as 别名]
def check_relationship(log, id):
my_screen_name = get_screen_name(log)
if my_screen_name == "Unknown":
raise("Couldn't get my own screen name")
log.debug(" Checking relationship of %s with me (%s)", id, my_screen_name)
check_twitter_config()
logging.captureWarnings(True)
old_level = log.getEffectiveLevel()
log.setLevel(logging.ERROR)
twitter = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET)
try:
result = twitter.show_friendship(source_screen_name=my_screen_name, target_screen_name=id)
except TwythonAuthError as e:
log.setLevel(old_level)
log.exception(" Problem trying to check relationship")
twitter_auth_issue(e)
raise
except:
raise
log.setLevel(old_level)
return result["relationship"]["source"]["following"], result["relationship"]["source"]["followed_by"]
示例9: follow_twitter_user
# 需要导入模块: import twython [as 别名]
# 或者: from twython import Twython [as 别名]
def follow_twitter_user(log, id):
log.debug(" Following %s", id)
check_twitter_config()
logging.captureWarnings(True)
old_level = log.getEffectiveLevel()
log.setLevel(logging.ERROR)
twitter = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET)
try:
twitter.create_friendship(screen_name=id)
except TwythonAuthError as e:
log.setLevel(old_level)
log.exception(" Problem trying to follow twitter user")
twitter_auth_issue(e)
raise
except:
raise
log.setLevel(old_level)
示例10: unfollow_twitter_user
# 需要导入模块: import twython [as 别名]
# 或者: from twython import Twython [as 别名]
def unfollow_twitter_user(log, id):
log.debug(" Unfollowing %s", id)
check_twitter_config()
logging.captureWarnings(True)
old_level = log.getEffectiveLevel()
log.setLevel(logging.ERROR)
twitter = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET)
try:
twitter.destroy_friendship(screen_name=id)
except TwythonAuthError as e:
log.setLevel(old_level)
log.exception("Error unfollowing %s", id)
twitter_auth_issue(e)
raise
except:
log.exception("Error unfollowing %s", id)
log.setLevel(old_level)
示例11: get_screen_name
# 需要导入模块: import twython [as 别名]
# 或者: from twython import Twython [as 别名]
def get_screen_name(log):
global MYSELF
if not MYSELF or MYSELF == "Unknown":
log.debug(" Getting current user screen name")
check_twitter_config()
logging.captureWarnings(True)
old_level = log.getEffectiveLevel()
log.setLevel(logging.ERROR)
twitter = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET)
try:
details = twitter.verify_credentials()
except TwythonAuthError as e:
log.setLevel(old_level)
log.exception(" Problem trying to get screen name")
twitter_auth_issue(e)
raise
except:
log.exception(" Problem trying to get screen name")
details = None
log.setLevel(old_level)
name = "Unknown"
if details:
name = details["screen_name"]
MYSELF = name
return MYSELF
示例12: search_and_retweet
# 需要导入模块: import twython [as 别名]
# 或者: from twython import Twython [as 别名]
def search_and_retweet(query: str, count=10):
"""Search for a query in tweets, and retweet those tweets.
Parameters
----------
query: str
A query to search for on Twitter.
count: int
Number of tweets to search for. You should probably keep this low
when you use search_and_retweet() on a schedule (e.g. cronjob).
"""
try:
twitter = Twython(TwitterAuth.consumer_key,
TwitterAuth.consumer_secret,
TwitterAuth.access_token,
TwitterAuth.access_token_secret)
search_results = twitter.search(q=query, count=count)
except TwythonError as e:
print(e)
return
for tweet in search_results["statuses"]:
# Make sure we don't retweet any dubplicates.
if not is_in_logfile(
tweet["id_str"], Settings.posted_retweets_output_file):
try:
twitter.retweet(id=tweet["id_str"])
write_to_logfile(
tweet["id_str"], Settings.posted_retweets_output_file)
print("Retweeted {} (id {})".format(shorten_text(
tweet["text"], maxlength=40), tweet["id_str"]))
except TwythonError as e:
print(e)
else:
print("Already retweeted {} (id {})".format(
shorten_text(tweet["text"], maxlength=40), tweet["id_str"]))
示例13: send
# 需要导入模块: import twython [as 别名]
# 或者: from twython import Twython [as 别名]
def send(self, tweetStr):
self.tweetStr = tweetStr
api = Twython(self._apiKey,self._apiSecret,self._accessToken,self._accessTokenSecret)
api.update_status(status=self.tweetStr)
示例14: __init__
# 需要导入模块: import twython [as 别名]
# 或者: from twython import Twython [as 别名]
def __init__(self, credentials):
self.twitter = twython.Twython(*credentials)
示例15: query
# 需要导入模块: import twython [as 别名]
# 或者: from twython import Twython [as 别名]
def query(self, q, **kw):
opts = copy(defaults)
opts.update(kw)
wait = 1
while True:
try:
response = Response(self.twitter.search(q=q, **opts))
break
except twython.exceptions.TwythonError as err:
logger.info("Twython error: {0}".format(err))
logger.info("Waiting {0} seconds...".format(wait))
sleep(wait)
wait *= 2
return response