Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(chatwoot): add some translations on chatwoot messages #434

Merged
merged 1 commit into from
Feb 21, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 20 additions & 1 deletion src/utils/translations/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,24 @@
"qrgeneratedsuccesfully": "QRCode successfully generated!",
"scanqr": "Scan this QR code within the next 40 seconds.",
"qrlimitreached": "QRCode generation limit reached, to generate a new QRCode, send the 'init' message again.",
"numbernotinwhatsapp": "The message was not sent as the contact is not a valid Whatsapp number."
"numbernotinwhatsapp": "The message was not sent as the contact is not a valid Whatsapp number.",
"cw.inbox.connected": "🚀 Connection successfully established!",
"cw.inbox.disconnect": "🚨 Disconnecting WhatsApp from inbox *{{inboxName}}*.",
"cw.inbox.alreadyConnected": "🚨 {{inboxName}} instance is connected.",
"cw.inbox.clearCache": "✅ {{inboxName}} instance cache cleared.",
"cw.inbox.notFound": "⚠️ {{inboxName}} instance not found.",
"cw.inbox.status": "⚠️ {{inboxName}} instance status: *{{state}}*.",
"cw.import.startImport": "💬 Starting to import messages. Please wait...",
"cw.import.importingMessages": "💬 Importing messages. More one moment...",
"cw.import.messagesImported": "💬 {{totalMessagesImported}} messages imported. Refresh page to see the new messages.",
"cw.import.messagesException": "💬 Something went wrong in importing messages.",
"cw.locationMessage.location": "Location",
"cw.locationMessage.latitude": "Latitude",
"cw.locationMessage.longitude": "Longitude",
"cw.locationMessage.locationName": "Name",
"cw.locationMessage.locationAddress": "Address",
"cw.locationMessage.locationUrl": "URL",
"cw.contactMessage.contact": "Contact",
"cw.contactMessage.name": "Name",
"cw.contactMessage.number": "Number"
}
23 changes: 21 additions & 2 deletions src/utils/translations/pt-BR.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,25 @@
{
"qrgeneratedsuccesfully": "QRCode gerado com sucesso!",
"scanqr": "Escanei o QRCode com o Whatsapp nos próximos 40 segundos.",
"scanqr": "Escaneie o QRCode com o WhatsApp nos próximos 40 segundos.",
"qrlimitreached": "Limite de geração de QRCode atingido! Para gerar um novo QRCode, envie o texto 'init' nesta conversa.",
"numbernotinwhatsapp": "A mensagem não foi enviada, pois o contato não é um número válido do Whatsapp."
"numbernotinwhatsapp": "A mensagem não foi enviada, pois o contato não é um número válido do WhatsApp.",
"cw.inbox.connected": "🚀 Conectado com sucesso!",
"cw.inbox.disconnect": "🚨 Instância *{{inboxName}}* desconectada do WhatsApp.",
"cw.inbox.alreadyConnected": "🚨 Instância *{{inboxName}}* já está conectada.",
"cw.inbox.clearCache": "✅ Instância *{{inboxName}}* cache removido.",
"cw.inbox.notFound": "⚠️ Instância *{{inboxName}}* não encontrada.",
"cw.inbox.status": "⚠️ Status da instância {{inboxName}}: *{{state}}*.",
"cw.import.startImport": "💬 Iniciando importação de mensagens. Por favor, aguarde...",
"cw.import.importingMessages": "💬 Importando mensagens. Mais um momento...",
"cw.import.messagesImported": "💬 {{totalMessagesImported}} mensagens importadas. Atualize a página para ver as novas mensagens.",
"cw.import.messagesException": "💬 Não foi possível importar as mensagens.",
"cw.locationMessage.location": "Localização",
"cw.locationMessage.latitude": "Latitude",
"cw.locationMessage.longitude": "Longitude",
"cw.locationMessage.locationName": "Nome",
"cw.locationMessage.locationAddress": "Endereço",
"cw.locationMessage.locationUrl": "URL",
"cw.contactMessage.contact": "Contato",
"cw.contactMessage.name": "Nome",
"cw.contactMessage.number": "Número"
}
98 changes: 61 additions & 37 deletions src/whatsapp/services/chatwoot.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1191,14 +1191,26 @@ export class ChatwootService {
await waInstance.connectToWhatsapp(number);
} else {
this.logger.verbose('whatsapp already connected');
await this.createBotMessage(instance, `🚨 ${body.inbox.name} instance is connected.`, 'incoming');
await this.createBotMessage(
instance,
i18next.t('cw.inbox.alreadyConnected', {
inboxName: body.inbox.name,
}),
'incoming',
);
}
}

