Chatfuel
Public API

Referencia de la API de flows

Lee y crea flows de Chatfuel con la Public API: flows y grupos, bloques y conexiones, componentes de mensaje y acción, reglas de palabras clave y Test chat.

Última actualización

Un flow es una conversación guionizada hecha de bloques conectados entre sí; cada bloque contiene componentes como un mensaje de WhatsApp, una lista, una condición o una llamada a la JSON API. Con la Public API puedes leer flows, crearlos y organizarlos, agregar y conectar bloques, configurar cada componente, gestionar reglas de palabras clave y disparadores, y ejecutar Test chats. Leer flows y ejecutar Test chats funciona para usuarios virtuales Agent; cualquier cambio requiere Editor.

Cómo leer flows

type Bot {
  # Agent.
  flowGroups: [FlowGroup!]!            # { id name flows { id name } }
  flowsWithoutGroup: [RegularFlow!]!
  defaultReplyFlows: [DefaultReplyFlow!]!
  flow(flowID: FlowID!): Flow!
}
query FlowStructure($botID: BotID!, $flowID: FlowID!) {
  bot(id: $botID) {
    flow(flowID: $flowID) {
      id
      name
      platform
      startingPointBlock { id }
      blocks {
        id
        name
        positionX
        positionY
        blockElements { id errors { __typename } }
      }
      connections { __typename }
    }
  }
}

Block y BlockElement son interfaces con un tipo por cada clase de bloque y de componente. Usa fragmentos en línea para los tipos con los que trabajas.

Cómo crear y organizar flows

Todas las mutaciones de esta página cambian flows y requieren Editor.

type Mutation {
  createFlow(botID: BotID!, platform: Platform!): Bot!
  updateFlowName(flowID: FlowID!, name: String!): Flow!
  deleteFlow(flowID: FlowID!): Bot!
  createFlowGroup(botID: BotID!): Bot!
  updateFlowGroupName(id: FlowGroupID!, name: String!): FlowGroup!
  deleteFlowGroup(flowGroupId: FlowGroupID!): Bot!
  moveFlowToGroup(flowID: FlowID!, groupID: FlowGroupID!): Bot!
  removeFlowFromGroup(flowID: FlowID!): Bot!
  sortFlowGroups(botID: BotID!, flowGroupIds: [FlowGroupID!]!): Bot!
  sortFlowsInGroup(groupID: FlowGroupID!, flowIds: [FlowID!]!): FlowGroup!
  sortUngroupedFlows(botID: BotID!, flowIds: [FlowID!]!): Bot!
}

Cómo trabajar con bloques y conexiones

type Mutation {
  updateBlockName(flowID: FlowID!, blockID: BlockID!, name: String!): Block!
  updateBlockPosition(flowID: FlowID!, blockID: BlockID!, positionX: Int!, positionY: Int!): Block!
  updateBlockPositionBulk(flowID: FlowID!, update: [BlockPositionBulkUpdate!]!): Flow!
  deleteBlock(flowID: FlowID!, blockID: BlockID!): Flow!
  blockSetStartingPoint(flowID: FlowID!, blockID: BlockID!): Flow!
  blockEnableEntryPoint(flowID: FlowID!, blockID: BlockID!): Flow!
  blockDisableEntryPoint(flowID: FlowID!, blockID: BlockID!): Flow!
  sortBlockElements(blockID: BlockID!, elementIDs: [BlockElementID!]!): Block!
  blockElementDelete(botID: BotID!, elementID: BlockElementID!): Flow!

  # Block → block, or a component's output handle (a button, a condition branch) → block.
  blockToBlockConnectionCreateOrUpdate(flowID: FlowID!, request: BlockToBlockConnectionCreateRequest!): Flow!
  blockToBlockConnectionDelete(flowID: FlowID!, sourceBlockID: BlockID!): Flow!
  componentToBlockConnectionCreateOrUpdate(flowID: FlowID!, request: ComponentToBlockConnectionCreateRequest!): Flow!
  componentToBlockConnectionDelete(flowID: FlowID!, sourceBlockElementID: BlockElementID!, sourceHandleID: ComponentHandleID!): Flow!
}

Las posiciones son coordenadas del lienzo en píxeles, las mismas que en el editor de flows del panel.

Cómo agregar componentes

Cada clase de componente tiene una familia de mutaciones que lleva su nombre. La mayoría de las familias ofrecen tres formas de crear un componente:

  • <family>CreateWithBlock(flowID, positionX, positionY) crea un bloque nuevo con el componente en la posición indicada.
  • <family>CreateWithBlockAndConnection(flowID, request, positionX, positionY) además lo conecta a un bloque o handle existente indicado en request: { sourceBlockID, sourceBlockElementID, sourceHandleID }.
  • <family>CreateInBlock(blockID) agrega el componente a un bloque existente.

