Ejemplo n.º 1
0
    def loadtest_logic(self, tweet, tweet_id, screen_name, user_id):
        """Logic similar to what is being used in the real bot so that we can 
        load test how much volume it can handle before twitter kicks it off 
        """
        # use SUTime to parse a datetime out of tweet
        time_room = self.parse_time_room(tweet)

        # fake time in the future that imitates a event's start time
        local_tz = pytz.timezone('US/Pacific')
        sample_time = datetime.datetime.now(local_tz) + datetime.timedelta(
            minutes=10)
        sample_time = sample_time.strftime("%Y-%m-%d %H:%M:%S")

        converted_time = time_utils.convert_to_utc(sample_time)
        room = "r123"

        # check for a time and room conflict, only 1 set of retweets per event
        conflict = db_utils.check_time_room_conflict(converted_time, room)

        # send message to slack when a tweet is scheduled to go out
        slack_message = "{} From: {}, id: {}".format(tweet, screen_name,
                                                     user_id)
        self.slacker.chat.post_message('#loadtest_tweets', slack_message)

        # This record lets us check that retweets not for same event
        db_utils.create_event(description=tweet,
                              start=converted_time,
                              location=room,
                              creator=screen_name)

        tweet_utils.loadtest_schedule_tweets(screen_name, tweet, tweet_id,
                                             converted_time)
        print("tweet scheduled for retweet: {}".format(tweet))
Ejemplo n.º 2
0
    def retweet_logic(self, tweet, tweet_id, screen_name, user_id):
        """Use SUTime to try to parse a datetime out of a tweet, if successful
        save tweet to OutgoingTweet to be retweeted
        """
        # use SUTime to parse a datetime out of tweet
        time_room = self.parse_time_room(tweet)

        # make sure both time and room extracted and only one val each
        val_check = self.value_check(time_room)

        if val_check == (1, 1):
            room = time_room["room"][0]
            date_mention = tweet_utils.check_date_mention(tweet)
            converted_time = time_utils.convert_to_utc(time_room["date"][0],
                                                       date_mention)

            # check for a time and room conflict, only 1 set of retweets per event
            # default time range that a room is resrved for is -15 +30 mins
            conflict = db_utils.check_time_room_conflict(converted_time, room)

            if not conflict:
                # send message to slack when a tweet is scheduled to go out
                slack_message = "{} From: {}, id: {}".format(
                    tweet, screen_name, user_id)
                self.send_slack_message('#outgoing_tweets', slack_message)

                self.send_mention_tweet(screen_name)

                # This record lets us check that retweets not for same event
                db_utils.create_event(description=tweet,
                                      start=converted_time,
                                      location=room,
                                      creator=screen_name)

                tweet_utils.schedule_tweets(screen_name, tweet, tweet_id,
                                            converted_time)
                loggly.info(
                    "scheduled this tweet for retweet: {}".format(tweet))

            else:
                message = """Tweet recived for an event bot is already scheduled
                    to retweet about. Sender: {}, room: {}, time: {}, 
                    tweet: {} tweet_id: {}
                    """
                message = message.format(screen_name, room, converted_time,
                                         tweet, tweet_id)
                self.send_slack_message("#event_conflict", message)
                loggly.info(message)

        elif val_check == (0, 0):
            # tweet found but without valid time or room extracted, ignore
            pass

        else:
            # tweet with relevant information but not exactly 1 time & 1 room
            message = """Tweet found that needs review: {}  tweet_id: {}
                screen_name: {}, user_id: {}
                """
            message = message.format(tweet, tweet_id, screen_name, user_id)
            self.send_slack_message("#need_review", message)
Ejemplo n.º 3
0
    def test_update_time_and_room_utils_works(self):
        no_records = OpenspacesEvent.objects.all()
        self.assertEqual(len(no_records), 0)

        # make call to utils func to create a db record
        db_utils.create_event(start=datetime.now(timezone.utc),
                              creator="fakeusername",
                              location="B123",
                              description="a fake tweet used in description")

        should_be_one = OpenspacesEvent.objects.all()
        self.assertEqual(len(should_be_one), 1)
