コード例 #1
0
ファイル: twitterbot.py プロジェクト: kordless/utter-va
def oauth_complete(oauth_verifier):
    # twitter credential db
    bot = TwitterBot.get()

    try:
        twitter = Twitter(auth=OAuth(bot.oauth_token, bot.oauth_token_secret,
                                     bot.consumer_key, bot.consumer_secret),
                          format='',
                          api_version=None)
        oauth_token, oauth_token_secret, screen_name = parse_oauth_tokens(
            twitter.oauth.access_token(oauth_verifier=oauth_verifier))
    except Exception as ex:
        return bot

    # twitter credential db
    bot = TwitterBot.get()

    # get a flavor we can use for default
    flavor = db.session.query(Flavors).order_by().first()

    # update the entry
    bot.screen_name = screen_name
    bot.oauth_url = ""  # becomes invalid
    bot.oauth_token = oauth_token
    bot.oauth_token_secret = oauth_token_secret
    bot.complete = 2
    bot.enabled = 1
    bot.flavor_id = flavor.id
    bot.max_instances = app.config['MAX_INSTANCES_DEFAULT']
    bot.announce = 0
    bot.updated = int(time.time())
    bot.update()

    return bot
コード例 #2
0
ファイル: twitterbot.py プロジェクト: kordless/utter-va
def tweet_status(text="Who wants to smoke some instances with me?", user=None):
    # default response
    response = {"response": "success", "result": {"message": "Tweet sent."}}

    bot = TwitterBot.get()

    try:
        twitter = Twitter(auth=OAuth(bot.oauth_token, bot.oauth_token_secret,
                                     bot.consumer_key, bot.consumer_secret))

        # toggle dm or regular message based on if we got a user in the call
        if user:
            try:
                twitter.direct_messages.new(text, user=None)
            except:
                # build a fake DM cause they aren't following us
                dm = ". @%s %s" % (user, text)
                twitter.statuses.update(status=dm)
        else:
            twitter.statuses.update(status=text)

    except Exception as ex:
        response['response'] = "error"
        response['result'][
            'message'] = "Something went wrong with posting.  Ensure you are running good credentials and making non-duplicate posts!"
        app.logger.error(ex)

    return response
コード例 #3
0
ファイル: twitterbot.py プロジェクト: brooklynne/utter-va
def tweet_status(text="Who wants to smoke some instances with me?", user=None):
    # default response
    response = {"response": "success", "result": {"message": "Tweet sent."}}

    bot = TwitterBot.get()

    try:
        twitter = Twitter(auth=OAuth(bot.oauth_token, bot.oauth_token_secret, bot.consumer_key, bot.consumer_secret))

        # toggle dm or regular message based on if we got a user in the call
        if user:
            try:
                twitter.direct_messages.new(text, user=None)
            except:
                # build a fake DM cause they aren't following us
                dm = ". @%s %s" % (user, text)
                twitter.statuses.update(status=dm)
        else:
            twitter.statuses.update(status=text)

    except Exception as ex:
        response["response"] = "error"
        response["result"][
            "message"
        ] = "Something went wrong with posting.  Ensure you are running good credentials and making non-duplicate posts!"
        app.logger.error(ex)

    return response
コード例 #4
0
    def action(
            cron=('c', 0),
            freq=('f', 0),
    ):
        """
		Provides Twitter command processing.

		Cron: Every 1 minute.
		"""

        # get bot settings
        bot = TwitterBot.get()

        # exit if we're not enabled
        if not bot:
            return action
        if not bot.enabled:
            print "The marketing bot is disabled."
            return action

        # check flags for non-cron run (for dev)
        if cron == 0 or freq == 0:
            task(bot)
            return action

        # current UTC time in seconds since epoch
        epoch_time = int(time.time())

        # cron, frequency length in seconds, run_time
        cron_frequency = cron
        frequency = freq
        run_time = 0

        # do a single run
        timer_in = int(time.time())
        task(bot)
        timer_out = int(time.time())

        # run task X many more times per cron period
        for x in range(1, cron_frequency / frequency):
            # run time
            run_time = timer_out - timer_in

            # sleep for a a bit
            if run_time < frequency:
                time.sleep(frequency - run_time)

            # check if we are going to go over on next run
            est_time = (frequency * x) + run_time
            if est_time > cron_frequency:
                break

            # wrap task above with time in and out
            timer_in = int(time.time())
            task(bot)
            timer_out = int(time.time())
