-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathgmail_api.py
153 lines (114 loc) · 5.12 KB
/
gmail_api.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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
from __future__ import print_function
import base64
import os.path
from email.message import EmailMessage
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError
import config
# If modifying these scopes, delete the file token.json.
SCOPES = ['https://www.googleapis.com/auth/gmail.modify']
def get_credentials():
creds = None
# The file token.json stores the user's access and refresh tokens, and is
# created automatically when the authorization flow completes for the first
# time.
if os.path.exists('token.json'):
creds = Credentials.from_authorized_user_file('token.json', SCOPES)
# If there are no (valid) credentials available, let the user log in.
if not creds or not creds.valid:
if creds and creds.expired and creds.refresh_token:
creds.refresh(Request())
else:
flow = InstalledAppFlow.from_client_secrets_file(
'credentials.json', SCOPES)
creds = flow.run_local_server(port=0)
# Save the credentials for the next run
with open('token.json', 'w') as token:
token.write(creds.to_json())
return creds
def get_service():
creds = get_credentials()
try:
# Call the Gmail API
return build('gmail', 'v1', credentials=creds)
except HttpError as error:
print(F'An error occurred: {error}')
def gmail_create_message(f_from, f_to, f_subject, f_in_reply_to, f_references, f_thread_id, f_answer):
print(f"Creating message: {f_subject}")
message = EmailMessage()
message.set_content(config.response_template.format(f_answer))
message['To'] = f_to
message['From'] = f_from
message['Subject'] = f_subject
message['In-Reply-To'] = f_in_reply_to
message['References'] = f_references
message['threadId'] = f_thread_id
# encoded message
encoded_message = base64.urlsafe_b64encode(message.as_bytes()).decode()
created_message = {
'message': {
'threadId': f_thread_id,
'raw': encoded_message
}
}
return created_message
def mark_as_read_by_bot(service, f_message_id, botlabel_id):
service.users().messages().modify(userId="me", id=f_message_id, body=dict(addLabelIds=[botlabel_id])).execute()
def post_draft_or_reply_message(service, created_message, reply_automatically=False):
try:
message = service.users().drafts().create(userId="me", body=created_message).execute()
print(F'Created Draft id: {message["id"]}\nDraft message: {message["message"]}')
if reply_automatically:
print("Sending draft")
service.users().drafts().send(userId="me", body=message).execute()
except HttpError as error:
print(F'An error occurred: {error}')
def get_label_id_for_botlabel(service, botname):
results = service.users().labels().list(userId='me').execute()
labels = results.get('labels', [])
for label in labels:
if label['name'] == botname:
return label["id"]
# if it gets here, it needs to create
label = service.users().labels().create(userId='me', body=dict(name=botname)).execute()
return label['id']
def gmail_get_unread(service, botname):
print("gmail_get_unread")
try:
inbox = service.users().messages().list(userId="me", q=f'in:inbox l:unread -l:{botname}').execute()
messages_raw = []
while True:
messages_raw += [service.users().messages().get(userId="me", id=m['id']).execute() for m in
inbox.get('messages', [])]
if 'pageToken' in inbox:
inbox = service.users().messages().list(userId="me", q='in:inbox',
pageToken=inbox['pageToken']).execute() # untested
else:
break
messages = []
for mraw in messages_raw:
payload = mraw['payload']
message = {d['name']: d['value'] for d in payload['headers'] if
d['name'] in ['From', 'To', 'Cc', 'Subject', 'Content-Type', 'Message-ID', 'References']}
body_message = ""
if (payload['body']['size'] != 0) and ('text/plain' in message['Content-Type']):
body_message = payload['body']['data']
elif 'parts' in payload and len(payload['parts']) > 0:
for part in payload['parts']:
if part['mimeType'] == 'text/plain':
body_message = part['body']['data']
if body_message != "":
body_message = base64.urlsafe_b64decode(body_message).decode()
message['Body'] = body_message
if 'Content-Type' in message:
message.pop('Content-Type')
message['threadId'] = mraw.get('threadId', '')
message['id'] = mraw.get('id')
messages.append(message)
return messages
except HttpError as error:
print(F'An error occurred: {error}')
return []