Syntax for if-else branch based on user input in Bot Framework Composer - botframework

When a user is prompted with a yes or no question, each user might respond differently. Say for example, responses for yes could be yeah, why not, sure, im okay with it, yup etc and similarly to respond for no users could say nope, nah, no.
I want to send a response if the user input belongs to Yes class and send a different response if he has uttered words from No type in Bot Framework Composer.
Under Expected Responses I created entities with value to distinguish the two classes as below
-{Accept = yeah}
-{Accept = Yea}
-{Accept = yup}
-{Accept = that will work}
-{Accept = why not}
-{Accept = yep}
-{Accept = yes}
-{Accept = yeah sure}
-{Reject = No}
-{Reject = Nope}
-{Reject = nah}
screenshot of the composer window
How to write condition checking the user input with the defined class?

Related

How do I add multiple roles form a list to a user?

I have a command that adds all the current roles of a user to a Database (MongoDB).
The code:
def add_roles_to_db(self):
check = cursor.find_one({"_id": self.ctx.author.id})
if check is None:
cursor.insert_one({"_id": self.ctx.author.id, "roles": [str(r) for r in self.ctx.author.roles[1:]]})
else:
cursor.update_one({"_id": self.ctx.author.id}, {"$set": {"roles": [str(r) for r in self.ctx.author.roles[1:]]}})
The code to get the roles:
def get_roles_from_db(self):
return cursor.find_one({"_id": self.ctx.author.id})["roles"]
When I get the roles from the DB I get a list, everything I've tried led to an error. Error: "AttributeError: 'str' object has no attribute 'id'"
if len(roles) != 0:
await author.add_roles(*roles)
I saw a other post where someone added roles via a list but that didn't work
You're passing a list of strings, not a list of Roles. Turn them into discord.Role instances using the id's first, and then pass them to add_roles.
You can get them using Guild.get_role, or Guild.roles.
await author.add_roles(*[discord.Object(role_id) for role_id in roles])
One good way of adding multiple roles to a user is to have the list of role IDs into a list. You would have to look at your code and figure out how to do that bit, as I don't know either but I reckon just append it into a list. Then interate through each item in that list (each ID) and append it.
Example code:
guild = client.get_guild(1234) #replace 1234 with your guild ID
guild = ctx.guild #this is another way of doing it, chose the one above or this
role_ids = [] #your role ids would be in this list
for id in role_ids:
role = guild.get_role(id)
await author.add_roles(role)
await ctx.send("Given you all the roles!")
I haven't tried this myself, but I don't see why it wouldn't work.
If you need any more clarification, please ask me and if this has worked, please mark it as correct! :)

Discord.js #everyone / #here issues with message