コード例 #5
0
ファイル: manage.py プロジェクト: replay/utter-va
	def action(
			cron=('c', 0),
			freq=('f', 0),
		):
		"""
		Provides Twitter command processing.

		Cron: Every 1 minute.
		"""

		# get bot settings
		bot = TwitterBot.get()
		
		# exit if we're not enabled
		if not bot:
			return action
		if not bot.enabled:
			print "The marketing bot is disabled."
			return action

		# check flags for non-cron run (for dev)
		if cron == 0 or freq == 0:
			task(bot)
			return action

		# current UTC time in seconds since epoch
		epoch_time = int(time.time())

		# cron, frequency length in seconds, run_time
		cron_frequency = cron
		frequency = freq
		run_time = 0

		# do a single run
		timer_in = int(time.time())
		task(bot)
		timer_out = int(time.time())

		# run task X many more times per cron period
		for x in range(1,cron_frequency/frequency):
			# run time
			run_time = timer_out - timer_in

			# sleep for a a bit
			if run_time < frequency:
				time.sleep(frequency - run_time)

			# check if we are going to go over on next run
			est_time = (frequency * x) + run_time
			if est_time > cron_frequency:
				break

			# wrap task above with time in and out
			timer_in = int(time.time())
			task(bot)
			timer_out = int(time.time())
コード例 #6
0
	def action():
		"""
		Posts marketing blurbs to Twitter.

		Cron: Depends on offering period.
		"""
		import random
		from webapp.libs.twitterbot import tweet_status

		# get bot settings
		bot = TwitterBot.get()

		# get the time
		epoch = int(time.time())

		if not bot:
			print "The marketing bot is disabled."
			return action

		if bot.announce == 0:
			print "The marketing bot is disabled."
			return action

		# if updated + announce > current time, do an update!
		if epoch > (bot.updated + (bot.announce * 3600)):
			# make up some stuff
			blurbs = [
				"Get your hot-n-fresh #openstack instances! ",
				"Instances for nothing and #bitcoins for free. ",
				"Now serving #42. ",
				"Pssst. Hey buddy, want some #openstack? ",
				"Sorry #openstack, we're all out of IPv4 addresses. ",
				"Any significantly advanced technology is indistinguishable from magic. ",
				"It's #bitcoin magic! ",
				"I'm hungry. Spare some #bitcoin? "
			]
			hashtags = [
				"trust",
				"cryptocurrency",
				"transparency",
				"globalcloud",
				"federation",
				"virtualization",
				"monkeys"
			]
			blurb = random.choice(blurbs)
			hashtag = random.choice(hashtags)
			
			# say it
			tweet_status("%s '@%s !status' for more info. #%s" % (blurb, bot.screen_name, hashtag))
			
			# update
			bot.updated = int(time.time())
			bot.update()
コード例 #7
0
ファイル: twitterbot.py プロジェクト: brooklynne/utter-va
def oauth_complete(oauth_verifier):
    # twitter credential db
    bot = TwitterBot.get()

    try:
        twitter = Twitter(
            auth=OAuth(bot.oauth_token, bot.oauth_token_secret, bot.consumer_key, bot.consumer_secret),
            format="",
            api_version=None,
        )
        oauth_token, oauth_token_secret, screen_name = parse_oauth_tokens(
            twitter.oauth.access_token(oauth_verifier=oauth_verifier)
        )
    except Exception as ex:
        return bot

        # twitter credential db
    bot = TwitterBot.get()

    # get a flavor we can use for default
    flavor = db.session.query(Flavors).order_by().first()

    # update the entry
    bot.screen_name = screen_name
    bot.oauth_url = ""  # becomes invalid
    bot.oauth_token = oauth_token
    bot.oauth_token_secret = oauth_token_secret
    bot.complete = 2
    bot.enabled = 1
    bot.flavor_id = flavor.id
    bot.max_instances = app.config["MAX_INSTANCES_DEFAULT"]
    bot.announce = 0
    bot.updated = int(time.time())
    bot.update()

    return bot
