phantasmobile/app/item/tasks.py

69 lines
2.1 KiB
Python
Raw Normal View History

2023-07-25 09:33:50 +00:00
import os
import tempfile
import requests
2023-07-24 11:05:45 +00:00
from celery.schedules import crontab
from django.conf import settings
2023-07-25 09:33:50 +00:00
from django.utils import timezone
2023-07-24 11:05:45 +00:00
from ..signalbot import rpc
from ..celery import app
from . import models
2023-07-25 09:33:50 +00:00
2023-07-25 19:03:54 +00:00
@app.task(queue="default", ignore_results=True)
2023-07-24 11:05:45 +00:00
def announce_items():
2023-07-25 09:33:50 +00:00
if not getattr(settings, 'SIGNAL_ANNOUNCE_GROUP'):
return
now = timezone.now()
qs = models.Item.objects.exclude(published=None).filter(announced=None).filter(published__lte=now).order_by('published')
for item in qs:
item.announced = now
link = settings.BASE_URL + item.get_absolute_url()
message = link
image = item.data.get('thumbnail')
description = ""
if image:
f = tempfile.NamedTemporaryFile(suffix=".jpg", delete=False)
r = requests.get(image)
f.write(r.content)
f.close()
image = f.name
r = rpc.send(
message, group=settings.SIGNAL_ANNOUNCE_GROUP,
preview_url=link,
preview_title=item.title,
preview_image=image,
preview_description=description,
)
item.save()
if image:
os.unlink(f.name)
2023-07-24 11:05:45 +00:00
2023-07-25 19:03:54 +00:00
@app.task(queue="default", ignore_results=True)
2023-07-24 11:05:45 +00:00
def notify_moderators(id, link):
comment = models.Comment.objects.filter(id=id).first()
if comment:
2023-07-25 19:03:54 +00:00
message = "%s commented on %s (%s)\n\n%s" % (
comment.name, comment.item.title, link, comment.text
)
2023-07-24 11:05:45 +00:00
r = rpc.send(message, group=settings.SIGNAL_MODERATORS_GROUP)
if r and "timestamp" in r:
comment.data["moderator_ts"] = r["timestamp"]
comment.save()
2023-07-25 19:03:54 +00:00
if comment.published:
account = settings.SIGNAL_ACCOUNT
group = settings.SIGNAL_MODERATORS_GROUP
rpc.send_reaction(
account, comment.data["moderator_ts"], "🎉", group=group
)
2023-07-24 11:05:45 +00:00
else:
print("failed to notify", r)
2023-07-25 19:03:54 +00:00
2023-07-24 11:05:45 +00:00
@app.on_after_finalize.connect
def setup_periodic_tasks(sender, **kwargs):
sender.add_periodic_task(crontab(minute="*/2"), announce_items.s())