Skip to content

Commit

Permalink
Nickname support
Browse files Browse the repository at this point in the history
  • Loading branch information
suicvne committed Apr 30, 2016
1 parent 8a4de75 commit ede51f4
Show file tree
Hide file tree
Showing 5 changed files with 111 additions and 22 deletions.
37 changes: 25 additions & 12 deletions DiscordSharp/DiscordClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1853,7 +1853,15 @@ public void Connect(bool useDotNetWebsocket = false)

ws.MessageReceived += (sender, e) =>
{
var message = JObject.Parse(e.Message);
var message = new JObject();
try
{
message = JObject.Parse(e.Message);
}
catch(Exception ex)
{
DebugLogger.Log($"MessageReceived Error: {ex.Message}\n\n```{e.Message}\n```\n", MessageLevel.Error);
}

if (EnableVerboseLogging)
if (message["t"].ToString() != "READY")
Expand Down Expand Up @@ -2497,26 +2505,30 @@ private void GuildMemberUpdateEvents(JObject message)
if (memberUpdated != null)
{
memberUpdated.Username = message["d"]["user"]["username"].ToString();
if(message["d"]["user"]["nick"] != null)
{
if (message["d"]["user"]["nick"].ToString() == null)
memberUpdated.Nickname = ""; //No nickname
else
memberUpdated.Nickname = message["d"]["user"]["nick"].ToString();
}

if (!message["d"]["user"]["avatar"].IsNullOrEmpty())
memberUpdated.Avatar = message["d"]["user"]["avatar"].ToString();
memberUpdated.Discriminator = message["d"]["user"]["discriminator"].ToString();
memberUpdated.ID = message["d"]["user"]["id"].ToString();



foreach (var roles in message["d"]["roles"])
{
memberUpdated.Roles.Add(server.Roles.Find(x => x.ID == roles.ToString()));
}

//server.Members.Remove(server.GetMemberByKey(x => x.ID == message["d"]["user"]["id"].ToString()));
server.AddMember(memberUpdated);

if (GuildMemberUpdated != null)
GuildMemberUpdated(this, new DiscordGuildMemberUpdateEventArgs { MemberUpdate = memberUpdated, RawJson = message, ServerUpdated = server });
GuildMemberUpdated?.Invoke(this, new DiscordGuildMemberUpdateEventArgs { MemberUpdate = memberUpdated, RawJson = message, ServerUpdated = server });
}
else
{
DebugLogger.Log("memberUpdated was null?!?!?!", MessageLevel.Critical);
DebugLogger.Log("memberUpdated was null?!?!?!", MessageLevel.Debug);
}
}

Expand Down Expand Up @@ -2555,8 +2567,7 @@ private void GuildRoleDeleteEvents(JObject message)
DebugLogger.Log($"Couldn't delete role with ID {message["d"]["role_id"].ToString()}! ({ex.Message})", MessageLevel.Critical);
}

if (RoleDeleted != null)
RoleDeleted(this, new DiscordGuildRoleDeleteEventArgs { DeletedRole = deletedRole, Guild = inServer, RawJson = message });
RoleDeleted?.Invoke(this, new DiscordGuildRoleDeleteEventArgs { DeletedRole = deletedRole, Guild = inServer, RawJson = message });
}

/// <summary>
Expand Down Expand Up @@ -2768,8 +2779,7 @@ private void GuildUpdateEvents(JObject message)
ServersList.Remove(oldServer);
ServersList.Add(newServer);
DiscordServerUpdateEventArgs dsuea = new DiscordServerUpdateEventArgs { NewServer = newServer, OldServer = oldServer };
if (GuildUpdated != null)
GuildUpdated(this, dsuea);
GuildUpdated?.Invoke(this, dsuea);
}

private void ChannelDeleteEvents(JObject message)
Expand Down Expand Up @@ -2914,6 +2924,9 @@ private void GuildCreateEvents(JObject message)
foreach (var mbr in message["d"]["members"])
{
DiscordMember member = JsonConvert.DeserializeObject<DiscordMember>(mbr["user"].ToString());
if(mbr["nick"] != null)
member.Nickname = mbr["nick"].ToString();

member.parentclient = this;
member.Parent = server;

Expand Down
36 changes: 36 additions & 0 deletions DiscordSharp/Objects/DiscordMember.cs
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,8 @@ public class DiscordMember
public bool IsBot { get; internal set; } = false;
[JsonProperty("joined_at")]
public DateTime JoinedAt { get; internal set; }
[JsonProperty("nick")]
public string Nickname { get; internal set; } = "";

public Status Status { get; internal set; } = Status.Offline;
public string CurrentGame { get; internal set; } = null;
Expand Down Expand Up @@ -121,6 +123,40 @@ public void Kick()
}
}

