Skip to content

Instantly share code, notes, and snippets.

@emidln
Created October 23, 2021 20:19
Show Gist options
  • Save emidln/d8225215a3c84c7f15e27059d18ae7f4 to your computer and use it in GitHub Desktop.
Save emidln/d8225215a3c84c7f15e27059d18ae7f4 to your computer and use it in GitHub Desktop.
Takes a csv of people and phone numbers and sends out text messages for who they received in secret santa.
#!/usr/bin/env python3
import csv
import itertools
import os
import random
import sys
from twilio.rest import Client as TwilioClient
def parse_csv(people_csv):
db = {}
with open(people_csv, 'r') as dbf:
for idx, (person, _, _, phone_number, *blacklist) in enumerate(csv.reader(dbf)):
if idx == 0:
continue
db[person] = {'phone': phone_number, 'blacklist': set(blacklist)}
return db
def converge_upon_ordering(db):
class Retry(Exception):
pass
while True:
order = list(db.items())
random.shuffle(order)
pairs = []
try:
for giver, maybe_receiver in itertools.zip_longest(order, order[1:]):
receiver = maybe_receiver if maybe_receiver is not None else order[0]
if receiver[0] in giver[1]['blacklist']:
raise Retry()
pairs.append([giver, receiver])
except Retry:
print("Broken Constraint! Retrying...")
continue
return pairs
def message_template(pair):
template = """Season's Greetings from the Sorrells Family Secret Santa Bot! {giver_name}, for 2021 you have drawn {receiver_name}. Nobody else knows who you have drawn, so please save this text message. Happy Shopping!"""
return template.format(
giver_name=pair[0][0].split()[0],
receiver_name=pair[1][0],
)
def send_sms(our_phone, twilio_client, pair):
giver = pair[0]
msg = message_template(pair)
message = twilio_client.messages.create(
to = giver['phone'],
from_ = out_phone,
body = msg,
)
print({'sid': message.sid, 'our_phone': our_phone, 'pair': pair})
def main(people_csv):
db = parse_csv(people_csv)
ordering = converge_upon_ordering(db)
for giver, receiver in ordering:
print(f"{giver[0]} -> {receiver[0]}")
twilio_client = TwilioClient(
os.environ['TWILLIO_SID'],
os.environ['TWILLIO_AUTH_TOKEN']
)
for pair in ordering:
send_sms(our_phone, twilio_client, pair)
return 0
if __name__ == '__main__':
sys.exit(main(sys.argv[1]))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment