Esempio n. 1
0
 protected override void BeforeExecute(CommandInfo command)
 {
     dataContext = new WaitingListDataContext();
     waitingList = new CommandWaitingList(dataContext, Context.Client.Rest, Context.Guild.Id);
     guildData   = dataContext.GetOrCreateGuildData(Context.Guild) !;
     base.BeforeExecute(command);
 }
Esempio n. 2
0
        public override Task <PreconditionResult> CheckPermissionsAsync(ICommandContext context, CommandInfo command, IServiceProvider services)
        {
            var guild = context.Guild;

            if (guild != null)
            {
                using (var dataContext = new WaitingListDataContext())
                {
                    var guildData = dataContext.GetGuild(guild.Id);

                    if (allowRunningIfListIsActive == guildData?.IsEnabled)
                    {
                        return(Task.FromResult(PreconditionResult.FromSuccess()));
                    }
                    else
                    {
                        if (allowRunningIfListIsActive)
                        {
                            return(Task.FromResult(PreconditionResult.FromError("Cannot run this command if the waiting list is closed.")));
                        }
                        else
                        {
                            return(Task.FromResult(PreconditionResult.FromError("Cannot run this command if the waiting list is open.")));
                        }
                    }
                }
            }
            return(Task.FromResult(PreconditionResult.FromSuccess()));
        }
Esempio n. 3
0
        public CommandWaitingList(WaitingListDataContext dataContext, DiscordSocketRestClient restClient, ulong guildId)
        {
            this.dataContext = dataContext;
            this.restClient  = restClient;
            this.guildId     = guildId;

            this.guildData = dataContext.GetGuild(guildId) !;
        }
Esempio n. 4
0
        private async void CheckForTimeout(object?state)
        {
            if (timerRunning)
            {
                return;
            }
            timerRunning = true;
            try
            {
                using (var waitingListDataContext = new WaitingListDataContext())
                {
                    foreach (var invitedUser in waitingListDataContext.InvitedUsers
                             .Include(iu => iu.User).ThenInclude(iu => iu.Guild).Include(iu => iu.Invite).ToList())
                    {
                        if (invitedUser.InviteAccepted == null)
                        {
                            if (invitedUser.InviteTime + TimeSpan.FromMinutes(1) < DateTime.Now)
                            {
                                var guild = client.GetGuild(invitedUser.User.Guild.GuildId);
                                if (guild != null)
                                {
                                    var waitingList = new CommandWaitingList(waitingListDataContext !, client.Rest, guild.Id);

                                    try
                                    {
                                        await DeclineInviteAsync(client.Rest, guild, waitingList, invitedUser);

                                        var dmChannel = await(await client.Rest.GetUserAsync(invitedUser.User.UserId)).CreateDMChannelAsync();

                                        var message = await dmChannel.GetMessageAsync(invitedUser.DmQuestionMessageId);

                                        await message.DeleteAsync();

                                        await dmChannel.SendMessageAsync("Time ran out. Invite has been declined");
                                    }
                                    catch (Exception ex)
                                    {
                                        logger.LogError("Error declining invite", ex);
                                    }

                                    waitingListDataContext.Update(invitedUser);

                                    waitingListDataContext.SaveChanges();

                                    await CommandWaitingListModule.UpdateInviteMessageAsync(guild, invitedUser.Invite);
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "Timeout timer failed to run");
            }
            timerRunning = false;
        }
Esempio n. 5
0
        public Worker(ILogger <Worker> logger)
        {
            var config = new DiscordSocketConfig
            {
                GatewayIntents = GatewayIntents.Guilds | GatewayIntents.GuildMembers | GatewayIntents.GuildMessages
                                 | GatewayIntents.GuildMessageReactions | GatewayIntents.DirectMessages | GatewayIntents.DirectMessageReactions,
                AlwaysDownloadUsers           = true,
                AlwaysAcknowledgeInteractions = false
            };

            client = new DiscordSocketClient(config);

            client.Log += Log;
            client.GuildMemberUpdated += GuildMemberUpdated;
            client.GuildUpdated       += Client_GuildUpdated;
            client.GuildAvailable     += Client_GuildAvailable;
            client.InteractionCreated += Client_InteractionCreated;

            //#if DEBUG
            //            token = File.ReadAllText("token-dev.txt");
            //#else
            //            token = File.ReadAllText("token.txt");
            //#endif
            token = File.ReadAllText("token.txt");

            // Commands are not thread safe. So set the run mode to sync
            var commandService = new CommandService(new CommandServiceConfig {
                DefaultRunMode = RunMode.Sync, LogLevel = LogSeverity.Info
            });

            serviceCollection = new ServiceCollection();
            serviceCollection.AddSingleton(typeof(CommandService), commandService);
            serviceCollection.AddDbContext <WaitingListDataContext>();
            serviceCollection.AddLogging(b =>
            {
                b.AddConsole();
                b.AddEventSourceLogger();
            });

            using (var waitingListDataContext = new WaitingListDataContext())
            {
                waitingListDataContext.Database.Migrate();
            }

            handler     = new CommandHandler(client, commandService, serviceCollection.BuildServiceProvider());
            this.logger = logger;

            DMTimeout = new Timer(CheckForTimeout, null, 0, 1000);
        }
Esempio n. 6
0
 public GuildController()
 {
     dataContext = new WaitingListDataContext();
 }
Esempio n. 7
0
        private async Task HandleCommandAsync(SocketMessage messageParam)
        {
            // Don't process the command if it was a system message
            if (messageParam is not SocketUserMessage message)
            {
                return;
            }

            if (message.Author.IsBot)
            {
                return;
            }

            var guild = (message.Channel as SocketTextChannel)?.Guild;

            if (guild == null)
            {
                await messageParam.Channel.SendMessageAsync("Sorry I dont work in private messages!");

                return;
            }

            // Create a number to track where the prefix ends and the command begins
            int argPos = 0;

            using (var dataContext = new WaitingListDataContext())
            {
                var guildData = dataContext !.GetOrCreateGuildData(guild);

                var channel = message.Channel;

                // Only allow mods to issue commands
                var guildUser = message.Author as IGuildUser;
                if (!ModPermissionAttribute.HasModPermission(guildUser).IsSuccess)
                {
                    return;
                }

                // Determine if the message is a command based on the prefix and make sure no bots trigger commands
                if (!(message.HasStringPrefix(guildData?.CommandPrefix, ref argPos) ||
                      message.HasMentionPrefix(_client.CurrentUser, ref argPos)))
                {
                    return;
                }
            }
            // Create a WebSocket-based command context based on the message
            var context = new SocketCommandContext(_client, message);

            // Execute the command with the command context we just
            // created, along with the service provider for precondition checks.
            var result = await _commands.ExecuteAsync(
                context : context,
                argPos : argPos,
                services : _services);

            if (!result.IsSuccess)
            {
                if (result.Error != CommandError.UnknownCommand)
                {
                    await messageParam.Channel.SendMessageAsync("Could not complete command: " + result.ErrorReason);

                    var logger = (ILogger)_services.GetService(typeof(ILogger));

                    logger.LogError(result.ErrorReason);
                }
            }
        }
Esempio n. 8
0
        private async Task Client_InteractionCreated(SocketInteraction arg)
        {
            try
            {
                using (var waitingListDataContext = new WaitingListDataContext())
                {
                    if (arg.Type == InteractionType.MessageComponent)
                    {
                        var parsedArg = (SocketMessageComponent)arg;

                        var customId = parsedArg.Data.CustomId;

                        var guild = (parsedArg.Channel as IGuildChannel)?.Guild;


                        var guildData = guild != null?waitingListDataContext.GetGuild(guild.Id) : null;

                        var waitingList = guild != null ? new CommandWaitingList(waitingListDataContext, client.Rest, guild.Id) : null;

                        if (arg.User.IsBot)
                        {
                            return;
                        }
                        if (parsedArg.Message.Id == guildData?.PublicMessageId)
                        {
                            if (guild == null || guildData == null)
                            {
                                logger.LogCritical("Guild or guildData was null in InteractionCreated");
                                return;
                            }
                            if (customId == "join")
                            {
                                if ((await waitingList !.AddUserAsync((IGuildUser)parsedArg.User)).Success)
                                {
                                    // await parsedArg.RespondAsync("Joined Waiting list.", ephemeral: true);
                                }
                                else
                                {
                                    // await arg.RespondAsync("Failed");
                                    logger.LogError("Failed to join " + parsedArg.User);
                                }
                            }
                            else if (customId == "leave")
                            {
                                await waitingList !.RemoveUserAsync(parsedArg.User.Id);
                                //await parsedArg.RespondAsync("Left waiting list.", ephemeral: true);
                            }

                            waitingListDataContext.SaveChanges();
                            guildData = waitingListDataContext.GetGuild(guild.Id);

                            await ButtonWaitingListModule.UpdatePublicMessageAsync(waitingList !, guild !, guildData);

                            await parsedArg.AcknowledgeAsync();
                        }
                        else
                        {
                            if (customId == "unpause")
                            {
                                guildData !.IsPaused = false;
                                waitingListDataContext.Update(guildData);
                                waitingListDataContext.SaveChanges();

                                await ButtonWaitingListModule.UpdatePublicMessageAsync(waitingList, guild !, guildData);

                                await parsedArg.AcknowledgeAsync();

                                await parsedArg.Message.DeleteAsync();
                            }
                            else if (customId == "clearcounters")
                            {
                                foreach (var user in guildData !.UsersInGuild)
                                {
                                    user.PlayCount = 0;
                                    waitingListDataContext.Update(user);
                                }
                                waitingListDataContext.SaveChanges();

                                await ButtonWaitingListModule.UpdatePublicMessageAsync(waitingList !, guild !, guildData);

                                await parsedArg.RespondAsync("Counters have been cleared");
                            }
                            else if (customId.StartsWith("joinYes") || customId.StartsWith("joinNo"))
                            {
                                var parts = customId.Split(new[] { ';' }, 2);

                                var inviteId = int.Parse(parts[1]);

                                var invite = waitingListDataContext.Invites.Include(i => i.Guild).Include(i => i.InvitedUsers).ThenInclude(iu => iu.User).Single(i => i.Id == inviteId);

                                var invitedUser = invite.InvitedUsers.Last(x => x.User.UserId == parsedArg.User.Id);

                                guildData   = invite.Guild;
                                waitingList = new CommandWaitingList(waitingListDataContext !, client.Rest, guildData.GuildId);

                                guild = client.GetGuild(guildData.GuildId);

                                if (invitedUser.InviteAccepted != null)
                                {
                                    return;
                                }

                                if (parts[0] == "joinYes")
                                {
                                    await parsedArg.Message.DeleteAsync();

                                    await parsedArg.Channel.SendMessageAsync(string.Format(guildData.DMMessageFormat, invite.FormatData));

                                    invitedUser.InviteAccepted = true;
                                    waitingListDataContext.Update(invitedUser);
                                    waitingListDataContext.SaveChanges();
                                    await CommandWaitingListModule.UpdateInviteMessageAsync(guild, invite);
                                }
                                else
                                {
                                    await parsedArg.Message.DeleteAsync();

                                    await parsedArg.Channel.SendMessageAsync("Invite has been declined");
                                    await DeclineInviteAsync(client.Rest, guild, waitingList, invitedUser);

                                    waitingListDataContext.Update(invitedUser);
                                    waitingListDataContext.SaveChanges();
                                    await CommandWaitingListModule.UpdateInviteMessageAsync(guild, invite);
                                }
                            }
                        }
                    }
                }
            }