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