예제 #1
0
            public async Task Stop(InteractionContext ctx)
            {
                // Perform feasibility checks
                if (!CheckPermissions(ctx, BotInstance.AdminUserName))
                {
                    return;
                }
                if (Utils.CheckConnectionStatus(ctx) == false)
                {
                    await ctx.CreateResponseAsync(InteractionResponseType.ChannelMessageWithSource, new DiscordInteractionResponseBuilder().AddEmbed
                                                      (Utils.GenerateEmbed(DiscordColor.Red, "Bot is not connected to a voice channel.")));

                    return;
                }
                if (BotInstance.AudioDevice == null || BotInstance.Capture == null)
                {
                    await ctx.CreateResponseAsync(InteractionResponseType.ChannelMessageWithSource, new DiscordInteractionResponseBuilder().AddEmbed
                                                      (Utils.GenerateEmbed(DiscordColor.Red, "No audio device is selected.")));

                    return;
                }
                if (BotInstance.Capture.CaptureState != CaptureState.Capturing)
                {
                    await ctx.CreateResponseAsync(InteractionResponseType.ChannelMessageWithSource, new DiscordInteractionResponseBuilder().AddEmbed
                                                      (Utils.GenerateEmbed(DiscordColor.Red, "Bot is not streaming.")));

                    return;
                }

                // Stop capturing.
                BotInstance.Capture.StopRecording();
                await ctx.CreateResponseAsync(InteractionResponseType.ChannelMessageWithSource, new DiscordInteractionResponseBuilder().AddEmbed
                                                  (Utils.GenerateEmbed(DiscordColor.Green, "Stopped streaming.")));
            }
예제 #2
0
        public async Task MessageSend(
            InteractionContext ctx,
            [Option("content", "The message to send")]
            string content
            )
        {
            if (((await ctx.Guild.GetMemberAsync(ctx.Client.CurrentUser.Id)).PermissionsIn(ctx.Channel) &
                 Permissions.SendMessages) == 0)
            {
                await ctx.CreateResponseAsync(
                    InteractionResponseType.ChannelMessageWithSource,
                    new DiscordInteractionResponseBuilder()
                    .AsEphemeral(true)
                    .WithContent("I can't send messages in that channel")
                    );

                return;
            }

            await ctx.Channel.SendMessageAsync(content);

            await ctx.CreateResponseAsync(
                InteractionResponseType.ChannelMessageWithSource,
                new DiscordInteractionResponseBuilder()
                .AsEphemeral(true)
                .WithContent("Sent!"));
        }
예제 #3
0
        public async Task LTPAsyncslash(InteractionContext ctx)
        {
            DiscordRole   ltp       = ctx.Guild.GetRole(SBGRoles.LookingToPlay);
            DiscordMember guildUser = await ctx.Guild.GetMemberAsync(ctx.User.Id);

            if (guildUser.Roles.Any(roles => roles.Id == SBGRoles.LookingToPlay))
            {
                await guildUser.RevokeRoleAsync(ltp);

                this.db.LTPJoins.Remove(new LTPJoin()
                {
                    UserId = ctx.User.Id,
                });

                await this.db.SaveChangesAsync();

                await ctx.CreateResponseAsync(InteractionResponseType.ChannelMessageWithSource, new DiscordInteractionResponseBuilder().WithContent("You have been removed from the Looking to Play role.").AsEphemeral(true));
            }
            else
            {
                await guildUser.GrantRoleAsync(ltp);

                this.db.LTPJoins.Add(new LTPJoin()
                {
                    UserId    = ctx.User.Id,
                    Timestamp = DateTime.UtcNow,
                });

                await this.db.SaveChangesAsync();

                await ctx.CreateResponseAsync(InteractionResponseType.ChannelMessageWithSource, new DiscordInteractionResponseBuilder().WithContent("You have been added to the Looking to Play role!").AsEphemeral(true));
            }
        }
