Exemple #1
0
        public async Task MainAsync()
        {
            await SetupDirectories();

            using (var services = ConfigureServices())
            {
                var client = services.GetRequiredService <DiscordSocketClient>();
                var config = new DiscordSocketConfig
                {
                    AlwaysDownloadUsers = true,
                    MessageCacheSize    = 200
                };

                _discord    = client;
                client.Log += LogAsync;
                services.GetRequiredService <CommandService>().Log += LogAsync;

                client.UserJoined += LogJoin;
                client.UserLeft   += LogLeave;



                Modules.LookupModule.InitialCache();

                //Token up
                await client.LoginAsync(TokenType.Bot, BotTools.GetSettingString(BotTools.ConfigurationEntries.BotToken));

                await client.StartAsync();

                //await services.GetRequiredService<ServerGuardService>().InitializeAsync();
                await services.GetRequiredService <CommandHandlingService>().InitializeAsync();

                await Task.Delay(-1);
            }
        }
Exemple #2
0
        /// <summary>
        /// This method asynchronously sends a message to the quote approval chat channel.
        /// </summary>
        /// <returns></returns>
        private async Task SendQuoteForApprovalAsync(SocketCommandContext context, SocketUser caller, string QuoteContents, int QuoteID)

        {
            SocketTextChannel chan = context.Guild.GetTextChannel(ulong.Parse(BotTools.GetSettingString(BotTools.ConfigurationEntries.QuoteReportChannelID)));
            var Caller             = caller as SocketGuildUser;
            //IEmote confirmEmote = caller.Guild.GetEmoteAsync()
            Emote confirmEmote = Emote.Parse("<:qbotDENY:858130936376590407>");
            Emote declineEmote = Emote.Parse("<:qbotAPPROVE:858130946985689088>");
            Emote ChonkboiL    = Emote.Parse("<:qbotBUFFER:858131961939361834>");
            Emote ChonkboiR    = Emote.Parse("<:qbotBUFFERER:858131975323779153>");
            Emote TFC          = Emote.Parse("<:TFC:297934728470855681>");
            var   sent         = await chan.SendMessageAsync($"__Quote Add Request__\n" +
                                                             $"**Requestor**: {Caller.Nickname} ({Caller.Username} - {Caller.Id})\n" +
                                                             $"**Quote**: {QuoteContents}");

            await sent.AddReactionAsync(confirmEmote);

            await sent.AddReactionAsync(ChonkboiL);

            await sent.AddReactionAsync(ChonkboiR);

            await sent.AddReactionAsync(declineEmote);

            discordclient = context.Client;
            context.Client.ReactionAdded += ListenForQuoteApproval;
        }
Exemple #3
0
        [RequireContext(ContextType.Guild)] //Cannot be requested via DM.
        public async Task GiveHamachiAsync()
        {
            //Log the caller.
            string LogEntry      = $"{DateTime.Now.ToString()} requested by {Context.User.Id} - {Context.User.Username}";
            var    ReportChannel = Context.Guild.GetTextChannel(BotTools.GetReportingChannelUlong());
            var    Requestor     = Context.User as SocketGuildUser;
            var    caller        = Context.User as IGuildUser;

            //Check the Netbattler Role.
            if (caller.RoleIds.Contains(RoleModule.GetRole("Netbattler", Context.Guild).Id))
            {
                //Check to see if the user can accept DMs.
                try
                {
                    string HamachiServer = BotTools.GetSettingString(BotTools.ConfigurationEntries.HamachiServer);
                    string HamachiPass   = BotTools.GetSettingString(BotTools.ConfigurationEntries.HamachiPassword);

                    await Context.User.SendMessageAsync($"**N1 Grand Prix Hamachi Server**\n```\nServer: {HamachiServer}\nPassword: {HamachiPass}\n```\n\nPlease ensure that your PC name on Hamachi matches your Nickname on the N1GP Discord to help make matchmaking easier.\n\n**DO NOT provide the N1 Grand Prix Hamachi server credentials to anyone outside the N1GP.**");

                    await ReportChannel.SendMessageAsync("", embed : EmbedTool.UserHamachiRequest(Requestor));

                    await ReplyAsync("You have e-mail.");
                }
                catch (Exception)
                {
                    await ReplyAsync("You currently have DMs disabled. Please enable DMs from users on the server to obtain the Hamachi credentials.");

                    throw;
                }
            }
            else
            {
                await ReplyAsync("You are not authorized to obtain Hamachi credentials. Use `!license` before attempting to use this command.");
            }
        }
