How to detect the end_interaction signal using the dialogflow_cx python library? - dialogflow-cx

I am using the DialogFlow CX python library for an agent integration. Once I send a request through detect_intent, I want to be able to check in the response for a flag that determines if the interaction with the agent has ended.
For this, I found a property within the ResponseMessage data type response called end_interaction. I tested this with one of my agents, and effectively once the interaction ends, I can see the end_interaction within the array of response messages:
# inspecting query_result.response_messages
[
text {
text: "Goodbye."
},
end_interaction {
}
]
Now, the problem is that I want to trigger some actions whenever we receive the signal, but since the end_interaction field is being sent empty whenever I try to check it returns me False:
# Both response messages from the example above return False under a bool
bool(query_result.response_messages[0].end_interaction) == False # text message response
bool(query_result.response_messages[1].end_interaction) == False # end_interaction signal
I have tried many things, such as checking with isinstance and hasattr, but they return True for all scenarios since the ResponseMessage data type always has an end_interaction attr.
Any help for finding how to detect and check for this signal is highly appreciated! Thanks!

To detect and check for the end_interaction field, you can use the following in your detect_intent:
any("end_interaction" in d for d in response.query_result.response_messages)
Please note that this will return True if the end_interaction field is found in the response_messages list and False if not. You can use this to determine if the interaction with the agent has ended.
Here is a python sample code of the detect_intent with the end_interaction field for your reference:
def detect_intent_texts(agent, session_id, texts, language_code):
session_path = f'{agent}/sessions/{session_id}'
print(f"Session path: {session_path}\n")
client_options = None
agent_components = AgentsClient.parse_agent_path(agent)
location_id = agent_components["location"]
if location_id != "global":
api_endpoint = f"{location_id}-dialogflow.googleapis.com:443"
print(f"API Endpoint: {api_endpoint}\n")
client_options = {"api_endpoint": api_endpoint}
session_client = SessionsClient(client_options=client_options)
for text in texts:
text_input = session.TextInput(text=text)
query_input = session.QueryInput(text=text_input, language_code=language_code)
request = session.DetectIntentRequest(
session=session_path, query_input=query_input
)
response = session_client.detect_intent(request=request)
print("=" * 20)
print(f"Query text: {response.query_result.text}")
response_messages = [
" ".join(msg.text.text) for msg in response.query_result.response_messages
]
print(f"Response Messages:\n {response.query_result.response_messages}")
print(f'End of interaction: {any("end_interaction" in d for d in response.query_result.response_messages)}')
Here is the result:

Related

How to rig a bot's command to only a certain user

I've been making this pp size machine, which is somewhat like dank memer's one
#client.command()
async def pp(ctx,member : discord.Member):
size=random.randint(1,10)
message = "8"
for x in range (size):
message= message + "="
if x == size-1:
message = message + "D"
if member == "PROTATO#6826":
message = "8D"
ppsize = discord.Embed(color=discord.Colour.orange(), title=f"PP size",description=f"""{member}'s penis
{message} """)
await ctx.send(embed = ppsize)
But i want to rig the command for a certain user to only show "8D" instead of the random lengths.
But no matter what it is the
if member == "PROTATO#6826":
message = "8D"
code doesnt run or gets over looked?
Can someone help me out with this?
You can check if the member mentioned has the same id as a specific user. You can either enable developer mode on discord, or you can print the member.id at the very beginning. Do view a code example below.
#client.command()
async def pp(ctx, member: discord.Member):
print(member.id) # this would print a user's unique id
message = "Hey!"
if member.id == 394506589350002688: # replace this id with what was printed at the start
message = "Hello!"
await ctx.send(message)
Similar Questions:
How to check if message was sent by certain user? - SO
How do I detect if the message is sent by a specific user id? - SO

How to make a bot respond to a certain message sent after the command?

I am trying to make a bot that simulates a turn based battle, but i have no idea how to make a bot respond after i've sent the command. what i have tried for now is:
async def battle(ctx):
keyword = (1,2,3)
enemy1 = ('Skeleton', 'Goblin', 'Bandit',)
enemy2 = ('Knight', 'Barbarian', 'Archer')
enemy3 = ('Elf Mage', 'Dwarf Warrior', 'Orc Brute')
enemy1hp = 50
enemy1dmg = 25
enemy2hp = 75
enemy2dmg = 35
enemy3hp = 100
enemy3dmg = 25
playerhp = 150
playerdmg = random.randint(10, 40)
await ctx.send('Pick a number between 1 and 3')
enemypicked = ctx.content.lower()
for keyword in enemypicked:
if keyword == '1':
opponent1 = random.choice(enemy1)
await ctx.send(f'{opponent1}, {enemy1hp}HP')
What i am trying to do is make the user choose a number and dependant on a number the bot will choose which enemy will appear,but i get the following error:
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Context' object has no attribute 'content'
and i am out of ideas on how to make it work. Any help is highly appreciated.
To fix your Exception, look into ctx.message.
You can then use ctx.message.content to get the content of the message.
Then to wait_for a response, look into https://discordpy.readthedocs.io/en/latest/ext/commands/api.html?highlight=wait_for#discord.ext.commands.Bot.wait_for

