Beispiel #1
0
        public async Task StartAsync()
        {
            _logger.LogInformation("LittleBigBot client starting up!");

            var serviceTypes = Assembly.GetEntryAssembly().GetTypes().Where(a =>
                                                                            typeof(BaseService).IsAssignableFrom(a) && a.GetCustomAttribute <ServiceAttribute>() != null &&
                                                                            !a.IsAbstract).ToList();

            foreach (var startupServiceType in serviceTypes)
            {
                if (_services.GetRequiredService(startupServiceType) is BaseService service && startupServiceType.GetCustomAttribute <ServiceAttribute>().AutoInit)
                {
                    await service.InitializeAsync().ConfigureAwait(false);
                }
            }

            _client.Log += HandleLogAsync;

            _client.Ready += async() =>
            {
                _applicationName = (await _client.GetApplicationInfoAsync()).Name;
                await _services.GetRequiredService <CommandHandlerService>().InitializeAsync();

                await _client.SetGameAsync(_appConfig.LittleBigBot.PlayingStatus);
            };

            await _client.LoginAsync(TokenType.Bot, _appConfig.Discord.Token).ConfigureAwait(false);

            await _client.StartAsync().ConfigureAwait(false);

            await Task.Delay(-1);
        }
        private async Task OnUserJoined(SocketGuildUser user)
        {
            var application = await _client.GetApplicationInfoAsync();

            var owner = application.Owner;

            if (user.Id != owner.Id)
            {
                return;
            }

            var channel = user.Guild.DefaultChannel;
            await channel.SendMessageAsync($"Welcome, my master o7");

            _client.MessageReceived += OnMessageReceived;

            async Task OnMessageReceived(SocketMessage message)
            {
                if (message.Channel.Id != channel.Id)
                {
                    return;
                }
                if (message.Author.Id != owner.Id)
                {
                    return;
                }
                string content = message.Content.ToLower();

                if (content == "at ease" || content == "at ease, navi")
                {
                    await channel.SendMessageAsync($"Understood, {owner.Username}-sama");
                }
            }
        }
Beispiel #3
0
        public async Task MainAsync(string apiToken, DiscordBotConfig cfg, CancellationToken token)
        {
            // Centralize the logic for commands into a separate method.
            await InitCommands(cfg).ConfigureAwait(false);

            // Login and connect.
            await _client.LoginAsync(TokenType.Bot, apiToken).ConfigureAwait(false);

            await _client.StartAsync().ConfigureAwait(false);

            await Task.Delay(5_000, token).ConfigureAwait(false);

            var game = Config.Name;

            if (!string.IsNullOrWhiteSpace(game))
            {
                await _client.SetGameAsync(game).ConfigureAwait(false);
            }

            var app = await _client.GetApplicationInfoAsync().ConfigureAwait(false);

            Owner = app.Owner.Id;

            // Wait infinitely so your bot actually stays connected.
            await MonitorStatusAsync(token).ConfigureAwait(false);
        }
        private async Task _client_Ready()
        {
            var application = await _client.GetApplicationInfoAsync();

            Log.Information(
                $"Invite: https://discordapp.com/oauth2/authorize?client_id={application.Id}&scope=bot&permissions=2146958591");
        }
Beispiel #5
0
        private Task LogErrorToOwnerDM(LogMessage message)
        {
            // lower indicates higher priority
            if (message.Severity > LogSeverity.Error)
            {
                return(Task.CompletedTask);
            }

            // per LogCommand (example code): "Don't risk blocking the logging task by awaiting a message send; ratelimits!?"
            var _ = Task.Run(async() =>
            {
                var appInfo        = await _discord.GetApplicationInfoAsync().ConfigureAwait(false);
                var ownerDmChannel = await appInfo?.Owner?.GetOrCreateDMChannelAsync().ConfigureAwait(false);
                if (ownerDmChannel == null)
                {
                    return;
                }

                // backtick, backtick, zero width space, backtick
                // this way it won't break our markdown
                const string threeBackticksEscaped = "``​`";

                await ownerDmChannel.SendMessageAsync(string.Empty,
                                                      embed: new EmbedBuilder()
                                                      .WithTitle("Application Message: " + message.Severity.ToStringCamelCaseToSpace() + (message.Exception != null ? ": " + message.Exception.GetType().Name : string.Empty))
                                                      .WithDescription("```" + message.ToString().Replace("```", threeBackticksEscaped) + "```")
                                                      .WithColor(Color.Red)
                                                      .Build()).ConfigureAwait(false);
            });

            return(Task.CompletedTask);
        }
