本文整理汇总了Python中twython.Twython类的典型用法代码示例。如果您正苦于以下问题:Python Twython类的具体用法?Python Twython怎么用?Python Twython使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Twython类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: getDescriptions
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)
示例2: Sufbot
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
示例3: generate
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)
示例4: thanks
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'], "[email protected]", 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)
示例5: perform_import
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
示例6: get
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"
示例7: search_twitter
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
示例8: tweet_tap_update
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)
示例9: twitter_search
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
示例10: TweetThread
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")
示例11: run
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()
示例12: get_tweets
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
示例13: RT
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)
示例14: ajax_user_timeline
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)
示例15: __init__
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')