The role is not issued when clicking on the reaction - c#

My exception says that user = null but I don't understand why? UserId is passed in the debugger
private async Task ReactionAdd(Cacheable<IUserMessage, ulong> cache, ISocketMessageChannel socketMessageChannel, SocketReaction reaction)
{
if (reaction.MessageId == 771361839917170748)
{
var emote = Emote.Parse("<:NepSmug:740928682310500412>").ToString();
if (reaction.Emote.ToString() == emote)
{
var sockettextChannel = socketMessageChannel as SocketTextChannel;
ulong roleid = 741342300499738715;
var role = sockettextChannel.Guild.GetRole(roleid);
var user = sockettextChannel.Guild.GetUser(reaction.UserId);
await user.AddRoleAsync(role);
}
}
}

The user is null might caused by recent change on the Discrod API refer to this. The changes caused the Guild.User info is not downloaded properly.
First thing to check is if the User is assigned on Context.Guild or not (You can also verify if the user in your Discord server is equal on the Context.Guild.Users).
Second you need to enable this feature on your Discord Bot

Related

Unity Firebase Authentication CreateUserWithEmailAndPasswordAsync returns empty UserID

When I run CreateUserWithEmailAndPasswordAsync() the task returns as IsCompleted and the FirebaseUser is also not null, but the UserID and email are null/empty. I can see the new user (with UserID) in the firebase console.
The same thing happens when trying to SignInWithEmailAndPasswordAsync() with the newly created User. But when I SignInWithEmailAndPasswordAsync() with an older user account everything works fine.
It's strange because it is the same code I used a year ago. In the mean time I did update the Firebase SDK to 7.0.2. Could that be the cause of the issue?
Here is my code for creating a new user:
public static async Task<CallbackMessage> RegisterNewUser(string email, string password)
{
CallbackMessage callback = new CallbackMessage();
callback.isSuccess = false;
if (!await DatabaseManager.CheckConnection())
{
callback.notConnected = true;
return callback;
}
return await auth.CreateUserWithEmailAndPasswordAsync(email, password).ContinueWith(task =>
{
if (task.IsCanceled)
{
callback.errorMessage = "Create User was canceled";
}
else if (task.IsFaulted)
{
callback.errorMessage = GetErrorMessage(task.Exception);
}
else if (task.IsCompleted)
{
FirebaseUser newUser = task.Result;
Debug.Log("User created succesfully! userID: " + newUser.UserId);
callback.userID = newUser.UserId;
callback.email = newUser.Email;
callback.isSuccess = true;
}
CleanTask(task);
return callback;
});
}
Could really use a nudge in the right direction on this one :)
I was able to solve it. Apologies for doubting the Firebase Auth service.
In my AuthStateChanged code I added a Signout() whenever a user signed in, but wasn't emailVerified yet. That's where the problem was.
My guess what happened: When user creation is called it signs the user in immediately, then goes to Firebase to set things up there. In the mean time I sign out the user because it's not email verified. When the callback comes back it looks for the FirebaseUser that it signed in before going to Firebase, but finds nothing.
Something like pulling the chair from underneath someone as he's about to sit :P

Nservice message field issue

