Created
August 12, 2012 10:32
-
-
Save drx/3331131 to your computer and use it in GitHub Desktop.
A small IMAP bot that searches for orders recently marked as done in an IMAP mailbox and marks them as done in Satchmo
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 | |
import re | |
from django.conf import settings | |
from django.core.cache import cache | |
def get_recent_done_orders(): | |
try: | |
orders = [] | |
M = imaplib.IMAP4_SSL(EMAIL_ORDERS_IMAP_HOST) | |
typ, data = M.login(settings.EMAIL_ORDERS_USERNAME, settings.EMAIL_ORDERS_PASSWORD) | |
if typ != 'OK': | |
raise Exception | |
typ, data = M.select('Order/Done') | |
if typ != 'OK': | |
raise Exception | |
typ, data = M.search(None, 'SINCE', (date.today()-timedelta(days=14)).strftime('%d-%b-%Y')) | |
if typ != 'OK': | |
raise Exception | |
email_ids = data[0].split() | |
for email_id in email_ids: | |
typ, data = M.fetch(email_id, '(BODY[HEADER.FIELDS (SUBJECT)])') | |
if typ != 'OK': | |
continue | |
match = re.match('Subject:.*? New order on Charsifood \(#(\d+)\)\s+', data[0][1]) | |
if match: | |
orders.append(int(match.group(1))) | |
return orders | |
except Exception: | |
return [] | |
def mark_done_orders(): | |
if cache.add('order_feed', 1): | |
orders = get_recent_done_orders() | |
for order in Order.objects.filter(status__exact='New').filter(id__in=orders): | |
order.add_status('Complete') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment