This repository has been archived by the owner on Dec 25, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 482
/
mail.py
59 lines (49 loc) · 2.05 KB
/
mail.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
#!/usr/bin/env python
# coding=utf-8
import logging
import re
from v2ex.babel import Member
from google.appengine.ext import db
from google.appengine.ext import webapp
from google.appengine.ext.webapp.mail_handlers import InboundMailHandler
from google.appengine.ext.webapp.util import run_wsgi_app
from twitter.oauthtwitter import OAuthApi
from twitter.oauth import OAuthToken
from config import twitter_consumer_key as CONSUMER_KEY
from config import twitter_consumer_secret as CONSUMER_SECRET
def extract_address(raw):
if raw.find('<') == -1:
return raw
else:
return re.findall('<(.+)>', raw)[0]
class MailHandler(InboundMailHandler):
def receive(self, message):
bodies = message.bodies(content_type = 'text/plain')
for body in bodies:
to = extract_address(message.to)
sender = extract_address(message.sender.lower())
if to[0:5].lower() == 'tweet':
q = db.GqlQuery("SELECT * FROM Member WHERE email = :1", sender)
if q.count() == 1:
member = q[0]
if member.twitter_oauth == 1:
access_token = OAuthToken.from_string(member.twitter_oauth_string)
twitter = OAuthApi(CONSUMER_KEY, CONSUMER_SECRET, access_token)
status = body[1].decode()
if len(status) > 140:
status = status[0:140]
try:
logging.info("About to send tweet: " + status)
twitter.PostUpdate(status.encode('utf-8'))
logging.info("Successfully tweet: " + status)
except:
logging.error("Failed to tweet for " + member.username)
else:
logging.error("User " + sender + " doesn't have Twitter link.")
application = webapp.WSGIApplication([
MailHandler.mapping()
], debug=True)
def main():
run_wsgi_app(application)
if __name__ == "__main__":
main()