Skip to content

Instantly share code, notes, and snippets.

@rwaldron
Created July 25, 2010 02:08
Show Gist options
  • Select an option

  • Save rwaldron/489210 to your computer and use it in GitHub Desktop.

Select an option

Save rwaldron/489210 to your computer and use it in GitHub Desktop.
import urllib
import optparse
import os.path
import pickle
def truncate(message,limit):
if len(message) > limit:
# break off at 137 chars and concat elipsis
return message[:(limit-3)] + "..."
else:
# not too long
return message
def nit_twit(username,password,message):
urllib.urlopen(
"http://%s:%s@twitter.com/statuses/update.xml" % (username,password),
urllib.urlencode({
"status" : truncate(message,140)
})
)
return
# TO DO: break up messages into 140 char parts
# send multiple posts for messages > 140? that might be annoying.
def post(opts, credentials):
# only post to twitter if the message wasn't blank
if opts.message != '':
nit_twit(credentials['username'], credentials['password'], opts.message)
print("\n\n'"+opts.message+"' \n\n>>> posted successfully\n\n")
else:
print("No Message? No Post. Those are the rules.\n\n")
return
# main command line program
def main():
# set up the option parser
parser = optparse.OptionParser()
# define this program's accepted option set
parser.add_option(
'--message', '-m',
default='' , help="Be sure to put your message in quotes :)"
)
parser.add_option(
'--username', '-u',
default='' , help="Twitter username"
)
parser.add_option(
'--password', '-p',
default='' , help="Twitter password"
)
# parse the opts passed
opts, arguments = parser.parse_args()
if os.path.exists("nit_twit"):
# conf exists, use pickle to load the stored object
credentials = pickle.load(open("nit_twit", "r"))
else:
# conf file does not exist:
# check first to see if credentials have been passed in as options
# otherwise prompt for credentials
# allows mix and match input
credentials = {
"username": opts.username if opts.username != '' else raw_input("Twitter username: "),
"password": opts.password if opts.password != '' else raw_input("Twitter password: ")
}
pickle.dump(credentials, open("nit_twit", "w"))
post(opts, credentials)
return
#usage: python nit_twit.py -m "posting to twitter"
#usage: python nit_twit.py -m "posting to twitter" -u username -p password
if __name__ == '__main__':
main()
@rwaldron
Copy link
Author

  • using pickle to save and retrieve an object of data
  • added -u and -p as options to the command
  • falls back to raw_input() if those arent used
  • additionally saves your credentials, so you only have to enter it once

@rwaldron
Copy link
Author

Installation:

$ curl -O https://gist.github.com/raw/489210/nit_twit.py

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment