Skip to content

Commit

Permalink
Merge branch 'master' of gitlab.com:pencillabs/ej/ej-bot into main
Browse files Browse the repository at this point in the history
  • Loading branch information
fabiola-m committed Mar 1, 2021
2 parents 70a94c8 + badfa3b commit 133cd34
Show file tree
Hide file tree
Showing 13 changed files with 209 additions and 61 deletions.
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -11,3 +11,6 @@
models
results/
train_test_split
.env/
env
.env
6 changes: 5 additions & 1 deletion .gitlab-ci.yml
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
image: docker:latest

variables:
DOCKER_DRIVER: overlay2
DOCKER_TLS_CERTDIR: ""

services:
- docker:dind

Expand Down Expand Up @@ -35,4 +39,4 @@ test:
script:
- make run-test-nlu
- make run-test-core
- make test-actions
- make test-actions
2 changes: 1 addition & 1 deletion bot/actions/__init__.py
Original file line number Diff line number Diff line change
@@ -1 +1 @@
from .actions import ActionSetupConversation, ActionAskVote, FormValidationAction
from .actions import ActionSetupConversation, ActionAskVote, ValidateVoteForm
62 changes: 41 additions & 21 deletions bot/actions/actions.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,18 +26,20 @@ def name(self):
def run(self, dispatcher, tracker, domain):
conversation_id = 1
user_email = tracker.get_slot("email")

if user_email:
user = API.create_user(tracker.sender_id, user_email, user_email)
else:
user = API.create_user(tracker.sender_id)
# TODO: get values from EJ server
number_comments = 2
number_voted_comments = 1

