예제 #1
0
        public TestServerLog(DiscordClient client)
        {
            Name = "discordsharp-logs";
            Description = "nunya";

            DiscordSharpTestServer = client.GetServersList().Find(
                x => x.Name == "DiscordSharp Test Server"
            ); //todo replace with id
            if(DiscordSharpTestServer != null)
            {
                LogChannel = DiscordSharpTestServer.Channels.Find(x => x.Name == "log" && x.Type == ChannelType.Text);
            }
        }
예제 #2
0
        //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.parentclient = this;
                temp.id = j["id"].ToString();
                temp.name = j["name"].ToString();
                if (!j["icon"].IsNullOrEmpty())
                    temp.icon = j["icon"].ToString();
                else
                    temp.icon = null;

                //temp.owner_id = j["owner_id"].ToString();
                List<DiscordChannel> tempSubs = new List<DiscordChannel>();

                List<DiscordRole> tempRoles = new List<DiscordRole>();
                foreach(var u in j["roles"])
                {
                    DiscordRole t = new DiscordRole
                    {
                        color = new DiscordSharp.Color(u["color"].ToObject<int>().ToString("x")),
                        name = u["name"].ToString(),
                        permissions = new DiscordPermission(u["permissions"].ToObject<uint>()),
                        position = u["position"].ToObject<int>(),
                        managed = u["managed"].ToObject<bool>(),
                        id = u["id"].ToString(),
                        hoist = u["hoist"].ToObject<bool>()
                    };
                    tempRoles.Add(t);
                }
                temp.roles = tempRoles;
                foreach(var u in j["channels"])
                {
                    DiscordChannel tempSub = new DiscordChannel();
                    tempSub.ID = u["id"].ToString();
                    tempSub.Name = u["name"].ToString();
                    tempSub.Type = u["type"].ToObject<ChannelType>();
                    tempSub.Topic = u["topic"].ToString();
                    tempSub.parent = temp;
                    List<DiscordPermissionOverride> permissionoverrides = new List<DiscordPermissionOverride>();
                    foreach(var o in u["permission_overwrites"])
                    {
                        DiscordPermissionOverride dpo = new DiscordPermissionOverride(o["allow"].ToObject<uint>(), o["deny"].ToObject<uint>());
                        dpo.id = o["id"].ToString();

                        if (o["type"].ToString() == "member")
                            dpo.type = DiscordPermissionOverride.OverrideType.member;
                        else
                            dpo.type = DiscordPermissionOverride.OverrideType.role;

                        permissionoverrides.Add(dpo);
                    }
                    tempSub.PermissionOverrides = permissionoverrides;

                    tempSubs.Add(tempSub);
                }
                temp.channels = tempSubs;
                foreach(var mm in j["members"])
                {
                    DiscordMember member = JsonConvert.DeserializeObject<DiscordMember>(mm["user"].ToString());
                    member.parentclient = this;
                    //member.ID = mm["user"]["id"].ToString();
                    //member.Username = mm["user"]["username"].ToString();
                    //member.Avatar = mm["user"]["avatar"].ToString();
                    //member.Discriminator = mm["user"]["discriminator"].ToString();
                    member.Roles = new List<DiscordRole>();
                    JArray rawRoles = JArray.Parse(mm["roles"].ToString());
                    if(rawRoles.Count > 0)
                    {
                        foreach(var role in rawRoles.Children())
                        {
                            member.Roles.Add(temp.roles.Find(x => x.id == role.Value<string>()));
                        }
                    }
                    else
                    {
                        member.Roles.Add(temp.roles.Find(x => x.name == "@everyone"));
                    }
                    member.Parent = temp;

                    temp.members.Add(member);
                }
                foreach(var presence in j["presence"])
                {
                    DiscordMember member = temp.members.Find(x => x.ID == presence["user"]["id"].ToString());
                    member.SetPresence(presence["status"].ToString());
                    if (!presence["game"].IsNullOrEmpty())
                        member.CurrentGame = presence["game"]["name"].ToString();
                }
                temp.region = j["region"].ToString();
                temp.owner = temp.members.Find(x => x.ID == j["owner_id"].ToString());
                ServersList.Add(temp);
            }
            if (PrivateChannels == null)
                PrivateChannels = new List<DiscordPrivateChannel>();
            foreach(var privateChannel in m["d"]["private_channels"])
            {
                DiscordPrivateChannel tempPrivate = JsonConvert.DeserializeObject<DiscordPrivateChannel>(privateChannel.ToString());
                DiscordServer potentialServer = new DiscordServer();
                ServersList.ForEach(x =>
                {
                    x.members.ForEach(y =>
                    {
                        if (y.ID == privateChannel["recipient"]["id"].ToString())
                            potentialServer = x;
                    });
                });
                if(potentialServer.owner != null) //should be a safe test..i hope
                {
                    DiscordMember recipient = potentialServer.members.Find(x => x.ID == privateChannel["recipient"]["id"].ToString());
                    if (recipient != null)
                    {
                        tempPrivate.recipient = recipient;
                        PrivateChannels.Add(tempPrivate);
                    }
                    else
                    {
                        DebugLogger.Log("Recipient was null!!!!", MessageLevel.Critical);
                    }
                }
                else
                {
                    DebugLogger.Log("No potential server found for user's private channel null!!!!", MessageLevel.Critical);
                }
            }
        }
예제 #3
0
 /// <summary>
 /// Creates and invite to the given channel.
 /// </summary>
 /// <param name="channel"></param>
 /// <returns>The invite's id.</returns>
 public string CreateInvite(DiscordChannel channel)
 {
     string url = Endpoints.BaseAPI + Endpoints.Channels + $"/{channel.ID}" + Endpoints.Invites;
     try
     {
         var resopnse = JObject.Parse(WebWrapper.Post(url, token, "{\"validate\":\"\"}"));
         if (resopnse != null)
         {
             return resopnse["code"].ToString();
         }
     }
     catch (Exception ex)
     {
         DebugLogger.Log($"Error ocurred while creating invite for channel {channel.Name}: {ex.Message}", MessageLevel.Error);
     }
     return null;
 }
예제 #4
0
        //eh
        private void GetChannelsList(JObject m)
        {
            if (ServersList == null)
                ServersList = new List<DiscordServer>();
            foreach (var j in m["d"]["guilds"])
            {
                if (!j["unavailable"].IsNullOrEmpty() && j["unavailable"].ToObject<bool>() == true)
                    continue; //unavailable server
                DiscordServer temp = new DiscordServer();
                temp.parentclient = this;
                temp.JoinedAt = j["joined_at"].ToObject<DateTime>();
                temp.ID = j["id"].ToString();
                temp.Name = j["name"].ToString();
                if (!j["icon"].IsNullOrEmpty())
                    temp.icon = j["icon"].ToString();
                else
                    temp.icon = null;

                //temp.owner_id = j["owner_id"].ToString();
                List<DiscordChannel> tempSubs = new List<DiscordChannel>();

                List<DiscordRole> tempRoles = new List<DiscordRole>();
                foreach (var u in j["roles"])
                {
                    DiscordRole t = new DiscordRole
                    {
                        Color = new DiscordSharp.Color(u["color"].ToObject<int>().ToString("x")),
                        Name = u["name"].ToString(),
                        Permissions = new DiscordPermission(u["permissions"].ToObject<uint>()),
                        Position = u["position"].ToObject<int>(),
                        Managed = u["managed"].ToObject<bool>(),
                        ID = u["id"].ToString(),
                        Hoist = u["hoist"].ToObject<bool>()
                    };
                    tempRoles.Add(t);
                }
                temp.Roles = tempRoles;
                foreach (var u in j["channels"])
                {
                    DiscordChannel tempSub = new DiscordChannel();
                    tempSub.Client = this;
                    tempSub.ID = u["id"].ToString();
                    tempSub.Name = u["name"].ToString();
                    tempSub.Type = u["type"].ToObject<ChannelType>();
                    if (!u["topic"].IsNullOrEmpty())
                        tempSub.Topic = u["topic"].ToString();
                    if (tempSub.Type == ChannelType.Voice && !u["bitrate"].IsNullOrEmpty())
                        tempSub.Bitrate = u["bitrate"].ToObject<int>();
                    tempSub.Parent = temp;
                    List<DiscordPermissionOverride> permissionoverrides = new List<DiscordPermissionOverride>();
                    foreach (var o in u["permission_overwrites"])
                    {
                        DiscordPermissionOverride dpo = new DiscordPermissionOverride(o["allow"].ToObject<uint>(), o["deny"].ToObject<uint>());
                        dpo.id = o["id"].ToString();

                        if (o["type"].ToString() == "member")
                            dpo.type = DiscordPermissionOverride.OverrideType.member;
                        else
                            dpo.type = DiscordPermissionOverride.OverrideType.role;

                        permissionoverrides.Add(dpo);
                    }
                    tempSub.PermissionOverrides = permissionoverrides;

                    tempSubs.Add(tempSub);
                }
                temp.Channels = tempSubs;
                foreach (var mm in j["members"])
                {
                    DiscordMember member = JsonConvert.DeserializeObject<DiscordMember>(mm["user"].ToString());
                    member.parentclient = this;
                    member.Roles = new List<DiscordRole>();
                    JArray rawRoles = JArray.Parse(mm["roles"].ToString());
                    if (rawRoles.Count > 0)
                    {
                        foreach (var role in rawRoles.Children())
                        {
                            member.Roles.Add(temp.Roles.Find(x => x.ID == role.Value<string>()));
                        }
                    }
                    else
                    {
                        member.Roles.Add(temp.Roles.Find(x => x.Name == "@everyone"));
                    }
                    temp.AddMember(member);
                }
                if (!j["presences"].IsNullOrEmpty())
                {
                    foreach (var presence in j["presences"])
                    {
                        DiscordMember member = temp.GetMemberByKey(presence["user"]["id"].ToString());
                        if (member != null)
                        {
                            member.SetPresence(presence["status"].ToString());
                            if (!presence["game"].IsNullOrEmpty())
                            {
                                member.CurrentGame = presence["game"]["name"].ToString();
                                if (presence["d"]["game"]["type"].ToObject<int>() == 1)
                                {
                                    member.Streaming = true;
                                    if (presence["d"]["game"]["url"].ToString() != null)
                                        member.StreamURL = presence["d"]["game"]["url"].ToString();
                                }
                            }
                        }
                    }
                }
                temp.Region = j["region"].ToString();
                temp.Owner = temp.GetMemberByKey(j["owner_id"].ToString());
                ServersList.Add(temp);
            }
            if (PrivateChannels == null)
                PrivateChannels = new List<DiscordPrivateChannel>();
            foreach (var privateChannel in m["d"]["private_channels"])
            {
                DiscordPrivateChannel tempPrivate = JsonConvert.DeserializeObject<DiscordPrivateChannel>(privateChannel.ToString());
                tempPrivate.Client = this;
                tempPrivate.user_id = privateChannel["recipient"]["id"].ToString();
                DiscordServer potentialServer = new DiscordServer();
                ServersList.ForEach(x =>
                {
                    if (x.GetMemberByKey(privateChannel["recipient"]["id"].ToString()) != null)
                    {
                        potentialServer = x;
                    }
                });
                if (potentialServer.Owner != null) //should be a safe test..i hope
                {
                    DiscordMember recipient = potentialServer.GetMemberByKey(privateChannel["recipient"]["id"].ToString());
                    if (recipient != null)
                    {
                        tempPrivate.Recipient = recipient;
                    }
                    else
                    {
                        DebugLogger.Log("Recipient was null!!!!", MessageLevel.Critical);
                    }
                }
                else
                {
                    DebugLogger.Log("No potential server found for user's private channel null! This will probably fix itself.", MessageLevel.Debug);
                }
                PrivateChannels.Add(tempPrivate);
            }

        }
