Almost done converting NSFW

This commit is contained in:
Kwoth
2016-08-15 16:57:40 +02:00
parent f748bad188
commit 40214c0deb
75 changed files with 1575 additions and 2061 deletions

View File

@@ -0,0 +1,185 @@
using Discord;
using Newtonsoft.Json;
using System;
using System.Linq;
using System.Text;
//using Manatee.Json.Serialization;
namespace NadekoBot.Classes.ClashOfClans
{
public enum DestroyStars
{
One, Two, Three
}
public enum WarState
{
Started, Ended, Created
}
internal class Caller
{
public string CallUser { get; set; }
public DateTime TimeAdded { get; set; }
public bool BaseDestroyed { get; set; }
public int Stars { get; set; } = 3;
public Caller() { }
public Caller(string callUser, DateTime timeAdded, bool baseDestroyed)
{
CallUser = callUser;
TimeAdded = timeAdded;
BaseDestroyed = baseDestroyed;
}
public void ResetTime()
{
TimeAdded = DateTime.UtcNow;
}
public void Destroy()
{
BaseDestroyed = true;
}
}
internal class ClashWar
{
private static TimeSpan callExpire => new TimeSpan(2, 0, 0);
public string EnemyClan { get; set; }
public int Size { get; set; }
public Caller[] Bases { get; set; }
public WarState WarState { get; set; } = WarState.Created;
//public bool Started { get; set; } = false;
public DateTime StartedAt { get; set; }
//public bool Ended { get; private set; } = false;
public ulong ServerId { get; set; }
public ulong ChannelId { get; set; }
[JsonIgnore]
public ITextChannel Channel { get; internal set; }
/// <summary>
/// This init is purely for the deserialization
/// </summary>
public ClashWar() { }
public ClashWar(string enemyClan, int size, ulong serverId, ulong channelId)
{
this.EnemyClan = enemyClan;
this.Size = size;
this.Bases = new Caller[size];
this.ServerId = serverId;
this.ChannelId = channelId;
this.Channel = NadekoBot.Client.GetGuildsAsync() //nice api you got here volt,
.GetAwaiter() //especially like how getguildsasync isn't async at all internally.
.GetResult() //But hey, lib has to be async kek
.FirstOrDefault(s => s.Id == serverId)? // srsly
.GetChannelsAsync() //wtf is this
.GetAwaiter() // oh i know, its the implementation detail
.GetResult() // and makes library look consistent
.FirstOrDefault(c => c.Id == channelId) // its not common sense to make library work like this.
as ITextChannel; // oh and don't forget to cast it to this arbitrary bullshit
}
internal void End()
{
//Ended = true;
WarState = WarState.Ended;
}
internal void Call(string u, int baseNumber)
{
if (baseNumber < 0 || baseNumber >= Bases.Length)
throw new ArgumentException("Invalid base number");
if (Bases[baseNumber] != null)
throw new ArgumentException("That base is already claimed.");
for (var i = 0; i < Bases.Length; i++)
{
if (Bases[i]?.BaseDestroyed == false && Bases[i]?.CallUser == u)
throw new ArgumentException($"@{u} You already claimed base #{i + 1}. You can't claim a new one.");
}
Bases[baseNumber] = new Caller(u.Trim(), DateTime.UtcNow, false);
}
internal void Start()
{
if (WarState == WarState.Started)
throw new InvalidOperationException("War already started");
//if (Started)
// throw new InvalidOperationException();
//Started = true;
WarState = WarState.Started;
StartedAt = DateTime.UtcNow;
foreach (var b in Bases.Where(b => b != null))
{
b.ResetTime();
}
}
internal int Uncall(string user)
{
user = user.Trim();
for (var i = 0; i < Bases.Length; i++)
{
if (Bases[i]?.CallUser != user) continue;
Bases[i] = null;
return i;
}
throw new InvalidOperationException("You are not participating in that war.");
}
public string ShortPrint() =>
$"`{EnemyClan}` ({Size} v {Size})";
public override string ToString()
{
var sb = new StringBuilder();
sb.AppendLine($"🔰**WAR AGAINST `{EnemyClan}` ({Size} v {Size}) INFO:**");
if (WarState == WarState.Created)
sb.AppendLine("`not started`");
for (var i = 0; i < Bases.Length; i++)
{
if (Bases[i] == null)
{
sb.AppendLine($"`{i + 1}.` ❌*unclaimed*");
}
else
{
if (Bases[i].BaseDestroyed)
{
sb.AppendLine($"`{i + 1}.` ✅ `{Bases[i].CallUser}` {new string('⭐', Bases[i].Stars)}");
}
else
{
var left = (WarState == WarState.Started) ? callExpire - (DateTime.UtcNow - Bases[i].TimeAdded) : callExpire;
sb.AppendLine($"`{i + 1}.` ✅ `{Bases[i].CallUser}` {left.Hours}h {left.Minutes}m {left.Seconds}s left");
}
}
}
return sb.ToString();
}
internal int FinishClaim(string user, int stars = 3)
{
user = user.Trim();
for (var i = 0; i < Bases.Length; i++)
{
if (Bases[i]?.BaseDestroyed != false || Bases[i]?.CallUser != user) continue;
Bases[i].BaseDestroyed = true;
Bases[i].Stars = stars;
return i;
}
throw new InvalidOperationException($"@{user} You are either not participating in that war, or you already destroyed a base.");
}
}
}

View File

