Loading presentation...
Prezi is an interactive zooming presentation

Present Remotely

Send the link below via email or IM

Copy

Present to your audience

Start remote presentation

  • Invited audience members will follow you as you navigate and present
  • People invited to a presentation do not need a Prezi account
  • This link expires 10 minutes after you close the presentation
  • A maximum of 30 users can follow your presentation
  • Learn more about this feature in our knowledge base article

Do you really want to delete this prezi?

Neither you, nor the coeditors you shared it with will be able to recover it again.

DeleteCancel

Make your likes visible on Facebook?

Connect your Facebook account to Prezi and let your likes appear on your timeline.
You can change this under Settings & Account at any time.

No, thanks

Python & twitter (english)

Creating a python application to talk to Twitter
by

Helio Loureiro

on 27 April 2016

Comments (0)

Please log in to add your comment.

Report abuse

Transcript of Python & twitter (english)

roots
Starting
Homeopathics dosage
Damage control
#FF
Playing a bit more...
Create twitter account
from the beginning...
Python & twitter

Safe searches (respecting limits)...
No all golden stuffs are gold...
Read friends list
Send decision based on: random.randrange()
Limit post to 140 chars
Include some breath: sleep()
https://apps.twitter.com
Creating an application in python that communicates to twitter
About me...
Helio Loureiro
Software developer
Ericsson



Graduated in electrical engineering by UFSC
MBA in IT strategical management by FGV

http://helio.loureiro.eng.br
@helioloureiro
https://prezi.com/user/helioloureiro/
https://github.com/helioloureiro
python-twitter
git clone https://github.com/bear/python-twitter.git

python setup.py build
python setup.py install

pip install python-twitter
Requirements
pip install -r requirements.txt
argparse [1.2.1]
httplib2 [0.7.7]
oauth2 [1.5.211]
wsgiref [0.1.2]
Extra helpful packages
simplejson
feedparser
ConfigParser
import twitter

api = twitter.Api(
consumer_key = 'xxxxx',
consumer_secret = 'yyyyyyyyyyyyyyyyy',
access_token_key = 'zzzzzzzzzzzzzzzzzzzzzzzz',
access_token_secret = 'kkkkkkkkkkkkkkkkkkkkkkkkkkk'
)
api.PostUpdate("python twitter hello world")
>>> users = api.GetFriends()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python2.7/dist-packages/python_twitter-1.0.1-py2.7.egg/twitter.py", line 3200, in GetFriends
data = self._ParseAndCheckTwitter(json)
File "/usr/local/lib/python2.7/dist-packages/python_twitter-1.0.1-py2.7.egg/twitter.py", line 4411, in _ParseAndCheckTwitter
self._CheckForTwitterError(data)
File "/usr/local/lib/python2.7/dist-packages/python_twitter-1.0.1-py2.7.egg/twitter.py", line 4436, in _CheckForTwitterError
raise TwitterError(data['errors'])
twitter.TwitterError: [{u'message': u'Rate limit exceeded', u'code': 88}]
Shit happens....
api.MaximumHitFrequency()

api.GetRateLimitStatus()
Be carefull...
user = api.GetUser()

user = api.GetUser(screen_name = "helioloureiro")

print user
Playing with data
print user.AsDict()

print user.AsDict().keys()

print user.id

print user.screen_name
Reading information...
friends = api.GetFriends()
followers = api.GetFollowers()

friends = api.GetFriends(screen_name = "helioloureiro")


Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python2.7/dist-packages/python_twitter-1.0.1-py2.7.egg/twitter.py", line 3200, in GetFriends
data = self._ParseAndCheckTwitter(json)
File "/usr/local/lib/python2.7/dist-packages/python_twitter-1.0.1-py2.7.egg/twitter.py", line 4411, in _ParseAndCheckTwitter
self._CheckForTwitterError(data)
File "/usr/local/lib/python2.7/dist-packages/python_twitter-1.0.1-py2.7.egg/twitter.py", line 4436, in _CheckForTwitterError
raise TwitterError(data['errors'])
twitter.TwitterError: [{u'message': u'Rate limit exceeded', u'code': 88}]
Damn you, twitter!!!
status = api.GetRateLimitStatus()
status
status.keys()
status['resources'].keys()
status['resources']['friends']
status['resources']['statuses']
Finding the limits
Getting friends or followers
https://github.com/bear/python-twitter/issues/71
result = []
parameters = {}
start_page = 0
cursor = -1
currentPage = start_page
parameters['user_id'] = user.id
parameters['screen_name'] = user.screen_name
parameters['cursor'] = cursor
url = '%s/friends/list.json' % api.base_url


