Esempio n. 1
0
        private static void OnUpdate(object sender, UpdateEventArgs e)
        {
            try
            {
                #region Messages
                if (e.Update.Type == UpdateType.MessageUpdate)
                {
                    #region Text Messages
                    if (!string.IsNullOrEmpty(e.Update.Message.Text))
                    {
                        #region Allowed chat?
                        if (e.Update.Message.Chat.Type != ChatType.Private && !allowedgroups.Contains(e.Update.Message.Chat.Id))
                        {
                            Methods.ReplyToMessage("<b>Hey there!</b>\n\nYou just sent me a message in your group. Sorry, but I am only to be used in my own group: @WWAchievement. If you want to use me, come there, we are glad about every single new member! :D\n\n<b>Good bye.</b>", e.Update);
                            client.LeaveChatAsync(e.Update.Message.Chat.Id).Wait();
                            Methods.SendMessage(e.Update.Message.From.FirstName + " (" + e.Update.Message.From.Id + ", @" + e.Update.Message.From.Username + ") just sent a message to me in the group " + e.Update.Message.Chat.Title + " (" + e.Update.Message.Chat.Id + ", @" + e.Update.Message.Chat.Username + "), which I left because it is not an allowed group.", testgroup);
                            return;
                        }
                        #endregion

                        #region Are we handling this message?
                        if (e.Update.Message.Chat.Type == ChatType.Channel)
                        {
                            return;
                        }
                        if (maintenance && e.Update.Message.Chat.Id != testgroup && !adminIds.Contains(e.Update.Message.From.Id) && !Game.Games.ContainsKey(e.Update.Message.Chat.Id))
                        {
                            return;
                        }
                        if (e.Update.Message.Date.ToUniversalTime() < startup.Date.ToUniversalTime())
                        {
                            return;
                        }
                        #endregion

                        #region Game cleaner time update?
                        if (Game.Games.ContainsKey(e.Update.Message.Chat.Id))
                        {
                            Game.Games[e.Update.Message.Chat.Id].Updatetime = DateTime.UtcNow;
                            Game.Games[e.Update.Message.Chat.Id].Notified   = false;
                        }
                        #endregion

                        var text = e.Update.Message.Text;

                        var args    = text.Contains(" ") ? new[] { text.Split(' ')[0], text.Remove(0, text.IndexOf(' ') + 1) } : new[] { text, null };
                        var command = args[0].ToLower().Replace('!', '/').Replace('@' + Bot.Username, "").Replace("@werewolfbot", "");

                        #region Commands
                        if (commands.ContainsKey(command))
                        {
                            commands[command].Invoke(null, new object[] { e.Update, args });
                        }
                        else if (admincommands.ContainsKey(command))
                        {
                            if (adminIds.Contains(e.Update.Message.From.Id))
                            {
                                admincommands[command].Invoke(null, new object[] { e.Update, args });
                            }
                            else
                            {
                                Methods.ReplyToMessage("This command is only for bot admins! You aren't a bot admin!", e.Update);
                            }
                        }
                        else if (devcommands.ContainsKey(command))
                        {
                            if (devs.Contains(e.Update.Message.From.Id))
                            {
                                devcommands[command].Invoke(null, new object[] { e.Update, args });
                            }
                            else
                            {
                                Methods.ReplyToMessage("This command is only for Ludwig! You aren't Ludwig!", e.Update);
                            }
                        }
                        #endregion

                        #region Assign Roles
                        else if (Game.roleAliases.ContainsKey(args[0].ToLower()) && args[0].ToLower() != "unknown")
                        {
                            Commands.AssignRole(e.Update, args, false);
                        }
                        else if (args[0].ToLower() == "now" && !string.IsNullOrEmpty(args[1]) && Game.roleAliases.ContainsKey(args[1].Split(' ')[0].ToLower()) && args[1].Split(' ')[0].ToLower() != "unknown")
                        {
                            args[0] = args[1].Split(' ')[0];
                            args[1] = args[1].Contains(' ') ? args[1].Remove(0, args[1].IndexOf(' ') + 1) : null;
                            Commands.AssignRole(e.Update, args, true);
                        }
                        #endregion

                        #region Set playerlist by forwarding #players
                        else if (args[0] == "#players:" && e.Update.Message.Entities.Count >= 2 && e.Update.Message.ForwardFrom != null && e.Update.Message.ForwardFrom.Id == wwbots[0])
                        {
                            if (e.Update.Message.Chat.Type != ChatType.Supergroup)
                            {
                                return;
                            }
                            if (Game.Games.ContainsKey(e.Update.Message.Chat.Id))
                            {
                                if (Game.Games[e.Update.Message.Chat.Id].Gamestate == Game.State.Joining)
                                {
                                    string failed = Game.Games[e.Update.Message.Chat.Id].SetPlayersByPlayerlist(e.Update.Message.Entities.Where(x => x.Type == MessageEntityType.TextMention).ToList());
                                    Methods.ReplyToMessage("Successfully set the players to:\n" + string.Join("", Game.Games[e.Update.Message.Chat.Id].players.Select(x => "\n" + x.Value.Name)) + (string.IsNullOrEmpty(failed) ? "" : "\n\n<b>Failed for:</b>\n" + failed), e.Update);
                                }
                                else
                                {
                                    Methods.ReplyToMessage("You can't set the players this way after the game started! You have to use /addplayer or /dead manually for corrections!", e.Update);
                                }
                            }
                            else
                            {
                                Methods.ReplyToMessage("It seems there was no game started in here, you can start one using /startgame@werewolfbot!", e.Update);
                            }
                        }
                        #endregion

                        #region Achv Thumb Up
                        else if (e.Update.Message.ForwardFrom != null && wwbots.Contains(e.Update.Message.ForwardFrom.Id) && (text.ToLower().Contains("new unlock") || text.ToLower().Contains("achievement unlock") || text.ToLower().Contains("new achievement")))
                        {
                            Methods.ReplyToMessage("👍🏻", e.Update);
                        }
                        #endregion
                    }
                    #endregion

                    #region NewChatMember
                    else if (e.Update.Message.NewChatMembers != null)
                    {
                        foreach (var ncm in e.Update.Message.NewChatMembers)
                        {
                            if (ncm.Id == Bot.Id)
                            {
                                if (!allowedgroups.Contains(e.Update.Message.Chat.Id))
                                {
                                    Methods.ReplyToMessage("<b>Hey there!</b>\n\nYou just added me to your group. Sorry, but I am only to be used in my own group: @WWAchievement. If you want to use me, come there, we are glad about every single new member! :D\n\n<b>Good bye.</b>", e.Update);
                                    client.LeaveChatAsync(e.Update.Message.Chat.Id).Wait();
                                    Methods.SendMessage(e.Update.Message.From.FirstName + " (" + e.Update.Message.From.Id + ", @" + e.Update.Message.From.Username + ") just added me to the group " + e.Update.Message.Chat.Title + " (" + e.Update.Message.Chat.Id + ", @" + e.Update.Message.Chat.Username + "), which I left because it is not an allowed group.", testgroup);
                                }
                            }
                            else
                            {
                                var name     = ncm.FirstName + (string.IsNullOrEmpty(ncm.LastName) ? "" : " " + ncm.LastName);
                                var username = string.IsNullOrEmpty(ncm.Username) ? "(no username)" : ncm.Username.ToLower();
                                var achv     = JsonConvert.DeserializeObject <List <WWAchievements> >(Methods.GetAchievements(ncm.Id)).Select(x => x.Name).Select(x => Game.achv.First(y => y.Value == x).Key).ToList() ?? new List <Game.Achievements>();

                                if (!BotUser.users.ContainsKey(ncm.Id))
                                {
                                    var bu = new BotUser(ncm.Id, Methods.FormatHTML(name), username, 0, false, string.Join("|", achv.Select(x => Game.achv[x])));
                                    BotUser.users.Add(ncm.Id, bu);
                                    Methods.SQL.ModifyUser("add", bu);
                                }
                                else if (BotUser.users[ncm.Id].Name != name || BotUser.users[ncm.Id].Username.ToLower() != username)
                                {
                                    BotUser.users[ncm.Id].Name         = Methods.FormatHTML(name);
                                    BotUser.users[ncm.Id].Username     = username;
                                    BotUser.users[ncm.Id].Achievements = achv;
                                    Methods.SQL.ModifyUser("modify", BotUser.users[ncm.Id]);
                                }
                            }
                        }
                    }
                    #endregion
                }
                #endregion

                #region Callback queries
                else if (e.Update.Type == UpdateType.CallbackQueryUpdate)
                {
                    if (e.Update.CallbackQuery.Message.Date.ToUniversalTime() >= startup.Date.ToUniversalTime())
                    {
                        var text = e.Update.CallbackQuery.Data;

                        var args = new[] { text.Split('|')[0], text.Remove(0, text.IndexOf('|') + 1) };
                        if (maintenance && e.Update.CallbackQuery.Message.Chat.Id != testgroup && !adminIds.Contains(e.Update.CallbackQuery.From.Id))
                        {
                            return;
                        }

                        if (callbacks.ContainsKey(args[0]))
                        {
                            callbacks[args[0]].Invoke(null, new object[] { e.Update, args });
                        }
                    }
                }
                #endregion

                #region Daily tasks
                if (LatestBackup == null || LatestBackup.Date.ToUniversalTime() < DateTime.UtcNow.AddDays(-1))
                {
                    #region Daily Backup
                    var temp = Methods.SendBackup();
                    if (temp != null && (temp.Caption == "#AchvBotBackup" || temp.Text == "*this would be a backup if I was running on release*"))
                    {
                        LatestBackup = temp;
                    }
                    #endregion

                    // other stuff will come
                }

                #endregion
            }
            catch (Exception ex)
            {
                long chatid;
                if (e.Update.Type == UpdateType.MessageUpdate)
                {
                    chatid = e.Update.Message.Chat.Id;
                }
                else if (e.Update.Type == UpdateType.CallbackQueryUpdate)
                {
                    chatid = e.Update.CallbackQuery.Message.Chat.Id;
                }
                else
                {
                    chatid = -1;
                }
                Methods.SendError(ex, chatid, false);
            }
        }
