示例#1
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;
            }
        }
示例#2
0
        private void Discord_MessageReceived(object sender, MessageEventArgs e)
        {
            string      firstWord    = Regex.Match(e.Message.Text, @"^\S+\b").Value.ToLower();
            UserCommand foundCommand = MainWindow.colBotCommands.FirstOrDefault(x =>
                                                                                x.Command == firstWord);

            if (foundCommand != null)
            {
                //foundCommand.ExecuteCommand(new IrcMessage(e.User.Name + "@Discord", e.Message.Text));
                foundCommand.ExecuteCommandDiscord(e.Message);
            }
            else
            {
                //BotCommands.RunBotCommand(firstWord, new IrcMessage(e.User.Name + "@Discord", e.Message.Text));
                BotCommands.RunBotCommandDiscord(firstWord, e.Message);
            }
            if (e.Channel.IsPrivate)
            {
                if (e.Message.Text.Split(' ')[0] == "confirm" && e.Message.Text.Split(' ').Length == 2)
                {
                    Discord.User   confirm = e.User;
                    Models.Channel target  = client.GetChannel(e.Message.Text.Split(' ')[1]);
                    string         id      = target.Game;
                    if (id == confirm.Id.ToString())
                    {
                        Viewer vwr = colDatabase.FirstOrDefault(x => x.UserName.ToLower() == target.Name.ToLower());
                        vwr.DiscordID = confirm.Id.ToString();
                        DatabaseUtils.UpdateViewer(vwr);
                    }
                }
            }
        }
        public bool CanRun(Command command, User user, Channel channel, out string error)
        {
            error = null;

            if (channel.IsPrivate)
                return DefaultPermissionLevel <= DefaultPermChecker.GetPermissionLevel(user, channel);

            DynPermFullData data = DynPerms.GetPerms(channel.Server.Id);

            // apply default perms.
            bool retval = DefaultPermissionLevel <= DefaultPermChecker.GetPermissionLevel(user, channel);

            // if we do not have dynamic perms in place for the user's server, return the default perms.
            if (data == null || (!data.Perms.RolePerms.Any() && !data.Perms.UserPerms.Any()))
                return retval;

            /* 
              Firsly do role checks.
              Lower entries override higher entries. 
              To do that we have to iterate over the dict instead of using roles the user has as keys.
            */

            foreach (var pair in data.Perms.RolePerms)
            {
                if (user.HasRole(pair.Key))
                    retval = EvaluatePerms(pair.Value, command, retval, channel, ref error);
            }

            // users override roles, do them next.
            DynamicPermissionBlock permBlock;
            if (data.Perms.UserPerms.TryGetValue(user.Id, out permBlock))
                retval = EvaluatePerms(permBlock, command, retval, channel, ref error);

            return retval;
        }
示例#4
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;
			});
		}
示例#5
0
    public void UpdateDisplayForId(Discord.User user, long key)
    {
        PortriaitPlayerView view;

        PlayerPortraitsCanvas.INSTANCE.pairedPortriats.TryGetValue(key, out view);

        var imageManager = DiscordManager.INSTANCE.GetDiscord().GetImageManager();

        if (user.Id != 0)
        {
            Texture2D avatar = null;
            try
            {
                avatar = imageManager.GetTexture(Discord.ImageHandle.User(user.Id));
            }
            catch (Discord.ResultException)
            {
                FetchMemberAvatar(user.Id);
            }
            Score score = null;
            ScoreUpdater.INSTANCE?.scores.TryGetValue(key, out score);
            if (score != null)
            {
                view.SetUser(user.Username, "Score: " + score.GetValue(), avatar);
            }
            else
            {
                view.SetUser(user.Username, "Score: " + 0, avatar);
            }
        }
        else
        {
            view.SetToDefault();
        }
    }
示例#6
0
        public bool CanRun(Command command, User user, Channel channel, out string error) {
            error = null;

            if (channel.IsPrivate)
                return true;

            try {
                //is it a permission command?
                // if it is, check if the user has the correct role
                // if yes return true, if no return false
                if (command.Category == "Permissions")
                    if (user.Server.IsOwner || user.HasRole(PermissionHelper.ValidateRole(user.Server, PermissionsHandler.GetServerPermissionsRoleName(user.Server))))
                        return true;
                    else
                        throw new Exception($"You don't have the necessary role (**{PermissionsHandler._permissionsDict[user.Server].PermissionsControllerRole}**) to change permissions.");

                var permissionType = PermissionsHandler.GetPermissionBanType(command, user, channel);

                string msg;

                switch (permissionType) {
                    case PermissionsHandler.PermissionBanType.None:
                        return true;
                    case PermissionsHandler.PermissionBanType.ServerBanCommand:
                        msg = $"**{command.Text}** command has been banned from use on this **server**.";
                        break;
                    case PermissionsHandler.PermissionBanType.ServerBanModule:
                        msg = $"**{command.Category}** module has been banned from use on this **server**.";
                        break;
                    case PermissionsHandler.PermissionBanType.ChannelBanCommand:
                        msg = $"**{command.Text}** command has been banned from use on this **channel**.";
                        break;
                    case PermissionsHandler.PermissionBanType.ChannelBanModule:
                        msg = $"**{command.Category}** module has been banned from use on this **channel**.";
                        break;
                    case PermissionsHandler.PermissionBanType.RoleBanCommand:
                        msg = $"You do not have a **role** which permits you the usage of **{command.Text}** command.";
                        break;
                    case PermissionsHandler.PermissionBanType.RoleBanModule:
                        msg = $"You do not have a **role** which permits you the usage of **{command.Category}** module.";
                        break;
                    case PermissionsHandler.PermissionBanType.UserBanCommand:
                        msg = $"{user.Mention}, You have been banned from using **{command.Text}** command.";
                        break;
                    case PermissionsHandler.PermissionBanType.UserBanModule:
                        msg = $"{user.Mention}, You have been banned from using **{command.Category}** module.";
                        break;
                    default:
                        return true;
                }
                if (PermissionsHandler._permissionsDict[user.Server].Verbose) //if verbose - print errors
                    Task.Run(() => channel.SendMessage(msg));
                return false;
            } catch (Exception ex) {
                if (PermissionsHandler._permissionsDict[user.Server].Verbose) //if verbose - print errors
                    Task.Run(() => channel.SendMessage(ex.Message));
                return false;
            }
        }
示例#7
0
 internal static bool GetMusic(User user)
 {
     SQLiteDataReader reader = SQL.ExecuteReader("select channel from flags where music = 1");
     List<long> streams = new List<long>();
     while (reader.Read())
         streams.Add(Convert.ToInt64(reader["channel"].ToString()));
     return user.VoiceChannel != null && streams.Contains(user.VoiceChannel.Id);
 }
		/// <summary> Bans a user from the provided server. </summary>
		public Task Ban(User user)
		{
			if (user == null) throw new ArgumentNullException(nameof(user));
			if (user.Server == null) throw new ArgumentException("Unable to ban a user in a private chat.");
			CheckReady();

			return _api.BanUser(user.Server.Id, user.Id);
		}
示例#9
0
 public int GetWarningsCount(User user)
 {
     if (_warnings.ContainsKey(user))
     {
         return _warnings[user];
     }
     return 0;
 }
		public Task SetChannelPermissions(Channel channel, User user, DualChannelPermissions permissions = null)
		{
			if (channel == null) throw new ArgumentNullException(nameof(channel));
			if (user == null) throw new ArgumentNullException(nameof(user));
			CheckReady();

			return SetChannelPermissions(channel, user?.Id, PermissionTarget.User, permissions?.Allow, permissions?.Deny);
		}
示例#11
0
 public Bomb(Discord.User atk, Discord.User def)
 {
     attacker = atk;
     defender = def;
     active   = true;
     wires    = wires.Skip(decider.Next(15, 23)).ToArray();
     wire     = wires[decider.Next(0, wires.Length)];
 }
		public Task SetChannelPermissions(Channel channel, User user, ChannelPermissions allow = null, ChannelPermissions deny = null)
		{
			if (channel == null) throw new ArgumentNullException(nameof(channel));
			if (user == null) throw new ArgumentNullException(nameof(user));
			CheckReady();

			return SetChannelPermissions(channel, user?.Id, PermissionTarget.User, allow, deny);
		}
示例#13
0
 public bool CanRun(Command command, User user, Channel channel, out string error)
 {
     error = string.Empty;
     if (user.ServerPermissions.ManageRoles)
         return true;
     error = "You do not have a permission to manage roles.";
     return false;
 }
		public Task RemoveChannelPermissions(Channel channel, User user)
		{
			if (channel == null) throw new ArgumentNullException(nameof(channel));
			if (user == null) throw new ArgumentNullException(nameof(user));
			CheckReady();

			return RemoveChannelPermissions(channel, user?.Id, PermissionTarget.User);
		}
示例#15
0
 public void SendLargeMessage(Discord.User user, string message)
 {
     while (message.Length > 1999)
     {
         user.SendMessage(message.Substring(0, 1999));
         message = message.Remove(0, 1999);
     }
     user.SendMessage(message);
 }
示例#16
0
    public UnspecificUserInfo(Discord.User User)
    {
        this.UserID          = User.Id;
        this.NumMessagesSent = 0;
        this.XP         = 0;
        this.LastXPGain = new DateTime();
        List <ServerSpecificUserInfo> NewServerInfo = new List <ServerSpecificUserInfo>();

        ServerInfo = NewServerInfo;
    }
示例#17
0
        public void AddWarning(Channel channel, User user)
        {
            if (!_warnings.ContainsKey(user))
            {
                _warnings.Add(user, 0);
            }
            _warnings[user]++;

            NotifyUserWarned(new UserWarnedEventArgs { Channel = channel, User = user, WarningCount = _warnings[user] });
        }
示例#18
0
 private Matbot.Client.User UserFromDiscordUser(Discord.User e)
 {
     if (e == null)
     {
         return(null);
     }
     Matbot.Client.User u = this.GetNewUser(e.Id);
     u.Name     = e.Name;
     u.Username = e.Nickname;
     return(u);
 }
示例#19
0
 static bool HasNeko(ref string msg, User user)
 {
     string neko = user.Name;
     string nekonick = user.Nickname;
     if (HasNekoEmojiOrNot(ref msg, neko)) // Have we been mentioned by our actual name?
     {
         HasNekoNick(ref msg, nekonick); // Strip nick, too, just in case.
         return true;
     }
     return HasNekoNick(ref msg, nekonick); // Have we been mentioned by our nick?
 }
