Пример #1
0
        private async Task UpdateInGame(SocketGuildUser user)
        {
            bool inGame = user.Game.HasValue;

            if (inGameRole == null)
            {
                inGameRole = _client.GetGuild(user.Guild.Id).Roles.FirstOrDefault(x => x.Name == "In Game");
            }

            if (streamingRole == null)
            {
                streamingRole = _client.GetGuild(user.Guild.Id).Roles.FirstOrDefault(x => x.Name == "Streaming");
            }

            if (inGame)
            {
                if (user.Game.Value.StreamType != StreamType.NotStreaming)
                {
                    await user.AddRoleAsync(streamingRole);
                }
                else
                {
                    await user.RemoveRoleAsync(streamingRole);
                }
                await user.AddRoleAsync(inGameRole);
            }
            else
            {
                await user.RemoveRoleAsync(inGameRole);

                await user.RemoveRoleAsync(streamingRole);
            }
        }
Пример #2
0
        public async Task MuteAsync([NoSelf] SocketGuildUser user)
        {
            var guildUser = Context.User as SocketGuildUser;

            if (!guildUser.GuildPermissions.ManageRoles)
            {
                string description =
                    $"{Global.ENo} **|** You Need the **Manage Roles** Permission to do that {Context.User.Username}";
                var errorEmbed = EmbedHandler.CreateEmbed(Context, "Error", description,
                                                          EmbedHandler.EmbedMessageType.Exception);
                await ReplyAndDeleteAsync("", embed : errorEmbed);

                return;
            }

            var muteRole = await GetMuteRole(user.Guild);

            if (!user.Roles.Any(r => r.Id == muteRole.Id))
            {
                await user.AddRoleAsync(muteRole).ConfigureAwait(false);
            }
            var gld   = Context.Guild as SocketGuild;
            var muted = user.Guild.Roles.Where(input => input.Name.ToUpper() == "MUTED").FirstOrDefault() as SocketRole;
            var embed = new EmbedBuilder();

            embed.WithColor(Global.NayuColor);
            embed.Title       = $"**{user.Username}** was muted";
            embed.Description = $"**Username: **{user.Username}\n**Muted by: **{Context.User.Username}";
            await user.AddRoleAsync(muted);

            await SendMessage(Context, embed.Build());
        }
Пример #3
0
        private async Task userjoinGiveaway(SocketGuildUser arg)
        {
            if (arg.Guild.Id == currgiveaway.giveawayguild.guildID)
            {
                var role         = _client.GetGuild(currgiveaway.giveawayguild.guildID).Roles.FirstOrDefault(r1 => r1.Name == "Admins");
                var role2        = _client.GetGuild(currgiveaway.giveawayguild.guildID).Roles.FirstOrDefault(r2 => r2.Name == "Contestants");
                var r            = _client.GetGuild(SwissGuildId).GetUser(arg.Id).Roles;
                var adminrolepos = _client.GetGuild(SwissGuildId).Roles.FirstOrDefault(x => x.Id == Global.DeveloperRoleId).Position;
                var rolepos      = r.FirstOrDefault(x => x.Position >= adminrolepos);
                if (rolepos != null)
                {
                    await arg.AddRoleAsync(role);
                }
                else
                {
                    await arg.AddRoleAsync(role2);

                    GiveawayUser u = new GiveawayUser()
                    {
                        id          = arg.Id,
                        user        = arg,
                        bannedUsers = new List <GiveawayUser>(),
                        bans        = 0,
                        DiscordName = arg.ToString()
                    };
                    currgiveaway.giveawayguild.giveawayEntryMembers.Add(u);
                }
            }
        }