How can I retrieve the "Description" field of inspect.exe in my pywinauto based automation script?

I have the following SysTreeView32 element from which I would like to retrieve the "Description" field:
In my pywinauto script (based on win32 backend), I can retrieve pretty easily the TreeViewWrapper element by looking for the class type and eventually looking at the items text, but some information that I need is only available in the Description field of this element.
I was not able to find a way to retrieve this information.
I tried in UIA mode as well:
But in this case, it does not even appear in the information.
So I tried using the TreeItemWrapper element with the UIA backend in pywinauto, but I could not find the appropriate description not even in the UIAElementInfo. Although something looked pretty similar in the following line:
impl = uia_defs.get_elem_interface(elem, "LegacyIAccessible").
When I call the legacy_properties of the uia_controls.TreeItemWrapper, I get:
{'ChildId': 0,
'DefaultAction': '',
'Description': '',
'Help': '',
'KeyboardShortcut': '',
'Name': 'Execute multiple tasks(MultiTask_ImportSysD)',
'Role': 36,
'State': 3145730,
'Value': ''}
And in there, the Description is empty.
I'm guessing that property comes from IAccessible::get_accDescription.
MSDN says that property is deprecated but if you still want to use it, call AccessibleObjectFromWindow to get a IAccessible for a window.
Finally, I could not find this possibility through the pywinauto exposed API.
Although pywniauto does expose the Description property through the legacy_properties of the uia_controls.TreeItemWrapper instance, but it returns an empty string. This correlates with the note in teh Windows SDK documentation that states:
Note The Description property is often used incorrectly and is not supported by Microsoft UI Automation. Microsoft Active Accessibility server developers should not use this property. If more information is needed for accessibility and automation scenarios, use the properties supported by UI Automation elements and control patterns.
In the end, I finally developed a small piece of code to search for the element that I need the description of and I could retrieve the Description from there. Here is the code:
# for OleAcc access
import ctypes
import comtypes, comtypes.automation, comtypes.client
comtypes.client.GetModule('oleacc.dll')
def accDescription(iaccessible, cid):
objChildId = comtypes.automation.VARIANT()
objChildId.vt = comtypes.automation.VT_I4
objChildId.value = cid
objDescription = comtypes.automation.BSTR()
iaccessible._IAccessible__com__get_accDescription(objChildId, ctypes.byref(objDescription))
return objDescription.value
def accRole(iaccessible, cid):
objChildId = comtypes.automation.VARIANT()
objChildId.vt = comtypes.automation.VT_I4
objChildId.value = cid
objRole = comtypes.automation.VARIANT()
objRole.vt = comtypes.automation.VT_BSTR
iaccessible._IAccessible__com__get_accRole(objChildId, objRole)
return AccRoleNameMap[objRole.value]
def accState(iaccessible, cid):
'''Get Element State'''
objChildId = comtypes.automation.VARIANT()
objChildId.vt = comtypes.automation.VT_I4
objChildId.value = cid
objState = comtypes.automation.VARIANT()
iaccessible._IAccessible__com__get_accState(objChildId, ctypes.byref(objState))
return objState.value
def accName(iaccessible, cid):
'''Get Element Name'''
objChildId = comtypes.automation.VARIANT()
objChildId.vt = comtypes.automation.VT_I4
objChildId.value = cid
objName = comtypes.automation.BSTR()
iaccessible._IAccessible__com__get_accName(objChildId, ctypes.byref(objName))
return objName.value
def accDescendants(iaccessible):
"""Iterate all desencendants of an object iaccessible, including the current one.
Arguments:
iaccessible -- the IAccessible element to start from
Yields:
(IAcessible instance, Child id)
"""
yield (iaccessible, 0)
objAccChildArray = (comtypes.automation.VARIANT * iaccessible.accChildCount)()
objAccChildCount = ctypes.c_long()
ctypes.oledll.oleacc.AccessibleChildren(iaccessible, 0, iaccessible.accChildCount, objAccChildArray, ctypes.byref(objAccChildCount))
for i in range(objAccChildCount.value):
objAccChild = objAccChildArray[i]
if objAccChild.vt == comtypes.automation.VT_DISPATCH:
# query the sub element accessible interface
newiaccessible = objAccChild.value.QueryInterface(comtypes.gen.Accessibility.IAccessible)
# then loop over its descendants
for (__i, __c) in accDescendants(newiaccessible):
yield (__i, __c)
else: #if objAccChild.vt == comtypes.automation.VT_I4:
yield (iaccessible, objAccChild.value)
def findObjIAccessible(handle, text):
"""Find the IAccessible based on the name, starting from a specific window handle
Arguments:
handle -- the window handle from which to search for the element
text -- text that should be contained in the name of the IAccessible instance
Return:
(None, 0) if not found
(IAccessible instance, child id) of the first element whose name contains the text
"""
iacc = ctypes.POINTER(comtypes.gen.Accessibility.IAccessible)()
ctypes.oledll.oleacc.AccessibleObjectFromWindow(handle, 0, ctypes.byref(comtypes.gen.Accessibility.IAccessible._iid_), ctypes.byref(iacc))
for (ia, ch) in accDescendants(iacc):
n = accName(ia, ch)
if n != None and text in n:
return (ia, ch)
else:
return (None, 0)

