コード例 #1
0
ファイル: ProfileCommand.cs プロジェクト: TheDarkCode/BusVbot
        public override async Task HandleAsync(
            IUpdateContext context,
            UpdateDelegate next,
            string[] args,
            CancellationToken cancellationToken
            )
        {
            if (args.Any() && args[0].Equals("remove", StringComparison.OrdinalIgnoreCase))
            {
                _logger.LogTrace(@"Removing user profile upon a ""/profile remove"" command.");

                await context.Bot.Client.SendTextMessageAsync(
                    context.Update.Message.Chat,
                    $"{context.Update.Message.From.FirstName}, You are about to remove your profile. " +
                    "Sadly, I won't remember much of our conversations after the removal.😟\n\n" +
                    "*Are you sure you want to remove your profile?* Reply to this message with the text `forget me`.",
                    ParseMode.Markdown,
                    replyMarkup : new ForceReplyMarkup(),
                    cancellationToken : cancellationToken
                    );
            }
            else
            {
                _logger.LogTrace(@"Showing the user his profile upon the ""/profile"" command.");
                var profile = context.GetUserProfile();

                var agency = await _agencyRepo.GetByTagAsync(profile.DefaultAgencyTag, cancellationToken)
                             .ConfigureAwait(false);

                if (agency != null)
                {
                    await context.Bot.Client.SendTextMessageAsync(
                        context.Update.Message.Chat,
                        $"Hey {context.Update.Message.From.FirstName}\n" +
                        $"Your default transit agency is set to *{agency.Title}* " +
                        $"in {agency.Region}, {agency.Country}.\n\n" +
                        "💡 *Pro Tip*: You can remove your profile from my memory by sending " +
                        "the `/profile remove` message.",
                        ParseMode.Markdown,
                        cancellationToken : cancellationToken
                        ).ConfigureAwait(false);
                }
                else
                {
                    _logger.LogError(
                        "User has the agency {0} on his profile but the agency is not found in the database.",
                        profile.DefaultAgencyTag
                        );

                    // ToDo clear the profile
                }
            }
        }
コード例 #2
0
ファイル: DataSeeder.cs プロジェクト: TheDarkCode/BusVbot
        /// <inheritdoc />
        public async Task SeedAgenciesAsync(
            CancellationToken cancellationToken = default
            )
        {
            var nextbusResponse = await GetNextBusPolicy()
                                  .ExecuteAsync(_ => _nextbusClient.GetAgencies(), cancellationToken)
                                  .ConfigureAwait(false);

            var nextbusAgencies = nextbusResponse.ToArray();

            _logger.LogInformation("{0} agencies are loaded from NextBus", nextbusAgencies.Length);

            for (int i = 0; i < nextbusAgencies.Length; i++)
            {
                var nextbusAgency = nextbusAgencies[i];

                if (nextbusAgency.Tag != "ttc")
                {
                    continue;
                }

                var mongoAgency = await _agencyRepo.GetByTagAsync(nextbusAgency.Tag, cancellationToken)
                                  .ConfigureAwait(false);

                if (mongoAgency == null)
                {
                    _logger.LogInformation("Inserting agency {0} ({1})", nextbusAgency.Title, nextbusAgency.Tag);

                    mongoAgency = Converter.FromNextBusAgency(nextbusAgency);

                    // ToDo find a better way to assign countries
                    if (new[] { "Quebec", "Ontario" }.Contains(mongoAgency.Region))
                    {
                        mongoAgency.Country = "Canada";
                    }
                    else if (mongoAgency.Region == "Other")
                    {
                        mongoAgency.Country = "Test";
                    }
                    else
                    {
                        mongoAgency.Country = "USA";
                    }

                    await _agencyRepo.AddAsync(mongoAgency, cancellationToken)
                    .ConfigureAwait(false);
                }
                else
                {
                    _logger.LogDebug("Agency {0} already exists", nextbusAgency.Tag);
                }

                var boundaries = await UpdateRoutesForAgencyAsync(nextbusAgency.Tag, cancellationToken)
                                 .ConfigureAwait(false);

                // ToDo first, check if update is really required

                mongoAgency.MinLatitude  = boundaries.MinLat;
                mongoAgency.MaxLatitude  = boundaries.MaxLat;
                mongoAgency.MinLongitude = boundaries.MinLon;
                mongoAgency.MaxLongitude = boundaries.MaxLon;
                await _agencyRepo.UpdateAsync(mongoAgency, cancellationToken)
                .ConfigureAwait(false);

                // ToDo update max/min lat/lon for agency
            }
        }