Пример #4
0
        public static async Task JoinBaboonHouse(SocketReaction emoji)
        {
            SocketGuildUser user         = emoji.User.Value as SocketGuildUser;
            IRole           previousRole = (user as IGuildUser).Guild.Roles.FirstOrDefault(x => x.Name == Setup.AwakenedApeRole);
            IRole           newRole      = (user as IGuildUser).Guild.Roles.FirstOrDefault(x => x.Name == Setup.TribeMemberRole);
            IRole           houseRole    = (user as IGuildUser).Guild.Roles.FirstOrDefault(x => x.Name == Setup.HouseOfBaboonRole);
            await user.AddRoleAsync(newRole);

            await user.AddRoleAsync(houseRole);

            await user.RemoveRoleAsync(previousRole);

            EmbedBuilder eb = new EmbedBuilder();
            await emoji.User.Value.SendFileAsync(Setup.BaboonIconPicturePath);

            eb.Title = "**" + user.Guild.Name + "**";
            string text =
                "You have been approved!" + "\n" +
                "Welcome to **House of Baboon**." + "\n" +
                "\n" +
                "__Type in server chat for list of commands:__ " + Setup.Client.CurrentUser.Mention + " help";

            eb.WithDescription(text);
            eb.WithColor(Color.Green);
            await emoji.User.Value.SendMessageAsync("", false, eb.Build());
        }
Пример #5
0
        private async Task MuteUserGuildAsync(SocketGuildUser user, SocketRole muteRole, IEnumerable <OwnedRole> roles, SocketRole modMuteRole = null)
        {
            if (muteRole != null)
            {
                if (!user.Roles.Contains(muteRole))
                {
                    await user.AddRoleAsync(muteRole);
                }
            }

            if (modMuteRole != null)
            {
                if (!user.Roles.Contains(modMuteRole))
                {
                    await user.AddRoleAsync(modMuteRole);
                }
            }

            if (roles != null)
            {
                foreach (var role in roles)
                {
                    var r = user.Guild.GetRole(role.Role);

                    if (r != null)
                    {
                        if (user.Roles.Contains(r))
                        {
                            await user.RemoveRoleAsync(r);
                        }
                    }
                }
            }
        }
Пример #6
0
        public static async Task ReapplyDisciplinaryAction(DisciplinaryEventEnum eventType, SocketGuildUser user)
        {
            try
            {
                IRole role;
                switch (eventType)
                {
                case DisciplinaryEventEnum.MuteEvent:
                    role = DiscordContextSeymour.GrabRole(MordhauRoleEnum.Muted);
                    await user.AddRoleAsync(role);

                    break;

                case DisciplinaryEventEnum.LimitedUserEvent:
                    role = DiscordContextSeymour.GrabRole(MordhauRoleEnum.LimitedUser);
                    await user.AddRoleAsync(role);

                    break;

                default:
                    break;
                }
            }
            catch (Exception ex)
            {
                ExceptionManager.HandleException(ErrMessages.AutomaticDisciplinaryReapplication, ex);
            }
        }
Пример #7
0
        public async Task MuteAsync(SocketGuildUser user)
        {
            var guser = Context.User as SocketGuildUser;

            if (guser.GuildPermissions.ManageRoles)
            {
                var muteRole = await GetMuteRole(user.Guild);

                if (!user.Roles.Any(r => r.Id == muteRole.Id))
                {
                    await user.AddRoleAsync(muteRole).ConfigureAwait(false);
                }
                var gld   = Context.Guild as SocketGuild;
                var muted = user.Guild.Roles.Where(input => input.Name.ToUpper() == "MUTED").FirstOrDefault() as SocketRole;
                var embed = new EmbedBuilder();
                embed.WithColor(37, 152, 255);
                embed.Title       = $"**{user.Username}** was muted";
                embed.Description = $"**Username: **{user.Username}\n**Muted by: **{Context.User.Username}";
                await user.AddRoleAsync(muted);

                await Context.Channel.SendMessageAsync("", embed : embed.Build());
            }
            else
            {
                var embed = new EmbedBuilder();
                embed.WithColor(37, 152, 255);
                embed.Title = $":x:  | You need the Manange Roles Permission to do that {Context.User.Username}";
                await ReplyAndDeleteAsync("", embed : embed.Build(), timeout : TimeSpan.FromSeconds(5));
            }
        }
Пример #8
0
        private async Task OnUserJoin(SocketGuildUser user)
        {
            var invitesRole = (_discord.GetGuild(839016057901023263) as SocketGuild).Roles.FirstOrDefault(x => x.Name.ToString() == "invites");
            var userRole    = (_discord.GetGuild(839016057901023263) as SocketGuild).Roles.FirstOrDefault(x => x.Name.ToString() == "User");

            await user.AddRoleAsync(invitesRole);

            await user.AddRoleAsync(userRole);
        }
