Receive incoming messages every 300 seconds

pull/1/head
Luca 2 years ago
parent 4c47546415
commit 23a95499b8

@ -0,0 +1,55 @@
from datetime import timezone
from django.conf import settings
import requests
BASE_URL = "https://api.sipgate.com/v2"
class SMS:
def __init__(self, item):
self.content = item["smsContent"]
self.created_at = item["created"]
self.id = item["id"]
self.sender = item["source"]
def list_incoming_sms(from_date=None):
if not settings.SIPGATE_INCOMING_TOKEN_ID:
raise RuntimeError("required setting SIPGATE_INCOMING_TOKEN_ID is not set")
if not settings.SIPGATE_INCOMING_TOKEN:
raise RuntimeError("required setting SIPGATE_INCOMING_TOKEN is not set")
limit = 10
params = {
"directions": "INCOMING",
"limit": limit,
"types": "SMS",
}
if from_date is not None:
params["from"] = (
from_dt.astimezone(timezone.utc).isoformat(timespec="seconds") + "Z"
)
items = []
offset = 0
total = 10
while offset < total:
r = requests.get(
f"{BASE_URL}/history",
auth=requests.auth.HTTPBasicAuth(
settings.SIPGATE_INCOMING_TOKEN_ID, settings.SIPGATE_INCOMING_TOKEN
),
params=params | {"offset": offset},
)
r.raise_for_status()
data = r.json()
items += data["items"]
offset += limit
total = data["totalCount"]
return list(map(lambda item: SMS(item), items))

@ -170,6 +170,10 @@ CELERY_BEAT_SCHEDULE = {
"task": "shiftregister.app.tasks.send_reminders", "task": "shiftregister.app.tasks.send_reminders",
"schedule": float(getenv("REMINDER_SEND_INTERVAL", 300.0)), # seconds "schedule": float(getenv("REMINDER_SEND_INTERVAL", 300.0)), # seconds
}, },
"receive-messages-every-300-seconds": {
"task": "shiftregister.team.tasks.receive_messages",
"schedule": float(getenv("MESSAGE_RECEIVE_INTERVAL", 300.0)), # seconds
},
} }
CELERY_BEAT_SCHEDULE_FILENAME = str(BASE_DIR / "storage" / "celerybeat-schedule") CELERY_BEAT_SCHEDULE_FILENAME = str(BASE_DIR / "storage" / "celerybeat-schedule")
@ -193,3 +197,7 @@ SIPGATE_SMS_EXTENSION = getenv("SIPGATE_SMS_EXTENSION")
SIPGATE_TOKEN_ID = getenv("SIPGATE_TOKEN_ID") SIPGATE_TOKEN_ID = getenv("SIPGATE_TOKEN_ID")
SIPGATE_TOKEN = getenv("SIPGATE_TOKEN") SIPGATE_TOKEN = getenv("SIPGATE_TOKEN")
SIPGATE_INCOMING_TOKEN_ID = getenv("SIPGATE_INCOMING_TOKEN_ID")
SIPGATE_INCOMING_TOKEN = getenv("SIPGATE_INCOMING_TOKEN")

@ -1,3 +1,9 @@
from django.contrib import admin from django.contrib import admin
from .models import IncomingMessage
# Register your models here. # Register your models here.
@admin.register(IncomingMessage)
class IncomingMessageAdmin(admin.ModelAdmin):
list_display = ("sender", "created_at")

@ -0,0 +1,30 @@
# Generated by Django 4.0.4 on 2023-05-06 23:27
from django.db import migrations, models
import phonenumber_field.modelfields
class Migration(migrations.Migration):
initial = True
dependencies = []
operations = [
migrations.CreateModel(
name="IncomingMessage",
fields=[
("id", models.IntegerField(primary_key=True, serialize=False)),
(
"sender",
phonenumber_field.modelfields.PhoneNumberField(
max_length=128, region=None
),
),
("content", models.TextField()),
("created_at", models.DateTimeField()),
],
options={
"get_latest_by": "created_at",
},
),
]

@ -1,4 +1,15 @@
from django.db import models from django.db import models
from phonenumber_field.modelfields import PhoneNumberField
from shiftregister.app.models import * from shiftregister.app.models import *
# Create your models here. # Create your models here.
class IncomingMessage(models.Model):
class Meta:
get_latest_by = "created_at"
id = models.IntegerField(primary_key=True)
sender = PhoneNumberField()
content = models.TextField()
created_at = models.DateTimeField()

@ -0,0 +1,27 @@
from celery import shared_task
from django.conf import settings
from shiftregister.app.sipgate.history import list_incoming_sms
from .models import IncomingMessage
import sentry_sdk
@shared_task
def receive_messages():
if not settings.SIPGATE_INCOMING_TOKEN or not settings.SIPGATE_INCOMING_TOKEN_ID:
return
try:
from_dt = IncomingMessage.objects.latest()
except IncomingMessage.DoesNotExist:
from_dt = None
try:
for sms in list_incoming_sms(from_dt):
IncomingMessage(
id=sms.id,
sender=sms.sender,
content=sms.content,
created_at=sms.created_at,
).save()
except Exception as e:
sentry_sdk.capture_exception(e)
Loading…
Cancel
Save