Compare commits

..

58 Commits

Author SHA1 Message Date
Nikolay Kochulin
6bbc85ebf0 Update dependencies and switch to .netcoreapp2.2 2019-06-14 22:46:38 +03:00
Nikolay Kochulin
178f1ee089 Ensure existence of DB 2019-06-07 18:37:11 +03:00
Nikolay Kochulin
ff63dbe386 Fix db isadministrator + update perfusion
Signed-off-by: Nikolay Kochulin <porez0xfeedface@gmail.com>
2019-05-17 15:31:54 +03:00
Nikolay Kochulin
7bef7255f8 Basic error telegram logging support
Signed-off-by: Nikolay Kochulin <porez0xfeedface@gmail.com>
2019-05-16 20:25:18 +03:00
Nikolay Kochulin
45b94e7561 Add field IsAdministrator
Signed-off-by: Nikolay Kochulin <porez0xfeedface@gmail.com>
2019-05-16 19:32:32 +03:00
Nikolay Kochulin
79e78f41c5 Add autocomplete based on language identifier
Signed-off-by: Nikolay Kochulin <porez0xfeedface@gmail.com>
2019-04-24 21:42:06 +03:00
Nikolay Kochulin
8322f4f871 Add rate limiting to /award
Signed-off-by: Nikolay Kochulin <porez0xfeedface@gmail.com>
2019-04-24 18:13:25 +03:00
Nikolay Kochulin
61166ea0c9 Add SqlDebug to config
Signed-off-by: Nikolay Kochulin <porez0xfeedface@gmail.com>
2019-04-24 18:10:34 +03:00
Nikolay Kochulin
e7c53fa2ad Fix "a a" in en-US locale
Signed-off-by: Nikolay Kochulin <porez0xfeedface@gmail.com>
2019-04-20 20:16:51 +03:00
Nikolay Kochulin
1ee1abc672 Better formatting for /currencies
Signed-off-by: Nikolay Kochulin <porez0xfeedface@gmail.com>
2019-04-18 18:09:50 +03:00
Nikolay Kochulin
71a2328eb1 Add accusative forms to award type names
Signed-off-by: Nikolay Kochulin <porez0xfeedface@gmail.com>
2019-04-18 17:44:05 +03:00
Nikolay Kochulin
4353428d41 Add /currencies
Signed-off-by: Nikolay Kochulin <porez0xfeedface@gmail.com>
2019-04-18 17:28:20 +03:00
Nikolay Kochulin
bf8778c7d9 Update to new Perfusion 2019-04-18 15:43:57 +03:00
Nikolay Kochulin
2cd40cb85d Merge branch 'master' of ssh://lserver1/srv/git/karmabot 2019-03-14 12:17:16 +03:00
Nikolay Kochulin
68c2715c17 Fix grammatical error 2019-03-14 12:17:13 +03:00
bcda3b9282 fix be-by.json build action 2019-02-12 11:41:50 +03:00
e2ee46eba9 build project under dotnet framework for deploy on linux x86 2019-02-09 19:01:38 +03:00
Nikolay Kochulin
d410d7ae47 Translate ru-RU into be-BY 2019-02-07 23:26:38 +03:00
e5d81925f0 ru help 2019-02-07 23:10:59 +03:00
Nikolay Kochulin
6835ba4843 Merge help-command into master 2019-02-07 17:53:52 +03:00
Nikolay Kochulin
d986a59844 Add functionality to localize command help strings. 2019-02-07 17:45:49 +03:00
Nikolay Kochulin
7f9e5918d4 Add all other awardtypes in 2019-02-07 17:20:12 +03:00
Nikolay Kochulin
4be28f3c1b Add functionality for awardtype localized names 2019-02-07 17:14:36 +03:00
Nikolay Kochulin
83d1b458af Add help command mechanisms 2019-02-07 16:44:32 +03:00
Nikolay Kochulin
b93d20e07e Start creating help command 2019-02-06 23:29:12 +03:00
Nikolay Kochulin
fadd970c5d Add joke belarusian locale + add locale notes 2019-02-06 20:38:58 +03:00
Nikolay Kochulin
09d2ce7bb6 Add joke belarusian locale. 2019-02-06 20:33:18 +03:00
Nikolay Kochulin
98361572dc Add /locale list and /locale all 2019-02-06 20:17:57 +03:00
Nikolay Kochulin
08ebdbaa37 Make logging accessible via perfusion 2019-02-06 18:19:09 +03:00
Nikolay Kochulin
0a3d969bec Update perfusion commit id + fix bug 2019-02-05 22:47:15 +03:00
Nikolay Kochulin
fdfea2bbb1 Update to use new perfusion version 2019-01-12 17:25:38 +03:00
Nikolay Kochulin
3e7ace4a7e Add "you have nothing yet" feature to /status 2019-01-11 22:10:28 +03:00
Nikolay Kochulin
4aee536c63 Make JetKarmaBot add chats to db 2019-01-11 21:58:48 +03:00
Nikolay Kochulin
6a4ee6e791 Add a bit of logging to AwardCommand and ChangeLocaleCommand 2019-01-06 23:49:02 +03:00
Nikolay Kochulin
1159af1785 Add logging to Program and CommandRouter 2019-01-06 23:39:31 +03:00
Nikolay Kochulin
a9cca3ee59 Added logging 2019-01-06 23:24:52 +03:00
Nikolay Kochulin
51dce7f588 Allow adding of common names of locales to locale files 2019-01-06 22:29:25 +03:00
d20cc89f28 localization fixes 2019-01-06 19:08:55 +03:00
fd732d8719 awards fix 2019-01-06 18:57:48 +03:00
Nikolay Kochulin
d95dae4ddb WIP entity framework 2019-01-06 18:29:00 +03:00
d3bbfe8c52 transition start 2019-01-02 17:07:31 +03:00
Nikolay Kochulin
23dbd6ca17 Allow getting locales 2018-12-31 23:05:13 +03:00
Nikolay Kochulin
c8adaaa0d4 Rename ChangeLanguageCommand to ChangeLocaleCommand 2018-12-31 21:56:46 +03:00
Nikolay Kochulin
bff68a9748 Add language chooser feature to chats 2018-12-26 20:56:53 +03:00
Nikolay Kochulin
12b90d010f
Make localization not use config 2018-12-21 23:00:32 +03:00
efb1a532bd ru-RU phrasing 2018-12-21 22:50:21 +03:00
Nikolay Kochulin
8918d576c4
Use now perfusion commit 2018-12-21 22:46:23 +03:00
Nikolay Kochulin
6fb4fdf544
Make /award output mentions 2018-12-21 19:53:25 +03:00
Nikolay Kochulin
58c6d52232
Add experimental russian locale 2018-12-21 19:50:35 +03:00
Nikolay Kochulin
8d0d70553c
Add localization 2018-12-21 18:13:36 +03:00
0025be1474 status command 2018-12-19 23:55:58 +03:00
2fbfde551b revoking support 2018-12-19 23:55:45 +03:00
37236d50ff pass through parsed string instead of sender to command 2018-12-19 22:45:57 +03:00
4947351b89 handle commands with mentions
skip commands directed at other bots
2018-12-19 22:43:30 +03:00
d535d2e8f4 Finish moving to Perfusion 2018-12-19 22:42:53 +03:00
fff2c0d3fa fix perfusion usage 2018-12-19 22:21:12 +03:00
a55f7a1d97 Merge remote-tracking branch 'origin/master' 2018-12-19 16:37:01 +03:00
Nikolay Kochulin
1394062930
Convert project to perfusion 2018-12-19 15:18:41 +03:00
36 changed files with 1302 additions and 1636 deletions

View File

