delayed response from chatterbot api python - python

when I started working on chatterbot API its result was coming frequently but gradually its response was getting delayed day by day. Now it's taking around 2 minutes to respond for a simple "hello" message. It's not a problem with the code. the problem is something else. Can anyone help me with this?
from chatterbot import ChatBot
from chatterbot.trainers import ListTrainer
bot = ChatBot(
'Norman',
storage_adapter='chatterbot.storage.SQLStorageAdapter',
input_adapter='chatterbot.input.TerminalAdapter',
output_adapter='chatterbot.output.TerminalAdapter',
logic_adapters=[
'chatterbot.logic.MathematicalEvaluation',
'chatterbot.logic.TimeLogicAdapter'
],
database='./db.sqlite3'
)
bot.set_trainer(ListTrainer)
bot.train([
'How are you?',
'I am good.',
'That is good to hear.',
'Thank you',
'You are welcome.'
])
while True:
try:
your_input = input("You: ")
bot_output = bot.get_response(your_input)
print(bot_output)
except(KeyboardInterrupt, EOFError, SystemExit):
break

The problem is that the code is using Terminal Input Adapater.
According to docs :
The input terminal adapter allows a user to type into their terminal to communicate with the chat bot.
So it is basically used to get input from terminal.
The code also tries to get manual user input using input() (inside while loop). This makes processing slower. By removing Terminal adapter as input adapter this problem can be solved.

Related

I keep getting same errors when trying to rerun Telethon script

so i`m trying to learn Telethon and wrote some script from tutorial. It works fine for the first time, when i have to confirm authorization.
from telethon import TelegramClient
api_id = 1234567
api_hash = ''
client = TelegramClient('anon', api_id, api_hash)
async def main():
me = await client.get_me()
print(me.username)
with client:
client.loop.run_until_complete(main())
but when i try to run it again with the same .session file i keep getting same error, which doesn`t help to understand the problem.
Server sent a very new message with ID 7144059125492611077, ignoring
Server sent a very new message with ID 7144059125964561409, ignoring
Also, program doesn`t stop running after this error.
After a couple of days searching for a fix, i just switched to pyrogram, which works perfectly fine. So if someone got the same problem I recommend just to change Telethon to something else.
Make sure your system time is correct. If the issue persists, it may be a bug you which you should report to https://github.com/LonamiWebs/Telethon/issues/new/choose. However recent versions of the library (v1.25.2) should not have this issue.

python requests module trouble logging into html that uses basic prompt login

ok, so I am trying to put together a program for work that scrapes logs from the machines I work on (S17+/T17+ bitmain miners) but I'm stuck with authenticating the session.
I am trying to use the requests module and currently have the fallowing test code to login
import requests
def ty(d):#ignore, just my type tool
return type(d).__name__
cred = {"Username" : "root", "Password" : "root"}#credentials for logging in
#when you into a browser, you would enter this into a browser prompt
#predefining some stuff
post = None
data = None
with requests.Session() as session:#opens a new session
post = session.post("http://10.0.4.1", data = cred)#attempts to connect, but gets 401 response
data = session.get("http://10.0.4.1/kernelLog.html")#same thing here
post#just spits out what the test code got bc making this in vs code
data
so as for the machines they are set up on a local network. when we login to them in a browser they prompt us for the login witch is root for both the user and pass, I could be naming the credentials wrong but I don't know how to even check that so just named them what the window prompt has them listed as
images of what it looks like to login to them...
https://drive.google.com/file/d/1Uyh5vvTi4F68vsKdpzsJesPREo6WGa9l/view?usp=sharing
the main screen I am trying to get into and the url...
https://drive.google.com/file/d/16uxeOJNXWZ-ip5xx7BFkzFC168CXebeO/view?usp=sharing
and finally the screen with the kernel log that I plan to rip when I get it to not 401...
https://drive.google.com/file/d/19sIM0EPSp6Ti5GDLqN8qCx07E6ItMj43/view?usp=sharing
I should probably add that I am pretty rusty with my programming so apologies if this has a really dumb fix I'm missing.
If any other data is needed, ask and I will try to get back with it.

chatbot interrupts conversation

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.

How to call this function that checks if a message as been received and then sends response?

I have this function that runs fine on its own but when I try to call to it in another program it doesnt work, I want to use it to check if a message has been received and then respond if one has.
from flask import Flask, request
from twilio.twiml.messaging_response import MessagingResponse
from flask import Flask
app = Flask(__name__)
#app.route("/sms", methods =['POST'])
def sms_reply():
number = request.form['From']
m_b = request.form['Body']
response_message='unknown response, type KEW for a list of known words'
resp = MessagingResponse()
print(m_b)
if m_b=='hello' or m_b== 'Hello':
response_message='Hi,how are you?'
elif m_b=='KEW' or m_b== 'kew' or m_b== 'Kew':
response_message='hello, ..... yeh thats only one i have set up so far im still testing it'
resp.message(response_message)
return str(resp)
if __name__ == "__main__":
app.run(debug=True)
the program its being called in
def bot():
timer=time.time()
sold_out=True
print('Bot is starting')
print('Loading item page')
still_running_check=0
while sold_out==True: #while item is sold out reload the page and print sold out to the console
driver.get(item_url)
#time.sleep(1)
sold_out=check_exists_by_xpath("/html/body/div[3]/main/div[2]/div[3]/div[2]/div/div/div[6]/div[1]/div/div/div/button")
still_running_check+=1
sms_reply()
#if still_running_check%100==0:
#sms('Bot is still running and is on attempt '+str(still_running_check)+'\n '+str(round((time.time()-timer)/60,2))+' minute(s) have passed')
if sold_out==False:
break
else:
print ("Sold out")
cart_button = driver.find_element_by_class_name("fulfillment-add-to-cart-button") #once sold out is no longer true add to cart button is clicked
cart_button.click()
time.sleep(1)
driver.get("https://www.bestbuy.com/checkout/r/fast-track") #navigates to checkout page
time.sleep(1)
code= driver.find_element_by_xpath('//*[#id="credit-card-cvv"]') #csv input location
code.send_keys(security_code) #inputs previously given csv code
time.sleep(2)
#confirm_button= driver.find_element_by_class_name("button--place-order-fast-track")
#confirm_button.click()
print('Order submission screenshot saved as "OrderSubmission.png" in repository location') #order completion code
driver.get_screenshot_as_file('OrderSubmission.png')
sms('Bot Program executed succesfully for '+title.text)
end=input(title.text+' program executed succesfuly hit enter to exit browser or type retry to start bot again:') #if program ran all the way through will print program ran succesfully
if end=='retry':
bot()
this returns the error "Working outside of request context.
This typically means that you attempted to use functionality that needed
an active HTTP request. Consult the documentation on testing for
information about how to avoid this problem."
I looked in the flask documentation and saw this
"This should typically only happen when testing code that expects an active request. One option is to use the test client to simulate a full request. Or you can use test_request_context() in a with block, and everything that runs in the block will have access to request, populated with your test data."
but I don't really understand what its saying and how to implement that into my code
Twilio developer evangelist here.
Your first function, sms_reply, looks as though it is set up to receive an incoming webhook from Twilio when an SMS message is sent to your Twilio phone number. The function receives an incoming HTTP request, checks the body of the message, constructs a reply and returns it as the response to the request.
The problem is that you are then trying to call that function, which is expecting to respond to an HTTP request, inside your second bit of code, which does not seem to have an HTTP request related to it at all.
You might find that you want to use the Twilio REST API if you want to list messages that you have received or send a message. I'm not sure exactly what your code is trying to do, so I can't be more specific than that.

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'
}

Categories

Resources