示例#20
0
 private int findUserProfile(Discord.User user)
 {
     for (int i = 0; i < userProfiles.Count; i++)
     {
         if (userProfiles.ElementAt(i).user.Equals(user))
         {
             return(i);
         }
     }
     return(-1);
 }
示例#21
0
 public override void Execute(Server server, Discord.Channel channel, Discord.User user, string parameter, Dictionary <string, string> flags)
 {
     foreach (KeyValuePair <string, string> flag in flags)
     {
         //Welcome Flag
         if (flag.Key == "welcome")
         {
             server.Welcome = flag.Value;
             channel.SendMessage("A new welcome message has been set for this server!");
         }
     }
 }
示例#22
0
        //Handles responses to the !Battlenet command
        private static string Battletag(MessageEventArgs e)
        {
            string ID = "";

            ID = ExtractInformation(e.Message.Text);
            Discord.User mentioneduser = null;

            if (IsBattlenetID(ID))
            {
                SaveUser(ID, e);
                return("Battletag " + ID + " saved for " + e.User.Name + ".");
            }
            else if (ID.StartsWith("@"))
            {
                foreach (Discord.User user in e.Server.Users)
                {
                    if (user.NicknameMention == ID)
                    {
                        mentioneduser = user;
                        break;
                    }
                }

                if (users.ContainsKey(mentioneduser.Name))
                {
                    string battletag;
                    users.TryGetValue(mentioneduser.Name, out battletag);
                    return(battletag);
                }
                else
                {
                    return("Battletag not found.");
                }
            }
            else if (ID.ToLower() == "!battletag")
            {
                if (users.ContainsKey(e.User.Name))
                {
                    string battletag;
                    users.TryGetValue(e.User.Name, out battletag);
                    return(battletag);
                }
                else
                {
                    return("You have not yet set your Battletag with !Battletag [your battletag].");
                }
            }
            else
            {
                return("Set your battletag by using !Battletag [Your battletag]. Post your battletag by using !Battletag. See another user's battletag by using !Battletag then @mentioning them");
            };
        }
示例#23
0
 public bool CanRun(Command command, User user, Channel channel, out string error)
 {
     if (user.IsPrivate)
     {
         error = "This command can't be run in n a private chat.";
         return false;
     }
     else
     {
         error = null;
         return true;
     }
 }
示例#24
0
 public bool CanRun(Command command, User user, Channel channel, out string error)
 {
     if (user.Server != null)
     {
         error = "This command may only be run in a private chat.";
         return false;
     }
     else
     {
         error = null;
         return true;
     }
 }
示例#25
0
        private async Task <bool> addToRole(Discord.Role role, Discord.User target, MessageEventArgs e)
        {
            try
            {
                await target.AddRoles(role);
            } catch (Exception)
            {
                await e.Channel.SendMessage(SystemMessages.MESSAGE_ROLESETEXCEPTION);

                return(true);
            }
            return(true);
        }
示例#26
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);
        }
示例#27
0
        public override void SendPrivateMessage(object sender, MessageEventArgs messagedata)
        {
            try
            {
                Discord.User user = (Discord.User)messagedata.Destination.ExtraData;

                Console.WriteLine("Casted Fine To Discord");
                SendLargeMessage(user, messagedata.ReplyMessage);
            }
            catch
            {
                Console.WriteLine("Casting Error");
            }
        }
示例#28
0
 private bool detonate()
 {
     if (attacker != null && 2 == decider.Next(1, 4))
     {
         return(true);
     }
     else
     {
         Discord.User vic = defender;
         defender = attacker;
         attacker = vic;
         return(false);
     }
 }
示例#29
0
        public RPGPlayer GetPlayerData(Discord.User u)
        {
            foreach (RPGPlayer p in players)
            {
                if (p.id == u.Id)
                {
                    p.UpdateName(u.Name);
                    return(p);
                }
            }
            RPGPlayer player = new RPGPlayer(u);

            players.Add(player);
            return(player);
        }
示例#30
0
        private SolidColorBrush GetRoleColor(Discord.User user)
        {
            SolidColorBrush brush        = new SolidColorBrush(Windows.UI.Color.FromArgb(255, 255, 255, 255));
            int             previousRole = 0;

            foreach (var role in user.Roles)
            {
                if (role.Position > 0 && role.Position > previousRole)
                {
                    brush        = new SolidColorBrush(Windows.UI.Color.FromArgb(255, role.Color.R, role.Color.G, role.Color.B));
                    previousRole = role.Position;
                }
            }

            return(brush);
        }
示例#31
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);
        }
示例#32
0
        public async void  SendHelpMessage(Discord.User user)
        {
            string message = "";

            foreach (var command in helpCommands)
            {
                if ((message.Length + command.Length + Environment.NewLine.Length) < 2000)
                {
                    message += command + Environment.NewLine;
                }
                else
                {
                    await user.SendMessage(message);

                    message = command + Environment.NewLine;
                }
            }
        }
示例#33
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);
        }
示例#34
0
 private void registerBanCommand()
 {
     commands.CreateCommand("ban")
     .AddCheck((cm, u, ch) => u.ServerPermissions.Administrator)
     .Parameter("player", ParameterType.Required)
     .Parameter("reason", ParameterType.Required)
     .Do(async(e) =>
     {
         Discord.User target = e.Server.FindUsers(e.GetArg("player")).FirstOrDefault();
         if (getLogChannel(e.Server.Id) == "")
         {
             await e.Channel.SendMessage("You've gotta set a banlog channel with .setlogchannel first.");
             return;
         }
         Discord.Channel logChannel = e.Server.FindChannels(getLogChannel(e.Server.Id)).FirstOrDefault();
         await e.Server.Ban(target);
         await logChannel.SendMessage("Banned user **" + target.Name + "**. Reason given: " + e.GetArg("reason"));
     });
 }
示例#35
0
        public async void LeaveQueue(Discord.User user)
        {
            SettingsRepo settingsRepo = new SettingsRepo(new SettingsContext());

            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.Messages)
                    {
                        if (message.Text.Contains(user.ToString()))
                        {
                            await message.Delete();
                        }
                    }
                }
            }
        }
示例#36
0
 public bool CanRun(User user, Channel channel, out string error)
 {
     error = null;
     if (_commands.Count > 0)
     {
         foreach (var cmd in _commands)
         {
             if (cmd.CanRun(user, channel, out error))
                 return true;
         }
     }
     if (_items.Count > 0)
     {
         foreach (var item in _items)
         {
             if (item.Value.CanRun(user, channel, out error))
                 return true;
         }
     }
     return false;
 }
示例#37
0
        public Task<Karma> AdjustKarma(int amount, Channel channel, User toUser, User fromUser = null)
        {
            var tcs = new TaskCompletionSource<Karma>();

            try
            {
                if (!_karmaRepository.Exists(toUser.Id))
                {
                    _karmaRepository.Insert(new Karma { Id = toUser.Id, User = toUser, Amount = 0, LastUpdated = DateTime.Now });
                }

                var karma = _karmaRepository.GetById(toUser.Id);
                karma.Amount += amount;
                karma.LastUpdated = DateTime.Now;
                _karmaRepository.Update(karma);

                NotifyKarmaChanged(new KarmaChangedEventArgs { Channel = channel, FromUser = fromUser, ToUser = toUser, Amount = amount });

                var nextRank = GetNextRank(karma.Amount);
                if (karma.Amount == nextRank.RequiredKarma)
                {
                    NotifyRankChanged(new RankChangedEventArgs { Channel = channel, User = toUser, NewRank = nextRank });
                }

                tcs.TrySetResult(karma);
            }
            catch (Exception ex)
            {
                tcs.TrySetException(ex);
            }

            if (tcs.Task.Exception != null)
            {
                throw tcs.Task.Exception;
            }

            return tcs.Task;
        }
示例#38
0
        public Task<bool> CheckUserSpamming(Channel channel, User user, DateTime timeStamp)
        {
            var tcs = new TaskCompletionSource<bool>();

            try
            {
                if (!_messages.ContainsKey(user))
                {
                    _messages.Add(user, new List<DateTime> { timeStamp });

                    tcs.TrySetResult(false);
                }

                _messages[user].Add(timeStamp);

                var messagesWithinThreshold = _messages[user].Where(m => m > DateTime.Now.AddSeconds(-10));
                if (messagesWithinThreshold.Count() > 3)
                {
                    NotifyUserSpamming(new UserSpammingEventArgs { Channel = channel, User = user});

                    tcs.TrySetResult(true);
                }

                tcs.TrySetResult(false);
            }
            catch (Exception ex)
            {
                tcs.TrySetException(ex);
            }

            if (tcs.Task.Exception != null)
            {
                throw tcs.Task.Exception;
            }

            return tcs.Task;
        }
示例#39
0
        /// <summary>
        /// Get a number of messages from a channel by a specific user.
        /// </summary>
        /// <param name="c">The channel</param>
        /// <param name="u">The user</param>
        /// <param name="numReq">The number of messages requested</param>
        /// <returns></returns>
        public static async Task<IEnumerable<Message>> GetMessages(Channel c, User u, int numReq)
        {
            int currentCount = 0;
            int numToGetThisLoop = 100;
            int newMsgCount = 100;
            ulong lastMsgId;
            IEnumerable<Message> allMsgs = new List<Message>();
            IEnumerable<Message> newMsgs = new List<Message>();
            if (numReq <= 0) return null;                                         //Quit on bad request

            lastMsgId = (await c.DownloadMessages(1))[0].Id;                        //Start from last message (will be excluded)

            while (currentCount < numReq && newMsgCount == numToGetThisLoop)      //Keep going while we don't have enough, and haven't reached end of channel
            {
                newMsgs = await c.DownloadMessages(numToGetThisLoop, lastMsgId, Relative.Before, false);    //Get N messages before that id
                newMsgCount = newMsgs.Count();                                      //Get the count we downloaded, usually 100
                lastMsgId = newMsgs.Last().Id;                                      //Get the id to start from on next iteration
                newMsgs = newMsgs.Where(x => x.User == u);                          //Add only messages of user
                currentCount += newMsgs.Count();                                    //Add new messages to count
                allMsgs = allMsgs.Concat(newMsgs);                                  //Add messages to the list
            }

            return allMsgs.Take(numReq);
        }
示例#40
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);
                        }
                    }
                }
            }
        }
示例#41
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);
            }
        }
