public async Task mute()
        {
            IReadOnlyCollection <SocketRole> Roles = Context.Guild.GetUser(Context.User.Id).Roles;
            var EventOrg = Context.Guild.Roles.FirstOrDefault(x => x.Name == "Event Organizer");
            var host     = Context.Guild.Roles.FirstOrDefault(x => x.Name == "host");

            List <SocketRole> userroles = Roles.ToList();

            if (userroles.Contains(EventOrg) == true)
            {
                IReadOnlyCollection <SocketGuildUser> Users = Context.Guild.VoiceChannels.FirstOrDefault(x => x.Name == "Events" || x.Name == "Open Mic" || x.Name == "🏆Events🏆" || x.Name == "Event" || x.Name == "Karaoke" || x.Name == "🎤Open Mic🎤" || x.Name == "Event Voice Chat").Users;
                SocketGuildChannel     EventChannel         = Context.Guild.VoiceChannels.FirstOrDefault(x => x.Name == "Events" || x.Name == "Open Mic" || x.Name == "🏆Events🏆" || x.Name == "Event" || x.Name == "Karaoke" || x.Name == "🎤Open Mic🎤" || x.Name == "Event Voice Chat");
                List <SocketGuildUser> SocketUsers          = Users.ToList();
                foreach (SocketGuildUser user in SocketUsers)
                {
                    new OverwritePermissions(speak: PermValue.Deny);
                    var MuteRole     = Context.Guild.Roles.FirstOrDefault(x => x.Name == "EventMute");
                    var EveryoneRole = Context.Guild.Roles.FirstOrDefault(x => x.Name == "Member");
                    await user.ModifyAsync(x => x.Mute = true);

                    await((SocketGuildUser)Context.User).ModifyAsync(x => x.Mute = false);
                    await EventChannel.AddPermissionOverwriteAsync(EveryoneRole, new OverwritePermissions(speak : PermValue.Deny));
                }
                var embed = new EmbedBuilder();
                embed.WithTitle("**Mute!**");
                embed.WithDescription("Users in the channel have been muted!");
                embed.WithColor(new Color(129, 127, 255));
                embed.WithThumbnailUrl(Context.Guild.IconUrl);

                await Context.Channel.SendMessageAsync("", false, embed.Build());
            }
            else
            {
                var embed = new EmbedBuilder();
                embed.WithTitle("**Sorry!**");
                embed.WithDescription("You're not an event organizer!");
                embed.WithColor(new Color(129, 127, 255));
                embed.WithThumbnailUrl(Context.User.GetAvatarUrl());

                await Context.Channel.SendMessageAsync("", false, embed.Build());
            }
        }
        private async Task OnReady()
        {
            // This means that the bot updated last time, so send a message, kill the useless process and delete the file
            if (File.Exists(Path.Combine(Directory.GetCurrentDirectory(), "updated.txt")))
            {
                OriginalProcess = false;
                string[] contents = (await File.ReadAllTextAsync(Path.Combine(Directory.GetCurrentDirectory(), "updated.txt"))).Split('\n');

                SocketGuild        guild   = _client.GetGuild(ulong.Parse(contents[0]));
                SocketGuildChannel channel = guild.GetChannel(ulong.Parse(contents[1]));

                await((IMessageChannel)channel).SendMessageAsync("Successfully updated! :white_check_mark:");
                File.Delete(Path.Combine(Directory.GetCurrentDirectory(), "updated.txt"));
            }
            // Bot didn't shut down gracefully, close leftover process
            if (File.Exists(VersioningCommand.pidPath) && OriginalProcess)
            {
                VersioningCommand.CloseChild(null, null);
            }
        }
Beispiel #3
0
        public static async Task RemoveGuessChannel(SocketGuildChannel channel)
        {
            var setting = _guildSettings[channel.Guild.Id];

            if (!setting.GuessChannels.Contains(channel.Id))
            {
                return;
            }

            setting.RemoveGuessChannel(channel.Id);

            using (var connection = new SqliteConnection(DbPath))
            {
                await connection.OpenAsync();

                await connection.UpdateAsync(setting);

                connection.Close();
            }
        }
