//Special thanks to the node-discord developer, izy521, for helping me out with this :D public DiscordMessage SendMessageToUser(string message, DiscordMember member) { string url = Endpoints.BaseAPI + Endpoints.Users + $"/{Me.ID}" + Endpoints.Channels; string initMessage = "{\"recipient_id\":" + member.ID + "}"; try { var result = JObject.Parse(WebWrapper.Post(url, token, initMessage)); if (result != null) { DiscordMember recipient = ServersList.Find( x => x.members.Find( y => y.ID == result["recipient"]["id"].ToString()) != null).members.Find( x => x.ID == result["recipient"]["id"].ToString()); return SendActualMessage(result["id"].ToString(), message, recipient); } } catch(Exception ex) { DebugLogger.Log($"Error ocurred while sending message to user, step 1: {ex.Message}", MessageLevel.Error); } return null; }
private void GuildMemberRemoveEvents(JObject message) { DiscordGuildMemberRemovedEventArgs e = new DiscordGuildMemberRemovedEventArgs(); DiscordMember removed = new DiscordMember(this); List<DiscordMember> membersToRemove = new List<DiscordMember>(); foreach(var server in ServersList) { if (server.id != message["d"]["guild_id"].ToString()) continue; for(int i = 0; i < server.members.Count; i++) { if(server.members[i].ID == message["d"]["user"]["id"].ToString()) { removed = server.members[i]; membersToRemove.Add(removed); } } } foreach(var member in membersToRemove) { foreach (var server in ServersList) { try { server.members.Remove(member); } catch { } //oh, you mean useless? } } e.MemberRemoved = removed; e.Server = ServersList.Find(x => x.id == message["d"]["guild_id"].ToString()); e.RawJson = message; if (UserRemovedFromServer != null) UserRemovedFromServer(this, e); }
private void UserUpdateEvents(JObject message) { DiscordUserUpdateEventArgs e = new DiscordUserUpdateEventArgs(); e.RawJson = message; DiscordMember newMember = JsonConvert.DeserializeObject<DiscordMember>(message["d"].ToString()); newMember.parentclient = this; DiscordMember oldMember = new DiscordMember(this); //Update members foreach (var server in ServersList) { for (int i = 0; i < server.members.Count; i++) { if (server.members[i].ID == newMember.ID) { server.members[i] = newMember; oldMember = server.members[i]; } } } newMember.Parent = oldMember.Parent; if (!message["roles"].IsNullOrEmpty()) { JArray rawRoles = JArray.Parse(message["roles"].ToString()); if (rawRoles.Count > 0) { foreach (var role in rawRoles.Children()) { newMember.Roles.Add(newMember.Parent.roles.Find(x => x.id == role.Value<string>())); } } else { newMember.Roles.Add(newMember.Parent.roles.Find(x => x.name == "@everyone")); } } e.NewMember = newMember; e.OriginalMember = oldMember; if (UserUpdate != null) UserUpdate(this, e); }
public void AssignRoleToMember(DiscordServer guild, DiscordRole role, DiscordMember member) { string url = Endpoints.BaseAPI + Endpoints.Guilds + $"/{guild.id}" + Endpoints.Members + $"/{member.ID}"; string message = JsonConvert.SerializeObject(new { roles = new string[] { role.id } }); try { Console.WriteLine(WebWrapper.Patch(url, token, message)); } catch(Exception ex) { DebugLogger.Log($"Exception ocurred while assigning role ({role.name}) to member ({member.Username}): " + ex.Message, MessageLevel.Error); } }
public void AssignRoleToMember(DiscordServer guild, List<DiscordRole> roles, DiscordMember member) { string url = Endpoints.BaseAPI + Endpoints.Guilds + $"/{guild.id}" + Endpoints.Members + $"/{member.ID}"; List<string> rolesAsIds = new List<string>(); roles.ForEach(x => rolesAsIds.Add(x.id)); string message = JsonConvert.SerializeObject(new { roles = rolesAsIds.ToArray() }); try { WebWrapper.Patch(url, token, message); } catch(Exception ex) { DebugLogger.Log($"Exception ocurred while assigning {roles.Count} role(s) to member ({member.Username}): " + ex.Message, MessageLevel.Error); } }
public void ConnectAndReadMessages() { ws = new WebSocket("wss://discordapp.com/hub"); ws.OnMessage += (sender, e) => { var message = JObject.Parse(e.Data); switch(message["t"].ToString()) { case ("READY"): using (var sw = new StreamWriter("READY")) sw.Write(message); Me = new DiscordMember { user = new DiscordUser { username = message["d"]["user"]["username"].ToString(), id = message["d"]["user"]["id"].ToString(), verified = message["d"]["user"]["verified"].ToObject<bool>(), avatar = message["d"]["user"]["avatar"].ToString(), discriminator = message["d"]["user"]["discriminator"].ToString()} }; HeartbeatInterval = int.Parse(message["d"]["heartbeat_interval"].ToString()); GetChannelsList(message); if (Connected != null) Connected(this, new DiscordConnectEventArgs { user = Me }); //Since I already know someone will ask for it. break; case ("PRESENCE_UPDATE"): PresenceUpdateEvents(message); break; case ("MESSAGE_UPDATE"): MessageUpdateEvents(message); break; case ("TYPING_START"): DiscordServer server = ServersList.Find(x => x.channels.Find(y => y.id == message["d"]["channel_id"].ToString()) != null); if (server != null) { DiscordChannel channel = server.channels.Find(x => x.id == message["d"]["channel_id"].ToString()); DiscordMember uuser = server.members.Find(x => x.user.id == message["d"]["user_id"].ToString()); if (UserTypingStart != null) UserTypingStart(this, new DiscordTypingStartEventArgs { user = uuser, channel = channel, timestamp = int.Parse(message["d"]["timestamp"].ToString()) }); } break; case ("MESSAGE_CREATE"): MessageCreateEvents(message); break; case ("CHANNEL_CREATE"): ChannelCreateEvents(message); break; #if DEBUG default: ni.BalloonTipText = "Check console! New message type!"; ni.ShowBalloonTip(10 * 1000); Console.WriteLine(message); break; #endif } }; ws.OnOpen += (sender, e) => { DiscordInitObj initObj = new DiscordInitObj(); initObj.op = 2; initObj.d.token = this.token; string json = initObj.AsJson(); ws.Send(json); if (SocketOpened != null) SocketOpened(this, null); Thread keepAlivetimer = new Thread(KeepAlive); keepAlivetimer.Start(); }; ws.OnClose += (sender, e) => { DiscordSocketClosedEventArgs scev = new DiscordSocketClosedEventArgs(); scev.Code = e.Code; scev.Reason = e.Reason; scev.WasClean = e.WasClean; if (SocketClosed != null) SocketClosed(this, scev); }; ws.Connect(); }
public void ConnectAndReadMessages() { CurrentGatewayURL = GetGatewayUrl(); ws = new WebSocket(CurrentGatewayURL); ws.EnableRedirection = true; ws.Log.File = "websocketlog.txt"; ws.OnMessage += (sender, e) => { var message = JObject.Parse(e.Data); switch(message["t"].ToString()) { case ("READY"): using (var sw = new StreamWriter("READY_LATEST.txt")) sw.Write(message); Me = new DiscordMember { user = new DiscordUser { username = message["d"]["user"]["username"].ToString(), id = message["d"]["user"]["id"].ToString(), verified = message["d"]["user"]["verified"].ToObject<bool>(), avatar = message["d"]["user"]["avatar"].ToString(), discriminator = message["d"]["user"]["discriminator"].ToString(), email = message["d"]["user"]["email"].ToString() } }; ClientPrivateInformation.avatar = Me.user.avatar; ClientPrivateInformation.username = Me.user.username; HeartbeatInterval = int.Parse(message["d"]["heartbeat_interval"].ToString()); GetChannelsList(message); if (Connected != null) Connected(this, new DiscordConnectEventArgs { user = Me }); //Since I already know someone will ask for it. break; case ("GUILD_MEMBER_REMOVE"): GuildMemberRemoveEvents(message); break; case ("GUILD_MEMBER_ADD"): GuildMemberAddEvents(message); break; case ("GUILD_DELETE"): GuildDeleteEvents(message); break; case ("GUILD_CREATE"): GuildCreateEvents(message); break; case ("PRESENCE_UPDATE"): PresenceUpdateEvents(message); break; case ("MESSAGE_UPDATE"): MessageUpdateEvents(message); break; case ("TYPING_START"): DiscordServer server = ServersList.Find(x => x.channels.Find(y => y.id == message["d"]["channel_id"].ToString()) != null); if (server != null) { DiscordChannel channel = server.channels.Find(x => x.id == message["d"]["channel_id"].ToString()); DiscordMember uuser = server.members.Find(x => x.user.id == message["d"]["user_id"].ToString()); if (UserTypingStart != null) UserTypingStart(this, new DiscordTypingStartEventArgs { user = uuser, channel = channel, timestamp = int.Parse(message["d"]["timestamp"].ToString()) }); } break; case ("MESSAGE_CREATE"): MessageCreateEvents(message); break; case ("CHANNEL_CREATE"): ChannelCreateEvents(message); break; case ("VOICE_STATE_UPDATE"): VoiceStateUpdateEvents(message); break; case ("MESSAGE_DELETE"): MessageDeletedEvents(message); break; case ("USER_UPDATE"): UserUpdateEvents(message); break; case ("CHANNEL_UPDATE"): ChannelUpdateEvents(message); break; default: if (UnknownMessageTypeReceived != null) UnknownMessageTypeReceived(this, new UnknownMessageEventArgs { RawJson = message }); break; } }; ws.OnOpen += (sender, e) => { DiscordInitObj initObj = new DiscordInitObj(); initObj.op = 2; initObj.d.token = this.token; string json = initObj.AsJson(); ws.Send(json); if (SocketOpened != null) SocketOpened(this, null); Thread keepAlivetimer = new Thread(KeepAlive); keepAlivetimer.Start(); }; ws.OnClose += (sender, e) => { DiscordSocketClosedEventArgs scev = new DiscordSocketClosedEventArgs(); scev.Code = e.Code; scev.Reason = e.Reason; scev.WasClean = e.WasClean; if (SocketClosed != null) SocketClosed(this, scev); }; ws.Connect(); }
//eh private void GetChannelsList(JObject m) { if (ServersList == null) ServersList = new List<DiscordServer>(); foreach(var j in m["d"]["guilds"]) { DiscordServer temp = new DiscordServer(); temp.id = j["id"].ToString(); temp.name = j["name"].ToString(); temp.owner_id = j["owner_id"].ToString(); List<DiscordChannel> tempSubs = new List<DiscordChannel>(); foreach(var u in j["channels"]) { DiscordChannel tempSub = new DiscordChannel(); tempSub.id = u["id"].ToString(); tempSub.name = u["name"].ToString(); tempSub.type = u["type"].ToString(); tempSub.topic = u["topic"].ToString(); tempSubs.Add(tempSub); } temp.channels = tempSubs; foreach(var mm in j["members"]) { DiscordMember member = new DiscordMember(); member.user.id = mm["user"]["id"].ToString(); member.user.username = mm["user"]["username"].ToString(); member.user.avatar = mm["user"]["avatar"].ToString(); member.user.discriminator = mm["user"]["discriminator"].ToString(); temp.members.Add(member); } ServersList.Add(temp); } }
//Special thanks to the node-discord developer, izy521, for helping me out with this :D public void SendMessageToUser(string message, DiscordMember member) { string initMessage = "{\"recipient_id\":" + member.user.id + "}"; var httpRequest = (HttpWebRequest)WebRequest.Create("https://discordapp.com/api/users/" + Me.user.id + "/channels"); httpRequest.Headers["authorization"] = token; httpRequest.ContentType = "application/json"; httpRequest.Method = "POST"; using (var sw = new StreamWriter(httpRequest.GetRequestStream())) { sw.Write(initMessage); sw.Flush(); sw.Close(); } try { var httpResponse = (HttpWebResponse)httpRequest.GetResponse(); using (var sr = new StreamReader(httpResponse.GetResponseStream())) { var result = JObject.Parse(sr.ReadToEnd()); SendActualMessage(result["id"].ToString(), message); } } catch(Exception ex) { //if (DebugMessageReceived != null) // DebugMessageReceived(this, new DiscordDebugMessagesEventArgs { message = ex.Message }); } }
private void GuildMemberAddEvents(JObject message) { DiscordGuildMemberAddEventArgs e = new DiscordGuildMemberAddEventArgs(); e.RawJson = message; DiscordMember newMember = new DiscordMember { user = new DiscordUser { username = message["d"]["user"]["username"].ToString(), id = message["d"]["user"]["id"].ToString(), discriminator = message["d"]["user"]["discriminator"].ToString(), avatar = message["d"]["user"]["avatar"].ToString(), } }; e.AddedMember = newMember; e.Guild = ServersList.Find(x => x.id == message["d"]["guild_id"].ToString()); e.roles = message["d"]["roles"].ToObject<string[]>(); e.JoinedAt = DateTime.Parse(message["d"]["joined_at"].ToString()); ServersList.Find(x => x == e.Guild).members.Add(newMember); if (UserAddedToServer != null) UserAddedToServer(this, e); }
private void UserUpdateEvents(JObject message) { DiscordUserUpdateEventArgs e = new DiscordUserUpdateEventArgs(); e.RawJson = message; DiscordMember newMember = new DiscordMember { user = new DiscordUser { username = message["d"]["username"].ToString(), id = message["d"]["id"].ToString(), verified = message["d"]["verified"].ToObject<bool>(), email = message["d"]["email"].ToString(), avatar = message["d"]["avatar"].ToString(), discriminator = message["d"]["discriminator"].ToString() } }; DiscordMember oldMember = new DiscordMember(); //Update members foreach(var server in ServersList) { for(int i = 0; i < server.members.Count; i++) { if(server.members[i].user.id == newMember.user.id) { server.members[i] = newMember; oldMember = server.members[i]; } } } e.NewMember = newMember; e.OriginalMember = oldMember; if (UserUpdate != null) UserUpdate(this, e); }
private void GuildCreateEvents(JObject message) { DiscordGuildCreateEventArgs e = new DiscordGuildCreateEventArgs(); e.RawJson = message; DiscordServer server = new DiscordServer(); server.id = message["d"]["id"].ToString(); server.name = message["d"]["name"].ToString(); server.owner_id = message["d"]["owner_id"].ToString(); server.members = new List<DiscordMember>(); server.channels = new List<DiscordChannel>(); foreach(var chn in message["d"]["channels"]) { DiscordChannel tempChannel = new DiscordChannel(); tempChannel.id = chn["id"].ToString(); tempChannel.type = chn["type"].ToString(); tempChannel.topic = chn["topic"].ToString(); tempChannel.name = chn["name"].ToString(); tempChannel.is_private = false; server.channels.Add(tempChannel); } foreach(var mbr in message["d"]["members"]) { DiscordMember member = new DiscordMember(); member.user.avatar = mbr["user"]["avatar"].ToString(); member.user.username = mbr["user"]["username"].ToString(); member.user.id = mbr["user"]["id"].ToString(); member.user.discriminator = mbr["user"]["discriminator"].ToString(); server.members.Add(member); } ServersList.Add(server); e.server = server; if (GuildCreated != null) GuildCreated(this, e); }
public void AssignRoleToMember(List<DiscordRole> roles, DiscordMember member) { string url = Endpoints.BaseAPI + Endpoints.Guilds + $"/{this.id}" + Endpoints.Members + $"/{member.ID}"; List<string> rolesAsIds = new List<string>(); roles.ForEach(x => rolesAsIds.Add(x.id)); string message = JsonConvert.SerializeObject(new { roles = rolesAsIds.ToArray() }); Console.WriteLine(WebWrapper.Patch(url, DiscordClient.token, message)); }
public void AssignRoleToMember(DiscordRole role, DiscordMember member) { string url = Endpoints.BaseAPI + Endpoints.Guilds + $"/{this.id}" + Endpoints.Members + $"/{member.ID}"; string message = JsonConvert.SerializeObject(new { roles = new string[] { role.id } }); Console.WriteLine(WebWrapper.Patch(url, DiscordClient.token, message)); }
private DiscordMessage SendActualMessage(string id, string message, DiscordMember recipient) { string url = Endpoints.BaseAPI + Endpoints.Channels + $"/{id}" + Endpoints.Messages; DiscordMessage toSend = Utils.GenerateMessage(message); try { var result = JObject.Parse(WebWrapper.Post(url, token, JsonConvert.SerializeObject(toSend).ToString())); DiscordMessage d = JsonConvert.DeserializeObject<DiscordMessage>(result.ToString()); d.Recipient = recipient; d.channel = PrivateChannels.Find(x => x.id == result["channel_id"].ToString()); d.author = Me; return d; } catch(Exception ex) { DebugLogger.Log($"Error ocurred while sending message to user, step 2: {ex.Message}", MessageLevel.Error); } return null; }
private void MessageCreateEvents(JObject message) { try { string tempChannelID = message["d"]["channel_id"].ToString(); var foundServerChannel = ServersList.Find(x => x.channels.Find(y => y.id == tempChannelID) != null); if (foundServerChannel == null) { var foundPM = PrivateChannels.Find(x => x.id == message["d"]["channel_id"].ToString()); DiscordPrivateMessageEventArgs dpmea = new DiscordPrivateMessageEventArgs(); dpmea.Channel = foundPM; dpmea.message = message["d"]["content"].ToString(); DiscordMember tempMember = new DiscordMember(); tempMember.user.username = message["d"]["author"]["username"].ToString(); tempMember.user.id = message["d"]["author"]["id"].ToString(); dpmea.author = tempMember; if (PrivateMessageReceived != null) PrivateMessageReceived(this, dpmea); } else { DiscordMessageEventArgs dmea = new DiscordMessageEventArgs(); dmea.Channel = foundServerChannel.channels.Find(y => y.id == tempChannelID); dmea.message_text = message["d"]["content"].ToString(); DiscordMember tempMember = new DiscordMember(); tempMember = foundServerChannel.members.Find(x => x.user.id == message["d"]["author"]["id"].ToString()); dmea.author = tempMember; DiscordMessage m = new DiscordMessage(); m.author = dmea.author; m.channel = dmea.Channel; m.content = dmea.message_text; m.id = message["d"]["id"].ToString(); m.RawJson = message; dmea.message = m; Regex r = new Regex("\\d+"); foreach (Match mm in r.Matches(dmea.message_text)) if (mm.Value == Me.user.id) if (MentionReceived != null) MentionReceived(this, dmea); if (MessageReceived != null) MessageReceived(this, dmea); KeyValuePair<string, DiscordMessage> toAdd = new KeyValuePair<string, DiscordMessage>(message["d"]["id"].ToString(), m); MessageLog.Add(toAdd); } } catch (Exception ex) { Console.WriteLine("!!! {0}", ex.Message); Console.Beep(100, 1000); } }
private void MessageCreateEvents(JObject message) { try { string tempChannelID = message["d"]["channel_id"].ToString(); var foundServerChannel = ServersList.Find(x => x.channels.Find(y => y.id == tempChannelID) != null); if (foundServerChannel == null) { if (message["d"]["author"]["id"].ToString() != Me.ID) { var foundPM = PrivateChannels.Find(x => x.id == message["d"]["channel_id"].ToString()); DiscordPrivateMessageEventArgs dpmea = new DiscordPrivateMessageEventArgs(); dpmea.Channel = foundPM; dpmea.message = message["d"]["content"].ToString(); DiscordMember tempMember = new DiscordMember(this); tempMember.Username = message["d"]["author"]["username"].ToString(); tempMember.ID = message["d"]["author"]["id"].ToString(); dpmea.author = tempMember; if (PrivateMessageReceived != null) PrivateMessageReceived(this, dpmea); } else { //if (DebugMessageReceived != null) // DebugMessageReceived(this, new DiscordDebugMessagesEventArgs { message = "Ignoring MESSAGE_CREATE for private channel for message sent from this client." }); } } else { DiscordMessageEventArgs dmea = new DiscordMessageEventArgs(); dmea.Channel = foundServerChannel.channels.Find(y => y.id == tempChannelID); dmea.message_text = message["d"]["content"].ToString(); DiscordMember tempMember = new DiscordMember(this); tempMember = foundServerChannel.members.Find(x => x.ID == message["d"]["author"]["id"].ToString()); dmea.author = tempMember; DiscordMessage m = new DiscordMessage(); m.author = dmea.author; m.channel = dmea.Channel; m.content = dmea.message_text; m.id = message["d"]["id"].ToString(); m.RawJson = message; m.timestamp = DateTime.Now; dmea.message = m; Regex r = new Regex("\\d+"); foreach (Match mm in r.Matches(dmea.message_text)) if (mm.Value == Me.ID) if (MentionReceived != null) MentionReceived(this, dmea); KeyValuePair<string, DiscordMessage> toAdd = new KeyValuePair<string, DiscordMessage>(message["d"]["id"].ToString(), m); MessageLog.Add(toAdd); if (MessageReceived != null) MessageReceived(this, dmea); } } catch (Exception ex) { DebugLogger.Log("Error ocurred during MessageCreateEvents: " + ex.Message, MessageLevel.Error); } }
//Special thanks to the node-discord developer, izy521, for helping me out with this :D public void SendMessageToUser(string message, DiscordMember member) { string initMessage = "{\"recipient_id\":" + member.user.id + "}"; var httpRequest = (HttpWebRequest)WebRequest.Create("https://discordapp.com/api/users/" + Me.user.id + "/channels"); httpRequest.Headers["authorization"] = token; httpRequest.ContentType = "application/json"; httpRequest.Method = "POST"; using (var sw = new StreamWriter(httpRequest.GetRequestStream())) { sw.Write(initMessage); sw.Flush(); sw.Close(); } try { var httpResponse = (HttpWebResponse)httpRequest.GetResponse(); using (var sr = new StreamReader(httpResponse.GetResponseStream())) { var result = JObject.Parse(sr.ReadToEnd()); SendActualMessage(result["id"].ToString(), message); } } catch { //shouldn't even have to worry about this.. } }