示例#42
0
        // Start the bot, pulling the calendar service from the main thread.
        public DiscordBot(CalendarService calendarService, DriveService driveService)
        {
            // Properly initialise the client.
            client = new DiscordClient(xyz =>
            {
                // Set log severity.
                xyz.LogLevel = LogSeverity.Info;
            });
            // Display the log message to the terminal.
            client.Log.Message += (s, e) => Console.WriteLine($"[{e.Severity}] {e.Source} { e.Message}");
            // Grab the provided prefix
            prefix = Program.config[1].ToCharArray()[0];
            // Configure the command structure.
            client.UsingCommands(xyz =>
            {
                // Set prefix character so that the bot knows what to look for.
                xyz.PrefixChar         = prefix;
                xyz.AllowMentionPrefix = true;
            });
            client.UsingAudio(xyz =>
            {
                // We're only sending audio, not receiving.
                xyz.Mode = AudioMode.Outgoing;
            });
            // Properly initialise the command service for issuing the commands to the bot.
            commands = client.GetService <CommandService>();

            /*
             * ██████╗  █████╗ ███████╗██╗ ██████╗
             * ██╔══██╗██╔══██╗██╔════╝██║██╔════╝
             * ██████╔╝███████║███████╗██║██║
             * ██╔══██╗██╔══██║╚════██║██║██║
             * ██████╔╝██║  ██║███████║██║╚██████╗
             * ╚═════╝ ╚═╝  ╚═╝╚══════╝╚═╝ ╚═════╝
             */
            commands.CreateCommand("help").Parameter("args", ParameterType.Multiple).Do(async(e) =>
            {
                // Command displays specified help text.
                // Delete the command message.
                await e.Message.Delete();
                // Initialise the arguments string
                string args = null;
                // If no arguments are passed, or 'all' is passed, we want to display all commands.
                if (e.Args.Length == 0 || e.Args.Contains("all"))
                {
                    args = "general beer events shitpost sound";
                }
                // Else we only want to display the ones that are specified.
                else
                {
                    args = string.Join(" ", e.Args).ToLower();
                }
                // Initialise the helptext list.
                List <string> helptext = new List <string>();
                // Add the basic usage to the helptext.
                helptext.Add($"Command usage : `{prefix}command <argument>`");
                // All text is pre-formatted when it's added to the list.
                // If general commands are specified, add them to the help text.
                if (args.Contains("general"))
                {
                    helptext.Add("**General**");
                    helptext.Add("```                info : display basic info about the bot.\n" +
                                 "        whois <user> : display <user>'s role on the server.\n" +
                                 "help <command group> : display help for specified command group.\n" +
                                 "         list groups : list the command groups.\n" +
                                 "         synchronise : sync the images & soundbytes with the Google Drive (Admin/OG FKTS only).\n" +
                                 "           changelog : show changelog.```");
                }
                // If beer commands are specified, add them to the help text.
                if (args.Contains("beer"))
                {
                    helptext.Add("**Beer**");
                    helptext.Add($"```  find <beername> : Search for <beername> and present to text channel.\n" +
                                 $"          suggest : get a random beer suggestion.\n" +
                                 $"giveme <beername> : grab the url of the store page of <beername> if possible.```");
                }
                // If event commands are specified, add them to the help text.
                if (args.Contains("event"))
                {
                    helptext.Add("**Event**");
                    helptext.Add("```      events : display upcoming events.\n" +
                                 "view <event> : display more information about <event>.```");
                }
                // If shitposting commands are specified, add them to the help text.
                if (args.Contains("image"))
                {
                    helptext.Add("**Random Image**");
                    helptext.Add("```         image : send a random shitpost.\n" +
                                 "     blacklist : display the current blacklist\n" +
                                 "clearblacklist : clear the shitpost blacklist.```");
                }
                // If sound commands are specified, add them to the help text.
                if (args.Contains("sound"))
                {
                    helptext.Add("**Sound**");
                    helptext.Add("```play <soundbyte> : play the specified soundbyte.\n" +
                                 "     list sounds : list available soundbytes.\n" +
                                 "           queue : display the current queue\n" +
                                 "     clear queue : clears the queue\n" +
                                 "      disconnect : force the bot to disconnect from the voice channel.```");
                }
                // Join the list into a continuous string, seperated by carriage returns
                string helpmessage = string.Join("\n", helptext.ToArray());
                // Inform the user help is on the way, and send the help.
                await e.Channel.SendMessage($"Sending requested help for {e.User.Mention}");
                await e.Channel.SendMessage($"{helpmessage}");
                // Inform the console of the command.
                Console.WriteLine($"[{e.Server}] Displaying help for {e.User.Name}");
            });
            commands.CreateCommand("whois").Parameter("otheruser", ParameterType.Multiple).Do(async(e) =>
            {
                // Command displas the primary role of the specified user.
                // Notes the command being issued and who issued it into the terminal.
                Console.WriteLine($"[{e.Server}] Command 'whois' called by {e.User.Name}");
                // Stores the provided name as a string.
                String name = string.Join(" ", e.Args);
                // Creates a DiscordUser object and finds the user in the server.
                Discord.User singleuser = e.Server.FindUsers(name).FirstOrDefault(t => t.Name == name);;
                // If the user exists...
                if (singleuser != null)
                {
                    // If the users role is not 'everyone'
                    if (singleuser.Roles.First().ToString() != "everyone")
                    {
                        // Converts role to a string, sends it to the FLIV function and tests if it begins with a vowel, this is for grammar.
                        if (functions.FLIV(singleuser.Roles.First().ToString().ToUpper()))
                        {
                            // Send the message back to the channel with correct grammar (eg. an Admin).
                            await e.Channel.SendMessage($"{singleuser.Name} is an {singleuser.Roles.First()}");
                        }
                        else
                        {
                            // Send the message back to the channel with correct grammar (eg. a Moderator).
                            await e.Channel.SendMessage($"{singleuser.Name} is a {singleuser.Roles.First()}");
                        }
                    }
                    else
                    {
                        // If the user has no special role, they're just a normal person.
                        await e.Channel.SendMessage($"{singleuser.Name} is just some random person.");
                    }
                }
                else
                {
                    // In the case of not finding the user, reports this to the terminal.
                    Console.WriteLine($"[{e.Server}] Command failed. No User '{e.GetArg("otheruser")}'");
                    // Also informs the command issuer by sending a message to the channel.
                    await e.Channel.SendMessage($"Could not find user: {e.GetArg("otheruser")}");
                }
            });
            // Command to display the author and status of this bot.
            commands.CreateCommand("info").Do(async(e) =>
            {
                // Command displays the bot info.
                // Delete the command message.
                await e.Message.Delete();
                // Notes the command being issued and who issued it into the terminal.
                Console.WriteLine($"[{e.Server}] Full bot info shown for {e.User.Name}");
                // Sends the information back to the channel
                await e.Channel.SendMessage($"CataBot v4, a Discord Bot made by Catalan.\n" +
                                            $"v4 adds Google Drive interaction.");
            });
            commands.CreateCommand("list").Parameter("args", ParameterType.Required).Do(async(e) =>
            {
                // Command lists the sounbytes or command groups
                // Delete the command message.
                await e.Message.Delete();
                // Inform the user that their list will be shown.
                await e.Channel.SendMessage($"List shown for {e.User.Mention}");
                // Display the correct list.
                if (e.GetArg("args").ToLower() == "sounds")
                {
                    // List the available soundbytes to the text channel.
                    await e.Channel.SendMessage($"*Available soundbytes:*");
                    string[] sounds = Directory.GetFiles(location + "sounds/");
                    for (int i = 0; i < sounds.Length; i++)
                    {
                        sounds[i] = sounds[i].Substring(sounds[i].LastIndexOf('/') + 1);
                        sounds[i] = sounds[i].Substring(0, sounds[i].IndexOf(".mp3"));
                    }
                    await e.Channel.SendMessage($"```{string.Join("\n", sounds)}```");
                    Console.WriteLine($"[{e.Server}] Soundbyte list shown for {e.User.Name}");
                }
                else if (e.GetArg("args").ToLower() == "groups")
                {
                    // Display what the command groups are to the text channel.
                    await e.Channel.SendMessage($"*Command Groups:*");
                    await e.Channel.SendMessage($"```null" +
                                                $"\nGeneral" +
                                                $"\nBeer" +
                                                $"\nEvents" +
                                                $"\nImages" +
                                                $"\nSound```");
                    Console.WriteLine($"[{e.Server}] Command groups shown for {e.User.Name}");
                }
                else
                {
                    // Inform the user if the specified list does not exist.
                    await e.Channel.SendMessage($"{e.User.Mention} that list doesn't exist!");
                }
            });
            commands.CreateCommand("synchronise").Alias(new string[] { "sync" }).Do(async(e) =>
            {
                // Command send a random shitpost to the text channel.
                // Delete the command message.
                await e.Message.Delete();
                // Specificy the roles need to issue this command,
                string[] reqRoles = { "Admin", "OG FKTS" };
                // If the user has the required permissions, execute the command as normal.
                if (reqRoles.Any(s => e.User.Roles.Any(r => r.Name.Contains(s))))
                {
                    // Inform the user that the shitpost is being sent
                    await e.Channel.SendMessage($"Synchronising files for {e.User.Mention}");
                    // Set the file extensions.
                    string[] imageExtensions = { ".jpg", ".png" };
                    string[] soundExtensions = { ".mp3", ".wav" };
                    try
                    {
                        // Pull the metadata for all image/sound files.
                        List <Google.Apis.Drive.v3.Data.File> iFiles = drive.GetFiles(driveService, imageExtensions);
                        List <Google.Apis.Drive.v3.Data.File> sFiles = drive.GetFiles(driveService, soundExtensions);
                        // Synchronise the folders.
                        drive.syncFiles(driveService, iFiles, "images/", e.Channel);
                        drive.syncFiles(driveService, sFiles, "sounds/", e.Channel);
                        await e.Channel.SendMessage("GDrive synchronisation complete.");
                        Console.WriteLine($"[{e.Server}] Synchronised with GDrive ({e.User.Name})");
                    }
                    catch
                    {
                        // If it fails, throw an error message to the user & console.
                        Console.WriteLine($"[{e.Server}] Failed to sync");
                        await e.Channel.SendMessage("GDrive synchronisation failed.");
                    }
                }
                else
                {
                    // If the user doesn't have the correct permissions, inform them.
                    await e.Channel.SendMessage($"{e.User.Mention} Insufficient permissions to  sync files.");
                }
            });
            commands.CreateCommand("exit").Do(async(e) =>
            {
                // Command shuts down the bot.
                // Delete the command message.
                await e.Message.Delete();
                await e.Channel.SendMessage($"***Shutting down CataBot***");
                // If user is an admin.
                if (e.User.Roles.Any(s => s.Name.Contains("Admin")))
                {
                    Environment.Exit(0);
                }
                else
                {
                    await e.Channel.SendMessage($"**YOU DO NOT HAVE ENOUGH BADGES TO TRAIN ME** {e.User.Mention}");
                }
            });

            /*
             * ██████╗ █████╗ ██╗     ███████╗███╗   ██╗██████╗  █████╗ ██████╗
             * ██╔════╝██╔══██╗██║     ██╔════╝████╗  ██║██╔══██╗██╔══██╗██╔══██╗
             * ██║     ███████║██║     █████╗  ██╔██╗ ██║██║  ██║███████║██████╔╝
             * ██║     ██╔══██║██║     ██╔══╝  ██║╚██╗██║██║  ██║██╔══██║██╔══██╗
             * ╚██████╗██║  ██║███████╗███████╗██║ ╚████║██████╔╝██║  ██║██║  ██║
             * ╚═════╝╚═╝  ╚═╝╚══════╝╚══════╝╚═╝  ╚═══╝╚═════╝ ╚═╝  ╚═╝╚═╝  ╚═╝
             */
            commands.CreateCommand("events").Do(async(e) =>
            {
                // Command displays all upcoming events.
                // Message handling for the command & log.
                Console.WriteLine($"[{e.Server}] Upcoming events shown for {e.User.Name}");
                await e.Message.Delete();
                // Set parameters and initial order for calendar events.
                calendarService = calendar.prepEvents(calendarService);
                // Begin the event feed.
                await e.Channel.SendMessage($"**Upcoming events:**");
                if (calendarService.Events.List("primary").Execute().Items != null && calendarService.Events.List("primary").Execute().Items.Count > 0)
                {
                    // Initialise event list
                    List <calendar.EventListItem> eventList = calendar.eshortDetails(calendarService);
                    // Create two new lists for events this month and next, Splitting the events list into the two new lists based on month.
                    List <calendar.EventListItem> ThisMonth = eventList.Where(x => x.ToString().Contains(functions.SanitiseMonth(DateTime.Now.Month.ToString()))).ToList();
                    List <calendar.EventListItem> NextMonth = eventList.Where(x => x.ToString().Contains(functions.SanitiseMonth((DateTime.Now.Month + 1).ToString()))).ToList();
                    // Builds the list into a multi-line string that can be printed.
                    string events          = string.Join("\n", eventList.ToArray());
                    string eventsthismonth = string.Join("\n", ThisMonth.ToArray());
                    string eventsnextmonth = string.Join("\n", NextMonth.ToArray());
                    // Print out the upcoming events, handling if there are none in the appropriate month.
                    await e.Channel.SendMessage($"*This Month:*");
                    if (ThisMonth.Count != 0)
                    {
                        await e.Channel.SendMessage($"```{eventsthismonth}```");
                    }
                    else
                    {
                        await e.Channel.SendMessage($"```*No events this month*```");
                    }
                    // Only display next month if there are any events.
                    if (ThisMonth.Count < 1)
                    {
                        await e.Channel.SendMessage($"*Later:*");
                        await e.Channel.SendMessage($"```{eventsnextmonth}```");
                    }
                }
                else
                {
                    // If there are no upcoming events at all, return this.
                    await e.Channel.SendMessage($"No upcoming events found.");
                }
            });
            commands.CreateCommand("view").Parameter("eventSearch", ParameterType.Multiple).Do(async(e) =>
            {
                // Command displays a specific event to the text channel.
                // Delete the command message.
                await e.Message.Delete();
                List <Event> events = new List <Event>(calendarService.Events.List("primary").Execute().Items);
                calendarService     = calendar.prepEvents(calendarService);
                if (events != null && events.Count > 0)
                {
                    string summaryMatch = calendar.matchEvent(calendarService, e.Args);
                    string[] details    = calendar.eventDetails(calendarService, summaryMatch);
                    await e.Channel.SendMessage($"**Event:** *{details[0]}*\n" +
                                                $"`Starts: {details[3]} | {details[2]}`\n" +
                                                $"`Ends:   {details[5]} | {details[4]}`\n" +
                                                $"Description:\n" +
                                                $"```{details[1]}```\n");
                }
                else
                {
                    await e.Channel.SendMessage($"No upcoming events to view");
                }
            });

            /*
             * ██████╗ ███████╗███████╗██████╗
             * ██╔══██╗██╔════╝██╔════╝██╔══██╗
             * ██████╔╝█████╗  █████╗  ██████╔╝
             * ██╔══██╗██╔══╝  ██╔══╝  ██╔══██╗
             * ██████╔╝███████╗███████╗██║  ██║
             * ╚═════╝ ╚══════╝╚══════╝╚═╝  ╚═╝
             */
            List <string> beers = new List <string>();

            beers.Add("brewery");
            beers.Add("country");
            beers.Add("styles");
            commands.CreateCommand("find").Parameter("beer", ParameterType.Multiple).Do(async(e) =>
            {
                // Command finds the specified beer and displays it.
                // Delete the command message.
                await e.Message.Delete();
                // Grab the name of the beer to look for.
                string BeerToSearch = string.Join(" ", e.Args);
                // Inform the user that a beer will be searched.
                await e.Channel.SendMessage($"Searching '*{BeerToSearch}*' for {e.User.Mention}");
                // Search for the beer and pull the URL.
                string url = beer.Search(BeerToSearch, beers);
                // Initialise lists to store beer info.
                List <string> MessageItem = new List <string>();
                List <string> Message     = new List <string>();
                if (url != "Not found!")
                {
                    // If beer was found, retrieve the details inc. image link
                    MessageItem = beer.Retrieve(url, e.Channel, "RandomBeer");
                    // Send beer name.
                    await e.Channel.SendMessage($"**{MessageItem[1]}**");
                    // Initialise a WebClient to grab the image.
                    WebClient webClient = new WebClient();
                    // Download the image and save it.
                    webClient.DownloadFile(MessageItem[0], "temp/beer-image.png");
                    // Dispose of the WebClient now that it is no longer needed.
                    webClient.Dispose();
                    // Send the image that was downloaded.
                    await e.Channel.SendFile("temp/beer-image.png");
                    // Send the remaining beer details.
                    string message = string.Join("\n", MessageItem.GetRange(2, MessageItem.Count - 2).ToArray());
                    await e.Channel.SendMessage($"{message}");
                    // Inform the console of the command.
                    Console.WriteLine($"[{e.Server}] beer found for {e.User.Name} ({MessageItem[1]})");
                }
                else
                {
                    await e.Channel.SendMessage($"Couldn't find '*{BeerToSearch}*'");
                    // Inform the console of the command.
                    Console.WriteLine($"[{e.Server}] beer not found for {e.User.Name} ({BeerToSearch})");
                }
            });
            commands.CreateCommand("suggest").Do(async(e) =>
            {
                // Command suggests a beer for the user and displays it.
                // Delete the command message.
                await e.Message.Delete();
                // Inform the user that a beer will be suggested.
                await e.Channel.SendMessage($"Suggesting a beer for {e.User.Mention}");
                // Search for a random beer and pull the URL.
                string url = beer.Search("RandomBeer", beers);
                // Initialise lists to store beer info.
                List <string> MessageItem = new List <string>();
                List <string> Message     = new List <string>();
                // Error handling if no URL could be pulled for whatever reason.
                if (url != "Not found!")
                {
                    // If beer was found, retrieve the details inc. image link
                    MessageItem = beer.Retrieve(url, e.Channel, "RandomBeer");
                    // Send beer name.
                    await e.Channel.SendMessage($"**{MessageItem[1]}**");
                    // Initialise a WebClient to grab the image.
                    WebClient webClient = new WebClient();
                    // Download the image and save it.
                    webClient.DownloadFile(MessageItem[0], "temp/beer-image.png");
                    // Dispose of the WebClient now that it is no longer needed.
                    webClient.Dispose();
                    // Send the image that was downloaded.
                    await e.Channel.SendFile("temp/beer-image.png");
                    // Send the remaining beer details.
                    string message = string.Join("\n", MessageItem.GetRange(2, MessageItem.Count - 2).ToArray());
                    await e.Channel.SendMessage($"{message}");
                    // Inform the console of the command.
                    Console.WriteLine($"[{e.Server}] beer suggested for {e.User.Name} ({MessageItem[1]})");
                }
                else
                {
                    await e.Channel.SendMessage($"Couldn't suggest a beer");
                    // Inform the console of the command.
                    Console.WriteLine($"[{e.Server}] beer could not be suggested for {e.User.Name}");
                }
            });
            commands.CreateCommand("giveme").Parameter("BeerToSearch", ParameterType.Multiple).Do(async(e) =>
            {
                // Command provides URL to the specified beer.
                // Delete the command message.
                await e.Message.Delete();
                // Grab the name of the beer to look for.
                string BeerToSearch = string.Join(" ", e.Args);
                // Inform the user that the link is being grabbed.
                await e.Channel.SendMessage($"Grabbing store page for {BeerToSearch} for {e.User.Mention}");
                // Find and pull the URL for the beer.
                string url = beer.Search(BeerToSearch, beers);
                // Send the URL to the channel.
                await e.Channel.SendMessage($"**URL:** {url}");
                // Inform the console of the command.
                Console.WriteLine($"[{e.Server}] beer URL pulled for {e.User.Name} ({BeerToSearch})");
            });

            /*
             * ███████╗ ██████╗ ██╗   ██╗███╗   ██╗██████╗
             * ██╔════╝██╔═══██╗██║   ██║████╗  ██║██╔══██╗
             * ███████╗██║   ██║██║   ██║██╔██╗ ██║██║  ██║
             * ╚════██║██║   ██║██║   ██║██║╚██╗██║██║  ██║
             * ███████║╚██████╔╝╚██████╔╝██║ ╚████║██████╔╝
             * ╚══════╝ ╚═════╝  ╚═════╝ ╚═╝  ╚═══╝╚═════╝
             */
            commands.CreateCommand("play").Parameter("audiofile", ParameterType.Required).Do(async(e) =>
            {
                // Command plays a specified soundbyte.
                // Delete the command message.
                await e.Message.Delete();
                // Get audio file selection.
                string audiofile = e.GetArg("audiofile");
                // Check if the requested file exists.
                if (functions.fileExists(audiofile))
                {
                    // Inform the user that the soundbyte is being played.
                    await e.Channel.SendMessage($"Playing '*{audiofile}*' for {e.User.Mention}");
                    // Add the soundbyte to the queue.
                    queue.Add(audiofile);
                    // If we're not sending audio, we will need to start sending audio.
                    if (!sendingAudio)
                    {
                        sendingAudio = true;
                        // Check if the user is in a voice channel.
                        if (e.User.VoiceChannel != null)
                        {
                            try
                            {
                                // If file exists, and user is in a voice channel, play it using the SendAudio function (further down).
                                SendAudio(e.User.VoiceChannel, e.Channel, e.Server);
                                // Inform the console.
                                Console.WriteLine($"[{e.Server}] {audiofile} soundbyte played for {e.User.Name}");
                            }
                            catch
                            {
                                // Inform the console.
                                Console.WriteLine($"[{e.Server}] {audiofile} soundbyte could not be played for {e.User.Name}");
                            }
                        }
                        else
                        {
                            // If user not in a voice channel, inform the terminal and tell the user to join a voice channel.
                            Console.WriteLine($"[{e.Server}] user {e.User.Name} not in voice channel");
                            await e.Channel.SendMessage($"{e.User.Mention} join a voice channel to use the soundboard!");
                        }
                    }
                }
                else
                {
                    // If the file does not exist, inform the user and the terminal.
                    await e.Channel.SendMessage($"{e.User.Mention} Couldn't find sound '{audiofile}'");
                    // Inform the console of the command.
                    Console.WriteLine($"[{e.Server}] file {audiofile} could not be found, or does not exist.");
                }
            });
            commands.CreateCommand("queue").Do(async(e) =>
            {
                // Command displays the queue.
                // Delete the command message.
                await e.Message.Delete();
                // Inform the user the queue will be shown.
                await e.Channel.SendMessage($"Showing queue for {e.User.Name}");
                // Grab the queue and turn it into a carriage return deliminated string.
                string Queue = string.Join("\n", queue.ToArray());
                // Send the list to the text channel and inform the console.
                await e.Channel.SendMessage("*Soundbyte queue:*");
                await e.Channel.SendMessage($"```{Queue}```");
                Console.WriteLine($"[{e.Server}] Showing soundbyte queue for {e.User.Name}");
            });
            commands.CreateCommand("clearqueue").Alias(new string[] { "cq" }).Do(async(e) =>
            {
                // Command clears the soundbyte queue.
                // Delete the command message.
                await e.Message.Delete();
                // Inform the user the queue is being cleared.
                await e.Channel.SendMessage($"Clearing queue for {e.User.Mention}");
                // Clear the blacklist.
                queue.Clear();
                // Inform the console of the command.
                Console.WriteLine($"[{e.Server}] Queue cleared by {e.User.Name}");
            });
            commands.CreateCommand("disconnect").Do(async(s) =>
            {
                // Command forces the bot to disconnect from the voice channel.
                // Delete the command message.
                await s.Message.Delete();
                // Disconnect the client from the voice channel.
                await vClient.Disconnect();
                // Clear the queue to avoid confusion upon restart of audio sending.
                queue.Clear();
            });

            /*
             * ██╗███╗   ███╗ █████╗  ██████╗ ███████╗███████╗
             *          ██║████╗ ████║██╔══██╗██╔════╝ ██╔════╝██╔════╝
             *          ██║██╔████╔██║███████║██║  ███╗█████╗  ███████╗
             *          ██║██║╚██╔╝██║██╔══██║██║   ██║██╔══╝  ╚════██║
             *          ██║██║ ╚═╝ ██║██║  ██║╚██████╔╝███████╗███████║
             *          ╚═╝╚═╝     ╚═╝╚═╝  ╚═╝ ╚═════╝ ╚══════╝╚══════╝
             */
            commands.CreateCommand("image").Do(async(e) =>
            {
                // Command send a random shitpost to the text channel.
                // Delete the command message.
                await e.Message.Delete();
                // Inform the user that the shitpost is being sent
                await e.Channel.SendMessage($"Sending random image for {e.User.Mention}");
                // Get all the filenames of the correct filetype from the google drive.
                string[] files = Directory.GetFiles(location + "images/");
                // Initialise a string to hold the file.
                string chosenfile = null;
                do
                {
                    // Pick a random file.
                    chosenfile = files[functions.GenIndex(files.Length)];
                    // Check if the file is on the blacklist
                    if (!blacklist.ToArray().Contains(chosenfile.Substring(chosenfile.LastIndexOf('/') + 1)))
                    {
                        // Add the sent file to the blacklist.
                        blacklist.Add(chosenfile.Substring(chosenfile.LastIndexOf('/') + 1));
                        // If it isn't, try to send the file.
                        try
                        {
                            // Send the file.
                            await e.Channel.SendFile(chosenfile);
                            // Inform the console.
                            Console.WriteLine($"[{e.Server}] Sending random image ('{chosenfile.Substring(chosenfile.LastIndexOf('/') + 1)}') for {e.User.Name}");
                        }
                        catch
                        {
                            // Inform the console.
                            Console.WriteLine($"[{e.Server}] Sending random image failure. Failed to send '{chosenfile.Substring(chosenfile.LastIndexOf('/') + 1)}' for {e.User.Name}");
                        }
                        break;
                    }
                    // If it is, repeat until it a non-blacklisted file is found and sent.
                } while (true);
                // If the blacklist is full, forget the first item.
                if (blacklist.Count > 100)
                {
                    blacklist.RemoveAt(0);
                }
                // Inform the console of the command.
                Console.WriteLine($"[{e.Server}] Blacklist updated [{blacklist.Count}]");
            });
            commands.CreateCommand("blacklist").Do(async(e) =>
            {
                // Delete the command message.
                await e.Message.Delete();
                // Inform the user the queue will be cleared.
                await e.Channel.SendMessage($"Showing blacklist for {e.User.Name}");
                string[] blcklst = blacklist.ToArray();
                for (int i = 0; i < blcklst.Length; i++)
                {
                    blcklst[i] = blcklst[i].Substring(blcklst[i].LastIndexOf('/'));
                }
                // Grab the queue and turn it into a carriage return deliminated string.
                string Blacklist = string.Join("\n", blcklst);
                // Send the list to the text channel and inform the console.
                await e.Channel.SendMessage("*Blacklist:*");
                await e.Channel.SendMessage($"```{string.Join("\n",blacklist.ToArray())}```");
                Console.WriteLine($"[{e.Server}] Showing blacklist for {e.User.Name}");
            });
            commands.CreateCommand("clearblacklist").Do(async(e) =>
            {
                // Command clears the shitpost blacklist.
                // Delete the command message.
                await e.Message.Delete();
                // Inform the user the blacklist is being cleared.
                await e.Channel.SendMessage($"Clearing random image blacklist for {e.User.Mention}");
                // Clear the blacklist.
                blacklist.Clear();
                // Inform the console of the command.
                Console.WriteLine($"[{e.Server}] Blacklist cleared by {e.User.Name}");
            });
            client.ExecuteAndWait(async() =>
            {
                // Connects the client using it's unique token.
                await client.Connect("BOT TOKEN HERE", TokenType.Bot);
                // Sets the game to be the help prompt, so users can easily issue the help command.
                client.SetGame($"v4 - {prefix}help for help.");
            });
        }
