Skip to content

Commit

Permalink
Merge pull request #13 from avaraline/discord-notification-updates
Browse files Browse the repository at this point in the history
update discord notification when players join and when server closes
  • Loading branch information
assertivist committed Apr 6, 2024
2 parents dc01430 + 2166a55 commit 21af859
Show file tree
Hide file tree
Showing 3 changed files with 91 additions and 16 deletions.
18 changes: 18 additions & 0 deletions tracker/migrations/0003_game_discord_msgid.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
# Generated by Django 3.2.13 on 2024-04-05 06:32

from django.db import migrations, models


class Migration(migrations.Migration):

dependencies = [
('tracker', '0002_game_password'),
]

operations = [
migrations.AddField(
model_name='game',
name='discord_msgid',
field=models.TextField(blank=True),
),
]
71 changes: 70 additions & 1 deletion tracker/models.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import datetime

import requests
from django.conf import settings
from django.db import models
from django.utils import timezone
Expand All @@ -13,6 +14,7 @@ class Game(models.Model):
players = models.TextField(blank=True)
description = models.TextField(blank=True)
password = models.BooleanField(default=False)
discord_msgid = models.TextField(blank=True)

class Meta:
unique_together = [
Expand All @@ -24,6 +26,19 @@ def prune(cls):
cutoff = timezone.now() - datetime.timedelta(
seconds=settings.TRACKER_PRUNE_SECONDS
)

if settings.TRACKER_DISCORD_WEBHOOK:
# cross out the game in discord
for game in cls.objects.filter(last_seen__lt=cutoff):
if not game.discord_msgid:
continue
try:
requests.patch(
settings.TRACKER_DISCORD_WEBHOOK + f"/messages/{game.discord_msgid}",
json={ "content": "~~" + game.discord_msg() + "~~" })
except:
pass

cls.objects.filter(last_seen__lt=cutoff).delete()

def update(self, data):
Expand All @@ -34,13 +49,67 @@ def update(self, data):

self.save()

def discord_msg(self):
players = self.player_list()
if len(players) < 1:
return ""
host = players[0]
address = self.address
description = self.description
myid = settings.TRACKER_DISCORD_ROLE_ID

msg = f"<@&{myid}> **{host}** is hosting at {address}"

if len(description) > 0:
msg += f" - *{description}*"

if len(players) == 2:
msg += f" - {players[1]} is playing"

if len(players) > 2:
plst = ", ".join(players[1:])
msg += f" - {plst} are playing"

return msg

def handle_notification(self, existing_msg):
d_url = settings.TRACKER_DISCORD_WEBHOOK
if not d_url:
return
new_msg = self.discord_msg()
if not self.discord_msgid:
# post new message
resp = requests.post(
# tell discord to be synchronous
# so we can get the message id
d_url + "?wait=true",
json={
"username": "Tracker",
"content": new_msg,
},
)
d_meta = resp.json()
msgid = d_meta["id"]
self.discord_msgid = msgid
self.save()
else:
if existing_msg != new_msg:
# update existing message
resp = requests.patch(
d_url + f"/messages/{self.discord_msgid}",
json={ "content": new_msg }
)

def player_list(self):
return [p.strip() for p in self.players.split("\n") if p.strip()]

def to_dict(self, **extra):
return {
"address": self.address,
"port": self.port,
"first_seen": self.first_seen.isoformat(),
"last_seen": self.last_seen.isoformat(),
"players": [p.strip() for p in self.players.split("\n") if p.strip()],
"players": self.player_list(),
"description": self.description.strip(),
"password": self.password,
**extra,
Expand Down
18 changes: 3 additions & 15 deletions tracker/views.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import json

import requests
from django.conf import settings
from django.core.exceptions import ObjectDoesNotExist
from django.http import Http404, JsonResponse
Expand Down Expand Up @@ -61,23 +60,12 @@ def post(self, request, *args, **kwargs):
game, created = Game.objects.get_or_create(
address=self.request_ip, port=int(self.json.get("port", 19567))
)
existing_msg = game.discord_msg()
game.update(self.json)
notify = (
created
and settings.TRACKER_DISCORD_WEBHOOK
settings.TRACKER_DISCORD_WEBHOOK
and (settings.TRACKER_DISCORD_NOTIFY_PASSWORDED or not game.password)
)
if notify:
requests.post(
settings.TRACKER_DISCORD_WEBHOOK,
json={
"username": "Tracker",
"content": "<@&{}> {} is hosting at {} - *{}*".format(
settings.TRACKER_DISCORD_ROLE_ID,
game.players.split("\n")[0],
game.address,
game.description,
),
},
)
game.handle_notification(existing_msg)
return game.to_dict()

0 comments on commit 21af859

Please sign in to comment.