[Memo] Tweet on twitter with python

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

setting file

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.

Oauth authentication file

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

File to actually tweet

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

[Memo] Tweet on twitter with python
Twitter graphing memo with Python
A memo with Python2.7 and Python3 on CentOS
I want to tweet on Twitter with Python, but I'm addicted to it
Get Twitter timeline with python
Use Twitter API with Python
Tweet with image in Python
Twitter posts on Python 3 etc.
Search twitter tweets with python
Crawl the URL contained in the twitter tweet with python
Automatic follow on Twitter with python and selenium! (RPA)
Python memo
Create a list in Python with all followers on twitter
python memo
python memo --Specify options with getopt
Input / output with Python (Python learning memo ⑤)
Python memo
Python environment construction memo on Mac
Post multiple Twitter images with python
python memo
Python memo
Notes on using rstrip with python.
Easily post to twitter with Python 3
"Scraping & machine learning with Python" Learning memo
Python memo
Python memo
Collecting information from Twitter with Python (Twitter API)
Get delay information on Twitter and tweet
Convert memo at once with Python 2to3
Run servo with Python on ESP32 (Windows)
Create wordcloud from your tweet with python3
"System trade starting with Python3" reading memo
Tweet using the Twitter API in Python
Map rent information on a map with python
Follow active applications on Mac with Python
Notes on doing Japanese OCR with Python
scipy stumbles with pip install on python 2.7.8
Download files on the web with Python
Build Python environment with Anaconda on Mac
Tweet analysis with Python, Mecab and CaboCha
Let's make a Twitter Bot with Python!
Installing PIL with Python 3.x on macOS
Working with GPS on Raspberry Pi 3 Python
[Python] Memo dictionary
FizzBuzz with Python3
Scraping with Python
python beginner memo (9.2-10)
Statistics with python
Python on Windows
Scraping with Python
python beginner memo (9.1)
Twilio with Python
Integrate with Python
Try tweeting arXiv's RSS feed on twitter from Raspberry Pi with python
Play with 2016-Python
AES256 with python
★ Memo ★ Python Iroha
python starts with ()
python on mac
Python 3 operator memo
Bingo with python