Ejemplo n.º 1
0
        public static void SetLink(Message msg, string[] args)
        {
            if (!String.IsNullOrEmpty(msg.Chat.Username))
            {
                msg.Reply(GetTranslation("SetLinkDone", GetLanguage(msg.Chat.Id), $"<a href='https://t.me/{msg.Chat.Username}'>{msg.Chat.Title.FormatHTML()}</a>"));
                return;
            }

            if (args.Length < 2 || String.IsNullOrEmpty(args[1]))
            {
                msg.Reply(GetTranslation("SetLinkNoLink", GetLanguage(msg.Chat.Id)));
                return;
            }

            var link = args[1].Trim();

            if (!Regex.IsMatch(link, @"^(https?:\/\/)?t(elegram)?\.me\/joinchat\/([a-zA-Z0-9_\-]+)$"))
            {
                msg.Reply(GetTranslation("SetLinkInvalidLink", GetLanguage(msg.Chat.Id)));
                return;
            }
            using (var db = new SixNimmtDb())
            {
                var grp = db.Groups.FirstOrDefault(x => x.GroupId == msg.Chat.Id) ?? MakeDefaultGroup(msg.Chat);
                grp.GroupLink = link;
                db.SaveChanges();
            }

            msg.Reply(GetTranslation("SetLinkDone", GetLanguage(msg.Chat.Id), $"<a href=\"{link}\">{msg.Chat.Title.FormatHTML()}</a>"));
        }
Ejemplo n.º 2
0
 public static Group GetGroup(long id)
 {
     using (var db = new SixNimmtDb())
     {
         return(db.Groups.FirstOrDefault(x => x.GroupId == id));
     }
 }
Ejemplo n.º 3
0
        public static void GroupListQuery(CallbackQuery query, string[] args)
        {
            var temp   = args[1].Split('|');
            var chatId = int.Parse(temp[0]);

            if (temp[1] == "done")
            {
                Bot.Edit(query.Message.Chat.Id, query.Message.MessageId, GetTranslation("ConfigDone", GetLanguage(chatId)));
            }
            else
            {
                var langChosen = temp[1];
                using (var db = new SixNimmtDb())
                {
                    try
                    {
                        var groups = db.Groups.Where(x => x.GroupLink != null && x.ShowOnGroupList == true && x.Language == langChosen).ToList().Shuffle().Take(10).ToList();

                        var msg = $"{GetTranslation("GroupListForLang", GetLanguage(chatId), Program.Langs[langChosen].LanguageName)}\n";
                        foreach (var grp in groups)
                        {
                            msg += $"<a href='{grp.GroupLink}'>{grp.Name.FormatHTML()}</a>\n";
                        }
                        Bot.Edit(query.Message.Chat.Id, query.Message.MessageId, msg);
                    }
                    catch (Exception e)
                    {
                        //
                    }
                }
            }
        }
Ejemplo n.º 4
0
 public static Player GetPlayer(long id)
 {
     using (var db = new SixNimmtDb())
     {
         return(db.Players.FirstOrDefault(x => x.TelegramId == id));
     }
 }
Ejemplo n.º 5
0
        public static void NextGame(Message msg, string[] args)
        {
            if (msg.Chat.Type == ChatType.Private)
            {
                return;
            }
            var grpId = msg.Chat.Id;

            using (var db = new SixNimmtDb())
            {
                var dbGrp = db.Groups.FirstOrDefault(x => x.GroupId == grpId);
                if (dbGrp != null)
                {
                    var notified = db.NotifyGames.FirstOrDefault(x => x.GroupId == grpId && x.UserId == msg.From.Id);
                    if (notified != null)
                    {
                        Bot.Send(msg.From.Id, GetTranslation("AlreadyInWaitingList", GetLanguage(msg.From.Id)));
                        return;
                    }
                    else
                    {
                    }
                    db.Database.ExecuteSqlCommand($"INSERT INTO NotifyGame VALUES ({msg.From.Id}, {msg.Chat.Id})");
                    db.SaveChanges();
                    Bot.Send(msg.From.Id, GetTranslation("NextGame", GetLanguage(msg.From.Id)));
                }
            }
        }
Ejemplo n.º 6
0
 public static void RemLink(Message msg, string[] args)
 {
     using (var db = new SixNimmtDb())
     {
         var grp = db.Groups.FirstOrDefault(x => x.GroupId == msg.Chat.Id) ?? MakeDefaultGroup(msg.Chat);
         grp.GroupLink = null;
         db.SaveChanges();
     }
     msg.Reply(GetTranslation("LinkRemoved", GetLanguage(msg.Chat.Id)));
 }
