· 5 years ago · Dec 03, 2020, 10:18 AM
1//MCCScript 1.0
2//using System.Threading.Tasks;
3//dll Newtonsoft.Json.dll
4//using Newtonsoft.Json;
5//using Newtonsoft.Json.Linq;
6
7//==== INFO START ====
8// Download Newtonsoft.Json.dll and install it into the program folder Link: https://www.newtonsoft.com/json
9//==== INFO END ====
10
11//==== CONFIG START ====
12string vkToken = "";
13string chatId = "1";
14string botCommunityId = "200542815";
15//==== CONFIG END ====
16
17MCC.LoadBot(new VkMessager(vkToken, chatId, botCommunityId));
18
19//MCCScript Extensions
20
21public class VkMessager : ChatBot
22{
23 private VkLongPoolClient VkLongPoolClient { get; set; }
24 private readonly string ChatId;
25
26 public VkMessager(string vkToken, string chatId, string botCommunityId)
27 {
28 VkLongPoolClient = new VkLongPoolClient(vkToken, botCommunityId, ProcessMsgFromVk);
29 ChatId = chatId;
30 }
31 public override void Initialize()
32 {
33 LogToConsole("Bot enabled!");
34 }
35
36 private void ProcessMsgFromVk(string senderId, string peer_id, string text, string conversation_message_id, string id, string event_id)
37 {
38 VkLongPoolClient.Messages_Send_Text("2000000001", text1);
39 }
40
41public override void GetText(string text, string json)
42{
43 string text1 = GetVerbatim(text);
44}
45
46}
47/// <summary>
48/// This bot forwarding messages between Minecraft and VKonrakte chats.
49/// Shares only messages that starts with dot ("."). Example: .Hello!
50/// Also, send message to VK when any player joins or leaves.
51///
52/// Needs:
53/// - VK Community token (also LongPool API with NewMessageEvent, api >= 5.80),
54/// - VK ChatId (typically 2000000001, etc.)
55/// - Bot's CommunityId
56/// </summary>
57
58/// <summary>
59/// Client for VK Community (bot) LongPool API.
60/// Also can send messages.
61/// </summary>
62internal class VkLongPoolClient
63{
64 /* VK Client*/
65 public VkLongPoolClient(string token, string botCommunityId, Action<string, string, string, string, string, string> onMessageReceivedCallback, IWebProxy webProxy = null)
66 {
67 Token = token;
68 BotCommunityId = botCommunityId;
69 OnMessageReceivedCallback = onMessageReceivedCallback;
70 ReceiverWebClient = new WebClient() { Proxy = webProxy, Encoding = Encoding.UTF8 };
71 SenderWebClient = new WebClient() { Proxy = webProxy, Encoding = Encoding.UTF8 };
72
73 Init();
74 StartLongPoolAsync();
75 }
76
77 private WebClient ReceiverWebClient { get; set; }
78 private WebClient SenderWebClient { get; set; }
79 private string Token { get; set; }
80 private int LastTs { get; set; }
81 private string Server { get; set; }
82 private string Key { get; set; }
83 private Action<string, string, string, string, string, string> OnMessageReceivedCallback { get; set; }
84 private string BotCommunityId { get; set; }
85 private Random rnd = new Random();
86
87 /* Utils */
88 public string Utils_GetShortLink(string url)
89 {
90 if (Uri.IsWellFormedUriString(url, UriKind.Absolute))
91 {
92 string json = CallVkMethod("utils.getShortLink", "url=" + url);
93 var j = JsonConvert.DeserializeObject(json) as JObject;
94 var link = j["response"]["short_url"].ToString();
95 if (link == "")
96 return Utils_GetShortLink(url);
97 else
98 return link;
99 }
100 else
101 return "Invalid link format";
102 }
103
104 /* Docs */
105 public string Docs_GetMessagesUploadServer(string peer_id, string type, string file)
106 {
107 string string1 = CallVkMethod("docs.getMessagesUploadServer", "peer_id=" + peer_id + "&type=" + type);
108 if (string1 != "")
109 {
110 string uploadurl = Regex.Match(string1, "\"upload_url\":\"(.*)\"").Groups[1].Value.Replace(@"\/", "/");
111 return uploadurl;
112 }
113 else
114 return Docs_GetMessagesUploadServer(peer_id, type, file);
115 }
116
117 public string Docs_Upload(string url, string file)
118 {
119 var c = new WebClient();
120 var r2 = Encoding.UTF8.GetString(c.UploadFile(url, "POST", file));
121 if (r2 != "") return r2;
122 else return Docs_Upload(url, file);
123 }
124
125 public string Docs_Save(string file, string title)
126 {
127 var j2 = JsonConvert.DeserializeObject(file) as JObject;
128 if (j2 != null)
129 {
130 string json = CallVkMethod("docs.save", "&file=" + j2["file"].ToString() + "&title=" + title);
131 if (json != "")
132 return json;
133 else return "";
134 }
135 else return "";
136 }
137
138 public string Docs_Get_Send_Attachment(string file)
139 {
140 var j3 = JsonConvert.DeserializeObject(file) as JObject;
141 var at = "doc" + j3["response"]["doc"]["owner_id"].ToString() + "_" + j3["response"]["doc"]["id"].ToString();
142 return at;
143 }
144
145 /* Groups */
146 public void Groups_Online(bool enable = true)
147 {
148 if (enable)
149 CallVkMethod("groups.enableOnline", "group_id=" + BotCommunityId);
150 else
151 CallVkMethod("groups.disableOnline", "group_id=" + BotCommunityId);
152 }
153
154 public string Groups_GetById_GetName(string group_id)
155 {
156 try
157 {
158 string js = CallVkMethod("groups.getById", "group_id=" + group_id);
159 if (js != "")
160 {
161 var j3 = JsonConvert.DeserializeObject(js) as JObject;
162 string name = j3["response"][0]["name"].ToString();
163 return name;
164 }
165 else return "";
166 }
167 catch { return ""; }
168 }
169
170 /* Messages */
171 public void Messages_Kick_Group(string chat_id, string user_id)
172 {
173 if (user_id != BotCommunityId)
174 {
175 string json = CallVkMethod("messages.removeChatUser", "chat_id=" + chat_id + "&member_id=" + "-" + user_id);
176 }
177 }
178
179 public void Messages_Kick_User(string chat_id, string user_id)
180 {
181 string json = CallVkMethod("messages.removeChatUser", "chat_id=" + chat_id + "&user_id=" + user_id + "&member_id=" + user_id);
182 }
183
184 public void Messages_SetActivity(string chatId, string type = "typing")
185 {
186 string id3 = chatId;
187 id3 = id3.Substring(1);
188 int ind = Convert.ToInt32(id3);
189 CallVkMethod("messages.setActivity", "user_id=" + BotCommunityId + "&peer_id=" + chatId + "&group_id=" + "&type=" + type + "&group_id=" + BotCommunityId);
190 CallVkMethod("messages.setActivity", "user_id=" + BotCommunityId + "&peer_id=" + ind + "&type=" + type + "&group_id=" + BotCommunityId);
191 }
192
193 public string Messages_GetInviteLink(string chatId, bool reset)
194 {
195 try
196 {
197 string json = CallVkMethod("messages.getInviteLink", "peer_id=" + chatId + "&group_id=" + BotCommunityId);
198 if (json != "")
199 {
200 var j = JsonConvert.DeserializeObject(json) as JObject;
201 var link = j["response"]["link"].ToString();
202 return link;
203 }
204 return "";
205 }
206 catch { return ""; }
207 }
208
209 /* Users */
210 public string Users_Get_First_Name(string user_id, string name_case = "nom")
211 {
212 try
213 {
214 string json = CallVkMethod("users.get", "user_ids=" + user_id + "&name_case=" + name_case);
215 if (json != "")
216 {
217 var firstname = Regex.Match(json, "{\"first_name\":\"(.*)\",\"id\":(.*)").Groups[1].Value;
218 return firstname;
219 }
220 return "";
221 }
222 catch { return ""; }
223 }
224
225 public string Users_Get_Last_Name(string user_id)
226 {
227 try
228 {
229 string json = CallVkMethod("users.get", "user_ids=" + user_id);
230 if (json != "")
231 {
232 var firstname = Regex.Match(json, "\"id\":(.*),\"last_name\":\"(.*)\",\"can_access_closed\":(.*)").Groups[2].Value;
233 return firstname;
234 }
235 return "";
236 }
237 catch { return ""; }
238 }
239
240 /* Messages Send */
241 public void Messages_Send_Text(string chatId, string text, int disable_mentions = 0)
242 {
243 string reply = CallVkMethod("messages.send", "peer_id=" + chatId + "&random_id=" + rnd.Next() + "&message=" + text + "&disable_mentions=" + disable_mentions);
244 }
245
246 public void Messages_Send_Keyboard(string chatId, Keyboard keyboard)
247 {
248 string kb = keyboard.GetKeyboard();
249 string reply = CallVkMethod("messages.send", "peer_id=" + chatId + "&random_id=" + rnd.Next() + "&keyboard=" + kb);
250 }
251
252 public void Messages_Send_TextAndKeyboard(string chatId, string text, Keyboard keyboard)
253 {
254 string kb = keyboard.GetKeyboard();
255 string reply = CallVkMethod("messages.send", "peer_id=" + chatId + "&random_id=" + rnd.Next() + "&message=" + text + "&keyboard=" + kb);
256 }
257
258 public void Messages_Send_Sticker(string chatId, int sticker_id)
259 {
260 string reply = CallVkMethod("messages.send", "peer_id=" + chatId + "&random_id=" + rnd.Next() + "&sticker_id=" + sticker_id);
261 }
262
263 public void Messages_Send_TextAndDocument(string chatId, string text, string file, string title)
264 {
265 string u2 = Docs_GetMessagesUploadServer(chatId, "doc", file);
266 string r2 = Docs_Upload(u2, file);
267 string r3 = Docs_Save(r2, title);
268 string at = Docs_Get_Send_Attachment(r3);
269 string reply = CallVkMethod("messages.send", "peer_id=" + chatId + "&random_id=" + rnd.Next() + "&message=" + text + "&attachment=" + at);
270 }
271
272 public void Messages_Send_Custom(string chatId, string custom)
273 {
274 string reply = CallVkMethod("messages.send", "peer_id=" + chatId + "&random_id=" + rnd.Next() + custom);
275 }
276
277 /* Messages GetConversationMembers*/
278 public int Messages_GetConversationMembers_GetCount(string chatId)
279 {
280 var json = CallVkMethod("messages.getConversationMembers", "peer_id=" + chatId + "&group_id=" + BotCommunityId);
281 if (json != "")
282 {
283 var j = JsonConvert.DeserializeObject(json) as JObject;
284 int u2 = int.Parse(j["response"]["count"].ToString());
285 return u2;
286 }
287 else return -1;
288 }
289
290 public string Messages_GetConversationMembers_GetProfiles(string chatId)
291 {
292 var json = CallVkMethod("messages.getConversationMembers", "peer_id=" + chatId + "&group_id=" + BotCommunityId);
293 if (json != "")
294 {
295 string ids = "";
296 JObject json1 = JObject.Parse(json);
297 IList<JToken> results = json1["response"]["profiles"].Children().ToList();
298 foreach (JToken result in results)
299 {
300 string id = result["id"].ToString();
301 if (!id.Contains("-"))
302 ids += id + ", ";
303 }
304 return ids;
305 }
306 return "";
307 }
308
309 public string Messages_GetConversationMembers_GetItems_member_id(string chatId)
310 {
311 var json = CallVkMethod("messages.getConversationMembers", "peer_id=" + chatId + "&group_id=" + BotCommunityId);
312 if (json != "")
313 {
314 string ids = "";
315 JObject json1 = JObject.Parse(json);
316 IList<JToken> results = json1["response"]["items"].Children().ToList();
317 foreach (JToken result in results)
318 {
319 string id = result["member_id"].ToString();
320 if (!id.Contains("-"))
321 ids += id + ", ";
322 }
323 return ids;
324 }
325 return "";
326 }
327
328 public class Keyboard
329 {
330 public enum Color
331 {
332 Negative,
333 Positive,
334 Primary,
335 Secondary
336 }
337
338 public bool one_time = false;
339 public List<List<object>> buttons = new List<List<object>>();
340 public bool inline = false;
341
342 public Keyboard(bool one_time2, bool line = false)
343 {
344 if (line == true && one_time2 == true)
345 one_time2 = false;
346 one_time = one_time2;
347 inline = line;
348 }
349
350 public void AddButton(string label, string payload, Color color)
351 {
352 string color2 = "";
353 if (color == Color.Negative)
354 color2 = "Negative";
355 else if (color == Color.Positive)
356 color2 = "Positive";
357 else if (color == Color.Primary)
358 color2 = "Primary";
359 else
360 color2 = "Secondary";
361 Buttons button = new Buttons(label, payload, color2);
362 buttons.Add(new List<object>() { button });
363 }
364
365 public string GetKeyboard()
366 {
367 return JsonConvert.SerializeObject(this, Formatting.Indented); ;
368 }
369
370 public class Buttons
371 {
372 public Action action;
373 public string color;
374 public Buttons(string labe11, string payload1, string color2)
375 {
376 action = new Action(labe11, payload1);
377 color = color2;
378 }
379
380 public class Action
381 {
382 public string type;
383 public string payload;
384 public string label;
385 public Action(string label3, string payload3)
386 {
387 type = "text";
388 payload = "{\"button\": \"" + payload3 + "\"}";
389 label = label3;
390 }
391 }
392 }
393 }
394
395 /* LoongPool */
396 private void Init()
397 {
398 var jsonResult = CallVkMethod("groups.getLongPollServer", "group_id=" + BotCommunityId);
399 var data = Json.ParseJson(jsonResult);
400
401 Key = data.Properties["response"].Properties["key"].StringValue;
402 Server = data.Properties["response"].Properties["server"].StringValue;
403 LastTs = Convert.ToInt32(data.Properties["response"].Properties["ts"].StringValue);
404 }
405
406 private void StartLongPoolAsync()
407 {
408 Task.Factory.StartNew(() =>
409 {
410 while (true)
411 {
412 try
413 {
414 string baseUrl = String.Format("{0}?act=a_check&version=2&wait=25&key={1}&ts=", Server, Key);
415 var data = ReceiverWebClient.DownloadString(baseUrl + LastTs);
416 var messages = ProcessResponse(data);
417
418 foreach (var message in messages)
419 {
420 OnMessageReceivedCallback(message.Item1, message.Item2, message.Item3, message.Item4, message.Item5, message.Item6);
421 }
422 }
423 catch { }
424 }
425 });
426 }
427
428 private IEnumerable<Tuple<string, string, string, string, string, string>> ProcessResponse(string jsonData)
429 {
430 var j = JsonConvert.DeserializeObject(jsonData) as JObject;
431 var data = Json.ParseJson(jsonData);
432 if (data.Properties.ContainsKey("failed"))
433 {
434 Init();
435 }
436 LastTs = Convert.ToInt32(data.Properties["ts"].StringValue);
437 var updates = data.Properties["updates"].DataArray;
438 List<Tuple<string, string, string, string, string, string>> messages = new List<Tuple<string, string, string, string, string, string>>();
439 foreach (var str in updates)
440 {
441 if (str.Properties["type"].StringValue != "message_new") continue;
442
443 var msgData = str.Properties["object"].Properties;
444
445 var id = msgData["from_id"].StringValue;
446 var userId = msgData["from_id"].StringValue;
447 var peer_id = msgData["peer_id"].StringValue;
448 string event_id = "";
449 var msgText = msgData["text"].StringValue;
450 var conversation_message_id = msgData["conversation_message_id"].StringValue;
451
452 messages.Add(new Tuple<string, string, string, string, string, string>(userId, peer_id, msgText, conversation_message_id, id, event_id));
453 }
454
455 return messages;
456 }
457
458 public string CallVkMethod(string methodName, string data)
459 {
460 try
461 {
462 var url = String.Format("https://api.vk.com/method/{0}?v=5.124&access_token={1}&{2}", methodName, Token, data);
463 var jsonResult = SenderWebClient.DownloadString(url);
464
465 return jsonResult;
466 }
467 catch { return String.Empty; }
468 }
469}