Advertisement
Agrair

Untitled

Aug 25th, 2019
162
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 6.59 KB | None | 0 0
  1. using System;
  2. using System.Collections.Specialized;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Net;
  6. using System.Net.Http;
  7. using System.Text;
  8. using System.Text.RegularExpressions;
  9. using System.Threading;
  10. using System.Threading.Tasks;
  11. using Discord;
  12. using Discord.WebSocket;
  13. using Microsoft.Extensions.DependencyInjection;
  14.  
  15. namespace Pandora.Services
  16. {
  17.     //https://github.com/tModLoader/tModLoader-Discord-Bot/blob/rework/Services/HastebinService.cs
  18.     public class HastebinService
  19.     {
  20.         private static readonly Regex KeyRegex = new Regex(@"{""key"":""(?<key>[a-z].*)""}",
  21.             RegexOptions.Compiled);
  22.  
  23.         private readonly DiscordSocketClient _client;
  24.  
  25.         private readonly string[] CodeBlockTypes = new string[]
  26.         {
  27.             "html",
  28.             "css",
  29.             "cs",
  30.             "dns",
  31.             "python",
  32.             "lua",
  33.             "http",
  34.             "markdown",
  35.         };
  36.  
  37.         private readonly char[] CodeKeyChars = new char[]
  38.         {
  39.             '{',
  40.             '}',
  41.             '=',
  42.             ';',
  43.             '<',
  44.             '>',
  45.             '(',
  46.             ')',
  47.         };
  48.  
  49.         private readonly string pasteKey = File.ReadAllText("D:/repos/pastekey.txt");
  50.  
  51.         private readonly Timer offlineCheck;
  52.         private string site;
  53.  
  54.         public HastebinService(IServiceProvider services)
  55.         {
  56.             _client = services.GetRequiredService<DiscordSocketClient>();
  57.  
  58.             _client.MessageReceived += HandleCommand;
  59.  
  60.             site = ChooseSite();
  61.             if (site == null) offlineCheck = new Timer(_ => OfflineCheck(), null,
  62.                 TimeSpan.FromDays(1), TimeSpan.FromDays(1));
  63.         }
  64.  
  65.         private void OfflineCheck()
  66.         {
  67.             site = ChooseSite();
  68.             if (site == null) offlineCheck.Change(TimeSpan.FromDays(1), TimeSpan.FromDays(1));
  69.             else offlineCheck.Change(-1, -1);
  70.         }
  71.  
  72.         public bool OfflineCheck(out string site)
  73.         {
  74.             OfflineCheck();
  75.             site = this.site;
  76.             return site != null;
  77.         }
  78.  
  79.         ~HastebinService()
  80.         {
  81.             _client.MessageReceived -= HandleCommand;
  82.             offlineCheck.Dispose();
  83.         }
  84.  
  85.         private async Task HandleCommand(SocketMessage socketMessage)
  86.         {
  87.             // Program is ready
  88.             if (!Core.PandoraHandler.Ready) return;
  89.  
  90.             if (site == null) return;
  91.  
  92.             // Valid message, no bot, no webhook
  93.             if (!(socketMessage is SocketUserMessage message)
  94.                 || message.Author.IsBot
  95.                 || message.Author.IsWebhook)
  96.                 return;
  97.  
  98.             string contents = message.Content;
  99.             bool shouldHastebin = false;
  100.             string extra = "";
  101.  
  102.             var attachents = message.Attachments;
  103.             if (attachents.Count == 1 && attachents.ElementAt(0) is Attachment attachment)
  104.             {
  105.                 if (attachment.Filename.EndsWith(".log") && attachment.Size < 100000)
  106.                 {
  107.                     using (var client = new HttpClient())
  108.                         contents = await client.GetStringAsync(attachment.Url);
  109.  
  110.                     shouldHastebin = true;
  111.                     extra = $" `({attachment.Filename})`";
  112.                 }
  113.             }
  114.  
  115.             if (string.IsNullOrWhiteSpace(contents))
  116.                 return;
  117.  
  118.             shouldHastebin = contents.Where(c => CodeKeyChars.Contains(c)).Count() > 1
  119.                 && message.Content.Split('\n').Length > 32;
  120.  
  121.             if (shouldHastebin)
  122.             {
  123.                 string hastebinContent = contents.Trim('`');
  124.                 for (int i = 0; i < CodeBlockTypes.Length; i++)
  125.                 {
  126.                     string keyword = CodeBlockTypes[i];
  127.                     if (hastebinContent.StartsWith(keyword))
  128.                     {
  129.                         hastebinContent = hastebinContent.Substring(keyword.Length);
  130.                     }
  131.                 }
  132.  
  133.                 var msg = await message.Channel.SendMessageAsync("Text-crunching in progress...");
  134.  
  135.                 if (site == "pastebin")
  136.                 {
  137.                     using WebClient client = new WebClient();
  138.                     var data = new NameValueCollection
  139.                         {
  140.                             { "api_option", "paste" },
  141.                             { "api_paste_name", "Quick Post by Pandora" },
  142.                             { "api_dev_key", pasteKey },
  143.                             { "api_paste_code", hastebinContent },
  144.                             { "api_paste_expire_date", "1D" }
  145.                         };
  146.                     client.UploadValuesCompleted += async (s, a) =>
  147.                     {
  148.                         await msg.ModifyAsync(x => x.Content = $"Automatic Pastebin for {message.Author.Username}" +
  149.                             $"{extra}: <{Encoding.UTF8.GetString(a.Result)}>");
  150.                     };
  151.                     client.UploadValuesAsync(new Uri("https://pastebin.com/api/api_post.php"), data);
  152.                 }
  153.  
  154.                 else
  155.                 {
  156.                     using var client = new HttpClient();
  157.                     HttpContent content = new StringContent(hastebinContent);
  158.  
  159.                     var response = await client.PostAsync(site + "/documents", content);
  160.                     string resultContent = await response.Content.ReadAsStringAsync();
  161.  
  162.                     var match = KeyRegex.Match(resultContent);
  163.  
  164.                     if (!match.Success) return;
  165.  
  166.                     string hasteUrl = $"{site}/{match.Groups["key"]}.cs";
  167.                     await msg.ModifyAsync(x => x.Content = $"Automatic Hastebin for {message.Author.Username}" +
  168.                         $"{extra}: {hasteUrl}");
  169.                 }
  170.                 await message.DeleteAsync();
  171.             }
  172.         }
  173.  
  174.         private string ChooseSite()
  175.         {
  176.             try
  177.             {
  178.                 using var ping = new System.Net.NetworkInformation.Ping();
  179.                 var result = ping.Send("paste.mod.gg");
  180.                 if (result.Status == System.Net.NetworkInformation.IPStatus.Success) return "https://paste.mod.gg";
  181.                 result = ping.Send("hastebin.com");
  182.                 if (result.Status == System.Net.NetworkInformation.IPStatus.Success) return "https://hastebin.com";
  183.                 result = ping.Send("pastebin.com");
  184.                 if (result.Status == System.Net.NetworkInformation.IPStatus.Success) return "pastebin";
  185.             } catch { }
  186.             return null;
  187.         }
  188.     }
  189. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement