Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Collections.ObjectModel;
- using System.IO;
- using System.Threading;
- using System.Threading.Tasks;
- using VkNet;
- using VkNet.Enums;
- using VkNet.Enums.Filters;
- using VkNet.Exception;
- using VkNet.Model;
- using VkNet.Model.RequestParams;
- namespace MonteceVkBot
- {
- class Program
- {
- static VkApi vkapi = new VkApi();
- static long userID = 0;
- static ulong? Ts;
- static ulong? Pts;
- static bool IsActive;
- static Timer WatchTimer = null;
- static byte MaxSleepSteps = 3;
- static int StepSleepTime = 333;
- static byte CurrentSleepSteps = 1;
- delegate void MessagesRecievedDelegate(VkApi owner, ReadOnlyCollection<Message> messages);
- static event MessagesRecievedDelegate NewMessages;
- static Func<string> DoubleCode = () =>
- {
- Console.Write("Введите код авторизации: ");
- return Console.ReadLine();
- };
- static void Main(string[] args)
- {
- string Login = "+79045429427";
- string Password = "svetik11";
- ulong ID = 6497404;
- bool DoubleAuth = false;
- ConsoleStyle();
- /*
- Console.Write("Введите логин: ");
- Login = Console.ReadLine();
- Console.Write("Введите пароль: ");
- Password = Console.ReadLine();
- Console.Write("Введите ID приложения: ");
- ID = ulong.Parse(Console.ReadLine());
- Console.Write("Есть двухэтапный аутификатор? (1/0): ");
- DoubleAuth = Convert.ToBoolean(Convert.ToInt32(Console.ReadLine()));
- */
- Console.WriteLine("Попытка авторизации...");
- if (Auth(Login, Password, ID, DoubleAuth))
- {
- ColorMessage("Авторизация успешно завершена.", ConsoleColor.Green);
- User I = vkapi.Users.Get(vkapi.UserId.Value);
- Console.WriteLine("Вы: " + I.FirstName + " " + I.LastName);
- Eye();
- ColorMessage("Слежение за сообщениями активировано.", ConsoleColor.Yellow);
- }
- else
- {
- ColorMessage("Не удалось произвести авторизацию!", ConsoleColor.Red);
- }
- Console.WriteLine("Нажмите ENTER чтобы выйти...");
- Console.ReadLine();
- }
- static void ConsoleStyle()
- {
- Console.Title = "Montece VK bot";
- ColorMessage("Montece VK bot", ConsoleColor.Yellow);
- }
- static void ColorMessage(string text, ConsoleColor color)
- {
- Console.ForegroundColor = color;
- Console.WriteLine(text);
- Console.ForegroundColor = ConsoleColor.Gray;
- }
- static bool Auth(string Login, string Password, ulong ID, bool HasCode)
- {
- try
- {
- if (HasCode == true)
- {
- vkapi.Authorize(new ApiAuthParams
- {
- Login = Login,
- Password = Password,
- Settings = Settings.All,
- ApplicationId = ID,
- TwoFactorAuthorization = DoubleCode
- });
- return true;
- }
- else
- {
- vkapi.Authorize(new ApiAuthParams
- {
- Login = Login,
- Password = Password,
- Settings = Settings.All,
- ApplicationId = ID
- });
- return true;
- }
- }
- catch
- {
- return false;
- }
- }
- static string[] Commands = { "помощь", "привет", "регистрация" };
- static void Command(string Message)
- {
- Message = Message.ToLower();
- if (Message == Commands[0])
- {
- string msg = "";
- for (int j = 0; j < Commands.Length; j++) msg += Commands[j] + ", ";
- SendMessage(msg);
- }
- else if (Message == Commands[1])
- {
- SendMessage("Приветик!!!)))");
- }
- else if (Message == Commands[2])
- {
- SendMessage("Введите поддомен");
- var user = new Users();
- user.subdomain = Message;
- File.AppendAllText("lol.txt", user.subdomain);
- }
- /*else if (Message == Commands[2])
- {
- SendMessage("MESSAGETEXT");
- }*/
- //else
- //{
- // SendMessage("Неизвестная команда. Напишите 'Помощь' для получения списка команд.");
- //}
- }
- static void Registration(string Message)
- {
- SendMessage("Введите поддомен");
- var user = new Users();
- user.subdomain = Message;
- File.AppendAllText("lol.txt", user.subdomain);
- }
- static void SendMessage(string Body)
- {
- try
- {
- vkapi.Messages.Send(new MessagesSendParams
- {
- UserId = userID,
- Message = Body
- });
- }
- catch(Exception e)
- {
- ColorMessage("Ошибка! " + e.Message, ConsoleColor.Red);
- }
- }
- static void Eye()
- {
- LongPollServerResponse Pool = vkapi.Messages.GetLongPollServer(true);
- StartAsync(Pool.Ts, Pool.Pts);
- NewMessages += Watcher_NewMessages;
- }
- static void Watcher_NewMessages(VkApi owner, ReadOnlyCollection<Message> messages)
- {
- for (int i = 0; i < messages.Count; i++)
- {
- if (messages[i].Type != MessageType.Sended)
- {
- User Sender = vkapi.Users.Get(messages[i].UserId.Value);
- Console.WriteLine("Новое сообщение: {0} {1}: {2}", Sender.FirstName, Sender.LastName, messages[i].Body);
- userID = messages[i].UserId.Value;
- Console.Beep();
- Command(messages[i].Body);
- }
- }
- }
- static LongPollServerResponse GetLongPoolServer(ulong? lastPts = null)
- {
- LongPollServerResponse response = vkapi.Messages.GetLongPollServer(false, lastPts == null);
- Ts = response.Ts;
- Pts = Pts == null ? response.Pts : lastPts;
- return response;
- }
- static Task<LongPollServerResponse> GetLongPoolServerAsync(ulong? lastPts = null)
- {
- return Task.Run(() =>
- {
- return GetLongPoolServer(lastPts);
- });
- }
- static LongPollHistoryResponse GetLongPoolHistory()
- {
- if (!Ts.HasValue) GetLongPoolServer(null);
- MessagesGetLongPollHistoryParams rp = new MessagesGetLongPollHistoryParams();
- rp.Ts = Ts.Value;
- rp.Pts = Pts;
- int i = 0;
- LongPollHistoryResponse history = null;
- string errorLog = "";
- while (i < 5 && history == null)
- {
- i++;
- try
- {
- history = vkapi.Messages.GetLongPollHistory(rp);
- }
- catch (TooManyRequestsException)
- {
- Thread.Sleep(150);
- i--;
- }
- catch (Exception ex)
- {
- errorLog += string.Format("{0} - {1}{2}", i, ex.Message, Environment.NewLine);
- }
- }
- if (history != null)
- {
- Pts = history.NewPts;
- foreach (var m in history.Messages)
- {
- m.FromId = m.Type == MessageType.Sended ? vkapi.UserId : m.UserId;
- }
- }
- else ColorMessage(errorLog, ConsoleColor.Red);
- return history;
- }
- static Task<LongPollHistoryResponse> GetLongPoolHistoryAsync()
- {
- return Task.Run(() => { return GetLongPoolHistory(); });
- }
- static async void WatchAsync(object state)
- {
- LongPollHistoryResponse history = await GetLongPoolHistoryAsync();
- if (history.Messages.Count > 0)
- {
- CurrentSleepSteps = 1;
- NewMessages?.Invoke(vkapi, history.Messages);
- }
- else if (CurrentSleepSteps < MaxSleepSteps) CurrentSleepSteps++;
- WatchTimer.Change(CurrentSleepSteps * StepSleepTime, Timeout.Infinite);
- }
- static async void StartAsync(ulong? lastTs = null, ulong? lastPts = null)
- {
- if (IsActive) ColorMessage("Messages for {0} already watching", ConsoleColor.Red);
- IsActive = true;
- await GetLongPoolServerAsync(lastPts);
- WatchTimer = new Timer(new TimerCallback(WatchAsync), null, 0, Timeout.Infinite);
- }
- static void Stop()
- {
- if (WatchTimer != null) WatchTimer.Dispose();
- IsActive = false;
- WatchTimer = null;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment