lhonda avatar lhonda committed 53eee52

versao apresentavel de Comofas?

Comments (0)

Files changed (4)

+Hi,
+
+You, fellow developer, might want to run comofas2.py and test.py
+
+comofas2.py creates a Comofas class and its purpose is to provide an (good/funny,weird) answer for all questions
+tagged by comofas.
+
+Please visit:
+
+http://www.pedrovalente.com
+
+Have fun  using comofas in twitter.com
+
+[]s
+lhonda
+
+
+
+Pedro, please rewrite this README. I'm not good @ it.
+
+LICENSE: Pedro, please choose one. 
 import re
 import simplejson
 import time
+import sys
+import logging
+import pickle
+import os
+
 from twitter import twitter
 from comofas_credentials import *
+from comofas_settings import *
 
 class Comofas(object):
     """
         self.twitter_connection = twitter_connection
         self.twitter_connection.SetXTwitterHeaders('fasassim',"http://twitter.com/fasassim",'Ni!')
         self.answers_connection = answers_connection
-        self.search_url='http://search.twitter.com/search.json?q=comofas'
+        self.search_url = 'http://search.twitter.com/search.json?q=' + KEYWORD
+        self.last_feeds = dict()
+        self.last_users = dict()
+
+        logging.basicConfig(filename=LOG_FILENAME,level=logging.DEBUG,)
+
+        if PICKLE_FILENAME in os.listdir('.'):
+            self.picklefd = open(PICKLE_FILENAME)
+            try:
+                self.last_feeds = pickle.load(self.picklefd)
+            except EOFError:
+                self.last_feeds = dict()
+        else:
+            self.picklefd =open(PICKLE_FILENAME,'wb')
+            pickle.dump(self.last_feeds,self.picklefd)
+            self.picklefd.close()
+            self.picklefd =open(PICKLE_FILENAME,'wb')
+            self.last_feeds = pickle.load(self.picklefd)
 
     def get_last_feed(self):
         """
         """
         Este metodo retorna todos os resultados, sem filtrar por text e from_user
         """
-        feed = urllib.urlopen('http://search.twitter.com/search.json?q=comofas')
+        feed = urllib.urlopen('http://search.twitter.com/search.json?q=' + KEYWORD)
         updates = feed.read()
         updates = simplejson.loads(updates)
 
         pergunta = re.sub('#\w+',' ', txt)
         pergunta = re.sub('@\w+',' ', pergunta)
 
-        pergunta = pergunta.replace('comofas',' ')
+        pergunta = pergunta.replace(KEYWORD,' ')
         s=string.find(pergunta,'http://')
         if s != -1:
             t = string.find(pergunta[s+7:], " ")
         mensagem = self.build_message(to_user=usuario, raw_answer=nao_entendi[random.randint(0,len(nao_entendi)-1)])
         status = self.twitter_connection.PostUpdate(mensagem)
         print '-' * 50
