Ejemplo n.º 1
0
        public static async Task HandleCommandAsync(SocketMessage messageParam)
        {
            var Client  = EntryPoint.Client;
            var message = messageParam as SocketUserMessage;

            if (message == null)
            {
                return;
            }
            var context = new SocketCommandContext(Client, message);

            SocketGuildUser me = context.Guild.Users.Where(x => x.Id == Client.CurrentUser.Id).ToList()[0];

            RestApplication application = await context.Client.GetApplicationInfoAsync();


            if (EntryPoint.Lockdown && context.User.Id != application.Owner.Id)
            {
                await context.Channel.SendMessageAsync("We are on lockdown.");

                return;
            }

            if (messageParam.Content.Count(c => c == '┻') > 1)
            {
                await context.Channel.SendMessageAsync("┬─┬ ノ( ゜-゜ノ)" + "\n" + messageParam.Author.Mention + ", please respect the goddamn tables. 😠");
            }
        }
Ejemplo n.º 2
0
            public async Task AdminGuildLeave(ulong guildid)
            {
                SocketGuild guild = Context.Client.GetGuild(guildid);

                if (guild == null)
                {
                    await ReplyAsync("Guild not found.");
                }
                else
                {
                    IUserMessage msg = await ReplyAsync($"Leaving {guild.Name}, is this correct? React with any emote.");

                    async Task onReact(Cacheable <IUserMessage, ulong> cachemsg, ISocketMessageChannel chnl, SocketReaction react)
                    {
                        RestApplication application = await Context.Client.GetApplicationInfoAsync();

                        if (react.UserId == application.Owner.Id)
                        {
                            await msg.ModifyAsync(x => x.Content = $"Leaving {guild.Name}.");

                            await Task.Delay(8000);

                            await Context.Client.GetGuild(guild.Id).LeaveAsync();
                        }
                        await msg.DeleteAsync();

                        Context.Client.ReactionAdded -= onReact;
                    };
                    Context.Client.ReactionAdded += onReact;
                }
            }
Ejemplo n.º 3
0
        public static async Task Initialize(EBotClient client)
        {
            _Client = client;
            _App    = await client.Discord.GetApplicationInfoAsync();

            foreach (string filepath in Directory.GetFiles(_Path))
            {
                string   path = filepath.Replace(@"\", "/");
                string[] dir  = path.Split("/");
                string   id   = dir[dir.Length - 1];
                id = id.Remove(id.Length - 4);
                ulong         chanid = ulong.Parse(id);
                SocketChannel chan   = _Client.Discord.GetChannel(chanid);

                Lua      state  = CreateState(chan);
                string   script = File.ReadAllText(path);
                string[] parts  = script.Split(ScriptSeparator);
                foreach (string part in parts)
                {
                    state["SCRIPT"] = part;
                    state.DoString("sandbox(SCRIPT)");
                    state["SCRIPT"] = null;
                }
            }
        }
Ejemplo n.º 4
0
 public InfoEmbed(RestApplication app)
 {
     Title        = $"About {app.Name}";
     Description  = app.Description;
     ThumbnailUrl = app.IconUrl;
     AddField("Author:", app.Owner);
     AddField("Git repo:", @"https://github.com/AbdShullah/OsuFriendsBot");
     AddField("Bot Version:", "0.1.0");
     Color = EmbedColors.Info;
 }
Ejemplo n.º 5
0
        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
                                      );
        }
Ejemplo n.º 6
0
        public async Task DisplayBotInfo()
        {
            RestApplication appInfo = await _bot.Client.GetApplicationInfoAsync();

            EmbedBuilder builder = new EmbedBuilder()
            {
                Title = "About Me"
            };

            TimeSpan uptime = DateTime.Now - _bot.StartTime;

            builder.AddField("Name: ", $"`{appInfo.Name}`");
            builder.AddField("Created at: ", $"`{appInfo.CreatedAt}`");
            builder.AddField("Owner: ", $"`{appInfo.Owner}`");
            builder.AddField("Discord.Net Version: ", $"`{DiscordConfig.Version}`");
            builder.AddField("Discord API Version: ", $"`{DiscordConfig.APIVersion}`");
            builder.AddField("Uptime: ", $"`{uptime.ToString("%d")} days, {uptime.ToString("%h")} hours, {uptime.ToString("%m")} minutes`");

            await ReplyAsync(embed : builder.Build());
        }
        public override async ValueTask <CheckResult> CheckAsync(CommandContext _)
        {
            var context = _ as DiscordCommandContext;

            switch (context.Bot.TokenType)
            {
            case TokenType.Bot:
            {
                if (application == null)
                {
                    application = await context.Bot.GetCurrentApplicationAsync().ConfigureAwait(false);
                }

                if (application.Team != null && application.Team.Members != null)
                {
                    if (application.Team.Members.ContainsKey(context.User.Id))
                    {
                        return(CheckResult.Successful);
                    }
                }

                return(application.Owner.Id == context.User.Id
                            ? CheckResult.Successful
                            : CheckResult.Unsuccessful("This can only be executed by the bot's owner or team members."));
            }

            case TokenType.Bearer:
            case TokenType.User:
            {
                return(context.Bot.CurrentUser.Id == context.User.Id
                            ? CheckResult.Successful
                            : CheckResult.Unsuccessful("This can only be executed by the currently logged in user."));
            }

            default:
                throw new InvalidOperationException("Invalid token type.");
            }
        }
        /// <inheritdoc />
        public override async System.Threading.Tasks.Task <PreconditionResult> CheckPermissionsAsync(ICommandContext context, CommandInfo command, IServiceProvider services)
        {
            switch (context.Client.TokenType)
            {
            case TokenType.Bot:
                RestApplication application = (RestApplication)await context.Client.GetApplicationInfoAsync().ConfigureAwait(false);

                if (!Global.IsDev((SocketUser)context.User))
                {
                    if (Global.clientCommands == true && context.User.Id == context.Client.CurrentUser.Id)
                    {
                        return(PreconditionResult.FromSuccess());
                    }

                    return(PreconditionResult.FromError(ErrorMessage ?? "Command can only be run by a listed developer of the bot."));
                }

                return(PreconditionResult.FromSuccess());

            default:
                return(PreconditionResult.FromError($"{nameof(RequireDeveloperAttribute)} is not supported by this {nameof(TokenType)}."));
            }
        }
Ejemplo n.º 9
0
        public async Task InfoCmd()
        {
            RestApplication app = await Context.Client.GetApplicationInfoAsync();

            await ReplyAsync(embed : new InfoEmbed(app).Build());
        }
Ejemplo n.º 10
0
        private async Task LoadAppInfo()
        {
            AppInfo = await client.GetApplicationInfoAsync(Bot.DefaultOptions);

            client.LoggedIn -= LoadAppInfo;
        }
