本文整理汇总了Python中TwitterAPI.TwitterAPI方法的典型用法代码示例。如果您正苦于以下问题:Python TwitterAPI.TwitterAPI方法的具体用法?Python TwitterAPI.TwitterAPI怎么用?Python TwitterAPI.TwitterAPI使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类TwitterAPI
的用法示例。
在下文中一共展示了TwitterAPI.TwitterAPI方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: robust_request
# 需要导入模块: import TwitterAPI [as 别名]
# 或者: from TwitterAPI import TwitterAPI [as 别名]
def robust_request(twitter, resource, params, max_tries=5):
""" If a Twitter request fails, sleep for 15 minutes.
Do this at most max_tries times before quitting.
Args:
twitter .... A TwitterAPI object.
resource ... A resource string to request; e.g., "friends/ids"
params ..... A parameter dict for the request, e.g., to specify
parameters like screen_name or count.
max_tries .. The maximum number of tries to attempt.
Returns:
A TwitterResponse object, or None if failed.
"""
for i in range(max_tries):
request = twitter.request(resource, params)
if request.status_code == 200:
return request
else:
print('Got error %s \nsleeping for 15 minutes.' % request.text)
sys.stderr.flush()
time.sleep(61 * 15)
示例2: get_users
# 需要导入模块: import TwitterAPI [as 别名]
# 或者: from TwitterAPI import TwitterAPI [as 别名]
def get_users(twitter, screen_names):
"""Retrieve the Twitter user objects for each screen_name.
Params:
twitter........The TwitterAPI object.
screen_names...A list of strings, one per screen_name
Returns:
A list of dicts, one per user, containing all the user information
(e.g., screen_name, id, location, etc)
See the API documentation here: https://dev.twitter.com/rest/reference/get/users/lookup
In this example, I test retrieving two users: twitterapi and twitter.
>>> twitter = get_twitter()
>>> users = get_users(twitter, ['twitterapi', 'twitter'])
>>> [u['id'] for u in users]
[6253282, 783214]
"""
###TODO
pass
示例3: get_friends
# 需要导入模块: import TwitterAPI [as 别名]
# 或者: from TwitterAPI import TwitterAPI [as 别名]
def get_friends(twitter, screen_name):
""" Return a list of Twitter IDs for users that this person follows, up to 5000.
See https://dev.twitter.com/rest/reference/get/friends/ids
Note, because of rate limits, it's best to test this method for one candidate before trying
on all candidates.
Args:
twitter.......The TwitterAPI object
screen_name... a string of a Twitter screen name
Returns:
A list of ints, one per friend ID, sorted in ascending order.
Note: If a user follows more than 5000 accounts, we will limit ourselves to
the first 5000 accounts returned.
In this test case, I return the first 5 accounts that I follow.
>>> twitter = get_twitter()
>>> get_friends(twitter, 'aronwc')[:5]
[695023, 1697081, 8381682, 10204352, 11669522]
"""
###TODO
pass
示例4: add_all_friends
# 需要导入模块: import TwitterAPI [as 别名]
# 或者: from TwitterAPI import TwitterAPI [as 别名]
def add_all_friends(twitter, users):
""" Get the list of accounts each user follows.
I.e., call the get_friends method for all 4 candidates.
Store the result in each user's dict using a new key called 'friends'.
Args:
twitter...The TwitterAPI object.
users.....The list of user dicts.
Returns:
Nothing
>>> twitter = get_twitter()
>>> users = [{'screen_name': 'aronwc'}]
>>> add_all_friends(twitter, users)
>>> users[0]['friends'][:5]
[695023, 1697081, 8381682, 10204352, 11669522]
"""
###TODO
pass
示例5: tweetImage
# 需要导入模块: import TwitterAPI [as 别名]
# 或者: from TwitterAPI import TwitterAPI [as 别名]
def tweetImage(message,image_file):
"""
Tweet image with message
:param message:
:param image_file:
:return:
"""
from TwitterAPI import TwitterAPI
global settings_data
CONSUMER_KEY = settings_data['twitter']['CONSUMER_KEY']
CONSUMER_SECRET = settings_data['twitter']['CONSUMER_SECRET']
ACCESS_TOKEN_KEY = settings_data['twitter']['ACCESS_TOKEN_KEY']
ACCESS_TOKEN_SECRET = settings_data['twitter']['ACCESS_TOKEN_SECRET']
api = TwitterAPI(CONSUMER_KEY, CONSUMER_SECRET, ACCESS_TOKEN_KEY, ACCESS_TOKEN_SECRET)
file = open(image_file, 'rb')
data = file.read()
r = api.request('statuses/update_with_media', {'status':message}, {'media[]':data})
return str(str(r.status_code))
示例6: clean
# 需要导入模块: import TwitterAPI [as 别名]
# 或者: from TwitterAPI import TwitterAPI [as 别名]
def clean(self):
# remove leading @
if self.name.startswith('@'):
self.name = self.name[1:]
twitter = TwitterAPI(settings.TWITTER_CONSUMER_KEY,
settings.TWITTER_CONSUMER_SECRET,
auth_type='oAuth2')
try:
user = twitter.request('users/show', {'screen_name': self.name}).json()
except TwitterConnectionError:
logger.warning("Could not connect to Twitter.")
raise ValidationError("Could not connect to Twitter to retrieve user_id.")
if 'id' in user:
self.account_id = user['id']
else:
logger.warning("Could not find user with provided name.")
raise ValidationError("Could not find user with provided name.")
if TwitterAccount.objects.filter(account_id=self.account_id):
logger.warning("TwitterAccount with account_id is already in database.")
raise ValidationError("Twitter account with this name already exists.")
示例7: _watch_twitter_link
# 需要导入模块: import TwitterAPI [as 别名]
# 或者: from TwitterAPI import TwitterAPI [as 别名]
def _watch_twitter_link(bot, event, command):
if event.user.is_self:
return
if " " in event.text:
return
if not re.match(r"^https?://(www\.)?twitter.com/[a-zA-Z0-9_]{1,15}/status/[0-9]+$", event.text, re.IGNORECASE):
return
try:
key = bot.memory.get_by_path(['twitter', 'key'])
secret = bot.memory.get_by_path(['twitter', 'secret'])
tweet_id = re.match(r".+/(\d+)", event.text).group(1)
api = TwitterAPI(key, secret, auth_type="oAuth2")
tweet = json.loads(api.request('statuses/show/:{}'.format(tweet_id)).text)
text = re.sub(r'(\W)@(\w{1,15})(\W)', r'\1<a href="https://twitter.com/\2">@\2</a>\3' ,tweet['text'])
text = re.sub(r'(\W)#(\w{1,15})(\W)', r'\1<a href="https://twitter.com/hashtag/\2">#\2</a>\3', text)
time = tweet['created_at']
timeago = prettydate(datetime.datetime.now(tz=datetime.timezone.utc) - datetime.datetime.strptime(time, '%a %b %d %H:%M:%S %z %Y'))
logger.info(timeago)
username = tweet['user']['name']
twhandle = tweet['user']['screen_name']
userurl = "https://twitter.com/intent/user?user_id={}".format(tweet['user']['id'])
message = "<b><u><a href='{}'>@{}</a> ({})</u></b>: {} <i>{}</i>".format(userurl, twhandle, username, text, timeago)
try:
images = tweet['extended_entities']['media']
for image in images:
if image['type'] == 'photo':
imagelink = image['media_url']
filename = os.path.basename(imagelink)
async with aiohttp.ClientSession() as session:
async with session.request('get',imagelink) as res:
raw = await res.read()
image_data = io.BytesIO(raw)
image_id = await bot._client.upload_image(image_data,
filename=filename)
await bot.coro_send_message(event.conv.id_, None, image_id=image_id)
except KeyError:
pass
await bot.coro_send_message(event.conv, message)
except:
url = event.text.lower()
try:
response = urllib.request.urlopen(url)
except urllib.error.URLError as e:
logger.info("Tried and failed to get the twitter status text:(")
logger.info(e.reason)
return
username = re.match(r".+twitter\.com/([a-zA-Z0-9_]+)/", url).group(1)
body = response.read()
soup = BeautifulSoup(body.decode("utf-8"), "lxml")
twhandle = soup.title.text.split(" on Twitter: ")[0].strip()
tweet = re.sub(r"#([a-zA-Z0-9]*)",r"<a href='https://twitter.com/hashtag/\1'>#\1</a>", soup.title.text.split(" on Twitter: ")[1].strip())
message = "<b><a href='{}'>@{}</a> [{}]</b>: {}".format("https://twitter.com/{}".format(username), username, twhandle, tweet)
await bot.coro_send_message(event.conv, message)
示例8: get_twitter
# 需要导入模块: import TwitterAPI [as 别名]
# 或者: from TwitterAPI import TwitterAPI [as 别名]
def get_twitter():
""" Construct an instance of TwitterAPI using the tokens you entered above.
Returns:
An instance of TwitterAPI.
"""
return TwitterAPI(consumer_key, consumer_secret, access_token, access_token_secret)
示例9: withImage
# 需要导入模块: import TwitterAPI [as 别名]
# 或者: from TwitterAPI import TwitterAPI [as 别名]
def withImage( filepath, text ):
api = TwitterAPI(CONSUMER_KEY, CONSUMER_SECRET, ACCESS_TOKEN_KEY, ACCESS_TOKEN_SECRET)
print('Tw:'+filepath)
print('Tw:'+text)
file = open( filepath, 'rb')
img_data = file.read()
r = api.request('statuses/update_with_media', {'status': text }, {'media[]':img_data})
print( 'Twitter status:' + str(r.status_code) )
示例10: __init__
# 需要导入模块: import TwitterAPI [as 别名]
# 或者: from TwitterAPI import TwitterAPI [as 别名]
def __init__(self):
self.max_messages = 10;
self.messages = [];
self.api = TwitterAPI(Twitter.CONSUMER_KEY,
Twitter.CONSUMER_SECRET,
Twitter.ACCESS_TOKEN_KEY,
Twitter.ACCESS_TOKEN_SECRET)
示例11: __init__
# 需要导入模块: import TwitterAPI [as 别名]
# 或者: from TwitterAPI import TwitterAPI [as 别名]
def __init__(self, photo_resolution, strip_resolution_ratio, yes_pin, no_pin, print_command,
twitter_credentials=None,
disable_quit=False):
self.photo_resolution = photo_resolution
self.yes_pin = yes_pin
self.no_pin = no_pin
self.strip_resolution_ratio = strip_resolution_ratio
self.print_command = print_command
self.disable_quit = disable_quit
self.camera_controller = None
self.window = None
self.window_renderer = None
self.preview_renderer = None
self.buffer_image = None
self.canvas = None
self.screen_resolution = None
self.normalized_screen_resolution = None
self.yes_button = None
self.no_button = None
self.fps = 1
self.picture_count = 4
self.state = STATE_DEFAULT
self.render_timer = Timer(0.1)
self.countdown_timer = Timer()
self.pictures_taken = list()
self._twitter = None
if twitter_credentials:
self._twitter_text = twitter_credentials.text
self._twitter = TwitterAPI(
twitter_credentials.consumer_key,
twitter_credentials.consumer_secret,
twitter_credentials.access_token,
twitter_credentials.access_token_secret)
for x in self._twitter.request('account/verify_credentials'):
self._twitter_username = x['screen_name']
示例12: annoy_vodafone
# 需要导入模块: import TwitterAPI [as 别名]
# 或者: from TwitterAPI import TwitterAPI [as 别名]
def annoy_vodafone(download, upload):
"""
Send the tweet
"""
api = TwitterAPI(CONSUMER_KEY, CONSUMER_SECRET, ACCESS_TOKEN_KEY, ACCESS_TOKEN_SECRET)
message = MESSAGE.format(download, upload)
print 'Sending message:', message
with open('graph.png', 'rb') as image:
data = image.read()
request = api.request('statuses/update_with_media',
{'status': message},
{'media[]': data})
print('Sent.' if request.status_code == 200 else 'Error. ' + request.text)
示例13: test_fetch_tweets_from_api_max_since_id_none
# 需要导入模块: import TwitterAPI [as 别名]
# 或者: from TwitterAPI import TwitterAPI [as 别名]
def test_fetch_tweets_from_api_max_since_id_none(self, request_mock):
twitter_account = TwitterAccount(name="Strassengezwitscher")
twitter = TwitterAPI('a', 'b', auth_type='oAuth2')
twitter_account._fetch_tweets_from_api(twitter)
self.assertEqual('since_id' in request_mock.call_args[0][1], False)
self.assertEqual('max_id' in request_mock.call_args[0][1], False)
示例14: test_fetch_tweets_from_api_max_since_id_set
# 需要导入模块: import TwitterAPI [as 别名]
# 或者: from TwitterAPI import TwitterAPI [as 别名]
def test_fetch_tweets_from_api_max_since_id_set(self, request_mock):
twitter_account = TwitterAccount(name="Strassengezwitscher")
twitter = TwitterAPI('a', 'b', auth_type='oAuth2')
twitter_account._fetch_tweets_from_api(twitter, max_id=99, since_id=17)
self.assertEqual('since_id' in request_mock.call_args[0][1], True)
self.assertEqual('max_id' in request_mock.call_args[0][1], True)
示例15: __init__
# 需要导入模块: import TwitterAPI [as 别名]
# 或者: from TwitterAPI import TwitterAPI [as 别名]
def __init__(self, consumer_key, consumer_secret, access_token_key,
access_token_secret):
"""Initialize the service."""
from TwitterAPI import TwitterAPI
self.api = TwitterAPI(consumer_key, consumer_secret, access_token_key,
access_token_secret)