Ejemplo n.º 1
0
def main():
    """Main function"""
    parser = make_parser()
    arguments = parser.parse_args(sys.argv[1:])
    # Convert parsed arguments from Namespace to dictionary
    arguments = vars(arguments)
    command = arguments.pop("command")

    if command == "where":
        auth = authorization.authorize(arguments['name'])
        response = requests.get(TIMELINE_URL, auth=auth)
        total, locs = where_from(response.json())
        sorted_locs = sorted(locs.iteritems(),
        key=operator.itemgetter(1),
        reverse=True)

        for loc, tweets in sorted_locs:
            print "{}: {:.1%}".format(loc, tweets/float(total))

    if command == "popular":
        auth = authorization.authorize(arguments['name'])
        response = requests.get(FRIENDS_URL, auth=auth)
        pop_list = popular(response.json(),arguments['size'])
        for item in pop_list:
            print "{} : {:,} followers".format(item[0], item[1])
Ejemplo n.º 2
0
def main():
    """Main function"""
    parser = make_parser()
    arguments = parser.parse_args(sys.argv[1:])
    # Convert parsed arguments from Namespace to dictionary
    arguments = vars(arguments)
    command = arguments.pop("command")

    if command == "where":
        auth = authorization.authorize(arguments['name'])
        response = requests.get(TIMELINE_URL, auth=auth)
        total, locs = where_from(response.json())
        sorted_locs = sorted(locs.iteritems(),
                             key=operator.itemgetter(1),
                             reverse=True)

        for loc, tweets in sorted_locs:
            print "{}: {:.1%}".format(loc, tweets / float(total))

    if command == "popular":
        auth = authorization.authorize(arguments['name'])
        response = requests.get(FRIENDS_URL, auth=auth)
        pop_list = popular(response.json(), arguments['size'])
        for item in pop_list:
            print "{} : {:,} followers".format(item[0], item[1])
Ejemplo n.º 3
0
 def log_entry():
     sup_id = input("Supervisor/Manger ID: ")
     sup_pass = input("Supervisor/Manager Password: "******"Authorized")
         return sup_id
     elif authorization.authorize(sup_id, sup_pass) == False:
         print("Please try again!")
         return False
Ejemplo n.º 4
0
def main():
    """ Main function """
    auth = authorization.authorize()

    """Get timeline"""
    #print get_timeline(auth)
    
    """Post to timeline"""
    #print post_to_timeline(auth, "hello twitter api")

    """Top Trends"""


    """http://woeid.rosselliot.co.nz/"""
    woeids = dict(
        gaza = 1979608
        #philadelphia = 2471217
        #brasilia = 455819,
        #telaviv = 1968212,
        #ramahlla = 1937180
    )
    
    
    for place, woeid in woeids.iteritems():
        print "\n" + place.upper()
        trends = get_top_tweets(auth, woeid)
        print_trends(trends)
Ejemplo n.º 5
0
def write_tweets(tweet):
	""" This will send a tweet"""
	while True:
		if (tweet == 'C' or tweet == 'c' or tweet == ' '):
			print " "
			return 1
		elif (tweet == 'Q' or tweet == 'q'):
			print " "
			sys.exit(0)
		elif (len(tweet) >= 1 and len(tweet) <= 140):
			payload = {'status': tweet}
			break
		else:
			tweet = raw_input("Enter your Tweet (C to Cancel or Q to Quit):")
	
	auth = authorization.authorize()
	response = requests.post(TWEET_URL, auth=auth, data=payload)
	if response.status_code == 200:
		print " "
		print "Tweet Successful. Code: {}".format(response)
		print " "
	else:
		print " "
		print "Something went wrong. Code: {}".format(response)
		print " "
Ejemplo n.º 6
0
def read_tweets(limit):
	""" This will read the last 10 tweets tweeted"""
	try:
		int(limit)
		if (limit >= 1 or limit <= 3200):
			limit = str(limit)
		else:
			limit = '10'
	except TypeError: 
		limit = '10'
	
	print "Printing the last {} tweets".format(limit)
	auth = authorization.authorize()
	url = USERTIMELINE_URL + "&count=" + limit
	response = requests.get(url, auth=auth)
	#tweets = json.loads(response)
	#for tweet in tweets:
	#	print tweet["text"]
	#tweets = urlparse.parse_qs(response.content)
	#first_tweet = tweets.get("text")
	#tweet = json.load(tweets)
	#print tweet
	#print first_tweet
	print json.dumps(response.json(), indent=4)
	print " "
