Guest User

Untitled

a guest
Jun 1st, 2018
113
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 9.91 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Collections.ObjectModel;
  4. using System.IO;
  5. using System.Threading;
  6. using System.Threading.Tasks;
  7. using VkNet;
  8. using VkNet.Enums;
  9. using VkNet.Enums.Filters;
  10. using VkNet.Exception;
  11. using VkNet.Model;
  12. using VkNet.Model.RequestParams;
  13.  
  14. namespace MonteceVkBot
  15. {
  16.    
  17.     class Program
  18.     {
  19.        
  20.         static VkApi vkapi = new VkApi();
  21.         static long userID = 0;
  22.         static ulong? Ts;
  23.         static ulong? Pts;
  24.         static bool IsActive;
  25.         static Timer WatchTimer = null;
  26.         static byte MaxSleepSteps = 3;
  27.         static int StepSleepTime = 333;
  28.         static byte CurrentSleepSteps = 1;
  29.         delegate void MessagesRecievedDelegate(VkApi owner, ReadOnlyCollection<Message> messages);
  30.         static event MessagesRecievedDelegate NewMessages;
  31.  
  32.         static Func<string> DoubleCode = () =>
  33.         {
  34.             Console.Write("Введите код авторизации: ");
  35.             return Console.ReadLine();
  36.         };
  37.  
  38.         static void Main(string[] args)
  39.         {
  40.             string Login = "+79045429427";
  41.             string Password = "svetik11";
  42.             ulong ID = 6497404;
  43.             bool DoubleAuth = false;
  44.             ConsoleStyle();
  45.             /*
  46.             Console.Write("Введите логин: ");
  47.             Login = Console.ReadLine();
  48.             Console.Write("Введите пароль: ");
  49.             Password = Console.ReadLine();
  50.             Console.Write("Введите ID приложения: ");
  51.             ID = ulong.Parse(Console.ReadLine());          
  52.             Console.Write("Есть двухэтапный аутификатор? (1/0): ");
  53.             DoubleAuth = Convert.ToBoolean(Convert.ToInt32(Console.ReadLine()));
  54.             */
  55.  
  56.             Console.WriteLine("Попытка авторизации...");
  57.  
  58.             if (Auth(Login, Password, ID, DoubleAuth))
  59.             {
  60.                 ColorMessage("Авторизация успешно завершена.", ConsoleColor.Green);
  61.                 User I = vkapi.Users.Get(vkapi.UserId.Value);
  62.                 Console.WriteLine("Вы: " + I.FirstName + " " + I.LastName);
  63.                 Eye();
  64.                 ColorMessage("Слежение за сообщениями активировано.", ConsoleColor.Yellow);
  65.             }
  66.             else
  67.             {
  68.                 ColorMessage("Не удалось произвести авторизацию!", ConsoleColor.Red);
  69.             }
  70.  
  71.             Console.WriteLine("Нажмите ENTER чтобы выйти...");
  72.             Console.ReadLine();
  73.         }
  74.  
  75.         static void ConsoleStyle()
  76.         {
  77.             Console.Title = "Montece VK bot";
  78.             ColorMessage("Montece VK bot", ConsoleColor.Yellow);
  79.         }
  80.  
  81.         static void ColorMessage(string text, ConsoleColor color)
  82.         {
  83.             Console.ForegroundColor = color;
  84.             Console.WriteLine(text);
  85.             Console.ForegroundColor = ConsoleColor.Gray;
  86.         }
  87.  
  88.         static bool Auth(string Login, string Password, ulong ID, bool HasCode)
  89.         {
  90.             try
  91.             {
  92.                 if (HasCode == true)
  93.                 {
  94.                     vkapi.Authorize(new ApiAuthParams
  95.                     {
  96.                         Login = Login,
  97.                         Password = Password,
  98.                         Settings = Settings.All,
  99.                         ApplicationId = ID,
  100.                         TwoFactorAuthorization = DoubleCode
  101.                     });
  102.                     return true;
  103.                 }
  104.                 else
  105.                 {
  106.                     vkapi.Authorize(new ApiAuthParams
  107.                     {
  108.                         Login = Login,
  109.                         Password = Password,
  110.                         Settings = Settings.All,
  111.                         ApplicationId = ID
  112.                     });
  113.                     return true;
  114.                 }
  115.             }
  116.             catch
  117.             {
  118.                 return false;
  119.             }
  120.         }
  121.  
  122.         static string[] Commands = { "помощь", "привет", "регистрация" };
  123.  
  124.         static void Command(string Message)
  125.         {
  126.             Message = Message.ToLower();
  127.             if (Message == Commands[0])
  128.             {
  129.                 string msg = "";
  130.                 for (int j = 0; j < Commands.Length; j++) msg += Commands[j] + ", ";
  131.                 SendMessage(msg);
  132.             }
  133.             else if (Message == Commands[1])
  134.             {
  135.                 SendMessage("Приветик!!!)))");
  136.             }
  137.             else if (Message == Commands[2])
  138.             {
  139.                 SendMessage("Введите поддомен");
  140.                 var user = new Users();
  141.                 user.subdomain = Message;
  142.                 File.AppendAllText("lol.txt", user.subdomain);
  143.             }
  144.             /*else if (Message == Commands[2])
  145.             {
  146.                 SendMessage("MESSAGETEXT");
  147.             }*/
  148.             //else
  149.             //{
  150.             //    SendMessage("Неизвестная команда. Напишите 'Помощь' для получения списка команд.");
  151.                
  152.             //}
  153.         }
  154.  
  155.         static void Registration(string Message)
  156.         {
  157.             SendMessage("Введите поддомен");
  158.             var user = new Users();
  159.             user.subdomain = Message;
  160.             File.AppendAllText("lol.txt", user.subdomain);
  161.         }
  162.  
  163.         static void SendMessage(string Body)
  164.         {
  165.             try
  166.             {
  167.                 vkapi.Messages.Send(new MessagesSendParams
  168.                 {
  169.                     UserId = userID,
  170.                     Message = Body
  171.                 });
  172.             }
  173.             catch(Exception e)
  174.             {
  175.                 ColorMessage("Ошибка! " + e.Message, ConsoleColor.Red);
  176.             }
  177.            
  178.         }
  179.  
  180.         static void Eye()
  181.         {
  182.             LongPollServerResponse Pool = vkapi.Messages.GetLongPollServer(true);
  183.             StartAsync(Pool.Ts, Pool.Pts);
  184.             NewMessages += Watcher_NewMessages;
  185.         }
  186.  
  187.         static void Watcher_NewMessages(VkApi owner, ReadOnlyCollection<Message> messages)
  188.         {
  189.             for (int i = 0; i < messages.Count; i++)
  190.             {
  191.                 if (messages[i].Type != MessageType.Sended)
  192.                 {
  193.                     User Sender = vkapi.Users.Get(messages[i].UserId.Value);
  194.                     Console.WriteLine("Новое сообщение: {0} {1}: {2}", Sender.FirstName, Sender.LastName, messages[i].Body);
  195.                     userID = messages[i].UserId.Value;
  196.                     Console.Beep();
  197.                     Command(messages[i].Body);
  198.                 }
  199.             }
  200.         }
  201.  
  202.         static LongPollServerResponse GetLongPoolServer(ulong? lastPts = null)
  203.         {
  204.             LongPollServerResponse response = vkapi.Messages.GetLongPollServer(false, lastPts == null);
  205.             Ts = response.Ts;
  206.             Pts = Pts == null ? response.Pts : lastPts;
  207.             return response;
  208.         }
  209.  
  210.         static Task<LongPollServerResponse> GetLongPoolServerAsync(ulong? lastPts = null)
  211.         {
  212.             return Task.Run(() =>
  213.             {
  214.                 return GetLongPoolServer(lastPts);
  215.             });
  216.         }
  217.  
  218.         static LongPollHistoryResponse GetLongPoolHistory()
  219.         {
  220.             if (!Ts.HasValue) GetLongPoolServer(null);
  221.             MessagesGetLongPollHistoryParams rp = new MessagesGetLongPollHistoryParams();
  222.             rp.Ts = Ts.Value;
  223.             rp.Pts = Pts;
  224.             int i = 0;
  225.             LongPollHistoryResponse history = null;
  226.             string errorLog = "";
  227.  
  228.             while (i < 5 && history == null)
  229.             {
  230.                 i++;
  231.                 try
  232.                 {
  233.                     history = vkapi.Messages.GetLongPollHistory(rp);
  234.                 }
  235.                 catch (TooManyRequestsException)
  236.                 {
  237.                     Thread.Sleep(150);
  238.                     i--;
  239.                 }
  240.                 catch (Exception ex)
  241.                 {                    
  242.                     errorLog += string.Format("{0} - {1}{2}", i, ex.Message, Environment.NewLine);
  243.                 }
  244.             }
  245.  
  246.             if (history != null)
  247.             {
  248.                 Pts = history.NewPts;
  249.                 foreach (var m in history.Messages)
  250.                 {
  251.                     m.FromId = m.Type == MessageType.Sended ? vkapi.UserId : m.UserId;
  252.                 }                    
  253.             }
  254.             else ColorMessage(errorLog, ConsoleColor.Red);
  255.             return history;
  256.         }
  257.  
  258.         static Task<LongPollHistoryResponse> GetLongPoolHistoryAsync()
  259.         {
  260.             return Task.Run(() => { return GetLongPoolHistory(); });
  261.         }
  262.  
  263.         static async void WatchAsync(object state)
  264.         {
  265.             LongPollHistoryResponse history = await GetLongPoolHistoryAsync();
  266.             if (history.Messages.Count > 0)
  267.             {
  268.                 CurrentSleepSteps = 1;
  269.                 NewMessages?.Invoke(vkapi, history.Messages);
  270.             }
  271.             else if (CurrentSleepSteps < MaxSleepSteps) CurrentSleepSteps++;
  272.             WatchTimer.Change(CurrentSleepSteps * StepSleepTime, Timeout.Infinite);
  273.         }
  274.  
  275.         static async void StartAsync(ulong? lastTs = null, ulong? lastPts = null)
  276.         {
  277.             if (IsActive) ColorMessage("Messages for {0} already watching", ConsoleColor.Red);
  278.             IsActive = true;
  279.             await GetLongPoolServerAsync(lastPts);
  280.             WatchTimer = new Timer(new TimerCallback(WatchAsync), null, 0, Timeout.Infinite);
  281.         }
  282.  
  283.         static void Stop()
  284.         {
  285.             if (WatchTimer != null) WatchTimer.Dispose();
  286.             IsActive = false;
  287.             WatchTimer = null;
  288.         }
  289.     }
  290. }
Advertisement
Add Comment
Please, Sign In to add comment