Beispiel #4
0
        public ReactionHandler(IMessage message, SocketReaction socketReaction, BotChannelSetting channelSettings = null, bool addedReaction = true)
        {
            // TODO DM reactions handling

            Message = message;
            if (Message != null)
            {
                SocketReaction          = socketReaction;
                SocketGuildMessageUser  = message.Author as SocketGuildUser;
                SocketGuildReactionUser = socketReaction.User.Value as SocketGuildUser; // TODO make sure user is never null
                SocketGuildChannel      = message.Channel as SocketGuildChannel;
                SocketTextChannel       = SocketGuildChannel as SocketTextChannel;
                SocketGuild             = SocketGuildChannel.Guild;

                ChannelSettings = channelSettings;
                DatabaseManager = DatabaseManager.Instance();

                AddedReaction = addedReaction;
            }
        }
Beispiel #5
0
        //Check if a message is filtered
        public static async Task FilterCheck(SocketMessage message, SocketGuildChannel channel)
        {
            if (Convert.ToBoolean(UserSettings.Filters.Enabled(channel.Guild.Id)))
            {
                foreach (string term in UserSettings.Filters.List(channel.Guild.Id))
                {
                    if (Regex.IsMatch(message.Content, string.Format(@"\b{0}\b|\b{0}d\b|\b{0}s\b|\b{0}ing\b|\b{0}ed\b|\b{0}er\b|\b{0}ers\b", Regex.Escape(term))))
                    {
                        string deleteReason = $"Message included a filtered term: {term}";

                        //Check if a message is clearly bypassing the filter, if so then warn
                        if (UserSettings.Filters.TermCausesWarn(term, channel.Guild.Id))
                        {
                            Moderation.Warn(channel.Guild.CurrentUser.Username, (ITextChannel)channel, (SocketGuildUser)message.Author, deleteReason);
                        }
                        await LogDeletedMessage(message, deleteReason);
                    }
                }
            }
        }
Beispiel #6
0
        public bool AddUserToScumChat(SocketGuild guild, SocketGuildUser user)
        {
            SocketGuildChannel scumChat = null;

            foreach (SocketGuildChannel channel in guild.Channels)
            {
                if (channel.Name == "mafia-scum-chat")
                {
                    scumChat = channel;
                }
            }

            if (scumChat != null)
            {
                scumChat.AddPermissionOverwriteAsync(user, new OverwritePermissions(viewChannel: PermValue.Allow, sendMessages: PermValue.Allow, readMessageHistory: PermValue.Allow));
                return(true);
            }

            return(false);
        }
Beispiel #7
0
        public bool RemoveUserFromScumChat(SocketGuild guild, SocketGuildUser user)
        {
            SocketGuildChannel scumChat = null;

            foreach (SocketGuildChannel channel in guild.Channels)
            {
                if (channel.Name == "mafia-scum-chat")
                {
                    scumChat = channel;
                }
            }

            if (scumChat != null)
            {
                scumChat.RemovePermissionOverwriteAsync(user, options: null);
                return(true);
            }

            return(false);
        }
Beispiel #8
0
        static private async Task ChannelCreated(SocketChannel channel)
        {
            SocketGuildChannel gChannel     = channel as SocketGuildChannel;
            jGuild             currentguild = Globals.requestDataFind(item => item.Id == gChannel.Guild.Id);

            if (currentguild.Channels.Where(item => item.Id == gChannel.Id).Count() > 0)
            {
                return;
            }
            else
            {
                currentguild.Channels.Add(new jChannel
                {
                    Name  = gChannel.Name,
                    Id    = gChannel.Id,
                    Users = new List <jUser>()
                });
                Console.WriteLine("[" + DateTime.Now.ToLocalTime().ToShortTimeString() + "]: Channel created");
            }
        }
Beispiel #9
0
        public SocketGuildChannel GetChannelFromId(ulong guildId, ulong channelId)
        {
            SocketGuildChannel foundChannel = null;

            SocketGuild guild = GetGuildFromId(guildId);

            if (guild != null)
            {
                foreach (SocketGuildChannel channel in guild.Channels)
                {
                    if (channel.Id == channelId)
                    {
                        foundChannel = channel;
                        break;
                    }
                }
            }

            return(foundChannel);
        }