Ejemplo n.º 4
0
    def loadtest_logic(self, tweet, tweet_id, screen_name, user_id):
        """Logic similar to what is being used in the real bot so that we can
        load test how much volume it can handle before twitter kicks it off
        """
        # use SUTime to parse a datetime out of tweet
        time_room = self.parse_time_room(tweet)

        # fake time in the future that imitates a event's start time
        local_tz = pytz.timezone('US/Eastern')
        sample_time = datetime.datetime.now(local_tz) + datetime.timedelta(
            minutes=10)
        sample_time = sample_time.strftime("%Y-%m-%d %H:%M:%S")

        event_time = time_utils.convert_to_utc(sample_time)
        room = random.randint(0, 3000)

        # check for a time and room conflict, only 1 set of retweets per event
        conflict = db_utils.check_time_room_conflict(event_time, room)

        if not conflict:
            # This record lets us check that retweets not for same event
            event_obj = db_utils.create_event(description=tweet,
                                              start=event_time,
                                              location=room,
                                              creator=screen_name)

            tweet_utils.loadtest_schedule_tweets(screen_name=screen_name,
                                                 tweet=tweet,
                                                 tweet_id=tweet_id,
                                                 event_time=event_time,
                                                 event_obj=event_obj)

            print("tweet scheduled for retweet: {}".format(tweet))

            slack_msg = "{} From: {}, id: {}".format(tweet, screen_name,
                                                     user_id)
            # self.send_slack_message('#outgoing_tweets', slack_message)

            send_slack_message(user_id=user_id,
                               tweet_id=tweet_id,
                               screen_name=screen_name,
                               tweet_created=True,
                               tweet=tweet,
                               slack_msg=slack_msg,
                               event_obj=event_obj)

        else:
            print("conflict when scheduling the tweet")
Ejemplo n.º 5
0
    def retweet_logic(self, tweet, tweet_id, screen_name, user_id):
        """Use SUTime to try to parse a datetime out of a tweet, if successful
        save tweet to OutgoingTweet to be retweeted
        """
        # use SUTime to parse a datetime out of tweet
        time_room = self.parse_time_room(tweet)

        # make sure both time and room extracted and only one val each
        val_check = self.value_check(time_room)

        if val_check == (1, 1):
            room = time_room["room"][0]
            date_mention = tweet_utils.check_date_mention(tweet)
            converted_time = time_utils.convert_to_utc(time_room["date"][0],
                                                       date_mention)

            # check for a time and room conflict, only 1 set of retweets per event
            # default time range that a room is resrved for is -15 +30 mins
            conflict = db_utils.check_time_room_conflict(converted_time, room)

            if not conflict:
                # This record lets us check that retweets not for same event
                event_obj = db_utils.create_event(description=tweet,
                                                  start=converted_time,
                                                  location=room,
                                                  creator=screen_name)

                tweet_utils.schedule_tweets(screen_name, tweet, tweet_id,
                                            converted_time, event_obj)

                slack_msg = "{} \n Tweet from: {}, \n id: {}".format(
                    tweet, screen_name, user_id)

                send_slack_message(user_id=user_id,
                                   tweet_id=tweet_id,
                                   screen_name=screen_name,
                                   tweet_created=True,
                                   tweet=tweet,
                                   slack_msg=slack_msg)

                self.send_mention_tweet(screen_name)

            else:
                message = f"Tweet found for an already scheduled event: \n {tweet}"
                send_slack_message(user_id=user_id,
                                   tweet_id=tweet_id,
                                   screen_name=screen_name,
                                   tweet_created=False,
                                   tweet=tweet,
                                   slack_msg=message,
                                   channel="conflict")

        elif val_check == (0, 0):
            # tweet found but without valid time or room extracted, ignore
            pass

        else:
            # tweet with relevant information but not exactly 1 time & 1 room
            slack_msg = "Tweet found that needs review: {} \n tweet_id: {} \n screen_name: {} \n user_id: {}"
            slack_msg = slack_msg.format(tweet, tweet_id, screen_name, user_id)

            send_slack_message(user_id=user_id,
                               tweet_id=tweet_id,
                               screen_name=screen_name,
                               tweet_created=False,
                               tweet=tweet,
                               slack_msg=slack_msg)