示例#43
0
 public UserProfile(Discord.User u, double p, Discord.Message m)
 {
     user        = u;
     pressure    = p;
     lastMessage = m;
 }
示例#44
0
		public Membership GetMembership(User user)
			=> GetMember(user.Id);
示例#45
0
 /// <summary>
 /// Sends the helpString to a user in a private message.
 /// </summary>
 /// <param name="user">User to send message to.</param>
 public void printHelp(Discord.User user)
 {
     user.SendMessage(String.Format(Resources.helpString, Assembly.GetExecutingAssembly().GetName().Version.ToString()));
 }
示例#46
0
        public static async Task SetUserCommandPermission(User user, string commandName, bool value)
        {
            var server = user.Server;
            var serverPerms = PermissionsDict.GetOrAdd(server.Id,
                new ServerPermissions(server.Id, server.Name));
            if (!serverPerms.UserPermissions.ContainsKey(user.Id))
                serverPerms.UserPermissions.Add(user.Id, new Permissions(user.Name));

            var commands = serverPerms.UserPermissions[user.Id].Commands;

            if (commands.ContainsKey(commandName))
                commands[commandName] = value;
            else
                commands.TryAdd(commandName, value);
            await WriteServerToJson(serverPerms).ConfigureAwait(false);
        }
示例#47
0
        internal static async Task CopyUserPermissions(User fromUser, User toUser)
        {
            var server = fromUser.Server;
            var serverPerms = PermissionsDict.GetOrAdd(server.Id,
                new ServerPermissions(server.Id, server.Name));

            var from = GetUserPermissionsById(server, fromUser.Id);
            if (from == null)
                serverPerms.UserPermissions.Add(fromUser.Id, from = new Permissions(fromUser.Name));
            var to = GetUserPermissionsById(server, toUser.Id);
            if (to == null)
                serverPerms.UserPermissions.Add(toUser.Id, to = new Permissions(toUser.Name));

            to.CopyFrom(from);

            await WriteServerToJson(serverPerms).ConfigureAwait(false);
        }