statistics = API.get_user_conversation_statistics(conversation_id, user.token)
first_comment = API.get_next_comment(conversation_id, user.token)
return [
SlotSet("number_voted_comments", number_voted_comments),
SlotSet("number_voted_comments", statistics["votes"]),
SlotSet("conversation_id", conversation_id),
SlotSet("number_comments", number_comments),
SlotSet(
"number_comments", statistics["missing_votes"] + statistics["votes"]
),
SlotSet("comment_text", first_comment["content"]),
SlotSet("current_comment_id", first_comment["id"]),
SlotSet("change_comment", False),
Expand All @@ -58,24 +60,32 @@ def run(
{"title": "Discordar", "payload": "Discordar"},
{"title": "Pular", "payload": "Pular"},
]
conversation_id = tracker.get_slot("conversation_id")
token = tracker.get_slot("ej_user_token")
statistics = API.get_user_conversation_statistics(conversation_id, token)
total_comments = statistics["missing_votes"] + statistics["votes"]
number_voted_comments = statistics["votes"]

if tracker.get_slot("change_comment"):
# TODO: get values from EJ server
# next_comment = get_random_comment()
new_comment = API.get_next_comment(conversation_id, token)
comment_content = new_comment["content"]
message = f"{comment_content} \n O que você acha disso ({number_voted_comments}/{total_comments})?"

dispatcher.utter_message(text=message, buttons=buttons)

conversation_id = tracker.get_slot("conversation_id")
token = tracker.get_slot("ej_user_token")
new_comment = API.get_next_comment(conversation_id, token)
dispatcher.utter_message(text=new_comment, buttons=buttons)
number_voted_comments = tracker.get_slot("number_comments") + 1
return [
SlotSet("number_voted_comments", number_voted_comments),
SlotSet("comment_text", new_comment["content"]),
SlotSet("number_comments", total_comments),
SlotSet("current_comment_id", new_comment["id"]),
]
else:
dispatcher.utter_message(
text=tracker.get_slot("comment_text"), buttons=buttons
)
comment_content = tracker.get_slot("comment_text")
message = f"{comment_content} \n O que você acha disso ({number_voted_comments}/{total_comments})?"
dispatcher.utter_message(text=message, buttons=buttons)
return [SlotSet("change_comment", True)]


Expand All @@ -91,20 +101,30 @@ def validate_vote(
domain: DomainDict,
) -> Dict[Text, Any]:
"""Validate vote value."""
token = tracker.get_slot("ej_user_token")
conversation_id = tracker.get_slot("conversation_id")
if str(slot_value) in ["Concordar", "Discordar", "Pular"]:
# TODO: Send vote value to EJ server
voted_comments = tracker.get_slot("number_voted_comments")
total_comments = tracker.get_slot("number_comments")
dispatcher.utter_message(template="utter_vote_received")
# TODO: Get next random comment
# was_sent = send_vote(vote_value)
if voted_comments < total_comments:
comment_id = tracker.get_slot("current_comment_id")
sent_vote = API.send_comment_vote(comment_id, slot_value, token)

if sent_vote["created"]:
dispatcher.utter_message(template="utter_vote_received")
statistics = API.get_user_conversation_statistics(conversation_id, token)
if statistics["missing_votes"] > 0:
# user still has comments to vote, remain in loop
return {"vote": None}
else:
# user voted in all comments, can exit loop
dispatcher.utter_message(template="utter_voted_all_comments")
return [{"vote": slot_value}]
elif str(slot_value) == "PARAR":
dispatcher.utter_message(template="utter_stopped")
return {"vote": "None"}
else:
dispatcher.utter_message(template="utter_out_of_context")
# did not send expected vote value
# register a new comment instead of a vote
response = API.send_new_comment(conversation_id, slot_value, token)
if response["created"]:
dispatcher.utter_message(template="utter_sent_comment")
else:
dispatcher.utter_message(template="utter_send_comment_error")
return {"vote": None}
32 changes: 32 additions & 0 deletions bot/actions/ej_connector/api.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import os
import requests
import json
from .user import User

HEADERS = {
Expand All @@ -10,6 +11,7 @@
API_URL = f"{HOST}/api/v1"
REGISTRATION_URL = f"{HOST}/rest-auth/registration/"
VOTES_URL = f"{API_URL}/votes/"
COMMENTS_URL = f"{API_URL}/comments/"


def conversation_url(conversation_id):
Expand Down Expand Up @@ -56,3 +58,33 @@ def get_next_comment(conversation_id, token):
comment_url_as_list = comment["links"]["self"].split("/")
comment["id"] = comment_url_as_list[len(comment_url_as_list) - 2]
return comment

def get_user_conversation_statistics(conversation_id, token):
url = user_statistics_url(conversation_id)
response = requests.get(url, headers=auth_headers(token))
return response.json()

def send_comment_vote(comment_id, choice, token):
body = json.dumps(
{
"comment": comment_id,
"choice": VOTE_CHOICES[choice],
}
)
response = requests.post(
VOTES_URL,
data=body,
headers=auth_headers(token),
)
return response.json()

def send_new_comment(conversation_id, content, token):
body = json.dumps(
{"content": content, "conversation": conversation_id, "status": "pending"}
)
response = requests.post(
COMMENTS_URL,
data=body,
headers=auth_headers(token),
)
return response.json()
21 changes: 14 additions & 7 deletions bot/data/nlu.yml
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,18 @@ nlu:
- email: esteemail@outroservidor.com
- meu email: email@email.com.br
- intent: stop
examples: |
- para
- PARAR
- PAUSAR
- parar
- pausa
- pausar
- chega
- sair
- stop
- intent: invalid_email
examples: |
- @wlor
Expand All @@ -79,11 +91,6 @@ nlu:
- você é um robô?
- Fala alguma coisa
- asdfgasd
- chega
- para
- parar
- pausa
- tempo
- stop
- sair
- oque
- que
10 changes: 9 additions & 1 deletion bot/data/rules.yml
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,12 @@ rules:
- rule: User ask a out of context question
steps:
- intent: out_of_context
- action: utter_out_of_context
- action: utter_out_of_context

- rule: User doesn't want to participate anymore
steps:
# This unhappy path handles the case of an intent `stop`.
- intent: stop
- action: utter_stopped
- action: utter_finish
- active_loop: null
17 changes: 10 additions & 7 deletions bot/data/stories.yml
Original file line number Diff line number Diff line change
Expand Up @@ -12,18 +12,20 @@ stories:
- intent: start
- action: utter_start
- intent: disagree
- action: utter_goodbye
- action: utter_finish

- story: User wants to participate
steps:
- intent: start
- action: utter_start
- intent: agree
- action: utter_agreed_participation
- action: utter_ask_email

- story: Activate vote form with user email
steps:
- intent: agree
- action: utter_agreed_participation
- action: utter_ask_email
- intent: email
entities:
Expand All @@ -32,24 +34,25 @@ stories:
- action: vote_form
- active_loop: vote_form
- active_loop: null
- slot_was_set:
- vote: null
- action: utter_finish


- story: Activate vote form without user email
steps:
- intent: agree
- action: utter_agreed_participation
- action: utter_ask_email
- intent: disagree
- action: action_setup_conversation
- action: vote_form
- active_loop: vote_form
- active_loop: null
- slot_was_set:
- vote: null
- action: utter_finish

- story: User provides invalid email
steps:
- intent: agree
- action: utter_agreed_participation
- action: utter_ask_email
- intent: invalid_email
- action: utter_invalid_email
Expand All @@ -60,5 +63,5 @@ stories:
- action: vote_form
- active_loop: vote_form
- active_loop: null
- slot_was_set:
- vote: null
- action: utter_finish

26 changes: 21 additions & 5 deletions bot/domain.yml
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,9 @@ intents:
use_entities: true
- invalid_email:
use_entities: true
entities:
- stop:
use_entities: true
entities:
- email
slots:
change_comment:
Expand All @@ -41,6 +43,7 @@ slots:
type: rasa.shared.core.slots.TextSlot
initial_value: null
auto_fill: true
influence_conversation: true
conversation_id:
type: rasa.shared.core.slots.FloatSlot
initial_value: null
Expand Down Expand Up @@ -80,17 +83,30 @@ slots:
- pular
responses:
utter_start:
- text: Olá, estou coletando opiniões, gostaria de participar?
- text: Você topa me dizer o que acha do que o pessoal anda falando? Vai me ajudar bastante a entender o assunto
utter_agreed_participation:
- text: Oba, muito obrigada!! :) A qualquer momento você pode parar a conversa, é só escrever PARAR.
utter_ask_email:
- text: Legal, você gostaria de se identificar pelo seu email? Se sim, já pode enviar que anoto aqui.
utter_invalid_email:
- text: Não entendi, esse email não parece válido, pode tentar enviar de novo?
utter_goodbye:
- text: Agradeço pela participação! Até logo
utter_vote_received:
- text: Seus votos foram computados, agradeço!
- text: Registrei sua opinião!
- text: Beleza, anotei aqui.
- text: Entendo, registrado.
- text: Obrigada por participar.
utter_out_of_context:
- text: Desculpe, não sei como posso te ajudar com isso.
utter_sent_comment:
- text: Seu comentário foi adicionado à conversa.
utter_send_comment_error:
- text: Não foi possível salvar seu comentário, tente novamente mais tarde.
utter_voted_all_comments:
- text: Obrigada! Você opinou em todos os comentários que existem atualmente sobre esse assunto.
utter_stopped:
- text: Você já me ajudou bastante, muito obrigada! Vou ficar esperando pra gente conversar mais um pouquinho
utter_finish:
- text: Volte quando quiser, é só me dar um "Oi". Mas pode deixar que te mantenho por dentro sobre as novidades desse assunto :)
actions:
- action_setup_conversation
- action_ask_vote
Expand Down
Loading

0 comments on commit 133cd34

Please sign in to comment.