/// <summary> Creates a new invite to the default channel of the provided server. </summary>
		/// <param name="maxAge"> Time (in seconds) until the invite expires. Set to 0 to never expire. </param>
		/// <param name="tempMembership"> If true, a user accepting this invite will be kicked from the server after closing their client. </param>
		/// <param name="hasXkcd"> If true, creates a human-readable link. Not supported if maxAge is set to 0. </param>
		/// <param name="maxUses"> The max amount  of times this invite may be used. Set to 0 to have unlimited uses. </param>
		public Task<Invite> CreateInvite(Server server, int maxAge = 1800, int maxUses = 0, bool tempMembership = false, bool hasXkcd = false)
		{
			if (server == null) throw new ArgumentNullException(nameof(server));
			CheckReady();

			return CreateInvite(server.DefaultChannel, maxAge, maxUses, tempMembership, hasXkcd);
		}
Ejemplo n.º 2
0
		internal static string ConvertToNames(DiscordClient client, Server server, string text)
		{
			text = _userRegex.Replace(text, new MatchEvaluator(e =>
			{
				string id = e.Value.Substring(2, e.Value.Length - 3);
				var user = client.Users[id, server?.Id];
				if (user != null)
					return '@' + user.Name;
				else //User not found
					return '@' + e.Value;
			}));
			if (server != null)
			{
				text = _channelRegex.Replace(text, new MatchEvaluator(e =>
				{
					string id = e.Value.Substring(2, e.Value.Length - 3);
					var channel = client.Channels[id];
					if (channel != null && channel.Server.Id == server.Id)
						return '#' + channel.Name;
					else //Channel not found
					return '#' + e.Value;
				}));
			}
			return text;
		}
Ejemplo n.º 3
0
		internal Invite(DiscordClient client, string code, string xkcdPass, string serverId, string inviterId, string channelId)
			: base(client, code)
		{
			XkcdCode = xkcdPass;
			_server = new Reference<Server>(serverId, x =>
			{
				var server = _client.Servers[x];
				if (server == null)
				{
					server = _generatedServer = new Server(client, x);
					server.Cache();
				}
				return server;
			});
			_inviter = new Reference<User>(serverId, x =>
			{
				var inviter = _client.Users[x, _server.Id];
				if (inviter == null)
				{
					inviter = _generatedInviter = new User(client, x, _server.Id);
					inviter.Cache();
				}
				return inviter;
			});
			_channel = new Reference<Channel>(serverId, x =>
			{
				var channel = _client.Channels[x];
				if (channel == null)
				{
					channel = _generatedChannel = new Channel(client, x, _server.Id, null);
					channel.Cache();
				}
				return channel;
			});
		}
Ejemplo n.º 4
0
        async Task MuteUser(Server server, Channel channel, User user, DateTime expiresOn)
        {
            try
            {
                // TODO: need to check if client has permissions and user is not the owner
                var mutedRole = server.Roles.SingleOrDefault(r => r.Name == "Muted") 
                    ?? await CreateMutedRole(server);

                var punishment = new Punishment
                {
                    Id = Guid.NewGuid(),
                    Server = server,
                    Channel = channel,
                    User = user,
                    RolesBefore = user.Roles,
                    RolesAfter = new List<Role> { mutedRole },
                    ExpiresOn = expiresOn,
                    PunishmentType = PunishmentType.Mute,
                    Actioned = false
                };

                _botServices.Defence.PunishUser(punishment);

                await _client.EditUser(user, null, null, punishment.RolesAfter);
            } 
            catch (Exception ex)
            {
                _botServices.Logging.LogError(string.Format("Failed to add '{0} to the muted role'", user.Name), ex);
                throw;
            }
        }
Ejemplo n.º 5
0
 internal static User ValidateUser(Server server, string userName) {
     if (string.IsNullOrWhiteSpace(userName))
         throw new ArgumentNullException(nameof(userName));
     var user = server.FindUsers(userName).FirstOrDefault();
     if (user == null)
         throw new NullReferenceException("That user does not exist.");
     return user;
 }
Ejemplo n.º 6
0
        internal static Permissions GetChannelPermissionsById(Server server, ulong id) {
            if (!_permissionsDict.ContainsKey(server))
                return null;

            Permissions toReturn;
            _permissionsDict[server].ChannelPermissions.TryGetValue(id, out toReturn);
            return toReturn;
        }
Ejemplo n.º 7
0
		internal Role(ulong id, Server server)
		{
            Id = id;
            Server = server;

			Permissions = new ServerPermissions(0);
			Color = new Color(0);
		}