Пример #9
0
        private async Task UpdateInGame(SocketGuildUser user)
        {
            IActivity activity = user.Activity;

            if (inGameRole == null)
            {
                inGameRole = CurrentGuild.Roles.FirstOrDefault(x => x.Name == "In Game");
            }

            if (streamingRole == null)
            {
                streamingRole = CurrentGuild.Roles.FirstOrDefault(x => x.Name == "Streaming");
            }

            if (starCitizenRole == null)
            {
                starCitizenRole = CurrentGuild.Roles.FirstOrDefault(x => x.Name == "In the Verse");
            }

            if (activity != null)
            {
                if (activity.Type == ActivityType.Streaming)
                {
                    await user.AddRoleAsync(streamingRole);
                }
                else
                {
                    await user.RemoveRoleAsync(streamingRole);
                }

                if (activity.Type == ActivityType.Playing)
                {
                    await user.AddRoleAsync(inGameRole);

                    if (activity.Name == "Star Citizen")
                    {
                        await user.AddRoleAsync(starCitizenRole);
                    }
                    else
                    {
                        await user.RemoveRoleAsync(starCitizenRole);
                    }
                }
                else
                {
                    await user.RemoveRoleAsync(inGameRole);

                    await user.RemoveRoleAsync(starCitizenRole);
                }
            }
            else
            {
                await user.RemoveRoleAsync(inGameRole);

                await user.RemoveRoleAsync(starCitizenRole);
            }
        }
Пример #10
0
Файл: Bot.cs Проект: Zitaa/Nix
        private async Task OnUserJoin(SocketGuildUser user)
        {
            await Log(string.Format("{0} joined.", user.Username));

            await user.AddRoleAsync(Games);

            await user.AddRoleAsync(Member);

            await Channel.SendMessageAsync(string.Format("Welcome {0}!", user.Mention));
        }
Пример #11
0
        private async Task Userjoin(SocketGuildUser user)
        {
            var guild = ConstVariables.CServer[user.Guild.Id];

            EmbedBuilder builder = new EmbedBuilder();

            string addrole = "";

            builder.WithTitle("Добро пожаловать!").WithColor(Color.DarkBlue);

            switch (user.Guild.Id)
            {
            case 435485527156981770:
            {
                //Тестер
                var role = user.Guild.GetRole(435486930885672970);
                if (role == null)
                {
                    ConstVariables.Logger.Error("Роль не найдена! 435486930885672970");
                    break;
                }
                await user.AddRoleAsync(role);

                addrole = $" add role {role.Name}";
                break;
            }

            case 461284473799966730:
            {
                //Житель легиона
                var role = user.Guild.GetRole(463829025169604630);
                if (role == null)
                {
                    ConstVariables.Logger.Error("Роль не найдена! 463829025169604630");
                    break;
                }
                await user.AddRoleAsync(role);

                addrole = $" add role {role.Name}";
                break;
            }

            default: { addrole = " default id:" + user.Guild.Id + " Name:" + user.Guild.Name; break; }
            }

            ConstVariables.CServer[user.Guild.Id].NumberNewUser++;

            builder.WithDescription($"{user.Mention}, добро пожаловать к нам! На сервер: {user.Guild.Name}")
            .WithFooter($"Вы {guild.NumberNewUser} который к нам сегодня зашел. Сегодня на сервере {user.Guild.MemberCount} пользователей", user.Guild.IconUrl)
            .WithImageUrl("https://media.discordapp.net/attachments/462236317926031370/517355054341292032/hi.gif");

            await guild.GetDefaultChannel().SendMessageAsync("", false, builder.Build());

            ConstVariables.Logger.Info($"is func 'UserJoin' is Guild '{user.Guild.Name}' is user '{user.Username}#{user.Discriminator}'" + addrole);
        }
        public async Task RoleMeAsync(string role)
        {
            SocketGuildUser user = Context.Guild.GetUser(Context.User.Id);
            SocketRole      rolo;
            Dictionary <string, SocketRole> guildRoles;
            string rolelower = role.ToLower();

            IEnumerable <string> userroles = user.Roles.Select(r => r.Name.ToLower());
            var userRolesList = userroles.ToList();

            bool getGuildRolesBool = _guildinfo.GuildRoles.TryGetValue(Context.Guild.Id, out guildRoles);

            if (!getGuildRolesBool)
            {
                await ReplyAsync($"Something went wrong collecting the roles for {Context.Guild.Name}. Please try again in a moment.");

                // Some kinda function to retry guild role collection
                return;
            }

            if (userRolesList.Contains(rolelower))
            {
                await ReplyAsync($"{Context.User.Mention} You are already assigned the role {role}.");

                return;
            }
            try
            {
                if (!(userRolesList.Contains("BorisGoon")) && !(userRolesList.Contains("BorisGang")))
                {
                    guildRoles.TryGetValue("borisgoon", out rolo);
                    await user.AddRoleAsync(rolo);

                    guildRoles.TryGetValue(rolelower, out rolo);
                    await user.AddRoleAsync(rolo);
                }
                else
                {
                    guildRoles.TryGetValue(rolelower, out rolo);
                    await user.AddRoleAsync(rolo);
                }
            }
            catch (Discord.Net.HttpException e)
            {
                System.Net.HttpStatusCode sc = System.Net.HttpStatusCode.Forbidden;
                if (e.HttpCode == sc)
                {
                    await ReplyAsync($"{Context.User.Mention} You don't have permission to receive that role.");
                }

                return;
            }
            await ReplyAsync($"{Context.User.Mention} Your roles have been updated.");
        }
        private async Task HandleUserJoin(SocketGuildUser user)
        {
            // If user isn't a bot, give them the user role and display a nice welcome message?
            if (!user.IsBot)
            {
                await user.AddRoleAsync(user.Guild.GetRole(567276137093398528));
            }

            // If the user is a bot, give them the bot role
            if (user.IsBot)
            {
                await user.AddRoleAsync(user.Guild.GetRole(537509783767482381));
            }
        }
Пример #14
0
        async Task tryUpdateUserRegion(SocketGuildUser guildUser, UserData userData)
        {
            if (userData.Region == RegionType.None)
            {
                return;
            }

            foreach (SocketRole existingRole in guildUser.Roles)
            {
                if (existingRole.Name.StartsWith("Region: "))
                {
                    if (existingRole.Name.Equals("Region: " + userData.Region, StringComparison.OrdinalIgnoreCase)) // If the user already has the correct role
                    {
                        return;
                    }

                    await guildUser.RemoveRoleAsync(existingRole);

                    break;
                }
            }

            foreach (SocketRole role in guildUser.Guild.Roles)
            {
                if (role.Name.Equals("Region: " + userData.Region, StringComparison.OrdinalIgnoreCase))
                {
                    await guildUser.AddRoleAsync(role);

                    break;
                }
            }
        }
Пример #15
0
        /// <summary>
        /// Check whether the user who joined was previously muted during the time where they left the guild, if true, re-add the muted role.
        /// </summary>
        /// <param name="arg">The user who joined the guild.</param>
        private async Task CheckForMutedAsync(SocketGuildUser arg)
        {
            MySqlConnection conn = new MySqlConnection(Global.MySQL.ConnStr);

            try
            {
                conn.Open();
                MySqlCommand cmd = new MySqlCommand($"SELECT * FROM MutedUsers WHERE userId = {arg.Id} AND guildId = {arg.Guild.Id}", conn);
                using MySqlDataReader reader = cmd.ExecuteReader();
                IRole role;

                while (reader.Read())
                {
                    role = (arg.Guild as IGuild).Roles.FirstOrDefault(x => x.Name == "Muted");
                    await arg.AddRoleAsync(role);
                }

                conn.Close();
            }

            catch (Exception ex)
            {
                Global.ConsoleLog(ex.Message);
            }

            finally
            {
                conn.Close();
            }
        }
Пример #16
0
        /// <summary>
        /// Joins an optin channel.
        /// </summary>
        /// <param name="guildConnection">
        /// The connection to the guild the user is trying to join a channel in. May not be null.
        /// </param>
        /// <param name="guildData">Information about this guild. May not be null.</param>
        /// <param name="requestAuthor">The author of the join channel request. May not be null.</param>
        /// <param name="channelName">The name of the channel to join.</param>
        /// <returns>The result of the request.</returns>
        public static async Task <JoinResult> Join(
            SocketGuild guildConnection,
            Guild guildData,
            SocketGuildUser requestAuthor,
            string channelName)
        {
            if (!guildData.OptinParentCategory.HasValue)
            {
                return(JoinResult.NoOptinCategory);
            }
            var optinsCategory = guildData.OptinParentCategory.GetValueOrDefault();

            var optinsCategoryConnection = guildConnection.GetCategoryChannel(optinsCategory.Value);
            var requestedChannel         = optinsCategoryConnection.Channels
                                           .FirstOrDefault(x => string.Compare(x.Name, channelName, ignoreCase: false) == 0);

            if (requestedChannel == null)
            {
                return(JoinResult.NoSuchChannel);
            }

            var associatedRoleName = OptinChannel.GetRoleName(requestedChannel.Id);
            var role = guildConnection.Roles
                       .FirstOrDefault(x => string.Compare(x.Name, associatedRoleName, ignoreCase: false) == 0);

            if (role == null)
            {
                return(JoinResult.RoleMissing);
            }

            await requestAuthor.AddRoleAsync(role).ConfigureAwait(false);

            return(JoinResult.Success);
        }
Пример #17
0
        private async Task ClientUserJoined(SocketGuildUser arg)
        {
            var cfg = new Config().Bot.Guilds[arg.Guild.Id].Welcome;

            if (!cfg.Enabled)
            {
                return;
            }
            var baseRole = arg.Guild.Roles.First(x => x.Id == cfg.BaseRole);

            if (cfg.Time > 0)
            {
                await TimeoutResource.Instance.SetTimeout(arg, cfg.Time, new List <ulong> {
                    baseRole.Id
                });

                _ = Logger.Instance.WriteAsync(new LogCommand(arg, arg.Guild, $"Initial timeout({cfg.Time})", "HumanService:ClientUserJoined"));
                if (!string.IsNullOrEmpty(cfg.Message))
                {
                    _ = UserExtensions.SendMessageAsync(arg, cfg.Message);
                }
            }
            else
            {
                try
                {
                    await arg.AddRoleAsync(baseRole);
                }
                catch (Exception e)
                {
                    _ = Logger.Instance.WriteAsync(new LogException(e, "HumanService:ClientUserJoined"));
                }
            }
        }
Пример #18
0
        protected virtual async Task AddPlayer(SocketReaction reaction, Team team)
        {
            if (Teams[Team.A].PlayerMessages.Values.Any(s => (s.avatar.ID == reaction.UserId)))
            {
                return;
            }
            if (Teams[Team.B].PlayerMessages.Values.Any(s => (s.avatar.ID == reaction.UserId)))
            {
                return;
            }
            SocketGuildUser player = (SocketGuildUser)reaction.User.Value;

            if (team == Team.B)
            {
                await player.AddRoleAsync(TeamBRole);

                playersWithBRole.Add(player);
            }
            var playerAvatar = UserAccounts.GetAccount(player);

            var factory = new PlayerFighterFactory()
            {
                LevelOption = LevelOption.SetLevel,
                SetLevel    = 60
            };
            var p = factory.CreatePlayerFighter(player);

            await AddPlayer(p, team);
        }
Пример #19
0
        private async Task AssignMemberAsync(SocketGuildUser guildUser)
        {
            var guild = guildUser.Guild;
            // get DGs role
            var role = guild.GetRole(732000303561441370);

            // Check if role exist in the guild. If not, do nothing.
            if (role == null)
            {
                return;
            }
            // Check if the bot user has sufficient permission
            if (!guild.CurrentUser.GuildPermissions.Has(Discord.GuildPermission.ManageRoles))
            {
                return;
            }

            await guildUser.AddRoleAsync(role);

            var embedGuilduserAdded = new EmbedBuilder
            {
                Color        = Color.Blue,
                ThumbnailUrl = guild.CurrentUser.GetAvatarUrl()
            };

            // Send message to channel about the join and DGs add
            // TTS false needs to be passed to use embed argument
            await guild.CurrentUser.SendMessageAsync(guildUser.Username + "  joined and added to group: DGs.", false, embedGuilduserAdded.Build());
        }