コード例 #8
0
def configure_twitter_tweet():
    # build response
    response = {
        "response": "success",
        "result": {
            "message": "Message goes here."
        }
    }

    # what are we suppose to do? (TODO convert to JSON POST, that's what)
    action = request.form.getlist('action')[0]

    # bot settings
    bot = TwitterBot.get()

    # tweet that shit
    if action == "tweet":
        ask = "%0.6f" % (float(bot.flavor.ask) / 1000000)
        response = tweet_status(
            u"Up to (%s) %s instances are now on sale for %s μBTC/hour via '@%s !status'."
            % (bot.max_instances, bot.flavor.name, ask, bot.screen_name))

    # disconnect twitter creds
    elif action == "disconnect":
        # this MUST say 'settings' for stream restart
        tweet_status("Appliance !settings dropping bot credentials.")
        bot.delete(bot)
        response['result'][
            'message'] = "Twitter credentials have been removed."

    # enable/disable bot
    elif action == "enabled":
        # this MUST say 'settings' for stream restart
        tweet_status("Appliance !settings enabling instance bot.")
        bot.enabled = True
        bot.update()
        response['result']['message'] = "Twitter bot has been enabled."

    elif action == "disabled":
        # this MUST say 'settings' for stream restart
        tweet_status(
            "Appliance !settings disabling bot temporarily.  I'll be back.")
        bot.enabled = False
        bot.update()
        response['result']['message'] = "Twitter bot has been disabled."

    return jsonify(response)
コード例 #9
0
ファイル: configurehandlers.py プロジェクト: replay/utter-va
def configure_twitter_tweet():
	# build response
	response = {"response": "success", "result": {"message": "Message goes here."}}

	# what are we suppose to do? (TODO convert to JSON POST, that's what)
	action = request.form.getlist('action')[0]
	
	# bot settings
	bot = TwitterBot.get()

	# tweet that shit
	if action == "tweet":
		ask = "%0.6f" % (float(bot.flavor.ask)/1000000)
		response = tweet_status(
			u"Up to (%s) %s instances are now on sale for %s μBTC/hour via '@%s !status'." % (
				bot.max_instances,
				bot.flavor.name, 
				ask,
				bot.screen_name
			)
		)

	# disconnect twitter creds
	elif action == "disconnect":
		# this MUST say 'settings' for stream restart
		tweet_status("Appliance !settings dropping bot credentials.")
		bot.delete(bot)
		response['result']['message'] = "Twitter credentials have been removed."

	# enable/disable bot
	elif action == "enabled":
		# this MUST say 'settings' for stream restart
		tweet_status("Appliance !settings enabling instance bot.")
		bot.enabled = True
		bot.update()
		response['result']['message'] = "Twitter bot has been enabled."

	elif action == "disabled":
		# this MUST say 'settings' for stream restart
		tweet_status("Appliance !settings disabling bot temporarily.  I'll be back.")
		bot.enabled = False
		bot.update()
		response['result']['message'] = "Twitter bot has been disabled."

	return jsonify(response)
コード例 #10
0
    def action():
        """
		Stream process for Twitter monitoring.  Do not run directly.
		"""
        from webapp.libs.twitterbot import get_stream

        # bot settings
        bot = TwitterBot.get()

        if bot:
            if bot.enabled:
                get_stream()
            else:
                # we're going to exit, and monit will try to restart
                # delay that a bit so monit doesn't freak out
                time.sleep(60)
        else:
            time.sleep(60)
コード例 #11
0
ファイル: manage.py プロジェクト: replay/utter-va
	def action():
		"""
		Stream process for Twitter monitoring.  Do not run directly.
		"""
		from webapp.libs.twitterbot import get_stream

		# bot settings
		bot = TwitterBot.get()

		if bot:
			if bot.enabled:
				get_stream()
			else:
				# we're going to exit, and monit will try to restart
				# delay that a bit so monit doesn't freak out
				time.sleep(60)
		else:
			time.sleep(60)