Ejemplo n.º 7
0
        public static void CheckGroupActivity(Message msg, string[] args)
        {
            var i = 7;

            if (args[1] != null)
            {
                int.TryParse(args[1].Split()[0], out i);
            }
            using (var db = new SixNimmtDb())
            {
                try
                {
                    var sql = $@"
    select top 10
	count(*) as [Num], [group].name as [Name]
	from game
	join [group] on game.grpid = [group].id
	where timeended is not null 
	and convert(date, timestarted) <> convert(date, getdate())
	and timeended > DATEADD(DAY, {-i}, getdate())
	group by [group].name
	order by count(*) desc"    ;
                    var res = db.Database.SqlQuery <GroupGameCountStat>(sql).ToList();
                    res.Reverse();
                    var ds = new DataSet();
                    var dt = new DataTable();
                    dt.Columns.Add("Num", typeof(int));
                    dt.Columns.Add("Name", typeof(string));


                    foreach (var r in res)
                    {
                        var row = dt.NewRow();
                        row[0] = r.Num;
                        row[1] = r.Name;
                        dt.Rows.Add(row);
                    }
                    ds.Tables.Add(dt);
                    var chart = CreateChart(ds, $"Group Activity for past {i} days", "Name", "Num", SeriesChartType.Bar, 800, 500);
                    using (MemoryStream ms = new MemoryStream())
                    {
                        chart.SaveImage(ms, ChartImageFormat.Png);
                        ms.Seek(0, SeekOrigin.Begin);
                        var image = new FileToSend("growth", ms);
                        Bot.Api.SendPhotoAsync(msg.Chat.Id, image, replyToMessageId: msg.MessageId).Wait();
                    }
                }
                catch (Exception e)
                {
                    //
                }
                //
            }
        }
Ejemplo n.º 8
0
        public static void CheckGrowth(Message msg, string[] args)
        {
            var i = 7;

            if (args[1] != null)
            {
                int.TryParse(args[1].Split()[0], out i);
            }
            using (var db = new SixNimmtDb())
            {
                try
                {
                    var sql = $@"
    select top {i} 
	CONVERT(date, timestarted) as [GameDate], 
	count(*) as [Num]
	from game
	where timeended is not null 
	and convert(date, timestarted) <> convert(date, getdate())
	group by CONVERT(date, timestarted) 
	order by CONVERT(date, timestarted) desc"    ;
                    var res = db.Database.SqlQuery <GameCountStat>(sql).ToList();
                    res.Reverse();
                    var ds = new DataSet();
                    var dt = new DataTable();
                    dt.Columns.Add("GameDate", typeof(string));
                    dt.Columns.Add("Num", typeof(int));

                    foreach (var r in res)
                    {
                        var row = dt.NewRow();
                        row[0] = r.GameDate.ToShortDateString();
                        row[1] = r.Num;
                        dt.Rows.Add(row);
                    }
                    ds.Tables.Add(dt);
                    var chart = CreateChart(ds, $"Game Count for past {i} days", "GameDate", "Num", SeriesChartType.Spline, 400, 250);
                    using (MemoryStream ms = new MemoryStream())
                    {
                        chart.SaveImage(ms, ChartImageFormat.Png);
                        ms.Seek(0, SeekOrigin.Begin);
                        var image = new FileToSend("growth", ms);
                        Bot.Api.SendPhotoAsync(msg.Chat.Id, image, replyToMessageId: msg.MessageId).Wait();
                    }
                }
                catch (Exception e)
                {
                    //
                }
                //
            }
        }
Ejemplo n.º 9
0
 public static void SetLanguage(int userId, string lang)
 {
     using (var db = new SixNimmtDb())
     {
         var user = db.Players.FirstOrDefault(x => x.TelegramId == userId);
         if (user == null)
         {
             return;
         }
         user.Language = lang;
         db.SaveChanges();
     }
 }
Ejemplo n.º 10
0
 public static void SetTableConfig(int userId, bool config)
 {
     using (var db = new SixNimmtDb())
     {
         var user = db.Players.FirstOrDefault(x => x.TelegramId == userId);
         if (user == null)
         {
             return;
         }
         user.UseSticker = config;
         db.SaveChanges();
     }
 }
