mirror of
https://github.com/Jetsparrow/karmabot.git
synced 2026-01-21 09:06:09 +03:00
Compare commits
111 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 2cc286ad9c | |||
| d2e8ed4d69 | |||
| 8fca14e398 | |||
| 67f05b6f3d | |||
| b666b43000 | |||
| e905b8583d | |||
| ed7346c16d | |||
| dc879e2984 | |||
| b454b09878 | |||
| 58f7e17ba6 | |||
| 6ff22680b9 | |||
| 98ba039788 | |||
| 8baf576733 | |||
| 38b1169309 | |||
| eae44695e7 | |||
| 0b40235c9b | |||
| 3544f521f9 | |||
| 09c07e6296 | |||
| e106681c11 | |||
| 66de361342 | |||
| af7def64a4 | |||
| 13e3be89b3 | |||
| 00dd51cea9 | |||
| 72fbee9c46 | |||
| 87ed735486 | |||
| a354305334 | |||
| a4f94428ce | |||
| 000a0d8718 | |||
| b3dbdb5806 | |||
| f47c48e1be | |||
| 636040c635 | |||
| cd2a0d5710 | |||
| df982d53aa | |||
| 228c078947 | |||
| 8132f8edac | |||
| d8b2b1c448 | |||
| 06703f13a6 | |||
| 666ba84a92 | |||
| 6ef9b602e5 | |||
| f0a55f305e | |||
| d005fd0ba4 | |||
| 0759fe2af6 | |||
| 85125a46f1 | |||
| 57c861e473 | |||
| 55333b95d3 | |||
| a1b5db8430 | |||
| 5e239c934c | |||
|
|
2410a5d826 | ||
| c1523f69db | |||
| ddf58321ec | |||
| 30035b0a83 | |||
| 92e996e599 | |||
| dbbc616c8c | |||
| c07a2051e3 | |||
| e4923e4d79 | |||
| 28bca4832d | |||
| 737063d2dc | |||
| 48be616899 | |||
| e3ece07d50 | |||
| 58ed942ca3 | |||
| de29905324 | |||
| 831a902fd1 | |||
| 633ef9ccba | |||
| e0411760e3 | |||
| 9b78abcd58 | |||
| 86ab927005 | |||
| 7291318dcc | |||
| 3ce21285fa | |||
| 5399bc03ba | |||
| 6b39a8f27f | |||
| a08b5da0f2 | |||
| e5a4c62214 | |||
| 6af15e7c29 | |||
| 431b47de69 | |||
| b9194b5743 | |||
| a7493e4911 | |||
| 7232d18736 | |||
| 5789890fd9 | |||
| 7552303a6e | |||
| fb1843360c | |||
| a7df153b8a | |||
| 89a0408ae5 | |||
| b5b5478446 | |||
| 55b65828b3 | |||
| 2944ea150c | |||
| 4c77b075c9 | |||
| 1781c2bdcf | |||
| cc82c02e44 | |||
| 66190a1eb0 | |||
| 7820d50fe8 | |||
| ef3db7ac50 | |||
| d55217e539 | |||
| ba9f698040 | |||
| 93e69db9ad | |||
| 320cbdba5e | |||
| fa2ad31963 | |||
| 314d861f4e | |||
| 20e043c669 | |||
| dee9baa037 | |||
| 501fc5d2c2 | |||
| 1e4ad52356 | |||
| 6f837dc67f | |||
| 2cdb9587ee | |||
| 4355ae4058 | |||
| ab90a15c8c | |||
| 1684b62e7d | |||
| 0bb9a58711 | |||
| d200249650 | |||
| 128e0b3fd2 | |||
| 91bb1dd383 | |||
| 36cb3d8fae |
3
.gitmodules
vendored
Normal file
3
.gitmodules
vendored
Normal file
@ -0,0 +1,3 @@
|
|||||||
|
[submodule "perfusion"]
|
||||||
|
path = perfusion
|
||||||
|
url = https://github.com/PorezPorezych/perfusion
|
||||||
@ -3,7 +3,9 @@ Microsoft Visual Studio Solution File, Format Version 12.00
|
|||||||
# Visual Studio 15
|
# Visual Studio 15
|
||||||
VisualStudioVersion = 15.0.28010.2036
|
VisualStudioVersion = 15.0.28010.2036
|
||||||
MinimumVisualStudioVersion = 10.0.40219.1
|
MinimumVisualStudioVersion = 10.0.40219.1
|
||||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "JetKarmaBot", "JetKarmaBot\JetKarmaBot.csproj", "{729E88EE-BE5E-4D12-B83F-EDC5FC5E2D07}"
|
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "JetKarmaBot", "JetKarmaBot\JetKarmaBot.csproj", "{729E88EE-BE5E-4D12-B83F-EDC5FC5E2D07}"
|
||||||
|
EndProject
|
||||||
|
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Perfusion", "perfusion\Perfusion\Perfusion.csproj", "{C3525FCF-0EE0-4802-B18D-83233BF0C85A}"
|
||||||
EndProject
|
EndProject
|
||||||
Global
|
Global
|
||||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||||
@ -15,6 +17,10 @@ Global
|
|||||||
{729E88EE-BE5E-4D12-B83F-EDC5FC5E2D07}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
{729E88EE-BE5E-4D12-B83F-EDC5FC5E2D07}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||||
{729E88EE-BE5E-4D12-B83F-EDC5FC5E2D07}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
{729E88EE-BE5E-4D12-B83F-EDC5FC5E2D07}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||||
{729E88EE-BE5E-4D12-B83F-EDC5FC5E2D07}.Release|Any CPU.Build.0 = Release|Any CPU
|
{729E88EE-BE5E-4D12-B83F-EDC5FC5E2D07}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||||
|
{C3525FCF-0EE0-4802-B18D-83233BF0C85A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||||
|
{C3525FCF-0EE0-4802-B18D-83233BF0C85A}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||||
|
{C3525FCF-0EE0-4802-B18D-83233BF0C85A}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||||
|
{C3525FCF-0EE0-4802-B18D-83233BF0C85A}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||||
EndGlobalSection
|
EndGlobalSection
|
||||||
GlobalSection(SolutionProperties) = preSolution
|
GlobalSection(SolutionProperties) = preSolution
|
||||||
HideSolutionNode = FALSE
|
HideSolutionNode = FALSE
|
||||||
|
|||||||
@ -1,36 +0,0 @@
|
|||||||
using JetKarmaBot.Commands;
|
|
||||||
using System;
|
|
||||||
using System.Collections.Generic;
|
|
||||||
using System.Linq;
|
|
||||||
using Telegram.Bot.Args;
|
|
||||||
|
|
||||||
namespace JetKarmaBot
|
|
||||||
{
|
|
||||||
class ChatCommandRouter
|
|
||||||
{
|
|
||||||
Dictionary<string, IChatCommand> commands = new Dictionary<string, IChatCommand>();
|
|
||||||
public bool Execute(object sender, MessageEventArgs args)
|
|
||||||
{
|
|
||||||
var text = args.Message.Text;
|
|
||||||
|
|
||||||
if (CommandString.TryParse(text, out var cs))
|
|
||||||
{
|
|
||||||
if (commands.ContainsKey(cs.Name))
|
|
||||||
return commands[cs.Name].Execute(sender,args);
|
|
||||||
}
|
|
||||||
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void Add(IChatCommand c)
|
|
||||||
{
|
|
||||||
foreach (var name in c.Names)
|
|
||||||
{
|
|
||||||
if (commands.ContainsKey(name))
|
|
||||||
throw new Exception($"command collision for name {name}, commands {commands[name].GetType()} and {c.GetType()}");
|
|
||||||
commands[name] = c;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@ -1,73 +1,156 @@
|
|||||||
using System;
|
using Microsoft.EntityFrameworkCore;
|
||||||
using System.Collections.Generic;
|
using NLog;
|
||||||
using System.Linq;
|
using JetKarmaBot.Services.Handling;
|
||||||
using System.Text;
|
using JetKarmaBot.Models;
|
||||||
using Telegram.Bot;
|
|
||||||
using Telegram.Bot.Args;
|
|
||||||
using Telegram.Bot.Types;
|
|
||||||
using Telegram.Bot.Types.Enums;
|
|
||||||
|
|
||||||
namespace JetKarmaBot.Commands
|
namespace JetKarmaBot.Commands;
|
||||||
|
|
||||||
|
class AwardCommand : IChatCommand
|
||||||
{
|
{
|
||||||
class AwardCommand : IChatCommand
|
public IReadOnlyCollection<string> Names => new[] { "award", "revoke" };
|
||||||
{
|
[Inject] private Logger log;
|
||||||
public IReadOnlyCollection<string> Names => new[] { "award", "revoke"};
|
|
||||||
|
|
||||||
public bool Execute(object sender, MessageEventArgs args)
|
public async Task<bool> Execute(RequestContext ctx)
|
||||||
{
|
{
|
||||||
if (args.Message.ReplyToMessage == null)
|
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)
|
||||||
{
|
{
|
||||||
Client.SendTextMessageAsync(args.Message.Chat.Id, "Please use this command in reply to another user.");
|
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;
|
||||||
|
}
|
||||||
|
|
||||||
|
string awardTypeText = null;
|
||||||
|
long recipientId = default;
|
||||||
|
foreach (string arg in ctx.Command.Parameters)
|
||||||
|
{
|
||||||
|
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 (ctx.EventArgs.Message.ReplyToMessage != null && recipientId == default)
|
||||||
|
{
|
||||||
|
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;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
var awarder = args.Message.From;
|
private string getLocalizedName(global::JetKarmaBot.Models.AwardType awardType, Locale loc)
|
||||||
var recipient = args.Message.ReplyToMessage.From;
|
|
||||||
|
|
||||||
if (awarder.Id == recipient.Id)
|
|
||||||
{
|
{
|
||||||
Client.SendTextMessageAsync(
|
if (loc.ContainsKey($"jetkarmabot.awardtypes.accusative.{awardType.CommandName}"))
|
||||||
args.Message.Chat.Id,
|
|
||||||
"Please stop playing with yourself.",
|
|
||||||
replyToMessageId: args.Message.MessageId);
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (Me.Id == recipient.Id)
|
|
||||||
{
|
{
|
||||||
Client.SendTextMessageAsync(
|
return loc[$"jetkarmabot.awardtypes.accusative.{awardType.CommandName}"];
|
||||||
args.Message.Chat.Id,
|
|
||||||
"I am a bot, and have no use for your foolish fake internet points.",
|
|
||||||
replyToMessageId: args.Message.MessageId);
|
|
||||||
return true;
|
|
||||||
}
|
}
|
||||||
|
else
|
||||||
var text = args.Message.Text;
|
|
||||||
var command = CommandString.Parse(text);
|
|
||||||
var awardTypeId = Db.GetAwardTypeId(command.Parameters.FirstOrDefault());
|
|
||||||
var awardType = Db.AwardTypes[awardTypeId];
|
|
||||||
|
|
||||||
Db.AddAward(awardTypeId, awarder.Id, recipient.Id, args.Message.Chat.Id, 1);
|
|
||||||
|
|
||||||
var response = $"Awarded a {awardType.Name} to {recipient.Username}!\n" +
|
|
||||||
$"{recipient.Username} is at {Db.CountAwards(recipient.Id, awardTypeId)}{awardType.Symbol} now.";
|
|
||||||
Client.SendTextMessageAsync(
|
|
||||||
args.Message.Chat.Id,
|
|
||||||
response,
|
|
||||||
replyToMessageId: args.Message.MessageId);
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
Db Db { get; }
|
|
||||||
TelegramBotClient Client { get; }
|
|
||||||
User Me { get; }
|
|
||||||
|
|
||||||
public AwardCommand(Db db, TelegramBotClient client, User me)
|
|
||||||
{
|
{
|
||||||
Db = db;
|
return awardType.Name;
|
||||||
Client = client;
|
|
||||||
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"
|
||||||
|
}
|
||||||
|
};
|
||||||
}
|
}
|
||||||
|
|||||||
75
JetKarmaBot/Commands/ChangeLocaleCommand.cs
Normal file
75
JetKarmaBot/Commands/ChangeLocaleCommand.cs
Normal file
@ -0,0 +1,75 @@
|
|||||||
|
using NLog;
|
||||||
|
using JetKarmaBot.Services.Handling;
|
||||||
|
using JetKarmaBot.Models;
|
||||||
|
|
||||||
|
namespace JetKarmaBot.Commands;
|
||||||
|
|
||||||
|
class LocaleCommand : IChatCommand
|
||||||
|
{
|
||||||
|
public IReadOnlyCollection<string> Names => new[] { "changelocale", "locale" };
|
||||||
|
[Inject] private Logger log;
|
||||||
|
|
||||||
|
public async Task<bool> Execute(RequestContext ctx)
|
||||||
|
{
|
||||||
|
var db = ctx.GetFeature<KarmaContext>();
|
||||||
|
var currentLocale = ctx.GetFeature<Locale>();
|
||||||
|
var cmd = ctx.Command;
|
||||||
|
var args = ctx.EventArgs;
|
||||||
|
|
||||||
|
if (cmd.Parameters.Length < 1)
|
||||||
|
{
|
||||||
|
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
|
||||||
|
{
|
||||||
|
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}");
|
||||||
|
|
||||||
|
currentLocale = Locale[localeId];
|
||||||
|
|
||||||
|
await ctx.SendMessage(
|
||||||
|
(currentLocale.HasNote ? currentLocale["jetkarmabot.changelocale.beforenote"] + currentLocale.Note + "\n" : "")
|
||||||
|
+ currentLocale["jetkarmabot.changelocale.justchanged"]);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
[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"
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
@ -1,31 +1,42 @@
|
|||||||
using System;
|
using System.Text.RegularExpressions;
|
||||||
using System.Collections.Generic;
|
|
||||||
using System.Text;
|
|
||||||
|
|
||||||
namespace JetKarmaBot.Commands
|
namespace JetKarmaBot.Commands;
|
||||||
|
|
||||||
|
public class CommandString
|
||||||
{
|
{
|
||||||
public class CommandString
|
public CommandString(string command, params string[] parameters)
|
||||||
{
|
{
|
||||||
public CommandString(string name, params string[] parameters)
|
Command = command;
|
||||||
{
|
|
||||||
Name = name;
|
|
||||||
Parameters = parameters;
|
Parameters = parameters;
|
||||||
}
|
}
|
||||||
|
|
||||||
public string Name { get; }
|
public string Command { get; }
|
||||||
|
public string UserName { get; set; } = null;
|
||||||
public string[] Parameters { get; }
|
public string[] Parameters { get; }
|
||||||
|
|
||||||
|
public static readonly char[] WS_CHARS = new[] { ' ', '\r', '\n', '\n' };
|
||||||
|
|
||||||
public static bool TryParse(string s, out CommandString result)
|
public static bool TryParse(string s, out CommandString result)
|
||||||
{
|
{
|
||||||
result = null;
|
result = null;
|
||||||
if (string.IsNullOrWhiteSpace(s) || s[0] != '/')
|
if (string.IsNullOrWhiteSpace(s) || s[0] != '/')
|
||||||
return false;
|
return false;
|
||||||
|
|
||||||
int space = s.IndexOf(' ');
|
string[] words = s.Split(WS_CHARS, StringSplitOptions.RemoveEmptyEntries);
|
||||||
if (space < 0)
|
|
||||||
result = new CommandString(s.Substring(1));
|
if (!words.Any())
|
||||||
else
|
return false;
|
||||||
result = new CommandString(s.Substring(1, space - 1), s.Substring(space).Split(' ', StringSplitOptions.RemoveEmptyEntries));
|
|
||||||
|
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();
|
||||||
|
|
||||||
|
result = new CommandString(cmd, parameters) { UserName = username };
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -34,5 +45,4 @@ namespace JetKarmaBot.Commands
|
|||||||
if (TryParse(s, out var c)) return c;
|
if (TryParse(s, out var c)) return c;
|
||||||
throw new ArgumentException($"\"{s}\" is not a command");
|
throw new ArgumentException($"\"{s}\" is not a command");
|
||||||
}
|
}
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
28
JetKarmaBot/Commands/CurrenciesCommand.cs
Normal file
28
JetKarmaBot/Commands/CurrenciesCommand.cs
Normal file
@ -0,0 +1,28 @@
|
|||||||
|
using Microsoft.EntityFrameworkCore;
|
||||||
|
using JetKarmaBot.Services.Handling;
|
||||||
|
using JetKarmaBot.Models;
|
||||||
|
|
||||||
|
namespace JetKarmaBot.Commands;
|
||||||
|
|
||||||
|
public class CurrenciesCommand : IChatCommand
|
||||||
|
{
|
||||||
|
[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)
|
||||||
|
{
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
}
|
||||||
38
JetKarmaBot/Commands/HelpCommand.cs
Normal file
38
JetKarmaBot/Commands/HelpCommand.cs
Normal file
@ -0,0 +1,38 @@
|
|||||||
|
using JetKarmaBot.Services.Handling;
|
||||||
|
|
||||||
|
namespace JetKarmaBot.Commands;
|
||||||
|
|
||||||
|
public class HelpCommand : IChatCommand
|
||||||
|
{
|
||||||
|
[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)
|
||||||
|
{
|
||||||
|
var currentLocale = ctx.GetFeature<Locale>();
|
||||||
|
var router = ctx.GetFeature<ChatCommandRouter.Feature>().Router;
|
||||||
|
if (ctx.Command.Parameters.Length < 1)
|
||||||
|
{
|
||||||
|
await ctx.SendMessage(router.GetHelpText(currentLocale));
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
await ctx.SendMessage(router.GetHelpTextFor(ctx.Command.Parameters[0], currentLocale));
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -1,12 +1,29 @@
|
|||||||
using System.Collections.Generic;
|
using JetKarmaBot.Services.Handling;
|
||||||
using Telegram.Bot.Args;
|
|
||||||
|
|
||||||
namespace JetKarmaBot.Commands
|
namespace JetKarmaBot.Commands;
|
||||||
|
|
||||||
|
public interface IChatCommand
|
||||||
{
|
{
|
||||||
public interface IChatCommand
|
|
||||||
{
|
|
||||||
IReadOnlyCollection<string> Names { get; }
|
IReadOnlyCollection<string> Names { get; }
|
||||||
bool Execute(object sender, MessageEventArgs messageEventArgs);
|
string Description { get; }
|
||||||
}
|
string DescriptionID { get; }
|
||||||
|
IReadOnlyCollection<ChatCommandArgument> Arguments { get; }
|
||||||
|
|
||||||
|
Task<bool> Execute(RequestContext ctx);
|
||||||
|
}
|
||||||
|
|
||||||
|
public struct ChatCommandArgument
|
||||||
|
{
|
||||||
|
public string Name;
|
||||||
|
public bool Required;
|
||||||
|
public ChatCommandArgumentType Type;
|
||||||
|
public string Description;
|
||||||
|
public string DescriptionID;
|
||||||
|
}
|
||||||
|
|
||||||
|
public enum ChatCommandArgumentType
|
||||||
|
{
|
||||||
|
Boolean,
|
||||||
|
String,
|
||||||
|
Integer,
|
||||||
}
|
}
|
||||||
|
|||||||
65
JetKarmaBot/Commands/LeaderboardCommand.cs
Normal file
65
JetKarmaBot/Commands/LeaderboardCommand.cs
Normal 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"
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
@ -1,24 +0,0 @@
|
|||||||
using System.Collections.Generic;
|
|
||||||
using Telegram.Bot.Args;
|
|
||||||
|
|
||||||
namespace JetKarmaBot.Commands
|
|
||||||
{
|
|
||||||
public class StartCommand : IChatCommand
|
|
||||||
{
|
|
||||||
Db Db;
|
|
||||||
|
|
||||||
public StartCommand(Db db)
|
|
||||||
{
|
|
||||||
Db = db;
|
|
||||||
}
|
|
||||||
|
|
||||||
public IReadOnlyCollection<string> Names => new[] { "start" };
|
|
||||||
|
|
||||||
public bool Execute(object sender, MessageEventArgs args)
|
|
||||||
{
|
|
||||||
Db.AddChat(new Db.Chat { ChatId = args.Message.Chat.Id });
|
|
||||||
Db.AddUser(new Db.User { UserId = args.Message.From.Id });
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
51
JetKarmaBot/Commands/StatusCommand.cs
Normal file
51
JetKarmaBot/Commands/StatusCommand.cs
Normal file
@ -0,0 +1,51 @@
|
|||||||
|
using Microsoft.EntityFrameworkCore;
|
||||||
|
using JetKarmaBot.Services.Handling;
|
||||||
|
using JetKarmaBot.Models;
|
||||||
|
|
||||||
|
namespace JetKarmaBot.Commands;
|
||||||
|
|
||||||
|
class StatusCommand : IChatCommand
|
||||||
|
{
|
||||||
|
public IReadOnlyCollection<string> Names => ["status"];
|
||||||
|
|
||||||
|
public async Task<bool> Execute(RequestContext ctx)
|
||||||
|
{
|
||||||
|
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;
|
||||||
|
|
||||||
|
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 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}"));
|
||||||
|
}
|
||||||
|
|
||||||
|
await ctx.SendMessage(response);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
[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 => [];
|
||||||
|
}
|
||||||
@ -1,25 +1,44 @@
|
|||||||
using System;
|
using System.IO;
|
||||||
using System.IO;
|
|
||||||
using Newtonsoft.Json;
|
using Newtonsoft.Json;
|
||||||
using JsonNet.PrivateSettersContractResolvers;
|
using JsonNet.PrivateSettersContractResolvers;
|
||||||
using Newtonsoft.Json.Linq;
|
using Newtonsoft.Json.Linq;
|
||||||
|
|
||||||
namespace JetKarmaBot
|
namespace JetKarmaBot;
|
||||||
|
|
||||||
|
public class Config : ConfigBase
|
||||||
{
|
{
|
||||||
public class Config : ConfigBase
|
|
||||||
{
|
|
||||||
public Config(string path) : base(path) { }
|
public Config(string path) : base(path) { }
|
||||||
|
|
||||||
public string ApiKey { get; private set; }
|
public string ApiKey { get; private set; }
|
||||||
public string ConnectionString { get; private set; }
|
public string ConnectionString { get; private set; }
|
||||||
public string ProxyUrl { get; private set; }
|
|
||||||
public int ProxyPort { get; private set; }
|
public class ProxySettings
|
||||||
public string ProxyLogin { get; private set; }
|
{
|
||||||
public string ProxyPassword { get; private set; }
|
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 abstract class ConfigBase
|
public ProxySettings Proxy { get; private set; }
|
||||||
|
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)
|
public ConfigBase(string path)
|
||||||
{
|
{
|
||||||
JObject configJson;
|
JObject configJson;
|
||||||
@ -53,6 +72,5 @@ namespace JetKarmaBot
|
|||||||
System.Diagnostics.Debug.WriteLine(e);
|
System.Diagnostics.Debug.WriteLine(e);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@ -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)
|
public static TValue GetOrDefault<TKey, TValue>(this IReadOnlyDictionary<TKey, TValue> dict, TKey key)
|
||||||
{
|
{
|
||||||
TValue res = default(TValue);
|
TValue res = default;
|
||||||
if (key != null)
|
if (key != null)
|
||||||
dict.TryGetValue(key, out res);
|
dict.TryGetValue(key, out res);
|
||||||
return res;
|
return res;
|
||||||
}
|
}
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@ -3,10 +3,10 @@ using Newtonsoft.Json;
|
|||||||
using Newtonsoft.Json.Serialization;
|
using Newtonsoft.Json.Serialization;
|
||||||
|
|
||||||
// ReSharper disable once CheckNamespace
|
// 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)
|
protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
|
||||||
{
|
{
|
||||||
var jProperty = base.CreateProperty(member, memberSerialization);
|
var jProperty = base.CreateProperty(member, memberSerialization);
|
||||||
@ -17,10 +17,10 @@ namespace JsonNet.PrivateSettersContractResolvers
|
|||||||
|
|
||||||
return jProperty;
|
return jProperty;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public class PrivateSetterCamelCasePropertyNamesContractResolver : CamelCasePropertyNamesContractResolver
|
public class PrivateSetterCamelCasePropertyNamesContractResolver : CamelCasePropertyNamesContractResolver
|
||||||
{
|
{
|
||||||
protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
|
protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
|
||||||
{
|
{
|
||||||
var jProperty = base.CreateProperty(member, memberSerialization);
|
var jProperty = base.CreateProperty(member, memberSerialization);
|
||||||
@ -31,15 +31,14 @@ namespace JsonNet.PrivateSettersContractResolvers
|
|||||||
|
|
||||||
return jProperty;
|
return jProperty;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
internal static class MemberInfoExtensions
|
internal static class MemberInfoExtensions
|
||||||
{
|
{
|
||||||
internal static bool IsPropertyWithSetter(this MemberInfo member)
|
internal static bool IsPropertyWithSetter(this MemberInfo member)
|
||||||
{
|
{
|
||||||
var property = member as PropertyInfo;
|
var property = member as PropertyInfo;
|
||||||
|
|
||||||
return property?.GetSetMethod(true) != null;
|
return property?.GetSetMethod(true) != null;
|
||||||
}
|
}
|
||||||
}
|
|
||||||
}
|
}
|
||||||
6
JetKarmaBot/GlobalUsings.cs
Normal file
6
JetKarmaBot/GlobalUsings.cs
Normal 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;
|
||||||
@ -1,74 +1,137 @@
|
|||||||
using JetKarmaBot.Commands;
|
using JetKarmaBot.Commands;
|
||||||
using System;
|
using JetKarmaBot.Models;
|
||||||
using System.Collections.Generic;
|
using JetKarmaBot.Services;
|
||||||
using System.Linq;
|
using JetKarmaBot.Services.Handling;
|
||||||
using System.Net;
|
using NLog;
|
||||||
using System.Reflection;
|
|
||||||
using System.Text;
|
|
||||||
using System.Threading.Tasks;
|
|
||||||
|
|
||||||
using Telegram.Bot;
|
using Telegram.Bot;
|
||||||
using Telegram.Bot.Args;
|
using Telegram.Bot.Polling;
|
||||||
using Telegram.Bot.Types;
|
using Telegram.Bot.Types;
|
||||||
using Telegram.Bot.Types.Enums;
|
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;
|
||||||
|
RequestChain Chain;
|
||||||
|
Task timeoutWaitTask;
|
||||||
|
CancellationTokenSource timeoutWaitTaskToken;
|
||||||
|
private bool stopped = false;
|
||||||
|
|
||||||
|
public async Task Init()
|
||||||
{
|
{
|
||||||
public void Broadcast(string message)
|
using (KarmaContext db = Db.GetContext())
|
||||||
{
|
await db.Database.EnsureCreatedAsync();
|
||||||
foreach (var u in db.Chats)
|
|
||||||
client.SendTextMessageAsync(u.Value.ChatId, message);
|
Client = new TelegramBotClient(Config.ApiKey);
|
||||||
|
Container.AddInstance(Client);
|
||||||
|
|
||||||
|
timeoutWaitTaskToken = new CancellationTokenSource();
|
||||||
|
timeoutWaitTask = Timeout.SaveLoop(timeoutWaitTaskToken.Token);
|
||||||
|
|
||||||
|
await InitCommands(Container);
|
||||||
|
InitChain(Container);
|
||||||
|
|
||||||
|
var receiverOptions = new ReceiverOptions { AllowedUpdates = new[] { UpdateType.Message } };
|
||||||
|
Client.StartReceiving(
|
||||||
|
HandleUpdateAsync,
|
||||||
|
HandleErrorAsync,
|
||||||
|
receiverOptions);
|
||||||
}
|
}
|
||||||
|
|
||||||
public JetKarmaBot(Config cfg, Db db)
|
public async Task Stop()
|
||||||
{
|
{
|
||||||
this.db = db;
|
if (stopped) return;
|
||||||
var httpProxy = new WebProxy($"{cfg.ProxyUrl}:{cfg.ProxyPort}")
|
Client?.CloseAsync();
|
||||||
|
timeoutWaitTaskToken?.Cancel();
|
||||||
|
try
|
||||||
{
|
{
|
||||||
Credentials = new NetworkCredential(cfg.ProxyLogin, cfg.ProxyPassword)
|
if (timeoutWaitTask != null)
|
||||||
};
|
await timeoutWaitTask;
|
||||||
var botClient = new TelegramBotClient(cfg.ApiKey, httpProxy);
|
|
||||||
var cred = new NetworkCredential(cfg.ProxyLogin, cfg.ProxyPassword);
|
|
||||||
client = new TelegramBotClient(cfg.ApiKey, httpProxy);
|
|
||||||
me = client.GetMeAsync().Result;
|
|
||||||
InitCommands();
|
|
||||||
client.OnMessage += BotOnMessageReceived;
|
|
||||||
client.StartReceiving();
|
|
||||||
}
|
}
|
||||||
|
catch (OperationCanceledException) { }
|
||||||
#region IDisposable
|
await Timeout?.Save();
|
||||||
public void Dispose()
|
Dispose();
|
||||||
{
|
stopped = true;
|
||||||
client.StopReceiving();
|
|
||||||
}
|
}
|
||||||
#endregion
|
|
||||||
|
|
||||||
#region service
|
#region service
|
||||||
Db db { get; }
|
|
||||||
TelegramBotClient client { get; }
|
|
||||||
User me { get; }
|
|
||||||
|
|
||||||
ChatCommandRouter commands;
|
Task HandleErrorAsync(ITelegramBotClient botClient, Exception exception, CancellationToken cancellationToken)
|
||||||
void BotOnMessageReceived(object sender, MessageEventArgs messageEventArgs)
|
{
|
||||||
|
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
|
||||||
{
|
{
|
||||||
var message = messageEventArgs.Message;
|
|
||||||
if (message == null || message.Type != MessageType.Text)
|
if (message == null || message.Type != MessageType.Text)
|
||||||
return;
|
return;
|
||||||
|
if (!CommandString.TryParse(message.Text, out var cmd))
|
||||||
|
return;
|
||||||
|
if (cmd.UserName != null && cmd.UserName != Commands.Me.Username)
|
||||||
|
return;
|
||||||
|
|
||||||
string s = message.Text;
|
RequestContext ctx = new RequestContext(Client, update, cmd);
|
||||||
long id = message.Chat.Id;
|
await Chain.Handle(ctx);
|
||||||
long from = message.From.Id;
|
|
||||||
Task.Run(() => commands.Execute(sender, messageEventArgs));
|
|
||||||
}
|
}
|
||||||
void InitCommands()
|
catch (Exception e)
|
||||||
{
|
{
|
||||||
commands = new ChatCommandRouter();
|
Log.Error(e, "Exception while handling message {0}", message);
|
||||||
commands.Add(new StartCommand(db));
|
}
|
||||||
commands.Add(new AwardCommand(db, client, me));
|
}
|
||||||
|
|
||||||
|
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
|
#endregion
|
||||||
|
|
||||||
|
#region IDisposable
|
||||||
|
|
||||||
|
public void Dispose()
|
||||||
|
{
|
||||||
|
timeoutWaitTaskToken?.Dispose();
|
||||||
|
timeoutWaitTask?.Dispose();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#endregion
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,21 +1,24 @@
|
|||||||
<Project Sdk="Microsoft.NET.Sdk">
|
<Project Sdk="Microsoft.NET.Sdk">
|
||||||
|
|
||||||
<PropertyGroup>
|
<PropertyGroup>
|
||||||
<OutputType>Exe</OutputType>
|
<OutputType>Exe</OutputType>
|
||||||
<TargetFramework>netcoreapp2.1</TargetFramework>
|
<TargetFramework>net8.0</TargetFramework>
|
||||||
</PropertyGroup>
|
</PropertyGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<PackageReference Include="Dapper" Version="1.50.5" />
|
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
|
||||||
<PackageReference Include="MySql.Data" Version="8.0.13" />
|
<PackageReference Include="Pomelo.EntityFrameworkCore.MySql" Version="8.0.2" />
|
||||||
<PackageReference Include="Newtonsoft.Json" Version="12.0.1" />
|
<PackageReference Include="Telegram.Bot" Version="22.0.2" />
|
||||||
<PackageReference Include="Telegram.Bot" Version="14.10.0" />
|
<PackageReference Include="NLog" Version="5.3.4" />
|
||||||
|
<ProjectReference Include="..\perfusion\Perfusion\Perfusion.csproj" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<None Update="karma.cfg.json">
|
<None Update="karma.cfg.json">
|
||||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||||
</None>
|
</None>
|
||||||
|
<None Update="lang\*">
|
||||||
|
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||||
|
</None>
|
||||||
|
<None Update="NLog.config">
|
||||||
|
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||||
|
</None>
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
</Project>
|
</Project>
|
||||||
22
JetKarmaBot/Models/Award.cs
Normal file
22
JetKarmaBot/Models/Award.cs
Normal file
@ -0,0 +1,22 @@
|
|||||||
|
using System.ComponentModel.DataAnnotations.Schema;
|
||||||
|
|
||||||
|
namespace JetKarmaBot.Models;
|
||||||
|
|
||||||
|
public partial class Award
|
||||||
|
{
|
||||||
|
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; }
|
||||||
|
}
|
||||||
17
JetKarmaBot/Models/AwardType.cs
Normal file
17
JetKarmaBot/Models/AwardType.cs
Normal file
@ -0,0 +1,17 @@
|
|||||||
|
namespace JetKarmaBot.Models;
|
||||||
|
|
||||||
|
public partial class AwardType
|
||||||
|
{
|
||||||
|
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; }
|
||||||
|
}
|
||||||
15
JetKarmaBot/Models/Chat.cs
Normal file
15
JetKarmaBot/Models/Chat.cs
Normal file
@ -0,0 +1,15 @@
|
|||||||
|
namespace JetKarmaBot.Models;
|
||||||
|
|
||||||
|
public partial class Chat
|
||||||
|
{
|
||||||
|
public Chat()
|
||||||
|
{
|
||||||
|
Awards = new HashSet<Award>();
|
||||||
|
}
|
||||||
|
|
||||||
|
public long ChatId { get; set; }
|
||||||
|
public string Locale { get; set; } = "ru-RU";
|
||||||
|
public bool IsAdministrator { get; set; }
|
||||||
|
|
||||||
|
public virtual ICollection<Award> Awards { get; set; }
|
||||||
|
}
|
||||||
179
JetKarmaBot/Models/KarmaContext.cs
Normal file
179
JetKarmaBot/Models/KarmaContext.cs
Normal file
@ -0,0 +1,179 @@
|
|||||||
|
using Microsoft.EntityFrameworkCore;
|
||||||
|
|
||||||
|
namespace JetKarmaBot.Models;
|
||||||
|
|
||||||
|
[Transient]
|
||||||
|
public partial class KarmaContext : DbContext
|
||||||
|
{
|
||||||
|
public KarmaContext()
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
|
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 =>
|
||||||
|
{
|
||||||
|
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 =>
|
||||||
|
{
|
||||||
|
entity.ToTable("awardtype");
|
||||||
|
|
||||||
|
entity.HasIndex(e => e.AwardTypeId)
|
||||||
|
.HasDatabaseName("awardtypeid_UNIQUE")
|
||||||
|
.IsUnique();
|
||||||
|
|
||||||
|
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 =>
|
||||||
|
{
|
||||||
|
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)");
|
||||||
|
|
||||||
|
entity.Property(e => e.CooldownDate)
|
||||||
|
.HasColumnName("cooldowndate")
|
||||||
|
.HasColumnType("timestamp")
|
||||||
|
.HasDefaultValueSql("CURRENT_TIMESTAMP");
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
20
JetKarmaBot/Models/User.cs
Normal file
20
JetKarmaBot/Models/User.cs
Normal file
@ -0,0 +1,20 @@
|
|||||||
|
using System.ComponentModel.DataAnnotations.Schema;
|
||||||
|
|
||||||
|
namespace JetKarmaBot.Models;
|
||||||
|
|
||||||
|
public partial class User
|
||||||
|
{
|
||||||
|
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; }
|
||||||
|
}
|
||||||
14
JetKarmaBot/NLog.config
Executable file
14
JetKarmaBot/NLog.config
Executable file
@ -0,0 +1,14 @@
|
|||||||
|
<?xml version="1.0" encoding="utf-8" ?>
|
||||||
|
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
|
||||||
|
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
|
||||||
|
|
||||||
|
<targets>
|
||||||
|
<target name="logfile" xsi:type="File" fileName="karmabot.log" />
|
||||||
|
<target name="logconsole" xsi:type="Console" />
|
||||||
|
</targets>
|
||||||
|
|
||||||
|
<rules>
|
||||||
|
<logger name="*" minlevel="Info" writeTo="logconsole" />
|
||||||
|
<logger name="*" minlevel="Trace" writeTo="logfile" />
|
||||||
|
</rules>
|
||||||
|
</nlog>
|
||||||
@ -1,28 +1,73 @@
|
|||||||
using System;
|
using Microsoft.EntityFrameworkCore;
|
||||||
|
using NLog;
|
||||||
|
using JetKarmaBot.Models;
|
||||||
|
|
||||||
namespace JetKarmaBot
|
namespace JetKarmaBot;
|
||||||
|
|
||||||
|
public static class Program
|
||||||
{
|
{
|
||||||
public class App
|
private static Logger log = LogManager.GetCurrentClassLogger();
|
||||||
|
public enum ExitCode : int
|
||||||
{
|
{
|
||||||
public static void Main(string[] args)
|
Ok = 0,
|
||||||
{
|
ErrorNotStarted = 0x80,
|
||||||
Current = new App(new Config("karma.cfg.json"));
|
ErrorRunning = 0x81,
|
||||||
|
ErrorException = 0x82,
|
||||||
|
ErrorInvalidCommandLine = 0x100
|
||||||
|
};
|
||||||
|
|
||||||
Console.ReadKey();
|
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)
|
||||||
|
{
|
||||||
|
dbOptions = dbOptions.UseLoggerFactory(c.GetInstance<NLoggerFactory>());
|
||||||
}
|
}
|
||||||
|
c.AddTransient(() => new KarmaContext(dbOptions.Options));
|
||||||
|
c.Add<JetKarmaBot>();
|
||||||
|
|
||||||
public static App Current { get; private set; }
|
var bot = c.GetInstance<JetKarmaBot>();
|
||||||
|
|
||||||
public App(Config cfg)
|
try
|
||||||
{
|
{
|
||||||
Config = cfg;
|
bot.Init().GetAwaiter().GetResult();
|
||||||
Db = new Db(Config);
|
log.Info("JetKarmaBot started. Press Ctrl-C to exit...");
|
||||||
Watcher = new JetKarmaBot(Config, Db);
|
|
||||||
Console.WriteLine("JetKarmaBot started!");
|
|
||||||
}
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
log.Error(ex);
|
||||||
|
return (int)ExitCode.ErrorException;
|
||||||
|
}
|
||||||
|
ManualResetEvent quitEvent = new ManualResetEvent(false);
|
||||||
|
try
|
||||||
|
{
|
||||||
|
Console.CancelKeyPress += (sender, eArgs) => // ctrl-c
|
||||||
|
{
|
||||||
|
eArgs.Cancel = true;
|
||||||
|
quitEvent.Set();
|
||||||
|
};
|
||||||
|
AppDomain.CurrentDomain.ProcessExit += (sender, args) =>
|
||||||
|
{
|
||||||
|
log.Info("Received stop request, waiting for exit...");
|
||||||
|
bot?.Stop()?.GetAwaiter().GetResult();
|
||||||
|
};
|
||||||
|
}
|
||||||
|
catch { }
|
||||||
|
|
||||||
Config Config { get; }
|
quitEvent.WaitOne(Timeout.Infinite);
|
||||||
Db Db { get; }
|
log.Info("Waiting for exit...");
|
||||||
JetKarmaBot Watcher { get; }
|
bot?.Stop()?.GetAwaiter().GetResult();
|
||||||
|
|
||||||
|
return (int)ExitCode.Ok;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,133 +0,0 @@
|
|||||||
using System;
|
|
||||||
using System.Collections.Generic;
|
|
||||||
using System.Data;
|
|
||||||
using System.Linq;
|
|
||||||
using Dapper;
|
|
||||||
using MySql.Data.MySqlClient;
|
|
||||||
|
|
||||||
namespace JetKarmaBot
|
|
||||||
{
|
|
||||||
public class Db
|
|
||||||
{
|
|
||||||
Dictionary<long, Chat> m_Chats;
|
|
||||||
public IReadOnlyDictionary<long, Chat> Chats => m_Chats;
|
|
||||||
public void AddChat(Chat chat)
|
|
||||||
{
|
|
||||||
lock (m_SyncRoot)
|
|
||||||
if (!m_Chats.ContainsKey(chat.ChatId))
|
|
||||||
{
|
|
||||||
Conn.Execute(@"INSERT INTO chat
|
|
||||||
(chatid)
|
|
||||||
VALUES
|
|
||||||
(@ChatId)",
|
|
||||||
chat);
|
|
||||||
m_Chats.Add(chat.ChatId, chat);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
Dictionary<long, User> m_Users;
|
|
||||||
public IReadOnlyDictionary<long, User> Users => m_Users;
|
|
||||||
public void AddUser(User user)
|
|
||||||
{
|
|
||||||
lock (m_SyncRoot)
|
|
||||||
if (!m_Users.ContainsKey(user.UserId))
|
|
||||||
{
|
|
||||||
Conn.Execute(@"INSERT INTO user
|
|
||||||
(userid)
|
|
||||||
VALUES
|
|
||||||
(@UserId)",
|
|
||||||
user);
|
|
||||||
m_Users.Add(user.UserId, user);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Dictionary<byte, AwardType> m_AwardTypes;
|
|
||||||
public byte DefaultAwardTypeId { get; } = 1;
|
|
||||||
public IReadOnlyDictionary<byte, AwardType> AwardTypes => m_AwardTypes;
|
|
||||||
public IReadOnlyDictionary<string, AwardType> AwardTypesByCommandName { get; private set; }
|
|
||||||
|
|
||||||
public int CountAwards(long userId, byte awardTypeId)
|
|
||||||
{
|
|
||||||
return Conn.QuerySingle<int?>
|
|
||||||
(
|
|
||||||
"SELECT SUM(amount) FROM award WHERE toid = @userId AND awardtypeid = @awardTypeId",
|
|
||||||
new { userId, awardTypeId }
|
|
||||||
) ?? 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
public byte GetAwardTypeId(string name)
|
|
||||||
=> AwardTypesByCommandName.GetOrDefault(name)?.AwardTypeId ?? DefaultAwardTypeId;
|
|
||||||
|
|
||||||
public bool AddAward(byte awardTypeId, long fromId, long toId, long chatId, int amount)
|
|
||||||
{
|
|
||||||
AddChat(new Chat() { ChatId = chatId });
|
|
||||||
AddUser(new User() { UserId = fromId});
|
|
||||||
AddUser(new User() { UserId = toId });
|
|
||||||
|
|
||||||
int affected = Conn.ExecuteScalar<int>(
|
|
||||||
@"INSERT INTO award
|
|
||||||
(chatid, fromid, toid, awardtypeid, amount)
|
|
||||||
VALUES
|
|
||||||
(@chatId, @fromId, @toId, @awardTypeId, @amount)",
|
|
||||||
new { awardTypeId, fromId, toId, chatId, amount });
|
|
||||||
return affected == 1;
|
|
||||||
}
|
|
||||||
|
|
||||||
#region types
|
|
||||||
public class Chat
|
|
||||||
{
|
|
||||||
public long ChatId { get; set; }
|
|
||||||
}
|
|
||||||
|
|
||||||
public class User
|
|
||||||
{
|
|
||||||
public long UserId { get; set; }
|
|
||||||
}
|
|
||||||
|
|
||||||
public class AwardType
|
|
||||||
{
|
|
||||||
public byte AwardTypeId { get; set; }
|
|
||||||
public string CommandName { get; set; }
|
|
||||||
public string Name { get; set; }
|
|
||||||
public string Symbol { get; set; }
|
|
||||||
public string Description { get; set; }
|
|
||||||
}
|
|
||||||
|
|
||||||
public class Award
|
|
||||||
{
|
|
||||||
public int AwardId { get; set; }
|
|
||||||
public byte AwardTypeId { get; set; }
|
|
||||||
public long FromId { get; set; }
|
|
||||||
public long ToId { get; set; }
|
|
||||||
public long ChatId { get; set; }
|
|
||||||
public byte Amount { get; set; }
|
|
||||||
}
|
|
||||||
|
|
||||||
#endregion
|
|
||||||
|
|
||||||
#region service
|
|
||||||
public Db(Config cfg)
|
|
||||||
{
|
|
||||||
Log("Initializing...");
|
|
||||||
Conn = new MySqlConnection(cfg.ConnectionString);
|
|
||||||
Conn.ExecuteScalar("select 1");
|
|
||||||
Load();
|
|
||||||
Log("Initialized!");
|
|
||||||
}
|
|
||||||
|
|
||||||
object m_SyncRoot = new object();
|
|
||||||
|
|
||||||
IDbConnection Conn { get; }
|
|
||||||
void Load()
|
|
||||||
{
|
|
||||||
Log("Populating cache...");
|
|
||||||
m_Chats = Conn.Query<Chat>("SELECT * FROM chat").ToDictionary(u => u.ChatId);
|
|
||||||
m_Users = Conn.Query<User>("SELECT * FROM user").ToDictionary(s => s.UserId);
|
|
||||||
m_AwardTypes = Conn.Query<AwardType>("SELECT * FROM awardtype").ToDictionary(c => c.AwardTypeId);
|
|
||||||
AwardTypesByCommandName = m_AwardTypes.Values.ToDictionary(kvp => kvp.CommandName);
|
|
||||||
Log("Cache populated!");
|
|
||||||
}
|
|
||||||
#endregion
|
|
||||||
|
|
||||||
void Log (string Message) => Console.WriteLine($"[{nameof(Db)}]: {Message}");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
105
JetKarmaBot/Services/Handling/CommandRouter.cs
Normal file
105
JetKarmaBot/Services/Handling/CommandRouter.cs
Normal 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>();
|
||||||
|
}
|
||||||
17
JetKarmaBot/Services/Handling/DatabaseHandler.cs
Normal file
17
JetKarmaBot/Services/Handling/DatabaseHandler.cs
Normal 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();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
37
JetKarmaBot/Services/Handling/RequestChain.cs
Normal file
37
JetKarmaBot/Services/Handling/RequestChain.cs
Normal 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);
|
||||||
|
}
|
||||||
|
}
|
||||||
32
JetKarmaBot/Services/Handling/RequestContext.cs
Normal file
32
JetKarmaBot/Services/Handling/RequestContext.cs
Normal 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 }
|
||||||
|
);
|
||||||
|
}
|
||||||
33
JetKarmaBot/Services/Handling/SaveData.cs
Normal file
33
JetKarmaBot/Services/Handling/SaveData.cs
Normal 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;
|
||||||
|
}
|
||||||
|
}
|
||||||
126
JetKarmaBot/Services/Handling/TimeoutManager.cs
Normal file
126
JetKarmaBot/Services/Handling/TimeoutManager.cs
Normal 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)) + ">" : "");
|
||||||
|
}
|
||||||
|
}
|
||||||
10
JetKarmaBot/Services/KarmaContextFactory.cs
Normal file
10
JetKarmaBot/Services/KarmaContextFactory.cs
Normal file
@ -0,0 +1,10 @@
|
|||||||
|
using JetKarmaBot.Models;
|
||||||
|
|
||||||
|
namespace JetKarmaBot.Services;
|
||||||
|
|
||||||
|
public class KarmaContextFactory
|
||||||
|
{
|
||||||
|
[Inject] IContainer C { get; set; }
|
||||||
|
|
||||||
|
public KarmaContext GetContext() => C.GetInstance<KarmaContext>();
|
||||||
|
}
|
||||||
166
JetKarmaBot/Services/Localization.cs
Normal file
166
JetKarmaBot/Services/Localization.cs
Normal file
@ -0,0 +1,166 @@
|
|||||||
|
using System.Collections;
|
||||||
|
using System.IO;
|
||||||
|
using System.Runtime.Serialization;
|
||||||
|
using Newtonsoft.Json.Linq;
|
||||||
|
using NLog;
|
||||||
|
|
||||||
|
namespace JetKarmaBot;
|
||||||
|
|
||||||
|
public class Localization : IReadOnlyDictionary<string, Locale>
|
||||||
|
{
|
||||||
|
private Dictionary<string, Locale> locales = new Dictionary<string, Locale>();
|
||||||
|
|
||||||
|
public Localization(IContainer c)
|
||||||
|
{
|
||||||
|
c.ResolveObject(this);
|
||||||
|
log.Info("Initializing...");
|
||||||
|
string langsFolder = "lang";
|
||||||
|
if (!Directory.Exists(langsFolder))
|
||||||
|
Directory.CreateDirectory(langsFolder);
|
||||||
|
|
||||||
|
foreach (string langFilePath in Directory.EnumerateFiles(langsFolder, "*.json"))
|
||||||
|
{
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (locales.Any())
|
||||||
|
log.Info("Initialized!");
|
||||||
|
else
|
||||||
|
throw new FileNotFoundException($"No locales found in {langsFolder}!");
|
||||||
|
}
|
||||||
|
|
||||||
|
public Locale this[string locale]
|
||||||
|
{
|
||||||
|
get
|
||||||
|
{
|
||||||
|
locale = locale.ToLowerInvariant();
|
||||||
|
return locales[locale];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[Inject]
|
||||||
|
private Logger log;
|
||||||
|
|
||||||
|
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.ContainsKey(locale);
|
||||||
|
}
|
||||||
|
|
||||||
|
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)
|
||||||
|
{
|
||||||
|
return locales.TryGetValue(key.ToLower(), out value);
|
||||||
|
}
|
||||||
|
|
||||||
|
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) { }
|
||||||
|
}
|
||||||
18
JetKarmaBot/Services/LogInfo.cs
Normal file
18
JetKarmaBot/Services/LogInfo.cs
Normal file
@ -0,0 +1,18 @@
|
|||||||
|
using NLog;
|
||||||
|
|
||||||
|
namespace JetKarmaBot;
|
||||||
|
|
||||||
|
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>");
|
||||||
|
}
|
||||||
|
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)) + ">" : "");
|
||||||
|
}
|
||||||
|
}
|
||||||
100
JetKarmaBot/Services/LoggerVirtualizer.cs
Normal file
100
JetKarmaBot/Services/LoggerVirtualizer.cs
Normal file
@ -0,0 +1,100 @@
|
|||||||
|
using Microsoft.Extensions.Logging;
|
||||||
|
using NLog;
|
||||||
|
|
||||||
|
namespace JetKarmaBot;
|
||||||
|
|
||||||
|
public class NLoggerFactory : ILoggerFactory
|
||||||
|
{
|
||||||
|
[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()
|
||||||
|
{
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
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)
|
||||||
|
{
|
||||||
|
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()
|
||||||
|
{
|
||||||
|
}
|
||||||
|
}
|
||||||
66
JetKarmaBot/lang/be-BY.json
Normal file
66
JetKarmaBot/lang/be-BY.json
Normal file
@ -0,0 +1,66 @@
|
|||||||
|
{
|
||||||
|
"names": [
|
||||||
|
"belarusian",
|
||||||
|
"белорусский",
|
||||||
|
"беларуская"
|
||||||
|
],
|
||||||
|
"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": "пілюлю"
|
||||||
|
}
|
||||||
|
}
|
||||||
65
JetKarmaBot/lang/en-US.json
Normal file
65
JetKarmaBot/lang/en-US.json
Normal file
@ -0,0 +1,65 @@
|
|||||||
|
{
|
||||||
|
"names": [
|
||||||
|
"english",
|
||||||
|
"английский",
|
||||||
|
"англійская"
|
||||||
|
],
|
||||||
|
"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.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.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.changelocale.justchanged": "Roger that.",
|
||||||
|
"jetkarmabot.changelocale.getlocale": "I'm currently speaking English.",
|
||||||
|
"jetkarmabot.changelocale.listalltext": "I know:",
|
||||||
|
"jetkarmabot.changelocale.errorall": "I would like to speak all languages at once, but because of the rules of the universe, I am not allowed to do that.",
|
||||||
|
"jetkarmabot.changelocale.beforenote": "Warning: ",
|
||||||
|
"jetkarmabot.changelocale.toomany": "I don't know what dialect you want me to speak in.\nI know these:",
|
||||||
|
"jetkarmabot.changelocale.help": "Switches current chat locale to [locale]",
|
||||||
|
"jetkarmabot.changelocale.localehelp": "The locale to switch to. Can be \"list\" to list all possible locales. Also can be empty to get current locale",
|
||||||
|
"jetkarmabot.help.help": "Displays help text for all(one) command(s)",
|
||||||
|
"jetkarmabot.help.commandhelp": "The command to return help text for. If empty shows all commands.",
|
||||||
|
"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"
|
||||||
|
}
|
||||||
|
}
|
||||||
65
JetKarmaBot/lang/ru-RU.json
Normal file
65
JetKarmaBot/lang/ru-RU.json
Normal file
@ -0,0 +1,65 @@
|
|||||||
|
{
|
||||||
|
"names": [
|
||||||
|
"russian",
|
||||||
|
"русский",
|
||||||
|
"руская"
|
||||||
|
],
|
||||||
|
"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": "РЕШИТЕЛЬНОСТЬ",
|
||||||
|
"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": "пилюлю"
|
||||||
|
}
|
||||||
|
}
|
||||||
41
karma.sql
Normal file
41
karma.sql
Normal 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
perfusion
Submodule
1
perfusion
Submodule
@ -0,0 +1 @@
|
|||||||
|
Subproject commit 115f59eecb2a4a74c63770866539502cde28d881
|
||||||
Loading…
Reference in New Issue
Block a user