示例#48
0
        private async Task <Discord.Role> addToRole(string roleName, ServerPermissions permissions, Discord.User target, MessageEventArgs e)
        {
            Discord.Role newrole = null;
            try
            {
                newrole = await e.Server.CreateRole(roleName, permissions);

                await target.AddRoles(newrole);
            } catch (Exception)
            {
                await newrole.Delete();

                await e.Channel.SendMessage(SystemMessages.MESSAGE_ROLESETEXCEPTION);

                return(null);
            }
            return(newrole);
        }
示例#49
0
 private static string GetName(Discord.User user)
 {
     return((user.Nickname ?? user.Name) + "#" + user.Discriminator);
 }
示例#50
0
		/*internal void InvalidatePermissionsCache(Role role)
		{
			_areMembersStale = true;
			foreach (var member in role.Members)
				member.UpdateChannelPermissions(this);
		}*/
		internal void InvalidatePermissionsCache(User user)
		{
			_areMembersStale = true;
			user.UpdateChannelPermissions(this);
		}
        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);
                //        }
                //    }
                //}
            }
        }
示例#52
0
        public Form1()
        {
            InitializeComponent();

            bool UserFound  = false;
            bool TimeRanOut = false;

            string filePath = "test.html";

            originalPreview = File.ReadAllText(filePath);

            string clientID = Form2.cID;


            ////////////////////////
            // Enter Loading Mode //
            ////////////////////////

            discord = new Discord.Discord(Int64.Parse(clientID), (UInt64)Discord.CreateFlags.Default);

            // Managers
            activityManager    = discord.GetActivityManager();
            userManager        = discord.GetUserManager();
            applicationManager = discord.GetApplicationManager();

            // Logger
            discord.SetLogHook(Discord.LogLevel.Debug, (level, message) =>
            {
                Console.WriteLine("Log[{0}] {1}", level, message);
            });

            // Get Current User
            userManager.OnCurrentUserUpdate += () =>
            {
                currentUser = userManager.GetCurrentUser();
                Console.WriteLine("User {0} is {1}", currentUser.Id, currentUser.Username);
                Console.WriteLine("Test: {0}", currentUser.Avatar);
                UserFound = true;
            };

            // Run callbacks until all criteria met

            System.Timers.Timer aTimer = new System.Timers.Timer(5000);
            aTimer.Elapsed += (s, e) =>
            {
                TimeRanOut = true;
            };

            while (!UserFound && !TimeRanOut)
            {
                discord.RunCallbacks();
            }

            aTimer.Stop();
            aTimer.Dispose();
            Console.WriteLine("Loaded...");


            ////////////////
            // Form Setup //
            ////////////////

            // Activity setup
            textBox1.ForeColor = Color.Gray;
            textBox1.Text      = ActivitiesFiller;

            // Details setup
            textBox2.ForeColor = Color.Gray;
            textBox2.Text      = DetailsFiller;

            // Preview Setup (put into seperate function later)

            String file = originalPreview;

            file = file.Replace("CRP_PROFILE_IMAGE_PLACEHOLDER", "https://cdn.discordapp.com/avatars/" + currentUser.Id + "/" + currentUser.Avatar + ".png"); //profile img
            file = file.Replace("CRP_USERNAME_PLACEHOLDER", currentUser.Username);                                                                            //username
            file = file.Replace("CRP_DISCRIM_PLACEHOLDER", "#" + currentUser.Discriminator);                                                                  //discriminator
            file = file.Replace("CRP_ACTIVITYNAME_PLACEHOLDER", "");                                                                                          //activity name
            file = file.Replace("CRP_DESCRIPTION_PLACEHOLDER", "");                                                                                           //description
            file = file.Replace("CRP_LOBBY_PLACEHOLDER", " ");                                                                                                //lobby
            file = file.Replace("CRP_IMAGE_MARGIN_PLACEHOLDER", "");                                                                                          // < v thumbnails
            file = file.Replace("CRP_IMAGE_PLACEHOLDER", "");
            file = file.Replace("CRP_TIME_PLACEHOLDER", "");

            webView1.NavigateToString(file);


            //load in last used preset (if available)

            if (Form2.LUPexists)
            {
                RPreset preset = JsonConvert.DeserializeObject <RPreset>(File.ReadAllText(Form2.LUPpath));

                textBox1.Text         = preset.ActivityName;
                textBox2.Text         = preset.Description;
                checkBox1.Checked     = preset.InLobby;
                numericUpDown1.Value  = preset.LobbyCount;
                numericUpDown2.Value  = preset.LobbyMax;
                checkBox2.Checked     = preset.Thumbnails;
                textBox3.Text         = preset.LargeImageKeyword;
                textBox4.Text         = preset.LargeImageText;
                textBox5.Text         = preset.SmallImageKeyword;
                textBox6.Text         = preset.SmallImageText;
                checkBox3.Checked     = preset.TimeElapsedCheckbox;
                checkBox4.Checked     = preset.TimeRemainingCheckbox;
                dateTimePicker1.Value = preset.TimeElapsed;
                dateTimePicker2.Value = preset.TimeRemaining;

                textBox1.ForeColor = Color.Black;
                textBox2.ForeColor = Color.Black;
                updatePreview();
            }
        }