Ejemplo n.º 7
0
def read_tweets(limit):
    """ This will read the last 10 tweets tweeted"""
    try:
        int(limit)
        if (limit >= 1 or limit <= 3200):
            limit = str(limit)
        else:
            limit = '10'
    except TypeError:
        limit = '10'

    print "Printing the last {} tweets".format(limit)
    auth = authorization.authorize()
    url = USERTIMELINE_URL + "&count=" + limit
    response = requests.get(url, auth=auth)
    #tweets = json.loads(response)
    #for tweet in tweets:
    #	print tweet["text"]
    #tweets = urlparse.parse_qs(response.content)
    #first_tweet = tweets.get("text")
    #tweet = json.load(tweets)
    #print tweet
    #print first_tweet
    print json.dumps(response.json(), indent=4)
    print " "
Ejemplo n.º 8
0
def write_tweets(tweet):
    """ This will send a tweet"""
    while True:
        if (tweet == 'C' or tweet == 'c' or tweet == ' '):
            print " "
            return 1
        elif (tweet == 'Q' or tweet == 'q'):
            print " "
            sys.exit(0)
        elif (len(tweet) >= 1 and len(tweet) <= 140):
            payload = {'status': tweet}
            break
        else:
            tweet = raw_input("Enter your Tweet (C to Cancel or Q to Quit):")

    auth = authorization.authorize()
    response = requests.post(TWEET_URL, auth=auth, data=payload)
    if response.status_code == 200:
        print " "
        print "Tweet Successful. Code: {}".format(response)
        print " "
    else:
        print " "
        print "Something went wrong. Code: {}".format(response)
        print " "
Ejemplo n.º 9
0
def get_trends(woeid):
	"""
	Get singular trends response from TwitterAPI and store to trends.json
	vars, woeid	
	Go here to look up a WOEID:
	http://woeid.rosselliot.co.nz/
	"""
	# Chicago, Cook County 			WOEID: 2379574
	# Indianapolis, Marion County 	WOEID: 2427032
	logging.info("Getting trends info from WOEID: '{}'".format(woeid))
	
	oauth = authorization.authorize()
	query = "?id="+str(woeid)
	url = TRENDS_URL+query
	response = requests.get(url, auth=oauth)
	# print response.encoding
	response = response.json()

	
	with open('trends.json', 'w') as outfile: # Save to file
		json.dump(response, outfile)

	""" Parse out the 'names' from response and return names[] """
	trends,location = parse_trends('trends.json')
	
	[x.encode('UTF-8','ignore') for x in trends]
	location = location.encode('utf-8','ignore')
	
	return woeid,trends,location
Ejemplo n.º 10
0
def main():
	""" Main function """
	auth = authorization.authorize()
	
	# Uncomment these lines to show that the auth is actually there and working.
	# response = requests.get(TIMELINE_URL, auth=auth)
	# print json.dumps(response.json(), indent=4)

	# Since we're already logged on at this point I can use the 
	# argparser to read the positional arguments and execute
	# what the user wants to do...

	# Command line parser here
	parser = make_parser()
	arguments = parser.parse_args()
	arguments = vars(arguments)
	command = arguments.pop("command")
	print command 

	if command == "post":
		payload = arguments
		r = requests.post(CHIRP_URL, params=payload, auth=auth)
		print "URL: ", r.url
		print "STATUS_CODE: ", r.status_code
		print "TEXT: " + r.text
	elif command =="show":
		payload = arguments
		r = requests.get(SHOW_URL, params=payload, auth=auth)
		print "URL: ", r.url
		print "STATUS_CODE: ", r.status_code
		pp(r.json(), width=40, indent=2)
	else:
		print "No post message to send a tweet"
Ejemplo n.º 11
0
async def login(request):
    username = request.json['username']
    pword = request.json['password']
    token = authorization.authorize(username, pword)
    if token:
        response = json({'result': 'success'})
        response.cookies['streetnode'] = token.decode('utf-8')
        return response
    else:
        return json({'result': 'failure'})