@ -0,0 +1,124 @@
using JetKarmaBot.Commands;
using JetKarmaBot.Services;
using NLog;
using Perfusion;
using System;
using System.Collections.Generic;
using System.Linq;
using Telegram.Bot;
using Telegram.Bot.Args;
namespace JetKarmaBot
{
public class ChatCommandRouter
{
Telegram.Bot.Types.User BotUser { get; }
[Inject] private Logger log;
[Inject] private KarmaContextFactory Db;
[Inject] private TelegramBotClient Client { get; set; }
public ChatCommandRouter(Telegram.Bot.Types.User botUser)
{
BotUser = botUser;
}
public bool Execute(object sender, MessageEventArgs args)
{
log.Debug("Message received");
var text = args.Message.Text;
if (CommandString.TryParse(text, out var cmd))
{
if (cmd.UserName != null && cmd.UserName != BotUser.Username)
{
// directed not at us!
log.Debug("Message not directed at us");
return false;
}
try
{
if (commands.ContainsKey(cmd.Command))
{
log.Debug($"Handling message via {commands[cmd.Command].GetType().Name}");
return commands[cmd.Command].Execute(cmd, args);
}
}
catch (Exception e)
{
log.Error($"Error while handling command {cmd.Command}!");
log.Error(e);
ReportToAdministratorChats($"Error while handling command {cmd.Command}!\n{e.ToString()}");
}
}
return false;
}
public void ReportToAdministratorChats(string text)
{
using (var db = Db.GetContext())
{
foreach (long chatid in db.Chats.Where(x => x.IsAdministrator).Select(x => x.ChatId))
{
Client.SendTextMessageAsync(chatid, text);
}
}
}
public void Add(IChatCommand c)
{
log.ConditionalTrace($"Adding command {c.GetType().Name}");
foreach (var name in c.Names)
{
log.ConditionalTrace($"Mounting {c.GetType().Name} to {name}");
if (commands.ContainsKey(name))
throw new Exception($"command collision for name {name}, commands {commands[name].GetType()} and {c.GetType()}");
commands[name] = c;
}
}
internal string GetHelpText(Locale loc)
{
List<string> pieces = new List<string>();
foreach (IChatCommand c in commands.Values.Distinct())
{
string build = "";
List<string> names = c.Names.ToList();
for (int i = 0; i < names.Count - 1; i++)
{
build = build + "/" + names[i] + "\n";
}
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);
}
return string.Join("\n", pieces);
}
internal string GetHelpTextFor(string commandname, Locale loc)
{
IChatCommand c = commands[commandname];
string build = "";
List<string> names = c.Names.ToList();
for (int i = 0; i < names.Count - 1; i++)
{
build = build + "/" + names[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>" + getLocalizedCMDArgDesc(ca, loc) + "</i>"));
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>();
}
}

View File

@ -1,156 +1,133 @@
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using Telegram.Bot;
using Telegram.Bot.Args;
using Telegram.Bot.Types;
using Perfusion;
using JetKarmaBot.Services;
using NLog;
using JetKarmaBot.Services.Handling;
using JetKarmaBot.Models;
namespace JetKarmaBot.Commands;
class AwardCommand : IChatCommand
namespace JetKarmaBot.Commands
{
public IReadOnlyCollection<string> Names => new[] { "award", "revoke" };
[Inject] private Logger log;
public async Task<bool> Execute(RequestContext ctx)
class AwardCommand : IChatCommand
{
var db = ctx.GetFeature<KarmaContext>();
var currentLocale = ctx.GetFeature<Locale>();
public IReadOnlyCollection<string> Names => new[] { "award", "revoke" };
[Inject]
private Logger log;
var awarder = ctx.EventArgs.Message.From;
if (Timeout.TimeoutCache[awarder.Id].PreviousAwardDate.AddSeconds(Config.Timeout.AwardTimeSeconds) > DateTime.Now)
public bool Execute(CommandString cmd, MessageEventArgs args)
{
ctx.GetFeature<TimeoutManager.Feature>().Multiplier = 0; // Doesn't count as success or failure
if (!Timeout.TimeoutCache[awarder.Id].TimeoutMessaged)
await ctx.SendMessage(currentLocale["jetkarmabot.ratelimit"]);
Timeout.TimeoutCache[awarder.Id].TimeoutMessaged = true;
return false;
using (var db = Db.GetContext())
{
var currentLocale = Locale[db.Chats.Find(args.Message.Chat.Id).Locale];
if (args.Message.ReplyToMessage == null)
{
Client.SendTextMessageAsync(args.Message.Chat.Id, currentLocale["jetkarmabot.award.errawardnoreply"]);
return true;
}
var awarder = args.Message.From;
var recipient = args.Message.ReplyToMessage.From;
bool awarding = cmd.Command == "award";
if (awarder.Id == recipient.Id)
{
Client.SendTextMessageAsync(
args.Message.Chat.Id,
currentLocale["jetkarmabot.award.errawardself"],
replyToMessageId: args.Message.MessageId);
return true;
}
if (Me.Id == recipient.Id)
{
Client.SendTextMessageAsync(
args.Message.Chat.Id,
awarding
? currentLocale["jetkarmabot.award.errawardbot"]
: currentLocale["jetkarmabot.award.errrevokebot"],
replyToMessageId: args.Message.MessageId);
return true;
}
var text = args.Message.Text;
var awardTypeText = cmd.Parameters.FirstOrDefault();
global::JetKarmaBot.Models.AwardType awardType = awardTypeText != null
? db.AwardTypes.First(at => at.CommandName == awardTypeText)
: db.AwardTypes.Find((sbyte)1);
DateTime cutoff = DateTime.Now - TimeSpan.FromMinutes(5);
if (db.Awards.Where(x => x.Date > cutoff && x.FromId == awarder.Id).Count() >= 10)
{
Client.SendTextMessageAsync(
args.Message.Chat.Id,
currentLocale["jetkarmabot.award.ratelimit"],
replyToMessageId: args.Message.MessageId);
return true;
}
db.Awards.Add(new Models.Award()
{
AwardTypeId = awardType.AwardTypeId,
Amount = (sbyte)(awarding ? 1 : -1),
FromId = awarder.Id,
ToId = recipient.Id,
ChatId = args.Message.Chat.Id
});
log.Debug($"Awarded {(awarding ? 1 : -1)}{awardType.Symbol} to {recipient.Username}");
db.SaveChanges();
string message = awarding
? string.Format(currentLocale["jetkarmabot.award.awardmessage"], getLocalizedName(awardType, currentLocale), "@" + recipient.Username)
: string.Format(currentLocale["jetkarmabot.award.revokemessage"], getLocalizedName(awardType, currentLocale), "@" + recipient.Username);
var currentCount = db.Awards
.Where(aw => aw.ToId == recipient.Id && aw.AwardTypeId == awardType.AwardTypeId)
.Sum(aw => aw.Amount);
var response = message + "\n" + String.Format(currentLocale["jetkarmabot.award.statustext"], "@" + recipient.Username, currentCount, awardType.Symbol);
Client.SendTextMessageAsync(
args.Message.Chat.Id,
response,
replyToMessageId: args.Message.MessageId);
return true;
}
}
string awardTypeText = null;
long recipientId = default;
foreach (string arg in ctx.Command.Parameters)
private string getLocalizedName(global::JetKarmaBot.Models.AwardType awardType, Locale loc)
{
if (arg.StartsWith('@'))
if (loc.ContainsKey($"jetkarmabot.awardtypes.accusative.{awardType.CommandName}"))
{
if (recipientId != default(int))
{
await ctx.SendMessage(currentLocale["jetkarmabot.award.errdup"]);
return false;
}
recipientId = await db.Users.Where(x => x.Username == arg).Select(x => x.UserId).FirstOrDefaultAsync();
if (recipientId == default(int))
{
await ctx.SendMessage(currentLocale["jetkarmabot.award.errbadusername"]);
return false;
}
return loc[$"jetkarmabot.awardtypes.accusative.{awardType.CommandName}"];
}
else
{
if (awardTypeText == null)
awardTypeText = arg;
else
{
await ctx.SendMessage(currentLocale["jetkarmabot.award.errdup"]);
return false;
}
return awardType.Name;
}
}
if (ctx.EventArgs.Message.ReplyToMessage != null && recipientId == default)
[Inject] KarmaContextFactory Db { get; set; }
[Inject] TelegramBotClient Client { get; set; }
[Inject] Localization Locale { get; set; }
User Me { get; }
public string Description => "Awards/revokes an award to a user.";
public string DescriptionID => "jetkarmabot.award.help";
public IReadOnlyCollection<ChatCommandArgument> Arguments => new ChatCommandArgument[] {
new ChatCommandArgument() {
Name="awardtype",
Required=false,
Type=ChatCommandArgumentType.String,
Description="The award to grant to/strip of the specified user",
DescriptionID="jetkarmabot.award.awardtypehelp"
}
};
public AwardCommand(User me)
{
recipientId = ctx.EventArgs.Message.ReplyToMessage.From.Id;
}
if (recipientId == default(int))
{
await ctx.SendMessage(currentLocale["jetkarmabot.award.errawardnoreply"]);
return false;
}
bool awarding = ctx.Command.Command == "award";
if (awarder.Id == recipientId)
{
await ctx.SendMessage(currentLocale["jetkarmabot.award.errawardself"]);
return false;
}
if (ctx.GetFeature<ChatCommandRouter.Feature>().Router.Me.Id == recipientId)
{
await ctx.SendMessage(awarding
? currentLocale["jetkarmabot.award.errawardbot"]
: currentLocale["jetkarmabot.award.errrevokebot"]);
return false;
}
var text = ctx.EventArgs.Message.Text;
global::JetKarmaBot.Models.AwardType awardType = awardTypeText != null
? await db.AwardTypes.FirstAsync(at => at.CommandName == awardTypeText)
: await db.AwardTypes.FindAsync((sbyte)1);
var prevCount = await db.Awards
.Where(aw => aw.ToId == recipientId && aw.AwardTypeId == awardType.AwardTypeId && aw.ChatId == ctx.EventArgs.Message.Chat.Id)
.SumAsync(aw => aw.Amount);
await db.Awards.AddAsync(new Models.Award()
{
AwardTypeId = awardType.AwardTypeId,
Amount = (sbyte)(awarding ? 1 : -1),
FromId = awarder.Id,
ToId = recipientId,
ChatId = ctx.EventArgs.Message.Chat.Id
});
var recUserName = (await db.Users.FindAsync(recipientId)).Username;
log.Debug($"Awarded {(awarding ? 1 : -1)}{awardType.Symbol} to {recUserName}");
string message = awarding
? string.Format(currentLocale["jetkarmabot.award.awardmessage"], getLocalizedName(awardType, currentLocale), recUserName)
: string.Format(currentLocale["jetkarmabot.award.revokemessage"], getLocalizedName(awardType, currentLocale), recUserName);
var response = message + "\n" + String.Format(currentLocale["jetkarmabot.award.statustext"], recUserName, prevCount + (awarding ? 1 : -1), awardType.Symbol);
await ctx.SendMessage(response);
Timeout.TimeoutCache[awarder.Id].PreviousAwardDate = DateTime.Now;
return true;
}
private string getLocalizedName(global::JetKarmaBot.Models.AwardType awardType, Locale loc)
{
if (loc.ContainsKey($"jetkarmabot.awardtypes.accusative.{awardType.CommandName}"))
{
return loc[$"jetkarmabot.awardtypes.accusative.{awardType.CommandName}"];
}
else
{
return awardType.Name;
Me = me;
}
}
[Inject] Localization Locale { get; set; }
[Inject] TimeoutManager Timeout { get; set; }
[Inject] Config Config { get; set; }
public string Description => "Awards/revokes an award to a user.";
public string DescriptionID => "jetkarmabot.award.help";
public IReadOnlyCollection<ChatCommandArgument> Arguments => new ChatCommandArgument[] {
new ChatCommandArgument() {
Name="awardtype",
Required=false,
Type=ChatCommandArgumentType.String,
Description="The award to grant to/strip of the specified user",
DescriptionID="jetkarmabot.award.awardtypehelp"
},
new ChatCommandArgument() {
Name="to",
Required=false,
Type=ChatCommandArgumentType.String,
Description="The user to award it to.",
DescriptionID="jetkarmabot.award.tohelp"
}
};
}

View File

@ -1,75 +1,95 @@
using System.Collections.Generic;
using Telegram.Bot;
using Telegram.Bot.Args;
using Perfusion;
using JetKarmaBot.Services;
using NLog;
using JetKarmaBot.Services.Handling;
using JetKarmaBot.Models;
using System.Linq;
namespace JetKarmaBot.Commands;
class LocaleCommand : IChatCommand
namespace JetKarmaBot.Commands
{
public IReadOnlyCollection<string> Names => new[] { "changelocale", "locale" };
[Inject] private Logger log;
public async Task<bool> Execute(RequestContext ctx)
class LocaleCommand : IChatCommand
{
var db = ctx.GetFeature<KarmaContext>();
var currentLocale = ctx.GetFeature<Locale>();
var cmd = ctx.Command;
var args = ctx.EventArgs;
public IReadOnlyCollection<string> Names => new[] { "changelocale", "locale" };
[Inject]
private Logger log;
if (cmd.Parameters.Length < 1)
public bool Execute(CommandString cmd, MessageEventArgs args)
{
await ctx.SendMessage(currentLocale["jetkarmabot.changelocale.getlocale"]);
return false;
}
else if (cmd.Parameters[0] == "list")
{
await ctx.SendMessage(currentLocale["jetkarmabot.changelocale.listalltext"] + "\n"
+ string.Join("\n", Locale.Select(a => a.Key)));
return false;
}
else if (cmd.Parameters[0] == "all")
{
await ctx.SendMessage(currentLocale["jetkarmabot.changelocale.errorall"]);
return false;
}
string localeId;
if (Locale.ContainsLocale(cmd.Parameters[0]))
localeId = cmd.Parameters[0];
else
try
using (var db = Db.GetContext())
{
localeId = Locale.FindByCommonName(cmd.Parameters[0]).Name;
}
catch (LocalizationException e)
{
await ctx.SendMessage(
currentLocale["jetkarmabot.changelocale.toomany"] + "\n"
+ string.Join("\n", (e.Data["LocaleNames"] as Locale[]).Select(x => x.Name)));
return false;
}
(await db.Chats.FindAsync(args.Message.Chat.Id)).Locale = localeId;
log.Debug($"Changed language of chat {args.Message.Chat.Id} to {localeId}");
var currentLocale = Locale[db.Chats.Find(args.Message.Chat.Id).Locale];
if (cmd.Parameters.Length < 1)
{
Client.SendTextMessageAsync(
args.Message.Chat.Id,
currentLocale["jetkarmabot.changelocale.getlocale"],
replyToMessageId: args.Message.MessageId);
return true;
}
else if (cmd.Parameters[0] == "list")
{
Client.SendTextMessageAsync(
args.Message.Chat.Id,
currentLocale["jetkarmabot.changelocale.listalltext"] + "\n"
+ string.Join("\n", Locale.Select(a => a.Key)),
replyToMessageId: args.Message.MessageId);
return true;
}
else if (cmd.Parameters[0] == "all")
{
Client.SendTextMessageAsync(
args.Message.Chat.Id,
currentLocale["jetkarmabot.changelocale.errorall"],
replyToMessageId: args.Message.MessageId);
return true;
}
string localeId;
if (Locale.ContainsLocale(cmd.Parameters[0]))
localeId = cmd.Parameters[0];
else
try
{
localeId = Locale.FindByCommonName(cmd.Parameters[0]).Name;
}
catch (LocalizationException e)
{
Client.SendTextMessageAsync(
args.Message.Chat.Id,
currentLocale["jetkarmabot.changelocale.toomany"] + "\n" + string.Join("\n", (e.Data["LocaleNames"] as Locale[]).Select(x => x.Name)),
replyToMessageId: args.Message.MessageId);
return true;
}
db.Chats.Find(args.Message.Chat.Id).Locale = localeId;
log.Debug($"Changed language of chat {args.Message.Chat.Id} to {localeId}");
db.SaveChanges();
currentLocale = Locale[localeId];
currentLocale = Locale[db.Chats.Find(args.Message.Chat.Id).Locale];
await ctx.SendMessage(
(currentLocale.HasNote ? currentLocale["jetkarmabot.changelocale.beforenote"] + currentLocale.Note + "\n" : "")
+ currentLocale["jetkarmabot.changelocale.justchanged"]);
return true;
Client.SendTextMessageAsync(
args.Message.Chat.Id,
(currentLocale.HasNote ? currentLocale["jetkarmabot.changelocale.beforenote"] + currentLocale.Note + "\n" : "")
+ currentLocale["jetkarmabot.changelocale.justchanged"],
replyToMessageId: args.Message.MessageId);
return true;
}
}
[Inject] KarmaContextFactory Db { get; set; }
[Inject] TelegramBotClient Client { get; set; }
[Inject] Localization Locale { get; set; }
public string Description => "Switches current chat locale to [locale]";
public string DescriptionID => "jetkarmabot.changelocale.help";
public IReadOnlyCollection<ChatCommandArgument> Arguments => new ChatCommandArgument[] {
new ChatCommandArgument() {
Name="locale",
Required=false,
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.",
DescriptionID="jetkarmabot.changelocale.localehelp"
}
};
}
[Inject] Localization Locale { get; set; }
public string Description => "Switches current chat locale to [locale]";
public string DescriptionID => "jetkarmabot.changelocale.help";
public IReadOnlyCollection<ChatCommandArgument> Arguments => new ChatCommandArgument[] {
new ChatCommandArgument() {
Name="locale",
Required=false,
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.",
DescriptionID="jetkarmabot.changelocale.localehelp"
}
};
}

View File

@ -1,48 +1,53 @@
using System.Text.RegularExpressions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
namespace JetKarmaBot.Commands;
public class CommandString
namespace JetKarmaBot.Commands
{
public CommandString(string command, params string[] parameters)
public class CommandString
{
Command = command;
Parameters = parameters;
}
public CommandString(string command, params string[] parameters)
{
Command = command;
Parameters = parameters;
}
public string Command { get; }
public string UserName { get; set; } = null;
public string[] Parameters { 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 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;
public static bool TryParse(string s, out CommandString result)
{
result = null;
if (string.IsNullOrWhiteSpace(s) || s[0] != '/')
return false;
string[] words = s.Split(WS_CHARS, StringSplitOptions.RemoveEmptyEntries);
string[] words = s.Split(WS_CHARS, StringSplitOptions.RemoveEmptyEntries);
if (!words.Any())
return false;
if (!words.Any())
return false;
var cmdRegex = new Regex(@"/(?<cmd>\w+)(@(?<name>\w+))?");
var match = cmdRegex.Match(words.First());
if (!match.Success)
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[0].Value;
string username = match.Groups["name"].Captures.Count > 0 ? match.Groups["name"].Captures[0].Value : null;
string[] parameters = words.Skip(1).ToArray();
string cmd = match.Groups["cmd"].Captures[0].Value;
string username = match.Groups["name"].Captures.Count > 0 ? match.Groups["name"].Captures[0].Value : null;
string[] parameters = words.Skip(1).ToArray();
result = new CommandString(cmd, parameters) { UserName = username };
return true;
}
result = new CommandString(cmd, parameters) { UserName = username};
return true;
}
public static CommandString Parse(string s)
{
if (TryParse(s, out var c)) return c;
throw new ArgumentException($"\"{s}\" is not a command");
public static CommandString Parse(string s)
{
if (TryParse(s, out var c)) return c;
throw new ArgumentException($"\"{s}\" is not a command");
}
}
}

View File

@ -1,28 +1,40 @@
using Microsoft.EntityFrameworkCore;
using JetKarmaBot.Services.Handling;
using JetKarmaBot.Models;
using System.Collections.Generic;
using Telegram.Bot.Args;
using Perfusion;
using JetKarmaBot.Services;
using Telegram.Bot;
using Telegram.Bot.Types.Enums;
using System.Linq;
namespace JetKarmaBot.Commands;
public class CurrenciesCommand : IChatCommand
namespace JetKarmaBot.Commands
{
[Inject] Localization Locale { get; set; }
public IReadOnlyCollection<string> Names => new[] { "currencies", "awardtypes" };
public string Description => "Shows all award types";
public string DescriptionID => "jetkarmabot.currencies.help";
public IReadOnlyCollection<ChatCommandArgument> Arguments => new ChatCommandArgument[] {
};
public async Task<bool> Execute(RequestContext ctx)
public class CurrenciesCommand : IChatCommand
{
var db = ctx.GetFeature<KarmaContext>();
var currentLocale = ctx.GetFeature<Locale>();
await ctx.SendMessage(
currentLocale["jetkarmabot.currencies.listtext"] + "\n" + string.Join("\n",
(await db.AwardTypes.ToListAsync())
.Select(x => $"{x.Symbol} ({x.CommandName}) <i>{currentLocale["jetkarmabot.awardtypes.nominative." + x.CommandName]}</i>")));
return true;
[Inject] KarmaContextFactory Db;
[Inject] TelegramBotClient Client { get; set; }
[Inject] Localization Locale { get; set; }
public IReadOnlyCollection<string> Names => new[] { "currencies", "awardtypes" };
public string Description => "Shows all award types";
public string DescriptionID => "jetkarmabot.currencies.help";
public IReadOnlyCollection<ChatCommandArgument> Arguments => new ChatCommandArgument[] {
};
public bool Execute(CommandString cmd, MessageEventArgs args)
{
using (var db = Db.GetContext())
{
var currentLocale = Locale[db.Chats.Find(args.Message.Chat.Id).Locale];
string resp = currentLocale["jetkarmabot.currencies.listtext"] + "\n" + string.Join("\n",
db.AwardTypes.ToList().Select(x => $"{x.Symbol} ({x.CommandName}) <i>{currentLocale["jetkarmabot.awardtypes.nominative." + x.CommandName]}</i>"));
Client.SendTextMessageAsync(
args.Message.Chat.Id,
resp,
replyToMessageId: args.Message.MessageId,
parseMode: ParseMode.Html);
return true;
}
}
}
}