コード例 #12
0
ファイル: twitterbot.py プロジェクト: kordless/utter-va
def oauth_initialize():
    # twitter credential db
    bot = TwitterBot.get()

    if not bot:
        bot = TwitterBot()
        bot.consumer_key = app.config['CONSUMER_KEY']
        bot.consumer_secret = app.config['CONSUMER_SECRET']
        bot.complete = 0
        bot.enabled = 0
        bot.flavor_id = 0
        bot.max_instances = app.config['MAX_INSTANCES_DEFAULT']
        bot.announce = 0
        bot.updated = int(time.time())

    # give twitter a holler
    try:
        twitter = Twitter(auth=OAuth("", "", bot.consumer_key,
                                     bot.consumer_secret),
                          format="",
                          api_version=None)

        # screen name won't be set until oauth_complete runs
        oauth_token, oauth_token_secret, screen_name = parse_oauth_tokens(
            twitter.oauth.request_token())
        oauth_url = "https://api.twitter.com/oauth/authorize?oauth_token=%s" % oauth_token

    except Exception as ex:
        return bot

    # update the entries with what we got back
    bot.oauth_token = oauth_token
    bot.oauth_token_secret = oauth_token_secret
    bot.oauth_url = oauth_url
    bot.screen_name = screen_name
    bot.complete = 1
    bot.enabled = 0
    bot.flavor_id = 0
    bot.max_instances = app.config['MAX_INSTANCES_DEFAULT']
    bot.announce = 0
    bot.updated = int(time.time())
    bot.update()

    return bot
コード例 #13
0
ファイル: twitterbot.py プロジェクト: brooklynne/utter-va
def oauth_initialize():
    # twitter credential db
    bot = TwitterBot.get()

    if not bot:
        bot = TwitterBot()
        bot.consumer_key = app.config["CONSUMER_KEY"]
        bot.consumer_secret = app.config["CONSUMER_SECRET"]
        bot.complete = 0
        bot.enabled = 0
        bot.flavor_id = 0
        bot.max_instances = app.config["MAX_INSTANCES_DEFAULT"]
        bot.announce = 0
        bot.updated = int(time.time())

        # give twitter a holler
    try:
        twitter = Twitter(auth=OAuth("", "", bot.consumer_key, bot.consumer_secret), format="", api_version=None)

        # screen name won't be set until oauth_complete runs
        oauth_token, oauth_token_secret, screen_name = parse_oauth_tokens(twitter.oauth.request_token())
        oauth_url = "https://api.twitter.com/oauth/authorize?oauth_token=%s" % oauth_token

    except Exception as ex:
        return bot

        # update the entries with what we got back
    bot.oauth_token = oauth_token
    bot.oauth_token_secret = oauth_token_secret
    bot.oauth_url = oauth_url
    bot.screen_name = screen_name
    bot.complete = 1
    bot.enabled = 0
    bot.flavor_id = 0
    bot.max_instances = app.config["MAX_INSTANCES_DEFAULT"]
    bot.announce = 0
    bot.updated = int(time.time())
    bot.update()

    return bot
コード例 #14
0
def configure_twitter():
    # check configuration
    settings = Status().check_settings()

    # get the forms for the page
    form = TwitterForm(request.form)
    mrof = BotForm(request.form)

    # blow the flavors into a list
    flavor_list = []
    flavors = Flavors.get_all()
    for flavor in flavors:
        flavor_list.append((flavor.id, flavor.description))

    mrof.flavor.choices = flavor_list

    # twitter bot credentials
    bot = TwitterBot.get()

    # initialize the bot if it's not
    if not bot:
        bot = oauth_initialize()
    else:
        if bot.complete == 0:
            bot = oauth_initialize()

        if bot.complete == 1 and request.method == "GET":
            # ensure we don't use stale creds
            bot = oauth_initialize()

        elif bot.complete == 1 and request.method == "POST":
            if form.validate_on_submit():
                pin = request.form["pin"]
                bot = oauth_complete(pin)
                if bot:
                    flash("Authentication with Twitter complete.", "success")
                else:
                    flash("Authentication with Twitter failed.", "error")
                    bot = TwitterBot.get()
                    bot.delete(bot)
                    return redirect(url_for(".configure_twitter"))
            else:
                # form was not valid, so show errors
                flash("There were form errors. Please check your entries and try again.", "error")

        elif request.method == "POST":
            if mrof.validate_on_submit():
                bot.flavor_id = mrof.flavor.data
                bot.announce = mrof.announce.data
                bot.max_instances = mrof.max_instances.data
                bot.updated = int(time.time())
                bot.update()

                if bot.announce > 0:
                    # announce (requires 'settings' in comment to reload stream bot)
                    tweet_status(
                        "Appliance settings updated. Now serving up to (%s) %s instances via '@%s !status'"
                        % (bot.max_instances, bot.flavor.name, bot.screen_name)
                    )
                flash("Bot settings updated.", "success")
            else:
                # form was not valid, so show errors
                flash("There were form errors. Please check your entries and try again.", "error")

                # no bot not hot
    if not bot:
        flash("Twitterbot failed to contact Twitter or get credentials.", "error")
        bot = None

    else:
        # set default form values
        mrof.flavor.data = bot.flavor_id
        mrof.announce.data = bot.announce

    return render_template("configure/twitter.html", bot=bot, settings=settings, form=form, mrof=mrof)
