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"); log.Debug("Message received");
var text = args.Message.Text; var text = args.Message.Text;
CommandString ncs; if (cs.UserName != null && cs.UserName != Me.Username)
if (cs == null)
{ {
if (!CommandString.TryParse(text, out ncs)) // directed not at us!
return Task.FromResult(false); log.Debug("Message not directed at us");
if (ncs.UserName != null && ncs.UserName != Me.Username) 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 try
{ {
if (commands.ContainsKey(ncs.Command)) if (commands.ContainsKey(cs.Command))
{ {
log.Debug($"Handling message via {commands[ncs.Command].GetType().Name}"); log.Debug($"Handling message via {commands[cs.Command].GetType().Name}");
return commands[ncs.Command].Execute(ncs, args); return commands[cs.Command].Execute(cs, args);
} }
} }
catch (Exception e) catch (Exception e)
{ {
log.Error($"Error while handling command {ncs.Command}!"); log.Error($"Error while handling command {cs.Command}!");
log.Error(e); log.Error(e);
} }

View File

@ -1,4 +1,5 @@
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks; using System.Threading.Tasks;
using JetKarmaBot.Services; using JetKarmaBot.Services;
using Perfusion; using Perfusion;
@ -51,7 +52,7 @@ namespace JetKarmaBot.Commands
using (var db = Db.GetContext()) using (var db = Db.GetContext())
{ {
var currentLocale = Locale[(await db.Chats.FindAsync(args.Message.Chat.Id)).Locale]; 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( await Client.SendTextMessageAsync(
args.Message.Chat.Id, args.Message.Chat.Id,

View File

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