Compare commits

..

111 Commits

Author SHA1 Message Date
2cc286ad9c Usings and namespace cleanup 2024-11-15 19:19:40 +03:00
d2e8ed4d69 Fix leaderboard command 2024-11-15 19:14:11 +03:00
8fca14e398 Fix updated bot api SendMessage 2024-11-15 18:39:44 +03:00
67f05b6f3d Fix status command, remove parameter in status command 2024-11-15 18:31:22 +03:00
b666b43000 Stop TimeoutManager spam 2024-11-15 18:30:35 +03:00
e905b8583d Update dependencies, bump .NET version 2024-11-15 18:30:04 +03:00
ed7346c16d Update dependencies 2023-11-19 19:13:22 +03:00
dc879e2984
why was this not commited 2021-10-17 14:47:04 +03:00
b454b09878
.net 5 2021-10-17 14:46:56 +03:00
58f7e17ba6
bail on error immediately 2021-10-17 14:46:51 +03:00
6ff22680b9
Allow not using proxy 2021-08-23 13:25:15 +03:00
98ba039788
AAAAAA 2021-08-23 13:25:14 +03:00
8baf576733
Spelling lol 2021-08-23 13:25:14 +03:00
38b1169309
Add award types 2021-08-23 13:25:14 +03:00
eae44695e7
Global leaderboards and specific statuses 2021-08-23 13:25:14 +03:00
0b40235c9b
Add pony localizations 2021-08-23 13:25:14 +03:00
3544f521f9
Try to only stop the bot once
This was causing errors on CTRL+C.
2021-08-23 13:25:13 +03:00
09c07e6296
Make RequestContext.Features a dictionary 2021-08-23 13:25:13 +03:00
e106681c11
Switch to .NET Core 3.1 2021-08-23 13:25:13 +03:00
66de361342
Add some awardtypes 2021-08-23 13:25:13 +03:00
af7def64a4
Add some belarusian translations 2021-08-23 13:25:12 +03:00
13e3be89b3
Make DatabaseHandler not error on non-existent chat 2021-08-23 13:25:12 +03:00
00dd51cea9
Add special ratelimit for award (1 in 1 minute) 2021-08-23 13:25:12 +03:00
72fbee9c46
Add logging to RequestChain and TimeoutManager 2021-08-23 13:25:12 +03:00
87ed735486
Make locale a feature 2021-08-23 13:25:12 +03:00
a354305334
Make TimeoutManager exit early on messaged user 2021-08-23 13:25:11 +03:00
a4f94428ce
Seperate db from RequestContext 2021-08-23 13:25:11 +03:00
000a0d8718
Add RequestContext.SendMessage + Silent messages 2021-08-23 13:25:11 +03:00
b3dbdb5806
Tweak of SaveData (DbHandler) 2021-08-23 13:25:11 +03:00
f47c48e1be
Add request chains 2021-08-23 13:25:11 +03:00
636040c635
Change column type to timestamp 2021-08-23 13:25:10 +03:00
cd2a0d5710
Remove while true 2021-08-23 13:25:10 +03:00
df982d53aa
Basic leaky bucket timeout 2021-08-23 13:25:10 +03:00
228c078947
Handle SIGTERM 2021-08-23 13:25:10 +03:00
8132f8edac
Performance improvement in /status 2021-08-23 13:25:09 +03:00
d8b2b1c448
Make private chats show all awards 2021-08-23 13:25:09 +03:00
06703f13a6
/award quickfix 2021-08-23 13:25:09 +03:00
666ba84a92
Make Localization actually try to help 2021-08-23 13:25:09 +03:00
6ef9b602e5
Award command improvement 2021-08-23 13:25:09 +03:00
f0a55f305e
Make karma.sql work when creating db 2021-08-23 13:25:08 +03:00
d005fd0ba4
Upgrade to .NET Core 3.0 2021-08-23 13:25:08 +03:00
0759fe2af6
Update perfusion 2021-08-23 13:25:08 +03:00
85125a46f1
Add example database 2021-08-23 13:25:08 +03:00
57c861e473
Remove reporting errors to admin chats 2021-08-23 13:25:07 +03:00
55333b95d3
Update perfusion 2021-08-23 13:25:07 +03:00
a1b5db8430
Make everything asynchronous 2021-08-23 13:25:07 +03:00
5e239c934c
Make /leaderboard show leaderboard for stars by default 2021-08-23 13:25:07 +03:00
Jetsparrow
2410a5d826
Update ru-RU.json
translated missing leaderboard texts
2021-08-23 13:25:07 +03:00
c1523f69db
Generate username from first and last names, and update usernames in
the database.
2021-08-23 13:25:06 +03:00
ddf58321ec
Make leaderboard entries be seperated by newlines 2021-08-23 13:25:06 +03:00
30035b0a83
Also filter for chat in /award 2021-08-23 13:25:06 +03:00
92e996e599
Add /leaderboard command 2021-08-23 13:25:06 +03:00
dbbc616c8c
Make /status only get awards from current chat 2021-08-23 13:25:05 +03:00
c07a2051e3
Update dependencies and switch to .netcoreapp2.2 2021-08-23 13:25:05 +03:00
e4923e4d79
Ensure existence of DB 2021-08-23 13:25:05 +03:00
28bca4832d
Fix db isadministrator + update perfusion
Signed-off-by: Basique Evangelist <basiqueevangelist@yandex.ru>
2021-08-23 13:25:00 +03:00
737063d2dc
Basic error telegram logging support
Signed-off-by: Basique Evangelist <basiqueevangelist@yandex.ru>
2021-08-23 13:24:54 +03:00
48be616899
Add field IsAdministrator
Signed-off-by: Basique Evangelist <basiqueevangelist@yandex.ru>
2021-08-23 13:24:49 +03:00
e3ece07d50
Add autocomplete based on language identifier
Signed-off-by: Basique Evangelist <basiqueevangelist@yandex.ru>
2021-08-23 13:24:41 +03:00
58ed942ca3
Add rate limiting to /award
Signed-off-by: Basique Evangelist <basiqueevangelist@yandex.ru>
2021-08-23 13:24:36 +03:00
de29905324
Add SqlDebug to config
Signed-off-by: Basique Evangelist <basiqueevangelist@yandex.ru>
2021-08-23 13:24:29 +03:00
831a902fd1
Fix "a a" in en-US locale
Signed-off-by: Basique Evangelist <basiqueevangelist@yandex.ru>
2021-08-23 13:24:27 +03:00
633ef9ccba
Better formatting for /currencies
Signed-off-by: Basique Evangelist <basiqueevangelist@yandex.ru>
2021-08-23 13:24:21 +03:00
e0411760e3
Add accusative forms to award type names
Signed-off-by: Basique Evangelist <basiqueevangelist@yandex.ru>
2021-08-23 13:24:04 +03:00
9b78abcd58 Add /currencies
Signed-off-by: Nikolay Kochulin <porez0xfeedface@gmail.com>
2019-04-18 17:28:20 +03:00
86ab927005 Update to new Perfusion 2019-04-18 15:43:57 +03:00
7291318dcc Merge branch 'master' of ssh://lserver1/srv/git/karmabot 2019-03-14 12:17:16 +03:00
3ce21285fa Fix grammatical error 2019-03-14 12:17:13 +03:00
5399bc03ba fix be-by.json build action 2019-02-12 11:41:50 +03:00
6b39a8f27f build project under dotnet framework for deploy on linux x86 2019-02-09 19:01:38 +03:00
a08b5da0f2 Translate ru-RU into be-BY 2019-02-07 23:26:38 +03:00
e5a4c62214 ru help 2019-02-07 23:10:59 +03:00
6af15e7c29 Merge help-command into master 2019-02-07 17:53:52 +03:00
431b47de69 Add functionality to localize command help strings. 2019-02-07 17:45:49 +03:00
b9194b5743 Add all other awardtypes in 2019-02-07 17:20:12 +03:00
a7493e4911 Add functionality for awardtype localized names 2019-02-07 17:14:36 +03:00
7232d18736 Add help command mechanisms 2019-02-07 16:44:32 +03:00
5789890fd9 Start creating help command 2019-02-06 23:29:12 +03:00
7552303a6e Add joke belarusian locale + add locale notes 2019-02-06 20:38:58 +03:00
fb1843360c Add joke belarusian locale. 2019-02-06 20:33:18 +03:00
a7df153b8a Add /locale list and /locale all 2019-02-06 20:17:57 +03:00
89a0408ae5 Make logging accessible via perfusion 2019-02-06 18:19:09 +03:00
b5b5478446 Update perfusion commit id + fix bug 2019-02-05 22:47:15 +03:00
55b65828b3 Update to use new perfusion version 2019-01-12 17:25:38 +03:00
2944ea150c Add "you have nothing yet" feature to /status 2019-01-11 22:10:28 +03:00
4c77b075c9 Make JetKarmaBot add chats to db 2019-01-11 21:58:48 +03:00
1781c2bdcf Add a bit of logging to AwardCommand and ChangeLocaleCommand 2019-01-06 23:49:02 +03:00
cc82c02e44 Add logging to Program and CommandRouter 2019-01-06 23:39:31 +03:00
66190a1eb0 Added logging 2019-01-06 23:24:52 +03:00
7820d50fe8 Allow adding of common names of locales to locale files 2019-01-06 22:29:25 +03:00
ef3db7ac50 localization fixes 2019-01-06 19:08:55 +03:00
d55217e539 awards fix 2019-01-06 18:57:48 +03:00
ba9f698040 WIP entity framework 2019-01-06 18:29:00 +03:00
93e69db9ad transition start 2019-01-02 17:07:31 +03:00
320cbdba5e Allow getting locales 2018-12-31 23:05:13 +03:00
fa2ad31963 Rename ChangeLanguageCommand to ChangeLocaleCommand 2018-12-31 21:56:46 +03:00
314d861f4e Add language chooser feature to chats 2018-12-26 20:56:53 +03:00
20e043c669 Make localization not use config 2018-12-21 23:00:32 +03:00
dee9baa037 ru-RU phrasing 2018-12-21 22:50:21 +03:00
501fc5d2c2 Use now perfusion commit 2018-12-21 22:46:23 +03:00
1e4ad52356 Make /award output mentions 2018-12-21 19:53:25 +03:00
6f837dc67f Add experimental russian locale 2018-12-21 19:50:35 +03:00
2cdb9587ee Add localization 2018-12-21 18:13:36 +03:00
4355ae4058 status command 2018-12-19 23:55:58 +03:00
ab90a15c8c revoking support 2018-12-19 23:55:45 +03:00
1684b62e7d pass through parsed string instead of sender to command 2018-12-19 22:45:57 +03:00
0bb9a58711 handle commands with mentions
skip commands directed at other bots
2018-12-19 22:43:30 +03:00
d200249650 Finish moving to Perfusion 2018-12-19 22:42:53 +03:00
128e0b3fd2 fix perfusion usage 2018-12-19 22:21:12 +03:00
91bb1dd383 Merge remote-tracking branch 'origin/master' 2018-12-19 16:37:01 +03:00
36cb3d8fae Convert project to perfusion 2018-12-19 15:18:41 +03:00
36 changed files with 1643 additions and 1309 deletions