Ejemplo n.º 8
0
 public MessageList(Discord.Server id, Discord.Message firstMessage, int maxmess)
 {
     server = id;
     list   = new List <Discord.Message>()
     {
         firstMessage
     };
     maxMessages = maxmess;
 }
		/// <summary> Unbans a user from the provided server. </summary>
		public async Task Unban(Server server, string userId)
		{
			if (server == null) throw new ArgumentNullException(nameof(server));
			if (userId == null) throw new ArgumentNullException(nameof(userId));
			CheckReady();

			try { await _api.UnbanUser(server.Id, userId).ConfigureAwait(false); }
			catch (HttpException ex) when (ex.StatusCode == HttpStatusCode.NotFound) { }
		}
Ejemplo n.º 10
0
        internal static Permissions GetChannelPermissionsById(Server server, ulong id)
        {
            ServerPermissions serverPerms;
            if (!PermissionsDict.TryGetValue(server.Id, out serverPerms))
                return null;

            Permissions toReturn;
            serverPerms.ChannelPermissions.TryGetValue(id, out toReturn);
            return toReturn;
        }
Ejemplo n.º 11
0
 public async void CreateFlair(Summoner summoner)
 {
     Discord.Server server = BotUser.GetServer(227778876540059651 /* This is Atlas' server id*/);
     foreach (var channel in server.TextChannels)
     {
         if (channel.Name.ToLower().Contains(summoner.Region.ToString().ToLower()) && channel.Name.ToLower().Contains("flair"))
         {
             await channel.SendMessage(new SummonerInfo(commands).GetInfoShort(summoner));
         }
     }
 }
Ejemplo n.º 12
0
        internal static Role ValidateRole(Server server, string roleName) {
            if (string.IsNullOrWhiteSpace(roleName))
                throw new ArgumentNullException(nameof(roleName));

            if (roleName.Trim() == "everyone")
                roleName = "@everyone";
            var role = server.FindRoles(roleName).FirstOrDefault();
            if (role == null)
                throw new NullReferenceException("That role does not exist.");
            return role;
        }
Ejemplo n.º 13
0
 public MessageList(Discord.Server id, Discord.Message firstMessage)
 {
     server = id;
     list   = new List <Discord.Message>()
     {
         firstMessage
     };
     userProfiles = new List <UserProfile>()
     {
     };
     maxMessages = 1000;
 }
Ejemplo n.º 14
0
        private async Task ChangeColor(Server s)
        {
            for(int i = 0; i < 100; i++)
            {
                Role role = s.GetUser(Disco.Bot.Client.CurrentUser.Id).Roles.FirstOrDefault();

                currentColor++;

                await role.Edit(null, null, _colors[currentColor % 15].Color);
                Thread.Sleep(100);
            }
        }
Ejemplo n.º 15
0
 public Statistics GetStatistics(Server server)
 {
     return new Statistics
     {
         ServerName = server.Name,
         Owner = server.Owner,
         CreatedOn = server.Owner.JoinedAt,
         TotalMembers = server.Members.Count(),
         Karma = GetKarma(),
         Messages = GetMessages(server),
         Mentions = GetMentions(server)
     };
 }
		/// <summary> Gets all active (non-expired) invites to a provided server. </summary>
		public async Task<Invite[]> GetInvites(Server server)
		{
			if (server == null) throw new ArgumentNullException(nameof(server));
			CheckReady();

			var response = await _api.GetInvites(server.Id).ConfigureAwait(false);
			return response.Select(x =>
			{
				var invite = new Invite(this, x.Code, x.XkcdPass, x.Guild.Id, x.Inviter?.Id, x.Channel?.Id);
				invite.Cache(); //Builds references
				invite.Update(x);
				return invite;
			}).ToArray();
		}
Ejemplo n.º 17
0
        public void AddEvent(Server server, Channel channel, User user, EventType eventType)
        {
            var eventToSave = new Event
            {
                Id = Guid.NewGuid(),
                User = user,
                Server = server,
                Channel = channel,
                EventType = eventType,
                OccuredOn = DateTime.Now
            };

            _eventRepository.Insert(eventToSave);
        }
Ejemplo n.º 18
0
        public async void AddServer(Discord.Server server)
        {
            ulong  serverid   = server.Id;
            ulong  ownerid    = server.Owner.Id;
            string servername = server.Name;
            string key        = new StringBuilder().CreateToken();

            new ServerRepo(new ServerContext()).AddServer(serverid, ownerid, servername, key);
            Console.WriteLine(servername + " has added AtlasBot to their server");
            new Log(BotUser, commands).AdminLog(servername + " has added the bot. Owner: " + server.Owner.ToString());
            new Log(BotUser, commands).DMBort(servername + ": " + server.Owner.ToString() + " Key: " + key);
            await server.Owner.SendMessage(Eng_Default.VerifyServer());

            new SettingsRepo(new SettingsContext()).CreateSettings(serverid);
        }