Después, los setters reciben el blockElementID del componente. Por ejemplo, un mensaje de texto de WhatsApp:

type Mutation {
  whatsAppTextCreateWithBlock(flowID: FlowID!, positionX: Int!, positionY: Int!): Flow!
  whatsAppTextCreateWithBlockAndConnection(flowID: FlowID!, request: UndefinedTargetBlockConnectionCreateRequest!, positionX: Int!, positionY: Int!): Flow!
  whatsAppTextCreateInBlock(blockID: BlockID!): ContentBlock!
  whatsAppTextSetText(blockElementID: BlockElementID!, text: String!): ContentBlock!
  whatsAppTextSetWaitForReplies(blockElementID: BlockElementID!, waitForReplies: Boolean!): ContentBlock!
  whatsAppTextSetSaveContactReplyToAttribute(blockElementID: BlockElementID!, saveContactReply: Boolean!, attribute: AttributeName): ContentBlock!
}

Las familias de componentes y sus mutaciones, después del prefijo de la familia:

  • whatsAppText, whatsAppImage, whatsAppVideo, whatsAppAudio, whatsAppDocument: las tres mutaciones de creación, SetText o SetImageFile / SetVideoFile / SetAudioFile / SetDocumentFile, SetCaption (imagen, video, documento), SetWaitForReplies, SetSaveContactReplyToAttribute.
  • whatsAppTextAndButtons: CreateWithBlock, CreateWithBlockAndConnection, SetHeaderText, SetBodyText, SetFooterText, SetButtonTitle, AddNewContinueFlowButton, DeleteButton, MoveButton, WaitForReplies, SetSaveContactReplyToAttribute.
  • whatsAppTextAndURL: CreateWithBlock, CreateWithBlockAndConnection, SetHeaderText, SetBodyText, SetFooterText, SetButtonTitle, SetButtonURL, WaitForReplies, SetSaveContactReplyToAttribute.
  • whatsAppList: CreateWithBlock, CreateWithBlockAndConnection, SetBodyText, SetButtonTitle, AddRow, DeleteRow, ReorderRows, SetRowTitle, SetRowDescription, WaitForReplies, SetSaveContactReplyToAttribute.
  • whatsAppTemplate: CreateWithBlock, CreateWithBlockAndConnection, SetTemplate, DeleteTemplate, SetHeaderTextParamValue, SetBodyTextParamValue, SetFooterTextParamValue, SetHeaderImageFile, SetHeaderVideoFile, SetHeaderDocumentFile, SetURLButtonTextParamValue, SetCopyCodeButtonCodeValue, SetWaitForReplies, SetSaveContactReplyToAttribute.
  • whatsAppScheduledMessage: CreateWithBlock, CreateWithBlockAndWATemplate, UpdateSegment, SetFirstSendTime, SetRepeatType, SetRepeatEveryNDays, SetOnCertainDates, SetWeekdays.
  • whatsAppOneTimeNotification: CreateWithBlock, CreateWithBlockAndWATemplate, UpdateSegment, Send.
  • widgetTextAndButtons: las tres mutaciones de creación, SetText, AddNewContinueFlowButton, AddNewOpenURLButton, AddNewPhoneButton, SetButtonTitle, SetButtonURL, SetButtonPhone, DeleteButton, MoveButton, SetWaitForReplies, SetSaveContactReplyToAttribute.
  • widgetImage: las tres mutaciones de creación, SetImageFile, SetWaitForReplies, SetSaveContactReplyToAttribute.
  • whatsAppSwitchToChatWithHumanAgent, facebookSwitchToChatWithHumanAgent, instagramSwitchToChatWithHumanAgent, tiktokSwitchToChatWithHumanAgent, widgetSwitchToChatWithHumanAgent: las tres mutaciones de creación.
  • aiAgent: CreateWithBlock y CreateWithBlockAndConnection con un templateID de la consulta aiAgentTemplates(locale:), UpdateAdditionalInstructions, CreateRule, DeleteRule, UpdateRuleTitle, UpdateRulePrompt. Un agente de IA personalizado usa aiAgentCustomUpdatePrompt, aiAgentCustomCreateRule, aiAgentCustomDeleteRule, aiAgentCustomUpdateRuleTitle y aiAgentCustomUpdateRulePrompt.
  • sendJson (la acción JSON API): las tres mutaciones de creación, UpdateHTTPMethod, UpdateURL, AddHeader, UpdateHeaderTitle, UpdateHeaderValue, DeleteHeader, AddURLParam, UpdateURLParamTitle, UpdateURLParamValue, DeleteURLParam, UpdatePayloadType, UpdateCustomRequestPayload, EnableResponseParsingRules, DisableResponseParsingRules, ResponseAddParsingRule, UpdateResponseParsingRuleJSONPath, UpdateResponseParsingRuleAttributeName, DeleteResponseParsingRule, TestRequest.
  • albatoIntegration: las tres mutaciones de creación con un templateID, UpdateSelectedEvent, UpdateEventFieldValue, AddEventCustomField, RemoveEventCustomField, UpdateEventCustomFieldName, UpdateEventCustomFieldValue.
  • setCondition: las tres mutaciones de creación, UpdateSegment.
  • setContactProperty: las tres mutaciones de creación, SetAttribute, SetValue. clearContactProperty: las tres mutaciones de creación, SetAttribute.
  • summarizeChat: las tres mutaciones de creación, AddEntry, UpdateEntry, DeleteEntry.
  • redirectToFlow: CreateWithBlock, CreateWithBlockAndConnection, SetTargetFlow, RemoveTargetFlow.
  • triggeredMessage: CreateWithBlock, CreateWithBlockAndWATemplate, SetSegment.