Ejemplo n.º 12
0
def get_mentions():
	logging.debug("Get Mentions")
	auth = authorization.authorize()
	response = requests.get(MENTIONS_URL, auth=auth)
##This guy prints out only a few items
	for t in response.json():
		print "HERE'S A TWEET"
		print t["text"]
		print t["user"]["name"]
		print t["user"]["screen_name"]
		print t["created_at"]
		print ''
Ejemplo n.º 13
0
def trends(location):
	yahoo_response = requests.get(WOEID_URL.format(location_name = location, app_id = YAHOO_APP_ID))
	
	# I had a HELL OF A TIME trying to parse the XML (could access the "woeid" element but couldn't get at the value in between the tags) so I took this very clumsy approach instead ...
	open_tag = yahoo_response.text.find('<woeid>')
	close_tag = yahoo_response.text.find('</woeid>')
	woeid = int(yahoo_response.text[open_tag+len('<woeid>'):close_tag])
	payload = {'id':woeid}

	auth = authorization.authorize()

	return requests.get(GET_TRENDS_URL, auth=auth, params = payload)
Ejemplo n.º 14
0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument(
        "--tweet_id",
        help="Enter the tweet id for a tweet you are interested in",
        action="store_true")
    parser.add_argument("--tweet",
                        help="Update your twitte status",
                        action="store_true")
    args = parser.parse_args()

    if (args.tweet_id):
        auth = authorization.authorize()
        #prompt the user to enter the tweet_id
        tweet_id = raw_input(
            "Please enter the id of the tweet you are interested in: ")
        print("Getting the contents of the tweet")
        response = get_tweet(tweet_id, auth)
        print json.dumps(response.json(), indent=4)
        #Prompt the user if they wish to retweet this tweet or try another tweet id
        print("Please note that you cannot retweet a tweet more than once!")
        user_input_retweet = raw_input(
            "Type Y if you would like to retweet this tweet.\nType anything else if you do not: "
        )
        if (user_input_retweet == "Y"):
            response = retweet(tweet_id, auth)
            print json.dumps(response.json(), indent=4)
        else:
            print "I see you don't find this interesting!\nYou should find another tweet!"

    if (args.tweet):
        auth = authorization.authorize()
        user_input = raw_input("Please type your status: ")
        #leave blank if you don't want to tweet anything
        if (user_input == ""):
            print "I guess you have nothing to tweet"
        else:
            response = tweet(user_input, auth)
            print json.dumps(response.json(), indent=4)
Ejemplo n.º 15
0
async def mqttPublishHandle(request):
    params = await request.json()

    requiredParams = ["topic", "payload", "username", "password"]

    for p in requiredParams:
        if not p in params:
            return web.json_response(data={
                "error":
                "Missing one of the parameters: " + ", ".join(requiredParams)
            },
                                     status=406)

    username = params["username"]
    password = params["password"]

    if username.lower() == "server":
        return web.json_response(data={"error": "Username can't be 'server'"},
                                 status=406)

    allowed = a.authorize(username, password)

    if not allowed:
        return web.json_response(data={"error": "Not authenticated"},
                                 status=401)

    t = params["topic"]
    p = params["payload"]
    q = params["qos"] if "qos" in params else 1
    r = params["ratain"] if "retain" in params else False

    messageInfo = mqtt_client.publish(topic=t, payload=p, qos=q, retain=r)
    messageInfo.wait_for_publish()

    if messageInfo.is_published():
        return web.json_response(data={
            "success":
            True,
            "msg":
            "Succesfully published to topic '{}'".format(t)
        },
                                 status=201)
    else:  # Can this happen?
        return web.json_response(data={
            "success":
            False,
            "msg":
            "The message wasn't published due to unknown reasons"
        },
                                 status=500)
Ejemplo n.º 16
0
def main():
	auth = authorization.authorize()
	arg_parser = my_parser.make_parser()
	arguments = arg_parser.parse_args(sys.argv[1:])
	#Convert parsed arguments from Namespace to dictionary
	arguments = vars(arguments)
	#Remove command from the arguments dictionary and store it as a variable
	command = arguments.pop("command")

	if command == "search":
		result = search.search(arguments['query'],arguments['result_type'], arguments['count'], auth)
		print len(result['statuses'])
		print result['statuses'][0]['text']
		print result['statuses'][1]['text']
		print result['statuses'][2]['text']
