Add functionality to localize command help strings.

This commit is contained in:
Nikolay Kochulin 2019-02-07 17:45:49 +03:00
parent 83d1b458af
commit d986a59844
10 changed files with 84 additions and 15 deletions

View File

@ -65,7 +65,7 @@ namespace JetKarmaBot
} }
} }
public string GetHelpText() internal string GetHelpText(Locale loc)
{ {
List<string> pieces = new List<string>(); List<string> pieces = new List<string>();
foreach (IChatCommand c in commands.Values.Distinct()) foreach (IChatCommand c in commands.Values.Distinct())
@ -76,13 +76,13 @@ namespace JetKarmaBot
{ {
build = build + "/" + names[i] + "\n"; build = build + "/" + names[i] + "\n";
} }
build += "/" + names[names.Count - 1] + " " + string.Join(' ', c.Arguments.Select(x => (!x.Required ? "[" : "") + x.Name + (!x.Required ? "]" : ""))) + " <i>" + c.Description + "</i>"; build += "/" + names[names.Count - 1] + " " + string.Join(' ', c.Arguments.Select(x => (!x.Required ? "[" : "") + x.Name + (!x.Required ? "]" : ""))) + " <i>" + getLocalizedCMDDesc(c, loc) + "</i>";
pieces.Add(build); pieces.Add(build);
} }
return string.Join('\n', pieces); return string.Join('\n', pieces);
} }
internal string GetHelpTextFor(string commandname) internal string GetHelpTextFor(string commandname, Locale loc)
{ {
IChatCommand c = commands[commandname]; IChatCommand c = commands[commandname];
string build = ""; string build = "";
@ -91,11 +91,22 @@ namespace JetKarmaBot
{ {
build = build + "/" + names[i] + "\n"; build = build + "/" + names[i] + "\n";
} }
build += "/" + names[names.Count - 1] + " " + string.Join(' ', c.Arguments.Select(x => (!x.Required ? "[" : "") + x.Name + (!x.Required ? "]" : ""))) + " <i>" + c.Description + "</i>\n"; build += "/" + names[names.Count - 1] + " " + string.Join(' ', c.Arguments.Select(x => (!x.Required ? "[" : "") + x.Name + (!x.Required ? "]" : ""))) + " <i>" + getLocalizedCMDDesc(c, loc) + "</i>\n";
build += string.Join("\n", c.Arguments.Select(ca => (!ca.Required ? "[" : "") + ca.Name + (!ca.Required ? "]" : "") + ": <i>" + ca.Description + "</i>")); build += string.Join("\n", c.Arguments.Select(ca => (!ca.Required ? "[" : "") + ca.Name + (!ca.Required ? "]" : "") + ": <i>" + getLocalizedCMDArgDesc(ca, loc) + "</i>"));
return build; return build;
} }
private string getLocalizedCMDDesc(IChatCommand cmd, Locale loc)
{
if (loc.ContainsKey(cmd.DescriptionID)) return loc[cmd.DescriptionID];
else return cmd.Description;
}
private string getLocalizedCMDArgDesc(ChatCommandArgument arg, Locale loc)
{
if (loc.ContainsKey(arg.DescriptionID)) return loc[arg.DescriptionID];
else return arg.Description;
}
Dictionary<string, IChatCommand> commands = new Dictionary<string, IChatCommand>(); Dictionary<string, IChatCommand> commands = new Dictionary<string, IChatCommand>();
} }
} }

View File

@ -93,13 +93,15 @@ namespace JetKarmaBot.Commands
User Me { get; } User Me { get; }
public string Description => "Awards/revokes an award to a user."; public string Description => "Awards/revokes an award to a user.";
public string DescriptionID => "jetkarmabot.award.help";
public IReadOnlyCollection<ChatCommandArgument> Arguments => new ChatCommandArgument[] { public IReadOnlyCollection<ChatCommandArgument> Arguments => new ChatCommandArgument[] {
new ChatCommandArgument() { new ChatCommandArgument() {
Name="awardtype", Name="awardtype",
Required=false, Required=false,
Type=ChatCommandArgumentType.String, Type=ChatCommandArgumentType.String,
Description="The award to grant to/strip of the specified user" Description="The award to grant to/strip of the specified user",
DescriptionID="jetkarmabot.award.awardtypehelp"
} }
}; };

View File