I have implemented Voice call in my code using .net with NServiceBus version 7.
Below is the code snippet to send voice call:
public Task Handle(AddServiceAuto message, IMessageHandlerContext context)
{
try
{
string VoiceCallCode = null;
Guid userID = User.userID;
VoiceCallCode = GetVoiceCallCode(userID);
if (VoiceCallCode != null)
{
publishAddVoiceCallEvent(context, user.caseID, userID.Mobile,
userID.Voicecall, VoiceMessageText, VoiceCallCode);
}
}
}
private void publishAddVoiceCallEvent(IMessageHandlerContext context,
Guid caseID, string mobile, bool voicecall,
string voiceMessageText, string voiceCallCode)
{
AddVoiceCallEvent addVoiceCallEvent = new AddVoiceCallEvent()
{
CaseID = caseID,
Mobile = mobile,
Voicecall = voicecall,
VoiceMessageText = voiceMessageText,
VoiceCallCode = voiceCallCode
};
context.Publish(addVoiceCallEvent).ConfigureAwait(false);
}
public Task Handle(AddVoiceCallEvent message, IMessageHandlerContext context)
{
try
{
Logger.InfoFormat("message.CaseID: {0}", message.CaseID);
Logger.InfoFormat("message.Voicecall= {0}", message.Voicecall);
Logger.InfoFormat("message.Mobile {0}", message.Mobile);
Logger.InfoFormat("message.VoiceCallCode {0}", message.VoiceCallCode);
// The user should satisfy below conditions in order to receive a voice call.
if ((message.Voicecall) && !string.IsNullOrEmpty(message.Mobile) &&
!string.IsNullOrEmpty(message.VoiceMessageText) &&
!string.IsNullOrEmpty(message.VoiceCallCode))
{
Voicecall(message.Mobile, message.Voicecall,
message.VoiceMessageText, message.VoiceCallCode);
}
else
{
Logger.Error("Mobile Value is Empty (OR) Voicecall is False (OR)
+ VoiceMessageText is Empty (OR) VoiceCallCode is Empty");
}
}
}
If condition satisfied it will send voice call, else it will print log.
Problem:
The Voice call is random i.e. sometimes user is receiving voice call and sometimes not(even though with same settings i.e mobile, VoiceCallCode values stored properly in DB and Voicecall is also true)
and the Strange part is, though the values are stored correctly DB, when we look into the logs that we are printing, it shows the value of Mobile, VoiceCallCode is null and Voicecall is false.
Again after 5 mins I tried, it worked.
One more thing is, when voice call is not working.
Logger.InfoFormat("message.CaseID: {0}", message.CaseID); // CaseID printed
For Below, data is not printing even though data is there in available in DB (i.e. printing as null)
Logger.InfoFormat("message.Voicecall= {0}", message.Voicecall);
Logger.InfoFormat("message.Mobile {0}", message.Mobile);
Logger.InfoFormat("message.VoiceCallCode {0}", message.VoiceCallCode);
Strange is that, for CaseID it printed while for others it is not printing.
Why this is happening? Can someone please help on this?
The code you've shared doesn't seem to be a running code (try w/o catch) therefore it would be hard to pinpoint what contributes to the issue. But the random behaviour could be attributed to improper use of async APIs. The handler methods should return a Task or use async/await. So are operations invoked on IMessageHandlerContext.
For example, publishAddVoiceCallEvent should be returning a Task and not void. The code inside it (context.Publish(addVoiceCallEvent).ConfigureAwait(false);) should be either return context.Publish(addVoiceCallEvent); or await context.Publish(addVoiceCallEvent).ConfigureAwait(false);.
NServiceBus comes with a Rozlyn analyzer to help with these issues.

How can I auto-assign a role to a new member with my bot?

The title suggests it. Is there any way for the bot to detect when a user joined the guild and automatically grant that user a specific role? I want to automatically grant every user the "member" role, how can I achieve this? I am not at all experienced with C#.
I have tried this, with no success:
public async Task auto_role(SocketGuildUser user)
{
await user.AddRoleAsync((Context.Guild.Roles.FirstOrDefault(x => x.Name == "Member")));
}
If you wish to add a role to any newly joined guild member, you should not be touching the command system at all since, well, it's not a command!
What you do want to do is hook something like the UserJoined event, which is fired whenever a new user joins a guild.
So, for example, you may want to do something like this:
public class MemberAssignmentService
{
private readonly ulong _roleId;
public MemberAssignmentService(DiscordSocketClient client, ulong roleId)
{
// Hook the evnet
client.UserJoined += AssignMemberAsync;
// Note that we are using role identifier here instead
// of name like your original solution; this is because
// a role name check could easily be circumvented by a new role
// with the exact name.
_roleId = roleId;
}
private async Task AssignMemberAsync(SocketGuildUser guildUser)
{
var guild = guildUser.Guild;
// Check if the desired role exist within this guild.
// If not, we simply bail out of the handler.
var role = guild.GetRole(_roleId);
if (role == null) return;
// Check if the bot user has sufficient permission
if (!guild.CurrentUser.GuildPermissions.Has(GuildPermissions.ManageRoles)) return;
// Finally, we call AddRoleAsync
await guildUser.AddRoleAsync(role);
}
}

Why I can not give a discord user a role? c#

I want to give a Discord client a role in a ReactionAdded event. Why does not this work?
public static async Task AddedReactEvent(Cacheable<IUserMessage, ulong> message, ISocketMessageChannel channel, SocketReaction reaction)
{
if (channel.Id == 504031332612046881)
{
if (reaction.Emote.Name == "PS4")
{
var context = new CommandContext(_client, message.Value);
var role = context.Guild.Roles.FirstOrDefault(x => x.Name == "PS4");
Console.WriteLine(role.Color.ToString());
await (reaction.User.Value as IGuildUser).AddRoleAsync(role);
}
}
}
It clearly seems to be a NullReferenceException. This could be because your var role could be null. You can find it out if you use breakpoints and run the debugger.
Also your method of getting the role though the channel through the _client seems inappropriate. Why bother to create a new commandContext just get the role from Cacheable channel.
var role = ((ITextChannel) channel).Guild.Roles.FirstOrDefault(x => x.Name == "PS4");
This ought to get you the role. Also if it is your private server you are coding for dont bother to use the role name thing. Instead use the role id something like
var role = ((ITextChannel) channel).Guild.GetRole(437634977941684226);
You can get the role id by mentioning the role and placing a \ before it (escaping it).
Like
\#bot
becomes
<#&437634977941684226>
and 437634977941684226 is your roleID

Add a user to parse role

I'm trying to create a new user and adding it to an already existing ParseRole, but i'm getting the ParseException: object not found for update after performing await parseRole.SaveAsync();.
I checked in the Parse website and both the Role and User are saved (the ids returned by c# code are correct), but the Role hasn't that user.
[TestMethod]
public async Task CanCreateCustomer()
{
var customer = ParseObject.Create<ApplicationUser>();
customer.FirstName = GetRandom.FirstName();
customer.LastName = GetRandom.LastName();
customer.Password = "123";
customer.Username = customer.GetUserName();
Assert.IsNull(customer.ObjectId);
await customer.SignUpAsync();
Assert.IsNotNull(customer.ObjectId);
var parseRole = await ParseRole.Query.Where(x => x.Name == Roles.CustomerRole).FirstAsync();
parseRole.Users.Add(customer);
await parseRole.SaveAsync();
}
The problem was I didn't set the ACL for my roles to allow write access to the logged user (or public, in case of my unit test)

Categories