@@ -0,0 +1,289 @@
using Discord.Commands;
using NadekoBot.Classes.ClashOfClans;
using Newtonsoft.Json;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Discord;
using NadekoBot.Services;
using NadekoBot.Attributes;
namespace NadekoBot.Modules.ClashOfClans
{
[Module(",",AppendSpace = false)]
internal class ClashOfClansModule : DiscordModule
{
public static ConcurrentDictionary<ulong, List<ClashWar>> ClashWars { get; set; } = new ConcurrentDictionary<ulong, List<ClashWar>>();
private readonly object writeLock = new object();
public ClashOfClansModule(ILocalization loc, CommandService cmds, IBotConfiguration config, IDiscordClient client) : base(loc, cmds, config, client)
{
}
private static async Task CheckWar(TimeSpan callExpire, ClashWar war)
{
var Bases = war.Bases;
for (var i = 0; i < Bases.Length; i++)
{
if (Bases[i] == null) continue;
if (!Bases[i].BaseDestroyed && DateTime.UtcNow - Bases[i].TimeAdded >= callExpire)
{
await war.Channel.SendMessageAsync($"❗🔰**Claim from @{Bases[i].CallUser} for a war against {war.ShortPrint()} has expired.**").ConfigureAwait(false);
Bases[i] = null;
}
}
}
[LocalizedCommand, LocalizedDescription, LocalizedSummary]
[RequireContext(ContextType.Guild)]
public async Task CreateWar(IMessage imsg, int size, [Remainder] string enemyClan)
{
var channel = imsg.Channel as IGuildChannel;
if (!(imsg.Author as IGuildUser).GuildPermissions.ManageChannels)
return;
if (string.IsNullOrWhiteSpace(enemyClan))
return;
if (size < 10 || size > 50 || size % 5 != 0)
{
await imsg.Channel.SendMessageAsync("💢🔰 Not a Valid war size").ConfigureAwait(false);
return;
}
List<ClashWar> wars;
if (!ClashWars.TryGetValue(channel.Guild.Id, out wars))
{
wars = new List<ClashWar>();
if (!ClashWars.TryAdd(channel.Guild.Id, wars))
return;
}
var cw = new ClashWar(enemyClan, size, channel.Guild.Id, imsg.Channel.Id);
//cw.Start();
wars.Add(cw);
await imsg.Channel.SendMessageAsync($"❗🔰**CREATED CLAN WAR AGAINST {cw.ShortPrint()}**").ConfigureAwait(false);
}
[LocalizedCommand, LocalizedDescription, LocalizedSummary]
[RequireContext(ContextType.Guild)]
public async Task StartWar(IMessage imsg, [Remainder] string number)
{
var channel = imsg.Channel as IGuildChannel;
int num = 0;
int.TryParse(number, out num);
var warsInfo = GetWarInfo(imsg, num);
if (warsInfo == null)
{
await imsg.Channel.SendMessageAsync("💢🔰 **That war does not exist.**").ConfigureAwait(false);
return;
}
var war = warsInfo.Item1[warsInfo.Item2];
try
{
war.Start();
await imsg.Channel.SendMessageAsync($"🔰**STARTED WAR AGAINST {war.ShortPrint()}**").ConfigureAwait(false);
}
catch
{
await imsg.Channel.SendMessageAsync($"🔰**WAR AGAINST {war.ShortPrint()} HAS ALREADY STARTED**").ConfigureAwait(false);
}
}
[LocalizedCommand, LocalizedDescription, LocalizedSummary]
[RequireContext(ContextType.Guild)]
public async Task ListWar(IMessage imsg, [Remainder] string number)
{
var channel = imsg.Channel as IGuildChannel;
// if number is null, print all wars in a short way
if (string.IsNullOrWhiteSpace(number))
{
//check if there are any wars
List<ClashWar> wars = null;
ClashWars.TryGetValue(channel.Guild.Id, out wars);
if (wars == null || wars.Count == 0)
{
await imsg.Channel.SendMessageAsync("🔰 **No active wars.**").ConfigureAwait(false);
return;
}
var sb = new StringBuilder();
sb.AppendLine("🔰 **LIST OF ACTIVE WARS**");
sb.AppendLine("**-------------------------**");
for (var i = 0; i < wars.Count; i++)
{
sb.AppendLine($"**#{i + 1}.** `Enemy:` **{wars[i].EnemyClan}**");
sb.AppendLine($"\t\t`Size:` **{wars[i].Size} v {wars[i].Size}**");
sb.AppendLine("**-------------------------**");
}
await imsg.Channel.SendMessageAsync(sb.ToString()).ConfigureAwait(false);
return;
}
var num = 0;
int.TryParse(number, out num);
//if number is not null, print the war needed
var warsInfo = GetWarInfo(imsg, num);
if (warsInfo == null)
{
await imsg.Channel.SendMessageAsync("💢🔰 **That war does not exist.**").ConfigureAwait(false);
return;
}
await imsg.Channel.SendMessageAsync(warsInfo.Item1[warsInfo.Item2].ToString()).ConfigureAwait(false);
}
[LocalizedCommand, LocalizedDescription, LocalizedSummary]
[RequireContext(ContextType.Guild)]
public async Task Claim(IMessage imsg, int number, int baseNumber, [Remainder] string other_name)
{
var channel = imsg.Channel as IGuildChannel;
var warsInfo = GetWarInfo(imsg, number);
if (warsInfo == null || warsInfo.Item1.Count == 0)
{
await imsg.Channel.SendMessageAsync("💢🔰 **That war does not exist.**").ConfigureAwait(false);
return;
}
var usr =
string.IsNullOrWhiteSpace(other_name) ?
imsg.Author.Username :
other_name;
try
{
var war = warsInfo.Item1[warsInfo.Item2];
war.Call(usr, baseNumber - 1);
await imsg.Channel.SendMessageAsync($"🔰**{usr}** claimed a base #{baseNumber} for a war against {war.ShortPrint()}").ConfigureAwait(false);
}
catch (Exception ex)
{
await imsg.Channel.SendMessageAsync($"💢🔰 {ex.Message}").ConfigureAwait(false);
}
}
[LocalizedCommand, LocalizedDescription, LocalizedSummary]
[RequireContext(ContextType.Guild)]
public async Task ClaimFinish1(IMessage imsg, int number, int baseNumber, [Remainder] string other_name)
{
var channel = imsg.Channel as IGuildChannel;
await FinishClaim(imsg, number, baseNumber, other_name, 1);
}
[LocalizedCommand, LocalizedDescription, LocalizedSummary]
[RequireContext(ContextType.Guild)]
public async Task ClaimFinish2(IMessage imsg, int number, int baseNumber, [Remainder] string other_name)
{
var channel = imsg.Channel as IGuildChannel;
await FinishClaim(imsg, number, baseNumber, other_name, 2);
}
[LocalizedCommand, LocalizedDescription, LocalizedSummary]
[RequireContext(ContextType.Guild)]
public async Task ClaimFinish(IMessage imsg, int number, int baseNumber, [Remainder] string other_name)
{
var channel = imsg.Channel as IGuildChannel;
await FinishClaim(imsg, number, baseNumber, other_name);
}
[LocalizedCommand, LocalizedDescription, LocalizedSummary]
[RequireContext(ContextType.Guild)]
public async Task EndWar(IMessage imsg, int number)
{
var channel = imsg.Channel as IGuildChannel;
var warsInfo = GetWarInfo(imsg,number);
if (warsInfo == null)
{
await imsg.Channel.SendMessageAsync("💢🔰 That war does not exist.").ConfigureAwait(false);
return;
}
warsInfo.Item1[warsInfo.Item2].End();
await imsg.Channel.SendMessageAsync($"❗🔰**War against {warsInfo.Item1[warsInfo.Item2].ShortPrint()} ended.**").ConfigureAwait(false);
var size = warsInfo.Item1[warsInfo.Item2].Size;
warsInfo.Item1.RemoveAt(warsInfo.Item2);
}
[LocalizedCommand, LocalizedDescription, LocalizedSummary]
[RequireContext(ContextType.Guild)]
public async Task Unclaim(IMessage imsg, int number, [Remainder] string otherName)
{
var channel = imsg.Channel as IGuildChannel;
var warsInfo = GetWarInfo(imsg, number);
if (warsInfo == null || warsInfo.Item1.Count == 0)
{
await imsg.Channel.SendMessageAsync("💢🔰 **That war does not exist.**").ConfigureAwait(false);
return;
}
var usr =
string.IsNullOrWhiteSpace(otherName) ?
imsg.Author.Username :
otherName;
try
{
var war = warsInfo.Item1[warsInfo.Item2];
var baseNumber = war.Uncall(usr);
await imsg.Channel.SendMessageAsync($"🔰 @{usr} has **UNCLAIMED** a base #{baseNumber + 1} from a war against {war.ShortPrint()}").ConfigureAwait(false);
}
catch (Exception ex)
{
await imsg.Channel.SendMessageAsync($"💢🔰 {ex.Message}").ConfigureAwait(false);
}
}
private async Task FinishClaim(IMessage imsg, int number, int baseNumber, [Remainder] string other_name, int stars = 3)
{
var channel = imsg.Channel as IGuildChannel;
var warInfo = GetWarInfo(imsg, number);
if (warInfo == null || warInfo.Item1.Count == 0)
{
await imsg.Channel.SendMessageAsync("💢🔰 **That war does not exist.**").ConfigureAwait(false);
return;
}
var usr =
string.IsNullOrWhiteSpace(other_name) ?
imsg.Author.Username :
other_name;
var war = warInfo.Item1[warInfo.Item2];
try
{
var baseNum = war.FinishClaim(usr, stars);
await imsg.Channel.SendMessageAsync($"❗🔰{imsg.Author.Mention} **DESTROYED** a base #{baseNum + 1} in a war against {war.ShortPrint()}").ConfigureAwait(false);
}
catch (Exception ex)
{
await imsg.Channel.SendMessageAsync($"💢🔰 {ex.Message}").ConfigureAwait(false);
}
}
private static Tuple<List<ClashWar>, int> GetWarInfo(IMessage imsg, int num)
{
var channel = imsg.Channel as IGuildChannel;
//check if there are any wars
List<ClashWar> wars = null;
ClashWars.TryGetValue(channel.Guild.Id, out wars);
if (wars == null || wars.Count == 0)
{
return null;
}
// get the number of the war
else if (num < 1 || num > wars.Count)
{
return null;
}
num -= 1;
//get the actual war
return new Tuple<List<ClashWar>, int>(wars, num);
}
}
}

