Last active
March 13, 2020 21:03
-
-
Save sweldon/9b10b7dbffde86bcf29b7415967504ea to your computer and use it in GitHub Desktop.
Handle SMS from Gmail
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import imaplib | |
mail = imaplib.IMAP4_SSL('imap.gmail.com') | |
mail.login(os.environ["EMAIL_USER"], os.environ["EMAIL_PASS"]) | |
def handle_text(): | |
mail.list() | |
# List of "folders" aka labels in gmail. | |
mail.select("inbox") | |
result, data = mail.search(None, "ALL") | |
ids = data[0] # data is a list. | |
id_list = ids.split() # ids is a space separated string | |
# Note: could get N emails back here | |
latest_email_id = id_list[-1] # get the latest | |
# fetch the email body (RFC822) for the given ID | |
result, data = mail.fetch(latest_email_id, "(RFC822)") | |
raw_email = data[0][1] | |
raw_email_string = raw_email.decode('utf-8') | |
email_message = email.message_from_string(raw_email_string) | |
action = None | |
user = None | |
if not email_message.is_multipart(): | |
user = email_message['From'] | |
action = email_message.as_string() | |
else: | |
# Get attachment and parse | |
for data in email_message.walk(): | |
if not user: | |
user = data.get('From') | |
if data.get_content_maintype() == 'multipart': | |
continue | |
if data.get('Content-Disposition') is None: | |
continue | |
fileName = data.get_filename() | |
# Create a temporary directory to download attachment | |
path = tempfile.mkdtemp() | |
if bool(fileName): | |
filePath = os.path.join(path, fileName) | |
if not os.path.isfile(filePath): | |
action = str(data.get_payload(decode=True)) | |
# Some custom logic I had for my project using Mongo | |
if not user: | |
return | |
if "start" in action.lower(): | |
if game.find({'game': 1}).count() > 0: | |
return "game already started" | |
game.insert_one({"game": 1}) | |
deck = deck_of_cards.DeckOfCards() | |
deck.shuffle_deck() | |
hands, deck = deal_hands(1, deck) | |
player_hand = random.sample(hands, 1)[0] | |
player_hand_str = ' '.join(player_hand) | |
return send(user, player_hand_str) | |
elif "end" in action.lower(): | |
game.delete_one({'game': 1}) | |
return "game ended" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment