'Chatbot' is not defined in Chatterbot - python-3.x

I am making a chatbot through Chatterbot. I am facing the problems as follow:
when I run the code, it shows error, but the ChatBot is imported from chatterbot at the beginning?
File ".../SquirralBot.py", line 5,
in
class SquirralBot: File "...SquirralBot.py", line 6, in
SquirralBot
bot = Chatbot("SquirralBot", NameError: name 'Chatbot' is not defined
I want to make the chatbot to distinguish specific texts then to trigger specific corpus, how can I make it? Is the "chatterbot.conversation.Response(text, **kwargs)" class for this purpose? e.g. when the user types "I am leaving", then it will trigger to call the training set "chatterbot.corpus.chinese.squirral_bye_conversation"?
Is it possible if I can store the reply specifically to the database e.g. MongoDB for different users? e.g. when user A replies "I am sick. I got fever and running nose", then the system store "sick" into "status" and "fever" and "running nose" into "symptoms" in the user A's data so that inside the database it would be like JSON:
{
"user A",
"gender": "male",
"record": [
{
"date": "25-12-2018",
"status": "fine",
"symptoms": "",
},
{
"date": "26-12-2018",
"status": "sick",
"symptoms": "fever", "running nose"
}
}
Is it possible to make the chatbot can text the user in specific time range?
The code for the above mentioned is as following. I am very new in programming so the code may be a bit messy. Please feel free to correct. Many thanks.
import sys
from chatterbot import ChatBot
from chatterbot.trainers import ChatterBotCorpusTrainer
class SquirralBot:
chatbot = Chatbot("SquirralBot",
logic_adapters=[
{
"import_path": "chatterbot.logic.BestMatch",
"statement_comparison_function": "chatterbot.comparisons.levenshtein_distance",
"response_selection_method": "chatterbot.response_selection.get_first_response"
}
],storage_adapter = "chatterbot.storage.JsonFileStorageAdapter",database = "./SquirralBot_DB.json")
def __init__(self):
self.chatbot.set_trainer(ChatterBotCorpusTrainer)
self.chatbot.train("chatterbot.corpus.chinese.squirral_greeting", "chatterbot.corpus.chinese.squirral_bye_conversation", "chatterbot.corpus.chinese.squirral_normal_conversation", "chatterbot.corpus.chinese.squirral_rabbit_bye_conversation", "chatterbot.corpus.chinese.squirral_rabbit_conversation")
def getResponse(self, message=""):
return self.chatbot.get_response(message)
if __name__ == "__main__":
bot = SquirralBot()
print(bot.getResponse(sys.argv[1]))

Your import statements hint a ChatBot class with a capitalized B:
from chatterbot import ChatBot
Change
chatbot = Chatbot("SquirralBot",...)
to
chatbot = ChatBot("SquirralBot",...)
Note the capitalize B in ChatBot.

Related

Create an event with conference using python and Google Calendar API creates the event but not the conference

I am trying to create an event using Google Calendar API in Python 3. I also want to generate a Google Meet conference link for the event. I am using the documentations provided here:
https://developers.google.com/calendar/quickstart/python
https://developers.google.com/calendar/v3/reference/events#conferenceData
https://developers.google.com/calendar/create-events
The event is created without a problem. However, it is missing the conference link. My code so far is as follows:
from pathlib import Path
from pickle import load
from pickle import dump
from google.auth.transport.requests import Request
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build
from uuid import uuid4
from typing import Dict, List
from oauth2client import file, client, tools
class EventPlanner:
def __init__(self, guests: Dict[str, str], schedule: Dict[str, str]):
guests = [{"email": email} for email in guests.values()]
service = self._authorize()
self.event_states = self._plan_event(guests, schedule, service)
#staticmethod
def _authorize():
scopes = ["https://www.googleapis.com/auth/calendar"]
credentials = None
token_file = Path("./calendar_creds/token.pickle")
if token_file.exists():
with open(token_file, "rb") as token:
credentials = load(token)
if not credentials or not credentials.valid:
if credentials and credentials.expired and credentials.refresh_token:
credentials.refresh(Request())
else:
flow = InstalledAppFlow.from_client_secrets_file('calendar_creds/credentials.json', scopes)
credentials = flow.run_local_server(port=0)
with open(token_file, "wb") as token:
dump(credentials, token)
calendar_service = build("calendar", "v3", credentials=credentials)
return calendar_service
#staticmethod
def _plan_event(attendees: List[Dict[str, str]], event_time, service: build):
event = {"summary": "test meeting",
"start": {"dateTime": event_time["start"]},
"end": {"dateTime": event_time["end"]},
"attendees": attendees,
"conferenceData": {"createRequest": {"requestId": f"{uuid4().hex}",
"conferenceSolutionKey": {"type": "hangoutsMeet"}}},
"reminders": {"useDefault": True}
}
event = service.events().insert(calendarId="primary", sendNotifications=True, body=event, conferenceDataVersion=1).execute()
return event
if __name__ == "__main__":
plan = EventPlanner({"test_guest": "test.guest#gmail.com"}, {"start": "2020-07-31T16:00:00",
"end": "2020-07-31T16:30:00"})
print(plan.event_states)
I suspect that the problem is with where I have passed conferenceDataVersion but the docs are not exactly clear about where it has to be passed other than that it must be passed. I also tried putting it in the body of the event or in createRequest. It always creates the event but not the conference. Unfortunately, I could not find anything about this online anywhere. Maybe I'm actually that bad at searching, but I have been testing different things and searching for a solution for several days! If anyone knows what I am missing, I will truly appreciate their assistance.
Thanks to #Tanaike, I found what was the problem. The token which is generated the first time the API is authenticated is very specific. The problem I was having turned out to be just with that. As soon as I removed the token and had it get generated again, the problem was solved. That being said, I have no idea why the problem appeared in the first place. I will update the response if I find the reason behind it. But for now, if you are having the same problem, just remove the token and regenerate it.
With this code we can create the conference (Google meet link) for me it works
"conferenceData": {
"createRequest": {
"requestId": "SecureRandom.uuid"
}
}

Google calendar API 400 error when creating event

I am trying to create an event using Google Calendar API in Python 3 using the documentations provided here:
https://developers.google.com/calendar/quickstart/python
https://developers.google.com/calendar/v3/reference/events#conferenceData
https://developers.google.com/calendar/create-events
However, I keep getting error 400 bad request and I have no idea why. My code is as follows:
from pathlib import Path
from pickle import load
from pickle import dump
from google.auth.transport.requests import Request
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build
from uuid import uuid4
from typing import Dict, List
from oauth2client import file, client, tools
class EventPlanner:
"""
pass
"""
def __init__(self, guests: Dict[str, str], schedule: Dict[str, str]):
guests = [{"email": email} for email in guests.values()]
service = self._authorize()
self.event_states = self._plan_event(guests, schedule, service)
#staticmethod
def _authorize():
scopes = ["https://www.googleapis.com/auth/calendar"]
credentials = None
token_file = Path("./calendar_creds/token.pickle")
if token_file.exists():
with open(token_file, "rb") as token:
credentials = load(token)
if not credentials or not credentials.valid:
if credentials and credentials.expired and credentials.refresh_token:
credentials.refresh(Request())
else:
flow = InstalledAppFlow.from_client_secrets_file('calendar_creds/credentials.json', scopes)
credentials = flow.run_local_server(port=0)
with open(token_file, "wb") as token:
dump(credentials, token)
calendar_service = build("calendar", "v3", credentials=credentials)
return calendar_service
#staticmethod
def _plan_event(attendees: List[Dict[str, str]], event_time, service: build):
event = {"summary": "test meeting",
"start": {"dateTime": event_time["start"]},
"end": {"dateTime": event_time["end"]},
"attendees": attendees,
"conferenceData": {"createRequest": {"requestId": f"{uuid4().hex}",
"conferenceSolutionKey": {"type": "hangoutsMeet"}}},
"reminders": {"useDefault": True}
}
event = service.events().insert(calendarId="primary", sendNotifications=True, body=event).execute()
return event
if __name__ == "__main__":
plan = EventPlanner({"test_guest": "test.guest#gmail.com"}, {"start": "2020-07-29T20:00:00-4:00",
"end": "2020-07-29T20:30:00-4:00"})
print(plan.event_states)
The first time authentication was done successfully. I also tried the different ways mentioned in the docs but non work. Does anyone know what I am doing wrong? Thanks.
I think that the reason of your issue is as follows.
Modification points:
At RFC3339, for dateTime of start, please modify 2020-07-29T20:00:00-4:00 to 2020-07-29T20:00:00-04:00. Also please modify this for dateTime of end.
Please add the time zone.
Modified script:
plan = EventPlanner({"test_guest": "test.guest#gmail.com"}, {"start": "2020-07-29T20:00:00-04:00", "end": "2020-07-29T20:30:00-04:00"})
And
time_zone = str(get_localzone())
event = {"summary": "test meeting",
"start": {"dateTime": event_time["start"], "timeZone": time_zone},
"end": {"dateTime": event_time["end"], "timeZone": time_zone},
"attendees": attendees,
"conferenceData": {"createRequest": {"requestId": f"{uuid4().hex}",
"conferenceSolutionKey": {"type": "hangoutsMeet"}}},
"reminders": {"useDefault": True}
}
Note:
I'm not sure about your time zone. So I used get_localzone() for the modified script. In this case, please also use from tzlocal import get_localzone. If you want to change the time zone, please modify above script.
This modified script supposes that you have already been able to create new event to the Google Calendar using Calendar API. Please be careful this.
References:
Events: insert
RFC3339
For me what worked was to copy the URI that is in the redirect_uri_mismatch window and past it in the redirect URI in the credentials of my project in the google console.

Modifying a private calender with Python backend using google functions

so I have the following problem:
I want to manipulate a calendar(my private google calendar) using GoogleFunctions with python backend.I have now followed an code example (which inserts an event) and in the google console it is also shown that a call has taken place. Now I'm just wondering which calendar I'm modifying?
The problem for me is, as soon as I enter the calendarId of my private calendar, the function runs on an error. But actually the service user has all permissions. If I understand it correctly, then I can manipulate all calendars within the organization with the Service user?
So that's my code. It works so far. Now I only ask myself, can I see the calendar I am modifying somewhere?
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
from google.oauth2 import service_account
SUBJECT = 's.........415.iam.gserviceaccount.com'
def main():
# create credntials
credentials = service_account.Credentials.from_service_account_file(SERVICE_ACCOUNT_FILE, scopes=SCOPES)
delegated_credentials = credentials.with_subject(SUBJECT)
service = build('calendar', 'v3', credentials=delegated_credentials)
d = datetime.utcnow().date()
tomorrow = datetime(d.year, d.month, d.day, 10)
start = tomorrow.isoformat()
end = (tomorrow).isoformat()
body={"summary": 'Hello there, Automating calendar',
"description": 'Google calendar with python',
"start": {"dateTime": start, "timeZone": 'Asia/Karachi'},
"end": {"dateTime": end, "timeZone": 'Asia/Karachi'},
}
event = service.events().insert(calendarId=SUBJECT,body=body).execute()
if __name__ == "__main__":
main()

why flask graphene return wrong id?

when i print the id before returning, the code print the right value ( same with id in mongo ).
but the client received a deferent id.
my query code :
def resolve_account(root, info, **kwargs):
email = kwargs.get('email', None)
password = kwargs.get('password', None)
accounts = AccountModel.objects(email=email, password=password)
if accounts.first() is None:
return ResponseMessageField(is_success=False, message="Not found")
print(accounts[0].id)
return AccountResults(accounts=[AccountField(id=account.id,
name=account.name)
for account in accounts])
console printed : `5e5f28a41e92b7cdb5cf30ea'
but my client received :
{
"data": {
"accountLogin": {
"accounts": [
{
"name": "test1",
"id": "QWNjb3VudEZpZWxkOjVlNWYyOGE0MWU5MmI3Y2RiNWNmMzBlYQ=="
}
]
}
}
}
python 3.6.9
mongoengine 0.1.9
graphene 2.1.8
graphene_mongo 0.1.1
flask 1.1.1
This is acutally an adavantage of graphene-django, if you're using auto-increment ID's.
Anyway it encodes them using base64 encoding, to get the real value, you can do
this in vanilla JS:
>> atob('QWNjb3VudEZpZWxkOjVlNWYyOGE0MWU5MmI3Y2RiNWNmMzBlYQ==')
>> "AccountField:5e5f28a41e92b7cdb5cf30ea"
So if you want to mutate something, and you have the ID, which is not bas64 encoded, what you'll have to do is:
>> btoa("AccountField:5e5f28a41e92b7cdb5cf30ea")
>> "QWNjb3VudEZpZWxkOjVlNWYyOGE0MWU5MmI3Y2RiNWNmMzBlYQ=="
In python, graphene provides an import, to_global_id and from_global_id to convert to and fro b/w base64 encoded values and the real IDs.

chatterbot.logic.SpecificResponseAdapter is not working

I want to develop my own custom chatbot but I get some issue during the development, I want to use Specific Response Adapter in chatterbot. There is a sample of code.
from chatterbot.trainers import ListTrainer
from chatterbot import ChatBot
from chatterbot.trainers import ChatterBotCorpusTrainer
bot = ChatBot('Mybot',
storage_adapter='chatterbot.storage.SQLStorageAdapter',
logic_adapters=[{'import_path': 'chatterbot.logic.SpecificResponseAdapter',
'input_text': 'Help me!',
'output_text': 'Ok'
}]) # Crate Chatbot
trainer = ListTrainer(bot)
text = open('/content/drive/My Drive/Chatbot/Data/data.txt').readlines()
trainer.train(text)
while True:
request = input("Your: ")
response = bot.get_response(request)
print("bot:",response)
This is the output:
Your: Help me!
bot: I am sorry, but I do not understand.
Your: 'Help me!'
bot: I am sorry, but I do not understand.
please help me to solve this problem

Resources