/// <summary>
/// Changes the nickname for this user, if you have permission to do so.
/// </summary>
/// <param name="nickname">null for no nickname.</param>
public void ChangeNickname(string nickname)
{
string url = Endpoints.BaseAPI + Endpoints.Guilds + $"/{Parent.ID}" + Endpoints.Members + $"/{ID}";
string payload = JsonConvert.SerializeObject
(
new
{
nick = (nickname == null ? "" : nickname)
}
);
var strResult = WebWrapper.Patch(url, DiscordClient.token, payload);
}

/// <summary>
/// Iterates all the roles the user has checking if any of the present have the permission you pass.
/// </summary>
/// <param name="permission">The permission to check.</param>
/// <returns>True if the permission is present.</returns>
public bool HasPermission(DiscordSpecialPermissions permission)
{
var result = false;
Roles.ForEach(x =>
{
if (x.Permissions.HasPermission(permission))
{ result = true; return; }
});

return result;
}

/// <summary>
/// Testing copy method.
/// </summary>
Expand Down
7 changes: 5 additions & 2 deletions DiscordSharp/Objects/DiscordPermission.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,9 @@ namespace DiscordSharp.Objects
{
public enum DiscordSpecialPermissions : byte
{
//Me
//Me, donut use
None = 255,

//General
CreateInstanceInvite = 0,
KickMembers = 1,
Expand All @@ -34,7 +35,9 @@ public enum DiscordSpecialPermissions : byte
VoiceMuteMembers = 22,
VoiceDeafenMembers = 23,
VoiceMoveMembers = 24,
VoiceUseActivationDetection = 25
VoiceUseActivationDetection = 25,
ChangeNickname = 26,
ManageNicknames = 27
}
public class DiscordPermission
{
Expand Down
20 changes: 12 additions & 8 deletions DiscordSharp/Objects/DiscordRole.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,28 +5,31 @@ namespace DiscordSharp.Objects
public class DiscordRole
{
[JsonProperty("color")]
public DiscordSharp.Color Color { get; set; }
public DiscordSharp.Color Color { get; internal set; }

/// <summary>
/// Whether or not to display all members seperate of others.
/// </summary>
[JsonProperty("hoist")]
public bool Hoist { get; set; }
public bool Hoist { get; internal set; }

[JsonProperty("name")]
public string Name { get; set; }
public string Name { get; internal set; }

[JsonProperty("permission")]
public DiscordPermission Permissions { get; set; }
public DiscordPermission Permissions { get; internal set; }

[JsonProperty("managed")]
public bool Managed { get; set; }
public bool Managed { get; internal set; }

[JsonProperty("position")]
public int Position { get; set; }
public int Position { get; internal set; }

[JsonProperty("id")]
public string ID { get; set; }
public string ID { get; internal set; }

[JsonProperty("mentionable")]
public bool CanBeMentioned { get; internal set; }

public DiscordRole Copy()
{
Expand All @@ -38,7 +41,8 @@ public DiscordRole Copy()
Permissions = this.Permissions,
Managed = this.Managed,
Position = this.Position,
ID = this.ID
ID = this.ID,
CanBeMentioned = this.CanBeMentioned
};
}

Expand Down
33 changes: 33 additions & 0 deletions DiscordSharpTestApplication/Modules/TestingModule.cs
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,39 @@ public override void Install(CommandsManager manager)
}
}
}), this);

manager.AddCommand(new CommandStub("info", "Displays info for a user.", "", PermissionType.Owner, 1, cmdArgs =>
{
if(cmdArgs.Args.Count > 0)
{
var user = cmdArgs.Channel.Parent.GetMemberByKey(cmdArgs.Args[0].Trim(new char[] { '<', '@', '!', '>' }));
if (user != null)
{
string msg = $"Info for {user.Username}\n```\n";
msg += $"Username: {user.Username}\nID: {user.ID}";
if (user.Nickname != null || user.Nickname.Trim() != "")
msg += $"\nNickname: {user.Nickname}";
msg += $"\nDiscrim: {user.Discriminator}\n";
msg += $"```";
cmdArgs.Channel.SendMessage(msg);
}
}
}));

manager.AddCommand(new CommandStub("changemynick", "Changes your nickname.", "Needs appropriate permissions.", PermissionType.Owner, 1, cmdArgs =>
{
if(cmdArgs.Args.Count > 0)
{
var meInServer = cmdArgs.Channel.Parent.GetMemberByKey(manager.Client.Me.ID);
if(meInServer != null)
{
if(meInServer.HasPermission(DiscordSpecialPermissions.ManageNicknames))
{
cmdArgs.Author.ChangeNickname(cmdArgs.Args[0]);
}
}
}
}));
}
}
}

0 comments on commit ede51f4

Please sign in to comment.