Ejemplo n.º 11
0
 public static void SetCardDeckConfig(long chatId, bool useDynamic)
 {
     using (var db = new SixNimmtDb())
     {
         var grp = db.Groups.FirstOrDefault(x => x.GroupId == chatId);
         if (grp == null)
         {
             return;
         }
         grp.DynamicDeck = useDynamic;
         db.SaveChanges();
     }
 }
Ejemplo n.º 12
0
 public static void SetGroupListConfig(long chatId, bool show)
 {
     using (var db = new SixNimmtDb())
     {
         var grp = db.Groups.FirstOrDefault(x => x.GroupId == chatId);
         if (grp == null)
         {
             return;
         }
         grp.ShowOnGroupList = show;
         db.SaveChanges();
     }
 }
Ejemplo n.º 13
0
 public static void SetChooseCardTimeConfig(long chatId, int chooseCardTime)
 {
     using (var db = new SixNimmtDb())
     {
         var grp = db.Groups.FirstOrDefault(x => x.GroupId == chatId);
         if (grp == null)
         {
             return;
         }
         grp.ChooseCardTime = chooseCardTime;
         db.SaveChanges();
     }
 }
Ejemplo n.º 14
0
 public static void Achievements(Message msg, string[] args)
 {
     using (var db = new SixNimmtDb())
     {
         var p        = db.Players.FirstOrDefault(x => x.TelegramId == msg.From.Id);
         var temp     = p.Achievements ?? 0;
         var achv     = (Achievements)temp;
         var lang     = GetLanguage(msg.From.Id);
         var achvList = achv.GetUniqueFlags().ToList();
         var msg1     = $"{GetTranslation("AchievementsGot", lang, achvList.Count)}\n\n";
         msg1 = achvList.Aggregate(msg1, (current, a) => current + $"{a.GetAchvName(lang).ToBold()}\n{a.GetAchvDescription(lang)}\n\n");
         var noAchvList = achv.GetUniqueFlags(true).ToList();
         var msg2       = $"{GetTranslation("AchievementsLack", lang, noAchvList.Count)}\n\n";
         msg2 = noAchvList.Aggregate(msg2, (current, a) => current + $"{a.GetAchvName(lang).ToBold()}\n{a.GetAchvDescription(lang)}\n\n");
         msg.ReplyPM(new[] { msg1, msg2 });
     }
 }
Ejemplo n.º 15
0
 public static void SetLanguage(long chatId, string lang)
 {
     if (int.TryParse(chatId.ToString(), out int o))
     {
         SetLanguage(o, lang);
         return;
     }
     using (var db = new SixNimmtDb())
     {
         var grp = db.Groups.FirstOrDefault(x => x.GroupId == chatId);
         if (grp == null)
         {
             return;
         }
         grp.Language = lang;
         db.SaveChanges();
     }
 }
Ejemplo n.º 16
0
 public static void SetTableConfig(long chatId, bool config)
 {
     if (int.TryParse(chatId.ToString(), out int o))
     {
         SetTableConfig(o, config);
         return;
     }
     using (var db = new SixNimmtDb())
     {
         var grp = db.Groups.FirstOrDefault(x => x.GroupId == chatId);
         if (grp == null)
         {
             return;
         }
         grp.UseSticker = config;
         db.SaveChanges();
     }
 }
Ejemplo n.º 17
0
 public static string GetLanguage(long id)
 {
     using (var db = new SixNimmtDb())
     {
         Player p   = null;
         var    grp = db.Groups.FirstOrDefault(x => x.GroupId == id);
         if (grp == null)
         {
             p = db.Players.FirstOrDefault(x => x.TelegramId == id);
         }
         if (p != null && String.IsNullOrEmpty(p.Language))
         {
             p.Language = "English";
             db.SaveChanges();
         }
         return(grp?.Language ?? p?.Language ?? "English");
     }
 }
