Export router logic into bot class and command

This commit is contained in:
Nikolay Kochulin 2019-11-17 14:00:10 +00:00
parent 3942b17c64
commit c6caaaec86
3 changed files with 12 additions and 19 deletions

View File

@ -26,32 +26,23 @@ namespace JetKarmaBot
{
log.Debug("Message received");
var text = args.Message.Text;
CommandString ncs;
if (cs == null)
if (cs.UserName != null && cs.UserName != Me.Username)
{
if (!CommandString.TryParse(text, out ncs))
return Task.FromResult(false);
if (ncs.UserName != null && ncs.UserName != Me.Username)
{
// directed not at us!
log.Debug("Message not directed at us");
return Task.FromResult(false);
}
// directed not at us!
log.Debug("Message not directed at us");
return Task.FromResult(false);
}
else
ncs = new CommandString(cs.Parameters[0], cs.Parameters.Skip(1).ToArray());
try
{
if (commands.ContainsKey(ncs.Command))
if (commands.ContainsKey(cs.Command))
{
log.Debug($"Handling message via {commands[ncs.Command].GetType().Name}");
return commands[ncs.Command].Execute(ncs, args);
log.Debug($"Handling message via {commands[cs.Command].GetType().Name}");
return commands[cs.Command].Execute(cs, args);
}
}
catch (Exception e)
{
log.Error($"Error while handling command {ncs.Command}!");
log.Error($"Error while handling command {cs.Command}!");
log.Error(e);
}

View File

@ -1,4 +1,5 @@
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using JetKarmaBot.Services;
using Perfusion;
@ -51,7 +52,7 @@ namespace JetKarmaBot.Commands
using (var db = Db.GetContext())
{
var currentLocale = Locale[(await db.Chats.FindAsync(args.Message.Chat.Id)).Locale];
if (!await VerbRouter.Execute(cmd, args))
if (!await VerbRouter.Execute(new CommandString(cmd.Parameters[0], cmd.Parameters.Skip(1).ToArray()), args))
{
await Client.SendTextMessageAsync(
args.Message.Chat.Id,

View File

@ -65,7 +65,8 @@ namespace JetKarmaBot
db.Chats.Add(new Models.Chat { ChatId = messageEventArgs.Message.Chat.Id });
await db.SaveChangesAsync();
}
await Commands.Execute(null, messageEventArgs);
if (CommandString.TryParse(message.Text, out var cmd))
await Commands.Execute(cmd, messageEventArgs);
});
}