예제 #4
0
        public async Task MessageEmbed(
            InteractionContext ctx,
            [Option("Content", "The plain text content of the embed")]
            string content = null,
            [Option("Title", "The title of the embed")]
            string title = null,
            [Option("Description", "The description of the embed")]
            string description = null,
            [Option("Thumbnail", "The thumbnail of the embed")]
            string thumbnail = null,
            [Option("Image", "The image on the bottom of the embed")]
            string image = null)
        {
            if (((await ctx.Guild.GetMemberAsync(ctx.Client.CurrentUser.Id)).PermissionsIn(ctx.Channel) &
                 Permissions.SendMessages) == 0)
            {
                await ctx.CreateResponseAsync(
                    InteractionResponseType.ChannelMessageWithSource,
                    new DiscordInteractionResponseBuilder()
                    .AsEphemeral(true)
                    .WithContent("I can't send messages in that channel")
                    );

                return;
            }

            var embedBuilder = new DiscordEmbedBuilder();

            if (title is not null)
            {
                embedBuilder.WithTitle(title);
            }
            if (description is not null)
            {
                embedBuilder.WithDescription(description);
            }
            if (thumbnail is not null)
            {
                embedBuilder.WithThumbnail(thumbnail);
            }
            if (image is not null)
            {
                embedBuilder.WithImageUrl(image);
            }

            if (content is not null)
            {
                await ctx.Channel.SendMessageAsync(content, embedBuilder.Build());
            }
            else
            {
                await ctx.Channel.SendMessageAsync(embedBuilder.Build());
            }

            await ctx.CreateResponseAsync(
                InteractionResponseType.ChannelMessageWithSource,
                new DiscordInteractionResponseBuilder()
                .AsEphemeral(true)
                .WithContent("Sent!"));
        }
예제 #5
0
            public async Task Join(InteractionContext ctx)
            {
                var vnext      = ctx.Client.GetVoiceNext();
                var connection = ctx.Client.GetVoiceNext().GetConnection(ctx.Guild);

                // Perform feasibility checks
                if (!CheckPermissions(ctx, BotInstance.AdminUserName))
                {
                    return;
                }
                if (connection != null)
                {
                    await ctx.CreateResponseAsync(InteractionResponseType.ChannelMessageWithSource, new DiscordInteractionResponseBuilder().AddEmbed
                                                      (Utils.GenerateEmbed(DiscordColor.Red, "Bot is already connected to a voice channel.")));

                    return;
                }
                var voicestate = ctx.Member?.VoiceState;

                if (voicestate?.Channel == null)
                {
                    await ctx.CreateResponseAsync(InteractionResponseType.ChannelMessageWithSource, new DiscordInteractionResponseBuilder().AddEmbed
                                                      (Utils.GenerateEmbed(DiscordColor.Red, "You are not in a voice channel.")));

                    return;
                }

                // Connect to voice channel
                DiscordChannel channel = voicestate.Channel;

                connection = await vnext.ConnectAsync(channel);

                // Open transmit stream
                var stream = connection.GetTransmitSink();

                if (BotInstance.Capture != null && BotInstance.AudioDevice != null)
                {
                    // Initialise new event handlers and subscribe to events for available audio from capture device and recording completion
                    // Note: This is a little messy, but creates the ability to unsubscribe from the events to prevent a memory leak
                    BotInstance.AudioHandler              = new EventHandler <WaveInEventArgs>((s, e) => AudioDataAvilableEventHander(s, e, stream, BotInstance.Capture));
                    BotInstance.Capture.DataAvailable    += BotInstance.AudioHandler;
                    BotInstance.StoppedHandler            = new EventHandler <StoppedEventArgs>((s, e) => AudioRecordingStoppedEventHandler(s, e, ctx));
                    BotInstance.Capture.RecordingStopped += BotInstance.StoppedHandler;
                }

                if (channel.Parent != null)
                {
                    await ctx.CreateResponseAsync(InteractionResponseType.ChannelMessageWithSource, new DiscordInteractionResponseBuilder().AddEmbed
                                                      (Utils.GenerateEmbed(DiscordColor.Green, $"Bot connected to **{channel.Name}** in '{channel.Parent.Name}'.")));
                }
                else
                {
                    await ctx.CreateResponseAsync(InteractionResponseType.ChannelMessageWithSource, new DiscordInteractionResponseBuilder().AddEmbed
                                                      (Utils.GenerateEmbed(DiscordColor.Green, $"Bot connected to **{channel.Name}**.")));
                }
            }
