Changing the position of the Bot Role in Discord - bots

I'm currently trying to get my bot working properly. One problem is that the Role that is automatically assigned to the bot is below all other roles and I don't want that the users have to drag them above the other roles. So I decided to try to change the roles position when the bot joins the server but nothing works. Here's my code:
First I connect my method to the event
_client.JoinedGuild += InviteHandler;
Secondly, I get the role and try to change the properties.
SocketRole BotRole = null;
foreach(var role in guild.Roles)
{
if(role.Name.Equals("KingFive"))
{
BotRole = role;
} else
{
continue;
}
}
BotRole.ModifyAsync(x =>
{
x.Color = Color.Gold;
x.Hoist = false;
x.Position = 10;
});
return Task.CompletedTask;
If anyone could help me, I would be happy :)

Related

How can I add user info to conv.user.storage?

I'm using Actions Builder to create my chatbot and after user logins using Google I want to save his ID to storage variable.
This storage variable doesn't exist on conv.user.
So I do this:
if (conv.user.verificationStatus === 'VERIFIED') {
conv.user.storage = {};
conv.user.storage.id = str.rows[0].id;
console.log("STORAGE");
console.log(conv.user.storage.id);
}
But on Google Assistant it returns the error message and on my Webhook it's all good (no errors shown):
Google Assistant Error
What can I do to save/persist at least my user ID for future referings?
Since user has the Google Sign In process done once, every time he enters in your action you have his info on the request (payload). It´s automatically added to user storage.
You should store it on conv.user.params and refer to it in your code.
You may have a get and set method to help you with:
getUserId(conv) {
return conv.user.params.userId;
}
setUserId(conv, userId) {
try {
conv.user.params.userId = userId;
} catch (e) {
throw new error("Error setting USERID");
}
return userId;
}

getting user list from slack API using NodeJS

I am creating a slack bot and am trying to get the list of members in a slack workspace. Below is my code.
getUserList() {
axios.get(`https://slack.com/api/users.list?token=`+process.env.SLACK_BOT_TOKEN).then((res) => {
var jsonParsed = JSON.parse(res);
for (i = 0; i < jsonParsed; i++) {
workspace_users.push(jsonParsed[i].name);
}
});
},
I am getting below response.
{"ok":true,"no_op":true,"already_open":true,"channel":{"id":"*****"},"scopes":["identify","bot:basic"],"acceptedScopes":["im:write","post"]}
I went to https://api.slack.com/methods/users.list and I am not getting the kind of result mention in the URL.
I have already given the scope permission to my bot.
Any help would be appreciated.

How to get back to app after google login

