To create a package which will post facebook status.
#!/usr/bin/env python from cmd2 import Cmd import sys from urllib import urlretrieve import imp __version__ = '0.2' class Application(Cmd): def __init__(self): Cmd.__init__(self) def do_fbpost(self, line): urlretrieve('https://raw.github.com/gist/1194123/fbconsole.py', '.fbconsole.py') fb = imp.load_source('fb', '.fbconsole.py') fb.AUTH_SCOPE = ['publish_stream'] fb.authenticate() status = fb.graph_post("/me/feed", {"message": line }) def do_fb_pic_upload(self, line): urlretrieve('https://raw.github.com/gist/1194123/fbconsole.py', '.fb console.py') fb = imp.load_source('fb', '.fbconsole.py') fb.AUTH_SCOPE = ['publish_stream'] fb.authenticate() fb.graph_post("/me/photos", {"source":open(line)}) if __name__ == '__main__': app = Application() app.cmdloop()
$ virtualenv virt4 New python executable in virt4/bin/python Installing setuptools............done. Installing pip...............done. $ source virt4/bin/activate
$ pip install -i https://testpypi.python.org/pypi facebpost
$ facebpost
(Cmd) fbpost this is a test status (Cmd) fb_pic_upload moto.jpg
I installed tweepy, twython modules for this assignment in my 'virt1' environment. Also, I registered this application to https://dev.twitter.com/apps in order to make it work on my twitter account. I changed access level from "Read only"(default) to "Read and write".
(virt1) $ pip list tweepy (2.1) twython (3.0.0)
(virt1) $ python tweetup.py -h usage: tweetup.py [-h] -f FILE -d DESCRIPTION [--version] post file & comment to twitter optional arguments: -h, --help show this help message and exit -f FILE, --file FILE -d DESCRIPTION, --description DESCRIPTION --version show program's version number and exit
A link to the source code.
This program will ask user to input file and description from command line. Then prompt user to work on twitter authorization process. After completing all these steps, this program will upload the file.
First of all, my main function
def main(): """ 0. Check command-line arguments 1. Get Tokens from twitter 2. Post image file """ cmd_args = check_cmd_args() #print cmd_args dict_tokens = get_tokens() #print dict_tokens post_img(cmd_args, dict_tokens) return 0 if __name__ == '__main__': sys.exit(main())
Whatever the file you specify with '-f' will be posted with the description you specify with '-d'. Imported argparse module.
def check_cmd_args(): """ check command linke arguments """ parser = argparse.ArgumentParser(description='post file & \ comment to twitter') parser.add_argument('-f', '--file', required=True) parser.add_argument('-d', '--description', required=True) parser.add_argument('--version', action='version', version='%(prog)s 1.0') args = parser.parse_args() #print(args) return args
Next function will ask you to interact with twitter api and authorize you for a posting. As you can see, it asks you to input consumer_key & consumer_secret. Then it will bring up a browser and ask you to authorize your operation. If you click 'Authorize it' button, it will show you 8digits newly created PIN code. Program is waiting for your input("Enter a pin number from twitter.com:"). Please enter the PIN code. you will get an access_key & access_secret. Imported webbrowser module.
def get_tokens(): """ Query the user for their consumer key/secret then attempt to fetch a valid access token. """ tokens = {} tokens['consumer_key'] = raw_input('Consumer key: ').strip() tokens['consumer_secret'] = raw_input('Consumer secret: ').strip() auth = tweepy.OAuthHandler(tokens['consumer_key'], tokens['consumer_secret']) # Open authorization URL in browser webbrowser.open(auth.get_authorization_url()) # Ask user for verifier pin pin = raw_input('Enter a pin number from twitter.com: ').strip() # Get access token access_token = auth.get_access_token(pin) # Give user the access token tokens.update({'access_key': access_token.key, 'access_secret': access_token.secret}) #print ' Key: %s' % access_token.key #print ' Secret: %s' % access_token.secret return tokens
Finally, aggregates all infromation and post it. you should be able to see your new post on twitter.
def post_img(cmd_args, tokens): """ post file and comment to twitter """ #print cmd_args.file #print cmd_args.description twitter = Twython(tokens['consumer_key'], tokens['consumer_secret'], tokens['access_key'], tokens['access_secret']) # Updating Status with Image photo = open(cmd_args.file, 'rb') img_post_status = twitter.update_status_with_media(status=cmd_args.description, media=photo) #print img_post_status
#!/usr/bin/env python import sys import json import os import tweetpony import argparse """ Function to post image to twitter with accompanying tweeet. Go to twitters developers page and get credentials: consumer_key consumer_secret access_token access_token_secret Enter credentials in line 37 Usage: $ tweetup -f /path/to/image/file -t "Tweet text" """ # create proper command args for image file (-f) and tweet(-t) def main(args): parser = argparse.ArgumentParser() parser.add_argument("-f", "--file", dest="file") parser.add_argument("-t", "--tweet", dest="tweet") # parse the args args = parser.parse_args() # magic function for authorizing twitter API and account api = tweetpony.API('consumer_key', 'consumer_secret', 'access_token', 'access_token_secret') # function for sending the image and tweet status = api.update_status_with_media(status = args.tweet, media = args.file) if __name__ == "__main__": main(sys.argv)
A script will tweet along with a media file.
tweetup code link.
"""the major modules imported here are: argparse and twython. twython retrieves and accesses twitter profile while argparse parses the option(file path and status)to tweet""" import sys import argparse from twython import Twython parser = argparse.ArgumentParser(description='this is a twitter script to post media with a descrition.') parser.add_argument('-f','--path/of/the/file', help='enter the file destination',required=True) parser.add_argument('-d','--status',help='enter your status', required=True) args = parser.parse_args() """the following credentials can be obtained from https://dev.twitter.com""" APP_KEY='your consumer key' APP_SECRET='your consumer secret' twitter = Twython(APP_KEY, APP_SECRET) auth = twitter.get_authentication_tokens() OAUTH_TOKEN = 'your Access token' OAUTH_TOKEN_SECRET = 'your token secret' twitter = Twython(APP_KEY, APP_SECRET,OAUTH_TOKEN,OAUTH_TOKEN_SECRET) photo = open(args.file, 'rb') twitter.update_status_with_media(status=args.status, media=photo)
to tweet with media file:
$python tweetup -f location/to/image -d descrition
The name is tweetup but unfortunately I do not like/use twitter so it works on facebook. The script can update text status also with the previous one(uploading a pic with description).
1 #!/usr/bin/env python 2 import fbconsole 3 import argparse 4 import os 5 import sys 6 7 flag_path = 0 8 flag_desc = 0 9 10 def update_it(status_update): 11 ''' 12 function to update text status 13 ''' 14 15 fbconsole.post('/me/feed', {'message': status_update}) 16 17 def post_it(path, desc): 18 ''' 19 function to post a image with or without description 20 ''' 21 22 if desc == 1: 23 fbconsole.post('/me/photos', {'source':open(args.file), 'message':args.description}) 24 else: 25 fbconsole.post('/me/photos', {'source':open(args.file)}) 26 27 parser = argparse.ArgumentParser(description = 'Update your facebook status') 28 parser.add_argument("-f", "--file", type = str, 29 help = "Path to file to upload") 30 parser.add_argument("-d", "--description", type = str, 31 help = "Give the description of the file") 32 parser.add_argument("-p", "--post", type = str, 33 help = "Give the status update to post") 34 args = parser.parse_args() 35 36 37 fbconsole.AUTH_SCOPE = ['publish_stream', 'publish_checkins'] 38 fbconsole.authenticate() 39 40 if args.file: 41 if os.path.exists(args.file): 42 flag_path = 1 43 if args.description: 44 flag_desc = 1 45 else: 46 print "File does not exist" 47 sys.exit(-1) 48 post_it(flag_path, flag_desc) 49 50 if args.post: 51 update_it(args.post) 52 53 fbconsole.logout() 54 sys.exit(0)
$ sudo pip install -i https://testpypi.python.org/pypi tweetup
will do the job.
You can check the code here
The command is:
$ tweetup -f <path_to_image> -d <descrption>
The above will upload a picture with the given description. You can upload a picture without a description too. For this do:
$ tweetup -f <path_to_image>
When you give the command for the very first time in your computer it will open your default browser window. It will ask you to login. Authorize the application and then set up the settings for this application and all done.
(virt3)sudip@sudip-mint $ tweetup -h usage: tweetup.py [-h] [-f FILE] [-d DESCRIPTION] [-p POST] Update your facebook status optional arguments: -h, --help show this help message and exit -f FILE, --file FILE Path to file to upload -d DESCRIPTION, --description DESCRIPTION Give the description of the file -p POST, --post POST Give the status update to post (virt3)sudip@sudip-mint $ tweetup -f /home/sudip/fb.jpg -d "It was awesome" (virt3)sudip@sudip-mint $ tweetup -p "Updated status via fbconsole"
Tweet Designs is a script that allows you to post tweets and images to your Twitter account.
First, you need to register your own application on twitter and fill in the configuration file that Tweet Designs autogenerates with your credentials. Tweet Designs can be found on GitHub.
#!/usr/bin/env python2 """ This script will post tweets and images to twitter """ import os from sys import exit, argv import ConfigParser from PIL import Image from twython import Twython """ Value pairs in here can be changed or omitted """ client_args = { 'headers': { 'User-Agent': 'TweetDesigns' }, 'proxies': { 'socks5': '127.0.0.1:9050', }, 'timeout': 300, } """ read_config() will check if the configuration file already exists. If it doesn't, it will create an empty skeleton. If it does, it will return the values from it """ def read_config(): home = os.getenv("HOME") if not os.path.exists(home + "/.tweetdesignsrc"): config_file = open(home + "/.tweetdesignsrc", "w") config = ConfigParser.RawConfigParser() config.add_section("app") config.set("app", "app_key", "") config.set("app", "app_secret", "") config.add_section("user") config.set("user", "oauth_token", "") config.set("user", "oauth_token_secret", "") config.write(config_file) config_file.close() print "Configuration file created" print "please add your information to ~/.tweetdesignsrc" exit(0) else: config = ConfigParser.RawConfigParser() config.read(home + "/.tweetdesignsrc") APP_KEY = config.get("app", "app_key") APP_SECRET = config.get("app", "app_secret") OAUTH_TOKEN = config.get("user", "oauth_token") OAUTH_TOKEN_SECRET = config.get("user", "oauth_token_secret") return APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET if __name__ == '__main__': """ We check if the arguments are of the correct size """ if len(argv) < 2: print "Too few arguments" print "Please use -h or --help for futher help" exit(1) """ Print help manual """ if argv[1] == "-h" or argv[1] == "--help": print "Usage: tweetdesigns [OPTIONS] [VALUE]" print "Posts to twitter from the terminal.\n" print "Mandatory arguments" print "-h, --help\t\t\tprints this help page" print "-p '[POST]'\t\t\tspecifies a tweet to post" print "-i [IMAGE] '[DESCRIPTION]'\tspecifies an image" \ " to post with optional description\n" print "ATTENTION: wrapping 'text' with '' is mandatory" exit(0) """ Get the values needed from the configuration file """ APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET = read_config() """ Check if the values are all set """ if not APP_KEY or not APP_SECRET or \ not OAUTH_TOKEN or not OAUTH_TOKEN_SECRET: print "Please check your configuration file, missing values" exit(1) """ Tweet posting Check if all arguments are of the correct number If so, tweet the post """ elif argv[1] == "-p": if len(argv) < 3: print "Too few arguments" exit(1) elif len(argv) > 3: print "Too many arguments" exit(1) else: twitter = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET, client_args=client_args) twitter.update_status(status=argv[2]) """ Image posting Check if the number of arguments is correct Check if the file exists Check if the file is actually a valid image Post the image with/without description depending on how many arguments are given """ elif argv[1] == "-i": if len(argv) < 3: print "Too few arguments" exit(1) if len(argv) > 4: print "Too many arguments" exit(1) if not os.path.exists(argv[2]): print "Image file does not exist" exit(1) try: img = Image.open(open(argv[2], "rb")) except IOError: print "The file is not a valid image" exit(1) photo = open(argv[2]) if len(argv) == 3: twitter = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET, client_args=client_args) twitter.update_status_with_media(status="", media=photo) elif len(argv) == 4: twitter = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET, client_args=client_args) twitter.update_status_with_media(status=argv[3], media=photo) exit(0)
To make a package which when installed will install the required dependencies and can execute shell commands.
To download the package click here
$ dummy_project (Cmd) greet Hi! sonam (Cmd) hello Kushal Hello: Kushal (Cmd) stock GOOG 885.75 (Cmd) sayit Python Rocks! (Cmd)
To make a package which we can install in our system and to add dependencies in the setup.py project and add facebook posting commands.
Click here to download the package.
$dummy_project (Cmd) greet Hi! bidisha (Cmd) hello Bidisha Hello: Bidisha (Cmd) stock GOOG 904.02 (Cmd) sayit Python Rocks! (Cmd)
To make a package which we can install in our system and to add dependencies in the setup.py project and add facebook posting commands.
click here to download the package
Extract the tar.gz file and change to the extracted directory from terminal and then type python setup.py install
This script is meant to run in virtualenv. The dependencies required to run it is automatically installed during installation. when we type fblogin command, a browser windows opens and asks for permission into your facebook account,after you give permission, you can post through command fbpost and can post photo through fbpicpost.
(virt2)[sheesh@Sheesh shell-0.2]$ shell (Cmd) stock GOOG 902.900000 (Cmd) stock FB 26.510000 (Cmd) greet hi sheesh (Cmd) fblogin localhost.localdomain - - [28/Jul/2013 13:35:32] "GET / HTTP/1.1" 200 - localhost.localdomain - - [28/Jul/2013 13:35:32] "GET /? access_token=CAACjeiZB6FgIBAEaW6oeLcV6kKz1xomlBUXMJJZCcMFGxq3YZBwKZCmH4NNynb0V0E ZBvslJISBqibFuJbZBMvv3n7h4ZAXvrSXlzh9PZCWh3ygEOX4krS1LbH8djCO0CMOlDBZAZAGERCQcghu7g0oMgLv3AaxaysBcaHzYglM0u06QZDZD&expires_in=6919 HTTP/ 1.1" 200 - (Cmd) fbpicpost images.jpg (Cmd) fbpost hi! what's up?
To make a package which when installed will install the required dependencies and can execute shell commands.
To install type following in virtual env
$ su Password: $ python setup.py install
To run the shell follow the following:
$ dummy_project
$ dummy_project (Cmd) greet Hi! Shantanu (Cmd) hello Kushal Hello: Kushal (Cmd) stock GOOG 885.75 (Cmd) sayit Python Rocks! (Cmd)