Dialogflow v2 Beta 1 Update Intent with Python - dialogflow-es

I am lost.
I have a currently existing Intent in my project, and I am trying to update ALL fields programmatically because that is what my project requires.
I read this documentation and checked this source file on GitHub, and I think the reason I am getting an error is because I don't understand this part of the source:
Args:
intent (Union[dict, ~google.cloud.dialogflow_v2beta1.types.Intent]): Required. The intent
to update.
Format: projects/<Project ID>/agent/intents/<Intent ID>.
If a dict is provided, it must be of the same form as the protobuf
message :class:~google.cloud.dialogflow_v2beta1.types.Intent
(Line 484 for reference)
The platform works great I just don't know what I am missing here..
My code
from constants import *
from google.oauth2 import service_account
import dialogflow_v2beta1
cred = service_account.Credentials.from_service_account_file(AUTH_JSON)
client = dialogflow_v2beta1.IntentsClient(credentials=cred)
params = dialogflow_v2beta1.types.Intent.Parameter(name='test', display_name='test', value='test', is_list=True)
t = dialogflow_v2beta1.types.Intent.Message.Text(text='TEST TEXT')
m = dialogflow_v2beta1.types.Intent.Message(text=t)
p = dialogflow_v2beta1.types.Intent.TrainingPhrase.Part(text='test',entity_type='#test_type', alias='test_alias', user_defined=True)
t = dialogflow_v2beta1.types.Intent.TrainingPhrase(name='test',type=2, parts=[p])
modified_intent = dialogflow_v2beta1.types.Intent(
display_name='test',
messages=[m],
webhook_state=1,
is_fallback=False,
ml_disabled=False,
input_context_names=PROJECT_DIR+'agent/sessions/-/contexts/' + 'TEST_CONTEXT',
events='TESTING EVENT',
training_phrases=[t],
action='TESTING ACTION',
reset_contexts=False,
parameters=[params]
)
name = client.intent_path(PROJECT_NAME, '7b8f2105-53d4-4724-8d4c-0170b8db7028')
intent = client.get_intent(name)
client.update_intent(intent=modified_intent, language_code=LANGUAGE_CODE, intent_view=0)
Full error message
Traceback (most recent call last):
File "/anaconda/envs/data/lib/python3.6/site-packages/google/api_core/grpc_helpers.py", line 57, in error_remapped_callable
return callable_(*args, **kwargs)
File "/anaconda/envs/data/lib/python3.6/site-packages/grpc/_channel.py", line 550, in __call__
return _end_unary_response_blocking(state, call, False, None)
File "/anaconda/envs/data/lib/python3.6/site-packages/grpc/_channel.py", line 467, in _end_unary_response_blocking
raise _Rendezvous(state, None, None, deadline)
grpc._channel._Rendezvous: <_Rendezvous of RPC that terminated with:
status = StatusCode.INVALID_ARGUMENT
details = "Resource name '' does not match 'projects/*/agent/intents/*'."
debug_error_string = "{"created":"#1552461629.958860000","description":"Error received from peer","file":"src/core/lib/surface/call.cc","file_line":1036,"grpc_message":"Resource name '' does not match 'projects/*/agent/intents/*'.","grpc_status":3}"
>
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "test.py", line 26, in <module>
client.update_intent(intent=modified_intent, language_code=LANGUAGE_CODE, intent_view=0)
File "/anaconda/envs/data/lib/python3.6/site-packages/dialogflow_v2beta1/gapic/intents_client.py", line 535, in update_intent
request, retry=retry, timeout=timeout, metadata=metadata)
File "/anaconda/envs/data/lib/python3.6/site-packages/google/api_core/gapic_v1/method.py", line 143, in __call__
return wrapped_func(*args, **kwargs)
File "/anaconda/envs/data/lib/python3.6/site-packages/google/api_core/retry.py", line 270, in retry_wrapped_func
on_error=on_error,
File "/anaconda/envs/data/lib/python3.6/site-packages/google/api_core/retry.py", line 179, in retry_target
return target()
File "/anaconda/envs/data/lib/python3.6/site-packages/google/api_core/timeout.py", line 214, in func_with_timeout
return func(*args, **kwargs)
File "/anaconda/envs/data/lib/python3.6/site-packages/google/api_core/grpc_helpers.py", line 59, in error_remapped_callable
six.raise_from(exceptions.from_grpc_error(exc), exc)
File "<string>", line 3, in raise_from
google.api_core.exceptions.InvalidArgument: 400 Resource name '' does not match 'projects/*/agent/intents/*'.

