chatbot interrupts conversation - python

I’m creating a chatbot a bit different from what we are used to use and I need help and advice. The idea is that the chatbot has an external interface as I have read that for the bot to start the conversation is necessary (correct me if it is not true), the problem is that I have never created an interface like this and when I have tried to take created projects and test them to see how it would look like I can not get it to work, I attach an example of how it looks once written rasa.
Example of a conversation:
(11:22) User:Hello
(11:22) Bot: Hello, how can I help you?
(11:23) User: What will the weather be like today?
(11:23) Bot: It will rain this afternoon.
(Stands by on hold)
(14:12) Bot: It's already raining.
(14:13) User: Will it rain for a long time?
(14:13) Bot: Yes, it will be raining for about three hours
I know how to do the first part, until the bot takes the initiative, but I don't know how to continue.
index.html:
<html>
<body>
<script>!(function () {
let e = document.createElement("script"),
t = document.head || document.getElementsByTagName("head")[0];
(e.src =
"https://cdn.jsdelivr.net/npm/rasa-webchat#1.0.0/lib/index.js"),
// Replace 1.x.x with the version that you want
(e.async = !0),
(e.onload = () => {
window.WebChat.default(
{
initPayload: '/greet',
customData: { language: "en" },
socketUrl: "http://localhost:5005",
// add other props here
},
null
);
}),
t.insertBefore(e, t.firstChild);
})();
</script>
</body>
</html>
credentials.yml:
# This file contains the credentials for the voice & chat platforms
# which your bot is using.
# https://rasa.com/docs/rasa/messaging-and-voice-channels
rest:
# # you don't need to provide anything here - this channel doesn't
# # require any credentials
#facebook:
# verify: "<verify>"
# secret: "<your secret>"
# page-access-token: "<your page access token>"
#slack:
# slack_token: "<your slack token>"
# slack_channel: "<the slack channel>"
# slack_signing_secret: "<your slack signing secret>"
socketio:
user_message_evt: user_uttered
bot_message_evt: bot_uttered
session_persistence: true
#mattermost:
# url: "https://<mattermost instance>/api/v4"
# token: "<bot token>"
# webhook_url: "<callback URL>"
# This entry is needed if you are using Rasa X. The entry represents credentials
# for the Rasa X "channel", i.e. Talk to your bot and Share with guest testers.
rasa:
url: "http://localhost:5002/api"
I have several questions:
Why if I type rasa shell the chatbot works correctly but if I type rasa run -m models --enable-api --cors "*" --debug and open index.html I get a blank.
[enter image description here][1]
How to make the second part even to test it with rasa shell?
Can you start the bot in different ways, for example, It is starting to rain and other times: It has stopped snowing?
Any ideas, suggestions, pages that can help me?
Thank you!
[1]: https://i.stack.imgur.com/shcz0.png

Why if I type rasa shell the chatbot works correctly but if I type
rasa run -m models --enable-api --cors "*" --debug and open index.html
I get a blank. enter image description here
I suggest using the official rasa chat widget as your frontend. If you have questions about it you can ask it in the rasa forum. If you found a bug, you can file a bug report in the rasa open source repo.
How to make the second part even to test it with rasa shell?
This documentation on how to get the bot to start the conversation with the user should help you get started.
Can you start the bot in different ways, for example, It is starting
to rain and other times: It has stopped snowing?
You can send to the bot the trigger intent that will trigger the desired response from the bot. See answer to the question for details.

Related

Python to post and format API response data into Slack channel