Ejemplo n.º 17
0
def tweet(tweet_text):
	""" Perform a tweet using TwitterAPI based on passed tweet_text """
	logging.info("Attempting to tweet '{}'".format(tweet_text))

	if len(tweet_text) > 140:
		print 'Tweets cannot be greater than 140 characters!'
		quit()
	
	oauth = authorization.authorize()
	url = TWEET_URL+"?status=" + urllib.quote(tweet_text)  #urllib.quote encode given text to url friendly
	response = requests.post(url, auth=oauth)
	response = response.json()

	with open('tweet.json', 'w') as outfile: # Save to file
		json.dump(response, outfile)

	return response,tweet_text
Ejemplo n.º 18
0
def main():
	""" Main function """
	parser = make_parser()
	arguments=parser.parse_args(sys.argv[1:])
	# convert parsed arguments from Namespace to dictionaries
	arguments=vars(arguments)
	command = arguments.pop("command")
	auth=authorization.authorize()
	if command == "timeline":
		response = requests.get(TIMELINE_URL, auth=auth)
		#json.dumps function to format the output nicely
		print json.dumps(response.json(),indent=4)
	elif command == "users":
		response = requests.get(USERS_URL, auth=auth)
		print json.dumps(response.json(),indent=4)
	elif command == "retweets_of_me":
		response = requests.get(RTM_URL, auth=auth)
		print json.dumps(response.json(),indent=4)
	else:
		return
Ejemplo n.º 19
0
def main():
    """ Main function """
    auth = authorization.authorize()

    parser = argparse.ArgumentParser()
    parser.add_argument("resource", type=str, help="specific resource to be queried (Timeline, Messages, Friends, Followers)")
    parser.add_argument("user", type=str, help="user to be queried about", nargs='?')
    args = vars(parser.parse_args())

    if args["resource"]=="Timeline":
        response = requests.get(TIMELINE_URL, auth=auth)
        print json.dumps((response.json()), sort_keys=True, indent=4, separators=(',',':'))
    elif args["resource"]=="Messages":
        response = requests.get(MESSAGES_URL, auth=auth)
        print json.dumps((response.json()), sort_keys=True, indent=4, separators=(',',':'))
    elif args["resource"]=="Followers":
        response = requests.get(FOLLOWERS_URL + args["user"], auth=auth)
        print json.dumps((response.json()), sort_keys=True, indent=4, separators=(',',':'))
    elif args["resource"]=="Friends":
        response = requests.get(FOLLOWERS_URL + args["user"], auth=auth)
        print json.dumps((response.json()), sort_keys=True, indent=4, separators=(',',':'))
Ejemplo n.º 20
0
def main():
    """ Main function """
    auth = authorization.authorize()
    """Get timeline"""
    #print get_timeline(auth)
    """Post to timeline"""
    #print post_to_timeline(auth, "hello twitter api")
    """Top Trends"""
    """http://woeid.rosselliot.co.nz/"""
    woeids = dict(
        gaza=1979608
        #philadelphia = 2471217
        #brasilia = 455819,
        #telaviv = 1968212,
        #ramahlla = 1937180
    )

    for place, woeid in woeids.iteritems():
        print "\n" + place.upper()
        trends = get_top_tweets(auth, woeid)
        print_trends(trends)
Ejemplo n.º 21
0
def main():
    """ Main function """

    parser = make_parser()
    arguments = parser.parse_args(sys.argv[1:])
    #convert parsed arguments from Namespace to dictionatry
    arguments = vars(arguments)
    api_feature = arguments.pop("API_feature")

    auth = authorization.authorize()

    if api_feature == "TIMELINE":
        response = requests.get(TIMELINE_URL, auth=auth)
        print json.dumps(response.json(), indent=4)

    if api_feature == "FRIEND_ID":
        response = requests.get(FRIEND_ID_URL, auth=auth)
        print json.dumps(response.json(), indent=4)

    if api_feature == "FRIEND_LIST":
    	response = requests.get(FRIEND_LIST_URL, auth=auth)
    	print json.dumps(response.json(), indent=4)