You are able to get the intent which you want to modify correctly by using
name = client.intent_path(PROJECT_NAME, your_intent_id)
You will get complete definition of your intent.
Then you need to change the values of this intent by accessing them and assigning your values.
After that, you need to pass the same intent in your update_intent() function.
It is also advised to use update_mask to avoid changing any other field or setting rest of the fields None.
Here is an example of updating intent display_name from greet to hello:
client = dialogflow.IntentsClient()
intent_name = client.intent_path(project_id, intent_id)
intent = client.get_intent(intent_name, intent_view=dialogflow.enums.IntentView.INTENT_VIEW_FULL)
intent.display_name = 'hello'
update_mask = field_mask_pb2.FieldMask(paths=['display_name'])
print(response)
You will need ope extra import as well in your code:
from google.protobuf import field_mask_pb2
This way, intent's display_name will be changed.
You can do same for the rest of your properties as well. Just remember to pass the value which the property is expecting by following this documentation and you can take help from this issue as well.
Hope it helps.

Related

Error in trying to create a topic subscription in Google PubSub python

I am trying to create a subscription to a topic using Google's pubsub_v1 library in python. I have successfully created a topic using the library (I can see it in the cloud console after creation). However I am having an issue trying to create a subscription. I tried to solution given in this question to no avail. Here is my subscription code:
from google.cloud import pubsub_v1 as pubsub
topic_name = 'logs'
sub_name = 'logs-consumer'
project_name = 'my-project' # valid project name
subscriber = pubsub.SubscriberClient()
topic_path = subscriber.topic_path(project_name, topic_name)
subscription_path = subscriber.subscription_path(project_name, sub_name)
# Wrap the subscriber in a 'with' block to automatically call close() to
# close the underlying gRPC channel when done.
with subscriber:
subscription = subscriber.create_subscription(
request={"name": subscription_path, "topic": topic_path}
)
Whenever I run this code, I get the following error:
Traceback (most recent call last):
File "/Users/zacharymcgrath/Library/Python/3.7/lib/python/site-packages/google/api_core/grpc_helpers.py", line 57, in error_remapped_callable
return callable_(*args, **kwargs)
File "/Users/zacharymcgrath/Library/Python/3.7/lib/python/site-packages/grpc/_channel.py", line 826, in __call__
return _end_unary_response_blocking(state, call, False, None)
File "/Users/zacharymcgrath/Library/Python/3.7/lib/python/site-packages/grpc/_channel.py", line 729, in _end_unary_response_blocking
raise _InactiveRpcError(state)
grpc._channel._InactiveRpcError: <_InactiveRpcError of RPC that terminated with:
status = StatusCode.INVALID_ARGUMENT
details = "Project 'project:gcp-python-291817' not found or deleted."
debug_error_string = "{"created":"#1607133732.705528000","description":"Error received from peer ipv6:[2607:f8b0:400f:801::200a]:443","file":"src/core/lib/surface/call.cc","file_line":1062,"grpc_message":"Project 'project:gcp-python-291817' not found or deleted.","grpc_status":3}"
>
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "logger_consumer_GCP.py", line 28, in <module>
request={"name": subscription_path, "topic": topic_path}
File "/Users/zacharymcgrath/Library/Python/3.7/lib/python/site-packages/google/cloud/pubsub_v1/_gapic.py", line 40, in <lambda>
fx = lambda self, *a, **kw: wrapped_fx(self.api, *a, **kw) # noqa
File "/Users/zacharymcgrath/Library/Python/3.7/lib/python/site-packages/google/pubsub_v1/services/subscriber/client.py", line 526, in create_subscription
response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,)
File "/Users/zacharymcgrath/Library/Python/3.7/lib/python/site-packages/google/api_core/gapic_v1/method.py", line 145, in __call__
return wrapped_func(*args, **kwargs)
File "/Users/zacharymcgrath/Library/Python/3.7/lib/python/site-packages/google/api_core/retry.py", line 286, in retry_wrapped_func
on_error=on_error,
File "/Users/zacharymcgrath/Library/Python/3.7/lib/python/site-packages/google/api_core/retry.py", line 184, in retry_target
return target()
File "/Users/zacharymcgrath/Library/Python/3.7/lib/python/site-packages/google/api_core/grpc_helpers.py", line 59, in error_remapped_callable
six.raise_from(exceptions.from_grpc_error(exc), exc)
File "<string>", line 3, in raise_from
google.api_core.exceptions.InvalidArgument: 400 Project 'project:gcp-python-291817' not found or deleted.
I thought it might be that my project gcloud variable had somehow changed and the library uses environment variables, but I double checked and it was correct. I'm not really sure what I'm doing thats different than the question referred to above. Thanks.
Update
Some helpful information from the comments:
gcp-python-291817 is not the name of the project
the project name is in a config file that both the publisher and the subscriber read from. The publisher did not have any problems when reading the project name from the file and publishing a message
I had a ssh configuration for a VM instance within this project named gcp-python, but was removed a while ago
clearing the gcloud cache and gsutils cache has not fixed the problem either
I found the issue. I re-ran
gcloud auth application-default login
and made sure that GOOGLE_APPLICATION_CREDENTIALS was pointed to the new credentials json file and it worked. I must have messed up the credentials file at some point. Thanks for the help!