示例#53
0
        public static async Task SetUserModulePermission(User user, string moduleName, bool value)
        {
            var server = user.Server;
            var serverPerms = PermissionsDict.GetOrAdd(server.Id,
                new ServerPermissions(server.Id, server.Name));

            if (!serverPerms.UserPermissions.ContainsKey(user.Id))
                serverPerms.UserPermissions.Add(user.Id, new Permissions(user.Name));

            var modules = serverPerms.UserPermissions[user.Id].Modules;

            if (modules.ContainsKey(moduleName))
                modules[moduleName] = value;
            else
                modules.TryAdd(moduleName, value);
            await WriteServerToJson(serverPerms).ConfigureAwait(false);
        }
示例#54
0
    public async void Start()
    {
        _client = new DiscordClient();
        Console.WriteLine("Booting up bot...");

        _client.UsingCommands(x =>
        {
            x.PrefixChar = '-';
            x.HelpMode   = HelpMode.Public;
        });

        _client.Log.Message += (s, e) => Console.WriteLine($"[{e.Severity}] {e.Source}: {e.Message}");

        int MiniPhase = 0;

        CurrentTime = DateTime.Now;                            //grab current system time
        Minute      = CurrentTime.Minute;                      //grab current second
        Second      = CurrentTime.Second;                      //grab current second
        List <User>   MiniPlaying       = new List <User>();   // create list for users playing a mini twow
        List <string> SubmitterID       = new List <string>(); // create list for users submitting responses
        List <string> SubmitterResponse = new List <string>(); // create list for prompt responses

        _client.MessageReceived += async(s, e) =>
        {
            // Check to make sure that the bot is not the author
            if (e.Message.Text.ToLower() == "-mini")
            {
                await e.Channel.SendMessage($"{e.User.Mention}, try using `-mini help`.");
            }
            else if (e.Channel.IsPrivate)
            {
                if (e.Message.IsAuthor)
                {
                }
                else if (e.Message.Text.ToLower().Contains("-mini"))
                {
                    await e.Channel.SendMessage($"You cannot run -mini commands in DM's.");
                }
            }
        };
        while (MiniTime == 60)
        {
            MiniTime = 0;
            if (VotingTime == false)
            {
                VotingTime = true;
                MiniPhase++;
                await MiniChannel.SendMessage($"**Round {RoundNumber}** voting has begun!\n" +
                                              "**Prompt: " + PromptInput + "**\n" +
                                              "Remember, you viewers can vote whether you're a contestant or not!\n" +
                                              "If you're not a player or spectator, to vote use `-mini spec`\n" +
                                              "There is 1 minute to vote! Get going!\n" +
                                              "If you did NOT get the options, use `-mini options`. Sometimes options can take a little bit to get sent to you, though.");

                PromptInput = "";
                foreach (User u in MiniPlaying)
                {
                    await u.SendMessage("its been 1 min");
                }
            }
        }

        _client.GetService <CommandService>().CreateCommand("info") //create command
        .Alias(new string[] { "botinfo", "twowbotinfo" })           //add 2 aliases
        .Description("Displays bot info.")                          //add description, it will be shown when ~help is used
        .Do(async e =>
        {
            await e.Channel.SendMessage($"Heya {e.User.Mention}. I'm TWOWBot, nice to meet you! I was coded in C# by Noahkiq. You can check out my github page if you're interested at https://github.com/Noahkiq/TWOWBot");
            //sends a message to channel with the given text
        });

        _client.GetService <CommandService>().CreateCommand("invite") //create command
        .Alias(new string[] { "joinserver", "join" })                 //add aliases
        .Description("Posts the link to get the bot on your server.") //add description
        .Do(async e =>
        {
            await e.Channel.SendMessage($"You can add me to your server using https://discordapp.com/oauth2/authorize?client_id=222869815650418690&scope=bot - make sure you have `Manage Server` permissions!");
            //sends a message to channel with the given text
        });

        _client.GetService <CommandService>().CreateCommand("msg-test") //create command
        .Hide()
        .Description("sends a pm to the user that ran the command")     //add description
        .Do(async e =>
        {
            await e.User.SendMessage("hi " + e.User.Name);
            //sends a message to channel with the given text
        });

        _client.GetService <CommandService>().CreateCommand("twowr") //create command
        .Alias(new string[] { "twowrandomizer" })                    //add alias
        .Description("Starts a TWOW Randomizer.")                    //add description
        .Do(async e =>
        {
            string seasonString = File.ReadAllText("season.txt");
            int season          = Convert.ToInt32(seasonString);
            season++;
            File.WriteAllLines("season.txt", new string[] { $"{season}" });
            var response = new List <string> {
                "Meester Tweester", "Joseph Howard", "Crafty7", "Yessoan", "Ping Pong Cup Shots", "Tak Ajnin", "TheMightyMidge", "Mike Ramsay", "Spicyman33", "Midnight Light", "GreenTree", "QwerbyKing", "taopwnh6427", "some_nerd (The Pi Guy)", "Riley", "fryUaj", "alexlion0511", "Sam Billinge", "xXBombs_AwayXx", "The Futech Hacker", "steveminecraft46", "Jennings AsYetUntitled", "rinkrat02", "Ean EStone", "beanme100", "THATcommentor", "FlareonTheFlareon", "Juhmatok", "Quinn Ruddy", "DeeandEd", "Ni Hao Guylan", "Stalemate", "pokemonmanic3595", "Christian deWeever", "John Petrucci", "John Dubuc", "NitroNinja", "Smileyworkscompany", "chichinitz", "TimVideo 326", "AnimationCreated", "legotd61", "Ulises Castillo", "Ronan Sandoval", "Not Pro", "Will Zhang", "Mariobrosaa Productions", "The All Rounder | Marble Races", "WhoNeedsAName", "Erikfassett", "Diamondcup67", "Endr Dragon", "DanTheStripe", "Henry Scott", "BlueLucario98", "Reid Pozzi", "Carrotkid08", "Ben1178", "Thecatsonice", "Truttle1", "Aaron Rubin", "Aiden .C", "TehPizzaMan", "LucidSigma", "1Kick 234", "Xenon Virus", "JayBud", "RAM Turtle", "dancingfb18", "RedAdamA (Anything Ever)", "greenninjalizard123", "The Slime Bros", "Brand Utger", "swimswum", "Mapmaker Mapping (Parker Pearmain)", "BFDIBOYERSFTW", "Conor OMalley", "SergeantSnivy", "RainingPlates", "InfinitySnapz", "Hazel Cricket", "goldenzoomi", "Milo Jacquet", "LengthxWidth", "edtringaming", "funkydoge", "TheKoolkid209", "jerri76 likes trees", "AnyatheArtist", "Theo L", "American Camper", "NoobWithAFez", "zoroark SixtyFive", "Tyler Chai", "AugustMK7", "ItsSoooooFluffy", "Ali161102", "Bazinga_9000", "book81able", "Whiskerando", "XclockXanimations", "Jeelhu77", "zRAGE", "~Mr Sunny~", "GudPiggeh", "ZerOcarina", "John Mars (4DJumpman)", "TheMagicalKBMan", "TTGuy10000", "funnyboy044", "ahahahajee", "Villager #9", "ButterFlamingo", "Victini and Infinity Productions", "SeanyBoy", "Andyman620", "WindowVoid", "Vivek Saravanan", "Jack Spero", "DaKillahAidan", "Jacoub The Person", "Max McKeay", "MMMIK13", "Izumi Yoshida", "Paintspot Infez", "Lpcarver", "deepdata1", "Duck Wrath", "Roston11", "J_duude", "Ieatpie Prodcutions", "tumble", "james cooper", "AnEpikReshiramRBLX - Probably Crappy Machinimas!", "DylanMultiProduction", "Experimental Account", "SuperTurtle408", "Tile is kuel", "Poilik098", "Geometry Dash BlokPurrsun", "SolarBolt4 (TheShinyRayquaza47)", "PhantomJax", "PacoMan", "wifishark", "RockDudeMKW", "Sam Baker (thecool1204)", "Sqlslammer", "Timm638", "SubscribeSubscribedUnsubscribe", "David Rycan", "Zachary Ridall", "iAnimate38", "random57877", "YearsAnimations", "mmKALLL", "Varth_EDM", "XO Mapping", "elfireball42", "Wyatt Buss", "Ploot Adrain", "Thedrievienden", "RunToastRun", "Reviloja753 (Magnavox)", "cahlos 11", "2NoobFriendz", "richcolour", "Mar View", "snowruntlvr", "TardistheTardis", "lempamo", "Justyn Rodriguez", "I made this channel for TWOW", "Sean Leong", "TheUtubedude101", "GoldenMinecraft 29", "Peter N", "Bryan Rodin (bryshmy126)", "Loong Yaw Lee", "Luke C. (PenBFDI)", "cool chansey", "AnonymousMango", "ShinyStoutland", "KandyCreeper", "Roger Houses", "10gamerguy", "YellowJellow12 Gaming", "RidgeRR4", "Meduza yt", "Emation 1", "6j108", "Roman Neill", "bling popo", "ScienceFreakProdcutions", "Seth Rollins", "Awesomeness765", "loɹʇuoɔ soɐɥɔ", "MineWraith", "Donnie Melton", "Law Dog", "TheAwesomeDude", "Mae Young", "Citing Ostrich (StridentBoss)", "Gabe LaSalle", "BinaryBubbleGaming", "Pie Plays", "Stephen Kamenar", "catsanddogs333", "Oscar Field", "Cid Styles", "matheweon", "Thecactigod Oh", "Vaughn P", "Andrew Ratzlaff", "CrystaltheCool", "sc9849", "Battle for Something Official (BFST)", "Austin Eastwood", "KirbyRider1337", "justthebomb \"justthebo50\" blue", "Quinson Hon", "JerusalemStrayCat", "MasterOfZoroark", "Sawygo", "Bunpuffy", "MrMGamer", "Wolfster J", "Bendariaku", "Kenneth Ruff", "WildKat", "pokpower8", "evan skolnick", "TheDonuts42", "Devoid Amoeba", "Vcr-San", "Isaiah Y", "Krangle", "Mista Fown", "Kathie Bennett", "Brady Chan", "Awesome Animator", "Snoop Frogg", "Krishna Mandal", "bubblestars", "Lyndon Fan", "TheITChap", "livingpyramid", "Harry Odiakosa", "Computer 2468", "Stadin6", "WhaiJay", "FrogEatsGames", "minecraftwithkitties", "Justin Lo", "Wobbuffet64", "TheGenoYoshi", "Cyffreddinol", "Shaymin Lover", "Phant0mInfinity", "Huri Churi", "stephan Eijgelaar", "Sam-Fone Cheung", "GizmotheGamer", "REX CAVALIER (Sprite)", "Pandadude12345", "Matthew Doan", "Tantusar", "Ann Ant", "Izach Castro", "Carroll Addington", "misterjakester", "Scrooty 6362161296", "SkyBox101", "dakillahbunnyz", "Marco Mora lorca", "AnimationEpic", "CyanDrop", "Theelementalraccoon", "StarSphere08", "Leo O'Connor", "Jacob Thomas", "Bahgg Muhhhbah (of the many realms)", "lorri peterman", "Objectdude73", "Object Awards", "sharunkis", "BeastModeON !", "IzlePox", "2004froggy CP AJ", "Jack Orange", "NOT a gaming channel", "DONT VOTE IN THE COMMENTS", "TheKimpesShow", "basedzach", "geisterfurz007", "Cactus Power", "FireProofPotatoes", "Aliendude 321", "WhattheDerp", "ElectricPichu", "Minecraft Player", "TheNamelessChannel", "Rainbow drugg", "NumberDerp", "pokemonwalkingdead", "Nazrininator", "shannon spriggs", "nathan T", "Hugheseyboy 103", "CobaltGameMixer676", "PlasmaEmpire", "Novakobx22", "Br Miller", "CrazyCyanWaffle", "AsrielAvenue", "Silver Koopa888", "Brandon Olague", "Lukas Chan", "Miniwa the adventurer", "Cy Duck", "CubeBag", "Mr Leafy The Leafeon2", "AnimationArtist", "CommentingEevee", "retro boy", "Minh Nguyễn Nhật", "Mason Liu (ThePiGuy31415926535)", "MatrVincent- Servicing the Object Community!", "Denis Kogevnikov", "A Doctor Who", "akka777", "Kyle Stubbs", "Andy Pham", "Colin Ho", "Ruby Ninja", "ישראלה מויאל", "Nate Animations", "Pie Mc Pie", "Mudkipian Emporer", "SupremeGoldenRockies", "bra me", "brettsmart58", "Aqua Vulpes", "dombie brains", "TheRedArmy", "Coo haa", "east3myway", "M&M Awesome", "Thatkomedykid - great comedy videos!", "Auto Cats", "SBem14", "TDSwaggyBoy", "danielordeath \"BFRI SOON\" 2015", "Magical Genie", "Ue Hang Wong", "Phantastrophy", "Jacob Ward", "Joseph ~ TNTcreeper", "Mortuary Manager", "TheTGrodz", "Loftix", "Noah Alperovitz", "Caspar Coster", "thesuperbouncyballs", "the worst person in the object community", "Ken \"Kidsy 128\"", "Jake Beaulieu (Jakegames2)", "MrTacoLazer", "ღEeveeLikesToastღ", "Kyle Lazorko", "MICHAEL MCQUAY", "YpCoProductions", "Anton Christensen", "WebzForevz / Excellent Entities !", "coolguy20000000", "Brendan Glascock", "MetalMan Studios", "4613theo", "lilczar00", "Tornusge Bladestorm", "PuffQuit", "KennyPlex InterWorld", "SkyMix_RMT", "hyates animations", "SnowballBFDI", "Grand Landmaster", "M00ZE", "RedTedGaming", "정보규", "josh9969", "Faith Erdem Kɪᴢɪlkaya", "Sam Lee", "Stanley Huh", "Rogers Six", "Achoo", "Timothy Salaway", "joshuathemagician (Joshua Mackenzie)", "Voyager Studio", "Nick Grant", "EvilOrso", "Nathan Hon", "Leonardo Viera de Souza", "Speedgoy", "Recent .Snowfall", "Awesomez53", "SilverLighter 11", "Vincent Valor", "pegasus6540", "Raylover9462", "CheckerboardsMC", "Oprah gives you a Flowey meme in your face", "Toad8508", "SoocieSoocie", "Numero Uno Apple", "KID GAMING!", "Kasper Christensen", "Tachibanana", "Official Confused Sign (OCS)", "Lautrix Gaming", "EmperorMagenta", "piplupfan32", "Eviyon Wygant", "CampsOfficial 123", "Nico Balint", "EverestAnimationz", "Lance Craig", "Silver Knight", "Firey", "ObjectsVsMinecraft", "PENGUN STUDIOS", "Dan \"rubberducky8000\" C.", "IronCow Tom", "Dalton Bledrose", "Panzer Inversion", "Lance Alip", "Wintar", "FUUUUman01", "pokelol97", "Popcorn", "Ferok", "Ryan Chow", "zie mij gamen", "Kyle Hubbard", "YTPmachine123", "Mikenkanikal", "RedBreloom", "naltronix", "This is my name", "Henrique Prestes", "MangledObject", "BlackPhanth0m", "vladik huk", "Minsel", "ChavoMixel Commentry", "Jamie Keane", "[MNI]TronCrusher", "kurpingspace productions", "Joshua Wong", "William Sze-to", "Rasengan Master 23", "Shattrdpixel", "stanley Jr. Huh", "Jacob Schuøszernouszęl 9001", "theawesomenessdude", "Samer Gamer", "The Fun Gang", "hamizannaruto", "Ashr", "Cool Mac Gaming", "wholewheat", "kaycalgamer 53", "bloon 104", "Nathan Show", "HeyLookInsteadIMadeAChannel !", "firstname iskowitz", "OmegaPsi", "Total Craft", "Dj Beta", "HVLetsPlay", "Animation Field", "sandroshubitidize HAH", "Kashif Chaudhry", "Samuel Argar", "WaterBrickCraft WBC DoubleUBeeCee", "Tai Mau", "ads13000", "Nashriq Akmal", "Alex Canine", "Geometry Dash Demonsodemonic", "Jaime Mora Lorca", "Bannapal Dog", "A.N.9K"
            };
            await e.Channel.SendMessage($"Welcome everyone to TWOW #{season}! We have a huge list of contestants, so many I can't even list them all, so let's just see who's being eliminated this first episode.");

            //sends a message to channel with the given text
        });

        _client.GetService <CommandService>().CreateGroup("mini", cgb =>
        {
            cgb.CreateCommand("help")
            .Description("Displays list of subcommands.")
            .Do(async(e) =>
            {
                await e.Channel.SendMessage($"__Mini TWOW Subcommands:__\n\n" +
                                            "`create` - Create a Mini TWOW.\n" +
                                            "`join` - Join a Mini TWOW.\n" +
                                            "`start` - Start a Mini TWOW.");
            });

            cgb.CreateCommand("debug")
            .Description("Displays debug info about Mini TWOWs.")
            .Hide()
            .Do(async(e) =>
            {
                if (e.User.Id == BotHost)
                {
                    await e.Channel.SendMessage($"__Debug Info:__\n" +
                                                "CreatorID: `" + CreatorID + "`\n" +
                                                "MiniPhase: `" + MiniPhase + "`\n" +
                                                "PromptInput: `" + PromptInput + "`\n" +
                                                "RoundNumber: `" + RoundNumber + "`\n" +
                                                "PlayerCount: `" + PlayerCount + "`\n" +
                                                "MiniTime: `" + MiniTime + "`\n");
                }
                else
                {
                    await e.Channel.SendMessage($"You are not permitted to use this command!");
                }
            });

            cgb.CreateCommand("create")
            .Description("Create a Mini TWOW.")
            .Do(async(e) =>
            {
                //checks if a mini twow is in progress
                if (MiniPhase > 0)
                {
                    await e.Channel.SendMessage($"A Mini TWOW is already in progress.");
                    //sends message
                }
                else
                {
                    Program.CreatorID = e.User.Id;
                    MiniPhase++;         //adds 1 to "MiniPhase" int
                    await e.Channel.SendMessage($"{e.User.Mention} has created a Mini TWOW!\n" +
                                                "Use `-mini join` to join.\n" +
                                                "Use `-mini leave` to leave.\n" +
                                                "Use `-mini spec` to spectate.");
                }
            });

            cgb.CreateCommand("join")
            .Description("Join a Mini TWOW.")
            .Do(async(e) =>
            {
                //check if game has started
                if (MiniPhase > 1)
                {
                    await e.Channel.SendMessage($"The game has already started.");
                    //send message
                }
                else if (MiniPhase == 0)
                {
                    await e.Channel.SendMessage($"There is no game running yet! Try doing `-mini create` first.");
                    //surprisingly, this sends a message.
                }
                else
                {
                    string UserID = e.User.Id.ToString();              //create string for user's id
                    foreach (var item in MiniPlaying)
                    {
                        if (item == e.Server.GetUser(e.User.Id))
                        {
                            MiniParticipating = true;
                        }
                    }
                    //^ check if user's id is in the miniplaying list already

                    if (MiniParticipating == true)
                    {
                        await e.Channel.SendMessage($"{e.User.Mention}, you've already joined the game!");
                        //send message
                    }
                    else
                    {
                        PlayerCount++;
                        await e.Channel.SendMessage($"{e.User.Mention} has joined the game.");             //send message
                        MiniPlaying.Add(e.User.Server.GetUser(e.User.Id));
                        MiniParticipating = false;
                    }
                }
            });

            cgb.CreateCommand("leave")
            .Description("Leave a Mini TWOW.")
            .Do(async(e) =>
            {
                string UserID = e.User.Id.ToString();              //create string for user's id
                foreach (var item in MiniPlaying)
                {
                    if (item == e.Server.GetUser(e.User.Id))
                    {
                        MiniParticipating = true;
                    }
                }
                //^ check if user's id is in the miniplaying list already

                if (MiniParticipating == false)
                {
                    await e.Channel.SendMessage($"{e.User.Mention}, you're not in a Mini TWOW!");
                    //send message
                }
                else
                {
                    PlayerCount--;
                    await e.Channel.SendMessage($"{e.User.Mention} has left the game.");             //send message
                    MiniPlaying.Remove(e.User.Server.GetUser(e.User.Id));
                    MiniParticipating = false;
                }
            });

            cgb.CreateCommand("start")
            .Description("Start a Mini TWOW.")
            .Do(async(e) =>
            {
                //check if game has started
                if (MiniPhase > 1)
                {
                    await e.Channel.SendMessage($"The game has already started.");
                    //send message
                }
                else if (MiniPhase == 0)
                {
                    await e.Channel.SendMessage($"There is no game running yet! Try doing `-mini create` first.");
                    //surprisingly, this sends a message.
                }
                else
                {
                    if (e.User.Id != Program.CreatorID)
                    {
                        await e.Channel.SendMessage($"Only the game creator can use this command.");
                    }
                    else
                    {
                        if (PlayerCount > 1)
                        {
                            MiniPhase++;             //add one to MiniPhase
                            await e.Channel.SendMessage($"The game has been started. Nobody else is allowed to join.");
                        }
                        else
                        {
                            await e.Channel.SendMessage($"You need atleast 2 players to start the game.");
                        }
                    }
                }
            });

            cgb.CreateCommand("prompt")
            .Description("Enter the round's prompt.")
            .Parameter("Prompt", ParameterType.Unparsed)
            .Do(async(e) =>
            {
                //check if game is running
                if (MiniPhase == 0)
                {
                    await e.Channel.SendMessage($"There is no game running yet! Try doing `-mini create` first.");
                    //surprisingly, this sends a message.
                }
                //check if command runner is creator
                else if (e.User.Id != CreatorID)
                {
                    await e.Channel.SendMessage($"Only the game creator can run this command!");
                }
                //check if game has started yet
                else if (MiniPhase == 1)
                {
                    await e.Channel.SendMessage($"You need to start the game first. (`-mini start`)");
                    //send message
                }
                else
                {
                    if (PromptInput == "")
                    {
                        if (e.GetArg("Prompt") != "")
                        {
                            MiniChannel   = e.Channel.Server.GetChannel(e.Channel.Id);
                            CurrentSecond = Second;
                            RoundNumber++;
                            MiniPhase++;
                            PromptInput = e.GetArg("Prompt");
                            await e.Channel.SendMessage($"**Round {RoundNumber} prompt** ({PlayerCount} players):\n" +
                                                        "**" + PromptInput + "**\n" +
                                                        "You have 2 minutes!\n" +
                                                        "If you are a player, send me a private message: `-mini submit <response>`\n" +
                                                        "e.g. `-mini submit Anything relating to the prompt in ten words or fewer!`\n");
                            foreach (User u in MiniPlaying)
                            {
                                await u.SendMessage("hi");
                            }

                            System.Timers.Timer aTimer = new System.Timers.Timer();
                            aTimer.Elapsed            += new ElapsedEventHandler(OnTimedEvent);
                            aTimer.Interval            = 1000;
                            aTimer.Enabled             = true;
                        }
                        else
                        {
                            await e.Channel.SendMessage($"You must enter a prompt.");
                        }
                    }
                    else
                    {
                        await e.Channel.SendMessage($"It's not time to enter a prompt yet!");
                    }
                }
            });
        });

        _client.GetService <CommandService>().CreateCommand("userinfo")
        .Description("Displays info about a user.")
        .Parameter("User", ParameterType.Optional)
        .Do(async e =>
        {
            string mension     = e.GetArg("User");
            ulong id           = e.User.Id;
            string username    = e.User.Name;
            string avatar      = e.User.AvatarUrl;
            Discord.User roles = (Discord.User)e.User.Roles;
            if (e.GetArg("User") != "")
            {
                if (mension.Contains("!"))
                {
                    id = ulong.Parse(mension.Split('!')[1].Split('>')[0]);
                }
                else
                {
                    id = ulong.Parse(mension.Split('@')[1].Split('>')[0]);
                }

                username = e.Server.GetUser(id).Name;
                avatar   = e.Server.GetUser(id).AvatarUrl;
                roles    = (Discord.User)e.Server.GetUser(id).Roles;
            }

            await e.Channel.SendMessage($"```\nID:       {id}\n" +
                                        $"Username: {username}\n" +
                                        $"Roles: {roles}\n```" +
                                        $"\n{avatar}\n");
        });

        string token = File.ReadAllText("token.config");

        _client.ExecuteAndWait(async() =>
        {
            await _client.Connect("Bot " + token);
            _client.SetGame("some Mini TWOWs. And losing. :(");
        });
    }