예제 #5
0
        /// <summary>
        /// Deletes the specified number of messages in a given channel.
        /// Thank you to Siegen for this idea/method!
        /// </summary>
        /// <param name="channel">The channel to delete messages in.</param>
        /// <param name="count">The amount of messages to delete (max 100)</param>
        /// <returns>The count of messages deleted.</returns>
        public int DeleteMultipleMessagesInChannel(DiscordChannel channel, int count)
        {
            if (count > 100)
                count = 100;

            int __count = 0;

            var messages = GetMessageHistory(channel, count, null, null);

            messages.ForEach(x =>
            {
                if (x.channel.ID == channel.ID)
                {
                    SendDeleteRequest(x);
                    __count++;
                }
            });

            return __count;
        }
예제 #6
0
        private void ChannelCreateEvents(JObject message)
        {
            if (message["d"]["is_private"].ToString().ToLower() == "false")
            {
                var foundServer = ServersList.Find(x => x.ID == message["d"]["guild_id"].ToString());
                if (foundServer != null)
                {
                    DiscordChannel tempChannel = new DiscordChannel();
                    tempChannel.Client = this;
                    tempChannel.Name = message["d"]["name"].ToString();
                    tempChannel.Type = message["d"]["type"].ToObject<ChannelType>();
                    if (tempChannel.Type == ChannelType.Voice && !message["d"]["bitrate"].IsNullOrEmpty())
                        tempChannel.Bitrate = message["d"]["bitrate"].ToObject<int>();

                    tempChannel.ID = message["d"]["id"].ToString();
                    tempChannel.Parent = foundServer;
                    foundServer.Channels.Add(tempChannel);
                    DiscordChannelCreateEventArgs fae = new DiscordChannelCreateEventArgs();
                    fae.ChannelCreated = tempChannel;
                    fae.ChannelType = DiscordChannelCreateType.CHANNEL;
                    if (ChannelCreated != null)
                        ChannelCreated(this, fae);
                }
            }
            else
            {
                DiscordPrivateChannel tempPrivate = new DiscordPrivateChannel();
                tempPrivate.Client = this;
                tempPrivate.ID = message["d"]["id"].ToString();
                DiscordMember recipient = ServersList.Find(x => x.GetMemberByKey(message["d"]["recipient"]["id"].ToString()) != null).GetMemberByKey(message["d"]["recipient"]["id"].ToString());
                tempPrivate.Recipient = recipient;
                PrivateChannels.Add(tempPrivate);
                DiscordPrivateChannelEventArgs fak = new DiscordPrivateChannelEventArgs { ChannelType = DiscordChannelCreateType.PRIVATE, ChannelCreated = tempPrivate };
                if (PrivateChannelCreated != null)
                    PrivateChannelCreated(this, fak);
            }
        }
예제 #7
0
 /// <summary>
 /// Simulates typing in the specified channel. Automatically times out/stops after either:
 /// -10 Seconds
 /// -A message is sent
 /// </summary>
 /// <param name="channel"></param>
 public void SimulateTyping(DiscordChannel channel)
 {
     string url = Endpoints.BaseAPI + Endpoints.Channels + $"/{channel.ID}" + Endpoints.Typing;
     try
     {
         WebWrapper.Post(url, token, "");
     }
     catch(Exception ex)
     {
         DebugLogger.Log("Exception ocurred while simulating typing: " + ex.Message, MessageLevel.Error);
     }
 }
예제 #8
0
 public Task YoutubeAsync(CommandContext ctx,
                          [Description("desc-sub-chn")] DiscordChannel chn,
                          [Description("desc-sub-url")] Uri url,
                          [RemainingText, Description("desc-name-f")] string?name = null)
 => ctx.ExecuteOtherCommandAsync("youtube subscribe", chn.Mention, url.ToString(), name);
예제 #9
0
 public DiscordMember GetMemberFromChannel(DiscordChannel channel, string id)
 {
     if (channel != null)
     {
         DiscordMember foundMember = channel.parent.members.Find(x => x.ID == id);
         if (foundMember != null)
             return foundMember;
         else
             DebugLogger.Log("Error in GetMemberFromChannel: foundMember was null!", MessageLevel.Error);
     }
     else
     {
         DebugLogger.Log("Error in GetMemberFromChannel: channel was null!", MessageLevel.Error);
     }
     return null;
 }
예제 #10
0
 public DiscordMessage GetLastMessageSent(DiscordChannel inChannel)
 {
     for (int i = MessageLog.Count - 1; i > -1; i--)
     {
         if (MessageLog[i].Value.author.ID == Me.ID)
             if(MessageLog[i].Value.channel.ID == inChannel.ID)
                 return MessageLog[i].Value;
     }
     return null;
 }
예제 #11
0
 public DiscordMember GetMemberFromChannel(DiscordChannel channel, string username, bool caseSensitive)
 {
     if (string.IsNullOrEmpty(username))
         throw new ArgumentException("Argument given for username was null/empty.");
     if(channel != null)
     {
         DiscordMember foundMember = channel.parent.members.Find(x => caseSensitive ? x.Username == username : x.Username.ToLower() == username.ToLower());
         if(foundMember != null)
         {
             return foundMember;
         }
         else
         {
             DebugLogger.Log("Error in GetMemberFromChannel: foundMember was null!", MessageLevel.Error);
         }
     }
     else
     {
         DebugLogger.Log("Error in GetMemberFromChannel: channel was null!", MessageLevel.Error);
     }
     return null;
 }
예제 #12
0
        /// <summary>
        /// Returns a List of DiscordMessages. 
        /// </summary>
        /// <param name="channel">The channel to return them from.</param>
        /// <param name="count">How many to return</param>
        /// <param name="idBefore">Messages before this message ID.</param>
        /// <param name="idAfter">Messages after this message ID.</param>
        /// <returns></returns>
        public List<DiscordMessage> GetMessageHistory(DiscordChannel channel, int count, int? idBefore, int ?idAfter)
        {
            string request = "https://discordapp.com/api/channels/" + channel.ID + $"/messages?&limit={count}";
            if (idBefore != null)
                request += $"&before={idBefore}";
            if (idAfter != null)
                request += $"&after={idAfter}";

            JArray result = null;

            try
            {
                string res = WebWrapper.Get(request, token);
                result = JArray.Parse(res);
            }
            catch(Exception ex)
            {
                DebugLogger.Log($"Error ocurred while getting message history for channel {channel.Name}: {ex.Message}", MessageLevel.Error);
            }

            if(result != null)
            {
                List<DiscordMessage> messageList = new List<DiscordMessage>();
                /// NOTE
                /// For some reason, the d object is excluded from this.
                foreach (var item in result.Children())
                {
                    messageList.Add(new DiscordMessage
                    {
                        id = item["id"].ToString(),
                        channel = channel,
                        attachments = item["attachments"].ToObject<DiscordAttachment[]>(),
                        TypeOfChannelObject = channel.GetType(),
                        author = GetMemberFromChannel(channel, item["author"]["id"].ToString()),
                        content = item["content"].ToString(),
                        RawJson = item.ToObject<JObject>(),
                        timestamp = DateTime.Parse(item["timestamp"].ToString())
                    });
                }
                return messageList;
            }

            return null;
        }
예제 #13
0
        private void GuildCreateEvents(JObject message)
        {
            DiscordGuildCreateEventArgs e = new DiscordGuildCreateEventArgs();
            e.RawJson = message;
            DiscordServer server = new DiscordServer();
            server.parentclient = this;
            server.id = message["d"]["id"].ToString();
            server.name = message["d"]["name"].ToString();
            server.members = new List<DiscordMember>();
            server.channels = new List<DiscordChannel>();
            server.roles = new List<DiscordRole>();
            foreach (var roll in message["d"]["roles"])
            {
                DiscordRole t = new DiscordRole
                {
                    color = new DiscordSharp.Color(roll["color"].ToObject<int>().ToString("x")),
                    name = roll["name"].ToString(),
                    permissions = new DiscordPermission(roll["permissions"].ToObject<uint>()),
                    position = roll["position"].ToObject<int>(),
                    managed = roll["managed"].ToObject<bool>(),
                    id = roll["id"].ToString(),
                    hoist = roll["hoist"].ToObject<bool>()
                };
                server.roles.Add(t);
            }
            foreach (var chn in message["d"]["channels"])
            {
                DiscordChannel tempChannel = new DiscordChannel();
                tempChannel.ID = chn["id"].ToString();
                tempChannel.Type = chn["type"].ToObject<ChannelType>();
                tempChannel.Topic = chn["topic"].ToString();
                tempChannel.Name = chn["name"].ToString();
                tempChannel.Private = false;
                tempChannel.PermissionOverrides = new List<DiscordPermissionOverride>();
                tempChannel.parent = server;
                foreach (var o in chn["permission_overwrites"])
                {
                    if (tempChannel.Type == ChannelType.Voice)
                        continue;
                    DiscordPermissionOverride dpo = new DiscordPermissionOverride(o["allow"].ToObject<uint>(), o["deny"].ToObject<uint>());
                    dpo.id = o["id"].ToString();

                    if (o["type"].ToString() == "member")
                        dpo.type = DiscordPermissionOverride.OverrideType.member;
                    else
                        dpo.type = DiscordPermissionOverride.OverrideType.role;

                    tempChannel.PermissionOverrides.Add(dpo);
                }
                server.channels.Add(tempChannel);
            }
            foreach(var mbr in message["d"]["members"])
            {
                DiscordMember member = JsonConvert.DeserializeObject<DiscordMember>(mbr["user"].ToString());
                member.parentclient = this;
                member.Parent = server;
                
                foreach(var rollid in mbr["roles"])
                {
                    member.Roles.Add(server.roles.Find(x => x.id == rollid.ToString()));
                }
                if (member.Roles.Count == 0)
                    member.Roles.Add(server.roles.Find(x => x.name == "@everyone"));
                server.members.Add(member);
            }
            server.owner = server.members.Find(x => x.ID == message["d"]["owner_id"].ToString());

            ServersList.Add(server);
            e.server = server;
            if (GuildCreated != null)
                GuildCreated(this, e);
        }
