Esempio n. 1
0
        public async Task <IUser> GetOwnerAsync(int segmentId)
        {
            var segment = await _botContext.Segments.Include(s => s.User).FirstAsync(s => s.SegmentId == segmentId).ConfigureAwait(false);

            var discordUserId = segment.User.DiscordUserId;

            return(await _client.GetUserAsync((ulong)discordUserId).ConfigureAwait(false));
        }
Esempio n. 2
0
        /// <summary>
        /// If this poll is being retreived from the database, please make a call to LOAD it.
        /// This will populate the actual values for channel/message.
        /// </summary>
        /// <param name="Client"></param>
        /// <returns></returns>
        public async Task LoadEntity(IDiscordClient Client)
        {
            this.channel = await Client.GetChannelAsync(this.ChannelId, CacheMode.AllowDownload) as ITextChannel;

            this.message = await channel.GetMessageAsync(this.MessageId, CacheMode.AllowDownload) as IUserMessage;

            //Populate the users.
            foreach (var vote in Votes)
            {
                vote.User = await Client.GetUserAsync(vote.UserId);
            }
        }
Esempio n. 3
0
        public static async Task <bool> TryDMAsync(this ulong userId, IDiscordClient client, string description, string title = null, Color color = default(Color))
        {
            var user = await client.GetUserAsync(userId);

            if (user == null)
            {
                return(false);
            }
            else
            {
                return(await user.TryDMAsync(description, title, color));
            }
        }
Esempio n. 4
0
        public static async Task <InhouseQueue> GetQueueAsync(ulong channelId, string name, IDiscordClient channel, LiteCollection <InhouseQueue> collection)
        {
            var queue = collection.FindOne(g => g.ChannelId == channelId && g.Name == name);

            if (queue == null)
            {
                return(null);
            }

            foreach (var u in queue.Players.Values)
            {
                u.DiscordUser = await channel.GetUserAsync(u.Id);
            }

            return(queue);
        }
Esempio n. 5
0
        public static async Task <Game> GetGameAsync(ulong id, IDiscordClient channel, ILiteCollection <Game> collection)
        {
            var game = collection.FindOne(g => g.Id == id);

            if (game == null)
            {
                throw new KeyNotFoundException();
            }

            foreach (var u in game.Players.Values)
            {
                u.DiscordUser = await channel.GetUserAsync(u.Id);
            }

            return(game);
        }
Esempio n. 6
0
        public async Task <bool> LoadAdminsAsync()
        {
            if (!File.Exists(_FILE))
            {
                Message = "No admin file found.";
                Console.WriteLine(Message);
                return(false);
            }

            Task <string[]> lines = File.ReadAllLinesAsync(_FILE);
            Regex           regex = new Regex(_PATTERN, RegexOptions.Compiled);
            string          username;
            string          discriminator;
            var             missingUsers = new List <User>();

            foreach (string line in await lines)
            {
                if (!line.StartsWith(_COMMENT))
                {
                    var match = regex.Matches(line);
                    if (match.Count == 1)
                    {
                        username      = match[0].Groups[1].Value;
                        discriminator = match[0].Groups[2].Value;

                        var user = await _client.GetUserAsync(username, discriminator);

                        if (user != null)
                        {
                            _admins.Add(new User(user));
                        }
                        else
                        {
                            missingUsers.Add(new User(user));
                        }
                    }
                }
            }

            Message = "Admin list loaded.";
            if (missingUsers.Count > 0)
            {
                string missingStr = String.Join(", ", missingUsers.Select(x => x.Username).ToArray());
                Message += $" (Could not find {missingStr})";
            }
            return(true);
        }
Esempio n. 7
0
        public async Task <IEntry <DiscordContact> > FetchAsync(ulong id)
        {
            var user = await _client.GetUserAsync(id);

            if (user is null)
            {
                throw new ContactNotFoundException <DiscordContact>(null);
            }

            return(_entryFactory.Create(
                       new DiscordContact(
                           user.Id,
                           user.Username,
                           user.Discriminator,
                           null
                           )
                       ));
        }
Esempio n. 8
0
        public async Task Handle(AnswerAddedToQuestionEvent notification, CancellationToken cancellationToken)
        {
            var question = await _dbContext.Questions
                           .FirstOrDefaultAsync(x => x.Id == notification.QuestionId, cancellationToken);

            if (question is null)
            {
                return;
            }

            var user = await _client.GetUserAsync(question.UserId);

            var dmChannel = await user.GetOrCreateDMChannelAsync();

            await dmChannel.SendMessageAsync(embed : new EmbedBuilder()
                                             .WithDescription($"Danke. Deine Antwort zu `{question}` wurde in die Wissensdatenbank aufgenommen.")
                                             .WithColor(Color.Green)
                                             .Build());
        }
Esempio n. 9
0
        private async Task <string> CreateSystemNotFoundError(Context ctx)
        {
            var input = ctx.PopArgument();

            if (input.TryParseMention(out var id))
            {
                // Try to resolve the user ID to find the associated account,
                // so we can print their username.
                var user = await _client.GetUserAsync(id);

                // Print descriptive errors based on whether we found the user or not.
                if (user == null)
                {
                    return($"Account with ID `{id}` not found.");
                }
                return($"Account **{user.Username}#{user.Discriminator}** does not have a system registered.");
            }

            return($"System with ID `{input}` not found.");
        }
