Ejemplo n.º 1
0
        public static async Task <bool> ReplyValidateZoneAsync(this OfcModuleBase moduleBase, IZone zone, string zoneName = "")
        {
            if (!zone.IsValid())
            {
                string message = "No such zone exists.";

                if (!string.IsNullOrEmpty(zoneName))
                {
                    zoneName = ZoneUtilities.GetFullName(zoneName);

                    if (zoneName.StartsWith("zone", System.StringComparison.OrdinalIgnoreCase))
                    {
                        message = $"{zoneName.ToTitle().ToBold()} does not exist.";
                    }
                    else
                    {
                        message = $"Zone {zoneName.ToTitle().ToBold()} does not exist.";
                    }
                }

                await DiscordUtilities.ReplyErrorAsync(moduleBase.Context.Channel, message);

                return(false);
            }

            return(true);
        }
Ejemplo n.º 2
0
        public Task RemoveChannelAsync(IChannel channel)
        {
            if (channel is null)
            {
                return(Task.CompletedTask);
            }

            var cid = channel.Id;

            if (!ServerConfigService.GetConfig(Context.Guild).PublicCommandChannels.Contains(cid))
            {
                return(ReplyAsync(
                           "This channel is not in the list!",
                           messageReference: DiscordUtilities.ContextReply(Context)
                           ));
            }

            var modifyTask = ServerConfigService.ModifyConfig(Context.Guild.Id, (config) =>
            {
                config.PublicCommandChannels.Remove(cid);
            }
                                                              );
            var loggerTask = ReplyAsync(
                $"Got it! The channel {DiscordUtilities.ClickableChannel(channel)} has been removed from the list!",
                messageReference: DiscordUtilities.ContextReply(Context)
                );

            return(Task.WhenAll(modifyTask, loggerTask));
        }
Ejemplo n.º 3
0
        public Task ViewChannelListAsync()
        {
            var config = ServerConfigService.GetConfig(Context.Guild);

            if (config.PublicCommandChannels.Count < 1)
            {
                ReplyAsync(
                    "There are currently no listed channels",
                    messageReference: DiscordUtilities.ContextReply(Context)
                    );
            }
            else if (config.PublicCommandChannels.Count == 1)
            {
                var channel = Context.Guild.GetChannel(config.PublicCommandChannels[0]);
                ReplyAsync(
                    $"The only channel I am listening to is: {DiscordUtilities.ClickableChannel(channel)}",
                    messageReference: DiscordUtilities.ContextReply(Context)
                    );
            }
            else
            {
                var message = "These are the channels I am listening to:\n";
                foreach (ulong id in config.PublicCommandChannels)
                {
                    var channel = Context.Guild.GetChannel(id);
                    message += $"- {DiscordUtilities.ClickableChannel(channel)}\n";
                }
                ReplyAsync(
                    message,
                    messageReference: DiscordUtilities.ContextReply(Context)
                    );
            }
            return(Task.CompletedTask);
        }
Ejemplo n.º 4
0
        public async Task RemoveOfficerNote(IUser discordUser, string categoryName, [Summary("dd/mm/yyyy")] string dateTime, [Remainder] string comment = null)
        {
            if (DiscordUtilities.UserIsInCallingOfficersGuild(Context.User as SocketGuildUser, discordUser as SocketGuildUser))
            {
                // TODO: This could be parsed simply by DateTime.Parse
                var datetimeParts = dateTime.Split('/');
                var dayString     = datetimeParts[0];
                var monthString   = datetimeParts[1];
                var yearString    = datetimeParts[2];

                if (!int.TryParse(dayString, out var day))
                {
                    throw new Exception("Could not parse the day from the datetime string, are you using dd/mm/yyyy format?");
                }
                if (!int.TryParse(monthString, out var month))
                {
                    throw new Exception("Could not parse the month from the datetime string, are you using dd/mm/yyyy format?");
                }
                if (!int.TryParse(yearString, out var year))
                {
                    throw new Exception("Could not parse the year from the datetime string, are you using dd/mm/yyyy format?");
                }

                await DbService.RemoveOfficerNotesAsync(discordUser.Id, categoryName, new DateTime(year, month, day), comment);
                await ReplyNewEmbed($"Removed the note successfully", Color.Green);
            }
            else
            {
                await ReplyNewEmbed("You cannot access members in other guilds.", Color.Red);
            }
        }