Ejemplo n.º 18
0
        public static InlineKeyboardMarkup GetConfigTableMenu(long id)
        {
            List <InlineKeyboardButton> buttons = new List <InlineKeyboardButton>();

            using (var db = new SixNimmtDb())
            {
                bool?currentSetting = null;
                var  gp             = db.Groups.FirstOrDefault(x => x.GroupId == id);
                if (gp != null)
                {
                    currentSetting = gp?.UseSticker;
                }
                else
                {
                    var p = db.Players.FirstOrDefault(x => x.TelegramId == id);
                    if (p != null)
                    {
                        currentSetting = p?.UseSticker;
                    }
                }

                foreach (var i in new string[] { GetTranslation("ChooseUseText", GetLanguage(id)), GetTranslation("ChooseUseSticker", GetLanguage(id)) })
                {
                    buttons.Add(new InlineKeyboardCallbackButton(i, currentSetting != true ? $"config|table|{id}|sticker" : $"config|table|{id}|text"));
                }
                var twoMenu = new List <InlineKeyboardButton[]>();
                for (var i = 0; i < buttons.Count; i++)
                {
                    if (buttons.Count - 1 == i)
                    {
                        twoMenu.Add(new[] { buttons[i] });
                    }
                    else
                    {
                        twoMenu.Add(new[] { buttons[i], buttons[i + 1] });
                    }
                    i++;
                }
                twoMenu.Add(new[] { new InlineKeyboardCallbackButton(GetTranslation("ConfigBack", GetLanguage(id)), $"config|back|{id}") });

                var menu = new InlineKeyboardMarkup(twoMenu.ToArray());
                return(menu);
            }
        }
Ejemplo n.º 19
0
        public static void GroupStats(Message msg, string[] args)
        {
            var chatId = msg.Chat.Id;

            using (var db = new SixNimmtDb())
            {
                var numOfGames = db.GetGroupNumOfGames(chatId).First().Value;
                var numOfBulls = db.GetGroupNumOfBulls(chatId).First().Value;

                var playerAverageBulls = db.GetGroupAverageNumOfBulls(chatId).ToList();
                var playerBullsText    = "";
                var i    = 1;
                var temp = playerAverageBulls.ToList();
                temp.Reverse();
                temp = temp.Take(3).ToList();
                foreach (var res in temp)
                {
                    var name = res.Username == null?res.Name.ToBold() : $"<a href='https://t.me/{res.Username}'>{res.Name}</a>";

                    var bulls = (decimal)res.average;
                    playerBullsText += $"{i}. {GetTranslation("GroupStatsPlayerBulls", GetLanguage(chatId), bulls.ToString("F").ToBold(), name)}\n";
                    i++;
                }
                var playerBullsText2 = "";
                i = 1;
                foreach (var res in playerAverageBulls.Take(3).ToList())
                {
                    var name = res.Username == null?res.Name.ToBold() : $"<a href='https://t.me/{res.Username}'>{res.Name}</a>";

                    var bulls = (decimal)res.average;
                    playerBullsText2 += $"{i}. {GetTranslation("GroupStatsPlayerBulls", GetLanguage(chatId), bulls.ToString("F").ToBold(), name)}\n";
                    i++;
                }

                var send = GetTranslation("GroupStatsDetails", GetLanguage(msg.Chat.Id),
                                          msg.Chat.Title.FormatHTML().ToBold(),
                                          numOfGames.ToBold(),
                                          numOfBulls.ToBold(),
                                          playerBullsText,
                                          playerBullsText2
                                          );
                msg.Reply(send);
            }
        }
Ejemplo n.º 20
0
        public static void Stats(Message msg, string[] args)
        {
            using (var db = new SixNimmtDb())
            {
                var isGroup   = !(msg.Chat.Type == ChatType.Private);
                var player    = msg.ReplyToMessage?.From ?? msg.From;
                var playerId  = player.Id;
                var temp      = db.Players.FirstOrDefault(x => x.TelegramId == playerId).Achievements ?? 0;
                var achv      = (Achievements)temp;
                var achvCount = achv.GetUniqueFlags().Count();
                if (!db.GamePlayers.Any(x => x.Player.TelegramId == playerId))
                {
                    msg.Reply(GetTranslation("StatsHaveNotPlayed", GetLanguage(playerId)));
                    return;
                }
                var playerName = $"{player.GetName()} (<code>{playerId}</code>)";
                int numOfWins  = db.GetNumOfWins(playerId).First().Value;
                int numOfLoss  = db.GetNumOfLoss(playerId).First().Value;
                var numOfGames = db.GetPlayerNumOfGames(playerId).First().Value;
                var numOfBulls = db.GetPlayerNumOfBulls(playerId).First().Value;

                double avg  = (double)numOfBulls / numOfGames;
                var    send = GetTranslation("StatsDetails", GetLanguage(isGroup == true ? msg.Chat.Id : playerId),
                                             playerName,
                                             achvCount.ToBold(),
                                             numOfGames.ToBold(),

                                             /* $"{numOfWins} ({Math.Round((double)numOfWins * 100 / numOfGames, 0)}%)".ToBold(),
                                              * $"{numOfGames - numOfWins} ({Math.Round((double)(numOfGames - numOfWins) * 100 / numOfGames, 0)}%)".ToBold(),
                                              * numOfBulls.ToBold(),
                                              * avg.ToString("F").ToBold()
                                              */
                                             // number of wins
                                             numOfWins.ToBold(),
                                             numOfLoss.ToBold(),
                                             numOfBulls.ToBold(),
                                             avg.ToString("F").ToBold()
                                             );
                msg.Reply(send);
            }
        }
