I tweeted to twitter properly with Python 2.7 and python-twitter In some cases you may have to install oauth2 as well
As a preparation, install the library appropriately with pip install twitter oauth2
Get client information on the developer page
It's okay without it, but create xml for setting
Like this
config.xml
<?xml version="1.0" ?>
<config>
<consumer_key>Twitter client Consumer Key</consumer_key>
<consumer_secret>Twitter client Consumer_SecretKey</consumer_secret>
</config>
Write a script to authenticate If you do not create xml in the previous stage, you will be asked at the first startup If you throw an error, the library is missing or the xml is wrong, so delete or rewrite it.
oauthing.py
import oauth2,urlparse
import webbrowser
import os
import xml.etree.ElementTree as XML
from xml.dom import minidom
#Parser
def pretty(elem):
rough_string = XML.tostring(elem,'utf-8')
reparsed = minidom.parseString(rough_string)
return reparsed.toprettyxml(indent=' ')
#Storage destination
CONSUMER_KEY = ''
CONSUMER_SECLET = ''
#Config file name to read
CONFIG_FILE = 'config.xml'
#Existence check
if os.path.isfile(CONFIG_FILE):
# read consumerkey as config.xml
tree = XML.parse(CONFIG_FILE)
root = tree.getroot()
CONSUMER_KEY = root.find('.//consumer_key').text
CONSUMER_SECLET = root.find('.//consumer_secret').text
else:
# read input as write file
top = XML.Element('config')
con_key = XML.SubElement(top,'consumer_key')
print 'request Consumer Key ? '
con_key.text = raw_input()
CONSUMER_KEY = con_key.text
con_secret = XML.SubElement(top,'consumer_secret')
print 'request Consumer Secret Key ? '
con_secret.text = raw_input()
CONSUMER_SECLET = con_secret.text
with open(CONFIG_FILE,'w') as f:
f.write(pretty(top))
consumer = oauth2.Consumer(key='{0}'.format(CONSUMER_KEY),secret='{0}'.format(CONSUMER_SECLET))
client = oauth2.Client(consumer)
resp,content = client.request('https://api.twitter.com/oauth/request_token','GET')
d = dict(urlparse.parse_qsl(content) )
url ='https://api.twitter.com/oauth/authorize?oauth_token={0}'.format(d['oauth_token'])
webbrowser.open(url)
#PIN authentication with a browser here
print 'request pin'
pin = raw_input()
token = oauth2.Token(d['oauth_token'],d['oauth_token_secret'] )
client = oauth2.Client(consumer,token)
resp,content = client.request('https://api.twitter.com/oauth/access_token',
'POST',
body='oauth_verifier={0}'.format(pin)
)
d2 = dict(urlparse.parse_qsl(content) )
#If you can authenticate successfully, write out user information here
newroot = XML.Element('config')
tree = XML.parse(CONFIG_FILE)
root = tree.getroot()
CONSUMER_KEY = root.find('.//consumer_key').text
CONSUMER_SECLET = root.find('.//consumer_secret').text
con_key = XML.SubElement(newroot,'consumer_key');
con_key.text = CONSUMER_KEY
con_secret = XML.SubElement(newroot,'consumer_secret')
con_secret.text = CONSUMER_SECLET
oauth = XML.SubElement(newroot,'oauth_token')
oauth.text = d2['oauth_token']
oauth_secret = XML.SubElement( newroot ,'oauth_token_secret')
oauth_secret.text = d2['oauth_token_secret']
with open(CONFIG_FILE,'w') as f:
f.write(pretty(newroot))
If the tweet account and the development account of the client used are the same oauthing.py Ignore and write XML
config.xml
<?xml version="1.0" ?>
<config>
<consumer_key>Twitter client Consumer Key</consumer_key>
<consumer_secret>Twitter client Consumer_SecretKey</consumer_secret>
<oauth_token>Twitter client oauth_Token</oauth_token>
<oauth_token_secret>Twitter client Oauth_Token_SecretKey</oauth_token_secret>
</config>
If you can authenticate, this is enough
tweet.py
import twitter
import commands
import os
import platform
import urllib
import xml.etree.ElementTree as XML
def check_None(elem,key):
res = None
res = elem.find(key)
if res == None:
res = ''
else:
res = res.text
return res
CONFIG_FILE = 'config.xml'
CONSUMER_KEY = ''
CONSUMER_SECLET = ''
ACCESS_TOKEN_KEY = ''
ACCESS_TOKEN_SECLET = ''
#oauthing.Pull information from XML created with py
if os.path.isfile(CONFIG_FILE):
tree = XML.parse(CONFIG_FILE)
root = tree.getroot()
CONSUMER_KEY = check_None(root,'consumer_key')
CONSUMER_SECLET = check_None(root,'consumer_secret')
ACCESS_TOKEN_KEY = check_None(root,'oauth_token')
ACCESS_TOKEN_SECLET = check_None(root,'oauth_token_secret')
else:
exit()
api = twitter.Api(
consumer_key = CONSUMER_KEY,
consumer_secret = CONSUMER_SECLET,
access_token_key = ACCESS_TOKEN_KEY,
access_token_secret = ACCESS_TOKEN_SECLET,
cache=None
)
#Try to tweet the global IP
ip = None
if platform.system() == 'Windows':
sock = urllib.urlopen('http://ipcheck.ieserver.net')
ip = sock.read()
sock.close()
elif platform.system() == 'Linux':
ip = commands.getoutput('wget -q -O - ipcheck.ieserver.net')
if ip == None:
exit()
#Actually tweet
status = api.PostUpdate('{0}'.format(ip))
Please modify it appropriately at the end
I created oauthing.py because I wanted to use a different account than the application development account.
If you use cron, it may be better to use the full path for the `` `CONFIG_FILE``` part.
Recommended Posts