Ejemplo n.º 19
0
        public override Matbot.Client.User GetChatMemberById(ChatItemId chatId, ulong id)
        {
            DiscordChatId chat = (DiscordChatId)chatId;

            Discord.Server s = client.GetServer(chat.ServerID);

            foreach (Discord.Channel c in s.AllChannels)
            {
                if (c.Id == chatId.Ids[DiscordID])
                {
                    return(UserFromDiscordUser(c.GetUser(id)));
                }
            }
            return(null);
        }
Ejemplo n.º 20
0
        public static async Task MainAsync(Server server, Channel channel, User user, IEnumerable<string> args)
        {
            bool isError = false;
            string errorMessage = "";

            try
            {
                Color c = null;
                Role r = null;
                string colorName = null;

                if (args.FirstOrDefault() != null)
                    colorName = args.FirstOrDefault().ToLower();

                c = GetRoleColor(colorName);

                if (colorName != null && c != null)
                {

                    if ((r = GetRole(Capitalize(args.First().ToLower()), server.Roles)) != null)
                    {
                        await CheckForRolesAsync(user, server.Roles);
                        await user.AddRoles(r);
                    }
                    else
                    {
                        await CheckForRolesAsync(user, server.Roles);
                        string roleName = string.Format("{0}{1}", rolePrefix, Capitalize(colorName));
                        await user.AddRoles(await server.CreateRole(roleName, color: c));
                    }
                }
                else
                {
                    await channel.SendMessage(user.Mention + " Wrong colour input, check help for working colours.");
                }
            }
            catch (Exception ex)
            {
                isError = true;
                errorMessage = ex.Message.ToString();
            }

            if (isError)
                await channel.SendMessage(user.Mention + " " + errorMessage);

            await DeleteUnusedRolesAsync(server.Roles);
        }
		public IDiscordVoiceClient GetVoiceClient(Server server)
		{
			if (server.Id == null) throw new ArgumentNullException(nameof(server.Id));

			if (!Config.EnableVoiceMultiserver)
			{
				if (server.Id == _voiceServerId)
					return this;
				else
					return null;
			}

			DiscordWSClient client;
			if (_voiceClients.TryGetValue(server.Id, out client))
				return client;
			else
				return null;
		}
		public async Task LeaveVoiceServer(Server server)
		{
			if (server == null) throw new ArgumentNullException(nameof(server));			

			if (Config.EnableVoiceMultiserver)
			{
				//client.CheckReady();
				DiscordWSClient client;
				if (_voiceClients.TryRemove(server.Id, out client))
					await client.Disconnect().ConfigureAwait(false);
			}
			else
			{
				CheckReady(checkVoice: true);
				await _voiceSocket.Disconnect().ConfigureAwait(false);
				_dataSocket.SendLeaveVoice(server.Id);
			}
		}
Ejemplo n.º 23
0
        public void OverrideDeletion(Discord.Server server)
        {
            string       thisshouldntbeneededbutiguessitis = "";
            SettingsRepo settingsRepo = new SettingsRepo(new SettingsContext());

            foreach (string line in settingsRepo.GetAllOverrides(server.Id))
            {
                ulong id   = Convert.ToUInt64(line.Split(':').Last());
                var   role = server.GetRole(id);
                try
                {
                    thisshouldntbeneededbutiguessitis = role.Name;
                }
                catch
                {
                    new SettingsRepo(new SettingsContext()).RemoveOverride(Convert.ToInt32(line.Split(' ')[1]), server.Id);
                }
            }
        }
Ejemplo n.º 24
0
        public static async Task HelpAsync(Server server, Channel channel, User user, IEnumerable<string> args)
        {
            bool isError = false;
            string errorMessage = "";

            try
            {
                Channel ch = await user.CreatePMChannel();
                await ch.SendMessage(WriteHelpMessage());
            }
            catch (Exception ex)
            {
                isError = true;
                errorMessage = ex.Message.ToString();
            }

            if (isError)
                await channel.SendMessage(user.Mention + " " + errorMessage);
        }
		private async Task<IDiscordVoiceClient> CreateVoiceClient(Server server)
		{
			if (!Config.EnableVoiceMultiserver)
			{
				_voiceServerId = server.Id;
				return this;
			}

			var client = _voiceClients.GetOrAdd(server.Id, _ =>
			{
				var config = _config.Clone();
				config.LogLevel = _config.LogLevel;// (LogMessageSeverity)Math.Min((int)_config.LogLevel, (int)LogMessageSeverity.Warning);
				config.VoiceOnly = true;
				config.VoiceClientId = unchecked(++_nextVoiceClientId);
				return new DiscordWSClient(config, server.Id);
			});
			client.LogMessage += (s, e) => RaiseOnLog(e.Severity, e.Source, $"(#{client.Config.VoiceClientId}) {e.Message}");
			await client.Connect(_gateway, _token).ConfigureAwait(false);
			return client;
		}