예제 #6
0
        public async Task QueryWikiAsync(InteractionContext ctx, [Option("article", "The name or title of a particular wiki article.")][RemainingText] string wikiArticle)
        {
            if (string.IsNullOrEmpty(wikiArticle))
            {
                await ctx.Channel.SendMessageAsync("Correct, we have a wiki.");

                return;
            }

            // Base embed
            DiscordEmbedBuilder wikiEmbed = new DiscordEmbedBuilder
            {
                Footer = new DiscordEmbedBuilder.EmbedFooter
                {
                    IconUrl = DiscordEmoji.FromGuildEmote(ctx.Client, PlatformEmojis.Wiki).Url,
                    Text    = "Superbossgames Wiki",
                },
                Color     = new DiscordColor(217, 187, 19),
                Timestamp = DateTime.UtcNow,
            };

            WikiArticle article = await this.wikiService.GetArticleAsync(wikiArticle);

            // Found a matching article
            if (article != null)
            {
                wikiEmbed.Footer.Text += $" | Last Edited: {article.Timestamp}";
                wikiEmbed.Title        = article.Title;
                wikiEmbed.Description  = article.Body;
                wikiEmbed.Url          = article.Url.ToString();
                await ctx.CreateResponseAsync(InteractionResponseType.ChannelMessageWithSource, new DiscordInteractionResponseBuilder().AddEmbed(wikiEmbed.Build()));

                return;
            }

            // No exact match, find page titles containing the passed title
            List <string> suggestedPages = await this.wikiService.GetSuggestedPagesAsync(wikiArticle);

            // Show what we found
            if (suggestedPages.Count > 0)
            {
                wikiEmbed.Title       = "No exact match";
                wikiEmbed.Description = $"Are you looking for any of the following pages:\n"
                                        + $"- {string.Join("\n- ", suggestedPages.Select(x => $"[{x}]({WikiUtils.GetUrlFromTitle(x)})"))}";
            }

            // No match, no suggestions, nothing
            else
            {
                wikiEmbed.Title       = "Nothing found";
                wikiEmbed.Description = @"¯\_(ツ)_/¯";
            }

            await ctx.CreateResponseAsync(InteractionResponseType.ChannelMessageWithSource, new DiscordInteractionResponseBuilder().AddEmbed(wikiEmbed.Build()).AsEphemeral(true));
        }
예제 #7
0
        public async Task PP(InteractionContext ctx)
        {
            int random = new Random().Next(0, 2);

            if (random == 1)
            {
                await ctx.CreateResponseAsync(InteractionResponseType.ChannelMessageWithSource, new DiscordInteractionResponseBuilder().WithContent("https://sweatyvirgins.com/assets/Audio/penis-bugged.mp3"));
            }
            else
            {
                await ctx.CreateResponseAsync(InteractionResponseType.ChannelMessageWithSource, new DiscordInteractionResponseBuilder().WithContent("https://sweatyvirgins.com/assets/Audio/penis.mp3"));
            }
        }
예제 #8
0
                public async Task ServerIconSet(
                    InteractionContext ctx,
                    [Option("url", "Url of the icon")] string url
                    )
                {
                    if ((ctx.Member.PermissionsIn(ctx.Channel) & Permissions.ManageGuild) == 0)
                    {
                        await ctx.CreateResponseAsync(
                            InteractionResponseType.ChannelMessageWithSource,
                            new DiscordInteractionResponseBuilder()
                            .WithContent("You must have manage server permissions to run this command")
                            .AsEphemeral(true)
                            );

                        return;
                    }

                    await ctx.CreateResponseAsync(InteractionResponseType.DeferredChannelMessageWithSource);

                    var request = WebRequest.Create(url);

                    using (var response = await request.GetResponseAsync())
                    {
                        using (var ms = new MemoryStream())
                        {
                            var respStream = response.GetResponseStream();
                            if (respStream is null)
                            {
                                await ctx.CreateResponseAsync(
                                    InteractionResponseType.ChannelMessageWithSource,
                                    new DiscordInteractionResponseBuilder()
                                    .WithContent("An error occured while setting that image")
                                    .AsEphemeral(true)
                                    );

                                return;
                            }

                            await respStream.CopyToAsync(ms);

                            ms.Position = 0;
                            await ctx.Guild.ModifyAsync(model => model.Icon = ms);
                        }
                    }


                    await ctx.EditResponseAsync(new DiscordWebhookBuilder()
                                                .AddEmbed(new DiscordEmbedBuilder()
                                                          .WithImageUrl(url)
                                                          .WithTitle("Icon set")));
                }
