Skip to content

Commit

Permalink
Add Mailgun input adapter
Browse files Browse the repository at this point in the history
  • Loading branch information
gunthercox committed Oct 31, 2016
1 parent c537e42 commit 894342f
Show file tree
Hide file tree
Showing 3 changed files with 57 additions and 1 deletion.
1 change: 1 addition & 0 deletions chatterbot/adapters/input/__init__.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from .input_adapter import InputAdapter
from .gitter import Gitter
from .hipchat import HipChat
from .mailgun import Mailgun
from .terminal import TerminalAdapter
from .variable_input_type_adapter import VariableInputTypeAdapter
54 changes: 54 additions & 0 deletions chatterbot/adapters/input/mailgun.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
from chatterbot.adapters.input import InputAdapter
from chatterbot.conversation import Statement
import requests
import datetime


class Mailgun(InputAdapter):

def __init__(self, **kwargs):
super(Mailgun, self).__init__(**kwargs)

# Use the bot's name for the name of the sender
self.name = kwargs.get('name')
self.from_address = kwargs.get('mailgun_from_address')
self.api_key = kwargs.get('mailgun_api_key')
self.endpoint = kwargs.get('mailgun_api_endpoint')

def get_email_stored_events(self):
yesterday = datetime.datetime.now() - datetime.timedelta(1)
return requests.get(
'{}/events'.format(self.endpoint),
auth=('api', self.api_key),
params={
'begin': yesterday.isoformat(),
'ascending': 'yes',
'limit': 1
}
)

def get_stored_email_urls(self):
response = self.get_email_stored_events()
data = response.json()

for item in data.get('items', []):
if 'storage' in item:
if 'url' in item['storage']:
yield item['storage']['url']

def get_message(self, url):
return requests.get(
url,
auth=('api', self.api_key)
)

def process_input(self, statement):
urls = m.get_stored_email_urls()
url = first(urls):

response = self.get_message(url)
message = response.json()

text = message.get('stripped-text')

return Statement(text)
3 changes: 2 additions & 1 deletion examples/mailgun.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,8 @@
mailgun_api_key=MAILGUN["CONSUMER_KEY"],
mailgun_api_endpoint=MAILGUN["API_ENDPOINT"],
mailgun_recipients=RECIPIENTS,
output_adapter="chatterbot.adapters.io.Mailgun",
input_adapter="chatterbot.adapters.input.Mailgun",
output_adapter="chatterbot.adapters.output.Mailgun",
storage_adapter="chatterbot.adapters.storage.JsonFileStorageAdapter",
database="../database.db"
)
Expand Down

0 comments on commit 894342f

Please sign in to comment.