Working on a script to present data in Slack channel.. I have a script I'm working on to request and return data that I need to post in the channel that gets invoked with a Slash command, but having an issue with presenting the data in the slack channel from where I've executed the Slash command. I've been attempting to work with the Block Kit Builder, but I see no way of presenting that data coming back from my script using the template I created.
Then in the Block kit builder, I can kind of see the format I want and send it to Slack from the Block kit builder, but if I wanted my return response from my Python script to be formatted by the template and respond in the channel, it doesn't seem to work.. I'm thinking I'm definitely doing something wrong, but was looking for suggestions..
I've been searching on possibly how to do it in Flask, which is what I'm using to execute a Slash command in Slack to invoke my Python script to query the API, get the response and send it to Slack..
Thanx.
P.S. Stackflow won't allow me to post a snippet of the json and/or images.. yet... something about a '10 reputation'...
I was able to figure this out. In my code, I reflected this:
for i in pdjson:
t = {}
try:
t["text"] = {
"type": "plain_text",
"text": f'{i["escalation_policy"]["summary"]} - Layer: {i["escalation_level"]}'
}
except (KeyError):
t["text"] = {
"type": "plain_text",
"text": f'{i["escalation_policy"]["summary"]} - Layer: {i["escalation_level"]}'
}
t["value"] = i["user"]["summary"]
Now I can present in the slack workspace with the block kit template. Now I just have to figure out how make the 'value' show up once I select an item in the list.

Rasa, Botfront and heroku: Frontend doesn't work after deployment

I have deployed my rasa chatbot online by creating a docker image, pushing and releasing it to Heroku. Now my bot is live on Heroku. I would like to communicate with this bot, through my website. I have added my bot url to Botfront widget's socketurl. However, when I send a message, I do not get any response. Does anyone know what I'm missing or doing wrong?
The content of my script is:
<!-- chatbot -->
<script>
!(function () {
let e = document.createElement("script"),
t = document.head || document.getElementsByTagName("head")[0];
(e.src = "{% static 'js/chatbot.js' %}"),
(e.async = !0),
(e.onload = () => {
window.WebChat.default(
{
customData: { language: "en" },
socketUrl: "https://app-name.herokuapp.com",//not real bot url
// add other props here
// initPayload: "/greet",
title: "Let's talk, we are online.",
subtitle: "Say hi to get started.",
},
null
);
}),
t.insertBefore(e, t.firstChild);
})();
</script>
If someone can help me, I would really appreciate it, been stuck on this for days!
Did you add the SocketIO configuration? You should add the following in your credentials.yml file (it will be inside your Docket container, not in git repository).
socketio:
user_message_evt: user_uttered
bot_message_evt: bot_uttered
session_persistence: true # or false
You can see more details in RASA documentation for web channel.
I see, since Heroku is using python as server end it might be not able to load index.html or any HTML code. try hosting your HTML code to a different server. I would suggest using Github's profile hosting.
I have also hosted my HTML page on GitHub and rasa server on a cloud server.
check it out here: https://horizon733.github.io/
Also, check out this documentation by Heroku while using the python server.
I hope this helps, feel free to ask any doubts.

Basic Python Echo Bot not addressable through Bot Framework Emulator (Post 500) after linking to Azure QnA Maker