예제 #9
0
파일: Slash.cs 프로젝트: Speyd3r/MikuSharp
        public static async Task SmolCarAsync(InteractionContext ctx)
        {
            if (ctx.Member.Roles.Any(x => x.Id == 607989212696018945))
            {
                await ctx.Member.RevokeRoleAsync(ctx.Guild.GetRole(607989212696018945));

                await ctx.CreateResponseAsync(InteractionResponseType.ChannelMessageWithSource, new DiscordInteractionResponseBuilder().WithContent(":("));

                return;
            }
            await ctx.Member.GrantRoleAsync(ctx.Guild.GetRole(607989212696018945));

            await ctx.CreateResponseAsync(InteractionResponseType.ChannelMessageWithSource, new DiscordInteractionResponseBuilder().WithContent("Welcome to smolcar"));
        }
예제 #10
0
        public async Task Docs(InteractionContext ctx,
                               [Option("name", "Function name")] string name,
                               [Option("version", "Experimental or stable game version")]
                               Versions version)
        {
            var doc = this._docs.DocsDictionary[version.GetEnumDescription()];

            if (doc is null)
            {
                throw new NullReferenceException("There was an error while trying to get docs");
            }

            var(cat, func) = FindDoc(name, doc);

            if (cat is null && func is null)
            {
                var errMsg = new DiscordInteractionResponseBuilder()
                             .WithContent($"Function `{name}` not found.");
                await ctx.CreateResponseAsync(InteractionResponseType.ChannelMessageWithSource, errMsg);

                return;
            }

            var baseUrl          = doc.BaseUrl;
            var funcName         = func !.Name;
            var argsFormatted    = FormatApiInputsAndOutputs(func.Arguments);
            var returnsFormatted = FormatApiInputsAndOutputs(func.Return);
            var info             = func.Info;
            var definition       = func.Def;
            var example          = $"```lua\n{func.Example}\n```";

            var embed = new DiscordEmbedBuilder();

            embed.WithTitle($"#{funcName}");
            embed.WithUrl($"{baseUrl}#{funcName}");
            embed.WithDescription($"`{definition}`\n\n{info}");
            embed.AddField("Arguments", argsFormatted);
            embed.AddField("Returns", returnsFormatted);
            embed.AddField("Example", example);
            embed.WithFooter($"API(game) Version: {doc.Version}");
            embed.WithColor(new DiscordColor(0xf0d080));

            var msg = new DiscordInteractionResponseBuilder()
                      .WithContent($"{baseUrl}#{funcName}")
                      .AddEmbed(embed.Build());

            await ctx.CreateResponseAsync(InteractionResponseType.ChannelMessageWithSource, msg);
        }
예제 #11
0
        public static async Task ResetLevel(InteractionContext ctx, DiscordUser user)
        {
            await ctx.CreateResponseAsync(InteractionResponseType.DeferredChannelMessageWithSource);

            var usr = await ctx.Guild.GetMemberAsync(ctx.User.Id);

            var perms = (usr.PermissionsIn(ctx.Channel) & Permissions.BanMembers) != 0;

            if (!perms)
            {
                await ctx.DeleteResponseAsync();

                return;
            }

            using var db = new LiteDatabase(@$ "{ctx.Guild.Id}.db");
            var col = db.GetCollection <UserData>("users");

            var userData = col.FindOne(x => x.Id == user.Id);

            if (userData != null)
            {
                userData.MessageCount = 0;
                userData.Level        = 0;

                await ctx.EditResponseAsync(new DiscordWebhookBuilder().WithContent("Users level reset"));

                return;
            }

            await ctx.EditResponseAsync(new DiscordWebhookBuilder().WithContent("User not found in database"));
        }
예제 #12
0
        public static async Task GetLevel(InteractionContext ctx,
                                          DiscordUser user = null !)
        {
            await ctx.CreateResponseAsync(InteractionResponseType.DeferredChannelMessageWithSource);

            using var db = new LiteDatabase(@$ "{ctx.Guild.Id}.db");
            var col = db.GetCollection <UserData>("users");

            if (user == null)
            {
                user = ctx.User;
            }
            var userData = col.FindOne(x => x.Id == user.Id);

            if (userData != null)
            {
                var embed = new DiscordEmbedBuilder();
                embed.AddField("Level", userData.Level.ToString());
                embed.AddField("Message Count", userData.MessageCount.ToString());

                await ctx.EditResponseAsync(new DiscordWebhookBuilder().AddEmbed(embed));

                return;
            }

            await ctx.DeleteResponseAsync();
        }
