def deleteOperation(tablename, key, user): # dynamodb = boto3.resource('dynamodb', region_name="us-east-1") # table = dynamodb.Table(tablename) # backup_table = dynamodb.Table('members_backup') table = dynamo_connect(tablename) backup_table = dynamo_connect("members_backup") peopleIveDeleted = "" for x in range(len(key)): print("Delete is attempting to DELETE: " + str(key[x]['value'])) entry = table.query( KeyConditionExpression=Key('name').eq(key[x]['value'])) # Backing up the entry in the case of accidental deletion. backup_entry(entry, backup_table) response = table.delete_item(Key={'name': key[x]['value']}) peopleIveDeleted += str(key[x]['value']) + ", " wooglin.sendmessage( "Well I've done it. If " + str(peopleIveDeleted[:len(peopleIveDeleted) - 2]) + " existed before, they don't now. If you accidentally deleted someone, contact Cole." )
def send_sms_exec(message): exec_members = [ "Cole Polyak", "Luke Srsen", "Evan Prechodko", "Thomas Oexeman", "Adam Snow", "Deegan Coles", "Rex Fathauer", "Caleb Bruce", "Cade Carter", "Kyle Waggoner" ] errors = [] message = "Message for the Executive Board: " + message # Sends to each exec member. for person in exec_members: print("Trying to notify: " + person) number = get_phone_number(person) resp = sendsms(number, message) if not resp: errors.append(person) if len(errors) == 0: wooglin.sendmessage("I successfully sent the executive board: " + message) else: message = "Okay. I've had some marginal success." message += "I was partially able to notify the executive board. I was unable to notify:\n" for person in errors: message += person + "," wooglin.sendmessage(message) return
def modifyOperation(resp, tablename, key): # dynamodb = boto3.resource('dynamodb', region_name="us-east-1") # table = dynamodb.Table(table) table = dynamo_connect(tablename) target = table.query( KeyConditionExpression=Key('name').eq(key[0]['value'])) # Our target doesn't exist in the table. if len(target) == 0: wooglin.sendmessage(stringify_member(target, tablename, key, "")) return attribute = resp['entities']['attribute'][0]['value'] new_value = resp['entities']['new_value'][0]['value'] print("attribute: " + str(attribute)) print("new_value: " + str(new_value)) response = table.update_item( Key={'name': key[0]['value']}, UpdateExpression='SET ' + str(attribute) + ' = :val1', ExpressionAttributeValues={':val1': new_value}) wooglin.sendmessage( stringify_update(response, key[0]['value'], attribute, new_value))
def createOperation(tablename, key): # dynamodb = boto3.resource('dynamodb', region_name='us-east-1') # table = dynamodb.Table(tablename) table = dynamo_connect(tablename) peopleIveCreated = "" for x in range(len(key)): table.put_item( Item={ 'name': key[x]['value'], 'phonenumber': 0, 'rollnumber': 0, 'address': "No Address", 'email': "no email", 'present': 0, 'unexcused': 0, 'excused': 0, 'excuses': [], 'absences': 0 }) peopleIveCreated += str(key[x]['value']) + ", " toReturn = "Well, I've added " + str( peopleIveCreated[:len(peopleIveCreated) - 1]) + " to " + tablename toReturn += ". However, their data is all null! You should probably fix that..." wooglin.sendmessage(toReturn)
def send_sms_chapter(message): data = DatabaseHandler.scanTable('members') account_sid = os.environ["TWILIO_SID"] auth_token = os.environ["TWILIO_TOKEN"] client = Client(account_sid, auth_token) for person in data: try: number = person['phonenumber'] binding_message = '{"binding_type":"sms", "address":"' + fix_phone_number_format( number) + '\"}' notification = client.notify.services(os.environ['TWILIO_NOTIFY_SERVICE_SID']) \ .notifications.create(to_binding=binding_message, body=message) # On the off chance someone has blacklisted Wooglin. except Exception as e: print("Errored on: " + number + " which should be: " + person['name']) continue if notification: wooglin.sendmessage("Alrighty! I have notified the chapter: " + message) else: wooglin.sendmessage( "I was unable to send that message to the chapter.")
def get_phone_number(key): dynamodb = boto3.resource('dynamodb', region_name="us-east-1") table = dynamodb.Table('members') resp = table.query(KeyConditionExpression=Key('name').eq(key)) try: number = resp['Items'][0]['phonenumber'] except KeyError as e: wooglin.sendmessage("Uh-oh. Looks like " + str(key) + " doesn't have a listed phonenumber.") return number
def getOperationSoberBros(tablename, date): # dynamodb = boto3.resource('dynamodb', region_name="us-east-1") # table = dynamodb.Table(table) table = dynamo_connect(tablename) response = table.query(KeyConditionExpression=Key('date').eq(date)) if len(response['Items']) == 0: message = "Looks like there aren't any sober bro shifts for " + str( unprocessDate(date)) + " yet." wooglin.sendmessage(message) return wooglin.sendmessage(stringify_soberbros(response['Items']))
def smshandler(resp): try: message = resp['entities']['message'][0]['value'] except KeyError: wooglin.sendmessage( "Uh-oh. Looks like I wasn't able to discern what you wanted me to send. Talk to Cole." ) return print("Trying to send message : " + str(message)) # Ensuring we get the proper date regardless of syntax used. if message == "ListSoberBros": try: date = resp['entities']['datetime'][0]['value'] except KeyError: try: date = resp['entities']['datetime'][0]['from']['value'] except KeyError: now = datetime.datetime.now() date = str(now.year) + "-" + str(now.month) + "-" + str( now.day) message = create_sober_bro_message(date) try: key = resp['entities']['key'][0]['value'] individual_sms_name(key, message) return except KeyError: print("No key specified... Could be a group message...") # No key given, let's see if there's a smslist specified. try: smslist = resp['entities']['smslist'][0]['value'] if smslist == "chapter": send_sms_chapter(message) return elif smslist == "exec": send_sms_exec(message) return elif smslist == "soberbros": send_sms_soberbros(message) return except KeyError: wooglin.sendmessage( "Oops. It looks like neither a name nor a smslist was specified. Talk to Cole." ) return
def sober_bro_deassign(tablename, key, date): SoberBros = list_sober_bros(tablename, date) key = key[0]['value'] # Only want active sober bro listings. SoberBros = [x for x in SoberBros if x != "NO ONE"] try: SoberBros.remove(key) except ValueError: wooglin.sendmessage("Oops. It looks like " + str(key) + " is not currently a sober bro on " + str(unprocessDate(date))) return message = "Alrighty! I've removed " + str( key) + " from the sober bro shift on " + str( unprocessDate(date)) + ".\nThere are now " + str( len(SoberBros)) + " sober brothers on that date." # Gotta have the proper grammar... if len(SoberBros) == 1: left = message.split("are") right = left[1].split("brothers") message = left[0] + "is" + right[0] + "brother" + right[1] wooglin.sendmessage(message) # Ensuring the table is fixed. while len(SoberBros) != 5: SoberBros.append("NO ONE") # dynamodb = boto3.resource("dynamodb", region_name="us-east-1") # table = dynamodb.Table("soberbros") table = dynamo_connect("soberbros") table.put_item( Item={ 'date': date, 'soberbro1': SoberBros[0], 'soberbro2': SoberBros[1], 'soberbro3': SoberBros[2], 'soberbro4': SoberBros[3], 'soberbro5': SoberBros[4] })
def no_sb_shift(): members = scanTable('members') soberbros = scanTable('soberbros') brothers = get_brothers(members) sober_brothers = get_sober_brothers(soberbros) print(type(brothers)) print(type(sober_brothers)) no_shifts = brothers - sober_brothers message = "These are the brothers who, according to my records, do not currently have sober bro shifts:\n" count = 0 for x in no_shifts: if count != len(no_shifts) - 1: message += str(x) + ", " else: message += "and " + str(x) + "." count = count + 1 wooglin.sendmessage(message)
def getOperation(tablename, key, attribute): # dynamodb = boto3.resource('dynamodb', region_name="us-east-1") # tablename = table # table = dynamodb.Table(table) table = dynamo_connect(tablename) # Handling for getting a list of users. if isinstance(key, list): print("In list option") for x in range(len(key)): # Getting the item! response = table.query( KeyConditionExpression=Key('name').eq(key[x]['value'])) print("Get operation returned: " + str(response)) wooglin.sendmessage( stringify_member(response['Items'], tablename, key, attribute)) elif isinstance(key, dict): # Getting one key. print("In dict option") # Getting the item! print("Starting get request with key : " + key[0]['value']) response = table.query( KeyConditionExpression=Key('name').eq(key[0]['value'])) print("Get operation returned: " + str(response)) wooglin.sendmessage( stringify_member(response['Items'], tablename, key, attribute)) elif isinstance(key, str): print("In String option!") print(str(key)) else: print("I'm not entirely sure how key was put into " + str(type(key)) + " but it was an I'm confused.")
def send_sms_soberbros(message): # Correcting for our timezone. Default is UTC. local_tz = pytz.timezone("US/Mountain") now = datetime.datetime.now() now = now.replace(tzinfo=pytz.utc).astimezone(local_tz) current_date = now.isoformat()[0:10] dynamodb = boto3.resource('dynamodb', region_name="us-east-1") table = dynamodb.Table('soberbros') response = table.query(KeyConditionExpression=Key('date').eq(current_date)) if len(response['Items']) == 0: message = "Looks like there aren't any sober bros for " + str( DatabaseHandler.unprocessDate(current_date) ) + ".\n Thus, I was unable to send them a message." wooglin.sendmessage(message) return response = response['Items'] SoberBros = [] SoberBros.append(response[0]['soberbro1'].strip()) SoberBros.append(response[0]['soberbro2'].strip()) SoberBros.append(response[0]['soberbro3'].strip()) SoberBros.append(response[0]['soberbro4'].strip()) SoberBros.append(response[0]['soberbro5'].strip()) SoberBros = [x for x in SoberBros if x != "NO ONE"] errors = [] # Notifies sober bros. for person in SoberBros: number = get_phone_number(person) try: sendsms(number, message) except Exception as e: errors.append(person) # All messages went through without issue. if len(errors) == 0: date_formatted = DatabaseHandler.unprocessDate(current_date) confirmation = "I've successfully sent the sober bros for " + date_formatted + " the message: " confirmation += message wooglin.sendmessage(confirmation) return # Messages went through with partial success. else: message = "Okay. I've had some marginal success." message += "I was partially able to notify the sober bros. I was unable to notify:\n" for person in errors: message += person + "," wooglin.sendmessage(message)
def sober_bro_assign(tablename, key, date): SoberBros = list_sober_bros(tablename, date) key = key[0]['value'] # We only want actual sober bros in the list. SoberBros = [x for x in SoberBros if x != "NO ONE"] if len(SoberBros) == 5: wooglin.sendmessage("It looks like the sober bro shift on " + str(unprocessDate(date)) + " is already full. I couldn't add " + str(key)) return if SoberBros.count(key) == 1: wooglin.sendmessage("Whoops! It looks like " + str(key) + " is already a sober bro on " + str(unprocessDate(date))) return SoberBros.append(key) message = "Alrighty! I've added " + str( key) + " to the sober bro shift on " + str( unprocessDate(date)) + ".\nThere are now " + str( len(SoberBros)) + " sober brothers on that date." # Gotta have the proper grammar... if len(SoberBros) == 1: left = message.split("are") right = left[1].split("brothers") message = left[0] + "is" + right[0] + "brother" + right[1] while len(SoberBros) != 5: SoberBros.append("NO ONE") # dynamodb = boto3.resource('dynamodb', region_name="us-east-1") # table = dynamodb.Table(tablename) table = dynamo_connect(tablename) table.put_item( Item={ 'date': date, 'soberbro1': SoberBros[0], 'soberbro2': SoberBros[1], 'soberbro3': SoberBros[2], 'soberbro4': SoberBros[3], 'soberbro5': SoberBros[4] }) wooglin.sendmessage(message)
def individual_sms_name(key, message): phone_number = get_phone_number(key) resp = sendsms(phone_number, message) wooglin.sendmessage("Alright! I've sent a message saying, \n[" + str(message) + "]\n to " + str(key)) return
def dbhandler(resp, user): # First, what are we doing? operation = resp['entities']['db_operation'][0]['value'] # Event creation. if "eventname" in resp['entities'] or "new_keyword" in resp['entities']: event_operation_handler(operation, resp) return "200 OK" # We probably have a key. try: key = resp['entities']['key'] except KeyError as e: key = "" # User specified an attribute. try: attribute = resp['entities']['attribute'][0]['value'] except KeyError as e: attribute = "" # User didn't specify a table, probably members. try: table = resp['entities']['table'][0]['value'] except KeyError as e: table = "members" print("key: " + str(key)) print("table: " + str(table)) print("attribute: " + str(attribute)) # TODO clean up this garbage routing table. if operation == "get": if table == "soberbros": date = extract_date(resp) print("Passing with get sober bros request: " + str(date)) getOperationSoberBros(table, date) else: getOperation(table, key, attribute) elif operation == "modify": modifyOperation(resp, table, key) elif operation == "close_event": event_operation_handler(operation, resp) elif operation == "delete": if table == "soberbros": date = extract_date(resp) sober_bro_deassign("soberbros", key, date) else: deleteOperation(table, key, user) elif operation == "create": createOperation(table, key) elif operation == "assign": date = extract_date(resp) sober_bro_assign("soberbros", key, date) elif operation == "deassign": date = extract_date(resp) sober_bro_deassign("soberbros", key, date) elif operation == "no_sb_shift": no_sb_shift() else: wooglin.sendmessage( "I'm sorry, that database functionality is either not understood or not supported" )
def handler(data): data['body'] = data['body'].encode() # We have to decode the message as its sent in base 64. message_parsed = (base64.b64decode(data['body'])) message_parsed = message_parsed.decode().split('&') message = dictify_message(message_parsed) current_event = get_current_event() # No event going on rn. if current_event == "none": SMSHandler.sendsms(message['From'], no_event_message()) return "200 OK" else: # Trigger for help flag raising. if message['Body'].lower().find('help') != -1: start_help_handler(message) return "200 OK" dynamodb = boto3.resource('dynamodb', region_name="us-east-1") table = dynamodb.Table(current_event) response = table.query( KeyConditionExpression=Key('number').eq(message['From'])) # If the number exists in our db and their flag is raised, let's forward their messages if response['Count'] != 0 and response['Items'][0]['help_flag']: notify_parties(response['Items'][0]['name'], message['Body']) SMSHandler.sendsms(response['Items'][0]['number'], "Successfully forwarded.") return "200 OK" # If the sender didn't have the keyword correct. if get_keyword() != "none": if not validate_keyword(message['Body']): SMSHandler.sendsms(message['From'], incorrect_keyword_message()) return "200 OK" # Ensuring the number doesn't exist in the DB yet. if response['Count'] == 0: SMSHandler.sendsms(message['From'], welcome_number_message(message['Body'])) table.put_item( Item={ 'number': message['From'], 'name': get_name(message['Body']), 'arrived': get_arrival_time(), 'help_flag': False, 'help_flag_raised': "n/a" }) current_guests = increment_guests(current_event) # Number of people attending the event. if current_guests % 50 == 0: wooglin.sendmessage("The current event: " + current_event + " has " + str(current_guests) + " guests registered.") else: SMSHandler.sendsms(message['From'], number_exists_message()) return "200 OK"
def event_operation_handler(operation, resp): # dynamodb = boto3.resource('dynamodb', region_name="us-east-1") dynamodb = dynamo_connect() # Creating an event. if operation == "create": response = dynamodb.create_table( AttributeDefinitions=[ { 'AttributeName': 'number', 'AttributeType': 'S', }, ], KeySchema=[ { 'AttributeName': 'number', 'KeyType': 'HASH', }, ], ProvisionedThroughput={ 'ReadCapacityUnits': 5, 'WriteCapacityUnits': 5, }, TableName=resp['entities']['eventname'][0]['value'], ) # Adding event to events db. table = dynamodb.Table('events') table.put_item( Item={ 'name': resp['entities']['eventname'][0]['value'], 'start_time': Wooglin_RM.get_arrival_time(), 'end_time': "currently active", 'guest_count': 0, 'comments': "none" }) keyword = "none" # Did the user specify a keyword at inception? if 'new_keyword' in resp['entities']: keyword = resp['entities']['new_keyword'][0]['value'] # Updating live entry. table.put_item( Item={ 'name': "active", 'comments': resp['entities']['eventname'][0]['value'], 'keyword': keyword }) # Yup. We got a keyword. if 'new_keyword' in resp['entities']: wooglin.sendmessage( "I have successfully created an event called : " + resp['entities']['eventname'][0]['value'] + ", with keyword " + resp['entities']['new_keyword'][0]['value']) # No keyword. else: wooglin.sendmessage( "I have successfully created an event called: " + resp['entities']['eventname'][0]['value'] + ". There is currently no keyword.") # Closing the current active event. elif operation == "close_event": table = dynamodb.Table('events') response = table.query( KeyConditionExpression=Key('name').eq('active'))['Items'][0] if response['comments'] == "none": wooglin.sendmessage( "Yikes. Doesn't look like there's an event going on right now." ) print("Terminating event: " + response['comments']) # Erasing the current party's active listing. table.put_item(Item={ 'name': "active", 'comments': "none", 'keyword': "none" }) # Grabbing the party's data from the events db. initial_data = table.query( KeyConditionExpression=Key('name').eq(response['comments'])) # Putting the new information about the party into the db. table.put_item( Item={ 'name': initial_data['Items'][0]['name'], 'start_time': initial_data['Items'][0]['start_time'], 'end_time': Wooglin_RM.get_arrival_time(), 'guest_count': initial_data['Items'][0]['guest_count'], 'comments': "Terminated by Wooglin." }) wooglin.sendmessage( "I have closed the current event. Somebody cue unwritten followed by closing time." ) # We're modifying the keyword. elif operation == "modify": table = dynamodb.Table('events') response = table.query( KeyConditionExpression=Key('name').eq('active'))['Items'][0] # No event happening. if response['comments'] == "none": wooglin.sendmessage( "Doesn't look like there's an event going on right now. I wasn't able to update the keyword." ) return "200 OK" # Let's update that keyword. table.put_item( Item={ 'name': 'active', 'comments': response['comments'], 'keyword': resp['entities']['new_keyword'][0]['value'] }) wooglin.sendmessage("I have updated the new event keyword to be: " + resp['entities']['new_keyword'][0]['value'])