def buscador(q, excep): twitter = Twython() query = q # tweets = twitter.searchTwitter(q = query, rpp = "100", page = "1") tweets = twitter.searchTwitter(q=query, rpp="100") lista_tweets = [] for tweet in tweets["results"]: if tweet["text"].encode("utf-8").find(excep) < 0: contenido = tweet["text"].encode("utf-8") usuario = tweet["from_user"].encode("utf-8") hora = tweet["created_at"] hora_convert = datetime.strptime(hora, "%a, %d %b %Y %H:%M:%S +0000") horaColombia = hora_convert - timedelta(minutes=300) objetoTweet = ObjTwitter(usuario=usuario, mensaje=contenido, timestamp=horaColombia) objetoTweet.avatar = tweet["profile_image_url"].encode("utf-8") lista_tweets.append(objetoTweet) return lista_tweets
def twittertag_query(self, tag): t_api = Twython() htmlentities = dict( map(lambda (key, value): ('&' + str(key) + ';', value), htmlentitydefs.entitydefs.items()) ) try: result = t_api.searchTwitter(q=tag, rpp='1')['results'][0] unitext = result['text'] author = result['from_user'] msg = author + ': ' + saxutils.unescape( unitext.encode("utf-8"), htmlentities) msg = msg.replace('\n', ' ') self.connection.notice(channel, msg) except (TwythonError, IndexError, urllib2.HTTPError, urllib2.URLError, UnicodeDecodeError) as e: print 'exception while searching for tag: ' + tag print type(e) print e
def twitteruser_query(self, user, search): t_api = Twython() htmlentities = dict( map(lambda (key, value): ('&' + str(key) + ';', value), htmlentitydefs.entitydefs.items()) ) try: unitext = '' if search != None: query = search + ' from:' + user tweetlist = t_api.searchTwitter(q=query, rpp='1') if len(tweetlist['results']) > 0: unitext = tweetlist['results'][0]['text'] # else: # tweetlist = t_api.getUserTimeline(screen_name=user, # count='200', # page='1') # for tweet in tweetlist: # if tweet['text'].lower().find( # search.lower()) > -1: # unitext = tweet['text'] # break else: tweetlist = t_api.getUserTimeline(screen_name=user, count='1') unitext = tweetlist[0]['text'] if len(unitext) > 0: msg = user + ': ' msg = msg + saxutils.unescape( unitext.encode("utf-8"), htmlentities) msg = msg.replace('\n', ' ') self.connection.notice(channel, msg) except (TwythonError, IndexError, KeyError, urllib2.HTTPError, urllib2.URLError) as e: print 'exception while retrieving user: ' + user print type(e) print e
def query(): """ Retrieve the most recent tweets """ t = Twython() # Search twitter for recent tweets containing any letter in the latin alphabet biglist = [] countdown = [5,4,3,2,1] # Get 7 pages of tweets for x in countdown: search = t.search(q="a+OR+b+OR+c+OR+d+OR+e+OR+f+OR+g+OR+h+OR+i+OR+j+OR+k+OR+l+OR+m+OR+n+OR+o+OR+p+OR+q+OR+r+OR+s+OR+t+OR+u+OR+v+OR+w+OR+x+OR+y+OR+z",rpp=30, result_type = "mixed" ,page = x) search = search['results'] englishlist = [] # Filter results to only english tweets # Note: average English tweets on a page is around 18 for i in search: if i['iso_language_code'] == 'en': # If the tweet is english englishlist.append(i) # add the tweet biglist.extend(englishlist) # don't want individual lists in a list; we want one big list texts = [] for i in biglist: texts.append(i['text'].lower() + '\n\n') texts = ' '.join(texts) return texts
def test_login(self): if not os.path.isfile(os.path.join(self.basepath, 'keys.txt')): return with open(os.path.join(self.basepath, 'keys.txt')) as f: data = f.readlines() self.oauth_data = {} for d in data: key, value = d.split('=', 1) self.oauth_data[key] = value.rstrip('\n') try: self.t = Twython(command.konsumer_ceys[0], command.konsumer_ceys[1], self.oauth_data['oauth_token'], self.oauth_data['oauth_token_secret']) self.user = self.t.verifyCredentials() except TwythonError: self.t = None
class MainHandler: palette = [ ('status', 'white,bold', 'dark gray'), ('error', 'dark red,bold', 'black'), ('info', 'white,bold', 'default'), ] def __init__(self): global command_handler command_handler = command.CommandHandler(self) self.t = None if os.environ['XDG_CONFIG_HOME']: path = os.environ['XDG_CONFIG_HOME'] else: path = os.environ['HOME'] self.basepath = os.path.join(path, 'twiclr') if not os.path.isdir(self.basepath): os.mkdir(self.basepath) self.test_login() def run(self): self.screen = urwid.raw_display.Screen() self.screen.tty_signal_keys(*['undefined'] * 5) self.footer = { 'edit': EditHandler(), 'error': urwid.Text(('error', '')), 'list': urwid.ListBox(urwid.SimpleListWalker([])), } if self.t: msg = _['welcome_login'].format(**self.user) else: msg = _['welcome_guest'] self.body = urwid.SimpleListWalker([ urwid.Text(u'twiclr\nTerminal twitter client.', align='center'), urwid.Text(msg, align='center') ]) self.statusbar = urwid.Text(('status', '')) self.inner = urwid.Frame(urwid.Filler(urwid.Pile(self.body)), footer=urwid.AttrMap(self.statusbar, 'status') ) self.outer = urwid.Frame(self.inner, footer=self.footer['edit']) self.loop = urwid.MainLoop(self.outer, self.palette, self.screen, unhandled_input=self.unhandled_input, handle_mouse=False) self.loop.run() def test_login(self): if not os.path.isfile(os.path.join(self.basepath, 'keys.txt')): return with open(os.path.join(self.basepath, 'keys.txt')) as f: data = f.readlines() self.oauth_data = {} for d in data: key, value = d.split('=', 1) self.oauth_data[key] = value.rstrip('\n') try: self.t = Twython(command.konsumer_ceys[0], command.konsumer_ceys[1], self.oauth_data['oauth_token'], self.oauth_data['oauth_token_secret']) self.user = self.t.verifyCredentials() except TwythonError: self.t = None def unhandled_input(self, key): # Set focus to status-edit if key == ':': self.outer.set_footer(self.footer['edit']) self.footer['edit'].set_caption(':') self.outer.set_focus('footer') elif key == 'esc': self.footer['edit'].set_caption('') self.footer['edit'].set_edit_text('') self.outer.set_focus('body') def error(self, msg): self.footer['error'].set_text(('error', msg)) self.outer.set_footer(self.footer['error']) def show_info(self, msg): self.footer['error'].set_text(('info', msg)) self.outer.set_footer(self.footer['error'])