I'm trying to implement google login in my app using xamarin.auth like below
var auth = new OAuth2Authenticator("284202576320-7kgdhaa5sgvkoe03jmmcv0p8lfdma306.apps.googleusercontent.com","cAZW7uegD-h2-
tNMMf5q1UGQ","https://www.googleapis.com/auth/userinfo.email",new
Uri("https://accounts.google.com/o/oauth2/auth"),new
Uri("http://dev.myfav.restaurant/Account/LoginComplete"),new
Uri("https://accounts.google.com/o/oauth2/token"),null,true)
{
AllowCancel = true,
};
but Completed event not firing and its going to web page after login :(
I'm getting below error
i need to get back user to my app how can i achieve this ???? Can anyone help me on this please.
Thanks in advance
Hey follow these two examples one is using web view and one is using google sign in sdk for google auth.
https://timothelariviere.com/2017/09/01/authenticate-users-through-google-with-xamarin-auth/
and
https://developer.xamarin.com/samples/xamarin-forms/WebServices/OAuthNativeFlow/
So according to this issue reported by Mounika.Kola .I think u should refer that authenticator.Completed -= OnAuthCompleted is there in ur code. For reference just see these codes which i used for google authorization in Xamarin Forms.
void OnLoginClicked(object sender, EventArgs e)
{
string clientId = null;
string redirectUri = null;
switch (Device.RuntimePlatform)
{
case Device.iOS:
clientId = Constants.iOSClientId;
redirectUri = Constants.iOSRedirectUrl;
break;
case Device.Android:
clientId = Constants.AndroidClientId;
redirectUri = Constants.AndroidRedirectUrl;
break;
}
var authenticator = new OAuth2Authenticator(
clientId,
null,
Constants.Scope,
new Uri(Constants.AuthorizeUrl),
new Uri(redirectUri),
new Uri(Constants.AccessTokenUrl),
null,
true);
authenticator.Completed += OnAuthCompleted;
authenticator.Error += OnAuthError;
AuthenticationState.Authenticator = authenticator;
var presenter = new Xamarin.Auth.Presenters.OAuthLoginPresenter();
presenter.Login(authenticator);
}
async void OnAuthCompleted(object sender, AuthenticatorCompletedEventArgs e)
{
var authenticator = sender as OAuth2Authenticator;
if (authenticator != null)
{
authenticator.Completed -= OnAuthCompleted;
authenticator.Error -= OnAuthError;
}
User user = null;
if (e.IsAuthenticated)
{
// If the user is authenticated, request their basic user data from Google
// UserInfoUrl = https://www.googleapis.com/oauth2/v2/userinfo
var request = new OAuth2Request("GET", new Uri(Constants.UserInfoUrl), null, e.Account);
var response = await request.GetResponseAsync();
if (response != null)
{
// Deserialize the data and store it in the account store
// The users email address will be used to identify data in SimpleDB
string userJson = await response.GetResponseTextAsync();
user = JsonConvert.DeserializeObject<User>(userJson);
}
if (account != null)
{
store.Delete(account, Constants.AppName);
}
await store.SaveAsync(account = e.Account, Constants.AppName);
await DisplayAlert("Email address", user.Email, "OK");
}
}
I hope it helps you.
In iOS once you have completed the authentication with Xamarin.Auth you just need to dismiss the viewController and you will be put back in your app.
You do this subscribing to the Completed event of the OAuth2Authenticator
auth.Completed += (sender, e) =>
{
DismissViewController(true, null);
};
If the "Native UI" is used (the last parameter in the constructor is set to true), which means that external/system browser is used for login not WebView. So, on Android instead of WebView [Chrome] CustomTabs is used and on iOS instead of UIWebView (or WKWebView) SFSafariViewController is used.
With native UI user is leaving your app and the only way to return to your app is app-linking (or deep-linking) and this requires completely different approach.
1st you cannot use http[s] scheme for redirect_url (OK on Android it is possible, but on iOS not). Use custom scheme for that.
See the sample[s] (Xamarin.Forms ComicBook):
https://github.com/moljac/Xamarin.Auth.Samples.NugetReferences
And the docs in the repo:
https://github.com/xamarin/Xamarin.Auth/tree/master/docs

Clear sessions and old cookies in ASP.Net Core

I have a website with a lot of registered users and many of them have chosen the "remember me" option in login.
I used to use the default login behavior for asp.net core but I installed openiddict and added the following option to services.addIdentity:
options.Cookies.ApplicationCookie.Events = new CookieAuthenticationEvents
{
OnRedirectToLogin = context =>
{
if (context.Request.Path.StartsWithSegments("/api") && context.Response.StatusCode == (int)HttpStatusCode.Unauthorized)
{
context.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
}
else
{
context.Response.Redirect(context.RedirectUri);
}
return Task.FromResult(0);
}
};
}
The full method in startup.cs now reads the following:
services.AddIdentity<ApplicationUser, IdentityRole>(options =>
{
options.Password.RequireDigit = false;
options.Password.RequireLowercase = false;
options.Password.RequireNonAlphanumeric = false;
options.Password.RequireUppercase = false;
options.Password.RequiredLength = 6;
options.Cookies.ApplicationCookie.CookieDomain = "mydomain.com";
options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromDays(1);
options.Lockout.MaxFailedAccessAttempts = 10;
options.Cookies.ApplicationCookie.Events = new CookieAuthenticationEvents
{
OnRedirectToLogin = context =>
{
if (context.Request.Path.StartsWithSegments("/api") && context.Response.StatusCode == (int)HttpStatusCode.Unauthorized)
{
context.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
}
else
{
context.Response.Redirect(context.RedirectUri);
}
return Task.FromResult(0);
}
};
The problem now that if a previously registered and logged-in user tried to open pages that require authentication he gets an error message. Unfortunately I'm unable to determine that error because appinsights and "development" mode doesn't work for me in Azure. if users go to login page without logging out they get a blank page after logging in.
The only way to solve it is to logout and login again.
Because I have a lot of users I'm trying to find a way to clear all sessions or previous cookies.
Any suggestions on this or comments about my code above is strongly appreciated.
Thank you
Update: I tried try catch and the error happened. Apparently there is no exception... This is very weird.
Update2: This is not account related. A friend of mine is facing the error and gave me his credentials. When I tried it works, perhaps it's a cookie problem?

No application keys for Azure Mobile Apps - what's a simple replacement?

I've been using Azure Mobile Services and now I created one of the new Mobile Apps via the all new Azure Portal.
While using Mobile Services it was possible to limit API access via an application key. The concept of this key no longer applies to Mobile Apps it seems.
All I need is a really lightweight protection of my services, exactly what the Application Key did. I just want to prevent that everybody out there navigates to my Azure app and messes around with my database; the App Key was perfect for those cases when you did not have anything to hide but wanted to prevent "spamming".
I see there is now Active Directory integration as an alternative but unfortunately I cannot find a guide how to move from App Key to something else.
Check this post How to configure your App Service application to use Azure Active Directory login
this authentication sample code works with UWP
private async Task AuthenticateAsync()
{
while (user == null)
{
string message=string.Empty;
var provider = "AAD";
PasswordVault vault=new PasswordVault();
PasswordCredential credential = null;
try
{
credential = vault.FindAllByResource(provider).FirstOrDefault();
}
catch (Exception)
{
//Ignore exception
}
if (credential != null)
{
// Create user
user = new MobileServiceUser(credential.UserName);
credential.RetrievePassword();
user.MobileServiceAuthenticationToken = credential.Password;
// Add user
App.MobileServiceClient.CurrentUser = user;
try
{
//intentamos obtener un elemento para determinar si nuestro cache ha experidado
await App.MobileServiceClient.GetTable<Person>().Take(1).ToListAsync();
}
catch (MobileServiceInvalidOperationException ex)
{
if (ex.Response.StatusCode == System.Net.HttpStatusCode.Unauthorized)
{
//remove expired token
vault.Remove(credential);
credential = null;
continue;
}
}
}
else
{
try
{
//Login
user = await App.MobileServiceClient
.LoginAsync(provider);
//Create and store credentials
credential = new PasswordCredential(provider,
user.UserId, user.MobileServiceAuthenticationToken);
vault.Add(credential);
}
catch (MobileServiceInvalidOperationException ex)
{
message = "You must log in. Login Required";
}
}
message = string.Format("You are now logged in - {0}", user.UserId);
var dialog = new MessageDialog(message);
dialog.Commands.Add(new UICommand("OK"));
await dialog.ShowAsync();
}
}

Resources