Beispiel #10
0
        public Task AddReactionAsync(ulong messageID, SocketGuildChannel channel, Emoji emote, SocketRole role)
        {
            Context.Message.AddReactionAsync(new Discord.Emoji("👍"));

            if (channel.Guild.Id != Context.Guild.Id || role.Guild.Id != Context.Guild.Id)
            {
                return(ReplyAsync("Error! Trying to add ReactionRole to a different server!"));
            }
            else if (channel.Guild.Id != role.Guild.Id)
            {
                return(ReplyAsync("Error! Channel and role are not from the same server!"));
            }

            lock (Data.ReactionRoles) Data.ReactionRoles.Add(new ReactionRole((channel as SocketGuildChannel).Guild.Id, messageID, emote.Name, role.Id));
            Data.Save();

            //TODO - Add emote reaction to specified message

            return(ReplyAsync("Success - " + role.ToString() + " will be added based on " + emote.ToString() + " reactions in the specified channel"));
        }
Beispiel #11
0
        private async Task OnPurge(IReadOnlyCollection <Cacheable <IMessage, ulong> > arg1, Cacheable <IMessageChannel, ulong> arg2)
        {
            try
            {
                IMongoCollection <BsonDocument> messages = MongoClient.GetDatabase("finlay").GetCollection <BsonDocument>("messages");
                SocketUserMessage  message;
                SocketGuildChannel sGC            = (SocketGuildChannel)_discord.GetChannel(arg2.Id);
                string             messageContent = "";

                foreach (Cacheable <IMessage, ulong> msg in arg1)
                {
                    message = (SocketUserMessage)await msg.GetOrDownloadAsync();

                    if (msg.HasValue)
                    {
                        messages.FindOneAndUpdate(new BsonDocument {
                            { "_id", (decimal)message.Id }
                        }, new BsonDocument {
                            { "$set", new BsonDocument {
                                  { "deleted", true },
                                  { "deletedTimestamp", (decimal)Global.ConvertToTimestamp(DateTime.Now) }
                              } }
                        });
                    }

                    if (message == null)
                    {
                        return;
                    }

                    messageContent = msg.HasValue ? msg.Value.Content : "Unable to retrieve message";
                    _logger.LogDebug($"[BULK DELETED]User: [{message.Author.Username}]<->[{message.Author.Id}] Discord Server: [{sGC.Guild.Name}/{sGC.Name}] -> [{messageContent}]");
                }

                return;
            }
            catch (Exception ex)
            {
                Global.ConsoleLog(ex.Message);
            }
        }
Beispiel #12
0
        private void AnnounceBirthday(Date date)
        {
            SocketGuildUser    user = Utility.GetServer().GetUser(date.userID);
            SocketGuildChannel main = Utility.GetMainChannel();

            AutoCommands.RunEvent(AutoCommands.Event.UserBirthday, user.Id.ToString());
            // I have no idea if this works, and it's possibly the worst possible way I could have done that.

            int age = 0;

            try {
                age = DateTime.MinValue.Add(DateTime.Now - new DateTime(date.day.Year, date.day.Month, date.day.Day)).Year - DateTime.MinValue.Year;
            } catch (IndexOutOfRangeException) {
                Logging.Log(Logging.LogType.EXCEPTION, user.Username + " has somehow set their birthday to be before now. wat.");
            }

            string ageSuffix = "'th";

            switch (age.ToString().LastOrDefault())
            {
            case '1':
                ageSuffix = "'st";
                break;

            case '2':
                ageSuffix = "'nd";
                break;

            case '3':
                ageSuffix = "'rd";
                break;
            }

            if (age % 10 > 0 && age % 10 < 4)
            {
                ageSuffix = "'th";
            }

            Program.messageControl.SendMessage(main as SocketTextChannel, onBirthdayAnnouncementMessage.Replace("{USERNAME}", Utility.GetUserName(user)).Replace("{AGE}", age + ageSuffix), true);
            Program.messageControl.SendMessage(user, onBirthdayCongratulationsDM);
        }
        internal override async Task ExecuteCommand(SocketMessage message, GuildConfig guild)
        {
            EmbedBuilder embedBuilder = new EmbedBuilder();

            if (!Program.IsAuthorized(message.Author, guild.GuildId))
            {
                embedBuilder.Title       = "Unauthorized.";
                embedBuilder.Description = "You are not authorized to use this command.";
            }
            else
            {
                SocketGuildChannel guildChannel = message.Channel as SocketGuildChannel;
                embedBuilder.Title       = "Unknown module.";
                embedBuilder.Description = "Module not found.";
                string[] message_contents = message.Content.Substring(1).Split(" ");

                if (message_contents.Length >= 2)
                {
                    string checkModuleName = message_contents[1].ToLower();
                    foreach (BotModule module in Program.modules)
                    {
                        if (module.moduleName.ToLower().Equals(checkModuleName))
                        {
                            List <string> result = new List <string>();
                            embedBuilder.Title = module.moduleName;
                            if (guild.enabledModules.Contains(module.moduleName))
                            {
                                result.Add($"{module.moduleName} (enabled for this guild)");
                            }
                            else
                            {
                                embedBuilder.Title = $"{module.moduleName} (disabled for this guild)";
                            }
                            embedBuilder.Description = $"{string.Join("\n", result.ToArray())}\n{module.Interrogate()}";
                            break;
                        }
                    }
                }
            }
            await Program.SendReply(message, embedBuilder);
        }
