· 6 years ago · Dec 31, 2019, 08:48 PM
1using System;
2using System.IO;
3using System.Linq;
4using System.Windows.Forms;
5using VkNet.Model.RequestParams;
6using VkNet.Model;
7using VkNet;
8using VkNet.Enums.SafetyEnums;
9using System.Threading;
10
11namespace VK_Bot
12{
13 public partial class Main : Form
14 {
15 public static VkApi api = new VkApi();
16 public static string ID;
17 public static string Token;
18 public static string file = @"data";
19 public Main()
20 {
21 InitializeComponent();
22 if (!File.Exists(file))
23 {
24 File.Create(file).Close();
25 File.WriteAllText(file, "ID: \r\nTOKEN: ");
26 }
27 else
28 {
29 ID = File.ReadLines(file).Skip(0).Take(1).First().Split(':').Last();
30 Token = File.ReadLines(file).Skip(1).Take(1).First().Split(':').Last();
31 if (ID == " " && Token == " ")
32 {
33 ID = "";
34 Token = "";
35 }
36
37 }
38 }
39
40 private void button1_Click(object sender, EventArgs e)
41 {
42 var auth = new auth();
43 auth.ShowDialog();
44 }
45
46 private void buttonRun_Click(object sender, EventArgs e)
47 {
48 FileInfo g = new FileInfo(file);
49 if (ID == " " && Token == " ")
50 {
51 MessageBox.Show("Require you to log in.", "Error");
52 }
53 api.Authorize(new ApiAuthParams() { AccessToken = Token });
54 Thread _search = new Thread(new ThreadStart(_to_serv));
55 _search.Start();
56 buttonRun.Text = "Running";
57 Text += " {Running}";
58 buttonSett.Enabled = false;
59 buttonRun.Enabled = false;
60 }
61
62 void _to_serv()
63 {
64 while (true) // Бесконечный цикл, получение обновлений
65 {
66 var s = api.Groups.GetLongPollServer(Convert.ToUInt64(ID));
67 var poll = api.Groups.GetBotsLongPollHistory(new BotsLongPollHistoryParams()
68 { Server = s.Server, Ts = s.Ts, Key = s.Key, Wait = 25 });
69 if (poll?.Updates == null)
70 {
71 MessageBox.Show("Нет");
72 continue;
73 }
74 else
75 {
76 MessageBox.Show("Да1");
77 foreach (var a in poll?.Updates)
78 {
79 MessageBox.Show("Да2");
80 if (a.Type == GroupUpdateType.MessageNew)
81 {
82 MessageBox.Show("Да3");
83 string userMessage = a.Message.Body.ToLower();
84 long? userID = a.Message.UserId;
85 textBox1.Text += "Принято: " + userMessage + "\r\n";
86 if (userMessage == "Привет")
87 {
88 string answ = "Здарова!";
89 SendMessage(answ, userID);
90 textBox1.Text += "Ответ: " + answ + "\r\n";
91 }
92 }
93 }// Проверка на новые события
94 }
95 }
96 }
97
98
99 public static void SendMessage(string message, long? userID)
100 {
101 Random rnd = new Random();
102 api.Messages.Send(new MessagesSendParams{RandomId = rnd.Next() ,UserId = userID,Message = message});
103 }
104
105 private void Main_FormClosing(object sender, FormClosingEventArgs e)
106 {
107 Environment.Exit(0);
108 }
109 }
110}