Ejemplo n.º 5
0
        // Private members

        private static async Task <string> ReplyUploadFileToScratchChannelAsync(this OfcModuleBase moduleBase, string filePath)
        {
            ulong serverId  = moduleBase.Config.ScratchServer;
            ulong channelId = moduleBase.Config.ScratchChannel;

            if (serverId <= 0 || channelId <= 0)
            {
                await moduleBase.ReplyErrorAsync("Cannot upload images because no scratch server/channel has been specified in the configuration file.");

                return(string.Empty);
            }

            IGuild guild = moduleBase.DiscordClient.GetGuild(serverId);

            if (guild is null)
            {
                await moduleBase.ReplyErrorAsync("Cannot upload images because the scratch server is inaccessible.");

                return(string.Empty);
            }

            ITextChannel channel = await guild.GetTextChannelAsync(channelId);

            if (channel is null)
            {
                await moduleBase.ReplyErrorAsync("Cannot upload images because the scratch channel is inaccessible.");

                return(string.Empty);
            }

            return(await DiscordUtilities.UploadFileAsync(channel, filePath, FileUploadOptions.DeleteFileAfterUpload));
        }
Ejemplo n.º 6
0
        protected async Task UploadDatabaseBackupAsync(IMessageChannel channel, string databaseFilePath)
        {
            bool backupInProgress = GetDatabaseStatus(databaseFilePath).BackupInProgress;

            if (backupInProgress)
            {
                await DiscordUtilities.ReplyErrorAsync(channel, "A backup is already in progress. Please wait until it has completed.");
            }
            else
            {
                GetDatabaseStatus(databaseFilePath).BackupInProgress = true;

                if (System.IO.File.Exists(databaseFilePath))
                {
                    try {
                        await DiscordUtilities.ReplyInfoAsync(channel,
                                                              string.Format("Uploading database backup ({0:0.##} MB).\nThe backup will be posted in this channel when it is complete.",
                                                                            new System.IO.FileInfo(databaseFilePath).Length / 1024000.0));

                        await channel.SendFileAsync(databaseFilePath, string.Format("`Database backup ({0})`", DateUtilities.GetCurrentDateUtc()));
                    }
                    catch (Exception) {
                        await DiscordUtilities.ReplyErrorAsync(channel, "Database file cannot be accessed.");
                    }
                }
                else
                {
                    await DiscordUtilities.ReplyErrorAsync(channel, "Database file does not exist at the specified path.");
                }

                GetDatabaseStatus(databaseFilePath).BackupInProgress = false;
            }
        }
Ejemplo n.º 7
0
        public async Task BozjaHelpAsync()
        {
            var guildConfig = Db.Guilds.FirstOrDefault(g => g.Id == Context.Guild.Id);
            var prefix      = Db.Config.Prefix.ToString();

            if (guildConfig != null && guildConfig.Prefix != ' ')
            {
                prefix = guildConfig.Prefix.ToString();
            }

            var commands = DiscordUtilities.GetFormattedCommandList(
                typeof(BozjaExtraModule),
                prefix,
                except: new List <string> {
                "bozhelp"
            });

            var embed = new EmbedBuilder()
                        .WithTitle("Useful Commands (Bozja)")
                        .WithColor(Color.LightOrange)
                        .WithDescription(commands)
                        .Build();

            await ReplyAsync(embed : embed);
        }