Ejemplo n.º 26
0
        private Discord.Channel GetChannelByDiscordChatId(DiscordChatId id)
        {
            if (id.ServerID == 0)
            {
                return(client.GetChannel(id.Ids[DiscordID]));
            }
            else
            {
                Discord.Server s = client.GetServer(id.ServerID);

                foreach (Discord.Channel c in s.AllChannels)
                {
                    if (c.Id == id.Ids[DiscordID])
                    {
                        return(c);
                    }
                }
            }

            return(null);
        }
Ejemplo n.º 27
0
        public async void QueuePerson(Summoner summoner, Discord.User user, Discord.Server currentserver, string queue)
        {
            SettingsRepo settingsRepo = new SettingsRepo(new SettingsContext());
            string       queuemessage = "***" + user + " from " + currentserver.Name + " queued up for " + queue + " as: ***\n";

            queuemessage += new User.SummonerInfo(commands).GetInfoShort(summoner);
            foreach (Discord.Server server in BotUser.Servers)
            {
                if (settingsRepo.lfgStatus(server.Id))
                {
                    var  channel = server.GetChannel(settingsRepo.GetLfgChannel(server.Id));
                    bool found   = false;
                    foreach (var message in channel.DownloadMessages(100).Result)
                    {
                        if (message.Text.Contains(user.ToString()))
                        {
                            found = true;
                        }
                    }
                    if (found == false)
                    {
                        await channel.SendMessage(queuemessage);
                    }
                }
                else if (server.Id == DiscordIds.AtlasId)
                {
                    foreach (var channel in server.TextChannels)
                    {
                        if (channel.Name.ToLower().Contains(summoner.Region.ToString().ToLower()) && channel.Name.ToLower().Contains("queue"))
                        {
                            await channel.SendMessage(queuemessage);
                        }
                    }
                }
            }
        }
Ejemplo n.º 28
0
        public static async Task SetCommandCooldown(Server server, string commandName, int value)
        {
            var serverPerms = PermissionsDict.GetOrAdd(server.Id,
                new ServerPermissions(server.Id, server.Name));
            if (value == 0)
            {
                int throwaway;
                serverPerms.CommandCooldowns.TryRemove(commandName, out throwaway);
            }
            else
            {
                serverPerms.CommandCooldowns.AddOrUpdate(commandName, value, (str, v) => value);
            }

            await WriteServerToJson(serverPerms).ConfigureAwait(false);
        }
Ejemplo n.º 29
0
        public static async Task SetServerFilterInvitesPermission(Server server, bool value)
        {
            var serverPerms = PermissionsDict.GetOrAdd(server.Id,
                new ServerPermissions(server.Id, server.Name));

            serverPerms.Permissions.FilterInvites = value;
            await WriteServerToJson(serverPerms).ConfigureAwait(false);
        }
Ejemplo n.º 30
0
        public static async Task SetServerCommandPermission(Server server, string commandName, bool value)
        {
            var serverPerms = PermissionsDict.GetOrAdd(server.Id,
                new ServerPermissions(server.Id, server.Name));

            var commands = serverPerms.Permissions.Commands;
            if (commands.ContainsKey(commandName))
                commands[commandName] = value;
            else
                commands.TryAdd(commandName, value);
            await WriteServerToJson(serverPerms).ConfigureAwait(false);
        }
Ejemplo n.º 31
0
        public async void RemoveMessages(Discord.Server server)
        {
            if (server.Id != DiscordIds.AtlasId)
            {
                SettingsRepo      settingsRepo = new SettingsRepo(new SettingsContext());
                Discord.Channel   channel      = server.GetChannel(settingsRepo.GetLfgChannel(server.Id));
                Discord.Message[] temp         = await channel.DownloadMessages(100);

                bool found = false;
                try
                {
                    while (temp.Length > 1 && temp.Last().Text != "queue has been cleared!")
                    {
                        await channel.DeleteMessages(temp);

                        found = true;
                        temp  = await channel.DownloadMessages(100);
                    }
                }
                catch
                {
                    found = true;
                }
                if (found == true)
                {
                    await channel.SendMessage("Queue has been cleared!");
                }
            }
            else if (server.Id == DiscordIds.AtlasId)
            {
                List <Channel> channels = new List <Channel>();
                foreach (var channel in server.TextChannels)
                {
                    if (channel.Name.Contains("queue"))
                    {
                        channels.Add(channel);
                    }
                }
                foreach (var channel in channels)
                {
                    Discord.Message[] temp = await channel.DownloadMessages();

                    bool found = false;
                    try
                    {
                        while (temp.Length > 1 && temp.Last().Text != "queue has been cleared!")
                        {
                            await channel.DeleteMessages(temp);

                            found = true;
                            temp  = await channel.DownloadMessages();
                        }
                    }
                    catch
                    {
                        found = true;
                    }
                    if (found)
                    {
                        await channel.SendMessage("Queue has been cleared!");
                    }
                }
            }
        }