示例#55
0
        internal static PermissionBanType GetPermissionBanType(Command command, User user, Channel channel)
        {
            var server = user.Server;
            ServerPermissions serverPerms = PermissionsDict.GetOrAdd(server.Id, id => new ServerPermissions(id, server.Name));
            bool val;
            Permissions perm;
            //server
            if (serverPerms.Permissions.Modules.TryGetValue(command.Category, out val) && val == false)
                return PermissionBanType.ServerBanModule;
            if (serverPerms.Permissions.Commands.TryGetValue(command.Text, out val) && val == false)
                return PermissionBanType.ServerBanCommand;
            //channel
            if (serverPerms.ChannelPermissions.TryGetValue(channel.Id, out perm) &&
                perm.Modules.TryGetValue(command.Category, out val) && val == false)
                return PermissionBanType.ChannelBanModule;
            if (serverPerms.ChannelPermissions.TryGetValue(channel.Id, out perm) &&
                perm.Commands.TryGetValue(command.Text, out val) && val == false)
                return PermissionBanType.ChannelBanCommand;

            //ROLE PART - TWO CASES
            // FIRST CASE:
            // IF EVERY ROLE USER HAS IS BANNED FROM THE MODULE,
            // THAT MEANS USER CANNOT RUN THIS COMMAND
            // IF AT LEAST ONE ROLE EXIST THAT IS NOT BANNED,
            // USER CAN RUN THE COMMAND
            var foundNotBannedRole = false;
            foreach (var role in user.Roles)
            {
                //if every role is banned from using the module -> rolebanmodule
                if (serverPerms.RolePermissions.TryGetValue(role.Id, out perm) &&
                perm.Modules.TryGetValue(command.Category, out val) && val == false)
                    continue;
                foundNotBannedRole = true;
                break;
            }
            if (!foundNotBannedRole)
                return PermissionBanType.RoleBanModule;

            // SECOND CASE:
            // IF EVERY ROLE USER HAS IS BANNED FROM THE COMMAND,
            // THAT MEANS USER CANNOT RUN THAT COMMAND
            // IF AT LEAST ONE ROLE EXISTS THAT IS NOT BANNED,
            // USER CAN RUN THE COMMAND
            foundNotBannedRole = false;
            foreach (var role in user.Roles)
            {
                //if every role is banned from using the module -> rolebanmodule
                if (serverPerms.RolePermissions.TryGetValue(role.Id, out perm) &&
                perm.Commands.TryGetValue(command.Text, out val) && val == false)
                    continue;
                else
                {
                    foundNotBannedRole = true;
                    break;
                }
            }
            if (!foundNotBannedRole)
                return PermissionBanType.RoleBanCommand;

            //user
            if (serverPerms.UserPermissions.TryGetValue(user.Id, out perm) &&
                perm.Modules.TryGetValue(command.Category, out val) && val == false)
                return PermissionBanType.UserBanModule;
            if (serverPerms.UserPermissions.TryGetValue(user.Id, out perm) &&
                perm.Commands.TryGetValue(command.Text, out val) && val == false)
                return PermissionBanType.UserBanCommand;

            return PermissionBanType.None;
        }
示例#56
0
 public bool CanRun(User user)
 {
     return _userList.ContainsKey(user.Id);
 }
示例#57
0
 public BridgeUser(Discord.User discordUser) : base(discordUser.Name)
 {
     DiscordUser = discordUser;
 }
示例#58
0
		/// <summary> Returns the string used to create a user mention. </summary>
		public static string User(User user)
			=> $"<@{user.Id}>";
示例#59
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");
                        }
                    }
                }
            }
        }
示例#60
0
 public BridgeUser(TShockAPI.DB.User user, Discord.User discordUser) : this(user)
 {
     DiscordUser = discordUser;
     IsLoggedIn  = true;
 }