Pablo
Posts: 34
Joined: Wed Aug 15, 2012 2:37 pm

writing my own twitter client

Tue Aug 21, 2012 5:56 pm

I'm learning python and, to do that, I'm trying to write a simple twitter client. I tried to understand tweebot, but it was impossible for me.

I can send tuits, but my mentions.py fails. I'm trying to write mentions to a file to reply them from another module that I will write later.

Code: Select all

#!/usr/bin/env python
import sys
import tweepy

CONSUMER_KEY = '-'
CONSUMER_SECRET = '-'
ACCESS_KEY = '-'
ACCESS_SECRET = '-'

auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
auth.set_access_token(ACCESS_KEY, ACCESS_SECRET)
api = tweepy.API(auth)
api.mentions()
http://packages.python.org/tweepy/html/ ... pi-wrapper

API.mentions()

Returns the 20 most recent mentions (status containing @username) for the authenticating user.

Parameters: since_id, max_id, count, page

Returns: list of class:Status objects
how can I write them on the command line and/or into a file?

:)

Pablo
Posts: 34
Joined: Wed Aug 15, 2012 2:37 pm

Re: writing my own twitter client

Tue Aug 21, 2012 7:30 pm

I have to edit with a reply because I can't find an 'edit button'.

I forgot to post an example.

If I try with

Code: Select all

auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
auth.set_access_token(ACCESS_KEY, ACCESS_SECRET)
api = tweepy.API(auth)



print api.mentions()

I get

[<tweepy.models.Status object at 0x8cc2f4c>, <tweepy.models.Status object at 0x8cc2f6c>, <tweepy.models.Status object at 0x8cdbc8c>, <tweepy.models.Status object at 0x8cdbd0c>, <tweepy.models.Status object at 0x8cdbf2c>, <tweepy.models.Status object at 0x8cdbfac>]

The total number of mentions is six, that's right. But I can't understand that output.

Pablo
Posts: 34
Joined: Wed Aug 15, 2012 2:37 pm

Re: writing my own twitter client

Tue Aug 21, 2012 11:43 pm

A friend gave me the key:
for mentions in api.mentions():
print "\n" + mentions.text[/code]

But I have now another trouble. How can I separate tuits to answer them one by one?

My next objective is to make an script to auto-answer mentions. To do that, I will need to know what tweet is new and which was already answered.

User avatar
stevo_300
Posts: 33
Joined: Thu Jan 26, 2012 9:38 am
Contact: Website

Re: writing my own twitter client

Thu Aug 23, 2012 8:42 am

I've been looking at twitter in python to.

Each tweet has a unique id for example:

Code: Select all

#creating the oAuth handler
auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
#setting the access keys
auth.set_access_token(ACCESS_KEY, ACCESS_SECRET)
#loading the oAuth handler into the twitter api to connect to the account.
api = tweepy.API(auth)
#getting an array of tweets that are mentions
tweets = api.mentions()
#for every tweet
for t in tweets:
	#print the tweet ID
	print t.id
if you do something like:

Code: Select all

for t in tweets:
	#print the tweet options
	print dir(t)
you can see what is inside each tweet

User avatar
stevo_300
Posts: 33
Joined: Thu Jan 26, 2012 9:38 am
Contact: Website

Re: writing my own twitter client

Thu Aug 23, 2012 8:44 am

in terms of the already answered part, you could write a log file that has the ID of the tweet in. If it is present in this list, then you will have replied to it. if not then it is new.

Pablo
Posts: 34
Joined: Wed Aug 15, 2012 2:37 pm

Re: writing my own twitter client

Thu Aug 23, 2012 8:50 am

@stevo_300: Amazing!! I can't work on it now. I'll try that later. Thank you, man!

User avatar
stevo_300
Posts: 33
Joined: Thu Jan 26, 2012 9:38 am
Contact: Website

Re: writing my own twitter client

Thu Aug 23, 2012 8:57 am

no problem, we're all in this together :)

Pablo
Posts: 34
Joined: Wed Aug 15, 2012 2:37 pm

Re: writing my own twitter client

Thu Aug 23, 2012 10:29 am

I Can't get the author.

Code: Select all

tweets = api.mentions()
#for every tweet
for t in tweets:
   #print the tweet ID, time, author, tweet
   print t.id , t.created_at , t.user, ": " , t.text
t.user is not working properly. See a tweet as an example.

237103647526379520 2012-08-19 08:28:09 <tweepy.models.User object at 0x8d2dd2c> : @RasPiPablo "@fotochismes: Bricolaje de alto riesgo y pero de alta potencia con una empuñadura de una 5D Mark II http://t.co/V2NBWvlA"

I tried almost every opcion. Is something wrong?


Edit: Can I answer a tweet from it ID? I'm trying that also, but I can make it work.

User avatar
stevo_300
Posts: 33
Joined: Thu Jan 26, 2012 9:38 am
Contact: Website

Re: writing my own twitter client

Thu Aug 23, 2012 11:41 am

the author is: t.author.screen_name

do a print dir(t.author) as there are multiple options.

I haven't tried the reply parts of the API so cant offer too much help there i'm afraid

User avatar
stevo_300
Posts: 33
Joined: Thu Jan 26, 2012 9:38 am
Contact: Website

Re: writing my own twitter client

Thu Aug 23, 2012 11:42 am

also based on that print result doing a dir(t.user) will offer you options in regards to the user object.