View File

@ -1,124 +0,0 @@
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,99 +1,122 @@
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 Microsoft.EntityFrameworkCore;
using NLog;
using JetKarmaBot.Services.Handling;
using JetKarmaBot.Models;
namespace JetKarmaBot.Commands
namespace JetKarmaBot.Commands;
class AwardCommand : IChatCommand
{
class AwardCommand : IChatCommand
{
public IReadOnlyCollection<string> Names => new[] { "award", "revoke" };
[Inject]
private Logger log;
[Inject] private Logger log;
public bool Execute(CommandString cmd, MessageEventArgs args)
public async Task<bool> Execute(RequestContext ctx)
{
using (var db = Db.GetContext())
var db = ctx.GetFeature<KarmaContext>();
var currentLocale = ctx.GetFeature<Locale>();
var awarder = ctx.EventArgs.Message.From;
if (Timeout.TimeoutCache[awarder.Id].PreviousAwardDate.AddSeconds(Config.Timeout.AwardTimeSeconds) > DateTime.Now)
{
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;
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;
}
var awarder = args.Message.From;
var recipient = args.Message.ReplyToMessage.From;
bool awarding = cmd.Command == "award";
if (awarder.Id == recipient.Id)
string awardTypeText = null;
long recipientId = default;
foreach (string arg in ctx.Command.Parameters)
{
Client.SendTextMessageAsync(
args.Message.Chat.Id,
currentLocale["jetkarmabot.award.errawardself"],
replyToMessageId: args.Message.MessageId);
return true;
if (arg.StartsWith('@'))
{
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;
}
}
else
{
if (awardTypeText == null)
awardTypeText = arg;
else
{
await ctx.SendMessage(currentLocale["jetkarmabot.award.errdup"]);
return false;
}
}
}
if (Me.Id == recipient.Id)
if (ctx.EventArgs.Message.ReplyToMessage != null && recipientId == default)
{
Client.SendTextMessageAsync(
args.Message.Chat.Id,
awarding
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"],
replyToMessageId: args.Message.MessageId);
return true;
: currentLocale["jetkarmabot.award.errrevokebot"]);
return false;
}
var text = args.Message.Text;
var awardTypeText = cmd.Parameters.FirstOrDefault();
var text = ctx.EventArgs.Message.Text;
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()
? 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 = recipient.Id,
ChatId = args.Message.Chat.Id
ToId = recipientId,
ChatId = ctx.EventArgs.Message.Chat.Id
});
log.Debug($"Awarded {(awarding ? 1 : -1)}{awardType.Symbol} to {recipient.Username}");
db.SaveChanges();
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), "@" + recipient.Username)
: string.Format(currentLocale["jetkarmabot.award.revokemessage"], getLocalizedName(awardType, currentLocale), "@" + recipient.Username);
? string.Format(currentLocale["jetkarmabot.award.awardmessage"], getLocalizedName(awardType, currentLocale), recUserName)
: string.Format(currentLocale["jetkarmabot.award.revokemessage"], getLocalizedName(awardType, currentLocale), recUserName);
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);
var response = message + "\n" + String.Format(currentLocale["jetkarmabot.award.statustext"], recUserName, prevCount + (awarding ? 1 : -1), awardType.Symbol);
Client.SendTextMessageAsync(
args.Message.Chat.Id,
response,
replyToMessageId: args.Message.MessageId);
await ctx.SendMessage(response);
Timeout.TimeoutCache[awarder.Id].PreviousAwardDate = DateTime.Now;
return true;
}
}
private string getLocalizedName(global::JetKarmaBot.Models.AwardType awardType, Locale loc)
{
@ -107,10 +130,9 @@ namespace JetKarmaBot.Commands
}
}
[Inject] KarmaContextFactory Db { get; set; }
[Inject] TelegramBotClient Client { get; set; }
[Inject] Localization Locale { get; set; }
User Me { get; }
[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";
@ -122,12 +144,13 @@ namespace JetKarmaBot.Commands
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"
}
};
public AwardCommand(User me)
{
Me = me;
}
}
}