Esempio n. 2
0
    public async Task AdminCheckerJobAsync(long chatId)
    {
        try
        {
            var sw = Stopwatch.StartNew();
            Log.Information("Starting check Admin in ChatID '{ChatId}'", chatId);

            var me = await _botClient.GetMeAsync();

            var isAdminChat = await this.IsAdminAsync(chatId, me.Id);

            if (isAdminChat)
            {
                await Task.Delay(5000);

                return;
            }

            Log.Debug("Doing leave chat from {ChatId}", chatId);

            var urlAddTo = await _botService.GetUrlStart("startgroup=new");

            var msgLeave = "Sepertinya saya bukan admin di grup ini, saya akan meninggalkan grup. Sampai jumpa!" +
                           "\n\nTerima kasih sudah menggunakan @MissZiziBot, silakan undang saya kembali jika diperlukan.";

            var inlineKeyboard = new InlineKeyboardMarkup
                                 (
                new[]
            {
                new[]
                {
                    InlineKeyboardButton.WithUrl("👥 Dukungan", "https://t.me/WinTenDev"),
                },
                new[]
                {
                    InlineKeyboardButton.WithUrl("➕ Tambahkan ke Grup", urlAddTo)
                }
            }
                                 );

            await _botClient.SendTextMessageAsync(
                chatId,
                msgLeave,
                ParseMode.Html,
                replyMarkup : inlineKeyboard
                );

            await _botClient.LeaveChatAsync(chatId);

            Log.Debug(
                "Checking Admin in ChatID '{ChatId}' job complete in {Elapsed}",
                chatId,
                sw.Elapsed
                );
            sw.Stop();

            await Task.Delay(5000);
        }
        catch (ApiRequestException requestException)
        {
            Log.Error(
                requestException,
                "Error when Check Admin on ChatID: '{ChatId}'",
                chatId
                );
            var setting = await _settingsService.GetSettingsByGroupCore(chatId);

            var exMessage = requestException.Message.ToLower();

            if (exMessage.IsContains("forbidden"))
            {
                var dateNow  = DateTime.UtcNow;
                var diffDays = (dateNow - setting.UpdatedAt).TotalDays;
                Log.Debug(
                    "Last activity days in '{ChatId}' is {DiffDays:N2} days",
                    chatId,
                    diffDays
                    );

                if (diffDays > AfterLeaveLimit)
                {
                    Log.Debug("This time is cleanup this chat!");
                    await _settingsService.DeleteSettings(chatId);
                }
            }
        }
        catch (Exception e)
        {
            Log.Error(
                e,
                "Error when Check Admin in ChatID: '{ChatId}'",
                chatId
                );
        }
    }