Exemple #4
0
        public static async Task NotifyStrike(DiscordUser victim, DiscordUser striker, DiscordUserDataStrike strike, DiscordGuild guild, DiscordUserData data)
        {
            //Notify a user that they've been struck
            DiscordEmbedBuilder builder = new DiscordEmbedBuilder();

            builder.Title       = "You have been struck in " + guild.Name + "!";
            builder.Description = $"{striker.Username}#{striker.Discriminator} struck you. You now have {data.GetActiveStrikes().Length} strikes. When you hit {Program.config.ban_strikes} strikes, you will be **banned** from {guild.Name}.";
            if (strike.expire_time.HasValue)
            {
                builder.AddField("Expires", BotTools.DateTimeToString(strike.GetExpiry().Value));
            }
            else
            {
                builder.AddField("Expires", "*Never*");
            }
            builder.AddField("Striked By", $"{striker.Username}#{striker.Discriminator}");
            builder.AddField("Added", BotTools.DateTimeToString(strike.GetTime()));
            builder.AddField("Message", strike.message);
            builder.Color  = DiscordColor.Yellow;
            builder.Footer = new DiscordEmbedBuilder.EmbedFooter
            {
                Text = Program.FOOTER_TEXT
            };
            await BotTools.SendMemberMsg(victim.Id, builder.Build());
        }
        public static async Task NotifyPermaBan(DiscordGuild server, DiscordUser victim, DiscordUser cataylist, string reason, bool is_automated)
        {
            //Notify the user
            DiscordEmbedBuilder builder = new DiscordEmbedBuilder();

            builder.Title = "You have been banned from " + server.Name + ".";
            if (is_automated)
            {
                builder.Description = "You were removed from this server. You have had too many strikes applied to your account.";
            }
            else
            {
                builder.Description = "You were removed from this server. You were removed by a member.";
            }
            if (!is_automated)
            {
                builder.AddField("Banned By", $"{cataylist.Username}#{cataylist.Discriminator}");
                builder.AddField("Reason", reason);
            }
            builder.AddField("Recourse", "You may appeal a ban by writing an email to " + Program.config.contact + ". Please be thoughtful and descriptive.");
            builder.Color  = DiscordColor.Red;
            builder.Footer = new DiscordEmbedBuilder.EmbedFooter
            {
                Text = Program.FOOTER_TEXT
            };
            DiscordEmbed embed = builder.Build();

            //Send
            await BotTools.SendMemberMsg(victim.Id, embed);
        }
        public static async Task DoBanMember(DiscordUserData data, DiscordGuild server, DiscordUser victim, DiscordUser cataylist, string reason, bool is_automated, DateTime expire_time)
        {
            //Apply the ban to the account
            DiscordUserDataStatusBanned status = new DiscordUserDataStatusBanned
            {
                applied_since = DateTime.UtcNow.Ticks,
                expiry        = expire_time.Ticks,
                is_applied    = true,
                is_automated  = is_automated,
                reason        = reason
            };

            if (!is_automated)
            {
                status.catalyst = cataylist.Id;
            }
            data.temp_banned = status;

            //Notify the user
            DiscordEmbedBuilder builder = new DiscordEmbedBuilder();

            builder.Title = "You have been temporarily banned from " + server.Name + ".";
            if (is_automated)
            {
                builder.Description = "You were removed from this server. You have had too many strikes applied to your account.";
            }
            else
            {
                builder.Description = "You were removed from this server. You were removed by a member.";
            }
            if (!is_automated)
            {
                builder.AddField("Banned By", $"{cataylist.Username}#{cataylist.Discriminator}");
                builder.AddField("Reason", reason);
            }
            builder.AddField("Expires", BotTools.DateTimeToString(expire_time));
            builder.AddField("Expires In", BotTools.DateTimeOffsetToString(expire_time - DateTime.UtcNow));
            builder.Color  = DiscordColor.Red;
            builder.Footer = new DiscordEmbedBuilder.EmbedFooter
            {
                Text = Program.FOOTER_TEXT
            };
            DiscordEmbed embed = builder.Build();

            //Send
            await BotTools.SendMemberMsg(victim.Id, embed);

            //Kick
            DiscordMember victimMember = await server.GetMemberAsync(victim.Id);

            await server.RemoveMemberAsync(victimMember, "Automated temporary ban system.");

            //Save
            data.Save();
        }
        public static async Task OnBannedMemberJoined(DiscordUserData data, DiscordGuild server, DiscordMember member)
        {
            //Gather data
            DiscordUserDataStatusBanned status = data.temp_banned;

            //Send them a message telling them why they were banned, if they have any strikes, ect.
            DiscordEmbedBuilder builder = new DiscordEmbedBuilder();

            builder.Title = "You are banned temporarily from " + server.Name + ".";
            if (status.is_automated)
            {
                builder.Description = "You cannot join this server. You were banned for having too many strikes. Your active strikes are listed below.";
                var strikes = data.GetActiveStrikes();
                for (int i = 0; i < strikes.Length; i += 1)
                {
                    DiscordUserDataStrike strike = strikes[i];
                    string message = $"*Added {BotTools.DateTimeToString(strike.GetTime())}*\n";
                    if (strike.expire_time.HasValue)
                    {
                        message += $"*__Expires {BotTools.DateTimeToString(strike.GetExpiry().Value)}__*\n";
                    }
                    else
                    {
                        message += "*__Never expires__*\n";
                    }
                    builder.AddField($"Strike {i+1} from {await BotTools.GetRemoteUsername(strike.striker)}", message + strike.message);
                }
            }
            else
            {
                DiscordUser user = await Program.discord.GetUserAsync(status.catalyst);

                builder.Description = $"You cannot join this server. You were banned by a member.";
                builder.AddField("Banned By", $"{user.Username}#{user.Discriminator}");
                builder.AddField("Reason", status.reason);
            }
            builder.AddField("Expires", $"This ban expires on {BotTools.DateTimeToString((DateTime)status.GetExpiry())}. You may rejoin after this time.");
            builder.AddField("Expires In", BotTools.DateTimeOffsetToString((DateTime)status.GetExpiry() - DateTime.UtcNow));
            builder.AddField("Added", $"You were banned on {BotTools.DateTimeToString(status.GetAppliedSince())}");
            builder.Color  = DiscordColor.Red;
            builder.Footer = new DiscordEmbedBuilder.EmbedFooter
            {
                Text = Program.FOOTER_TEXT
            };
            DiscordEmbed embed = builder.Build();

            //DM this to the person
            await BotTools.SendMemberMsg(member.Id, embed);

            //Kick them from this server
            await server.RemoveMemberAsync(member, "Automated temp ban system.");
        }
        ///// <summary>
        ///// Enables the NewMoon module.
        ///// </summary>
        ///// <returns></returns>
        //[Command("newmoon open")]
        //public async Task EnableNewMoonAsync()
        //{
        //    if (IsEventOrganizer(Context.User as IGuildUser, Context.Guild))
        //    {

        //    }
        //}

        ///// <summary>
        ///// Temporarily halts the NewMoon module.
        ///// </summary>
        ///// <returns></returns>
        //[Command("newmoon close")]
        //public async Task DisableNewMoonAsync()
        //{
        //    if (IsEventOrganizer(Context.User as IGuildUser, Context.Guild))
        //    {

        //    }
        //}

        //[Command("newmoon close 1")]
        //public async Task CloseCycle1Async()
        //{
        //    dynamic EventConfiguration = JsonConvert.DeserializeObject(System.IO.File.ReadAllText($"{Directory.GetCurrentDirectory()}{Path.DirectorySeparatorChar}NewMoon{Path.DirectorySeparatorChar}Config.json"));
        //    EventConfiguration.Cycle1OpenReg = false;
        //    File.WriteAllText($"{Directory.GetCurrentDirectory()}{Path.DirectorySeparatorChar}NewMoon{Path.DirectorySeparatorChar}Config.json", JsonConvert.SerializeObject(EventConfiguration, Formatting.Indented));
        //    await ReplyAsync("Cycle 1 registration has been closed.");
        //}

        //TODO: Implement Newmoon close 2, open 1, open 2. Update Save acceptance to see if Newmoon is active and implement setups accordingly. Implement registratnt listing.

        /// <summary>
        /// DMs the caller the New Moon registrations with the following spec:
        ///
        /// 1. "[Registrant Name] (Discord Nickname)"
        /// 2. Folder 1
        /// 3. Folder 2
        /// 4. Navicust Setups
        ///
        /// This method compiles all active registrations into a singular text file for easy parsing.
        /// </summary>
        /// <returns></returns>
        //[Command("newmoon setups")]
        //public async Task GetNewMoonRegistrantsAsync()
        //{
        //    //PSUEDO:
        //    // obtain a list of setup files from the setups folder.
        //    // substring out the Discord ID for lookup
        //    //
        //}

        /// <summary>
        /// Registers the caller for the New Moon cycle that's currently active.
        /// </summary>
        //[Command("newmoon join")]
        //public async Task RegisterNewMoonAsync([Remainder]string NetbattlerName)
        //{

        //    if (IsNewMoonActive == true) //Is Newmoon Active?
        //    {
        //        if (Cycle1Open) //Is the current cycle open?
        //        {
        //            await AddNewMoonRoleAsync(Context.User as IGuildUser, RoleModule.GetRole("MOON BATTLER", Context.Guild)); //Add the MOON BATTLER role.
        //            NewMoonParticipant newParticipant = new NewMoonParticipant(NetbattlerName.Replace('@', ' '), Context.User.Id, 1); //Create the Participant Entry based on the model. The Model creation automatically sets the location based on the cycle.
        //            Cycle1Participants.Add(newParticipant);
        //            WriteParticipantList();
        //            await ReplyAsync("You have registered for NEW MOON. Your Cycle is the current one. !awoo");
        //        }
        //        else //The registration needs to go to the next upcoming cycle.
        //        {
        //            await AddNewMoonRoleAsync(Context.User as IGuildUser, RoleModule.GetRole("MOON BATTLER", Context.Guild)); //Add the MOON BATTLER role.
        //            NewMoonParticipant newParticipant = new NewMoonParticipant(NetbattlerName.Replace('@', ' '), Context.User.Id, 2); //Create the Participant Entry based on the model. The Model creation automatically sets the location based on the cycle.
        //            Cycle2Participants.Add(newParticipant);
        //            WriteParticipantList();
        //            await ReplyAsync("You have registered for NEW MOON. Your Cycle is the upcoming one. !awoo");
        //        }

        //        SyncParticipantList();
        //    }

        //}

        //[Command("newmoon advance")]
        //public async Task AdvanceNewmoonAsync()
        //{

        //}

        //========================Support Functions=====================

        private bool IsEventOrganizer(IGuildUser caller, SocketGuild TargetServer)
        {
            SocketRole role = BotTools.GetRole("Event Organizer", TargetServer);

            if (caller.RoleIds.Contains(role.Id))
            {
                return(true); //The user is an event organizer.
            }
            else
            {
                return(false); //The user is not an event organizer.
            }
        }
        public static async Task OnCmd(DSharpPlus.EventArgs.MessageCreateEventArgs e, string prefix, string content, DiscordMember member, DiscordPermissionLevel perms, DiscordUserData data)
        {
            if (content.Length == 0)
            {
                await ReturnHelp(e);

                return;
            }

            //Do it

            //Find the user
            DiscordUser victim = await BotTools.ParseOfflineName(content.Trim(' '));

            //If not found, complain
            if (victim == null)
            {
                DiscordEmbedBuilder badBuilder = new DiscordEmbedBuilder();
                badBuilder.Title       = "User Not Found";
                badBuilder.Description = $"\"{content.Trim(' ')}\" was not found. Try their ID.";
                badBuilder.Color       = DiscordColor.Yellow;
                badBuilder.Footer      = new DiscordEmbedBuilder.EmbedFooter
                {
                    Text = Program.FOOTER_TEXT
                };
                await e.Message.RespondAsync(embed : badBuilder.Build());

                return;
            }

            //Get user
            DiscordUserData victimData = BotTools.GetUserDataById(victim.Id);

            //Set as not active
            victimData.temp_banned.is_applied = false;

            //Save
            victimData.Save();

            //Write OK
            DiscordEmbedBuilder okBuilder = new DiscordEmbedBuilder();

            okBuilder.Title       = "User Unbanned";
            okBuilder.Description = $"{victim.Username}#{victim.Discriminator} ({victim.Id}) was unbanned.";
            okBuilder.Color       = DiscordColor.Green;
            okBuilder.Footer      = new DiscordEmbedBuilder.EmbedFooter
            {
                Text = Program.FOOTER_TEXT
            };
            await e.Message.RespondAsync(embed : okBuilder.Build());
        }
