Exemple #1
0
        public async Task RunBotAsync()
        {
            var service = new BotServices();
            var cfg     = new DiscordConfiguration
            {
                Token                   = service.GetAPIToken("discord"),
                TokenType               = TokenType.Bot,
                AutoReconnect           = true,
                LogLevel                = LogLevel.Info,
                UseInternalLogHandler   = false, //true
                GatewayCompressionLevel = GatewayCompressionLevel.Stream,
                LargeThreshold          = 250
            };
            // initialize cnext dependencies
            //var deps = new ServiceCollection().AddSingleton(Client);
            var cmd = new CommandsNextConfiguration
            {
                PrefixResolver      = PrefixResolverAsync, // Set the command prefix that will be used by the bot
                EnableDms           = false,               // Set the boolean for responding to direct messages
                EnableDefaultHelp   = false,
                EnableMentionPrefix = true,                // Set the boolean for mentioning the bot as a command prefix
                CaseSensitive       = false,
                DefaultHelpChecks   = new List <CheckBaseAttribute>()
                                      //Services = deps.BuildServiceProvider()
            };

            Client                = new DiscordClient(cfg);
            Client.Ready         += Client_Ready;
            Client.ClientErrored += Client_ClientError;
            //Client.MessageCreated += Client_OnMessageCreated;
            //Client.SocketErrored += Client_OnSocketErrored;
            Client.DebugLogger.LogMessageReceived += Client_LogMessageHandler;
            //Interactivity = this.Client.UseInteractivity(new InteractivityConfiguration());
            Client.UseInteractivity(new InteractivityConfiguration
            {
                PaginationBehavior = TimeoutBehaviour.Ignore, // Default pagination behaviour to just ignore the reactions
                PaginationTimeout  = TimeSpan.FromMinutes(5), // Default pagination timeout to 5 minutes
                Timeout            = TimeSpan.FromMinutes(2)  // Default timeout for other actions to 2 minutes
            });
            Commands = Client.UseCommandsNext(cmd);
            Commands.CommandExecuted += Commands_CommandExecuted;
            Commands.CommandErrored  += Commands_CommandErrored;
            Commands.SetHelpFormatter <HelperService>(); // Set up the custom help formatter
            Commands.RegisterCommands <BotModule>();
            Commands.RegisterCommands <CommonModule>();
            Commands.RegisterCommands <GoogleModule>();
            Commands.RegisterCommands <ModeratorModule>();
            Commands.RegisterCommands <ServerModule>();
            Commands.RegisterCommands <SteamModule>();
            //Commands.RegisterCommands(Assembly.GetExecutingAssembly());

            // Start the uptime counter
            GlobalVariables.ProcessStarted = DateTime.Now;
            FeedCheckTimer = new Timer(FeedCheckTimerCallback, null, TimeSpan.FromSeconds(30), TimeSpan.FromMinutes(1));
            await UpdateSteamAsync();    // Update the Steam App list

            await Client.ConnectAsync(); // Connect and log into Discord

            await Task.Delay(-1);        // Prevent the console window from closing
        }
        public async Task Imgur(CommandContext ctx, [RemainingText] string query)
        {
            await ctx.TriggerTypingAsync();

            var rnd      = new Random();
            var service  = new BotServices();
            var imgur    = new ImgurClient(service.GetAPIToken("imgur"));
            var endpoint = new GalleryEndpoint(imgur);
            var gallery  = string.IsNullOrWhiteSpace(query) ? (await endpoint.GetRandomGalleryAsync()).ToList() : (await endpoint.SearchGalleryAsync(query)).ToList();
            var img      = gallery.Any() ? gallery[rnd.Next(0, gallery.Count)] : null;
            var output   = new DiscordEmbedBuilder();

            switch (img)
            {
            case null:
                output.WithTitle(":mag: No results found!");
                output.WithColor(DiscordColor.Yellow);
                break;

            case GalleryAlbum _:
                output.WithImageUrl(((GalleryAlbum)img).Link);
                output.WithColor(DiscordColor.SapGreen);
                break;

            case GalleryImage _:
                output.WithImageUrl(((GalleryImage)img).Link);
                output.WithColor(DiscordColor.SapGreen);
                break;
            }
            await ctx.RespondAsync(embed : output.Build());
        }