예제 #13
0
        public async Task tldr(InteractionContext ctx, [Option("package", "Search term to use to find tldr pages")]
                               string searchTerm)
        {
            //response may take a while so we need to do this first
            await ctx.CreateResponseAsync(InteractionResponseType.DeferredChannelMessageWithSource);

            searchTerm = searchTerm.ToLower();
            var tldrUrl = $"https://raw.githubusercontent.com/tldr-pages/tldr/master/pages/common/{searchTerm}.md";
            var resp    = "";

            try
            {
                resp = await tldrUrl.GetStringAsync();
            }
            catch (FlurlHttpException ex)
            {
                await ctx.EditResponseAsync(new DiscordWebhookBuilder().WithContent("No tldr page found"));

                return;
            }

            var lines = resp.Replace("\n\n", "\n").Split("\n");
            var embed = new DiscordEmbedBuilder()
                        .WithTitle($"TLDR page: {lines.FirstOrDefault()?.Remove(0, 2)}")
                        .WithColor(new DiscordColor(0x478061))
                        .WithDescription(string.Join("\n", lines.Skip(1)))
                        .Build();
            await ctx.EditResponseAsync(new DiscordWebhookBuilder().AddEmbed(embed));
        }
예제 #14
0
        public async Task UnBan(InteractionContext ctx,
                                [Option("user", "User to unban")] DiscordUser user, [Option("reason", "reason for ban")] string reason)
        {
            await ctx.CreateResponseAsync(InteractionResponseType.DeferredChannelMessageWithSource);

            var usr = await ctx.Guild.GetMemberAsync(ctx.User.Id);

            var perms = (usr.PermissionsIn(ctx.Channel) & Permissions.BanMembers) != 0;


            if (!perms || user.Id == ctx.User.Id)
            {
                await ctx.Client.SendMessageAsync(ctx.Guild.GetChannel(607392574235344928),
                                                  $"{ctx.User.Mention} tried to use the unban command on {user.Mention} for reason {reason} but was denied\n(►˛◄’!)");

                await ctx.DeleteResponseAsync();

                return;
            }

            try
            {
                await ctx.Guild.UnbanMemberAsync(user.Id, reason);
            }
            catch (Exception e)
            {
                await ctx.EditResponseAsync(
                    new DiscordWebhookBuilder().WithContent($"Failed to unban {user.Mention}."));

                return;
            }

            await ctx.EditResponseAsync(
                new DiscordWebhookBuilder().WithContent($"{user.Mention} has been unbanned."));
        }
예제 #15
0
        public async Task Help(InteractionContext ctx)
        {
            await ctx.CreateResponseAsync(InteractionResponseType.ChannelMessageWithSource,
                                          new DiscordInteractionResponseBuilder().WithContent(ServerContext.HelpMessage));

            Logger.Log(Logging.HelpMessageCreated);
        }
예제 #16
0
        public static async Task EditLevelRole(InteractionContext ctx, DiscordRole role, long level)
        {
            await ctx.CreateResponseAsync(InteractionResponseType.DeferredChannelMessageWithSource);

            var usr = await ctx.Guild.GetMemberAsync(ctx.User.Id);

            var perms = (usr.PermissionsIn(ctx.Channel) & Permissions.BanMembers) != 0;

            if (!perms)
            {
                await ctx.DeleteResponseAsync();

                return;
            }

            using var db = new LiteDatabase(@$ "global.db");
            var col = db.GetCollection <ServerSettings>("servers");

            var server = col.FindOne(x => x.Id == ctx.Guild.Id);

            if (server == null)
            {
                server = new ServerSettings()
                {
                    Id = ctx.Guild.Id
                };
                col.Insert(server);
            }

            if (level == -1)
            {
                if (server.RoleLevels.ContainsKey(role.Id))
                {
                    await ctx.EditResponseAsync(new DiscordWebhookBuilder().WithContent("Role level removed"));
                }
                else
                {
                    await ctx.EditResponseAsync(new DiscordWebhookBuilder().WithContent("Role level does not exist"));
                }
            }
            else if (level > 0)
            {
                server.RoleLevels ??= new Dictionary <ulong, long>();
                if (server.RoleLevels.TryAdd(role.Id, level))
                {
                    await ctx.EditResponseAsync(new DiscordWebhookBuilder().WithContent("Role level added"));
                }
                else
                {
                    await ctx.EditResponseAsync(new DiscordWebhookBuilder().WithContent("Role level already exists"));
                }
            }
            else
            {
                await ctx.DeleteResponseAsync();
            }

            col.Update(server);
        }