View File

@ -1,38 +1,61 @@
using JetKarmaBot.Services.Handling;
using System.Collections.Generic;
using Telegram.Bot.Args;
using Perfusion;
using JetKarmaBot.Services;
using Telegram.Bot;
using Telegram.Bot.Types.Enums;
namespace JetKarmaBot.Commands;
public class HelpCommand : IChatCommand
namespace JetKarmaBot.Commands
{
[Inject] Localization Locale { get; set; }
public IReadOnlyCollection<string> Names => new[] { "help" };
public string Description => "Displays help text for all(one) command(s)";
public string DescriptionID => "jetkarmabot.help.help";
public IReadOnlyCollection<ChatCommandArgument> Arguments => new ChatCommandArgument[] {
new ChatCommandArgument() {
Name="command",
Required=false,
Type=ChatCommandArgumentType.String,
Description="The command to return help text for. If empty shows all commands.",
DescriptionID="jetkarmabot.help.commandhelp"
}
};
public async Task<bool> Execute(RequestContext ctx)
public class HelpCommand : IChatCommand
{
var currentLocale = ctx.GetFeature<Locale>();
var router = ctx.GetFeature<ChatCommandRouter.Feature>().Router;
if (ctx.Command.Parameters.Length < 1)
[Inject] KarmaContextFactory Db;
[Inject] TelegramBotClient Client { get; set; }
[Inject] Localization Locale { get; set; }
ChatCommandRouter Router;
public IReadOnlyCollection<string> Names => new[] { "help" };
public string Description => "Displays help text for all(one) command(s)";
public string DescriptionID => "jetkarmabot.help.help";
public IReadOnlyCollection<ChatCommandArgument> Arguments => new ChatCommandArgument[] {
new ChatCommandArgument() {
Name="command",
Required=false,
Type=ChatCommandArgumentType.String,
Description="The command to return help text for. If empty shows all commands.",
DescriptionID="jetkarmabot.help.commandhelp"
}
};
public bool Execute(CommandString cmd, MessageEventArgs args)
{
await ctx.SendMessage(router.GetHelpText(currentLocale));
return true;
using (var db = Db.GetContext())
{
var currentLocale = Locale[db.Chats.Find(args.Message.Chat.Id).Locale];
if (cmd.Parameters.Length < 1)
{
Client.SendTextMessageAsync(
args.Message.Chat.Id,
Router.GetHelpText(currentLocale),
replyToMessageId: args.Message.MessageId,
parseMode: ParseMode.Html);
return true;
}
else
{
Client.SendTextMessageAsync(
args.Message.Chat.Id,
Router.GetHelpTextFor(cmd.Parameters[0], currentLocale),
replyToMessageId: args.Message.MessageId,
parseMode: ParseMode.Html);
return true;
}
}
}
else
public HelpCommand(ChatCommandRouter router)
{
await ctx.SendMessage(router.GetHelpTextFor(ctx.Command.Parameters[0], currentLocale));
return true;
Router = router;
}
}
}

View File

@ -1,29 +1,31 @@
using JetKarmaBot.Services.Handling;
using System.Collections.Generic;
using Telegram.Bot.Args;
namespace JetKarmaBot.Commands;
public interface IChatCommand
namespace JetKarmaBot.Commands
{
IReadOnlyCollection<string> Names { get; }
string Description { get; }
string DescriptionID { get; }
IReadOnlyCollection<ChatCommandArgument> Arguments { get; }
public interface IChatCommand
{
IReadOnlyCollection<string> Names { get; }
string Description { get; }
string DescriptionID { get; }
IReadOnlyCollection<ChatCommandArgument> Arguments { get; }
Task<bool> Execute(RequestContext ctx);
}
bool Execute(CommandString cmd, MessageEventArgs messageEventArgs);
}
public struct ChatCommandArgument
{
public string Name;
public bool Required;
public ChatCommandArgumentType Type;
public string Description;
public string DescriptionID;
}
public struct ChatCommandArgument
{
public string Name;
public bool Required;
public ChatCommandArgumentType Type;
public string Description;
public string DescriptionID;
}
public enum ChatCommandArgumentType
{
Boolean,
String,
Integer,
public enum ChatCommandArgumentType
{
Boolean,
String,
Integer,
}
}

View File

@ -1,65 +0,0 @@
using Microsoft.EntityFrameworkCore;
using JetKarmaBot.Services.Handling;
using JetKarmaBot.Models;
namespace JetKarmaBot.Commands;
class LeaderboardCommand : IChatCommand
{
public IReadOnlyCollection<string> Names => new[] { "leaderboard" };
public async Task<bool> Execute(RequestContext ctx)
{
bool isPrivate = ctx.EventArgs.Message.Chat.Type == Telegram.Bot.Types.Enums.ChatType.Private;
var currentLocale = ctx.GetFeature<Locale>();
if (isPrivate)
{
await ctx.SendMessage(currentLocale["jetkarmabot.award.errawardself"]);
return true;
}
var db = ctx.GetFeature<KarmaContext>();
var asker = ctx.EventArgs.Message.From;
var awardTypeName = ctx.Command.Parameters.FirstOrDefault();
if (string.IsNullOrWhiteSpace(awardTypeName))
awardTypeName = "star";
var awardTypeIdQuery = from awt in db.AwardTypes
where awt.CommandName == awardTypeName
select awt.AwardTypeId;
var awardTypeId = await awardTypeIdQuery.FirstAsync();
var awardType = await db.AwardTypes.FindAsync(awardTypeId);
var topEarners = await db.Awards
.Where(x => x.ChatId == ctx.EventArgs.Message.Chat.Id && x.AwardTypeId == awardTypeId)
.GroupBy(x => x.To)
.Select(x => new { User = x.Key, Amount = x.Sum(y => y.Amount) })
.OrderByDescending(x => x.Amount)
.Take(5)
.ToListAsync();
var response = string.Format(currentLocale["jetkarmabot.leaderboard.specifictext"], awardType.Symbol) + "\n"
+ string.Join('\n', topEarners.Select((x, index)
=> $"{index + 1}. {x.User.Username} - {x.Amount}")
);
await ctx.SendMessage(response);
return true;
}
[Inject] Localization Locale { get; set; }
public string Description => "Shows the people with the most of a specific award.";
public string DescriptionID => "jetkarmabot.leaderboard.help";
public IReadOnlyCollection<ChatCommandArgument> Arguments => new ChatCommandArgument[] {
new ChatCommandArgument() {
Name="awardtype",
Required=true,
Type=ChatCommandArgumentType.String,
Description="The awardtype to show a leaderboard for.",
DescriptionID= "jetkarmabot.leaderboard.awardtypehelp"
}
};
}

View File

@ -1,51 +1,83 @@
using Microsoft.EntityFrameworkCore;
using JetKarmaBot.Services.Handling;
using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using Perfusion;
using Telegram.Bot;
using Telegram.Bot.Args;
using Telegram.Bot.Types;
using JetKarmaBot.Models;
using JetKarmaBot.Services;
namespace JetKarmaBot.Commands;
class StatusCommand : IChatCommand
namespace JetKarmaBot.Commands
{
public IReadOnlyCollection<string> Names => ["status"];
public async Task<bool> Execute(RequestContext ctx)
class StatusCommand : IChatCommand
{
var db = ctx.GetFeature<KarmaContext>();
var currentLocale = ctx.GetFeature<Locale>();
var asker = ctx.EventArgs.Message.From;
bool isPrivate = ctx.EventArgs.Message.Chat.Type == Telegram.Bot.Types.Enums.ChatType.Private;
public IReadOnlyCollection<string> Names => new[] { "status" };
string response;
var awards = db.Awards.Where(x => x.ToId == asker.Id);
if (!isPrivate)
awards = awards.Where(x => x.ChatId == ctx.EventArgs.Message.Chat.Id);
if (!awards.Any())
response = currentLocale["jetkarmabot.status.havenothing"];
else
public bool Execute(CommandString cmd, MessageEventArgs args)
{
var aq = db.AwardTypes.GroupJoin(
awards,
at => at.AwardTypeId,
aw => aw.AwardTypeId,
(at, aws) => new {at.Symbol, Amount = aws.Sum(aw => aw.Amount) });
var awardsByType = await aq.ToListAsync();
response =
currentLocale["jetkarmabot.status.listalltext"] + "\n"
+ string.Join("\n", awardsByType.Select(a => $" - {a.Symbol} {a.Amount}"));
using (var db = Db.GetContext())
{
var currentLocale = Locale[db.Chats.Find(args.Message.Chat.Id).Locale];
var asker = args.Message.From;
var awardTypeName = cmd.Parameters.FirstOrDefault();
string response;
if (string.IsNullOrWhiteSpace(awardTypeName))
{
// var awards = db.Awards.Where(x => x.ToId == asker.Id)
// .GroupBy(x => x.AwardTypeId)
// .Select(x => new { AwardTypeId = x.Key, Amount = x.Sum(y => y.Amount) });
if (!db.Awards.Any(x => x.ToId == asker.Id))
response = currentLocale["jetkarmabot.status.havenothing"];
else
{
var awardsQuery = from award in db.Awards
where award.ToId == asker.Id
group award by award.AwardTypeId into g
select new { AwardTypeId = g.Key, Amount = g.Sum(x => x.Amount) };
var awardsByType = awardsQuery.ToList();
response = currentLocale["jetkarmabot.status.listalltext"] + "\n"
+ string.Join("\n", awardsByType.Select(a => $" - {db.AwardTypes.Find(a.AwardTypeId).Symbol} {a.Amount}"));
}
}
else
{
var awardTypeIdQuery = from awt in db.AwardTypes
where awt.CommandName == awardTypeName
select awt.AwardTypeId;
var awardTypeId = awardTypeIdQuery.First();
var awardType = db.AwardTypes.Find(awardTypeId);
response = string.Format(currentLocale["jetkarmabot.status.listspecifictext"], db.Awards.Where(x => x.AwardTypeId == awardTypeId && x.ToId == asker.Id).Sum(x => x.Amount), awardType.Symbol);
}
Client.SendTextMessageAsync(
args.Message.Chat.Id,
response,
replyToMessageId: args.Message.MessageId);
return true;
}
}
await ctx.SendMessage(response);
return true;
[Inject] KarmaContextFactory Db { get; set; }
[Inject] TelegramBotClient Client { get; set; }
[Inject] Localization Locale { get; set; }
public string Description => "Shows the amount of awards that you have";
public string DescriptionID => "jetkarmabot.status.help";
public IReadOnlyCollection<ChatCommandArgument> Arguments => new ChatCommandArgument[] {
new ChatCommandArgument(){
Name="awardtype",
Required=false,
Type=ChatCommandArgumentType.String,
Description="The awardtype to show. If empty shows everything.",
DescriptionID= "jetkarmabot.status.awardtypehelp"
}
};
}
[Inject] Localization Locale { get; set; }
public string Description => "Shows the amount of awards that you have";
public string DescriptionID => "jetkarmabot.status.help";
public IReadOnlyCollection<ChatCommandArgument> Arguments => [];
}

View File

@ -3,74 +3,62 @@ using Newtonsoft.Json;
using JsonNet.PrivateSettersContractResolvers;
using Newtonsoft.Json.Linq;
namespace JetKarmaBot;
public class Config : ConfigBase
namespace JetKarmaBot
{
public Config(string path) : base(path) { }
public string ApiKey { get; private set; }
public string ConnectionString { get; private set; }
public class ProxySettings
public class Config : ConfigBase
{
public string Url { get; private set; }
public int Port { get; private set; }
public string Login { get; private set; }
public string Password { get; private set; }
public Config(string path) : base(path) { }
public string ApiKey { get; private set; }
public string ConnectionString { get; private set; }
public class ProxySettings
{
public string Url { get; private set; }
public int Port { get; private set; }
public string Login { get; private set; }
public string Password { get; private set; }
}
public ProxySettings Proxy { get; private set; }
public bool SqlDebug { get; private set; }
}
public ProxySettings Proxy { get; private set; }
public class TimeoutConfig
public abstract class ConfigBase
{
public int DebtLimitSeconds { get; private set; } = 60 * 60 * 2;
public Dictionary<string, int> CommandCostsSeconds { get; private set; } = new Dictionary<string, int>()
public ConfigBase(string path)
{
{"JetKarmaBot.Commands.AwardCommand (OK)", 60*15},
{"JetKarmaBot.Commands.AwardCommand (ERR)", 60*5},
{"Default", 60*5}
};
public int SaveIntervalSeconds { get; private set; } = 60 * 5;
public double AwardTimeSeconds { get; private set; } = 60;
}
public TimeoutConfig Timeout { get; private set; } = new TimeoutConfig();
public bool SqlDebug { get; private set; } = false;
}
JObject configJson;
public abstract class ConfigBase
{
public ConfigBase(string path)
{
JObject configJson;
if (File.Exists(path))
{
configJson = JObject.Parse(File.ReadAllText(path));
using (var sr = configJson.CreateReader())
if (File.Exists(path))
{
var settings = new JsonSerializerSettings
configJson = JObject.Parse(File.ReadAllText(path));
using (var sr = configJson.CreateReader())
{
ContractResolver = new PrivateSetterContractResolver()
};
JsonSerializer.CreateDefault(settings).Populate(sr, this);
var settings = new JsonSerializerSettings
{
ContractResolver = new PrivateSetterContractResolver()
};
JsonSerializer.CreateDefault(settings).Populate(sr, this);
}
}
else configJson = new JObject();
configJson.Merge(JToken.FromObject(this), new JsonMergeSettings
{
MergeArrayHandling = MergeArrayHandling.Union
});
try // populate possible missing properties in file
{
File.WriteAllText(path, configJson.ToString(Formatting.Indented));
}
catch (IOException e)
{
System.Diagnostics.Debug.WriteLine(e);
}
}
else configJson = new JObject();
configJson.Merge(JToken.FromObject(this), new JsonMergeSettings
{
MergeArrayHandling = MergeArrayHandling.Union
});
try // populate possible missing properties in file
{
File.WriteAllText(path, configJson.ToString(Formatting.Indented));
}
catch (IOException e)
{
System.Diagnostics.Debug.WriteLine(e);
}
}
}

