Exemplo n.º 1
0
    def post(self):
        data = {"status": "success", "error_message": ""}
        form = TweetCreateForm()

        if form.validate():
            try:
                print(session["user_id"])
                tweet = Tweets(
                    tweet_content=form.tweet_content.data,
                    user=session["user_id"],
                    tweet_date=datetime.now(),
                )
                tweet.save()

            except Exception as e:
                data["status"] = "error"
                data["error_message"] = _("Unknown error occured")
                print(e)
            finally:
                if data["status"] == "error":
                    data["error_message"] = render_template(
                        "errors/ajax_errors.html", form=form, data=data)
        else:
            data["status"] = "error"
            data["error_message"] = render_template("errors/ajax_errors.html",
                                                    form=form,
                                                    data=data)

        return jsonify(data)
Exemplo n.º 2
0
def get_twitter(user, twitter_name):
	print "entered twitter"

	# check if user exists
	if (Twitter_User.objects.filter(username = twitter_name).exists()):
		print "exists already"
		# increment the tweets that haven't been cached
		return HttpResponseRedirect('http://yahoo.com') 

	else:
		crawl_user = crawl_tt.twitter_user(twitter_name)

		twitter_user = Twitter_User(Id = user, username = twitter_name,
				twitter_id = crawl_user.user.id , location = crawl_user.user.location,
				description = crawl_user.user.description,
				followers = str(crawl_user.get_followers()),
				friends = str(crawl_user.get_friends())
				)
		twitter_user.save()
		print "saved twitter user"
		tweets = crawl_user.get_tweets()
		for tweet in tweets:
			add_tweet = Tweets(Id = user, created_at = tweet.created_at,
							text= tweet.text, coords = 'llala',
							hashtags = tweet.hashtags(),links=tweet.links())
			add_tweet.save()
		return ''	
Exemplo n.º 3
0
def collectTweets(p_noms):
    os.chdir('../sentimentClassifier')
    with open('savedNBClassifier.pkl', 'rb') as f:
        NBClassifier = pickle.load(f)
    auth = tweepy.OAuthHandler(twitter_creds.TWITTER_APP_KEY,
                               twitter_creds.TWITTER_APP_SECRET)
    auth.set_access_token(twitter_creds.TWITTER_KEY,
                          twitter_creds.TWITTER_SECRET)

    api = tweepy.API(auth)

    for nom in p_noms:
        results = api.search(q=nom, count=10)

        for (idx, tweet) in enumerate(results[0:10]):
            tweet_text = results[idx].text

            processedTestLine = tweetProcessor.formatTweet(tweet_text)
            sent = NBClassifier.classify(
                tweetProcessor.extract_features(
                    tweetProcessor.getFeatureVector(processedTestLine)))

            tweet = Tweets(nominee=nom, tweet=tweet_text, sentiment=sent)

            tweet.save()
Exemplo n.º 4
0
def createTweet(request):
    """
    This method is used to create a tweet by a logged in user.
    'request.user' represents username of logged in user.
    'request.body' contains tweet in JSON format which the user
    wants to create.
    """
    to_tweet = request.data.get("tweet")
    if to_tweet is None:
        return Response({'error':'Please provide content of tweet to create with key tweet'},
                        status=HTTP_400_BAD_REQUEST)
    tweet = Tweets(username = request.user, tweet = str(to_tweet))
    tweet.save()
    obj = Tweets.objects.filter(username = request.user, tweet = str(to_tweet)).last()
    note = "Tweet Creation Successfull, with Tweet ID " + str(obj.id)
    return Response({'Note': note}, status=HTTP_200_OK)
Exemplo n.º 5
0
def watch_stream():
  auth = OAuth(ACCESS_TOKEN, ACCESS_TOKEN_SECRET, CONSUMER_KEY, CONSUMER_SECRET)
  stream = TwitterStream(auth=auth, domain="userstream.twitter.com")
  for msg in stream.user():
    if msg.has_key('text'):
      if len(msg['entities']['urls']) > 0:
        user_id = msg['user']['id_str']
        user_name = msg['user']['name']
        screen_name = msg['user']['screen_name']
        text = msg['text']
        tweet_id = msg['id_str']
        timestamp = msg['timestamp_ms']
        created_dt =  datetime.datetime.fromtimestamp(int(timestamp)/1000.0)
        for eurl in msg['entities']['urls']:
          link = eurl['expanded_url']
          if "flic.kr" in link or "twitter.com" in link:
            continue
          try:
            hres = requests.head(link, timeout=3)
            if hres.status_code == 301 or hres.status_code == 302:
              link = hres.headers.get("location", link)
            for s in ["?utm_", "&utm_", "%26utm_", "?from=", "?ref=", "&ref=" "?ncid=rss", "?n_cid="]:
              if s in link:
                idx = link.find(s)
                link = link[:idx]
            if link == "h":
              print ">>", link
              print ">>", eurl['expanded_url']
            tweet = Tweets(
                url=link, text=text,
                tweet_id=tweet_id,
                user_id=user_id,
                user_name=user_name,
                screen_name=screen_name,
                created_at=created_dt
                )
            tweet.save()
            fetch(link, created_dt)
          except requests.exceptions.Timeout, e:
            print ">>", "error", link, e
          except requests.exceptions.SSLError, e:
            print ">>", "error", link, e
          except requests.exceptions.ConnectionError ,e:
            print ">>", "error", link, e
Exemplo n.º 6
0
def create_post(request):
    if request.method == 'POST':
        post_text = request.POST.get('the_post')
        response_data = {}

        post = Tweets(tweet=post_text, user_id=request.user.id)
        post.save()

        response_data['result'] = 'Create post successful!'
        response_data['postpk'] = post.pk
        response_data['text'] = post.tweet


        return HttpResponse(
            json.dumps(response_data),
            content_type="application/json"
        )
    else:
        return HttpResponse(
            json.dumps({"nothing to see": "this isn't happening"}),
            content_type="application/json"
        )
def save_tweets_in_db(location, tweets):
    tweets_data = Tweets(location = location.lower(), tweets = tweets)
    tweets_data.save()
Exemplo n.º 8
0
                api_version=3,
                config_file=None)

q = ironmq.queue('tweets')
users = []

for token in RawTokens.select():
    users.append({"client": token.client, "secret": token.secret})



# lastTweet = Tweets.select().order_by(Tweets.id.desc()).get().tid


auth = tweepy.OAuthHandler(CONSUMER_TOKEN, CONSUMER_SECRET)
auth.set_access_token(users[0]['client'], users[0]['secret'])
api = tweepy.API(auth)

for update in api.user_timeline(screen_name="daniel7447d4rb4",count=5):
    try:
        print(update.id)
        tw = Tweets(tid=update.id,send="false")
        tw.save()
    except Exception as e:
        print(e)