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