コード例 #15
0
def configure_twitter():
    # check configuration
    settings = Status().check_settings()

    # get the forms for the page
    form = TwitterForm(request.form)
    mrof = BotForm(request.form)

    # blow the flavors into a list
    flavor_list = []
    flavors = Flavors.get_all()
    for flavor in flavors:
        flavor_list.append((flavor.id, flavor.description))

    mrof.flavor.choices = flavor_list

    # twitter bot credentials
    bot = TwitterBot.get()

    # initialize the bot if it's not
    if not bot:
        bot = oauth_initialize()
    else:
        if bot.complete == 0:
            bot = oauth_initialize()

        if bot.complete == 1 and request.method == 'GET':
            # ensure we don't use stale creds
            bot = oauth_initialize()

        elif bot.complete == 1 and request.method == 'POST':
            if form.validate_on_submit():
                pin = request.form['pin']
                bot = oauth_complete(pin)
                if bot:
                    flash("Authentication with Twitter complete.", "success")
                else:
                    flash("Authentication with Twitter failed.", "error")
                    bot = TwitterBot.get()
                    bot.delete(bot)
                    return redirect(url_for(".configure_twitter"))
            else:
                # form was not valid, so show errors
                flash(
                    "There were form errors. Please check your entries and try again.",
                    "error")

        elif request.method == 'POST':
            if mrof.validate_on_submit():
                bot.flavor_id = mrof.flavor.data
                bot.announce = mrof.announce.data
                bot.max_instances = mrof.max_instances.data
                bot.updated = int(time.time())
                bot.update()

                if bot.announce > 0:
                    # announce (requires 'settings' in comment to reload stream bot)
                    tweet_status(
                        "Appliance settings updated. Now serving up to (%s) %s instances via '@%s !status'"
                        %
                        (bot.max_instances, bot.flavor.name, bot.screen_name))
                flash("Bot settings updated.", "success")
            else:
                # form was not valid, so show errors
                flash(
                    "There were form errors. Please check your entries and try again.",
                    "error")

    # no bot not hot
    if not bot:
        flash("Twitterbot failed to contact Twitter or get credentials.",
              "error")
        bot = None

    else:
        # set default form values
        mrof.flavor.data = bot.flavor_id
        mrof.announce.data = bot.announce

    return render_template('configure/twitter.html',
                           bot=bot,
                           settings=settings,
                           form=form,
                           mrof=mrof)
