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)
twitter = Twitter(domain='search.twitter.com') twitter.uriparts=() last_id_replied = '' poster = Twitter( auth=OAuth( OAUTH_TOKEN.rstrip(), OAUTH_TOKEN_SECRET.rstrip(), TWITTER_CONSUMER_KEY.rstrip(), TWITTER_CONSUMER_SECRET.rstrip()), secure=True, api_version='1', domain='api.twitter.com') #Infinite loop to monitor the twitter account while True: try: results = twitter.search(q=TWITTER_NAME, since_id=last_id_replied)['results'] if not results: logging.info("No tweets to "+TWITTER_NAME+" this time...") for result in results: question = result['text'].replace(TWITTER_NAME, '') asker = result['from_user'] id = str(result['id']) logging.info(" Person who asked: " + asker + " and his question is: " + question) #Building json needed for the chatbot API messageJSON =json.dumps({ 'message': { 'message': "'"+question.strip()+"'",
if __name__ == "__main__": parser = OptionParser() parser.add_option("-d", "--database", dest="dbname", help="Name of database to create") parser.add_option("-f", "--followers", dest="followers", help="Extra users for whom we should retrieve followers") (options, args) = parser.parse_args() search = Twitter(domain="search.twitter.com") twitter = Twitter() conn = httplib.HTTPConnection(dbhost,dbport) # Create the DB before continuing create_database(conn,options.dbname) searchresults = search.search(q=searchquery,rpp=100) tweets = searchresults["results"] def create_tweet(tweet): doc = tweet doc['resource'] = 'tweet' tmp = create_document(conn,options.dbname,"tweet.%s" % tweet["id"],doc) return (tweet["id"],tmp) tweetmap = dict(map(create_tweet,tweets)) print "Tweets created: %s" % ",".join([str(k) for (k,v) in tweetmap.iteritems() if not v]) authors = list(unique_everseen([t["from_user"] for t in tweets])) def create_author(authorname): doc = twitter.users.show(id=authorname) doc['resource'] = 'author' tmp = create_document(conn,options.dbname,"author.%s" % authorname,doc) return (authorname,tmp)
last_id_file = 'last_id_replied' if (os.path.exists(last_id_file)): last_id_replied = int(open(last_id_file).read()) print 'Using last id from file ', last_id_replied doctor = eliza.eliza() poster = Twitter( auth=OAuth( oauth_token, oauth_token_secret, CONSUMER_KEY, CONSUMER_SECRET), secure=True, api_version='1', domain='api.twitter.com') while True: results = twitter.search(q="@PMStevenHarper", since_id=last_id_replied)['results'] if not results: print 'No results this time...' for result in results: # Remove my name from the question. question = result['text'].replace('@PMStevenHarper', '') asker = result['from_user'] id = str(result['id']) print " <<< " + asker + ": " + question doctor_response = doctor.respond(question.strip()) # We append part of the ID to avoid duplicates. msg = '@%s %s (%s)' % (asker, doctor_response, id[-4:]) print '====> Resp = %s' % msg
#make sure this guy is a tuple sbird.uriparts = () #anyone talking to us? last_id_replied = '' #twitter client to post. Posting requires oAuth schutff pbird = Twitter(auth=OAuth(oa_token, oa_token_secret, CONSUMER_KEY, CONSUMER_SECRET), secure=True, api_version='1', domain="api.twitter.com") #main loop. Just keep searching anyone talking to us while True: mentions = sbird.search(q='@SpeakingSecret', since_id=last_id_replied)['results'] if not mentions: print "No one talking to us now..." for mention in mentions: #cut our @SpeakingSecret out message = mention['text'].replace('@SpeakingSecret', '') speaker = mention['from_user'] speaker_id = str(mention['id']) print "Something named " + speaker + " is saying " + message last_id_replied = speaker_id print "Slumber...\n\n" time.sleep(10)
else: print"[!] Didn't find ~/.twitter_last_reply file.. starting fresh prince" #twitter client to post. Posting requires oAuth schutff pbird = Twitter(auth=OAuth(oa_token , oa_token_secret, CONSUMER_KEY , CONSUMER_SECRET), secure=True, api_version='1', domain="api.twitter.com") #our cleverbot instance cbot=cleverbot.Session() #main loop. Just keep searching anyone talking to us while True: try: mentions = sbird.search(q='@SpeakingSecret', since_id=last_id_replied)['results'] if not mentions: print "No one talking to us now...", time.ctime() for mention in mentions: #cut our @SpeakingSecret out message = mention['text'].replace('@SpeakingSecret' , '') speaker = mention['from_user'] speaker_id = str(mention['id']) print "[+] Something named "+speaker+" is saying "+message clever_response = cbot.Ask(message) reply = '@%s %s' % (speaker, clever_response) print "[+] Replying " , reply pbird.statuses.update(status=reply) #update last_id_replied
print '###### args = ', sys.argv if len(sys.argv) > 1: last_id_replied = sys.argv[1] doctor = eliza.eliza() poster = Twitter( auth=OAuth( oauth_token, oauth_token_secret, CONSUMER_KEY, CONSUMER_SECRET), secure=True, api_version='1', domain='api.twitter.com') while True: results = twitter.search(q="@the_shrinkbot", since_id=last_id_replied)['results'] if not results: print 'No results this time...' for result in results: # Remove my name from the question. question = result['text'].replace('@the_shrinkbot', '') asker = result['from_user'] id = str(result['id']) print " <<< " + asker + ": " + question doctor_response = doctor.respond(question.strip()) # We append part of the ID to avoid duplicates. msg = '@%s %s (%s)' % (asker, doctor_response, id[-4:]) print '====> Resp = %s' % msg