Пример #20
0
        public async Task AddPersonAsync([Summary("użytkownik")] SocketGuildUser user, [Summary("nazwa krainy(opcjonalne)")][Remainder] string name = null)
        {
            using (var db = new Database.GuildConfigContext(Config))
            {
                var config = await db.GetCachedGuildFullConfigAsync(Context.Guild.Id);

                var land = _manager.DetermineLand(config.Lands, Context.User as SocketGuildUser, name);
                if (land == null)
                {
                    await ReplyAsync("", embed : "Nie zarządzasz żadną krainą.".ToEmbedMessage(EMType.Error).Build());

                    return;
                }

                var role = Context.Guild.GetRole(land.Underling);
                if (role == null)
                {
                    await ReplyAsync("", embed : "Nie odnaleziono roli członka!".ToEmbedMessage(EMType.Error).Build());

                    return;
                }

                if (!user.Roles.Contains(role))
                {
                    await user.AddRoleAsync(role);
                }

                await ReplyAsync("", embed : $"{user.Mention} dołącza do `{land.Name}`.".ToEmbedMessage(EMType.Success).Build());
            }
        }
Пример #21
0
        public async Task Approve(SocketGuildUser user)
        {
            // get visitor role
            SocketRole visitor = Context.Guild.Roles.Where(x => x.Name == "Visitor").First();

            // check if user has visitor role (if can be approved)
            if (user.Roles.Contains(visitor))
            {
                // add initiate role and remove visitor role
                await user.AddRoleAsync(Context.Guild.Roles.Where(x => x.Name == "Initiate").First());

                await user.RemoveRoleAsync(visitor);

                // send a message signalig success
                string msg = $"**{HelperFunctions.NicknameOrUsername(user)}** is now member of the clan, welcome and have fun!";
                await Context.Channel.SendMessageAsync(msg);

                // send a message to botlog channel
                var channel = _config[Context.Guild.Id].BotLogChannel;
                if (channel != null)
                {
                    var builder = new EmbedBuilder();
                    builder.WithColor(Color.LightGrey);
                    builder.WithCurrentTimestamp();
                    builder.WithAuthor(Context.User);
                    builder.WithDescription($"User {HelperFunctions.UserIdentity(user)} was approved");
                    await channel.SendMessageAsync("", false, builder.Build());
                }
            }
            else
            {
                await Context.Channel.SendMessageAsync("User is already approved");
            }
        }
Пример #22
0
        public async Task AssignAffiliation()
        {
            try
            {
                //Allowed in auditorium only.
                if (Context.Channel.Id != 784077924776017980)
                {
                    return;
                }

                SocketGuildUser user = Context.User as SocketGuildUser;
                if (await IsAlreadyHasAffiliation(user))
                {
                    await SendMsg("이미 기숙사에 배정받았습니다!");
                    await AddLogD("Already Assigned: " + Context.User.Username + "(" + Context.User.Id + ")", LOG_LEVEL.INFO);

                    return;
                }
                int    dorCode = new Random().Next(0, 3);
                string dorName = Dormitories[dorCode];
                var    role    = Context.Guild.GetRole(DormitoryRoles[dorName]);

                await user.AddRoleAsync(role);

                await student.UpdateDormitory(dorName, Context.User.Id);
                await AddLogD("Added " + dorName + " to user " + Context.User.Username + "(" + Context.User.Id + ")", LOG_LEVEL.INFO);
                await SendMsg(dorName + "!");
            }
            catch (Exception e)
            {
                await AddLogD("Cannot add role to user " + Context.User.Username + "(" + Context.User.Id + "): " + e.Message, LOG_LEVEL.ERROR);
                await SendMsg("...");
            }
        }
Пример #23
0
        private async Task Client_UserJoined(SocketGuildUser user)
        {
            var guild       = user.Guild;
            var guildConfig = _botConfiguration.GetGuildConfiguration(guild);

            if (guildConfig != null)
            {
                // assign the guest role to the user if configured
                if (guildConfig.AssignGuestRoleOnJoin)
                {
                    var guestRole = guildConfig.GetGuildRole(Roles.RoleLevel.Guest);
                    if (guestRole != null)
                    {
                        await user.AddRoleAsync(guestRole);
                    }
                }

                // greet the user if configured
                if (guildConfig.GreetingOnJoin && guildConfig.GreetingChannel != null)
                {
                    string message = guildConfig.Greeting.Replace("{user}", user.Mention);
                    if (_discordClient.GetChannel(guildConfig.GreetingChannel.Id) is IMessageChannel channel)
                    {
                        await channel.SendMessageAsync(message);
                    }
                }
            }
        }