Ejemplo n.º 21
0
        public static void GlobalStats(Message msg, string[] args)
        {
            using (var db = new SixNimmtDb())
            {
                int numOfGroups  = db.GetTotalNumOfGroups().First().Value;
                int numOfPlayers = db.GetTotalNumOfPlayers().First().Value;

                int numOfGames = db.GetTotalNumOfGames().First().Value;
                var numOfBulls = db.GetTotalNumOfBulls().First().Value;
                var average    = db.GetAverageNumOfBulls().First().Value;

                var send = GetTranslation("GlobalStatsDetails", GetLanguage(msg.Chat.Id),
                                          numOfGroups.ToBold(),
                                          numOfPlayers.ToBold(),
                                          numOfGames.ToBold(),
                                          numOfBulls.ToBold(),
                                          average.ToString("F").ToBold()
                                          );
                msg.Reply(send);
            }
        }
Ejemplo n.º 22
0
        public static void Config(Message msg, string[] args)
        {
            var id = msg.Chat.Id;

            //make sure the group is in the database
            using (var db = new SixNimmtDb())
            {
                switch (msg.Chat.Type)
                {
                case ChatType.Group:
                case ChatType.Supergroup:
                    var grp = db.Groups.FirstOrDefault(x => x.GroupId == id);
                    if (grp == null)
                    {
                        grp = Helpers.MakeDefaultGroup(msg.Chat);
                        db.Groups.Add(grp);
                    }
                    grp.UserName = msg.Chat.Username;
                    grp.Name     = msg.Chat.Title;
                    break;

                case ChatType.Private:
                    var p = db.Players.FirstOrDefault(x => x.TelegramId == id);
                    if (p == null)
                    {
                        p = Helpers.MakeDefaultPlayer(msg.From);
                        db.Players.Add(p);
                    }
                    p.UserName = msg.From.Username;
                    p.Name     = msg.From.FirstName;
                    break;
                }
                db.SaveChanges();
            }

            var menu = Handler.GetConfigMenu(msg.Chat.Id);

            Bot.Send(msg.From.Id, GetTranslation("WhatToDo", GetLanguage(msg.Chat.Id)), replyMarkup: menu);
        }
Ejemplo n.º 23
0
        public static void SetLang(Message msg, string[] args)
        {
            var id = msg.From.Id;

            //make sure the user is in the database
            using (var db = new SixNimmtDb())
            {
                var user = db.Players.FirstOrDefault(x => x.TelegramId == id);
                if (user == null)
                {
                    user = Helpers.MakeDefaultPlayer(msg.From);
                    db.Players.Add(user);
                }

                user.UserName = msg.From.Username;
                user.Name     = msg.From.FirstName;
                db.SaveChanges();
            }

            var menu = Handler.GetConfigLangMenu(msg.From.Id, true);

            Bot.Send(msg.From.Id, GetTranslation("ChoosePMLanguage", GetLanguage(msg.From.Id)), replyMarkup: menu);
        }
Ejemplo n.º 24
0
        public static void ChangeGroupLang(Message msg, string[] args)
        {
            if (args == null)
            {
                return;
            }
            var lang = args[1];

            try
            {
                using (var db = new SixNimmtDb())
                {
                    var p = db.Groups.FirstOrDefault(x => x.GroupId == msg.Chat.Id);
                    if (p != null)
                    {
                        p.Language = lang;
                        db.SaveChanges();
                        Bot.Send(msg.Chat.Id, "OK");
                    }
                }
            }
            catch { }
        }