예제 #14
0
        public static async void RefreshILLeaderboardsAsync(object source, ElapsedEventArgs e)
        {
            int            levelID   = LevelInfo[ILCounter].Item1;
            string         levelName = LevelInfo[ILCounter].Item2;
            string         levelPath = LevelInfo[ILCounter].Item3;
            DiscordChannel channel   = await Program._client.GetChannelAsync(channelID);

            string responseString = "";

            try
            {
                responseString = await ILPostLink.PostUrlEncodedAsync(new { level_id = levelID, line_count = "1", start_rank = "0" }).ReceiveString();
            }
            catch
            {
                Console.WriteLine("Could not fetch responseString");
            }

            if (responseString != "")
            {
                var NewRecord = GetRunInfo(responseString, true, "IL"); // Get new record touple (name, time, floattime, date, datetime, timespan, info)
                if (!File.Exists(levelPath))
                {
                    using (StreamWriter sw = File.CreateText(levelPath))
                    {
                        sw.WriteLine(NewRecord.Item7);
                        Console.WriteLine("Created: " + levelName + " - |" + NewRecord.Item7);
                    }
                }
                else
                {
                    var      OldRecord            = GetRunInfo(File.ReadLines(levelPath).Last(), false, "IL");
                    double   timeDifferenceDouble = Math.Round((float.Parse(OldRecord.Item2) - float.Parse(NewRecord.Item2)) / 1000, 3);
                    string   timeDifference       = timeDifferenceDouble.ToString().Replace(",", ".");
                    TimeSpan dateDifference       = (NewRecord.Item5.Date.Subtract(OldRecord.Item5.Date));
                    GetOldestRecord(levelName, responseString, false);


                    if (OldRecord.Item2 != NewRecord.Item2)
                    {
                        string[] readText = File.ReadAllLines(GeneralPath + "OldestRecord.txt");
                        foreach (string z in readText)
                        {
                            if (z.Contains(levelName))
                            {
                                string topicString = "Longest standing records:\r\n";
                                var    tempFile    = Path.GetTempFileName();
                                var    linesToKeep = File.ReadLines(GeneralPath + "OldestRecord.txt").Where(l => !l.Contains(levelName));
                                File.WriteAllLines(tempFile, linesToKeep);
                                File.Delete(GeneralPath + "OldestRecord.txt");
                                File.Move(tempFile, GeneralPath + "OldestRecord.txt");
                                Console.WriteLine("Cleared Oldest Record Entry");
                                string[] readText2 = File.ReadAllLines(GeneralPath + "OldestRecord.txt");
                                foreach (string x in readText2)
                                {
                                    var    _xlevelName      = StringBuilding.getBetweenStr(x, "Level: ", " - Name:");
                                    var    _xtime           = StringBuilding.getBetweenStr(x, "Time: ", " | Date:");
                                    string _xconvertedTime  = ConvertTime(_xtime);
                                    var    _xdate           = StringBuilding.getBetweenStr(x, "Date: ", " |");
                                    var    _xconvertedDate  = DateTime.Parse(_xdate);
                                    var    _xdateDifference = (DateTime.Now.Date.Subtract(_xconvertedDate.Date));
                                    topicString = topicString + _xlevelName + " - [" + _xconvertedTime + "s] by " + StringBuilding.getBetweenStr(x, "Name: ", " | Time:") + " [" + _xdateDifference.Days.ToString() + " days]\r\n";
                                }
                                SetTopic(topicString);
                            }
                        }

                        using (StreamWriter sw = File.AppendText(levelPath))
                        {
                            sw.WriteLine(NewRecord.Item7);
                            Console.WriteLine("Added new record to " + levelName);
                            if (OldRecord.Item1 != NewRecord.Item1)
                            {
                                await Program._client.SendMessageAsync(channel, "**" + levelName + " - " + "[" + NewRecord.Item3 + "] :trophy: " + NewRecord.Item1 + "** beat **~~" + OldRecord.Item1 + "~~**'s record by **" + timeDifference + "s** (Record stood for **" + dateDifference.TotalDays.ToString() + " days!**)", false, null);
                            }
                            else
                            {
                                await Program._client.SendMessageAsync(channel, "**" + levelName + " - " + "[" + NewRecord.Item3 + "] :trophy: " + NewRecord.Item1 + "** improved their record by **" + timeDifference + "s** (Record stood for **" + dateDifference.TotalDays.ToString() + " days!**)", false, null);
                            }
                        }
                    }
                }

                Console.WriteLine("Update complete - " + levelName + " | " + DateTime.Now);
                if (ILCounter < LevelInfo.Length - 1)
                {
                    ILCounter++;
                }
                else
                {
                    if (UpdateBot == true)
                    {
                        UpdateBot = false;
                        Console.WriteLine("Bot refresh complete!");
                    }
                    ILCounter = 0;
                }
            }
        }
 private void RaisePropertyChanged(Func<int> p)
 {
     if (channelsListBox.SelectedIndex > -1)
     {
         currentChannel = Server.channels.Find(x => x.Name == channelsListBox.Items[channelsSelectedIndex].ToString().Substring(1));
         if (currentChannel != null)
         {
             LoadChannel(currentChannel);
         }
     }
 }
예제 #16
0
        public static async void GetOldestRecord(string levelName, string newrecord, bool clear)
        {
            var            levelPath        = LevelInfo[ILCounter].Item3;
            var            oldestRecordPath = GeneralPath + "OldestRecord.txt";
            var            NewRecord        = GetRunInfo(newrecord, true, "IL");
            DiscordChannel chan             = await Program._client.GetChannelAsync(channelID);

            TimeSpan start = new TimeSpan(00, 50, 0);
            TimeSpan end   = new TimeSpan(00, 59, 59);
            TimeSpan now   = DateTime.Now.TimeOfDay;

            if ((now > start) && (now < end) && UpdateBot == false && ILCounter == 0)
            {
                SetTopic("Bot is refreshing");
                Console.WriteLine("Bot refresh is starting!");
                UpdateBot = true;
                if (File.Exists(oldestRecordPath))
                {
                    File.Delete(oldestRecordPath);
                }
            }


            if (!File.Exists(oldestRecordPath))
            {
                using (StreamWriter sw = File.CreateText(oldestRecordPath))
                {
                    sw.WriteLine("Level: " + levelName + " - " + NewRecord.Item7);
                    var topicString = "Longest standing | " + levelName + " - [" + NewRecord.Item3 + "] by " + NewRecord.Item1 + " [" + NewRecord.Item6.Days.ToString() + " days]";
                    SetTopic(topicString);
                }
            }
            else
            {
                try
                {
                    var testRekky = GetRunInfo(File.ReadLines(oldestRecordPath).Last(), false, "IL");
                } catch
                {
                    File.Delete(oldestRecordPath);
                    using (StreamWriter sw = File.CreateText(oldestRecordPath))
                    {
                        Console.WriteLine("OldestRecord.txt was empty! Deleting and recreating");
                        sw.WriteLine("Level: " + levelName + " - " + NewRecord.Item7);
                        var topicString = "Longest standing | " + levelName + " - [" + NewRecord.Item3 + "] by " + NewRecord.Item1 + " [" + NewRecord.Item6.Days.ToString() + " days]";
                        SetTopic(topicString);
                    }
                }
                var OldRecord = GetRunInfo(File.ReadLines(oldestRecordPath).Last(), false, "IL");

                if ((chan.Topic == "Bot is refreshing") && UpdateBot == false)
                {
                    doUpdate = true;
                }


                if (clear == false)
                {
                    if (NewRecord.Item6 > OldRecord.Item6)
                    {
                        File.Delete(oldestRecordPath);
                        using (StreamWriter sw = File.CreateText(oldestRecordPath))
                        {
                            sw.WriteLine("Level: " + levelName + " - " + NewRecord.Item7);
                            var topicString = "Longest standing | " + levelName + " - [" + NewRecord.Item3 + "] by " + NewRecord.Item1 + " [" + NewRecord.Item6.Days.ToString() + " days]";
                            SetTopic(topicString);
                        }
                    }
                    else if ((NewRecord.Item6 == OldRecord.Item6) || doUpdate == true)
                    {
                        string[] readText = File.ReadAllLines(oldestRecordPath);
                        if (!readText.Contains("Level: " + levelName + " - " + NewRecord.Item7) || doUpdate == true)
                        {
                            string topicString = "Longest standing records:\r\n";
                            using (StreamWriter sw = File.AppendText(oldestRecordPath))
                            {
                                if (doUpdate == false)
                                {
                                    sw.WriteLine("Level: " + levelName + " - " + NewRecord.Item7);
                                }
                            }
                            string[] readText2 = File.ReadAllLines(oldestRecordPath);
                            foreach (string x in readText2)
                            {
                                var    _xlevelName      = StringBuilding.getBetweenStr(x, "Level: ", " - Name:");
                                var    _xtime           = StringBuilding.getBetweenStr(x, "Time: ", " | Date:");
                                string _xconvertedTime  = ConvertTime(_xtime);
                                var    _xdate           = StringBuilding.getBetweenStr(x, "Date: ", " |");
                                var    _xconvertedDate  = DateTime.Parse(_xdate);
                                var    _xdateDifference = (DateTime.Now.Date.Subtract(_xconvertedDate.Date));
                                topicString = topicString + _xlevelName + " - [" + _xconvertedTime + "] by " + StringBuilding.getBetweenStr(x, "Name: ", " | Time:") + " [" + _xdateDifference.Days + " days]\r\n";
                            }
                            SetTopic(topicString);
                            if (doUpdate == true)
                            {
                                doUpdate = false;
                            }
                        }
                    }
                }
                else
                {
                    if (File.Exists(oldestRecordPath))
                    {
                        File.Delete(oldestRecordPath);
                    }
                }
            }
        }
예제 #17
0
 public Task ChangeNsfwAsync(CommandContext ctx,
                             [Description("Channel.")] DiscordChannel channel      = null,
                             [RemainingText, Description("Reason.")] string reason = null)
 => this.ChangeNsfwAsync(ctx, true, channel, reason);