View File

@ -1,12 +1,15 @@
namespace JetKarmaBot;
using System.Collections.Generic;
public static class IReadOnlyDictionaryExtensions
namespace JetKarmaBot
{
public static TValue GetOrDefault<TKey, TValue>(this IReadOnlyDictionary<TKey, TValue> dict, TKey key)
public static class IReadOnlyDictionaryExtensions
{
TValue res = default;
if (key != null)
dict.TryGetValue(key, out res);
return res;
public static TValue GetOrDefault<TKey, TValue>(this IReadOnlyDictionary<TKey, TValue> dict, TKey key)
{
TValue res = default(TValue);
if (key != null)
dict.TryGetValue(key, out res);
return res;
}
}
}

View File

@ -3,42 +3,43 @@ using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
// ReSharper disable once CheckNamespace
namespace JsonNet.PrivateSettersContractResolvers;
public class PrivateSetterContractResolver : DefaultContractResolver
namespace JsonNet.PrivateSettersContractResolvers
{
protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
public class PrivateSetterContractResolver : DefaultContractResolver
{
var jProperty = base.CreateProperty(member, memberSerialization);
if (jProperty.Writable)
protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
{
var jProperty = base.CreateProperty(member, memberSerialization);
if (jProperty.Writable)
return jProperty;
jProperty.Writable = member.IsPropertyWithSetter();
return jProperty;
jProperty.Writable = member.IsPropertyWithSetter();
return jProperty;
}
}
}
public class PrivateSetterCamelCasePropertyNamesContractResolver : CamelCasePropertyNamesContractResolver
{
protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
public class PrivateSetterCamelCasePropertyNamesContractResolver : CamelCasePropertyNamesContractResolver
{
var jProperty = base.CreateProperty(member, memberSerialization);
if (jProperty.Writable)
protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
{
var jProperty = base.CreateProperty(member, memberSerialization);
if (jProperty.Writable)
return jProperty;
jProperty.Writable = member.IsPropertyWithSetter();
return jProperty;
jProperty.Writable = member.IsPropertyWithSetter();
return jProperty;
}
}
}
internal static class MemberInfoExtensions
{
internal static bool IsPropertyWithSetter(this MemberInfo member)
internal static class MemberInfoExtensions
{
var property = member as PropertyInfo;
internal static bool IsPropertyWithSetter(this MemberInfo member)
{
var property = member as PropertyInfo;
return property?.GetSetMethod(true) != null;
return property?.GetSetMethod(true) != null;
}
}
}

View File

@ -1,6 +0,0 @@
global using System;
global using System.Collections.Generic;
global using System.Linq;
global using System.Threading;
global using System.Threading.Tasks;
global using Perfusion;

View File

@ -1,137 +1,96 @@
using JetKarmaBot.Commands;
using JetKarmaBot.Models;
using JetKarmaBot.Services;
using JetKarmaBot.Services.Handling;
using NLog;
using Perfusion;
using System;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using Telegram.Bot;
using Telegram.Bot.Polling;
using Telegram.Bot.Args;
using Telegram.Bot.Types;
using Telegram.Bot.Types.Enums;
namespace JetKarmaBot;
public class JetKarmaBot : IDisposable
namespace JetKarmaBot
{
[Inject] Config Config { get; set; }
[Inject] IContainer Container { get; set; }
[Inject] KarmaContextFactory Db { get; set; }
[Inject] TimeoutManager Timeout { get; set; }
[Inject] Localization Locale { get; set; }
[Inject] Logger Log { get; set; }
TelegramBotClient Client { get; set; }
ChatCommandRouter Commands;
RequestChain Chain;
Task timeoutWaitTask;
CancellationTokenSource timeoutWaitTaskToken;
private bool stopped = false;
public async Task Init()
public class JetKarmaBot : IDisposable
{
using (KarmaContext db = Db.GetContext())
await db.Database.EnsureCreatedAsync();
Client = new TelegramBotClient(Config.ApiKey);
Container.AddInstance(Client);
[Inject] Config Config { get; set; }
[Inject] IContainer Container { get; set; }
[Inject] KarmaContextFactory Db { get; set; }
timeoutWaitTaskToken = new CancellationTokenSource();
timeoutWaitTask = Timeout.SaveLoop(timeoutWaitTaskToken.Token);
TelegramBotClient Client { get; set; }
ChatCommandRouter Commands;
Telegram.Bot.Types.User Me { get; set; }
await InitCommands(Container);
InitChain(Container);
var receiverOptions = new ReceiverOptions { AllowedUpdates = new[] { UpdateType.Message } };
Client.StartReceiving(
HandleUpdateAsync,
HandleErrorAsync,
receiverOptions);
}
public async Task Stop()
{
if (stopped) return;
Client?.CloseAsync();
timeoutWaitTaskToken?.Cancel();
try
public async Task Init()
{
if (timeoutWaitTask != null)
await timeoutWaitTask;
using (KarmaContext db = Db.GetContext())
await db.Database.EnsureCreatedAsync();
var httpProxy = new WebProxy($"{Config.Proxy.Url}:{Config.Proxy.Port}")
{
Credentials = new NetworkCredential(Config.Proxy.Login, Config.Proxy.Password)
};
Client = new TelegramBotClient(Config.ApiKey, httpProxy);
Container.AddInstance(Client);
Me = await Client.GetMeAsync();
InitCommands(Container);
Client.OnMessage += BotOnMessageReceived;
Client.StartReceiving();
}
catch (OperationCanceledException) { }
await Timeout?.Save();
Dispose();
stopped = true;
}
#region service
Task HandleErrorAsync(ITelegramBotClient botClient, Exception exception, CancellationToken cancellationToken)
{
Log.Error(exception, "Exception while handling API message");
return Task.CompletedTask;
}
async Task HandleUpdateAsync(ITelegramBotClient sender, Update update, CancellationToken cancellationToken)
{
if (update.Type != UpdateType.Message || update?.Message?.Type != MessageType.Text)
return;
var message = update.Message!;
try
public async Task Stop()
{
Dispose();
}
#region service
void BotOnMessageReceived(object sender, MessageEventArgs messageEventArgs)
{
var message = messageEventArgs.Message;
if (message == null || message.Type != MessageType.Text)
return;
if (!CommandString.TryParse(message.Text, out var cmd))
return;
if (cmd.UserName != null && cmd.UserName != Commands.Me.Username)
return;
RequestContext ctx = new RequestContext(Client, update, cmd);
await Chain.Handle(ctx);
using (KarmaContext db = Db.GetContext())
{
if (!db.Users.Any(x => x.UserId == messageEventArgs.Message.From.Id))
db.Users.Add(new Models.User { UserId = messageEventArgs.Message.From.Id });
if (messageEventArgs.Message.ReplyToMessage != null)
if (!db.Users.Any(x => x.UserId == messageEventArgs.Message.ReplyToMessage.From.Id))
db.Users.Add(new Models.User { UserId = messageEventArgs.Message.ReplyToMessage.From.Id });
if (!db.Chats.Any(x => x.ChatId == messageEventArgs.Message.Chat.Id))
db.Chats.Add(new Models.Chat { ChatId = messageEventArgs.Message.Chat.Id });
db.SaveChanges();
}
string s = message.Text;
long id = message.Chat.Id;
long from = message.From.Id;
Task.Run(() => Commands.Execute(sender, messageEventArgs));
}
catch (Exception e)
void InitCommands(IContainer c)
{
Log.Error(e, "Exception while handling message {0}", message);
Commands = c.ResolveObject(new ChatCommandRouter(Me));
Commands.Add(c.ResolveObject(new HelpCommand(Commands)));
Commands.Add(c.ResolveObject(new AwardCommand(Me)));
Commands.Add(c.ResolveObject(new StatusCommand()));
Commands.Add(c.ResolveObject(new LocaleCommand()));
Commands.Add(c.ResolveObject(new CurrenciesCommand()));
}
}
async Task InitCommands(IContainer c)
{
c.Add<HelpCommand>();
c.Add<AwardCommand>();
c.Add<StatusCommand>();
c.Add<LocaleCommand>();
c.Add<CurrenciesCommand>();
c.Add<LeaderboardCommand>();
Commands = c.GetInstance<ChatCommandRouter>();
await Commands.Start();
foreach (IChatCommand cmd in c.GetInstances<IChatCommand>())
#endregion
#region IDisposable
public void Dispose()
{
Commands.Add(cmd);
Client.StopReceiving();
}
#endregion
}
void InitChain(IContainer c)
{
Chain = c.ResolveObject(new RequestChain());
Chain.Add(c.GetInstance<TimeoutManager.PreDbThrowout>());
Chain.Add(c.GetInstance<DatabaseHandler>());
Chain.Add(Timeout);
Chain.Add(c.GetInstance<SaveData>());
Chain.Add(Commands);
}
#endregion
#region IDisposable
public void Dispose()
{
timeoutWaitTaskToken?.Dispose();
timeoutWaitTask?.Dispose();
}
#endregion
}

View File

@ -1,20 +1,31 @@
<Project Sdk="Microsoft.NET.Sdk">
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework>
<TargetFrameworks>netcoreapp2.2;</TargetFrameworks>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
<PackageReference Include="Pomelo.EntityFrameworkCore.MySql" Version="8.0.2" />
<PackageReference Include="Telegram.Bot" Version="22.0.2" />
<PackageReference Include="NLog" Version="5.3.4" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="2.2.4">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers</IncludeAssets>
</PackageReference>
<PackageReference Include="Newtonsoft.Json" Version="12.0.2" />
<PackageReference Include="Pomelo.EntityFrameworkCore.MySql" Version="2.2.0" />
<PackageReference Include="Telegram.Bot" Version="14.12.0" />
<PackageReference Include="NLog" Version="4.6.5" />
<PackageReference Include="NLog.Config" Version="4.6.5" />
<ProjectReference Include="..\perfusion\Perfusion\Perfusion.csproj" />
</ItemGroup>
<ItemGroup>
<None Update="karma.cfg.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Update="lang\*">
<None Update="lang\be-BY.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Update="lang\en-US.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Update="lang\ru-RU.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Update="NLog.config">

View File

@ -1,22 +1,25 @@
using System.ComponentModel.DataAnnotations.Schema;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
namespace JetKarmaBot.Models;
public partial class Award
namespace JetKarmaBot.Models
{
public int AwardId { get; set; }
public long ChatId { get; set; }
public long FromId { get; set; }
public long ToId { get; set; }
public sbyte AwardTypeId { get; set; }
public sbyte Amount { get; set; }
public DateTime Date { get; set; }
[ForeignKey("AwardTypeId")]
public virtual AwardType AwardType { get; set; }
[ForeignKey("ChatId")]
public virtual Chat Chat { get; set; }
[ForeignKey("FromId")]
public virtual User From { get; set; }
[ForeignKey("ToId")]
public virtual User To { get; set; }
public partial class Award
{
public int AwardId { get; set; }
public long ChatId { get; set; }
public int FromId { get; set; }
public int ToId { get; set; }
public sbyte AwardTypeId { get; set; }
public sbyte Amount { get; set; }
public DateTime Date { get; set; }
[ForeignKey("AwardTypeId")]
public virtual AwardType AwardType { get; set; }
[ForeignKey("ChatId")]
public virtual Chat Chat { get; set; }
[ForeignKey("FromId")]
public virtual User From { get; set; }
[ForeignKey("ToId")]
public virtual User To { get; set; }
}
}

View File

@ -1,17 +1,21 @@
namespace JetKarmaBot.Models;
using System;
using System.Collections.Generic;
public partial class AwardType
namespace JetKarmaBot.Models
{
public AwardType()
public partial class AwardType
{
Awards = new HashSet<Award>();
public AwardType()
{
Awards = new HashSet<Award>();
}
public sbyte AwardTypeId { get; set; }
public string CommandName { get; set; }
public string Name { get; set; }
public string Symbol { get; set; }
public string Description { get; set; }
public virtual ICollection<Award> Awards { get; set; }
}
public sbyte AwardTypeId { get; set; }
public string CommandName { get; set; }
public string Name { get; set; }
public string Symbol { get; set; }
public string Description { get; set; }
public virtual ICollection<Award> Awards { get; set; }
}

View File

@ -1,15 +1,19 @@
namespace JetKarmaBot.Models;
using System;
using System.Collections.Generic;
public partial class Chat
namespace JetKarmaBot.Models
{
public Chat()
public partial class Chat
{
Awards = new HashSet<Award>();
public Chat()
{
Awards = new HashSet<Award>();
}
public long ChatId { get; set; }
public string Locale { get; set; }
public bool IsAdministrator { get; set; }
public virtual ICollection<Award> Awards { get; set; }
}
public long ChatId { get; set; }
public string Locale { get; set; } = "ru-RU";
public bool IsAdministrator { get; set; }
public virtual ICollection<Award> Awards { get; set; }
}

View File

