L
L
lolik202021-04-03 15:48:47
ASP.NET
lolik20, 2021-04-03 15:48:47

How to display the model using TG bot?

There is a shorter TG bot. There is a model which contains 2 properties: TItle and Description. I mapped ModelDTO and DBModel. Writes an error on the mapper, how to solve this trouble? As I understand it, the problem is in the conversion from object to DTO. But how to solve it?

using AutoMapper;
using SolaraNet.BusinessLogic.Abstracts;
using SolaraNet.BusinessLogic.Contracts.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SolaraNet.TelegramBot.Commands
{
    public class GetCommand:IBotCommand
    {
        private readonly ITelegramService _telegramService;
     
        public GetCommand(ITelegramService telegramService)
        {
            _telegramService = telegramService;  
        }
        public string Command => "ads";

        public string Description => "This is a simple command that can be used to test if the bot is online";

        public bool InternalCommand => false;
       
        public async Task Execute(IChatService chatService, long chatId, int userId, int messageId, string? commandText)
        {
            IEnumerable<TestDTO> ads = await _telegramService.GetAllAdvertismentsAsync();
            foreach (var n in ads)
            {
                await chatService.SendMessage(chatId,n.Title.ToString()+n.Description.ToString() );
            }

        }
    }
}

using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using SolaraNet.TelegramBot.Commands;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;

namespace SolaraNet.TelegramBot
{
    public class Bot : IHostedService
    {
        private readonly IChatService _chatService;
        private readonly IServiceProvider _serviceProvider;
        private readonly ILogger<Bot> _logger;

        public const string UnknownCommandMessage = "Unknown command. Try /help for a list of available commands.";

        public Bot(IChatService chatService, IServiceProvider serviceProvider, ILogger<Bot> logger)
        {
            _chatService = chatService;
            _serviceProvider = serviceProvider;
            _logger = logger;
        }

        public Task StartAsync(CancellationToken cancellationToken)
        {
            _chatService.ChatMessage += OnChatMessage;
            _chatService.Callback += OnCallback;
            return Task.CompletedTask;
        }

        public Task StopAsync(CancellationToken cancellationToken)
        {
            _chatService.ChatMessage -= OnChatMessage;
            return Task.CompletedTask;
        }

        private async void OnChatMessage(object? sender, ChatMessageEventArgs chatMessageArgs)
        {
            try
            {
                await ProcessChatMessage(sender, chatMessageArgs);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "{Time}: OnChatMessage - Error {Exception}", DateTime.UtcNow, ex.Message);
            }
        }

        private async void OnCallback(object? sender, CallbackEventArgs callbackEventArgs)
        {
            try
            {
                await ProcessCallback(sender, callbackEventArgs);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "{Time}: OnChatMessage - Error {Exception}", DateTime.UtcNow, ex.Message);
            }
        }

        private async Task ProcessChatMessage(object? sender, ChatMessageEventArgs chatMessageArgs)
        {
            if (sender is IChatService chatService)
            {
                var command = _serviceProvider.GetServices<IBotCommand>().SingleOrDefault(x => $"/{x.Command}".Equals(chatMessageArgs.Command, StringComparison.InvariantCultureIgnoreCase));
                if (command != null)
                {
                    await command.Execute(chatService,
                        chatMessageArgs.ChatId,
                        chatMessageArgs.UserId,
                        chatMessageArgs.MessageId,
                        chatMessageArgs.Text);
                }
                else
                {
                    _logger.LogTrace("Unknown command was sent");
                    await chatService.SendMessage(chatMessageArgs.ChatId, UnknownCommandMessage);
                }
            }
        }

        private async Task ProcessCallback(object? sender, CallbackEventArgs callbackEventArgs)
        {
            if (sender is IChatService chatService)
            {
                var commandText = callbackEventArgs.Command?.Split(' ').First();
                var command = _serviceProvider.GetServices<IBotCommand>().SingleOrDefault(x => $"/{x.Command}".Equals(commandText, StringComparison.InvariantCultureIgnoreCase));

                if (command != null && !string.IsNullOrEmpty(commandText))
                {
                    await command.Execute(chatService,
                        callbackEventArgs.ChatId,
                        callbackEventArgs.UserId,
                        callbackEventArgs.MessageId,
                        callbackEventArgs.Command?.Replace(commandText, string.Empty).Trim());
                }
                else
                {
                    _logger.LogCritical("Invalid callback data was provided: {CallbackData}", callbackEventArgs);
                }
            }
        }
    }
}


CreateMap<DBTest, TestDTO>()
                .ForMember(x => x.Id, x => x.MapFrom(x => x.Id))
                .ForMember(x => x.Title, x => x.MapFrom(x => x.Title))
                .ForMember(x => x.Description, x => x.MapFrom(x => x.Description));
            CreateMap<TestDTO, DBTest>()
            .ForMember(x => x.Id, x => x.MapFrom(x => x.Id))
            .ForMember(x => x.Title, x => x.MapFrom(x => x.Title))
            .ForMember(x => x.Description, x => x.MapFrom(x => x.Description));

606863d92e0fb831822071.png

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question