-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
278 lines (233 loc) · 9.52 KB
/
main.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
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
#!/usr/bin/env python
#
# Copyright 2007 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
from google.appengine.ext import webapp
from google.appengine.ext.webapp import util
import tweepy
import twitter
import logging
import config
import datastore
import brains
import settings
from google.appengine.ext.webapp import template
import constants
import os
from google.appengine.api import users
from google.appengine.api import taskqueue
import state
import datetime
def get_url( request, path ):
callback_url = request.url
callback_url = callback_url[:callback_url.rfind("/")]
callback_url += path
return callback_url
class MainHandler(webapp.RequestHandler):
def get(self):
self.response.out.write('Hello world!')
class SessionCleanupHandler( webapp.RequestHandler ):
def get(self):
while not delete_expired_sessions():
pass
message = "Cleaned up expired sessions."
logging.log( 1, message )
self.response.out.write( message )
class RunHandler( webapp.RequestHandler ):
def run_one( self, bot_name ):
logging.debug( "RunHandler.run_one: %s", bot_name )
creds = twitter.get_twitter_creds( bot_name )
force_tweet = self.request.get( "force_tweet") == "true"
debug = self.request.get( "debug" ) == "true"
brains.run( creds, force_tweet, debug )
def run_all( self ):
then = datetime.datetime.now()
all_creds = twitter.get_all_creds()
logging.debug( "RunHandler.run_all: queue up %d jobs" % len( all_creds ) )
for mm_twittercreds in all_creds:
bot_state = state.get_state( mm_twittercreds )
bot_settings = settings.get_settings( mm_twittercreds )
lastrun = bot_state.last_run
do_run = False
if lastrun is None:
do_run = True
else:
nextrun = lastrun + datetime.timedelta( hours=bot_settings.tweet_frequency )
if nextrun > then:
logging.debug( "-> %s not due yet (due at %s)" % (mm_twittercreds.screen_name,nextrun) )
else:
do_run = True
if do_run:
url = "/%s/run" % mm_twittercreds.screen_name
logging.debug( "-> queue up job: %s" % url )
taskqueue.add( url=url )
def handle_both( self, bot_name=None ):
if bot_name is None:
self.run_all()
else:
self.run_one( bot_name )
def get( self, bot_name=None ):
self.handle_both( bot_name )
def post( self, bot_name=None ):
self.handle_both( bot_name )
def path_for_template( template_name ):
return os.path.join( os.path.dirname(__file__), 'templates', template_name )
class SettingsHandler( webapp.RequestHandler ):
def render_notloggedin( self ):
template_values = {}
template_values[ 'message' ] = "Sorry, you need to be logged in to a Google account to create bots."
template_values[ 'login_url' ] = users.create_login_url( self.request.path )
template_path = path_for_template( "notloggedin.html" )
self.response.out.write( template.render( template_path, template_values ) )
def render_template( self, creds, bot_settings=None, values=None ):
template_values = {}
if values is not None:
template_values.update( values )
template_values[ "form_action" ] = self.request.path
if creds.screen_name is not None:
template_values[ 'twitter_username' ] = creds.screen_name
if bot_settings is None:
bot_settings = settings.get_settings( creds )
template_path = None
if bot_settings is None:
template_path = path_for_template( "nobot.html" )
else :
template_values[ 'guru_name' ] = bot_settings.learning_guru
template_values[ "tweet_frequency" ] = bot_settings.tweet_frequency
template_values[ "tweet_chance" ] = bot_settings.tweet_chance
try:
lists_in = creds.lists
if lists_in:
lists_out = []
for list_in in lists_in:
lists_out.append( { 'name' : list_in.name, 'id' : list_in.id_str } )
template_values[ 'lists' ] = lists_out
except Exception, err:
pass
if bot_settings.learning_style == constants.learning_style_oneuser:
template_values[ 'learnfrom_oneuser_checked' ] = "checked"
elif bot_settings.learning_style == constants.learning_style_followers:
template_values[ 'learnfrom_followers_checked' ] = "checked"
elif bot_settings.learning_style == constants.learning_style_following:
template_values[ 'learnfrom_following_checked' ] = "checked"
elif bot_settings.learning_style == constants.learning_style_list:
template_values[ 'learnfrom_list_checked' ] = "checked"
if bot_settings.learn_retrospectively:
template_values[ 'learn_retrospectively_checked' ] = "checked"
if bot_settings.locquacity_onschedule:
template_values[ 'locquacity_onschedule_checked' ] = "checked"
if bot_settings.locquacity_reply:
template_values[ 'locquacity_reply_checked' ] = "checked"
if bot_settings.locquacity_speakonnew:
template_values[ 'locquacity_speakonnew_checked' ] = "checked"
if bot_settings.locquacity_greetnew:
template_values[ 'locquacity_greetnew_checked' ] = "checked"
template_path = path_for_template( "settings.html" )
self.response.out.write( template.render( template_path, template_values ) )
def authenticate_user( self, creds ):
user = users.get_current_user()
return user is not None and user == creds.owner
# straight page load, dish out template
def get( self, bot_name ):
creds = twitter.get_twitter_creds( bot_name )
if self.authenticate_user( creds ):
self.render_template( creds )
else:
self.render_notloggedin()
# form data has been posted, process it
def post( self, bot_name ):
creds = twitter.get_twitter_creds( bot_name )
if not self.authenticate_user( creds ):
self.render_notloggedin()
else:
bot_settings = settings.get_settings( creds )
bot_settings.learning_style = self.request.get( 'learnfrom' )
bot_settings.learning_guru = self.request.get( 'guru_name' )
bot_settings.locquacity_onschedule = self.request.get( 'locquacity_onschedule' ) == "true"
bot_settings.locquacity_reply = self.request.get( 'locquacity_reply' ) == "true"
bot_settings.locquacity_speakonnew = self.request.get( 'locquacity_speakonnew' ) == "true"
bot_settings.learn_retrospectively = self.request.get( 'learn_retrospectively' ) == "true"
gn = self.request.get( 'locquacity_greetnew' ) == "true"
logging.debug( 'SettingsHandler.post(): locquacity_greetnew=%s, bot_settings.locquacity_greetnew=%s' % (gn, bot_settings.locquacity_greetnew) )
if gn and not bot_settings.locquacity_greetnew:
logging.debug( '-> fetch follower ids' )
api = twitter.get_api( creds )
follower_ids = api.followers_ids()
creds.follower_ids = follower_ids
creds.put()
bot_settings.locquacity_greetnew = gn
tweet_frequency = self.request.get( 'tweet_frequency' )
if tweet_frequency is not None and len(tweet_frequency) > 0:
bot_settings.tweet_frequency = float( tweet_frequency )
tweet_chance = self.request.get( 'tweet_chance' )
if tweet_chance is not None and len(tweet_chance) > 0:
bot_settings.tweet_chance = float( tweet_chance )
self.render_template( creds, bot_settings, { "saved" : True } )
bot_settings.creds = creds
bot_settings.put()
class NewHandler( webapp.RequestHandler ):
# vanilla get, serve up new bot page
def get(self):
template_values = {}
user = users.get_current_user()
if user is None:
template_values[ 'login_url' ] = users.create_login_url("/new")
template_values[ 'message' ] = "Sorry, but you need to be logged in to create new bots."
template_path = path_for_template( "notloggedin.html" )
self.response.out.write( template.render( template_path, template_values ) )
else:
redirect_url = None
tw_error = None
callback_url = get_url( self.request, "/oauth_return" )
template_values[ 'form_action' ] = "/twitter_return"
try:
redirect_url = twitter.get_authurl( callback_url )
except tweepy.TweepError, err:
tw_error = err
if tw_error is not None:
template_values[ 'message' ] = "Error! Failed to get request token."
else:
template_values[ "twitter_auth" ] = redirect_url
template_path = path_for_template( "new.html" )
self.response.out.write( template.render( template_path, template_values ) )
class OAuthReturnHandler( webapp.RequestHandler ):
def get(self):
verifier = self.request.get('oauth_verifier')
tw_error = None
api = None
try:
api = twitter.consume_verifier( verifier )
except tweepy.TweepError, err:
tw_error = err
if tw_error is None:
me = api.me()
self.response.out.write( "Auth complete for %s, redirecting..." % me.name )
redirect_url = get_url( self.request, "/%s/settings" % me.screen_name )
self.redirect( redirect_url )
else:
self.response.out.write( "Error! Failed to get access token." )
self.response.out.write( tw_error )
def main():
application = webapp.WSGIApplication( [ ('/', MainHandler),
('/new', NewHandler),
('/oauth_return', OAuthReturnHandler),
('/session_cleanup', SessionCleanupHandler),
('/run', RunHandler),
('/(.*)/run', RunHandler),
('/(.*)/settings', SettingsHandler) ],
debug=True )
util.run_wsgi_app(application)
if __name__ == '__main__':
main()