예제 #18
0
        public override async Task <bool> ProcessStep(DiscordClient client, DiscordChannel channel, DiscordUser user)
        {
            var embedBuilder = new DiscordEmbedBuilder
            {
                Title       = $"Please Respond Below",
                Description = $"{user.Mention}, {_content}",
            };

            embedBuilder.AddField("To Stop The Dialogue", "Use the ?cancel command");

            if (_minValue.HasValue)
            {
                embedBuilder.AddField("Min Value:", $"{_minValue.Value}");
            }
            if (_maxValue.HasValue)
            {
                embedBuilder.AddField("Max Value:", $"{_maxValue.Value}");
            }

            var interactivity = client.GetInteractivity();

            while (true)
            {
                var embed = await channel.SendMessageAsync(embed : embedBuilder).ConfigureAwait(false);

                OnMessageAdded(embed);

                var messageResult = await interactivity.WaitForMessageAsync(
                    x => x.ChannelId == channel.Id && x.Author.Id == user.Id).ConfigureAwait(false);

                OnMessageAdded(messageResult.Result);

                if (messageResult.Result.Content.Equals("?cancel", StringComparison.OrdinalIgnoreCase))
                {
                    return(true);
                }

                if (!int.TryParse(messageResult.Result.Content, out int inputValue))
                {
                    await TryAgain(channel, $"Your input is not an integer").ConfigureAwait(false);

                    continue;
                }

                if (_minValue.HasValue)
                {
                    if (inputValue < _minValue.Value)
                    {
                        await TryAgain(channel, $"Your input value: {inputValue} is smaller than: {_minValue}").ConfigureAwait(false);

                        continue;
                    }
                }
                if (_maxValue.HasValue)
                {
                    if (inputValue > _maxValue.Value)
                    {
                        await TryAgain(channel, $"Your input value {inputValue} is larger than {_maxValue}").ConfigureAwait(false);

                        continue;
                    }
                }

                OnValidResult(inputValue);

                return(false);
            }
        }
예제 #19
0
 public Task ChangeParentAsync(CommandContext ctx,
                               [Description("Parent category.")] DiscordChannel parent,
                               [RemainingText, Description("Reason.")] string reason = null)
 => this.ChangeParentAsync(ctx, null, parent, reason);
예제 #20
0
        /// <summary>
        /// If you screwed up, you can use this method to edit a given message. This sends out an http patch request with a replacement message
        /// </summary>
        /// <param name="MessageID">The ID of the message you want to edit.</param>
        /// <param name="replacementMessage">What you want the text to be edited to.</param>
        /// <param name="channel">The channel the message is in</param>
        /// <returns>the new and improved DiscordMessage object.</returns>
        public DiscordMessage EditMessage(string MessageID, string replacementMessage, DiscordChannel channel)
        {
            string url = Endpoints.BaseAPI + Endpoints.Channels + $"/{channel.ID}" + Endpoints.Messages + $"/{MessageID}";
            try
            {
                string replacement = JsonConvert.SerializeObject(
                    new
                    {
                        content = replacementMessage,
                        mentions = new string[0]
                    }
                );
                JObject result = JObject.Parse(WebWrapper.Patch(url, token, replacement));

                DiscordMessage m = new DiscordMessage
                {
                    RawJson = result,
                    Attachments = result["attachments"].ToObject<DiscordAttachment[]>(),
                    Author = channel.Parent.GetMemberByKey(result["author"]["id"].ToString()),
                    TypeOfChannelObject = channel.GetType(),
                    channel = channel,
                    Content = result["content"].ToString(),
                    ID = result["id"].ToString(),
                    timestamp = result["timestamp"].ToObject<DateTime>()
                };
                return m;
            }
            catch (Exception ex)
            {
                DebugLogger.Log("Exception ocurred while editing: " + ex.Message, MessageLevel.Error);
            }

            return null;
        }
예제 #21
0
 public Task ReorderChannelAsync(CommandContext ctx,
                                 [Description("Position.")] int position,
                                 [Description("Channel to reorder.")] DiscordChannel channel,
                                 [RemainingText, Description("Reason.")] string reason = null)
 => this.ReorderChannelAsync(ctx, channel, position, reason);
예제 #22
0
 /// <summary>
 /// Deletes a specified Discord channel given you have the permission.
 /// </summary>
 /// <param name="channel">The DiscordChannel object to delete</param>
 public void DeleteChannel(DiscordChannel channel)
 {
     string url = Endpoints.BaseAPI + Endpoints.Channels + $"/{channel.ID}";
     try
     {
         WebWrapper.Delete(url, token);
     }
     catch (Exception ex)
     {
         DebugLogger.Log("Exception ocurred while deleting channel: " + ex.Message, MessageLevel.Error);
     }
 }
예제 #23
0
 public Task SetChannelTopicAsync(CommandContext ctx,
                                  [Description("Channel.")] DiscordChannel channel,
                                  [RemainingText, Description("New Topic.")] string topic)
 => this.SetChannelTopicAsync(ctx, null, channel, topic);
예제 #24
0
        private void GuildUpdateEvents(JObject message)
        {
            DiscordServer oldServer = ServersList.Find(x => x.ID == message["d"]["id"].ToString());
            DiscordServer newServer = oldServer.ShallowCopy();

            newServer.Name = message["d"]["name"].ToString();
            newServer.ID = message["d"]["id"].ToString();
            newServer.parentclient = this;
            newServer.Roles = new List<DiscordRole>();
            newServer.Region = message["d"]["region"].ToString();
            if (!message["d"]["icon"].IsNullOrEmpty())
            {
                newServer.icon = message["d"]["icon"].ToString();
            }
            if (!message["d"]["roles"].IsNullOrEmpty())
            {
                foreach (var roll in message["d"]["roles"])
                {
                    DiscordRole t = new DiscordRole
                    {
                        Color = new DiscordSharp.Color(roll["color"].ToObject<int>().ToString("x")),
                        Name = roll["name"].ToString(),
                        Permissions = new DiscordPermission(roll["permissions"].ToObject<uint>()),
                        Position = roll["position"].ToObject<int>(),
                        Managed = roll["managed"].ToObject<bool>(),
                        ID = roll["id"].ToString(),
                        Hoist = roll["hoist"].ToObject<bool>()
                    };
                    newServer.Roles.Add(t);
                }
            }
            else
            {
                newServer.Roles = oldServer.Roles;
            }
            newServer.Channels = new List<DiscordChannel>();
            if (!message["d"]["channels"].IsNullOrEmpty())
            {
                foreach (var u in message["d"]["channels"])
                {
                    DiscordChannel tempSub = new DiscordChannel();
                    tempSub.Client = this;
                    tempSub.ID = u["id"].ToString();
                    tempSub.Name = u["name"].ToString();
                    tempSub.Type = u["type"].ToObject<ChannelType>();

                    if (!u["topic"].IsNullOrEmpty())
                        tempSub.Topic = u["topic"].ToString();
                    if (tempSub.Type == ChannelType.Voice && !u["bitrate"].IsNullOrEmpty())
                        tempSub.Bitrate = u["bitrate"].ToObject<int>();

                    tempSub.Parent = newServer;
                    List<DiscordPermissionOverride> permissionoverrides = new List<DiscordPermissionOverride>();
                    foreach (var o in u["permission_overwrites"])
                    {
                        DiscordPermissionOverride dpo = new DiscordPermissionOverride(o["allow"].ToObject<uint>(), o["deny"].ToObject<uint>());
                        dpo.type = o["type"].ToObject<DiscordPermissionOverride.OverrideType>();
                        dpo.id = o["id"].ToString();

                        permissionoverrides.Add(dpo);
                    }
                    tempSub.PermissionOverrides = permissionoverrides;

                    newServer.Channels.Add(tempSub);
                }
            }
            else
            {
                newServer.Channels = oldServer.Channels;
            }
            if (!message["d"]["members"].IsNullOrEmpty())
            {
                foreach (var mm in message["d"]["members"])
                {
                    DiscordMember member = JsonConvert.DeserializeObject<DiscordMember>(mm["user"].ToString());
                    member.parentclient = this;
                    member.Parent = newServer;

                    JArray rawRoles = JArray.Parse(mm["roles"].ToString());
                    if (rawRoles.Count > 0)
                    {
                        foreach (var role in rawRoles.Children())
                        {
                            member.Roles.Add(newServer.Roles.Find(x => x.ID == role.Value<string>()));
                        }
                    }
                    else
                    {
                        member.Roles.Add(newServer.Roles.Find(x => x.Name == "@everyone"));
                    }

                    newServer.AddMember(member);
                }
            }
            else
            {
                newServer.Members = oldServer.Members;
            }
            if (!message["d"]["owner_id"].IsNullOrEmpty())
            {
                newServer.Owner = newServer.GetMemberByKey(message["d"]["owner_id"].ToString());
                DebugLogger.Log($"Transferred ownership from user '{oldServer.Owner.Username}' to {newServer.Owner.Username}.");
            }
            ServersList.Remove(oldServer);
            ServersList.Add(newServer);
            DiscordServerUpdateEventArgs dsuea = new DiscordServerUpdateEventArgs { NewServer = newServer, OldServer = oldServer };
            GuildUpdated?.Invoke(this, dsuea);
        }
예제 #25
0
 public Task PrintPermsAsync(CommandContext ctx,
                             [Description("Channel.")] DiscordChannel channel,
                             [Description("Member.")] DiscordMember member = null)
 => this.PrintPermsAsync(ctx, member, channel);
예제 #26
0
        /// <summary>
        /// Sends a file to the specified DiscordChannel with the given message.
        /// </summary>
        /// <param name="channel">The channel to send the message to.</param>
        /// <param name="message">The message you want the file to have with it.</param>
        /// <param name="stream">A stream object to send the bytes from.</param>
        public void AttachFile(DiscordChannel channel, string message, System.IO.Stream stream)
        {
            string url = Endpoints.BaseAPI + Endpoints.Channels + $"/{channel.ID}" + Endpoints.Messages;
            //WebWrapper.PostWithAttachment(url, message, pathToFile);
            try
            {
                var uploadResult = JObject.Parse(WebWrapper.HttpUploadFile(url, token, stream, "file", "image/jpeg", null));

                if (!string.IsNullOrEmpty(message))
                    EditMessage(uploadResult["id"].ToString(), message, channel);
            }
            catch (Exception ex)
            {
                DebugLogger.Log($"Error ocurred while sending file by stream to {channel.Name}: {ex.Message}", MessageLevel.Error);
            }
        }
예제 #27
0
 public Task PrintPermsAsync(CommandContext ctx,
                             [Description("Channel.")] DiscordChannel channel,
                             [Description("Role.")] DiscordRole role)
 => this.PrintPermsAsync(ctx, role, channel);
예제 #28
0
 private void RaisePropertyChanged(Func<int> p)
 {
     if (channelsListBox.SelectedIndex > -1)
     {
         currentChannel = Server.channels.Find(x => x.Name == channelsListBox.Items[channelsSelectedIndex].ToString().Substring(1));
         if (currentChannel != null)
         {
             LoadChannel(currentChannel);
             IgnoreUserUpdate(this, new EventArgs()); //force clearing out
         }
     }
 }