Esempio n. 3
0
        static async void OnMessage(object sender, MessageEventArgs e)
        {
            try
            {
                if (e.Message.From.Id == _telegram.BotId)
                {
                    return;
                }

                bool isAdmin   = e.Message.From.Id == BotConfig.TelegramAdminId;
                bool isPrivate = e.Message.Chat.Id == e.Message.From.Id;

                if (!isAdmin && isPrivate)
                {
                    return;
                }

                List <TelegramAllowlist> allowlist = Database.GetMany <TelegramAllowlist>();

                TelegramAllowlist allowlistEntry = null;
                foreach (TelegramAllowlist entry in allowlist)
                {
                    if (entry.ChannelId == e.Message.Chat.Id)
                    {
                        allowlistEntry = entry;
                        break;
                    }
                }

                if (allowlistEntry == null)
                {
                    allowlistEntry = new TelegramAllowlist()
                    {
                        ChannelId = e.Message.Chat.Id,
                        Approved  = false,
                        Warnings  = 0
                    };

                    allowlistEntry.Insert();
                }

                if (!allowlistEntry.Approved && !isAdmin)
                {
                    if (allowlistEntry.Warnings >= 5)
                    {
                        try
                        {
                            await _telegram.LeaveChatAsync(e.Message.Chat.Id);
                        }
                        catch { }
                        return;
                    }
                    else
                    {
                        allowlistEntry.Warnings++;
                        allowlistEntry.Update();
                        return;
                    }
                }

                UserAuthority authority = UserAuthority.User;
                if (isAdmin)
                {
                    authority = UserAuthority.Admin;
                }

                string message = e.Message.Text ?? "";
                if (message != "")
                {
                    if (message[0] == '/')
                    {
                        message = '!' + message[1..];