Beispiel #14
0
        private async Task BackgroundTempChannelExpiryCheck(SocketGuild g, GuildInformation info)
        {
            SocketGuildChannel ch = null;

            lock (info)
            {
                ch = info.GetTemporaryChannel(g);
                if (ch == null)
                {
                    return;             // No temporary channel. Nothing to do.
                }
                if (!info.IsTempChannelExpired())
                {
                    return;
                }

                // If we got this far, the channel's expiring. Start the voting cooldown.
                info.Voting.StartCooldown();
            }
            await ch.DeleteAsync();
        }
Beispiel #15
0
        private bool IsValidMessage(SocketUserMessage message, SocketGuild guild, SocketGuildChannel channel)
        {
            var emotes = message.Tags
                         .Where(o => o.Type == TagType.Emoji && guild.Emotes.Any(x => x.Id == o.Key))
                         .ToList();

            var isUTFEmoji = NeoSmart.Unicode.Emoji.IsEmoji(message.Content);

            if (emotes.Count == 0 && !isUTFEmoji)
            {
                return(false);
            }

            if (!IsValidWithWithFirstInChannel(channel, message.Content))
            {
                return(false);
            }
            var emoteTemplate = string.Join(" ", emotes.Select(o => o.Value.ToString()));

            return(emoteTemplate == message.Content || isUTFEmoji);
        }
Beispiel #16
0
        private async Task <bool> Respond(ulong toID, ulong userID, string message)
        {
            string[] query = StripCommand(message, Options.ChatCommand.Command);
            if (query != null && query.Length == 1)
            {
                await SendMessageAfterDelay(toID, "Usage: " + Options.ChatCommand.Command + " <uri> - checks online status of a uri");

                return(true);
            }
            else if (query != null && query.Length == 2)
            {
                SocketGuildChannel           channel = Bot.Client.GetChannel(toID) as SocketGuildChannel;
                HttpWebResponse              response;
                System.Diagnostics.Stopwatch timer = new System.Diagnostics.Stopwatch();
                try
                {
                    timer.Start();
                    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(query[1]);
                    response = (HttpWebResponse)(await request.GetResponseAsync());
                    timer.Stop();
                }
                catch (UriFormatException ufe)
                {
                    Log.Instance.Error(IfError(ufe));
                    await SendMessageAfterDelay(toID, "Uri was not in the correct format (needs http:// or https://)");

                    response = null;
                    return(true);
                }
                catch (WebException we)
                {
                    Log.Instance.Error(IfError(we));
                    response = (HttpWebResponse)we.Response;
                }
                await SendMessageAfterDelay(toID, response.StatusDescription.ToString() + " (" + (int)response.StatusCode + ")\nTime: " + timer.ElapsedMilliseconds + " ms");

                return(true);
            }
            return(false);
        }
