def service(): """ Json service to answer the user's questions """ if request.method == 'POST': data = json.loads(request.data) #todo ensure data['method'] == 'answer' question = data['params']['question'] answer = decisiverobot.snarkyanswer(question) return jsonify(result=answer) #assume method is GET answer = decisiverobot.snarkyanswer(request.args['question']) return jsonify(answer=answer)
def run(): """ Runs the bot it a loop, checking for questions and replying """ # We use two twitter clients, one to search, another to update. Just # easier that way... twitter = Twitter(domain="search.twitter.com") twitter.uriparts = () last_id_replied = "" # Fetch the last message replied to from disk to # ensure we don't answer the same question twice. try: with file(LAST_ID_FILE, "r") as content: last_id_replied = content.read() except IOError as ex: print(LAST_ID_FILE + " not found") poster = Twitter( auth=OAuth(ACCESS_TOKEN, ACCESS_TOKEN_SECRET, CONSUMER_KEY, CONSUMER_SECRET), secure=True, api_version="1", domain="api.twitter.com", ) while True: results = twitter.search(q=TWITTER_USER, since_id=last_id_replied)["results"] for result in results: last_id_replied = str(result["id"]) question = result["text"] # Only answer tweets with username at the beginning if REG_USER_BEGINNING.match(question) is None: continue # Remove our twitter name from the question. question = REG_USER_BEGINNING.sub("", question) asker = result["from_user"] print("<- {0} (@{1} {2})".format(question, asker, last_id_replied)) # Get the answer from the bot bot_response = decisiverobot.snarkyanswer(question) # Add the twitter @address of the asker msg = "@{0} {1}".format(asker, bot_response) print("-> " + msg) # post reply to twitter poster.statuses.update(status=msg, in_reply_to_status_id=last_id_replied) # Write the last message replied to to disk try: with file(LAST_ID_FILE, "w") as writer: writer.write(last_id_replied) except IOError as ex: print(ex) time.sleep(SLEEP_INTERVAL)
def index(): """ Serves the landing page """ if 'question' in request.args: question = request.args['question'] questionurl = "/?question=" + urllib.quote(question) answer = decisiverobot.snarkyanswer(question) else: question = None questionurl = None answer = None return render_template('index.html', question=question, questionurl=questionurl, answer=answer)