@ -1,179 +1,178 @@
using Microsoft.EntityFrameworkCore;
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata;
using Perfusion;
namespace JetKarmaBot.Models;
[Transient]
public partial class KarmaContext : DbContext
namespace JetKarmaBot.Models
{
public KarmaContext()
[Transient]
public partial class KarmaContext : DbContext
{
}
public KarmaContext(DbContextOptions<KarmaContext> options)
: base(options)
{
}
public virtual DbSet<Award> Awards { get; set; }
public virtual DbSet<AwardType> AwardTypes { get; set; }
public virtual DbSet<Chat> Chats { get; set; }
public virtual DbSet<User> Users { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Award>(entity =>
public KarmaContext()
{
entity.ToTable("award");
}
entity.HasIndex(e => e.AwardId)
.HasDatabaseName("awardid_UNIQUE")
.IsUnique();
entity.HasIndex(e => e.AwardTypeId)
.HasDatabaseName("fk_awardtype_idx");
entity.HasIndex(e => e.ChatId)
.HasDatabaseName("fk_chat_idx");
entity.HasIndex(e => e.FromId)
.HasDatabaseName("fk_from_idx");
entity.HasIndex(e => e.ToId)
.HasDatabaseName("fk_to_idx");
entity.Property(e => e.AwardId)
.HasColumnName("awardid")
.HasColumnType("int(11)");
entity.Property(e => e.Amount)
.HasColumnName("amount")
.HasColumnType("tinyint(3)")
.HasDefaultValueSql("'1'");
entity.Property(e => e.AwardTypeId)
.HasColumnName("awardtypeid")
.HasColumnType("tinyint(3)");
entity.Property(e => e.ChatId)
.HasColumnName("chatid")
.HasColumnType("bigint(20)");
entity.Property(e => e.Date)
.HasColumnName("date")
.HasColumnType("datetime")
.HasDefaultValueSql("CURRENT_TIMESTAMP");
entity.Property(e => e.FromId)
.HasColumnName("fromid")
.HasColumnType("bigint(20)");
entity.Property(e => e.ToId)
.HasColumnName("toid")
.HasColumnType("bigint(20)");
entity.HasOne(d => d.AwardType)
.WithMany(p => p.Awards)
.HasForeignKey(d => d.AwardTypeId)
.OnDelete(DeleteBehavior.ClientSetNull)
.HasConstraintName("fk_awardtype");
entity.HasOne(d => d.Chat)
.WithMany(p => p.Awards)
.HasForeignKey(d => d.ChatId)
.OnDelete(DeleteBehavior.ClientSetNull)
.HasConstraintName("fk_chat");
entity.HasOne(d => d.From)
.WithMany(p => p.AwardsFrom)
.HasForeignKey(d => d.FromId)
.OnDelete(DeleteBehavior.ClientSetNull)
.HasConstraintName("fk_from");
entity.HasOne(d => d.To)
.WithMany(p => p.AwardsTo)
.HasForeignKey(d => d.ToId)
.OnDelete(DeleteBehavior.ClientSetNull)
.HasConstraintName("fk_to");
});
modelBuilder.Entity<AwardType>(entity =>
public KarmaContext(DbContextOptions<KarmaContext> options)
: base(options)
{
entity.ToTable("awardtype");
}
entity.HasIndex(e => e.AwardTypeId)
.HasDatabaseName("awardtypeid_UNIQUE")
.IsUnique();
public virtual DbSet<Award> Awards { get; set; }
public virtual DbSet<AwardType> AwardTypes { get; set; }
public virtual DbSet<Chat> Chats { get; set; }
public virtual DbSet<User> Users { get; set; }
entity.HasIndex(e => e.CommandName)
.HasDatabaseName("commandname_UNIQUE")
.IsUnique();
entity.Property(e => e.AwardTypeId)
.HasColumnName("awardtypeid")
.HasColumnType("tinyint(3)");
entity.Property(e => e.CommandName)
.IsRequired()
.HasColumnName("commandname")
.HasColumnType("varchar(35)");
entity.Property(e => e.Description)
.IsRequired()
.HasColumnName("description")
.HasColumnType("text");
entity.Property(e => e.Name)
.IsRequired()
.HasColumnName("name")
.HasColumnType("varchar(32)");
entity.Property(e => e.Symbol)
.IsRequired()
.HasColumnName("symbol")
.HasColumnType("varchar(16)");
});
modelBuilder.Entity<Chat>(entity =>
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
entity.ToTable("chat");
entity.Property(e => e.ChatId)
.HasColumnName("chatid")
.HasColumnType("bigint(20)");
}
entity.Property(e => e.Locale)
.IsRequired()
.HasColumnName("locale")
.HasColumnType("varchar(10)")
.HasDefaultValueSql("'ru-RU'");
entity.Property(e => e.IsAdministrator)
.HasColumnName("isadministrator")
.HasColumnType("tinyint(1)")
.HasDefaultValueSql("'0'");
});
modelBuilder.Entity<User>(entity =>
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
entity.ToTable("user");
modelBuilder.Entity<Award>(entity =>
{
entity.ToTable("award");
entity.Property(e => e.UserId)
.HasColumnName("userid")
.HasColumnType("bigint(20)");
entity.HasIndex(e => e.AwardId)
.HasName("awardid_UNIQUE")
.IsUnique();
entity.Property(e => e.Username)
.HasColumnName("username")
.HasColumnType("varchar(45)");
entity.HasIndex(e => e.AwardTypeId)
.HasName("fk_awardtype_idx");
entity.Property(e => e.CooldownDate)
.HasColumnName("cooldowndate")
.HasColumnType("timestamp")
.HasDefaultValueSql("CURRENT_TIMESTAMP");
});
entity.HasIndex(e => e.ChatId)
.HasName("fk_chat_idx");
entity.HasIndex(e => e.FromId)
.HasName("fk_from_idx");
entity.HasIndex(e => e.ToId)
.HasName("fk_to_idx");
entity.Property(e => e.AwardId)
.HasColumnName("awardid")
.HasColumnType("int(11)");
entity.Property(e => e.Amount)
.HasColumnName("amount")
.HasColumnType("tinyint(3)")
.HasDefaultValueSql("'1'");
entity.Property(e => e.AwardTypeId)
.HasColumnName("awardtypeid")
.HasColumnType("tinyint(3)");
entity.Property(e => e.ChatId)
.HasColumnName("chatid")
.HasColumnType("bigint(20)");
entity.Property(e => e.Date)
.HasColumnName("date")
.HasColumnType("datetime")
.HasDefaultValueSql("CURRENT_TIMESTAMP");
entity.Property(e => e.FromId)
.HasColumnName("fromid")
.HasColumnType("bigint(20)");
entity.Property(e => e.ToId)
.HasColumnName("toid")
.HasColumnType("bigint(20)");
entity.HasOne(d => d.AwardType)
.WithMany(p => p.Awards)
.HasForeignKey(d => d.AwardTypeId)
.OnDelete(DeleteBehavior.ClientSetNull)
.HasConstraintName("fk_awardtype");
entity.HasOne(d => d.Chat)
.WithMany(p => p.Awards)
.HasForeignKey(d => d.ChatId)
.OnDelete(DeleteBehavior.ClientSetNull)
.HasConstraintName("fk_chat");
entity.HasOne(d => d.From)
.WithMany(p => p.AwardsFrom)
.HasForeignKey(d => d.FromId)
.OnDelete(DeleteBehavior.ClientSetNull)
.HasConstraintName("fk_from");
entity.HasOne(d => d.To)
.WithMany(p => p.AwardsTo)
.HasForeignKey(d => d.ToId)
.OnDelete(DeleteBehavior.ClientSetNull)
.HasConstraintName("fk_to");
});
modelBuilder.Entity<AwardType>(entity =>
{
entity.ToTable("awardtype");
entity.HasIndex(e => e.AwardTypeId)
.HasName("awardtypeid_UNIQUE")
.IsUnique();
entity.HasIndex(e => e.CommandName)
.HasName("commandname_UNIQUE")
.IsUnique();
entity.Property(e => e.AwardTypeId)
.HasColumnName("awardtypeid")
.HasColumnType("tinyint(3)");
entity.Property(e => e.CommandName)
.IsRequired()
.HasColumnName("commandname")
.HasColumnType("varchar(35)");
entity.Property(e => e.Description)
.IsRequired()
.HasColumnName("description")
.HasColumnType("text");
entity.Property(e => e.Name)
.IsRequired()
.HasColumnName("name")
.HasColumnType("varchar(32)");
entity.Property(e => e.Symbol)
.IsRequired()
.HasColumnName("symbol")
.HasColumnType("varchar(16)");
});
modelBuilder.Entity<Chat>(entity =>
{
entity.ToTable("chat");
entity.Property(e => e.ChatId)
.HasColumnName("chatid")
.HasColumnType("bigint(20)");
entity.Property(e => e.Locale)
.IsRequired()
.HasColumnName("locale")
.HasColumnType("varchar(10)")
.HasDefaultValueSql("'ru-RU'");
entity.Property(e => e.IsAdministrator)
.HasColumnName("isadministrator")
.HasColumnType("tinyint(1)")
.HasDefaultValueSql("'0'");
});
modelBuilder.Entity<User>(entity =>
{
entity.ToTable("user");
entity.Property(e => e.UserId)
.HasColumnName("userid")
.HasColumnType("bigint(20)");
entity.Property(e => e.Username)
.HasColumnName("username")
.HasColumnType("varchar(45)");
});
}
}
}

View File

@ -1,20 +1,22 @@
using System.ComponentModel.DataAnnotations.Schema;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
namespace JetKarmaBot.Models;
public partial class User
namespace JetKarmaBot.Models
{
public User()
public partial class User
{
AwardsFrom = new HashSet<Award>();
AwardsTo = new HashSet<Award>();
}
public User()
{
AwardsFrom = new HashSet<Award>();
AwardsTo = new HashSet<Award>();
}
public long UserId { get; set; }
public string Username { get; set; }
public DateTime CooldownDate { get; set; }
[InverseProperty("From")]
public virtual ICollection<Award> AwardsFrom { get; set; }
[InverseProperty("To")]
public virtual ICollection<Award> AwardsTo { get; set; }
public int UserId { get; set; }
public string Username { get; set; }
[InverseProperty("From")]
public virtual ICollection<Award> AwardsFrom { get; set; }
[InverseProperty("To")]
public virtual ICollection<Award> AwardsTo { get; set; }
}
}

View File

@ -1,73 +1,70 @@
using Microsoft.EntityFrameworkCore;
using NLog;
using System;
using System.Threading;
using JetKarmaBot.Models;
using Microsoft.EntityFrameworkCore;
using NLog;
using Perfusion;
namespace JetKarmaBot;
public static class Program
namespace JetKarmaBot
{
private static Logger log = LogManager.GetCurrentClassLogger();
public enum ExitCode : int
public static class Program
{
Ok = 0,
ErrorNotStarted = 0x80,
ErrorRunning = 0x81,
ErrorException = 0x82,
ErrorInvalidCommandLine = 0x100
};
public static int Main(string[] args)
{
log.Info("Starting JetKarmaBot.");
Container c = new Container();
var cfg = new Config("karma.cfg.json");
c.AddInstance(cfg);
var connStr = cfg.ConnectionString + (cfg.ConnectionString.EndsWith(";") ? "" : ";") + "TreatTinyAsBoolean=false";
var serverVersion = ServerVersion.AutoDetect(connStr);
var dbOptions = new DbContextOptionsBuilder<KarmaContext>()
.UseMySql(connStr, serverVersion);
c.AddInfo<Logger>(new LogInfo());
if (cfg.SqlDebug)
private static Logger log = LogManager.GetCurrentClassLogger();
public enum ExitCode : int
{
dbOptions = dbOptions.UseLoggerFactory(c.GetInstance<NLoggerFactory>());
}
c.AddTransient(() => new KarmaContext(dbOptions.Options));
c.Add<JetKarmaBot>();
Ok = 0,
ErrorNotStarted = 0x80,
ErrorRunning = 0x81,
ErrorException = 0x82,
ErrorInvalidCommandLine = 0x100
};
var bot = c.GetInstance<JetKarmaBot>();
public static int Main(string[] args)
{
log.Info("Starting JetKarmaBot.");
Container c = new Container();
var cfg = new Config("karma.cfg.json");
c.AddInstance(cfg);
try
{
bot.Init().GetAwaiter().GetResult();
log.Info("JetKarmaBot started. Press Ctrl-C to exit...");
}
catch (Exception ex)
{
log.Error(ex);
return (int)ExitCode.ErrorException;
}
ManualResetEvent quitEvent = new ManualResetEvent(false);
try
{
Console.CancelKeyPress += (sender, eArgs) => // ctrl-c
var dbOptions = new DbContextOptionsBuilder<KarmaContext>()
.UseMySql(cfg.ConnectionString + (cfg.ConnectionString.EndsWith(";") ? "" : ";") + "TreatTinyAsBoolean=false");
c.AddInfo<Logger>(new LogInfo());
if (cfg.SqlDebug)
{
eArgs.Cancel = true;
quitEvent.Set();
};
AppDomain.CurrentDomain.ProcessExit += (sender, args) =>
dbOptions = dbOptions.UseLoggerFactory(c.GetInstance<NLoggerFactory>());
}
c.AddTransient(() => new KarmaContext(dbOptions.Options));
c.Add<JetKarmaBot>();
var bot = c.GetInstance<JetKarmaBot>();
try
{
log.Info("Received stop request, waiting for exit...");
bot?.Stop()?.GetAwaiter().GetResult();
};
bot.Init().Wait();
log.Info("JetKarmaBot started. Press Ctrl-C to exit...");
Environment.ExitCode = (int)ExitCode.ErrorRunning;
}
catch (Exception ex)
{
log.Error(ex);
Environment.ExitCode = (int)ExitCode.ErrorException;
}
ManualResetEvent quitEvent = new ManualResetEvent(false);
try
{
Console.CancelKeyPress += (sender, eArgs) => // ctrl-c
{
eArgs.Cancel = true;
quitEvent.Set();
};
}
catch { }
quitEvent.WaitOne(Timeout.Infinite);
log.Info("Waiting for exit...");
bot?.Stop()?.Wait();
return (int)ExitCode.Ok;
}
catch { }
quitEvent.WaitOne(Timeout.Infinite);
log.Info("Waiting for exit...");
bot?.Stop()?.GetAwaiter().GetResult();
return (int)ExitCode.Ok;
}
}

View File