Exemple #3
0
        private static Task UpdateSteamAsync()
        {
            Console.WriteLine("Updating Steam App List...");
            var service = new BotServices();
            var token   = service.GetAPIToken("steam");
            var apps    = new SteamApps(token);
            var games   = apps.GetAppListAsync().Result.Data;

            GlobalVariables.SteamAppList.Clear();
            foreach (var game in games)
            {
                if (!string.IsNullOrWhiteSpace(game.Name))
                {
                    GlobalVariables.SteamAppList.Add(Convert.ToUInt32(game.AppId), game.Name);
                }
            }

            Console.WriteLine("Updating TF2 Item Schema...");
            var schema = new EconItems(token, EconItemsAppId.TeamFortress2);
            var items  = schema.GetSchemaForTF2Async();

            GlobalVariables.TFItemSchema.Clear();
            foreach (var item in items.Result.Data.Items)
            {
                if (!string.IsNullOrWhiteSpace(item.ItemName))
                {
                    GlobalVariables.TFItemSchema.Add(Convert.ToUInt32(item.DefIndex), item.ItemName);
                }
            }

            return(Task.CompletedTask);
        }
        public async Task OMDB(CommandContext ctx, [RemainingText] string query)
        {
            if (string.IsNullOrWhiteSpace(query))
            {
                await BotServices.SendErrorEmbedAsync(ctx, ":warning: A search query is required!");
            }
            else
            {
                var service = new BotServices();
                var client  = new OMDbClient(service.GetAPIToken("omdb"), true);
                var movie   = await client.GetItemByTitle(query.Replace(" ", "+"));

                if (movie.Response == "False")
                {
                    await BotServices.SendErrorEmbedAsync(ctx, ":mag: No results found!");
                }
                else
                {
                    await ctx.TriggerTypingAsync();

                    var output = new DiscordEmbedBuilder()
                                 .WithTitle(movie.Title)
                                 .WithDescription(movie.Plot.Length < 500 ? movie.Plot : movie.Plot.Take(500) + "...")
                                 .AddField("Released", movie.Released, true)
                                 .AddField("Runtime", movie.Runtime, true)
                                 .AddField("Genre", movie.Genre, true)
                                 .AddField("Country", movie.Country, true)
                                 .AddField("Box Office", movie.BoxOffice, true)
                                 .AddField("Production", movie.Production, true)
                                 .AddField("IMDB Rating", movie.imdbRating, true)
                                 .AddField("Metacritic", movie.Metascore, true)
                                 .AddField("Rotten Tomatoes", movie.tomatoRating, true)
                                 .AddField("Director", movie.Director, true)
                                 .AddField("Actors", movie.Actors, true)
                                 .WithColor(DiscordColor.Goldenrod);
                    if (movie.Poster != "N/A")
                    {
                        output.WithImageUrl(movie.Poster);
                    }
                    if (movie.tomatoURL != "N/A")
                    {
                        output.WithUrl(movie.tomatoURL);
                    }
                    await ctx.RespondAsync(embed : output.Build());
                }
            }
        }
        public async Task GetTime(CommandContext ctx, [RemainingText] string location)
        {
            if (string.IsNullOrWhiteSpace(location))
            {
                await BotServices.SendErrorEmbedAsync(ctx, ":warning: A valid location is required! Try **.time Ottawa, CA**");
            }
            else
            {
                try
                {
                    await ctx.TriggerTypingAsync();

                    var http = new HttpClient();
                    http.DefaultRequestHeaders.Clear();
                    var service          = new BotServices();
                    var token            = service.GetAPIToken("google");
                    var locationResource = await http.GetStringAsync($"https://maps.googleapis.com/maps/api/geocode/json?address={location.Replace(" ", "")}&key={token}");

                    var locationObject = JsonConvert.DeserializeObject <TimeService>(locationResource);
                    if (locationObject.status != "OK")
                    {
                        await BotServices.SendErrorEmbedAsync(ctx, ":mag: Location not found!");
                    }
                    else
                    {
                        var currentSeconds = (int)DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1)).TotalSeconds;
                        var url            = $"https://maps.googleapis.com/maps/api/timezone/json?location={locationObject.results[0].geometry.location.lat},{locationObject.results[0].geometry.location.lng}&timestamp={currentSeconds}&key={token}";
                        var timeResource   = await http.GetStringAsync(url);

                        var timeObject = JsonConvert.DeserializeObject <TimeService.TimeZoneResult>(timeResource);
                        var time       = DateTime.UtcNow.AddSeconds(timeObject.dstOffset + timeObject.rawOffset);
                        var output     = new DiscordEmbedBuilder()
                                         .WithTitle($"Time in {locationObject.results[0].formatted_address}")
                                         .WithDescription($":clock1: **{time.ToShortTimeString()}** {timeObject.timeZoneName}")
                                         .WithColor(DiscordColor.Cyan);
                        await ctx.RespondAsync(embed : output.Build());
                    }
                }
                catch
                {
                    await BotServices.SendErrorEmbedAsync(ctx, ":mag: Unable to find time data for this location!");
                }
            }
        }
