-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.py
218 lines (205 loc) · 5.82 KB
/
server.py
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
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
from flask import Flask,render_template,request,jsonify
import multiprocessing as mp
import feedparser
import tweepy
import time
from dateutil import parser
#config
app = Flask(__name__)
#setup variables
setup=[]
feed=[]
running=False
process=None
user = "Bot Inactive"
#authenticating twitter account
def authenticate():
global user
auth = tweepy.OAuthHandler(setup[0], setup[1])
auth.set_access_token(setup[2], setup[3])
api = tweepy.API(auth)
user=api.me().screen_name
return api
#start bot process
def start():
global process
try:
authenticate()
except Exception as e:
print("\n!! ERROR : "+str(e)+"\n")
return False
if not running:
process=mp.Process(target=feedUpdate, args=(setup,feed))
process.start()
return True
return False
#terminate bot process
def stop():
global process
try:
if running:
process.terminate()
process=None
print("\nBot Stopped\n")
return True
return False
except Exception as e:
print("\n!! ERROR : "+str(e)+"\n")
return False
#bot
def feedUpdate(setup,urls):
print("\nBot Started\n")
auth = tweepy.OAuthHandler(setup[0], setup[1])
auth.set_access_token(setup[2], setup[3])
ap = tweepy.API(auth)
lastUpdate = time.time()
tweetInterval=int(setup[4])
startTime = lastUpdate
while True:
if (time.time()-lastUpdate) < tweetInterval :
continue
print("\n!! Fetching Updates !!\n")
for url in urls:
feed = feedparser.parse(url)
for feeds in feed['entries']:
dt = parser.parse(feeds["published"]).timestamp()
if lastUpdate < dt:
print("\n**New Feed Posted From "+str(feed['feed']['title'])+'\n-->'+feeds['title']+'\n')
msg = feeds['title']+" "+feeds['link']
try:
ap.update_status(msg)
except Exception as e:
print("\n!! ERROR : "+str(e)+" !!\n")
lastUpdate = time.time()
#routes
#homepage
@app.route('/index/')
@app.route('/')
def index():
if setup==[]:
return render_template('index.html',erorr="Bot not Configured. Visit Settings tab to configure.",run=running,user=user)
return render_template('index.html',run=running,user=user)
#settings route
@app.route('/settings/',methods = ['POST', 'GET'])
def settings():
global setup
global running
if request.method == 'POST':
try:
setup=[]
setup.append(request.form['consumer_key']+"\n")
setup.append(request.form['consumer_secret_key']+"\n")
setup.append(request.form['access_token']+"\n")
setup.append(request.form['access_token_secret']+"\n")
setup.append(request.form['interval']+"\n")
file = open("secret.txt","w")
file.writelines(setup)
file.close()
setup = [x.rstrip() for x in setup]
if running:
stop()
running=not running
start()
running=not running
except Exception as e:
print("\n!! ERROR : "+str(e)+" !!\n")
return render_template('settings.html',setup=setup,message="ERROR Please Check Again")
return render_template('settings.html',setup=setup,message="UPDATED SUCCESFULLY")
else:
return render_template('settings.html',setup=setup)
#feed edit route
@app.route('/feed_list/',methods = ['POST', 'GET'])
def feed_list():
global feed
global running
update=""
if request.method == 'POST':
feed=[x.rstrip().replace('\t','') for x in request.form['feed_list'].split('\n') if x.rstrip().replace('\t','')!=""]
print("\nFeed List updated:-\n",feed)
try:
file = open("feed_list.txt","w")
file.writelines([x+"\n" for x in feed])
file.close()
if running:
stop()
running=not running
start()
running=not running
update="UPDATED SUCCESFULLY"
except Exception as e:
print("\n!! ERROR : "+str(e)+"\n")
update="ERROR : COULDN'T UPDATE"
return render_template('feed_list.html',feed=feed,message=update)
#bot access route
@app.route('/changestate')
def changestate():
global running
global user
if request.method != 'GET':
return "ERORR"
state = request.args.get('state')
if state!=str(running) or setup==[]:
return jsonify(
resp="False",
erorr="Configuration Erorr"
)
elif feed==[]:
return jsonify(
resp="False",
erorr="Feed List is Empty. Add RSS Feeds"
)
else:
if not running:
if start():
resp=jsonify(pstate=str(not running),resp='True',stat='Running',color='#25abff',user=user)
running= not running
return resp
else:
return jsonify(resp="False",erorr="PROCESS/AUTH ERORR")
else:
if stop():
user="Bot Inactive"
resp=jsonify(pstate=str(not running),resp='True',stat='Start',color='red',user=user)
running= not running
return resp
else:
return jsonify(resp="False",erorr="PROCESS ERORR")
#post manual tweet
@app.route('/tweets/',methods = ['POST', 'GET'])
def tweet_man():
if setup==[]:
return render_template('tweet.html',message="Bot not Configured. Visit Settings tab to configure.")
if request.method == 'POST':
try:
api = authenticate()
try:
msg=request.form['status']
print(msg)
if msg==None or msg==' ':
raise Exception('Value Not Present')
except Exception as e:
print("\n!! ERROR : "+str(e)+"\n")
return render_template('tweet.html',message="ERROR : Empty Status")
api.update_status(msg)
return render_template('tweet.html',message="Status Updated")
except Exception as e:
print("\n!! ERROR : "+str(e)+"\n")
return render_template('tweet.html',message="Authentication ERROR. Re-Configure Bot.")
return render_template('tweet.html')
#main running development server
if __name__ == '__main__':
running=False
#initializing if setup exists
try:
file = open("secret.txt","r")
setup = [x.rstrip() for x in file.readlines()]
file.close()
except:
pass
try:
file = open("feed_list.txt","r")
feed = [x.rstrip() for x in file.readlines()]
file.close()
except:
pass
app.run()