Ejemplo n.º 11
0
        public static async Task <DiscordUser> CreateAsync(SocketGuild guild, SocketGuildUser user, DBDiscordUser dbUser, DiscordSocketClient discordClient,
                                                           RestApplication botAppInfo)
        {
            var result = new DiscordUser()
            {
                ApiAccess              = !string.IsNullOrEmpty(dbUser.ApiToken),
                Guild                  = guild,
                User                   = user,
                ID                     = dbUser.ID,
                Points                 = dbUser.Points,
                GivenReactionsCount    = dbUser.GivenReactionsCount,
                ObtainedReactionsCount = dbUser.ObtainedReactionsCount,
                WebAdminAccess         = !string.IsNullOrEmpty(dbUser.WebAdminPassword),
                Birthday               = dbUser.Birthday,
                ApiAccessCount         = dbUser.ApiAccessCount,
                WebAdminLoginCount     = dbUser.WebAdminLoginCount,
                Flags                  = dbUser.Flags,
                UnverifyEndsAt         = dbUser.Unverify?.EndDateTime,
                UnverifyImunityGroup   = dbUser.UnverifyImunityGroup
            };

            if (botAppInfo.Owner.Id == user.Id)
            {
                result.Flags |= (long)UserFlags.BotAdmin;
            }

            result.Channels = dbUser.Channels
                              .Select(o => new ChannelStatItem(guild.GetChannel(o.ChannelIDSnowflake), o))
                              .Where(o => o.Channel != null)
                              .OrderByDescending(o => o.Count)
                              .ThenByDescending(o => o.LastMessageAt)
                              .ToList();

            if (dbUser.UsedInvite != null)
            {
                SocketGuildUser inviteCreator = null;
                if (dbUser.UsedInvite.Creator != null)
                {
                    inviteCreator = await guild.GetUserFromGuildAsync(dbUser.UsedInvite.Creator.UserIDSnowflake);
                }

                result.UsedInvite = new InviteModel(dbUser.UsedInvite, inviteCreator);
            }
            else if (!string.IsNullOrEmpty(dbUser.UsedInviteCode))
            {
                result.UsedInvite = new InviteModel(dbUser.UsedInviteCode);
            }

            result.UnverifyHistory = dbUser.IncomingUnverifyOperations
                                     .Select(o => new UnverifyLogItem(o, discordClient))
                                     .OrderByDescending(o => o.DateTime)
                                     .ToList();

            result.GivenUnverifyHistory = dbUser.OutgoingUnverifyOperations
                                          .Select(o => new UnverifyLogItem(o, discordClient))
                                          .OrderByDescending(o => o.DateTime)
                                          .ToList();

            result.Reminders = new List <RemindItem>();
            foreach (var remind in dbUser.Reminders)
            {
                var fromUser = remind.FromUser != null ? await guild.GetUserFromGuildAsync(remind.FromUser.UserIDSnowflake) : null;

                result.Reminders.Add(new RemindItem(remind, fromUser));
            }

            result.CreatedInvites = dbUser.CreatedInvites.Select(o => new InviteModel(o, user, o.UsedUsers.Count)).ToList();

            return(result);
        }