View File

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

View File

@ -1,13 +1,9 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Text.RegularExpressions;
namespace JetKarmaBot.Commands
namespace JetKarmaBot.Commands;
public class CommandString
{
public class CommandString
{
public CommandString(string command, params string[] parameters)
{
Command = command;
@ -40,7 +36,7 @@ namespace JetKarmaBot.Commands
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};
result = new CommandString(cmd, parameters) { UserName = username };
return true;
}
@ -49,5 +45,4 @@ namespace JetKarmaBot.Commands
if (TryParse(s, out var c)) return c;
throw new ArgumentException($"\"{s}\" is not a command");
}
}
}

View File

@ -1,17 +1,11 @@
using System.Collections.Generic;
using Telegram.Bot.Args;
using Perfusion;
using JetKarmaBot.Services;
using Telegram.Bot;
using Telegram.Bot.Types.Enums;
using System.Linq;
using Microsoft.EntityFrameworkCore;
using JetKarmaBot.Services.Handling;
using JetKarmaBot.Models;
namespace JetKarmaBot.Commands
namespace JetKarmaBot.Commands;
public class CurrenciesCommand : IChatCommand
{
public class CurrenciesCommand : IChatCommand
{
[Inject] KarmaContextFactory Db;
[Inject] TelegramBotClient Client { get; set; }
[Inject] Localization Locale { get; set; }
public IReadOnlyCollection<string> Names => new[] { "currencies", "awardtypes" };
@ -21,20 +15,14 @@ namespace JetKarmaBot.Commands
public IReadOnlyCollection<ChatCommandArgument> Arguments => new ChatCommandArgument[] {
};
public bool Execute(CommandString cmd, MessageEventArgs args)
public async Task<bool> Execute(RequestContext ctx)
{
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);
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;
}
}
}
}