@ -69,13 +69,15 @@ namespace JetKarmaBot.Commands
[Inject] Localization Locale { get; set; } [Inject] Localization Locale { get; set; }
public string Description => "Switches current chat locale to [locale]"; public string Description => "Switches current chat locale to [locale]";
public string DescriptionID => "jetkarmabot.changelocale.help";
public IReadOnlyCollection<ChatCommandArgument> Arguments => new ChatCommandArgument[] { public IReadOnlyCollection<ChatCommandArgument> Arguments => new ChatCommandArgument[] {
new ChatCommandArgument() { new ChatCommandArgument() {
Name="locale", Name="locale",
Required=false, Required=false,
Type=ChatCommandArgumentType.String, Type=ChatCommandArgumentType.String,
Description="The locale to switch to. Can be \"list\" to list all possible locales. Also can be empty to get current locale" Description="The locale to switch to. Can be \"list\" to list all possible locales. Also can be empty to get current locale.",
DescriptionID="jetkarmabot.changelocale.localehelp"
} }
}; };
} }

View File

@ -16,13 +16,15 @@ namespace JetKarmaBot.Commands
public IReadOnlyCollection<string> Names => new[] { "help" }; public IReadOnlyCollection<string> Names => new[] { "help" };
public string Description => "Displays help text for all(one) command(s)"; public string Description => "Displays help text for all(one) command(s)";
public string DescriptionID => "jetkarmabot.help.help";
public IReadOnlyCollection<ChatCommandArgument> Arguments => new ChatCommandArgument[] { public IReadOnlyCollection<ChatCommandArgument> Arguments => new ChatCommandArgument[] {
new ChatCommandArgument() { new ChatCommandArgument() {
Name="command", Name="command",
Required=false, Required=false,
Type=ChatCommandArgumentType.String, Type=ChatCommandArgumentType.String,
Description="The command to return help text for. If empty shows all commands" Description="The command to return help text for. If empty shows all commands.",
DescriptionID="jetkarmabot.help.commandhelp"
} }
}; };
@ -35,7 +37,7 @@ namespace JetKarmaBot.Commands
{ {
Client.SendTextMessageAsync( Client.SendTextMessageAsync(
args.Message.Chat.Id, args.Message.Chat.Id,
Router.GetHelpText(), Router.GetHelpText(currentLocale),
replyToMessageId: args.Message.MessageId, replyToMessageId: args.Message.MessageId,
parseMode: ParseMode.Html); parseMode: ParseMode.Html);
return true; return true;
@ -44,7 +46,7 @@ namespace JetKarmaBot.Commands
{ {
Client.SendTextMessageAsync( Client.SendTextMessageAsync(
args.Message.Chat.Id, args.Message.Chat.Id,
Router.GetHelpTextFor(cmd.Parameters[0]), Router.GetHelpTextFor(cmd.Parameters[0], currentLocale),
replyToMessageId: args.Message.MessageId, replyToMessageId: args.Message.MessageId,
parseMode: ParseMode.Html); parseMode: ParseMode.Html);
return true; return true;

View File

@ -7,6 +7,7 @@ namespace JetKarmaBot.Commands
{ {
IReadOnlyCollection<string> Names { get; } IReadOnlyCollection<string> Names { get; }
string Description { get; } string Description { get; }
string DescriptionID { get; }
IReadOnlyCollection<ChatCommandArgument> Arguments { get; } IReadOnlyCollection<ChatCommandArgument> Arguments { get; }
bool Execute(CommandString cmd, MessageEventArgs messageEventArgs); bool Execute(CommandString cmd, MessageEventArgs messageEventArgs);
@ -18,6 +19,7 @@ namespace JetKarmaBot.Commands
public bool Required; public bool Required;
public ChatCommandArgumentType Type; public ChatCommandArgumentType Type;
public string Description; public string Description;
public string DescriptionID;
} }
public enum ChatCommandArgumentType public enum ChatCommandArgumentType

View File

@ -68,13 +68,15 @@ namespace JetKarmaBot.Commands
[Inject] Localization Locale { get; set; } [Inject] Localization Locale { get; set; }
public string Description => "Shows the amount of awards that you have"; public string Description => "Shows the amount of awards that you have";
public string DescriptionID => "jetkarmabot.status.help";
public IReadOnlyCollection<ChatCommandArgument> Arguments => new ChatCommandArgument[] { public IReadOnlyCollection<ChatCommandArgument> Arguments => new ChatCommandArgument[] {
new ChatCommandArgument(){ new ChatCommandArgument(){
Name="awardtype", Name="awardtype",
Required=false, Required=false,
Type=ChatCommandArgumentType.String, Type=ChatCommandArgumentType.String,
Description="The awardtype to show. If empty shows everything." Description="The awardtype to show. If empty shows everything.",
DescriptionID= "jetkarmabot.status.awardtypehelp"
} }
}; };
} }

View File

@ -100,7 +100,7 @@ namespace JetKarmaBot
} }
public class Locale public class Locale : IReadOnlyDictionary<string, string>
{ {
private Dictionary<string, string> locale; private Dictionary<string, string> locale;
private string localeName; private string localeName;
@ -119,6 +119,33 @@ namespace JetKarmaBot
public bool HasNote => note != null; public bool HasNote => note != null;
public string Note => note; public string Note => note;
public IEnumerable<string> Keys => ((IReadOnlyDictionary<string, string>)locale).Keys;
public IEnumerable<string> Values => ((IReadOnlyDictionary<string, string>)locale).Values;
public int Count => ((IReadOnlyDictionary<string, string>)locale).Count;
public string this[string name] => locale.ContainsKey(name) ? locale[name] : "unknown"; public string this[string name] => locale.ContainsKey(name) ? locale[name] : "unknown";
public bool ContainsKey(string key)
{
return ((IReadOnlyDictionary<string, string>)locale).ContainsKey(key);
}
public bool TryGetValue(string key, out string value)
{
return ((IReadOnlyDictionary<string, string>)locale).TryGetValue(key, out value);
}
public IEnumerator<KeyValuePair<string, string>> GetEnumerator()
{
return ((IReadOnlyDictionary<string, string>)locale).GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return ((IReadOnlyDictionary<string, string>)locale).GetEnumerator();
}
} }
} }