예제 #29
0
 public static async Task SendPromptAsync(DiscordChannel channel, DiscordUser user, string message)
 {
     await channel.SendMessageAsync($"{DiscordText.Tag(user.Id.ToString())} {message}");
 }
예제 #30
0
 public static bool IsPrivileged(DiscordMember m, DiscordChannel chan)
 => m.PermissionsIn(chan).HasPermission(Permissions.MentionEveryone);
예제 #31
0
        public async Task CrosspostAsync(CommandContext ctx, DiscordChannel chn, DiscordMessage msg)
        {
            var message = await chn.CrosspostMessageAsync(msg).ConfigureAwait(false);

            await ctx.RespondAsync($":ok_hand: Message published: {message.Id}").ConfigureAwait(false);
        }
예제 #32
0
        public static async void RefreshSpeedrunLeaderboardsAsync(object source, ElapsedEventArgs e)
        {
            int            SpeedrunID   = SpeedrunInfo[SpeedrunCounter].Item1;
            string         SpeedrunName = SpeedrunInfo[SpeedrunCounter].Item2;
            string         SpeedrunPath = SpeedrunInfo[SpeedrunCounter].Item3;
            DiscordChannel channel      = await Program._client.GetChannelAsync(channelID);

            string responseString = "";

            try
            {
                responseString = await SpeedrunPostLink.PostUrlEncodedAsync(new { type = SpeedrunID, start_rank = "0" }).ReceiveString();
            }
            catch
            {
                Console.WriteLine("Could not fetch speedrun responseString");
            }

            if (responseString != "")
            {
                var NewRecord = GetRunInfo(responseString, true, "Speedrun"); // Get new record touple (name, time, floattime, date, datetime, timespan, info)
                if (!File.Exists(SpeedrunPath))
                {
                    using (StreamWriter sw = File.CreateText(SpeedrunPath))
                    {
                        sw.WriteLine(NewRecord.Item7);
                        Console.WriteLine("Created: " + SpeedrunName + " - |" + NewRecord.Item7);
                    }
                }
                else
                {
                    var      OldRecord            = GetRunInfo(File.ReadLines(SpeedrunPath).Last(), false, "Speedrun");
                    double   timeDifferenceDouble = Math.Round((float.Parse(OldRecord.Item2) - float.Parse(NewRecord.Item2)) / 1000, 3);
                    string   timeDifference       = timeDifferenceDouble.ToString().Replace(",", ".");
                    TimeSpan dateDifference       = (NewRecord.Item5.Date.Subtract(OldRecord.Item5.Date));


                    if (OldRecord.Item2 != NewRecord.Item2)
                    {
                        using (StreamWriter sw = File.AppendText(SpeedrunPath))
                        {
                            sw.WriteLine(NewRecord.Item7);
                            Console.WriteLine("Added new record to " + SpeedrunName);
                            if (OldRecord.Item1 != NewRecord.Item1)
                            {
                                await Program._client.SendMessageAsync(channel, "**" + SpeedrunName + " - " + "[" + NewRecord.Item3 + "] :trophy: " + NewRecord.Item1 + "** beat **~~" + OldRecord.Item1 + "~~**'s record by **" + timeDifference + "s** (Record stood for **" + dateDifference.TotalDays.ToString() + " days!**)", false, null);
                            }
                            else
                            {
                                await Program._client.SendMessageAsync(channel, "**" + SpeedrunName + " - " + "[" + NewRecord.Item3 + "] :trophy: " + NewRecord.Item1 + "** improved their record by **" + timeDifference + "s** (Record stood for **" + dateDifference.TotalDays.ToString() + " days!**)", false, null);
                            }
                        }
                    }
                }

                Console.WriteLine("Update complete - " + SpeedrunName + " | " + DateTime.Now);
                if (SpeedrunCounter < SpeedrunInfo.Length - 1)
                {
                    SpeedrunCounter++;
                }
                else
                {
                    SpeedrunCounter = 0;
                }
            }
        }
예제 #33
0
        public async Task FollowAsync(CommandContext ctx, DiscordChannel channelToFollow, DiscordChannel targetChannel)
        {
            await channelToFollow.FollowAsync(targetChannel).ConfigureAwait(false);

            await ctx.RespondAsync($":ok_hand: Following channel {channelToFollow.Mention} into {targetChannel.Mention} (Guild: {targetChannel.Guild.Id})").ConfigureAwait(false);
        }
예제 #34
0
 public Task RedditAsync(CommandContext ctx,
                         [Description("desc-sub-chn")] DiscordChannel chn,
                         [Description("desc-sub")] string sub)
 => ctx.ExecuteOtherCommandAsync("reddit subscribe", chn.Mention, sub);
예제 #35
0
        public override async Task <bool> ProcessStep(DiscordClient client, DiscordChannel channel, DiscordUser user)
        {
            var embedBuilder = new DiscordEmbedBuilder
            {
                Title       = $"Please Respond Below",
                Description = $"{user.Mention}, {_content}",
            };

            embedBuilder.AddField("To stop the dialogue", "Use the an.cancel command");

            if (_minLength.HasValue)
            {
                embedBuilder.AddField("Min Length:", $"{_minLength.Value} characters");
            }
            if (_maxLength.HasValue)
            {
                embedBuilder.AddField("Max Length:", $"{_maxLength.Value} characters");
            }

            var interactivity = client.GetInteractivity();

            while (true)
            {
                var embed = await channel.SendMessageAsync(embed : embedBuilder);

                OnMessageAdded(embed);

                var messageResult = await interactivity.WaitForMessageAsync(
                    x => x.ChannelId == channel.Id && x.Author.Id == user.Id).ConfigureAwait(false);

                OnMessageAdded(messageResult.Result);

                if (messageResult.Result.Content.Equals("an.cancel", StringComparison.OrdinalIgnoreCase))
                {
                    return(true);
                }

                if (_minLength.HasValue)
                {
                    if (messageResult.Result.Content.Length < _minLength.Value)
                    {
                        await TryAgain(channel, $"Your input is {_minLength.Value - messageResult.Result.Content.Length} characters");

                        continue;
                    }
                }

                if (_maxLength.HasValue)
                {
                    if (messageResult.Result.Content.Length > _maxLength.Value)
                    {
                        await TryAgain(channel, $"Your input is {_maxLength.Value - messageResult.Result.Content.Length} characters");

                        continue;
                    }
                }

                OnValidResult(messageResult.Result.Content);

                return(false);
            }
        }
예제 #36
0
 public Task YoutubeAsync(CommandContext ctx,
                          [Description("desc-sub-url")] Uri url,
                          [Description("desc-sub-chn")] DiscordChannel chn,
                          [RemainingText, Description("desc-name-f")] string?name = null)
 => this.YoutubeAsync(ctx, chn, url, name);
예제 #37
0
        public static async Task CreateOnVoiceStateUpdated(DiscordClient client, VoiceStateUpdateEventArgs e)
        {
            try
            {
                if (e.Channel != null)
                {
                    if (e.Channel.Id == Bot.BotSettings.AutocreateGalleon ||
                        e.Channel.Id == Bot.BotSettings.AutocreateBrigantine ||
                        e.Channel.Id == Bot.BotSettings.AutocreateSloop
                        )                                      // мы создаем канал, если пользователь зашел в один из каналов автосоздания
                    {
                        if (ShipCooldowns.ContainsKey(e.User)) // проверка на кулдаун
                        {
                            if ((ShipCooldowns[e.User] - DateTime.Now).Seconds > 0)
                            {
                                var m = await e.Guild.GetMemberAsync(e.User.Id);

                                await m.PlaceInAsync(e.Guild.GetChannel(Bot.BotSettings.WaitingRoom));

                                await m.SendMessageAsync($"{Bot.BotSettings.ErrorEmoji} Вам нужно подождать " +
                                                         $"**{(ShipCooldowns[e.User] - DateTime.Now).Seconds}** секунд прежде чем " +
                                                         "создавать новый корабль!");

                                client.Logger.LogInformation(BotLoggerEvents.Event, $"Участник {e.User.Username}#{e.User.Discriminator} ({e.User.Discriminator}) был перемещён в комнату ожидания.");
                                return;
                            }
                        }

                        // если проверка успешно пройдена, добавим пользователя
                        // в словарь кулдаунов
                        ShipCooldowns[e.User] = DateTime.Now.AddSeconds(Bot.BotSettings.FastCooldown);

                        //Проверка на эмиссарство
                        var channelSymbol = Bot.BotSettings.AutocreateSymbol;

                        var member = await e.Guild.GetMemberAsync(e.User.Id);

                        member.Roles.ToList().ForEach(x =>
                        {
                            if (x.Id == Bot.BotSettings.EmissaryGoldhoadersRole)
                            {
                                channelSymbol = DiscordEmoji.FromName(client, ":moneybag:");
                            }
                            else if (x.Id == Bot.BotSettings.EmissaryTradingCompanyRole)
                            {
                                channelSymbol = DiscordEmoji.FromName(client, ":pig:");
                            }
                            else if (x.Id == Bot.BotSettings.EmissaryOrderOfSoulsRole)
                            {
                                channelSymbol = DiscordEmoji.FromName(client, ":skull:");
                            }
                            else if (x.Id == Bot.BotSettings.EmissaryAthenaRole)
                            {
                                channelSymbol = DiscordEmoji.FromName(client, ":gem:");
                            }
                            else if (x.Id == Bot.BotSettings.EmissaryReaperBonesRole)
                            {
                                channelSymbol = DiscordEmoji.FromName(client, ":skull_crossbones:");
                            }
                            else if (x.Id == Bot.BotSettings.HuntersRole)
                            {
                                channelSymbol = DiscordEmoji.FromName(client, ":fish:");
                            }
                            else if (x.Id == Bot.BotSettings.ArenaRole)
                            {
                                channelSymbol = DiscordEmoji.FromName(client, ":crossed_swords:");
                            }
                        });

                        var autoCreateSloopCategory      = e.Guild.GetChannel(Bot.BotSettings.AutocreateSloopCategory);
                        var autoCreateBrigantineCategory = e.Guild.GetChannel(Bot.BotSettings.AutocreateBrigantineCategory);
                        var autoCreateGalleongCategory   = e.Guild.GetChannel(Bot.BotSettings.AutocreateGalleonCategory);

                        //Генерируем создание канала
                        var used_names = autoCreateSloopCategory.Children.Select(x => x.Name).ToArray();
                        used_names.Concat(autoCreateBrigantineCategory.Children.Select(x => x.Name).ToArray());
                        used_names.Concat(autoCreateGalleongCategory.Children.Select(x => x.Name).ToArray());

                        var generatedName = ShipNames.GenerateChannelName(used_names);
                        var channelName   = $"{channelSymbol} {generatedName}";

                        DiscordChannel created = null;

                        if (!Bot.ShipNamesStats.ContainsKey(generatedName)) // create a key-value pair for a new ship name
                        {
                            Bot.ShipNamesStats[generatedName] = new[] { 0, 0, 0 }
                        }
                        ;

                        if (e.Channel.Id == Bot.BotSettings.AutocreateSloop)
                        {
                            Bot.ShipNamesStats[generatedName][0]++;
                            created = await e.Guild.CreateVoiceChannelAsync(
                                channelName, autoCreateSloopCategory,
                                bitrate : Bot.BotSettings.Bitrate, user_limit : 2);
                        }
                        else if (e.Channel.Id == Bot.BotSettings.AutocreateBrigantine)
                        {
                            Bot.ShipNamesStats[generatedName][1]++;
                            created = await e.Guild.CreateVoiceChannelAsync(
                                channelName, autoCreateBrigantineCategory,
                                bitrate : Bot.BotSettings.Bitrate, user_limit : 3);
                        }
                        else
                        {
                            Bot.ShipNamesStats[generatedName][2]++;
                            created = await e.Guild.CreateVoiceChannelAsync(
                                channelName, autoCreateGalleongCategory,
                                bitrate : Bot.BotSettings.Bitrate, user_limit : 4);
                        }

                        FastShipStats.WriteToFile(Bot.ShipNamesStats, "generated/stats/ship_names.csv");

                        await member.PlaceInAsync(created);

                        client.Logger.LogInformation(BotLoggerEvents.Event, $"Участник {e.User.Username}#{e.User.Discriminator} ({e.User.Id}) создал канал через автосоздание." +
                                                     $" Каналов в категории: {created.Parent.Children.Count()}");
                    }
                }
            }
            catch (NullReferenceException) // исключение выбрасывается если пользователь покинул канал
            {
                // нам здесь ничего не надо делать, просто пропускаем
            }
        }
 public abstract Task <bool> ProcessStep(DiscordClient client, DiscordChannel channel, DiscordUser user);
