Automatically detect users language
# 📖tutorials
q
User language detection (from computer/phone system settings) Let's try three things that can also be found in the Botpress documentation and on their YouTube channel. The Bot Sends the First Message Normally the first message is in English, I want to modify it a little bit so that the bot always sends the first message in the user's preferred language. Timely Greeting It didn't matter where I tried the chatbot, still, the Luxon library always shows the server time, not the real time, so let's get that from the website. Recognizing the Language from the User's First Message Let’s try to detect it before the user sends the first message, from the system settings of the user's computer/phone. The user's language could also be automatically detected (more like guessed) based on time zone & city (does not require the user's permission) or location (IP address or using GPS, it requires the user to agree to provide the location). But for example, if a user is traveling in Germany and can't speak German, it might not be a good idea to send them the first message in German. On the other hand, if computer settings and language are in English, and phone settings and language are in Japanese, they would probably be happy to receive the first message in English or Japanese. There's usually a reason why the user has put such settings on their device, so the bot's opening message in the user system settings language may be the preferred option for them.
Copy these Botpress chatbot scripts into your website as always
w
🔥🔥🔥
q
This script on website is listening the Botpress LIFECYCLE.READY event (when the bot is ready for interaction) and getting users timezone, correct time and system language (I also needed to send the time from website to chatbot as string (text), otherwise it changed it again back to server or UTC time) All console.log(xxxxxx) are just for testing, to see the received data also in console, those are not needed when chatbot is in production.
Copy code
js
    <script>
      window.botpressWebChat.onEvent(
        function(event) {
          const userTimeZone = Intl.DateTimeFormat().resolvedOptions().timeZone;
          const currentTime = new Date();
          const currentHour = currentTime.getHours();
          const timeString = currentTime.toString();
          console.log("TIMEZONE: " + userTimeZone)
          console.log("TIME: " + currentTime)
          console.log("HOUR: " + currentHour)
          const userLanguage = (navigator.language || navigator.userLanguage).substring(0, 2);
          console.log("USER LANGUAGE: " + userLanguage);

          window.botpressWebChat.sendPayload({
            type: 'trigger',
            payload: {
              userLanguage: userLanguage,
              userTimeZone: userTimeZone,
              currentTime: currentTime,
              timeString: timeString,
              currentHour: currentHour
            }
          });


        },
        ['LIFECYCLE.READY']
      )

    </script>
That code detects the users language and correct time before the user has send any messages.
This is additional code, to include a button which you can click and get the same results again (mainly for testing purposes)
Copy code
html
    <button id="timeButton">TIME</button>
Copy code
js
    <script>
      //REMOVE IF YOU DON'T NEED THE TIME BUTTON
      document.getElementById('timeButton').addEventListener('click', function() {

        const userTimeZone = Intl.DateTimeFormat().resolvedOptions().timeZone;
        const currentTime = new Date();
        const currentHour = currentTime.getHours();
        const timeString = currentTime.toString();
        console.log("TIMEZONE: " + userTimeZone)
        console.log("TIME: " + currentTime)
        console.log("HOUR: " + currentHour)
        const userLanguage = (navigator.language || navigator.userLanguage).substring(0, 2);
        console.log("USER LANGUAGE: " + userLanguage);

        window.botpressWebChat.sendPayload({
          type: 'trigger',
          payload: {
            userLanguage: userLanguage,
            userTimeZone: userTimeZone,
            currentTime: currentTime,
            timeString: timeString,
            currentHour: currentHour
          }
        });
      });
      // REMOVE UNTIL HERE IF YOU DON'T NEED THE TIME BUTTON

    </script>
This is what the chatbot looks like. It may be the opening workflow for your larger use case, as it doesn't do much yet.
first add a Trigger, and select Custom Trigger Advanced
That trigger is listening when data comes from the website into your chatbot. Then add an Expression card with the condition event.payload.payload
Then add another Node with Execute code card and Set User Language gard  Execute code card to set the users language, timely greeting, correct time and timezone
Copy code
js
let { userLanguage, userTimeZone, timeString, currentTime, currentHour } = event.payload.payload

user.TranslatorAgent.language = event.payload.payload.userLanguage

workflow.userLanguage = userLanguage

let timelyGreeting = '';
if (currentHour >= 0 && currentHour < 12) {
  timelyGreeting = 'Good morning, Boss';
} else if (currentHour >= 12 && currentHour < 18) {
  timelyGreeting = 'Good afternoon, Boss';
} else {
  timelyGreeting = 'Good evening, Boss';
}
 