View File

@@ -0,0 +1,26 @@
using Discord;
using Discord.Commands;
using NadekoBot.Services;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace NadekoBot.Modules
{
public class DiscordModule
{
protected ILocalization _l;
protected CommandService _commands;
protected IBotConfiguration _config;
protected IDiscordClient _client;
public DiscordModule(ILocalization loc, CommandService cmds, IBotConfiguration config,IDiscordClient client)
{
_l = loc;
_commands = cmds;
_config = config;
_client = client;
}
}
}

View File

@@ -0,0 +1,237 @@
using Discord;
using Discord.Commands;
using NadekoBot.Attributes;
using Newtonsoft.Json.Linq;
using System;
using System.Linq;
using System.Threading.Tasks;
using NadekoBot.Services;
using System.Net.Http;
using System.Text.RegularExpressions;
namespace NadekoBot.Modules.NSFW
{
[Module("~", AppendSpace = false)]
public class NSFWModule : DiscordModule
{
private readonly Random rng = new Random();
public NSFWModule(ILocalization loc, CommandService cmds, IBotConfiguration config, IDiscordClient client) : base(loc, cmds, config, client)
{
}
[LocalizedCommand, LocalizedDescription, LocalizedSummary]
[RequireContext(ContextType.Guild)]
public async Task Hentai(IMessage imsg, [Remainder] string tag)
{
var channel = imsg.Channel as IGuildChannel;
tag = tag?.Trim() ?? "";
var links = await Task.WhenAll(GetGelbooruImageLink("rating%3Aexplicit+" + tag), GetDanbooruImageLink("rating%3Aexplicit+" + tag)).ConfigureAwait(false);
if (links.All(l => l == null))
{
await imsg.Channel.SendMessageAsync("`No results.`");
return;
}
await imsg.Channel.SendMessageAsync(String.Join("\n\n", links)).ConfigureAwait(false);
}
[LocalizedCommand, LocalizedDescription, LocalizedSummary]
[RequireContext(ContextType.Guild)]
public async Task Danbooru(IMessage imsg, [Remainder] string tag)
{
var channel = imsg.Channel as IGuildChannel;
tag = tag?.Trim() ?? "";
var link = await GetDanbooruImageLink(tag).ConfigureAwait(false);
if (string.IsNullOrWhiteSpace(link))
await imsg.Channel.SendMessageAsync("Search yielded no results ;(");
else
await imsg.Channel.SendMessageAsync(link).ConfigureAwait(false);
}
[LocalizedCommand, LocalizedDescription, LocalizedSummary]
[RequireContext(ContextType.Guild)]
public async Task Gelbooru(IMessage imsg, [Remainder] string tag)
{
var channel = imsg.Channel as IGuildChannel;
tag = tag?.Trim() ?? "";
var link = await GetRule34ImageLink(tag).ConfigureAwait(false);
if (string.IsNullOrWhiteSpace(link))
await imsg.Channel.SendMessageAsync("Search yielded no results ;(");
else
await imsg.Channel.SendMessageAsync(link).ConfigureAwait(false);
}
[LocalizedCommand, LocalizedDescription, LocalizedSummary]
[RequireContext(ContextType.Guild)]
public async Task Rule34(IMessage imsg, [Remainder] string tag)
{
var channel = imsg.Channel as IGuildChannel;
tag = tag?.Trim() ?? "";
var link = await GetGelbooruImageLink(tag).ConfigureAwait(false);
if (string.IsNullOrWhiteSpace(link))
await imsg.Channel.SendMessageAsync("Search yielded no results ;(");
else
await imsg.Channel.SendMessageAsync(link).ConfigureAwait(false);
}
[LocalizedCommand, LocalizedDescription, LocalizedSummary]
[RequireContext(ContextType.Guild)]
public async Task E621(IMessage imsg, [Remainder] string tag)
{
var channel = imsg.Channel as IGuildChannel;
tag = tag?.Trim() ?? "";
var link = await GetE621ImageLink(tag).ConfigureAwait(false);
if (string.IsNullOrWhiteSpace(link))
await imsg.Channel.SendMessageAsync("Search yielded no results ;(");
else
await imsg.Channel.SendMessageAsync(link).ConfigureAwait(false);
}
[LocalizedCommand, LocalizedDescription, LocalizedSummary]
[RequireContext(ContextType.Guild)]
public async Task Cp(IMessage imsg)
{
var channel = imsg.Channel as IGuildChannel;
await imsg.Channel.SendMessageAsync("http://i.imgur.com/MZkY1md.jpg").ConfigureAwait(false);
}
[LocalizedCommand, LocalizedDescription, LocalizedSummary]
[RequireContext(ContextType.Guild)]
public async Task Boobs(IMessage imsg)
{
var channel = imsg.Channel as IGuildChannel;
try
{
JToken obj;
using (var http = new HttpClient())
{
obj = JArray.Parse(await http.GetStringAsync($"http://api.oboobs.ru/boobs/{rng.Next(0, 9380)}").ConfigureAwait(false))[0];
}
await imsg.Channel.SendMessageAsync($"http://media.oboobs.ru/{ obj["preview"].ToString() }").ConfigureAwait(false);
}
catch (Exception ex)
{
await imsg.Channel.SendMessageAsync($"💢 {ex.Message}").ConfigureAwait(false);
}
}
[LocalizedCommand, LocalizedDescription, LocalizedSummary]
[RequireContext(ContextType.Guild)]
public async Task Butts(IMessage imsg)
{
var channel = imsg.Channel as IGuildChannel;
try
{
JToken obj;
using (var http = new HttpClient())
{
obj = JArray.Parse(await http.GetStringAsync($"http://api.obutts.ru/butts/{rng.Next(0, 3373)}").ConfigureAwait(false))[0];
}
await imsg.Channel.SendMessageAsync($"http://media.obutts.ru/{ obj["preview"].ToString() }").ConfigureAwait(false);
}
catch (Exception ex)
{
await imsg.Channel.SendMessageAsync($"💢 {ex.Message}").ConfigureAwait(false);
}
}
public static async Task<string> GetDanbooruImageLink(string tag)
{
var rng = new Random();
if (tag == "loli") //loli doesn't work for some reason atm
tag = "flat_chest";
var link = $"http://danbooru.donmai.us/posts?" +
$"page={rng.Next(0, 15)}";
if (!string.IsNullOrWhiteSpace(tag))
link += $"&tags={tag.Replace(" ", "_")}";
using (var http = new HttpClient())
{
var webpage = await http.GetStringAsync(link).ConfigureAwait(false);
var matches = Regex.Matches(webpage, "data-large-file-url=\"(?<id>.*?)\"");
if (matches.Count == 0)
return null;
return $"http://danbooru.donmai.us" +
$"{matches[rng.Next(0, matches.Count)].Groups["id"].Value}";
}
}
public static async Task<string> GetGelbooruImageLink(string tag)
{
var headers = new Dictionary<string, string>() {
{"User-Agent", "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/14.0.835.202 Safari/535.1"},
{"Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8" },
};
var url =
$"http://gelbooru.com/index.php?page=dapi&s=post&q=index&limit=100&tags={tag.Replace(" ", "_")}";
var webpage = await GetResponseStringAsync(url, headers).ConfigureAwait(false);
var matches = Regex.Matches(webpage, "file_url=\"(?<url>.*?)\"");
if (matches.Count == 0)
return null;
var rng = new Random();
var match = matches[rng.Next(0, matches.Count)];
return matches[rng.Next(0, matches.Count)].Groups["url"].Value;
}
public static async Task<string> GetSafebooruImageLink(string tag)
{
var rng = new Random();
var url =
$"http://safebooru.org/index.php?page=dapi&s=post&q=index&limit=100&tags={tag.Replace(" ", "_")}";
var webpage = await GetResponseStringAsync(url).ConfigureAwait(false);
var matches = Regex.Matches(webpage, "file_url=\"(?<url>.*?)\"");
if (matches.Count == 0)
return null;
var match = matches[rng.Next(0, matches.Count)];
return matches[rng.Next(0, matches.Count)].Groups["url"].Value;
}
public static async Task<string> GetRule34ImageLink(string tag)
{
var rng = new Random();
var url =
$"http://rule34.xxx/index.php?page=dapi&s=post&q=index&limit=100&tags={tag.Replace(" ", "_")}";
var webpage = await GetResponseStringAsync(url).ConfigureAwait(false);
var matches = Regex.Matches(webpage, "file_url=\"(?<url>.*?)\"");
if (matches.Count == 0)
return null;
var match = matches[rng.Next(0, matches.Count)];
return "http:" + matches[rng.Next(0, matches.Count)].Groups["url"].Value;
}
internal static async Task<string> GetE621ImageLink(string tags)
{
try
{
var headers = new Dictionary<string, string>() {
{"User-Agent", "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/14.0.835.202 Safari/535.1"},
{"Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8" },
};
var data = await GetResponseStreamAsync(
"http://e621.net/post/index.xml?tags=" + Uri.EscapeUriString(tags) + "%20order:random&limit=1",
headers);
var doc = XDocument.Load(data);
return doc.Descendants("file_url").FirstOrDefault().Value;
}
catch (Exception ex)
{
Console.WriteLine("Error in e621 search: \n" + ex);
return "Error, do you have too many tags?";
}
}
}
}