コード例 #3
0
        public async Task HandleAsync(IUpdateContext context, UpdateDelegate next, CancellationToken cancellationToken)
        {
            string queryData = context.Update.CallbackQuery.Data;

            // ToDo if user already has profile set, ignore this. check if "instructions sent" is set in cache
            // if (await _userContextManager.TryReplyIfOldSetupInstructionMessageAsync(bot, update)) return;

            if (queryData.StartsWith("ups/a:"))
            {
                _logger.LogTrace("Setting the agency for user");

                var userchat = context.Update.ToUserchat();

                string agencyTag = queryData.Substring("ups/a:".Length);
                Agency agency    = await _agencyRepo.GetByTagAsync(agencyTag, cancellationToken)
                                   .ConfigureAwait(false);

                var error = await _userService.SetDefaultAgencyAsync(
                    userchat.UserId.ToString(),
                    userchat.ChatId.ToString(),
                    agency.Tag,
                    cancellationToken
                    ).ConfigureAwait(false);

                if (error is null)
                {
                    _logger.LogTrace("Updating the cache and removing the instructions.");

                    var profileContext = await _cache.GetProfileAsync(userchat, cancellationToken)
                                         .ConfigureAwait(false);

                    profileContext.IsInstructionsSent = false;
                    await _cache.SetProfileAsync(userchat, profileContext, cancellationToken)
                    .ConfigureAwait(false);

                    await context.Bot.Client.SendTextMessageAsync(
                        context.Update.CallbackQuery.Message.Chat,
                        $"Great! Your default agency is now set to *{agency.Title}* " +
                        $"in {agency.Region}, {agency.Country}.\n\n\n" +
                        "💡 *Pro Tip*: You can always view or modify it using the /profile command.",
                        ParseMode.Markdown,
                        replyMarkup : new ReplyKeyboardRemove(),
                        cancellationToken : cancellationToken
                        );


                    context.Items[nameof(WebhookResponse)] = new EditMessageReplyMarkupRequest(
                        context.Update.CallbackQuery.Message.Chat,
                        context.Update.CallbackQuery.Message.MessageId
                        );
                }
                else
                {
                    context.Items[nameof(WebhookResponse)] = new AnswerCallbackQueryRequest
                                                                 (context.Update.CallbackQuery.Id)
                    {
                        Text      = "Oops! failed to set the agency. Try again later",
                        CacheTime = 10,
                    };
                }
            }
            else
            {
                _logger.LogTrace("Updating the inline keyboard of the profile setup message");

                InlineKeyboardMarkup inlineKeyboard;

                if (queryData.StartsWith("ups/c:"))
                {
                    _logger.LogTrace("Update the menu with unique regions for a country");
                    string country  = queryData.Substring("ups/c:".Length);
                    var    agencies = await _agencyRepo.GetByCountryAsync(country)
                                      .ConfigureAwait(false);

                    string[] regions = agencies
                                       .Select(a => a.Region)
                                       .Distinct(StringComparer.OrdinalIgnoreCase)
                                       .OrderBy(r => r)
                                       .ToArray();

                    inlineKeyboard = CreateRegionsInlineKeyboard(regions);
                }
                else if (queryData.StartsWith("ups/r:"))
                {
                    _logger.LogTrace("Updating the menu with all agencies in the region");
                    string region   = queryData.Substring("ups/r:".Length);
                    var    agencies = await _agencyRepo.GetByRegionAsync(region)
                                      .ConfigureAwait(false);

                    inlineKeyboard = CreateAgenciesInlineKeyboard(agencies);
                }
                else if (queryData == "ups/c")
                {
                    _logger.LogTrace("Updating the menu with the list of countries");
                    inlineKeyboard = CreateCountriesInlineKeyboard();
                }
                else
                {
                    _logger.LogError("Invalid callback query data {0} is passed", queryData);
                    return;
                }

                await context.Bot.Client.EditMessageReplyMarkupAsync(
                    context.Update.CallbackQuery.Message.Chat,
                    context.Update.CallbackQuery.Message.MessageId,
                    inlineKeyboard
                    ).ConfigureAwait(false);

                context.Items[nameof(WebhookResponse)] =
                    new AnswerCallbackQueryRequest(context.Update.CallbackQuery.Id);
            }
        }