def twitter_login(): if not twitter.authorized: return redirect(url_for('twitter.login')) account_info = twitter.get('account/settings.json') account_info_more = twitter.get('account/verify_credentials.json') if account_info.ok: account_info_json = account_info.json() account_info_more_json = account_info_more.json() users = mongo.db.users existing_user = users.find_one( {'username': account_info_json['screen_name']}) if existing_user is None: users.insert({ 'username': account_info_json['screen_name'], 'email': 'utilizator twitter', 'password': '******', 'firstname': account_info_more_json['name'], 'lastname': '', 'points': 10, 'gamesp': 0, 'gamesw': 0, 'ac1': 0, 'ac2': 0, 'ac3': 0, 'ac4': 0, 'ac5': 0, 'ac6': 0, 'online': 1, 'ingame': 0, 'admin': 0, 'imglink': account_info_more_json['profile_image_url_https'] }) session['username'] = account_info_json['screen_name'] shutil.copy('static/images/person_blank.png', 'static/img/' + session['username'] + '.png') else: session['username'] = account_info_json['screen_name'] return redirect(url_for('index'))
def api_user(): message = "" user_message = "" friend_message = "" follower_message = "" count = 20 try: if request.method == 'GET' and request.args: screen_name = request.args.get('screenName') cleaned_screen_name = screen_name.replace("@", "") queryString = "?screen_name=" + cleaned_screen_name + "&count=" + str( count) user = None friends = [] followers = [] resp_screenName = twitter.get("users/show.json" + "?screen_name=" + cleaned_screen_name) if (resp_screenName.ok): user = get_user_info(resp_screenName) else: user_message = resp_screenName.reason resp_friends = twitter.get("friends/list.json" + queryString) if (resp_friends.ok): friends = get_accounts(resp_friends) else: friend_message = resp_friends.reason resp_followers = twitter.get("followers/list.json" + queryString) if (resp_followers.ok): followers = get_accounts(resp_followers) else: follower_message = resp_followers.reason return render_template('api/user.html', formSubmitted=True, user=user, friends=friends, followers=followers, user_message=user_message, friend_message=friend_message, follower_message=follower_message) else: return render_template('api/user.html', formSubmitted=False, user_message=user_message, friend_message=friend_message, follower_message=follower_message) except: print(sys.exc_info()[0]) return render_template('api/user.html', formSubmitted=False, user_message=user_message, friend_message=friend_message, follower_message=follower_message)
def get_twitter_data(): """Function to authenticate and analyze a twitter user""" # Check if our user is authorized already if not twitter.authorized: return redirect('/homepage') # Query twitter for the users tweets and name response = twitter.get("statuses/home_timeline.json", params={'count': '200'}) username = twitter.get("account/settings.json") if response.status_code != 200 or username.status_code != 200: return render_template('error.html', status_code=response.status_code) # Get our username username = username.json()['screen_name'] # Loop over the results building a long string with all tweets from their timeline results = response.json() final_string = "" for result in results: final_string += result['text'] + " ." # Analyzer our final string and display the info to the user tones = string_analyzer.string_analysis(final_string) # Remove duplicates new_tones = [] [new_tones.append(x) for x in tones if x not in new_tones] tones = new_tones # Add this data to our database if db_client.find_one({"username": username}): # Update a users data try: to_insert = db_client.find_one({"username": username}) to_insert['twitter_analysis'] = tones db_client.update_one({'username': username}, {"$set": to_insert}, upsert=False) except: print(f"[DB]: Something went wrong when updating {username}") return render_template('user/twitter_analysis.html', tones=tones) else: # Create the user document try: to_insert = DATABASE_SCHEMA to_insert['username'] = username to_insert['twitter_analysis'] = tones db_client.insert_one(to_insert).inserted_id except: print(f"[DB]: Something went wrong when updating {username}") return render_template('user/twitter_analysis.html', tones=tones) # Return return render_template('user/twitter_analysis.html', tones=tones)
def get_image_data(): """Function to authenticate and analyze a image data""" # Check if our user is authorized already if not twitter.authorized: return redirect('/homepage') # Query twitter for the users username and display picture username = twitter.get("account/settings.json") if username.status_code != 200: return render_template('error.html', status_code=username.status_code) # Get our username username = username.json()['screen_name'] response = twitter.get("users/show.json", params={'screen_name': username}) if response.status_code != 200: return render_template('error.html', status_code=reponse.status_code) # Get our profile picture URL image_url = response.json()['profile_image_url'] # Analyze it image_tones = image_analyzer.analyse(image_url) # Remove duplicates new_tones = [] [new_tones.append(x) for x in image_tones if x not in new_tones] image_tones = new_tones # Add this data to our database if db_client.find_one({"username": username}): # Update a users data try: to_insert = db_client.find_one({"username": username}) to_insert['image_analysis'] = image_tones db_client.update_one({'username': username}, {"$set": to_insert}, upsert=False) except: print(f"[DB]: Something went wrong when updating {username}") return render_template('error.html', status_code=487) else: # Create the user document try: to_insert = DATABASE_SCHEMA to_insert['username'] = username to_insert['image_analysis'] = image_tones db_client.insert_one(to_insert).inserted_id except: print(f"[DB]: Something went wrong when updating {username}") return render_template('error.html') # Return return render_template('user/image_analysis.html', tones=image_tones)
def twitter_loggin(): if not twitter.authorized: return redirect(url_for("twitter.login")) resp = twitter.get("account/verify_credentials.json") assert resp.ok return "You are @{screen_name} on Twitter".format( screen_name=resp.json()["screen_name"])
def login_with_twitter(): if not twitter.authorized: return redirect(url_for("twitter.login")) resp = twitter.get("account/settings.json") assert resp.ok print(twitter.token) return {"screen_name": resp.json()["screen_name"]}
def index(): if not twitter.authorized: return {"screen_name": "Please click on Log in with Twitter button"} resp = twitter.get("account/settings.json") assert resp.ok print(twitter.token) return {"screen_name": resp.json()["screen_name"]}
def getCollectionInfo(username): dynamodb = aws_session.resource('dynamodb', region_name='us-west-2') table = dynamodb.Table('tweetlights_users') response = table.get_item(Key={'userid': username}) tweets = [] if 'Item' in response: if 'collectionid' in response['Item']: collectionID = response['Item']['collectionid'] response = twitter.get('collections/entries.json?id=%s' % collectionID) try: tweets = list(response.json()['objects']['tweets'].keys()) except: tweets = [] else: response = twitter.post( 'collections/create.json?name=tweetlights.com&timeline_order=tweet_reverse_chron' ) collectionID = response.json()['response']['timeline_id'] response = table.put_item(Item={ 'userid': username, 'collectionid': collectionID }) flash('New tweetlights collection created. Now add your highlights!') return collectionID, tweets
def twitter_login(): if not twitter.authorized: return redirect(url_for('twitter.login')) account_info = twitter.get('account/settings.json') if account_info.ok: account_info_json = account_info.json() my_client_id = 'giTIdWnkh_cDlA' my_client_secret = '7LcUbaGSCJtbqy5YlW8bmQQXSxw' reddit = praw.Reddit(client_id=my_client_id, client_secret=my_client_secret, user_agent='gaurav2621') l = { 1: '/r/python', 2: '/r/java', 3: '/r/c++' } #predefined the subreddit intrests.We can get the subbreddit list through a text file from the user or create a dictionary and store the input data c = {} #we can extend a dictionary to a database for i in l: for submission in reddit.subreddit(l[i]).hot(limit=1): c[i] = submission.url #throwing back http 400 error needs to be fixed twitter1 = Twython( consumer_key, consumer_secret, OAUTH_TOKEN, OAUTH_TOKEN_SECRET ) #was unable to extract OAUTH_TOKEN and OAUTH_TOKEN_SECRET for j in range(len(c)): twitter1.update_status(status=c[j]) #when ever the app is run it tweets on your profile but not on daily basis return '<h1>Hey! <h2>Welcome @{} Click <a href="https://twitter.com/"> here </a> to go to twitter'.format( account_info_json['screen_name']) return '<h1>Request failed!</h1>'
def fake_detector(): if not twitter.authorized: return redirect(url_for('twitter_login_verify')) else: account_info = twitter.get('account/verify_credentials.json') # print(account_info.json()) account_info = account_info.json() account_details = [ str(account_info['id']), account_info['id_str'], account_info['screen_name'], account_info['description'], str(account_info['url']), str(account_info['followers_count']), str(account_info['friends_count']), str(account_info['listed_count']), str(account_info['created_at']), str(account_info['favourites_count']), str(account_info['verified']), str(account_info['statuses_count']), str(account_info['lang']), str(account_info['status']), str(account_info['default_profile']), str(account_info['default_profile_image']), str(account_info['has_extended_profile']), str(account_info['name']) ] csvFile = open('test_data.csv', 'w') csvFile.write( "id id_str screen_name location description url followers_count friends_count listed_count created_at favorites_count verified statuses_count lang status default_profile default_profile_image has_extended_profile name\n" ) csvFile.write("\t".join(account_details)) csvFile.close() return "\t".join(account_details)
def twitter_mentions_timeline(user_id): """ 将用户 mentions 存入数据库 API: https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-mentions_timeline """ if not twitter.authorized: return redirect(url_for('twitter.login')) user = db.session.query(models.User).get(user_id) screen_name = get_twitter_screen_name(twitter_blueprint, user) # 获取数据库中最后 mention last_mention = get_user_last_tweet_or_mention(user, models.TweetMention) # 获取路径 path = get_twitter_path(last_mention, screen_name, 'mention') # 更新最后 mention 之后的文章 resp = twitter.get(path) if not resp.ok: return jsonify(resp.json()) # 存入数据库 save_twitter_data(resp, user, models.TweetMention) return jsonify({'msg': 'success'})
def auth(): if not twitter.authorized: return redirect(url_for("twitter.login")) resp = twitter.get("account/verify_credentials.json") rjson = resp.json() t_id = rjson["id_str"] screen_name = rjson["screen_name"] user_record = User.query.filter_by(t_id=t_id).first() if user_record is None: user_record = User(t_id = t_id, screen_name=screen_name) t = twitter_blueprint.get_token() twitter_blueprint.set_token_storage_sqlalchemy(OAuth, db.session, user=user_record) twitter_blueprint.set_token(t) db.session.add(user_record) db.session.commit() login_user(user_record) return redirect("/")
def twitter_auth(twitter_blueprint, token): """ Twitter 授权 """ if not token: return False user = current_user resp = twitter.get("account/settings.json") if not resp.ok: if resp.json()['errors'][0]['message'] == "Invalid or expired token.": return redirect(url_for("twitter.login")) return jsonify(resp.json()) screen_name = resp.json()['screen_name'] oauth, created = get_oauth_or_create(twitter_blueprint.name, user, screen_name) actions.update_oauth_token(oauth, twitter.token) print('==== get twitter user timeline') twitter_user_timeline(user.id) print('==== get twitter user mention timeline') twitter_mentions_timeline(user.id) return redirect('/#/index?name={}&id={}'.format(user.username, user.id))
def log_in_twitter(user): if not twitter_dance.authorized: return redirect(url_for("twitter.login")) tag = "@" + twitter_dance.get( "account/settings.json").json()['screen_name'] facade.set_user_twitter_tag(user, tag) return redirect(url_for('profile.profile'))
def match_user(): """Function to match our user""" # Get our users username query = twitter.get("account/settings.json") if not query.ok: return render_template('error.html', status_code=query.status_code) result = query.json() username = result["screen_name"] # Get our users data, if they don't have any data create it if db_client.find_one({"username": username}): # Update a users data try: to_insert = db_client.find_one({"username": username}) match_ret, all_data = matcher.match_data(to_insert) match_ret = (match_ret[0], int(match_ret[1])) to_insert['dog_match'] = match_ret db_client.update_one({'username': username}, {"$set": to_insert}, upsert=False) except: print( f"[DB]: Something went wrong when getting data for {username}") return render_template('error.html', status_code=487) else: print(f"[DB]: No data for {username}") return render_template('error.html', status_code=487) # If everything went well return the user the data return render_template( 'user/match.html', data=to_insert, local_images=LOCAL_DOG_IMAGES, all_data=all_data, )
def search_tweets(q, count): params = {'q': q, 'count': count, "lang": "en"} encoded = urllib.parse.urlencode(params) print(encoded) url = search_tweets_url + '?' + encoded print(url) return twitter.get(url)
def index(): if not twitter.authorized: return redirect(url_for("twitter.login")) resp = twitter.get("account/settings.json") assert resp.ok return "You are @{screen_name} on Twitter".format( screen_name=resp.json()["screen_name"])
def twitter_login(): if not twitter.authorized: return redirect(url_for('twitter.login')) resp = twitter.get('account/verify_credentials.json?include_email=true') retval = resp.json() # Note - email may not be present user = User.query.outerjoin(Social) \ .filter( (Social.gmail == retval['email']) | (Social.tmail == retval['email']) | (User.email == retval['email'])).first() if not user: user = User() user.social = Social(handle=retval['screen_name'], tmail=retval.get('email')) db.session.add(user) db.session.commit() elif not user.social: user.social = Social(handle=retval['screen_name'], tmail=retval.get('email')) db.session.commit() else: user.social.handle = retval['screen_name'] user.social.tmail = retval.get('email') db.session.commit() login_user(user) return redirect(url_for('main.dashboard'))
def twitter_user_timeline(user_id): """ 将用户 tweet 存入数据库 API: https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-user_timeline """ if not twitter.authorized: return redirect(url_for('twitter.login')) user = db.session.query(models.User).get(user_id) screen_name = get_twitter_screen_name(twitter_blueprint, user) # 获取数据库中最后 tweet last_tweet = get_user_last_tweet_or_mention(user, models.Tweet) # 获取 API 路径 path = get_twitter_path(last_tweet, screen_name, 'tweet') # 访问 twitter API resp = twitter.get(path) if not resp.ok: return jsonify(resp.json()) timeline = json.dumps(resp.json(), indent=2, ensure_ascii=False) # 存入数据库 save_twitter_data(resp, user, models.Tweet) return jsonify({'msg': 'success'})
def login(): # if not logged in redirect to oauth twitter login if not twitter.authorized: return redirect(url_for('twitter.login')) settings = twitter.get('account/settings.json') settings_json = settings.json() # convert to dictionary return '@{} is logged in to Tweet Guard'.format( settings_json['screen_name'])
def home(): if not twitter.authorized: return redirect(url_for("twitter.login")) resp = twitter.get("account/settings.json") # assert resp.ok screenname = resp.json()["screen_name"] return render_template('pages/placeholder.home.html', screenname=screenname)
def start(): if not twitter.authorized: return redirect(url_for("twitter.login")) resp = twitter.get("account/verify_credentials.json") screen_name = resp.json()["screen_name"] name = resp.json()["name"] assert resp.ok return redirect(url_for('twitter_api'))
def twtsignin(): if not twitter.authorized: return redirect(url_for("twitter.login")) resp = twitter.get("account/settings.json") # print('what is resp', resp.json()) assert resp.ok # return "You are @{screen_name} on Twitter".format(screen_name=resp.json()["screen_name"]) return redirect(url_for("user_details"))
def twitter(): if not twitter.authorized: return redirect(url_for("twitter.login")) resp = twitter.get("/user") print(resp.json()) assert resp.ok return "You are @{login} on Twitter".format( login=resp.json()["screen_name"])
def manage(): user_name = twitter.token["screen_name"] if len(get_user(user_name)) == 0: resp = twitter.get("account/verify_credentials.json", params={'include_email': 'true', "skip_status": 'true', "include_entities": 'false'}) insert_into_users(user_name, resp.json()["name"], resp.json()["email"]) udhaars = get_udhaars(user_name) return render_template("manage.html", udhaars=udhaars)
def twitter_login(): if not twitter.authorized: print(session) return redirect(url_for('twitter.login')) resp = twitter.get("account/verify_credentials.json") print(resp.json()) assert resp.ok flash(f"You are successfully Logged in as @{resp.json()['screen_name']}") return render_template('dashboard.html')
def retrieve_twitter_screen_name(): account_info = twitter.get('account/settings.json') if account_info.ok: account_info_json = account_info.json() screen_name = account_info_json['screen_name'] return screen_name else: return False
def twitter_login(): if not twitter.authorized: return redirect(url_for('twitter.login')) account_info = twitter.get('account/settings.json') account_info_json = account_info.json() return '<h1>Your Twitter Name is @{}</h1>'.format( account_info_json['screen_name'])
def twitter_login(): # If the user is not authorized, redirect to the twitter login page if not twitter.authorized: return redirect(url_for('twitter.login')) # If user is authorized retrieve his/her account details account_info = twitter.get('account/settings.json') # If user is authorized retrieve his/her tweets user_tweets = twitter.get("statuses/user_timeline.json") # If account information is successfully retrieved, proceed to analyse and display it if account_info.ok: # Convert retrieved info to json format user_tweets_json = user_tweets.json() account_info_json = account_info.json() # Get tweet text from the objects returned all_tweets = [] print(account_info_json) for tweet in user_tweets_json: all_tweets.append(tweet['text']) # Text Cleaning for tweets all_tweets_cleaned = text_cleaning.clean_tweets(all_tweets) # BTM model for topic modeling results classified_tweets, topics = btm_model.categorize(all_tweets_cleaned) # Sentiment analysis tweet_sentiment = sentiment.get_sentiment(all_tweets_cleaned) # Prepare data to be sent and rendered on the template for user dashboard data = { "all_tweets": all_tweets, "account_info_json": account_info_json, "classified_tweets": classified_tweets, "topics": topics, "sentiment": tweet_sentiment } # Render template with user data return render_template('user_dash.html', data=data) # If account info is not retrieved successfully return an error message. return '<h2>Error</h2>'
def twitter_login(): if not twitter.authorized: return redirect(url_for('twitter.login')) else: account_info = twitter.get('account/settings.json') if account_info.ok: account_info_json = account_info.json() return account_info_json else: return account_info
def twitter_login(): if not twitter.authorized: return redirect(url_for('twitter.login')) account_info = twitter.get('account/settings.json') account_info_json = account_info.json() screen_name = account_info_json['discoverable_by_email'] print(f'{account_info_json}') print(f'{screen_name}') return '<h1>Your Twitter name is @{}</h1>'.format( account_info_json['screen_name'])
def twitterLogin(): if not twitter.authorized: return redirect(url_for("twitter.login")) resp = twitter.get("account/settings.json") print(resp) print(twitter.authorized) if resp.ok: session["username"] = resp.json()["screen_name"] session["loggedIn"] = True print(session["username"]) print(session["loggedIn"]) # return "You have been authorized by twitter as @{screen_name}".format(resp.json()["screen_name"]) return redirect(url_for("dashboard"))
def test_context_local(): responses.add(responses.GET, "https://google.com") # set up two apps with two different set of auth tokens app1 = Flask(__name__) tbp1 = make_twitter_blueprint("foo1", "bar1", redirect_to="url1") app1.register_blueprint(tbp1) app2 = Flask(__name__) tbp2 = make_twitter_blueprint("foo2", "bar2", redirect_to="url2") app2.register_blueprint(tbp2) # outside of a request context, referencing functions on the `twitter` object # will raise an exception with pytest.raises(RuntimeError): twitter.get("https://google.com") # inside of a request context, `twitter` should be a proxy to the correct # blueprint session with app1.test_request_context("/"): tbp1.session.auth.client.get_oauth_signature = mock.Mock(return_value="sig1") tbp2.session.auth.client.get_oauth_signature = mock.Mock(return_value="sig2") app1.preprocess_request() twitter.get("https://google.com") auth_header = dict( parse_authorization_header( responses.calls[0].request.headers["Authorization"].decode("utf-8") ) ) assert auth_header["oauth_consumer_key"] == "foo1" assert auth_header["oauth_signature"] == "sig1" with app2.test_request_context("/"): tbp1.session.auth.client.get_oauth_signature = mock.Mock(return_value="sig1") tbp2.session.auth.client.get_oauth_signature = mock.Mock(return_value="sig2") app2.preprocess_request() twitter.get("https://google.com") auth_header = dict( parse_authorization_header( responses.calls[1].request.headers["Authorization"].decode("utf-8") ) ) assert auth_header["oauth_consumer_key"] == "foo2" assert auth_header["oauth_signature"] == "sig2"