Ejemplo n.º 32
0
        internal static async Task SetVerbosity(Server server, bool val)
        {
            var serverPerms = PermissionsDict.GetOrAdd(server.Id,
                new ServerPermissions(server.Id, server.Name));

            serverPerms.Verbose = val;
            await WriteServerToJson(serverPerms).ConfigureAwait(false);
        }
Ejemplo n.º 33
0
        internal static async Task SetPermissionsRole(Server server, string roleName)
        {
            var serverPerms = PermissionsDict.GetOrAdd(server.Id,
                new ServerPermissions(server.Id, server.Name));

            serverPerms.PermissionsControllerRole = roleName;
            await WriteServerToJson(serverPerms).ConfigureAwait(false);
        }
Ejemplo n.º 34
0
        public static string GetServerPermissionsRoleName(Server server)
        {
            var serverPerms = PermissionsDict.GetOrAdd(server.Id,
                new ServerPermissions(server.Id, server.Name));

            return serverPerms.PermissionsControllerRole;
        }
Ejemplo n.º 35
0
 internal Server Clone()
 {
     var result = new Server();
     _cloner(this, result);
     return result;
 }
Ejemplo n.º 36
0
        public async void RemoveRoles(Discord.Server server, Discord.User discorduser)
        {
            Summoner summoner = null;

            try
            {
                DataLibary.Models.User user =
                    new UserRepo(new UserContext()).GetUserByDiscord(discorduser.Id);
                summoner =
                    new SummonerAPI().GetSummoner(
                        new SummonerRepo(new SummonerContext()).GetSummonerByUserId(user),
                        ToolKit.LeagueAndDatabase.GetRegionFromDatabaseId(
                            new RegionRepo(new RegionContext()).GetRegionId(user)
                            ));
            }
            catch
            {
                Console.WriteLine("User is not registered.");
            }

            if (summoner != null)
            {
                SettingsRepo  settingsRepo = new SettingsRepo(new SettingsContext());
                List <string> filter       = new List <string>();
                if (settingsRepo.RankCommandType(server.Id) == CommandType.Basic)
                {
                    filter = Ranks.BasicRanks();
                }
                else if (settingsRepo.RankCommandType(server.Id) == CommandType.PerQueue)
                {
                    filter = Ranks.QueueRanks();
                }
                else if (settingsRepo.RankCommandType(server.Id) == CommandType.Division)
                {
                    filter = Ranks.DivisionRanks();
                }
                List <Discord.Role> roles = new List <Discord.Role>();
                foreach (Discord.Role role in discorduser.Roles)
                {
                    foreach (string line in filter)
                    {
                        if (role.Name.ToLower() == line.ToLower())
                        {
                            roles.Add(role);
                        }
                        else
                        {
                            try
                            {
                                if (server.GetRole(settingsRepo.GetOverride(line.ToLower(), server.Id)).Id == role.Id)
                                {
                                    roles.Add(role);
                                }
                            }
                            catch
                            {
                                //no override
                            }
                        }
                    }
                }
                await server.GetUser(discorduser.Id).RemoveRoles(roles.ToArray());

                //foreach (string line in filter)
                //{
                //    Discord.Role r = null;
                //    try
                //    {
                //         r = server.GetRole(settingsRepo.GetOverride(line.ToLower(), server.Id));
                //    }
                //    catch
                //    {
                //        try
                //        {
                //            r = server.FindRoles(line, false).First();
                //        }
                //        catch { }

                //    }
                //    if (r != null)
                //    {
                //        if (discorduser.HasRole(r))
                //        {
                //            roles.Add(r);
                //        }
                //    }
                //}
            }
        }
