Skip to content

Commit

Permalink
Added discord notifications
Browse files Browse the repository at this point in the history
  • Loading branch information
rojosinalma committed Nov 30, 2023
1 parent 413d326 commit 63cd673
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 0 deletions.
1 change: 1 addition & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,4 @@ RELAY_HOST= # Host where the relay will listen (Default: 0.0.0.0)
RELAY_PORT= # Port for the relay (Default: 50000)
RELAY_TIMEOUT= # Timeout for incoming requests
RELAY_DST_URL= # Destination url for the relayed requests (No default, can't be empty)
DISCORD_WEBHOOK_URL= # Send Discord notifications when successful
14 changes: 14 additions & 0 deletions app.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,25 @@

app = Flask(__name__)

def send_discord_notification(message):
discord_webhook_url = os.environ.get("DISCORD_WEBHOOK_URL")
if discord_webhook_url is None:
logging.error("DISCORD_WEBHOOK_URL environment variable is not set")
return

payload = { "content": message }
response = requests.post(discord_webhook_url, json=payload)
logging.info("Discord notification sent successfully")

def async_request(url, headers, data):
try:
res = requests.post(url, headers=headers, json=data, verify=False)
res.raise_for_status() # Raise an exception if the request was not successful (status code >= 400)
logging.info(f"Successfully relayed request to {url}")

message = "Request successfully relayed to " + url
send_discord_notification(message)

except requests.exceptions.RequestException as e:
logging.error(f"Failed to make a request to {url}: {e}")
except Exception as e:
Expand Down
16 changes: 16 additions & 0 deletions tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,5 +43,21 @@ def test_status_endpoint(self):
response = self.client.get('/status')
self.assertEqual(response.status_code, 200)

@patch('app.send_discord_notification')
@patch('app.requests.post')
def test_discord_notification_sent(self, mock_post, mock_send_discord_notification):
os.environ['RELAY_DST_URL'] = 'http://localhost'
os.environ['DISCORD_WEBHOOK_URL'] = 'http://discordwebhook'

# Mock a successful response from the relay destination
mock_post.return_value.status_code = 200

response = self.client.post('/webhooks/test')
self.assertEqual(response.status_code, 200)
self.assertEqual(response.json, {'success': True})

# Check if the Discord notification was sent
mock_send_discord_notification.assert_called_once_with("Request successfully relayed to http://localhost/test")

if __name__ == '__main__':
unittest.main()

0 comments on commit 63cd673

Please sign in to comment.