首页 > 解决方案 > 我正在尝试将 Twilio 广播 SMS 功能添加到我的 Django 应用程序,但无法弄清楚如何检索所有数据库电话号码

问题描述

我在我的 Django 应用程序中创建了一个“发布”模型,它将一篇基本文章上传到数据库。我正在尝试实现一个功能,通知用户已通过 SMS 上传了一篇新文章,但这需要发送给在数据库中注册其号码的所有用户(保存在单独的“个人资料”模型中)。

我在上传帖子时发送 SMS 的模型中添加了“保存”功能:

class Post(models.Model):
    title = models.CharField(max_length=100)
    content = models.TextField()
    detail_text = models.TextField(default='')

def __str__(self):
    return self.title

def get_absolute_url(self):
    return reverse('post-detail', kwargs={'pk': self.pk})

def save(self, *args, **kwargs):
    account_sid = settings.TWILIO_ACCOUNT_SID 
    auth_token = settings.TWILIO_AUTH_TOKEN 
    user_numbers = ''

    client = Client(account_sid, auth_token)

    message = client.messages.create(
                                  body= 'Hello, a new article is available from your 
                                  dashboard.',
                                  from_= settings.TWILIO_NUMBER,
                                  to = user_numbers         
    )

    print(message.sid)

    return super().save(*args, **kwargs)

我已经让 API 使用一个数字,在应用程序中硬编码,但现在想从数据库中提取数字并将它们发送给所有注册了手机号码的用户。

我曾尝试使用 Profile.objects.get(phone_numbers) 但这没有用。查看 Twilio 文档,我认为我需要将 settings.py 中的数字保存为数组,并更改“保存”函数中的代码以运行循环遍历数组中的所有数字并将其分配给'user_numbers' 变量使用 settings.USER_NUMBERS(例如)。然而,我对 Python 和 Django 还是很陌生,不知道该怎么做。

Twilio 的例子:

def broadcast_sms(request):
    message_to_broadcast = ("Have you played the incredible TwilioQuest "
                                                "yet? Grab it here: https://www.twilio.com/quest")
    client = Client(settings.TWILIO_ACCOUNT_SID, settings.TWILIO_AUTH_TOKEN)
    for recipient in settings.SMS_BROADCAST_TO_NUMBERS:
        if recipient:
            client.messages.create(to=recipient,
                                   from_=settings.TWILIO_NUMBER,
                                   body=message_to_broadcast)
    return HttpResponse("messages sent!", 200)

任何帮助将不胜感激。

我阅读过的一些相关文档包括:

Twillio - 从 Python 广播 SMS 文本消息

一个 API 调用将消息发送给多个人

标签: pythondjangoapitwilio

解决方案


你没有提供你的模型,所以我假设你有一个带有 phone_number 字段的 Profile 模型。在 Post 类中使用此保存方法:

def save(self, *args, **kwargs):
    if not self.pk: # Only if the instance is being created the code is executed
        phone_numbers = [profile.phone_number for profile in Profile.objects.all()]

        account_sid = settings.TWILIO_ACCOUNT_SID 
        auth_token = settings.TWILIO_AUTH_TOKEN
        client = Client(account_sid, auth_token)
    
        for phone_number in phone_numbers:
            if phone_number:
                message = client.messages.create(body='Hello, a new article is available from your dashboard.', from=settings.TWILIO_NUMBER, to=phone_number)

    super().save(*args, **kwargs)

推荐阅读