Skip to content

Commit

Permalink
refactor + remove twilio connect function
Browse files Browse the repository at this point in the history
  • Loading branch information
SanderGi committed Jul 14, 2024
1 parent 3833b4a commit 855eeeb
Show file tree
Hide file tree
Showing 7 changed files with 217 additions and 242 deletions.
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
# Generated by Django 4.2.7 on 2024-07-08 20:35
# Generated by Django 4.2.7 on 2024-07-11 01:30

from django.db import migrations, models
import phonenumber_field.modelfields


class Migration(migrations.Migration):
Expand Down Expand Up @@ -48,7 +49,7 @@ class Migration(migrations.Migration):
migrations.AddField(
model_name='botintegration',
name='twilio_phone_number',
field=models.TextField(blank=True, default='', help_text='Twilio unformatted phone number as found on twilio.com/console/phone-numbers/incoming (mandatory)'),
field=phonenumber_field.modelfields.PhoneNumberField(blank=True, default='', help_text='Twilio unformatted phone number as found on twilio.com/console/phone-numbers/incoming (mandatory)', max_length=128, region=None),
),
migrations.AddField(
model_name='botintegration',
Expand Down Expand Up @@ -78,7 +79,7 @@ class Migration(migrations.Migration):
migrations.AddField(
model_name='conversation',
name='twilio_phone_number',
field=models.TextField(blank=True, default='', help_text="User's Twilio phone number (mandatory)"),
field=phonenumber_field.modelfields.PhoneNumberField(blank=True, default='', help_text="User's Twilio phone number (mandatory)", max_length=128, region=None),
),
migrations.AlterField(
model_name='botintegration',
Expand Down
30 changes: 25 additions & 5 deletions bots/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -635,7 +635,7 @@ class BotIntegration(models.Model):
default="",
help_text="Twilio auth token as found on twilio.com/console (mandatory)",
)
twilio_phone_number = models.TextField(
twilio_phone_number = PhoneNumberField(
blank=True,
default="",
help_text="Twilio unformatted phone number as found on twilio.com/console/phone-numbers/incoming (mandatory)",
Expand Down Expand Up @@ -731,7 +731,7 @@ def get_display_name(self):
or " | #".join(
filter(None, [self.slack_team_name, self.slack_channel_name])
)
or self.twilio_phone_number
or (self.twilio_phone_number and self.twilio_phone_number.as_international)
or self.name
or (
self.platform == Platform.WEB
Expand Down Expand Up @@ -764,6 +764,21 @@ def get_web_widget_config(self, target="#gooey-embed") -> dict:
)
return config

def translate(self, text: str) -> str:
from daras_ai_v2.asr import run_google_translate, should_translate_lang

if text and should_translate_lang(self.user_language):
active_run = self.get_active_saved_run()
return run_google_translate(
[text],
self.user_language,
glossary_url=(
active_run.state.get("output_glossary") if active_run else None
),
)[0]
else:
return text


class BotIntegrationAnalysisRun(models.Model):
bot_integration = models.ForeignKey(
Expand Down Expand Up @@ -834,7 +849,12 @@ class ConversationQuerySet(models.QuerySet):
def get_unique_users(self) -> "ConversationQuerySet":
"""Get unique conversations"""
return self.distinct(
"fb_page_id", "ig_account_id", "wa_phone_number", "slack_user_id"
"fb_page_id",
"ig_account_id",
"wa_phone_number",
"slack_user_id",
"twilio_phone_number",
"web_user_id",
)

def to_df(self, tz=pytz.timezone(settings.TIME_ZONE)) -> "pd.DataFrame":
Expand Down Expand Up @@ -1027,7 +1047,7 @@ class Conversation(models.Model):
help_text="Whether this is a personal slack channel between the bot and the user",
)

twilio_phone_number = models.TextField(
twilio_phone_number = PhoneNumberField(
blank=True,
default="",
help_text="User's Twilio phone number (mandatory)",
Expand Down Expand Up @@ -1078,7 +1098,7 @@ def get_display_name(self):
or self.fb_page_id
or self.slack_user_id
or self.web_user_id
or self.twilio_phone_number
or (self.twilio_phone_number and self.twilio_phone_number.as_international)
)

get_display_name.short_description = "User"
Expand Down
9 changes: 9 additions & 0 deletions bots/tasks.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
create_personal_channel,
SlackBot,
)
from daras_ai_v2.twilio_bot import create_voice_call, send_sms_message
from daras_ai_v2.vector_search import references_as_prompt
from gooeysite.bg_db_conn import get_celery_result_db_safe
from recipes.VideoBots import ReplyButton, messages_as_prompt
Expand Down Expand Up @@ -153,6 +154,7 @@ def send_broadcast_msgs_chunked(
buttons: list[ReplyButton] = None,
convo_qs: QuerySet[Conversation],
bi: BotIntegration,
medium: str,
):
convo_ids = list(convo_qs.values_list("id", flat=True))
for i in range(0, len(convo_ids), 100):
Expand All @@ -164,6 +166,7 @@ def send_broadcast_msgs_chunked(
documents=documents,
bi_id=bi.id,
convo_ids=convo_ids[i : i + 100],
medium=medium,
)


Expand All @@ -177,6 +180,7 @@ def send_broadcast_msg(
documents: list[str] = None,
bi_id: int,
convo_ids: list[int],
medium: str,
):
bi = BotIntegration.objects.get(id=bi_id)
convos = Conversation.objects.filter(id__in=convo_ids)
Expand Down Expand Up @@ -205,6 +209,11 @@ def send_broadcast_msg(
username=bi.name,
token=bi.slack_access_token,
)[0]
case Platform.TWILIO:
if medium == "Voice Call":
create_voice_call(convo, text, audio)
else:
send_sms_message(convo, text, media_url=audio)
case _:
raise NotImplementedError(
f"Platform {bi.platform} doesn't support broadcasts yet"
Expand Down
57 changes: 37 additions & 20 deletions daras_ai_v2/bots.py
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ class BotInterface:

page_cls: typing.Type[BasePage] | None
query_params: dict
language: str
language: str | None
billing_account_uid: str
show_feedback_buttons: bool = False
streaming_enabled: bool = False
Expand Down Expand Up @@ -140,37 +140,44 @@ def nice_filename(self, mime_type: str) -> str:
return f"{self.platform.name}_{self.input_type}_from_{self.user_id}_to_{self.bot_id}{ext}"

def _unpack_bot_integration(self):
bi = self.convo.bot_integration
if bi.published_run:
self.page_cls = Workflow(bi.published_run.workflow).page_cls
self.bi = self.convo.bot_integration
if self.bi.published_run:
self.page_cls = Workflow(self.bi.published_run.workflow).page_cls
self.query_params = self.page_cls.clean_query_params(
example_id=bi.published_run.published_run_id,
example_id=self.bi.published_run.published_run_id,
run_id="",
uid="",
)
saved_run = bi.published_run.saved_run
saved_run = self.bi.published_run.saved_run
self.input_glossary = saved_run.state.get("input_glossary_document")
self.output_glossary = saved_run.state.get("output_glossary_document")
self.language = saved_run.state.get("user_language")
elif bi.saved_run:
self.page_cls = Workflow(bi.saved_run.workflow).page_cls
elif self.bi.saved_run:
self.page_cls = Workflow(self.bi.saved_run.workflow).page_cls
self.query_params = self.page_cls.clean_query_params(
example_id=bi.saved_run.example_id,
run_id=bi.saved_run.run_id,
uid=bi.saved_run.uid,
example_id=self.bi.saved_run.example_id,
run_id=self.bi.saved_run.run_id,
uid=self.bi.saved_run.uid,
)
self.input_glossary = bi.saved_run.state.get("input_glossary_document")
self.output_glossary = bi.saved_run.state.get("output_glossary_document")
self.language = bi.saved_run.state.get("user_language")
self.input_glossary = self.bi.saved_run.state.get("input_glossary_document")
self.output_glossary = self.bi.saved_run.state.get(
"output_glossary_document"
)
self.language = self.bi.saved_run.state.get("user_language")
else:
self.page_cls = None
self.query_params = {}

self.billing_account_uid = bi.billing_account_uid
if should_translate_lang(bi.user_language):
self.language = bi.user_language
self.show_feedback_buttons = bi.show_feedback_buttons
self.streaming_enabled = bi.streaming_enabled
self.billing_account_uid = self.bi.billing_account_uid
if should_translate_lang(self.bi.user_language):
self.language = self.bi.user_language
else:
self.language = None
self.show_feedback_buttons = self.bi.show_feedback_buttons
self.streaming_enabled = self.bi.streaming_enabled

def translate(self, text: str | None) -> str:
return self.bi.translate(text or "")


def _echo(bot, input_text):
Expand Down Expand Up @@ -199,8 +206,18 @@ def _mock_api_output(input_text):
}


@db_middleware
def msg_handler(bot: BotInterface):
try:
_msg_handler(bot)
except Exception as e:
bot.send_msg(
text=bot.translate("Sorry, an error occurred. Please try again later."),
)
capture_exception(e)


@db_middleware
def _msg_handler(bot: BotInterface):
recieved_time: datetime = timezone.now()
if not bot.page_cls:
bot.send_msg(text=PAGE_NOT_CONNECTED_ERROR)
Expand Down
Loading

0 comments on commit 855eeeb

Please sign in to comment.