Skip to content

Commit

Permalink
Added output adapter for mailgun api.
Browse files Browse the repository at this point in the history
  • Loading branch information
gunthercox committed May 11, 2016
1 parent e076eca commit f73a04d
Show file tree
Hide file tree
Showing 2 changed files with 78 additions and 0 deletions.
47 changes: 47 additions & 0 deletions chatterbot/adapters/output/mailgun.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
from chatterbot.adapters.output import OutputAdapter
import requests


class MailgunAdapter(OutputAdapter):

def __init__(self, **kwargs):
super(MailgunAdapter, 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")
self.recipients = kwargs.get("mailgun_recipients")

def send_message(self, subject, text, from_address, recipients):
"""
* subject: Subject of the email.
* text: Text body of the email.
* from_email: The email address that the message will be sent from.
* recipients: A list of recipient email addresses.
"""
return requests.post(
self.endpoint,
auth=("api", self.api_key),
data={
"from": "%s <%s>" % (self.name, from_address),
"to": recipients,
"subject": subject,
"text": text
})

def process_response(self, statement):
"""
Send the response statement as an email.
"""
subject = "Message from %s" % (self.name)

self.send_message(
subject,
statement.text,
self.from_address,
self.recipients
)

return statement
31 changes: 31 additions & 0 deletions examples/mailgun.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
from chatterbot import ChatBot
from settings import MAILGUN

'''
To use this example, create a new file called settings.py.
In settings.py define the following:
MAILGUN = {
"CONSUMER_KEY": "my-mailgun-api-key",
"API_ENDPOINT": "https://api.mailgun.net/v3/my-domain.com/messages"
}
'''

# Change these to match your own email configuration
FROM_EMAIL = "mailgun@salvius.org"
RECIPIENTS = ["gunthercx@gmail.com"]

bot = ChatBot(
"Mailgun Example Bot",
mailgun_from_address=FROM_EMAIL,
mailgun_api_key=MAILGUN["CONSUMER_KEY"],
mailgun_api_endpoint=MAILGUN["API_ENDPOINT"],
mailgun_recipients=RECIPIENTS,
output_adapter="chatterbot.adapters.io.MailgunAdapter",
storage_adapter="chatterbot.adapters.storage.JsonDatabaseAdapter",
database="../database.db"
)

# Send an example email to the address provided
response = bot.get_response("How are you?")
print("Check your inbox at ", RECIPIENTS)

0 comments on commit f73a04d

Please sign in to comment.