add email notifications

This commit is contained in:
Ben Harris 2020-07-13 11:59:43 -04:00
parent dd3dba5d40
commit 369ccd3c53
1 changed files with 44 additions and 3 deletions

View File

@ -4,6 +4,7 @@ import random
from dns.resolver import query
from email.utils import parseaddr
from mastodon import Mastodon
from smtplib import SMTP
from src import ModuleManager, utils
CHANNEL = "#tilderadio"
@ -46,6 +47,19 @@ SLOGANS = [
"that's not what she said!",
"not product placement, we promise! (tildestore.com)",
]
EMAIL_TEMPLATE = """
From: radiobot <radiobot@tilde.chat>
To: {nickname} <{email_addr}>
Subject: tilderadio: dj {dj} is now streaming!
{dj} just came on the air on tilderadio.org!
now playing: {now_playing}
have a listen here: {link}
~radiobot
"""
class Module(ModuleManager.BaseModule):
@ -102,9 +116,11 @@ class Module(ModuleManager.BaseModule):
server = self.bot.get_server_by_alias("tilde")
if server is not None:
# a different dj is online
if self.dj != "" and self.dj != previous_dj:
newdj_message = f"{self.dj} is now online playing {self.song}! tune in here now: {LISTEN_URL}"
# post toot to @tilderadio
self.mastodon.toot(newdj_message)
# send dm notifications
@ -118,8 +134,24 @@ class Module(ModuleManager.BaseModule):
message=newdj_message,
)
# TODO: send email notifications
# send email notifications
with SMTP("localhost") as smtp:
for nick, email in self.bot.get_setting(
"tilderadio-email-subscriptions", {}
).items():
smtp.sendmail(
"radiobot@tilde.chat",
email,
EMAIL_TEMPLATE.format(
nickname=nick,
email_addr=email,
dj=self.dj,
now_playing=self.format_nowplaying(),
link=LISTEN_URL,
),
)
# post to all registered channels
for channel_name in NOTIFY_CHANNELS:
if channel_name in server.channels:
channel = server.channels[channel_name]
@ -207,7 +239,11 @@ class Module(ModuleManager.BaseModule):
domain = addr.rsplit("@", 1)[-1]
try:
mxfound = bool(query(domain, "MX"))
# TODO: add email subscription if not already there
subs = self.bot.get_setting("tilderadio-email-subscriptions", {})
nick = event["user"].nickname
subs.update({nick: addr})
self.bot.set_setting("tilderadio-email-subscriptions", subs)
event["stdout"].write(
f"ok, i'll send an email to you at {addr} when a dj goes online"
)
@ -221,7 +257,12 @@ class Module(ModuleManager.BaseModule):
@utils.hook("received.command.emailunsubscribe")
@utils.kwarg("help", "stop sending email notifications")
def email_unsubscribe(self, event):
# TODO: remove email subscription if there
subs = self.bot.get_setting("tilderadio-email-subscriptions", {})
nick = event["user"].nickname
if nick in subs:
subs.pop(nick)
self.bot.set_setting("tilderadio-email-subscriptions", subs)
event["stdout"].write("ok i'll stop sending you emails")
@utils.hook("received.command.dj")