def get_followers_or_followees(twitter_user_id, twitter_url, retry=0, oauth=False, access_token=''): """Return a list of followers or followees of a Twitter user""" x = [] tw = None params = {'user_id': twitter_user_id, 'cursor': '-1'} try: px = urlencode(params) if oauth: if not access_token: tw_prof = TwitterProfile.objects.active().filter( appuser_id=twitter_user_id).exclude( access_token=u'').order_by("-updated_on")[:1].get() access_token = tw_prof.access_token tw = TwitterAPI() if PROTOCOL == 'https': twitter_url = twitter_url.replace('http:', 'https:') _url = twitter_url % px _log.debug("OAuth URL %s" % _url) ret = tw.get_url(access_token, _url) tw.close() else: _url = twitter_url % px _log.debug(_url) req = urllib2.Request(_url) req.add_header("Content-type", "application/x-www-form-urlencoded") req.add_header('User-Agent', settings.USER_AGENT) resp = urllib2.urlopen(req) ret = resp.read() resp.close() results = json.loads(ret) if type(results) == dict: x = results.get('ids', []) else: x = results time.sleep(settings.TWITTER_SLEEP) return x except urllib2.HTTPError, h: if h.code == 401 and retry < 2: # Try with OAuth return get_followers_or_followees(twitter_user_id, twitter_url, retry=retry + 1, oauth=True, access_token=access_token) _log.error("%s failed for twitter id: %s (HTTP Error)", twitter_url, twitter_user_id) _log.exception(h) if h.code in (503, 502, 420): time.sleep(30 + retry * 30) # throttle if x or retry > 1: return x return get_followers_or_followees(twitter_user_id, twitter_url, retry=retry + 1, oauth=oauth, access_token=access_token)
def register(request, template='registration/registration_form.html', redirect_field_name='next'): if request.user.is_authenticated(): prof = request.user_profile u = prof.user if prof.is_sso and prof.twitter_profile: # populate current open profile into session t = prof.twitter_profile # get profile image URL from Twitter profile_image = '' try: tw = TwitterAPI() twitter_profile = tw.get_profile(t.access_token) tw.close() if twitter_profile: p = simplejson.loads(twitter_profile) profile_image = p.get('profile_image_url', '') if '/images/default_profile' in profile_image: profile_image = '' except Exception, e: _log.exception(e) # continue without profile image open_profile = dict( profile_type=u'twitter', screen_name=t.screen_name, first_name=u.first_name, last_name=u.last_name, appuser_id=t.appuser_id, profile_image_url=profile_image, access_token=t.access_token ) # logout(request) # request.user_profile = None request.session['OPEN_PROFILE'] = open_profile else: return HttpResponseRedirect(reverse('account'))
def random_tweet(): tweet = TwitterAPI.get_random_tweet() tweet_id = tweet['id'] # Store the random tweet with open('tweets/%d.json' % tweet_id, 'w') as f: f.write(json.dumps(tweet)) # Get our additional information query = Query(tweet['text'] + " " + tweet['user']['name']) query.run() article = query.get_result_article() article_file_name = query.get_result_filename() # Replace all the links in the article if article is not None: article = article.replace('/wiki/', 'https://en.wikipedia.org/wiki/') if article is not None: markup = TwitterAPI.get_tweet_markup(tweet_id) parameters = { 'article_html': article, 'article_filename': article_file_name, 'tweet_html': markup, 'ratings': [1, 2, 3, 4, 5], 'tweet_id': tweet_id, } return render_template('tweet.html', **parameters) else: # We need to find another tweet return random_tweet()
def post_to_twitter(user, status): """Helper function to post a user's status to her authorized Twitter account.""" posting_status = '' try: tw_prof = user.get_profile().twitter_profile if tw_prof and tw_prof.access_token: _log.debug("Posting %s's status - %s", user.username.title(), status) tw = TwitterAPI() posting_status = tw.post_status(tw_prof.access_token, status) tw.close() s = json.loads(posting_status) if s.get('id', False): _log.debug("Posted %s's status - %s", user.username.title(), s.get("text", "NO TEXT")) return s else: _log.error("Could not post %s's status:\n%s\n", user.username.title(), posting_status) return False except Exception, e: _log.exception(e) if posting_status: _log.debug("Posting status error:\n%s", posting_status) if tw_prof and 'invalid oauth request' in posting_status.lower() or 'failed to validate oauth' in posting_status.lower(): # Remove unusable access token tw_prof.access_token = u'' tw_prof.save() return False
def post_to_twitter(user, status): """Helper function to post a user's status to her authorized Twitter account.""" posting_status = '' try: tw_prof = user.get_profile().twitter_profile if tw_prof and tw_prof.access_token: _log.debug("Posting %s's status - %s", user.username.title(), status) tw = TwitterAPI() posting_status = tw.post_status(tw_prof.access_token, status) tw.close() s = json.loads(posting_status) if s.get('id', False): _log.debug("Posted %s's status - %s", user.username.title(), s.get("text", "NO TEXT")) return s else: _log.error("Could not post %s's status:\n%s\n", user.username.title(), posting_status) return False except Exception, e: _log.exception(e) if posting_status: _log.debug("Posting status error:\n%s", posting_status) if tw_prof and 'invalid oauth request' in posting_status.lower( ) or 'failed to validate oauth' in posting_status.lower(): # Remove unusable access token tw_prof.access_token = u'' tw_prof.save() return False
def request_token(self, user): tweaked_twitter_client = TwitterAPI(auth=self.oauth, format='', api_version=None) try: response = tweaked_twitter_client.oauth.request_token( oauth_callback=Twitter.AUTHORIZE_CALLBACK) except Exception as e: self.error('Error while generating oauth token: {}'.format(e)) else: params = dict( (key, value) for key, value in (component.split('=') for component in response.split('&'))) try: token = params['oauth_token'] secret = params['oauth_token_secret'] except: return else: self.info('Generated request token for {}'.format(user.name)) self.request_tokens[token] = secret return token
def save_user(self, user, oauth_token, oauth_verifier): oauth = OAuth( oauth_token, self.request_tokens[oauth_token], self.config.get(c.CONSUMER_KEY_KEY), self.config.get(c.CONSUMER_SECRET_KEY), ) tweaked_twitter_client = TwitterAPI(auth=oauth, format='', api_version=None) try: response = tweaked_twitter_client.oauth.access_token( oauth_verifier=oauth_verifier) except Exception as e: self.error(e) pass else: params = dict( (key, value) for key, value in (component.split('=') for component in response.split('&'))) with self.transaction() as trans: trans.execute( q.add_user, dict(id=user.id, token=params['oauth_token'], secret=params['oauth_token_secret']))
def load(self): self.oauth = OAuth( self.config.get(c.ACCESS_TOKEN_KEY), self.config.get(c.ACCESS_TOKEN_SECRET_KEY), self.config.get(c.CONSUMER_KEY_KEY), self.config.get(c.CONSUMER_SECRET_KEY), ) self.client = TwitterAPI(auth=self.oauth) context = dict(plugin=self, bot=self.bot) self.add_web_handlers( (r'/twitter/oauth_token', OAuthTokenHandler, context), (r'/twitter/authorize', OAuthAuthorizeHandler, context), (r'/twitter/status', TwitterStatusHandler, context), (r'/twitter/disconnect', TwitterDisconnectHandler, context), ) self.monitored = set() self.restore_monitored() self.request_tokens = dict() self.last_tweets = dict() self.interactive_tweets = dict()
def tweet(self): try: twitter = TwitterAPI() sec = (datetime.now() - self.starttime).seconds soundcloud_link = self.ss.current_track_permalink() if not sec < 3: if self.twitter_un: twitter.tweet( '@%s just peed for %d seconds while jamming to %s' % ( self.twitter_un, sec, soundcloud_link)) else: twitter.tweet('Just peed for %d seconds while jamming to %s' % ( sec, soundcloud_link)) except Exception, e: print 'could not tweet: ', e
def get_followers_or_followees(twitter_user_id, twitter_url, retry=0, oauth=False, access_token=''): """Return a list of followers or followees of a Twitter user""" x = [] tw = None params = {'user_id':twitter_user_id, 'cursor':'-1'} try: px = urlencode(params) if oauth: if not access_token: tw_prof = TwitterProfile.objects.active().filter( appuser_id=twitter_user_id ).exclude(access_token=u'').order_by("-updated_on")[:1].get() access_token = tw_prof.access_token tw = TwitterAPI() if PROTOCOL == 'https': twitter_url = twitter_url.replace('http:', 'https:') _url = twitter_url % px _log.debug("OAuth URL %s" % _url) ret = tw.get_url(access_token, _url) tw.close() else: _url = twitter_url % px _log.debug(_url) req = urllib2.Request(_url) req.add_header("Content-type", "application/x-www-form-urlencoded") req.add_header('User-Agent', settings.USER_AGENT) resp = urllib2.urlopen(req) ret = resp.read() resp.close() results = json.loads(ret) if type(results) == dict: x = results.get('ids', []) else: x = results time.sleep(settings.TWITTER_SLEEP) return x except urllib2.HTTPError, h: if h.code == 401 and retry < 2: # Try with OAuth return get_followers_or_followees(twitter_user_id, twitter_url, retry=retry+1, oauth=True, access_token=access_token) _log.error("%s failed for twitter id: %s (HTTP Error)", twitter_url, twitter_user_id) _log.exception(h) if h.code in (503, 502, 420): time.sleep(30 + retry*30) # throttle if x or retry > 1: return x return get_followers_or_followees(twitter_user_id, twitter_url, retry=retry+1, oauth=oauth, access_token=access_token)
def get_user_api(self, oauth_user): oauth = OAuth( oauth_user.token, oauth_user.secret, self.config.get(c.CONSUMER_KEY_KEY), self.config.get(c.CONSUMER_SECRET_KEY), ) return TwitterAPI(auth=oauth)
def save(self, commit=True): comment = super(CommentForm, self).save(commit=False) comment.user = self.user comment.content_type = self.content_type comment.object_pk = self.object_pk comment.is_public = self.is_public comment.submit_date = datetime.now() comment.site = self.site comment.save() try: if self.cleaned_data.get("do_tweet", False) and getattr(settings, 'ENABLE_COMMENT_TWEET', True): tw_prof = self.user.get_profile().twitter_profile if tw_prof and tw_prof.access_token: tw = TwitterAPI() tweet = tw.post_status(tw_prof.access_token, comment.comment) tw.close() self.tweet_posted(comment, tweet) except Exception, e: _log.exception(e)
def save(self, commit=True): comment = super(CommentForm, self).save(commit=False) comment.user = self.user comment.content_type = self.content_type comment.object_pk = self.object_pk comment.is_public = self.is_public comment.submit_date = datetime.now() comment.site = self.site comment.save() try: if self.cleaned_data.get("do_tweet", False) and getattr( settings, 'ENABLE_COMMENT_TWEET', True): tw_prof = self.user.get_profile().twitter_profile if tw_prof and tw_prof.access_token: tw = TwitterAPI() tweet = tw.post_status(tw_prof.access_token, comment.comment) tw.close() self.tweet_posted(comment, tweet) except Exception, e: _log.exception(e)
def load(self): self.oauth = OAuth( self.config.get(c.ACCESS_TOKEN_KEY), self.config.get(c.ACCESS_TOKEN_SECRET_KEY), self.config.get(c.CONSUMER_KEY_KEY), self.config.get(c.CONSUMER_SECRET_KEY), ) self.client = TwitterAPI(auth=self.oauth) self.monitored = set() self.restore_monitored()
def go(): # get random city city = Geo().get_location() # get 4 images (urls) urls = Google().search(city) # save images image_names = ImageManager().save(urls) # tweet 'em TwitterAPI().compose(city, image_names) # clean image directory ImageManager().delete() # done print('Done.')
def request(self, url, payload=None, method=TwitterAPI.Requestor.GET, headers={}, follow_redirects=True, validate_certificate=None): """ Requests the given HTTP URL using Google AppEngine urlfetch """ response = urlfetch.fetch(url, payload=payload, method=method, headers=headers, follow_redirects=follow_redirects, validate_certificate=validate_certificate) return TwitterAPI.Response(data=response.content, status_code=response.status_code, headers=response.headers)
def __init__(self, consumer_key: str, consumer_secret: str, access_token_key: str, access_token_secret: str, model_filepath: str, cuda: bool = False, logger: Optional[Logger] = None): """コンストラクタ. Parameters ---------- consumer_key : str TwitterのConsumer Key consumer_secret : str TwitterのConsumer Secret access_token_key : str TwitterのAccess Token access_token_secret : str TwitterのAccess Token Secret model_filepath : str モデルファイルパス cuda : bool, default False CUDAの利用するか否かのフラグ(デフォルト:利用しない) logger : Optional[logging.Logger], default None ロガー """ self.twitter_api = TwitterAPI(consumer_key=consumer_key, consumer_secret=consumer_secret, access_token_key=access_token_key, access_token_secret=access_token_secret) self.logger = logger if logger else self.create_logger() self.model_filepath = model_filepath self.cuda = cuda self.gp_generator: Optional[GenerateGPText] = None self.steady_tweets = self.load_steady_tweets() self.tz = timezone(timedelta(hours=+9), 'Asia/Tokyo')
def run(): try: with TweetDatabase() as db: # Connect to Twitter API. api = TwitterAPI() # Get data. img_data = get_data(db) # Tweet it. api.tweet_image(img_data) logger.info('Tweeted %s', img_data) # Add record of tweet to database db.add(img_data) # Follow new followers api.follow_new() except Exception: logger.exception('Something went wrong.')
#!/usr/bin python # -*- coding: utf-8 -*- from twitter import TwitterAPI import time import sys from random import Random # TwitterAPIを利用するインスタンス取得 twitter = TwitterAPI() api = twitter.get_api() if (len(sys.argv) != 2): print "start bot" text = [] sleepMin = 2 # つぶやきのテキスト取得 postData = open('resource/postData.txt', 'r') for line in postData: text.append(line) # 一定時間ごとにつぶやき temp = text random = Random() id = 0 while(True): if(temp.count < 2): temp = text time.sleep(sleepMin * 60) # テキストデータの中からつぶやき post = random.choice(temp) twitter.update_status(post) temp.remove(post)
# -*- coding:utf-8 -*- from twitter import Api as TwitterAPI from config import APP_INFO API_LIST = [] API_COUNT = len(APP_INFO) for i in range(API_COUNT): API_LIST.append( TwitterAPI(consumer_key=APP_INFO[i]['consumer_key'], consumer_secret=APP_INFO[i]['consumer_secret'], access_token_key=APP_INFO[i]['access_token_key'], access_token_secret=APP_INFO[i]['access_token_secret'], cache=None)) class Api: def __init__(self): self.api_index = 0 ''' 获取 twitter app,每次调用返回一个新的 app ''' def get_api(self): api_index = self.api_index api_index = (api_index + 1) % API_COUNT self.api_index = api_index return API_LIST[api_index]
# Twitter instance @property def twitter_instance(self) -> TwitterAPI: return self._twitter_instance @twitter_instance.setter def twitter_instance(self, value: TwitterAPI): self._twitter_instance = value # Discord instance @property def discord_instance(self) -> DiscordBot: return self._discord_instance @discord_instance.setter def discord_instance(self, value: DiscordBot): self._discord_instance = value if __name__ == "__main__": controller = ParentController() discord_bot = DiscordBot(controller) controller.discord_instance = discord_bot twitter_api = TwitterAPI(controller) controller.twitter_instance = twitter_api # Run the bot last discord_bot.run_bot()
def authorize(request): """Get an unauth token and redirect user to Twitter's authorization URL.""" next = request.GET.get('next', None) if next: request.session['TWITTER_NEXT_URL'] = next try: tw = TwitterAPI() try: token = tw.get_unauthorised_request_token() except KeyError: # retry once tw.close() tw = TwitterAPI() token = tw.get_unauthorised_request_token() request.session['TWITTER_UNAUTH_TOKEN'] = token.to_string() auth_url = tw.get_authorisation_url(token) response = HttpResponseRedirect(auth_url) tw.close() return response except Exception, e: _log.exception(e) if request.user.is_authenticated(): add_message(request, u"We are unable to connect to Twitter at the moment. Please try again in a few minutes.") else: add_message(request, u"We are unable to connect to Twitter at the moment. Please continue signing up below. You will be able to connect your account to Twitter later from our homepage.") return _denied_response(request)
def callback(request): """This is where Twitter will redirect the user after this app has been authorized.""" try: unauthed_token = request.session.get('TWITTER_UNAUTH_TOKEN', None) oauth_verifier = request.GET.get('oauth_verifier', None) try: if unauthed_token: del request.session['TWITTER_UNAUTH_TOKEN'] except KeyError: pass if not unauthed_token: _log.debug("Unauthenticated token not found in session") return _denied_response(request) token = oauth.OAuthToken.from_string(unauthed_token) oauth_token = request.GET.get('oauth_token', None) if token.key != oauth_token: _log.debug("Tokens did not match %s - %s", token.key, oauth_token) return _denied_response(request) tw = TwitterAPI() try: access_token = tw.exchange_request_token_for_access_token(token, oauth_verifier) except KeyError: tw.close() return _denied_response(request) twitter_profile = tw.get_profile(access_token) tw.close() if twitter_profile: _log.debug("Twitter profile downloaded:\n%s", twitter_profile) try: p = simplejson.loads(twitter_profile) except Exception, e: # try one more time try: tw = TwitterAPI() twitter_profile = tw.get_profile(access_token) tw.close() _log.debug("Twitter profile downloaded on retry:\n%s", twitter_profile) if not twitter_profile: raise Exception("OAuth error: retry failed on get_profile") p = simplejson.loads(twitter_profile) except Exception, e: _log.warn("Twitter profile could not be JSON decoded.\n%s", twitter_profile) _log.exception(e) add_message(request, u"We are unable to connect to Twitter at the moment. Please try again in a few minutes.") return _denied_response(request) _log.debug(p) screen_name = p.get('screen_name') full_name = p.get('name', p['screen_name']) # Split full_name into first name and last name x = full_name.split(' ', 1) first_name, last_name = u'', u'' if len(x) > 1: first_name, last_name = x[0], x[1] elif len(x) == 1: first_name, last_name = u'', x[0] profile_image = p.get('profile_image_url', '') if '/images/default_profile' in profile_image: profile_image = '' profile = dict( profile_type=u'twitter', screen_name=screen_name, first_name=first_name, last_name=last_name, appuser_id=p['id'], profile_image_url=profile_image, access_token=access_token.to_string() ) if request.user.is_authenticated(): user = request.user p = save_open_profile(user, profile) add_message(request, u"You've connected your Twitter account successfully.") # user.message_set.create(message=_(u"Thank you for authorizing us to update your Twitter status!")) else: request.session['OPEN_PROFILE'] = profile
""" response = urlfetch.fetch(url, payload=payload, method=method, headers=headers, follow_redirects=follow_redirects, validate_certificate=validate_certificate) return TwitterAPI.Response(data=response.content, status_code=response.status_code, headers=response.headers) twitter_api = TwitterAPI(options={ 'consumer_key': twitter_credentials.API_KEY, 'consumer_secret': twitter_credentials.API_SECRET }, requestor=URLFetchRequestor()) def load_locations(): allQuery = Location.query() locations = [] for location in allQuery.iter(): locations.append(location.to_dict()) return locations def update_locations():