@ -1,105 +0,0 @@
using NLog;
using Telegram.Bot;
using JetKarmaBot.Commands;
namespace JetKarmaBot.Services.Handling;
public class ChatCommandRouter : IRequestHandler
{
public class Feature
{
public Type CommandType;
public ChatCommandRouter Router;
public bool Succeded;
}
public Telegram.Bot.Types.User Me { get; private set; }
[Inject] private Logger log;
[Inject] private TelegramBotClient Client { get; set; }
public async Task Start()
{
Me = await Client.GetMeAsync();
}
public Task Handle(RequestContext ctx, Func<RequestContext, Task> next)
{
log.Debug("Message received");
CommandString cmd = ctx.Command;
Feature feature = new Feature() { Router = this };
ctx.AddFeature(feature);
try
{
if (commands.ContainsKey(cmd.Command))
{
feature.CommandType = commands[cmd.Command].GetType();
log.Debug($"Handling message via {feature.CommandType.Name}");
async Task processCommand() => feature.Succeded = await commands[cmd.Command].Execute(ctx);
return processCommand();
}
}
catch (Exception e)
{
log.Error($"Error while handling command {cmd.Command}!");
log.Error(e);
}
return next(ctx);
}
public void Add(IChatCommand c)
{
log.ConditionalTrace($"Adding command {c.GetType().Name}");
foreach (var name in c.Names)
{
log.ConditionalTrace($"Mounting {c.GetType().Name} to {name}");
if (commands.ContainsKey(name))
throw new Exception($"command collision for name {name}, commands {commands[name].GetType()} and {c.GetType()}");
commands[name] = c;
}
}
internal string GetHelpText(Locale loc)
{
List<string> pieces = new List<string>();
foreach (IChatCommand c in commands.Values.Distinct())
{
string build = "";
List<string> names = c.Names.ToList();
for (int i = 0; i < names.Count - 1; i++)
{
build = build + "/" + names[i] + "\n";
}
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);
}
return string.Join("\n", pieces);
}
internal string GetHelpTextFor(string commandname, Locale loc)
{
IChatCommand c = commands[commandname];
string build = "";
List<string> names = c.Names.ToList();
for (int i = 0; i < names.Count - 1; i++)
{
build = build + "/" + names[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>" + getLocalizedCMDArgDesc(ca, loc) + "</i>"));
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>();
}

View File

@ -1,17 +0,0 @@
namespace JetKarmaBot.Services.Handling;
public class DatabaseHandler : IRequestHandler
{
[Inject] private KarmaContextFactory Db;
[Inject] private Localization Locale;
public async Task Handle(RequestContext ctx, Func<RequestContext, Task> next)
{
using (var db = Db.GetContext())
{
ctx.AddFeature(db); // KarmaContext
ctx.AddFeature(Locale[(await db.Chats.FindAsync(ctx.EventArgs.Message.Chat.Id))?.Locale ?? "ru-ru"]); // Locale
await next(ctx);
await db.SaveChangesAsync();
}
}
}

View File

@ -1,37 +0,0 @@
using NLog;
namespace JetKarmaBot.Services.Handling;
public interface IRequestHandler
{
Task Handle(RequestContext ctx, Func<RequestContext, Task> next);
}
public class RequestChain : IRequestHandler
{
[Inject] private Logger log;
List<IRequestHandler> handlerStack = new List<IRequestHandler>();
public async Task Handle(RequestContext ctx, Func<RequestContext, Task> next = null)
{
int i = 0;
Func<RequestContext, Task> chainNext = null;
chainNext = (newCtx) =>
{
if (i == handlerStack.Count)
{
log.ConditionalTrace("(next) End of request chain");
return Task.CompletedTask;
}
IRequestHandler handler = handlerStack[i++];
log.ConditionalTrace($"(next) Executing handler {handler.GetType().Name}");
return handler.Handle(newCtx, chainNext);
};
await chainNext(ctx);
if (next != null)
await next(ctx);
}
public void Add(IRequestHandler handler)
{
log.ConditionalTrace($"Adding {handler.GetType().Name} to reqchain");
handlerStack.Add(handler);
}
}

View File

@ -1,32 +0,0 @@
using Telegram.Bot;
using Telegram.Bot.Types;
using JetKarmaBot.Commands;
namespace JetKarmaBot.Services.Handling;
public class RequestContext : IServiceProvider
{
public ITelegramBotClient Client { get; }
public Update EventArgs { get; }
public CommandString Command { get; }
public Dictionary<Type, object> Features { get; } = new Dictionary<Type, object>();
public RequestContext(ITelegramBotClient client, Update args, CommandString cmd)
{
Client = client;
EventArgs = args;
Command = cmd;
}
public object GetService(Type serviceType) => Features[serviceType];
public T GetFeature<T>() => (T)Features[typeof(T)];
public void AddFeature<T>(T feat) => Features[typeof(T)] = feat;
//Method to reduce WET in commands
public Task SendMessage(string text)
=> Client.SendMessage(
chatId: EventArgs.Message.Chat.Id,
text: text,
disableNotification: true,
parseMode: Telegram.Bot.Types.Enums.ParseMode.Html,
replyParameters: new ReplyParameters { MessageId = EventArgs.Message.MessageId }
);
}

View File

@ -1,33 +0,0 @@
using Microsoft.EntityFrameworkCore;
using JetKarmaBot.Models;
namespace JetKarmaBot.Services.Handling;
public class SaveData : IRequestHandler
{
public async Task Handle(RequestContext ctx, Func<RequestContext, Task> next)
{
KarmaContext db = ctx.GetFeature<KarmaContext>();
await AddUserToDatabase(db, ctx.EventArgs.Message.From);
if (ctx.EventArgs.Message.ReplyToMessage != null)
await AddUserToDatabase(db, ctx.EventArgs.Message.ReplyToMessage.From);
if (!await db.Chats.AnyAsync(x => x.ChatId == ctx.EventArgs.Message.Chat.Id))
db.Chats.Add(new Models.Chat
{
ChatId = ctx.EventArgs.Message.Chat.Id
});
await next(ctx);
}
private async Task AddUserToDatabase(KarmaContext db, Telegram.Bot.Types.User u)
{
string un;
if (u.Username == null)
un = u.FirstName + (u.LastName != null ? " " + u.LastName : "");
else
un = "@" + u.Username;
if (!await db.Users.AnyAsync(x => x.UserId == u.Id))
await db.Users.AddAsync(new Models.User { UserId = u.Id, Username = un });
else
(await db.Users.FindAsync(u.Id)).Username = un;
}
}

View File

@ -1,126 +0,0 @@
using NLog;
using JetKarmaBot.Models;
namespace JetKarmaBot.Services.Handling;
[Singleton]
public class TimeoutManager : IRequestHandler
{
public class Feature
{
public double Multiplier = 1;
}
public class PreDbThrowout : IRequestHandler
{
public TimeoutManager Timeout { get; }
public PreDbThrowout(TimeoutManager timeout)
{
Timeout = timeout;
}
public async Task Handle(RequestContext ctx, Func<RequestContext, Task> next)
{
var uid = ctx.EventArgs.Message.From.Id;
if (Timeout.TimeoutCache.TryGetValue(uid, out var stats))
{
DateTime debtLimit = DateTime.Now.AddSeconds(Timeout.cfg.Timeout.DebtLimitSeconds);
if (debtLimit < stats.CooldownDate && stats.TimeoutMessaged)
return;
}
await next(ctx);
}
}
public class TimeoutStats
{
public DateTime CooldownDate;
public bool TimeoutMessaged;
public DateTime PreviousAwardDate;
}
[Inject] private KarmaContextFactory Db;
[Inject] private Config cfg;
[Inject] private Localization Locale;
[Inject] private Logger log;
public Dictionary<long, TimeoutStats> TimeoutCache = new ();
private async Task ApplyCost(string name, bool succeded, long uid, KarmaContext db, Feature feature)
{
if (feature.Multiplier == 0)
return;
if (!cfg.Timeout.CommandCostsSeconds.TryGetValue(name + (succeded ? " (OK)" : "(ERR)"), out var costSeconds))
if (!cfg.Timeout.CommandCostsSeconds.TryGetValue(name, out costSeconds))
if (!cfg.Timeout.CommandCostsSeconds.TryGetValue("Default", out costSeconds))
{
throw new LocalizationException("Default key not present");
}
await PopulateStats(uid, db);
DateTime debtLimit = DateTime.Now.AddSeconds(cfg.Timeout.DebtLimitSeconds);
if (TimeoutCache[uid].CooldownDate >= debtLimit)
//Programming error
throw new NotImplementedException();
TimeoutCache[uid].CooldownDate = (TimeoutCache[uid].CooldownDate <= DateTime.Now ? DateTime.Now : TimeoutCache[uid].CooldownDate)
.AddSeconds(feature.Multiplier * costSeconds);
TimeoutCache[uid].TimeoutMessaged = false;
}
private async Task PopulateStats(long uid, KarmaContext db)
{
if (!TimeoutCache.ContainsKey(uid))
{
log.ConditionalTrace($"User {uid} not present: saving to cache");
TimeoutCache[uid] = new TimeoutStats()
{
CooldownDate = (await db.Users.FindAsync(uid))?.CooldownDate ?? DateTime.Now
};
}
}
public async Task Save(CancellationToken ct = default(CancellationToken))
{
log.Debug("Saving timeout info to database");
using (KarmaContext db = Db.GetContext())
{
foreach (var i in TimeoutCache.Keys)
{
(await db.Users.FindAsync(new object[] { i }, ct)).CooldownDate = TimeoutCache[i].CooldownDate;
}
await db.SaveChangesAsync(ct);
}
log.Debug("Saved timeout info to database");
}
public async Task SaveLoop(CancellationToken ct = default(CancellationToken))
{
while (!ct.IsCancellationRequested)
{
await Task.Delay(cfg.Timeout.SaveIntervalSeconds * 1000, ct);
await Save(ct);
}
}
public async Task Handle(RequestContext ctx, Func<RequestContext, Task> next)
{
var uid = ctx.EventArgs.Message.From.Id;
KarmaContext db = ctx.GetFeature<KarmaContext>();
await PopulateStats(uid, db);
DateTime debtLimit = DateTime.Now.AddSeconds(cfg.Timeout.DebtLimitSeconds);
if (debtLimit < TimeoutCache[uid].CooldownDate)
{
if (!TimeoutCache[uid].TimeoutMessaged)
{
Locale currentLocale = ctx.GetFeature<Locale>();
await ctx.SendMessage(currentLocale["jetkarmabot.ratelimit"]);
TimeoutCache[uid].TimeoutMessaged = true;
}
return;
}
Feature feature = new Feature();
ctx.AddFeature(feature);
await next(ctx);
var routerFeature = ctx.GetFeature<ChatCommandRouter.Feature>();
await ApplyCost(getTypeName(routerFeature.CommandType), routerFeature.Succeded, uid, db, feature);
}
private string getTypeName(Type t)
{
return (t.DeclaringType == null ? t.Namespace + "." + t.Name : getTypeName(t.DeclaringType) + "." + t.Name)
+ (t.GenericTypeArguments.Length > 0 ? "<" + string.Join(",", t.GenericTypeArguments.Select(getTypeName)) + ">" : "");
}
}

View File

@ -1,10 +1,12 @@
using JetKarmaBot.Models;
using Perfusion;
namespace JetKarmaBot.Services;
public class KarmaContextFactory
namespace JetKarmaBot.Services
{
[Inject] IContainer C { get; set; }
public class KarmaContextFactory
{
[Inject] IContainer C { get; set; }
public KarmaContext GetContext() => C.GetInstance<KarmaContext>();
public KarmaContext GetContext() => C.GetInstance<KarmaContext>();
}
}

View File

@ -1,166 +1,172 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using Newtonsoft.Json.Linq;
using NLog;
using Perfusion;
namespace JetKarmaBot;
public class Localization : IReadOnlyDictionary<string, Locale>
namespace JetKarmaBot
{
private Dictionary<string, Locale> locales = new Dictionary<string, Locale>();
public Localization(IContainer c)
public class Localization : IReadOnlyDictionary<string, Locale>
{
c.ResolveObject(this);
log.Info("Initializing...");
string langsFolder = "lang";
if (!Directory.Exists(langsFolder))
Directory.CreateDirectory(langsFolder);
private Dictionary<string, Locale> locales = new Dictionary<string, Locale>();
foreach (string langFilePath in Directory.EnumerateFiles(langsFolder, "*.json"))
[Inject]
public Localization(IContainer c)
{
try
c.ResolveObject(this);
log.Info("Initializing...");
string langsFolder = "lang";
if (!Directory.Exists(langsFolder))
Directory.CreateDirectory(langsFolder);
foreach (string langFilePath in Directory.EnumerateFiles(langsFolder, "*.json"))
{
string langName = Path.GetFileNameWithoutExtension(langFilePath);
string langKey = langName.ToLowerInvariant();
locales[langKey] = new Locale(JObject.Parse(File.ReadAllText(langFilePath)), langKey);
log.Debug("Found " + langName);
try
{
string langName = Path.GetFileNameWithoutExtension(langFilePath);
string langKey = langName.ToLowerInvariant();
locales[langKey] = new Locale(JObject.Parse(File.ReadAllText(langFilePath)), langKey);
log.Debug("Found " + langName);
}
catch (Exception e)
{
log.Error($"Error while parsing {langFilePath}!");
log.Error(e);
}
}
catch (Exception e)
if (locales.Any())
log.Info("Initialized!");
else
throw new FileNotFoundException($"No locales found in {langsFolder}!");
}
public Locale this[string locale]
{
get
{
log.Error($"Error while parsing {langFilePath}!");
log.Error(e);
locale = locale.ToLowerInvariant();
return locales[locale];
}
}
if (locales.Any())
log.Info("Initialized!");
else
throw new FileNotFoundException($"No locales found in {langsFolder}!");
}
[Inject]
private Logger log;
public Locale this[string locale]
{
get
public Locale FindByCommonName(string name)
{
log.ConditionalTrace("Trying to find locale " + name);
foreach (Locale l in locales.Values)
{
if (l.CommonNames.Contains(name))
{
log.ConditionalTrace("Found locale " + l.Name);
return l;
}
}
// Try to find as locale prefix
IEnumerable<Locale> matchinglocales = locales.Values.Where(x => x.Name.StartsWith(name + "-"));
if (matchinglocales.Count() > 1)
{
LocalizationException l = new LocalizationException("Too many locales");
l.Data["LocaleNames"] = matchinglocales.ToArray();
throw l;
}
else if (matchinglocales.Count() == 1)
return matchinglocales.First();
log.Warn("Failed to find locale " + name);
return null;
}
public bool ContainsLocale(string locale)
{
locale = locale.ToLowerInvariant();
return locales[locale];
return locales.ContainsKey(locale);
}
}
[Inject]
private Logger log;
void Log(Exception e) => Console.WriteLine(e);
public Locale FindByCommonName(string name)
{
log.ConditionalTrace("Trying to find locale " + name);
foreach (Locale l in locales.Values)
public IEnumerable<string> Keys => locales.Keys;
public IEnumerable<Locale> Values => locales.Values;
public int Count => locales.Count;
public bool ContainsKey(string key) => locales.ContainsKey(key.ToLower());
public bool TryGetValue(string key, out Locale value)
{
if (l.CommonNames.Contains(name))
{
log.ConditionalTrace("Found locale " + l.Name);
return l;
}
return locales.TryGetValue(key.ToLower(), out value);
}
// Try to find as locale prefix
IEnumerable<Locale> matchinglocales = locales.Values.Where(x => x.Name.StartsWith(name + "-"));
if (matchinglocales.Count() > 1)
public IEnumerator<KeyValuePair<string, Locale>> GetEnumerator()
{
LocalizationException l = new LocalizationException("Too many locales");
l.Data["LocaleNames"] = matchinglocales.ToArray();
throw l;
return locales.GetEnumerator();
}
else if (matchinglocales.Count() == 1)
return matchinglocales.First();
log.Warn("Failed to find locale " + name);
return null;
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
}
public bool ContainsLocale(string locale)
public class Locale : IReadOnlyDictionary<string, string>
{
locale = locale.ToLowerInvariant();
return locales.ContainsKey(locale);
private Dictionary<string, string> locale;
private string localeName;
private string[] commonNames;
private string note;
public Locale(JObject locale, string localeName)
{
this.locale = locale.Property("strings").Value.ToObject<Dictionary<string, string>>();
this.localeName = localeName;
this.commonNames = locale.Property("names").Value.ToObject<string[]>();
if (locale.ContainsKey("note")) this.note = locale.Property("note").Value.ToObject<string>();
}
public string[] CommonNames => commonNames;
public string Name => localeName;
public bool HasNote => note != null;
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 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();
}
}
void Log(Exception e) => Console.WriteLine(e);
public IEnumerable<string> Keys => locales.Keys;
public IEnumerable<Locale> Values => locales.Values;
public int Count => locales.Count;
public bool ContainsKey(string key) => locales.ContainsKey(key.ToLower());
public bool TryGetValue(string key, out Locale value)
[System.Serializable]
public class LocalizationException : Exception
{
return locales.TryGetValue(key.ToLower(), out value);
public LocalizationException() { }
public LocalizationException(string message) : base(message) { }
public LocalizationException(string message, Exception inner) : base(message, inner) { }
protected LocalizationException(
SerializationInfo info,
StreamingContext context) : base(info, context) { }
}
public IEnumerator<KeyValuePair<string, Locale>> GetEnumerator()
{
return locales.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
}
public class Locale : IReadOnlyDictionary<string, string>
{
private Dictionary<string, string> locale;
private string localeName;
private string[] commonNames;
private string note;
public Locale(JObject locale, string localeName)
{
this.locale = locale.Property("strings").Value.ToObject<Dictionary<string, string>>();
this.localeName = localeName;
this.commonNames = locale.Property("names").Value.ToObject<string[]>();
if (locale.ContainsKey("note")) this.note = locale.Property("note").Value.ToObject<string>();
}
public string[] CommonNames => commonNames;
public string Name => localeName;
public bool HasNote => note != null;
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] : "Unmapped locale key: " + name;
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();
}
}
[System.Serializable]
public class LocalizationException : Exception
{
public LocalizationException() { }
public LocalizationException(string message) : base(message) { }
public LocalizationException(string message, Exception inner) : base(message, inner) { }
protected LocalizationException(
SerializationInfo info,
StreamingContext context) : base(info, context) { }
}