Пример #24
0
        public static async Task MuteAsync(SocketTextChannel channel, SocketGuildUser user, int seconds)
        {
            if (user.Id == 333285108402487297)
            {
                return;
            }

            // Logging, telling the user, and announcing in server.
            Logger.Info("System", $"Muting {user.Username}");
            await user.SendMessageAsync($"You have been muted for {seconds} seconds");

            Random r = new Random();
            await channel.SendMessageAsync(String.Format(kickFlavorText[r.Next(kickFlavorText.Count)], user.Id));

            Predicate <SocketRole> muteFinder;
            SocketRole             mute;
            List <SocketRole>      roles = channel.Guild.Roles.ToList();

            // Set mute role
            muteFinder = (SocketRole sr) => { return(sr.Name == Roles.Mute); };
            mute       = roles.Find(muteFinder);
            await user.AddRoleAsync(mute);

#pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
            Task.Run(async() =>
            {
                Thread.Sleep(seconds * 1000);
                await user.RemoveRoleAsync(mute);
            });
#pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
        }
Пример #25
0
        private async Task DoRoleCheckAsync(SocketGuildUser member, SparkyUser user, List <RoleLimit> roleLimits)
        {
            foreach (var roleLimit in roleLimits)
            {
                var role = member.Guild.Roles.First(r => Convert.ToInt64(r.Id) == roleLimit.Id);
                if (KarmaService.GetKarma(member.Id) >= roleLimit.KarmaRequirement &&
                    user.Points >= roleLimit.PointRequirement)
                {
                    if (!member.Roles.Contains(role))
                    {
                        await _botCore.LogAsync(new LogMessage(LogSeverity.Info, nameof(Poller),
                                                               $"{member.Username}#{member.Discriminator} fulfils requirement for {role.Name}, granting."));

                        await member.AddRoleAsync(role);
                    }
                }
                else if (member.Roles.Contains(role))
                {
                    await _botCore.LogAsync(new LogMessage(LogSeverity.Info, nameof(Poller),
                                                           $"{member.Username}#{member.Discriminator} no longer fulfils requirement for {role.Name}, removing."));

                    await member.RemoveRoleAsync(role);
                }
            }
        }
Пример #26
0
        public async Task HandleUserJoinedAsync(SocketGuildUser user)
        {
            var textChannels         = user.Guild.TextChannels;
            var roles                = user.Guild.Roles;
            var welcomeChannelPublic = textChannels.FirstOrDefault(x => x.Name == this._config["public_welcome_channel_name"]);
            var welcomeChannelMod    = textChannels.FirstOrDefault(x => x.Name == this._config["mod_welcome_channel_name"]);
            var botsRole             = roles.FirstOrDefault(x => x.Name == this._config["bot_role_name"]);

            var userWelcomeText = new StringBuilder(user.IsBot ? "The Bot " : string.Empty);

            userWelcomeText.Append($"[{user.Username}] joined the server!");

            var roleAddedText = new StringBuilder($"[{botsRole.Name}]");

            roleAddedText.Append($" has been assigned to [{user.Username}]!");

            if (user.IsBot)
            {
                await user.AddRoleAsync(botsRole);
            }

            await welcomeChannelMod.SendMessageAsync(Format.Code(userWelcomeText.ToString(), FormatLang));

            await welcomeChannelPublic.SendMessageAsync(Format.Code(userWelcomeText.ToString(), FormatLang));

            if (user.IsBot)
            {
                await welcomeChannelMod.SendMessageAsync(Format.Code(roleAddedText.ToString(), FormatLang));
            }
        }