-        print "twitter.fasassim(nao entendi) postUpdate: %s" % mensagem
+        print "twitter.fasassim(nao entendi) postUpdate: %s - status:%s" % (mensagem,status)
 
     def build_message(self,to_user, raw_answer):
         """
             a.pop(-1)
         return "%s%s" % (msg, " ".join(a))
 
+    def add_new_friends(self):
+        added_friends = self.twitter_connection.GetFriends()
 
-def old_main():
-    """
-    este eh o antigo comofas funcional
-    """
+        for friend in added_friends:
+            if not self.last_users.has_key(friend.name) and friend.name != 'fasassim':
+                self.twitter_connection.CreateFriendship(friend)
+                print "twitter.fasassim.following %s" % friend.name
+                self.last_users.pop(friend.name)
+        self.last_users = dict()
+
+
+    def answer_tweets(self):
+        """
+        este metodo busca os feeds do twitter, limpa o texto e processa a resposta para cada feed
+        ele nao foi testado e deve ser refatorado p/ dividir as responsabilidades
+
+        twitter keys:
+        [u'iso_language_code',
+     u'text',
+     u'created_at',
+     u'profile_image_url',
+     u'from_user',
+     u'from_user_id',
+     u'to_user_id',
+     u'id']
+
+        twitter user methods:
+        AsDict
+    AsJsonString
+    GetDescription
+    GetId
+    GetLocation
+    GetName
+    GetProfileImageUrl
+    GetScreenName
+    GetStatus
+    GetUrl
+    NewFromJsonDict
+    SetDescription
+    SetId
+    SetLocation
+    SetName
+    SetProfileImageUrl
+    SetScreenName
+    SetStatus
+    SetUrl
+        """
+        try:
+            while (True):
+                time.sleep(random.randint(15,30)*2)
+                feeds = self.get_feeds()
+
+                for feed in feeds:
+                    if feed.get('id') in self.last_feeds:
+                        continue
+                    else:
+
+                        usuario = feed.get('from_user')
+                        pergunta = feed.get('text')
+                        self.last_users[usuario] = 1
+
+                        pergunta = self.clean_text(pergunta)
+
+                        try:
+                            answers_for_questions = answers.questionSearch({'query':pergunta, 'search_in':'question', 'region': REGION, 'type':'resolved', 'results':'1'})
+                        except:
+                            logging.debug("answer exception:" + sys.exc_info()[1])
+                            continue
+
+                        if len(self.last_users) == LAST_USERS_SIZE:
+                            self.add_new_friends()
+
+                        if answers_for_questions:
+                            for question in answers_for_questions:
+                                try:
+                                    print '-'* 50
+                                    print "Twitter: %s\nPergunta: %s \n\n" % (pergunta, question['Subject'])
+
+                                    mensagem = self.build_message(to_user=usuario, raw_answer=question['ChosenAnswer'])
+                                    meu_timeline =self.twitter_connection.GetUserTimeline(TWITTER_USERNAME)
+
+                                    for msg in meu_timeline:
+                                        if mensagem == msg.text:
+                                            continue
+
+                                    print '-' * 50
+                                    print "twitter.fasassim postUpdate: %s" % mensagem
+
+                                    status = self.twitter_connection.PostUpdate(mensagem)
+                                    self.last_feeds[feed.get('id')] = feed
+                                except UnicodeEncodeError:
+                                    continue
+                        else:
+                            logging.debug("Nao entendi:" + pergunta)
+                            self.nao_entendi(usuario)
+        except KeyboardInterrupt:
+            # TODO: testar como faz o pickle gravar direito o self.last_feeds
+            pickle.dump(self.last_feeds,self.picklefd)
+            self.picklefd.close()
+            sys.exit(1)
+
+
+
+if __name__=='__main__':
     answers = Answers()
     answers.appid = answers_appid
 
-    twitter_api = twitter.Api(username=twitter_username, password=twitter_password)
-
-    comofas =Comofas(twitter_api)
-    ultimos_usuarios={}
-    ultima_pergunta=''
-
-    while (True):
-        time.sleep(random.randint(15,30)*2)
-        (pergunta,usuario) = comofas.get_last_feed()
-
-        follow_counter=0
-
-        ultimos_usuarios[usuario]=1
-
-        if ultima_pergunta == pergunta:
-            continue
-        else:
-            ultima_pergunta = pergunta
-            pergunta = comofas.clean_text(pergunta)
-
-            try:
-                questions = answers.questionSearch({'query':pergunta, 'search_in':'question', 'region': 'br', 'type':'resolved', 'results':'1'})
-            except:
-                continue
-
-            follow_counter = follow_counter + 1
-
-            if follow_counter==5:
-                follow_counter = 0
-                added_friends = twitter_api.GetFriends()
-
-                for friend in added_friends:
-                    if not ultimos_usuarios.has_key(friend.name) and usuario != 'fasassim':
-                        twitter_api.CreateFriendship(friend)
-                        print "twitter.fasassim.following %s" % friend.name
-                        ultimos_usuarios.pop(friend.name)
-                ultimos_usuarios={}
-
-            if questions:
-                for question in questions:
-                    try:
-                        print '-'* 50
-                        print "Twitter: %s\nPergunta: %s \n\n" % (pergunta, question['Subject'])
-                        mensagem = comofas.build_message(to_user=usuario, raw_answer=question['ChosenAnswer'])
-                        meu_timeline = twitter_api.GetUserTimeline(twitter_username)
-                        if mensagem == meu_timeline[0].text:
-                            ultima_pergunta = pergunta
-                            continue
-
-                        print '-' * 50
-                        print "twitter.fasassim postUpdate: %s" % mensagem
-                        status = comofas.twitter_connection.PostUpdate(mensagem)
-                        ultimos_usuarios[usuario]=1
-                    except UnicodeEncodeError:
-                        continue
-            else:
-                #nao_entendi(usuario)
-                pass
-
-
-def run_comofas():
-    """
-    este metodo busca os feeds do twitter, limpa o texto e processa a resposta para cada feed
-    ele nao foi testado e deve ser refatorado p/ dividir as responsabilidades
-
-    twitter keys:
-    [u'iso_language_code',
- u'text',
- u'created_at',
- u'profile_image_url',
- u'from_user',
- u'from_user_id',
- u'to_user_id',
- u'id']
-    """
-    answers = Answers()
-    answers.appid = 'GwZLVv32'
-
-    twitter_api = twitter.Api(username=twitter_username, password=twitter_password)
+    twitter_api = twitter.Api(username=TWITTER_USERNAME, password=TWITTER_PASSWORD)
     twitter_api.SetXTwitterHeaders('fasassim',"http://twitter.com/fasassim",'Ni!')
 
-    comofas =Comofas(twitter_connection = twitter_api,answers_connection = answers)
-    last_users=dict()
-
-    follow_counter=0
-
-    while (True):
-        time.sleep(random.randint(15,30)*2)
-        feeds = comofas.get_feeds()
-
-
-        last_feeds=dict()
-        for feed in feeds:
-            if not last_feeds.has_key(feed.get('id')):
-                last_feeds[feed.get('id')] = feed
-
-            usuario = feed.get('from_user')
-            pergunta = feed.get('text')
-            last_users[usuario]=1
-
-            pergunta = comofas.clean_text(pergunta)
-
-            try:
-                questions = answers.questionSearch({'query':pergunta, 'search_in':'question', 'region': 'br', 'type':'resolved', 'results':'1'})
-            except:
-                continue
-
-            follow_counter = follow_counter + 1
-
-            if follow_counter==5:
-                follow_counter = 0
-                added_friends = comofas.twitter_connection.GetFriends()
-
-                for friend in added_friends:
-                    if not last_users.has_key(friend.name) and usuario != 'fasassim':
-                        twitter_api.CreateFriendship(friend)
-                        print "twitter.fasassim.following %s" % friend.name
-                        last_users.pop(friend.name)
-                last_users=dict()
-
-            if questions:
-                for question in questions:
-                    try:
-                        print '-'* 50
-                        print "Twitter: %s\nPergunta: %s \n\n" % (pergunta, question['Subject'])
-                        mensagem = comofas.build_message(to_user=usuario, raw_answer=question['ChosenAnswer'])
-                        meu_timeline = twitter_api.GetUserTimeline(twitter_username)
-                        if mensagem == meu_timeline[0].text:
-                            ultima_pergunta = pergunta
-                            continue
-
-                        print '-' * 50
-                        print "twitter.fasassim postUpdate: %s" % mensagem
-                        status = comofas.twitter_connection.PostUpdate(mensagem)
-                        last_users[usuario]=1
-                    except UnicodeEncodeError:
-                        continue
-            else:
-                #nao_entendi(usuario)
-                pass
-
-
-if __name__=='__main__':
-    old_main()
-    #run_comofas()
+    comofas2 = Comofas(twitter_connection = twitter_api,answers_connection = answers)
+    comofas2.answer_tweets()

comofas_settings.py

+REGION='br'
+KEYWORD='pythontest'
+
+LOG_FILENAME='logging.out'
+
+PICKLE_FILENAME = 'comofas.persistence'
+
+# dicionario com os ultimos users que postaram comofas
+# usado para fazer follow de novos usuarios
+LAST_USERS_SIZE=5
+
+TWITTER_USERNAME = 'fasassim'
+TWITTER_PASSWORD = 'abc123'
 # -*- coding: utf-8 -*-
 
 import unittest
-from comofas import Comofas
+from comofas2 import Comofas
 from pynswers.Answers import Answers
 import twitter
 from comofas_credentials import *
 
+class AnswerProtocol(object):
+    def questionSearch(self,**kws):
+        resps = list()
+        resp = dict()
+        resp["ChosenAnswer"] = "Por mas que se tente ficar ileso aos erros inerentes os atos politicos, algum projetil vai ser enderecado ao seu alvo."
+        resps.append(resp)
+
+        return resps
+
+class TwitterProtocol(object):
+
+    def PostUpdate(self,mensagem):
+        return "ok"
+
 class TestComofas(unittest.TestCase):
 
     def setUp(self):
-        answers = Answers()
-        answers.appid = answers_appid
+        pass
 
-        twitter_api = twitter.Api(username=twitter_username, password=twitter_password)
-        twitter_api.SetXTwitterHeaders('fasassim',"http://twitter.com/fasassim",'Ni!')
-
-        self.comofas = Comofas(twitter_connection = twitter_api,answers_connection = answers)
-
-    def test_get_last_feed(self):
-        res = self.comofas.get_last_feed()
-        self.assertTrue(len(res) > 0)
-
-    def test_clean_text(self):
-        msg='@comofas para manter  sanidade mental dos incansaveis doidos?'
-        res = self.comofas.clean_text(msg)
-        self.assertEqual(res,u'para OR mantersanidade OR mental OR dos OR incansaveis OR doidos')
-
-    def test_build_message(self):
-    	res = self.comofas.build_message('pvalente',"voce pode abrir a lata com aquele tijolo que deixei na cozinha, pois a revolta dos designers direciona a energia positiva pela Dutra.")
-    	self.assertTrue(len(res)<=140)
 
 if __name__ == '__main__':
     unittest.main()
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.