Ejemplo n.º 8
0
        public Task AddChannelAsync(
            [Summary("What command, module, behaviour, or setting to change")]
            IChannel channel
            )
        {
            if (channel is null)
            {
                return(ReplyAsync(
                           "Please give me a valid channel, for I got none.",
                           messageReference: DiscordUtilities.ContextReply(Context)
                           ));
            }

            var cid = channel.Id;

            var modifyTask = ServerConfigService.ModifyConfig(Context.Guild.Id, (config) =>
            {
                config.PublicCommandChannels.Add(cid);
            }
                                                              );

            var replyTask = ReplyAsync(
                $"Got it! Added channel {DiscordUtilities.ClickableChannel(channel)} to the list.",
                messageReference: DiscordUtilities.ContextReply(Context));

            return(Task.WhenAll(modifyTask, replyTask));
        }
Ejemplo n.º 9
0
        public async Task <string> UploadFileAsync(string filePath, IMessageChannel channel = null, FileUploadOptions options = FileUploadOptions.None)
        {
            if (channel is null)
            {
                ulong serverId  = config.ScratchServer;
                ulong channelId = config.ScratchChannel;

                if (serverId <= 0 || channelId <= 0)
                {
                    throw new Exception("Cannot upload images because no scratch server/channel has been specified in the configuration file.");
                }

                IGuild guild = client.GetGuild(serverId);

                if (guild is null)
                {
                    throw new Exception("Cannot upload images because the scratch server is inaccessible.");
                }

                channel = await guild.GetTextChannelAsync(channelId);

                if (channel is null)
                {
                    throw new Exception("Cannot upload images because the scratch channel is inaccessible.");
                }
            }

            return(await DiscordUtilities.UploadFileAsync(channel, filePath, options));
        }
Ejemplo n.º 10
0
        public async Task Save()
        {
            string configFilename = "config.json";

            Config.Save(configFilename);

            await DiscordUtilities.ReplySuccessAsync(Context.Channel, string.Format("Successfully saved config to **{0}**.", configFilename));
        }
Ejemplo n.º 11
0
        public async Task SendOrder(string playerInGameName)
        {
            var finalOrders    = AnzacSpiritService.GetWarOrdersSortedByDiscordUser();
            var playerDiscords = DbService.GetInGamePlayerDiscordLinks();
            // TODO: Refactor this searching for id
            var playerId = playerDiscords.First(x => x.InGameName.Trim().ToLower() == playerInGameName.Trim().ToLower()).DiscordId;

            var user  = Context.Guild.Users.First(x => x.Id == playerId);
            var embed = AnzacSpiritService.GetPlayerOrdersEmbed(finalOrders.First(x => x.Key == playerId));
            await DiscordUtilities.DirectMessageUserAsync(embed, user);
        }
Ejemplo n.º 12
0
 public async Task AddOfficerNote(IUser discordUser, string categoryName, [Remainder] string notes)
 {
     if (DiscordUtilities.UserIsInCallingOfficersGuild(Context.User as SocketGuildUser, discordUser as SocketGuildUser))
     {
         await DbService.AddOfficerNote(categoryName, discordUser.Id, notes);
         await ReplyNewEmbed("Added the note successfully", Color.Green);
     }
     else
     {
         await ReplyNewEmbed("You cannot access members in other guilds.", Color.Red);
     }
 }
Ejemplo n.º 13
0
        private async Task <string> GetDescriptionFromMessageAsync(IMessage message)
        {
            // The user can either provide a message or text attachment.

            string descriptionText = message.Text;

            if (message.Attachments.Any())
            {
                descriptionText = await DiscordUtilities.DownloadTextAttachmentAsync(message.Attachments.First());
            }

            return(descriptionText);
        }
Ejemplo n.º 14
0
        public async override Task <ICreator> GetCreatorAsync(ICreator creator)
        {
            IUser discordUser = await DiscordUtilities.GetDiscordUserFromStringAsync(commandContext, creator.Name);

            if (discordUser is null)
            {
                return(creator);
            }
            else
            {
                return(new Creator(discordUser.Id, discordUser.Username));
            }
        }
Ejemplo n.º 15
0
        public virtual async Task RestartAsync(IMessageChannel channel = null)
        {
            restartChannel = channel;

            if (restartChannel != null)
            {
                restartMessage = await DiscordUtilities.ReplySuccessAsync(restartChannel, $"Restarting {Name.ToBold()}...");
            }

            await StopAsync();

            await StartAsync();
        }