Cómo integrar con la JSON API explica qué hace cada opción de sendJson.

Reglas de palabras clave y disparadores

Las reglas de palabras clave envían a un contacto a un flow o responden con un mensaje cuando su texto coincide. Tanto leerlas con bot.keywordRules(first, after) como cambiarlas requiere Editor.

type Mutation {
  keywordRuleCreate(botID: BotID!): KeywordRule!
  # matchType: similarTo, contains or matches
  keywordRuleUpdateMatchType(botID: BotID!, keywordRuleID: KeywordRuleID!, matchType: KeywordRuleMatchType!): KeywordRule!
  keywordRuleUpdateKeywords(botID: BotID!, keywordRuleID: KeywordRuleID!, keywords: [String!]!): KeywordRule!
  # actionType: switchToFlow, sendMessage or doNothing, set per platform
  keywordRuleUpdateActionType(botID: BotID!, keywordRuleID: KeywordRuleID!, platform: Platform!, actionType: KeywordRuleActionType!): KeywordRule!
  keywordRuleDelete(botID: BotID!, keywordRuleID: KeywordRuleID!): Bot!

  # Triggers of triggered messages. An enabled trigger can't be changed (EnabledTriggerIsImmutable).
  # conditionType: LastMessageFromContact or ContactAttributeChanged
  triggerSetConditionType(id: TriggerID!, conditionType: TriggerConditionType!): Trigger!
  triggerSetAttributeFilter(id: TriggerID!, attrCondition: AttrFilterInput!): Trigger!
  triggerDeleteAttributeFilter(id: TriggerID!): Trigger!
  triggerSetDelay(id: TriggerID!, delay: TriggerDelayInput!): Trigger!
}

Cómo probar un flow en el Test chat

El Test chat ejecuta un flow, todo el bot o una automatización en una conversación aislada, sin enviar mensajes a contactos reales. Iniciar una sesión funciona para Agent:

type Mutation {
  previewResponsesStartInFlow(flowID: FlowID!): PreviewResponsesFlowSession!
  previewResponsesStartForBot(botID: BotID!, platform: Platform!): PreviewResponsesBotSession!
  previewResponsesStartForFuelyAutomation(botID: BotID!, fuelyAutomationID: FuelyAutomationID!): PreviewResponsesFuelyAutomationSession!
}

La sesión devuelve un conversationID. Haz el papel del contacto con previewResponsesWhatsappTextSend, previewResponsesInstagramTextSend, previewResponsesFacebookTextSend, previewResponsesTikTokTextSend o previewResponsesWidgetTextSend, simula comentarios con previewResponsesInstagramPostCommentSend y previewResponsesFacebookPostCommentSend, y simula clics con previewResponsesWhatsappContinueFlowBtnClickSend, previewResponsesWhatsappListRowClickSend, previewResponsesWhatsappTemplateQuickReplyBtnClickSend y las mutaciones previewResponsesWidget*BtnClickSend. Todas reciben botID y conversationID. Lee las respuestas del bot con la suscripción messageAdded descrita en mensajería.

Problemas comunes

"NotEnoughPermissions" al cambiar un flow

Los usuarios virtuales Agent pueden leer flows y ejecutar Test chats, pero no pueden modificar flows. Cambia el rol a Editor.

"EnabledTriggerIsImmutable"

Un mensaje activado por disparador no se puede editar mientras está activo. Desactívalo en el panel, cambia el disparador y vuelve a activarlo.

Un componente muestra errores en el flow

blockElements { errors } lista lo que falta, como un texto vacío o una plantilla sin configurar. El panel muestra los mismos errores en el bloque; completa las opciones que faltan con los setters del componente.

En esta página