77 lines
3.8 KiB
Python
77 lines
3.8 KiB
Python
"""Durable Discord webhook delivery; secrets never enter queue payloads."""
|
|
import re
|
|
from urllib.parse import urlsplit
|
|
import requests
|
|
from flask import Blueprint, render_template, request, flash, redirect, url_for, g
|
|
from web_framework.auth import require_permission
|
|
from web_framework.plugins import Plugin, Setting, get_plugins
|
|
from web_framework.plugin_runtime import Service, QUEUE_SETTING, text, run_one
|
|
|
|
bp = Blueprint('plugin_discord_notifications', __name__, template_folder='templates')
|
|
|
|
|
|
def webhook_url(value):
|
|
parsed = urlsplit(text(value, 'Discord webhook URL', 2000))
|
|
if (parsed.scheme != 'https' or parsed.hostname not in {'discord.com', 'discordapp.com', 'canary.discord.com', 'ptb.discord.com'}
|
|
or parsed.username or parsed.password or parsed.query or parsed.fragment or parsed.port not in (None, 443)
|
|
or not re.fullmatch(r'/api(?:/v\d+)?/webhooks/\d+/[A-Za-z0-9_.-]+', parsed.path)):
|
|
raise ValueError('Use an official HTTPS Discord /api/webhooks/<id>/<token> URL.')
|
|
return value
|
|
|
|
|
|
class Notifications(Service):
|
|
plugin_id = 'discord-notifications'
|
|
|
|
def send(self, event, message):
|
|
event, message = text(event, 'Event', 100), text(message, 'Message', 1800)
|
|
settings = self.settings()
|
|
webhook_url(settings['webhook'])
|
|
selected = {value.strip() for value in settings['events'].split(',') if value.strip()}
|
|
if '*' not in selected and event not in selected:
|
|
return None
|
|
return self.enqueue('Notification: ' + event, {'event': event, 'message': message})
|
|
|
|
def process(self, payload, progress):
|
|
progress(0, 1, 'Sending notification.')
|
|
settings = self.settings()
|
|
url = webhook_url(settings['webhook'])
|
|
try:
|
|
response = requests.post(url, json={'content': f"**{payload['event']}**\n{payload['message']}", 'allowed_mentions': {'parse': []}}, timeout=(5, 15), allow_redirects=False)
|
|
if response.status_code == 429:
|
|
raise ValueError('Discord rate limit reached. Retry this job later.')
|
|
if not 200 <= response.status_code < 300:
|
|
raise ValueError('Discord rejected the webhook. Check its configuration.')
|
|
except requests.RequestException:
|
|
raise ValueError('Discord could not be reached. Retry this job later.') from None
|
|
progress(1, 1, 'Notification delivered.')
|
|
|
|
|
|
def service():
|
|
return get_plugins().service('discord-notifications', 'notify')
|
|
|
|
|
|
@bp.route('/', methods=['GET', 'POST'])
|
|
def index():
|
|
if request.method == 'POST':
|
|
return test_notification()
|
|
return render_template('discord-notifications/index.html', title='Discord Notifications', jobs=service().resolve('queue').jobs(source='discord-notifications', limit=25))
|
|
|
|
|
|
@require_permission('content.write')
|
|
def test_notification():
|
|
try:
|
|
job = service().send('test', 'Test notification requested from your workspace.')
|
|
service().state.audit(g.user['username'], 'discord-notifications.test')
|
|
flash('Test notification submitted. Check the Queue for delivery status.' if job else 'Test notification skipped by the event filter.', 'success')
|
|
except ValueError as exc:
|
|
flash(str(exc), 'error')
|
|
return redirect(url_for('plugin_discord_notifications.index'))
|
|
|
|
|
|
plugin = Plugin('discord-notifications', 'Discord Notifications', description='Queued webhook notifications with event filtering and no automatic mentions.', blueprint=bp,
|
|
endpoint='plugin_discord_notifications.index', hooks={'validate_settings': lambda values: webhook_url(values['webhook'])}, services={'notify': Notifications}, workers={'deliver': lambda: run_one(service())}, settings_schema={
|
|
'queue': QUEUE_SETTING,
|
|
'webhook': Setting('Discord webhook URL', kind='secret', required=True),
|
|
'events': Setting('Events (comma separated, or *)', default='*'),
|
|
})
|