View File

@ -13,14 +13,21 @@
"jetkarmabot.award.awardmessage": "Ўручыў \"{0}\" {1}!", "jetkarmabot.award.awardmessage": "Ўручыў \"{0}\" {1}!",
"jetkarmabot.award.revokemessage": "Адабраў \"{0}\" у {1}!", "jetkarmabot.award.revokemessage": "Адабраў \"{0}\" у {1}!",
"jetkarmabot.award.statustext": "У {0} цяпер {1}{2}.", "jetkarmabot.award.statustext": "У {0} цяпер {1}{2}.",
"jetkarmabot.award.help": "",
"jetkarmabot.award.awardtypehelp": "",
"jetkarmabot.status.listalltext": "У вас :", "jetkarmabot.status.listalltext": "У вас :",
"jetkarmabot.status.listspecifictext": "У вас зараз {0}{1}.", "jetkarmabot.status.listspecifictext": "У вас зараз {0}{1}.",
"jetkarmabot.status.havenothing": "У вас пакуль нічога няма.", "jetkarmabot.status.havenothing": "У вас пакуль нічога няма.",
"jetkarmabot.status.help": "",
"jetkarmabot.status.awardtypehelp": "",
"jetkarmabot.changelocale.justchanged": "Так дакладна.", "jetkarmabot.changelocale.justchanged": "Так дакладна.",
"jetkarmabot.changelocale.getlocale": "Я зараз кажу па-беларускай.", "jetkarmabot.changelocale.getlocale": "Я зараз кажу па-беларускай.",
"jetkarmabot.changelocale.listalltext": "Я ведаю:", "jetkarmabot.changelocale.listalltext": "Я ведаю:",
"jetkarmabot.changelocale.errorall": "Мне б хацелася гаварыць на ўсіх мовах у той жа самы час, але з-за абмежаванняў сусвету, мне гэта не дазваляецца.", "jetkarmabot.changelocale.errorall": "Мне б хацелася гаварыць на ўсіх мовах у той жа самы час, але з-за абмежаванняў сусвету, мне гэта не дазваляецца.",
"jetkarmabot.changelocale.beforenote": "Увага: ", "jetkarmabot.changelocale.beforenote": "Увага: ",
"jetkarmabot.help": "TODO TODO TODO TODO" "jetkarmabot.changelocale.help": "",
"jetkarmabot.changelocale.localehelp": "",
"jetkarmabot.help.help": "",
"jetkarmabot.help.commandhelp": ""
} }
} }

View File