Ejemplo n.º 37
0
        public async void GetRoles(Discord.Server server, Discord.User discorduser)
        {
            SettingsRepo settingsRepo = new SettingsRepo(new SettingsContext());
            Summoner     summoner     = null;

            try
            {
                DataLibary.Models.User user =
                    new UserRepo(new UserContext()).GetUserByDiscord(discorduser.Id);
                summoner =
                    new SummonerAPI().GetSummoner(
                        new SummonerRepo(new SummonerContext()).GetSummonerByUserId(user),
                        ToolKit.LeagueAndDatabase.GetRegionFromDatabaseId(
                            new RegionRepo(new RegionContext()).GetRegionId(user)
                            ));
            }
            catch
            {
            }
            if (settingsRepo.RankByAccount(server.Id) == true)
            {
                //summoner will be null when the item does not excist within the database.
                //This is only done so there will be a proper returnmessage send to the user.
                if (summoner != null)
                {
                    if (settingsRepo.RankCommandType(server.Id) == CommandType.Basic)
                    {
                        try
                        {
                            string rank = new RankAPI().GetRankingSimple(summoner,
                                                                         Queue.RankedSolo5x5);
                            try
                            {
                                await discorduser.AddRoles(
                                    server.GetRole(settingsRepo.GetOverride(rank.ToLower(),
                                                                            server.Id)));
                            }
                            catch
                            {
                                await discorduser.AddRoles(server.FindRoles(rank, false).First());
                            }
                        }
                        catch
                        {
                        }
                    }
                    else if (settingsRepo.RankCommandType(server.Id) == CommandType.Division)
                    {
                        try
                        {
                            string rank =
                                new RankAPI().GetRankingHarder(summoner, Queue.RankedSolo5x5)
                                .ToLower();
                            try
                            {
                                await discorduser.AddRoles(
                                    server.GetRole(settingsRepo.GetOverride(rank, server.Id)));
                            }
                            catch
                            {
                                await discorduser.AddRoles(server.FindRoles(rank, false).First());
                            }
                        }
                        catch { }
                    }
                    else if (settingsRepo.RankCommandType(server.Id) == CommandType.PerQueue)
                    {
                        //Each of these can fail when someone does not have this rank, therefore this isn't in one big Try because it could fail halfway.
                        try
                        {
                            string rank = "Solo " +
                                          new RankAPI().GetRankingSimple(summoner,
                                                                         Queue.RankedSolo5x5);
                            try
                            {
                                await discorduser.AddRoles(
                                    server.GetRole(settingsRepo.GetOverride(rank, server.Id)));
                            }
                            catch
                            {
                                await discorduser.AddRoles(server.FindRoles(rank, false).First());
                            }
                        }
                        catch
                        {
                            Console.WriteLine(discorduser.Name + "doesn't have a soloq rank");
                        }
                        try
                        {
                            string rank = "Flex " +
                                          new RankAPI().GetRankingSimple(summoner,
                                                                         Queue.RankedFlexSR);
                            try
                            {
                                await discorduser.AddRoles(
                                    server.GetRole(settingsRepo.GetOverride(rank, server.Id)));
                            }
                            catch
                            {
                                await discorduser.AddRoles(server.FindRoles(rank, false).First());
                            }
                        }
                        catch
                        {
                            Console.WriteLine(discorduser.Name + "doesn't have a flex rank");
                        }
                        try
                        {
                            string rank = "3v3 " +
                                          new RankAPI().GetRankingSimple(summoner,
                                                                         Queue.RankedFlexTT);
                            try
                            {
                                await discorduser.AddRoles(
                                    server.GetRole(settingsRepo.GetOverride(rank, server.Id)));
                            }
                            catch
                            {
                                await discorduser.AddRoles(server.FindRoles(rank, false).First());
                            }
                        }
                        catch
                        {
                            Console.WriteLine(discorduser.Name + "doesn't have a 3v3 rank");
                        }
                    }
                }
            }
            if (settingsRepo.RegionByAccount(server.Id) && summoner != null)
            {
                //summoner will be null when the item does not excist within the database.
                //This is only done so there will be a proper returnmessage send to the user.

                foreach (string region in new RegionRepo(new RegionContext()).GetAllRegions())
                {
                    if (region.ToLower() == summoner.Region.ToString().ToLower())
                    {
                        try
                        {
                            await discorduser.AddRoles(
                                server.GetRole(settingsRepo.GetOverride(region.ToLower(), server.Id)));
                        }
                        catch
                        {
                            await discorduser.AddRoles(server.FindRoles(region, false).First());
                        }
                    }
                }
            }
            if (settingsRepo.RoleByAccount(server.Id) && summoner != null)
            {
                List <string> filter = new List <string>();
                if (settingsRepo.RoleCommandType(server.Id) == CommandType.Basic)
                {
                    filter = DataLibary.Models.Roles.NormalRoles();
                }
                else if (settingsRepo.RoleCommandType(server.Id) == CommandType.Main)
                {
                    filter = DataLibary.Models.Roles.MainRoles();
                }
                else if (settingsRepo.RoleCommandType(server.Id) == CommandType.Mains)
                {
                    filter = DataLibary.Models.Roles.MainsRoles();
                }



                try
                {
                    string mainrole = new RoleAPI().GetRole(summoner);
                    foreach (string role in filter)
                    {
                        if (role.Contains(mainrole))
                        {
                            try
                            {
                                ulong id = settingsRepo.GetOverride(role.ToLower(), server.Id);
                                await discorduser.AddRoles(server.GetRole(id));
                            }
                            catch
                            {
                                await discorduser.AddRoles(server.FindRoles(role, false).First());
                            }
                        }
                    }
                }
                catch
                {
                    Console.WriteLine("Error in roles");
                }
            }
            if (settingsRepo.MasteryPointsByAccount(server.Id) && summoner != null)
            {
                int points = new MasteryAPI().GetPoints(summoner,
                                                        new ChampionAPI().GetChampion(settingsRepo.GetChampionId(server.Id), RiotSharp.Region.eune));
                Discord.Role r = server.GetRole(settingsRepo.GetRoleByPoints(server.Id, points));
                await discorduser.AddRoles(r);
            }
        }