Ejemplo n.º 25
0
        public static void Sql(Message msg, string[] args)
        {
            if (args[1] == null)
            {
                msg.Reply("You must enter a sql query.");
                return;
            }
            using (var db = new SixNimmtDb())
            {
                var conn = db.Database.Connection;
                if (conn.State != ConnectionState.Open)
                {
                    conn.Open();
                }
                string raw = "";

                var queries = args[1].Split(';');
                foreach (var sql in queries)
                {
                    try
                    {
                        using (var comm = conn.CreateCommand())
                        {
                            comm.CommandText = sql;
                            if (string.IsNullOrEmpty(sql))
                            {
                                continue;
                            }
                            var reader = comm.ExecuteReader();
                            var result = "";
                            if (reader.HasRows)
                            {
                                for (int i = 0; i < reader.FieldCount; i++)
                                {
                                    raw += $"<code>{reader.GetName(i).FormatHTML()}</code>" + (i == reader.FieldCount - 1 ? "" : " - ");
                                }
                                result += raw + Environment.NewLine;
                                raw     = "";
                                while (reader.Read())
                                {
                                    for (int i = 0; i < reader.FieldCount; i++)
                                    {
                                        raw += (reader.IsDBNull(i) ? "<i>NULL</i>" : $"<code>{reader[i].ToString().FormatHTML()}</code>") + (i == reader.FieldCount - 1 ? "" : " - ");
                                    }
                                    result += raw + Environment.NewLine;
                                    raw     = "";
                                }
                            }

                            result += reader.RecordsAffected == -1 ? "" : (reader.RecordsAffected + " records affected");
                            result  = !String.IsNullOrEmpty(result) ? result : (sql.ToLower().StartsWith("select") ? "Nothing found" : "Done.");
                            msg.Reply(result);
                        }
                    }
                    catch (Exception e)
                    {
                        msg.Reply($"<b>SQL Exception</b>:\n{e.Message}");
                    }
                }
            }
        }
Ejemplo n.º 26
0
        public static void AddAchv(Message msg, string[] args)
        {
            //get the user to add the achievement to
            //first, try by reply
            var id       = 0;
            var achIndex = 0;
            var param    = args[1].Split(' ');

            if (msg.ReplyToMessage != null)
            {
                var m = msg.ReplyToMessage;
                while (m.ReplyToMessage != null)
                {
                    m = m.ReplyToMessage;
                }
                //check for forwarded message

                id = m.From.Id;
                if (m.ForwardFrom != null)
                {
                    id = m.ForwardFrom.Id;
                }
            }
            else
            {
                //ok, check for a user mention
                var e = msg.Entities?.FirstOrDefault();
                if (e != null)
                {
                    switch (e.Type)
                    {
                    case MessageEntityType.Mention:
                        //get user
                        var username = msg.Text.Substring(e.Offset + 1, e.Length - 1);
                        using (var db = new SixNimmtDb())
                        {
                            id = db.Players.FirstOrDefault(x => x.UserName == username)?.TelegramId ?? 0;
                        }
                        break;

                    case MessageEntityType.TextMention:
                        id = e.User.Id;
                        break;
                    }
                    achIndex = 1;
                }
            }

            if (id == 0)
            {
                //check for arguments then
                if (int.TryParse(param[0], out id))
                {
                    achIndex = 1;
                }
                else if (int.TryParse(param[1], out id))
                {
                    achIndex = 0;
                }
            }


            if (id != 0)
            {
                //try to get the achievement
                if (Enum.TryParse(param[achIndex], out Achievements a))
                {
                    //get the player from database
                    using (var db = new SixNimmtDb())
                    {
                        var p = db.Players.FirstOrDefault(x => x.TelegramId == id);
                        if (p != null)
                        {
                            if (p.Achievements == null)
                            {
                                p.Achievements = 0;
                            }
                            var ach = (Achievements)p.Achievements;
                            if (ach.HasFlag(a))
                            {
                                msg.Reply("This player already have this achivement!");
                                return; //no point making another db call if they already have it
                            }
                            ach            = ach | a;
                            p.Achievements = (long)ach;
                            db.SaveChanges();
                            var achvMsg = GetTranslation("NewUnlocks", GetLanguage(p.TelegramId)).ToBold() + Environment.NewLine + Environment.NewLine;
                            achvMsg += $"{a.GetAchvName(GetLanguage(p.TelegramId)).ToBold()}\n{a.GetAchvDescription(GetLanguage(p.TelegramId))}";
                            Bot.Send(p.TelegramId, achvMsg);
                            msg.Reply($"Achievement {a} unlocked for {p.Name}");
                        }
                    }
                }
            }
            else
            {
                msg.Reply("Please reply to a (forwarded) message of the player, or provide the ID/Username/Mention.");
            }
        }
