def index(request):
	if request.method == 'POST':
		print request.POST
	logged_users = []
	if request.user.username and request.user.profile.is_chat_user:
		auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
		auth.set_access_token(request.session.get('key'), request.session.get('secret'))
		api = tweepy.API(auth_handler=auth)
		#print request.user.username
		u = api.get_user(request.user.username)
		logged_users=u.screen_name
		context = {'logged_users':logged_users}
		return render(request, 'index.html', context)
	else:
		'''
		Twitter OAuth Authenticate
		'''
		auth_tw = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET, CALLBACK_URL)
		try:
			auth_url = auth_tw.get_authorization_url()
		except tweepy.TweepError:
			print 'Error! Failed to get request token. You have to access network'
			return HttpResponseRedirect(reverse('index'))
		request.session['request_token'] = auth_tw.request_token
		request.session.save()
		return HttpResponseRedirect(auth_url)
Beispiel #2
0
def index(request):
    if request.method == 'POST':
        print request.POST
    logged_users = []
    if request.user.username and request.user.profile.is_chat_user:
        auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
        auth.set_access_token(request.session.get('key'),
                              request.session.get('secret'))
        api = tweepy.API(auth_handler=auth)
        #print request.user.username
        u = api.get_user(request.user.username)
        logged_users = u.screen_name
        context = {'logged_users': logged_users}
        return render(request, 'index.html', context)
    else:
        '''
		Twitter OAuth Authenticate
		'''
        auth_tw = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET,
                                      CALLBACK_URL)
        try:
            auth_url = auth_tw.get_authorization_url()
        except tweepy.TweepError:
            print 'Error! Failed to get request token. You have to access network'
            return HttpResponseRedirect(reverse('index'))
        request.session['request_token'] = auth_tw.request_token
        request.session.save()
        return HttpResponseRedirect(auth_url)
Beispiel #3
0
def reply_tweet(request, user, tweet_id, tweet_text, screen_name, area,
                keyword):  #replies a tweet.
    location = User.objects.filter(pk=user).get().settings.first()
    hitarea = Locations.objects.filter(twittername=area).get()
    keyword = Keywords.objects.filter(name=keyword).get()
    AreaHit.gethit(
        hitarea, location
    )  #keep hit values for further recommendations to other new users.
    KeywordHit.gethit(
        keyword, location
    )  #keep hit values for further recommendations to other new users.
    instance = UserSocialAuth.objects.filter(user=user).get()
    oauth_access_token = (instance.access_token).get('oauth_token')
    oauth_access_secret = (instance.access_token).get('oauth_token_secret')
    auth.set_access_token(oauth_access_token, oauth_access_secret)
    api = tweepy.API(auth)
    try:
        id = api.update_status('@' + screen_name + ' ' + tweet_text, tweet_id)
        reply = Reply(
            tweet_id=Tweet.objects.filter(tweet_id=tweet_id).get().pk,
            reply_id=id.id,
            user=User.objects.get(pk=user))
        reply.save()
        messages.info(request, 'Your reply is successfully tweeted')
    except:
        messages.warning(
            request,
            'Something is wrong about your twitter credentials. Try Logging on again'
        )
def chat_api(request):
	if request.method == 'POST':
		###Oauth system:userid for username
		auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
		auth.set_access_token(request.session.get('key'), request.session.get('secret'))
		api = tweepy.API(auth_handler=auth)
		##makes json
		d = json.loads(request.body)
		msg =  d.get('msg')
		if len(msg) > 120:
			print "error to much word"
			return 0
		u = api.get_user(request.user.username)
		user= u.screen_name
		gravatar = request.user.profile.gravatar_url
		m = Message(user=user,message=msg,gravatar=gravatar)
		m.save()
		res = {'id':m.id,'msg':m.message,'user':m.user,'time':m.time.strftime('%I:%M:%S %p').lstrip('0'),'gravatar':m.gravatar}
		data = json.dumps(res)
		try:
			auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
			auth.set_access_token(request.session.get('key'), request.session.get('secret'))
			api = tweepy.API(auth_handler=auth)
			""" test get tweet"""
			api.update_status(status=m.message+" "+"#test")
			#count=count+1
		except tweepy.TweepError,e:
			p = re.compile('^\[{u\'message\': u\'(.+)\', u\'code\': (\d+)}\]$')
			m = p.match(e.reason)
			if m:
				message =  m.group(1)
				code = m.group(2)
		return HttpResponse(data,content_type="application/json")
