Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Specialized;
- using System.IO;
- using System.Linq;
- using System.Net;
- using System.Net.Http;
- using System.Text;
- using System.Text.RegularExpressions;
- using System.Threading;
- using System.Threading.Tasks;
- using Discord;
- using Discord.WebSocket;
- using Microsoft.Extensions.DependencyInjection;
- namespace Pandora.Services
- {
- //https://github.com/tModLoader/tModLoader-Discord-Bot/blob/rework/Services/HastebinService.cs
- public class HastebinService
- {
- private static readonly Regex KeyRegex = new Regex(@"{""key"":""(?<key>[a-z].*)""}",
- RegexOptions.Compiled);
- private readonly DiscordSocketClient _client;
- private readonly string[] CodeBlockTypes = new string[]
- {
- "html",
- "css",
- "cs",
- "dns",
- "python",
- "lua",
- "http",
- "markdown",
- };
- private readonly char[] CodeKeyChars = new char[]
- {
- '{',
- '}',
- '=',
- ';',
- '<',
- '>',
- '(',
- ')',
- };
- private readonly string pasteKey = File.ReadAllText("D:/repos/pastekey.txt");
- private readonly Timer offlineCheck;
- private string site;
- public HastebinService(IServiceProvider services)
- {
- _client = services.GetRequiredService<DiscordSocketClient>();
- _client.MessageReceived += HandleCommand;
- site = ChooseSite();
- if (site == null) offlineCheck = new Timer(_ => OfflineCheck(), null,
- TimeSpan.FromDays(1), TimeSpan.FromDays(1));
- }
- private void OfflineCheck()
- {
- site = ChooseSite();
- if (site == null) offlineCheck.Change(TimeSpan.FromDays(1), TimeSpan.FromDays(1));
- else offlineCheck.Change(-1, -1);
- }
- public bool OfflineCheck(out string site)
- {
- OfflineCheck();
- site = this.site;
- return site != null;
- }
- ~HastebinService()
- {
- _client.MessageReceived -= HandleCommand;
- offlineCheck.Dispose();
- }
- private async Task HandleCommand(SocketMessage socketMessage)
- {
- // Program is ready
- if (!Core.PandoraHandler.Ready) return;
- if (site == null) return;
- // Valid message, no bot, no webhook
- if (!(socketMessage is SocketUserMessage message)
- || message.Author.IsBot
- || message.Author.IsWebhook)
- return;
- string contents = message.Content;
- bool shouldHastebin = false;
- string extra = "";
- var attachents = message.Attachments;
- if (attachents.Count == 1 && attachents.ElementAt(0) is Attachment attachment)
- {
- if (attachment.Filename.EndsWith(".log") && attachment.Size < 100000)
- {
- using (var client = new HttpClient())
- contents = await client.GetStringAsync(attachment.Url);
- shouldHastebin = true;
- extra = $" `({attachment.Filename})`";
- }
- }
- if (string.IsNullOrWhiteSpace(contents))
- return;
- shouldHastebin = contents.Where(c => CodeKeyChars.Contains(c)).Count() > 1
- && message.Content.Split('\n').Length > 32;
- if (shouldHastebin)
- {
- string hastebinContent = contents.Trim('`');
- for (int i = 0; i < CodeBlockTypes.Length; i++)
- {
- string keyword = CodeBlockTypes[i];
- if (hastebinContent.StartsWith(keyword))
- {
- hastebinContent = hastebinContent.Substring(keyword.Length);
- }
- }
- var msg = await message.Channel.SendMessageAsync("Text-crunching in progress...");
- if (site == "pastebin")
- {
- using WebClient client = new WebClient();
- var data = new NameValueCollection
- {
- { "api_option", "paste" },
- { "api_paste_name", "Quick Post by Pandora" },
- { "api_dev_key", pasteKey },
- { "api_paste_code", hastebinContent },
- { "api_paste_expire_date", "1D" }
- };
- client.UploadValuesCompleted += async (s, a) =>
- {
- await msg.ModifyAsync(x => x.Content = $"Automatic Pastebin for {message.Author.Username}" +
- $"{extra}: <{Encoding.UTF8.GetString(a.Result)}>");
- };
- client.UploadValuesAsync(new Uri("https://pastebin.com/api/api_post.php"), data);
- }
- else
- {
- using var client = new HttpClient();
- HttpContent content = new StringContent(hastebinContent);
- var response = await client.PostAsync(site + "/documents", content);
- string resultContent = await response.Content.ReadAsStringAsync();
- var match = KeyRegex.Match(resultContent);
- if (!match.Success) return;
- string hasteUrl = $"{site}/{match.Groups["key"]}.cs";
- await msg.ModifyAsync(x => x.Content = $"Automatic Hastebin for {message.Author.Username}" +
- $"{extra}: {hasteUrl}");
- }
- await message.DeleteAsync();
- }
- }
- private string ChooseSite()
- {
- try
- {
- using var ping = new System.Net.NetworkInformation.Ping();
- var result = ping.Send("paste.mod.gg");
- if (result.Status == System.Net.NetworkInformation.IPStatus.Success) return "https://paste.mod.gg";
- result = ping.Send("hastebin.com");
- if (result.Status == System.Net.NetworkInformation.IPStatus.Success) return "https://hastebin.com";
- result = ping.Send("pastebin.com");
- if (result.Status == System.Net.NetworkInformation.IPStatus.Success) return "pastebin";
- } catch { }
- return null;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement