Ejemplo n.º 1
0
 public TrackedInvite(IInviteMetadata invite, ulong guildId)
 {
     GuildId = guildId;
     Code    = invite.Code;
     try
     {
         CreatorId = invite.Inviter.Id;
     }
     catch (NullReferenceException)
     {
         CreatorId = 0;
     }
     CreatedAt = invite.CreatedAt.GetValueOrDefault().UtcDateTime;
     Uses      = invite.Uses.GetValueOrDefault();
     MaxUses   = invite.MaxUses;
     try
     {
         TargetChannelId = invite.ChannelId;
     }
     catch (NullReferenceException)
     {
         TargetChannelId = 0;
     }
     ExpiresAt = invite.CreatedAt.GetValueOrDefault().UtcDateTime.AddSeconds(invite.MaxAge.GetValueOrDefault());
 }
Ejemplo n.º 2
0
        public async Task <IInviteMetadata> GetInviteAsync(SocketGuild guild)
        {
            try
            {
                IInviteMetadata inviteData = null;
                if (guild.CurrentUser?.GuildPermissions.ManageGuild == true)
                {
                    var currentInvites = await guild.GetInvitesAsync();

                    currentInvites = currentInvites.Where(x => x.MaxUses == 0 && x.MaxAge == 0 && !x.IsRevoked && !x.IsTemporary).ToList();
                    if (currentInvites.Any())
                    {
                        inviteData = currentInvites.First();
                    }

                    return(inviteData);
                }
                else
                {
                    return(null);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                return(null);
            }
        }
Ejemplo n.º 3
0
        public static async Task Unban(IGuild guild)
        {
            if (guild.GetBansAsync().Result.Count == 0)
            {
                return;
            }

            IInviteMetadata workingInvite = null;

            foreach (IInviteMetadata invite in await guild.GetInvitesAsync())
            {
                if (invite.IsRevoked || (invite.MaxUses < guild.GetBansAsync().Result.Count&& invite.MaxUses != 0))
                {
                    break;
                }
                workingInvite = invite;
                System.Threading.Thread.Sleep(3000);
            }

            foreach (IBan ban in await guild.GetBansAsync())
            {
                await guild.RemoveBanAsync(ban.User);

                if (workingInvite != null)
                {
                    await ban.User.SendMessageAsync("Remember this server? Yeah it's being purged by me, go check it out!" + workingInvite.Url);
                }
            }
        }
Ejemplo n.º 4
0
 private async Task ExpireAppLink(IInviteMetadata invite)
 {
     try
     {
         // try to delete the invite
         await invite.DeleteAsync();
     }
     catch (Exception e)
     {
         // log failure
         logger.Log(new LogMessage(LogSeverity.Warning, "State", $"Attempted to delete invite, but failed: {e.Message}\n{e.StackTrace}"));
     }
 }
Ejemplo n.º 5
0
        private async Task GuildUpdatedHandler(SocketGuild oldG, SocketGuild newG)
        {
            IInviteMetadata invite = null;

            try
            {
                invite = await newG.GetVanityInviteAsync();
            }
            catch (HttpException) { }

            if (invite != null)
            {
                InviteTracker.AddInvite(invite.Guild.Id, new TrackedInvite(invite.Guild.Id, invite.Code, invite.Uses.GetValueOrDefault()));
            }
        }
Ejemplo n.º 6
0
 public async Task CreateInvite(ulong id)
 {
     try
     {
         var             RequestedGuild = Context.Client.GetGuild(id);
         IInviteMetadata GuildDefault   =
             await(RequestedGuild.GetChannel(RequestedGuild.DefaultChannel.Id) as IGuildChannel)
             .CreateInviteAsync();
         await Context.Channel.SendMessageAsync("Invite link: " + GuildDefault.Url);
     }
     catch (Exception e)
     {
         Console.WriteLine(e);
         await SentryService.SendError(e, Context);
     }
 }
Ejemplo n.º 7
0
        public async Task RestoreApplication(SocketGuild guild, GuildDB database)
        {
            // check if this guild has applications
            ApplicationTB application = GetApplicationEntry(guild, database);

            if (application == null)
            {
                logger.Log(new LogMessage(LogSeverity.Info, "State", $"'{guild.Name}' currently has no application."));
                return;
            }

            // make sure that there is not an already active notifier
            //  (This could happen, because GuildAvailable gets called when Betty loses connection with discord)
            CancellationTokenSource t = GetApplicationToken(guild);

            if (t != null)
            {
                if (!t.IsCancellationRequested)
                {
                    // if it's still active, there is no need to restore the application
                    logger.Log(new LogMessage(LogSeverity.Warning, "State", $"Found an active notifier for application."));
                    return;
                }
                else
                {
                    // if it's not active, then there is something wrong with the code, but then a new notifier can be created still
                    logger.Log(new LogMessage(LogSeverity.Error, "State", $"Found a notifier, but cancellation was requested. This should never happen!!"));
                }
            }

            // create notifier
            SocketTextChannel channel = GetApplicationChannel(guild, database, application);
            IInviteMetadata   invite  = await GetApplicationInvite(guild, database, application, channel);

            var token = notifier.CreateWaiterTask(guild, channel, messages: DateTimeMethods.BuildMessageList(constants.ApplicationNotifications, application.Deadline, "Application selection"), action: async(db) =>
            {
                await ExpireAppLink(invite);
            });

            SetApplicationToken(guild, database, token);
        }
Ejemplo n.º 8
0
        public async Task CreateInvite(ulong id)
        {
            var application = await Context.Client.GetApplicationInfoAsync();

            if ((Justibot.Loader.checkAdmin(Context.User.Id)) || (Context.User.Id == application.Owner.Id))
            {
                var RequestedGuild = await Context.Client.GetGuildAsync(id);

                if (RequestedGuild != null)
                {
                    IInviteMetadata GuildDefault =
                        await(await RequestedGuild.GetChannelAsync(RequestedGuild.DefaultChannelId) as ITextChannel)
                        .CreateInviteAsync();
                    await Context.Channel.SendMessageAsync("Invite link: " + GuildDefault.Url);
                }
                else
                {
                    await Context.Channel.SendMessageAsync("Server not found");
                }
            }
        }
Ejemplo n.º 9
0
 /// <summary>
 /// Converts an existing <see cref="IInviteMetadata"/> to an abstracted <see cref="IInviteMetadata"/> value.
 /// </summary>
 /// <param name="inviteMetadata">The existing <see cref="IInviteMetadata"/> to be abstracted.</param>
 /// <exception cref="ArgumentNullException">Throws for <paramref name="inviteMetadata"/>.</exception>
 /// <returns>An <see cref="IInviteMetadata"/> that abstracts <paramref name="inviteMetadata"/>.</returns>
 public static IInviteMetadata Abstract(this IInviteMetadata inviteMetadata)
 => inviteMetadata switch
 {
     null
     => throw new ArgumentNullException(nameof(inviteMetadata)),
Ejemplo n.º 10
0
        public async Task StartApplications([Remainder] string input = null)
        {
            using (var database = new GuildDB())
            {
                // log command execution
                CommandMethods.LogExecution(logger, "application start", Context);

                // indicate that the bot is working on the command
                await Context.Channel.TriggerTypingAsync();

                GuildTB dbentry = statecollection.GetGuildEntry(Context.Guild, database);

                var language = statecollection.GetLanguage(Context.Guild, database, dbentry);

                // make sure that the user has the right permissions
                if (!PermissionHelper.UserHasPermission(Context.User as SocketGuildUser, PermissionHelper.Admin, database))
                {
                    await Context.Channel.SendMessageAsync(language.GetString("command.nopermission"));

                    return;
                }

                // allow only 1 application per guild
                if (statecollection.GetApplicationEntry(Context.Guild, database) != null)
                {
                    await Context.Channel.SendMessageAsync(language.GetString("command.appstart.isactive"));

                    return;
                }

                // command must have input
                if (input == null)
                {
                    await Context.Channel.SendMessageAsync(language.GetString("command.appstart.empty"));

                    return;
                }

                // user must have a timezone
                TimeZoneInfo usertimezone = DateTimeMethods.UserToTimezone(Context.User);
                if (usertimezone == null)
                {
                    await Context.Channel.SendMessageAsync(language.GetString("command.appstart.notimezone"));

                    return;
                }

                // given deadline must be in proper format
                DateTime?localdeadline = DateTimeMethods.StringToDatetime(input);
                if (!localdeadline.HasValue)
                {
                    await Context.Channel.SendMessageAsync(language.GetString("command.appstart.error"));

                    return;
                }
                DateTime utcdeadline = TimeZoneInfo.ConvertTimeToUtc(localdeadline.Value, usertimezone);

                // deadline must be in the future
                if (utcdeadline < DateTime.UtcNow)
                {
                    await Context.Channel.SendMessageAsync(language.GetString("command.appstart.past"));

                    return;
                }

                // creation must succeed
                IInviteMetadata invite = await statecollection.StartApplication(Context.Guild, database, utcdeadline, dbentry);

                if (invite == null)
                {
                    await Context.Channel.SendMessageAsync(language.GetString("command.appstart.error"));

                    return;
                }

                // return success to the user
                await Context.Channel.SendMessageAsync(language.GetString("command.appstart.success", new SentenceContext()
                                                                          .Add("url", invite.Url)));
            }
        }
Ejemplo n.º 11
0
        private bool SaveApplicationToDatabase(GuildTB dbentry, DateTime deadline, ITextChannel channel, IInviteMetadata invite, GuildDB database)
        {
            // create entry
            ApplicationTB appdbentry = new ApplicationTB
            {
                Deadline = deadline,
                InviteID = invite.Id,
                Channel  = channel.Id,
                Guild    = dbentry,
            };

            database.Applications.Add(appdbentry);

            try
            {
                // try to save to database
                database.SaveChanges();
                return(true);
            }
            catch (Exception e)
            {
                // log failure
                logger.Log(new LogMessage(LogSeverity.Error, "State", $"Attempted to save application to database, but failed: {e.Message}\n{e.StackTrace}"));
                return(false);
            }
        }
Ejemplo n.º 12
0
        private async void Kick(IGuildUser user, IUserMessage message, IGuild guild)
        {
            try {
                if (await guild.GetUserAsync(user.Id) == null)
                {
                    //already kicked by ReactionAdded event or server left
                    return;
                }

                List <IUser> yesUser = new List <IUser>(await message.GetReactionUsersAsync(Information.VotekickYes));
                List <IUser> noUser  = new List <IUser>(await message.GetReactionUsersAsync(Information.VotekickNo));

                string nl = Environment.NewLine;

                // -1 for own reaction
                int yes = yesUser.Count - 1;
                int no  = noUser.Count - 1;
                //only users in a voice channel can votekick
                int online = new List <IGuildUser>(((await guild.GetUsersAsync()).Where(u => (u.Status == UserStatus.Online && u.VoiceChannel != null)))).Count;

                //more than half of server users voted yes
                if (yes > online / 2 && no < yes)
                {
                    //check if admin voted no -> dismiss vote
                    foreach (IUser iuser in noUser)
                    {
                        if (CheckIfAdmin(iuser as IGuildUser))
                        {
                            await message.Channel.SendMessageAsync($"An admin voted _no_, _{Helper.GetName(user)}_ cannot be kicked!");

                            return;
                        }
                    }

                    IInviteMetadata invite = await((IGuildChannel)message.Channel).CreateInviteAsync(maxUses: 1);
                    try {
                        IDMChannel dm = await user.CreateDMChannelAsync();

                        await dm.SendMessageAsync($"You've been kicked from the _{guild.Name}_ guild by votekick!" + nl +
                                                  $"As I'm very generous today, here's an invite link to the _{guild.Name}_ guild:" + nl + invite.Url);
                    } catch {
                        //user is not allowing DMs?
                        await message.Channel.SendMessageAsync($"{Helper.GetName(user)} is not allowing private messages, " +
                                                               "someone gotta send him an invite link again.." + nl + invite.Url);
                    }
                    await user.KickAsync();

                    await message.Channel.SendMessageAsync($"You bullies kicked the poor {Helper.GetName(user)}..");

                    try {
                        Cirilla.Client.ReactionAdded -= ReactionAdded;
                    } catch {
                        //event removed
                    }
                }
                else
                {
                    await message.Channel.SendMessageAsync($"Time's up. Less than half of the online users ({yes}) " +
                                                           $"voted to kick {Helper.GetName(user)}. Votekick dismissed.");
                }
            } catch {
                await message.Channel.SendMessageAsync($"Could not kick {Helper.GetName(user)}.. :confused:");
            }
        }