handle commands with mentions

skip commands directed at other bots
This commit is contained in:
jetsparrow 2018-12-19 22:43:30 +03:00
parent d535d2e8f4
commit 4947351b89
3 changed files with 39 additions and 13 deletions

View File

@ -3,20 +3,30 @@ using System;
using System.Collections.Generic;
using System.Linq;
using Telegram.Bot.Args;
using Telegram.Bot.Types;
namespace JetKarmaBot
{
class ChatCommandRouter
{
Dictionary<string, IChatCommand> commands = new Dictionary<string, IChatCommand>();
User BotUser { get; }
public ChatCommandRouter(User botUser)
{
BotUser = botUser;
}
public bool Execute(object sender, MessageEventArgs args)
{
var text = args.Message.Text;
if (CommandString.TryParse(text, out var cs))
{
if (commands.ContainsKey(cs.Name))
return commands[cs.Name].Execute(sender,args);
if (cs.UserName != null && cs.UserName != BotUser.Username) // directed not at us!
return false;
if (commands.ContainsKey(cs.Command))
return commands[cs.Command].Execute(sender,args);
}
return false;
@ -32,5 +42,6 @@ namespace JetKarmaBot
}
}
Dictionary<string, IChatCommand> commands = new Dictionary<string, IChatCommand>();
}
}

View File

@ -1,31 +1,46 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
namespace JetKarmaBot.Commands
{
public class CommandString
{
public CommandString(string name, params string[] parameters)
public CommandString(string command, params string[] parameters)
{
Name = name;
Command = command;
Parameters = parameters;
}
public string Name { get; }
public string Command { get; }
public string UserName { get; set; } = null;
public string[] Parameters { get; }
public static readonly char[] WS_CHARS = new[] { ' ', '\r', '\n', '\n' };
public static bool TryParse(string s, out CommandString result)
{
result = null;
if (string.IsNullOrWhiteSpace(s) || s[0] != '/')
return false;
int space = s.IndexOf(' ');
if (space < 0)
result = new CommandString(s.Substring(1));
else
result = new CommandString(s.Substring(1, space - 1), s.Substring(space).Split(' ', StringSplitOptions.RemoveEmptyEntries));
string[] words = s.Split(WS_CHARS, StringSplitOptions.RemoveEmptyEntries);
if (!words.Any())
return false;
var cmdRegex = new Regex(@"/(?<cmd>\w+)(@(?<name>\w+))?");
var match = cmdRegex.Match(words.First());
if (!match.Success)
return false;
string cmd = match.Groups["cmd"].Captures.First().Value;
string username = match.Groups["name"].Captures.FirstOrDefault()?.Value;
string[] parameters = words.Skip(1).ToArray();
result = new CommandString(cmd, parameters) { UserName = username};
return true;
}

View File

@ -59,7 +59,7 @@ namespace JetKarmaBot
void InitCommands(Container c)
{
commands = new ChatCommandRouter();
Commands = new ChatCommandRouter(Me);
Commands.Add(c.ResolveObject(new StartCommand()));
Commands.Add(c.ResolveObject(new AwardCommand(Me)));
}