Beispiel #6
0
        // log the OAuth2 Invite URL of the bot on client ready so that user can see it on startup
        private async Task Client_Ready()
        {
            var application = await client.GetApplicationInfoAsync();

            await Log(new LogMessage(LogSeverity.Info, "Program",
                                     $"Invite URL: <https://discordapp.com/oauth2/authorize?client_id={application.Id}&scope=bot>"));
        }
Beispiel #7
0
        public async Task MainAsync(string apiToken, CancellationToken token)
        {
            // Centralize the logic for commands into a separate method.
            await InitCommands().ConfigureAwait(false);

            // Login and connect.
            await _client.LoginAsync(TokenType.Bot, apiToken).ConfigureAwait(false);

            await _client.StartAsync().ConfigureAwait(false);

            // Restore Echoes
            await Task.Delay(5_000, token).ConfigureAwait(false);

            EchoModule.RestoreChannels(_client);

            // Restore Logging
            await Task.Delay(5_000, token).ConfigureAwait(false);

            LogModule.RestoreLogging(_client);
            TradeStartModule.RestoreTradeStarting(_client);

            var game = SysCordInstance.Settings.BotGameStatus;

            if (!string.IsNullOrWhiteSpace(game))
            {
                await _client.SetGameAsync(game).ConfigureAwait(false);
            }

            var app = await _client.GetApplicationInfoAsync().ConfigureAwait(false);

            SysCordInstance.Manager.Owner = app.Owner.Id;

            // Wait infinitely so your bot actually stays connected.
            await MonitorStatusAsync(token).ConfigureAwait(false);
        }
        public async Task MainAsync()
        {
            _client = new DiscordSocketClient();
            _config = BuildConfig();

            var services = ConfigureServices();

            services.GetRequiredService <LogService>();
            await Task.WhenAll(
                services.GetRequiredService <CommandHandlingService>().InitializeAsync(services),
                services.GetRequiredService <IDataPersistenceService>().InitializeAsync(services),
                services.GetRequiredService <CyberPatriotEventHandlingService>().InitializeAsync(services),
                services.GetRequiredService <IScoreRetrievalService>().InitializeAsync(services, null),
                services.GetRequiredService <ILocationResolutionService>().InitializeAsync(services),
                services.GetService <AlternateDataBackendProviderService>()?.InitializeAsync(services) ?? Task.CompletedTask,
                services.GetService <IExternalCategoryProviderService>()?.InitializeAsync(services) ?? Task.CompletedTask,
                services.GetService <ScoreboardDownloadService>()?.InitializeAsync(services) ?? Task.CompletedTask
                );

            string enableUpNotificationConfSetting = _config["enableUpNotification"] ?? "false";

            if (bool.TryParse(enableUpNotificationConfSetting, out bool enableUpNotification) && enableUpNotification)
            {
                _client.Ready += async() =>
                {
                    IUser        owner       = (await _client.GetApplicationInfoAsync().ConfigureAwait(false))?.Owner;
                    var          currentTime = DateTimeOffset.UtcNow;
                    TimeZoneInfo ownerTz;
                    if ((ownerTz = await(services.GetService <PreferenceProviderService>()?.GetTimeZoneAsync(user: owner).ConfigureAwait(false))) != null)
                    {
                        currentTime = TimeZoneInfo.ConvertTime(currentTime, ownerTz);
                    }
                    await(await owner?.GetOrCreateDMChannelAsync())?.SendMessageAsync($"[{currentTime.ToString("g")}] Now online!");
                };
            }

            _client.Ready += () =>
            {
                StartupTime = DateTimeOffset.UtcNow;
                return(Task.CompletedTask);
            };

            _client.Disconnected += (e) =>
            {
                if (e != null)
                {
                    Console.Error.Write("{Disconnecting due to following error:} ");
                    Console.Error.WriteLine(e.ToString());
                }
                Environment.Exit(e == null ? 0 : 1);
                return(Task.CompletedTask);
            };

            await _client.LoginAsync(Discord.TokenType.Bot, _config["token"]);

            await _client.StartAsync();

            await Task.Delay(-1);
        }