예제 #17
0
            public async Task HandleMissCommand(InteractionContext ctx, ServerReplayLoader replayLoader)
            {
                await ctx.CreateResponseAsync(InteractionResponseType.DeferredChannelMessageWithSource);

                var guildSettings = context.Settings.GetGuild(ctx.Channel);

                _ = Task.Run(() => context.CreateResponse(ctx.Client, new InteractionResponse(context, guildSettings, ctx), replayLoader));
            }
예제 #18
0
 /// <summary>
 /// An event handler that prints potential error messages from the audio capture process to a Discord text channel.
 /// </summary>
 /// <param name="ctx">The InteractionContext.</param>
 private static async void AudioRecordingStoppedEventHandler(object s, StoppedEventArgs e, InteractionContext ctx)
 {
     if (e.Exception != null)
     {
         await ctx.CreateResponseAsync(InteractionResponseType.ChannelMessageWithSource, new DiscordInteractionResponseBuilder().AddEmbed
                                           (Utils.GenerateEmbed(DiscordColor.Red, $"An error occured while capturing audio: '{e.Exception.Message}'")));
     }
 }
예제 #19
0
        public async Task GSISlash(InteractionContext ctx)
        {
            CurrentServerInfo csi = await this.roomService.GetCSIRooms(null, null, null, null, "false", "false", "false", "false", "false", null, 1, 100);

            DiscordEmbedBuilder serverEmbed = new DiscordEmbedBuilder
            {
                Footer = new DiscordEmbedBuilder.EmbedFooter
                {
                    IconUrl = DiscordEmoji.FromGuildEmote(ctx.Client, ServerEmojis.Unofficial).Url,
                },
                Color     = new DiscordColor(217, 187, 19),
                Timestamp = DateTime.UtcNow,
            };

            serverEmbed.Url = "https://intruderfps.com/rooms";
            int skipRoomCount = 0;

            if (csi.Rooms.Count > 0)
            {
                StringBuilder serverList = new StringBuilder();
                int           roomCount  = 0;
                foreach (Rooms room in csi.Rooms)
                {
                    roomCount++;
                    if (roomCount >= 12)
                    {
                        skipRoomCount++;
                    }
                    else
                    {
                        serverList.AppendLine($"{room.ServerIcon} | {room.RegionFlag} | {room.Name} - [{room.AgentCount}/{room.MaxAgents}]");
                    }
                }

                if (skipRoomCount >= 1)
                {
                    serverList.Append($"<:unofficial:{ServerEmojis.Unofficial}> <:os:{ServerEmojis.Official}> <:passworded:{ServerEmojis.Password}> and **{skipRoomCount}** more servers.");
                }

                serverEmbed.Title = "Current Server Information";
                serverEmbed.Url   = "https://intruderfps.com/rooms";
                serverEmbed.AddField($"Server | Region | Name - [Agents]", serverList.ToString(), true);
            }
            else
            {
                serverEmbed.AddField($"Current Server Information", $"N/A", true);
            }

            string extensions = $"{DiscordEmoji.FromGuildEmote(ctx.Client, BrowserEmojis.Chrome)} [**Chrome**](https://chrome.google.com/webstore/detail/intruder-notifications/aoebpknpfcepopfgnbnikaipjeekalim) | "
                                + $"[**Firefox**](https://addons.mozilla.org/en-US/firefox/addon/intruder-notifications/) {DiscordEmoji.FromGuildEmote(ctx.Client, BrowserEmojis.Firefox)}";

            serverEmbed.AddField("Browser Extensions", extensions);
            serverEmbed.Footer.Text = $"SuperbossGames | #current-server-info | Total Agents: {csi.PlayerCount}";

            await ctx.CreateResponseAsync(InteractionResponseType.ChannelMessageWithSource, new DiscordInteractionResponseBuilder().AddEmbed(serverEmbed.Build()).AsEphemeral(true));
        }
예제 #20
0
 public async Task ServerIconGet(InteractionContext ctx)
 {
     await ctx.CreateResponseAsync(
         InteractionResponseType.ChannelMessageWithSource,
         new DiscordInteractionResponseBuilder()
         .AddEmbed(new DiscordEmbedBuilder()
                   .WithDescription(ctx.Guild.IconUrlGifPng())
                   .WithImageUrl(ctx.Guild.IconUrlGifPng()))
         );
 }