View File

@ -1,18 +1,20 @@
using System;
using System.Linq;
using NLog;
using Perfusion;
namespace JetKarmaBot;
public class LogInfo : ObjectInfo
namespace JetKarmaBot
{
public override ObjectInfo Clone() => new LogInfo();
public override object GetInstance(IContainer c, Type requester = null)
public class LogInfo : ObjectInfo
{
return LogManager.GetLogger(requester != null ? getTypeName(requester) : "<type unspecified>");
}
private string getTypeName(Type t)
{
return (t.DeclaringType == null ? t.Namespace + "." + t.Name : getTypeName(t.DeclaringType) + "." + t.Name)
+ (t.GenericTypeArguments.Length > 0 ? "<" + string.Join(",", t.GenericTypeArguments.Select(getTypeName)) + ">" : "");
public override object GetInstance(IContainer c, Type requester = null)
{
return LogManager.GetLogger(requester != null ? getTypeName(requester) : "<type unspecified>");
}
private string getTypeName(Type t)
{
return (t.DeclaringType == null ? t.Namespace + "." + t.Name : getTypeName(t.DeclaringType) + "." + t.Name)
+ (t.GenericTypeArguments.Length > 0 ? "<" + string.Join(",", t.GenericTypeArguments.Select(getTypeName)) + ">" : "");
}
}
}

View File

@ -1,100 +1,103 @@
using System;
using Microsoft.Extensions.Logging;
using NLog;
using Perfusion;
namespace JetKarmaBot;
public class NLoggerFactory : ILoggerFactory
namespace JetKarmaBot
{
[Inject]
private NLoggerProvider c;
public void AddProvider(ILoggerProvider provider)
public class NLoggerFactory : ILoggerFactory
{
}
public Microsoft.Extensions.Logging.ILogger CreateLogger(string categoryName) => c.CreateLogger(categoryName);
public void Dispose()
{
}
}
public class NLoggerProvider : ILoggerProvider
{
[Inject]
private Container c;
public Microsoft.Extensions.Logging.ILogger CreateLogger(string categoryName) => new LoggerVirtualizer(LogManager.GetLogger(categoryName));
public void Dispose()
{
}
}
public class LoggerVirtualizer : Microsoft.Extensions.Logging.ILogger
{
private Logger logger;
public LoggerVirtualizer(Logger logger)
{
this.logger = logger;
}
private Microsoft.Extensions.Logging.LogLevel getAppropriate(NLog.LogLevel level)
{
if (level == NLog.LogLevel.Trace)
return Microsoft.Extensions.Logging.LogLevel.Trace;
else if (level == NLog.LogLevel.Debug)
return Microsoft.Extensions.Logging.LogLevel.Debug;
else if (level == NLog.LogLevel.Info)
return Microsoft.Extensions.Logging.LogLevel.Information;
else if (level == NLog.LogLevel.Warn)
return Microsoft.Extensions.Logging.LogLevel.Warning;
else if (level == NLog.LogLevel.Error)
return Microsoft.Extensions.Logging.LogLevel.Error;
else if (level == NLog.LogLevel.Fatal)
return Microsoft.Extensions.Logging.LogLevel.Critical;
else if (level == NLog.LogLevel.Off)
return Microsoft.Extensions.Logging.LogLevel.None;
else
return Microsoft.Extensions.Logging.LogLevel.None;
}
private NLog.LogLevel getAppropriate(Microsoft.Extensions.Logging.LogLevel level)
{
switch (level)
[Inject]
private NLoggerProvider c;
public void AddProvider(ILoggerProvider provider)
{
}
public Microsoft.Extensions.Logging.ILogger CreateLogger(string categoryName) => c.CreateLogger(categoryName);
public void Dispose()
{
}
}
public class NLoggerProvider : ILoggerProvider
{
[Inject]
private Container c;
public Microsoft.Extensions.Logging.ILogger CreateLogger(string categoryName) => new LoggerVirtualizer(LogManager.GetLogger(categoryName));
public void Dispose()
{
case Microsoft.Extensions.Logging.LogLevel.Trace:
return NLog.LogLevel.Trace;
case Microsoft.Extensions.Logging.LogLevel.Debug:
return NLog.LogLevel.Debug;
case Microsoft.Extensions.Logging.LogLevel.Information:
return NLog.LogLevel.Info;
case Microsoft.Extensions.Logging.LogLevel.Warning:
return NLog.LogLevel.Warn;
case Microsoft.Extensions.Logging.LogLevel.Error:
return NLog.LogLevel.Error;
case Microsoft.Extensions.Logging.LogLevel.Critical:
return NLog.LogLevel.Fatal;
default:
return NLog.LogLevel.Off;
}
}
public IDisposable BeginScope<TState>(TState state) => new SomeDisposable();
public class LoggerVirtualizer : Microsoft.Extensions.Logging.ILogger
{
private Logger logger;
public bool IsEnabled(Microsoft.Extensions.Logging.LogLevel logLevel)
{
return logger.IsEnabled(getAppropriate(logLevel));
}
public LoggerVirtualizer(Logger logger)
{
this.logger = logger;
}
public void Log<TState>(Microsoft.Extensions.Logging.LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter)
{
string message = state.ToString();
if (exception != null) logger.Log(getAppropriate(logLevel), exception, formatter(state, exception));
else logger.Log(getAppropriate(logLevel), state);
private Microsoft.Extensions.Logging.LogLevel getAppropriate(NLog.LogLevel level)
{
if (level == NLog.LogLevel.Trace)
return Microsoft.Extensions.Logging.LogLevel.Trace;
else if (level == NLog.LogLevel.Debug)
return Microsoft.Extensions.Logging.LogLevel.Debug;
else if (level == NLog.LogLevel.Info)
return Microsoft.Extensions.Logging.LogLevel.Information;
else if (level == NLog.LogLevel.Warn)
return Microsoft.Extensions.Logging.LogLevel.Warning;
else if (level == NLog.LogLevel.Error)
return Microsoft.Extensions.Logging.LogLevel.Error;
else if (level == NLog.LogLevel.Fatal)
return Microsoft.Extensions.Logging.LogLevel.Critical;
else if (level == NLog.LogLevel.Off)
return Microsoft.Extensions.Logging.LogLevel.None;
else
return Microsoft.Extensions.Logging.LogLevel.None;
}
private NLog.LogLevel getAppropriate(Microsoft.Extensions.Logging.LogLevel level)
{
switch (level)
{
case Microsoft.Extensions.Logging.LogLevel.Trace:
return NLog.LogLevel.Trace;
case Microsoft.Extensions.Logging.LogLevel.Debug:
return NLog.LogLevel.Debug;
case Microsoft.Extensions.Logging.LogLevel.Information:
return NLog.LogLevel.Info;
case Microsoft.Extensions.Logging.LogLevel.Warning:
return NLog.LogLevel.Warn;
case Microsoft.Extensions.Logging.LogLevel.Error:
return NLog.LogLevel.Error;
case Microsoft.Extensions.Logging.LogLevel.Critical:
return NLog.LogLevel.Fatal;
default:
return NLog.LogLevel.Off;
}
}
public IDisposable BeginScope<TState>(TState state) => new SomeDisposable();
public bool IsEnabled(Microsoft.Extensions.Logging.LogLevel logLevel)
{
return logger.IsEnabled(getAppropriate(logLevel));
}
public void Log<TState>(Microsoft.Extensions.Logging.LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter)
{
string message = state.ToString();
if (exception != null) logger.Log(getAppropriate(logLevel), exception, formatter(state, exception));
else logger.Log(getAppropriate(logLevel), state);
}
}
}
public class SomeDisposable : IDisposable
{
public void Dispose()
public class SomeDisposable : IDisposable
{
public void Dispose()
{
}
}
}

View File

@ -5,62 +5,45 @@
"беларуская"
],
"note": "This is a joke. And made with google translate.",
"strings": {
"jetkarmabot.ratelimit": "Павольны, чувак!",
"jetkarmabot.award.errawardnoreply": "Пра каго ты кажаш?",
"jetkarmabot.award.errbadusername": "Хто гэта?",
"jetkarmabot.award.errdup": "Калі ласка, спыніце батчіць ўзнагароды.",
"jetkarmabot.award.errawardself": "Хопіць з сабой гуляцца.",
"jetkarmabot.award.errawardbot": "Я бот, і мяне вашы нікчэмныя пузамеркі не вабяць.",
"jetkarmabot.award.errrevokebot": "ಠ_ಠ",
"jetkarmabot.award.awardmessage": "Ўручыў \"{0}\" {1}!",
"jetkarmabot.award.revokemessage": "Адабраў \"{0}\" у {1}!",
"jetkarmabot.award.statustext": "У {0} цяпер {1}{2}.",
"jetkarmabot.award.help": "Уручае ачко карыстачу (або адымае)",
"jetkarmabot.award.awardtypehelp": "Тып ачкі",
"jetkarmabot.award.tohelp": "Карыстальнік, якога ўзнагародзіць",
"jetkarmabot.status.listalltext": "У вас :",
"jetkarmabot.status.listspecifictext": "У вас зараз {0}{1}.",
"jetkarmabot.status.havenothing": "У вас пакуль нічога няма.",
"jetkarmabot.status.help": "Паказвае справаздачу па ўзнагародах.",
"jetkarmabot.changelocale.justchanged": "Так дакладна.",
"jetkarmabot.changelocale.getlocale": "Я зараз кажу па-беларускай.",
"jetkarmabot.changelocale.listalltext": "Я ведаю:",
"jetkarmabot.changelocale.errorall": "Мне б хацелася гаварыць на ўсіх мовах у той жа самы час, але з-за абмежаванняў сусвету, мне гэта не дазваляецца.",
"jetkarmabot.changelocale.beforenote": "Увага: ",
"jetkarmabot.changelocale.toomany": "Не ведаю, на якім дыялекце хочаш, каб я казаў.\nЯ ведаю гэтыя:",
"jetkarmabot.changelocale.help": "Змяняе мову, на якім бот кажа ў гэтым чаце",
"jetkarmabot.changelocale.localehelp": "Новая лакаль, альбо каманда list - спіс перакладаў. Калі пуста - паказваецца бягучая лакаль.",
"jetkarmabot.help.help": "Паказвае інструкцыю да каманды, ці спіс каманд.",
"jetkarmabot.help.commandhelp": "Каманда, да якой трэба паказаць інструкцыю. Калі пуста, то паказваецца спіс каманд.",
"jetkarmabot.currencies.help": "Паказвае ўсе тыпы узнагарод",
"jetkarmabot.currencies.listtext": "Тыпы узнагарод:",
"jetkarmabot.leaderboard.help": "Табліца лідэраў па колькасці ўзнагарод",
"jetkarmabot.leaderboard.awardtypehelp": "Тып ўзнагароды, па якой падасца справаздачу.",
"jetkarmabot.leaderboard.specifictext": "Перадавікі ў намінацыі \"{0}\":",
"jetkarmabot.awardtypes.nominative.star": "зорачка",
"jetkarmabot.awardtypes.nominative.pie": "з паліцы піражок",
"jetkarmabot.awardtypes.nominative.dream": "мара",
"jetkarmabot.awardtypes.nominative.banana": "стыкер-бананчык",
"jetkarmabot.awardtypes.nominative.determination": "DETERMINATION",
"jetkarmabot.awardtypes.nominative.raisin": "разынка",
"jetkarmabot.awardtypes.nominative.touche": "touché",
"jetkarmabot.awardtypes.nominative.covid": "каронавірус",
"jetkarmabot.awardtypes.nominative.pony": "поніс",
"jetkarmabot.awardtypes.nominative.bellissimo": "беліссімо",
"jetkarmabot.awardtypes.nominative.based": "сярдзіта",
"jetkarmabot.awardtypes.nominative.redpill": "пілюля",
"jetkarmabot.awardtypes.accusative.star": "зорачку",
"jetkarmabot.awardtypes.accusative.pie": "з паліцы піражкі",
"jetkarmabot.awardtypes.accusative.dream": "мары",
"jetkarmabot.awardtypes.accusative.banana": "стыкера-бананчыка",
"jetkarmabot.awardtypes.accusative.determination": "DETERMINATION",
"jetkarmabot.awardtypes.accusative.raisin": "разыначкі",
"jetkarmabot.awardtypes.accusative.touche": "touché",
"jetkarmabot.awardtypes.accusative.covid": "каронавірус",
"jetkarmabot.awardtypes.accusative.pony": "поніса",
"jetkarmabot.awardtypes.accusative.bellissimo": "беліссімо",
"jetkarmabot.awardtypes.accusative.based": "сярдзіта",
"jetkarmabot.awardtypes.accusative.redpill": "пілюлю"
}
"strings": {
"jetkarmabot.award.errawardnoreply": "Калі ласка выкарыстоўвайце гэтую каманду ў адказе іншаму карыстальніку.",
"jetkarmabot.award.errawardself": "Хопіць з сабой гуляцца.",
"jetkarmabot.award.errawardbot": "Я бот, і мяне вашы нікчэмныя пузамеркі не вабяць.",
"jetkarmabot.award.errrevokebot": "ಠ_ಠ",
"jetkarmabot.award.awardmessage": "Ўручыў \"{0}\" {1}!",
"jetkarmabot.award.revokemessage": "Адабраў \"{0}\" у {1}!",
"jetkarmabot.award.statustext": "У {0} цяпер {1}{2}.",
"jetkarmabot.award.ratelimit": "Павольны, чувак!",
"jetkarmabot.award.help": "Уручае ачко карыстачу (або адымае)",
"jetkarmabot.award.awardtypehelp": "Тып ачкі",
"jetkarmabot.status.listalltext": "У вас :",
"jetkarmabot.status.listspecifictext": "У вас зараз {0}{1}.",
"jetkarmabot.status.havenothing": "У вас пакуль нічога няма.",
"jetkarmabot.status.help": "Паказвае справаздачу па ўзнагародах.",
"jetkarmabot.status.awardtypehelp": "Тып ўзнагароды, па якой падасца справаздачу. Калі пуста, то падасца зводны справаздачу.",
"jetkarmabot.changelocale.justchanged": "Так дакладна.",
"jetkarmabot.changelocale.getlocale": "Я зараз кажу па-беларускай.",
"jetkarmabot.changelocale.listalltext": "Я ведаю:",
"jetkarmabot.changelocale.errorall": "Мне б хацелася гаварыць на ўсіх мовах у той жа самы час, але з-за абмежаванняў сусвету, мне гэта не дазваляецца.",
"jetkarmabot.changelocale.beforenote": "Увага: ",
"jetkarmabot.changelocale.toomany": "Не ведаю, на якім дыялекце хочаш, каб я казаў.\nЯ ведаю гэтыя:",
"jetkarmabot.changelocale.help": "Змяняе мову, на якім бот кажа ў гэтым чаце",
"jetkarmabot.changelocale.localehelp": "Новая лакаль, альбо каманда list - спіс перакладаў. Калі пуста - паказваецца бягучая лакаль.",
"jetkarmabot.help.help": "Паказвае інструкцыю да каманды, ці спіс каманд.",
"jetkarmabot.help.commandhelp": "Каманда, да якой трэба паказаць інструкцыю. Калі пуста, то паказваецца спіс каманд.",
"jetkarmabot.currencies.help": "Паказвае ўсе тыпы узнагарод",
"jetkarmabot.currencies.listtext": "Тыпы узнагарод:",
"jetkarmabot.awardtypes.nominative.star": "зорачка",
"jetkarmabot.awardtypes.nominative.pie": "з паліцы піражок",
"jetkarmabot.awardtypes.nominative.dream": "мара",
"jetkarmabot.awardtypes.nominative.banana": "стыкер-бананчык",
"jetkarmabot.awardtypes.nominative.determination": "DETERMINATION",
"jetkarmabot.awardtypes.nominative.raisin": "разынка",
"jetkarmabot.awardtypes.accusative.star": "зорачку",
"jetkarmabot.awardtypes.accusative.pie": "з паліцы піражкі",
"jetkarmabot.awardtypes.accusative.dream": "мары",
"jetkarmabot.awardtypes.accusative.banana": "стыкера-бананчыка",
"jetkarmabot.awardtypes.accusative.determination": "DETERMINATION",
"jetkarmabot.awardtypes.accusative.raisin": "разыначкі"
}
}