Beispiel #9
0
        private async Task HandleMessageReceived(SocketMessage incoming)
        {
            var message = incoming as SocketUserMessage;

            if (message is null)
            {
                return;
            }

            int argPos      = 0;
            var borkContext = new DoggoCommandContext(borkClient, message);

            if (!message.HasStringPrefix(borkConfig.LoadedSecrets.BotPrefix, ref argPos) || message.HasMentionPrefix(borkClient.CurrentUser, ref argPos))
            {
                return;
            }

            if (borkConfig.BlockedUsers.ContainsKey(message.Author.Id))
            {
                string           ifBlockIsPerm = "";
                BlockedUserModel blockedUser   = borkConfig.BlockedUsers[message.Author.Id];

                if (blockedUser.Permanent)
                {
                    ifBlockIsPerm = $"Your block is permanent, please DM {(await borkClient.GetApplicationInfoAsync()).Owner} if you wish to appeal.";
                }
                else
                {
                    ifBlockIsPerm = $"Your block is not permanent, it will be repealed eventually.";
                }

                await borkContext.Channel.SendMessageAsync("", false, new EmbedBuilder()
                                                           .WithColor(new Color(0, 0, 0))
                                                           .WithDescription($"**Error: You have been blocked from using commands.**\n`Blocked On:` *{blockedUser.BlockedTime.Date:MM/dd/yyyy}*\n\n`Reason:` *{blockedUser.Reason}*")
                                                           .WithFooter(x => { x.Text = ifBlockIsPerm; }).Build()); return;
            }

            using (IDisposable enterTyping = borkContext.Channel.EnterTypingState())
            {
                var res = await borkCommands.ExecuteAsync(borkContext, argPos, borkServices);

                if (!res.IsSuccess)
                {
                    if (res.Error == CommandError.UnknownCommand)
                    {
                        await borkContext.Channel.SendMessageAsync("Sorry! I didn't understand that command, please try again! :triangular_flag_on_post:");
                    }
                    else if (res.Error == CommandError.BadArgCount)
                    {
                        await borkContext.Channel.SendMessageAsync("Oh no! You didn't put enough parameters, check help if you need to! :scales:");
                    }
                    else
                    {
                        await borkContext.Channel.SendMessageAsync(res.ErrorReason);
                    }
                }
                enterTyping.Dispose();
            }
        }
Beispiel #10
0
        private async Task Client_Ready()
        {
            // display a helpful invite url in the log when the bot is ready
            var application = await m_client.GetApplicationInfoAsync();

            await Log(new LogMessage(LogSeverity.Info, "Program",
                                     $"Invite URL: <https://discordapp.com/oauth2/authorize?client_id={application.Id}&scope=bot>"));
        }
Beispiel #11
0
        // We can do something when our bot joins a guild
        // For this example, we will send a DM to the bot application owner
        private async Task ClientJoinGuild(SocketGuild guild)
        {
            var appInfo = await _client.GetApplicationInfoAsync();                                 // Get app info of our bot

            var channel = await appInfo.Owner.CreateDMChannelAsync();                              // Get the DM channel with our app owner, create it if it doesn't exist

            await channel.SendMessageAsync($"I just joined a guild: `{guild.Name}` ({guild.Id})"); // Send a new message in our DM channel
        }
Beispiel #12
0
        public async Task OnMessageReceivedAsync(SocketMessage s)
        {
            var msg = s as SocketUserMessage; // Ensure the message is from a user/bot

            if (msg == null)
            {
                return;
            }

            if (ShouldIgnore(msg))
            {
                return;
            }

            var argPos  = 0;                                       // Check if the message has a valid command prefix
            var context = new SocketCommandContext(_discord, msg); // Create the command context

            using (var scope = _provider.CreateScope()) {
                var provider = scope.ServiceProvider;

                // Load commands and modules into the command service
                var commandService = provider.GetRequiredService <CommandService>();
                commandService.Log += _logService.LogMessage;

                var contextService = provider.GetRequiredService <ContextService>();
                contextService.Context     = context;
                contextService.Application = await _discord.GetApplicationInfoAsync();

                await commandService.AddModulesAsync(Assembly.GetEntryAssembly(), provider);

                if (msg.HasStringPrefix(_options.Prefix, ref argPos) ||
                    msg.HasMentionPrefix(_discord.CurrentUser, ref argPos))
                {
                    var message = msg.Content.Substring(argPos);

                    var result = await commandService.ExecuteAsync(context, argPos, _provider); // Execute the command

                    if (!result.IsSuccess)
                    {
                        if (await ProcessParsers(provider, message))
                        {
                            return;
                        }
                    }

                    var replies = new [] {
                        "Huh?", "What?", "Eh?", "Mmm?",
                        "Come again?", "Sorry?", "No idea what you're saying.",
                        "That's not a command.",
                        "Uh, try `!help`"
                    };

                    await context.Channel.SendMessageAsync(replies[_rng.Next(replies.Length)]);
                }
            }
        }