Ejemplo n.º 27
0
        public static void HandleMessage(Message msg)
        {
            if (msg.Date.ToUniversalTime() < Program.Startup.ToUniversalTime())
            {
                return;
            }
            switch (msg.Type)
            {
            case MessageType.TextMessage:
                string   text = msg.Text;
                string[] args = text.Contains(' ')
                                    ? new[] { text.Split(' ')[0].ToLower(), text.Remove(0, text.IndexOf(' ') + 1) }
                                    : new[] { text.ToLower(), null };
                if (args[0].EndsWith('@' + Bot.Me.Username.ToLower()))
                {
                    args[0] = args[0].Remove(args[0].Length - Bot.Me.Username.Length - 1);
                }
                if (msg.Text.StartsWith("/"))
                {
                    args[0] = args[0].Substring(1);
                    var cmd = Bot.Commands.FirstOrDefault(x => x.Trigger == args[0]);
                    if (cmd != null)
                    {
                        if (new[] { ChatType.Supergroup, ChatType.Group }.Contains(msg.Chat.Type))
                        {
                            using (var db = new SixNimmtDb())
                            {
                                var DbGroup = db.Groups.FirstOrDefault(x => x.GroupId == msg.Chat.Id);
                                if (DbGroup == null)
                                {
                                    DbGroup = Helpers.MakeDefaultGroup(msg.Chat);
                                    db.Groups.Add(DbGroup);
                                    db.SaveChanges();
                                }
                            }
                        }
                        if (cmd.GroupOnly && !new[] { ChatType.Supergroup, ChatType.Group }.Contains(msg.Chat.Type))
                        {
                            msg.Reply("This command can only be used in groups!");
                            return;
                        }

                        if (cmd.AdminOnly && new[] { ChatType.Supergroup, ChatType.Group }.Contains(msg.Chat.Type) && !Helpers.IsGroupAdmin(msg))
                        {
                            msg.Reply("You aren't a group admin!");
                            return;
                        }

                        if (cmd.DevOnly && !Constants.Dev.Contains(msg.From.Id))
                        {
                            msg.Reply("You aren't a bot dev!");
                            return;
                        }

                        cmd.Method.Invoke(msg, args);
                        return;
                    }
                }
                break;

            case MessageType.ServiceMessage:
                bool me = false;
                if (msg.NewChatMembers.Any())
                {
                    foreach (var c in msg.NewChatMembers)
                    {
                        if (c.Id == Bot.Me.Id)
                        {
                            me = true;
                        }
                    }
                }
                if (msg.NewChatMember != null && msg.NewChatMember.Id == Bot.Me.Id)
                {
                    me = true;
                }

                if (me)
                {
                    msg.ReplyNoQuote("Thank you for adding me into this chat! [6 Nimmt!] is a board game orininated in Germany, it's meaning is [Take 6!]. " +
                                     "It is a easy game to be played by 3 - 10 players. Admins can use /config to do simple configurations. Press /startgame to start a new game now!");
                }
                break;

                /*
                 * case MessageType.SuccessfulPayment:
                 * var randomRef = Guid.NewGuid().ToString();
                 * randomRef = $"#crim_{randomRef.Substring(randomRef.Length - 12)}";
                 * using (var db = new SixNimmtDb())
                 * {
                 *  var donate = new Donation
                 *  {
                 *      TelegramId = msg.From.Id,
                 *      Amount = msg.SuccessfulPayment.TotalAmount / 100,
                 *      Reference = randomRef,
                 *      DonationTime = DateTime.UtcNow
                 *  };
                 *  db.Donations.Add(donate);
                 *  db.SaveChanges();
                 * }
                 * // notify user successful donation, provide reference code for checking in case
                 * msg.Reply(GetTranslation("DonateSuccessful", GetLanguage(msg.From.Id), randomRef));
                 * // log who, how much, when and ref code to log group
                 * Bot.Send(Constants.LogGroupId, $"Donation from user <a href='tg://user?id={msg.From.Id}'>{msg.From.FirstName.FormatHTML()}</a>.\nAmount: {msg.SuccessfulPayment.TotalAmount / 100} HKD\nReference: {randomRef}");
                 * break;
                 */
            }
        }