View File

@ -1,18 +1,10 @@
using System.Collections.Generic;
using Telegram.Bot.Args;
using Perfusion;
using JetKarmaBot.Services;
using Telegram.Bot;
using Telegram.Bot.Types.Enums;
using JetKarmaBot.Services.Handling;
namespace JetKarmaBot.Commands
namespace JetKarmaBot.Commands;
public class HelpCommand : IChatCommand
{
public class HelpCommand : IChatCommand
{
[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)";
@ -28,34 +20,19 @@ namespace JetKarmaBot.Commands
}
};
public bool Execute(CommandString cmd, MessageEventArgs args)
public async Task<bool> Execute(RequestContext ctx)
{
using (var db = Db.GetContext())
var currentLocale = ctx.GetFeature<Locale>();
var router = ctx.GetFeature<ChatCommandRouter.Feature>().Router;
if (ctx.Command.Parameters.Length < 1)
{
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);
await ctx.SendMessage(router.GetHelpText(currentLocale));
return true;
}
else
{
Client.SendTextMessageAsync(
args.Message.Chat.Id,
Router.GetHelpTextFor(cmd.Parameters[0], currentLocale),
replyToMessageId: args.Message.MessageId,
parseMode: ParseMode.Html);
await ctx.SendMessage(router.GetHelpTextFor(ctx.Command.Parameters[0], currentLocale));
return true;
}
}
}
public HelpCommand(ChatCommandRouter router)
{
Router = router;
}
}
}

