def search_twitter(search_term, geocode=None): twitter = Twython(ckey, csecret) if geocode: result_search = twitter.search(q=search_term, geocode=geocode) else: result_search = twitter.search(q=search_term) return result_search
def thanks(request, redirect_url=settings.LOGIN_REDIRECT_URL): # tokens obtained from Twitter oauth_token = request.session['request_token']['oauth_token'] oauth_token_secret = request.session['request_token']['oauth_token_secret'] twitter = Twython(settings.TWITTER_KEY, settings.TWITTER_SECRET, oauth_token, oauth_token_secret) # retrieving tokens authorized_tokens = twitter.get_authorized_tokens(request.GET['oauth_verifier']) # if tokens already exist, use them to login and redirect to the battle try: user = User.objects.get(username=authorized_tokens['screen_name']) user.set_password(authorized_tokens['oauth_token_secret']) user.save() except User.DoesNotExist: # mock a creation here; no email, password is just the token, etc. since no need for users in this app user = User.objects.create_user(authorized_tokens['screen_name'], "*****@*****.**", authorized_tokens['oauth_token_secret']) profile = TwitterProfile() profile.user = user profile.oauth_token = authorized_tokens['oauth_token'] profile.oauth_secret = authorized_tokens['oauth_token_secret'] profile.save() user = authenticate( username=authorized_tokens['screen_name'], password=authorized_tokens['oauth_token_secret'] ) login(request, user) return HttpResponseRedirect(redirect_url)
def auth(request, num="1"): log = ["auth1"] OAUTH_VERIFIER = request.GET['oauth_verifier'] twitter = Twython( settings.TWITTER_CONSUMER_KEY, settings.TWITTER_CONSUMER_SECRET, request.session['OAUTH_TOKEN'], request.session['OAUTH_TOKEN_SECRET'] ) final_step = twitter.get_authorized_tokens(OAUTH_VERIFIER) OAUTH_TOKEN = final_step['oauth_token'] OAUTH_TOKEN_SECERT = final_step['oauth_token_secret'] request.session['OAUTH_TOKEN'] = OAUTH_TOKEN request.session['OAUTH_TOKEN_SECRET'] = OAUTH_TOKEN_SECERT request.session['new'] = True user, created = User.objects.get_or_create(oauth_token=OAUTH_TOKEN, oauth_token_secret=OAUTH_TOKEN_SECERT) request.session['userid'] = user.id if OAUTH_TOKEN: return HttpResponseRedirect("/view") return render_to_response('auth.html', {'log': log})
def tweet_tap_update(beer, previous_beer=None): twitter = Twython( TWITTER_CONSUMER_KEY, TWITTER_CONSUMER_SECRET, TWITTER_ACCESS_TOKEN, TWITTER_ACCESS_SECRET ) # tweet about the beer that used to be on tap if previous_beer: tweet = u'Blown keg at {0}: {1}, {2} from {3} in {4}, is gone'.format( previous_beer['location'].decode('utf-8'), previous_beer['name'].decode('utf-8'), INFLECTION.a(previous_beer['style'].decode('utf-8')), previous_beer['brewery'].decode('utf-8'), previous_beer['city'].decode('utf-8') ) tweet = check_tweet(tweet) if DRY_RUN: print 'Would Tweet: ' + tweet else: twitter.update_status(status=tweet) # tweet about the new beer on tap tweet = u'Now on tap at {0}: {1}, {2} from {3} in {4}'.format( beer['location'].decode('utf-8'), beer['name'].decode('utf-8'), INFLECTION.a(beer['style'].decode('utf-8')), beer['brewery'].decode('utf-8'), beer['city'].decode('utf-8') ) tweet = check_tweet(tweet) if DRY_RUN: print 'Would Tweet: ' + tweet else: twitter.update_status(status=tweet)
class Sufbot(object): def __init__(self, argDict=None): if not argDict: argDict = {"force": False, 'stream': False} # update this object's internal dict with the dict of args that was passed # in so we can access those values as attributes. self.__dict__.update(argDict) self.tweet = "" self.settings = defaultConfigDict s = self.settings self.twitter = Twython(s['appKey'], s['appSecret'], s['accessToken'], s['accessTokenSecret']) def SendTweets(self): ''' send each of the status updates that are collected in self.tweets ''' self.twitter.update_status(status=self.tweet) def Run(self): self.GetLyric() self.SendTweets() def GetLyric(self): sufjanList = sufbotLyrics.processArtist("http://www.lyricsmode.com/lyrics/s/sufjan_stevens/") charcount = 141 while charcount>140: # ensure tweet is 140 characters or less (twitter character limit) lyrics = sufbotLyrics.getRandomLyrics(sufjanList) charcount = 0 for l in lyrics: charcount+=len(l) tweet = "" for l in lyrics: tweet+=l+"\n" self.tweet = tweet
def __sendToTwitter(text): try: twitter = Twython(TWITTER_APP_KEY, TWITTER_APP_SECRET, TWITTER_OAUTH_TOKEN, TWITTER_OAUTH_TOKEN_SECRET) twitter.update_status(status=text) log.debug('Sent message to Twitter.') except: log.error('Twitter exception!')
def main(request, num="1"): tweets = ['1111','22222','3333'] template_name = 'main_view.html' if request.POST: tweets.append("Tweetout - " + settings.TWITTER_CONSUMER_KEY) twitter = Twython(settings.TWITTER_CONSUMER_KEY, settings.TWITTER_CONSUMER_SECRET) auth = twitter.get_authentication_tokens(callback_url=settings.TWITTER_CALLBACK_URL) #callback_url='' #Not final tokens, save in session later OAUTH_TOKEN = auth['oauth_token'] OAUTH_TOKEN_SECRET = auth['oauth_token_secret'] request.session['OAUTH_TOKEN'] = OAUTH_TOKEN request.session['OAUTH_TOKEN_SECRET'] = OAUTH_TOKEN_SECRET #redirect to this url URL = auth['auth_url'] print "********************" print OAUTH_TOKEN print OAUTH_TOKEN_SECRET if URL: return HttpResponseRedirect(URL) return render_to_response("main_view.html",{'tweets': tweets}, context_instance=RequestContext(request))
def user_timeline(request): """An example view with Twython/OAuth hooks/calls to fetch data about the user in question.""" user = request.user.twitterprofile twitter = Twython(settings.TWITTER_KEY, settings.TWITTER_SECRET, user.oauth_token, user.oauth_secret) user_tweets = twitter.get_home_timeline() return render_to_response('tweets.html', {'tweets': user_tweets})
def thanks(request, redirect_url=settings.LOGIN_REDIRECT_URL): """A user gets redirected here after hitting Twitter and authorizing your app to use their data. This is the view that stores the tokens you want for querying data. Pay attention to this. """ # Now that we've got the magic tokens back from Twitter, we need to exchange # for permanent ones and store them... oauth_token = request.session['request_token']['oauth_token'] oauth_token_secret = request.session['request_token']['oauth_token_secret'] twitter = Twython(settings.TWITTER_KEY, settings.TWITTER_SECRET, oauth_token, oauth_token_secret) # Retrieve the tokens we want... authorized_tokens = twitter.get_authorized_tokens(request.GET['oauth_verifier']) # If they already exist, grab them, login and redirect to a page displaying stuff. try: user = User.objects.get(username=authorized_tokens['screen_name']) except User.DoesNotExist: # We mock a creation here; no email, password is just the token, etc. user = User.objects.create_user(authorized_tokens['screen_name'], "*****@*****.**", authorized_tokens['oauth_token_secret']) profile = TwitterProfile() profile.user = user profile.oauth_token = authorized_tokens['oauth_token'] profile.oauth_secret = authorized_tokens['oauth_token_secret'] profile.save() user = authenticate( username=authorized_tokens['screen_name'], password=authorized_tokens['oauth_token_secret'] ) login(request, user) return HttpResponseRedirect(redirect_url)
def fetch_twitter_followers(self): twitter = Twython(APP_KEY_TWITTER, APP_SECRET_TWITTER, OAUTH_TOKEN_TWITTER, OAUTH_TOKEN_SECRET_TWITTER) twitter_obj = twitter.get_followers_ids() twitter_followers = len(twitter_obj['ids']) twitter_followers = '{:,}'.format(int(twitter_followers)) self.twitter = twitter_followers
def generate(request): context = RequestContext(request) if request.method == 'POST': form = BotTokenForm(request.POST) if form.is_valid(): global yellow yellow = Bot.objects.get(id=request.POST.get('user')) twitter = Twython(settings.API, settings.API_SECRET) # Request an authorization url to send the user to... callback_url = request.build_absolute_uri(reverse('grabber.views.thanks')) auth_props = twitter.get_authentication_tokens(callback_url) # Then send them over there, durh. request.session['request_token'] = auth_props return HttpResponseRedirect(auth_props['auth_url']) else: print form.errors else: form = BotTokenForm() return render_to_response('grabber/generate.html',{'form': form}, context)
def twitteradd(request, usertoadd): #usertoadd = User.get(username=uidtofollow) twitterauth = UserSocialAuth.objects.get(user=request.user, provider="twitter") if twitterauth is None: return False oauth_consumer_key = settings.SOCIAL_AUTH_TWITTER_KEY oauth_token = twitterauth.extra_data['access_token']['oauth_token'] #oauth_nonce = "91227c2566963d6ae01eb72f974e964a" oauth_nonce = "".join([random.choice(string.letters) for i in xrange(32)]) oauth_signature = "eGxVJXIYoG%2B9ay0A4E7QxnBHHrI%3D" #currenttime = "1381017251" currenttime = str(int(time.time())) #user_to_follow = "15378324" from twython import Twython twitter = Twython(settings.SOCIAL_AUTH_TWITTER_KEY, settings.SOCIAL_AUTH_TWITTER_SECRET, twitterauth.extra_data['access_token']['oauth_token'], twitterauth.extra_data['access_token']['oauth_token_secret']) try: useridtofollow = UserSocialAuth.objects.get(user=usertoadd, provider="twitter").extra_data['id'] except: return False try: twitter.create_friendship(user_id=useridtofollow) except: return False return True
def get(self): tweets = Tweet.query.order_by(Tweet.tweetId.asc()).limit(1).all() oldest = tweets[0] if len(tweets) > 0 else None twitter = Twython(s.CONSUMER_KEY, s.CONSUMER_SECRET, s.ACCESS_TOKEN, s.ACCESS_TOKEN_SECRET) data = [] try: if oldest: logging.info('\n\nOldest tweetId = {0}\n\n'.format(oldest.tweetId)) data = twitter.get_home_timeline(count=50, max_id=oldest.tweetId) else: data = twitter.get_home_timeline(count=200) except TwythonError as e: logging.error('{0}'.format(e)) else: logging.info(str(data)) for tweet in data: if len(tweet.get('entities').get('urls')) > 0: logging.info("\n\nFound urls!\n\n") process_link(tweet, s.USER_ID) else: logging.info("\n\nNo urls :(\n\n") return "OK"
def task(): APP_KEY = "lF79UQiDsP4kUSRlsg1cW3N9g" APP_SECRET = "0nIBU4KJcCXCfZKcWKkQZ8bUPcRpl2gc6kAkmDvc5Rq5998X3K" ACCESS_TOKEN = "737898701939716100-JaDquL9VV8O7i8OnVjQd6KSYrq98AtR" ACCESS_TOKEN_SECRET = "dgvNfhklbUac2MmWQwT3LHKPk04EJWUzJLSkEMQaZM2Aa" darkVarderLink = "https://www.youtube.com/watch?v=-bzWSJG93P8" eyeOfTigerLink = "https://www.youtube.com/watch?v=btPJPFnesV4" energyKey = [] zneKey = [] addressKey = [] differenceVal = [] twitter = Twython(APP_KEY, APP_SECRET, ACCESS_TOKEN, ACCESS_TOKEN_SECRET) #Get Winner and update according Flag jsonData = '[{"energy_sum_week":0,"zne_sum_week":90,"address":"215"},{"energy_sum_week":0,"zne_sum_week":90,"address":"1590"},{"energy_sum_week":10,"zne_sum_week":90,"address":"1605"},{"energy_sum_week":130,"zne_sum_week":90,"address":"1715"}]' jdata = json.loads(jsonData) for d in jdata: for key, value in d.iteritems(): if(key == "energy_sum_week"): energyKey.append(value) elif(key == "zne_sum_week"): zneKey.append(value) else: addressKey.append(value) for x in range(len(energyKey)): differenceVal.append(zneKey[x] - energyKey[x]) winnerIndex = differenceVal.index(max(differenceVal)) winnerAddress = addressKey[winnerIndex]; twitter.update_status(status='The winner is ' + winnerAddress +' Street\n' + eyeOfTigerLink)
def twitter_search(twitter_id, index = 0): APP_KEY = APP_KEYS[index] APP_SECRET = APP_SECRETS[index] OAUTH_TOKEN = OAUTH_TOKENS[index] OAUTH_TOKEN_SECRET = OAUTH_TOKEN_SECRETS[index] twitter = Twython (APP_KEY, APP_SECRET) auth = twitter.get_authentication_tokens() #OAUTH_TOKEN = auth['oauth_token'] #OAUTH_TOKEN_SECRET = auth['oauth_token_secret'] #print OAUTH_TOKEN twitter = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET) #ACCESS_TOKEN = twitter.obtain_access_token() #print twitter.verify_credentials() #ACCESS_TOKEN = '701759705421639681-nutlNGruF7WZjq0kXZUTcKVbrnXs3vD' #twitter = Twython(APP_KEY, access_token = ACCESS_TOKEN) response = twitter.get_user_timeline(screen_name = twitter_id) # gets 20 results, by default L = [] for r in response: d = {} d['text'] = r['text'] d['screenname'] = r['user']['screen_name'] d['date'] = r['created_at'] L.append(d) return L
class TweetThread(threading.Thread): def __init__(self,message): super(TweetThread,self).__init__() self.message = message self.twitter = Twython( #consumer key "fF86BdSdopE9FAES5UNgPw", #consumer secret "n7G4K80kYQ6NDMQiYn3GY5Hyk82fF2So17Nl1UQdGWE", #access_token "1336977176-4CgpPJnJBx7kCRqnwLcRbXI3nLpHj44sp3r2bXy", #access_token_secret "5rLNvZm3JZdkx0K1Jx9jgsqMG6MmGLAQmPdJ7ChtzA", ) def run(self): #send a picture tweet print("sending a tweet with an image...") photo = open('mugshot.jpg', 'rb') try: self.twitter.update_status_with_media(media=photo, status=self.message) print("sent") except: print("twython problem")
def get_tweets(keyword): keys = dict() keys['ConsumerKey'] = 'dPVleyBRcgwvg8avQuCb0Emyo' keys['ConsumerSecret'] = '9u2DgDBW3vMBww2lMvEuqPN1JrTkwoVbY6pCgeR1FwU9hLmXbE' keys['AccessToken'] = '915677970-L73XsdyABhajS0O7jya2OT2hhcJxps4lBJN27m8C' keys['AccessTokenSecret'] = 'pDPXHRmSOJ9HwCUaadCpzALiBTsEOaFXWF4crbsjK0ial' acctDict = keys #get_api_keys() twitter = Twython(acctDict['ConsumerKey'], acctDict['ConsumerSecret'], acctDict['AccessToken'], acctDict['AccessTokenSecret']) response = twitter.search(q=keyword, result_type='recent') itemsList = list() for tweet in response['statuses']: hashtgs = list() price = re.search(r'\$\S*', tweet['text']) if price is None: price ='OFFER' else: price = price.group(0) tweet['text'] = tweet['text'].replace(price, '') #remove price for hashtag in tweet['entities']['hashtags']: hashtgs.append(hashtag['text']) tweet['text'] = tweet['text'].replace('#'+hashtag['text'], '') #remove hashtags temp = {'user_handle': tweet['user']['screen_name'], 'user_photo': tweet['user']['profile_image_url'], 'url':'https://twitter.com/statuses/'+ tweet['id_str'], \ 'content': tweet['text'].encode('utf-8'), 'price': price, 'hashtags': hashtgs, 'time': tweet['created_at'] } itemsList.append(temp) #print tweet['user']['screen_name'], tweet['user']['profile_image_url'], tweet['text'].encode('utf-8'), 'https://twitter.com/statuses/'+ tweet['id_str'] return itemsList
def run(self): pp = pprint.PrettyPrinter(depth=6) api = Twython(app_key=options.consumer_key, app_secret=options.consumer_secret, oauth_token=options.access_token_key, oauth_token_secret=options.access_token_secret) #do_simulate = True do_simulate = False current_user = { 'id_str' : '1041065317' } if not do_simulate: current_user = api.verifyCredentials() pp.pprint(current_user) fortuneComposer = FortuneComposer() followController = follow.FollowController([ follow.FollowComposer(current_user) ], current_user=current_user) retweetController = retweet.RetweetController([ retweet.RetweetComposer() ], current_user=current_user) replyController = reply.ReplyController([ fortuneComposer ], current_user=current_user) postController = post.PostController([ fortuneComposer ], current_user=current_user) default_time_to_sleep = 1 if do_simulate: default_time_to_sleep = 1 user_stream = stream.Stream(api, { 'endpoint' : 'https://userstream.twitter.com/1.1/user.json', 'track' : 'bucketobytes' }, [ followController, retweetController, replyController, postController ], default_time_to_sleep, do_simulate) user_stream.connectStream()
def RT(ID, name): """Function that actually retweets tweet""" """Takes a ID and username parameter""" """Once tweeted log is updated in overall and to date tweetlog""" config = config_create() print("RT") #Tid = int(float(ID)) Tweetusername = config.get('Auth', 'botname') #TweetText = 'https://twitter.com/'+Tweetusername+'/status/'+ID #ReTweet = 'Hi I am ComicTweetBot!('+tim+') I Retweet Comics! Use #comicretweetbot '+TweetText x2 = config.get('Latest_Log', 'currenttweetlog') x3 = config.get('Latest_Log', 'overalllog') CONSUMER_KEY = config.get('Auth', 'CONSUMER_KEY') CONSUMER_SECRET = config.get('Auth', 'CONSUMER_SECRET') ACCESS_KEY = config.get('Auth', 'ACCESS_KEY') ACCESS_SECRET = config.get('Auth', 'ACCESS_SECRET') api = Twython(CONSUMER_KEY, CONSUMER_SECRET, ACCESS_KEY, ACCESS_SECRET) tMax = int(float(config.get('Tweet_Delay', 'Max'))) tMin = int(float(config.get('Tweet_Delay', 'Min'))) tStep = int(float(config.get('Tweet_Delay', 'Step'))) Log = open(x2, 'w') enterlog = ID+' '+name+ '\n' Log.write(enterlog) Log2 = open(x3, 'w') Log2.write(ID+'\n') #api.update_status(status= ReTweet) api.retweet(id = ID) api.create_favorite(id=ID, include_entities = True) #randomize the time for sleep 1.5mins to 5 mins rant = random.randrange(tMin, tMax, tStep) time.sleep(rant)
def getDescriptions(credentials_list, users_data, directory): if len(users_data) is 0: print('Complete') return for credential in credentials_list: users = users_data[0:100] credentials = Twython(app_key=credential[0], app_secret=credential[1], oauth_token=credential[2], oauth_token_secret=credential[3], oauth_version=1) data = credentials.lookup_user(screen_name = users) for dat in data: profile = dat handle = str(profile['id']) time_zone = str(profile['time_zone']) screen_name = profile['screen_name'] #utc_offset = profile['utc_offset'] description = profile['description'].replace("\t", " ") with codecs.open(directory[:-4] + "_IDs.csv", 'a', encoding='utf-8') as out: out.write(u''+ screen_name + '\t' + handle +'\n') users_data = users_data[101:] getDescriptions(credentials_list, users_data, directory)
class TwitterPublisher(publisher.PublisherBase): def __init__(self, parsed_url): super(TwitterPublisher, self).__init__(parsed_url) self.twitter = Twython("xIpbyvwmQK4YMwXaO2z9NR2NV", "fOFKEl0U64f7no8JDoEZZZZvesgWcHDC5Y0c2EKiVTAWBeRat0", "781505281377218560-tWW00zVr7RN9YrCMQAfsC1djTPLwUhX", "EwPNbO62G1dfbVbNUbMQnfM0w2HpUx1K9T4kqClTCzo5J") def publish_samples(self, context, samples): """Send a metering message for publishing :param context: Execution context from the service or RPC call :param samples: Samples from pipeline after transformation """ if self.twitter: for sample in samples: d = sample.as_dict() event = d.get("resource_metadata", {}).get("event_type") status = d.get("resource_metadata", {}).get("status") timestamp = d.get("timestamp") id = d.get("resource_id") msg = "Event: %s status: %s timestamp: %s id: %s" % (event, status, timestamp, id) self.twitter.update_status(status=msg) def publish_events(self, context, events): """Send an event message for publishing :param context: Execution context from the service or RPC call :param events: events from pipeline after transformation """ raise ceilometer.NotImplementedError
def ajax_user_timeline(request): if not request.user.is_authenticated() or 'twitter_tokens' not in request.session: return HttpResponse("") results = {'success': 'False'} if request.method != u'GET': return HttpResponseBadRequest('Must be GET request') if not request.GET.has_key(u'screenname'): return HttpResponseBadRequest('screenname missing') if not request.GET.has_key(u'max_id'): return HttpResponseBadRequest('start id missing') if not request.GET.has_key(u'page'): return HttpResponseBadRequest('page number missing') screenname = request.GET[u'screenname'] max_id = request.GET[u'max_id'] page = request.GET[u'page'] if 'twitter_tokens' in request.session: twitter_tokens = request.session['twitter_tokens'] api = get_authorized_twython(twitter_tokens) else: # Get public api if no authentication possible api = Twython() results['statuses'] = api.getUserTimeline(screen_name=screenname, max_id=max_id, page=page) t = get_template('twitter/status_list.html') results['success'] = 'True' html = t.render(RequestContext(request, results)) return HttpResponse(html)
def perform_import(self, retrieval_param, course_code): # Setup Twitter API Keys app_key = os.environ.get("TWITTER_APP_KEY") app_secret = os.environ.get("TWITTER_APP_SECRET") oauth_token = os.environ.get("TWITTER_OAUTH_TOKEN") oauth_token_secret = os.environ.get("TWITTER_OAUTH_TOKEN_SECRET") twitter = Twython(app_key, app_secret, oauth_token, oauth_token_secret) count = 0 next_max_id = None results = None while True: try: if count==0: results = twitter.search(q=retrieval_param,count=100, result_type='mixed') else: results = twitter.search(q=retrieval_param,count=100,max_id=next_max_id, result_type='mixed') for tweet in results['statuses']: self.insert_tweet(tweet, course_code) if 'next_results' not in results['search_metadata']: break else: next_results_url_params = results['search_metadata']['next_results'] next_max_id = next_results_url_params.split('max_id=')[1].split('&')[0] count += 1 except KeyError: # When there are no more pages (['paging']['next']), break from the # loop and end the script. break
def clean_tweet(screen_name, clean_interval, clean_threshold, consumer_key, consumer_secret, access_key, access_secret): while True: try: twitter = Twython(consumer_key, consumer_secret, access_key, access_secret) my_statuses = twitter.get_user_timeline(screen_name=screen_name) # logging.debug(my_statuses) clean_base_datetime = (datetime.datetime.now() - datetime.timedelta(seconds=clean_threshold)) for status in my_statuses: status_id = status['id'] created_at = datetime.datetime.strptime(status['created_at'], '%a %b %d %H:%M:%S +0000 %Y') text = status['text'] # logging.debug("id:{} created_at:{} text:{}".format(status_id, created_at, text)) should_destroy = (created_at < clean_base_datetime) if should_destroy: logging.info("removing status:{} {} {}".format(status_id, created_at, text)) twitter.destroy_status(id=status_id) # logging.info("removed status") # raise Exception() except Exception as exception: logging.error("caught exception:{}".format(exception)) logging.debug("sleeping {} seconds...".format(clean_interval)) time.sleep(clean_interval)
def buscar_en_todos_los_tweets(busqueda, cantidad_de_tweets=50, partir_del_tweet=None): # llaves de la aplicacion APP_KEY = 'IR5sQyceHa34Cxxm2hAw' APP_SECRET = 'y5Nti0zdCFfzY1ifokC6iHIZFZ14Z2GAjTI6VFx2mg' # llaves del usuario OAUTH_TOKEN = '202826188-6OCQEmzi7JCu8S6UERP5nhjUo4NHirk0Kd4VRRvl' OAUTH_TOKEN_SECRET = '1wmkXUkqkDhBnbugzaNIzf07VKeCddjEPynVG2gayU' # requires authentication as of Twitter API v1.1 twitter = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET) try: search_results = twitter.search(q=busqueda, count=cantidad_de_tweets) print '===============', busqueda, '===============' except TwythonError as e: print e # imprimir en consola todos los tweets for tweet in search_results['statuses']: # print '%s.- Tweet from @%s Date: %s' % (tweet['id'], tweet['user']['screen_name'].encode('utf-8'), tweet['created_at']) # print tweet['text'].encode('utf-8'), '\n' # print "llaves: ", tweet.keys() # imprimir las llaves print "id: ", tweet['id_str'], "reply: ", tweet['in_reply_to_user_id_str'], "retweeted: ", tweet['retweet_count']
class Tester(object): def __init__(self): try: with open('config.yaml', 'r') as fptr: configs = yaml.load(fptr.read()) c_key = configs['Twython']['consumer']['key'] c_secret = configs['Twython']['consumer']['secret'] a_key = configs['Twython']['access']['key'] a_secret = configs['Twython']['access']['secret'] self.location = configs['location'] self.sleep = configs['timer'] # assuming seconds for now except: raise ConfigError self.twitter = Twython(c_key, c_secret, a_key, a_secret) self.msg_format = 'Hey @Comcast, why is my internet speed {} in {}? @ComcastCares @xfinity #comcast #speedtest' self.quality = SpeedQuality() def run(self): while True: complain = self.quality.judge() if complain: msg = self.msg_format.format(complain, self.location) print msg print 'len(msg): {}'.format(len(msg)) self.twitter.update_status(status = msg) else: print 'Speeds are acceptable: {}'.format(self.quality.get_speeds()) sleep(self.sleep)
def callback(Rate_id): """ twitter로부터 callback url이 요청되었을때 최종인증을 한 후 트위터로 해당 사진과 커멘트를 전송한다. """ Log.info("callback oauth_token:" + request.args['oauth_token']); Log.info("callback oauth_verifier:" + request.args['oauth_verifier']); # oauth에서 twiter로 부터 넘겨받은 인증토큰을 세션으로 부터 가져온다. OAUTH_TOKEN = session['OAUTH_TOKEN'] OAUTH_TOKEN_SECRET = session['OAUTH_TOKEN_SECRET'] oauth_verifier = request.args['oauth_verifier'] try: # 임시로 받은 인증토큰을 이용하여 twitter 객체를 만들고 인증토큰을 검증한다. twitter = Twython(current_app.config['TWIT_APP_KEY'], current_app.config['TWIT_APP_SECRET'], OAUTH_TOKEN, OAUTH_TOKEN_SECRET) final_step = twitter.get_authorized_tokens(oauth_verifier) # oauth_verifier를 통해 얻은 최종 인증토큰을 이용하여 twitter 객체를 새로 생성한다. twitter = Twython(current_app.config['TWIT_APP_KEY'], current_app.config['TWIT_APP_SECRET'], final_step['oauth_token'], final_step['oauth_token_secret']) session['TWITTER'] = twitter # 파라미터로 받은 Rate_id를 이용하여 해당 사진과 커멘트를 트위터로 전송한다. __send_twit(twitter, Rate_id) except TwythonError as e: Log.error("callback(): TwythonError , "+ str(e)) session['TWITTER_RESULT'] = str(e) return redirect(url_for('.show_all'))
def __oauth(Rate_id): """ twitter로부터 인증토큰을 받기 위한 함수 """ try: twitter = Twython(current_app.config['TWIT_APP_KEY'], current_app.config['TWIT_APP_SECRET']) callback_svr = current_app.config['TWIT_CALLBACK_SERVER'] auth = twitter.get_authentication_tokens( callback_url= callback_svr + \ url_for('.callback', Rate_id=Rate_id)) # 중간단계로 받은 임시 인증토큰은 최종인증을 위해 필요하므로 세션에 저장한다. session['OAUTH_TOKEN'] = auth['oauth_token'] session['OAUTH_TOKEN_SECRET'] = auth['oauth_token_secret'] except TwythonError as e: Log.error("__oauth(): TwythonError , "+ str(e)) session['TWITTER_RESULT'] = str(e) return redirect(url_for('.show_all')) # 트위터의 사용자 권한 인증 URL로 페이지를 리다이렉트한다. return redirect(auth['auth_url'])
def update_twitter_data(self): twitter = Twython( TWITTER_CONSUMER_KEY, TWITTER_CONSUMER_SECRET, TWITTER_ACCESS_TOKEN, TWITTER_ACCESS_SECRET ) # get the data from Twitter API twitter_data = twitter.lookup_status(id=','.join(self.tweet_ids())) # so ugly for tweet_data in twitter_data: tweet_data_id = str(tweet_data['id']) tweet_data_media = tweet_data.get('entities').get('media') tweet_data_photo = tweet_data_media[0].get('media_url_https') if len(tweet_data_media) else None tweet_data_text = tweet_data.get('text') tweet_data_text = strip_tweet_text(tweet_data_text) if self.tweet1.endswith(tweet_data_id): if not self.tweet1_photo: self.tweet1_photo = tweet_data_photo if not self.tweet1_text: self.tweet1_text = tweet_data_text if self.tweet2.endswith(tweet_data_id): if not self.tweet2_photo: self.tweet2_photo = tweet_data_photo if not self.tweet2_text: self.tweet2_text = tweet_data_text if self.tweet3.endswith(tweet_data_id): if not self.tweet3_photo: self.tweet3_photo = tweet_data_photo if not self.tweet3_text: self.tweet3_text = tweet_data_text if self.tweet4.endswith(tweet_data_id): if not self.tweet4_photo: self.tweet4_photo = tweet_data_photo if not self.tweet4_text: self.tweet4_text = tweet_data_text if self.tweet5.endswith(tweet_data_id): if not self.tweet5_photo: self.tweet5_photo = tweet_data_photo if not self.tweet5_text: self.tweet5_text = tweet_data_text
def __init__(self,text='',image=False,file_photo='/var/www/foto.jpg'): CONSUMER_KEY = 'TPcId3ZdR7jCYwec1A' CONSUMER_SECRET = '5eY3k8mEpHI0wCD2LSFK4y2b4zlMunbfc9zpEjdNU' ACCESS_KEY = '2273997643-dqvuxb4B2oOm2bFE0TKKMjXzt7vfCF7DZgy1HcW' ACCESS_SECRET = 'W9LcdB5qRh2dvWjbzR0C366nYQRPZq8f5RTOdvCZKuxFq' if(rpi_device): api = Twython(CONSUMER_KEY,CONSUMER_SECRET,ACCESS_KEY,ACCESS_SECRET) if(text==''): date = datetime.datetime.now() text = date.strftime('%d %b %Y %I:%M') if(image): photo = open(file_photo,'rb') try: api.update_status_with_media(media=photo, status=text) except TwythonError as e: logging.error(e) else : try: api.update_status_with_media(status=text) except TwythonError as e: logging.error(e) logging.info('Tweet sent') else : logging.error('Twython lib not found')
requests.get('https://cronitor.link/{}/run'.format(cv.cronitor_hash), timeout=10) logging.basicConfig(filename=cv.log_dir + cv.log_filename, format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO) # we're using randint() here to prevent Twitter deleting tweets it feels are duplicates # Twython APP_KEY = cv.APPKEY APP_SECRET = cv.APPSECRET OAUTH_TOKEN = cv.ACCESSTOKEN OAUTH_TOKEN_SECRET = cv.ACCESSTOKENSECRET twitter = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET) logging.info('----------------------------') logging.info('Initiated FeedGoo routine for {}'.format( datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S %Z%z"))) GPIO.setmode(GPIO.BCM) GPIO.setup(cv.servo_pin, GPIO.OUT) GPIO.setup(cv.buzz_pin, GPIO.OUT) GPIO.setup(cv.butt_switch_pin, GPIO.IN) GPIO.setup(cv.butt_led_pin, GPIO.OUT) GPIO.output(cv.buzz_pin, False) GPIO.output(cv.butt_led_pin, False)
from twython import Twython ConsumerKey = "..." ConsumerSecret = "..." AccessToken = "..." AccessTokenSecret = "..." twitter = Twython(ConsumerKey, ConsumerSecret, AccessToken, AccessTokenSecret) followers = twitter.get_followers_list(screen_name="hmcuesta") for follower in followers["users"]: print(" user: {0} \n name: {1} \n Number of tweets: {2} ".format( follower["screen_name"], follower["name"], follower["statuses_count"]))
from twython import Twython from auth import (consumer_key, consumer_secret, access_token, access_token_secret) import subprocess class MyStreamer(TwythonStreamer, Twython): subprocess = __import__('subprocess') def on_success(self, data): if 'text' in data: username = data['user']['screen_name'] tweet = data['text'] ln = subprocess.Popen(["lncli", "addinvoice", "21000"], stdout=subprocess.PIPE) pay_req_deet = ln.communicate()[0] pr = pay_req_deet.split() twitter.update_status( status="@{} pay deets: {}".format(username, pr[4])) stream = MyStreamer(consumer_key, consumer_secret, access_token, access_token_secret) twitter = Twython(consumer_key, consumer_secret, access_token, access_token_secret) MyStreamer.subprocess stream.statuses.filter(track='#stacksonscotty')
import sys import random import threading import os import LCD_functions from random import randint from threading import Thread from twython import Twython from datetime import datetime #twitter credentials apiKey = 'xxxxxxxxxxxxxxxxxxxxxxxxxx' apiSecret = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' accessToken = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' accessTokenSecret = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' api = Twython(apiKey, apiSecret, accessToken, accessTokenSecret) #initialize gpio pins for buttons and leds GPIO.setmode(GPIO.BOARD) GPIO.setwarnings(False) GPIO.setup(32, GPIO.IN) #setup for removetwitter button GPIO.setup(38, GPIO.IN) #setup for inserttwitter button GPIO.setup(36, GPIO.IN) #setup for shutdown button pins = [11, 12, 13, 15, 16, 18, 22, 7] for pin in pins: GPIO.setup(pin, GPIO.OUT) # Set all pins' mode to output GPIO.output(pin, GPIO.HIGH) # Set all pins to high(+3.3V) to off led #initialize of tweetbutton presses
credentials[ 'CONSUMER_SECRET'] = 'VgMggXa5lynttR4q88zbK3YVGhrc9VX0tpAiQrDL4ZUBf4AKey' credentials[ 'ACCESS_TOKEN'] = '1148727050628263941-GJUJIjUrQ69mjOddkxY09pHiH8dfU4' credentials['ACCESS_SECRET'] = 'lBWT5wb2y0u3f9LzzalUDcSQsu0VwIaFu8mObbHayQPkU' #Save the credentials object to file with open("twitter_credentials.json", "w") as file: json.dump(credentials, file) #Load credentials from json file with open("twitter_credentials.json", "r") as file: creds = json.load(file) #Instantiate an object python_tweets = Twython(creds['CONSUMER_KEY'], creds['CONSUMER_SECRET']) # Create our query query = { 'q': 'eagles', 'result_type': 'popular', 'count': 10, 'lang': 'en', } import pandas as pd # Search tweets dict_ = {'user': [], 'date': [], 'text': [], 'favorite_count': []} for status in python_tweets.search(**query)['statuses']: dict_['user'].append(status['user']['screen_name']) dict_['date'].append(status['created_at'])
def change_twitter_profile(): twitter = Twython(twitter_consumer_key, twitter_consumer_secret, twitter_access_key, twitter_access_secret) weather_user_name = f"{user_name} {get_weather_icon()}" twitter.update_profile(name=weather_user_name)
def __init__(self, app_key, app_secret, oauth_token, oauth_token_secret): self.handler = None self.do_continue = True Twython.__init__(self, app_key, app_secret, oauth_token, oauth_token_secret)
# Developer : Hamdy Abou El Anein # [email protected] # percentage of the year for the earth, the moon, jupiter, Saturn, etc... # Lunar Perigee and Apogee Calculator : https://www.fourmilab.ch/earthview/pacalc.html # Mercury and others : https://in-the-sky.org/newscalyear.php from datetime import date, datetime, timedelta import re import json from keys import * from twython import Twython twitter = Twython(consumer_key, consumer_secret, access_token, access_token_secret) class Percentage: def __init__(self): self.current_year self.today self.thisMonth self.EarthResult self.earthHTML self.BarrEarth self.BarrEarthHTML self.NewobjectPerihelion self.objectPerihelion self.objectResult self.objectHTML
def loginTwitter(): try: twitter = Twython('###','###','###','###') except: return False return twitter
#camera.brightness = 70 #initializes pygame and pygame font pygame.init() pygame.font.init() screen = pygame.display.set_mode((0, 0), pygame.FULLSCREEN) myfontsmall = pygame.font.Font( "/usr/share/fonts/truetype/LiberationSans-Regular.ttf", 30) myfont = pygame.font.Font( "/usr/share/fonts/truetype/LiberationSans-Regular.ttf", 144) infoObject = pygame.display.Info() #twitter app info apiKey = '' apiSecret = '' accessToken = '' accessTokenSecret = '' api = Twython(apiKey, apiSecret, accessToken, accessTokenSecret) #sets image name. only one image is saved and it is overwritten every time a picture is taken. IMG_NAME = "testImage.jpg" #method to take picture def takePicture(): for event in gamepad.read_loop(): if event.type == ecodes.EV_KEY: keyevent = categorize(event) if keyevent.keystate == KeyEvent.key_down: if keyevent.keycode == 'BTN_TR2': camera.start_preview(alpha=100) count = 5 while (count > -1): screen.fill(BLACK)
def parse_ids(season_id, game_id): ### pull common variables from the parameters file charts_teams = parameters.charts_teams files_root = parameters.files_root ### generate date and team information schedule_csv = files_root + season_id + "_schedule.csv" schedule_df = pd.read_csv(schedule_csv) schedule_date = schedule_df[(schedule_df['GAME_ID'] == int(game_id))] home = schedule_date['HOME'].item() away = schedule_date['AWAY'].item() ### establish common filepaths livefeed_file = files_root + 'livefeed.json' ### post charts to Twitter APP_KEY = twitter_credentials.APP_KEY APP_SECRET = twitter_credentials.APP_SECRET OAUTH_TOKEN = twitter_credentials.OAUTH_TOKEN OAUTH_TOKEN_SECRET = twitter_credentials.OAUTH_TOKEN_SECRET twitter = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET) shots_gameflow = open(charts_teams + 'shots_gameflow.png', 'rb') shots_gameflow_5v5 = open(charts_teams + 'shots_gameflow_5v5.png', 'rb') with open(livefeed_file) as livefeed_json: livefeed_data = json.load(livefeed_json) period = livefeed_data["liveData"]["linescore"]["currentPeriod"] status = livefeed_data["liveData"]["linescore"][ "currentPeriodTimeRemaining"] minutes_gone = int() seconds_gone = int() regulation_time_gone = str() ot_time_gone = str() try: time_left_split = status.split(':') regulation_minutes_gone = 20 - int(time_left_split[0]) ot_minutes_gone = 5 - int(time_left_split[0]) if int(time_left_split[1]) == 0 and int(time_left_split[1]) > 50: seconds_gone = 0 - int(time_left_split[0]) seconds_gone = '0' + str(seconds_gone) elif int(time_left_split[1]) != 0 and int(time_left_split[1]) > 50: seconds_gone = 60 - int(time_left_split[1]) seconds_gone = '0' + str(seconds_gone) regulation_time_gone = str(regulation_minutes_gone) + ':' + str( seconds_gone) ot_time_gone = str(ot_minutes_gone) + ':' + str(seconds_gone) except: pass images = [shots_gameflow, shots_gameflow_5v5] media_ids = [] for i in images: response = twitter.upload_media(media=i) media_ids.append(response['media_id_string']) if period == 1 and status != 'END': twitter.update_status(status=away + ' @ ' + home + ' gameflow through ' + regulation_time_gone + ' of the 1st Period:', media_ids=media_ids) elif period == 1 and status == 'END': twitter.update_status(status=away + ' @ ' + home + ' gameflow through the 1st Period:', media_ids=media_ids) if period == 2 and status != 'END': twitter.update_status(status=away + ' @ ' + home + ' gameflow through ' + regulation_time_gone + ' of the 2nd Period:', media_ids=media_ids) elif period == 2 and status == 'END': twitter.update_status(status=away + ' @ ' + home + ' gameflow through the 2nd Period:', media_ids=media_ids) if period == 3 and status != 'END' and status != 'Final': twitter.update_status(status=away + ' @ ' + home + ' gameflow through ' + regulation_time_gone + ' of the 3rd Period:', media_ids=media_ids) elif period == 3 and status == 'END': twitter.update_status(status=away + ' @ ' + home + ' gameflow through the 3rd Period:', media_ids=media_ids) elif period == 3 and status == 'Final': twitter.update_status(status=away + ' @ ' + home + ' gameflow (FINAL):', media_ids=media_ids) if period == 4 and status != 'END' and status != 'Final': twitter.update_status(status=away + ' @ ' + home + ' gameflow through ' + ot_time_gone + ' of Overtime:', media_ids=media_ids) elif period == 4 and status == 'END': twitter.update_status(status=away + ' @ ' + home + ' gameflow through Overtime:', media_ids=media_ids) elif period == 4 and status == 'Final': twitter.update_status(status=away + ' @ ' + home + ' gameflow (FINAL):', media_ids=media_ids) if period == 5 and status != 'Final': twitter.update_status(status=away + ' @ ' + home + ' unit 5v5 on-ice shots through Overtime:', media_ids=media_ids) elif period == 5 and status == 'Final': twitter.update_status(status=away + ' @ ' + home + ' unit 5v5 on-ice shots (FINAL):', media_ids=media_ids) print('Tweeted the gameflow by game state.')
self.id = id self.hashtags = hashtags self.bld = bld self.text = text self.user = user self.url = url self.geo = geo self.coordinates = coordinates self.place = place if __name__ == '__main__': ### Initialize Twython search tool ### mydb = mysql.connector.connect(host="name", user="******", passwd="password") mycursor = mydb.cursor() t = Twython(app_key="", app_secret="") ### Query keywords ### q_list = [ "NYCHA", "#NYCHA", "New York City Housing Authority", "New York public housing" ] for i in range(len(q_list)): q = q_list[i] results = t.search(q=q, count=100, tweet_mode='extended') all_tweets = results["statuses"] #nextToken = results["next"] ### FILTERING ### for tweet in all_tweets:
from twython import Twython import csv from collections import Counter CONSUMER_KEY = 'R2pWRXsbIvXqkHxljWC7muqf4' CONSUMER_SECRET = 'RIPuyuK8wdd81M23xDqxSWUiwcBaQO5q4TbkfiqIEAIq8T4x1C' ACCESS_TOKEN = '2806069908-UMVC9dsiI4gMqSBdDSKU1YiJ1fG8gOV0YY0dqCx' ACCESS_TOKEN_SECRET = 'F93y3Nn9wgaPG91iX1Gm3nPsy5jrZCa00dVIYkYabLK8I' twitter = Twython(CONSUMER_KEY, CONSUMER_SECRET, ACCESS_TOKEN, ACCESS_TOKEN_SECRET) from datetime import datetime created_at = '4/26/2017 10:52:29 PM' dt_obj = datetime.strptime(created_at, '%m/%d/%Y %I:%M:%S %p') dt_obj all_words = [] infinite_tweets = twitter.search(q='#InfiniteKusama', count=1000) yayoi_tweets = twitter.search(q='#YayoiKusama', count=1000) # setup containers for csvs inf_tweets = [] yay_tweets = [] with open('infinite.csv', 'w') as fp: a = csv.writer(fp) # add a header row a.writerow( ['Hashtag', 'id', 'screen_name', 'Tweet Text', 'URL', 'created_at'])
__copyrighta__ = "Copyright (C) Benjamin D. McGinnes, 2013-2015" __license__ = "BSD" __version__ = "0.0.1" __bitcoin__ = "1KvKMVnyYgLxU1HnLQmbWaMpDx3Dz15DVU" # import datetime import time import os import os.path import shutil import subprocess import sys from twython import Twython, TwythonError from config import * twitter = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET) cred = twitter.verify_credentials() ls = os.listdir op = os.path ow = os.walk s = subprocess tt = time.time pandoc = op.expanduser("~/Library/Haskell/bin/pandoc") # pandoc = "/usr/local/bin/pandoc" wkhtmltoimage = "/usr/local/bin/wkhtmltoimage" mfid = [] l = len(sys.argv)
from twython import Twython, TwythonAuthError, TwythonError, TwythonRateLimitError, TwythonStreamer from analyzer import analyze from chart import chart import timer from sentiment import sentiment #set up OAuth API_KEY = ' ' API_SECRET = ' ' OAUTH_TOKEN = ' ' OAUTH_TOKEN_SECRET = ' ' twitter = Twython(API_KEY, API_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET) #set up path to references negPath = 'negative-words.txt' posPath = 'positive-words.txt' #open references, read into lists negWords = open(negPath, 'r') posWords = open(posPath, 'r') negative = negWords.readlines() positive = posWords.readlines() #get rid of the "/n" for n in range(4783): #negative reference convertneg = "" convertneg = negative[n] convertneg = convertneg[:-1] negative[n] = convertneg
from twython import Twython, TwythonError import time import os ckey = os.environ.get("ckey") skey = os.environ.get("skey") access_token = os.environ.get("access_token") access_token_secret = os.environ.get("access_token_secret") twitter = Twython(ckey, skey, access_token, access_token_secret) try: with open('liners.txt', 'r+') as tweetfile: buff = tweetfile.readlines() for line in buff[:]: line = line.strip(r'\n') if len(line) <= 140 and len(line) > 0: print("Tweeting...") twitter.update_status(status=line) with open('liners.txt', 'w') as tweetfile: buff.remove(line) tweetfile.writelines(buff) time.sleep(900) else: with open('liners.txt', 'w') as tweetfile: buff.remove(line) tweetfile.writelines(buff) print("Skipped line - Char length violation") continue print("No more lines to tweet...")