Ejemplo n.º 12
0
        private async Task StartAsync()
        {
            async Task LoginRoutine()
            {
                await discordClient.LoginAsync(TokenType.Bot, _config.DiscordToken);

                await discordClient.StartAsync();

                await Task.Delay(-1);
            }

            discordClient.Ready += async() =>
            {
                if (!IsReady)
                {
                    ApplicationInfo = await discordClient.GetApplicationInfoAsync();

                    _logger.LogInformation($"Logged into Discord as \"{discordClient.CurrentUser}\" in {discordClient.Guilds.Count} guild{(discordClient.Guilds.Count > 1 ? "s" : "")}.");

                    LoadCommands();

                    var guildStorage = _serviceProvider.GetService <GuildStorage>();

                    var dbGuilds = await guildStorage.GetAllGuildsAsync();

                    foreach (var guild in dbGuilds)
                    {
                        var unexpiredCases = guild.Cases.Where(x => (x.GetEndingTime() > DateTimeOffset.UtcNow && x.ActionType != ActionType.Warn) || (x.ActionType == ActionType.Warn && x.GetWarnEndingTime() > DateTimeOffset.UtcNow));

                        int failedCaseAdds = 0;
                        foreach (var guildCase in unexpiredCases)
                        {
                            if (!_caseHandlingService.TryAdd(guildCase))
                            {
                                failedCaseAdds++;
                            }
                        }

                        if (failedCaseAdds > 0)
                        {
                            _logger.LogWarning($"Failed to add {failedCaseAdds} cases to in-memory cache.");
                        }

                        //resolve all cases that had expired
                        var unresolvedExpiredCases = guild.Cases.Where(x => !x.Resolved && ((x.ActionType != ActionType.Warn && x.GetEndingTime() <= DateTimeOffset.UtcNow) || (x.GetWarnEndingTime() <= DateTimeOffset.UtcNow && x.ActionType == ActionType.Warn)));

                        foreach (var guildCase in unresolvedExpiredCases)
                        {
                            await _caseHandlingService.ResolveAsync(guildCase, null, null, false, false);
                        }
                    }

                    IsReady = true;
                }
            };

            discordClient.MessageReceived += async(m) =>
            {
                if (m.Channel is IDMChannel)
                {
                    return;
                }
                if (!(m is SocketUserMessage msg))
                {
                    return;
                }

                if (CommandUtilities.HasAnyPrefix(msg.Content, _prefixes, StringComparison.OrdinalIgnoreCase, out string pfx, out string output))
                {
                    var context = new QuiccbanContext(discordClient, msg, _serviceProvider);
                    var result  = await _commands.ExecuteAsync(output, context, _serviceProvider);

                    if (result is QuiccbanSuccessResult success && !string.IsNullOrWhiteSpace(success.ReplyValue))
                    {
                        await context.Channel.SendMessageAsync(success.ReplyValue);
                    }

                    if (result is QuiccbanFailResult inCommandFail)
                    {
                        await context.Channel.SendMessageAsync(inCommandFail.Reason);
                    }

                    if (result is ChecksFailedResult checkFail)
                    {
                        await context.Channel.SendMessageAsync(checkFail.FailedChecks.FirstOrDefault().Error);
                    }

                    if (result is ParameterChecksFailedResult paramCheckFail)
                    {
                        await context.Channel.SendMessageAsync(paramCheckFail.FailedChecks.FirstOrDefault().Error);
                    }
                }
            };

            discordClient.UserBanned += async(u, g) =>
            {
                await Task.Delay(500);

                var auditLogs = await g.GetAuditLogsAsync(20).FlattenAsync();

                var auditLog = auditLogs.FirstOrDefault(a => a.Data is BanAuditLogData ban && ban.Target.Id == u.Id);
                if (auditLog == null)
                {
                    return;
                }

                if (auditLog.User.Id == discordClient.CurrentUser.Id)
                {
                    return;
                }

                var data      = auditLog.Data as BanAuditLogData;
                var dbService = _serviceProvider.GetService <DatabaseService>();

                await dbService.CreateNewCaseAsync(g, auditLog.Reason, ActionType.Ban, 0, auditLog.User, data.Target);
            };

            discordClient.UserUnbanned += async(u, g) =>
            {
                await Task.Delay(500);

                var auditLogs = await g.GetAuditLogsAsync(20).FlattenAsync();

                var auditLog = auditLogs.FirstOrDefault(a => a.Data is UnbanAuditLogData unban && unban.Target.Id == u.Id);
                if (auditLog == null)
                {
                    return;
                }

                if (auditLog.User.Id == discordClient.CurrentUser.Id)
                {
                    return;
                }

                var data        = auditLog.Data as UnbanAuditLogData;
                var dbService   = _serviceProvider.GetService <DatabaseService>();
                var caseService = _serviceProvider.GetService <CaseHandlingService>();

                var tempcase = caseService.GetCases().FirstOrDefault(x => x.GuildId == g.Id && x.TargetId == data.Target.Id && x.ActionType == ActionType.TempBan && !x.Resolved);
                if (tempcase != null)
                {
                    await _caseHandlingService.ResolveAsync(tempcase, auditLog.User, auditLog.Reason, true, false);
                }
                else
                {
                    await dbService.CreateNewCaseAsync(g, auditLog.Reason, ActionType.Ban, 0, auditLog.User, data.Target);
                }
            };

            discordClient.UserLeft += async(u) =>
            {
                await Task.Delay(500);

                var auditLogs = await u.Guild.GetAuditLogsAsync(20).FlattenAsync();

                var auditLog = auditLogs.FirstOrDefault(a => a.Data is KickAuditLogData kick && kick.Target.Id == u.Id);
                if (auditLog == null)
                {
                    return;
                }

                if (auditLog.User.Id == discordClient.CurrentUser.Id)
                {
                    return;
                }

                var data      = auditLog.Data as KickAuditLogData;
                var dbService = _serviceProvider.GetService <DatabaseService>();

                await dbService.CreateNewCaseAsync(u.Guild, auditLog.Reason, ActionType.Kick, 0, auditLog.User, data.Target);
            };

            discordClient.GuildMemberUpdated += async(u_before, u_after) =>
            {
                await Task.Delay(500);

                var auditLogs = await u_after.Guild.GetAuditLogsAsync(20).FlattenAsync();

                var auditLog = auditLogs.FirstOrDefault(a => a.Data is MemberRoleAuditLogData role && role.Target.Id == u_after.Id);
                if (auditLog == null)
                {
                    return;
                }

                if (auditLog.User.Id == discordClient.CurrentUser.Id)
                {
                    return;
                }

                var data = auditLog.Data as MemberRoleAuditLogData;

                var dbService   = _serviceProvider.GetService <DatabaseService>();
                var caseService = _serviceProvider.GetService <CaseHandlingService>();
                var dbGuild     = await dbService.GetOrCreateGuildAsync(u_after.Guild);

                if (data.Roles.Any(x => x.RoleId == dbGuild.MuteRoleId && x.Added))
                {
                    await dbService.CreateNewCaseAsync(u_after.Guild, auditLog.Reason, ActionType.Mute, 0, auditLog.User, data.Target);
                }
                else if (data.Roles.Any(x => x.RoleId == dbGuild.MuteRoleId && !x.Added))
                {
                    var tempcase = caseService.GetCases().FirstOrDefault(x => x.TargetId == data.Target.Id && x.ActionType == ActionType.TempMute && !x.Resolved);
                    if (tempcase != null)
                    {
                        await _caseHandlingService.ResolveAsync(tempcase, auditLog.User, auditLog.Reason, true, false);
                    }
                    else
                    {
                        await dbService.CreateNewCaseAsync(u_after.Guild, auditLog.Reason, ActionType.Unmute, 0, auditLog.User, data.Target);
                    }
                }
            };



            _logger.LogInformation("Attempting to log into Discord...");

            try
            {
                await LoginRoutine();
            }
            catch
            {
                _logger.LogError("Failed to log into Discord. Attempting reconnect in 10 seconds.");
                await Task.Delay(10000);

                try
                {
                    await LoginRoutine();
                }
                catch
                {
                    _logger.LogError("Reconnection failed. Exiting.");
                    Environment.Exit(0);
                }
            }
        }