Beispiel #13
0
        private async Task Client_Ready()
        {
            Console.WriteLine($"Part of {client.Guilds.Count} guilds.");

            var application = await client.GetApplicationInfoAsync().ConfigureAwait(false);

            Log(new LogMessage(LogSeverity.Info, "Program",
                               $"Invite URL: <https://discordapp.com/oauth2/authorize?client_id={application.Id}&scope=bot>"));
            Console.WriteLine($"Invite URL: <https://discordapp.com/oauth2/authorize?client_id={application.Id}&scope=bot>");
        }
Beispiel #14
0
        public GlobalConfiguration(DiscordSocketClient socketClient, string tok, string pref, bool edit)
        {
            Token               = tok;
            DefaultPrefix       = pref;
            DefaultExecuteEdits = edit;
            OwnerId             = socketClient.GetApplicationInfoAsync().Result.Owner.Id;
            GlobalAdminIds.Add(OwnerId);
            DebugMode = false;

            BlacklistedIds = new List <ulong>();
        }
Beispiel #15
0
        public Help(IBotCredentials creds, GlobalPermissionService perms, CommandService cmds,
                    IServiceProvider services, DiscordSocketClient client)
        {
            _creds    = creds;
            _cmds     = cmds;
            _perms    = perms;
            _services = services;
            _client   = client;

            _lazyClientId = new AsyncLazy <ulong>(async() => (await _client.GetApplicationInfoAsync()).Id);
        }
Beispiel #16
0
        private async Task OnLogAsync(LogMessage logMessage)
        {
            if (logMessage.Exception is CommandException cmdException)
            {
                await cmdException.Context.Channel.SendMessageAsync("Something went catastrophically wrong!");

                var application = await _client.GetApplicationInfoAsync();

                await application.Owner.SendMessageAsync("```" + cmdException.ToString() + "```");
            }
        }
Beispiel #17
0
        public Help(GlobalPermissionService perms, CommandService cmds, BotConfigService bss,
                    IServiceProvider services, DiscordSocketClient client, IBotStrings strings)
        {
            _cmds     = cmds;
            _bss      = bss;
            _perms    = perms;
            _services = services;
            _client   = client;
            _strings  = strings;

            _lazyClientId = new AsyncLazy <ulong>(async() => (await _client.GetApplicationInfoAsync()).Id);
        }
Beispiel #18
0
        /// <summary>
        /// Housekeeping functions to run just as bot comes online
        /// </summary>
        /// <returns></returns>
        private async Task ReadyEvent()
        {
            // Update bot name if app name is different
            IApplication app = await Client.GetApplicationInfoAsync();

            await Client.CurrentUser.ModifyAsync(x =>
            {
                x.Username = app.Name;
            });

            // Set bot status message
            await Client.SetGameAsync($"!help");
        }
Beispiel #19
0
        private async Task <Task> FinishSetup()
        {
            var appInfo = await client.GetApplicationInfoAsync();

            redis.StringSet("botOwner", appInfo.Owner.Id);

            var req = HttpWebRequest.Create(appInfo.IconUrl);

            using (Stream stream = req.GetResponse().GetResponseStream())
            {
                await client.CurrentUser.ModifyAsync(Avatar => new Image(stream));
            }
            return(Task.CompletedTask);
        }
