yes, `event.userId` is a system-generated ID that ...
# 💻developers
a
yes,
event.userId
is a system-generated ID that is based on the user's browser and device. It is, however, immutable so you cannot set it with another value. If you want to have a way to authenticate users, you should set that up within your website and pass the user ID in via the
init()
script. However an easy (but not secure) way to check if the user is returning or not is to save the userId to a table, and then check in the table at the start of the conversation for that userId
f
Sorry. Maybe you didn't notice my question regarding your last piece of advice. So I'll ask it again. This is very important to me because this is what I need to finish the bot. In reference to your earlier answer that's what I want to do. First get the userID and then put it in the table. However, I don't know how to solve this problem: "you should set that up within your website and pass the user ID in via the init() script." I apologize for perhaps an excessive number of questions, but could you please give me the full procedure on how to achieve this, i.e. provide a piece of code, as you do, for example when discussing embedding a chatbot via iFrame, which should be placed on the website to achieve this. I'm not a programmer in these new languages, so maybe that's where my problem lies. It would be very good if you could make a video on this topic. Thank you
a
So in order to put a chatbot on a website, you have to put code on the website to embed the chatbot inside the web page. There's a video on it here

https://youtu.be/tuO9aQGTZtc?si=XD62WBU9RU67rTFW

You don't need to write any of this code- it is written for you in the admin panel for the bot. Just go to the bot > integrations > web chat and see the code. There are two options: pre-configured
and configurable
For your use case, you will need to use the "configurable" code
Inside this code is a function called
window.botpressWebChat.init()
, which starts the web chat. A lot of data is passed into this function to make it work, and we can pass additional, custom data as shown in our documentation here https://botpress.com/docs/developers/webchat/controlling-webchat-using-js/#send-user-data-from-your-website-to-botpress
Copy code
js
window.botpressWebChat.init({
  userData: {
    name: 'Jack Black',
  },
})
We can combine them inside your website to pass information from your site to your bot.
let's build a demo of this together
First, go to ChatGPT and ask for a demo HTML page. Paste this into https://jsfiddle.net/
Then, copy the "configurable" code from the botpress admin panel and paste it inside the HTML
At this point, my HTML looks like this:
Copy code
html
<!DOCTYPE html>
<html>
<head>
    <title>My First HTML Page</title>
</head>
<body>
    <h1>Welcome to My Website</h1>
    <p>This is a basic example of an HTML page.</p>
    <ul>
        <li>Item 1</li>
        <li>Item 2</li>
        <li>Item 3</li>
    </ul>
    <p>Thank you for visiting!</p>
</body>

<script src="https://cdn.botpress.cloud/webchat/v0/inject.js"></script>
<script>
  window.botpressWebChat.init({
      "composerPlaceholder": "Chat with bot",
      "botConversationDescription": "This chatbot was built surprisingly fast with Botpress",
      "botId": "5fcacb4c-baae-4061-a258-0a7d47b060d3",
      "hostUrl": "https://cdn.botpress.cloud/webchat/v0",
      "messagingUrl": "https://messaging.botpress.cloud",
      "clientId": "5fcacb4c-baae-4061-a258-0a7d47b060d3",
      "lazySocket": true,
      "frontendVersion": "v0",
      "useSessionStorage": true,
      "enableConversationDeletion": true,
      "showPoweredBy": true,
      "theme": "prism",
      "themeColor": "#2563eb"
  });
</script>

</html>
Finally, add a "userData" parameter to the
window.botpressWebChat.init()
function with whatever data you want to pass to the bot
I've made up some data and put it right at the top of the function. My HTML now looks like this:
Copy code
html
<!DOCTYPE html>
<html>
<head>
    <title>My First HTML Page</title>
</head>
<body>
    <h1>Welcome to My Website</h1>
    <p>This is a basic example of an HTML page.</p>
    <ul>
        <li>Item 1</li>
        <li>Item 2</li>
        <li>Item 3</li>
    </ul>
    <p>Thank you for visiting!</p>