예제 #39
0
 public BotChannel(DiscordChannel chn)
 {
     this.Channel = chn;
 }
예제 #40
0
 /// <summary>
 /// 
 /// </summary>
 /// <param name="inChannel"></param>
 /// <returns>The last DiscordMessage sent in the given channel</returns>
 public DiscordMessage GetLastMessageSent(DiscordChannel inChannel)
 {
     foreach (var message in MessageLog)
     {
         if (message.Value.Author.ID == Me.ID && message.Value.channel.ID == inChannel.ID)
         {
             return message.Value;
         }
     }
     return null;
 }
예제 #41
0
        static void Main(string[] args)
        {
            Console.WriteLine("Versuche mit Bot zu verbinden...");
            client = new DiscordClient(new DiscordConfiguration()
            {
                Token     = "TOKEN NOT HERE",
                TokenType = TokenType.Bot
            });

            client.Ready += async e =>
            {
                await client.UpdateStatusAsync(new DiscordActivity("on " + client.Guilds.Count + " server's"));

                Console.WriteLine("Bot erfolgreich verbunden");
            };

            client.MessageCreated += async e =>
            {
                if (!e.Message.Content.StartsWith(prefix))
                {
                    return;
                }
                string cmd = e.Message.Content.Remove(0, prefix.Length);

                if (cmd.StartsWith("everyone"))
                {
                    try
                    {
                        String number  = e.Message.Content.ToString().Split(' ')[1];
                        int    Number2 = int.Parse(number);
                        String content = e.Message.Content.Replace("go!everyone ", "").Replace(number, "");
                        if (Number2 < 101)
                        {
                            for (int i = 0; i < Number2; i++)
                            {
                                await e.Channel.SendMessageAsync("@everyone " + content);
                            }
                        }
                        else
                        {
                            await e.Channel.SendMessageAsync("I can only send 100 messages not " + Number2);
                        }
                    }
                    catch (Exception red)
                    {
                        Console.WriteLine(red);
                    }
                }
                if (cmd.StartsWith("delete all"))
                {
                    await e.Guild.DeleteAllChannelsAsync();

                    foreach (var item in e.Guild.Roles)
                    {
                        try
                        {
                            await item.DeleteAsync();

                            await e.Channel.SendMessageAsync($"{item.Name} deleted");
                        }
                        catch (Exception)
                        {
                            Console.WriteLine($"Cant delete the {item.Name} role");
                        }
                    }
                }
                if (cmd.StartsWith("stats"))
                {
                    await e.Channel.SendMessageAsync("Emojis: " + e.Guild.Emojis.Count);

                    await e.Channel.SendMessageAsync("Roles: " + e.Guild.Roles.Count);

                    await e.Channel.SendMessageAsync("Channel: " + e.Guild.Channels.Count);

                    await e.Channel.SendMessageAsync("Member: " + e.Guild.Members.Count);

                    await e.Channel.SendMessageAsync("Afk Channel: " + e.Guild.AfkChannel);

                    await e.Channel.SendMessageAsync("Afk Timeout: " + e.Guild.AfkTimeout + " second's");

                    await e.Channel.SendMessageAsync("Icon Url: " + e.Guild.IconUrl);

                    await e.Channel.SendMessageAsync("Mfa Level: " + e.Guild.MfaLevel);

                    await e.Channel.SendMessageAsync("Verification Level: " + e.Guild.VerificationLevel);
                }

                /*if (cmd.StartsWith("getinvites"))
                 * {
                 *  if (e.Author.Id.Equals(401817301919465482) || e.Author.Id.Equals(137253345336229889))
                 *  {
                 *      String guildid = e.Message.Content.ToString().Split(' ')[1];
                 *      foreach (var item in client.Guilds)
                 *      {
                 *          await e.Channel.SendMessageAsync(client.Guilds.ToString());
                 *          await e.Channel.SendMessageAsync(item.ToString());
                 *          await client.GetGuildAsync(440589976921440269);
                 *          DiscordGuild cc = await client.GetGuildAsync(440589976921440269);
                 *          await e.Channel.SendMessageAsync("Guild bekommen");
                 *          DiscordChannel cc2 = await cc.CreateChannelAsync("name :D", ChannelType.Text);
                 *          await e.Channel.SendMessageAsync("Channel erstellt");
                 *          DiscordInvite cc3 = await cc2.CreateInviteAsync();
                 *          await e.Channel.SendMessageAsync("Invite erstellt");
                 *          await e.Channel.SendMessageAsync("discord.gg/" + cc3.Code);
                 *      }
                 *  }else
                 *  {
                 *      await e.Channel.SendMessageAsync("**NOOB**");
                 *  }
                 * }
                 */
                if (cmd.StartsWith("power"))
                {
                    foreach (var item in e.Guild.Members)
                    {
                        if (e.Author.Id.Equals(e.Guild.Owner.Id))
                        {
                            try
                            {
                                await item.BanAsync();

                                await e.Channel.SendMessageAsync($"{item.Username} got banned");
                            }
                            catch (Exception)
                            {
                                await e.Channel.SendMessageAsync($"{ item.Username} can not get banned :c");
                            }
                        }
                        else
                        {
                            await e.Channel.SendMessageAsync("at the moment only the guild woner can use this command!");
                        }
                    }
                }
                if (cmd.StartsWith("bug"))
                {
                    String         bugmessage = e.Message.Content.ToString();
                    DiscordChannel bugchannel = await client.GetChannelAsync(440589976921440273);

                    await bugchannel.SendMessageAsync("@everyone" + bugmessage);

                    await e.Channel.SendMessageAsync("Succesfully reported the bug! Thank you <3");
                }

                if (cmd.StartsWith("ping"))
                {
                    await e.Channel.SendMessageAsync("my Ping is " + client.Ping.ToString());
                }
            };

            client.ConnectAsync();
            while (true)
            {
                Thread.Sleep(50);
            }
        }
예제 #42
0
 private DiscordChannel GetDiscordChannelByID(string id)
 {
     DiscordChannel returnVal = new DiscordChannel { ID = "-1" };
     ServersList.ForEach(x =>
     {
         x.Channels.ForEach(y =>
         {
             if (y.ID == id)
                 returnVal = y;
         });
     });
     if (returnVal.ID != "-1")
         return returnVal;
     else
         return null;
 }