Ejemplo n.º 13
0
 public BotInfo(RestApplication app)
 {
     Name        = app.Name;
     Description = app.Description;
     ClientId    = app.Id.ToString();
 }
Ejemplo n.º 14
0
        private async Task ProcessMessageAsync(string cmd, Optional <string> evnt, Optional <object> payload)
        {
            try
            {
                switch (cmd)
                {
                case "DISPATCH":
                    switch (evnt.Value)
                    {
                    //Connection
                    case "READY":
                    {
                        await _rpcLogger.DebugAsync("Received Dispatch (READY)").ConfigureAwait(false);

                        var data = (payload.Value as JToken).ToObject <ReadyEvent>(_serializer);

                        RequestOptions options = new RequestOptions
                        {
                            //CancellationToken = _cancelToken //TODO: Implement
                        };

                        if (ApiClient.LoginState == LoginState.LoggedIn)
                        {
                            var _ = Task.Run(async() =>
                                {
                                    try
                                    {
                                        var response            = await ApiClient.SendAuthenticateAsync(options).ConfigureAwait(false);
                                        CurrentUser             = RestSelfUser.Create(this, response.User);
                                        ApiClient.CurrentUserId = CurrentUser.Id;
                                        ApplicationInfo         = RestApplication.Create(this, response.Application);
                                        Scopes         = response.Scopes;
                                        TokenExpiresAt = response.Expires;

                                        var __ = _connectTask.TrySetResultAsync(true);         //Signal the .Connect() call to complete
                                        await _rpcLogger.InfoAsync("Ready").ConfigureAwait(false);
                                    }
                                    catch (Exception ex)
                                    {
                                        await _rpcLogger.ErrorAsync($"Error handling {cmd}{(evnt.IsSpecified ? $" ({evnt})" : "")}", ex).ConfigureAwait(false);
                                        return;
                                    }
                                });
                        }
                        else
                        {
                            var _ = _connectTask.TrySetResultAsync(true);             //Signal the .Connect() call to complete
                            await _rpcLogger.InfoAsync("Ready").ConfigureAwait(false);
                        }
                    }
                    break;

                    //Channels
                    case "CHANNEL_CREATE":
                    {
                        await _rpcLogger.DebugAsync("Received Dispatch (CHANNEL_CREATE)").ConfigureAwait(false);

                        var data    = (payload.Value as JToken).ToObject <ChannelSummary>(_serializer);
                        var channel = RpcChannelSummary.Create(data);

                        await _channelCreatedEvent.InvokeAsync(channel).ConfigureAwait(false);
                    }
                    break;

                    //Guilds
                    case "GUILD_CREATE":
                    {
                        await _rpcLogger.DebugAsync("Received Dispatch (GUILD_CREATE)").ConfigureAwait(false);

                        var data  = (payload.Value as JToken).ToObject <GuildSummary>(_serializer);
                        var guild = RpcGuildSummary.Create(data);

                        await _guildCreatedEvent.InvokeAsync(guild).ConfigureAwait(false);
                    }
                    break;

                    case "GUILD_STATUS":
                    {
                        await _rpcLogger.DebugAsync("Received Dispatch (GUILD_STATUS)").ConfigureAwait(false);

                        var data        = (payload.Value as JToken).ToObject <GuildStatusEvent>(_serializer);
                        var guildStatus = RpcGuildStatus.Create(data);

                        await _guildStatusUpdatedEvent.InvokeAsync(guildStatus).ConfigureAwait(false);
                    }
                    break;

                    //Voice
                    case "VOICE_STATE_CREATE":
                    {
                        await _rpcLogger.DebugAsync("Received Dispatch (VOICE_STATE_CREATE)").ConfigureAwait(false);

                        var data       = (payload.Value as JToken).ToObject <ExtendedVoiceState>(_serializer);
                        var voiceState = RpcVoiceState.Create(this, data);

                        await _voiceStateCreatedEvent.InvokeAsync(voiceState).ConfigureAwait(false);
                    }
                    break;

                    case "VOICE_STATE_UPDATE":
                    {
                        await _rpcLogger.DebugAsync("Received Dispatch (VOICE_STATE_UPDATE)").ConfigureAwait(false);

                        var data       = (payload.Value as JToken).ToObject <ExtendedVoiceState>(_serializer);
                        var voiceState = RpcVoiceState.Create(this, data);

                        await _voiceStateUpdatedEvent.InvokeAsync(voiceState).ConfigureAwait(false);
                    }
                    break;

                    case "VOICE_STATE_DELETE":
                    {
                        await _rpcLogger.DebugAsync("Received Dispatch (VOICE_STATE_DELETE)").ConfigureAwait(false);

                        var data       = (payload.Value as JToken).ToObject <ExtendedVoiceState>(_serializer);
                        var voiceState = RpcVoiceState.Create(this, data);

                        await _voiceStateDeletedEvent.InvokeAsync(voiceState).ConfigureAwait(false);
                    }
                    break;

                    case "SPEAKING_START":
                    {
                        await _rpcLogger.DebugAsync("Received Dispatch (SPEAKING_START)").ConfigureAwait(false);

                        var data = (payload.Value as JToken).ToObject <SpeakingEvent>(_serializer);

                        await _speakingStartedEvent.InvokeAsync(data.UserId).ConfigureAwait(false);
                    }
                    break;

                    case "SPEAKING_STOP":
                    {
                        await _rpcLogger.DebugAsync("Received Dispatch (SPEAKING_STOP)").ConfigureAwait(false);

                        var data = (payload.Value as JToken).ToObject <SpeakingEvent>(_serializer);

                        await _speakingStoppedEvent.InvokeAsync(data.UserId).ConfigureAwait(false);
                    }
                    break;

                    case "VOICE_SETTINGS_UPDATE":
                    {
                        await _rpcLogger.DebugAsync("Received Dispatch (VOICE_SETTINGS_UPDATE)").ConfigureAwait(false);

                        var data     = (payload.Value as JToken).ToObject <API.Rpc.VoiceSettings>(_serializer);
                        var settings = VoiceSettings.Create(data);

                        await _voiceSettingsUpdated.InvokeAsync(settings).ConfigureAwait(false);
                    }
                    break;

                    //Messages
                    case "MESSAGE_CREATE":
                    {
                        await _rpcLogger.DebugAsync("Received Dispatch (MESSAGE_CREATE)").ConfigureAwait(false);

                        var data = (payload.Value as JToken).ToObject <MessageEvent>(_serializer);
                        var msg  = RpcMessage.Create(this, data.ChannelId, data.Message);

                        await _messageReceivedEvent.InvokeAsync(msg).ConfigureAwait(false);
                    }
                    break;

                    case "MESSAGE_UPDATE":
                    {
                        await _rpcLogger.DebugAsync("Received Dispatch (MESSAGE_UPDATE)").ConfigureAwait(false);

                        var data = (payload.Value as JToken).ToObject <MessageEvent>(_serializer);
                        var msg  = RpcMessage.Create(this, data.ChannelId, data.Message);

                        await _messageUpdatedEvent.InvokeAsync(msg).ConfigureAwait(false);
                    }
                    break;

                    case "MESSAGE_DELETE":
                    {
                        await _rpcLogger.DebugAsync("Received Dispatch (MESSAGE_DELETE)").ConfigureAwait(false);

                        var data = (payload.Value as JToken).ToObject <MessageEvent>(_serializer);

                        await _messageDeletedEvent.InvokeAsync(data.ChannelId, data.Message.Id).ConfigureAwait(false);
                    }
                    break;

                    //Others
                    default:
                        await _rpcLogger.WarningAsync($"Unknown Dispatch ({evnt})").ConfigureAwait(false);

                        return;
                    }
                    break;

                    /*default: //Other opcodes are used for command responses
                     *  await _rpcLogger.WarningAsync($"Unknown OpCode ({cmd})").ConfigureAwait(false);
                     *  return;*/
                }
            }
            catch (Exception ex)
            {
                await _rpcLogger.ErrorAsync($"Error handling {cmd}{(evnt.IsSpecified ? $" ({evnt})" : "")}", ex).ConfigureAwait(false);

                return;
            }
        }