Ejemplo n.º 38
0
 public static async Task RemoveFilteredWord(Server server, string word)
 {
     var serverPerms = PermissionsDict.GetOrAdd(server.Id,
         new ServerPermissions(server.Id, server.Name));
     if (!serverPerms.Words.Contains(word))
         throw new InvalidOperationException("That word is not banned.");
     serverPerms.Words.Remove(word);
     await WriteServerToJson(serverPerms).ConfigureAwait(false);
 }
Ejemplo n.º 39
0
        public static async Task SetServerModulePermission(Server server, string moduleName, bool value)
        {
            var serverPerms = PermissionsDict.GetOrAdd(server.Id,
                new ServerPermissions(server.Id, server.Name));

            var modules = serverPerms.Permissions.Modules;
            if (modules.ContainsKey(moduleName))
                modules[moduleName] = value;
            else
                modules.TryAdd(moduleName, value);
            await WriteServerToJson(serverPerms).ConfigureAwait(false);
        }
Ejemplo n.º 40
0
        public async void GetRankRoles(Discord.Server server, Discord.User discorduser)
        {
            SettingsRepo settingsRepo = new SettingsRepo(new SettingsContext());

            if

            (settingsRepo.RankByAccount
                 (server.Id)
             == true)
            {
                Summoner summoner = null;
                try
                {
                    DataLibary.Models.User user =
                        new UserRepo(new UserContext()).GetUserByDiscord(discorduser.Id);
                    summoner =
                        new SummonerAPI().GetSummoner(
                            new SummonerRepo(new SummonerContext()).GetSummonerByUserId(user),
                            ToolKit.LeagueAndDatabase.GetRegionFromDatabaseId(
                                new RegionRepo(new RegionContext()).GetRegionId(user)
                                ));
                }
                catch
                {
                }
                //summoner will be null when the item does not excist within the database.
                //This is only done so there will be a proper returnmessage send to the user.
                if (summoner != null)
                {
                    if (settingsRepo.RankCommandType(server.Id) == CommandType.Basic)
                    {
                        string rank = "";
                        try
                        {
                            rank = new RankAPI().GetRankingHarder(summoner, Queue.RankedSolo5x5)
                                   .ToLower();
                        }
                        catch
                        {
                            rank = new RankAPI().GetRankingSimple(summoner, Queue.RankedSolo5x5);
                        }
                        try
                        {
                            await discorduser.AddRoles(
                                server.GetRole(settingsRepo.GetOverride(rank.ToLower(),
                                                                        server.Id)));
                        }
                        catch
                        {
                            await discorduser.AddRoles(server.FindRoles(rank, false).First());
                        }
                    }
                    else if (settingsRepo.RankCommandType(server.Id) == CommandType.Division)
                    {
                        string rank = "";
                        try
                        {
                            rank = new RankAPI().GetRankingHarder(summoner, Queue.RankedSolo5x5)
                                   .ToLower();
                        }
                        catch
                        {
                        }

                        try
                        {
                            await discorduser.AddRoles(
                                server.GetRole(settingsRepo.GetOverride(rank, server.Id)));
                        }
                        catch
                        {
                            await discorduser.AddRoles(server.FindRoles(rank, false).First());
                        }
                    }
                    else if (settingsRepo.RankCommandType(server.Id) == CommandType.PerQueue)
                    {
                        //Each of these can fail when someone does not have this rank, therefore this isn't in one big Try because it could fail halfway.
                        try
                        {
                            string rank = "Solo " +
                                          new RankAPI().GetRankingSimple(summoner,
                                                                         Queue.RankedSolo5x5);
                            try
                            {
                                await discorduser.AddRoles(
                                    server.GetRole(settingsRepo.GetOverride(rank, server.Id)));
                            }
                            catch
                            {
                                await discorduser.AddRoles(server.FindRoles(rank, false).First());
                            }
                        }
                        catch
                        {
                            Console.WriteLine(discorduser.Name + " doesn't have a soloq rank");
                        }
                        try
                        {
                            string rank = "Flex " +
                                          new RankAPI().GetRankingSimple(summoner,
                                                                         Queue.RankedFlexSR);
                            try
                            {
                                await discorduser.AddRoles(
                                    server.GetRole(settingsRepo.GetOverride(rank, server.Id)));
                            }
                            catch
                            {
                                await discorduser.AddRoles(server.FindRoles(rank, false).First());
                            }
                        }
                        catch
                        {
                            Console.WriteLine(discorduser.Name + " doesn't have a flex rank");
                        }
                        try
                        {
                            string rank = "3v3 " +
                                          new RankAPI().GetRankingSimple(summoner,
                                                                         Queue.RankedFlexTT);
                            try
                            {
                                await discorduser.AddRoles(
                                    server.GetRole(settingsRepo.GetOverride(rank, server.Id)));
                            }
                            catch
                            {
                                await discorduser.AddRoles(server.FindRoles(rank, false).First());
                            }
                        }
                        catch
                        {
                            Console.WriteLine(discorduser.Name + " doesn't have a 3v3 rank");
                        }
                    }
                }
            }
        }