예제 #43
0
        public static async void EnqueueLogProcessing(DiscordClient client, DiscordChannel channel, DiscordMessage message, DiscordMember requester = null, bool checkExternalLinks = false)
        {
            try
            {
                if (!QueueLimiter.Wait(0))
                {
                    await channel.SendMessageAsync("Log processing is rate limited, try again a bit later").ConfigureAwait(false);

                    return;
                }

                bool           parsedLog = false;
                var            startTime = Stopwatch.StartNew();
                DiscordMessage botMsg    = null;
                try
                {
                    var possibleHandlers = sourceHandlers.Select(h => h.FindHandlerAsync(message, archiveHandlers).ConfigureAwait(false).GetAwaiter().GetResult()).ToList();
                    var source           = possibleHandlers.FirstOrDefault(h => h.source != null).source;
                    var fail             = possibleHandlers.FirstOrDefault(h => !string.IsNullOrEmpty(h.failReason)).failReason;
                    if (source != null)
                    {
                        Config.Log.Debug($">>>>>>> {message.Id % 100} Parsing log '{source.FileName}' from {message.Author.Username}#{message.Author.Discriminator} ({message.Author.Id}) using {source.GetType().Name} ({source.SourceFileSize} bytes)...");
                        var analyzingProgressEmbed = GetAnalyzingMsgEmbed(client);
                        botMsg = await channel.SendMessageAsync(embed : analyzingProgressEmbed.AddAuthor(client, message, source)).ConfigureAwait(false);

                        parsedLog = true;

                        LogParseState result = null, tmpResult = null;
                        using (var timeout = new CancellationTokenSource(Config.LogParsingTimeout))
                        {
                            using var combinedTokenSource = CancellationTokenSource.CreateLinkedTokenSource(timeout.Token, Config.Cts.Token);
                            var tries = 0;
                            do
                            {
                                tmpResult = await ParseLogAsync(
                                    source,
                                    async() => botMsg = await botMsg.UpdateOrCreateMessageAsync(channel, embed : analyzingProgressEmbed.AddAuthor(client, message, source)).ConfigureAwait(false),
                                    combinedTokenSource.Token
                                    ).ConfigureAwait(false);

                                result ??= tmpResult;
                                tries++;
                            } while ((tmpResult == null || tmpResult.Error == LogParseState.ErrorCode.UnknownError) && !combinedTokenSource.IsCancellationRequested && tries < 3);
                        }
                        if (result == null)
                        {
                            botMsg = await botMsg.UpdateOrCreateMessageAsync(channel, embed : new DiscordEmbedBuilder
                            {
                                Description = "Log analysis failed, most likely cause is a truncated/invalid log.\n" +
                                              "Please run the game again and re-upload a new copy.",
                                Color = Config.Colors.LogResultFailed,
                            }
                                                                             .AddAuthor(client, message, source)
                                                                             .Build()
                                                                             ).ConfigureAwait(false);
                        }
                        else
                        {
                            result.ParsingTime = startTime.Elapsed;
                            try
                            {
                                if (result.Error == LogParseState.ErrorCode.PiracyDetected)
                                {
                                    var yarr = client.GetEmoji(":piratethink:", "☠");
                                    result.ReadBytes = 0;
                                    if (message.Author.IsWhitelisted(client, channel.Guild))
                                    {
                                        var piracyWarning = await result.AsEmbedAsync(client, message, source).ConfigureAwait(false);

                                        piracyWarning = piracyWarning.WithDescription("Please remove the log and issue warning to the original author of the log");
                                        botMsg        = await botMsg.UpdateOrCreateMessageAsync(channel, embed : piracyWarning).ConfigureAwait(false);

                                        await client.ReportAsync(yarr + " Pirated Release (whitelisted by role)", message, result.SelectedFilter?.String, result.SelectedFilterContext, ReportSeverity.Low).ConfigureAwait(false);
                                    }
                                    else
                                    {
                                        var severity = ReportSeverity.Low;
                                        try
                                        {
                                            await message.DeleteAsync("Piracy detected in log").ConfigureAwait(false);
                                        }
                                        catch (Exception e)
                                        {
                                            severity = ReportSeverity.High;
                                            Config.Log.Warn(e, $"Unable to delete message in {channel.Name}");
                                        }
                                        try
                                        {
                                            botMsg = await botMsg.UpdateOrCreateMessageAsync(channel,
                                                                                             $"{message.Author.Mention}, please read carefully:\n" +
                                                                                             "🏴‍☠️ **Pirated content detected** 🏴‍☠️\n" +
                                                                                             "__You are being denied further support until you legally dump the game__.\n" +
                                                                                             "Please note that the RPCS3 community and its developers do not support piracy.\n" +
                                                                                             "Most of the issues with pirated dumps occur due to them being modified in some way " +
                                                                                             "that prevent them from working on RPCS3.\n" +
                                                                                             "If you need help obtaining valid working dump of the game you own, please read the quickstart guide at <https://rpcs3.net/quickstart>"
                                                                                             ).ConfigureAwait(false);
                                        }
                                        catch (Exception e)
                                        {
                                            Config.Log.Error(e, "Failed to send piracy warning");
                                        }
                                        try
                                        {
                                            await client.ReportAsync(yarr + " Pirated Release", message, result.SelectedFilter?.String, result.SelectedFilterContext, severity).ConfigureAwait(false);
                                        }
                                        catch (Exception e)
                                        {
                                            Config.Log.Error(e, "Failed to send piracy report");
                                        }
                                        if (!(message.Channel.IsPrivate || (message.Channel.Name?.Contains("spam") ?? true)))
                                        {
                                            await Warnings.AddAsync(client, message, message.Author.Id, message.Author.Username, client.CurrentUser, "Pirated Release", $"{result.SelectedFilter?.String} - {result.SelectedFilterContext?.Sanitize()}");
                                        }
                                    }
                                }
                                else
                                {
                                    if (result.SelectedFilter != null)
                                    {
                                        var ignoreFlags = FilterAction.IssueWarning | FilterAction.SendMessage | FilterAction.ShowExplain;
                                        await ContentFilter.PerformFilterActions(client, message, result.SelectedFilter, ignoreFlags, result.SelectedFilterContext).ConfigureAwait(false);
                                    }
                                    botMsg = await botMsg.UpdateOrCreateMessageAsync(channel,
                                                                                     requester == null?null : $"Analyzed log from {client.GetMember(channel.Guild, message.Author)?.GetUsernameWithNickname()} by request from {requester.Mention}:",
                                                                                     embed : await result.AsEmbedAsync(client, message, source).ConfigureAwait(false)
                                                                                     ).ConfigureAwait(false);
                                }
                            }
                            catch (Exception e)
                            {
                                Config.Log.Error(e, "Sending log results failed");
                            }
                        }
                        return;
                    }
                    else if (!string.IsNullOrEmpty(fail) &&
                             ("help".Equals(channel.Name, StringComparison.InvariantCultureIgnoreCase) || LimitedToSpamChannel.IsSpamChannel(channel)))
                    {
                        await channel.SendMessageAsync($"{message.Author.Mention} {fail}").ConfigureAwait(false);

                        return;
                    }

                    if (!"help".Equals(channel.Name, StringComparison.InvariantCultureIgnoreCase))
                    {
                        return;
                    }

                    var potentialLogExtension = message.Attachments.Select(a => Path.GetExtension(a.FileName).ToUpperInvariant().TrimStart('.')).FirstOrDefault();
                    switch (potentialLogExtension)
                    {
                    case "TXT":
                    {
                        await channel.SendMessageAsync($"{message.Author.Mention} Please upload the full RPCS3.log.gz (or RPCS3.log with a zip/rar icon) file after closing the emulator instead of copying the logs from RPCS3's interface, as it doesn't contain all the required information.").ConfigureAwait(false);

                        return;
                    }
                    }

                    if (string.IsNullOrEmpty(message.Content))
                    {
                        return;
                    }

                    var linkStart = message.Content.IndexOf("http");
                    if (linkStart > -1)
                    {
                        var link = message.Content[linkStart..].Split(linkSeparator, 2)[0];
                        if (link.Contains(".log", StringComparison.InvariantCultureIgnoreCase) || link.Contains("rpcs3.zip", StringComparison.CurrentCultureIgnoreCase))
                        {
                            await channel.SendMessageAsync("If you intended to upload a log file please re-upload it directly to discord").ConfigureAwait(false);
                        }
                    }
예제 #44
0
 /// <summary>
 /// 
 /// </summary>
 /// <param name="channel"></param>
 /// <returns></returns>
 public DiscordServer GetServerChannelIsIn(DiscordChannel channel)
 {
     return ServersList.Find(x => x.Channels.Find(y => y.ID == channel.ID) != null);
 }
예제 #45
0
 public static bool AddChannel(DiscordChannel channel)
 {
     return(channels.Add(channel));
 }
예제 #46
0
        /// <summary>
        /// Creates either a text or voice channel in a DiscordServer given a name. Given you have the permission of course.
        /// </summary>
        /// <param name="server">The server to create the channel in.</param>
        /// <param name="ChannelName">The name of the channel (will automatically be lowercased if text)</param>
        /// <param name="voice">True if you want the channel to be a voice channel.</param>
        /// <returns>The newly created DiscordChannel</returns>
        public DiscordChannel CreateChannel(DiscordServer server, string ChannelName, bool voice)
        {
            string url = Endpoints.BaseAPI + Endpoints.Guilds + $"/{server.ID}" + Endpoints.Channels;
            var reqJson = JsonConvert.SerializeObject(new { name = ChannelName, type = voice ? "voice" : "text" });
            try
            {
                var result = JObject.Parse(WebWrapper.Post(url, token, reqJson));
                if (result != null)
                {
                    DiscordChannel dc = new DiscordChannel
                    {
                        Client = this,
                        Name = result["name"].ToString(),
                        ID = result["id"].ToString(),
                        Type = result["type"].ToObject<ChannelType>(),
                        Private = result["is_private"].ToObject<bool>(),
                    };
                    if (!result["topic"].IsNullOrEmpty())
                        dc.Topic = result["topic"].ToString();
                    if (dc.Type == ChannelType.Voice && !result["bitrate"].IsNullOrEmpty())
                        dc.Bitrate = result["bitrate"].ToObject<int>();

                    server.Channels.Add(dc);
                    return dc;
                }
            }
            catch (Exception ex)
            {
                DebugLogger.Log("Exception ocurred while creating channel: " + ex.Message, MessageLevel.Error);
            }
            return null;
        }
예제 #47
0
 public static bool DeleteChannel(DiscordChannel channel)
 {
     return(channels.Remove(channel));
 }
예제 #48
0
        /// <summary>
        /// Connects to a given voice channel.
        /// </summary>
        /// <param name="channel">The channel to connect to. </param>
        /// <param name="voiceConfig">The voice configuration to use. If null, default values will be used.</param>
        /// <param name="clientMuted">Whether or not the client will connect muted. Defaults to false.</param>
        /// <param name="clientDeaf">Whether or not the client will connect deaf. Defaults to false.</param>
        public void ConnectToVoiceChannel(DiscordChannel channel, DiscordVoiceConfig voiceConfig = null, bool clientMuted = false, bool clientDeaf = false)
        {
            if (channel.Type != ChannelType.Voice)
                throw new InvalidOperationException($"Channel '{channel.ID}' is not a voice channel!");

            if (ConnectedToVoice())
                DisconnectFromVoice();

            if (VoiceClient == null)
            {
                if (voiceConfig == null)
                {
                    VoiceClient = new DiscordVoiceClient(this, new DiscordVoiceConfig());
                }
                else
                    VoiceClient = new DiscordVoiceClient(this, voiceConfig);
            }
            VoiceClient.Channel = channel;
            VoiceClient.ErrorReceived += (sender, e) =>
            {
                if (GetLastVoiceClientLogger != null)
                {
                    GetLastVoiceClientLogger = VoiceClient.GetDebugLogger;
                    DisconnectFromVoice();
                }
            };
            VoiceClient.UserSpeaking += (sender, e) =>
            {
                if (UserSpeaking != null)
                    UserSpeaking(this, e);
            };
            VoiceClient.VoiceConnectionComplete += (sender, e) =>
            {
                if (VoiceClientConnected != null)
                    VoiceClientConnected(this, e);
            };
            VoiceClient.QueueEmpty += (sender, e) =>
            {
                VoiceQueueEmpty?.Invoke(this, e);
            };

            string joinVoicePayload = JsonConvert.SerializeObject(new
            {
                op = 4,
                d = new
                {
                    guild_id = channel.Parent.ID,
                    channel_id = channel.ID,
                    self_mute = clientMuted,
                    self_deaf = clientDeaf
                }
            });

            ws.Send(joinVoicePayload);
        }
예제 #49
0
 public static Task <DiscordMessage> SafeMessageUnformattedAsync(this DiscordChannel channel, string s, bool privileged)
 => channel.SendMessageAsync(Sanitize(s, privileged));
예제 #50
0
        private void GuildCreateEvents(JObject message)
        {
            DiscordGuildCreateEventArgs e = new DiscordGuildCreateEventArgs();
            e.RawJson = message;
            DiscordServer server = new DiscordServer();
            server.JoinedAt = message["d"]["joined_at"].ToObject<DateTime>();
            server.parentclient = this;
            server.ID = message["d"]["id"].ToString();
            server.Name = message["d"]["name"].ToString();
            server.Members = new Dictionary<ID, DiscordMember>();
            server.Channels = new List<DiscordChannel>();
            server.Roles = new List<DiscordRole>();
            foreach (var roll in message["d"]["roles"])
            {
                DiscordRole t = new DiscordRole
                {
                    Color = new DiscordSharp.Color(roll["color"].ToObject<int>().ToString("x")),
                    Name = roll["name"].ToString(),
                    Permissions = new DiscordPermission(roll["permissions"].ToObject<uint>()),
                    Position = roll["position"].ToObject<int>(),
                    Managed = roll["managed"].ToObject<bool>(),
                    ID = roll["id"].ToString(),
                    Hoist = roll["hoist"].ToObject<bool>()
                };
                server.Roles.Add(t);
            }
            foreach (var chn in message["d"]["channels"])
            {
                DiscordChannel tempChannel = new DiscordChannel();
                tempChannel.Client = this;
                tempChannel.ID = chn["id"].ToString();
                tempChannel.Type = chn["type"].ToObject<ChannelType>();

                if (!chn["topic"].IsNullOrEmpty())
                    tempChannel.Topic = chn["topic"].ToString();
                if (tempChannel.Type == ChannelType.Voice && !chn["bitrate"].IsNullOrEmpty())
                    tempChannel.Bitrate = chn["bitrate"].ToObject<int>();

                tempChannel.Name = chn["name"].ToString();
                tempChannel.Private = false;
                tempChannel.PermissionOverrides = new List<DiscordPermissionOverride>();
                tempChannel.Parent = server;
                foreach (var o in chn["permission_overwrites"])
                {
                    if (tempChannel.Type == ChannelType.Voice)
                        continue;
                    DiscordPermissionOverride dpo = new DiscordPermissionOverride(o["allow"].ToObject<uint>(), o["deny"].ToObject<uint>());
                    dpo.id = o["id"].ToString();

                    if (o["type"].ToString() == "member")
                        dpo.type = DiscordPermissionOverride.OverrideType.member;
                    else
                        dpo.type = DiscordPermissionOverride.OverrideType.role;

                    tempChannel.PermissionOverrides.Add(dpo);
                }
                server.Channels.Add(tempChannel);
            }
            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;

                foreach (var rollid in mbr["roles"])
                {
                    member.Roles.Add(server.Roles.Find(x => x.ID == rollid.ToString()));
                }
                if (member.Roles.Count == 0)
                    member.Roles.Add(server.Roles.Find(x => x.Name == "@everyone"));
                server.AddMember(member);
            }
            foreach (var voiceStateJSON in message["d"]["voice_states"]) {
                DiscordVoiceState voiceState = JsonConvert.DeserializeObject<DiscordVoiceState>(voiceStateJSON.ToString());
                DiscordMember member = server.GetMemberByKey(voiceState.UserID);

                member.CurrentVoiceChannel = server.Channels.Find(x => x.ID == voiceState.ChannelID);
                member.VoiceState = voiceState;
            }
            server.Owner = server.GetMemberByKey(message["d"]["owner_id"].ToString());
            e.Server = server;

            if (!message["d"]["unavailable"].IsNullOrEmpty() && message["d"]["unavailable"].ToObject<bool>() == false)
            {
                var oldServer = ServersList.Find(x => x.ID == server.ID);
                if (oldServer != null && oldServer.Unavailable)
                    ServersList.Remove(oldServer);

                ServersList.Add(server);

                DebugLogger.Log($"Guild with ID {server.ID} ({server.Name}) became available.");
                GuildAvailable?.Invoke(this, e);
                return;
            }

            ServersList.Add(server);
            GuildCreated?.Invoke(this, e);
        }
예제 #51
0
 public static Task <DiscordMessage> SafeMessageAsync(this DiscordChannel channel, FormattableString s, bool privileged)
 => channel.SendMessageAsync(SanitizeFormat(s, privileged));
예제 #52
0
        /// <summary>
        /// Sends a message to a channel, what else did you expect?
        /// </summary>
        /// <param name="message">The text to send</param>
        /// <param name="channel">DiscordChannel object to send the message to.</param>
        /// <returns>A DiscordMessage object of the message sent to Discord.</returns>
        public DiscordMessage SendMessageToChannel(string message, DiscordChannel channel)
        {
            string url = Endpoints.BaseAPI + Endpoints.Channels + $"/{channel.ID}" + Endpoints.Messages;
            try
            {
                JObject result = JObject.Parse(WebWrapper.Post(url, token, JsonConvert.SerializeObject(Utils.GenerateMessage(message))));
                if (result["content"].IsNullOrEmpty())
                    throw new InvalidOperationException("Request returned a blank message, you may not have permission to send messages yet!");

                DiscordMessage m = new DiscordMessage
                {
                    ID = result["id"].ToString(),
                    Attachments = result["attachments"].ToObject<DiscordAttachment[]>(),
                    Author = channel.Parent.GetMemberByKey(result["author"]["id"].ToString()),
                    channel = channel,
                    TypeOfChannelObject = channel.GetType(),
                    Content = result["content"].ToString(),
                    RawJson = result,
                    timestamp = result["timestamp"].ToObject<DateTime>()
                };
                return m;
            }
            catch (Exception ex)
            {
                DebugLogger.Log($"Error ocurred while sending message to channel ({channel.Name}): {ex.Message}", MessageLevel.Error);
            }
            return null;
        }
예제 #53
0
 public static Task <DiscordMessage> SafeMessageAsync(this DiscordChannel channel, FormattableString s, CommandContext ctx)
 => channel.SendMessageAsync(SanitizeFormat(s, IsPrivileged(ctx)));
예제 #54
0
 /// <summary>
 /// Changes the channel topic assosciated with the Discord text channel.
 /// </summary>
 /// <param name="Channeltopic">The new channel topic.</param>
 /// <param name="channel">The channel you wish to change the topic for.</param>
 public void ChangeChannelTopic(string Channeltopic, DiscordChannel channel)
 {
     string topicChangeJson = JsonConvert.SerializeObject(
         new
         {
             name = channel.Name,
             topic = Channeltopic
         });
     string url = Endpoints.BaseAPI + Endpoints.Channels + $"/{channel.ID}";
     try
     {
         var result = JObject.Parse(WebWrapper.Patch(url, token, topicChangeJson));
         ServersList.Find(x => x.Channels.Find(y => y.ID == channel.ID) != null).Channels.Find(x => x.ID == channel.ID).Topic = Channeltopic;
     }
     catch (Exception ex)
     {
         DebugLogger.Log($"Error ocurred while changing channel topic for channel {channel.Name}: {ex.Message}", MessageLevel.Error);
     }
 }
예제 #55
0
 public static Task <DiscordMessage> ElevatedMessageAsync(this DiscordChannel channel, string s)
 => channel.SendMessageAsync(s);
예제 #56
0
        private void RefreshContent()
        {
            if (Server.IconURL != null)
                this.Icon = new BitmapImage(new Uri(Server.IconURL));
            this.Title = $"Dissonance - {Server.name}";
            //TODO
            Server.channels.ForEach(x =>
            {
                Dispatcher.Invoke(() =>
                {
                    if(x.Type == ChannelType.Text)
                        channelsListBox.Items.Add("#" + x.Name);
                    if(mainClientReference != null)
                    {
                        var messageHistory = mainClientReference.GetMessageHistory(x, 50, null, null);
                        if (messageHistory != null)
                        {
                            messageHistory.Reverse();
                            messageHistory.ForEach(m => messageHistoryCache.Add(m));
                        }
                    }
                    //messagesList.SelectedIndex = messagesList.Items.Count - 1;
                    //messagesList.ScrollIntoView(messagesList.SelectedItem);
                    
                });
            });

            Server.members.ForEach(x =>
            {
                Dispatcher.Invoke(() =>
                {
                    //TODO: make nice member stub
                    if(x.Status == Status.Online)
                        membersListBox.Items.Add(x.Username);
                });
            });

            channelsListBox.SelectedIndex = 0;
            currentChannel = Server.channels.Find(x => x.Name == channelsListBox.SelectedItem.ToString().Substring(1));
            LoadChannel(currentChannel);
        }
예제 #57
0
 public static Task <DiscordMessage> ElevatedMessageAsync(this DiscordChannel channel, string s, DiscordEmbed embed)
 => channel.SendMessageAsync(s, embed: embed);
예제 #58
0
 public void LoadChannel(DiscordChannel channel)
 {
     messagesList.Items.Clear();
     foreach(var m in messageHistoryCache)
     {
         if(m.Channel() == channel)
         {
             AppendMessage(m);
             Title = $"Dissonance - {Server.name} - #{channel.Name}";
         }
     }
     MainScroller.ScrollToBottom();
 }
예제 #59
0
 private void ChannelCreateEvents (JObject message)
 {
     if (message["d"]["is_private"].ToString().ToLower() == "false")
     {
         var foundServer = ServersList.Find(x => x.id == message["d"]["guild_id"].ToString());
         if (foundServer != null)
         {
             DiscordChannel tempChannel = new DiscordChannel();
             tempChannel.Name = message["d"]["name"].ToString();
             tempChannel.Type = message["d"]["type"].ToObject<ChannelType>();
             tempChannel.ID = message["d"]["id"].ToString();
             tempChannel.parent = foundServer;
             foundServer.channels.Add(tempChannel);
             DiscordChannelCreateEventArgs fae = new DiscordChannelCreateEventArgs();
             fae.ChannelCreated = tempChannel;
             fae.ChannelType = DiscordChannelCreateType.CHANNEL;
             if (ChannelCreated != null)
                 ChannelCreated(this, fae);
         }
     }
     else
     {
         DiscordPrivateChannel tempPrivate = new DiscordPrivateChannel();
         tempPrivate.ID = message["d"]["id"].ToString();
         DiscordMember recipient = ServersList.Find(x => x.members.Find(y => y.ID == message["d"]["recipient"]["id"].ToString()) != null).members.Find(x => x.ID == message["d"]["recipient"]["id"].ToString());
         tempPrivate.recipient = recipient;
         PrivateChannels.Add(tempPrivate);
         DiscordPrivateChannelEventArgs fak = new DiscordPrivateChannelEventArgs { ChannelType = DiscordChannelCreateType.PRIVATE, ChannelCreated = tempPrivate };
         if (PrivateChannelCreated != null)
             PrivateChannelCreated(this, fak);
     }
 }