I have followed the official instructions (Docs) on how to create a python echo bot with the SDKv4 and as soon as the described init function is added my bot ceases to work. The echo bot by itself, without the connection to the Azure QnA Maker works perfectly within the Bot Framework Emulator.
The Error displayed in the Bot Framework Emulator:
POST500directline/conversations//activities. Also it doesn't display the welcoming message any more and when I send a message the bot apparently does not receive that message (send failed, retry is displayed below the message).
This problem occurs after adding the init function from the guide to the MyBot class from the bot.py file. The function reads:
def __init__(self, config: Config):
self.qna_maker = QnAMaker(
QnAMakerEndpoint(
knowledge_base_id=config["QNA_KNOWLEDGEBASE_ID"],
endpoint_key=config["QNA_ENDPOINT_KEY"],
host=config["QNA_ENDPOINT_HOST"],
)
)
When following the guide, I had to move the bot instance creation to the very bottom of the app.py file, below:
APP = web.Application(middlewares=[aiohttp_error_middleware])
APP.router.add_post("/api/messages", messages)
if __name__ == "__main__": (...)`
as the code otherwise doesn't run: BOT = MyBot(APP.config) causes: NameError: name 'APP' is not defined
Also I get the problem in the app.py file: No name 'DefaultConfig' in module 'config' - even though config.py exists and is obviously used as the ports change when I change them in the config file.
Aside from that I followed the guide precisely. I would be very thankful for any help or resource recommendations, over the past two days I've tried to everything I could find online. Thank you!

Overriding pre-defined answer in ChatterBot

I want to specify my own answer to a particular question for a chat bot written using ChatterBot library. Here is my code
from chatterbot import ChatBot
# Create a new chat bot named Charlie
chatbot = ChatBot(
'Charlie',
trainer='chatterbot.trainers.ListTrainer'
)
chatbot.train([
"who are you?",
"I'm a friendly chat bot"
])
# Get a response to the input text 'who are you?'
response = chatbot.get_response('who are you?')
print(response)
The output after running this piece of code is
Who? Who is but a form following the function of what
instead of
I'm a friendly chat bot
So it looks like there is a pre-specified answer to this question embedded in the library. How can I configure a bot that will use only my answers?
#DavidBankom The bot will train only with your data. The code snippet also tells same thing from source code.
# Use specified trainer or fall back to the default
trainer = kwargs.get('trainer', 'chatterbot.trainers.Trainer')
TrainerClass = utils.import_module(trainer)
self.trainer = TrainerClass(self.storage, **kwargs)
self.training_data = kwargs.get('training_data')
I think the behavior your are seeing due to pertained database exists in your environment.
Could you please try to delete your sqlite database file, I think in your case it could db.sqlite
default_uri = "sqlite:///db.sqlite3"
Let me know if you need any help.
You can use Specific Response Adapter. Below is the sample code. You can find more on this link: http://chatterbot.readthedocs.io/en/stable/logic/index.html
{
'import_path': 'chatterbot.logic.SpecificResponseAdapter',
'input_text': 'Help me!',
'output_text': 'Ok, here is a link: http://chatterbot.rtfd.org'
}

How to convert terminal window chat application (built using socket programming, written in python) into a web application?

So, I wrote this chat application which works well in terminal windows:
GitHub Source
Now what I want is to convert into a web chat application so that my friends can connect/chat/test it from their network. But, I am clueless about how to proceed!
Please help me. Suggest me which technologies can I use to make it available on a website?
It looks like you've written a Python server to handle your Python chat clients, and you'd like to extend this to web clients.
I would recommend using a real-time network such as PubNub to relay data between your chat clients and the server. Using a real-time network means that you can spend less time worrying about low-level socket issues such as concurrency and more time building your application.
In the case of PubNub, a Python SDK will allow your server to subscribe to chat channels, while the JavaScript SDK will help with web-based clients. You can build a simple JavaScript-based web client using the code in this blog post: Build Real-Time Chat Apps in 10 Lines of Code.
Enter Chat and press enter
<div><input id=input placeholder=you-chat-here /></div>
Chat Output
<div id=box></div>
<script src=http://cdn.pubnub.com/pubnub.min.js></script>
<script>(function(){
var box = PUBNUB.$('box'), input = PUBNUB.$('input'), channel = 'chat';
PUBNUB.subscribe({
channel : channel,
callback : function(text) { box.innerHTML = (''+text).replace( /[<>]/g, '' ) + '<br>' + box.innerHTML }
});
PUBNUB.bind( 'keyup', input, function(e) {
(e.keyCode || e.charCode) === 13 && PUBNUB.publish({
channel : channel, message : input.value, x : (input.value='')
})
} )
})()</script>
Then, on your Python server, you could subscribe to the same chat channel:
# Listen for Messages *BLOCKING*
def receive(message) :
broadcast_data(message) #This is using your Python function from your github link
return True
pubnub.subscribe({
'channel' : 'chat',
'callback' : receive
})
Let me know if this works for you. Good luck!

Categories

Resources