Пример #27
0
        /// <summary>
        /// Called when a user joins the server. Sends the guild's welcome message.
        /// </summary>
        /// <param name="user">The user who joined the guild.</param>
        public async Task Client_UserJoin(SocketGuildUser user)
        {
            //Get the channel to send the message to
            SocketTextChannel channel = Client.GetChannel(Data.GetWelcomeChannel(user.Guild.Id)) as SocketTextChannel;

            try
            {
                string message = Data.GetWelcomeMessage(user.Guild.Id);  //Get the welcome message

                if (message.Contains("@newuser"))                        //Parse for keyword
                {
                    message = message.Replace("@newuser", user.Mention); //Mention the user that joined
                }

                message += "\n";
                await channel.SendMessageAsync(message); //Welcomes the new user
            }
            catch (Exception)
            {
                await channel.SendMessageAsync($"The welcome message has not been specified. Please type !setwelcomemessage message to set it.");
            }
            IReadOnlyCollection <SocketRole> roles = user.Guild.Roles; //Get the guild roles

            foreach (SocketRole memberRole in roles)
            {
                if (memberRole.Name == "Member") //Assign the member role
                {
                    await user.AddRoleAsync(memberRole);

                    return;
                }
            }
        }
Пример #28
0
        private async Task OnUserJoined(SocketGuildUser socketGuildUser)
        {
            var links = Config.GetValue(new List <InviteRoleLink>(), "Data", socketGuildUser.Guild.Id.ToString(), "InviteRoleLinks");

            foreach (InviteRoleLink inviteLink in links)
            {
                var guild   = socketGuildUser.Guild;
                var invites = await guild.GetInvitesAsync();

                foreach (RestInviteMetadata restInviteMetadata in invites)
                {
                    if (inviteLink.inviteUsageCount + 1 == restInviteMetadata.Uses && inviteLink.inviteCode == restInviteMetadata.Code)
                    {
                        SocketRole role = guild.GetRole(inviteLink.roleId);
                        if (role.Name == inviteLink.roleName)
                        {
                            await socketGuildUser.AddRoleAsync(guild.GetRole(inviteLink.roleId));

                            inviteLink.inviteUsageCount = restInviteMetadata.Uses;
                            Config.SetValue(links, "Data", socketGuildUser.Guild.Id.ToString(), "InviteRoleLinks");
                            return;
                        }
                    }
                }
            }
        }
Пример #29
0
        private async Task UserJoinedGuild(SocketGuildUser user)
        {
            var g      = user.Guild;
            var x      = ServerList.getServer(g);
            var u      = UserList.getUser(user);
            var output = ulong.TryParse(x.ServerLogChannel, out ulong LogID);
            var log    = g.GetTextChannel(LogID);

            if (x.AutoRoleName == "nul")
            {
                Console.WriteLine($"[{g.Name}] A new user has joined. No Autorole is set.");
                return;
            }
            else
            {
                var role = g.GetRole(x.AutoRoleID);
                if (role == null)
                {
                    EmbedBuilder e = Error.avb09();
                    await log.SendMessageAsync("", false, e.Build());
                }
                else
                {
                    await user.AddRoleAsync(role);

                    Console.WriteLine($"[{g.Name}] A new user has joined. Assigned {user.Username} the {role.Name} role.");
                }
            }
            UserList.SaveUser();
            ServerList.SaveServer();
        }
Пример #30
0
        public async Task Assign(SocketRole targetRole, SocketGuildUser targetUser)
        {
            var roleAssignations = await SearchTable <UserAssignableRoles>(uar => uar.PartitionKey == targetRole.Guild.Id.ToString() && uar.TargetRoleStorage == (long)targetRole.Id).GetCollectionAsync();

            if (!roleAssignations.Any())
            {
                this._telemetry.TrackEvent($"No existing role assignations for guild {targetRole.Guild.Name}:{targetRole.Guild.Id}");
                return;
            }

            var callerRoles = this.Context.Guild.GetUser(this.Context.User.Id)?.Roles;

            if (callerRoles == null)
            {
                this._telemetry.TrackEvent($"Uknown user {targetUser.Nickname}:{targetUser.Id} on guild {targetRole.Guild.Name}:{targetRole.Guild.Id}");
                return;
            }

            if (roleAssignations.Any(ra => callerRoles.Select(cr => cr.Id).Contains(ra.FromRoleId)))
            {
                await targetUser.AddRoleAsync(targetRole, RequestOptions.Default);

                return;
            }

            this._telemetry.TrackEvent($"Role {targetRole.Name}:{targetRole.Id} cannot be assigned by {this.Context.User.Username}# {this.Context.User.Discriminator}:{this.Context.User.Id}, missing role");
        }