Ejemplo n.º 6
0
def message_update_func(json_data):
    """
    Take the original message and update the default in the
    selected button with the one selected. If user clicks approve/deny
    use current default text values for each button as values and update
    tweet model
    """
    # extract information from Slack payload into vars
    tweet_type, tweet_id, screen_name = json_data["callback_id"].split("|")
    original_msg = json_data["original_message"]
    user_action = json_data["actions"]
    slack_user = json_data["user"]["name"]
    action_ts = json_data["action_ts"]

    # two types of actions in our messages "select" or "button"
    action_type = user_action[0]["type"]
    actions_list = original_msg["attachments"][0]["actions"]

    if action_type == "select":
        # modify the original message and update with a user's drop down selection
        selected_val = user_action[0]["selected_options"][0]["value"]
        selected_action = user_action[0]["name"]

        for sub_action in actions_list:
            if selected_action == sub_action["name"]:
                sub_action["text"] = selected_val

    elif action_type == "button":
        action_val = user_action[0]["value"]

        if action_val == "submit":
            # lookup dict to convert text options in slack buttons to db value
            db_val_lookup = {"Needs approval": "0",
                             "Approve": "1",
                             "Deny": "2"}

            # build up a dict of all choices made by slack user
            final_vals = {}
            for sub_action in actions_list:
                if sub_action["type"] == "select":
                    try:
                        choosen_val = db_val_lookup[sub_action["text"]]
                    except KeyError:
                        choosen_val = sub_action["text"]
                    final_vals[sub_action["name"]] = choosen_val

            # check to make sure there are values filled out for each field
            for choice in final_vals.values():
                if bool(re.search("Choose", choice)):
                    return footer_creator(original_msg, slack_user, action_ts, "missing_info")


            # vars pulled out of slack message that are needed to save the model obj
            event_datetime = button_format_to_utc_datetime(final_vals["slack_date"], final_vals["slack_time"])
            event_location = final_vals["slack_room"]
            tweet = original_msg["attachments"][0]["text"]
            approval_val = final_vals["slack_approved"]

            original_msg = footer_creator(original_msg, slack_user, action_ts, approval_val)

            # check if the tweet already exists, then update/or create
            try:
                # update the exsisting tweet instance
                target_tweet = OutgoingTweet.objects.get(tweet_id=tweet_id)
                target_tweet.approved = approval_val
                target_tweet.scheduled_time = event_datetime - datetime.timedelta(minutes=15) # calc the new remind time if update in slack
                target_tweet.save()

                # update the coresponding event
                event_id = target_tweet.event_obj.id
                event_instance = OpenspacesEvent.objects.get(id=event_id)
                event_instance.start = event_datetime
                event_instance.location = event_location
                event_instance.save()

            except OutgoingTweet.DoesNotExist:
                # need to create a new outgoing tweet instance and the event that goes with it
                event_obj = db_utils.create_event(description=tweet,
                                                  start=event_datetime,
                                                  location=event_location,
                                                  creator=screen_name)

                tweet_utils.schedule_slack_tweets(tweet_id=tweet_id,
                                                  screen_name=screen_name,
                                                  tweet=tweet,
                                                  approved=int(approval_val),
                                                  event_time=event_datetime,
                                                  event_obj=event_obj)

    else:
        # this shouldn't ever happen
        raise ValueError("missing action value in message")

    return original_msg