json = api._FetchUrl(url, parameters=parameters)
data = api._ParseAndCheckTwitter(json)

data.keys()

for user in data['users']:
print user['screen_name']
Hard way
cursor
cusor controlls search
Search ends once it has no value (cursor == 0)
Always use cursor in parameters = {}
Cursor usage
cursor = 0

while (cursor):
parameters['cursor'] = cursor
json = api._FetchUrl(url, parameters=parameters)
data = api._ParseAndCheckTwitter(json)
for user in data['users']:
code...
code...
code...
cursor = data['next_cursor']

It verifies limit and searches next or just wait...
tweets = api.GetHomeTimeline()

for t in tweets:
print t.AsDict().keys()


for t in tweets:
print t.user.screen_name, '=>', t.text
Reading timeline
Listing
u_lists = api.GetLists()
h_lists = api.GetLists(screen_name = 'helioloureiro')

for l in h_lists:
print l.AsDict().keys()

for l in h_lists:
print l.name, l.slug, l.id, l.member_count
Mentions
mentions = api.GetMentions()

for m in mentions:
print m.AsDict().keys()

for m in mentions:
print m.user.screen_name, '=>', m.text
Replies
replies = api.GetReplies()

for r in replies:
print r.user.screen_name, '=>', r.text
My retweets (RT)
retweet = api.GetRetweetsOfMe()

for r in retweet:
print r.user.screen_name, '=>', r.text, '=>', r.retweeted, '=>', [u.screen_name for u in r.user_mentions], '=>', [t.text for t in r.hashtags]
Searching by patterns
search = api.GetSearch(term = "ericsson")

for b in search:
print b.user.screen_name,'=>', b.created_at, '=>', b.text
Getting trends
trends = api.GetTrendsCurrent()

for t in trends:
print t.name

trends = api.GetTrendsWoeid(id)

for t in trends:
print t.name
Yahoo! Where On Earth ID
woeid = 906057 (Stockholm, SE)

trends_sthml = api.GetTrendsWoeid(906057)
WOEID = Where On Earth ID
http://developer.yahoo.com/geo/geoplanet/guide/concepts.html
http://isithackday.com/geoplanet-explorer/index.php
python-twitter 1.0.1
Requirements
pip install python-twitter
argparse [1.2.1]
httplib2 [0.7.7]
oauth2 [1.5.211]
wsgiref [0.1.2]
python-twitter 1.1
http://helio.loureiro.eng.br/pyconse.txt
import twitter
import ConfigParser

cfg = ConfigParser.ConfigParser()
cfg.read("pyconse.txt")

api = twitter.Api(
consumer_key = cfg.get("tw", "ck"),
consumer_secret = cfg.get("tw", "cs"),
access_token_key = cfg.get("tw", "ak"),
access_token_secret = cfg.get("tw", "as")
)
api.PostUpdate("python twitter hello world")
Testing api 294
Testing api 295
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
File "/usr/local/lib/python2.7/dist-packages/twitter/api.py", line 887, in PostUpdate
data = self._ParseAndCheckTwitter(json.content)
File "/usr/local/lib/python2.7/dist-packages/twitter/api.py", line 3530, in _ParseAndCheckTwitter
self._CheckForTwitterError(data)
File "/usr/local/lib/python2.7/dist-packages/twitter/api.py", line 3557, in _CheckForTwitterError
raise TwitterError(data['errors'])
twitter.error.TwitterError: [{u'message': u'User is over daily status update limit.', u'code': 185}]

#Pictures
Post w/ pictures from webcam or static jpg
Use api.PostMedia()
Use pydoc twitter.Api.PostMedia
Don't forget hashtag #pyconse
#reading webcam
import pygame
import pygame.camera

pygame.init()
pygame.camera.init()
cam = pygame.camera.Camera("/dev/video0", (1280, 720))
cam.start()
img = cam.get_image()
cam.stop()
pygame.image.save(img, "snapshot.jpg")
twitter.Api.lists.members(owner_screen_name="helioloureiro", slug="python")
Full transcript