Ejemplo n.º 16
0
        public async Task MovePlayers()
        {
            var players       = Context.Guild.Users;
            var voiceChannels = Context.Guild.VoiceChannels;

            foreach (var player in players)
            {
                if (player.Activity != null)
                {
                    if (player.Activity.Type == ActivityType.Playing)
                    {
                        string game = player.Activity.Name;
                        switch (game)
                        {
                        case "Dota 2":
                            await DiscordUtilities.MoveToChannel(player, voiceChannels, "Dota 2");

                            break;

                        case "Minecraft":
                            await DiscordUtilities.MoveToChannel(player, voiceChannels, "Minecraft");

                            break;

                        case "LabyMod":
                            await DiscordUtilities.MoveToChannel(player, voiceChannels, "Minecraft");

                            break;

                        case "Rocket League":
                            await DiscordUtilities.MoveToChannel(player, voiceChannels, "Rocket League");

                            break;

                        case "Overwatch":
                            await DiscordUtilities.MoveToChannel(player, voiceChannels, "Overwatch");

                            break;

                        default:
                            await DiscordUtilities.MoveToChannel(player, voiceChannels, "General");

                            break;
                        }
                    }
                }
            }
        }
Ejemplo n.º 17
0
        public static async Task <bool> ReplyValidateZoneAsync(ICommandContext context, Common.Zones.IZone zone, string zoneName = "")
        {
            if (!zone.IsValid())
            {
                string message = "No such zone exists.";

                if (!string.IsNullOrEmpty(zoneName))
                {
                    message = $"Zone {zoneName.ToTitle().ToBold()} does not exist.";
                }

                await DiscordUtilities.ReplyErrorAsync(context.Channel, message);

                return(false);
            }

            return(true);
        }
        // Protected members

        protected override async Task OnMessageReceivedAsync(SocketMessage rawMessage)
        {
            ulong userId = rawMessage.Author.Id;

            // If the user has been banned, show an error message.
            // Bot admins cannot be banned.

            bool userIsBanned   = botConfiguration.BannedUserIds?.Any(id => id.Equals(userId)) ?? false;
            bool userIsBotAdmin = botConfiguration.BotAdminUserIds?.Any(id => id.Equals(userId)) ?? false;

            if (userIsBanned && !userIsBotAdmin)
            {
                await DiscordUtilities.ReplyErrorAsync(rawMessage.Channel, "You do not have permission to use this command.");
            }
            else
            {
                await base.OnMessageReceivedAsync(rawMessage);
            }
        }