Esempio n. 10
0
        async Task <TypeReaderResult> FindSystemByAccountHelper(ulong id, IDiscordClient client, SystemStore systems)
        {
            var foundByAccountId = await systems.GetByAccount(id);

            if (foundByAccountId != null)
            {
                return(TypeReaderResult.FromSuccess(foundByAccountId));
            }

            // We didn't find any, so we try to resolve the user ID to find the associated account,
            // so we can print their username.
            var user = await client.GetUserAsync(id);

            // Return descriptive errors based on whether we found the user or not.
            if (user == null)
            {
                return(TypeReaderResult.FromError(CommandError.ObjectNotFound, $"System or account with ID `{id}` not found."));
            }
            return(TypeReaderResult.FromError(CommandError.ObjectNotFound, $"Account **{user.Username}#{user.Discriminator}** not found."));
        }
Esempio n. 11
0
        public async Task <Embed> CreateSystemEmbed(PKSystem system)
        {
            var accounts = await _data.GetSystemAccounts(system);

            // Fetch/render info for all accounts simultaneously
            var users = await Task.WhenAll(accounts.Select(async uid => (await _client.GetUserAsync(uid))?.NameAndMention() ?? $"(deleted account {uid})"));

            var memberCount = await _data.GetSystemMemberCount(system);

            var eb = new EmbedBuilder()
                     .WithColor(Color.Blue)
                     .WithTitle(system.Name ?? null)
                     .WithThumbnailUrl(system.AvatarUrl ?? null)
                     .WithFooter($"System ID: {system.Hid} | Created on {Formats.ZonedDateTimeFormat.Format(system.Created.InZone(system.Zone))}");

            var latestSwitch = await _data.GetLatestSwitch(system);

            if (latestSwitch != null)
            {
                var switchMembers = (await _data.GetSwitchMembers(latestSwitch)).ToList();
                if (switchMembers.Count > 0)
                {
                    eb.AddField("Fronter".ToQuantity(switchMembers.Count(), ShowQuantityAs.None),
                                string.Join(", ", switchMembers.Select(m => m.Name)));
                }
            }

            if (system.Tag != null)
            {
                eb.AddField("Tag", system.Tag);
            }
            eb.AddField("Linked accounts", string.Join(", ", users).Truncate(1000), true);
            eb.AddField($"Members ({memberCount})", $"(see `pk;system {system.Hid} list` or `pk;system {system.Hid} list full`)", true);

            if (system.Description != null)
            {
                eb.AddField("Description", system.Description.Truncate(1024), false);
            }

            return(eb.Build());
        }
Esempio n. 12
0
        async Task SendAsync(IDiscordClient client, DbNotification notification)
        {
            var recipient = await client.GetUserAsync(notification.User.DiscordUserId ?? 0);

            if (recipient == null)
            {
                _logger.LogWarning($"No recipient user {notification.User.DiscordUserId?.ToString() ?? "<null>"} found.");
                return;
            }

            string fixUrl(string url)
            => Uri.TryCreate(_defaultBaseUri, url, out var uri) ? uri.AbsoluteUri : null;

            await recipient.SendMessageAsync("", embed : new EmbedBuilder
            {
                ThumbnailUrl = fixUrl(notification.Icon),
                Title        = notification.Title,
                Description  = notification.Description,
                Url          = fixUrl(notification.Url),
                Color        = uint.TryParse(notification.Color?.TrimStart('#'), NumberStyles.HexNumber, null, out var c) ? new Color(c) : null as Color?
            }.Build());
Esempio n. 13
0
        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            while (!stoppingToken.IsCancellationRequested)
            {
                try
                {
                    using var scope           = _serviceProvider.CreateScope();
                    await using var dbContext = scope.ServiceProvider.GetRequiredService <FaqDbContext>();

                    var questions = await GetDanglingQuestionsAsync(dbContext, stoppingToken);

                    foreach (var question in questions)
                    {
                        try
                        {
                            var user = await _client.GetUserAsync(question.UserId);

                            if (user is null)
                            {
                                continue;
                            }

                            await SendReminderDirectMessageAsync(user, question);
                        }
                        catch (Exception ex)
                        {
                            _logger.LogError(ex, "Couldn't send reminder DM to user {UserId}", question.UserId);
                        }
                    }

                    await _mediator.Publish(new ReminderSentEvent(questions.Select(x => x.Id)), stoppingToken);
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, "Couldn't send pending reminders. Trying again later...");
                }

                await Task.Delay(TimeSpan.FromHours(1), stoppingToken);
            }
        }
Esempio n. 14
0
        private async Task HandleAdventureResultAsync(Cat cat, AdventureEntry adventureEntry)
        {
            var adventure = _adventureRepository.FindByAdventureRef(adventureEntry.AdventureRef);

            var owner = await _ownerRepository.FindAsync(cat.OwnerId);

            var reward = adventure.GetReward();
            var item   = await _itemRepository.FindByItemRefAsync(reward.ItemRef);

            cat.ApplyStatModifiers(adventure.StatGain);
            owner.GiveItem(reward.ItemRef, reward.Quantity);

            var user = await _discordClient.GetUserAsync(Convert.ToUInt64(owner.AuthorId));

            var guild = ((DiscordSocketClient)_discordClient).Guilds.FirstOrDefault(i => i.Users.Any(j => j.Id == user.Id));

            // TODO: For now we select the default channel. Replace with configurable channel
            var channel = guild.GetTextChannel(guild.DefaultChannel.Id);

            var embed = CatSheet.GetRewardSheet(owner, cat, adventure, item, reward);
            await channel.SendMessageAsync(string.Empty, embed : embed);

            ////await channel.SendMessageAsync($"{cat.Name} got {reward.Quantity} {item.Name}!");
        }
Esempio n. 15
0
 /// <inheritdoc />
 public async ValueTask <IDiscordUser> GetUserAsync()
 {
     return(await client.GetUserAsync(packet.UserId));
 }