</body>

<script src="https://cdn.botpress.cloud/webchat/v0/inject.js"></script>
<script>
  window.botpressWebChat.init({
          "userData":{
            "platform":"discord",
              "userNames":"Mieczysław"
      },
      "composerPlaceholder": "Chat with bot",
      "botConversationDescription": "This chatbot was built surprisingly fast with Botpress",
      "botId": "5fcacb4c-baae-4061-a258-0a7d47b060d3",
      "hostUrl": "https://cdn.botpress.cloud/webchat/v0",
      "messagingUrl": "https://messaging.botpress.cloud",
      "clientId": "5fcacb4c-baae-4061-a258-0a7d47b060d3",
      "lazySocket": true,
      "frontendVersion": "v0",
      "useSessionStorage": true,
      "enableConversationDeletion": true,
      "showPoweredBy": true,
      "theme": "prism",
      "themeColor": "#2563eb"
  });
</script>
</html>
That's it for the website part, next we head into Botpress
We can build a very simple bot of just three nodes
Trigger1 This starts te bot automatically as soon as the chat is opened
Standard5 This node uses the "Get User Data" card to extract the data that we included in the
window.botpressWebChat.init()
function. We pass
event.userId
as input and define a workflow variable as output
Then we use a normal text card to speak the variable's value.
then we Publish the bot
And now, when we open the bot, it will say the data we passed to it
You can view my code here https://jsfiddle.net/fybmwzqk/9/
though I won't keep the bot up for very long, so I encourage you to follow this tutorial and build your own
f
Thank you for your comprehensive answer. Two things. 1. The problem that I couldn't get userID was because I didn't pay attention to the case-sensitive nature of the variable name. I used event.userID (capital D) instead of event.userId. I think it is worth drawing attention to this somewhere in the documentation. 2. After I embedded the code via iFrame, every time the page is reloaded, the chatbot restarts with a different userId. I noticed that after embedding the Pre-configured chatbot, it remembers the previous conversation and starts with the same userId as before. Unfortunately, there is no way to check which parameter causes this. Unfortunately, today I noticed that this only works for a while. Can you tell me what should be done so that every time someone enters from the same website on the same computer, the UserId remains the same. Thank you.
a
I'm not too sure about #2. @famous-jewelry-85388 do you have any idea?
f
@few-area-98148 can you share your embedding code after removing sensitive information?
f
Here is a link to a screen recording of how it works. Event.userId is displayed and you can see that this changes every time the page is refreshed. https://screenrec.com/share/253wlgau7V <iframe style="border: none;" srcdoc=" window.botpressWebChat.init({ 'composerPlaceholder': 'Tu wpisz swoje pytanie', 'botConversationDescription': 'd/s kursu Doradca d/s wniosków unijnych', 'botName': 'To JA. Twój asystent AI', 'botId': '*********************************************', 'hostUrl': 'https://cdn.botpress.cloud/webchat/v0', 'messagingUrl': 'https://messaging.botpress.cloud', 'clientId': '*******************************************', 'enableConversationDeletion': true, 'showPoweredBy': true, 'className': 'webchatIframe', 'containerWidth': '100%25', 'layoutWidth': '100%25', 'hideWidget': true, 'showCloseButton': false, 'disableAnimations': true, 'closeOnEscape': false, 'showConversationsButton': false, 'enableTranscriptDownload': false, 'stylesheet':'https://webchat-styler-css.botpress.app/prod/code/e7f2881f-77e6-447f-a6b1-2e0af83b93de/v47831/style.css' }); window.botpressWebChat.onEvent(function () { window.botpressWebChat.sendEvent({ type: 'show' }) }, ['LIFECYCLE.LOADED']); " width="100%" height="100%" > If there's anything else you need, I'll be happy to send it.
f
Understood. And why do you need the userId? what do you use it for?
I am not challenging you, just want to better unsderstood your use case
Why don 't you use the normal embedding and not the Iframe way?
what happens if you embed it directly? does it work - without the iframe
there is no parameter that causes this. This is part of your browsers local storage
f
I'll explain again what I already explained to Gordy. I want to distinguish when a user uses the bot for the first time and when he returns and uses it again. Depending on this, I have a different way of greeting - for new users, I ask them to provide their data such as name, email, etc. and save it in the table under the userId index, - for those returning, I already have this data in the table and I could find it in the table via userId (if it was the same as during the first visit); then I can also supplement the information about the user with that obtained in the next conversation, e.g. what questions he asked and what answers he received. I don't know what you mean by normal embedding. I use iFrame embedding because I want to have the chatbot in a specific place on the website, not as a widget. But when embedded as a widget, it also does not remember the previous userId and uses a different one each time it is entered. It works the same without iFrame. PS Maybe it's not local storage but session storage. Someone who programmed this for you should know. Then it could be changed to local storage and it would work on every entry. I will say that in the current system, I don't really see the point of having such a variable, because in a given conversation it is known who the bot is talking to.
f
It is local storage, for the session storage you have to specify the "useSessionStorage" variable.
Can you try the same URL from your phone? or another machine?
You can send it to me here and I can try it
f
This is a link to the page with the embedded bot. Let me know when I can remove it https://sites.google.com/view/365tymczasowy This is embedded code <iframe style="border: none;" srcdoc=" window.botpressWebChat.init({ 'composerPlaceholder': 'Tu zadaj pytanie lub odpowiedz botowi', 'botConversationDescription': 'd/s kursu Doradca d/s wniosków unijnych', 'botName': 'To Ja, Twój asystent AI', 'botId': '**', 'hostUrl': 'https://cdn.botpress.cloud/webchat/v0', 'messagingUrl': 'https://messaging.botpress.cloud', 'clientId': '**', 'enableConversationDeletion': true, 'showPoweredBy': true, 'className': 'webchatIframe', 'containerWidth': '100%25', 'layoutWidth': '100%25', 'hideWidget': true, 'showCloseButton': false, 'disableAnimations': true, 'closeOnEscape': false, 'showConversationsButton': false, 'enableTranscriptDownload': false, 'useSessionStorage': true, 'enablePersistHistory': true, 'stylesheet':'https://webchat-styler-css.botpress.app/prod/code/e7f2881f-77e6-447f-a6b1-2e0af83b93de/v47831/style.css' }); window.botpressWebChat.onEvent(function () { window.botpressWebChat.sendEvent({ type: 'show' }) }, ['LIFECYCLE.LOADED']); " width="100%" height="100%" > This is bot screen
f
can you retry after removing the "useSessionStorage" attribute?
One more thing, I copy pasted your code in a plain HTML and it is working for me, the userId doesn't change on refresh
So maybe there is something strange with the hosting
f
Thank you. Removing "useSessionStorage" doesn't change anything. It seems that if the bot is a separate page, it works. When it's an iFrame on another page, it doesn't seem to work. Most likely, the pages on which the iFrame is embedded clear the entire cache before exiting, because I noticed that even when I added a fragment of the code that created a write to the cache, the data disappeared after exiting. The best way to find out how it actually works in cases of iFrame embedding is to visit your bot on some website and check how it works. For me, the ability to use iFrame embedding is important and in this respect it is probably underdeveloped. Please remove this code because it contains my identification data.
One more important thing for me. I embedded this code as an iFrame in a wordpress site. Unfortunately, it is not fully displayed here. I'm sending screenshots. Can you do something with it.
f
Yes there is a problem between wordpress and "iframe srcdoc"
Someone here in Discord overcame it and fixed it.
I can look for that conversation if you want
f
I don't use Gutenberg, I use the classic editor. The code attached there doesn't work for me. I decided on botpress because it has the ability to embed the bot as an iframe. The fact that it doesn't work with WordPress is for me difficult to understand. Wordpress is most popular website builder and in my opinion all functionality of botpress should work there. Is it possible you will solve this problem? By the way userId also stopped being maintained on the second day on the page sent to me. I've tested it on qiute diferrent website and it don't work too.* One important thing. Please remove this code you send me, because my bot and uesr ID are there.*
f
1) The problem is between wordpress and iframe with attribute srcdoc. It works on normal HTML pages and other hosts. There is a new webchat being released. Maybe it will fix the issue! maybe not I am not sure because I can't replicate it. I would say, check with WordPress support or community, maybe they have a fix 🙂
2) I think I have deleted it, can you double check/
3) I didn't understand this message. Can you elaborate more?
f
Thank you. You said:"One more thing, I copy pasted your code in a plain HTML and it is working for me, the userId doesn't change on refresh So maybe there is something strange with the hosting". It only worked for a while. The next day the userId was different again.
g
Hey guys hope you all have a good one! I want to setup an AI task that creates a random user Id consisting of 8 numbers and two letters at the end. I prompted the AI to compare that generated Id with all of the Ids in the knowledgebase - table, in the ID column. It seems like the AI is not able to view the values inside the table. Does anyone know a trick here?
a
Why do want to use an AI task for this? Code can do this much quicker & more reliably. Try:
Copy code
js
function generateRandomUserId() {
  const chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
  return Array.from({ length: 10 }, (_, i) =>
    chars[Math.floor(Math.random() * (i < 8 ? 10 : chars.length))]
  ).join('');
}
//Call the function like this:
workflow.randomUserId = generateRandomUserId();
g
TRhanky gordy! this is exactly how I did it in the end.
One other question concerning custom code, ther eis the validate option on all capture cards, but no matter what i try it always gives me an error and I made sure my code is to the point and has no mistakes. Do i somehow have to call the validate function?
a
you do need to call the validation function, yes
I stand corrected! You do not have to call the validation function, it is called automatically
g
So the bot will register if i return true or false?
f
What do you mean by register?
g
Sorry i meant registrate, because I had the feeling that the output of the validation is not passed on correctly to the capture card sometimes and I was wondering if I maybie have to put some kind of expression in the code that states that the validation was successful.
But I now realize gordy answered that question already. I should not work in the night XD
f
😄 \o/
Perfect!
thanks @acceptable-kangaroo-64719
@few-area-98148 Were you able to fix the unique "userID" issue? Can you share it with us? This is really important for me to learn 🙂
I have seen you posting here and made me wonder: https://discord.com/channels/1108396290624213082/1175047238062444565
Thanks in advance for sharing your solution 🙂
f
Unfortunately not. The problem is that if you use event.UserId (note the small d in the name - a small thing, but very important), the system does not remember it during the next session and generates a new UserId for the same user. I tried saving this userId in the browser cache, but it also disappears when I close the browser. You can still try to use cookies for this purpose, but I've given up on it for now. Currently, I ask the user whether he has already talked to the chatbot and depending on his answer, I generate a different flow.
f
Oh! that's unfortunate. I still believe the problem is from the google site, there is something that doesn't keep the local storage.
hmm.... I will think about it on Monday, maybe I can find something
f
I only use Google sites as a demo. Ultimately, I will install on Wordpress. But it doesn't work even in share mode.
f
Can you give me your shareable URL please?
f
But what you want check?
f
I wanted to check why it isn't working
f
I don't know why event.userId doesn't work. This is what the author of this solution should find by analyzing the code he wrote. I can only say that when a bot is installed on some other website via iFrame, it most often stops working immediately the next time the bot is launched. If the bot is a separate page, it takes a little longer. It stopped working the next day.
Regarding user identification, there is the FingerprintJS library, which allows user identification. Unfortunately, it is quite expensive. There are several alternatives, but they are also paid. At this point in my knowledge I don't think it's worth using.
9 Views