Beispiel #20
0
        /*
         * private async Task HandleUpdatedMessageAsync (Cacheable<IMessage, ulong> before, SocketMessage after, ISocketMessageChannel channel) {
         *  ulong logChannelId;
         *  var logChannel = _client.GetChannel (logChannelId) as ISocketMessageChannel;
         *
         *  try {
         *      var message = await before.GetOrDownloadAsync ();
         *
         *      if (after.Author.IsBot == true || after is null) {
         *          return;
         *      } else {
         *          string channelName = channel.Name;
         *
         *          var author = after.Author as SocketUser;
         *          var avatar = author.GetAvatarUrl (ImageFormat.Auto);
         *          var defaultAvatar = author.GetDefaultAvatarUrl ();
         *
         *          EmbedAuthorBuilder embedAuthorBuilder = new EmbedAuthorBuilder ();
         *
         *          embedAuthorBuilder.WithName ($"Message edited by {author.Username}#{author.Discriminator} in #{channelName}");
         *
         *          if (avatar == null) {
         *              embedAuthorBuilder.WithIconUrl (defaultAvatar);
         *          } else {
         *              embedAuthorBuilder.WithIconUrl (avatar);
         *          }
         *
         *          EmbedBuilder builder = new EmbedBuilder ();
         *
         *          builder.AddField ("Before", $"```diff\n- {message}\n```", true);
         *          builder.AddField ("After", $"```diff\n+ {after}\n```", true);
         *          builder.WithAuthor (embedAuthorBuilder);
         *          builder.WithCurrentTimestamp ();
         *          builder.WithColor (Color.Blue);
         *
         *          await logChannel.SendMessageAsync ("", false, builder.Build ());
         *      }
         *  } catch (Exception ex) {
         *      await logChannel.SendMessageAsync (ex.Message);
         *  }
         * }
         *
         * private async Task HandleDeletedMessageAsync (Cacheable<IMessage, ulong> message, ISocketMessageChannel channel) {
         *  ulong logChannelId;
         *  var logChannel = _client.GetChannel (logChannelId) as ISocketMessageChannel;
         *
         *  try {
         *      var originalMessage = await message.GetOrDownloadAsync ();
         *
         *      if (originalMessage.Author.IsBot == true || originalMessage is null) {
         *          return;
         *      } else {
         *          string channelName = channel.Name;
         *
         *          var author = originalMessage.Author as SocketUser;
         *          var avatar = author.GetAvatarUrl (ImageFormat.Auto);
         *          var defaultAvatar = author.GetDefaultAvatarUrl ();
         *
         *          EmbedAuthorBuilder embedAuthorBuilder = new EmbedAuthorBuilder ();
         *
         *          embedAuthorBuilder.WithName ($"Message deleted by {author.Username}#{author.Discriminator} in #{channelName}");
         *
         *          if (avatar == null) {
         *              embedAuthorBuilder.WithIconUrl (defaultAvatar);
         *          } else {
         *              embedAuthorBuilder.WithIconUrl (avatar);
         *          }
         *
         *          EmbedBuilder builder = new EmbedBuilder ();
         *
         *          builder.AddField ("Message", $"```diff\n- {originalMessage}\n```", true);
         *          builder.WithAuthor (embedAuthorBuilder);
         *          builder.WithCurrentTimestamp ();
         *          builder.WithColor (Color.Blue);
         *
         *          await logChannel.SendMessageAsync ("", false, builder.Build ());
         *      }
         *  } catch (Exception ex) {
         *      await logChannel.SendMessageAsync (ex.Message);
         *  }
         * }
         */

        private async Task HandleGuildJoinedAsync(SocketGuild socketGuild)
        {
            var invites = await socketGuild.GetInvitesAsync();

            foreach (var invite in invites)
            {
                if (invite != null)
                {
                    var info = await _client.GetApplicationInfoAsync();

                    await info.Owner.SendMessageAsync(invite.ToString());
                }
            }
        }