cannot unpack non-iterable bool object(when trying to filter result for user registered in auth>User module)

I’m creating a django based web app and I have used Auth > User model (without any customization except password hiding) and for user detail I have created another model ChangeShift. and model based form.
Case 1: When I am using alluser = ShiftChange.objects.all() I'm able to see all the data available in ShiftChange model.
Case 2: Now I want that when user is logging, he should be able to see data related to his name and I'm using this:
def retrieve_view(request):
# alluser = ShiftChange.objects.all()
alluser = ShiftChange.objects.filter(ShiftChange.ldap_id == request.user.username)
return render(request, 'apple/shift2.html', {'alluser': alluser})
For this code I am getting error:
cannot unpack non-iterable bool object
Error Traceback:
[21/Sep/2020 11:13:18] "GET /static/css/auth.css HTTP/1.1" 404 1662
Internal Server Error: /alldata/
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner
response = get_response(request)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/core/handlers/base.py", line 179, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Users/shaileshyadaav/djangoshaileshdurga/mapsIT/apple/views.py", line 53, in retrieve_view
alluser = ShiftChange.objects.filter(ShiftChange.ldap_id == request.user.username)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/db/models/manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/db/models/query.py", line 942, in filter
return self._filter_or_exclude(False, *args, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/db/models/query.py", line 962, in _filter_or_exclude
clone._filter_or_exclude_inplace(negate, *args, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/db/models/query.py", line 969, in _filter_or_exclude_inplace
self._query.add_q(Q(*args, **kwargs))
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/db/models/sql/query.py", line 1358, in add_q
clause, _ = self._add_q(q_object, self.used_aliases)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/db/models/sql/query.py", line 1377, in _add_q
child_clause, needed_inner = self.build_filter(
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/db/models/sql/query.py", line 1255, in build_filter
arg, value = filter_expr
TypeError: cannot unpack non-iterable bool object
The line:
alluser = ShiftChange.objects.filter(
ShiftChange.ldap_id == request.user.username)
is the error. The part ShiftChange.ldap_id == request.user.username is an expression that evaluates to True or False, and then your code becomes equivalent to
alluser = ShiftChange.objects.filter(True)
or
alluser = ShiftChange.objects.filter(False)
and that is probably not what you want.
Try using a single = sign and use a valid left side kwarg (because ShiftChange.ldap_id with the dot in the middle is not valid here).
So your code may end up similar to this:
alluser = ShiftChange.objects.filter(ldap_id=request.user.username)

exchangelib get task from task queryset MIME conversion is not supported for this item

I am trying to access an object
through a queryset created with exchangelib however I get an error MIME CONVERSION IS NOT SUPPORTED FOR THIS ITEM, I don't know what it means. I have tried the same code with calendar items and I have no problem whatsoever. thanks
from exchangelib import Account, Credentials, DELEGATE
credentials = Credentials(username='BUREAU\\pepe', password='pepe')
pepe_account = Account(
primary_smtp_address='pepe#office.com',
credentials=credentials,
autodiscover=True,
access_type=DELEGATE)
tasks = pepe_account.tasks.filter()
print(tasks) -- Works
for task in tasks:
print(task)
The iteration fails, instead of print(task) I also tried pass and I get the same message.
Traceback (most recent call last):
File "test.py", line 13, in <module>
for task in tasks:
File "/home/pepe/.local/lib/python3.5/site-packages/exchangelib/queryset.py", line 197, in __iter__
for val in result_formatter(self._query()):
File "/home/pepe/.local/lib/python3.5/site-packages/exchangelib/queryset.py", line 272, in _as_items
for i in iterable:
File "/home/pepe/.local/lib/python3.5/site-packages/exchangelib/account.py", line 393, in fetch
for i in GetItem(account=self).call(items=ids, additional_fields=additional_fields, shape=IdOnly):
File "/home/pepe/.local/lib/python3.5/site-packages/exchangelib/services.py", line 456, in _pool_requests
for elem in elems:
File "/home/pepe/.local/lib/python3.5/site-packages/exchangelib/services.py", line 283, in _get_elements_in_response
container_or_exc = self._get_element_container(message=msg, name=self.element_container_name)
File "/home/pepe/.local/lib/python3.5/site-packages/exchangelib/services.py", line 256, in _get_element_container
self._raise_errors(code=response_code, text=msg_text, msg_xml=msg_xml)
File "/home/pepe/.local/lib/python3.5/site-packages/exchangelib/services.py", line 273, in _raise_errors
raise vars(errors)[code](text)
exchangelib.errors.ErrorUnsupportedMimeConversion: MIME conversion is not supported for this item type.

"Type error: unhashable type: 'list'" in Praw bot

Running the following code for a Reddit bot gives the error message listed below the code, can anyone help me resolve this error? I've tried several things and cant find the answer on Google. Thanks in advance.
D_035
#Bot
import praw
import time
import re
import os
r = praw.Reddit(user_agent = "Bot")
r.login()
cache = []
def run_bot():
subreddit = r.get_subreddit("broap")
comments = subreddit.get_comments(limit=25)
for comment in comments:
comment_text = comment.body.lower()
author = comment.author
url = comment.link_id
msg = "User {} has tagged you in a post!".format(author)
words = filter( lambda x:x.startswith('//'), comment_text.split())
user = words[2:]
if comment.id not in cache and words:
r.user.send_message(user ,msg)
cache.add(comment.id)
while True:
run_bot()
time.sleep(5)
Error message it gives after running:
raceback (most recent call last):
File "Test.py", line 32, in <module>
run_bot()
File "Test.py", line 25, in run_bot
r.user.send_message(user ,msg)
File "/usr/local/lib/python2.7/dist-packages/praw/decorators.py", line 60, in wrapped
return function(self.reddit_session, self, *args, **kwargs)
File "<decorator-gen-144>", line 2, in send_message
File "/usr/local/lib/python2.7/dist-packages/praw/decorators.py", line 271, in wrap
return function(*args, **kwargs)
File "<decorator-gen-143>", line 2, in send_message
File "/usr/local/lib/python2.7/dist-packages/praw/decorators.py", line 177, in require_captcha
return function(*args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/praw/__init__.py", line 2555, in send_message
retry_on_error=False)
File "<decorator-gen-8>", line 2, in request_json
File "/usr/local/lib/python2.7/dist-packages/praw/decorators.py", line 116, in raise_api_exceptions
return_value = function(*args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/praw/__init__.py", line 620, in request_json
retry_on_error=retry_on_error)
File "/usr/local/lib/python2.7/dist-packages/praw/__init__.py", line 451, in _request
response = handle_redirect()
File "/usr/local/lib/python2.7/dist-packages/praw/__init__.py", line 432, in handle_redirect
verify=self.http.validate_certs, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/praw/handlers.py", line 137, in wrapped
if _cache_key in cls.cache:
TypeError: unhashable type: 'list'
r.user.send_message() doesn't expect a list as first argument. From the documentation, it looks like it expects a string (something like a user name).
The way you build user:
words = filter( lambda x:x.startswith('//'), comment_text.split())
user = words[2:]
makes it a list (filter returns an iterable, and then [2:] returns a "portion" of this iterable; the 'source' being a list (output of split()), it returns a list), hence the error.
In order to correct your function, you have to change the way you build user. Don't know how to help you more since I don't know what exactly you want to do.
EDIT:
Now you told a little bit more, I would to it this way:
def run_bot():
subreddit = r.get_subreddit("broap")
comments = subreddit.get_comments(limit=25)
for comment in comments:
comment_text = comment.body.lower()
author = comment.author
url = comment.link_id
words = filter( lambda x:x.startswith('//'), comment_text.split())
users_list = [ w[2:] for w in words ]
for u in users_list:
if comment.id not in cache and words:
r.user.send_message(u,
"User {a} has tagged you in a post!".format(a=author))
cache.append(comment.id)
This should deal with any //username found in the comment. (How are you sure the username does exist? Isn't it a problem? (for instance if I write "A dummy comment just to try //invalid_username", what happens?))
Something else: this is unrelated to your question directly, but this line:
if comment.id not in cache and words:
may not do what you want (will be True only if comment.id is not in cache AND if words is not an empty list, it won't check if comment.id belongs to words).

Strange deform/colander behaviour "string indices must be integers"

So I have the following working code, that I have been using for the past few months
class UserSchema(colander.MappingSchema):
dob = colander.SchemaNode(
colander.Date(),
title='Date of birth:')
if 'submit' in request.POST:
controls = request.POST.items()
try:
appstruct = myform.validate(controls)
except ValidationFailure, e:
return {'form':e.render(), 'values': False}
Now this is a basic date picker, as shown here:
http://deform2demo.repoze.org/dateinput/
But all of a sudden, when using this widget I get the error:
Traceback (most recent call last):
File "/home/luke/virts/pyramid-1.4.5/lib/python2.7/site-packages/pyramid_debugtoolbar-1.0.9-py2.7.egg/pyramid_debugtoolbar/panels/performance.py", line 55, in resource_timer_handler
result = handler(request)
File "/home/luke/virts/pyramid-1.4.5/lib/python2.7/site-packages/pyramid/tweens.py", line 21, in excview_tween
response = handler(request)
File "/home/luke/virts/pyramid-1.4.5/lib/python2.7/site-packages/pyramid_tm-0.7-py2.7.egg/pyramid_tm/__init__.py", line 82, in tm_tween
reraise(*exc_info)
File "/home/luke/virts/pyramid-1.4.5/lib/python2.7/site-packages/pyramid_tm-0.7-py2.7.egg/pyramid_tm/__init__.py", line 63, in tm_tween
response = handler(request)
File "/home/luke/virts/pyramid-1.4.5/lib/python2.7/site-packages/pyramid/router.py", line 161, in handle_request
response = view_callable(context, request)
File "/home/luke/virts/pyramid-1.4.5/lib/python2.7/site-packages/pyramid/config/views.py", line 347, in rendered_view
result = view(context, request)
File "/home/luke/virts/pyramid-1.4.5/lib/python2.7/site-packages/pyramid/config/views.py", line 493, in _requestonly_view
response = view(request)
File "/home/luke/pyramids/getwork2day.co.uk/getwork2day/views/signup.py", line 244, in user_signup
appstruct = myform.validate(controls)
File "/home/luke/virts/pyramid-1.4.5/lib/python2.7/site-packages/deform-2.0a2-py2.7.egg/deform/field.py", line 636, in validate
return self.validate_pstruct(pstruct)
File "/home/luke/virts/pyramid-1.4.5/lib/python2.7/site-packages/deform-2.0a2-py2.7.egg/deform/field.py", line 661, in validate_pstruct
cstruct = self.deserialize(pstruct)
File "/home/luke/virts/pyramid-1.4.5/lib/python2.7/site-packages/deform-2.0a2-py2.7.egg/deform/field.py", line 512, in deserialize
return self.widget.deserialize(self, pstruct)
File "/home/luke/virts/pyramid-1.4.5/lib/python2.7/site-packages/deform-2.0a2-py2.7.egg/deform/widget.py", line 1274, in deserialize
result[name] = subfield.deserialize(subval)
File "/home/luke/virts/pyramid-1.4.5/lib/python2.7/site-packages/deform-2.0a2-py2.7.egg/deform/field.py", line 512, in deserialize
return self.widget.deserialize(self, pstruct)
File "/home/luke/virts/pyramid-1.4.5/lib/python2.7/site-packages/deform-2.0a2-py2.7.egg/deform/widget.py", line 551, in deserialize
date = pstruct['date'].strip()
TypeError: string indices must be integers
At least dump current form controls to logging and post it here. Try to be more verbose & clear with your code examples and do not mix up colander schema code and pyramid view code.
if 'submit' in request.POST:
controls = request.POST.items()
try:
appstruct = myform.validate(controls)
except ValidationFailure, e:
log.debug('form validation fails for %r' % controls)
return {'form':e.render(), 'values': False}

Resources