Beispiel #17
0
        private async Task HandleCommandAsync(SocketMessage messageParam)
        {
            var message = messageParam as SocketUserMessage;

            if (message == null)
            {
                return;
            }

            int argPos = 0;

            IReadOnlyCollection <SocketGuild> guilds = _bot.Guilds;
            SocketGuild        oneplusGuild          = guilds.FirstOrDefault(x => x.Name == "/r/oneplus");
            SocketGuildChannel wallpapersChannel     = oneplusGuild.Channels.FirstOrDefault(x => x.Name == "wallpapers");

            if (messageParam.Channel.Id == wallpapersChannel.Id)
            {
                var messageContent = messageParam.Content;

                if (!Regex.IsMatch(messageContent, @"^http(s)?://([\w-]+.)+[\w-]+(/[\w- ./?%&=])?$") && messageParam.Attachments.Count == 0 && messageParam.Embeds.Count == 0)
                {
                    await messageParam.DeleteAsync();
                }
            }


            if (!(message.HasCharPrefix(';', ref argPos) ||
                  message.HasMentionPrefix(_bot.CurrentUser, ref argPos)) ||
                message.Author.IsBot)
            {
                return;
            }

            var context = new SocketCommandContext(_bot, message);

            var result = await _commands.ExecuteAsync(
                context : context,
                argPos : argPos,
                services : _services);
        }
Beispiel #18
0
        public async Task MoveOne([Required] string message, [Required] SocketGuildChannel chnl)
        {
            if (!(chnl is SocketTextChannel to))
            {
                await Interaction.RespondAsync(":x: You must select a text channel.",
                                               ephemeral : true);

                return;
            }
            var from      = Interaction.Channel as ITextChannel;
            var fromPerms = (Interaction.User as SocketGuildUser).GetPermissions(from);

            if (!ulong.TryParse(message, out var messageId))
            {
                await Interaction.RespondAsync(":x: You must enter a message id - a long number.",
                                               ephemeral : true);

                return;
            }
            if (!fromPerms.ManageMessages)
            {
                await Interaction.RespondAsync($":x: You do not have permission to move mesages to {to.Mention}",
                                               ephemeral : true);

                return;
            }
            await Interaction.AcknowledgeAsync();

            var msg = await from.GetMessageAsync(messageId);

            if (msg == null || !(msg is IUserMessage umsg))
            {
                await Interaction.FollowupAsync(":x: That message does not exist");

                return;
            }
            await MoveMsg(umsg, to);

            await Interaction.FollowupAsync("Moved one message");
        }
        private async Task <ITextChannel> FindOrCreateThread(guid userId, bool sendUserInfo, bool sendCustomMessage = false)
        {
            IGuildUser user   = null;
            Server     server = this.Client.Servers.Values.FirstOrDefault(s => (user = s.Guild.Users.FirstOrDefault(u => u.Id == userId)) != null || (user = this.Client.DiscordClient.Rest.GetGuildUserAsync(s.Id, userId).GetAwaiter().GetResult()) != null);

            if (server == null || !this.Client.Servers.ContainsKey(this.Client.Config.ModmailServerId) || (server = this.Client.Servers[this.Client.Config.ModmailServerId]) == null)
            {
                return(null);
            }

            IChannel channel = server.Guild.Channels.FirstOrDefault(c => c is SocketTextChannel cc && (cc.Topic?.Contains(userId.ToString()) ?? false));

            if (channel == null)
            {
                channel = await server.Guild.CreateTextChannelAsync(user.GetUsername().Replace('#', '-'), c => {
                    c.Topic      = $"UserId: {userId}";
                    c.CategoryId = this.Client.Config.ModmailCategoryId;
                });

                if (sendUserInfo)
                {
                    string message = null;
                    if (sendCustomMessage && !string.IsNullOrEmpty(this.Client.Config.ModmailNewThreadMessage))
                    {
                        message = this.Client.Config.ModmailNewThreadMessage;
                    }
                    Embed embed = GetUserInfoEmbed(user);
                    ((ITextChannel)channel)?.SendMessageAsync(message, embed: embed);
                }
            }
            else
            {
                SocketGuildChannel socketGuildChannel = channel as SocketGuildChannel;
                await socketGuildChannel.ModifyAsync(c => c.CategoryId = this.Client.Config.ModmailCategoryId);
            }


            return(channel as ITextChannel);
        }
        public async Task AddOrUpdateChannel(SocketGuildChannel channel, string city = null)
        {
            var channelEntity = Channels.FirstOrDefault(x => x.Id == channel.Id);

            if (channelEntity == null)
            {
                channelEntity = _mapper.Map <DiscordChannelEntity>(channel);
                channelEntity.FirstSeenDate = DateTime.Now;
                Channels.Add(channelEntity);
            }

            if (channelEntity.Server == null || channelEntity.ServerId == 0)
            {
                channelEntity.Server   = _mapper.Map <DiscordServerEntity>(channel.Guild);
                channelEntity.ServerId = channel.Guild.Id;
            }

            channelEntity.LastSeenDate = DateTime.Now;
            channelEntity.City         = city ?? channelEntity.City;

            await SaveChangesAsync();
        }