View File

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

View File

@ -0,0 +1,65 @@
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,83 +1,51 @@
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 Microsoft.EntityFrameworkCore;
using JetKarmaBot.Services.Handling;
using JetKarmaBot.Models;
using JetKarmaBot.Services;
namespace JetKarmaBot.Commands
namespace JetKarmaBot.Commands;
class StatusCommand : IChatCommand
{
class StatusCommand : IChatCommand
{
public IReadOnlyCollection<string> Names => new[] { "status" };
public IReadOnlyCollection<string> Names => ["status"];
public bool Execute(CommandString cmd, MessageEventArgs args)
public async Task<bool> Execute(RequestContext ctx)
{
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();
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;
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))
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
{
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}"));
var aq = db.AwardTypes.GroupJoin(
awards,
at => at.AwardTypeId,
aw => aw.AwardTypeId,
(at, aws) => new {at.Symbol, Amount = aws.Sum(aw => aw.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);
var awardsByType = await aq.ToListAsync();
response = string.Format(currentLocale["jetkarmabot.status.listspecifictext"], db.Awards.Where(x => x.AwardTypeId == awardTypeId && x.ToId == asker.Id).Sum(x => x.Amount), awardType.Symbol);
response =
currentLocale["jetkarmabot.status.listalltext"] + "\n"
+ string.Join("\n", awardsByType.Select(a => $" - {a.Symbol} {a.Amount}"));
}
Client.SendTextMessageAsync(
args.Message.Chat.Id,
response,
replyToMessageId: args.Message.MessageId);
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"
}
};
}
public IReadOnlyCollection<ChatCommandArgument> Arguments => [];
}

View File

@ -3,10 +3,10 @@ using Newtonsoft.Json;
using JsonNet.PrivateSettersContractResolvers;
using Newtonsoft.Json.Linq;
namespace JetKarmaBot
namespace JetKarmaBot;
public class Config : ConfigBase
{
public class Config : ConfigBase
{
public Config(string path) : base(path) { }
public string ApiKey { get; private set; }
@ -21,11 +21,24 @@ namespace JetKarmaBot
}
public ProxySettings Proxy { get; private set; }
public bool SqlDebug { get; private set; }
}
public abstract class ConfigBase
public class TimeoutConfig
{
public int DebtLimitSeconds { get; private set; } = 60 * 60 * 2;
public Dictionary<string, int> CommandCostsSeconds { get; private set; } = new Dictionary<string, int>()
{
{"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;
}
public abstract class ConfigBase
{
public ConfigBase(string path)
{
JObject configJson;
@ -59,6 +72,5 @@ namespace JetKarmaBot
System.Diagnostics.Debug.WriteLine(e);
}
}
}
}