Exemple #10
0
        public void Execute(Message message)
        {
            Manager.BotClient.DeleteMessageAsync(message.Chat.Id, message.MessageId);

            string text = Utils.Parsers.VariablesParser(CacheData.SysConfigs
                                                        .Single(x => x.SysConfigId == "HelpMenu")
                                                        .Value);

            if (ChatTools.IsUserAdmin(message.Chat.Id, message.From.Id))
            {
                text += Environment.NewLine;
                text += CacheData.SysConfigs
                        .Single(x => x.SysConfigId == "HelpMenuAdmin")
                        .Value;
            }

            if (BotTools.IsUserOperator(message.From.Id))
            {
                text += Environment.NewLine;
                text += CacheData.SysConfigs
                        .Single(x => x.SysConfigId == "HelpMenuOperatorBase")
                        .Value;

                if (BotTools.IsUserOperator(message.From.Id, Models.Operator.Levels.Advanced))
                {
                    text += Environment.NewLine;
                    text += CacheData.SysConfigs
                            .Single(x => x.SysConfigId == "HelpMenuOperatorAdv")
                            .Value;
                }
            }

            text += Environment.NewLine;
            text += Environment.NewLine;
            text += "* usernames are saved in cache and never stored on database or file. The cache is cleared at every reboot or update.";

            MessageQueueManager.EnqueueMessage(
                new Models.ChatMessage()
            {
                Timestamp = DateTime.UtcNow,
                Chat      = message.Chat,
                ParseMode = ParseMode.Html,
                Text      = text
            });
        }
Exemple #11
0
        public async static void ProcessInput(this ITelegramBotClient botClient, Update update)
        {
            if (update == null)
            {
                return;
            }
            var message = update.Message;

            if (message?.Type == MessageType.TextMessage)
            {
                if (BotTools.TryParseCommand(message.Text, out string command, out string args))
                {
                    if (VpnBotCommandCollection.Includes(command))
                    {
                        botClient.ProcessCommand(message, command, args);
                    }
                }
                else
                {
                    await botClient.SendTextMessageAsync(message.Chat.Id, "Sorry, i don't understand you.");
                }
            }
Exemple #12
0
        [RequireContext(ContextType.Guild)] //Cannot be requested via DM.
        public async Task GiveRadminAsync()
        {
            //Log the caller.
            string LogEntry      = $"{DateTime.Now.ToString()} requested by {Context.User.Id} - {Context.User.Username}";
            var    ReportChannel = Context.Guild.GetTextChannel(BotTools.GetReportingChannelUlong());
            var    Requestor     = Context.User as SocketGuildUser;
            var    caller        = Context.User as IGuildUser;

            //Check the Netbattler Role.
            if (caller.RoleIds.Contains(RoleModule.GetRole("Netbattler", Context.Guild).Id))
            {
                //Check to see if the user can accept DMs.
                try
                {
                    //Pivoting this to a complete message rather than


                    string RadminServer = BotTools.GetSettingString(BotTools.ConfigurationEntries.RadminCredentialString);

                    await Context.User.SendMessageAsync(RadminServer);              //Updated this to, instead of using a template, use a moderator-specified string in its entirety. -MMX 6/18/2021

                    await ReportChannel.SendMessageAsync("", embed : EmbedTool.UserRadminRequest(Requestor));
                    await ReplyAsync("You have e-mail.");
                }
                catch (Exception)
                {
                    await ReplyAsync("You currently have DMs disabled. Please enable DMs from users on the server to obtain the Radmin credentials.");

                    throw;
                }
            }
            else
            {
                await ReplyAsync("You are not authorized to obtain Radmin credentials. Use `!license` before attempting to use this command.");
            }
        }
        public static async Task ReturnOk(DSharpPlus.EventArgs.MessageCreateEventArgs e, DiscordUser victim, DateTime time)
        {
            DiscordEmbedBuilder builder = new DiscordEmbedBuilder();

            builder.Title       = "User Temporarily Banned";
            builder.Description = $"{victim.Username}#{victim.Discriminator} ({victim.Id}) has been banned. They will be unbanned in {BotTools.DateTimeOffsetToString(time - DateTime.UtcNow).TrimEnd(' ')}.";
            builder.Color       = DiscordColor.Green;
            builder.Footer      = new DiscordEmbedBuilder.EmbedFooter
            {
                Text = Program.FOOTER_TEXT
            };
            await e.Message.RespondAsync(embed : builder.Build());
        }
        public static async Task OnCmd(DSharpPlus.EventArgs.MessageCreateEventArgs e, string prefix, string content, DiscordMember member, DiscordPermissionLevel perms, DiscordUserData data)
        {
            //Check if this is prompting for help
            string[] split = content.Split(',');
            if (content.Length == 0 || split.Length < 3)
            {
                await ReturnHelp(e);

                return;
            }

            //Parse the message parts
            string memberString  = split[0];
            string timeString    = split[1];
            string messageString = content.Substring(2 + memberString.Length + timeString.Length);

            //Find the user
            DiscordUser victim = await BotTools.ParseName(e.Guild, memberString.Trim(' '));

            //If the bot failed to find the user, throw an error
            if (victim == null)
            {
                await ReturnError(e, "Failed to Find User", $"Failed to find the user, ``{memberString.Trim(' ')}``. You can use their ID, their full name, or their first name. You can also mention them.");

                return;
            }

            //Find time
            DateTime time;
            int      timeParseErrorCount = 0;
            int      timeParseCount      = 0;

            if (timeString.Trim(' ').ToLower() != "never")
            {
                time = BotTools.ParseTime(timeString.Trim(' '), out timeParseErrorCount, out timeParseCount);
            }
            else
            {
                await ReturnError(e, "Cannot Perma Ban", "Please use the ban function built into Discord to permaban a member.");

                return;
            }

            //If the time parse didn't find any, or if there were any errors, stop
            if ((timeParseCount == 0 || timeParseErrorCount > 0))
            {
                await ReturnError(e, "Failed to Parse Time", "There was a problem parsing the time you entered. Do not include commas in the time, make sure you use spaces to separate each part, and make sure you do not use weeks. For help, do not include any arguments and run the command again.");

                return;
            }

            //Limit message to 900 characters
            if (messageString.Length > 900)
            {
                await ReturnError(e, "Reason is Too Long", "Sorry, the reason is limited by Discord to 900 characters.");

                return;
            }

            //Get the user data for the person we just banned and apply.
            DiscordUserData victimUserData = BotTools.GetUserDataById(victim.Id);

            victimUserData.latest_name = $"{victim.Username}#{victim.Discriminator}";
            victimUserData.temp_banned = new DiscordUserDataStatusBanned
            {
                applied_since = DateTime.UtcNow.Ticks,
                catalyst      = e.Author.Id,
                expiry        = time.Ticks,
                is_applied    = true,
                is_automated  = false,
                reason        = messageString
            };

            //Apply the ban to the account
            await ActionTools.BanTools.DoBanMember(victimUserData, e.Guild, victim, e.Author, messageString, false, time);

            //Save
            victimUserData.Save();

            //Write OK
            await ReturnOk(e, victim, time);
        }
Exemple #15
0
        public static async Task OnCmd(DSharpPlus.EventArgs.MessageCreateEventArgs e, string prefix, string content, DiscordMember member, DiscordPermissionLevel perms, DiscordUserData data)
        {
            //Check if this is prompting for help
            string[] split = content.Split(',');
            if (content.Length == 0 || split.Length < 3)
            {
                await ReturnHelp(e);

                return;
            }

            //Parse the message parts
            string memberString  = split[0];
            string timeString    = split[1];
            string messageString = content.Substring(2 + memberString.Length + timeString.Length);

            //Find the user
            DiscordUser victim = await BotTools.ParseName(e.Guild, memberString.Trim(' '));

            //If the bot failed to find the user, throw an error
            if (victim == null)
            {
                await ReturnError(e, "Failed to Find User", $"Failed to find the user, ``{memberString.Trim(' ')}``. You can use their ID, their full name, or their first name. You can also mention them.");

                return;
            }

            //Find time
            bool     isForever = true;
            DateTime?time;
            int      timeParseErrorCount = 0;
            int      timeParseCount      = 0;

            if (timeString.Trim(' ').ToLower() != "never")
            {
                time      = BotTools.ParseTime(timeString.Trim(' '), out timeParseErrorCount, out timeParseCount);
                isForever = false;
            }
            else
            {
                time = null;
            }

            //If the time parse didn't find any, or if there were any errors, stop
            if (time != null && (timeParseCount == 0 || timeParseErrorCount > 0))
            {
                await ReturnError(e, "Failed to Parse Time", "There was a problem parsing the time you entered. Do not include commas in the time, make sure you use spaces to separate each part, and make sure you do not use weeks. For help, do not include any arguments and run the command again.");

                return;
            }

            //Limit message to 900 characters
            if (messageString.Length > 900)
            {
                await ReturnError(e, "Reason is Too Long", "Sorry, the reason is limited by Discord to 900 characters.");

                return;
            }

            //Awesome. Now, create the strike
            DiscordUserDataStrike strike = new DiscordUserDataStrike
            {
                time    = DateTime.UtcNow.Ticks,
                striker = e.Author.Id,
                message = messageString
            };

            if (time.HasValue)
            {
                strike.expire_time = time.Value.Ticks;
            }

            //Get the user data for the person we just struck and apply.
            DiscordUserData victimUserData = BotTools.GetUserDataById(victim.Id);

            victimUserData.strikes.Add(strike);

            //Send a notification of this to the person
            await NotifyStrike(victim, member, strike, e.Guild, victimUserData);

            //Check if we need to issue a ban for this member
            var activeStrikes = victimUserData.GetActiveStrikes();

            if (activeStrikes.Length >= Program.config.ban_strikes)
            {
                //Ban time! Find when the latest ban expire happens
                DateTime latest_expire = DateTime.MaxValue;
                bool     does_expire   = false;
                foreach (var a in activeStrikes)
                {
                    if (a.expire_time.HasValue)
                    {
                        does_expire = true;
                        if (a.GetExpiry().Value < latest_expire)
                        {
                            latest_expire = a.GetExpiry().Value;
                        }
                    }
                }
                if (does_expire)
                {
                    //Temp ban
                    await ActionTools.BanTools.DoBanMember(victimUserData, e.Guild, victim, e.Author, "You are banned for having too many strikes.", true, latest_expire);
                }
                else
                {
                    //Send message
                    await ActionTools.BanTools.NotifyPermaBan(e.Guild, victim, e.Author, "You are banned for having too many strikes.", true);

                    //Ban from the server
                    DiscordMember victimMember = await e.Guild.GetMemberAsync(victim.Id);

                    await e.Guild.BanMemberAsync(victimMember, 0, "Temporary ban system.");
                }
            }

            //Save
            victimUserData.Save();

            //Return OK
            await ReturnOk(e, victim, activeStrikes.Length);
        }
 /// <summary>
 /// To be called from the bot's initialization, this caches the ChipLibrary JSON.
 /// </summary>
 public static void InitialCache()
 {
     ChipLibrary = JsonConvert.DeserializeObject <List <Chip> >(File.ReadAllText(BotTools.GetSettingString(BotTools.ConfigurationEntries.ChipLibraryFileLocation)));
     Console.WriteLine("Chip Library Initialized.");
 }
Exemple #17
0
        public void Execute(Message message)
        {
            Manager.BotClient.DeleteMessageAsync(message.Chat.Id, message.MessageId);

            if (!BotTools.IsUserOperator(message.From.Id) &&
                !ChatTools.IsUserAdmin(message.Chat.Id, message.From.Id))
            {
                MessageQueueManager.EnqueueMessage(
                    new Models.ChatMessage()
                {
                    Timestamp        = DateTime.UtcNow,
                    Chat             = message.Chat,
                    ReplyToMessageId = message.MessageId,
                    Text             = CacheData.GetTranslation("en", "error_not_auth_command")
                });
                return;
            }
            int userToKick;

            if (message.ReplyToMessage == null)
            {
                if (message.Text.Split(" ")[1].StartsWith("@"))
                {
                    if (!CacheData.Usernames.Keys.Contains(message.Text.Split(" ")[1].Remove(0, 1)))
                    {
                        MessageQueueManager.EnqueueMessage(
                            new Models.ChatMessage()
                        {
                            Timestamp = DateTime.UtcNow,
                            Chat      = message.Chat,
                            Text      = CacheData.GetTranslation("en", "kick_command_error_invalidUsername")
                        });
                        return;
                    }
                    userToKick = CacheData.Usernames[message.Text.Split(" ")[1].Remove(0, 1)];
                }
                else
                {
                    bool isValid = int.TryParse(message.Text.Split(" ")[1], out userToKick);
                    if (!isValid)
                    {
                        MessageQueueManager.EnqueueMessage(
                            new Models.ChatMessage()
                        {
                            Timestamp = DateTime.UtcNow,
                            Chat      = message.Chat,
                            Text      = CacheData.GetTranslation("en", "kick_command_error_invalidUserId")
                        });
                        return;
                    }
                }
            }
            else
            {
                userToKick = message.ReplyToMessage.From.Id;
            }

            if (userToKick == 777000) // Telegram's official updateServiceNotification
            {
                Manager.BotClient.SendTextMessageAsync(
                    chatId: message.Chat.Id,
                    parseMode: ParseMode.Markdown,
                    text: String.Format(
                        "*[Error]*\n" +
                        "This is an official Telegram's user/id.")
                    );

                return;
            }

            if (BotTools.IsUserOperator(userToKick))
            {
                MessageQueueManager.EnqueueMessage(
                    new Models.ChatMessage()
                {
                    Timestamp = DateTime.UtcNow,
                    Chat      = message.Chat,
                    Text      = CacheData.GetTranslation("en", "command_to_operator_not_allowed")
                });

                return;
            }

            try
            {
                Manager.BotClient.KickChatMemberAsync(message.Chat.Id, userToKick);
                if (message.Chat.Type == ChatType.Supergroup)
                {
                    Manager.BotClient.UnbanChatMemberAsync(message.Chat.Id, userToKick);
                }
            }
            catch
            {
                MessageQueueManager.EnqueueMessage(
                    new Models.ChatMessage()
                {
                    Timestamp = DateTime.UtcNow,
                    Chat      = message.Chat,
                    ParseMode = ParseMode.Markdown,
                    Text      = CacheData.GetTranslation("en", "command_kick_error")
                });
                return;
            }

            UserTools.AddPenalty(message.Chat.Id, userToKick,
                                 Models.TrustFactorLog.TrustFactorAction.kick, Manager.MyId);
        }
Exemple #18
0
        public void Execute(Message message)
        {
            Manager.BotClient.DeleteMessageAsync(message.Chat.Id, message.MessageId);

            if (!BotTools.IsUserOperator(message.From.Id) &&
                !ChatTools.IsUserAdmin(message.Chat.Id, message.From.Id))
            {
                MessageQueueManager.EnqueueMessage(
                    new Models.ChatMessage()
                {
                    Timestamp        = DateTime.UtcNow,
                    Chat             = message.Chat,
                    ReplyToMessageId = message.MessageId,
                    Text             = CacheData.GetTranslation("en", "error_not_auth_command")
                });
                return;
            }

            int userId;

            if (message.ReplyToMessage == null)
            {
                if (message.Text.Split(" ")[1].StartsWith("@"))
                {
                    if (!CacheData.Usernames.Keys.Contains(message.Text.Split(" ")[1].Remove(0, 1)))
                    {
                        MessageQueueManager.EnqueueMessage(
                            new Models.ChatMessage()
                        {
                            Timestamp = DateTime.UtcNow,
                            Chat      = message.Chat,
                            Text      = CacheData.GetTranslation("en", "mute_command_error_invalidUsername")
                        });
                        return;
                    }
                    userId = CacheData.Usernames[message.Text.Split(" ")[1].Remove(0, 1)];
                }
                else
                {
                    bool isValid = int.TryParse(message.Text.Split(" ")[1], out userId);
                    if (!isValid)
                    {
                        MessageQueueManager.EnqueueMessage(
                            new Models.ChatMessage()
                        {
                            Timestamp = DateTime.UtcNow,
                            Chat      = message.Chat,
                            Text      = CacheData.GetTranslation("en", "mute_command_error_invalidUserId")
                        });
                        return;
                    }
                }
            }
            else
            {
                userId = message.ReplyToMessage.From.Id;
            }

            if (BotTools.IsUserOperator(userId))
            {
                MessageQueueManager.EnqueueMessage(
                    new Models.ChatMessage()
                {
                    Timestamp = DateTime.UtcNow,
                    Chat      = message.Chat,
                    Text      = CacheData.GetTranslation("en", "command_to_operator_not_allowed")
                });

                return;
            }

            try
            {
                Manager.BotClient.RestrictChatMemberAsync(
                    message.Chat.Id,
                    userId,
                    new ChatPermissions()
                {
                    CanSendMessages       = false,
                    CanAddWebPagePreviews = false,
                    CanChangeInfo         = false,
                    CanInviteUsers        = false,
                    CanPinMessages        = false,
                    CanSendMediaMessages  = false,
                    CanSendOtherMessages  = false,
                    CanSendPolls          = false
                });

                MessageQueueManager.EnqueueMessage(
                    new Models.ChatMessage()
                {
                    Timestamp = DateTime.UtcNow,
                    Chat      = message.Chat,
                    Text      = CacheData.GetTranslation("en", "mute_command_success")
                });
            }
            catch
            {
                MessageQueueManager.EnqueueMessage(
                    new Models.ChatMessage()
                {
                    Timestamp = DateTime.UtcNow,
                    Chat      = message.Chat,
                    ParseMode = ParseMode.Markdown,
                    Text      = CacheData.GetTranslation("en", "command_mute_error")
                });
            }
        }
Exemple #19
0
 /// <summary>
 /// Creates and sends an embed for a user Leaving the Discord server.
 /// </summary>
 /// <param name="user"></param>
 /// <returns></returns>
 private async Task LogLeave(SocketGuildUser user)
 {
     await BotTools.GetReportingChannel(_discord).SendMessageAsync("", embed: EmbedTool.UserLeaveLog(user));
 }
Exemple #20
0
 private async Task LogJoin(SocketGuildUser user)
 {
     //v4: Moved redundant code to BotTools.
     await BotTools.GetReportingChannel(_discord).SendMessageAsync("", embed: EmbedTool.UserJoinLog(user));
 }
Exemple #21
0
        public void Execute(Message message)
        {
            if (!BotTools.IsUserOperator(message.From.Id, Models.Operator.Levels.Basic) &&
                !ChatTools.IsUserAdmin(message.Chat.Id, message.From.Id))
            {
                MessageQueueManager.EnqueueMessage(
                    new Models.ChatMessage()
                {
                    Timestamp = DateTime.UtcNow,
                    Chat      = message.Chat,
                    Text      = CacheData.GetTranslation("en", "ban_command_error_notadmin")
                });
                return;
            }

            if (Manager.BotClient.GetChatAdministratorsAsync(message.Chat.Id).Result
                .Single(x => x.User.Id == message.From.Id)
                .CanRestrictMembers == false)
            {
                MessageQueueManager.EnqueueMessage(
                    new Models.ChatMessage()
                {
                    Timestamp = DateTime.UtcNow,
                    Chat      = message.Chat,
                    Text      = CacheData.GetTranslation("en", "ban_command_error_adminPrivilege")
                });
                return;
            }

            int userToKick;

            if (message.ReplyToMessage == null)
            {
                if (message.Text.Split(" ")[1].StartsWith("@"))
                {
                    if (!CacheData.Usernames.Keys.Contains(message.Text.Split(" ")[1].Remove(0, 1)))
                    {
                        MessageQueueManager.EnqueueMessage(
                            new Models.ChatMessage()
                        {
                            Timestamp = DateTime.UtcNow,
                            Chat      = message.Chat,
                            Text      = CacheData.GetTranslation("en", "ban_command_error_invalidUsername")
                        });
                        return;
                    }
                    userToKick = CacheData.Usernames[message.Text.Split(" ")[1].Remove(0, 1)];
                }
                else
                {
                    bool isValid = int.TryParse(message.Text.Split(" ")[1], out userToKick);
                    if (!isValid)
                    {
                        MessageQueueManager.EnqueueMessage(
                            new Models.ChatMessage()
                        {
                            Timestamp = DateTime.UtcNow,
                            Chat      = message.Chat,
                            Text      = CacheData.GetTranslation("en", "ban_command_error_invalidUserId")
                        });
                        return;
                    }
                }
            }
            else
            {
                userToKick = message.ReplyToMessage.From.Id;
            }

            if (userToKick == 777000) // Telegram's official updateServiceNotification
            {
                Manager.BotClient.SendTextMessageAsync(
                    chatId: message.Chat.Id,
                    parseMode: ParseMode.Markdown,
                    text: String.Format(
                        "*[Error]*\n" +
                        "This is an official Telegram's user/id.")
                    );

                return;
            }

            if (BotTools.IsUserOperator(userToKick))
            {
                MessageQueueManager.EnqueueMessage(
                    new Models.ChatMessage()
                {
                    Timestamp = DateTime.UtcNow,
                    Chat      = message.Chat,
                    Text      = CacheData.GetTranslation("en", "command_to_operator_not_allowed")
                });

                return;
            }

            try
            {
                Manager.BotClient.KickChatMemberAsync(message.Chat.Id, userToKick,
                                                      DateTime.UtcNow.AddMinutes(-5));
                MessageQueueManager.EnqueueMessage(
                    new Models.ChatMessage()
                {
                    Timestamp = DateTime.UtcNow,
                    Chat      = message.Chat,
                    Text      = CacheData.GetTranslation("en", "ban_command_success")
                });
            }
            catch
            {
                MessageQueueManager.EnqueueMessage(
                    new Models.ChatMessage()
                {
                    Timestamp = DateTime.UtcNow,
                    Chat      = message.Chat,
                    Text      = CacheData.GetTranslation("en", "ban_command_error")
                });
                return;
            }

            UserTools.AddPenalty(message.Chat.Id, userToKick,
                                 Models.TrustFactorLog.TrustFactorAction.ban, Manager.MyId);
        }