-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathprofile_search_api.txt
198 lines (171 loc) · 6.64 KB
/
profile_search_api.txt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
import os
import time
import tweepy
from flask import Flask, request, render_template, redirect, abort, flash, jsonify
from flask_cors import CORS, cross_origin # This is the magic
from bson import json_util
import json
import pandas as pd
import psycopg2 as pg
import pandas.io.sql as psql
import datetime
from psycopg2.extras import RealDictCursor
import numpy as np
import networkx as nx
import re
from collections import Counter
import csv
import json
import tweepy
import time
app = Flask(__name__) # create our flask app
CORS(app)
app.config['CORS_HEADERS'] = 'Content-Type'
def search_user(string1,string2=None,string3=None,string4=None):
import psycopg2 as pg
from psycopg2.extras import RealDictCursor
import pandas as pd
#connection = pg.connect(dbname="platform", user="ps", password="ps@123", host="172.20.1.51", port="6011")
#
#df_user = pd.read_sql("SELECT * FROM sm_user WHERE sm_screen_name LIKE '%"+string1+"%'"
# ,con= connection)
#connection.close()
#df_user['sm_user_name'] = df_user['sm_user_name'].str.lower()
#df_user['sm_location']=df_user['sm_location'].str.lower()
#
#if string2 is not None:
# df_user=df_user[df_user['sm_user_name'].str.contains(string2,na=False)]
#
#if string3 is not None:
# df_user=df_user[df_user['sm_location'].str.contains(string3,na=False)]
#
#if string4 is not None:
# df_user.loc[df_user['sm_channel_id'] == string4]
#
#user=df_user['sm_screen_name'].iloc[0]
#
#
#result=df_user.to_json(orient="index")
#parsed = json.loads(result)
#
# user 5 tweets
# configure Twitter API
consumer_key = "lKPbSIynHJeYcMfsiXIJuayCd"
consumer_secret = "QDFkW07TwnNfm5sVP0poR1sqfe0FVrFQQD1qBQtx6K3kfSP67a"
access_token = "1197604244-G9qyiTNfs9V1VPKtRkz8rv0YaxdMc9vPovNU6Dw"
access_token_secret = "9ahcXDBj76JQetdTxQL3hvyE6BoqRn9wfW1tUn9rCMmWf"
# Authenticate twitter Api
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
ntwrk=[]
my_dict=[]
api = tweepy.API(auth)
user = api.get_user(string1)
parsed=user._json
result = []
for tweet in api.user_timeline(id=string1, count=5):
result.append({
"sm_text": tweet.text,
"created_at": tweet.created_at,
"social_user": {
"sm_profile_image_url": tweet.user.profile_image_url,
"sm_user_name": tweet.user.name,
"sm_social_user_id": tweet.user.id_str,
"sm_screen_name": tweet.user.screen_name
},
"channel": {
"sm_name": "Twitter",
"id": 1
},
"sm_status_created_on": tweet.created_at,
"sm_media": [],
"sm_text": tweet.text,
"sm_social_id": tweet.id_str,
"sm_shared_count":tweet.retweet_count,
"sm_favorite_count":tweet.favorite_count
})
def getIntForString(s):
r = ''
for c in s:
r = r + str(ord(c))
return r
def getFollowers(api, root_user, no_of_followers):
primary_followers = []
counter = True
while counter == True:
try:
newUser = api.get_user(root_user)
followers = newUser.followers()
try:
for index in range(no_of_followers):
primary_followers.append((str(followers[index].screen_name), root_user))
counter == False
return primary_followers
except (tweepy.error.RateLimitError):
print("User has 0 followers")
sys.exit(1)
except (tweepy.error.RateLimitError):
print("Sleeping on getFollowers. Please wait")
time.sleep(15*60)
def getSecondaryFollowers(api, followers_list, no_of_followers):
secondary_followers = []
counter = True
while counter == True:
try:
for user in followers_list:
try:
newUser = api.get_user(user[0])
followers = newUser.followers()
count = 0
for username in followers:
if count < no_of_followers:
secondary_followers.append((username.screen_name, user[0]))
count += 1
except (tweepy.TweepError):
print ("Not authorized to view user. Skipping to next user")
pass
counter == False
#print(secondary_followers)
return secondary_followers
except (tweepy.error.RateLimitError):
print ("Sleeping on getSecondaryFollowers. Please wait")
time.sleep(15*60)
def get_links(ROOT_USER,NO_OF_FOLLOWERS=4):
#ROOT_USER = string1
primary_followers = getFollowers(api, ROOT_USER, NO_OF_FOLLOWERS)
secondary_followers = getSecondaryFollowers(api, primary_followers, NO_OF_FOLLOWERS)
followers = primary_followers + secondary_followers
unique_pairs = {tuple(sorted(x)) for x in followers}
uniq=sorted(set().union(*unique_pairs))
for n in uniq:
a={'id': getIntForString(n),'name':n,'size' : 10}
my_dict.append(a)
for pair in unique_pairs:
b={"source" : getIntForString(pair[0]),"source_name" : pair[0],"target" : getIntForString(pair[1]),"target_name" : pair[1]}
ntwrk.append(b)
return my_dict, ntwrk
nodes,links=get_links(string1,NO_OF_FOLLOWERS=4)
templateData = {
'user_data' : parsed,
'user_Tweets' : result,
'links' : links,
'nodes' : nodes
}
return(json.dumps(templateData,default=json_util.default))
@app.route('/social_media/profile_search',methods=['GET','POST'])
@cross_origin()
def add_message():
request.get_json(force=True)
content = request.json
records = None
user_name = content["profile_name"]
#name = content["name"]
#location = content["location"]
#platform = content["platform"]
if user_name:
records = search_user(content["profile_name"])
return records
else:
return jsonify({})
app.debug = True
app.run(host='0.0.0.0', port=6022,debug=True)