public async Task Suggest([Remainder] string suggestion = null) { if (suggestion == null) { await ReplyAsync("Please suggest something lol..."); } else { try { var s = Homeserver.Load().Suggestion; var c = Context.Client.GetChannel(s); var embed = new EmbedBuilder(); embed.AddField($"Suggestion from {Context.User.Username}", suggestion); embed.WithFooter(x => { x.Text = $"{Context.Message.CreatedAt} || {Context.Guild.Name}"; }); embed.Color = Color.Blue; await((ITextChannel)c).SendMessageAsync("", false, embed.Build()); await ReplyAsync("Suggestion Sent!!"); } catch { await ReplyAsync("The bots owner has not yet configured the suggestion channel"); } } }
public async Task PReport([Remainder] string message = null) { if (message == null) { await ReplyAsync( "Please provide some information about the Partner message you are reporting, and we will do our best to remove it"); } else { try { var s = Homeserver.Load().Suggestion; var c = await Context.Client.GetChannelAsync(s); var embed = new EmbedBuilder(); embed.AddField($"Partner Message Report from {Context.User.Username}", message); embed.WithFooter(x => { x.Text = $"{Context.Message.CreatedAt} || {Context.Guild.Name}"; }); embed.Color = Color.Blue; await((ITextChannel)c).SendMessageAsync("", false, embed.Build()); await ReplyAsync("Report Sent!!"); } catch { await ReplyAsync("The bots owner has not yet configured the Reports channel"); } } }
public async Task Bug([Remainder] string bug = null) { if (bug == null) { await ReplyAsync("Please provide an error report"); } else { try { var s = Homeserver.Load().Suggestion; var c = Context.Client.GetChannel(s); var embed = new EmbedBuilder(); embed.AddField($"BugReport from {Context.User.Username}", bug); embed.WithFooter(x => { x.Text = $"{Context.Message.CreatedAt} || {Context.Guild.Name}"; }); embed.Color = Color.Red; await((ITextChannel)c).SendMessageAsync("", false, embed.Build()); await ReplyAsync("Bug Report Sent!!"); } catch { await ReplyAsync("The bots owner has not yet configured the Bug channel"); } } }
public override Task <PreconditionResult> CheckPermissions(ICommandContext context, CommandInfo command, IServiceProvider services) { if (context.Channel is IDMChannel) { return(Task.FromResult(PreconditionResult.FromSuccess())); } var own = context.Client.GetApplicationInfoAsync(); if (own.Result.Owner.Id == context.User.Id) { return(Task.FromResult(PreconditionResult.FromSuccess())); } var role = Homeserver.Load().BotModerator; if (role == 0) { return(Task.FromResult(PreconditionResult.FromError("User is not a BOT Moderator"))); } if (((IGuildUser)context.User).RoleIds.Contains(role)) { return(Task.FromResult(PreconditionResult.FromSuccess())); } return(Task.FromResult(PreconditionResult.FromError("User is not BOT Moderator"))); }
public async Task PUserCount() { var guild = GuildConfig.GetServer(Context.Guild); guild.PartnerSetup.showusercount = !guild.PartnerSetup.showusercount; await ReplyAsync($"Will show UserCount in pertner messages: {guild.PartnerSetup.showusercount}"); var home = Homeserver.Load().PartnerUpdates; var chan = await Context.Client.GetChannelAsync(home); if (chan is IMessageChannel channel) { var embed2 = new EmbedBuilder { Title = "Partner UserCount Toggled", Description = $"{Context.Guild.Name}\n" + $"`{Context.Guild.Id}`\n" + $"Channel: {Context.Channel.Name}\n" + $"ShowUserCount: {guild.PartnerSetup.showusercount}" }; await channel.SendMessageAsync("", false, embed2.Build()); } GuildConfig.SaveServer(guild); }
public async Task ASTog() { var hs = Homeserver.Load(); hs.DisableCheckMsg = !hs.DisableCheckMsg; Homeserver.SaveHome(hs); await ReplyAsync($"Antispam Disabled: {hs.NoToxicityDisabled}"); }
public async Task NTDis() { var hs = Homeserver.Load(); hs.NoToxicityDisabled = !hs.NoToxicityDisabled; Homeserver.SaveHome(hs); await ReplyAsync($"Toxicity Disabled: {hs.NoToxicityDisabled}"); }
public async Task Error() { var home = Homeserver.Load(); home.Error = Context.Channel.Id; Homeserver.SaveHome(home); await ReplyAsync("Done"); }
public async Task Suggest() { var home = Homeserver.Load(); home.Suggestion = Context.Channel.Id; Homeserver.SaveHome(home); await ReplyAsync("Done"); }
public async Task BModRole(SocketRole role = null) { var home = Homeserver.Load(); home.BotModerator = role?.Id ?? 0; Homeserver.SaveHome(home); await ReplyAsync($"ModRole is set to {(role == null ? "N/A" : role.Name)}!"); }
public async Task PupDates() { var home = Homeserver.Load(); home.PartnerUpdates = Context.Channel.Id; Homeserver.SaveHome(home); await ReplyAsync("PartnerUpdates will now be posted here!"); }
public async Task Error() { var file = Path.Combine(AppContext.BaseDirectory, $"setup/config/home.json"); var home = JsonConvert.DeserializeObject <Homeserver>(File.ReadAllText(file)); home.Error = Context.Channel.Id; Homeserver.SaveHome(home); await ReplyAsync("Done"); }
public async Task HomeAsync() { var homes = new Homeserver { GuildId = Context.Guild.Id, GuildName = Context.Guild.Name }; Homeserver.SaveHome(homes); await ReplyAsync("Done"); }
public async Task PImage(string URL = null) { var guild = GuildConfig.GetServer(Context.Guild); if (URL == null) { guild.PartnerSetup.ImageUrl = null; await ReplyAsync("Image has been removed."); } else if (RedditHelper.isimage(URL).isimage) { guild.PartnerSetup.ImageUrl = URL; var embed = new EmbedBuilder { ImageUrl = URL }; await ReplyAsync("Image Set", false, embed.Build()); var home = Homeserver.Load().PartnerUpdates; var chan = await Context.Client.GetChannelAsync(home); if (chan is IMessageChannel channel) { var embed2 = new EmbedBuilder { Title = "Partner Image Set", Description = $"{Context.Guild.Name}\n" + $"`{Context.Guild.Id}`\n" + $"Channel: {Context.Channel.Name}", ImageUrl = URL }; await channel.SendMessageAsync("", false, embed2.Build()); } } else { await ReplyAsync("You have not provided an image URL."); return; } GuildConfig.SaveServer(guild); }
public async Task PToggle() { var guild = GuildConfig.GetServer(Context.Guild); guild.PartnerSetup.IsPartner = !guild.PartnerSetup.IsPartner; GuildConfig.SaveServer(guild); await ReplyAsync($"Partner service enabled: {guild.PartnerSetup.IsPartner}"); if (guild.PartnerSetup.IsPartner) { if (!TimerService.AcceptedServers.Contains(Context.Guild.Id)) { TimerService.AcceptedServers.Add(Context.Guild.Id); } } else { if (TimerService.AcceptedServers.Contains(Context.Guild.Id)) { TimerService.AcceptedServers.Remove(Context.Guild.Id); } } var home = Homeserver.Load().PartnerUpdates; var chan = await Context.Client.GetChannelAsync(home); if (chan is IMessageChannel channel) { var embed = new EmbedBuilder { Title = "Partner Toggled", Description = $"{Context.Guild.Name}\n" + $"`{Context.Guild.Id}`\n" + $"Status: {guild.PartnerSetup.IsPartner}" }; await channel.SendMessageAsync("", false, embed.Build()); } }
public async Task DoCommand(SocketMessage parameterMessage) { Load.Messages++; if (!(parameterMessage is SocketUserMessage message)) { return; } var argPos = 0; var context = new ShardedCommandContext(_client, message); //new CommandContext(_client, message); if (context.User.IsBot) { return; } if (message.Content.Contains("discord.gg")) { try { if (context.Channel is IGuildChannel) { if (GuildConfig.Load(context.Guild.Id).Invite&& !((SocketGuildUser)context.User).GuildPermissions.Administrator) { if (!((IGuildUser)context.User).RoleIds .Intersect(GuildConfig.Load(context.Guild.Id).InviteExcempt).Any()) { await message.DeleteAsync(); await context.Channel.SendMessageAsync( $"{context.User.Mention} - Pls Daddy, no sending invite links... the admins might get angry"); //if // 1. The server Has Invite Deletions turned on // 2. The user is not an admin // 3. The user does not have one of the invite excempt roles } } } } catch { // } } if (message.Content.Contains("@everyone") || message.Content.Contains("@here")) { try { if (context.Channel is IGuildChannel) { if (GuildConfig.Load(context.Guild.Id).MentionAll&& !((SocketGuildUser)context.User).GuildPermissions.Administrator) { if (!((IGuildUser)context.User).RoleIds .Intersect(GuildConfig.Load(context.Guild.Id).InviteExcempt).Any()) { await message.DeleteAsync(); var rnd = new Random(); var res = rnd.Next(0, FunStr.Everyone.Length); var emb = new EmbedBuilder { Title = $"{context.User} - the admins might get angry", ImageUrl = FunStr.Everyone[res] }; await context.Channel.SendMessageAsync("", false, emb.Build()); //if // 1. The server Has Mention Deletions turned on // 2. The user is not an admin // 3. The user does not have one of the mention excempt roles } } } } catch { // } } try { if (GuildConfig.Load(context.Guild.Id).Blacklist .Any(b => context.Message.Content.ToLower().Contains(b.ToLower())) && !((IGuildUser)context.User).GuildPermissions.Administrator) { await message.DeleteAsync(); var blmessage = ""; try { blmessage = GuildConfig.Load(context.Guild.Id).BlacklistMessage; } catch { // } if (blmessage != "") { var r = await context.Channel.SendMessageAsync(blmessage); await Task.Delay(5000); await r.DeleteAsync(); } } } catch { // } if (!(message.HasMentionPrefix(_client.CurrentUser, ref argPos) || message.HasStringPrefix(Load.Pre, ref argPos) || message.HasStringPrefix(GuildConfig.Load(context.Guild.Id).Prefix, ref argPos))) { return; } if (message.HasMentionPrefix(_client.CurrentUser, ref argPos)) { var newmessage = Regex.Replace(context.Message.Content, @"^\!?<@[0-9]+>\s*", "", RegexOptions.Multiline); var response = _apiAi.TextRequest(newmessage); if (response.Result.Fulfillment.Speech != "") { await context.Channel.SendMessageAsync(response.Result.Fulfillment.Speech); } return; } var result = await _commands.ExecuteAsync(context, argPos, Provider); var commandsuccess = result.IsSuccess; string server; if (context.Channel is IPrivateChannel) { server = "Direct Message "; //because direct messages have no guild name define it as Direct Message } else { server = context.Guild.Name; } if (!commandsuccess) { try { if (!(result.ErrorReason == "Unknown command." || result.ErrorReason == "The input text has too many parameters." || result.ErrorReason == "The input text has too few parameters." || result.ErrorReason == "Timeout" || result.ErrorReason == "This command may only be invoked in an NSFW channel." || result.ErrorReason == "Command can only be run by the owner of the bot" || result.ErrorReason == "This command is locked to NSFW Channels. Pervert.")) { var s = Homeserver.Load().Error; var c = await(context.Client as IDiscordClient).GetChannelAsync(s); var embed = new EmbedBuilder(); embed.AddField("ERROR", context.Message); embed.AddField("Reason", result.ErrorReason); embed.WithFooter(x => { x.Text = $"{context.Message.CreatedAt} || {context.Guild.Name}"; }); embed.Color = Color.Red; await((ITextChannel)c).SendMessageAsync("", false, embed.Build()); } } catch { // } var errmessage = await context.Channel.SendMessageAsync( $"**COMMAND: **{context.Message} \n**ERROR: **{result.ErrorReason}"); //if in server error responses are enabled reply on error await Task.Delay(5000); await errmessage.DeleteAsync(); await context.Message.DeleteAsync(); await ColourLog.In3Error($"{context.Message}", 'S', $"{context.Guild.Name}", 'E', $"{result.ErrorReason}"); // log errors as arrors } else { await ColourLog.In3( $"{context.Message}", 'S', $"{server}", 'U', $"{context.User}", System.Drawing.Color.Teal); //if there is no error log normally Load.Commands++; } }
private async Task ChannelUpdatedEvent(SocketChannel s1, SocketChannel s2) { var ChannelBefore = s1 as SocketGuildChannel; var ChannelAfter = s2 as SocketGuildChannel; if (ChannelBefore != null) { var guild = ChannelBefore.Guild; var gChannel = ChannelAfter; var guildobj = GuildConfig.GetServer(guild); if (guildobj.PartnerSetup.IsPartner && !guildobj.PartnerSetup.banned && ChannelBefore.Id == guildobj.PartnerSetup.PartherChannel) { var changes = ChannelAfter.PermissionOverwrites.Where(x => x.TargetType == PermissionTarget.Role && ChannelBefore.PermissionOverwrites .FirstOrDefault(y => y.TargetId == x.TargetId && (y.Permissions.AllowValue != x.Permissions.AllowValue || y.Permissions.DenyValue != x.Permissions.DenyValue)) .TargetId == x.TargetId).ToList(); var userlist = ((SocketTextChannel)s2).Users; var userstring = $"Users Visible/Total Users: {userlist.Count} / {guild.Users.Count}\n" + $"Percent Visible: {(double) userlist.Count / guild.Users.Count * 100}%"; var homeserver = Homeserver.Load(); var embed = new EmbedBuilder { Title = $"Partner Channel Updated", Description = $"{(changes.Any() ? string.Join("\n", changes.Select(x => $"Role: {guild.GetRole(x.TargetId)?.Name}\n" + $"Read Messages: {x.Permissions.ReadMessages}\n" + $"Read History: {x.Permissions.ReadMessageHistory}\n")) : "No Role Permissions Detected")}\n\n" + $"__**Channel Visibility**__\n" + $"{userstring}\n" + $"__**Server Info**__\n" + $"Guild ID: {guild.Id}\n" + $"Guild Name: {guild.Name}\n" + $"Channel name: {ChannelAfter.Name}", Color = Color.Blue, Footer = new EmbedFooterBuilder { Text = $"{DateTime.UtcNow.ToString(CultureInfo.InvariantCulture)} UTC TIME" } }; var channel = client.GetChannel(homeserver.PartnerUpdates); if (channel != null && !string.IsNullOrEmpty(embed.Description)) { await((ITextChannel)channel).SendMessageAsync("", false, embed.Build()); } } /* * if (guildobj.EventLogging) * { * if (ChannelAfter != null && ChannelBefore.Position != ChannelAfter.Position) * return; * var embed = new EmbedBuilder * { * Title = "Channel Updated", * Description = gChannel.Name, * Color = Color.Blue, * Footer = new EmbedFooterBuilder * { * Text = $"{DateTime.UtcNow.ToString(CultureInfo.InvariantCulture)} UTC TIME" * } * }; * await SendMessage(guild, guildobj, embed); * }*/ } }
public async Task PChannel() { var guild = GuildConfig.GetServer(Context.Guild); guild.PartnerSetup.PartherChannel = Context.Channel.Id; GuildConfig.SaveServer(guild); await ReplyAsync($"Partner Channel set to {Context.Channel.Name}"); if ((decimal)((SocketTextChannel)Context.Channel).Users.Count / ((SocketGuild)Context.Guild).Users.Count * 100 < 90) { await ReplyAsync( "NOTE: The partner channel is currently inactive as less that 90% of this server's users can view the channel. You can fix this by ensuring that all roles have permissions to view messages and message history in the channel settings"); } var home = Homeserver.Load().PartnerUpdates; var chan = await Context.Client.GetChannelAsync(home); if (chan is IGuildChannel channel) { try { var perms = ""; if (((SocketTextChannel)Context.Channel).PermissionOverwrites.Any()) { foreach (var perm in ((SocketTextChannel)Context.Channel).PermissionOverwrites.Where(x => x.TargetType == PermissionTarget.Role)) { var role = Context.Guild.Roles.FirstOrDefault(x => x.Id == perm.TargetId); if (role == null) { continue; } perms += $"__{role.Name}__\n" + $"Read Messages: {perm.Permissions.ReadMessages}\n" + $"Read history: {perm.Permissions.ReadMessageHistory}\n"; } } var userlist = ((SocketTextChannel)Context.Channel).Users; var userstring = $"Users Visible/Total Users: {userlist.Count} / {((SocketGuild) Context.Guild).Users.Count}\n" + $"Percent Visible: {(double) userlist.Count / ((SocketGuild) Context.Guild).Users.Count * 100}%"; var embed = new EmbedBuilder { Title = "Partner Channel Set", Description = $"{Context.Guild.Name}\n" + $"`{Context.Guild.Id}`\n" + $"Channel: {Context.Channel.Name}\n\n" + $"{perms}\n\n" + "__**Visibility**__\n" + $"{userstring}" }; await((IMessageChannel)channel).SendMessageAsync("", false, embed.Build()); } catch (Exception e) { Console.WriteLine(e); } } }
public async Task PMessage([Remainder] string input = null) { if (input == null) { await ReplyAsync("Please input a message"); return; } if (input.Length > 1024) { await ReplyAsync( $"Message is too long. Please limit it to 1024 characters or less. (Current = {input.Length})"); return; } if (NsfwStr.Profanity.Any(x => ProfanityFilter.RemoveDiacritics(input.ToLower()) .Contains(x.ToLower()))) { await ReplyAsync("Profanity Detected, unable to set message!"); return; } if (Context.Message.MentionedRoleIds.Any() || Context.Message.MentionedUserIds.Any() || Context.Message.MentionedChannelIds.Any() || Context.Message.Content.Contains("@everyone") || Context.Message.Content.Contains("@here")) { await ReplyAsync("There is no need to mention roles, users or channels in the partner " + "program as it shares to other servers which may not have access" + "to them!"); return; } if (!Regex.Match(input, @"(http:\/\/www\.|https:\/\/www\.|http:\/\/|https:\/\/)?(d+i+s+c+o+r+d+|a+p+p)+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(:[0-9]{1,5})?(\/.*)?$") .Success&& !input.Contains("discord.me")) { await ReplyAsync("You should include an invite link to your server in the Partner Message too\n" + $"If you believe this is an error, please contact the support server: {Tokens.Load().SupportServer}"); return; } if (Regex.Match(input, @"(http:\/\/www\.|https:\/\/www\.|http:\/\/|https:\/\/)?(d+i+s+c+o+r+d+|a+p+p)+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(:[0-9]{1,5})?(\/.*)?$") .Success) { var invites = Regex.Matches(input, @"(http:\/\/www\.|https:\/\/www\.|http:\/\/|https:\/\/)?(d+i+s+c+o+r+d+|a+p+p)+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(:[0-9]{1,5})?(\/.*)?$") .ToList(); var officialinvites = ((SocketGuild)Context.Guild).GetInvitesAsync().Result; var mismatch = false; foreach (var invite in invites) { var match = officialinvites.FirstOrDefault(x => invite.ToString().ToLower().Contains(x.Code.ToLower())); if (match == null) { mismatch = true; await ReplyAsync(invite.ToString()); } } if (mismatch) { await ReplyAsync("Only invites from this server are allowed in the partner message!\n" + "Also please ensure that the invite link you are using is set to never expire\n\n" + "If you are using an invite for your server and you are seeing this message, please generate a new invite for your server\n\n" + $"If you believe this is an error, please contact the support server: {Tokens.Load().SupportServer}"); return; } } var guild = GuildConfig.GetServer(Context.Guild); guild.PartnerSetup.Message = input; GuildConfig.SaveServer(guild); var embed = new EmbedBuilder { Title = Context.Guild.Name, Description = input, ThumbnailUrl = Context.Guild.IconUrl, Color = Color.Green }; await ReplyAsync("Success, here is your Partner Message:", false, embed.Build()); var home = Homeserver.Load().PartnerUpdates; var chan = await Context.Client.GetChannelAsync(home); if (chan is IMessageChannel channel) { try { var embed2 = new EmbedBuilder { Title = "Partner Msg. Updated", Description = $"{Context.Guild.Name}\n" + $"`{Context.Guild.Id}`\n" + $"{guild.PartnerSetup.Message}", Footer = new EmbedFooterBuilder { Text = $"{((SocketGuild) Context.Guild).Owner.Username}#{((SocketGuild) Context.Guild).Owner.Discriminator}" } }; await channel.SendMessageAsync("", false, embed2.Build()); } catch { // } } }
private async Task DoCommand(SocketMessage parameterMessage) { //Load.Messages++; if (!(parameterMessage is SocketUserMessage message)) { return; } var argPos = 0; var context = new SocketCommandContext(_client, message); //new CommandContext(_client, message); if (context.User.IsBot) { return; } Initialise(); var guild = GuildConfig.GetServer(context.Guild); if (await CheckMessage(message, context, guild)) { return; } await AutoMessage(context); if (message.HasMentionPrefix(_client.CurrentUser, ref argPos) && guild.chatwithmention) { var mcontent = context.Message.MentionedUsers.Aggregate(message.Content, (current, mentionedUser) => current.Replace(mentionedUser.Mention, mentionedUser.Username)); mcontent = context.Message.MentionedRoles.Aggregate(mcontent, (current, mentionedRole) => current.Replace(mentionedRole.Mention, mentionedRole.Name)); mcontent = context.Message.MentionedChannels.Aggregate(mcontent, (current, mentionedChannel) => current.Replace(((ITextChannel)mentionedChannel).Mention, mentionedChannel.Name)); try { var response = _apiAi.TextRequest(mcontent); if (response.Result.Fulfillment.Speech != "") { await context.Channel.SendMessageAsync(response.Result.Fulfillment.Speech); } } catch { // } return; } if (!(message.HasMentionPrefix(_client.CurrentUser, ref argPos) || message.HasStringPrefix(Load.Pre, ref argPos) || message.HasStringPrefix(GuildConfig.GetServer(context.Guild).Prefix, ref argPos))) { return; } var HS = Homeserver.Load(); if (HS.GlobalBans.Any(x => x.ID == context.User.Id)) { return; } var result = await _commands.ExecuteAsync(context, argPos, Provider); var server = context.Channel is IPrivateChannel ? "Direct Message " : context.Guild.Name; if (result.IsSuccess) { await LogHandler.In3($"{context.Message}", 'S', $"{server}", 'U', $"{context.User}"); //if there is no error log normally var srch = _commands.Search(context, argPos); if (srch.IsSuccess) { var name = srch.Commands.Select(x => x.Command.Name).FirstOrDefault(); if (name != null) { if (CommandUses.Any(x => string.Equals(x.Name, name, StringComparison.CurrentCultureIgnoreCase))) { var cmd = CommandUses.First(x => string.Equals(x.Name, name, StringComparison.CurrentCultureIgnoreCase)); cmd.Uses++; } else { CommandUses.Add(new CMD { Name = name.ToLower(), Uses = 1 }); } } } } else { try { if (!(result.Error == CommandError.UnknownCommand || result.Error == CommandError.BadArgCount || result.Error == CommandError.UnmetPrecondition)) { if (context.Client.GetChannel(HS.Error) is IMessageChannel ErrorChannel) { var embed = new EmbedBuilder { Title = $"ERROR: {context.Message}", Description = "REASON:\n" + $"{result.ErrorReason}", Color = Color.Red }; embed.WithFooter(x => { x.Text = $"{context.Message.CreatedAt} || {context.Guild.Name}"; }); await ErrorChannel.SendMessageAsync("", false, embed.Build()); } } } catch { // } try { //if in server error responses are enabled reply on error var desc = ""; if (result.Error != CommandError.UnknownCommand) { var srch = _commands.Search(context, argPos); var cmd = srch.Commands.FirstOrDefault(); desc += $"Command: {cmd.Command.Name}\n"; if (cmd.Command.Parameters.Any()) { desc += $"Parameters: {string.Join(" ", cmd.Command.Parameters.Select(x => x.IsOptional ? $" `<(Optional){x.Name}>` " : $" `<{x.Name}>` "))}\n"; } else { desc += "Parameters: N/A\n"; } desc += $"Summary: `{cmd.Command?.Summary}`\n" + $"Remarks: `{cmd.Command?.Remarks}`\n"; if (cmd.Command.Aliases.Any()) { desc += $"Aliases: {string.Join(" ", cmd.Command.Aliases)}\n"; } desc += "Error Reason:\n" + $"{result.ErrorReason}"; } else { desc += "Command: N/A"; } var errmsg = new EmbedBuilder { Title = $"**Error, {context.User.Username}**", Description = desc }; try { await context.Channel.SendMessageAsync("", false, errmsg.Build()); } catch { // } await LogHandler.In3Error($"{context.Message}", 'S', $"{context.Guild.Name}", 'E', $"{result.ErrorReason}"); // log errors as arrors }
private async Task <bool> CheckMessage(SocketUserMessage message, SocketCommandContext context, GuildConfig guild) { if (context.Channel is IDMChannel) { return(false); } try { var gmc = Load.GuildMsgCounts.FirstOrDefault(x => x.GuildID == context.Guild.Id); if (gmc == null) { Load.GuildMsgCounts.Add(new Load.GuildMSGCount { GuildID = context.Guild.Id, msgs = 0 }); } else { gmc.msgs++; } if (Homeserver.Load().DisableCheckMsg) { return(false); } if (guild.Levels.LevellingEnabled) { var apos = 0; if (!context.Message.HasStringPrefix(Config.Load().Prefix, ref apos) && !(context.Message.HasStringPrefix(guild.Prefix, ref apos) && !string.IsNullOrEmpty(guild.Prefix))) { try { //var userlv = guild.Levels.Users.FirstOrDefault(x => x.userID == context.User.Id); var LVGuild = Levels.FirstOrDefault(x => x.GuildID == guild.GuildId); var userlv = LVGuild.Users.FirstOrDefault(x => x.userID == context.User.Id); if (userlv != null) { if (!userlv.banned) { userlv.xp = userlv.xp + 10; var requiredxp = userlv.level * 50 + userlv.level * userlv.level * 25; if (userlv.xp >= requiredxp) { userlv.level++; string roleadded = null; if (guild.Levels.LevelRoles.Any()) { var rolesavailable = guild.Levels.LevelRoles.Where(x => x.LevelToEnter <= userlv.level - 1).ToList(); var roletoreceive = new List <GuildConfig.levelling.Level>(); if (rolesavailable.Any()) { if (guild.Levels.IncrementLevelRewards) { var maxrole = rolesavailable.Max(x => x.LevelToEnter); roletoreceive.Add(rolesavailable.FirstOrDefault(x => x.LevelToEnter == maxrole)); } else { roletoreceive = rolesavailable; } } if (roletoreceive.Count != 0) { foreach (var role in roletoreceive) { if (((IGuildUser)context.User).RoleIds.Contains(role.RoleID)) { continue; } var grole = context.Guild.GetRole(role.RoleID); if (grole != null) { try { await((SocketGuildUser)context.User).AddRoleAsync(grole); roleadded += $"Role Reward: {grole.Name}\n"; } catch { // } } else { guild.Levels.LevelRoles.Remove(role); } } if (roletoreceive.Count != rolesavailable.Count && roletoreceive.Count == 1) { try { rolesavailable.Remove(roletoreceive.First()); var roles = rolesavailable.Select(x => context.Guild.GetRole(x.RoleID)).Where(x => x != null); await((SocketGuildUser)context.User).RemoveRolesAsync(roles); } catch { // } } } } var embed = new EmbedBuilder { Title = $"{context.User.Username} Levelled Up!", ThumbnailUrl = context.User.GetAvatarUrl(), Description = $"Level: {userlv.level - 1}\n" + $"{roleadded}" + $"XP: {requiredxp}\n" + $"Next Level At: {userlv.level * 50 + userlv.level * userlv.level * 25} XP", Color = Color.Blue }; if (guild.Levels.UseLevelChannel) { try { if (context.Guild.GetChannel(guild.Levels.LevellingChannel) is IMessageChannel chan) { await chan.SendMessageAsync("", false, embed.Build()); } } catch { // } } if (guild.Levels.UseLevelMessages) { try { await context.Channel.SendMessageAsync("", false, embed.Build()); } catch { // } } } } } else { LVGuild.Users.Add(new GuildConfig.levelling.user { userID = context.User.Id, banned = false, level = 1, xp = 0 }); } LVGuild.UpdatesSinceLastSave++; if (LVGuild.UpdatesSinceLastSave > 25) { guild.Levels.Users = LVGuild.Users; GuildConfig.SaveServer(guild); LVGuild.UpdatesSinceLastSave = 0; } } catch (Exception e) { Console.WriteLine(e); } } } } catch (Exception e) { Console.WriteLine("CheckMessage Failed."); Console.WriteLine(e); } return(false); }
public async Task Start() { Console.Title = $"PassiveBOT"; Console.WriteLine( "██████╗ █████╗ ███████╗███████╗██╗██╗ ██╗███████╗██████╗ ██████╗ ████████╗\n" + "██╔══██╗██╔══██╗██╔════╝██╔════╝██║██║ ██║██╔════╝██╔══██╗██╔═══██╗╚══██╔══╝\n" + "██████╔╝███████║███████╗███████╗██║██║ ██║█████╗ ██████╔╝██║ ██║ ██║ \n" + "██╔═══╝ ██╔══██║╚════██║╚════██║██║╚██╗ ██╔╝██╔══╝ ██╔══██╗██║ ██║ ██║ \n" + "██║ ██║ ██║███████║███████║██║ ╚████╔╝ ███████╗██████╔╝╚██████╔╝ ██║ \n" + "╚═╝ ╚═╝ ╚═╝╚══════╝╚══════╝╚═╝ ╚═══╝ ╚══════╝╚═════╝ ╚═════╝ ╚═╝ \n" + "/--------------------------------------------------------------------------\\ \n" + "| Designed by PassiveModding - PassiveNation.com || Status: Connected | \n" + "\\--------------------------------------------------------------------------/ \n"); if (!Directory.Exists(Path.Combine(AppContext.BaseDirectory, "setup/"))) { Directory.CreateDirectory(Path.Combine(AppContext.BaseDirectory, "setup/")); } if (!Directory.Exists(Path.Combine(AppContext.BaseDirectory, "setup/config/"))) { Directory.CreateDirectory(Path.Combine(AppContext.BaseDirectory, "setup/config/")); } if (!Directory.Exists(Path.Combine(AppContext.BaseDirectory, "setup/server/"))) { Directory.CreateDirectory(Path.Combine(AppContext.BaseDirectory, "setup/server/")); } //if (!File.Exists(Path.Combine(AppContext.BaseDirectory, "setup/config/home.json"))) // File.Create(Path.Combine(AppContext.BaseDirectory, "setup/config/home.json")).Dispose(); Config.CheckExistence(); Homeserver.CheckExistence(); Tokens.CheckExistence(); var debug = Config.Load().Debug.ToUpper(); var token = Config.Load().Token; var ll = LogSeverity.Info; switch (debug) { case "Y": ll = LogSeverity.Debug; break; case "N": ll = LogSeverity.Info; break; default: await LogHandler.In1Run($"Error Loading Debug Config, Set to default (Entry = {debug})"); break; } Client = new DiscordSocketClient(new DiscordSocketConfig { LogLevel = ll, MessageCacheSize = 50 }); try { await Client.LoginAsync(TokenType.Bot, token); await Client.StartAsync(); } catch (Exception e) { await LogHandler.In1Run("Token was rejected by Discord (Invalid Token or Connection Error)\n" + $"{e}"); } var serviceProvider = ConfigureServices(); _handler = new CommandHandler(serviceProvider); var _ = new EventHandler(serviceProvider); await _handler.ConfigureAsync(); //checks if the user wants to log debug info or not if (ll == LogSeverity.Debug) { Client.Log += LogDebug; } else { Client.Log += LogMessageInfo; } await Task.Delay(-1); }