Beispiel #21
0
        private async Task Client_Ready()
        {
            var application = await Client.GetApplicationInfoAsync();

            await ColourLog.In1Run(
                $"Invite: https://discordapp.com/oauth2/authorize?client_id={application.Id}&scope=bot&permissions=2146958591");

            var k = JsonConvert.DeserializeObject <List <string> >(
                File.ReadAllText(Path.Combine(AppContext.BaseDirectory, "setup/keys.json")));

            if (k.Count > 0)
            {
                Keys = k;
            }
        }
        private async Task HandleReadyAsync()
        {
            RestApplication info = await Client.GetApplicationInfoAsync();

            IReadOnlyCollection <SocketGuild> Guilds = Client.Guilds;

            foreach (SocketGuild Guild in Guilds)
            {
            }
            Environment.SetEnvironmentVariable("startTime", DateTime.Now.ToString());
            await Client.SetGameAsync($"You on {Guilds.Count} servers\nPrefix {Environment.GetEnvironmentVariable("prefix")}",
                                      null,
                                      ActivityType.Watching
                                      );
        }
        private async Task ThreadEntry(CancellationToken token)
        {
            try
            {
                while (!token.IsCancellationRequested)
                {
                    foreach (var feed in await _notifications.GetSubscriptions().ToListAsync(token))
                    {
                        try
                        {
                            var syndication = await _rss.Fetch(feed.FeedUrl);

                            foreach (var item in syndication)
                            {
                                if (!await HasBeenPublished(feed.Channel.ToString(), feed.FeedUrl, item.Id))
                                {
                                    await Publish(feed, item);

                                    await Task.Delay(150, token);
                                }
                            }
                        }
                        catch (Exception e)
                        {
                            Console.WriteLine($"{nameof(DatabaseRssNotificationsSender)} Swallowed exception:\n{e}");
                        }
                    }

                    await Task.Delay(PollDelay, token);
                }
            }
            catch (Exception e)
            {
                var info = await _client.GetApplicationInfoAsync();

                if (info.Owner != null)
                {
                    var channel = await info.Owner.CreateDMChannelAsync();

                    await channel.SendMessageAsync($"{nameof(DatabaseRssNotificationsSender)} notifications thread crashed:");

                    await channel.SendLongMessageAsync(e.ToString());
                }
            }
        }
        public static async Task <bool> IsBotOwner([NotNull] this ClaimsPrincipal user, DiscordSocketClient client)
        {
            var discordUser = user.TryGetDiscordUser(client);

            if (discordUser == null)
            {
                return(false);
            }

            var info = await client.GetApplicationInfoAsync();

            if (info.Owner == null)
            {
                return(false);
            }

            return(info.Owner.Id == discordUser.Id);
        }
        public async Task GuildsAsync()
        {
            await Context.Channel.SendMessageAsync(":b:");

            List <string> guildList = new List <string>();

            foreach (SocketGuild g in borkClient.Guilds)
            {
                guildList.Add($"[{borkClient.Guilds.ToList().IndexOf(g)}]: {g.Name} ({g.Id})");
            }

            await(await borkClient.GetApplicationInfoAsync()).Owner.SendFileAsync(
                new MemoryStream(Encoding.Unicode.GetBytes(
                                     JsonConvert.SerializeObject(guildList, Formatting.Indented, new JsonSerializerSettings {
                NullValueHandling = NullValueHandling.Include
            }) ?? "Err - NULL")),
                "Guilds.json");
        }
Beispiel #26
0
        public async Task AddNewGuild(ulong guildId)
        {
            using (var db = new LiteDatabase(DatabaseDir))
            {
                var guilds = db.GetCollection <GuildObject>("guilds");
                guilds.EnsureIndex($"{guildId}");
                await _logMethod.Invoke(new LogMessage(LogSeverity.Info, LogSource,
                                                       $"Inserting {guildId} into the database"));

                guilds.Insert(new GuildObject(guildId, (await _client.GetApplicationInfoAsync()).Owner.Id, _client.GetGuild(guildId).OwnerId));
                _currentTags.Add(guildId, new List <TagObject>());
                _approvedUsers.Add(guildId, new List <ulong>()
                {
                    _client.CurrentUser.Id,
                    _client.GetGuild(guildId).OwnerId
                });
            }
        }
Beispiel #27
0
        public static bool IsModeratorOrHigher(this SocketGuildUser currentUser, GuildModel.GuildSettings._Moderation moderationSettings, DiscordSocketClient client)
        {
            if (currentUser.Roles.Any(r => moderationSettings.ModRoles.Contains(r.Id) || moderationSettings.AdminRoles.Contains(r.Id)))
            {
                return(true);
            }

            if (currentUser.Id == currentUser.Guild.OwnerId)
            {
                return(true);
            }

            if (currentUser.Id == client.GetApplicationInfoAsync().Result.Owner.Id)
            {
                return(true);
            }

            return(false);
        }