Ejemplo n.º 15
0
        public async Task BotInfoAsync()
        {
            RestApplication application = await Context.Client.GetApplicationInfoAsync();

            EmbedBuilder eb = new EmbedBuilder()
            {
                Color       = new Discord.Color(51, 102, 153),
                Title       = "**__Bot Info__**",
                Description = ""
            };

            eb.AddField(x =>
            {
                x.Name     = "**Author**";
                x.Value    = $"{application.Owner.Username} (ID {application.Owner.Id})";
                x.IsInline = false;
            });
            eb.AddField(x =>
            {
                x.Name     = "**Version**";
                x.Value    = $"{Version.Number}";
                x.IsInline = true;
            });
            eb.AddField(x =>
            {
                x.Name     = "**Variant**";
                x.Value    = $"AzureDevops Build";
                x.IsInline = true;
            });
            eb.AddField(x =>
            {
                x.Name  = "**Libraries**";
                x.Value = "" +
                          $"Discord.Net ({DiscordConfig.Version})\n" +
                          $"TwitchLib.API {System.Reflection.Assembly.GetAssembly(typeof(TwitchLib.Api.TwitchAPI)).GetName().Version}\n" +
                          $"StrawPollNet {System.Reflection.Assembly.GetAssembly(typeof(StrawPollNET.API)).GetName().Version}\n" +
                          $"SteamStoreQuery {System.Reflection.Assembly.GetAssembly(typeof(SteamStoreQuery.Query)).GetName().Version}";
                x.IsInline = false;
            });
            eb.AddField(x =>
            {
                x.Name     = "**Runtime**";
                x.Value    = $"{RuntimeInformation.FrameworkDescription} {RuntimeInformation.OSArchitecture}";
                x.IsInline = true;
            });
            eb.AddField(x =>
            {
                x.Name  = "**Stats**";
                x.Value = "" +
                          $"Heap Size: {GetHeapSize()} MB\n" +
                          $"Latency: {Context.Client.Latency}ms\n";
                x.IsInline = true;
            });
            string guildsStr = "";

            foreach (SocketGuild guild in Context.Client.Guilds)
            {
                guildsStr += $"**{guild.Name}** ({guild.Id})\n" +
                             $"- Members ({guild.MemberCount})\n" +
                             $"- Owner = {guild.Owner}({guild.OwnerId})\n";
            }
            eb.AddField(x =>
            {
                x.Name     = "**Guilds**";
                x.Value    = $"{guildsStr}";
                x.IsInline = false;
            });
            eb.WithFooter(x =>
            {
                x.Text = $"Uptime: {GetUptime()}";
            });
            eb.WithCurrentTimestamp();
            await ReplyAsync("", embed : eb.Build());
        }