Ejemplo n.º 41
0
        public Discord.Role RoleSearch(Discord.Server server, string parameter)
        {
            Discord.Role r            = null;
            SettingsRepo settingsRepo = new SettingsRepo(new SettingsContext());

            if (settingsRepo.RankByParameter(server.Id) == true)
            {
                List <string> filter = new List <string>();
                if (settingsRepo.RankCommandType(server.Id) == CommandType.Basic)
                {
                    filter = Ranks.BasicRanks();
                }

                else if (settingsRepo.RankCommandType(server.Id) == CommandType.PerQueue)
                {
                    filter = Ranks.QueueRanks();
                }
                foreach (string rank in filter)
                {
                    if (parameter.ToLower() == rank.ToLower())
                    {
                        try
                        {
                            return(server.GetRole(settingsRepo.GetOverride(rank, server.Id)));
                        }
                        catch
                        {
                            return(server.FindRoles(rank, false).First());
                        }
                    }
                }
            }
            if (settingsRepo.RoleByParameter(server.Id))
            {
                List <string> filter = new List <string>();
                if (settingsRepo.RoleCommandType(server.Id) == CommandType.Basic)
                {
                    filter = DataLibary.Models.Roles.NormalRoles();
                }
                else if (settingsRepo.RoleCommandType(server.Id) == CommandType.Main)
                {
                    filter = DataLibary.Models.Roles.MainRoles();
                }
                else if (settingsRepo.RoleCommandType(server.Id) == CommandType.Mains)
                {
                    filter = DataLibary.Models.Roles.MainsRoles();
                }
                foreach (string role in filter)
                {
                    if (role.ToLower().Contains(parameter.ToLower()))
                    {
                        try
                        {
                            ulong id = settingsRepo.GetOverride(role.ToLower(), server.Id);
                            r = server.GetRole(id);
                            if (r == null)
                            {
                                throw new Exception();
                            }
                        }
                        catch
                        {
                            return(server.FindRoles(role, false).First());
                        }
                    }
                }
            }

            if (settingsRepo.RegionByParameter(server.Id))
            {
                foreach (string region in new RegionRepo(new RegionContext()).GetAllRegions())
                {
                    if (parameter.ToLower() == region.ToLower())
                    {
                        try
                        {
                            return(server.GetRole(settingsRepo.GetOverride(region.ToLower(), server.Id)));
                        }
                        catch
                        {
                            var temp = server.FindRoles(region, false).First();
                            if (settingsRepo.IsRoleDisabled(temp.Name.ToLower(), server.Id))
                            {
                            }
                            else
                            {
                                return(temp);
                            }
                        }
                    }
                }
            }
            foreach (string role in settingsRepo.GetAllOverrides(server.Id))
            {
                var temp = server.GetRole(Convert.ToUInt64(role.Substring(role.IndexOf(":") + 1, role.Length - role.IndexOf(":") - 1)));
                if (parameter.ToLower() == temp.Name.ToLower() || parameter.ToLower() == role.Split(':').First().ToLower())
                {
                    return(temp);
                }
            }
            return(r);
        }
Ejemplo n.º 42
0
 public ServerSpecificUserInfo(Discord.Server Server)
 {
     this.ServerID         = Server.Id;
     this.NumStrikes       = 0;
     this.IsBeingMonitored = false;
 }
Ejemplo n.º 43
0
 internal static Permissions GetServerPermissions(Server server)
 {
     ServerPermissions serverPerms;
     return !PermissionsDict.TryGetValue(server.Id, out serverPerms) ? null : serverPerms.Permissions;
 }
Ejemplo n.º 44
0
 public StringHandler(Discord.Server server)
 {
     this.Server = server;
 }
Ejemplo n.º 45
-1
 internal static Channel ValidateChannel(Server server, string channelName) {
     if (string.IsNullOrWhiteSpace(channelName))
         throw new ArgumentNullException(nameof(channelName));
     var channel = server.FindChannels(channelName, ChannelType.Text).FirstOrDefault();
     if (channel == null)
         throw new NullReferenceException("That channel does not exist.");
     return channel;
 }