workflow.timelyGreeting = timelyGreeting
workflow.userTimeZone = userTimeZone
workflow.currentTime = timeString
add these workflow variables
in Set User Language card use this: @workflow.userLanguage
Add another Node with Text card, use this @workflow.timelyGreeting
last Node, an AI Task to write a limerick based on user's timezone or hometown (just for laughs 😂 ) AI Task input: @workflow.userTimeZone Store the result: @workflow.limerick and then a Text card to send the second message (after timely greeting) to the user @workflow.limerick
I tested on two computers with different languages (system settings), and both worked correctly. If you test this, and your computer's settings are in a language other than English, please let me know if it works, or better yet, post a picture 🤖
so go to that jsfiddle web page where the chatbot is (that link earlier), and click the bot open. After a few seconds it should greet you in the right language and also give the correct time.
also when you click the TIME button after first opening the bot, you'll get the same results
For example, if the user's computer was originally installed with English as the operating language, and this is still the system setting, but the user has changed to another language (e.g., because of an external keyboard or some other reason). The navigator.language property in JavaScript typically reflects the user's preferred language settings as configured in their browser. However, if the user has changed their device's language settings, and the browser respects those settings, then navigator.language should reflect the updated language. 💡 So, if the user's system settings are originally 'en-US', but they've changed the device's language to something else (e.g., 'fr-FR'), and the browser takes that into account, then navigator.language should return the updated language (e.g., 'fr' for French) rather than the default 'en-US.' The behavior might vary slightly depending on the browser and operating system. It's always good practice to test your code in different environments to ensure it behaves as expected. 🔍 The default here (in this method) is that the user's preferred language for the chatbot is the same as the language in which everything on the user's computer is, including web browsers, menus, folders, etc. If there are a lot of testers who have changed the language to be other than the system settings, or for some other reason it doesn't work, then let's make the next version of this which works for them too (if possible).
g
Hi, how are you? I have a question regarding the above guide: Where should I enter this part of the code?
q
Hi, to your webpage. Check that jsfiddle link ⬆️
There is an example webpage
code included
h
@quick-musician-29561 I get this error saying payload is undefined, how come? Im using fiddle with code you providede but just inputet my firs scripts, and left the trigger eventy
b
If the website of my clients is in react can we made this? @quick-musician-29561
q
Did you publish your chatbot? After downloading the bot file and publishing it, change the website code to use your Botpress configurable webchat code instead of mine. Then try it on the website, not on the Emulator. I just tried this again after two months, and it seems to be working well. [Website code](https://jsfiddle.net/devmik/sL05co4f/64/)
b
yep, it works well.
q
I can also try to build the same with React.
b
@quick-musician-29561 Idk much of React, I'm learning since yesterday. If my client website is in React, can we do this??
I would be user usefull for me 🦾⚡︎
w
Devmik is the type of guy who will build cutting-edge software that hacks the entire stock market if enough people will ask and benefit from it😆
Even if it would take him 3 years, no sleep, 3069 cans of red bull and 5.2% of his life expectancy
b
jajajajajaj
yeah, @quick-musician-29561 is the goat
@quick-musician-29561 years ago
@quick-musician-29561 don't forget about this 🥲
q
Here is the same code in ReactJS. Add your Botpress configurable webchat code there and test it out when you have time. I tested it and it worked the same as this original JavaScript version.
You can also try it on CodeSandbox. I left my bot details there, which I don't mind sharing now. I'll delete that bot when we have tested enough 🛠️ https://codesandbox.io/p/sandbox/interesting-wiles-pznytk?file=%2Fsrc%2FApp.js%3A65%2C21
So if it works properly, it should show a greeting to the user using the correct language (from the user's device settings, more instructions earlier in this thread), and then use an AI Task to write a limerick based on the user's timezone or hometown (just for laughs).
@jolly-policeman-82775
The toturial you needed
j
oh.
f
Hi, I'm trying to get this to work but even in the jsfiddle i can't get anything. the bot just stays there and doesn't do any detection. All i'm getting is this... Can someone explain what am i doing wrong, please? Thanks https://cdn.discordapp.com/attachments/1191029818083512380/1231268753921015888/Captura_de_Pantalla_2024-04-20_a_las_11.40.48_a._m..png?ex=662533e2&is=6623e262&hm=86d2bacace2ace59d8bf6f6c70a022976a55f3ebce862ad939e6ca724b61e9d4&
double-check that you have the latest jsfiddle link, and that you've also published your chatbot
f
Hey @quick-musician-29561! Bro, i have a quick question about this. What if i wanted to run this only from the webchat? i mean, not on any website (since i don't offer the clients a website as the final product). What should i do then? Because i know that the bot is getting the user's language from the system settings of the browser. But in this case, being the same web browser that's gonna open the webchat, does the bot collects that info the same way? I'm sorry but i'm a little confused. Hope you understand what i mean.
14 Views