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