Ejemplo n.º 22
0
def main():
    """ Main function """
    logging.info("Tweetful -- starting main()")
    parser = make_parser()
    arguments = parser.parse_args(sys.argv[1:])
    # Convert parsed arguments from Namespace to dictionary
    arguments = vars(arguments)

    auth = authorization.authorize()

    if arguments['tweet']:
        print 'Tweeting "{}"'.format(arguments['tweet'])
        post_status(format(arguments['tweet']), auth)

    if arguments['info']:
        if arguments['info'] == "friends":
            get_friends(auth)

        if arguments['info'] == "followers":
            get_followers(auth)

        if arguments['info'] == "timeline":
            get_timeline(auth)
Ejemplo n.º 23
0
def main():
    ##  main function
    print ("arg that was entered is: " + sys.argv[1])
    parser = make_parser()
    arguments = parser.parse_args(sys.argv[1:])
    print arguments
    # Convert parsed arguments from Namespace to dictionary
    arguments = vars(arguments)
    print arguments
    command = arguments.pop("command")

    auth = authorization.authorize()

    if command == "timeline":
        response = requests.get(TIMELINE_URL, auth=auth)
        print json.dumps(response.json(), indent=4)

    #elif command == "nextthing":



    else:
        #print "geuss again sucka"
        return    
Ejemplo n.º 24
0
def main():
    """ Maint function """
    auth = authorization.authorize()
    
    response = requests.get(TIMELINE_URL, auth=auth)
    print response.json()
Ejemplo n.º 25
0
def main():
	"""Main function"""
	authorization.authorize()
	retweets = get_retweets(sys.argv[1])
	print json.loads(retweets.json())
	'''
Ejemplo n.º 26
0
def home():
	auth = authorization.authorize()
	return requests.get(TIMELINE_URL, auth=auth)
Ejemplo n.º 27
0
def tweet(message):
	auth = authorization.authorize()
	payload = {'status':message}
	return requests.post(UPDATE_STATUS_URL, auth=auth, params=payload)
Ejemplo n.º 28
0
def main():
  # main function
  auth = authorization.authorize()

  response = requests.get(TIMELINE_URL, auth=auth)
  print json.dumps(response.kson(), indent=4)
Ejemplo n.º 29
0
                clients.append(address)
                nickname, password = data.decode().split("---_---")[:-1]
                if nickname not in authorization.get_nicknames():
                    new_user_created = authorization.create_new(nickname,
                                                                hashlib.sha1(password.encode('utf-8')).hexdigest())
                    if new_user_created:
                        for client in clients:
                            if client == address:
                                server.sendto(('Welcome, ' + nickname + '!').encode(), address)
                                server.sendto(('You successfully created new account.\n').encode(), address)
                            else:
                                server.sendto(('------------ ' + nickname + ' connected to server ------------').encode('utf-8'),
                                              client)
                    else:
                        server.sendto("You entered incorrect login/password pair.╘╘".encode('utf-8'), address)
                else:
                    if authorization.authorize(nickname, hashlib.sha1(password.encode('utf-8')).hexdigest()):
                        for client in clients:
                            if client == address:
                                server.sendto(('Welcome back, ' + nickname + '!').encode(), address)
                            else:
                                server.sendto(('------------ ' + nickname + ' connected to server ------------').encode('utf-8'),
                                              client)
                    else:
                        server.sendto("You entered incorrect login/password pair.╘╘".encode('utf-8'), address)
        else:
            for client in clients:
                    if client == address:
                        continue
                    server.sendto(data, client)
Ejemplo n.º 30
0
def get_timeline():
	logging.debug("Get Timeline")
	auth = authorization.authorize()
	response = requests.get(TIMELINE_URL, auth=auth)
	return json.dumps(response[text].json(), indent=4)
Ejemplo n.º 31
0
def main():
	""" Main Function """
	auth = authorization.authorize()
	response = requests.get(TIMELINE_URL, auth=auth)
	print json.dumps(response.json(), indent=4)
 def setUp(self):
     self._validator_mock = Mock()
     self._action_mock = Mock()
     self._subject = authorization.authorize(self._validator_mock)(
         self._action_mock)