- First of all go to TWITTER and log in to your account.
- Follow the below pictures to create a new app.
- Now you need to go to TWITTER DEVELOPER'S PAGE and follow the instructions below.
So long. Take some tea or coffee break !!
################################################################################
INSTALLATION INSTRUCTIONS AND LINKS FOR pip AND twitter version 1.16.0 OR LOWER .
################################################################################
NOTE: YOU NEED TO USE COMMAND PROMPT (ON WINDOWS) AND TERMINAL (ON LINUX AND MAC) WITH ADMIN PRIVILEGE FOR INSTALLING PIP AND TWITTER API.
For Linux (yum and apt based):
1. yum install python-pip python3-pip
or
sudo apt-get install python-pip python3-pip
For Windows click me
For Mac OS click me
OR
FOLLOW THIS PIP INSTALLATION GUIDE (CLICK ME)
2. pip install twitter
3. pip3 install twitter
################################################################################
Script for python-2.7.x (tested using python-2.7.8) :
################################################################################
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 | import twitter as t import urllib2 as ur import time CONSUMER_KEY = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' # Same as API key CONSUMER_SECRET = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' # Same as API secret ACCESS_TOKEN_KEY= 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' ACCESS_TOKEN_SECRET= 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' ''' This function updates the status of my twitter account requires twitter python module ''' def tweet(status_msg): if len(status_msg) > 140 : raise Exception ('Status message too long !!!') else: authkey = t.Twitter(auth=t.OAuth(ACCESS_TOKEN_KEY, ACCESS_TOKEN_SECRET, CONSUMER_KEY, CONSUMER_SECRET)) result = authkey.statuses.update(status=status_msg) return result ''' This function get the coffee price (both below a desired price and in emergency; the current price) ''' def get_price(page): text = page.read().decode("utf8") ss_pos = text.find('>$') soss = ss_pos + 2 eoss = soss + 4 return float(text[soss:eoss]) ''' main program requires urllib.request requires time library also. ''' print ("Welcome to Starbuzz Coffee price checking program") choice = raw_input ("Do You want to know the coffee price immediately ?? (y/n) : ") if choice == "y": page = ur.urlopen("http://beans.itcarlow.ie/prices.html") price = get_price(page) status_msg = "@starbuzzceo\nCurrent price of coffee = $" + str(price) res = tweet(status_msg) else : price =99.99 while price > 4.74 : time.sleep(10) page = ur.urlopen("http://beans.itcarlow.ie/prices-loyalty.html") price = get_price(page) status_msg = "@starbuzzceo\nCurrent price of coffee is $" + str(price) + "; BUY !!!" res = tweet(status_msg) if res != None: print ("tweeted coffee price successfully to Starbuzz CEO") else: print ("problem !!") |
################################################################################
Script for python-3.x (tested using python-3.4.1) :
################################################################################
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 | import twitter as t import urllib.request as ur import time CONSUMER_KEY = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' # Same as API key CONSUMER_SECRET = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' # Same as API secret ACCESS_TOKEN_KEY= 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' ACCESS_TOKEN_SECRET= 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' ''' This function updates the status of my twitter account requires twitter python module ''' def tweet(status_msg): if len(status_msg) > 140 : raise Exception ('Status message too long !!!') else: authkey = t.Twitter(auth=t.OAuth(ACCESS_TOKEN_KEY, ACCESS_TOKEN_SECRET, CONSUMER_KEY, CONSUMER_SECRET)) result = authkey.statuses.update(status=status_msg) return result ''' This function get the coffee price (both below a desired price and in emergency; the current price) ''' def get_price(page): text = page.read().decode("utf8") ss_pos = text.find('>$') soss = ss_pos + 2 eoss = soss + 4 return float(text[soss:eoss]) ''' main program requires urllib.request requires time library also. ''' print ("Welcome to Starbuzz Coffee price checking program") choice = input ("Do You want to know the coffee price immediately ?? (y/n) : ") if choice == "y": page = ur.urlopen("http://beans.itcarlow.ie/prices.html") price = get_price(page) status_msg = "@starbuzzceo\nCurrent price of coffee = $" + str(price) res = tweet(status_msg) else : price =99.99 while price > 4.74 : time.sleep(10) page = ur.urlopen("http://beans.itcarlow.ie/prices-loyalty.html") price = get_price(page) status_msg = "@starbuzzceo\nCurrent price of coffee is $" + str(price) + "; BUY !!!" res = tweet(status_msg) if res != None: print ("tweeted coffee price successfully to Starbuzz CEO") else: print ("problem !!") |
################################################################################
SCRIPTS FOR PYTHON 2.7.X USING tweepy
################################################################################
Try it yourself for Python 3.X.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 | import tweepy import urllib2 import time CONSUMER_KEY = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'# Same as API key CONSUMER_SECRET = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'# Same as API secret ACCESS_TOKEN_KEY= 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' ACCESS_TOKEN_SECRET= 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' ''' This below function updates the status of my twitter account requires tweepy ''' def tweet(status): if len(status) > 140 : raise Exception ('Status message too long !!!') auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET) auth.set_access_token(ACCESS_TOKEN_KEY, ACCESS_TOKEN_SECRET) api = tweepy.API(auth) result = api.update_status(status) return result # I do not feel any need of this though. #it is always good to make a function return something ''' This below function get the coffee price (both below a desired price and in emergency; the current price) ''' def get_price(page): text = page.read().decode("utf8") ss_pos = text.find('>$') soss = ss_pos + 2 eoss = soss + 4 return float(text[soss:eoss]) ''' main program requires urllib2 (incase of python 2.7.x series) requires time library also. ''' print ("Welcome to Starbuzz Coffee price checking program") choice = raw_input ("Do You want to know the coffee price immediately ?? (y/n) : ") if choice == "y": page_emergency = urllib2.urlopen("http://beans.itcarlow.ie/prices.html") price = get_price(page_emergency) res = tweet("@starbuzzceo\nCurrent price of coffee = $" + str(price)) else : price =99.99 while price > 4.74 : time.sleep(10) page_optimal = urllib2.urlopen("http://beans.itcarlow.ie/prices-loyalty.html") price = get_price(page_optimal) res = tweet("@starbuzzceo\nCurrent price of coffee is $" + str(price) + "; BUY !!!") if res != None: print ("tweeted coffee price successfully to starbuzz ceo") else: print ("problem !!") |
I need some assistance with a portion of this code. I am using the bottom portion for python 3.x
ReplyDeleteI am getting an error message for
line 18 (authkey = t.twitter(auth=t.OAuth(etc))
line 42 (res = tweet(status_msg))
The error message says "AttributeError: 'module' object has no attribute 'twitter'"
If you could help me in correcting this error it would be greatly appreciated. Thank you
LOOK AT THE ERROR
ReplyDeletePYTHON 3.X IS TELLING THAT IT HAS NO SUCH ATTRIBUTE AS "twitter". RATHER IT HAS THE ATTRIBUTE AS "Twitter".
;-)
I mean to say just change the "t.twitter" to "t.Twitter" in line no 18 of your code.
note:- You must have installed twitter-1.9.0
Hi. I Have problem with your program Could you help me?
ReplyDeleteWelcome to Starbuzz Coffee price checking program
Do You want to know the coffee price immediately ?? (y/n) : y
Traceback (most recent call last):
File "E:\PT\mine\3\190.py", line 31, in
res = tweet(status_msg)
File "E:\PT\mine\3\190.py", line 15, in tweet
result = authkey.statuses.update(status=status_msg)
File "E:\PT\lib\site-packages\twitter-1.9.0-py3.1.egg\twitter\api.py", line 165, in __call__
arg_data = self.auth.encode_params(uriBase, method, kwargs)
File "E:\PT\lib\site-packages\twitter-1.9.0-py3.1.egg\twitter\oauth.py", line 105, in encode_params
enc_params = urlencode_noplus(sorted(params.items()))
File "E:\PT\lib\site-packages\twitter-1.9.0-py3.1.egg\twitter\oauth.py", line 134, in urlencode_noplus
return urlencode(query, safe='~').replace("+", "%20")
TypeError: urlencode() got an unexpected keyword argument 'safe'
Try reinstalling setup-tools if you are using easy_install to install the twitter library.
DeleteUse 'pip' otherwise.
Also can you tell me which version of python you are using and on which OS ?!
Thanks a lot for putting this together. I was in chapter 3 and got stuck. This totally helps!
ReplyDeleteYou are welcome and i'm glad that it helps you !
DeleteSorry, I am a total Python newbie and quite confused - I installed twitter-1.10.2 (opened setup.py and ran it in IDLE), and still I get "ImportError: No module named 'Twitter' " - what am I doing wrong? Thanks for your help - I am sure I am making a stupid mistake here, but I appreciate any help.
ReplyDeleteBest,
Ken
I don't exactly understand the problem. You can easily install twitter package using pip in linux and windows and brew in mac (You don't have to open the the setup.py file and run it in IDLE). Can you tell me which Operating System you are using and which version of python?? Python is showing import error because there is no library installed named "Twitter". To find out; open python console and type "import twitter". See what happens and tell me.
DeleteI have this problem too! I tried to write it in the python console and it says:
DeleteTraceback (most recent call last):
File "", line 1, in
ImportError: No module named 'twitter'
How can I solve it???
p.s.: I'm pretty sure that pip is installed.
Thanks
Hi @LOLIPOP BARER , Sorry for the late response! I think its because the library twitter is not installed yet. use "pip install twitter" (without the double quotes) to install the library.
DeleteThis comment has been removed by the author.
DeleteWhen you say: use "pip install twitter", what do you mean by that?
DeleteShould I run this in python, IDLE, command prompt?
I have the same question on the linked guides. it keeps saying statements like the one below as if we are in Linux:
To install pip, securely download get-pip.py. [2]
Then run the following:
python get-pip.py
Thank you! I live in Brazil and I am studying programming. You helped me a lot, I am very grateful.
ReplyDeleteMy Pleasure ! Great to know that you got necessary information here. keep up programming and study hard :-)
DeleteHi can u help me get the json from twitter api?
ReplyDeleteTruthfully speaking, I have just started JavaScript and have no idea about JSON format. Any way, twitter API calls return decoded JSON which is converted into lists, dictionaries, strings etc. So, do you want the output without any parsing and as a raw string of JSON or what ?!! Please let me know.
DeleteIt says "Access Denied" when attempting login for step #1. Is there a workaround for this? Thanks
ReplyDeleteHi Kyle, I am really sorry for a really late answer. Anyway, I figured out Twitter has changed a lot of things now. You need to add mobile number for even to make an app. So, I am going to change a whole lot of procedure for the above. Will be up by couple of hours with correct procedure and program again. :)
DeleteI'm running into an error saying:
ReplyDeleteLine 1, in
Import twitter as t
ImportError: no module named 'twitter'
Hi Tanner, The error is self-explanatory. You haven't installed twitter module / api yet.
DeleteInstructions are there in this blog post above on how to install twitter module according to your OS.
Please read and try those. If any problem still persists, feel free to ask. :)
I'm getting this error:
ReplyDeleteTraceback (most recent call last):
File "C:\Python34\lib\site-packages\twitter\api.py", line 315, in _handle_response
handle = urllib_request.urlopen(req, **kwargs)
File "C:\Python34\lib\urllib\request.py", line 161, in urlopen
return opener.open(url, data, timeout)
File "C:\Python34\lib\urllib\request.py", line 469, in open
response = meth(req, response)
File "C:\Python34\lib\urllib\request.py", line 579, in http_response
'http', request, response, code, msg, hdrs)
File "C:\Python34\lib\urllib\request.py", line 507, in error
return self._call_chain(*args)
File "C:\Python34\lib\urllib\request.py", line 441, in _call_chain
result = func(*args)
File "C:\Python34\lib\urllib\request.py", line 587, in http_error_default
raise HTTPError(req.full_url, code, msg, hdrs, fp)
urllib.error.HTTPError: HTTP Error 401: Authorization Required
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "D:\G7\Desktop\HF3.py", line 43, in
res = tweet(status_msg)
File "D:\G7\Desktop\HF3.py", line 19, in tweet
result = authkey.statuses.update(status=status_msg)
File "C:\Python34\lib\site-packages\twitter\api.py", line 308, in __call__
return self._handle_response(req, uri, arg_data, _timeout)
File "C:\Python34\lib\site-packages\twitter\api.py", line 341, in _handle_response
raise TwitterHTTPError(e, uri, self.format, arg_data)
twitter.api.TwitterHTTPError: Twitter sent status 401 for URL: 1.1/statuses/update.json using parameters: (oauth_consumer_key=xxxxxxxxxxxxxxxxxxxxxxxxx&oauth_nonce=5971842895720071914&oauth_signature_method=HMAC-SHA1&oauth_timestamp=1432302535&oauth_token=xxxxxxxxxxxxxxxxxxxxxxxxxx&oauth_version=1.0&status=%40starbuzzceo%0ACurrent%20price%20of%20coffee%20%3D%20%246.3&oauth_signature=%2BIlh8XuJWmyJfPrwTo7t2DJ9CuI%3D)
details: {'error': 'Read-only application cannot POST.', 'request': '/1.1/statuses/update.json'}
The app was already created before. So I didn't follow the add mobile number part.
I've also changed the permissions to :
Read, Write and Access direct messages
Yet I get this error.
Anybody have any clue?
Hi You are 22 coolz,
DeleteIts may be because the Keys get expired after few days automatically unless used frequently.
If you have created (and changed the permissions to read, write) any application before the mobile no. thingy came into business; then its fine. Just regenerate your keys and its will work.
But if you have created it before and left it read-only at that time and changing permissions now, it will not work. You have to add your mobile no. for that.