Ejemplo n.º 19
0
        private async Task ShowGenericCommandErrorAsync(Optional <CommandInfo> command, ICommandContext context, IResult result)
        {
            if (result is null)
            {
                // Show a generic message if we don't have a result indicating what happened.

                if (command.IsSpecified)
                {
                    await DiscordUtilities.ReplyErrorAsync(context.Channel, $"Something went wrong while executing the **{command.Value.Name}** command.");
                }
                else
                {
                    await DiscordUtilities.ReplyErrorAsync(context.Channel, $"Something went wrong while executing the command.");
                }
            }
            else if (result is ExecuteResult executeResult && executeResult.Exception?.InnerException != null && !string.IsNullOrWhiteSpace(executeResult.Exception.InnerException.Message))
            {
                await DiscordUtilities.ReplyErrorAsync(context.Channel, executeResult.Exception.InnerException.Message);
            }
Ejemplo n.º 20
0
        public async Task Set(string key, string value)
        {
            if (Config.SetProperty(key, value))
            {
                await DiscordUtilities.ReplySuccessAsync(Context.Channel, string.Format("Successfully set **{0}** to **{1}**.", key, value));
            }
            else
            {
                await DiscordUtilities.ReplyErrorAsync(Context.Channel, string.Format("No setting with the name **{0}** exists.", key));
            }

            // Reload commands (the commands available are dependent on configuration settings).

            await CommandService.InstallCommandsAsync();

            // Update the bot's "Playing" status.

            await DiscordClient.SetGameAsync(Config.Playing);
        }
Ejemplo n.º 21
0
        public async Task SendOrders()
        {
            var finalOrders = AnzacSpiritService.GetWarOrdersSortedByDiscordUser();

            // DM to each user
            foreach (var finalOrder in finalOrders)
            {
                var user = Context.Guild.Users.FirstOrDefault(x => x.Id == finalOrder.Key);
                if (user == null)
                {
                    await ReplyNewEmbed($"No user found for {finalOrder.Value[0].Item2.Player}", Color.Red);

                    return;
                }
                var embed = AnzacSpiritService.GetPlayerOrdersEmbed(finalOrder);
                await DiscordUtilities.DirectMessageUserAsync(embed, user);
            }

            await ReplyNewEmbed("Success", Color.Purple);
        }
Ejemplo n.º 22
0
        public async Task BAHelpAsync()
        {
            var guildConfig = Db.Guilds.FirstOrDefault(g => g.Id == Context.Guild.Id);
            var prefix      = Db.Config.Prefix.ToString();

            if (guildConfig != null && guildConfig.Prefix != ' ')
            {
                prefix = guildConfig.Prefix.ToString();
            }

            var baseCommands = await DiscordUtilities.GetFormattedCommandList(Services, Context, prefix, "BA Extra Module", except : new List <string> {
                "bahelp"
            });

            var hostCommands = await DiscordUtilities.GetFormattedCommandList(Services, Context, prefix, "Run");

            var embed = new EmbedBuilder()
                        .WithTitle("Useful Commands (Baldesion Arsenal)")
                        .WithColor(Color.LightOrange)
                        .WithDescription(baseCommands + "==============================\n" + hostCommands)
                        .Build();

            await ReplyAsync(embed : embed);
        }
Ejemplo n.º 23
0
        public async Task QgAsync()
        {
            await DiscordUtilities.PostImage(Http, Context, "https://i.imgur.com/vbpph3t.png");

            await Task.Delay(200);

            await DiscordUtilities.PostImage(Http, Context, "https://i.imgur.com/pkdrt09.png");

            await Task.Delay(200);

            await DiscordUtilities.PostImage(Http, Context, "https://cdn.discordapp.com/attachments/613149980114550794/891468340541919252/testbomb_20fps.gif");

            await Task.Delay(200);

            await DiscordUtilities.PostImage(Http, Context, "https://i.imgur.com/U2rTaAg.png");

            await Task.Delay(200);

            await DiscordUtilities.PostImage(Http, Context, "https://i.imgur.com/kqaMaEC.png");

            await Task.Delay(200);

            await DiscordUtilities.PostImage(Http, Context, "https://i.imgur.com/c6XyZJd.png");
        }
Ejemplo n.º 24
0
 public Task OwainAsync() => DiscordUtilities.PostImage(Http, Context, "https://i.imgur.com/ADwopqC.jpg");
Ejemplo n.º 25
0
 public Task ArtAsync() => DiscordUtilities.PostImage(Http, Context, "https://i.imgur.com/sehs4Tw.jpg");
Ejemplo n.º 26
0
 public Task PortalsAsync() => DiscordUtilities.PostImage(Http, Context, "https://i.imgur.com/XcXACQp.png");
Ejemplo n.º 27
0
 public Task AccelBombAsync() => DiscordUtilities.PostImage(Http, Context, "https://cdn.discordapp.com/attachments/550709673104375818/721527266441560064/unknown.png");
Ejemplo n.º 28
0
 public Task OzmaAsync() => DiscordUtilities.PostImage(Http, Context, "https://cdn.discordapp.com/attachments/588592729609469952/721522648949063730/unknown.png");
Ejemplo n.º 29
0
 public Task AbsoluteVirtueAsync() => DiscordUtilities.PostImage(Http, Context, "https://cdn.discordapp.com/attachments/588592729609469952/721522585866731580/unknown.png");
Ejemplo n.º 30
0
 public Task RaidenAsync() => DiscordUtilities.PostImage(Http, Context, "https://cdn.discordapp.com/attachments/588592729609469952/721522493197779035/unknown.png");