View File

@ -5,23 +5,21 @@
"англійская"
],
"strings": {
"jetkarmabot.ratelimit": "Slow down there, turbo!",
"jetkarmabot.award.errawardnoreply": "Who are you talking about?",
"jetkarmabot.award.errbadusername": "I don't know who that is.",
"jetkarmabot.award.errdup": "Please stop batching awards.",
"jetkarmabot.award.errawardnoreply": "Please use this command in reply to another user.",
"jetkarmabot.award.errawardself": "Please stop playing with yourself.",
"jetkarmabot.award.errawardbot": "I am a bot, and have no use for your foolish fake internet points.",
"jetkarmabot.award.errrevokebot": "ಠ_ಠ",
"jetkarmabot.award.awardmessage": "Awarded a {0} to {1}!",
"jetkarmabot.award.revokemessage": "Revoked a {0} from {1}!",
"jetkarmabot.award.statustext": "{0} is at {1}{2} now.",
"jetkarmabot.award.ratelimit": "Slow down there, turbo!",
"jetkarmabot.award.help": "Awards/revokes an award to a user.",
"jetkarmabot.award.awardtypehelp": "The award to grant to/strip of the specified user",
"jetkarmabot.award.tohelp": "The user to award",
"jetkarmabot.status.listalltext": "Your badges report:",
"jetkarmabot.status.listspecifictext": "You are at {0}{1} now.",
"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.getlocale": "I'm currently speaking English.",
"jetkarmabot.changelocale.listalltext": "I know:",
@ -34,32 +32,17 @@
"jetkarmabot.help.commandhelp": "The command to return help text for. If empty shows all commands.",
"jetkarmabot.currencies.help": "Shows all award types",
"jetkarmabot.currencies.listtext": "Award types:",
"jetkarmabot.leaderboard.help": "Shows the people with the most of a specific award.",
"jetkarmabot.leaderboard.awardtypehelp": "The awardtype to show a leaderboard for.",
"jetkarmabot.leaderboard.specifictext": "Leaderboard for {0}:",
"jetkarmabot.awardtypes.nominative.star": "star",
"jetkarmabot.awardtypes.nominative.pie": "pie from the shelf",
"jetkarmabot.awardtypes.nominative.dream": "dream",
"jetkarmabot.awardtypes.nominative.banana": "banana sticker",
"jetkarmabot.awardtypes.nominative.determination": "DETERMINATION",
"jetkarmabot.awardtypes.nominative.raisin": "raisin",
"jetkarmabot.awardtypes.nominative.touche": "touché",
"jetkarmabot.awardtypes.nominative.covid": "coronavirus",
"jetkarmabot.awardtypes.nominative.pony": "pony",
"jetkarmabot.awardtypes.nominative.bellissimo": "bellissimo",
"jetkarmabot.awardtypes.nominative.based": "based",
"jetkarmabot.awardtypes.nominative.redpill": "redpill",
"jetkarmabot.awardtypes.accusative.star": "star",
"jetkarmabot.awardtypes.accusative.pie": "pie from the shelf",
"jetkarmabot.awardtypes.accusative.dream": "dream",
"jetkarmabot.awardtypes.accusative.banana": "banana sticker",
"jetkarmabot.awardtypes.accusative.determination": "DETERMINATION",
"jetkarmabot.awardtypes.accusative.raisin": "raisin",
"jetkarmabot.awardtypes.accusative.touche": "touché",
"jetkarmabot.awardtypes.accusative.covid": "coronavirus",
"jetkarmabot.awardtypes.accusative.pony": "pony",
"jetkarmabot.awardtypes.accusative.bellissimo": "bellissimo",
"jetkarmabot.awardtypes.accusative.based": "based",
"jetkarmabot.awardtypes.accusative.redpill": "redpill"
"jetkarmabot.awardtypes.accusative.raisin": "raisin"
}
}

View File

@ -5,23 +5,21 @@
"руская"
],
"strings": {
"jetkarmabot.ratelimit": "Помедленней, чувак!",
"jetkarmabot.award.errawardnoreply": "О ком ты говоришь?",
"jetkarmabot.award.errbadusername": "Кто это?",
"jetkarmabot.award.errdup": "Пожалуйста, не батчайте награды.",
"jetkarmabot.award.errawardnoreply": "Пожалуйста используйте эту команду в ответе другому пользователю.",
"jetkarmabot.award.errawardself": "Хватит с собой играться.",
"jetkarmabot.award.errawardbot": "Я бот, и меня ваши жалкие пузомерки не интересуют.",
"jetkarmabot.award.errrevokebot": "ಠ_ಠ",
"jetkarmabot.award.awardmessage": "Вручил \"{0}\" {1}!",
"jetkarmabot.award.revokemessage": "Отнял \"{0}\" у {1}!",
"jetkarmabot.award.statustext": "У {0} теперь {1}{2}.",
"jetkarmabot.award.ratelimit": "Помедленней, чувак!",
"jetkarmabot.award.help": "Вручает очко пользователю (или отнимает)",
"jetkarmabot.award.awardtypehelp": "Тип очка",
"jetkarmabot.award.tohelp": "Пользователь, которого наградить",
"jetkarmabot.status.listalltext": "У вас :",
"jetkarmabot.status.listspecifictext": "У вас сейчас {0}{1}.",
"jetkarmabot.status.havenothing": "У вас пока ничего нет.",
"jetkarmabot.status.help": "Показывает отчет по наградам.",
"jetkarmabot.status.awardtypehelp": "Тип награды, по которой покажется отчет. Если пусто, то покажется сводный отчет.",
"jetkarmabot.changelocale.justchanged": "Так точно.",
"jetkarmabot.changelocale.getlocale": "Я сейчас говорю по-русски.",
"jetkarmabot.changelocale.listalltext": "Я знаю:",
@ -34,32 +32,17 @@
"jetkarmabot.help.commandhelp": "Команда, к которой нужно показать инструкцию. Если пусто, то показывается список команд.",
"jetkarmabot.currencies.help": "Показывает все типы наград",
"jetkarmabot.currencies.listtext": "Типы наград:",
"jetkarmabot.leaderboard.help": "Таблица лидеров по количеству наград",
"jetkarmabot.leaderboard.awardtypehelp": "Тип награды, по которой покажется отчет.",
"jetkarmabot.leaderboard.specifictext": "Передовики в номинации \"{0}\":",
"jetkarmabot.awardtypes.nominative.star": "звездочка",
"jetkarmabot.awardtypes.nominative.pie": "с полки пирожок",
"jetkarmabot.awardtypes.nominative.dream": "мечта",
"jetkarmabot.awardtypes.nominative.banana": "стикер-бананчик",
"jetkarmabot.awardtypes.nominative.determination": "РЕШИТЕЛЬНОСТЬ",
"jetkarmabot.awardtypes.nominative.raisin": "изюм",
"jetkarmabot.awardtypes.nominative.touche": "touché",
"jetkarmabot.awardtypes.nominative.covid": "коронавирус",
"jetkarmabot.awardtypes.nominative.pony": "понис",
"jetkarmabot.awardtypes.nominative.bellissimo": "белиссимо",
"jetkarmabot.awardtypes.nominative.based": "сердито",
"jetkarmabot.awardtypes.nominative.redpill": "пилюля",
"jetkarmabot.awardtypes.accusative.star": "звездочку",
"jetkarmabot.awardtypes.accusative.pie": "с полки пирожок",
"jetkarmabot.awardtypes.accusative.dream": "мечту",
"jetkarmabot.awardtypes.accusative.banana": "стикер-бананчик",
"jetkarmabot.awardtypes.accusative.determination": "РЕШИТЕЛЬНОСТЬ",
"jetkarmabot.awardtypes.accusative.raisin": "изюм",
"jetkarmabot.awardtypes.accusative.touche": "touché",
"jetkarmabot.awardtypes.accusative.covid": "коронавирус",
"jetkarmabot.awardtypes.accusative.pony": "пониса",
"jetkarmabot.awardtypes.accusative.bellissimo": "белиссимо",
"jetkarmabot.awardtypes.accusative.based": "сердито",
"jetkarmabot.awardtypes.accusative.redpill": "пилюлю"
"jetkarmabot.awardtypes.accusative.raisin": "изюм"
}
}

View File

@ -1,41 +0,0 @@
-- Example JetKarmaBot database
-- (taken from mysqldump)
DROP TABLE IF EXISTS `awardtype`;
CREATE TABLE `awardtype` (
`awardtypeid` tinyint(3) NOT NULL PRIMARY KEY,
`commandname` varchar(35) NOT NULL UNIQUE,
`name` varchar(32) NOT NULL,
`symbol` varchar(16) NOT NULL,
`description` text NOT NULL
);
LOCK TABLES `awardtype` WRITE;
INSERT INTO `awardtype` VALUES (1,'example','Example','Examples','An example');
UNLOCK TABLES;
DROP TABLE IF EXISTS `chat`;
CREATE TABLE `chat` (
`chatid` bigint(20) NOT NULL PRIMARY KEY,
`locale` varchar(10) NOT NULL DEFAULT 'ru-RU',
`isadministrator` tinyint(1) NOT NULL DEFAULT 0
);
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`userid` bigint(20) NOT NULL,
`username` varchar(45) DEFAULT NULL,
`cooldowndate` timestamp NOT NULL DEFAULT current_timestamp(),
PRIMARY KEY (`userid`)
);
DROP TABLE IF EXISTS `award`;
CREATE TABLE `award` (
`awardid` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
`chatid` bigint(20) NOT NULL REFERENCES `chat` (`chatid`),
`fromid` bigint(20) NOT NULL REFERENCES `user` (`userid`),
`toid` bigint(20) NOT NULL REFERENCES `user` (`userid`),
`awardtypeid` tinyint(3) NOT NULL REFERENCES `awardtype` (`awardtypeid`),
`amount` tinyint(3) NOT NULL DEFAULT 1,
`date` datetime NOT NULL DEFAULT current_timestamp()
);

@ -1 +1 @@
Subproject commit 115f59eecb2a4a74c63770866539502cde28d881
Subproject commit 40e8f8871f42f1f32c29480505cf5ac6ba61c393