Exemple #6
0
        public async Task SQLQuery(CommandContext ctx, [RemainingText] string query)
        {
            try
            {
                var service = new BotServices();
                using (var conn = new SqlConnection(service.GetAPIToken("database")))
                    using (var cmd = conn.CreateCommand())
                    {
                        await conn.OpenAsync().ConfigureAwait(false);

                        cmd.CommandText = query;
                        await cmd.ExecuteNonQueryAsync().ConfigureAwait(false);

                        await ctx.RespondAsync("SQL Query Executed...");

                        Console.WriteLine($"Executed SQL Query: {query}");
                    }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error updating RSS feeds! Exception: {ex.Message}");
            }
        }
Exemple #7
0
        public async Task TF2Item(CommandContext ctx)
        {
            await ctx.TriggerTypingAsync();

            var rnd      = new Random();
            var textInfo = new CultureInfo("en-US", false).TextInfo;
            var service  = new BotServices();
            var schema   = new EconItems(service.GetAPIToken("steam"), EconItemsAppId.TeamFortress2);
            var items    = await schema.GetSchemaForTF2Async();

            var index    = rnd.Next(0, items.Data.Items.Count);
            var wikiName = items.Data.Items[index].ItemName.Replace(' ', '_');
            var output   = new DiscordEmbedBuilder()
                           .WithTitle(items.Data.Items[index].ItemName)
                           .WithThumbnailUrl(items.Data.Items[index].ImageUrl)
                           .WithUrl($"https://wiki.teamfortress.com/wiki/{wikiName}")
                           .WithColor(DiscordColor.Orange);

            if (items.Data.Items[index].ItemDescription != null)
            {
                output.WithDescription(items.Data.Items[index].ItemDescription);
            }
            if (items.Data.Items[index].ItemSlot != null)
            {
                output.AddField("Item Slot:", textInfo.ToTitleCase(items.Data.Items[index].ItemSlot), true);
            }
            var classes = items.Data.Items[index].UsedByClasses.Aggregate <string, string>(null, (current, userClass) => current + $" {userClass} ");

            if (classes != null)
            {
                output.AddField("Used by:", textInfo.ToTitleCase(classes), true);
            }
            if (items.Data.Items[index].ModelPlayer != null)
            {
                await ctx.RespondAsync(embed : output.Build());
            }
        }
        public async Task Twitch(CommandContext ctx, [RemainingText] string stream)
        {
            if (string.IsNullOrWhiteSpace(stream))
            {
                await BotServices.SendErrorEmbedAsync(ctx, ":warning: An existing Twitch channel name is required!");
            }
            else
            {
                try
                {
                    await ctx.TriggerTypingAsync();

                    var http      = new HttpClient();
                    var service   = new BotServices();
                    var twitchUrl = $"https://api.twitch.tv/kraken/streams/{stream.ToLower()}?client_id={service.GetAPIToken("twitch")}";
                    var response  = await http.GetStringAsync(twitchUrl).ConfigureAwait(false);

                    var twitch = JsonConvert.DeserializeObject <TwitchService>(response);
                    twitch.Url = twitchUrl;
                    if (!twitch.IsLive)
                    {
                        await BotServices.SendErrorEmbedAsync(ctx, "Channel is **Offline** (or doesn't exist) :pensive:");
                    }
                    else
                    {
                        var output = new DiscordEmbedBuilder()
                                     .WithTitle($"{twitch.Stream.Channel.display_name} is live streaming on Twitch!")
                                     .AddField("Now Playing", twitch.Game)
                                     .AddField("Stream Title", twitch.Title)
                                     .AddField("Followers", twitch.Followers.ToString(), true)
                                     .AddField("Viewers", twitch.Viewers.ToString(), true)
                                     .WithThumbnailUrl(twitch.Icon)
                                     .WithUrl(twitch.Url)
                                     .WithColor(DiscordColor.Purple);
                        await ctx.RespondAsync(embed : output.Build());
                    }
                }
                catch
                {
                    await BotServices.SendErrorEmbedAsync(ctx, ":warning: Unable to determine channel status, please do not include special characters in your input!");
                }
            }
        }