Beispiel #21
0
        public static async Task MsgLengthCheck(SocketMessage message, SocketGuildChannel channel)
        {
            var user  = (IGuildUser)message.Author;
            var guild = user.Guild;

            if ((Moderation.IsModerator((IGuildUser)message.Author) == false) && (message.Author.IsBot == false))
            {
                //Delete Messages that are too short
                int minimum   = UserSettings.BotOptions.MinimumLength(channel.Guild.Id);
                int msgLength = message.Content.ToString().Trim(new char[] { ' ', '.' }).Length;
                if (message.Content.Length < minimum && message.Attachments.Count == 0)
                {
                    await LogDeletedMessage(message, $"Message was too short (minimum is {minimum})");
                }
                int minletters = UserSettings.BotOptions.MinimumLetters(channel.Guild.Id);
                //Delete messages that don't have enough alphanumeric characters
                if (message.Content.Count(char.IsLetterOrDigit) < minletters && message.Tags.Count <= 0 && !Regex.IsMatch(message.Content, @"\p{Cs}") && message.Attachments.Count <= 0)
                {
                    await LogDeletedMessage(message, $"Message didn't have enough letters (minimum is {minletters})");
                }
            }
        }
        private async Task Client_MessageReceived(SocketMessage MessageParam)
        {
            var Message = MessageParam as SocketUserMessage;
            var Context = new SocketCommandContext(Client, Message);

            if (Context.Message == null || Context.Message.Content == "")
            {
                return;
            }
            if (Context.User.IsBot)
            {
                return;
            }
            if (Context.Message == null || Context.Message.Content == "agree")
            {
                IReadOnlyCollection <SocketRole> Roles = Context.Guild.GetUser(Context.User.Id).Roles;
                var role = Context.Guild.Roles.FirstOrDefault(x => x.Name == "Member");
                List <SocketRole> userroles = Roles.ToList();
                if (userroles.Contains(role) == false)
                {
                    SocketGuildChannel roleadd = Context.Guild.TextChannels.FirstOrDefault(x => x.Name == "roleadd");
                    await((SocketGuildUser)Context.User).AddRoleAsync(role);
                }
            }

            int ArgPos = 0;

            if (!(Message.HasStringPrefix("+", ref ArgPos) || Message.HasMentionPrefix(Client.CurrentUser, ref ArgPos)))
            {
                return;
            }

            var Result = await Commands.ExecuteAsync(Context, ArgPos);

            if (!Result.IsSuccess)
            {
                Console.WriteLine($"{DateTime.Now} at Commands] Something went wrong with executing a command. Text: {Context.Message.Content} | Error: {Result.ErrorReason}");
            }
        }