コード例 #16
0
ファイル: twitterbot.py プロジェクト: kordless/utter-va
def get_stream():
    # loop forever trying to talk to twitter
    while True:
        # load and check bot settings
        bot = TwitterBot.get()
        if not bot.enabled:
            sys.exit()

        # authenticate and begin
        try:
            auth = OAuth(bot.oauth_token, bot.oauth_token_secret,
                         bot.consumer_key, bot.consumer_secret)

            # establish connection
            twitter_userstream = TwitterStream(auth=auth,
                                               domain='userstream.twitter.com')

            # iterator provides infinite status updates
            for update in twitter_userstream.user():
                # look in the update for a text message (others include delete, friends)
                if 'text' in update:
                    # skip it if it's a reply
                    if update['in_reply_to_status_id']:
                        continue

                    # load the screen name/username
                    user = update['user']['screen_name']

                    # check if somebody said 'settings' and then restart
                    if "!settings" in update['text']:
                        sys.exit()

                    # grab the command in the format !instance
                    r = re.search('\!([a-zA-Z]*)', update['text'])
                    try:
                        command = r.group(1)
                    except:
                        # always need a command
                        continue

                    # ignore ourselves
                    if user == bot.screen_name:
                        continue

                    # ditch it if it's blank
                    if command == "":
                        continue

                    # extract a url following a ^
                    try:
                        r = re.search('\^(\S*)', update['text'])
                        url = r.group(1)

                    except:
                        url = ""

                    # grab an instance name in the format ~smi-avv4mtmm
                    instance = None
                    try:
                        r = re.search('\~(\S*)', update['text'])

                        # extract and lookup instance by name
                        instance_name = r.group(1)
                        instance = db.session.query(Instances).filter_by(
                            name=instance_name).first()

                    except:
                        pass

                    # write to database
                    tc = TweetCommands()
                    tc.created = int(time.time())
                    tc.updated = int(time.time())
                    tc.user = user
                    tc.command = command.lower()
                    tc.url = url

                    if instance:
                        tc.instance_id = instance.id
                    else:
                        tc.instance_id = 0

                    tc.state = 1  # initialize
                    tc.update()

                    # send message
                    message("Received a command from Twitter", "success",
                            False)
                    app.logger.info("Received a command=(%s) from Twitter." %
                                    tc.command)
                else:
                    # other types of messages
                    pass

        except Exception as ex:
            app.logger.error(
                "Twitter stream disconnected.  Letting monit handle restart.")
            time.sleep(15)

    return
コード例 #17
0
ファイル: twitterbot.py プロジェクト: brooklynne/utter-va
def get_stream():
    # loop forever trying to talk to twitter
    while True:
        # load and check bot settings
        bot = TwitterBot.get()
        if not bot.enabled:
            sys.exit()

            # authenticate and begin
        try:
            auth = OAuth(bot.oauth_token, bot.oauth_token_secret, bot.consumer_key, bot.consumer_secret)

            # establish connection
            twitter_userstream = TwitterStream(auth=auth, domain="userstream.twitter.com")

            # iterator provides infinite status updates
            for update in twitter_userstream.user():
                # look in the update for a text message (others include delete, friends)
                if "text" in update:
                    # skip it if it's a reply
                    if update["in_reply_to_status_id"]:
                        continue

                        # load the screen name/username
                    user = update["user"]["screen_name"]

                    # check if somebody said 'settings' and then restart
                    if "!settings" in update["text"]:
                        sys.exit()

                        # grab the command in the format !instance
                    r = re.search("\!([a-zA-Z]*)", update["text"])
                    try:
                        command = r.group(1)
                    except:
                        # always need a command
                        continue

                        # ignore ourselves
                    if user == bot.screen_name:
                        continue

                        # ditch it if it's blank
                    if command == "":
                        continue

                        # extract a url following a ^
                    try:
                        r = re.search("\^(\S*)", update["text"])
                        url = r.group(1)

                    except:
                        url = ""

                        # grab an instance name in the format ~smi-avv4mtmm
                    instance = None
                    try:
                        r = re.search("\~(\S*)", update["text"])

                        # extract and lookup instance by name
                        instance_name = r.group(1)
                        instance = db.session.query(Instances).filter_by(name=instance_name).first()

                    except:
                        pass

                        # write to database
                    tc = TweetCommands()
                    tc.created = int(time.time())
                    tc.updated = int(time.time())
                    tc.user = user
                    tc.command = command.lower()
                    tc.url = url

                    if instance:
                        tc.instance_id = instance.id
                    else:
                        tc.instance_id = 0

                    tc.state = 1  # initialize
                    tc.update()

                    # send message
                    message("Received a command from Twitter", "success", False)
                    app.logger.info("Received a command=(%s) from Twitter." % tc.command)
                else:
                    # other types of messages
                    pass

        except Exception as ex:
            app.logger.error("Twitter stream disconnected.  Letting monit handle restart.")
            time.sleep(15)

    return