Beispiel #28
0
        public async Task DiagnosticAsync(
            [Summary("If set, wait until the next performance service tick, collect unused memory and show diagnostic info. Requires bot ownership")]
            bool forceCollect = false)
        {
            EmbedBuilder embed;
            IUserMessage msg = null;

            if (forceCollect)
            {
                var ownerId = (await discord.GetApplicationInfoAsync()).Owner.Id;
                if (Context.User.Id != ownerId)
                {
                    return;
                }

                embed = new EmbedBuilder()
                        .WithColor(100, 149, 237)
                        .WithDescription("Waiting for next performance service tick...");
                msg = await ReplyAsync("", embed : embed.Build());

                await perf.WaitNextTick(true);
            }

            embed = new EmbedBuilder()
                    .WithColor(100, 149, 237)
                    .AddInlineField("Gateway latency", $"{perf.AverageLatency:.##} ms")
                    .AddInlineField("Memory", $"Heap: {perf.AverageHeapMemory / 1_000_000f:.##}MB\nProcess: {perf.AverageProcessMemory / 1_000_000f:.##}MB")
                    .AddInlineField("Cache", $"{cache.Queries} queries\n{cache.Articles} articles\n{cache.FileSize / 1_000_000f:.##}MB file")
                    .AddInlineField("GC", $"{GC.MaxGeneration} generations\nGen-0 collections: {GC.CollectionCount(0)}")
                    .WithTimestamp(DateTimeOffset.UtcNow);

            if (msg != null)
            {
                await msg.ModifyAsync(f => f.Embed = embed.Build());
            }
            else
            {
                await ReplyAsync("", embed : embed.Build());
            }
        }
Beispiel #29
0
        private async Task HandleCommandAsync(SocketMessage messageParam)
        {
            // Don't process the command if it was a System Message
            var message = messageParam as SocketUserMessage;

            if (message == null)
            {
                return;
            }
            // Also do not process other bots (bot loop would be bad)
            else if (message.Author.IsBot)
            {
                return;
            }
            // Create a number to track where the prefix ends and the command begins
            int argPos = 0;

            // Determine if the message is a command, based on if it starts with prefix from json config or a mention prefix
            if (!(message.HasStringPrefix(_config["bot_prefix"], ref argPos) || message.HasMentionPrefix(_client.CurrentUser, ref argPos)) ||
                (message.Author != (await _client.GetApplicationInfoAsync()).Owner && messageParam.Channel.GetType() == typeof(SocketDMChannel)))
            {
                return;
            }
            // Create a Command Context
            var context = new SocketCommandContext(_client, message);

            // Execute the command. (result does not indicate a return value,
            // rather an object stating if the command executed successfully)
            if (_config.GetValue <bool>("debug", false))
            {
                Console.WriteLine($"Executing command \"{context.Message.ToString()}\" for user \"{context.User.ToString()}\"");
            }
            var result = await _commands.ExecuteAsync(context, argPos, _services);

            if (!result.IsSuccess)
            {
                await context.Channel.SendMessageAsync(result.ErrorReason);
            }
        }
Beispiel #30
0
        public async Task HandleCommand(SocketMessage messageParam)
        {
            var message = messageParam as SocketUserMessage;

            if (message == null || message.Author.Id == client.CurrentUser.Id)
            {
                return;
            }

            if (isDev)
            {
                var appInfo = await client.GetApplicationInfoAsync();

                if (message.Author.Id != appInfo.Owner.Id)
                {
                    return;
                }
            }

            int argPos = 0;

            if (!(message.HasCharPrefix('!', ref argPos) || message.HasMentionPrefix(client.CurrentUser, ref argPos)))
            {
                return;
            }

            var context = new CommandContext(client, message);
            var result  = await commands.ExecuteAsync(context, argPos, services);

            if (!result.IsSuccess && result.Error == CommandError.UnmetPrecondition)
            {
                await context.Channel.SendMessageAsync(result.ErrorReason);
            }
            else if (!result.IsSuccess && result.Error == CommandError.BadArgCount)
            {
                await context.Channel.SendMessageAsync($"{context.Message.Author.Mention}: You didn't specify the right " +
                                                       "parameters. If you're using a role command, you probably forgot to specify the user.");
            }
        }