Beispiel #23
0
        public async Task SetIdIntoConfig(SocketGuildChannel chnl)
        {
            var guser = Context.User as SocketGuildUser;

            if (guser.GuildPermissions.Administrator)
            {
                var config = GlobalGuildAccounts.GetGuildAccount(Context.Guild.Id);
                var embed  = new EmbedBuilder();
                embed.WithColor(37, 152, 255);
                embed.WithDescription($"Set this guild's welcome channel to #{chnl}.");
                config.WelcomeChannel = chnl.Id;
                GlobalGuildAccounts.SaveAccounts();
                await Context.Channel.SendMessageAsync("", embed : embed.Build());
            }
            else
            {
                var embed = new EmbedBuilder();
                embed.WithColor(37, 152, 255);
                embed.Title = $":x:  | You Need the Administrator Permission to do that {Context.User.Username}";
                await ReplyAndDeleteAsync("", embed : embed.Build(), timeout : TimeSpan.FromSeconds(5));
            }
        }
        /// <summary>
        /// Given a channel, will remove the language "-en" part and return the base name
        /// </summary>
        public static string BaseName(this SocketGuildChannel channel)
        {
            var supportedLanguages = SupportedLanguages.GetInstance()
                                     .GetLanguages();

            var name  = channel.Name;
            var split = name.Split('-');

            if (split.Length > 1)
            {
                var language = supportedLanguages.FirstOrDefault(l =>
                                                                 string.Compare(l.Code, split.Last(), StringComparison.OrdinalIgnoreCase) == 0);

                if (language.IsNotNull())
                {
                    split = split.Take(split.Length - 1).ToArray();
                    return(split.StringJoin('-'));
                }
            }

            return(name);
        }
        public async Task MoveMessagesCommand(int numMessages, SocketGuildChannel channel, ulong bottomMessageId = 0)
        {
            var context = Context;

            context.server.CurrentUser.RequirePermission(channel, DiscordPermission.ManageMessages);

            if (!(channel is ITextChannel toChannel))
            {
                throw new BotError($"<#{channel.Id}> isn't a text channel.");
            }

            var messageList = await CopyMessagesInternal(numMessages, toChannel, bottomMessageId);

            try {
                await context.socketTextChannel.DeleteMessagesAsync(messageList);
            }
            catch (Exception e) {
                await MopBot.HandleException(e);

                await context.ReplyAsync($"Error deleting messages: ```{string.Join("\r\n",messageList.Select(m => m==null ? "NULL" : m.Id.ToString()))}```");
            }
        }
Beispiel #26
0
        public async Task SetNominationChannel([Summary("#channel")] SocketGuildChannel channel)
        {
            Global.MemberNominationChannel = channel.Id;

            // Save the channel to a file to preserve data
            //Core.ConfigurationData.WriteString("ChannelData", "NominationChannel", channel.Id.ToString());
            Core.iniConfig.WriteValue("ChannelData", "NominationChannel", channel.Id.ToString());
            Core.iniConfig.Save();

            if (Core.iniConfig.GetValue("ChannelData", "NominationChannel") != null || !Core.iniConfig.GetValue("ChannelData", "NominationChannel").Equals(""))
            {
                Embed eb = new EmbedBuilder()
                           .WithTitle("Initialisation")
                           .WithDescription($"Nomination channel initialised to {Context.Guild.GetTextChannel(ulong.Parse(Core.iniConfig.GetValue("ChannelData", "NominationChannel"))).Mention}")
                           .Build();
                var response = await Context.Channel.SendMessageAsync(null, embed : eb);

                await Task.Delay(3000);

                await Context.Channel.DeleteMessageAsync(response);
            }
        }
        private async Task <DiscordChannelConfig> GetChatConfiguration(SocketUserMessage message, IServiceProvider serviceProvider)
        {
            var channelConfigService = serviceProvider.GetService <IDiscordChannelConfigService>();

            var channelConfig = await channelConfigService.GetConfigurationByChannelId(message.Channel.Id);

            if (channelConfig != null)
            {
                return(channelConfig);
            }

            var messageBuilder = new StringBuilder();

            messageBuilder.AppendLine("Hi, I'm GrammarNazi.");
            messageBuilder.AppendLine("I'm currently working and correcting all spelling errors in this channel.");
            messageBuilder.AppendLine($"Type `{DiscordBotCommands.Help}` to get useful commands.");

            ulong guild = message.Channel switch
            {
                SocketDMChannel dmChannel => dmChannel.Id,
                SocketGuildChannel guildChannel => guildChannel.Guild.Id,
                  _ => default
            };

            var channelConfiguration = new DiscordChannelConfig
            {
                ChannelId        = message.Channel.Id,
                GrammarAlgorithm = Defaults.DefaultAlgorithm,
                Guild            = guild,
                SelectedLanguage = SupportedLanguages.Auto
            };

            await channelConfigService.AddConfiguration(channelConfiguration);

            await message.Channel.SendMessageAsync(messageBuilder.ToString());

            return(channelConfiguration);
        }