Pablo
Posts: 34
Joined: Wed Aug 15, 2012 2:37 pm

Re: writing my own twitter client

Thu Aug 23, 2012 5:54 pm

I found something great! http://inventwithpython.com/blog/2012/0 ... dreamhost/

Code: Select all

API.update_status()

Update the authenticated user’s status. Statuses that are duplicates or too long will be silently ignored.

Parameters: status (Required), in_reply_to_status_id, lat, long

Returns: class:Status object

But when trying to mix it up with my code, I got errors that I don't know how to fix

My mixed code is:

Code: Select all

#!/usr/bin/env python

import sys
import tweepy
import time


sys.path = ['/home/lagarto/Documentos/Code']

import os
os.chdir('/home/lagarto/Documentos/Code')

CONSUMER_KEY = 'x'
CONSUMER_SECRET = 'x'
ACCESS_KEY = 'x'
ACCESS_SECRET = 'x'



auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
auth.set_access_token(ACCESS_KEY, ACCESS_SECRET)
api = tweepy.API(auth)



LATESTFILE = 'Base_latest.txt'
LOGFILE = 'Base_log.txt'




if os.path.exists(LATESTFILE):
    fp = open(LATESTFILE)
    lastid = fp.read().strip()
    fp.close()

    if lastid == '':
        lastid = 0
else:
    lastid = 0

# read in the file of users we've already responded to
fp = open(LOGFILE)
alreadyMessaged = fp.readlines()
fp.close()
for i in range(len(alreadyMessaged)):
    if alreadyMessaged[i].strip() == '':
        continue

    alreadyMessaged[i] = alreadyMessaged[i].split('|')[1]
alreadyMessaged.append('RasPiPablo') # don't reply to myself

"""

results = api.mentions(since_id=lastid)
#print 'Found %s results.' % (len(results))
if len(results) == 0:
    #print 'Nothing to reply to. Quitting.'
    sys.exit()
repliedTo = []



for statusObj in results:
    postTime = time.mktime(time.strptime(statusObj.created_at[:-6], '%a, %d %b %Y %H:%M:%S'))

    if time.time() - (24*60*60) < postTime and statusObj.user.screen_name not in alreadyMessaged and '@RasPiPablo' not in statusObj.text.lower():
        if [True for x in alreadyMessaged if ('@' + x).lower() in statusObj.text.lower()]:
            #print 'Skipping because it\'s a mention: @%s - %s' % (statusObj.user.screen_name.encode('ascii', 'replace'), statusObj.text.encode('ascii', 'replace'))
            continue

        try:
            #print 'Posting in reply to @%s: %s' % (statusObj.user.screen_name.encode('ascii', 'replace'), statusObj.text.encode('ascii', 'replace'))
            api.update_status('TEMPLATES' % (statusObj.user.screen_name), in_reply_to_status_id=statusObj.id)
            repliedTo.append( (statusObj.id, statusObj.user.screen_name, statusObj.text.encode('ascii', 'replace')) )
            time.sleep(1)
        except Exception:
            print "Unexpected error:", sys.exc_info()[0:2]


fp = open(LATESTFILE, 'w')
fp.write(str(max([x.id for x in results])))
fp.close()

fp = open(LOGFILE, 'a')
fp.write('\n'.join(['%s|%s|%s' % (x[0], x[1], x[2]) for x in repliedTo]) + '\n')
fp.write('\n')
fp.close()

and the errors:

Code: Select all

./respuesta.py 
Traceback (most recent call last):
  File "./respuesta.py", line 76, in <module>
    results = api.mentions(since_id=lastid)
  File "/usr/lib/python2.7/dist-packages/tweepy/binder.py", line 179, in _call
    return method.execute()
  File "/usr/lib/python2.7/dist-packages/tweepy/binder.py", line 162, in execute
    raise TweepError(error_msg, resp)
tweepy.error.TweepError: Error in 'since_id' parameter: invalid id.
Error in sys.excepthook:
Traceback (most recent call last):
  File "/usr/lib/python2.7/dist-packages/apport_python_hook.py", line 64, in apport_excepthook
    from apport.fileutils import likely_packaged, get_recent_crashes
ImportError: No module named apport.fileutils

Original exception was:
Traceback (most recent call last):
  File "./respuesta.py", line 76, in <module>
    results = api.mentions(since_id=lastid)
  File "/usr/lib/python2.7/dist-packages/tweepy/binder.py", line 179, in _call
    return method.execute()
  File "/usr/lib/python2.7/dist-packages/tweepy/binder.py", line 162, in execute
    raise TweepError(error_msg, resp)
tweepy.error.TweepError: Error in 'since_id' parameter: invalid id.

User avatar
LetHopeItsSnowing
Posts: 357
Joined: Sat May 26, 2012 6:40 am
Location: UK
Contact: Website

Re: writing my own twitter client

Sun Oct 28, 2012 6:16 pm

Hi,

Slightly off topic, but you might find it easier to use twitter streams for receiving your incoming tweets, i have written a talking twitter client which uses twitter streams and text to speech to output tweets to audio. Its only a proof of concept but it might give you some useful code and functions.

http://www.raspberrypi.org/phpBB3/viewt ... 59#p203959

LHIS
"am I getting slower, or is stuff more complicated; either way I now have to write it down - stuffaboutcode.com"

Return to “Python”