예제 #21
0
 public async Task SettingsGet(InteractionContext ctx)
 {
     if (CheckPermissions(ctx.Member))
     {
         var    guildSettings = context.Settings.GetGuild(ctx.Guild.Id);
         string response      = string.Join("\n", guildSettings.GetSettings()
                                            .Select(s => $"{s.Key}: {s.Value}"));
         await ctx.CreateResponseAsync(InteractionResponseType.ChannelMessageWithSource,
                                       new DiscordInteractionResponseBuilder().WithContent(response));
     }
 }
예제 #22
0
        public async Task Stats(InteractionContext ctx)
        {
            var embed = new DiscordEmbedBuilder()
                        .WithTitle($"About)")
                        .WithAuthor("tldr pages", "https://tldr.sh/", "https://tldr.sh/assets/img/icon.png")
                        .WithColor(new DiscordColor("#54B59A"))
                        .AddField("Servers", ctx.Client.Guilds.Count.ToString())
                        .Build();

            await ctx.CreateResponseAsync(InteractionResponseType.ChannelMessageWithSource, new DiscordInteractionResponseBuilder().AddEmbed(embed));
        }
예제 #23
0
            public async Task Search(InteractionContext ctx, [Option("searchTerm", "locate files in all XBPS packages")]
                                     string searchTerm)
            {
                //response may take a while so we need to do this first
                await ctx.CreateResponseAsync(InteractionResponseType.DeferredChannelMessageWithSource);

                var resp = "";

                if (!Directory.Exists("tmp/xlocate"))
                {
                    await ctx.EditResponseAsync(
                        new DiscordWebhookBuilder().WithContent("No database found please update"));

                    return;
                }

                var files = Directory.GetFiles("tmp/xlocate");

                foreach (var file in files)
                {
                    // if (file.Contains(".git"))
                    // {
                    //     continue;
                    // }

                    Console.WriteLine(file);
                    var pkg = Path.GetFileName(file);

                    foreach (var line in File.ReadLines(file))
                    {
                        if (!line.Contains(searchTerm))
                        {
                            continue;
                        }

                        if (resp.Length + line.Length + pkg.Length + 1 + Environment.NewLine.Length > 1994)
                        {
                            break;
                        }

                        resp += $"{pkg}:{line}{Environment.NewLine}";
                    }
                }

                if (!string.IsNullOrEmpty(resp))
                {
                    await ctx.EditResponseAsync(new DiscordWebhookBuilder().WithContent(
                                                    $"```{resp}```"));

                    return;
                }

                await ctx.EditResponseAsync(new DiscordWebhookBuilder().WithContent("Could not find files"));
            }
            public async Task AddAsync(InteractionContext ctx,
                                       [Option("user", "User to insert into Trustlist")] DiscordUser user,
                                       [Option("severity", "Escalation level (severity) of Trustlist entry")] TrustlistEscalationLevel level,
                                       [Option("reason", "Description of Trustlist entry")] string reason,
                                       [Option("ban", "Ban the user locally?")] bool localBan = false,
                                       [Option("message-removal-span", "Remove message history (if ban) from last..."), Choice("None", 0), Choice("1 Day", 1), Choice("1 Week", 7)] long deleteDays = 0)
            {
                await ctx.CreateResponseAsync(InteractionResponseType.DeferredChannelMessageWithSource, new() { IsEphemeral = true });

                await InsertUserAsync(ctx, user, (byte)level, reason, localBan, (int)deleteDays);
            }
예제 #25
0
 public async Task Reload(
     InteractionContext ctx,
     [Option("thing", "Thing to reload")] ThingsToReload thing
     )
 {
     if (thing == ThingsToReload.Docs)
     {
         await this._docs.WriteDocs();
     }
     await ctx.CreateResponseAsync(InteractionResponseType.ChannelMessageWithSource,
                                   new DiscordInteractionResponseBuilder().WithContent("done").AsEphemeral(true));
 }
            public async Task SetLoginAsync(InteractionContext ctx,
                                            [Option("username", "Account Username")] string username,
                                            [Option("email", "Account Email"), EmailAddress] string email,
                                            [Option("password", "Account Password")] string password)
            {
                await ctx.CreateResponseAsync(InteractionResponseType.DeferredChannelMessageWithSource, new() { IsEphemeral = true });

                RegisterModel credentials = new() { Username = username, Email = email, Password = password };
                Response      result      = await _apiAuth.RegisterNewUserAsync(credentials, CancellationToken.None);

                await ctx.FollowUpAsync($"{ctx.User.Mention} {result.Status} : {result.Message}\n");
            }