View File

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

View File

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

View File

@ -0,0 +1,6 @@
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,85 +1,126 @@
using JetKarmaBot.Commands;
using JetKarmaBot.Models;
using JetKarmaBot.Services;
using Perfusion;
using System;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using JetKarmaBot.Services.Handling;
using NLog;
using Telegram.Bot;
using Telegram.Bot.Args;
using Telegram.Bot.Polling;
using Telegram.Bot.Types;
using Telegram.Bot.Types.Enums;
namespace JetKarmaBot
namespace JetKarmaBot;
public class JetKarmaBot : IDisposable
{
public class JetKarmaBot : IDisposable
{
[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;
Telegram.Bot.Types.User Me { get; set; }
RequestChain Chain;
Task timeoutWaitTask;
CancellationTokenSource timeoutWaitTaskToken;
private bool stopped = false;
public async Task Init()
{
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);
Client = new TelegramBotClient(Config.ApiKey);
Container.AddInstance(Client);
Me = await Client.GetMeAsync();
InitCommands(Container);
timeoutWaitTaskToken = new CancellationTokenSource();
timeoutWaitTask = Timeout.SaveLoop(timeoutWaitTaskToken.Token);
Client.OnMessage += BotOnMessageReceived;
Client.StartReceiving();
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
{
if (timeoutWaitTask != null)
await timeoutWaitTask;
}
catch (OperationCanceledException) { }
await Timeout?.Save();
Dispose();
stopped = true;
}
#region service
void BotOnMessageReceived(object sender, MessageEventArgs messageEventArgs)
Task HandleErrorAsync(ITelegramBotClient botClient, Exception exception, CancellationToken cancellationToken)
{
var message = messageEventArgs.Message;
if (message == null || message.Type != MessageType.Text)
return;
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));
Log.Error(exception, "Exception while handling API message");
return Task.CompletedTask;
}
void InitCommands(IContainer c)
async Task HandleUpdateAsync(ITelegramBotClient sender, Update update, CancellationToken cancellationToken)
{
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()));
if (update.Type != UpdateType.Message || update?.Message?.Type != MessageType.Text)
return;
var message = update.Message!;
try
{
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);
}
catch (Exception e)
{
Log.Error(e, "Exception while handling message {0}", message);
}
}
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>())
{
Commands.Add(cmd);
}
}
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
@ -88,9 +129,9 @@ namespace JetKarmaBot
public void Dispose()
{
Client.StopReceiving();
timeoutWaitTaskToken?.Dispose();
timeoutWaitTask?.Dispose();
}
#endregion
}
}

View File

@ -1,31 +1,20 @@
<Project Sdk="Microsoft.NET.Sdk">
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFrameworks>netcoreapp2.2;</TargetFrameworks>
<TargetFramework>net8.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<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" />
<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" />
<ProjectReference Include="..\perfusion\Perfusion\Perfusion.csproj" />
</ItemGroup>
<ItemGroup>
<None Update="karma.cfg.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<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">
<None Update="lang\*">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Update="NLog.config">

View File

@ -1,15 +1,13 @@
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.ComponentModel.DataAnnotations.Schema;
namespace JetKarmaBot.Models
namespace JetKarmaBot.Models;
public partial class Award
{
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 long FromId { get; set; }
public long ToId { get; set; }
public sbyte AwardTypeId { get; set; }
public sbyte Amount { get; set; }
public DateTime Date { get; set; }
@ -21,5 +19,4 @@ namespace JetKarmaBot.Models
public virtual User From { get; set; }
[ForeignKey("ToId")]
public virtual User To { get; set; }
}
}

View File