Problem with (AttributeError) client.logs_from

i was creating bot for discord channel. But I don't understand where i have wronged or errored in my code
I was do from tutorial but in video this wrong not present. Then I search this problem in another tutorial, but i don't have result pls help
#client.command(pass_context=True, name='clear', aliases=['purgemessages'], no_pm=True)
async def clear(ctx, number):
number = int(number)
if number > 99 or number < 1:
await ctx.send("Sorry comrade>-< \n But i can deleted message within a range of 1 - 99")
else:
author = ctx.message.author
authorID = author.id
mgs = []
number = int(number)
channel = ctx.message.channel
async for x in client.logs_from((channel), limit = int(number)):
mgs.append
await ctx.message.channel.delete_messages(ctx, member, mgs)
await ctx.send("This was deleted ^^")
I want a bot to delete messages
You should use client.purge() to do it.
It seems that you're looking for a way to delete the command caller's messages (a.k.a author).
Here's a quick example using purge() method :
author = ctx.message.author
# check function
def is_caller(message):
if(message.author.id == author.id):
return(True)
else:
return(False)
# delete the author's messages
# the purge method returns a list of deleted messages
deleted_message = await client.purge(
limit = number,
check = is_caller
)
await ctx.send(f"{len(deleted_message)} messages deleted.")
The limit is represented by the number parameter of your command.
Hope it helped !

Django Session Persistent but Losing Data

I have been working for hours trying to understand the following problem: I have a user send an Ajax request to dynamically send a form and record that the number of forms to read on submission has increased. Toward this end I use request.session['editing_foo'] = { 'prefix_of_form_elements' : pkey } so that I can associate them with the database for saving and loading (-1 is for new forms that haven't been saved yet).
However, when I use the following code (see bottom) I get the following bizarre output:
1st Click:
{} foousername
next_key 1
1
{u'1-foo': -1}
2nd Click:
{} foousername
next_key 1
1
{u'1-foo': -1}
3rd Request:
{} foousername
next_key 1
1
{u'1-foo': -1}
What the heck is going on?
id_fetcher = re.compile(r'\d')
#login_required
def ajax_add_foo(request):
def id_from_prefix(key):
return int( id_fetcher.search(key).group(0) )
if 'editing_foos' not in request.session:
print "reinitializing"
request.session['editing_foos'] = {}
print request.session['editing_foos'], request.user
keys = request.session['editing_foos'].keys()
if len(keys) == 0:
next_key = 1
else:
print [ id_from_prefix(key) for key in keys ]
next_key = max([ id_from_prefix(key) for key in keys ]) + 1
print "next_key", next_key
fooform = FooForm(prefix=next_key)
print next_key
request.session['editing_foos'].update( {create_prefix(FooForm, next_key) : -1 } ) # This quote is new and has no pkey
print request.session['editing_foos']
return render_to_response( 'bar/foo_fragment.html',
{'fooform' : fooform, },
context_instance=RequestContext(request))
Thank you all very much!
Note: This is a followup to a previous question concerning the same source code.
I don't think I completely understand the question, but you may want to take a look at which session engine you're using
if you're using the cache session engine you need to make sure you have caching properly set up (for instance the dummy cache would just throw out your session data)
another possibility is that your session isn't being saved because you're not changing the session, you're changing a mutable object that is stored in the session. you can try forcing the session to save by adding this somewhere in your view:
request.session.modified = True

Resources