I have the code here for my embed announce feature, if a role is mentioned then it sends that role mention to the channel and then sends the rest of the message in an embed, i also have a variation for user mentions. How do i adapt this to do the same for #everyone & #here? they dont have ID's like roles. Either that or i cant find the ID of #everyone & #here. typing #everyone results in #everyone being returned, not an ID
if (args[1].startsWith('<#&') && args[1].endsWith('>')) {
message.channel.send(args[1])
const embed = new Discord.MessageEmbed()
.setTitle(`${(args.slice(2).join(" "))}`)
.setColor(0x320b52)
.setTimestamp()
.setFooter('Requested by ' + message.author.tag)
message.channel.send(embed);
Correct, #everyone and #here do not have IDs. Simply check whether either of them matches args[1].

Writing a custom claims issuance rule

For a specific use case, we need to add external users to our AD and allow these to login through AD FS to an external service.
Everything was set up with only internal users in mind, so we wrote a claim rule as follows:
c:[Type == "http://schemas.microsoft.com/ws/2008/06/identity/claims/windowsaccountname", Issuer == "AD AUTHORITY"]
=> issue(store = "Active Directory", types = ("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/givenname"), query = ";sAMAccountName;{0}", param = c.Value);
Basically, this is LDAP Attribute "SAM-Account-Name", and Outgoing Claim Type "Given Name". This works well for internal users.
For external users, there's a use case where the user name in the external site should be the email address used in AD. The easiest thing would be to fill in the email address in the sAMAccountName, but it doesn't allow # symbols.
So I was messing around with claim transformation rules, and figured I could try to add two conditional claim rules, as follows:
Internal users:
c:[Type == "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress", Value =~ "domain.com$"]
=> issue(store = "Active Directory", types = ("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/givenname"), query = ";sAMAccountName;{0}", param = c.Value);
External users:
c:[Type == "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress", Value !=~ "domain.com$"]
=> issue(store = "Active Directory", types = ("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/givenname"), query = ";mail;{0}", param = c.Value);
The first claim rule checks if the email address ends with "domain.com", and if so, it will use the sAmAccountName (internal users).
The second claim rule does the reverse: if it doesn't end with "domain.com", it will use the mail attribute (external users).
But pity, it's not working (either one tested separately).
What's wrong with my approach?

how to check if user has permission to delete objects in django

I am trying to write a view method that responds to an AJAX request to delete an entry. I want to check if the end user is the actual author of the Entry before deleting that Entry. Does my "if" statement accomplish this?
VIEWS.PY
latest_entries=Entry.objects.order_by('-pub_date')[:16]
#login_required
def delete_object(request):
if request.is_ajax():
object_name = request.POST.get('entryname')
targetobject = Entry.objects.get(author=object_name)
if request.user = targetobject.author:
targetobject.delete()
return HttpResponseRedirect('/storefront/')
MODELS
Class Entry(models.Model):
author = models.CharField(max_length=30)
subject = models.CharField(max_length=30)
description = models.CharField(max_length=30)
You're almost there. request.user is an instance of django.utils.SimpleLazyObject, so you won't be able to do an == comparison of request.user to a CharField, of which the value is a string under the covers.
You need to do something like:
if request.user.username == targetobject.author:
targetobject.delete()
or just use whatever field from the User object is synonymous with Entry.author.
I'd say your model is wrong. author should be a ForeignKey to the auth.User model. Then your comparison would work (with the change to ==), and there are other benefits too in terms of grouping and querying by user attributes.

What is the best way pre filter user access for sqlalchemy queries?

I have been looking at the sqlalchemy recipes on their wiki, but don't know which one is best to implement what I am trying to do.
Every row on in my tables have an user_id associated with it. Right now, for every query, I queried by the id of the user that's currently logged in, then query by the criteria I am interested in. My concern is that the developers might forget to add this filter to the query (a huge security risk). Therefore, I would like to set a global filter based on the current user's admin rights to filter what the logged in user could see.
Appreciate your help. Thanks.
Below is simplified redefined query constructor to filter all model queries (including relations). You can pass it to as query_cls parameter to sessionmaker. User ID parameter don't need to be global as far as session is constructed when it's already available.
class HackedQuery(Query):
def get(self, ident):
# Use default implementation when there is no condition
if not self._criterion:
return Query.get(self, ident)
# Copied from Query implementation with some changes.
if hasattr(ident, '__composite_values__'):
ident = ident.__composite_values__()
mapper = self._only_mapper_zero(
"get() can only be used against a single mapped class.")
key = mapper.identity_key_from_primary_key(ident)
if ident is None:
if key is not None:
ident = key[1]
else:
from sqlalchemy import util
ident = util.to_list(ident)
if ident is not None:
columns = list(mapper.primary_key)
if len(columns)!=len(ident):
raise TypeError("Number of values doen't match number "
'of columns in primary key')
params = {}
for column, value in zip(columns, ident):
params[column.key] = value
return self.filter_by(**params).first()
def QueryPublic(entities, session=None):
# It's not directly related to the problem, but is useful too.
query = HackedQuery(entities, session).with_polymorphic('*')
# Version for several entities needs thorough testing, so we
# don't use it yet.
assert len(entities)==1, entities
cls = _class_to_mapper(entities[0]).class_
public_condition = getattr(cls, 'public_condition', None)
if public_condition is not None:
query = query.filter(public_condition)
return query
It works for single model queries only, and there is a lot of work to make it suitable for other cases. I'd like to see an elaborated version since it's MUST HAVE functionality for most web applications. It uses fixed condition stored in each model class, so you have to modify it to your needs.
Here is a very naive implementation that assumes there is the attribute/property self.current_user logged in user has stored.
class YourBaseRequestHandler(object):
#property
def current_user(self):
"""The current user logged in."""
pass
def query(self, session, entities):
"""Use this method instead of :method:`Session.query()
<sqlalchemy.orm.session.Session.query>`.
"""
return session.query(entities).filter_by(user_id=self.current_user.id)
I wrote an SQLAlchemy extension that I think does what you are describing: https://github.com/mwhite/multialchemy
It does this by proxying changes to the Query._from_obj and QueryContext._froms properties, which is where the tables to select from ultimately get set.

Resources