View File

@@ -1,99 +1,86 @@
//using Discord;
//using Discord.Commands;
//using NadekoBot.Classes;
//using NadekoBot.Extensions;
//using System;
//using System.Linq;
//using System.Text;
using Discord;
using Discord.Commands;
using NadekoBot.Attributes;
using NadekoBot.Extensions;
using System;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
//namespace NadekoBot.Modules.Utility.Commands
//{
// class InfoCommands : DiscordCommand
// {
// public InfoCommands(DiscordModule module) : base(module)
// {
// }
namespace NadekoBot.Modules.Utility
{
partial class UtilityModule : DiscordModule
{
[LocalizedCommand, LocalizedDescription, LocalizedSummary]
[RequireContext(ContextType.Guild)]
public async Task ServerInfo(IMessage msg, string guild = null)
{
var channel = msg.Channel as IGuildChannel;
guild = guild?.ToUpperInvariant();
IGuild server;
if (guild == null)
server = channel.Guild;
else
server = (await _client.GetGuildsAsync()).Where(g => g.Name.ToUpperInvariant() == guild.ToUpperInvariant()).FirstOrDefault();
if (server == null)
return;
// internal override void Init(CommandGroupBuilder cgb)
// {
// cgb.CreateCommand(Module.Prefix + "serverinfo")
// .Alias(Module.Prefix + "sinfo")
// .Description($"Shows info about the server the bot is on. If no channel is supplied, it defaults to current one. |`{Module.Prefix}sinfo Some Server`")
// .Parameter("server", ParameterType.Optional)
// .Do(async e =>
// {
// var servText = e.GetArg("server")?.Trim();
// var server = string.IsNullOrWhiteSpace(servText)
// ? e.Server
// : NadekoBot.Client.FindServers(servText).FirstOrDefault();
// if (server == null)
// return;
// var createdAt = new DateTime(2015, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc).AddMilliseconds(server.Id >> 22);
// var sb = new StringBuilder();
// sb.AppendLine($"`Name:` **#{server.Name}**");
// sb.AppendLine($"`Owner:` **{server.Owner}**");
// sb.AppendLine($"`Id:` **{server.Id}**");
// sb.AppendLine($"`Icon Url:` **{await server.IconUrl.ShortenUrl().ConfigureAwait(false)}**");
// sb.AppendLine($"`TextChannels:` **{server.TextChannels.Count()}** `VoiceChannels:` **{server.VoiceChannels.Count()}**");
// sb.AppendLine($"`Members:` **{server.UserCount}** `Online:` **{server.Users.Count(u => u.Status == UserStatus.Online)}** (may be incorrect)");
// sb.AppendLine($"`Roles:` **{server.Roles.Count()}**");
// sb.AppendLine($"`Created At:` **{createdAt}**");
// if (server.CustomEmojis.Count() > 0)
// sb.AppendLine($"`Custom Emojis:` **{string.Join(", ", server.CustomEmojis)}**");
// if (server.Features.Count() > 0)
// sb.AppendLine($"`Features:` **{string.Join(", ", server.Features)}**");
// if (!string.IsNullOrWhiteSpace(server.SplashId))
// sb.AppendLine($"`Region:` **{server.Region.Name}**");
// await e.Channel.SendMessage(sb.ToString()).ConfigureAwait(false);
// });
var createdAt = new DateTime(2015, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc).AddMilliseconds(server.Id >> 22);
var sb = new StringBuilder();
var users = await server.GetUsersAsync();
sb.AppendLine($@"`Name:` **{server.Name}**
`Owner:` **{await server.GetUserAsync(server.OwnerId)}**
`Id:` **{server.Id}**
`Icon Url:` **{ server.IconUrl}**
`TextChannels:` **{(await server.GetTextChannelsAsync()).Count()}** `VoiceChannels:` **{(await server.GetVoiceChannelsAsync()).Count()}**
`Members:` **{users.Count}** `Online:` **{users.Count(u => u.Status == UserStatus.Online)}**
`Roles:` **{server.Roles.Count()}**
`Created At:` **{createdAt}**");
if (server.Emojis.Count() > 0)
sb.AppendLine($"`Custom Emojis:` **{string.Join(", ", server.Emojis)}**");
if (server.Features.Count() > 0)
sb.AppendLine($"`Features:` **{string.Join(", ", server.Features)}**");
if (!string.IsNullOrWhiteSpace(server.SplashUrl))
sb.AppendLine($"`Region:` **{server.VoiceRegionId}**");
await msg.Reply(sb.ToString()).ConfigureAwait(false);
}
// cgb.CreateCommand(Module.Prefix + "channelinfo")
// .Alias(Module.Prefix + "cinfo")
// .Description($"Shows info about the channel. If no channel is supplied, it defaults to current one. |`{Module.Prefix}cinfo #some-channel`")
// .Parameter("channel", ParameterType.Optional)
// .Do(async e =>
// {
// var chText = e.GetArg("channel")?.Trim();
// var ch = string.IsNullOrWhiteSpace(chText)
// ? e.Channel
// : e.Server.FindChannels(chText, Discord.ChannelType.Text).FirstOrDefault();
// if (ch == null)
// return;
// var createdAt = new DateTime(2015, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc).AddMilliseconds(ch.Id >> 22);
// var sb = new StringBuilder();
// sb.AppendLine($"`Name:` **#{ch.Name}**");
// sb.AppendLine($"`Id:` **{ch.Id}**");
// sb.AppendLine($"`Created At:` **{createdAt}**");
// sb.AppendLine($"`Topic:` **{ch.Topic}**");
// sb.AppendLine($"`Users:` **{ch.Users.Count()}**");
// await e.Channel.SendMessage(sb.ToString()).ConfigureAwait(false);
// });
[LocalizedCommand, LocalizedDescription, LocalizedSummary]
[RequireContext(ContextType.Guild)]
public async Task ChannelInfo(IMessage msg, ITextChannel channel = null)
{
var ch = channel ?? msg.Channel as ITextChannel;
if (ch == null)
return;
var createdAt = new DateTime(2015, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc).AddMilliseconds(ch.Id >> 22);
var sb = new StringBuilder();
sb.AppendLine($"`Name:` **#{ch.Name}**");
sb.AppendLine($"`Id:` **{ch.Id}**");
sb.AppendLine($"`Created At:` **{createdAt}**");
sb.AppendLine($"`Topic:` **{ch.Topic}**");
sb.AppendLine($"`Users:` **{(await ch.GetUsersAsync()).Count()}**");
await msg.Reply(sb.ToString()).ConfigureAwait(false);
}
// cgb.CreateCommand(Module.Prefix + "userinfo")
// .Alias(Module.Prefix + "uinfo")
// .Description($"Shows info about the user. If no user is supplied, it defaults a user running the command. |`{Module.Prefix}uinfo @SomeUser`")
// .Parameter("user", ParameterType.Optional)
// .Do(async e =>
// {
// var userText = e.GetArg("user")?.Trim();
// var user = string.IsNullOrWhiteSpace(userText)
// ? e.User
// : e.Server.FindUsers(userText).FirstOrDefault();
// if (user == null)
// return;
// var sb = new StringBuilder();
// sb.AppendLine($"`Name#Discrim:` **#{user.Name}#{user.Discriminator}**");
// if (!string.IsNullOrWhiteSpace(user.Nickname))
// sb.AppendLine($"`Nickname:` **{user.Nickname}**");
// sb.AppendLine($"`Id:` **{user.Id}**");
// sb.AppendLine($"`Current Game:` **{(user.CurrentGame?.Name == null ? "-" : user.CurrentGame.Value.Name)}**");
// if (user.LastOnlineAt != null)
// sb.AppendLine($"`Last Online:` **{user.LastOnlineAt:HH:mm:ss}**");
// sb.AppendLine($"`Joined At:` **{user.JoinedAt}**");
// sb.AppendLine($"`Roles:` **({user.Roles.Count()}) - {string.Join(", ", user.Roles.Select(r => r.Name))}**");
// sb.AppendLine($"`AvatarUrl:` **{await user.AvatarUrl.ShortenUrl().ConfigureAwait(false)}**");
// await e.Channel.SendMessage(sb.ToString()).ConfigureAwait(false);
// });
// }
// }
//}
[LocalizedCommand, LocalizedDescription, LocalizedSummary]
[RequireContext(ContextType.Guild)]
public async Task UserInfo(IMessage msg, IGuildUser usr = null)
{
var channel = msg.Channel as IGuildChannel;
var user = usr ?? msg.Author as IGuildUser;
if (user == null)
return;
var sb = new StringBuilder();
sb.AppendLine($"`Name#Discrim:` **#{user.Username}#{user.Discriminator}**");
if (!string.IsNullOrWhiteSpace(user.Nickname))
sb.AppendLine($"`Nickname:` **{user.Nickname}**");
sb.AppendLine($"`Id:` **{user.Id}**");
sb.AppendLine($"`Current Game:` **{(user.Game?.Name == null ? "-" : user.Game.Name)}**");
sb.AppendLine($"`Joined At:` **{user.JoinedAt}**");
sb.AppendLine($"`Roles:` **({user.Roles.Count()}) - {string.Join(", ", user.Roles.Select(r => r.Name))}**");
sb.AppendLine($"`AvatarUrl:` **{user.AvatarUrl}**");
await msg.Reply(sb.ToString()).ConfigureAwait(false);
}
}
}

View File

@@ -113,7 +113,7 @@
// if (ch == null)
// {
// await e.Channel.SendMessage($"{e.User.Mention} Something went wrong (channel cannot be found) ;(").ConfigureAwait(false);
// await channel.SendMessageAsync($"{e.User.Mention} Something went wrong (channel cannot be found) ;(").ConfigureAwait(false);
// return;
// }
@@ -123,7 +123,7 @@
// if (m.Length == 0)
// {
// await e.Channel.SendMessage("Not a valid time format blablabla").ConfigureAwait(false);
// await channel.SendMessageAsync("Not a valid time format blablabla").ConfigureAwait(false);
// return;
// }
@@ -148,7 +148,7 @@
// (groupName == "hours" && value > 23) ||
// (groupName == "minutes" && value > 59))
// {
// await e.Channel.SendMessage($"Invalid {groupName} value.").ConfigureAwait(false);
// await channel.SendMessageAsync($"Invalid {groupName} value.").ConfigureAwait(false);
// return;
// }
// else
@@ -175,7 +175,7 @@
// reminders.Add(StartNewReminder(rem));
// await e.Channel.SendMessage($"⏰ I will remind \"{ch.Name}\" to \"{e.GetArg("message").ToString()}\" in {output}. ({time:d.M.yyyy.} at {time:HH:mm})").ConfigureAwait(false);
// await channel.SendMessageAsync($"⏰ I will remind \"{ch.Name}\" to \"{e.GetArg("message").ToString()}\" in {output}. ({time:d.M.yyyy.} at {time:HH:mm})").ConfigureAwait(false);
// });
// cgb.CreateCommand(Module.Prefix + "remindmsg")
// .Description("Sets message for when the remind is triggered. " +
@@ -190,7 +190,7 @@
// return;
// NadekoBot.Config.RemindMessageFormat = arg;
// await e.Channel.SendMessage("`New remind message set.`");
// await channel.SendMessageAsync("`New remind message set.`");
// });
// }
// }

View File

@@ -4,16 +4,24 @@ using NadekoBot.Attributes;
using System;
using System.Linq;
using System.Threading.Tasks;
using NadekoBot.Services;
using System.Text;
using NadekoBot.Extensions;
using System.Text.RegularExpressions;
using System.Collections.Generic;
using System.Reflection;
namespace NadekoBot.Modules.Utility
{
[Module(".", AppendSpace = false)]
public class UtilityModule
public partial class UtilityModule : DiscordModule
{
[LocalizedCommand]
[LocalizedDescription]
[LocalizedSummary]
public UtilityModule(ILocalization loc, CommandService cmds, IBotConfiguration config, IDiscordClient client) : base(loc, cmds, config, client)
{
}
[LocalizedCommand, LocalizedDescription, LocalizedSummary]
[RequireContext(ContextType.Guild)]
public async Task WhoPlays(IMessage imsg, [Remainder] string game)
{
@@ -22,154 +30,161 @@ namespace NadekoBot.Modules.Utility
if (string.IsNullOrWhiteSpace(game))
return;
var arr = (await chnl.Guild.GetUsersAsync())
.Where(u => u.Game?.Name.ToUpperInvariant() == game)
.Where(u => u.Game?.Name?.ToUpperInvariant() == game)
.Select(u => u.Username)
.ToList();
int i = 0;
if (!arr.Any())
await imsg.Channel.SendMessageAsync("`Noone is playing that game.`").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync(_l["`Nobody is playing that game.`"]).ConfigureAwait(false);
else
await imsg.Channel.SendMessageAsync("```xl\n" + string.Join("\n", arr.GroupBy(item => (i++) / 3).Select(ig => string.Concat(ig.Select(el => $"• {el,-35}")))) + "\n```").ConfigureAwait(false);
}
[LocalizedCommand]
[LocalizedDescription]
[LocalizedSummary]
[LocalizedCommand, LocalizedDescription, LocalizedSummary]
[RequireContext(ContextType.Guild)]
public async Task InRole(IMessage imsg, [Remainder] string roles) {
public async Task InRole(IMessage imsg, [Remainder] string roles)
{
if (string.IsNullOrWhiteSpace(roles))
return;
var channel = imsg.Channel as IGuildChannel;
var arg = roles.Split(',').Select(r => r.Trim().ToUpperInvariant());
string send = $"`Here is a list of users in a specfic role:`";
string send = _l["`Here is a list of users in a specfic role:`"];
foreach (var roleStr in arg.Where(str => !string.IsNullOrWhiteSpace(str) && str != "@EVERYONE" && str != "EVERYONE"))
{
var role = channel.Guild.Roles.Where(r => r.Name.ToUpperInvariant() == roleStr).FirstOrDefault();
if (role == null) continue;
send += $"\n`{role.Name}`\n";
send += string.Join(", ", (await channel.Guild.GetUsersAsync()).Where(u=>u.Roles.Contains(role)).Select(u => u.ToString()));
send += string.Join(", ", (await channel.Guild.GetUsersAsync()).Where(u => u.Roles.Contains(role)).Select(u => u.ToString()));
}
//todo
//while (send.Length > 2000)
//{
// if (!)
// {
// await e.Channel.SendMessage($"{e.User.Mention} you are not allowed to use this command on roles with a lot of users in them to prevent abuse.");
// return;
// }
// var curstr = send.Substring(0, 2000);
// await imsg.Channel.SendMessageAsync(curstr.Substring(0,
// curstr.LastIndexOf(", ", StringComparison.Ordinal) + 1)).ConfigureAwait(false);
// send = curstr.Substring(curstr.LastIndexOf(", ", StringComparison.Ordinal) + 1) +
// send.Substring(2000);
//}
//await e.Channel.Send(send).ConfigureAwait(false);
var usr = imsg.Author as IGuildUser;
while (send.Length > 2000)
{
if (!usr.GetPermissions(channel).ManageMessages)
{
await imsg.Channel.SendMessageAsync($"{usr.Mention} you are not allowed to use this command on roles with a lot of users in them to prevent abuse.");
return;
}
var curstr = send.Substring(0, 2000);
await imsg.Channel.SendMessageAsync(curstr.Substring(0,
curstr.LastIndexOf(", ", StringComparison.Ordinal) + 1)).ConfigureAwait(false);
send = curstr.Substring(curstr.LastIndexOf(", ", StringComparison.Ordinal) + 1) +
send.Substring(2000);
}
await imsg.Channel.SendMessageAsync(send).ConfigureAwait(false);
}
[LocalizedCommand, LocalizedDescription, LocalizedSummary]
[RequireContext(ContextType.Guild)]
public async Task CheckMyPerms(IMessage msg)
{
StringBuilder builder = new StringBuilder("```\n");
var user = msg.Author as IGuildUser;
var perms = user.GetPermissions(msg.Channel as ITextChannel);
foreach (var p in perms.GetType().GetProperties().Where(p => !p.GetGetMethod().GetParameters().Any()))
{
builder.AppendLine($"{p.Name} : {p.GetValue(perms, null).ToString()}");
}
builder.Append("```");
await msg.Reply(builder.ToString());
}
[LocalizedCommand, LocalizedDescription, LocalizedSummary]
[RequireContext(ContextType.Guild)]
public async Task UserId(IMessage msg, IGuildUser target = null)
{
var usr = target ?? msg.Author;
await msg.Reply($"Id of the user { usr.Username } is { usr.Id })");
}
[LocalizedCommand, LocalizedDescription, LocalizedSummary]
public async Task ChannelId(IMessage msg)
{
await msg.Reply($"This Channel's ID is {msg.Channel.Id}");
}
[LocalizedCommand, LocalizedDescription, LocalizedSummary]
[RequireContext(ContextType.Guild)]
public async Task ServerId(IMessage msg)
{
await msg.Reply($"This server's ID is {(msg.Channel as IGuildChannel).Guild.Id}");
}
[LocalizedCommand, LocalizedDescription, LocalizedSummary]
[RequireContext(ContextType.Guild)]
public async Task Roles(IMessage msg, IGuildUser target = null)
{
var guild = (msg.Channel as IGuildChannel).Guild;
if (target != null)
{
await msg.Reply($"`List of roles for **{target.Username}**:` \n• " + string.Join("\n• ", target.Roles.Except(new[] { guild.EveryoneRole })));
}
else
{
await msg.Reply("`List of roles:` \n• " + string.Join("\n• ", (msg.Channel as IGuildChannel).Guild.Roles.Except(new[] { guild.EveryoneRole })));
}
}
[LocalizedCommand, LocalizedDescription, LocalizedSummary]
[RequireContext(ContextType.Guild)]
public async Task Prune(IMessage msg, [Remainder] string target = null)
{
var channel = msg.Channel as IGuildChannel;
var user = await channel.Guild.GetCurrentUserAsync();
if (string.IsNullOrWhiteSpace(target))
{
var enumerable = (await msg.Channel.GetMessagesAsync(limit: 100)).Where(x => x.Author.Id == user.Id);
await msg.Channel.DeleteMessagesAsync(enumerable);
return;
}
target = target.Trim();
if (!user.GetPermissions(channel).ManageMessages)
{
await msg.Reply("Don't have permissions to manage messages in channel");
return;
}
int count;
if (int.TryParse(target, out count))
{
while (count > 0)
{
int limit = (count < 100) ? count : 100;
var enumerable = (await msg.Channel.GetMessagesAsync(limit: limit));
await msg.Channel.DeleteMessagesAsync(enumerable);
if (enumerable.Count < limit) break;
count -= limit;
}
}
else if (msg.MentionedUsers.Count > 0)
{
var toDel = new List<IMessage>();
var match = Regex.Match(target, @"\s(\d+)\s");
if (match.Success)
{
int.TryParse(match.Groups[1].Value, out count);
var messages = new List<IMessage>(count);
while (count > 0)
{
var toAdd = await msg.Channel.GetMessagesAsync(limit: count < 100 ? count : 100);
messages.AddRange(toAdd);
count -= toAdd.Count;
}
foreach (var mention in msg.MentionedUsers)
{
toDel.AddRange(messages.Where(m => m.Author.Id == mention.Id));
}
//TODO check if limit == 100 or there is no limit
await msg.Channel.DeleteMessagesAsync(toDel);
}
}
}
}
}
//public void Install()
//{
// manager.CreateCommands("", cgb =>
// {
// cgb.AddCheck(PermissionChecker.Instance);
// var client = manager.Client;
// commands.ForEach(cmd => cmd.Init(cgb));
// cgb.CreateCommand(Prefix + "whoplays")
// .Description()
// .Parameter("game", ParameterType.Unparsed)
// .Do(async e =>
// {
// });
// cgb.CreateCommand(Prefix + "checkmyperms")
// .Description($"Checks your userspecific permissions on this channel. | `{Prefix}checkmyperms`")
// .Do(async e =>
// {
// var output = "```\n";
// foreach (var p in e.User.ServerPermissions.GetType().GetProperties().Where(p => !p.GetGetMethod().GetParameters().Any()))
// {
// output += p.Name + ": " + p.GetValue(e.User.ServerPermissions, null).ToString() + "\n";
// }
// output += "```";
// await e.User.SendMessage(output).ConfigureAwait(false);
// });
// cgb.CreateCommand(Prefix + "stats")
// .Description($"Shows some basic stats for Nadeko. | `{Prefix}stats`")
// .Do(async e =>
// {
// await e.Channel.SendMessage(await NadekoStats.Instance.GetStats()).ConfigureAwait(false);
// });
// cgb.CreateCommand(Prefix + "dysyd")
// .Description($"Shows some basic stats for Nadeko. | `{Prefix}dysyd`")
// .Do(async e =>
// {
// await e.Channel.SendMessage((await NadekoStats.Instance.GetStats()).Matrix().TrimTo(1990)).ConfigureAwait(false);
// });
// cgb.CreateCommand(Prefix + "userid").Alias(Prefix + "uid")
// .Description($"Shows user ID. | `{Prefix}uid` or `{Prefix}uid \"@SomeGuy\"`")
// .Parameter("user", ParameterType.Unparsed)
// .Do(async e =>
// {
// var usr = e.User;
// if (!string.IsNullOrWhiteSpace(e.GetArg("user"))) usr = e.Channel.FindUsers(e.GetArg("user")).FirstOrDefault();
// if (usr == null)
// return;
// await e.Channel.SendMessage($"Id of the user { usr.Name } is { usr.Id }").ConfigureAwait(false);
// });
// cgb.CreateCommand(Prefix + "channelid").Alias(Prefix + "cid")
// .Description($"Shows current channel ID. | `{Prefix}cid`")
// .Do(async e => await e.Channel.SendMessage("This channel's ID is " + e.Channel.Id).ConfigureAwait(false));
// cgb.CreateCommand(Prefix + "serverid").Alias(Prefix + "sid")
// .Description($"Shows current server ID. | `{Prefix}sid`")
// .Do(async e => await e.Channel.SendMessage("This server's ID is " + e.Server.Id).ConfigureAwait(false));
// cgb.CreateCommand(Prefix + "roles")
// .Description("List all roles on this server or a single user if specified. | `{Prefix}roles`")
// .Parameter("user", ParameterType.Unparsed)
// .Do(async e =>
// {
// if (!string.IsNullOrWhiteSpace(e.GetArg("user")))
// {
// var usr = e.Server.FindUsers(e.GetArg("user")).FirstOrDefault();
// if (usr == null) return;
// await e.Channel.SendMessage($"`List of roles for **{usr.Name}**:` \n• " + string.Join("\n• ", usr.Roles)).ConfigureAwait(false);
// return;
// }
// await e.Channel.SendMessage("`List of roles:` \n• " + string.Join("\n• ", e.Server.Roles)).ConfigureAwait(false);
// });
// cgb.CreateCommand(Prefix + "channeltopic")
// .Alias(Prefix + "ct")
// .Description($"Sends current channel's topic as a message. | `{Prefix}ct`")
// .Do(async e =>
// {
// var topic = e.Channel.Topic;
// if (string.IsNullOrWhiteSpace(topic))
// return;
// await e.Channel.SendMessage(topic).ConfigureAwait(false);
// });
// });
// }
// }
//}