Beispiel #5
0
def uploadImage(request):
    auth = OAuthHandler(ckey,csecret)
    auth.set_access_token(atoken,asecret)
    api = tweepy.API(auth)
    status = "testing"
    fn = os.path.abspath('/home/niks/Desktop/download.jpg')
    api.update_with_media(fn,status)
    return HttpResponse('Done')
Beispiel #6
0
def tweet_kill(request, user, id):  #Deletes a reply.
    instance = UserSocialAuth.objects.filter(user=user).get()
    oauth_access_token = (instance.access_token).get('oauth_token')
    oauth_access_secret = (instance.access_token).get('oauth_token_secret')
    auth.set_access_token(oauth_access_token, oauth_access_secret)
    api = tweepy.API(auth)
    api.destroy_status(id)
    Reply.objects.filter(reply_id=id).delete()
    messages.info(request, 'Your reply is successfully deleted')
Beispiel #7
0
def chat_api(request):
    if request.method == 'POST':
        ###Oauth system:userid for username
        auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
        auth.set_access_token(request.session.get('key'),
                              request.session.get('secret'))
        api = tweepy.API(auth_handler=auth)
        ###Update user
        if request.user.username:
            u = request.user.profile
            u.last_accessed = utcnow()
            u.is_chat_user = True
            u.save()
        ###Makes json
        #d = json.loads(request.body)
        msg = request.POST['msg']
        #msg =  d.get('msg')
        if len(msg) > 120:
            print "error to much word"
            return 0
        ######################################
        #形態素解析による不明なコメント除去
        ######################################
        word = msg
        node = tagger.parseToNode(word.encode('utf-8'))
        while (node):
            if node.feature.split(",")[0] == "名詞" or node.feature.split(
                    ",")[0] == "動詞":
                for checks in find:
                    if node.surface == checks:
                        #print "Bad Word",node.surface
                        return 0
            node = node.next
        ######################################
        u = api.get_user(request.user.username)
        user = u.screen_name
        #print 'user',user
        m = Message(user=user, message=msg)
        m.save()
        #res = {'id':m.id,'msg':m.message,'user':m.user,'time':m.time.strftime('%I:%M:%S %p').lstrip('0')}
        #data = json.dumps(res)
        try:
            auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
            auth.set_access_token(request.session.get('key'),
                                  request.session.get('secret'))
            api = tweepy.API(auth_handler=auth)
            """ test get tweet"""
            api.update_status(status=m.message + " " + "#spicetest")
            #count=count+1
        except tweepy.TweepError, e:
            p = re.compile('^\[{u\'message\': u\'(.+)\', u\'code\': (\d+)}\]$')
            m = p.match(e.reason)
            if m:
                message = m.group(1)
                code = m.group(2)
        #return HttpResponse(data,content_type="application/json")
        return HttpResponse("Sended")
Beispiel #8
0
def resident(
    username, town, user
):  #returns true if a user follows the districts mayor's office twitter account. We use this to filter tweets that have the desired keywords.
    instance = UserSocialAuth.objects.filter(user=user).get()
    oauth_access_token = (instance.access_token).get('oauth_token')
    oauth_access_secret = (instance.access_token).get('oauth_token_secret')
    auth.set_access_token(oauth_access_token, oauth_access_secret)
    api = tweepy.API(auth)
    return api.show_friendship(source_screen_name=username,
                               target_screen_name=town)[0].following
def chat_api(request):
	if request.method == 'POST':
		###Oauth system:userid for username
		auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
		auth.set_access_token(request.session.get('key'), request.session.get('secret'))
		api = tweepy.API(auth_handler=auth)
		###Update user
		if request.user.username:
			u = request.user.profile
			u.last_accessed = utcnow()
			u.is_chat_user = True
			u.save()
		###Makes json
		#d = json.loads(request.body)
		msg = request.POST['msg'] 
		#msg =  d.get('msg')
		if len(msg) > 120:
			print "error to much word"
			return 0
		######################################
		#形態素解析による不明なコメント除去
		######################################
		word=msg
		node = tagger.parseToNode(word.encode('utf-8'))
		while(node):
			if node.feature.split(",")[0] == "名詞" or node.feature.split(",")[0] == "動詞":
				for checks in find:
					if node.surface == checks:
						#print "Bad Word",node.surface
						return 0;
			node = node.next
		######################################
		u = api.get_user(request.user.username)
		user= u.screen_name
		#print 'user',user
		m = Message(user=user,message=msg)
		m.save()
		#res = {'id':m.id,'msg':m.message,'user':m.user,'time':m.time.strftime('%I:%M:%S %p').lstrip('0')}
		#data = json.dumps(res)
		try:
			auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
			auth.set_access_token(request.session.get('key'), request.session.get('secret'))
			api = tweepy.API(auth_handler=auth)
			""" test get tweet"""
			api.update_status(status=m.message+" "+"#spicetest")
			#count=count+1
		except tweepy.TweepError,e:
			p = re.compile('^\[{u\'message\': u\'(.+)\', u\'code\': (\d+)}\]$')
			m = p.match(e.reason)
			if m:
				message =  m.group(1)
				code = m.group(2)
		#return HttpResponse(data,content_type="application/json")
		return HttpResponse("Sended")