@ -1,10 +1,7 @@
using System;
using System.Collections.Generic;
namespace JetKarmaBot.Models;
namespace JetKarmaBot.Models
public partial class AwardType
{
public partial class AwardType
{
public AwardType()
{
Awards = new HashSet<Award>();
@ -17,5 +14,4 @@ namespace JetKarmaBot.Models
public string Description { get; set; }
public virtual ICollection<Award> Awards { get; set; }
}
}

View File

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

View File

@ -1,13 +1,10 @@
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata;
using Perfusion;
using Microsoft.EntityFrameworkCore;
namespace JetKarmaBot.Models
namespace JetKarmaBot.Models;
[Transient]
public partial class KarmaContext : DbContext
{
[Transient]
public partial class KarmaContext : DbContext
{
public KarmaContext()
{
}
@ -34,20 +31,20 @@ namespace JetKarmaBot.Models
entity.ToTable("award");
entity.HasIndex(e => e.AwardId)
.HasName("awardid_UNIQUE")
.HasDatabaseName("awardid_UNIQUE")
.IsUnique();
entity.HasIndex(e => e.AwardTypeId)
.HasName("fk_awardtype_idx");
.HasDatabaseName("fk_awardtype_idx");
entity.HasIndex(e => e.ChatId)
.HasName("fk_chat_idx");
.HasDatabaseName("fk_chat_idx");
entity.HasIndex(e => e.FromId)
.HasName("fk_from_idx");
.HasDatabaseName("fk_from_idx");
entity.HasIndex(e => e.ToId)
.HasName("fk_to_idx");
.HasDatabaseName("fk_to_idx");
entity.Property(e => e.AwardId)
.HasColumnName("awardid")
@ -109,11 +106,11 @@ namespace JetKarmaBot.Models
entity.ToTable("awardtype");
entity.HasIndex(e => e.AwardTypeId)
.HasName("awardtypeid_UNIQUE")
.HasDatabaseName("awardtypeid_UNIQUE")
.IsUnique();
entity.HasIndex(e => e.CommandName)
.HasName("commandname_UNIQUE")
.HasDatabaseName("commandname_UNIQUE")
.IsUnique();
entity.Property(e => e.AwardTypeId)
@ -172,7 +169,11 @@ namespace JetKarmaBot.Models
entity.Property(e => e.Username)
.HasColumnName("username")
.HasColumnType("varchar(45)");
entity.Property(e => e.CooldownDate)
.HasColumnName("cooldowndate")
.HasColumnType("timestamp")
.HasDefaultValueSql("CURRENT_TIMESTAMP");
});
}
}
}

View File

@ -1,22 +1,20 @@
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.ComponentModel.DataAnnotations.Schema;
namespace JetKarmaBot.Models
namespace JetKarmaBot.Models;
public partial class User
{
public partial class User
{
public User()
{
AwardsFrom = new HashSet<Award>();
AwardsTo = new HashSet<Award>();
}
public int UserId { get; set; }
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; }
}
}

View File

@ -1,14 +1,11 @@
using System;
using System.Threading;
using JetKarmaBot.Models;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using NLog;
using Perfusion;
using JetKarmaBot.Models;
namespace JetKarmaBot
namespace JetKarmaBot;
public static class Program
{
public static class Program
{
private static Logger log = LogManager.GetCurrentClassLogger();
public enum ExitCode : int
{
@ -26,8 +23,11 @@ namespace JetKarmaBot
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(cfg.ConnectionString + (cfg.ConnectionString.EndsWith(";") ? "" : ";") + "TreatTinyAsBoolean=false");
.UseMySql(connStr, serverVersion);
c.AddInfo<Logger>(new LogInfo());
if (cfg.SqlDebug)
{
@ -40,14 +40,13 @@ namespace JetKarmaBot
try
{
bot.Init().Wait();
bot.Init().GetAwaiter().GetResult();
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;
return (int)ExitCode.ErrorException;
}
ManualResetEvent quitEvent = new ManualResetEvent(false);
try
@ -57,14 +56,18 @@ namespace JetKarmaBot
eArgs.Cancel = true;
quitEvent.Set();
};
AppDomain.CurrentDomain.ProcessExit += (sender, args) =>
{
log.Info("Received stop request, waiting for exit...");
bot?.Stop()?.GetAwaiter().GetResult();
};
}
catch { }
quitEvent.WaitOne(Timeout.Infinite);
log.Info("Waiting for exit...");
bot?.Stop()?.Wait();
bot?.Stop()?.GetAwaiter().GetResult();
return (int)ExitCode.Ok;
}
}
}

View File

@ -0,0 +1,105 @@
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

@ -0,0 +1,17 @@
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

@ -0,0 +1,37 @@
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

@ -0,0 +1,32 @@
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

@ -0,0 +1,33 @@
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

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

View File

