oex2003/evolution-api
0
1import { advancedOperatorsSearch } from './advancedOperatorsSearch';2 3export const findBotByTrigger = async (botRepository: any, content: string, instanceId: string) => {4 // Check for triggerType 'all' or 'none' (both should match any message)5 const findTriggerAllOrNone = await botRepository.findFirst({6 where: {7 enabled: true,8 triggerType: {9 in: ['all', 'none'],10 },11 instanceId: instanceId,12 },13 });14 15 if (findTriggerAllOrNone) {16 return findTriggerAllOrNone;17 }18 19 const findTriggerAdvanced = await botRepository.findMany({20 where: {21 enabled: true,22 triggerType: 'advanced',23 instanceId: instanceId,24 },25 });26 for (const advanced of findTriggerAdvanced) {27 if (advancedOperatorsSearch(content, advanced.triggerValue)) {28 return advanced;29 }30 }31 32 // Check for exact match33 const findTriggerEquals = await botRepository.findFirst({34 where: {35 enabled: true,36 triggerType: 'keyword',37 triggerOperator: 'equals',38 triggerValue: content,39 instanceId: instanceId,40 },41 });42 43 if (findTriggerEquals) {44 return findTriggerEquals;45 }46 47 // Check for regex match48 const findRegex = await botRepository.findMany({49 where: {50 enabled: true,51 triggerType: 'keyword',52 triggerOperator: 'regex',53 instanceId: instanceId,54 },55 });56 57 let findTriggerRegex = null;58 59 for (const regex of findRegex) {60 const regexValue = new RegExp(regex.triggerValue);61 62 if (regexValue.test(content)) {63 findTriggerRegex = regex;64 break;65 }66 }67 68 if (findTriggerRegex) return findTriggerRegex;69 70 // Check for startsWith match71 const findStartsWith = await botRepository.findMany({72 where: {73 enabled: true,74 triggerType: 'keyword',75 triggerOperator: 'startsWith',76 instanceId: instanceId,77 },78 });79 80 let findTriggerStartsWith = null;81 82 for (const startsWith of findStartsWith) {83 if (content.startsWith(startsWith.triggerValue)) {84 findTriggerStartsWith = startsWith;85 break;86 }87 }88 89 if (findTriggerStartsWith) return findTriggerStartsWith;90 91 // Check for endsWith match92 const findEndsWith = await botRepository.findMany({93 where: {94 enabled: true,95 triggerType: 'keyword',96 triggerOperator: 'endsWith',97 instanceId: instanceId,98 },99 });100 101 let findTriggerEndsWith = null;102 103 for (const endsWith of findEndsWith) {104 if (content.endsWith(endsWith.triggerValue)) {105 findTriggerEndsWith = endsWith;106 break;107 }108 }109 110 if (findTriggerEndsWith) return findTriggerEndsWith;111 112 // Check for contains match113 const findContains = await botRepository.findMany({114 where: {115 enabled: true,116 triggerType: 'keyword',117 triggerOperator: 'contains',118 instanceId: instanceId,119 },120 });121 122 let findTriggerContains = null;123 124 for (const contains of findContains) {125 if (content.includes(contains.triggerValue)) {126 findTriggerContains = contains;127 break;128 }129 }130 131 if (findTriggerContains) return findTriggerContains;132 133 return null;134};135 