Beispiel #10
0
def testView2(request):
    auth = OAuthHandler(ckey,csecret)
    auth.set_access_token(atoken,asecret)
    #twitterStream = Stream(auth,listener())
    #print twitterStream.filter(track=["car"])
    #text = twitterStream.filter(track=["car"])
    api = tweepy.API(auth)
    value = tweepy.Cursor(api.friends).items()
    value = value.next()
    print type(value)
    #value='hello'
    return HttpResponse(value)
Beispiel #11
0
def _tweet(job):
    # get short url for the job
    long_url = "http://jobs.code4lib.org/job/%s/" % job.id
    bitly = bitlyapi.BitLy(settings.BITLY_USERNAME, settings.BITLY_PASSWORD)
    response = bitly.shorten(longUrl=long_url)
    url = response['url']

    # construct tweet message
    msg = job.title
    if job.employer:
        msg = msg + " at " + job.employer.name
    msg += ' ' + url

    # tweet it
    auth = tweepy.OAuthHandler(settings.CODE4LIB_TWITTER_OAUTH_CONSUMER_KEY,
                               settings.CODE4LIB_TWITTER_OAUTH_CONSUMER_SECRET)
    auth.set_access_token(settings.CODE4LIB_TWITTER_OAUTH_ACCESS_TOKEN_KEY,
                          settings.CODE4LIB_TWITTER_OAUTH_ACCESS_TOKEN_SECRET)

    twitter = tweepy.API(auth)
    twitter.update_status(msg)
Beispiel #12
0
def _tweet(job):
    # get short url for the job
    long_url = "http://jobs.code4lib.org/job/%s/" % job.id
    bitly = bitlyapi.BitLy(settings.BITLY_USERNAME, settings.BITLY_PASSWORD)
    response = bitly.shorten(longUrl=long_url)
    url = response["url"]

    # construct tweet message
    msg = job.title
    if job.employer:
        msg = msg + " at " + job.employer.name
    msg += " " + url

    # tweet it
    auth = tweepy.OAuthHandler(
        settings.CODE4LIB_TWITTER_OAUTH_CONSUMER_KEY, settings.CODE4LIB_TWITTER_OAUTH_CONSUMER_SECRET
    )
    auth.set_access_token(
        settings.CODE4LIB_TWITTER_OAUTH_ACCESS_TOKEN_KEY, settings.CODE4LIB_TWITTER_OAUTH_ACCESS_TOKEN_SECRET
    )

    twitter = tweepy.API(auth)
    twitter.update_status(msg)
Beispiel #13
0
def generate_twitter_account_data(username):
    
    atoken='xxxxxxxxxxxxxxxx
    asecret='xxxxxxxxxxxxxxxxxxxxxx'
    auth=tweepy.OAuthHandler(TWITTER_CONSUMER_KEY,TWITTER_CONSUMER_SECRET)
    auth.set_access_token(atoken, asecret)
    api=tweepy.API(auth)

    user = api.get_user(username)
    followers = user.followers_count
    
    statuses = api.user_timeline(screen_name=username,count='10')
    
    total_reactions = 0
    
    for status in statuses:
        total_reactions = total_reactions + status.retweet_count + status.favorite_count

    averageReactions = (total_reactions/len(statuses))
    engagement = (float(averageReactions)/float(followers))*100
    
    userData = [followers,averageReactions,engagement]
        
    return userData
 def authenticate_twitter_app(self):
     auth = OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
     auth.set_access_token(ACCESS_TOKEN, ACCESS_TOKEN_SECRET)
     return auth