send msg to twitter form python(api)

step1.
Tweepy is an awesome Twitter library for Python. Much of this post is based on
information I found in the documentation for Tweepy.
Download Tweepy from GitHub and install it on your system.

Step 2.
Register a new client app with Twitter
Navigate to http://twitter.com/oauth_clients and click on Register a new application.
You might have to log in to the Twitter site first, if you're not already.

Step 3.
Connect the app to your Twitter account
Next, the app needs to be authorized to connect to your account so it can send tweets under your name.
We'll create a one-off utility script to do this. Save the following Python code as a script on your local system.
#!/usr/bin/env python
import tweepy

CONSUMER_KEY = 'paste your Consumer Key here'
CONSUMER_SECRET = 'paste your Consumer Secret here'

auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
auth_url = auth.get_authorization_url()
print ('Please authorize: ' + auth_url)
verifier = raw_input('PIN: ').strip()
auth.get_access_token(verifier)
print ("ACCESS_KEY = '%s'" % auth.access_token.key)
print ("ACCESS_SECRET = '%s'" % auth.access_token.secret)
app key you can sign up inhttps://dev.twitter.com/
Step 4.
You should see a prompt like this:
Please authorize:URL
PIN:
go to the url,and you will see the pin.

Step 5.
Send a test tweet from python
tweepy.api
import tweepy
def send_to_twitter(msg):
    #以下為twitter api 所獲得的KEY 
    CONSUMER_KEY = 'paste your Consumer Key here'
    CONSUMER_SECRET = 'paste your Consumer Secret here'
    ACCESS_KEY = 'paste your ACCESS_KEY here'
    ACCESS_SECRET = 'paste your ACCESS_SECRET here'

    auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
    auth.set_access_token(ACCESS_KEY, ACCESS_SECRET)
    api = tweepy.API(auth)
    #api.update_status(msg)#更新狀態
    api.direct_messages(msg)#發出推文
send_to_twitter("python say hello")

0 意見:

張貼留言