Exemple #9
0
        private static Task <int> PrefixResolverAsync(DiscordMessage m)
        {
            var service = new BotServices();

            return(Task.FromResult(m.GetStringPrefixLength(service.GetAPIToken("prefix"))));
        }
Exemple #10
0
        public async Task SteamUser(CommandContext ctx, string query)
        {
            if (string.IsNullOrWhiteSpace(query))
            {
                await BotServices.SendErrorEmbedAsync(ctx, ":warning: SteamID or Community URL are required! Try **.su criticalflaw**");
            }
            else
            {
                var service = new BotServices();
                var steam   = new SteamUser(service.GetAPIToken("steam"));
                SteamCommunityProfileModel             profile = null;
                ISteamWebResponse <PlayerSummaryModel> summary = null;
                try
                {
                    var decode = await steam.ResolveVanityUrlAsync(query);

                    profile = await steam.GetCommunityProfileAsync(decode.Data).ConfigureAwait(false);

                    summary = await steam.GetPlayerSummaryAsync(decode.Data).ConfigureAwait(false);
                }
                catch
                {
                    profile = await steam.GetCommunityProfileAsync(ulong.Parse(query)).ConfigureAwait(false);

                    summary = await steam.GetPlayerSummaryAsync(ulong.Parse(query)).ConfigureAwait(false);
                }
                finally
                {
                    if (profile != null && summary != null)
                    {
                        await ctx.TriggerTypingAsync();

                        var output = new DiscordEmbedBuilder()
                                     .WithTitle(summary.Data.Nickname);
                        if (summary.Data.ProfileVisibility == ProfileVisibility.Public)
                        {
                            output.WithThumbnailUrl(profile.AvatarFull.ToString());
                            output.WithColor(DiscordColor.MidnightBlue);
                            output.WithUrl($"http://steamcommunity.com/id/{profile.SteamID}/");
                            output.WithFooter($"Steam ID: {profile.SteamID}");
                            output.AddField("Member since",
                                            summary.Data.AccountCreatedDate.ToUniversalTime().ToString(CultureInfo.CurrentCulture), true);
                            if (!string.IsNullOrWhiteSpace(profile.Summary))
                            {
                                output.WithDescription(Regex.Replace(profile.Summary, "<[^>]*>", ""));
                            }
                            if (summary.Data.UserStatus != UserStatus.Offline)
                            {
                                output.AddField("Status:", summary.Data.UserStatus.ToString(), true);
                            }
                            else
                            {
                                output.AddField("Last seen:", summary.Data.LastLoggedOffDate.ToUniversalTime().ToString(CultureInfo.CurrentCulture), true);
                            }
                            output.AddField("VAC Banned?:", profile.IsVacBanned ? "YES" : "NO", true);
                            output.AddField("Trade Banned?:", profile.TradeBanState, true);
                            if (profile.InGameInfo != null)
                            {
                                output.AddField("In-Game:", $"[{profile.InGameInfo.GameName}]({profile.InGameInfo.GameLink})", true);
                                output.AddField("Game Server IP:", profile.InGameServerIP, true);
                                output.WithImageUrl(profile.InGameInfo.GameLogoSmall);
                            }
                        }
                        else
                        {
                            output.Description = "This profile is private...";
                        }
                        await ctx.RespondAsync(embed : output.Build());
                    }
                    else
                    {
                        await BotServices.SendErrorEmbedAsync(ctx, ":mag: No results found!");
                    }
                }
            }
        }