@ -12,14 +12,21 @@
"jetkarmabot.award.awardmessage": "Awarded a {0} to {1}!", "jetkarmabot.award.awardmessage": "Awarded a {0} to {1}!",
"jetkarmabot.award.revokemessage": "Revoked a {0} from {1}!", "jetkarmabot.award.revokemessage": "Revoked a {0} from {1}!",
"jetkarmabot.award.statustext": "{0} is at {1}{2} now.", "jetkarmabot.award.statustext": "{0} is at {1}{2} now.",
"jetkarmabot.award.help": "Awards/revokes an award to a user.",
"jetkarmabot.award.awardtypehelp": "The award to grant to/strip of the specified user",
"jetkarmabot.status.listalltext": "Your badges report:", "jetkarmabot.status.listalltext": "Your badges report:",
"jetkarmabot.status.listspecifictext": "You are at {0}{1} now.", "jetkarmabot.status.listspecifictext": "You are at {0}{1} now.",
"jetkarmabot.status.havenothing": "You don't have anything yet.", "jetkarmabot.status.havenothing": "You don't have anything yet.",
"jetkarmabot.status.help": "Shows the amount of awards that you have",
"jetkarmabot.status.awardtypehelp": "The awardtype to show. If empty shows everything.",
"jetkarmabot.changelocale.justchanged": "Roger that.", "jetkarmabot.changelocale.justchanged": "Roger that.",
"jetkarmabot.changelocale.getlocale": "I'm currently speaking English.", "jetkarmabot.changelocale.getlocale": "I'm currently speaking English.",
"jetkarmabot.changelocale.listalltext": "I know:", "jetkarmabot.changelocale.listalltext": "I know:",
"jetkarmabot.changelocale.errorall": "I would like to speak all languages at once, but because of the rules of the universe, I am not allowed to do that.", "jetkarmabot.changelocale.errorall": "I would like to speak all languages at once, but because of the rules of the universe, I am not allowed to do that.",
"jetkarmabot.changelocale.beforenote": "Warning: ", "jetkarmabot.changelocale.beforenote": "Warning: ",
"jetkarmabot.help": "TODO TODO TODO TODO" "jetkarmabot.changelocale.help": "Switches current chat locale to [locale]",
"jetkarmabot.changelocale.localehelp": "The locale to switch to. Can be \"list\" to list all possible locales. Also can be empty to get current locale",
"jetkarmabot.help.help": "Displays help text for all(one) command(s)",
"jetkarmabot.help.commandhelp": "The command to return help text for. If empty shows all commands."
} }
} }

View File

@ -12,14 +12,21 @@
"jetkarmabot.award.awardmessage": "Вручил \"{0}\" {1}!", "jetkarmabot.award.awardmessage": "Вручил \"{0}\" {1}!",
"jetkarmabot.award.revokemessage": "Отнял \"{0}\" у {1}!", "jetkarmabot.award.revokemessage": "Отнял \"{0}\" у {1}!",
"jetkarmabot.award.statustext": "У {0} теперь {1}{2}.", "jetkarmabot.award.statustext": "У {0} теперь {1}{2}.",
"jetkarmabot.award.help": "Поручает/лишает награду от ползователя/пользователю.",
"jetkarmabot.award.awardtypehelp": "Награду которую поручить/лишить от пользователя",
"jetkarmabot.status.listalltext": "У вас :", "jetkarmabot.status.listalltext": "У вас :",
"jetkarmabot.status.listspecifictext": "У вас сейчас {0}{1}.", "jetkarmabot.status.listspecifictext": "У вас сейчас {0}{1}.",
"jetkarmabot.status.havenothing": "У вас пока ничего нет.", "jetkarmabot.status.havenothing": "У вас пока ничего нет.",
"jetkarmabot.status.help": "",
"jetkarmabot.status.awardtypehelp": "",
"jetkarmabot.changelocale.justchanged": "Так точно.", "jetkarmabot.changelocale.justchanged": "Так точно.",
"jetkarmabot.changelocale.getlocale": "Я сейчас говорю по-русски.", "jetkarmabot.changelocale.getlocale": "Я сейчас говорю по-русски.",
"jetkarmabot.changelocale.listalltext": "Я знаю:", "jetkarmabot.changelocale.listalltext": "Я знаю:",
"jetkarmabot.changelocale.errorall": "Мне бы хотелось говорить на всех языках в то же самое время, но из-за ограничений вселенной, мне это не позволяется.", "jetkarmabot.changelocale.errorall": "Мне бы хотелось говорить на всех языках в то же самое время, но из-за ограничений вселенной, мне это не позволяется.",
"jetkarmabot.changelocale.beforenote": "Внимание: ", "jetkarmabot.changelocale.beforenote": "Внимание: ",
"jetkarmabot.help": "TODO TODO TODO TODO" "jetkarmabot.changelocale.help": "",
"jetkarmabot.changelocale.localehelp": "",
"jetkarmabot.help.help": "",
"jetkarmabot.help.commandhelp": ""
} }
} }