Beispiel #28
0
        public async Task SetChannelToBeIgnored(string type, SocketGuildChannel chnl = null)
        {
            var config = GuildConfig.GetOrCreateConfig(Context.Guild.Id);
            var embed  = new EmbedBuilder()
                         .WithColor(new Color(config.EmbedColour1, config.EmbedColour2, config.EmbedColour3))
                         .WithFooter(Bot.Internal.Utilities.GetFormattedLocaleMsg("CommandFooter", Context.User.Username));

            switch (type)
            {
            case "add":
            case "Add":
                config.AntilinkIgnoredChannels.Add(chnl.Id);
                GuildConfig.SaveGuildConfig();
                embed.WithDescription($"Added <#{chnl.Id}> to the list of ignored channels for Antilink.");
                break;

            case "rem":
            case "Rem":
                config.AntilinkIgnoredChannels.Remove(chnl.Id);
                GuildConfig.SaveGuildConfig();
                embed.WithDescription($"Removed <#{chnl.Id}> from the list of ignored channels for Antilink.");
                break;

            case "clear":
            case "Clear":
                config.AntilinkIgnoredChannels.Clear();
                GuildConfig.SaveGuildConfig();
                embed.WithDescription("List of channels to be ignored by Antilink has been cleared.");
                break;

            default:
                embed.WithDescription(
                    $"Valid types are `add`, `rem`, and `clear`. Syntax: `{config.CommandPrefix}ali {{add/rem/clear}} [channelMention]`");
                break;
            }

            await SendMessage(embed);
        }
        public async Task LeaderboardAddAsync(
            [Name("Channel")]
            [Description("The channel to post the leaderboard to")]
            SocketGuildChannel channel,
            [Name("Enabled")]
            [Description("True to allow posting, False to disable")]
            bool enabled,
            [Name("Console")]
            [Description("The Console that the leaderboard is for")]
            string console,
            [Name("Variant")]
            [Description("The Leaderboard name to pull")]
            [Remainder] string variant)
        {
            var guild = await Database.Guilds.AsNoTracking().Include(x => x.Leaderboards).FirstAsync(x => x.GuildId == Context.Guild.Id);

            variant = variant.Replace(" ", "_");

            if (guild.Leaderboards.Any(x => x.Variant == variant && x.Console == console && x.ChannelId == channel.Id))
            {
                await ReplyAsync(EmoteHelper.Cross + " My spirit is spent. *`" + variant + "` is already in the list.*");

                return;
            }

            await Database.Leaderboards.AddAsync(new Leaderboard
            {
                ChannelId = channel.Id,
                Enabled   = enabled,
                Console   = console,
                Variant   = variant,
                GuildId   = guild.Id
            });

            await Database.SaveChangesAsync();

            await ReplyWithEmoteAsync(EmoteHelper.OkHand);
        }
Beispiel #30
0
        public async Task CheckForAFK(SocketMessage msg)
        {
            if (msg.Author.IsBot || msg.Channel.GetType() == typeof(SocketDMChannel))
            {
                return;
            }

            if (msg.MentionedUsers.Count > 1 || msg.MentionedUsers.Count == 0)
            {
                return;
            }

            SocketGuildChannel ContextChannel = (SocketGuildChannel)msg.Channel;
            ulong        _id      = ContextChannel.Guild.Id;
            BsonDocument document = new BsonDocument {
                { "_id", (decimal)_id }
            };
            BsonDocument item = await collection.Find(document).FirstOrDefaultAsync();

            try
            {
                string        itemVal     = item?.GetValue($"AFKUsers").ToJson();
                List <string> stringArray = JsonConvert.DeserializeObject <string[]>(itemVal).ToList();

                foreach (var i in stringArray)
                {
                    Global.ConsoleLog(i);
                }

                //if (stringArray.Contains($"{msg.Author.Id}"))
                //{
                //    SocketUserMessage message = (SocketUserMessage)msg;
                //    await message.ReplyAsync($"{msg.MentionedUsers.First()} is AFK: {itemVal}");
                //}
            }

            catch { }
        }