Ejemplo n.º 1
0
        private async Task ApplyCost(string name, bool succeded, int 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;
        }
Ejemplo n.º 2
0
        public async Task Handle(RequestContext ctx, Func <RequestContext, Task> next)
        {
            int          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);
        }
Ejemplo n.º 3
0
        public async Task Init()
        {
            using (KarmaContext db = Db.GetContext())
                await db.Database.EnsureCreatedAsync();
            if (Config.Proxy?.Url == null)
            {
                Client = new TelegramBotClient(Config.ApiKey);
            }
            else
            {
                var httpProxy = new WebProxy($"{Config.Proxy.Url}:{Config.Proxy.Port}")
                {
                    Credentials = new NetworkCredential(Config.Proxy.Login, Config.Proxy.Password)
                };

                Client = new TelegramBotClient(Config.ApiKey, httpProxy);
            }
            Container.AddInstance(Client);

            timeoutWaitTaskToken = new CancellationTokenSource();
            timeoutWaitTask      = Timeout.SaveLoop(timeoutWaitTaskToken.Token);

            await InitCommands(Container);

            InitChain(Container);

            Client.OnMessage += BotOnMessageReceived;
            Client.StartReceiving();
        }
 public void Start()
 {
     Console.WriteLine("KarmaPlugin started");
     _context = new KarmaContext();
     _context.Database.Migrate();
     _karmaRepository  = new KarmaRepository(_context);
     _reasonRepository = new ReasonRepository(_context);
 }
 protected void InitContext()
 {
     if (string.IsNullOrEmpty(_databaseFilename))
     {
         _databaseFilename = Guid.NewGuid().ToString();
     }
     Context?.Dispose();
     Context = new KarmaContext(_databaseFilename);
     Context.Database.Migrate();
 }
Ejemplo n.º 6
0
 private async Task PopulateStats(int 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
         };
     }
 }
Ejemplo n.º 7
0
 public async Task Save(CancellationToken ct = default(CancellationToken))
 {
     log.Info("Saving timeout info to database");
     using (KarmaContext db = Db.GetContext())
     {
         foreach (int i in TimeoutCache.Keys)
         {
             (await db.Users.FindAsync(new object[] { i }, ct)).CooldownDate = TimeoutCache[i].CooldownDate;
         }
         await db.SaveChangesAsync(ct);
     }
     log.Info("Saved");
 }
Ejemplo n.º 8
0
        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);
        }
Ejemplo n.º 9
0
        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;
            }
        }