if (command === 'clearcache') {
this.logger.verbose('command clearcache found');
waInstance.clearCacheChatwoot();
await this.createBotMessage(instance, `✅ ${body.inbox.name} instance cache cleared.`, 'incoming');
await this.createBotMessage(
instance,
i18next.t('cw.inbox.clearCache', {
inboxName: body.inbox.name,
}),
'incoming',
);
}

if (command === 'status') {
Expand All @@ -1208,19 +1220,34 @@ export class ChatwootService {

if (!state) {
this.logger.verbose('state not found');
await this.createBotMessage(instance, `⚠️ ${body.inbox.name} instance not found.`, 'incoming');
await this.createBotMessage(
instance,
i18next.t('cw.inbox.notFound', {
inboxName: body.inbox.name,
}),
'incoming',
);
}

if (state) {
this.logger.verbose('state: ' + state + ' found');
await this.createBotMessage(instance, `⚠️ ${body.inbox.name} instance status: *${state}*`, 'incoming');
await this.createBotMessage(
instance,
i18next.t('cw.inbox.status', {
inboxName: body.inbox.name,
state: state,
}),
'incoming',
);
}
}

if (command === 'disconnect' || command === 'desconectar') {
this.logger.verbose('command disconnect found');

const msgLogout = `🚨 Disconnecting Whatsapp from inbox *${body.inbox.name}*: `;
const msgLogout = i18next.t('cw.inbox.disconnect', {
inboxName: body.inbox.name,
});

this.logger.verbose('send message to chatwoot');
await this.createBotMessage(instance, msgLogout, 'incoming');
Expand Down Expand Up @@ -1509,27 +1536,17 @@ export class ChatwootService {
const latitude = result.degreesLatitude;
const longitude = result.degreesLongitude;

const locationName = result?.name || 'Unknown';
const locationAddress = result?.address || 'Unknown';
const locationName = result?.name;
const locationAddress = result?.address;

const formattedLocation =
'*Localização:*\n\n' +
'_Latitude:_ ' +
latitude +
'\n' +
'_Longitude:_ ' +
longitude +
'\n' +
'_Nome:_ ' +
locationName +
'\n' +
'_Endereço:_ ' +
locationAddress +
'\n' +
'_Url:_ https://www.google.com/maps/search/?api=1&query=' +
latitude +
',' +
longitude;
`*${i18next.t('cw.locationMessage.location')}:*\n\n` +
`_${i18next.t('cw.locationMessage.latitude')}:_ ${latitude} \n` +
`_${i18next.t('cw.locationMessage.longitude')}:_ ${longitude} \n` +
(locationName ? `_${i18next.t('cw.locationMessage.locationName')}:_ ${locationName}\n` : '') +
(locationAddress ? `_${i18next.t('cw.locationMessage.locationAddress')}:_ ${locationAddress} \n` : '') +
`_${i18next.t('cw.locationMessage.locationUrl')}:_ ` +
`https://www.google.com/maps/search/?api=1&query=${latitude},${longitude}`;

this.logger.verbose('message content: ' + formattedLocation);

Expand All @@ -1547,17 +1564,19 @@ export class ChatwootService {
}
});

let formattedContact = '*Contact:*\n\n' + '_Name:_ ' + contactInfo['FN'];
let formattedContact =
`*${i18next.t('cw.contactMessage.contact')}:*\n\n` +
`_${i18next.t('cw.contactMessage.name')}:_ ${contactInfo['FN']}`;

let numberCount = 1;
Object.keys(contactInfo).forEach((key) => {
if (key.startsWith('item') && key.includes('TEL')) {
const phoneNumber = contactInfo[key];
formattedContact += '\n_Number (' + numberCount + '):_ ' + phoneNumber;
formattedContact += `\n_${i18next.t('cw.contactMessage.number')} (${numberCount}):_ ${phoneNumber}`;
numberCount++;
} else if (key.includes('TEL')) {
const phoneNumber = contactInfo[key];
formattedContact += '\n_Number (' + numberCount + '):_ ' + phoneNumber;
formattedContact += `\n_${i18next.t('cw.contactMessage.number')} (${numberCount}):_ ${phoneNumber}`;
numberCount++;
}
});
Expand All @@ -1578,17 +1597,19 @@ export class ChatwootService {
}
});