@ -1,20 +1,15 @@
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
namespace JetKarmaBot;
public class Localization : IReadOnlyDictionary<string, Locale>
{
public class Localization : IReadOnlyDictionary<string, Locale>
{
private Dictionary<string, Locale> locales = new Dictionary<string, Locale>();
[Inject]
public Localization(IContainer c)
{
c.ResolveObject(this);
@ -110,9 +105,9 @@ namespace JetKarmaBot
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
}
public class Locale : IReadOnlyDictionary<string, string>
{
}
public class Locale : IReadOnlyDictionary<string, string>
{
private Dictionary<string, string> locale;
private string localeName;
private string[] commonNames;
@ -137,7 +132,7 @@ namespace JetKarmaBot
public int Count => ((IReadOnlyDictionary<string, string>)locale).Count;
public string this[string name] => locale.ContainsKey(name) ? locale[name] : "unknown";
public string this[string name] => locale.ContainsKey(name) ? locale[name] : "Unmapped locale key: " + name;
public bool ContainsKey(string key)
{
@ -158,15 +153,14 @@ namespace JetKarmaBot
{
return ((IReadOnlyDictionary<string, string>)locale).GetEnumerator();
}
}
[System.Serializable]
public class LocalizationException : Exception
{
}
[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,12 +1,11 @@
using System;
using System.Linq;
using NLog;
using Perfusion;
namespace JetKarmaBot
namespace JetKarmaBot;
public class LogInfo : ObjectInfo
{
public class LogInfo : ObjectInfo
{
public override ObjectInfo Clone() => new LogInfo();
public override object GetInstance(IContainer c, Type requester = null)
{
return LogManager.GetLogger(requester != null ? getTypeName(requester) : "<type unspecified>");
@ -16,5 +15,4 @@ namespace JetKarmaBot
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,12 +1,10 @@
using System;
using Microsoft.Extensions.Logging;
using NLog;
using Perfusion;
namespace JetKarmaBot
namespace JetKarmaBot;
public class NLoggerFactory : ILoggerFactory
{
public class NLoggerFactory : ILoggerFactory
{
[Inject]
private NLoggerProvider c;
public void AddProvider(ILoggerProvider provider)
@ -18,9 +16,9 @@ namespace JetKarmaBot
public void Dispose()
{
}
}
public class NLoggerProvider : ILoggerProvider
{
}
public class NLoggerProvider : ILoggerProvider
{
[Inject]
private Container c;
@ -29,10 +27,10 @@ namespace JetKarmaBot
public void Dispose()
{
}
}
}
public class LoggerVirtualizer : Microsoft.Extensions.Logging.ILogger
{
public class LoggerVirtualizer : Microsoft.Extensions.Logging.ILogger
{
private Logger logger;
public LoggerVirtualizer(Logger logger)
@ -93,11 +91,10 @@ namespace JetKarmaBot
if (exception != null) logger.Log(getAppropriate(logLevel), exception, formatter(state, exception));
else logger.Log(getAppropriate(logLevel), state);
}
}
public class SomeDisposable : IDisposable
{
}
public class SomeDisposable : IDisposable
{
public void Dispose()
{
}
}
}

View File

@ -6,21 +6,23 @@
],
"note": "This is a joke. And made with google translate.",
"strings": {
"jetkarmabot.award.errawardnoreply": "Калі ласка выкарыстоўвайце гэтую каманду ў адказе іншаму карыстальніку.",
"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.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": "Я ведаю:",
@ -33,17 +35,32 @@
"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.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": "пілюлю"
}
}

View File

@ -5,21 +5,23 @@
"англійская"
],
"strings": {
"jetkarmabot.award.errawardnoreply": "Please use this command in reply to another user.",
"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.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:",
@ -32,17 +34,32 @@
"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.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"
}
}

View File

@ -5,21 +5,23 @@
"руская"
],
"strings": {
"jetkarmabot.award.errawardnoreply": "Пожалуйста используйте эту команду в ответе другому пользователю.",
"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.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": "Я знаю:",
@ -32,17 +34,32 @@
"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.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": "пилюлю"
}
}

41
karma.sql Normal file
View File

@ -0,0 +1,41 @@
-- 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 40e8f8871f42f1f32c29480505cf5ac6ba61c393
Subproject commit 115f59eecb2a4a74c63770866539502cde28d881