예제 #27
0
        public static async Task EditBlacklist(InteractionContext ctx, string option, DiscordChannel channel)
        {
            await ctx.CreateResponseAsync(InteractionResponseType.DeferredChannelMessageWithSource);

            var usr = await ctx.Guild.GetMemberAsync(ctx.User.Id);

            var perms = (usr.PermissionsIn(ctx.Channel) & Permissions.BanMembers) != 0;

            if (!perms)
            {
                await ctx.DeleteResponseAsync();

                return;
            }

            using var db = new LiteDatabase(@$ "global.db");
            var col = db.GetCollection <ServerSettings>("servers");

            var server = col.FindOne(x => x.Id == ctx.Guild.Id);

            if (server == null)
            {
                server = new ServerSettings()
                {
                    Id = ctx.Guild.Id
                };
                col.Insert(server);
            }

            switch (option)
            {
            case "add":
                server.ExperienceBlacklistedChannels ??= new List <ulong>();
                server.ExperienceBlacklistedChannels.Add(channel.Id);
                await ctx.EditResponseAsync(new DiscordWebhookBuilder().WithContent($"{channel.Mention} added"));

                break;

            case "remove":
                if (server.ExperienceBlacklistedChannels.Contains(channel.Id))
                {
                    server.ExperienceBlacklistedChannels.Remove(channel.Id);
                    await ctx.EditResponseAsync(new DiscordWebhookBuilder().WithContent($"{channel.Mention} removed"));
                }
                else
                {
                    await ctx.EditResponseAsync(new DiscordWebhookBuilder().WithContent($"{channel.Mention} not blacklisted"));
                }
                break;
            }
            col.Update(server);
        }
예제 #28
0
        public async Task BanCommandAsync(InteractionContext ctx,
                                          [Option("Id", "The guild or user to ban.")]
                                          string id,

                                          [Option("Reason", "Reason for the ban")]
                                          string reason)
        {
            if (ulong.TryParse(id, out var res))
            {
                PartnerBot.Core.Entities.Moderation.GuildBan?ban = await this._ban.BanGuildAsync(res, reason);

                await this._ban.FinalizeBanAsync(ban.GuildId, ban.Reason);

                await ctx.CreateResponseAsync(InteractionResponseType.ChannelMessageWithSource,
                                              new DiscordInteractionResponseBuilder()
                                              .WithContent($"Guild {ban.GuildId} banned successfully."));
            }

            await ctx.CreateResponseAsync(InteractionResponseType.ChannelMessageWithSource,
                                          new DiscordInteractionResponseBuilder()
                                          .WithContent("A valid ID was not provided."));
        }
예제 #29
0
        public async Task About(InteractionContext ctx)
        {
            var embed = new DiscordEmbedBuilder()
                        .WithTitle($"About")
                        .WithAuthor("tldr pages", "https://tldr.sh/", "https://tldr.sh/assets/img/icon.png")
                        .WithColor(new DiscordColor("#54B59A"))
                        .WithDescription($"**What is tldr-pages?**\n The tldr-pages project is a collection of community-maintained help pages for command-line tools, that aims to be a simpler, more approachable complement to traditional man pages.")
                        .AddField("Bot Created By", "<@63306150757543936>")
                        .AddField("Git Repo", "https://github.com/Epictek/tldr-Discord")
                        .Build();

            await ctx.CreateResponseAsync(InteractionResponseType.ChannelMessageWithSource, new DiscordInteractionResponseBuilder().AddEmbed(embed));
        }
예제 #30
0
 /// <summary>
 /// Checks whether the user has permissions to execute the command.
 /// </summary>
 /// <param name="ctx">The InteractionContext of the command.</param>
 /// <param name="adminUsername">The username of the potentially non-privileged user that is allowed to execute commands.</param>
 /// <returns>True if the user can execute the command, false if not.</returns>
 private static bool CheckPermissions(InteractionContext ctx, string adminUsername)
 {
     if (ctx.Member.PermissionsIn(ctx.Channel).HasFlag(DSharpPlus.Permissions.ManageGuild) || ctx.Member.Username + "#" + ctx.Member.Discriminator == adminUsername)
     {
         return(true);
     }
     else
     {
         ctx.CreateResponseAsync(InteractionResponseType.ChannelMessageWithSource, new DiscordInteractionResponseBuilder().AddEmbed
                                     (Utils.GenerateEmbed(DiscordColor.Red, $"Sorry {ctx.Member.Mention}, you're not the DJ today.")));
         return(false);
     }
 }