本文整理汇总了Python中twitter.TwitterError方法的典型用法代码示例。如果您正苦于以下问题:Python twitter.TwitterError方法的具体用法?Python twitter.TwitterError怎么用?Python twitter.TwitterError使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类twitter
的用法示例。
在下文中一共展示了twitter.TwitterError方法的14个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: plugin
# 需要导入模块: import twitter [as 别名]
# 或者: from twitter import TwitterError [as 别名]
def plugin(srv, item):
srv.logging.debug("*** MODULE=%s: service=%s, target=%s", __file__, item.service, item.target)
twitter_keys = item.addrs
twapi = twitter.Api(
consumer_key=twitter_keys[0],
consumer_secret=twitter_keys[1],
access_token_key=twitter_keys[2],
access_token_secret=twitter_keys[3]
)
text = item.message[0:138]
try:
srv.logging.debug("Sending tweet to %s..." % (item.target))
res = twapi.PostUpdate(text, trim_user=False)
srv.logging.debug("Successfully sent tweet")
except twitter.TwitterError as e:
srv.logging.error("TwitterError: %s" % e)
return False
except Exception as e:
srv.logging.error("Error sending tweet to %s: %s" % (item.target, e))
return False
return True
示例2: enf_type
# 需要导入模块: import twitter [as 别名]
# 或者: from twitter import TwitterError [as 别名]
def enf_type(field, _type, val):
""" Checks to see if a given val for a field (i.e., the name of the field)
is of the proper _type. If it is not, raises a TwitterError with a brief
explanation.
Args:
field:
Name of the field you are checking.
_type:
Type that the value should be returned as.
val:
Value to convert to _type.
Returns:
val converted to type _type.
"""
try:
return _type(val)
except ValueError:
raise TwitterError({
'message': '"{0}" must be type {1}'.format(field, _type.__name__)
})
示例3: delete
# 需要导入模块: import twitter [as 别名]
# 或者: from twitter import TwitterError [as 别名]
def delete(api, date, r):
with open("tweets.csv") as file:
count = 0
for row in csv.DictReader(file):
tweet_id = int(row["tweet_id"])
tweet_date = parse(row["timestamp"], ignoretz=True).date()
if date != "" and tweet_date >= parse(date).date():
continue
if (r == "retweet" and row["retweeted_status_id"] == "" or
r == "reply" and row["in_reply_to_status_id"] == ""):
continue
try:
print "Deleting tweet #{0} ({1})".format(tweet_id, tweet_date)
api.DestroyStatus(tweet_id)
count += 1
time.sleep(0.5)
except twitter.TwitterError, err:
print "Exception: %s\n" % err.message
示例4: add
# 需要导入模块: import twitter [as 别名]
# 或者: from twitter import TwitterError [as 别名]
def add(request):
"""
Add news items to the home page.
"""
if request.method == 'POST':
form = AddItemForm(data=request.POST)
if form.is_valid():
item = form.save(commit=False)
item.reporter = request.user
try:
with transaction.atomic():
item.save()
except twitter.TwitterError as e:
messages.error(request, "Twitter error: \"%s\" Please try again." % e.message[0]['message'])
else:
messages.info(request, "Your news item has been published!")
return redirect('home')
else:
form = AddItemForm()
return render(request, 'form.html', {
'title': 'Add Item',
'form': form,
'description': "Enter the details for the news item below.",
'action': 'Add',
})
示例5: catch_up_twitter
# 需要导入模块: import twitter [as 别名]
# 或者: from twitter import TwitterError [as 别名]
def catch_up_twitter(bridge):
if bridge.twitter_last_id == 0 and bridge.twitter_oauth_token:
# get twitter ID
twitter_api = twitter.Api(
consumer_key=app.config['TWITTER_CONSUMER_KEY'],
consumer_secret=app.config['TWITTER_CONSUMER_SECRET'],
access_token_key=bridge.twitter_oauth_token,
access_token_secret=bridge.twitter_oauth_secret,
tweet_mode='extended' # Allow tweets longer than 140 raw characters
)
try:
tl = twitter_api.GetUserTimeline()
except TwitterError as e:
flash(f"Twitter error: {e}")
else:
if len(tl) > 0:
bridge.twitter_last_id = tl[0].id
d = datetime.strptime(tl[0].created_at, '%a %b %d %H:%M:%S %z %Y')
bridge.md.last_tweet = d
else:
bridge.twitter_last_id = 0
bridge.updated = datetime.now()
db.session.commit()
示例6: email_bridge_details
# 需要导入模块: import twitter [as 别名]
# 或者: from twitter import TwitterError [as 别名]
def email_bridge_details(app, bridge):
if app.config.get('MAIL_SERVER', None):
mail = Mail(app)
twitter_follower_count = 0
if bridge.twitter_oauth_token:
# Fetch twitter follower count
twitter_api = twitter.Api(
consumer_key=app.config['TWITTER_CONSUMER_KEY'],
consumer_secret=app.config['TWITTER_CONSUMER_SECRET'],
access_token_key=bridge.twitter_oauth_token,
access_token_secret=bridge.twitter_oauth_secret
)
try:
follower_list = twitter_api.GetFollowerIDs()
except TwitterError as e:
twitter_follower_count = e
else:
twitter_follower_count = len(follower_list)
body = render_template('new_user_email.txt.j2',
bridge=bridge,
twitter_follower_count=twitter_follower_count)
msg = Message(subject="moa.party bridge updated",
body=body,
recipients=[app.config.get('MAIL_TO', None)])
try:
mail.send(msg)
except Exception as e:
app.logger.error(e)
示例7: media
# 需要导入模块: import twitter [as 别名]
# 或者: from twitter import TwitterError [as 别名]
def media(self):
if not self.__fetched_attachments:
if self.is_retweet:
target_id = self.data.retweeted_status.id
elif self.is_quoted:
if self.data.media and len(self.data.media) > 0:
# Does the user's tweet have media?
target_id = self.data.id
else:
# If not, use the media from the quoted tweet
target_id = self.data.quoted_status.id
else:
target_id = self.data.id
try:
fetched_tweet = self.api.GetStatus(
status_id=target_id,
trim_user=True,
include_my_retweet=False,
include_entities=True,
include_ext_alt_text=True
)
self.__fetched_attachments = fetched_tweet.media
except (TwitterError, ConnectionError) as e:
logger.error(e)
if not self.__fetched_attachments:
self.__fetched_attachments = []
return self.__fetched_attachments
示例8: testTwitterError
# 需要导入模块: import twitter [as 别名]
# 或者: from twitter import TwitterError [as 别名]
def testTwitterError(self):
'''Test that twitter responses containing an error message are wrapped.'''
self._AddHandler('http://twitter.com/statuses/public_timeline.json',
curry(self._OpenTestData, 'public_timeline_error.json'))
# Manually try/catch so we can check the exception's value
try:
statuses = self._api.GetPublicTimeline()
except twitter.TwitterError, error:
# If the error message matches, the test passes
self.assertEqual('test error', error.message)
示例9: get_statements
# 需要导入模块: import twitter [as 别名]
# 或者: from twitter import TwitterError [as 别名]
def get_statements(self):
"""
Returns list of random statements from the API.
"""
from twitter import TwitterError
statements = []
# Generate a random word
random_word = self.random_word(self.random_seed_word, self.lang)
self.logger.info(u'Requesting 50 random tweets containing the word {}'.format(random_word))
tweets = self.api.GetSearch(term=random_word, count=50, lang=self.lang)
for tweet in tweets:
statement = Statement(tweet.text)
if tweet.in_reply_to_status_id:
try:
status = self.api.GetStatus(tweet.in_reply_to_status_id)
statement.add_response(Response(status.text))
statements.append(statement)
except TwitterError as error:
self.logger.warning(str(error))
self.logger.info('Adding {} tweets with responses'.format(len(statements)))
return statements
示例10: destroy
# 需要导入模块: import twitter [as 别名]
# 或者: from twitter import TwitterError [as 别名]
def destroy(self, tweet_id):
try:
print("delete tweet %s" % tweet_id)
if not self.dry_run:
self.twitter_api.DestroyStatus(tweet_id)
# NOTE: A poor man's solution to honor Twitter's rate limits.
time.sleep(0.5)
except twitter.TwitterError as err:
print("Exception: %s\n" % err.message)
示例11: parse_media_file
# 需要导入模块: import twitter [as 别名]
# 或者: from twitter import TwitterError [as 别名]
def parse_media_file(passed_media):
""" Parses a media file and attempts to return a file-like object and
information about the media file.
Args:
passed_media: media file which to parse.
Returns:
file-like object, the filename of the media file, the file size, and
the type of media.
"""
img_formats = ['image/jpeg',
'image/png',
'image/gif',
'image/bmp',
'image/webp']
video_formats = ['video/mp4',
'video/quicktime']
# If passed_media is a string, check if it points to a URL, otherwise,
# it should point to local file. Create a reference to a file obj for
# each case such that data_file ends up with a read() method.
if not hasattr(passed_media, 'read'):
if passed_media.startswith('http'):
data_file = http_to_file(passed_media)
filename = os.path.basename(passed_media)
else:
data_file = open(os.path.realpath(passed_media), 'rb')
filename = os.path.basename(passed_media)
# Otherwise, if a file object was passed in the first place,
# create the standard reference to media_file (i.e., rename it to fp).
else:
if passed_media.mode not in ['rb', 'rb+', 'w+b']:
raise TwitterError('File mode must be "rb" or "rb+"')
filename = os.path.basename(passed_media.name)
data_file = passed_media
data_file.seek(0, 2)
file_size = data_file.tell()
try:
data_file.seek(0)
except Exception as e:
pass
media_type = mimetypes.guess_type(os.path.basename(filename))[0]
if media_type is not None:
if media_type in img_formats and file_size > 5 * 1048576:
raise TwitterError({'message': 'Images must be less than 5MB.'})
elif media_type in video_formats and file_size > 15 * 1048576:
raise TwitterError({'message': 'Videos must be less than 15MB.'})
elif media_type not in img_formats and media_type not in video_formats:
raise TwitterError({'message': 'Media type could not be determined.'})
return data_file, filename, file_size, media_type
示例12: fetch_tweet_data
# 需要导入模块: import twitter [as 别名]
# 或者: from twitter import TwitterError [as 别名]
def fetch_tweet_data(tweet_id: str) -> Optional[Dict[str, Any]]:
if settings.TEST_SUITE:
from . import testing_mocks
res = testing_mocks.twitter(tweet_id)
else:
creds = {
'consumer_key': settings.TWITTER_CONSUMER_KEY,
'consumer_secret': settings.TWITTER_CONSUMER_SECRET,
'access_token_key': settings.TWITTER_ACCESS_TOKEN_KEY,
'access_token_secret': settings.TWITTER_ACCESS_TOKEN_SECRET,
}
if not all(creds.values()):
return None
# We lazily import twitter here because its import process is
# surprisingly slow, and doing so has a significant impact on
# the startup performance of `manage.py` commands.
import twitter
try:
api = twitter.Api(tweet_mode='extended', **creds)
# Sometimes Twitter hangs on responses. Timing out here
# will cause the Tweet to go through as-is with no inline
# preview, rather than having the message be rejected
# entirely. This timeout needs to be less than our overall
# formatting timeout.
tweet = timeout(3, api.GetStatus, tweet_id)
res = tweet.AsDict()
except AttributeError:
markdown_logger.error('Unable to load twitter api, you may have the wrong '
'library installed, see https://github.com/zulip/zulip/issues/86')
return None
except TimeoutExpired:
# We'd like to try again later and not cache the bad result,
# so we need to re-raise the exception (just as though
# we were being rate-limited)
raise
except twitter.TwitterError as e:
t = e.args[0]
if len(t) == 1 and ('code' in t[0]) and (t[0]['code'] == 34):
# Code 34 means that the message doesn't exist; return
# None so that we will cache the error
return None
elif len(t) == 1 and ('code' in t[0]) and (t[0]['code'] == 88 or
t[0]['code'] == 130):
# Code 88 means that we were rate-limited and 130
# means Twitter is having capacity issues; either way
# just raise the error so we don't cache None and will
# try again later.
raise
else:
# It's not clear what to do in cases of other errors,
# but for now it seems reasonable to log at error
# level (so that we get notified), but then cache the
# failure to proceed with our usual work
markdown_logger.exception("Unknown error fetching tweet data")
return None
return res
示例13: send_tweet
# 需要导入模块: import twitter [as 别名]
# 或者: from twitter import TwitterError [as 别名]
def send_tweet(self, status_text, reply_to, media_ids=None) -> Optional[int]:
retry_counter = 0
post_success = False
while not post_success and retry_counter < TWITTER_RETRIES:
logger.info(f'Tweeting "{status_text}"')
if self.media_ids:
logger.info(f'With media')
try:
reply_to = self.api.PostUpdate(status_text,
media=media_ids,
in_reply_to_status_id=reply_to,
verify_status_length=False).id
post_success = True
except TwitterError as e:
logger.error(e.message)
if e.message[0]['code'] == 187:
# Status is a duplicate
return None
elif e.message[0]['code'] == 186:
# Status is too long. Nowadays this happens because of UTF-8 text.
return None
elif e.message[0]['code'] == 144:
# tweet being replied to is gone
return None
elif e.message[0]['code'] in [64, 89]:
logger.warning(f"Disabling bridge for Twitter user @{self.bridge.twitter_handle}")
self.bridge.twitter_oauth_token = None
self.bridge.twitter_oauth_secret = None
self.bridge.enabled = False
return None
if retry_counter < TWITTER_RETRIES:
retry_counter += 1
time.sleep(TWITTER_RETRY_DELAY)
if retry_counter == TWITTER_RETRIES:
logger.error("Retry limit reached.")
return None
return reply_to
示例14: parse_media_file
# 需要导入模块: import twitter [as 别名]
# 或者: from twitter import TwitterError [as 别名]
def parse_media_file(passed_media):
""" Parses a media file and attempts to return a file-like object and
information about the media file.
Args:
passed_media: media file which to parse.
Returns:
file-like object, the filename of the media file, the file size, and
the type of media.
"""
img_formats = ['image/jpeg',
'image/png',
'image/gif',
'image/bmp',
'image/webp']
video_formats = ['video/mp4',
'video/quicktime']
# If passed_media is a string, check if it points to a URL, otherwise,
# it should point to local file. Create a reference to a file obj for
# each case such that data_file ends up with a read() method.
if not hasattr(passed_media, 'read'):
if passed_media.startswith('http'):
data_file = http_to_file(passed_media)
filename = os.path.basename(urlparse(passed_media).path)
else:
data_file = open(os.path.realpath(passed_media), 'rb')
filename = os.path.basename(passed_media)
# Otherwise, if a file object was passed in the first place,
# create the standard reference to media_file (i.e., rename it to fp).
else:
if passed_media.mode not in ['rb', 'rb+', 'w+b']:
raise TwitterError('File mode must be "rb" or "rb+"')
filename = os.path.basename(passed_media.name)
data_file = passed_media
data_file.seek(0, 2)
file_size = data_file.tell()
try:
data_file.seek(0)
except Exception as e:
pass
media_type = mimetypes.guess_type(os.path.basename(filename))[0]
if media_type is not None:
if media_type in img_formats and file_size > 5 * 1048576:
raise TwitterError({'message': 'Images must be less than 5MB.'})
elif media_type in video_formats and file_size > 15 * 1048576:
raise TwitterError({'message': 'Videos must be less than 15MB.'})
elif media_type not in img_formats and media_type not in video_formats:
raise TwitterError({'message': 'Media type could not be determined.'})
return data_file, filename, file_size, media_type