let formattedContact = '*Contact:*\n\n' + '_Name:_ ' + contact.displayName;
let formattedContact = `*${i18next.t('cw.contactMessage.contact')}:*\n\n_${i18next.t(
'cw.contactMessage.name',
)}:_ ${contact.displayName}`;

let numberCount = 1;
Object.keys(contactInfo).forEach((key) => {
if (key.startsWith('item') && key.includes('TEL')) {
const phoneNumber = contactInfo[key];
formattedContact += '\n_Number (' + numberCount + '):_ ' + phoneNumber;
formattedContact += `\n_${i18next.t('cw.contactMessage.number')} (${numberCount}):_ ${phoneNumber}`;
numberCount++;
} else if (key.includes('TEL')) {
const phoneNumber = contactInfo[key];
formattedContact += '\n_Number (' + numberCount + '):_ ' + phoneNumber;
formattedContact += `\n_${i18next.t('cw.contactMessage.number')} (${numberCount}):_ ${phoneNumber}`;
numberCount++;
}
});
Expand Down Expand Up @@ -2074,7 +2095,10 @@ export class ChatwootService {
return;
}

const msgStatus = `⚡️ Instance status ${inbox.name}: ${data.status}`;
const msgStatus = i18next.t('cw.inbox.status', {
inboxName: inbox.name,
state: data.status,
});

this.logger.verbose('send message to chatwoot');
await this.createBotMessage(instance, msgStatus, 'incoming');
Expand All @@ -2086,7 +2110,7 @@ export class ChatwootService {
if (body.status === 'open') {
// if we have qrcode count then we understand that a new connection was established
if (this.waMonitor.waInstances[instance.instanceName].qrCode.count > 0) {
const msgConnection = `🚀 Connection successfully established!`;
const msgConnection = i18next.t('cw.inbox.connected');
this.logger.verbose('send message to chatwoot');
await this.createBotMessage(instance, msgConnection, 'incoming');
this.waMonitor.waInstances[instance.instanceName].qrCode.count = 0;
Expand Down Expand Up @@ -2147,7 +2171,7 @@ export class ChatwootService {
return;
}

this.createBotMessage(instance, `💬 Starting to import messages. Please wait...`, 'incoming');
this.createBotMessage(instance, i18next.t('cw.import.startImport'), 'incoming');
}

public isImportHistoryAvailable() {
Expand Down Expand Up @@ -2180,7 +2204,7 @@ export class ChatwootService {
return;
}

this.createBotMessage(instance, '💬 Importing messages. More one moment...', 'incoming');
this.createBotMessage(instance, i18next.t('cw.import.importingMessages'), 'incoming');

const totalMessagesImported = await chatwootImport.importHistoryMessages(
instance,
Expand All @@ -2191,10 +2215,10 @@ export class ChatwootService {
this.updateContactAvatarInRecentConversations(instance);

const msg = Number.isInteger(totalMessagesImported)
? `${totalMessagesImported} messages imported. Refresh page to see the new messages`
: `Something went wrong in importing messages`;
? i18next.t('cw.import.messagesImported', { totalMessagesImported })
: i18next.t('cw.import.messagesException');

this.createBotMessage(instance, `💬 ${msg}`, 'incoming');
this.createBotMessage(instance, msg, 'incoming');

return totalMessagesImported;
}
Expand Down
6 changes: 5 additions & 1 deletion tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,5 +18,9 @@
"incremental": true,
"noImplicitAny": false
},
"exclude": ["node_modules", "./test", "./dist", "./prisma"]
"exclude": ["node_modules", "./test", "./dist", "./prisma"],
"include": [
"src/**/*",
"src/**/*.json"
]
}