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

@ -10,7 +10,7 @@ namespace NadekoBot.Attributes
{ {
public class LocalizedCommandAttribute : CommandAttribute public class LocalizedCommandAttribute : CommandAttribute
{ {
public LocalizedCommandAttribute([CallerMemberName] string memberName="") : base(Localization.LoadString(memberName.ToLowerInvariant() + "_text")) public LocalizedCommandAttribute([CallerMemberName] string memberName="") : base(Localization.LoadCommandString(memberName.ToLowerInvariant() + "_text"))
{ {
} }

View File

@ -10,7 +10,7 @@ namespace NadekoBot.Attributes
{ {
public class LocalizedDescriptionAttribute : DescriptionAttribute public class LocalizedDescriptionAttribute : DescriptionAttribute
{ {
public LocalizedDescriptionAttribute([CallerMemberName] string memberName="") : base(Localization.LoadString(memberName.ToLowerInvariant()+"_description")) public LocalizedDescriptionAttribute([CallerMemberName] string memberName="") : base(Localization.LoadCommandString(memberName.ToLowerInvariant()+"_description"))
{ {
} }

View File

@ -10,7 +10,7 @@ namespace NadekoBot.Attributes
{ {
public class LocalizedSummaryAttribute : SummaryAttribute public class LocalizedSummaryAttribute : SummaryAttribute
{ {
public LocalizedSummaryAttribute([CallerMemberName] string memberName="") : base(Localization.LoadString(memberName.ToLowerInvariant() + "_summary")) public LocalizedSummaryAttribute([CallerMemberName] string memberName="") : base(Localization.LoadCommandString(memberName.ToLowerInvariant() + "_summary"))
{ {
} }

View File

@ -1,378 +0,0 @@
using Discord;
using Discord.Commands;
using NadekoBot.Classes;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
namespace NadekoBot.Extensions
{
public static class Extensions
{
private static Random rng = new Random();
public static string Scramble(this string word)
{
var letters = word.ToArray();
var count = 0;
for (var i = 0; i < letters.Length; i++)
{
if (letters[i] == ' ')
continue;
count++;
if (count <= letters.Length / 5)
continue;
if (count % 3 == 0)
continue;
if (letters[i] != ' ')
letters[i] = '_';
}
return "`" + string.Join(" ", letters) + "`";
}
public static string TrimTo(this string str, int num, bool hideDots = false)
{
if (num < 0)
throw new ArgumentOutOfRangeException(nameof(num), "TrimTo argument cannot be less than 0");
if (num == 0)
return string.Empty;
if (num <= 3)
return string.Concat(str.Select(c => '.'));
if (str.Length < num)
return str;
return string.Concat(str.Take(num - 3)) + (hideDots ? "" : "...");
}
/// <summary>
/// Removes trailing S or ES (if specified) on the given string if the num is 1
/// </summary>
/// <param name="str"></param>
/// <param name="num"></param>
/// <param name="es"></param>
/// <returns>String with the correct singular/plural form</returns>
public static string SnPl(this string str, int? num, bool es = false)
{
if (str == null)
throw new ArgumentNullException(nameof(str));
if (num == null)
throw new ArgumentNullException(nameof(num));
return num == 1 ? str.Remove(str.Length - 1, es ? 2 : 1) : str;
}
/// <summary>
/// Sends a message to the channel from which this command is called.
/// </summary>
/// <param name="e">EventArg</param>
/// <param name="message">Message to be sent</param>
/// <returns></returns>
public static async Task<Message> Send(this CommandEventArgs e, string message)
=> await e.Channel.SendMessage(message).ConfigureAwait(false);
/// <summary>
/// Sends a message to the channel from which MessageEventArg came.
/// </summary>
/// <param name="e">EventArg</param>
/// <param name="message">Message to be sent</param>
/// <returns></returns>
public static async Task Send(this MessageEventArgs e, string message)
{
if (string.IsNullOrWhiteSpace(message))
return;
await e.Channel.SendMessage(message).ConfigureAwait(false);
}
/// <summary>
/// Sends a message to this channel.
/// </summary>
/// <param name="c"></param>
/// <param name="message"></param>
/// <returns></returns>
public static async Task Send(this Channel c, string message)
{
await c.SendMessage(message).ConfigureAwait(false);
}
/// <summary>
/// Sends a private message to this user.
/// </summary>
/// <param name="c"></param>
/// <param name="message"></param>
/// <returns></returns>
public static async Task Send(this User u, string message)
{
await u.SendMessage(message).ConfigureAwait(false);
}
/// <summary>
/// Replies to a user who invoked this command, message start with that user's mention.
/// </summary>
/// <param name="e"></param>
/// <param name="message"></param>
/// <returns></returns>
public static async Task Reply(this CommandEventArgs e, string message)
{
await e.Channel.SendMessage(e.User.Mention + " " + message).ConfigureAwait(false);
}
/// <summary>
/// Replies to a user who invoked this command, message start with that user's mention.
/// </summary>
/// <param name="e"></param>
/// <param name="message"></param>
/// <returns></returns>
public static async Task Reply(this MessageEventArgs e, string message)
{
await e.Channel.SendMessage(e.User.Mention + " " + message).ConfigureAwait(false);
}
/// <summary>
/// Randomizes element order in a list
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="list"></param>
public static IList<T> Shuffle<T>(this IList<T> list)
{
// Thanks to @Joe4Evr for finding a bug in the old version of the shuffle
var provider = new RNGCryptoServiceProvider();
var n = list.Count;
while (n > 1)
{
var box = new byte[(n / Byte.MaxValue) + 1];
int boxSum;
do
{
provider.GetBytes(box);
boxSum = box.Sum(b => b);
}
while (!(boxSum < n * ((Byte.MaxValue * box.Length) / n)));
var k = (boxSum % n);
n--;
var value = list[k];
list[k] = list[n];
list[n] = value;
}
return list;
}
/// <summary>
/// Shortens a string URL
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="source"></param>
/// <param name="action"></param>
public static async Task<string> ShortenUrl(this string str)
{
try
{
var result = await SearchHelper.ShortenUrl(str).ConfigureAwait(false);
return result;
}
catch (WebException ex)
{
throw new InvalidOperationException("You must enable URL shortner in google developers console.", ex);
}
}
public static string GetOnPage<T>(this IEnumerable<T> source, int pageIndex, int itemsPerPage = 5)
{
var items = source.Skip(pageIndex * itemsPerPage).Take(itemsPerPage);
if (!items.Any())
{
return $"No items on page {pageIndex + 1}.";
}
var sb = new StringBuilder($"---page {pageIndex + 1} --\n");
var itemsDC = items as IEnumerable<KeyValuePair<string, IEnumerable<string>>>;
var itemsDS = items as IEnumerable<KeyValuePair<string, string>>;
if (itemsDC != null)
{
foreach (var item in itemsDC)
{
sb.Append($"{ Format.Code(item.Key)}\n");
int i = 1;
var last = item.Value.Last();
foreach (var value in item.Value)
{
if (last != value)
sb.AppendLine(" `├" + i++ + "─`" + Format.Bold(value));
else
sb.AppendLine(" `└" + i++ + "─`" + Format.Bold(value));
}
}
}
else if (itemsDS != null)
{
foreach (var item in itemsDS)
{
sb.Append($"{ Format.Code(item.Key)}\n");
sb.AppendLine(" `└─`" + Format.Bold(item.Value));
}
}
else
{
foreach (var item in items)
{
sb.Append($"{ Format.Code(item.ToString())} \n");
}
}
return sb.ToString();
}
/// <summary>
/// Gets the program runtime
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="source"></param>
/// <param name="action"></param>
public static string GetRuntime(this DiscordClient c) => ".Net Framework 4.5.2";
public static string Matrix(this string s)
=>
string.Concat(s.Select(c => c.ToString() + " ̵̢̬̜͉̞̭̖̰͋̉̎ͬ̔̇̌̀".TrimTo(rng.Next(0, 12), true)));
//.Replace("`", "");
public static void ForEach<T>(this IEnumerable<T> source, Action<T> action)
{
foreach (var element in source)
{
action(element);
}
}
//http://www.dotnetperls.com/levenshtein
public static int LevenshteinDistance(this string s, string t)
{
var n = s.Length;
var m = t.Length;
var d = new int[n + 1, m + 1];
// Step 1
if (n == 0)
{
return m;
}
if (m == 0)
{
return n;
}
// Step 2
for (var i = 0; i <= n; d[i, 0] = i++)
{
}
for (var j = 0; j <= m; d[0, j] = j++)
{
}
// Step 3
for (var i = 1; i <= n; i++)
{
//Step 4
for (var j = 1; j <= m; j++)
{
// Step 5
var cost = (t[j - 1] == s[i - 1]) ? 0 : 1;
// Step 6
d[i, j] = Math.Min(
Math.Min(d[i - 1, j] + 1, d[i, j - 1] + 1),
d[i - 1, j - 1] + cost);
}
}
// Step 7
return d[n, m];
}
public static int KiB(this int value) => value * 1024;
public static int KB(this int value) => value * 1000;
public static int MiB(this int value) => value.KiB() * 1024;
public static int MB(this int value) => value.KB() * 1000;
public static int GiB(this int value) => value.MiB() * 1024;
public static int GB(this int value) => value.MB() * 1000;
public static ulong KiB(this ulong value) => value * 1024;
public static ulong KB(this ulong value) => value * 1000;
public static ulong MiB(this ulong value) => value.KiB() * 1024;
public static ulong MB(this ulong value) => value.KB() * 1000;
public static ulong GiB(this ulong value) => value.MiB() * 1024;
public static ulong GB(this ulong value) => value.MB() * 1000;
public static Stream ToStream(this Image img, System.Drawing.Imaging.ImageFormat format = null)
{
if (format == null)
format = System.Drawing.Imaging.ImageFormat.Jpeg;
var stream = new MemoryStream();
img.Save(stream, format);
stream.Position = 0;
return stream;
}
/// <summary>
/// Merges Images into 1 Image and returns a bitmap.
/// </summary>
/// <param name="images">The Images you want to merge.</param>
/// <returns>Merged bitmap</returns>
public static Bitmap Merge(this IEnumerable<Image> images, int reverseScaleFactor = 1)
{
var imageArray = images as Image[] ?? images.ToArray();
if (!imageArray.Any()) return null;
var width = imageArray.Sum(i => i.Width);
var height = imageArray.First().Height;
var bitmap = new Bitmap(width / reverseScaleFactor, height / reverseScaleFactor);
var r = new Random();
var offsetx = 0;
foreach (var img in imageArray)
{
var bm = new Bitmap(img);
for (var w = 0; w < img.Width; w++)
{
for (var h = 0; h < bitmap.Height; h++)
{
bitmap.SetPixel(w / reverseScaleFactor + offsetx, h, bm.GetPixel(w, h * reverseScaleFactor));
}
}
offsetx += img.Width / reverseScaleFactor;
}
return bitmap;
}
/// <summary>
/// Merges Images into 1 Image and returns a bitmap asynchronously.
/// </summary>
/// <param name="images">The Images you want to merge.</param>
/// <param name="reverseScaleFactor"></param>
/// <returns>Merged bitmap</returns>
public static async Task<Bitmap> MergeAsync(this IEnumerable<Image> images, int reverseScaleFactor = 1) =>
await Task.Run(() => images.Merge(reverseScaleFactor)).ConfigureAwait(false);
public static string Unmention(this string str) => str.Replace("@", "ම");
public static Stream ToStream(this string str)
{
var sw = new StreamWriter(new MemoryStream());
sw.Write(str);
sw.Flush();
sw.BaseStream.Position = 0;
return sw.BaseStream;
}
public static double UnixTimestamp(this DateTime dt) => dt.ToUniversalTime().Subtract(new DateTime(1970, 1, 1)).TotalSeconds;
}
}

View File

@ -251,91 +251,7 @@ namespace NadekoBot.Classes
} }
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(" ", "_")}";
var webpage = await GetResponseStringAsync(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?";
}
}
public static async Task<string> ShortenUrl(string url) public static async Task<string> ShortenUrl(string url)
{ {

View File

@ -1,4 +1,5 @@
using Newtonsoft.Json; using Discord;
using Newtonsoft.Json;
using System; using System;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
@ -14,7 +15,7 @@ namespace NadekoBot.Classes.ClashOfClans
{ {
Started, Ended, Created Started, Ended, Created
} }
[System.Serializable]
internal class Caller internal class Caller
{ {
public string CallUser { get; set; } public string CallUser { get; set; }
@ -62,7 +63,7 @@ namespace NadekoBot.Classes.ClashOfClans
public ulong ChannelId { get; set; } public ulong ChannelId { get; set; }
[JsonIgnore] [JsonIgnore]
public Discord.Channel Channel { get; internal set; } public ITextChannel Channel { get; internal set; }
/// <summary> /// <summary>
/// This init is purely for the deserialization /// This init is purely for the deserialization
@ -76,7 +77,15 @@ namespace NadekoBot.Classes.ClashOfClans
this.Bases = new Caller[size]; this.Bases = new Caller[size];
this.ServerId = serverId; this.ServerId = serverId;
this.ChannelId = channelId; this.ChannelId = channelId;
this.Channel = NadekoBot.Client.Servers.FirstOrDefault(s => s.Id == serverId)?.TextChannels.FirstOrDefault(c => c.Id == 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() internal void End()

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

View File

@ -113,7 +113,7 @@
// if (ch == null) // 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; // return;
// } // }
@ -123,7 +123,7 @@
// if (m.Length == 0) // 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; // return;
// } // }
@ -148,7 +148,7 @@
// (groupName == "hours" && value > 23) || // (groupName == "hours" && value > 23) ||
// (groupName == "minutes" && value > 59)) // (groupName == "minutes" && value > 59))
// { // {
// await e.Channel.SendMessage($"Invalid {groupName} value.").ConfigureAwait(false); // await channel.SendMessageAsync($"Invalid {groupName} value.").ConfigureAwait(false);
// return; // return;
// } // }
// else // else
@ -175,7 +175,7 @@
// reminders.Add(StartNewReminder(rem)); // 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") // cgb.CreateCommand(Module.Prefix + "remindmsg")
// .Description("Sets message for when the remind is triggered. " + // .Description("Sets message for when the remind is triggered. " +
@ -190,7 +190,7 @@
// return; // return;
// NadekoBot.Config.RemindMessageFormat = arg; // 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;
using System.Linq; using System.Linq;
using System.Threading.Tasks; 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 namespace NadekoBot.Modules.Utility
{ {
[Module(".", AppendSpace = false)] [Module(".", AppendSpace = false)]
public class UtilityModule public partial class UtilityModule : DiscordModule
{ {
[LocalizedCommand] public UtilityModule(ILocalization loc, CommandService cmds, IBotConfiguration config, IDiscordClient client) : base(loc, cmds, config, client)
[LocalizedDescription] {
[LocalizedSummary] }
[LocalizedCommand, LocalizedDescription, LocalizedSummary]
[RequireContext(ContextType.Guild)] [RequireContext(ContextType.Guild)]
public async Task WhoPlays(IMessage imsg, [Remainder] string game) public async Task WhoPlays(IMessage imsg, [Remainder] string game)
{ {
@ -22,154 +30,161 @@ namespace NadekoBot.Modules.Utility
if (string.IsNullOrWhiteSpace(game)) if (string.IsNullOrWhiteSpace(game))
return; return;
var arr = (await chnl.Guild.GetUsersAsync()) var arr = (await chnl.Guild.GetUsersAsync())
.Where(u => u.Game?.Name.ToUpperInvariant() == game) .Where(u => u.Game?.Name?.ToUpperInvariant() == game)
.Select(u => u.Username) .Select(u => u.Username)
.ToList(); .ToList();
int i = 0; int i = 0;
if (!arr.Any()) 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 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); 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] [LocalizedCommand, LocalizedDescription, LocalizedSummary]
[LocalizedDescription]
[LocalizedSummary]
[RequireContext(ContextType.Guild)] [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)) if (string.IsNullOrWhiteSpace(roles))
return; return;
var channel = imsg.Channel as IGuildChannel; var channel = imsg.Channel as IGuildChannel;
var arg = roles.Split(',').Select(r => r.Trim().ToUpperInvariant()); 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")) 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(); var role = channel.Guild.Roles.Where(r => r.Name.ToUpperInvariant() == roleStr).FirstOrDefault();
if (role == null) continue; if (role == null) continue;
send += $"\n`{role.Name}`\n"; 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()));
} }
var usr = imsg.Author as IGuildUser;
//todo while (send.Length > 2000)
{
if (!usr.GetPermissions(channel).ManageMessages)
//while (send.Length > 2000) {
//{ 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.");
// if (!) return;
// { }
// 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."); var curstr = send.Substring(0, 2000);
// return; await imsg.Channel.SendMessageAsync(curstr.Substring(0,
// } curstr.LastIndexOf(", ", StringComparison.Ordinal) + 1)).ConfigureAwait(false);
// var curstr = send.Substring(0, 2000); send = curstr.Substring(curstr.LastIndexOf(", ", StringComparison.Ordinal) + 1) +
// await imsg.Channel.SendMessageAsync(curstr.Substring(0, send.Substring(2000);
// curstr.LastIndexOf(", ", StringComparison.Ordinal) + 1)).ConfigureAwait(false); }
// send = curstr.Substring(curstr.LastIndexOf(", ", StringComparison.Ordinal) + 1) + await imsg.Channel.SendMessageAsync(send).ConfigureAwait(false);
// send.Substring(2000);
//}
//await e.Channel.Send(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);
// });
// });
// }
// }
//}

View File

@ -1,6 +1,9 @@
using Discord.Commands; using Discord;
using Discord.Commands;
using Discord.WebSocket; using Discord.WebSocket;
using NadekoBot.Modules.Utility; using NadekoBot.Modules.Utility;
using NadekoBot.Services;
using NadekoBot.Services.Impl;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
@ -13,30 +16,50 @@ namespace NadekoBot
{ {
public static CommandService Commands { get; private set; } public static CommandService Commands { get; private set; }
public static DiscordSocketClient Client { get; private set; } public static DiscordSocketClient Client { get; private set; }
public BotConfiguration Config { get; private set; }
public Localization Localizer { get; private set; }
public async Task RunAsync(string[] args) public async Task RunAsync(string[] args)
{ {
Client = new DiscordSocketClient(new Discord.DiscordSocketConfig //create client
Client = new DiscordSocketClient(new DiscordSocketConfig
{ {
AudioMode = Discord.Audio.AudioMode.Incoming, AudioMode = Discord.Audio.AudioMode.Incoming,
LargeThreshold = 200, LargeThreshold = 200,
LogLevel = Discord.LogSeverity.Warning, LogLevel = LogSeverity.Warning,
MessageCacheSize = 10, MessageCacheSize = 10,
}); });
//initialize Services
Commands = new CommandService(); Commands = new CommandService();
Config = new BotConfiguration();
Localizer = new Localization();
//setup DI
var depMap = new DependencyMap();
depMap.Add<ILocalization>(Localizer);
depMap.Add<IBotConfiguration>(Config);
depMap.Add<IDiscordClient>(Client);
depMap.Add<CommandService>(Commands);
//Client.MessageReceived += Client_MessageReceived; //connect
await Client.LoginAsync(TokenType.Bot, "MTE5Nzc3MDIxMzE5NTc3NjEw.CpGoCA.yQBJbLWurrjSk7IlGpGzBm-tPTg");
//await Commands.Load(new UtilityModule());
await Commands.LoadAssembly(Assembly.GetEntryAssembly());
await Client.LoginAsync(Discord.TokenType.Bot, "MTE5Nzc3MDIxMzE5NTc3NjEw.CmxGHA.nk1KyvR6y05nntj-J0W_Zvu-2kk");
await Client.ConnectAsync(); await Client.ConnectAsync();
//load commands
await Commands.LoadAssembly(Assembly.GetEntryAssembly(), depMap);
Client.MessageReceived += Client_MessageReceived;
Console.WriteLine(Commands.Commands.Count()); Console.WriteLine(Commands.Commands.Count());
await Task.Delay(-1); await Task.Delay(-1);
} }
private async Task Client_MessageReceived(IMessage arg)
{
var t = await Commands.Execute(arg, 0);
if(!t.IsSuccess)
Console.WriteLine(t.ErrorReason);
}
} }
} }

View File

@ -22,13 +22,13 @@ namespace NadekoBot.Resources {
// with the /str option, or rebuild your VS project. // with the /str option, or rebuild your VS project.
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
public class Strings { public class CommandStrings {
private static global::System.Resources.ResourceManager resourceMan; private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture; private static global::System.Globalization.CultureInfo resourceCulture;
internal Strings() { internal CommandStrings() {
} }
/// <summary> /// <summary>
@ -38,7 +38,7 @@ namespace NadekoBot.Resources {
public static global::System.Resources.ResourceManager ResourceManager { public static global::System.Resources.ResourceManager ResourceManager {
get { get {
if (object.ReferenceEquals(resourceMan, null)) { if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("NadekoBot.Resources.Strings", typeof(Strings).GetTypeInfo().Assembly); global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("NadekoBot.Resources.CommandStrings", typeof(CommandStrings).GetTypeInfo().Assembly);
resourceMan = temp; resourceMan = temp;
} }
return resourceMan; return resourceMan;

View File

@ -0,0 +1,71 @@
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace NadekoBot.Resources {
using System;
using System.Reflection;
/// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
// This class was auto-generated by the StronglyTypedResourceBuilder
// class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
public class ResponseStrings {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
internal ResponseStrings() {
}
/// <summary>
/// Returns the cached ResourceManager instance used by this class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
public static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("NadekoBot.Resources.ResponseStrings", typeof(ResponseStrings).GetTypeInfo().Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Overrides the current thread's CurrentUICulture property for all
/// resource lookups using this strongly typed resource class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
public static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
/// <summary>
/// Looks up a localized string similar to TESTING.
/// </summary>
public static string test {
get {
return ResourceManager.GetString("test", resourceCulture);
}
}
}
}

View File

@ -0,0 +1,123 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<data name="test" xml:space="preserve">
<value>TESTING</value>
</data>
</root>

View File

@ -0,0 +1,13 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace NadekoBot.Services
{
public interface ILocalization
{
string this[string key] { get; }
}
}

View File

@ -7,13 +7,34 @@ using System.Resources;
namespace NadekoBot.Services namespace NadekoBot.Services
{ {
public class Localization public class Localization : ILocalization
{ {
public static string LoadString(string key) => GetOrAddResourceKey(key); public string this[string key] {
get {
try
{
return Resources.ResponseStrings.ResourceManager.GetString(key);
}
catch (Exception) {
return key;
}
}
}
private static string GetOrAddResourceKey(string key) public static string LoadCommandString(string key)
{ {
return Resources.Strings.ResourceManager.GetString(key); try
{
return Resources.CommandStrings.ResourceManager.GetString(key);
}
catch (Exception) {
return key;
}
}
//private static string GetCommandString(string key)
//{
// return key;
//var resx = new List<DictionaryEntry>(); //var resx = new List<DictionaryEntry>();
//var fs = new StreamReader(File.OpenRead("./Strings.resx")); //var fs = new StreamReader(File.OpenRead("./Strings.resx"));
//Console.WriteLine(fs.ReadToEnd()); //Console.WriteLine(fs.ReadToEnd());
@ -41,6 +62,6 @@ namespace NadekoBot.Services
// writer.Generate(); // writer.Generate();
//} //}
//return key; //return key;
} //}
} }
} }

View File

@ -0,0 +1,51 @@
using Discord;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace NadekoBot.Extensions
{
public static class Extensions
{
public static async Task<IMessage> Reply(this IMessage msg, string content) => await msg.Channel.SendMessageAsync(content);
public static async Task<IMessage[]> ReplyLong(this IMessage msg, string content, string breakOn = "\n", string addToEnd = "", string addToStart = "")
{
if (content.Length < 2000) return new[] { await msg.Channel.SendMessageAsync(content) };
var list = new List<IMessage>();
var temp = Regex.Split(content, breakOn).Select(x => x += breakOn).ToList();
string toolong;
//while ((toolong = temp.FirstOrDefault(x => x.Length > 2000)) != null)
//{
// //TODO more desperate measures == split on whitespace?
//}
StringBuilder builder = new StringBuilder();
//TODO make this less crappy to look at, maybe it's bugged
for (int i = 0; i < temp.Count; i++)
{
var addition = temp[i];
//we append
if (builder.Length == 0 && i != 0) builder.Append(addToStart + addition);
else builder.Append(addition);
//Check if the next would have room
if (i + 1 >= temp.Count || temp[i + 1].Length + builder.Length + addToEnd.Length > 2000)
{
if (i + 1 < temp.Count) builder.Append(addToEnd);
list.Add(await msg.Channel.SendMessageAsync(builder.ToString()));
builder.Clear();
}
}
return list.ToArray();
}
}
}

View File

@ -72,9 +72,9 @@ namespace NadekoBot.Modules.Administration
conf.AutoDeleteMessagesOnCommand = !conf.AutoDeleteMessagesOnCommand; conf.AutoDeleteMessagesOnCommand = !conf.AutoDeleteMessagesOnCommand;
await Classes.JSONModels.ConfigHandler.SaveConfig().ConfigureAwait(false); await Classes.JSONModels.ConfigHandler.SaveConfig().ConfigureAwait(false);
if (conf.AutoDeleteMessagesOnCommand) if (conf.AutoDeleteMessagesOnCommand)
await e.Channel.SendMessage("❗`Now automatically deleting successfull command invokations.`"); await channel.SendMessageAsync("❗`Now automatically deleting successfull command invokations.`");
else else
await e.Channel.SendMessage("❗`Stopped automatic deletion of successfull command invokations.`"); await channel.SendMessageAsync("❗`Stopped automatic deletion of successfull command invokations.`");
}); });
@ -83,7 +83,7 @@ namespace NadekoBot.Modules.Administration
.AddCheck(SimpleCheckers.OwnerOnly()) .AddCheck(SimpleCheckers.OwnerOnly())
.Do(async e => .Do(async e =>
{ {
await e.Channel.SendMessage("`Restarting in 2 seconds...`"); await channel.SendMessageAsync("`Restarting in 2 seconds...`");
await Task.Delay(2000); await Task.Delay(2000);
System.Diagnostics.Process.Start(System.Reflection.Assembly.GetExecutingAssembly().Location); System.Diagnostics.Process.Start(System.Reflection.Assembly.GetExecutingAssembly().Location);
Environment.Exit(0); Environment.Exit(0);
@ -103,31 +103,31 @@ namespace NadekoBot.Modules.Administration
if (!e.User.ServerPermissions.ManageRoles) if (!e.User.ServerPermissions.ManageRoles)
{ {
await e.Channel.SendMessage("You have insufficient permissions.").ConfigureAwait(false); await channel.SendMessageAsync("You have insufficient permissions.").ConfigureAwait(false);
} }
var usr = e.Server.FindUsers(userName).FirstOrDefault(); var usr = e.Server.FindUsers(userName).FirstOrDefault();
if (usr == null) if (usr == null)
{ {
await e.Channel.SendMessage("You failed to supply a valid username").ConfigureAwait(false); await channel.SendMessageAsync("You failed to supply a valid username").ConfigureAwait(false);
return; return;
} }
var role = e.Server.FindRoles(roleName).FirstOrDefault(); var role = e.Server.FindRoles(roleName).FirstOrDefault();
if (role == null) if (role == null)
{ {
await e.Channel.SendMessage("You failed to supply a valid role").ConfigureAwait(false); await channel.SendMessageAsync("You failed to supply a valid role").ConfigureAwait(false);
return; return;
} }
try try
{ {
await usr.AddRoles(role).ConfigureAwait(false); await usr.AddRoles(role).ConfigureAwait(false);
await e.Channel.SendMessage($"Successfully added role **{role.Name}** to user **{usr.Name}**").ConfigureAwait(false); await channel.SendMessageAsync($"Successfully added role **{role.Name}** to user **{usr.Name}**").ConfigureAwait(false);
} }
catch (Exception ex) catch (Exception ex)
{ {
await e.Channel.SendMessage("Failed to add roles. Bot has insufficient permissions.\n").ConfigureAwait(false); await channel.SendMessageAsync("Failed to add roles. Bot has insufficient permissions.\n").ConfigureAwait(false);
Console.WriteLine(ex.ToString()); Console.WriteLine(ex.ToString());
} }
}); });
@ -147,25 +147,25 @@ namespace NadekoBot.Modules.Administration
var usr = e.Server.FindUsers(userName).FirstOrDefault(); var usr = e.Server.FindUsers(userName).FirstOrDefault();
if (usr == null) if (usr == null)
{ {
await e.Channel.SendMessage("You failed to supply a valid username").ConfigureAwait(false); await channel.SendMessageAsync("You failed to supply a valid username").ConfigureAwait(false);
return; return;
} }
var role = e.Server.FindRoles(roleName).FirstOrDefault(); var role = e.Server.FindRoles(roleName).FirstOrDefault();
if (role == null) if (role == null)
{ {
await e.Channel.SendMessage("You failed to supply a valid role").ConfigureAwait(false); await channel.SendMessageAsync("You failed to supply a valid role").ConfigureAwait(false);
return; return;
} }
try try
{ {
await usr.RemoveRoles(role).ConfigureAwait(false); await usr.RemoveRoles(role).ConfigureAwait(false);
await e.Channel.SendMessage($"Successfully removed role **{role.Name}** from user **{usr.Name}**").ConfigureAwait(false); await channel.SendMessageAsync($"Successfully removed role **{role.Name}** from user **{usr.Name}**").ConfigureAwait(false);
} }
catch catch
{ {
await e.Channel.SendMessage("Failed to remove roles. Most likely reason: Insufficient permissions.").ConfigureAwait(false); await channel.SendMessageAsync("Failed to remove roles. Most likely reason: Insufficient permissions.").ConfigureAwait(false);
} }
}); });
@ -183,7 +183,7 @@ namespace NadekoBot.Modules.Administration
var roleToEdit = e.Server.FindRoles(r1).FirstOrDefault(); var roleToEdit = e.Server.FindRoles(r1).FirstOrDefault();
if (roleToEdit == null) if (roleToEdit == null)
{ {
await e.Channel.SendMessage("Can't find that role.").ConfigureAwait(false); await channel.SendMessageAsync("Can't find that role.").ConfigureAwait(false);
return; return;
} }
@ -191,15 +191,15 @@ namespace NadekoBot.Modules.Administration
{ {
if (roleToEdit.Position > e.Server.CurrentUser.Roles.Max(r => r.Position)) if (roleToEdit.Position > e.Server.CurrentUser.Roles.Max(r => r.Position))
{ {
await e.Channel.SendMessage("I can't edit roles higher than my highest role.").ConfigureAwait(false); await channel.SendMessageAsync("I can't edit roles higher than my highest role.").ConfigureAwait(false);
return; return;
} }
await roleToEdit.Edit(r2); await roleToEdit.Edit(r2);
await e.Channel.SendMessage("Role renamed.").ConfigureAwait(false); await channel.SendMessageAsync("Role renamed.").ConfigureAwait(false);
} }
catch (Exception) catch (Exception)
{ {
await e.Channel.SendMessage("Failed to rename role. Probably insufficient permissions.").ConfigureAwait(false); await channel.SendMessageAsync("Failed to rename role. Probably insufficient permissions.").ConfigureAwait(false);
} }
}); });
@ -214,18 +214,18 @@ namespace NadekoBot.Modules.Administration
var usr = e.Server.FindUsers(userName).FirstOrDefault(); var usr = e.Server.FindUsers(userName).FirstOrDefault();
if (usr == null) if (usr == null)
{ {
await e.Channel.SendMessage("You failed to supply a valid username").ConfigureAwait(false); await channel.SendMessageAsync("You failed to supply a valid username").ConfigureAwait(false);
return; return;
} }
try try
{ {
await usr.RemoveRoles(usr.Roles.ToArray()).ConfigureAwait(false); await usr.RemoveRoles(usr.Roles.ToArray()).ConfigureAwait(false);
await e.Channel.SendMessage($"Successfully removed **all** roles from user **{usr.Name}**").ConfigureAwait(false); await channel.SendMessageAsync($"Successfully removed **all** roles from user **{usr.Name}**").ConfigureAwait(false);
} }
catch catch
{ {
await e.Channel.SendMessage("Failed to remove roles. Most likely reason: Insufficient permissions.").ConfigureAwait(false); await channel.SendMessageAsync("Failed to remove roles. Most likely reason: Insufficient permissions.").ConfigureAwait(false);
} }
}); });
@ -240,11 +240,11 @@ namespace NadekoBot.Modules.Administration
try try
{ {
var r = await e.Server.CreateRole(e.GetArg("role_name")).ConfigureAwait(false); var r = await e.Server.CreateRole(e.GetArg("role_name")).ConfigureAwait(false);
await e.Channel.SendMessage($"Successfully created role **{r.Name}**.").ConfigureAwait(false); await channel.SendMessageAsync($"Successfully created role **{r.Name}**.").ConfigureAwait(false);
} }
catch (Exception) catch (Exception)
{ {
await e.Channel.SendMessage(":warning: Unspecified error.").ConfigureAwait(false); await channel.SendMessageAsync(":warning: Unspecified error.").ConfigureAwait(false);
} }
}); });
@ -258,7 +258,7 @@ namespace NadekoBot.Modules.Administration
{ {
if (!e.User.ServerPermissions.ManageRoles) if (!e.User.ServerPermissions.ManageRoles)
{ {
await e.Channel.SendMessage("You don't have permission to use this!").ConfigureAwait(false); await channel.SendMessageAsync("You don't have permission to use this!").ConfigureAwait(false);
return; return;
} }
@ -266,7 +266,7 @@ namespace NadekoBot.Modules.Administration
if (args.Count() != 2 && args.Count() != 4) if (args.Count() != 2 && args.Count() != 4)
{ {
await e.Channel.SendMessage("The parameters are invalid.").ConfigureAwait(false); await channel.SendMessageAsync("The parameters are invalid.").ConfigureAwait(false);
return; return;
} }
@ -274,7 +274,7 @@ namespace NadekoBot.Modules.Administration
if (role == null) if (role == null)
{ {
await e.Channel.SendMessage("That role does not exist.").ConfigureAwait(false); await channel.SendMessageAsync("That role does not exist.").ConfigureAwait(false);
return; return;
} }
try try
@ -287,11 +287,11 @@ namespace NadekoBot.Modules.Administration
var blue = Convert.ToByte(rgb ? int.Parse(e.Args[3]) : Convert.ToInt32(arg1.Substring(4, 2), 16)); var blue = Convert.ToByte(rgb ? int.Parse(e.Args[3]) : Convert.ToInt32(arg1.Substring(4, 2), 16));
await role.Edit(color: new Color(red, green, blue)).ConfigureAwait(false); await role.Edit(color: new Color(red, green, blue)).ConfigureAwait(false);
await e.Channel.SendMessage($"Role {role.Name}'s color has been changed.").ConfigureAwait(false); await channel.SendMessageAsync($"Role {role.Name}'s color has been changed.").ConfigureAwait(false);
} }
catch (Exception) catch (Exception)
{ {
await e.Channel.SendMessage("Error occured, most likely invalid parameters or insufficient permissions.").ConfigureAwait(false); await channel.SendMessageAsync("Error occured, most likely invalid parameters or insufficient permissions.").ConfigureAwait(false);
} }
}); });
@ -308,7 +308,7 @@ namespace NadekoBot.Modules.Administration
var usr = e.Server.FindUsers(user).FirstOrDefault(); var usr = e.Server.FindUsers(user).FirstOrDefault();
if (usr == null) if (usr == null)
{ {
await e.Channel.SendMessage("User not found.").ConfigureAwait(false); await channel.SendMessageAsync("User not found.").ConfigureAwait(false);
return; return;
} }
if (!string.IsNullOrWhiteSpace(msg)) if (!string.IsNullOrWhiteSpace(msg))
@ -321,11 +321,11 @@ namespace NadekoBot.Modules.Administration
{ {
await e.Server.Ban(usr, 7).ConfigureAwait(false); await e.Server.Ban(usr, 7).ConfigureAwait(false);
await e.Channel.SendMessage("Banned user " + usr.Name + " Id: " + usr.Id).ConfigureAwait(false); await channel.SendMessageAsync("Banned user " + usr.Name + " Id: " + usr.Id).ConfigureAwait(false);
} }
catch catch
{ {
await e.Channel.SendMessage("Error. Most likely I don't have sufficient permissions.").ConfigureAwait(false); await channel.SendMessageAsync("Error. Most likely I don't have sufficient permissions.").ConfigureAwait(false);
} }
} }
}); });
@ -343,7 +343,7 @@ namespace NadekoBot.Modules.Administration
var usr = e.Server.FindUsers(user).FirstOrDefault(); var usr = e.Server.FindUsers(user).FirstOrDefault();
if (usr == null) if (usr == null)
{ {
await e.Channel.SendMessage("User not found.").ConfigureAwait(false); await channel.SendMessageAsync("User not found.").ConfigureAwait(false);
return; return;
} }
if (!string.IsNullOrWhiteSpace(msg)) if (!string.IsNullOrWhiteSpace(msg))
@ -357,11 +357,11 @@ namespace NadekoBot.Modules.Administration
await e.Server.Ban(usr, 7).ConfigureAwait(false); await e.Server.Ban(usr, 7).ConfigureAwait(false);
await e.Server.Unban(usr).ConfigureAwait(false); await e.Server.Unban(usr).ConfigureAwait(false);
await e.Channel.SendMessage("Soft-Banned user " + usr.Name + " Id: " + usr.Id).ConfigureAwait(false); await channel.SendMessageAsync("Soft-Banned user " + usr.Name + " Id: " + usr.Id).ConfigureAwait(false);
} }
catch catch
{ {
await e.Channel.SendMessage("Error. Most likely I don't have sufficient permissions.").ConfigureAwait(false); await channel.SendMessageAsync("Error. Most likely I don't have sufficient permissions.").ConfigureAwait(false);
} }
} }
}); });
@ -379,7 +379,7 @@ namespace NadekoBot.Modules.Administration
var usr = e.Server.FindUsers(user).FirstOrDefault(); var usr = e.Server.FindUsers(user).FirstOrDefault();
if (usr == null) if (usr == null)
{ {
await e.Channel.SendMessage("User not found.").ConfigureAwait(false); await channel.SendMessageAsync("User not found.").ConfigureAwait(false);
return; return;
} }
if (!string.IsNullOrWhiteSpace(msg)) if (!string.IsNullOrWhiteSpace(msg))
@ -391,11 +391,11 @@ namespace NadekoBot.Modules.Administration
try try
{ {
await usr.Kick().ConfigureAwait(false); await usr.Kick().ConfigureAwait(false);
await e.Channel.SendMessage("Kicked user " + usr.Name + " Id: " + usr.Id).ConfigureAwait(false); await channel.SendMessageAsync("Kicked user " + usr.Name + " Id: " + usr.Id).ConfigureAwait(false);
} }
catch catch
{ {
await e.Channel.SendMessage("Error. Most likely I don't have sufficient permissions.").ConfigureAwait(false); await channel.SendMessageAsync("Error. Most likely I don't have sufficient permissions.").ConfigureAwait(false);
} }
} }
}); });
@ -406,7 +406,7 @@ namespace NadekoBot.Modules.Administration
{ {
if (!e.User.ServerPermissions.MuteMembers) if (!e.User.ServerPermissions.MuteMembers)
{ {
await e.Channel.SendMessage("I most likely don't have the permission necessary for that.").ConfigureAwait(false); await channel.SendMessageAsync("I most likely don't have the permission necessary for that.").ConfigureAwait(false);
return; return;
} }
if (!e.Message.MentionedUsers.Any()) if (!e.Message.MentionedUsers.Any())
@ -417,11 +417,11 @@ namespace NadekoBot.Modules.Administration
{ {
await u.Edit(isMuted: true).ConfigureAwait(false); await u.Edit(isMuted: true).ConfigureAwait(false);
} }
await e.Channel.SendMessage("Mute successful").ConfigureAwait(false); await channel.SendMessageAsync("Mute successful").ConfigureAwait(false);
} }
catch catch
{ {
await e.Channel.SendMessage("I most likely don't have the permission necessary for that.").ConfigureAwait(false); await channel.SendMessageAsync("I most likely don't have the permission necessary for that.").ConfigureAwait(false);
} }
}); });
@ -432,7 +432,7 @@ namespace NadekoBot.Modules.Administration
{ {
if (!e.User.ServerPermissions.MuteMembers) if (!e.User.ServerPermissions.MuteMembers)
{ {
await e.Channel.SendMessage("You do not have permission to do that.").ConfigureAwait(false); await channel.SendMessageAsync("You do not have permission to do that.").ConfigureAwait(false);
return; return;
} }
if (!e.Message.MentionedUsers.Any()) if (!e.Message.MentionedUsers.Any())
@ -443,11 +443,11 @@ namespace NadekoBot.Modules.Administration
{ {
await u.Edit(isMuted: false).ConfigureAwait(false); await u.Edit(isMuted: false).ConfigureAwait(false);
} }
await e.Channel.SendMessage("Unmute successful").ConfigureAwait(false); await channel.SendMessageAsync("Unmute successful").ConfigureAwait(false);
} }
catch catch
{ {
await e.Channel.SendMessage("I most likely don't have the permission necessary for that.").ConfigureAwait(false); await channel.SendMessageAsync("I most likely don't have the permission necessary for that.").ConfigureAwait(false);
} }
}); });
@ -459,7 +459,7 @@ namespace NadekoBot.Modules.Administration
{ {
if (!e.User.ServerPermissions.DeafenMembers) if (!e.User.ServerPermissions.DeafenMembers)
{ {
await e.Channel.SendMessage("You do not have permission to do that.").ConfigureAwait(false); await channel.SendMessageAsync("You do not have permission to do that.").ConfigureAwait(false);
return; return;
} }
if (!e.Message.MentionedUsers.Any()) if (!e.Message.MentionedUsers.Any())
@ -470,11 +470,11 @@ namespace NadekoBot.Modules.Administration
{ {
await u.Edit(isDeafened: true).ConfigureAwait(false); await u.Edit(isDeafened: true).ConfigureAwait(false);
} }
await e.Channel.SendMessage("Deafen successful").ConfigureAwait(false); await channel.SendMessageAsync("Deafen successful").ConfigureAwait(false);
} }
catch catch
{ {
await e.Channel.SendMessage("I most likely don't have the permission necessary for that.").ConfigureAwait(false); await channel.SendMessageAsync("I most likely don't have the permission necessary for that.").ConfigureAwait(false);
} }
}); });
@ -486,7 +486,7 @@ namespace NadekoBot.Modules.Administration
{ {
if (!e.User.ServerPermissions.DeafenMembers) if (!e.User.ServerPermissions.DeafenMembers)
{ {
await e.Channel.SendMessage("You do not have permission to do that.").ConfigureAwait(false); await channel.SendMessageAsync("You do not have permission to do that.").ConfigureAwait(false);
return; return;
} }
if (!e.Message.MentionedUsers.Any()) if (!e.Message.MentionedUsers.Any())
@ -497,11 +497,11 @@ namespace NadekoBot.Modules.Administration
{ {
await u.Edit(isDeafened: false).ConfigureAwait(false); await u.Edit(isDeafened: false).ConfigureAwait(false);
} }
await e.Channel.SendMessage("Undeafen successful").ConfigureAwait(false); await channel.SendMessageAsync("Undeafen successful").ConfigureAwait(false);
} }
catch catch
{ {
await e.Channel.SendMessage("I most likely don't have the permission necessary for that.").ConfigureAwait(false); await channel.SendMessageAsync("I most likely don't have the permission necessary for that.").ConfigureAwait(false);
} }
}); });
@ -519,12 +519,12 @@ namespace NadekoBot.Modules.Administration
if (ch == null) if (ch == null)
return; return;
await ch.Delete().ConfigureAwait(false); await ch.Delete().ConfigureAwait(false);
await e.Channel.SendMessage($"Removed channel **{e.GetArg("channel_name")}**.").ConfigureAwait(false); await channel.SendMessageAsync($"Removed channel **{e.GetArg("channel_name")}**.").ConfigureAwait(false);
} }
} }
catch catch
{ {
await e.Channel.SendMessage("Insufficient permissions."); await channel.SendMessageAsync("Insufficient permissions.");
} }
}); });
@ -539,12 +539,12 @@ namespace NadekoBot.Modules.Administration
if (e.User.ServerPermissions.ManageChannels) if (e.User.ServerPermissions.ManageChannels)
{ {
await e.Server.CreateChannel(e.GetArg("channel_name"), ChannelType.Voice).ConfigureAwait(false); await e.Server.CreateChannel(e.GetArg("channel_name"), ChannelType.Voice).ConfigureAwait(false);
await e.Channel.SendMessage($"Created voice channel **{e.GetArg("channel_name")}**.").ConfigureAwait(false); await channel.SendMessageAsync($"Created voice channel **{e.GetArg("channel_name")}**.").ConfigureAwait(false);
} }
} }
catch catch
{ {
await e.Channel.SendMessage("Insufficient permissions.").ConfigureAwait(false); await channel.SendMessageAsync("Insufficient permissions.").ConfigureAwait(false);
} }
}); });
@ -561,12 +561,12 @@ namespace NadekoBot.Modules.Administration
var channel = e.Server.FindChannels(e.GetArg("channel_name"), ChannelType.Text).FirstOrDefault(); var channel = e.Server.FindChannels(e.GetArg("channel_name"), ChannelType.Text).FirstOrDefault();
if (channel == null) return; if (channel == null) return;
await channel.Delete().ConfigureAwait(false); await channel.Delete().ConfigureAwait(false);
await e.Channel.SendMessage($"Removed text channel **{e.GetArg("channel_name")}**.").ConfigureAwait(false); await channel.SendMessageAsync($"Removed text channel **{e.GetArg("channel_name")}**.").ConfigureAwait(false);
} }
} }
catch catch
{ {
await e.Channel.SendMessage("Insufficient permissions.").ConfigureAwait(false); await channel.SendMessageAsync("Insufficient permissions.").ConfigureAwait(false);
} }
}); });
@ -581,12 +581,12 @@ namespace NadekoBot.Modules.Administration
if (e.User.ServerPermissions.ManageChannels) if (e.User.ServerPermissions.ManageChannels)
{ {
await e.Server.CreateChannel(e.GetArg("channel_name"), ChannelType.Text).ConfigureAwait(false); await e.Server.CreateChannel(e.GetArg("channel_name"), ChannelType.Text).ConfigureAwait(false);
await e.Channel.SendMessage($"Added text channel **{e.GetArg("channel_name")}**.").ConfigureAwait(false); await channel.SendMessageAsync($"Added text channel **{e.GetArg("channel_name")}**.").ConfigureAwait(false);
} }
} }
catch catch
{ {
await e.Channel.SendMessage("Insufficient permissions.").ConfigureAwait(false); await channel.SendMessageAsync("Insufficient permissions.").ConfigureAwait(false);
} }
}); });
@ -599,7 +599,7 @@ namespace NadekoBot.Modules.Administration
{ {
var topic = e.GetArg("topic")?.Trim() ?? ""; var topic = e.GetArg("topic")?.Trim() ?? "";
await e.Channel.Edit(topic: topic).ConfigureAwait(false); await e.Channel.Edit(topic: topic).ConfigureAwait(false);
await e.Channel.SendMessage(":ok: **New channel topic set.**").ConfigureAwait(false); await channel.SendMessageAsync(":ok: **New channel topic set.**").ConfigureAwait(false);
}); });
cgb.CreateCommand(Prefix + "setchanlname") cgb.CreateCommand(Prefix + "setchanlname")
@ -613,7 +613,7 @@ namespace NadekoBot.Modules.Administration
if (string.IsNullOrWhiteSpace(name)) if (string.IsNullOrWhiteSpace(name))
return; return;
await e.Channel.Edit(name: name).ConfigureAwait(false); await e.Channel.Edit(name: name).ConfigureAwait(false);
await e.Channel.SendMessage(":ok: **New channel name set.**").ConfigureAwait(false); await channel.SendMessageAsync(":ok: **New channel name set.**").ConfigureAwait(false);
}); });
cgb.CreateCommand(Prefix + "heap") cgb.CreateCommand(Prefix + "heap")
@ -622,7 +622,7 @@ namespace NadekoBot.Modules.Administration
.Do(async e => .Do(async e =>
{ {
var heap = await Task.Run(() => NadekoStats.Instance.Heap()).ConfigureAwait(false); var heap = await Task.Run(() => NadekoStats.Instance.Heap()).ConfigureAwait(false);
await e.Channel.SendMessage($"`Heap Size:` {heap}").ConfigureAwait(false); await channel.SendMessageAsync($"`Heap Size:` {heap}").ConfigureAwait(false);
}); });
cgb.CreateCommand(Prefix + "prune") cgb.CreateCommand(Prefix + "prune")
@ -647,7 +647,7 @@ namespace NadekoBot.Modules.Administration
return; return;
else if (!e.Server.CurrentUser.GetPermissions(e.Channel).ManageMessages) else if (!e.Server.CurrentUser.GetPermissions(e.Channel).ManageMessages)
{ {
await e.Channel.SendMessage("💢I don't have the permission to manage messages."); await channel.SendMessageAsync("💢I don't have the permission to manage messages.");
return; return;
} }
int val; int val;
@ -678,7 +678,7 @@ namespace NadekoBot.Modules.Administration
.AddCheck(SimpleCheckers.OwnerOnly()) .AddCheck(SimpleCheckers.OwnerOnly())
.Do(async e => .Do(async e =>
{ {
await e.Channel.SendMessage("`Shutting down.`").ConfigureAwait(false); await channel.SendMessageAsync("`Shutting down.`").ConfigureAwait(false);
await Task.Delay(2000).ConfigureAwait(false); await Task.Delay(2000).ConfigureAwait(false);
Environment.Exit(0); Environment.Exit(0);
}); });
@ -711,7 +711,7 @@ namespace NadekoBot.Modules.Administration
await client.CurrentUser.Edit("", avatar: image.ToStream()).ConfigureAwait(false); await client.CurrentUser.Edit("", avatar: image.ToStream()).ConfigureAwait(false);
// Send confirm. // Send confirm.
await e.Channel.SendMessage("New avatar set.").ConfigureAwait(false); await channel.SendMessageAsync("New avatar set.").ConfigureAwait(false);
// Save the image to disk. // Save the image to disk.
image.Save("data/avatar.png", System.Drawing.Imaging.ImageFormat.Png); image.Save("data/avatar.png", System.Drawing.Imaging.ImageFormat.Png);
@ -770,7 +770,7 @@ namespace NadekoBot.Modules.Administration
} }
else else
{ {
await e.Channel.SendMessage("`Invalid format.`"); await channel.SendMessageAsync("`Invalid format.`");
} }
}); });
@ -824,7 +824,7 @@ namespace NadekoBot.Modules.Administration
var donatorsOrdered = rows.OrderByDescending(d => d.Amount); var donatorsOrdered = rows.OrderByDescending(d => d.Amount);
string str = $"**Thanks to the people listed below for making this project happen!**\n"; string str = $"**Thanks to the people listed below for making this project happen!**\n";
await e.Channel.SendMessage(str + string.Join("⭐", donatorsOrdered.Select(d => d.UserName))).ConfigureAwait(false); await channel.SendMessageAsync(str + string.Join("⭐", donatorsOrdered.Select(d => d.UserName))).ConfigureAwait(false);
}).ConfigureAwait(false); }).ConfigureAwait(false);
}); });
@ -848,7 +848,7 @@ namespace NadekoBot.Modules.Administration
UserName = donator.Name, UserName = donator.Name,
UserId = (long)donator.Id UserId = (long)donator.Id
}); });
e.Channel.SendMessage("Successfuly added a new donator. 👑").ConfigureAwait(false); channel.SendMessageAsync("Successfuly added a new donator. 👑").ConfigureAwait(false);
} }
catch { } catch { }
}).ConfigureAwait(false); }).ConfigureAwait(false);
@ -865,7 +865,7 @@ namespace NadekoBot.Modules.Administration
await ch.SendMessage(e.GetArg("msg")).ConfigureAwait(false); await ch.SendMessage(e.GetArg("msg")).ConfigureAwait(false);
} }
await e.Channel.SendMessage(":ok:").ConfigureAwait(false); await channel.SendMessageAsync(":ok:").ConfigureAwait(false);
}); });
cgb.CreateCommand(Prefix + "savechat") cgb.CreateCommand(Prefix + "savechat")

View File

@ -41,7 +41,7 @@ namespace NadekoBot.Modules.Administration.Commands
{ {
if (!e.Server.CurrentUser.ServerPermissions.ManageRoles) if (!e.Server.CurrentUser.ServerPermissions.ManageRoles)
{ {
await e.Channel.SendMessage("I do not have the permission to manage roles.").ConfigureAwait(false); await channel.SendMessageAsync("I do not have the permission to manage roles.").ConfigureAwait(false);
return; return;
} }
var r = e.GetArg("role")?.Trim(); var r = e.GetArg("role")?.Trim();
@ -52,19 +52,19 @@ namespace NadekoBot.Modules.Administration.Commands
{ {
config.AutoAssignedRole = 0; config.AutoAssignedRole = 0;
await e.Channel.SendMessage("`Auto assign role on user join is now disabled.`").ConfigureAwait(false); await channel.SendMessageAsync("`Auto assign role on user join is now disabled.`").ConfigureAwait(false);
return; return;
} }
var role = e.Server.FindRoles(r).FirstOrDefault(); var role = e.Server.FindRoles(r).FirstOrDefault();
if (role == null) if (role == null)
{ {
await e.Channel.SendMessage("💢 `Role not found.`").ConfigureAwait(false); await channel.SendMessageAsync("💢 `Role not found.`").ConfigureAwait(false);
return; return;
} }
config.AutoAssignedRole = role.Id; config.AutoAssignedRole = role.Id;
await e.Channel.SendMessage("`Auto assigned role is set.`").ConfigureAwait(false); await channel.SendMessageAsync("`Auto assigned role is set.`").ConfigureAwait(false);
}); });
} }

View File

@ -91,7 +91,7 @@ namespace NadekoBot.Modules.Administration.Commands
if (!Subscribers.TryGetValue(token, out set)) if (!Subscribers.TryGetValue(token, out set))
return; return;
set.Add(e.Channel); set.Add(e.Channel);
await e.Channel.SendMessage(":ok:").ConfigureAwait(false); await channel.SendMessageAsync(":ok:").ConfigureAwait(false);
}); });
cgb.CreateCommand(Module.Prefix + "lcsc") cgb.CreateCommand(Module.Prefix + "lcsc")
@ -103,7 +103,7 @@ namespace NadekoBot.Modules.Administration.Commands
{ {
subscriber.Value.Remove(e.Channel); subscriber.Value.Remove(e.Channel);
} }
await e.Channel.SendMessage(":ok:").ConfigureAwait(false); await channel.SendMessageAsync(":ok:").ConfigureAwait(false);
}); });
} }
} }

View File

@ -33,7 +33,7 @@ namespace NadekoBot.Modules.Administration.Commands
var message = e.GetArg("message")?.Trim(); var message = e.GetArg("message")?.Trim();
if (string.IsNullOrWhiteSpace(message)) if (string.IsNullOrWhiteSpace(message))
{ {
await e.Channel.SendMessage($"Incorrect command usage. See -h {Prefix}acr for correct formatting").ConfigureAwait(false); await channel.SendMessageAsync($"Incorrect command usage. See -h {Prefix}acr for correct formatting").ConfigureAwait(false);
return; return;
} }
if (NadekoBot.Config.CustomReactions.ContainsKey(name)) if (NadekoBot.Config.CustomReactions.ContainsKey(name))
@ -41,7 +41,7 @@ namespace NadekoBot.Modules.Administration.Commands
else else
NadekoBot.Config.CustomReactions.Add(name, new System.Collections.Generic.List<string>() { message }); NadekoBot.Config.CustomReactions.Add(name, new System.Collections.Generic.List<string>() { message });
await Classes.JSONModels.ConfigHandler.SaveConfig().ConfigureAwait(false); await Classes.JSONModels.ConfigHandler.SaveConfig().ConfigureAwait(false);
await e.Channel.SendMessage($"Added {name} : {message}").ConfigureAwait(false); await channel.SendMessageAsync($"Added {name} : {message}").ConfigureAwait(false);
}); });
@ -69,12 +69,12 @@ namespace NadekoBot.Modules.Administration.Commands
var cmds = GetCustomsOnPage(num - 1); var cmds = GetCustomsOnPage(num - 1);
if (!cmds.Any()) if (!cmds.Any())
{ {
await e.Channel.SendMessage("`There are no custom reactions.`"); await channel.SendMessageAsync("`There are no custom reactions.`");
} }
else else
{ {
string result = SearchHelper.ShowInPrettyCode<string>(cmds, s => $"{s,-25}"); //People prefer starting with 1 string result = SearchHelper.ShowInPrettyCode<string>(cmds, s => $"{s,-25}"); //People prefer starting with 1
await e.Channel.SendMessage($"`Showing page {num}:`\n" + result).ConfigureAwait(false); await channel.SendMessageAsync($"`Showing page {num}:`\n" + result).ConfigureAwait(false);
} }
}); });
@ -89,7 +89,7 @@ namespace NadekoBot.Modules.Administration.Commands
return; return;
if (!NadekoBot.Config.CustomReactions.ContainsKey(name)) if (!NadekoBot.Config.CustomReactions.ContainsKey(name))
{ {
await e.Channel.SendMessage("`Can't find that custom reaction.`").ConfigureAwait(false); await channel.SendMessageAsync("`Can't find that custom reaction.`").ConfigureAwait(false);
return; return;
} }
var items = NadekoBot.Config.CustomReactions[name]; var items = NadekoBot.Config.CustomReactions[name];
@ -101,7 +101,7 @@ namespace NadekoBot.Modules.Administration.Commands
{ {
message.AppendLine($"[{i++}] " + Format.Code(Format.Escape(reaction))); message.AppendLine($"[{i++}] " + Format.Code(Format.Escape(reaction)));
} }
await e.Channel.SendMessage(message.ToString()); await channel.SendMessageAsync(message.ToString());
}); });
cgb.CreateCommand(Prefix + "editcustreact") cgb.CreateCommand(Prefix + "editcustreact")
@ -127,21 +127,21 @@ namespace NadekoBot.Modules.Administration.Commands
if (!NadekoBot.Config.CustomReactions.ContainsKey(name)) if (!NadekoBot.Config.CustomReactions.ContainsKey(name))
{ {
await e.Channel.SendMessage("`Could not find given commandname`").ConfigureAwait(false); await channel.SendMessageAsync("`Could not find given commandname`").ConfigureAwait(false);
return; return;
} }
int index; int index;
if (!int.TryParse(indexstr, out index) || index < 1 || index > NadekoBot.Config.CustomReactions[name].Count) if (!int.TryParse(indexstr, out index) || index < 1 || index > NadekoBot.Config.CustomReactions[name].Count)
{ {
await e.Channel.SendMessage("`Invalid index.`").ConfigureAwait(false); await channel.SendMessageAsync("`Invalid index.`").ConfigureAwait(false);
return; return;
} }
index = index - 1; index = index - 1;
NadekoBot.Config.CustomReactions[name][index] = msg; NadekoBot.Config.CustomReactions[name][index] = msg;
await Classes.JSONModels.ConfigHandler.SaveConfig().ConfigureAwait(false); await Classes.JSONModels.ConfigHandler.SaveConfig().ConfigureAwait(false);
await e.Channel.SendMessage($"Edited response #{index + 1} from `{name}`").ConfigureAwait(false); await channel.SendMessageAsync($"Edited response #{index + 1} from `{name}`").ConfigureAwait(false);
}); });
cgb.CreateCommand(Prefix + "delcustreact") cgb.CreateCommand(Prefix + "delcustreact")
@ -157,7 +157,7 @@ namespace NadekoBot.Modules.Administration.Commands
return; return;
if (!NadekoBot.Config.CustomReactions.ContainsKey(name)) if (!NadekoBot.Config.CustomReactions.ContainsKey(name))
{ {
await e.Channel.SendMessage("Could not find given commandname").ConfigureAwait(false); await channel.SendMessageAsync("Could not find given commandname").ConfigureAwait(false);
return; return;
} }
string message = ""; string message = "";
@ -167,7 +167,7 @@ namespace NadekoBot.Modules.Administration.Commands
index = index - 1; index = index - 1;
if (index < 0 || index > NadekoBot.Config.CustomReactions[name].Count) if (index < 0 || index > NadekoBot.Config.CustomReactions[name].Count)
{ {
await e.Channel.SendMessage("Given index was out of range").ConfigureAwait(false); await channel.SendMessageAsync("Given index was out of range").ConfigureAwait(false);
return; return;
} }
@ -184,7 +184,7 @@ namespace NadekoBot.Modules.Administration.Commands
message = $"Deleted custom reaction: `{name}`"; message = $"Deleted custom reaction: `{name}`";
} }
await Classes.JSONModels.ConfigHandler.SaveConfig().ConfigureAwait(false); await Classes.JSONModels.ConfigHandler.SaveConfig().ConfigureAwait(false);
await e.Channel.SendMessage(message).ConfigureAwait(false); await channel.SendMessageAsync(message).ConfigureAwait(false);
}); });
} }

View File

@ -42,7 +42,7 @@ namespace NadekoBot.Modules.Administration.Commands
var usr = e.Message.MentionedUsers.FirstOrDefault(u => u != e.User); var usr = e.Message.MentionedUsers.FirstOrDefault(u => u != e.User);
if (usr?.Status != UserStatus.Offline) if (usr?.Status != UserStatus.Offline)
return; return;
await e.Channel.SendMessage($"User `{usr.Name}` is offline. PM sent.").ConfigureAwait(false); await channel.SendMessageAsync($"User `{usr.Name}` is offline. PM sent.").ConfigureAwait(false);
await usr.SendMessage( await usr.SendMessage(
$"User `{e.User.Name}` mentioned you on " + $"User `{e.User.Name}` mentioned you on " +
$"`{e.Server.Name}` server while you were offline.\n" + $"`{e.Server.Name}` server while you were offline.\n" +
@ -383,10 +383,10 @@ namespace NadekoBot.Modules.Administration.Commands
specificConfig.SendPrivateMessageOnMention = specificConfig.SendPrivateMessageOnMention =
!specificConfig.SendPrivateMessageOnMention; !specificConfig.SendPrivateMessageOnMention;
if (specificConfig.SendPrivateMessageOnMention) if (specificConfig.SendPrivateMessageOnMention)
await e.Channel.SendMessage(":ok: I will send private messages " + await channel.SendMessageAsync(":ok: I will send private messages " +
"to mentioned offline users.").ConfigureAwait(false); "to mentioned offline users.").ConfigureAwait(false);
else else
await e.Channel.SendMessage(":ok: I won't send private messages " + await channel.SendMessageAsync(":ok: I won't send private messages " +
"to mentioned offline users anymore.").ConfigureAwait(false); "to mentioned offline users anymore.").ConfigureAwait(false);
}); });
@ -400,7 +400,7 @@ namespace NadekoBot.Modules.Administration.Commands
if (chId == null) if (chId == null)
{ {
SpecificConfigurations.Default.Of(e.Server.Id).LogServerChannel = e.Channel.Id; SpecificConfigurations.Default.Of(e.Server.Id).LogServerChannel = e.Channel.Id;
await e.Channel.SendMessage($"❗**I WILL BEGIN LOGGING SERVER ACTIVITY IN THIS CHANNEL**❗").ConfigureAwait(false); await channel.SendMessageAsync($"❗**I WILL BEGIN LOGGING SERVER ACTIVITY IN THIS CHANNEL**❗").ConfigureAwait(false);
return; return;
} }
Channel ch; Channel ch;
@ -408,7 +408,7 @@ namespace NadekoBot.Modules.Administration.Commands
return; return;
SpecificConfigurations.Default.Of(e.Server.Id).LogServerChannel = null; SpecificConfigurations.Default.Of(e.Server.Id).LogServerChannel = null;
await e.Channel.SendMessage($"❗**NO LONGER LOGGING IN {ch.Mention} CHANNEL**❗").ConfigureAwait(false); await channel.SendMessageAsync($"❗**NO LONGER LOGGING IN {ch.Mention} CHANNEL**❗").ConfigureAwait(false);
}); });
@ -421,12 +421,12 @@ namespace NadekoBot.Modules.Administration.Commands
var config = SpecificConfigurations.Default.Of(e.Server.Id); var config = SpecificConfigurations.Default.Of(e.Server.Id);
if (config.LogserverIgnoreChannels.Remove(e.Channel.Id)) if (config.LogserverIgnoreChannels.Remove(e.Channel.Id))
{ {
await e.Channel.SendMessage($"`{Prefix}logserver will stop ignoring this channel.`"); await channel.SendMessageAsync($"`{Prefix}logserver will stop ignoring this channel.`");
} }
else else
{ {
config.LogserverIgnoreChannels.Add(e.Channel.Id); config.LogserverIgnoreChannels.Add(e.Channel.Id);
await e.Channel.SendMessage($"`{Prefix}logserver will ignore this channel.`"); await channel.SendMessageAsync($"`{Prefix}logserver will ignore this channel.`");
} }
}); });
@ -439,11 +439,11 @@ namespace NadekoBot.Modules.Administration.Commands
if (chId == null) if (chId == null)
{ {
SpecificConfigurations.Default.Of(e.Server.Id).LogPresenceChannel = e.Channel.Id; SpecificConfigurations.Default.Of(e.Server.Id).LogPresenceChannel = e.Channel.Id;
await e.Channel.SendMessage($"**User presence notifications enabled.**").ConfigureAwait(false); await channel.SendMessageAsync($"**User presence notifications enabled.**").ConfigureAwait(false);
return; return;
} }
SpecificConfigurations.Default.Of(e.Server.Id).LogPresenceChannel = null; SpecificConfigurations.Default.Of(e.Server.Id).LogPresenceChannel = null;
await e.Channel.SendMessage($"**User presence notifications disabled.**").ConfigureAwait(false); await channel.SendMessageAsync($"**User presence notifications disabled.**").ConfigureAwait(false);
}); });
cgb.CreateCommand(Module.Prefix + "voicepresence") cgb.CreateCommand(Module.Prefix + "voicepresence")
@ -460,23 +460,23 @@ namespace NadekoBot.Modules.Administration.Commands
{ {
config.VoiceChannelLog.TryAdd(voiceChannel.Id, e.Channel.Id); config.VoiceChannelLog.TryAdd(voiceChannel.Id, e.Channel.Id);
} }
await e.Channel.SendMessage("Started logging user presence for **ALL** voice channels!").ConfigureAwait(false); await channel.SendMessageAsync("Started logging user presence for **ALL** voice channels!").ConfigureAwait(false);
return; return;
} }
if (e.User.VoiceChannel == null) if (e.User.VoiceChannel == null)
{ {
await e.Channel.SendMessage("💢 You are not in a voice channel right now. If you are, please rejoin it.").ConfigureAwait(false); await channel.SendMessageAsync("💢 You are not in a voice channel right now. If you are, please rejoin it.").ConfigureAwait(false);
return; return;
} }
ulong throwaway; ulong throwaway;
if (!config.VoiceChannelLog.TryRemove(e.User.VoiceChannel.Id, out throwaway)) if (!config.VoiceChannelLog.TryRemove(e.User.VoiceChannel.Id, out throwaway))
{ {
config.VoiceChannelLog.TryAdd(e.User.VoiceChannel.Id, e.Channel.Id); config.VoiceChannelLog.TryAdd(e.User.VoiceChannel.Id, e.Channel.Id);
await e.Channel.SendMessage($"`Logging user updates for` {e.User.VoiceChannel.Mention} `voice channel.`").ConfigureAwait(false); await channel.SendMessageAsync($"`Logging user updates for` {e.User.VoiceChannel.Mention} `voice channel.`").ConfigureAwait(false);
} }
else else
await e.Channel.SendMessage($"`Stopped logging user updates for` {e.User.VoiceChannel.Mention} `voice channel.`").ConfigureAwait(false); await channel.SendMessageAsync($"`Stopped logging user updates for` {e.User.VoiceChannel.Mention} `voice channel.`").ConfigureAwait(false);
}); });
} }
} }

View File

@ -64,7 +64,7 @@ namespace NadekoBot.Modules.Administration.Commands
Repeater rep; Repeater rep;
if (!repeaters.TryGetValue(e.Server, out rep)) if (!repeaters.TryGetValue(e.Server, out rep))
{ {
await e.Channel.SendMessage("`No repeating message found on this server.`"); await channel.SendMessageAsync("`No repeating message found on this server.`");
return; return;
} }
@ -90,13 +90,13 @@ namespace NadekoBot.Modules.Administration.Commands
if (!repeaters.TryRemove(e.Server, out rep)) if (!repeaters.TryRemove(e.Server, out rep))
return; return;
rep.MessageTimer.Stop(); rep.MessageTimer.Stop();
await e.Channel.SendMessage("Repeating disabled").ConfigureAwait(false); await channel.SendMessageAsync("Repeating disabled").ConfigureAwait(false);
return; return;
} }
int minutes; int minutes;
if (!int.TryParse(minutesStr, out minutes) || minutes < 1 || minutes > 1440) if (!int.TryParse(minutesStr, out minutes) || minutes < 1 || minutes > 1440)
{ {
await e.Channel.SendMessage("Invalid value").ConfigureAwait(false); await channel.SendMessageAsync("Invalid value").ConfigureAwait(false);
return; return;
} }
@ -117,7 +117,7 @@ namespace NadekoBot.Modules.Administration.Commands
repeater.MessageTimer.Stop(); repeater.MessageTimer.Stop();
repeater.MessageTimer.Start(); repeater.MessageTimer.Start();
await e.Channel.SendMessage(String.Format("👌 Repeating `{0}` every " + await channel.SendMessageAsync(String.Format("👌 Repeating `{0}` every " +
"**{1}** minutes on {2} channel.", "**{1}** minutes on {2} channel.",
repeater.RepeatingMessage, minutes, repeater.RepeatingChannel)) repeater.RepeatingMessage, minutes, repeater.RepeatingChannel))
.ConfigureAwait(false); .ConfigureAwait(false);

View File

@ -89,7 +89,7 @@ namespace NadekoBot.Modules.Administration.Commands
finally { finally {
playingPlaceholderLock.Release(); playingPlaceholderLock.Release();
} }
await e.Channel.SendMessage($"❗`Rotating playing status has been {(timer.Enabled ? "enabled" : "disabled")}.`").ConfigureAwait(false); await channel.SendMessageAsync($"❗`Rotating playing status has been {(timer.Enabled ? "enabled" : "disabled")}.`").ConfigureAwait(false);
}; };
internal override void Init(CommandGroupBuilder cgb) internal override void Init(CommandGroupBuilder cgb)
@ -121,7 +121,7 @@ namespace NadekoBot.Modules.Administration.Commands
{ {
playingPlaceholderLock.Release(); playingPlaceholderLock.Release();
} }
await e.Channel.SendMessage("🆗 `Added a new playing string.`").ConfigureAwait(false); await channel.SendMessageAsync("🆗 `Added a new playing string.`").ConfigureAwait(false);
}); });
cgb.CreateCommand(Module.Prefix + "listplaying") cgb.CreateCommand(Module.Prefix + "listplaying")
@ -131,14 +131,14 @@ namespace NadekoBot.Modules.Administration.Commands
.Do(async e => .Do(async e =>
{ {
if (NadekoBot.Config.RotatingStatuses.Count == 0) if (NadekoBot.Config.RotatingStatuses.Count == 0)
await e.Channel.SendMessage("`There are no playing strings. " + await channel.SendMessageAsync("`There are no playing strings. " +
"Add some with .addplaying [text] command.`").ConfigureAwait(false); "Add some with .addplaying [text] command.`").ConfigureAwait(false);
var sb = new StringBuilder(); var sb = new StringBuilder();
for (var i = 0; i < NadekoBot.Config.RotatingStatuses.Count; i++) for (var i = 0; i < NadekoBot.Config.RotatingStatuses.Count; i++)
{ {
sb.AppendLine($"`{i + 1}.` {NadekoBot.Config.RotatingStatuses[i]}"); sb.AppendLine($"`{i + 1}.` {NadekoBot.Config.RotatingStatuses[i]}");
} }
await e.Channel.SendMessage(sb.ToString()).ConfigureAwait(false); await channel.SendMessageAsync(sb.ToString()).ConfigureAwait(false);
}); });
cgb.CreateCommand(Module.Prefix + "removeplaying") cgb.CreateCommand(Module.Prefix + "removeplaying")
@ -160,7 +160,7 @@ namespace NadekoBot.Modules.Administration.Commands
await ConfigHandler.SaveConfig().ConfigureAwait(false); await ConfigHandler.SaveConfig().ConfigureAwait(false);
} }
finally { playingPlaceholderLock.Release(); } finally { playingPlaceholderLock.Release(); }
await e.Channel.SendMessage($"🆗 `Removed playing string #{num}`({str})").ConfigureAwait(false); await channel.SendMessageAsync($"🆗 `Removed playing string #{num}`({str})").ConfigureAwait(false);
}); });
} }
} }

View File

@ -48,12 +48,12 @@ namespace NadekoBot.Modules.Administration.Commands
ConcurrentDictionary<ulong, DateTime> throwaway; ConcurrentDictionary<ulong, DateTime> throwaway;
if (RatelimitingChannels.TryRemove(e.Channel.Id, out throwaway)) if (RatelimitingChannels.TryRemove(e.Channel.Id, out throwaway))
{ {
await e.Channel.SendMessage("Slow mode disabled.").ConfigureAwait(false); await channel.SendMessageAsync("Slow mode disabled.").ConfigureAwait(false);
return; return;
} }
if (RatelimitingChannels.TryAdd(e.Channel.Id, new ConcurrentDictionary<ulong, DateTime>())) if (RatelimitingChannels.TryAdd(e.Channel.Id, new ConcurrentDictionary<ulong, DateTime>()))
{ {
await e.Channel.SendMessage("Slow mode initiated. " + await channel.SendMessageAsync("Slow mode initiated. " +
"Users can't send more than 1 message every 5 seconds.") "Users can't send more than 1 message every 5 seconds.")
.ConfigureAwait(false); .ConfigureAwait(false);
} }

View File

@ -40,7 +40,7 @@ namespace NadekoBot.Modules.Administration.Commands
msg.AppendLine($":ok:Role **{role.Name}** added to the list."); msg.AppendLine($":ok:Role **{role.Name}** added to the list.");
} }
} }
await e.Channel.SendMessage(msg.ToString()).ConfigureAwait(false); await channel.SendMessageAsync(msg.ToString()).ConfigureAwait(false);
}); });
cgb.CreateCommand(Module.Prefix + "rsar") cgb.CreateCommand(Module.Prefix + "rsar")
@ -55,17 +55,17 @@ namespace NadekoBot.Modules.Administration.Commands
var role = e.Server.FindRoles(roleName).FirstOrDefault(); var role = e.Server.FindRoles(roleName).FirstOrDefault();
if (role == null) if (role == null)
{ {
await e.Channel.SendMessage(":anger:That role does not exist.").ConfigureAwait(false); await channel.SendMessageAsync(":anger:That role does not exist.").ConfigureAwait(false);
return; return;
} }
var config = SpecificConfigurations.Default.Of(e.Server.Id); var config = SpecificConfigurations.Default.Of(e.Server.Id);
if (!config.ListOfSelfAssignableRoles.Contains(role.Id)) if (!config.ListOfSelfAssignableRoles.Contains(role.Id))
{ {
await e.Channel.SendMessage(":anger:That role is not self-assignable.").ConfigureAwait(false); await channel.SendMessageAsync(":anger:That role is not self-assignable.").ConfigureAwait(false);
return; return;
} }
config.ListOfSelfAssignableRoles.Remove(role.Id); config.ListOfSelfAssignableRoles.Remove(role.Id);
await e.Channel.SendMessage($":ok:**{role.Name}** has been removed from the list of self-assignable roles").ConfigureAwait(false); await channel.SendMessageAsync($":ok:**{role.Name}** has been removed from the list of self-assignable roles").ConfigureAwait(false);
}); });
cgb.CreateCommand(Module.Prefix + "lsar") cgb.CreateCommand(Module.Prefix + "lsar")
@ -93,7 +93,7 @@ namespace NadekoBot.Modules.Administration.Commands
{ {
config.ListOfSelfAssignableRoles.Remove(id); config.ListOfSelfAssignableRoles.Remove(id);
} }
await e.Channel.SendMessage(msg.ToString()).ConfigureAwait(false); await channel.SendMessageAsync(msg.ToString()).ConfigureAwait(false);
}); });
@ -106,7 +106,7 @@ namespace NadekoBot.Modules.Administration.Commands
var config = SpecificConfigurations.Default.Of(e.Server.Id); var config = SpecificConfigurations.Default.Of(e.Server.Id);
config.ExclusiveSelfAssignedRoles = !config.ExclusiveSelfAssignedRoles; config.ExclusiveSelfAssignedRoles = !config.ExclusiveSelfAssignedRoles;
string exl = config.ExclusiveSelfAssignedRoles ? "exclusive" : "not exclusive"; string exl = config.ExclusiveSelfAssignedRoles ? "exclusive" : "not exclusive";
await e.Channel.SendMessage("Self assigned roles are now " + exl); await channel.SendMessageAsync("Self assigned roles are now " + exl);
}); });
cgb.CreateCommand(Module.Prefix + "iam") cgb.CreateCommand(Module.Prefix + "iam")
@ -122,24 +122,24 @@ namespace NadekoBot.Modules.Administration.Commands
var role = e.Server.FindRoles(roleName).FirstOrDefault(); var role = e.Server.FindRoles(roleName).FirstOrDefault();
if (role == null) if (role == null)
{ {
await e.Channel.SendMessage(":anger:That role does not exist.").ConfigureAwait(false); await channel.SendMessageAsync(":anger:That role does not exist.").ConfigureAwait(false);
return; return;
} }
var config = SpecificConfigurations.Default.Of(e.Server.Id); var config = SpecificConfigurations.Default.Of(e.Server.Id);
if (!config.ListOfSelfAssignableRoles.Contains(role.Id)) if (!config.ListOfSelfAssignableRoles.Contains(role.Id))
{ {
await e.Channel.SendMessage(":anger:That role is not self-assignable.").ConfigureAwait(false); await channel.SendMessageAsync(":anger:That role is not self-assignable.").ConfigureAwait(false);
return; return;
} }
if (e.User.HasRole(role)) if (e.User.HasRole(role))
{ {
await e.Channel.SendMessage($":anger:You already have {role.Name} role.").ConfigureAwait(false); await channel.SendMessageAsync($":anger:You already have {role.Name} role.").ConfigureAwait(false);
return; return;
} }
var sameRoles = e.User.Roles.Where(r => config.ListOfSelfAssignableRoles.Contains(r.Id)); var sameRoles = e.User.Roles.Where(r => config.ListOfSelfAssignableRoles.Contains(r.Id));
if (config.ExclusiveSelfAssignedRoles && sameRoles.Any()) if (config.ExclusiveSelfAssignedRoles && sameRoles.Any())
{ {
await e.Channel.SendMessage($":anger:You already have {sameRoles.FirstOrDefault().Name} role.").ConfigureAwait(false); await channel.SendMessageAsync($":anger:You already have {sameRoles.FirstOrDefault().Name} role.").ConfigureAwait(false);
return; return;
} }
try try
@ -151,10 +151,10 @@ namespace NadekoBot.Modules.Administration.Commands
} }
catch (Exception ex) catch (Exception ex)
{ {
await e.Channel.SendMessage($":anger:`I am unable to add that role to you. I can't add roles to owners or other roles higher than my role in the role hierarchy.`").ConfigureAwait(false); await channel.SendMessageAsync($":anger:`I am unable to add that role to you. I can't add roles to owners or other roles higher than my role in the role hierarchy.`").ConfigureAwait(false);
return; return;
} }
var msg = await e.Channel.SendMessage($":ok:You now have {role.Name} role.").ConfigureAwait(false); var msg = await channel.SendMessageAsync($":ok:You now have {role.Name} role.").ConfigureAwait(false);
await Task.Delay(3000).ConfigureAwait(false); await Task.Delay(3000).ConfigureAwait(false);
await msg.Delete().ConfigureAwait(false); await msg.Delete().ConfigureAwait(false);
try try
@ -178,22 +178,22 @@ namespace NadekoBot.Modules.Administration.Commands
var role = e.Server.FindRoles(roleName).FirstOrDefault(); var role = e.Server.FindRoles(roleName).FirstOrDefault();
if (role == null) if (role == null)
{ {
await e.Channel.SendMessage(":anger:That role does not exist.").ConfigureAwait(false); await channel.SendMessageAsync(":anger:That role does not exist.").ConfigureAwait(false);
return; return;
} }
var config = SpecificConfigurations.Default.Of(e.Server.Id); var config = SpecificConfigurations.Default.Of(e.Server.Id);
if (!config.ListOfSelfAssignableRoles.Contains(role.Id)) if (!config.ListOfSelfAssignableRoles.Contains(role.Id))
{ {
await e.Channel.SendMessage(":anger:That role is not self-assignable.").ConfigureAwait(false); await channel.SendMessageAsync(":anger:That role is not self-assignable.").ConfigureAwait(false);
return; return;
} }
if (!e.User.HasRole(role)) if (!e.User.HasRole(role))
{ {
await e.Channel.SendMessage($":anger:You don't have {role.Name} role.").ConfigureAwait(false); await channel.SendMessageAsync($":anger:You don't have {role.Name} role.").ConfigureAwait(false);
return; return;
} }
await e.User.RemoveRoles(role).ConfigureAwait(false); await e.User.RemoveRoles(role).ConfigureAwait(false);
var msg = await e.Channel.SendMessage($":ok:Successfuly removed {role.Name} role from you.").ConfigureAwait(false); var msg = await channel.SendMessageAsync($":ok:Successfuly removed {role.Name} role from you.").ConfigureAwait(false);
await Task.Delay(3000).ConfigureAwait(false); await Task.Delay(3000).ConfigureAwait(false);
await msg.Delete().ConfigureAwait(false); await msg.Delete().ConfigureAwait(false);
try try

View File

@ -24,7 +24,7 @@ namespace NadekoBot.Modules.Administration.Commands
NadekoBot.Client.FindServers(arg).FirstOrDefault(); NadekoBot.Client.FindServers(arg).FirstOrDefault();
if (server == null) if (server == null)
{ {
await e.Channel.SendMessage("Cannot find that server").ConfigureAwait(false); await channel.SendMessageAsync("Cannot find that server").ConfigureAwait(false);
return; return;
} }
if (!server.IsOwner) if (!server.IsOwner)

View File

@ -226,9 +226,9 @@ namespace NadekoBot.Modules.Administration.Commands
var ann = AnnouncementsDictionary.GetOrAdd(e.Server.Id, new AnnounceControls(e.Server.Id)); var ann = AnnouncementsDictionary.GetOrAdd(e.Server.Id, new AnnounceControls(e.Server.Id));
if (ann.ToggleDelete()) if (ann.ToggleDelete())
await e.Channel.SendMessage("`Automatic deletion of greet and bye messages has been enabled.`").ConfigureAwait(false); await channel.SendMessageAsync("`Automatic deletion of greet and bye messages has been enabled.`").ConfigureAwait(false);
else else
await e.Channel.SendMessage("`Automatic deletion of greet and bye messages has been disabled.`").ConfigureAwait(false); await channel.SendMessageAsync("`Automatic deletion of greet and bye messages has been disabled.`").ConfigureAwait(false);
}); });
cgb.CreateCommand(Module.Prefix + "greet") cgb.CreateCommand(Module.Prefix + "greet")
@ -239,9 +239,9 @@ namespace NadekoBot.Modules.Administration.Commands
var ann = AnnouncementsDictionary.GetOrAdd(e.Server.Id, new AnnounceControls(e.Server.Id)); var ann = AnnouncementsDictionary.GetOrAdd(e.Server.Id, new AnnounceControls(e.Server.Id));
if (ann.ToggleGreet(e.Channel.Id)) if (ann.ToggleGreet(e.Channel.Id))
await e.Channel.SendMessage("Greet announcements enabled on this channel.").ConfigureAwait(false); await channel.SendMessageAsync("Greet announcements enabled on this channel.").ConfigureAwait(false);
else else
await e.Channel.SendMessage("Greet announcements disabled.").ConfigureAwait(false); await channel.SendMessageAsync("Greet announcements disabled.").ConfigureAwait(false);
}); });
cgb.CreateCommand(Module.Prefix + "greetmsg") cgb.CreateCommand(Module.Prefix + "greetmsg")
@ -253,15 +253,15 @@ namespace NadekoBot.Modules.Administration.Commands
var ann = AnnouncementsDictionary.GetOrAdd(e.Server.Id, new AnnounceControls(e.Server.Id)); var ann = AnnouncementsDictionary.GetOrAdd(e.Server.Id, new AnnounceControls(e.Server.Id));
if (string.IsNullOrWhiteSpace(e.GetArg("msg"))) if (string.IsNullOrWhiteSpace(e.GetArg("msg")))
{ {
await e.Channel.SendMessage("`Current greet message:` " + ann.GreetText); await channel.SendMessageAsync("`Current greet message:` " + ann.GreetText);
return; return;
} }
ann.GreetText = e.GetArg("msg"); ann.GreetText = e.GetArg("msg");
await e.Channel.SendMessage("New greet message set.").ConfigureAwait(false); await channel.SendMessageAsync("New greet message set.").ConfigureAwait(false);
if (!ann.Greet) if (!ann.Greet)
await e.Channel.SendMessage("Enable greet messsages by typing `.greet`").ConfigureAwait(false); await channel.SendMessageAsync("Enable greet messsages by typing `.greet`").ConfigureAwait(false);
}); });
cgb.CreateCommand(Module.Prefix + "bye") cgb.CreateCommand(Module.Prefix + "bye")
@ -272,9 +272,9 @@ namespace NadekoBot.Modules.Administration.Commands
var ann = AnnouncementsDictionary.GetOrAdd(e.Server.Id, new AnnounceControls(e.Server.Id)); var ann = AnnouncementsDictionary.GetOrAdd(e.Server.Id, new AnnounceControls(e.Server.Id));
if (ann.ToggleBye(e.Channel.Id)) if (ann.ToggleBye(e.Channel.Id))
await e.Channel.SendMessage("Bye announcements enabled on this channel.").ConfigureAwait(false); await channel.SendMessageAsync("Bye announcements enabled on this channel.").ConfigureAwait(false);
else else
await e.Channel.SendMessage("Bye announcements disabled.").ConfigureAwait(false); await channel.SendMessageAsync("Bye announcements disabled.").ConfigureAwait(false);
}); });
cgb.CreateCommand(Module.Prefix + "byemsg") cgb.CreateCommand(Module.Prefix + "byemsg")
@ -286,14 +286,14 @@ namespace NadekoBot.Modules.Administration.Commands
var ann = AnnouncementsDictionary.GetOrAdd(e.Server.Id, new AnnounceControls(e.Server.Id)); var ann = AnnouncementsDictionary.GetOrAdd(e.Server.Id, new AnnounceControls(e.Server.Id));
if (string.IsNullOrWhiteSpace(e.GetArg("msg"))) if (string.IsNullOrWhiteSpace(e.GetArg("msg")))
{ {
await e.Channel.SendMessage("`Current bye message:` " + ann.ByeText); await channel.SendMessageAsync("`Current bye message:` " + ann.ByeText);
return; return;
} }
ann.ByeText = e.GetArg("msg"); ann.ByeText = e.GetArg("msg");
await e.Channel.SendMessage("New bye message set.").ConfigureAwait(false); await channel.SendMessageAsync("New bye message set.").ConfigureAwait(false);
if (!ann.Bye) if (!ann.Bye)
await e.Channel.SendMessage("Enable bye messsages by typing `.bye`.").ConfigureAwait(false); await channel.SendMessageAsync("Enable bye messsages by typing `.bye`.").ConfigureAwait(false);
}); });
cgb.CreateCommand(Module.Prefix + "byepm") cgb.CreateCommand(Module.Prefix + "byepm")
@ -305,11 +305,11 @@ namespace NadekoBot.Modules.Administration.Commands
if (ann.ToggleByePM()) if (ann.ToggleByePM())
await e.Channel.SendMessage("Bye messages will be sent in a PM from now on.\n ⚠ Keep in mind this might fail if the user and the bot have no common servers after the user leaves.").ConfigureAwait(false); await channel.SendMessageAsync("Bye messages will be sent in a PM from now on.\n ⚠ Keep in mind this might fail if the user and the bot have no common servers after the user leaves.").ConfigureAwait(false);
else else
await e.Channel.SendMessage("Bye messages will be sent in a bound channel from now on.").ConfigureAwait(false); await channel.SendMessageAsync("Bye messages will be sent in a bound channel from now on.").ConfigureAwait(false);
if (!ann.Bye) if (!ann.Bye)
await e.Channel.SendMessage("Enable bye messsages by typing `.bye`, and set the bye message using `.byemsg`").ConfigureAwait(false); await channel.SendMessageAsync("Enable bye messsages by typing `.bye`, and set the bye message using `.byemsg`").ConfigureAwait(false);
}); });
cgb.CreateCommand(Module.Prefix + "greetpm") cgb.CreateCommand(Module.Prefix + "greetpm")
@ -321,11 +321,11 @@ namespace NadekoBot.Modules.Administration.Commands
var ann = AnnouncementsDictionary.GetOrAdd(e.Server.Id, new AnnounceControls(e.Server.Id)); var ann = AnnouncementsDictionary.GetOrAdd(e.Server.Id, new AnnounceControls(e.Server.Id));
if (ann.ToggleGreetPM()) if (ann.ToggleGreetPM())
await e.Channel.SendMessage("Greet messages will be sent in a PM from now on.").ConfigureAwait(false); await channel.SendMessageAsync("Greet messages will be sent in a PM from now on.").ConfigureAwait(false);
else else
await e.Channel.SendMessage("Greet messages will be sent in a bound channel from now on.").ConfigureAwait(false); await channel.SendMessageAsync("Greet messages will be sent in a bound channel from now on.").ConfigureAwait(false);
if (!ann.Greet) if (!ann.Greet)
await e.Channel.SendMessage("Enable greet messsages by typing `.greet`, and set the greet message using `.greetmsg`").ConfigureAwait(false); await channel.SendMessageAsync("Enable greet messsages by typing `.greet`, and set the greet message using `.greetmsg`").ConfigureAwait(false);
}); });
} }
} }

View File

@ -95,7 +95,7 @@ namespace NadekoBot.Modules.Administration.Commands
{ {
if (!e.Server.CurrentUser.ServerPermissions.ManageChannels) if (!e.Server.CurrentUser.ServerPermissions.ManageChannels)
{ {
await e.Channel.SendMessage("`I have insufficient permission to do that.`"); await channel.SendMessageAsync("`I have insufficient permission to do that.`");
return; return;
} }
@ -114,7 +114,7 @@ namespace NadekoBot.Modules.Administration.Commands
await Task.Delay(500); await Task.Delay(500);
} }
await e.Channel.SendMessage("`Done.`"); await channel.SendMessageAsync("`Done.`");
}); });
cgb.CreateCommand(Module.Prefix + "voice+text") cgb.CreateCommand(Module.Prefix + "voice+text")
@ -139,24 +139,24 @@ namespace NadekoBot.Modules.Administration.Commands
} }
catch catch
{ {
await e.Channel.SendMessage( await channel.SendMessageAsync(
":anger: Error: Most likely i don't have permissions to do this.") ":anger: Error: Most likely i don't have permissions to do this.")
.ConfigureAwait(false); .ConfigureAwait(false);
return; return;
} }
} }
await e.Channel.SendMessage("Successfuly removed voice + text feature.").ConfigureAwait(false); await channel.SendMessageAsync("Successfuly removed voice + text feature.").ConfigureAwait(false);
return; return;
} }
config.VoicePlusTextEnabled = true; config.VoicePlusTextEnabled = true;
await e.Channel.SendMessage("Successfuly enabled voice + text feature. " + await channel.SendMessageAsync("Successfuly enabled voice + text feature. " +
"**Make sure the bot has manage roles and manage channels permissions**") "**Make sure the bot has manage roles and manage channels permissions**")
.ConfigureAwait(false); .ConfigureAwait(false);
} }
catch (Exception ex) catch (Exception ex)
{ {
await e.Channel.SendMessage(ex.ToString()).ConfigureAwait(false); await channel.SendMessageAsync(ex.ToString()).ConfigureAwait(false);
} }
}); });
} }

View File

@ -1,418 +0,0 @@
using Discord.Commands;
using Discord.Modules;
using NadekoBot.Classes.ClashOfClans;
using NadekoBot.Modules.Permissions.Classes;
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;
namespace NadekoBot.Modules.ClashOfClans
{
internal class ClashOfClansModule : DiscordModule
{
public override string Prefix { get; } = NadekoBot.Config.CommandPrefixes.ClashOfClans;
public static ConcurrentDictionary<ulong, List<ClashWar>> ClashWars { get; set; } = new ConcurrentDictionary<ulong, List<ClashWar>>();
private readonly object writeLock = new object();
public ClashOfClansModule()
{
NadekoBot.OnReady += () => Task.Run(async () =>
{
if (File.Exists("data/clashofclans/wars.json"))
{
try
{
var content = File.ReadAllText("data/clashofclans/wars.json");
var dict = JsonConvert.DeserializeObject<Dictionary<ulong, List<ClashWar>>>(content);
foreach (var cw in dict)
{
cw.Value.ForEach(war =>
{
war.Channel = NadekoBot.Client.GetServer(war.ServerId)?.GetChannel(war.ChannelId);
if (war.Channel == null)
{
cw.Value.Remove(war);
}
}
);
}
//urgh
ClashWars = new ConcurrentDictionary<ulong, List<ClashWar>>(dict);
}
catch (Exception e)
{
Console.WriteLine("Could not load coc wars: " + e.Message);
}
}
//Can't this be disabled if the modules is disabled too :)
var callExpire = new TimeSpan(2, 0, 0);
var warExpire = new TimeSpan(23, 0, 0);
while (true)
{
try
{
var hash = ClashWars.GetHashCode();
foreach (var cw in ClashWars)
{
foreach (var war in cw.Value)
{
await CheckWar(callExpire, war);
}
List<ClashWar> newVal = new List<ClashWar>();
foreach (var w in cw.Value)
{
//We add when A: the war is not ended
if (w.WarState != WarState.Ended)
{
//and B: the war has not expired
if ((w.WarState == WarState.Started && DateTime.UtcNow - w.StartedAt <= warExpire) || w.WarState == WarState.Created)
{
newVal.Add(w);
}
}
}
//var newVal = cw.Value.Where(w => !(w.Ended || DateTime.UtcNow - w.StartedAt >= warExpire)).ToList();
foreach (var exWar in cw.Value.Except(newVal))
{
await exWar.Channel.SendMessage($"War against {exWar.EnemyClan} ({exWar.Size}v{exWar.Size}) has ended");
}
if (newVal.Count == 0)
{
List<ClashWar> obj;
ClashWars.TryRemove(cw.Key, out obj);
}
else
{
ClashWars.AddOrUpdate(cw.Key, newVal, (x, s) => newVal);
}
}
if (hash != ClashWars.GetHashCode()) //something changed
{
Save();
}
}
catch { }
await Task.Delay(5000);
}
});
}
private static void Save()
{
try
{
Directory.CreateDirectory("data/clashofclans");
File.WriteAllText("data/clashofclans/wars.json", JsonConvert.SerializeObject(ClashWars, Formatting.Indented));
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
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.SendMessage($"❗🔰**Claim from @{Bases[i].CallUser} for a war against {war.ShortPrint()} has expired.**").ConfigureAwait(false);
Bases[i] = null;
}
}
}
#region commands
public override void Install(ModuleManager manager)
{
manager.CreateCommands("", cgb =>
{
cgb.AddCheck(PermissionChecker.Instance);
cgb.CreateCommand(Prefix + "createwar")
.Alias(Prefix + "cw")
.Description($"Creates a new war by specifying a size (>10 and multiple of 5) and enemy clan name. | `{Prefix}cw 15 The Enemy Clan`")
.Parameter("size")
.Parameter("enemy_clan", ParameterType.Unparsed)
.Do(async e =>
{
if (!e.User.ServerPermissions.ManageChannels)
return;
var enemyClan = e.GetArg("enemy_clan");
if (string.IsNullOrWhiteSpace(enemyClan))
{
return;
}
int size;
if (!int.TryParse(e.GetArg("size"), out size) || size < 10 || size > 50 || size % 5 != 0)
{
await e.Channel.SendMessage("💢🔰 Not a Valid war size").ConfigureAwait(false);
return;
}
List<ClashWar> wars;
if (!ClashWars.TryGetValue(e.Server.Id, out wars))
{
wars = new List<ClashWar>();
if (!ClashWars.TryAdd(e.Server.Id, wars))
return;
}
var cw = new ClashWar(enemyClan, size, e.Server.Id, e.Channel.Id);
//cw.Start();
wars.Add(cw);
await e.Channel.SendMessage($"❗🔰**CREATED CLAN WAR AGAINST {cw.ShortPrint()}**").ConfigureAwait(false);
Save();
//war with the index X started.
});
cgb.CreateCommand(Prefix + "startwar")
.Alias(Prefix + "sw")
.Description("Starts a war with a given number. | `{Prefix}sw 15`")
.Parameter("number", ParameterType.Required)
.Do(async e =>
{
var warsInfo = GetInfo(e);
if (warsInfo == null)
{
await e.Channel.SendMessage("💢🔰 **That war does not exist.**").ConfigureAwait(false);
return;
}
var war = warsInfo.Item1[warsInfo.Item2];
try
{
war.Start();
await e.Channel.SendMessage($"🔰**STARTED WAR AGAINST {war.ShortPrint()}**").ConfigureAwait(false);
}
catch
{
await e.Channel.SendMessage($"🔰**WAR AGAINST {war.ShortPrint()} HAS ALREADY STARTED**").ConfigureAwait(false);
}
Save();
});
cgb.CreateCommand(Prefix + "listwar")
.Alias(Prefix + "lw")
.Description($"Shows the active war claims by a number. Shows all wars in a short way if no number is specified. | `{Prefix}lw [war_number] or {Prefix}lw`")
.Parameter("number", ParameterType.Optional)
.Do(async e =>
{
// if number is null, print all wars in a short way
if (string.IsNullOrWhiteSpace(e.GetArg("number")))
{
//check if there are any wars
List<ClashWar> wars = null;
ClashWars.TryGetValue(e.Server.Id, out wars);
if (wars == null || wars.Count == 0)
{
await e.Channel.SendMessage("🔰 **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 e.Channel.SendMessage(sb.ToString()).ConfigureAwait(false);
return;
}
//if number is not null, print the war needed
var warsInfo = GetInfo(e);
if (warsInfo == null)
{
await e.Channel.SendMessage("💢🔰 **That war does not exist.**").ConfigureAwait(false);
return;
}
await e.Channel.SendMessage(warsInfo.Item1[warsInfo.Item2].ToString()).ConfigureAwait(false);
});
cgb.CreateCommand(Prefix + "claim")
.Alias(Prefix + "call")
.Alias(Prefix + "c")
.Description($"Claims a certain base from a certain war. You can supply a name in the third optional argument to claim in someone else's place. | `{Prefix}call [war_number] [base_number] [optional_other_name]`")
.Parameter("number")
.Parameter("baseNumber")
.Parameter("other_name", ParameterType.Unparsed)
.Do(async e =>
{
var warsInfo = GetInfo(e);
if (warsInfo == null || warsInfo.Item1.Count == 0)
{
await e.Channel.SendMessage("💢🔰 **That war does not exist.**").ConfigureAwait(false);
return;
}
int baseNum;
if (!int.TryParse(e.GetArg("baseNumber"), out baseNum))
{
await e.Channel.SendMessage("💢🔰 **Invalid base number.**").ConfigureAwait(false);
return;
}
var usr =
string.IsNullOrWhiteSpace(e.GetArg("other_name")) ?
e.User.Name :
e.GetArg("other_name");
try
{
var war = warsInfo.Item1[warsInfo.Item2];
war.Call(usr, baseNum - 1);
await e.Channel.SendMessage($"🔰**{usr}** claimed a base #{baseNum} for a war against {war.ShortPrint()}").ConfigureAwait(false);
Save();
}
catch (Exception ex)
{
await e.Channel.SendMessage($"💢🔰 {ex.Message}").ConfigureAwait(false);
}
});
cgb.CreateCommand(Prefix + "claimfinish")
.Alias(Prefix + "cf")
.Alias(Prefix + "cf3")
.Alias(Prefix + "claimfinish3")
.Description($"Finish your claim with 3 stars if you destroyed a base. Optional second argument finishes for someone else. | `{Prefix}cf [war_number] [optional_other_name]`")
.Parameter("number", ParameterType.Required)
.Parameter("other_name", ParameterType.Unparsed)
.Do(e => FinishClaim(e));
cgb.CreateCommand(Prefix + "claimfinish2")
.Alias(Prefix + "cf2")
.Description($"Finish your claim with 2 stars if you destroyed a base. Optional second argument finishes for someone else. | `{Prefix}cf [war_number] [optional_other_name]`")
.Parameter("number", ParameterType.Required)
.Parameter("other_name", ParameterType.Unparsed)
.Do(e => FinishClaim(e, 2));
cgb.CreateCommand(Prefix + "claimfinish1")
.Alias(Prefix + "cf1")
.Description($"Finish your claim with 1 stars if you destroyed a base. Optional second argument finishes for someone else. | `{Prefix}cf [war_number] [optional_other_name]`")
.Parameter("number", ParameterType.Required)
.Parameter("other_name", ParameterType.Unparsed)
.Do(e => FinishClaim(e, 1));
cgb.CreateCommand(Prefix + "unclaim")
.Alias(Prefix + "uncall")
.Alias(Prefix + "uc")
.Description($"Removes your claim from a certain war. Optional second argument denotes a person in whose place to unclaim | `{Prefix}uc [war_number] [optional_other_name]`")
.Parameter("number", ParameterType.Required)
.Parameter("other_name", ParameterType.Unparsed)
.Do(async e =>
{
var warsInfo = GetInfo(e);
if (warsInfo == null || warsInfo.Item1.Count == 0)
{
await e.Channel.SendMessage("💢🔰 **That war does not exist.**").ConfigureAwait(false);
return;
}
var usr =
string.IsNullOrWhiteSpace(e.GetArg("other_name")) ?
e.User.Name :
e.GetArg("other_name");
try
{
var war = warsInfo.Item1[warsInfo.Item2];
var baseNumber = war.Uncall(usr);
await e.Channel.SendMessage($"🔰 @{usr} has **UNCLAIMED** a base #{baseNumber + 1} from a war against {war.ShortPrint()}").ConfigureAwait(false);
Save();
}
catch (Exception ex)
{
await e.Channel.SendMessage($"💢🔰 {ex.Message}").ConfigureAwait(false);
}
});
cgb.CreateCommand(Prefix + "endwar")
.Alias(Prefix + "ew")
.Description($"Ends the war with a given index. | `{Prefix}ew [war_number]`")
.Parameter("number")
.Do(async e =>
{
var warsInfo = GetInfo(e);
if (warsInfo == null)
{
await e.Channel.SendMessage("💢🔰 That war does not exist.").ConfigureAwait(false);
return;
}
warsInfo.Item1[warsInfo.Item2].End();
await e.Channel.SendMessage($"❗🔰**War against {warsInfo.Item1[warsInfo.Item2].ShortPrint()} ended.**").ConfigureAwait(false);
var size = warsInfo.Item1[warsInfo.Item2].Size;
warsInfo.Item1.RemoveAt(warsInfo.Item2);
Save();
});
});
}
#endregion
private async Task FinishClaim(CommandEventArgs e, int stars = 3)
{
var warInfo = GetInfo(e);
if (warInfo == null || warInfo.Item1.Count == 0)
{
await e.Channel.SendMessage("💢🔰 **That war does not exist.**").ConfigureAwait(false);
return;
}
var usr =
string.IsNullOrWhiteSpace(e.GetArg("other_name")) ?
e.User.Name :
e.GetArg("other_name");
var war = warInfo.Item1[warInfo.Item2];
try
{
var baseNum = war.FinishClaim(usr, stars);
await e.Channel.SendMessage($"❗🔰{e.User.Mention} **DESTROYED** a base #{baseNum + 1} in a war against {war.ShortPrint()}").ConfigureAwait(false);
Save();
}
catch (Exception ex)
{
await e.Channel.SendMessage($"💢🔰 {ex.Message}").ConfigureAwait(false);
}
}
private static Tuple<List<ClashWar>, int> GetInfo(CommandEventArgs e)
{
//check if there are any wars
List<ClashWar> wars = null;
ClashWars.TryGetValue(e.Server.Id, out wars);
if (wars == null || wars.Count == 0)
{
return null;
}
// get the number of the war
int num;
if (string.IsNullOrWhiteSpace(e.GetArg("number")))
num = 0;
else if (!int.TryParse(e.GetArg("number"), out num) || num > wars.Count)
{
return null;
}
num -= 1;
//get the actual war
return new Tuple<List<ClashWar>, int>(wars, num);
}
}
}

View File

@ -1,120 +0,0 @@
using NadekoBot.Classes;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Discord.Commands;
using System.Drawing;
using System.Drawing.Drawing2D;
using NadekoBot.Properties;
using System.IO;
using System.Drawing.Imaging;
using NadekoBot.Extensions;
namespace NadekoBot.Modules.Conversations.Commands
{
class RipCommand : DiscordCommand
{
public RipCommand(DiscordModule module) : base(module)
{
}
internal override void Init(CommandGroupBuilder cgb)
{
cgb.CreateCommand("rip")
.Description("Shows a grave image of someone with a start year | `@NadekoBot rip @Someone 2000`")
.Parameter("user", ParameterType.Required)
.Parameter("year", ParameterType.Optional)
.Do(async e =>
{
if (string.IsNullOrWhiteSpace(e.GetArg("user")))
return;
var usr = e.Channel.FindUsers(e.GetArg("user")).FirstOrDefault();
var text = "";
Stream file;
if (usr == null)
{
text = e.GetArg("user");
file = RipName(text, string.IsNullOrWhiteSpace(e.GetArg("year"))
? null
: e.GetArg("year"));
}
else
{
var avatar = await GetAvatar(usr.AvatarUrl);
text = usr.Name;
file = RipUser(text, avatar, string.IsNullOrWhiteSpace(e.GetArg("year"))
? null
: e.GetArg("year"));
}
await e.Channel.SendFile("ripzor_m8.png",
file);
});
}
/// <summary>
/// Create a RIP image of the given name and avatar, with an optional year
/// </summary>
/// <param name="name"></param>
/// <param name="avatar"></param>
/// <param name="year"></param>
/// <returns></returns>
public Stream RipUser(string name, Image avatar, string year = null)
{
var bm = Resources.rip;
int width = 300;
var fontSize = width / name.Length -2;
if (fontSize > 20) fontSize = 20;
var g = Graphics.FromImage(bm);
Font nameFont = new Font("Comic Sans MS", fontSize, FontStyle.Bold, GraphicsUnit.Pixel);
SizeF nameSize = g.MeasureString(name, nameFont);
g.DrawString(name, new Font("Comic Sans MS", fontSize, FontStyle.Bold), Brushes.Black, (bm.Width /2 - 8) - (nameSize.Width /2), 243 - nameSize.Height);
g.DrawString((year ?? "?") + " - " + DateTime.Now.Year, new Font("Consolas", 12, FontStyle.Bold), Brushes.Black, 80, 240);
g.DrawImage(avatar, 80, 135);
g.DrawImage((Image)Resources.rose_overlay, 0, 0);
g.Flush();
g.Dispose();
return bm.ToStream(ImageFormat.Png);
}
public Stream RipName(string name, string year = null)
{
var bm = Resources.rip;
int width = 190;
var offset = name.Length * 5;
var fontSize = width / name.Length;
if (fontSize > 20) fontSize = 20;
var g = Graphics.FromImage(bm);
Font nameFont = new Font("Comic Sans MS", fontSize, FontStyle.Bold, GraphicsUnit.Pixel);
SizeF nameSize = g.MeasureString(name, nameFont);
g.DrawString(name, nameFont, Brushes.Black, (bm.Width / 2) - (nameSize.Width / 2), 200);
g.DrawString((year ?? "?") + " - " + DateTime.Now.Year, new Font("Consolas", 12, FontStyle.Bold), Brushes.Black, 80, 235);
g.Flush();
g.Dispose();
return bm.ToStream(ImageFormat.Png);
}
public static async Task<Image> GetAvatar(string url)
{
var stream = await SearchHelper.GetResponseStreamAsync(url);
Bitmap bmp = new Bitmap(100, 100);
using (GraphicsPath gp = new GraphicsPath())
{
gp.AddEllipse(0, 0, bmp.Width, bmp.Height);
using (Graphics gr = Graphics.FromImage(bmp))
{
gr.SetClip(gp);
gr.DrawImage(Image.FromStream(stream), Point.Empty);
}
}
return bmp;
}
}
}

View File

@ -1,224 +0,0 @@
using Discord;
using Discord.Commands;
using Discord.Modules;
using NadekoBot.DataModels;
using NadekoBot.Extensions;
using NadekoBot.Modules.Conversations.Commands;
using NadekoBot.Modules.Permissions.Classes;
using System;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Threading.Tasks;
namespace NadekoBot.Modules.Conversations
{
internal class Conversations : DiscordModule
{
private const string firestr = "🔥 ด้้้้้็็็็็้้้้้็็็็็้้้้้้้้็ด้้้้้็็็็็้้้้้็็็็็้้้้้้้้็็็็็้้้้้็็็็็้้้้้้้้็็็ด้้้้้็็็็็้้้้้็็็็็้้้้้้้้็็็็็้้้้้็็็็็้้้้ 🔥";
public Conversations()
{
commands.Add(new RipCommand(this));
}
public override string Prefix { get; } = String.Format(NadekoBot.Config.CommandPrefixes.Conversations, NadekoBot.Creds.BotId);
public override void Install(ModuleManager manager)
{
var rng = new Random();
manager.CreateCommands("", cgb =>
{
cgb.AddCheck(PermissionChecker.Instance);
cgb.CreateCommand("..")
.Description("Adds a new quote with the specified name (single word) and message (no limit). | `.. abc My message`")
.Parameter("keyword", ParameterType.Required)
.Parameter("text", ParameterType.Unparsed)
.Do(async e =>
{
var text = e.GetArg("text");
if (string.IsNullOrWhiteSpace(text))
return;
await Task.Run(() =>
Classes.DbHandler.Instance.Connection.Insert(new DataModels.UserQuote()
{
DateAdded = DateTime.Now,
Keyword = e.GetArg("keyword").ToLowerInvariant(),
Text = text,
UserName = e.User.Name,
})).ConfigureAwait(false);
await e.Channel.SendMessage("`New quote added.`").ConfigureAwait(false);
});
cgb.CreateCommand("...")
.Description("Shows a random quote with a specified name. | `... abc`")
.Parameter("keyword", ParameterType.Required)
.Do(async e =>
{
var keyword = e.GetArg("keyword")?.ToLowerInvariant();
if (string.IsNullOrWhiteSpace(keyword))
return;
var quote =
Classes.DbHandler.Instance.GetRandom<DataModels.UserQuote>(
uqm => uqm.Keyword == keyword);
if (quote != null)
await e.Channel.SendMessage($"📣 {quote.Text}").ConfigureAwait(false);
else
await e.Channel.SendMessage("💢`No quote found.`").ConfigureAwait(false);
});
cgb.CreateCommand("..qdel")
.Alias("..quotedelete")
.Description("Deletes all quotes with the specified keyword. You have to either be bot owner or the creator of the quote to delete it. | `..qdel abc`")
.Parameter("quote", ParameterType.Required)
.Do(async e =>
{
var text = e.GetArg("quote")?.Trim();
if (string.IsNullOrWhiteSpace(text))
return;
await Task.Run(() =>
{
if (NadekoBot.IsOwner(e.User.Id))
Classes.DbHandler.Instance.DeleteWhere<UserQuote>(uq => uq.Keyword == text);
else
Classes.DbHandler.Instance.DeleteWhere<UserQuote>(uq => uq.Keyword == text && uq.UserName == e.User.Name);
}).ConfigureAwait(false);
await e.Channel.SendMessage("`Done.`").ConfigureAwait(false);
});
});
manager.CreateCommands(NadekoBot.BotMention, cgb =>
{
var client = manager.Client;
cgb.AddCheck(PermissionChecker.Instance);
commands.ForEach(cmd => cmd.Init(cgb));
cgb.CreateCommand("die")
.Description("Works only for the owner. Shuts the bot down. | `@NadekoBot die`")
.Do(async e =>
{
if (NadekoBot.IsOwner(e.User.Id))
{
await e.Channel.SendMessage(e.User.Mention + ", Yes, my love.").ConfigureAwait(false);
await Task.Delay(5000).ConfigureAwait(false);
Environment.Exit(0);
}
else
await e.Channel.SendMessage(e.User.Mention + ", No.").ConfigureAwait(false);
});
var randServerSw = new Stopwatch();
randServerSw.Start();
cgb.CreateCommand("do you love me")
.Description("Replies with positive answer only to the bot owner. | `@NadekoBot do you love me`")
.Do(async e =>
{
if (NadekoBot.IsOwner(e.User.Id))
await e.Channel.SendMessage(e.User.Mention + ", Of course I do, my Master.").ConfigureAwait(false);
else
await e.Channel.SendMessage(e.User.Mention + ", Don't be silly.").ConfigureAwait(false);
});
cgb.CreateCommand("how are you")
.Alias("how are you?")
.Description("Replies positive only if bot owner is online. | `@NadekoBot how are you`")
.Do(async e =>
{
if (NadekoBot.IsOwner(e.User.Id))
{
await e.Channel.SendMessage(e.User.Mention + " I am great as long as you are here.").ConfigureAwait(false);
return;
}
var kw = e.Server.GetUser(NadekoBot.Creds.OwnerIds[0]);
if (kw != null && kw.Status == UserStatus.Online)
{
await e.Channel.SendMessage(e.User.Mention + " I am great as long as " + kw.Mention + " is with me.").ConfigureAwait(false);
}
else
{
await e.Channel.SendMessage(e.User.Mention + " I am sad. My Master is not with me.").ConfigureAwait(false);
}
});
cgb.CreateCommand("fire")
.Description("Shows a unicode fire message. Optional parameter [x] tells her how many times to repeat the fire. | `@NadekoBot fire [x]`")
.Parameter("times", ParameterType.Optional)
.Do(async e =>
{
int count;
if (string.IsNullOrWhiteSpace(e.Args[0]))
count = 1;
else
int.TryParse(e.Args[0], out count);
if (count < 1 || count > 12)
{
await e.Channel.SendMessage("Number must be between 1 and 12").ConfigureAwait(false);
return;
}
var str = new StringBuilder();
for (var i = 0; i < count; i++)
{
str.Append(firestr);
}
await e.Channel.SendMessage(str.ToString()).ConfigureAwait(false);
});
cgb.CreateCommand("dump")
.Description("Dumps all of the invites it can to dump.txt.** Owner Only.** | `@NadekoBot dump`")
.Do(async e =>
{
if (!NadekoBot.IsOwner(e.User.Id)) return;
var i = 0;
var j = 0;
var invites = "";
foreach (var s in client.Servers)
{
try
{
var invite = await s.CreateInvite(0).ConfigureAwait(false);
invites += invite.Url + "\n";
i++;
}
catch
{
j++;
continue;
}
}
File.WriteAllText("dump.txt", invites);
await e.Channel.SendMessage($"Got invites for {i} servers and failed to get invites for {j} servers")
.ConfigureAwait(false);
});
cgb.CreateCommand("ab")
.Description("Try to get 'abalabahaha'| `@NadekoBot ab`")
.Do(async e =>
{
string[] strings = { "ba", "la", "ha" };
var construct = "@a";
var cnt = rng.Next(4, 7);
while (cnt-- > 0)
{
construct += strings[rng.Next(0, strings.Length)];
}
await e.Channel.SendMessage(construct).ConfigureAwait(false);
});
});
}
private static Func<CommandEventArgs, Task> SayYes()
=> async e => await e.Channel.SendMessage("Yes. :)").ConfigureAwait(false);
}
}

View File

@ -58,7 +58,7 @@ namespace NadekoBot.Modules.CustomReactions
commandFuncs.Keys.ForEach(key => str = key.Replace(str, m => commandFuncs[key](e, m))); commandFuncs.Keys.ForEach(key => str = key.Replace(str, m => commandFuncs[key](e, m)));
await e.Channel.SendMessage(str).ConfigureAwait(false); await channel.SendMessageAsync(str).ConfigureAwait(false);
}); });
} }
}); });

View File

@ -48,7 +48,7 @@ namespace NadekoBot.Modules.Gambling.Commands
if (userFlowers < amount) if (userFlowers < amount)
{ {
await e.Channel.SendMessage($"{e.User.Mention} You don't have enough {NadekoBot.Config.CurrencyName}s. You only have {userFlowers}{NadekoBot.Config.CurrencySign}.").ConfigureAwait(false); await channel.SendMessageAsync($"{e.User.Mention} You don't have enough {NadekoBot.Config.CurrencyName}s. You only have {userFlowers}{NadekoBot.Config.CurrencySign}.").ConfigureAwait(false);
return; return;
} }
@ -58,7 +58,7 @@ namespace NadekoBot.Modules.Gambling.Commands
AnimalRace ar; AnimalRace ar;
if (!AnimalRaces.TryGetValue(e.Server.Id, out ar)) if (!AnimalRaces.TryGetValue(e.Server.Id, out ar))
{ {
await e.Channel.SendMessage("No race exists on this server"); await channel.SendMessageAsync("No race exists on this server");
return; return;
} }
await ar.JoinRace(e.User, amount); await ar.JoinRace(e.User, amount);

View File

@ -80,7 +80,7 @@ namespace NadekoBot.Modules.Gambling
arr[i] = r.Next(1, n2 + 1); arr[i] = r.Next(1, n2 + 1);
} }
var elemCnt = 0; var elemCnt = 0;
await e.Channel.SendMessage($"`Rolled {n1} {(n1 == 1 ? "die" : "dice")} 1-{n2}.`\n`Result:` " + string.Join(", ", (ordered ? arr.OrderBy(x => x).AsEnumerable() : arr).Select(x => elemCnt++ % 2 == 0 ? $"**{x}**" : x.ToString()))).ConfigureAwait(false); await channel.SendMessageAsync($"`Rolled {n1} {(n1 == 1 ? "die" : "dice")} 1-{n2}.`\n`Result:` " + string.Join(", ", (ordered ? arr.OrderBy(x => x).AsEnumerable() : arr).Select(x => elemCnt++ % 2 == 0 ? $"**{x}**" : x.ToString()))).ConfigureAwait(false);
} }
return; return;
} }
@ -90,7 +90,7 @@ namespace NadekoBot.Modules.Gambling
if (num < 1) num = 1; if (num < 1) num = 1;
if (num > 30) if (num > 30)
{ {
await e.Channel.SendMessage("You can roll up to 30 dice at a time.").ConfigureAwait(false); await channel.SendMessageAsync("You can roll up to 30 dice at a time.").ConfigureAwait(false);
num = 30; num = 30;
} }
var dices = new List<Image>(num); var dices = new List<Image>(num);
@ -121,12 +121,12 @@ namespace NadekoBot.Modules.Gambling
} }
var bitmap = dices.Merge(); var bitmap = dices.Merge();
await e.Channel.SendMessage(values.Count + " Dice rolled. Total: **" + values.Sum() + "** Average: **" + (values.Sum() / (1.0f * values.Count)).ToString("N2") + "**").ConfigureAwait(false); await channel.SendMessageAsync(values.Count + " Dice rolled. Total: **" + values.Sum() + "** Average: **" + (values.Sum() / (1.0f * values.Count)).ToString("N2") + "**").ConfigureAwait(false);
await e.Channel.SendFile("dice.png", bitmap.ToStream(ImageFormat.Png)).ConfigureAwait(false); await e.Channel.SendFile("dice.png", bitmap.ToStream(ImageFormat.Png)).ConfigureAwait(false);
} }
catch catch
{ {
await e.Channel.SendMessage("Please enter a number of dice to roll.").ConfigureAwait(false); await channel.SendMessageAsync("Please enter a number of dice to roll.").ConfigureAwait(false);
} }
}; };
} }
@ -153,11 +153,11 @@ namespace NadekoBot.Modules.Gambling
rolled = new Random().Next(0, int.Parse(e.GetArg("range")) + 1); rolled = new Random().Next(0, int.Parse(e.GetArg("range")) + 1);
} }
await e.Channel.SendMessage($"{e.User.Mention} rolled **{rolled}**.").ConfigureAwait(false); await channel.SendMessageAsync($"{e.User.Mention} rolled **{rolled}**.").ConfigureAwait(false);
} }
catch (Exception ex) catch (Exception ex)
{ {
await e.Channel.SendMessage($":anger: {ex.Message}").ConfigureAwait(false); await channel.SendMessageAsync($":anger: {ex.Message}").ConfigureAwait(false);
} }
}; };
} }

View File

@ -41,7 +41,7 @@ namespace NadekoBot.Modules.Gambling
return c; return c;
}); });
await e.Channel.SendMessage("Deck reshuffled.").ConfigureAwait(false); await channel.SendMessageAsync("Deck reshuffled.").ConfigureAwait(false);
}; };
} }
@ -68,7 +68,7 @@ namespace NadekoBot.Modules.Gambling
{ {
if (cards.CardPool.Count == 0 && i != 0) if (cards.CardPool.Count == 0 && i != 0)
{ {
await e.Channel.SendMessage("No more cards in a deck.").ConfigureAwait(false); await channel.SendMessageAsync("No more cards in a deck.").ConfigureAwait(false);
break; break;
} }
var currentCard = cards.DrawACard(); var currentCard = cards.DrawACard();
@ -79,7 +79,7 @@ namespace NadekoBot.Modules.Gambling
await e.Channel.SendFile(images.Count + " cards.jpg", bitmap.ToStream()).ConfigureAwait(false); await e.Channel.SendFile(images.Count + " cards.jpg", bitmap.ToStream()).ConfigureAwait(false);
if (cardObjects.Count == 5) if (cardObjects.Count == 5)
{ {
await e.Channel.SendMessage($"{e.User.Mention} `{Cards.GetHandValue(cardObjects)}`").ConfigureAwait(false); await channel.SendMessageAsync($"{e.User.Mention} `{Cards.GetHandValue(cardObjects)}`").ConfigureAwait(false);
} }
} }
catch (Exception ex) catch (Exception ex)

View File

@ -47,7 +47,7 @@ namespace NadekoBot.Modules.Gambling
if (userFlowers < amount) if (userFlowers < amount)
{ {
await e.Channel.SendMessage($"{e.User.Mention} You don't have enough {NadekoBot.Config.CurrencyName}s. You only have {userFlowers}{NadekoBot.Config.CurrencySign}.").ConfigureAwait(false); await channel.SendMessageAsync($"{e.User.Mention} You don't have enough {NadekoBot.Config.CurrencyName}s. You only have {userFlowers}{NadekoBot.Config.CurrencySign}.").ConfigureAwait(false);
return; return;
} }
@ -75,7 +75,7 @@ namespace NadekoBot.Modules.Gambling
else else
str = $"{e.User.Mention}`More luck next time.`"; str = $"{e.User.Mention}`More luck next time.`";
await e.Channel.SendMessage(str).ConfigureAwait(false); await channel.SendMessageAsync(str).ConfigureAwait(false);
}; };
public Func<CommandEventArgs, Task> FlipCoinFunc() => async e => public Func<CommandEventArgs, Task> FlipCoinFunc() => async e =>
@ -105,7 +105,7 @@ namespace NadekoBot.Modules.Gambling
await e.Channel.SendFile($"{result} coins.png", imgs.Merge().ToStream(System.Drawing.Imaging.ImageFormat.Png)).ConfigureAwait(false); await e.Channel.SendFile($"{result} coins.png", imgs.Merge().ToStream(System.Drawing.Imaging.ImageFormat.Png)).ConfigureAwait(false);
return; return;
} }
await e.Channel.SendMessage("Invalid number").ConfigureAwait(false); await channel.SendMessageAsync("Invalid number").ConfigureAwait(false);
} }
}; };
} }

View File

@ -41,13 +41,13 @@ namespace NadekoBot.Modules.Gambling
var role = e.Server.FindRoles(arg).FirstOrDefault(); var role = e.Server.FindRoles(arg).FirstOrDefault();
if (role == null) if (role == null)
{ {
await e.Channel.SendMessage("💢 Role not found.").ConfigureAwait(false); await channel.SendMessageAsync("💢 Role not found.").ConfigureAwait(false);
return; return;
} }
var members = role.Members.Where(u => u.Status == UserStatus.Online); // only online var members = role.Members.Where(u => u.Status == UserStatus.Online); // only online
var membersArray = members as User[] ?? members.ToArray(); var membersArray = members as User[] ?? members.ToArray();
var usr = membersArray[new Random().Next(0, membersArray.Length)]; var usr = membersArray[new Random().Next(0, membersArray.Length)];
await e.Channel.SendMessage($"**Raffled user:** {usr.Name} (id: {usr.Id})").ConfigureAwait(false); await channel.SendMessageAsync($"**Raffled user:** {usr.Name} (id: {usr.Id})").ConfigureAwait(false);
}); });
cgb.CreateCommand(Prefix + "$$") cgb.CreateCommand(Prefix + "$$")
@ -59,7 +59,7 @@ namespace NadekoBot.Modules.Gambling
var usr = e.Message.MentionedUsers.FirstOrDefault() ?? e.User; var usr = e.Message.MentionedUsers.FirstOrDefault() ?? e.User;
var pts = GetUserFlowers(usr.Id); var pts = GetUserFlowers(usr.Id);
var str = $"{usr.Name} has {pts} {NadekoBot.Config.CurrencySign}"; var str = $"{usr.Name} has {pts} {NadekoBot.Config.CurrencySign}";
await e.Channel.SendMessage(str).ConfigureAwait(false); await channel.SendMessageAsync(str).ConfigureAwait(false);
}); });
cgb.CreateCommand(Prefix + "give") cgb.CreateCommand(Prefix + "give")
@ -83,14 +83,14 @@ namespace NadekoBot.Modules.Gambling
if (userFlowers < amount) if (userFlowers < amount)
{ {
await e.Channel.SendMessage($"{e.User.Mention} You don't have enough {NadekoBot.Config.CurrencyName}s. You only have {userFlowers}{NadekoBot.Config.CurrencySign}.").ConfigureAwait(false); await channel.SendMessageAsync($"{e.User.Mention} You don't have enough {NadekoBot.Config.CurrencyName}s. You only have {userFlowers}{NadekoBot.Config.CurrencySign}.").ConfigureAwait(false);
return; return;
} }
await FlowersHandler.RemoveFlowers(e.User, "Gift", (int)amount, true).ConfigureAwait(false); await FlowersHandler.RemoveFlowers(e.User, "Gift", (int)amount, true).ConfigureAwait(false);
await FlowersHandler.AddFlowersAsync(mentionedUser, "Gift", (int)amount).ConfigureAwait(false); await FlowersHandler.AddFlowersAsync(mentionedUser, "Gift", (int)amount).ConfigureAwait(false);
await e.Channel.SendMessage($"{e.User.Mention} successfully sent {amount} {NadekoBot.Config.CurrencyName}s to {mentionedUser.Mention}!").ConfigureAwait(false); await channel.SendMessageAsync($"{e.User.Mention} successfully sent {amount} {NadekoBot.Config.CurrencyName}s to {mentionedUser.Mention}!").ConfigureAwait(false);
}); });
@ -113,7 +113,7 @@ namespace NadekoBot.Modules.Gambling
await FlowersHandler.AddFlowersAsync(mentionedUser, $"Awarded by bot owner. ({e.User.Name}/{e.User.Id})", (int)amount).ConfigureAwait(false); await FlowersHandler.AddFlowersAsync(mentionedUser, $"Awarded by bot owner. ({e.User.Name}/{e.User.Id})", (int)amount).ConfigureAwait(false);
await e.Channel.SendMessage($"{e.User.Mention} successfully awarded {amount} {NadekoBot.Config.CurrencyName}s to {mentionedUser.Mention}!").ConfigureAwait(false); await channel.SendMessageAsync($"{e.User.Mention} successfully awarded {amount} {NadekoBot.Config.CurrencyName}s to {mentionedUser.Mention}!").ConfigureAwait(false);
}); });
cgb.CreateCommand(Prefix + "take") cgb.CreateCommand(Prefix + "take")
@ -135,7 +135,7 @@ namespace NadekoBot.Modules.Gambling
await FlowersHandler.RemoveFlowers(mentionedUser, $"Taken by bot owner.({e.User.Name}/{e.User.Id})", (int)amount).ConfigureAwait(false); await FlowersHandler.RemoveFlowers(mentionedUser, $"Taken by bot owner.({e.User.Name}/{e.User.Id})", (int)amount).ConfigureAwait(false);
await e.Channel.SendMessage($"{e.User.Mention} successfully took {amount} {NadekoBot.Config.CurrencyName}s from {mentionedUser.Mention}!").ConfigureAwait(false); await channel.SendMessageAsync($"{e.User.Mention} successfully took {amount} {NadekoBot.Config.CurrencyName}s from {mentionedUser.Mention}!").ConfigureAwait(false);
}); });
cgb.CreateCommand(Prefix + "betroll") cgb.CreateCommand(Prefix + "betroll")
@ -154,7 +154,7 @@ namespace NadekoBot.Modules.Gambling
if (userFlowers < amount) if (userFlowers < amount)
{ {
await e.Channel.SendMessage($"{e.User.Mention} You don't have enough {NadekoBot.Config.CurrencyName}s. You only have {userFlowers}{NadekoBot.Config.CurrencySign}.").ConfigureAwait(false); await channel.SendMessageAsync($"{e.User.Mention} You don't have enough {NadekoBot.Config.CurrencyName}s. You only have {userFlowers}{NadekoBot.Config.CurrencySign}.").ConfigureAwait(false);
return; return;
} }
@ -181,7 +181,7 @@ namespace NadekoBot.Modules.Gambling
await FlowersHandler.AddFlowersAsync(e.User, "Betroll Gamble", amount * 10, true).ConfigureAwait(false); await FlowersHandler.AddFlowersAsync(e.User, "Betroll Gamble", amount * 10, true).ConfigureAwait(false);
} }
await e.Channel.SendMessage(str).ConfigureAwait(false); await channel.SendMessageAsync(str).ConfigureAwait(false);
}); });
@ -194,7 +194,7 @@ namespace NadekoBot.Modules.Gambling
var richest = richestTemp as CurrencyState[] ?? richestTemp.ToArray(); var richest = richestTemp as CurrencyState[] ?? richestTemp.ToArray();
if (richest.Length == 0) if (richest.Length == 0)
return; return;
await e.Channel.SendMessage( await channel.SendMessageAsync(
richest.Aggregate(new StringBuilder( richest.Aggregate(new StringBuilder(
$@"```xl $@"```xl

View File

@ -90,7 +90,7 @@ namespace NadekoBot.Modules.Games.Commands
UserPoints -= 3; UserPoints -= 3;
} }
await e.Channel.SendMessage($"**ROUND {++round}**\n" + await channel.SendMessageAsync($"**ROUND {++round}**\n" +
$"{response}\n" + $"{response}\n" +
$"{nadekoResponse}\n" + $"{nadekoResponse}\n" +
$"--------------------------------\n" + $"--------------------------------\n" +
@ -100,11 +100,11 @@ namespace NadekoBot.Modules.Games.Commands
.ConfigureAwait(false); .ConfigureAwait(false);
if (round < 10) return; if (round < 10) return;
if (nadekoPoints == userPoints) if (nadekoPoints == userPoints)
await e.Channel.SendMessage("Its a draw").ConfigureAwait(false); await channel.SendMessageAsync("Its a draw").ConfigureAwait(false);
else if (nadekoPoints > userPoints) else if (nadekoPoints > userPoints)
await e.Channel.SendMessage("Nadeko won.").ConfigureAwait(false); await channel.SendMessageAsync("Nadeko won.").ConfigureAwait(false);
else else
await e.Channel.SendMessage("You won.").ConfigureAwait(false); await channel.SendMessageAsync("You won.").ConfigureAwait(false);
nadekoPoints = 0; nadekoPoints = 0;
userPoints = 0; userPoints = 0;
round = 0; round = 0;

View File

@ -93,7 +93,7 @@ namespace NadekoBot.Modules.Games.Commands
// { // {
// if (gameChannel != null) // if (gameChannel != null)
// return; // return;
// godMsg = await e.Channel.SendMessage("GAME START IN 1 SECOND....").ConfigureAwait(false); // godMsg = await channel.SendMessageAsync("GAME START IN 1 SECOND....").ConfigureAwait(false);
// gameChannel = e.Channel; // gameChannel = e.Channel;
// players[0] = new BombermanPlayer // players[0] = new BombermanPlayer
// { // {

View File

@ -310,7 +310,7 @@ namespace NadekoBot.Modules.Games.Commands
return; return;
if (string.IsNullOrWhiteSpace(text)) if (string.IsNullOrWhiteSpace(text))
return; return;
await e.Channel.SendMessage(ToLeet(text, level)).ConfigureAwait(false); await channel.SendMessageAsync(ToLeet(text, level)).ConfigureAwait(false);
}); });
} }
} }

View File

@ -49,7 +49,7 @@ namespace NadekoBot.Modules.Games.Commands
var rnd = Math.Abs(rng.Next(0,101)); var rnd = Math.Abs(rng.Next(0,101));
if (rnd == 0) if (rnd == 0)
{ {
var msgs = new[] { await e.Channel.SendFile(GetRandomCurrencyImagePath()), await e.Channel.SendMessage($"❗ A random {NadekoBot.Config.CurrencyName} appeared! Pick it up by typing `>pick`") }; var msgs = new[] { await e.Channel.SendFile(GetRandomCurrencyImagePath()), await channel.SendMessageAsync($"❗ A random {NadekoBot.Config.CurrencyName} appeared! Pick it up by typing `>pick`") };
plantedFlowerChannels.AddOrUpdate(e.Channel.Id, msgs, (u, m) => { m.ForEach(async msgToDelete => { try { await msgToDelete.Delete(); } catch { } }); return msgs; }); plantedFlowerChannels.AddOrUpdate(e.Channel.Id, msgs, (u, m) => { m.ForEach(async msgToDelete => { try { await msgToDelete.Delete(); } catch { } }); return msgs; });
plantpickCooldowns.AddOrUpdate(e.Channel.Id, now, (i, d) => now); plantpickCooldowns.AddOrUpdate(e.Channel.Id, now, (i, d) => now);
} }
@ -78,7 +78,7 @@ namespace NadekoBot.Modules.Games.Commands
await msgToDelete.Delete().ConfigureAwait(false); await msgToDelete.Delete().ConfigureAwait(false);
await FlowersHandler.AddFlowersAsync(e.User, "Picked a flower.", 1, true).ConfigureAwait(false); await FlowersHandler.AddFlowersAsync(e.User, "Picked a flower.", 1, true).ConfigureAwait(false);
var msg = await e.Channel.SendMessage($"**{e.User.Name}** picked a {NadekoBot.Config.CurrencyName}!").ConfigureAwait(false); var msg = await channel.SendMessageAsync($"**{e.User.Name}** picked a {NadekoBot.Config.CurrencyName}!").ConfigureAwait(false);
ThreadPool.QueueUserWorkItem(async (state) => ThreadPool.QueueUserWorkItem(async (state) =>
{ {
try try
@ -99,24 +99,24 @@ namespace NadekoBot.Modules.Games.Commands
{ {
if (plantedFlowerChannels.ContainsKey(e.Channel.Id)) if (plantedFlowerChannels.ContainsKey(e.Channel.Id))
{ {
await e.Channel.SendMessage($"There is already a {NadekoBot.Config.CurrencyName} in this channel.").ConfigureAwait(false); await channel.SendMessageAsync($"There is already a {NadekoBot.Config.CurrencyName} in this channel.").ConfigureAwait(false);
return; return;
} }
var removed = await FlowersHandler.RemoveFlowers(e.User, "Planted a flower.", 1, true).ConfigureAwait(false); var removed = await FlowersHandler.RemoveFlowers(e.User, "Planted a flower.", 1, true).ConfigureAwait(false);
if (!removed) if (!removed)
{ {
await e.Channel.SendMessage($"You don't have any {NadekoBot.Config.CurrencyName}s.").ConfigureAwait(false); await channel.SendMessageAsync($"You don't have any {NadekoBot.Config.CurrencyName}s.").ConfigureAwait(false);
return; return;
} }
var file = GetRandomCurrencyImagePath(); var file = GetRandomCurrencyImagePath();
Message msg; Message msg;
if (file == null) if (file == null)
msg = await e.Channel.SendMessage(NadekoBot.Config.CurrencySign).ConfigureAwait(false); msg = await channel.SendMessageAsync(NadekoBot.Config.CurrencySign).ConfigureAwait(false);
else else
msg = await e.Channel.SendFile(file).ConfigureAwait(false); msg = await e.Channel.SendFile(file).ConfigureAwait(false);
var vowelFirst = new[] { 'a', 'e', 'i', 'o', 'u' }.Contains(NadekoBot.Config.CurrencyName[0]); var vowelFirst = new[] { 'a', 'e', 'i', 'o', 'u' }.Contains(NadekoBot.Config.CurrencyName[0]);
var msg2 = await e.Channel.SendMessage($"Oh how Nice! **{e.User.Name}** planted {(vowelFirst ? "an" : "a")} {NadekoBot.Config.CurrencyName}. Pick it using {Module.Prefix}pick").ConfigureAwait(false); var msg2 = await channel.SendMessageAsync($"Oh how Nice! **{e.User.Name}** planted {(vowelFirst ? "an" : "a")} {NadekoBot.Config.CurrencyName}. Pick it using {Module.Prefix}pick").ConfigureAwait(false);
plantedFlowerChannels.TryAdd(e.Channel.Id, new[] { msg, msg2 }); plantedFlowerChannels.TryAdd(e.Channel.Id, new[] { msg, msg2 });
} }
finally { locker.Release(); } finally { locker.Release(); }
@ -139,12 +139,12 @@ namespace NadekoBot.Modules.Games.Commands
int throwaway; int throwaway;
if (config.GenerateCurrencyChannels.TryRemove(e.Channel.Id, out throwaway)) if (config.GenerateCurrencyChannels.TryRemove(e.Channel.Id, out throwaway))
{ {
await e.Channel.SendMessage("`Currency generation disabled on this channel.`").ConfigureAwait(false); await channel.SendMessageAsync("`Currency generation disabled on this channel.`").ConfigureAwait(false);
} }
else else
{ {
if (config.GenerateCurrencyChannels.TryAdd(e.Channel.Id, cd)) if (config.GenerateCurrencyChannels.TryAdd(e.Channel.Id, cd))
await e.Channel.SendMessage($"`Currency generation enabled on this channel. Cooldown is {cd} minutes.`").ConfigureAwait(false); await channel.SendMessageAsync($"`Currency generation enabled on this channel. Cooldown is {cd} minutes.`").ConfigureAwait(false);
} }
}); });
} }

View File

@ -83,7 +83,7 @@ namespace NadekoBot.Modules.Games.Commands
var num = 1; var num = 1;
msgToSend = answers.Aggregate(msgToSend, (current, answ) => current + $"`{num++}.` **{answ}**\n"); msgToSend = answers.Aggregate(msgToSend, (current, answ) => current + $"`{num++}.` **{answ}**\n");
msgToSend += "\n**Private Message me with the corresponding number of the answer.**"; msgToSend += "\n**Private Message me with the corresponding number of the answer.**";
await e.Channel.SendMessage(msgToSend).ConfigureAwait(false); await channel.SendMessageAsync(msgToSend).ConfigureAwait(false);
} }
public async Task StopPoll(Channel ch) public async Task StopPoll(Channel ch)

View File

@ -114,7 +114,7 @@ namespace NadekoBot.Modules.Games.Commands
await channel.Send($"{e.User.Mention} finished in **{sw.Elapsed.Seconds}** seconds with { distance } errors, **{ CurrentSentence.Length / WORD_VALUE / sw.Elapsed.Seconds * 60 }** WPM!").ConfigureAwait(false); await channel.Send($"{e.User.Mention} finished in **{sw.Elapsed.Seconds}** seconds with { distance } errors, **{ CurrentSentence.Length / WORD_VALUE / sw.Elapsed.Seconds * 60 }** WPM!").ConfigureAwait(false);
if (finishedUserIds.Count % 2 == 0) if (finishedUserIds.Count % 2 == 0)
{ {
await e.Channel.SendMessage($":exclamation: `A lot of people finished, here is the text for those still typing:`\n\n:book:**{CurrentSentence}**:book:").ConfigureAwait(false); await channel.SendMessageAsync($":exclamation: `A lot of people finished, here is the text for those still typing:`\n\n:book:**{CurrentSentence}**:book:").ConfigureAwait(false);
} }
} }
} }
@ -142,7 +142,7 @@ namespace NadekoBot.Modules.Games.Commands
if (game.IsActive) if (game.IsActive)
{ {
await e.Channel.SendMessage( await channel.SendMessageAsync(
$"Contest already running in " + $"Contest already running in " +
$"{game.Channell.Mention} channel.") $"{game.Channell.Mention} channel.")
.ConfigureAwait(false); .ConfigureAwait(false);
@ -162,7 +162,7 @@ namespace NadekoBot.Modules.Games.Commands
await game.Stop().ConfigureAwait(false); await game.Stop().ConfigureAwait(false);
return; return;
} }
await e.Channel.SendMessage("No contest to stop on this channel.").ConfigureAwait(false); await channel.SendMessageAsync("No contest to stop on this channel.").ConfigureAwait(false);
}; };
internal override void Init(CommandGroupBuilder cgb) internal override void Init(CommandGroupBuilder cgb)
@ -188,7 +188,7 @@ namespace NadekoBot.Modules.Games.Commands
DateAdded = DateTime.Now DateAdded = DateTime.Now
}); });
await e.Channel.SendMessage("Added new article for typing game.").ConfigureAwait(false); await channel.SendMessageAsync("Added new article for typing game.").ConfigureAwait(false);
}); });
} }
} }

View File

@ -37,12 +37,12 @@ namespace NadekoBot.Modules.Games.Commands
return; return;
var triviaGame = new TriviaGame(e, showHints, number == 0 ? 10 : number); var triviaGame = new TriviaGame(e, showHints, number == 0 ? 10 : number);
if (RunningTrivias.TryAdd(e.Server.Id, triviaGame)) if (RunningTrivias.TryAdd(e.Server.Id, triviaGame))
await e.Channel.SendMessage($"**Trivia game started! {triviaGame.WinRequirement} points needed to win.**").ConfigureAwait(false); await channel.SendMessageAsync($"**Trivia game started! {triviaGame.WinRequirement} points needed to win.**").ConfigureAwait(false);
else else
await triviaGame.StopGame().ConfigureAwait(false); await triviaGame.StopGame().ConfigureAwait(false);
} }
else else
await e.Channel.SendMessage("Trivia game is already running on this server.\n" + trivia.CurrentQuestion).ConfigureAwait(false); await channel.SendMessageAsync("Trivia game is already running on this server.\n" + trivia.CurrentQuestion).ConfigureAwait(false);
}); });
cgb.CreateCommand(Module.Prefix + "tl") cgb.CreateCommand(Module.Prefix + "tl")
@ -51,9 +51,9 @@ namespace NadekoBot.Modules.Games.Commands
{ {
TriviaGame trivia; TriviaGame trivia;
if (RunningTrivias.TryGetValue(e.Server.Id, out trivia)) if (RunningTrivias.TryGetValue(e.Server.Id, out trivia))
await e.Channel.SendMessage(trivia.GetLeaderboard()).ConfigureAwait(false); await channel.SendMessageAsync(trivia.GetLeaderboard()).ConfigureAwait(false);
else else
await e.Channel.SendMessage("No trivia is running on this server.").ConfigureAwait(false); await channel.SendMessageAsync("No trivia is running on this server.").ConfigureAwait(false);
}); });
cgb.CreateCommand(Module.Prefix + "tq") cgb.CreateCommand(Module.Prefix + "tq")
@ -66,7 +66,7 @@ namespace NadekoBot.Modules.Games.Commands
await trivia.StopGame().ConfigureAwait(false); await trivia.StopGame().ConfigureAwait(false);
} }
else else
await e.Channel.SendMessage("No trivia is running on this server.").ConfigureAwait(false); await channel.SendMessageAsync("No trivia is running on this server.").ConfigureAwait(false);
}); });
} }
} }

View File

@ -46,7 +46,7 @@ namespace NadekoBot.Modules.Games
var list = arg.Split(';'); var list = arg.Split(';');
if (list.Count() < 2) if (list.Count() < 2)
return; return;
await e.Channel.SendMessage(list[rng.Next(0, list.Length)]).ConfigureAwait(false); await channel.SendMessageAsync(list[rng.Next(0, list.Length)]).ConfigureAwait(false);
}); });
cgb.CreateCommand(Prefix + "8ball") cgb.CreateCommand(Prefix + "8ball")
@ -59,7 +59,7 @@ namespace NadekoBot.Modules.Games
return; return;
try try
{ {
await e.Channel.SendMessage( await channel.SendMessageAsync(
$":question: `Question` __**{question}**__ \n🎱 `8Ball Answers` __**{NadekoBot.Config._8BallResponses[rng.Next(0, NadekoBot.Config._8BallResponses.Length)]}**__") $":question: `Question` __**{question}**__ \n🎱 `8Ball Answers` __**{NadekoBot.Config._8BallResponses[rng.Next(0, NadekoBot.Config._8BallResponses.Length)]}**__")
.ConfigureAwait(false); .ConfigureAwait(false);
} }
@ -103,7 +103,7 @@ namespace NadekoBot.Modules.Games
else else
msg = $"{e.User.Mention} won! :{GetRPSPick(pick)}: beats :{GetRPSPick(nadekoPick)}:"; msg = $"{e.User.Mention} won! :{GetRPSPick(pick)}: beats :{GetRPSPick(nadekoPick)}:";
await e.Channel.SendMessage(msg).ConfigureAwait(false); await channel.SendMessageAsync(msg).ConfigureAwait(false);
}); });
cgb.CreateCommand(Prefix + "linux") cgb.CreateCommand(Prefix + "linux")
@ -115,7 +115,7 @@ namespace NadekoBot.Modules.Games
var guhnoo = e.Args[0]; var guhnoo = e.Args[0];
var loonix = e.Args[1]; var loonix = e.Args[1];
await e.Channel.SendMessage( await channel.SendMessageAsync(
$@" $@"
I'd just like to interject for moment. What you're refering to as {loonix}, is in fact, {guhnoo}/{loonix}, or as I've recently taken to calling it, {guhnoo} plus {loonix}. {loonix} is not an operating system unto itself, but rather another free component of a fully functioning {guhnoo} system made useful by the {guhnoo} corelibs, shell utilities and vital system components comprising a full OS as defined by POSIX. I'd just like to interject for moment. What you're refering to as {loonix}, is in fact, {guhnoo}/{loonix}, or as I've recently taken to calling it, {guhnoo} plus {loonix}. {loonix} is not an operating system unto itself, but rather another free component of a fully functioning {guhnoo} system made useful by the {guhnoo} corelibs, shell utilities and vital system components comprising a full OS as defined by POSIX.

View File

@ -31,7 +31,7 @@ namespace NadekoBot.Classes.Help.Commands
if (alias != null) if (alias != null)
str = $" / `{ com.Aliases.FirstOrDefault()}`"; str = $" / `{ com.Aliases.FirstOrDefault()}`";
if (com != null) if (com != null)
await e.Channel.SendMessage($@"**__Help for:__ `{com.Text}`**" + str + $"\n**Desc:** {new Regex(@"\|").Replace(com.Description, "\n**Usage:**", 1)}").ConfigureAwait(false); await channel.SendMessageAsync($@"**__Help for:__ `{com.Text}`**" + str + $"\n**Desc:** {new Regex(@"\|").Replace(com.Description, "\n**Usage:**", 1)}").ConfigureAwait(false);
}).ConfigureAwait(false); }).ConfigureAwait(false);
}; };
public static string HelpString { public static string HelpString {
@ -91,7 +91,7 @@ $@"######For more information and how to setup your own NadekoBot, go to: <http:
.Alias(Module.Prefix + "guide") .Alias(Module.Prefix + "guide")
.Description($"Sends a readme and a guide links to the channel. | `{Prefix}readme` or `{Prefix}guide`") .Description($"Sends a readme and a guide links to the channel. | `{Prefix}readme` or `{Prefix}guide`")
.Do(async e => .Do(async e =>
await e.Channel.SendMessage( await channel.SendMessageAsync(
@"**Wiki with all info**: <https://github.com/Kwoth/NadekoBot/wiki> @"**Wiki with all info**: <https://github.com/Kwoth/NadekoBot/wiki>
**WINDOWS SETUP GUIDE**: <https://github.com/Kwoth/NadekoBot/blob/master/ComprehensiveGuide.md> **WINDOWS SETUP GUIDE**: <https://github.com/Kwoth/NadekoBot/blob/master/ComprehensiveGuide.md>
@ -105,7 +105,7 @@ $@"######For more information and how to setup your own NadekoBot, go to: <http:
.Description($"Instructions for helping the project! | `{Prefix}donate` or `~donate`") .Description($"Instructions for helping the project! | `{Prefix}donate` or `~donate`")
.Do(async e => .Do(async e =>
{ {
await e.Channel.SendMessage( await channel.SendMessageAsync(
$@"You can support the project on patreon. <https://patreon.com/nadekobot> or $@"You can support the project on patreon. <https://patreon.com/nadekobot> or
You can send donations to `nadekodiscordbot@gmail.com` You can send donations to `nadekodiscordbot@gmail.com`
Don't forget to leave your discord name or id in the message. Don't forget to leave your discord name or id in the message.

View File

@ -32,7 +32,7 @@ namespace NadekoBot.Modules.Help
.Description($"List all bot modules. | `{Prefix}modules` or `.modules`") .Description($"List all bot modules. | `{Prefix}modules` or `.modules`")
.Do(async e => .Do(async e =>
{ {
await e.Channel.SendMessage("`List of modules:` \n• " + string.Join("\n• ", NadekoBot.Client.GetService<ModuleService>().Modules.Select(m => m.Name)) + $"\n`Type \"{Prefix}commands module_name\" to get a list of commands in that module.`") await channel.SendMessageAsync("`List of modules:` \n• " + string.Join("\n• ", NadekoBot.Client.GetService<ModuleService>().Modules.Select(m => m.Name)) + $"\n`Type \"{Prefix}commands module_name\" to get a list of commands in that module.`")
.ConfigureAwait(false); .ConfigureAwait(false);
}); });
@ -52,20 +52,20 @@ namespace NadekoBot.Modules.Help
var cmdsArray = cmds as Command[] ?? cmds.ToArray(); var cmdsArray = cmds as Command[] ?? cmds.ToArray();
if (!cmdsArray.Any()) if (!cmdsArray.Any())
{ {
await e.Channel.SendMessage("That module does not exist.").ConfigureAwait(false); await channel.SendMessageAsync("That module does not exist.").ConfigureAwait(false);
return; return;
} }
if (module != "customreactions" && module != "conversations") if (module != "customreactions" && module != "conversations")
{ {
await e.Channel.SendMessage("`List Of Commands:`\n" + SearchHelper.ShowInPrettyCode<Command>(cmdsArray, await channel.SendMessageAsync("`List Of Commands:`\n" + SearchHelper.ShowInPrettyCode<Command>(cmdsArray,
el => $"{el.Text,-15}{"[" + el.Aliases.FirstOrDefault() + "]",-8}")) el => $"{el.Text,-15}{"[" + el.Aliases.FirstOrDefault() + "]",-8}"))
.ConfigureAwait(false); .ConfigureAwait(false);
} }
else else
{ {
await e.Channel.SendMessage("`List Of Commands:`\n• " + string.Join("\n• ", cmdsArray.Select(c => $"{c.Text}"))); await channel.SendMessageAsync("`List Of Commands:`\n• " + string.Join("\n• ", cmdsArray.Select(c => $"{c.Text}")));
} }
await e.Channel.SendMessage($"`You can type \"{Prefix}h command_name\" to see the help about that specific command.`").ConfigureAwait(false); await channel.SendMessageAsync($"`You can type \"{Prefix}h command_name\" to see the help about that specific command.`").ConfigureAwait(false);
}); });
}); });
} }

View File

@ -92,9 +92,9 @@ namespace NadekoBot.Modules.Music
return; return;
musicPlayer.TogglePause(); musicPlayer.TogglePause();
if (musicPlayer.Paused) if (musicPlayer.Paused)
await e.Channel.SendMessage("🎵`Music Player paused.`").ConfigureAwait(false); await channel.SendMessageAsync("🎵`Music Player paused.`").ConfigureAwait(false);
else else
await e.Channel.SendMessage("🎵`Music Player unpaused.`").ConfigureAwait(false); await channel.SendMessageAsync("🎵`Music Player unpaused.`").ConfigureAwait(false);
}); });
cgb.CreateCommand(Prefix + "queue") cgb.CreateCommand(Prefix + "queue")
@ -137,7 +137,7 @@ namespace NadekoBot.Modules.Music
MusicPlayer musicPlayer; MusicPlayer musicPlayer;
if (!MusicPlayers.TryGetValue(e.Server, out musicPlayer)) if (!MusicPlayers.TryGetValue(e.Server, out musicPlayer))
{ {
await e.Channel.SendMessage("🎵 No active music player.").ConfigureAwait(false); await channel.SendMessageAsync("🎵 No active music player.").ConfigureAwait(false);
return; return;
} }
@ -163,7 +163,7 @@ namespace NadekoBot.Modules.Music
const int itemsPerPage = 15; const int itemsPerPage = 15;
int startAt = itemsPerPage * (page - 1); int startAt = itemsPerPage * (page - 1);
var number = 1 + startAt; var number = 1 + startAt;
await e.Channel.SendMessage(toSend + string.Join("\n", musicPlayer.Playlist.Skip(startAt).Take(15).Select(v => $"`{number++}.` {v.PrettyName}"))).ConfigureAwait(false); await channel.SendMessageAsync(toSend + string.Join("\n", musicPlayer.Playlist.Skip(startAt).Take(15).Select(v => $"`{number++}.` {v.PrettyName}"))).ConfigureAwait(false);
}); });
cgb.CreateCommand(Prefix + "nowplaying") cgb.CreateCommand(Prefix + "nowplaying")
@ -177,7 +177,7 @@ namespace NadekoBot.Modules.Music
var currentSong = musicPlayer.CurrentSong; var currentSong = musicPlayer.CurrentSong;
if (currentSong == null) if (currentSong == null)
return; return;
await e.Channel.SendMessage($"🎵`Now Playing` {currentSong.PrettyName} " + await channel.SendMessageAsync($"🎵`Now Playing` {currentSong.PrettyName} " +
$"{currentSong.PrettyCurrentTime()}").ConfigureAwait(false); $"{currentSong.PrettyCurrentTime()}").ConfigureAwait(false);
}); });
@ -196,11 +196,11 @@ namespace NadekoBot.Modules.Music
int volume; int volume;
if (!int.TryParse(arg, out volume)) if (!int.TryParse(arg, out volume))
{ {
await e.Channel.SendMessage("Volume number invalid.").ConfigureAwait(false); await channel.SendMessageAsync("Volume number invalid.").ConfigureAwait(false);
return; return;
} }
volume = musicPlayer.SetVolume(volume); volume = musicPlayer.SetVolume(volume);
await e.Channel.SendMessage($"🎵 `Volume set to {volume}%`").ConfigureAwait(false); await channel.SendMessageAsync($"🎵 `Volume set to {volume}%`").ConfigureAwait(false);
}); });
cgb.CreateCommand(Prefix + "defvol") cgb.CreateCommand(Prefix + "defvol")
@ -214,12 +214,12 @@ namespace NadekoBot.Modules.Music
float volume; float volume;
if (!float.TryParse(arg, out volume) || volume < 0 || volume > 100) if (!float.TryParse(arg, out volume) || volume < 0 || volume > 100)
{ {
await e.Channel.SendMessage("Volume number invalid.").ConfigureAwait(false); await channel.SendMessageAsync("Volume number invalid.").ConfigureAwait(false);
return; return;
} }
var conf = SpecificConfigurations.Default.Of(e.Server.Id); var conf = SpecificConfigurations.Default.Of(e.Server.Id);
conf.DefaultMusicVolume = volume / 100; conf.DefaultMusicVolume = volume / 100;
await e.Channel.SendMessage($"🎵 `Default volume set to {volume}%`").ConfigureAwait(false); await channel.SendMessageAsync($"🎵 `Default volume set to {volume}%`").ConfigureAwait(false);
}); });
cgb.CreateCommand(Prefix + "mute") cgb.CreateCommand(Prefix + "mute")
@ -271,12 +271,12 @@ namespace NadekoBot.Modules.Music
return; return;
if (musicPlayer.Playlist.Count < 2) if (musicPlayer.Playlist.Count < 2)
{ {
await e.Channel.SendMessage("💢 Not enough songs in order to perform the shuffle.").ConfigureAwait(false); await channel.SendMessageAsync("💢 Not enough songs in order to perform the shuffle.").ConfigureAwait(false);
return; return;
} }
musicPlayer.Shuffle(); musicPlayer.Shuffle();
await e.Channel.SendMessage("🎵 `Songs shuffled.`").ConfigureAwait(false); await channel.SendMessageAsync("🎵 `Songs shuffled.`").ConfigureAwait(false);
}); });
cgb.CreateCommand(Prefix + "playlist") cgb.CreateCommand(Prefix + "playlist")
@ -290,25 +290,25 @@ namespace NadekoBot.Modules.Music
return; return;
if (e.User.VoiceChannel?.Server != e.Server) if (e.User.VoiceChannel?.Server != e.Server)
{ {
await e.Channel.SendMessage("💢 You need to be in a voice channel on this server.\n If you are already in a voice channel, try rejoining it.").ConfigureAwait(false); await channel.SendMessageAsync("💢 You need to be in a voice channel on this server.\n If you are already in a voice channel, try rejoining it.").ConfigureAwait(false);
return; return;
} }
var plId = await SearchHelper.GetPlaylistIdByKeyword(arg).ConfigureAwait(false); var plId = await SearchHelper.GetPlaylistIdByKeyword(arg).ConfigureAwait(false);
if (plId == null) if (plId == null)
{ {
await e.Channel.SendMessage("No search results for that query."); await channel.SendMessageAsync("No search results for that query.");
return; return;
} }
var ids = await SearchHelper.GetVideoIDs(plId, 500).ConfigureAwait(false); var ids = await SearchHelper.GetVideoIDs(plId, 500).ConfigureAwait(false);
if (ids == null || ids.Count == 0) if (ids == null || ids.Count == 0)
{ {
await e.Channel.SendMessage($"🎵 `Failed to find any songs.`").ConfigureAwait(false); await channel.SendMessageAsync($"🎵 `Failed to find any songs.`").ConfigureAwait(false);
return; return;
} }
var idArray = ids as string[] ?? ids.ToArray(); var idArray = ids as string[] ?? ids.ToArray();
var count = idArray.Length; var count = idArray.Length;
var msg = var msg =
await e.Channel.SendMessage($"🎵 `Attempting to queue {count} songs".SnPl(count) + "...`").ConfigureAwait(false); await channel.SendMessageAsync($"🎵 `Attempting to queue {count} songs".SnPl(count) + "...`").ConfigureAwait(false);
foreach (var id in idArray) foreach (var id in idArray)
{ {
try try
@ -383,7 +383,7 @@ namespace NadekoBot.Modules.Music
} }
catch { } catch { }
} }
await e.Channel.SendMessage("🎵 `Directory queue complete.`").ConfigureAwait(false); await channel.SendMessageAsync("🎵 `Directory queue complete.`").ConfigureAwait(false);
} }
catch { } catch { }
}); });
@ -395,7 +395,7 @@ namespace NadekoBot.Modules.Music
{ {
if (e.User.VoiceChannel?.Server != e.Server) if (e.User.VoiceChannel?.Server != e.Server)
{ {
await e.Channel.SendMessage("💢 You need to be in a voice channel on this server.\n If you are already in a voice channel, try rejoining it.").ConfigureAwait(false); await channel.SendMessageAsync("💢 You need to be in a voice channel on this server.\n If you are already in a voice channel, try rejoining it.").ConfigureAwait(false);
return; return;
} }
await QueueSong(e.User, e.Channel, e.User.VoiceChannel, e.GetArg("radio_link"), musicType: MusicType.Radio).ConfigureAwait(false); await QueueSong(e.User, e.Channel, e.User.VoiceChannel, e.GetArg("radio_link"), musicType: MusicType.Radio).ConfigureAwait(false);
@ -448,7 +448,7 @@ namespace NadekoBot.Modules.Music
if (arg?.ToLower() == "all") if (arg?.ToLower() == "all")
{ {
musicPlayer.ClearQueue(); musicPlayer.ClearQueue();
await e.Channel.SendMessage($"🎵`Queue cleared!`").ConfigureAwait(false); await channel.SendMessageAsync($"🎵`Queue cleared!`").ConfigureAwait(false);
return; return;
} }
int num; int num;
@ -460,7 +460,7 @@ namespace NadekoBot.Modules.Music
return; return;
var song = (musicPlayer.Playlist as List<Song>)?[num - 1]; var song = (musicPlayer.Playlist as List<Song>)?[num - 1];
musicPlayer.RemoveSongAt(num - 1); musicPlayer.RemoveSongAt(num - 1);
await e.Channel.SendMessage($"🎵**Track {song.PrettyName} at position `#{num}` has been removed.**").ConfigureAwait(false); await channel.SendMessageAsync($"🎵**Track {song.PrettyName} at position `#{num}` has been removed.**").ConfigureAwait(false);
}); });
//var msRegex = new Regex(@"(?<n1>\d+)>(?<n2>\d+)", RegexOptions.Compiled); //var msRegex = new Regex(@"(?<n1>\d+)>(?<n2>\d+)", RegexOptions.Compiled);
@ -487,7 +487,7 @@ namespace NadekoBot.Modules.Music
!int.TryParse(fromtoArr[1], out n2) || n1 < 1 || n2 < 1 || n1 == n2 || !int.TryParse(fromtoArr[1], out n2) || n1 < 1 || n2 < 1 || n1 == n2 ||
n1 > playlist.Count || n2 > playlist.Count) n1 > playlist.Count || n2 > playlist.Count)
{ {
await e.Channel.SendMessage("`Invalid input.`").ConfigureAwait(false); await channel.SendMessageAsync("`Invalid input.`").ConfigureAwait(false);
return; return;
} }
@ -496,7 +496,7 @@ namespace NadekoBot.Modules.Music
var nn1 = n2 < n1 ? n1 : n1 - 1; var nn1 = n2 < n1 ? n1 : n1 - 1;
playlist.RemoveAt(nn1); playlist.RemoveAt(nn1);
await e.Channel.SendMessage($"🎵`Moved` {s.PrettyName} `from #{n1} to #{n2}`").ConfigureAwait(false); await channel.SendMessageAsync($"🎵`Moved` {s.PrettyName} `from #{n1} to #{n2}`").ConfigureAwait(false);
}); });
@ -520,7 +520,7 @@ namespace NadekoBot.Modules.Music
} }
musicPlayer.MaxQueueSize = size; musicPlayer.MaxQueueSize = size;
await e.Channel.SendMessage($"🎵 `Max queue set to {(size == 0 ? ("unlimited") : size + " tracks")}`"); await channel.SendMessageAsync($"🎵 `Max queue set to {(size == 0 ? ("unlimited") : size + " tracks")}`");
}); });
cgb.CreateCommand(Prefix + "cleanup") cgb.CreateCommand(Prefix + "cleanup")
@ -553,7 +553,7 @@ namespace NadekoBot.Modules.Music
if (currentSong == null) if (currentSong == null)
return; return;
var currentValue = musicPlayer.ToggleRepeatSong(); var currentValue = musicPlayer.ToggleRepeatSong();
await e.Channel.SendMessage(currentValue ? await channel.SendMessageAsync(currentValue ?
$"🎵🔂`Repeating track:`{currentSong.PrettyName}" : $"🎵🔂`Repeating track:`{currentSong.PrettyName}" :
$"🎵🔂`Current track repeat stopped.`") $"🎵🔂`Current track repeat stopped.`")
.ConfigureAwait(false); .ConfigureAwait(false);
@ -568,7 +568,7 @@ namespace NadekoBot.Modules.Music
if (!MusicPlayers.TryGetValue(e.Server, out musicPlayer)) if (!MusicPlayers.TryGetValue(e.Server, out musicPlayer))
return; return;
var currentValue = musicPlayer.ToggleRepeatPlaylist(); var currentValue = musicPlayer.ToggleRepeatPlaylist();
await e.Channel.SendMessage($"🎵🔁`Repeat playlist {(currentValue ? "enabled" : "disabled")}`").ConfigureAwait(false); await channel.SendMessageAsync($"🎵🔁`Repeat playlist {(currentValue ? "enabled" : "disabled")}`").ConfigureAwait(false);
}); });
cgb.CreateCommand(Prefix + "save") cgb.CreateCommand(Prefix + "save")
@ -620,7 +620,7 @@ namespace NadekoBot.Modules.Music
SongInfoId = s.Id.Value SongInfoId = s.Id.Value
}), typeof(PlaylistSongInfo)); }), typeof(PlaylistSongInfo));
await e.Channel.SendMessage($"🎵 `Saved playlist as {name}-{playlist.Id}`").ConfigureAwait(false); await channel.SendMessageAsync($"🎵 `Saved playlist as {name}-{playlist.Id}`").ConfigureAwait(false);
}); });
@ -655,7 +655,7 @@ namespace NadekoBot.Modules.Music
if (playlist == null) if (playlist == null)
{ {
await e.Channel.SendMessage("Can't find playlist under that name.").ConfigureAwait(false); await channel.SendMessageAsync("Can't find playlist under that name.").ConfigureAwait(false);
return; return;
} }
@ -665,7 +665,7 @@ namespace NadekoBot.Modules.Music
var songInfos = psis.Select(psi => DbHandler.Instance var songInfos = psis.Select(psi => DbHandler.Instance
.FindOne<DataModels.SongInfo>(si => si.Id == psi.SongInfoId)); .FindOne<DataModels.SongInfo>(si => si.Id == psi.SongInfoId));
await e.Channel.SendMessage($"`Attempting to load {songInfos.Count()} songs`").ConfigureAwait(false); await channel.SendMessageAsync($"`Attempting to load {songInfos.Count()} songs`").ConfigureAwait(false);
foreach (var si in songInfos) foreach (var si in songInfos)
{ {
try try
@ -695,9 +695,9 @@ namespace NadekoBot.Modules.Music
return; return;
var result = DbHandler.Instance.GetPlaylistData(num); var result = DbHandler.Instance.GetPlaylistData(num);
if (result.Count == 0) if (result.Count == 0)
e.Channel.SendMessage($"`No saved playlists found on page {num}`").ConfigureAwait(false); channel.SendMessageAsync($"`No saved playlists found on page {num}`").ConfigureAwait(false);
else else
e.Channel.SendMessage($"```js\n--- List of saved playlists ---\n\n" + string.Join("\n", result.Select(r => $"'{r.Name}-{r.Id}' by {r.Creator} ({r.SongCnt} songs)")) + $"\n\n --- Page {num} ---```").ConfigureAwait(false); channel.SendMessageAsync($"```js\n--- List of saved playlists ---\n\n" + string.Join("\n", result.Select(r => $"'{r.Name}-{r.Id}' by {r.Creator} ({r.SongCnt} songs)")) + $"\n\n --- Page {num} ---```").ConfigureAwait(false);
}); });
cgb.CreateCommand(Prefix + "deleteplaylist") cgb.CreateCommand(Prefix + "deleteplaylist")
@ -714,7 +714,7 @@ namespace NadekoBot.Modules.Music
DbHandler.Instance.Delete<MusicPlaylist>(plnum); DbHandler.Instance.Delete<MusicPlaylist>(plnum);
else else
DbHandler.Instance.DeleteWhere<MusicPlaylist>(mp => mp.Id == plnum && (long)e.User.Id == mp.CreatorId); DbHandler.Instance.DeleteWhere<MusicPlaylist>(mp => mp.Id == plnum && (long)e.User.Id == mp.CreatorId);
await e.Channel.SendMessage("`Ok.` :ok:").ConfigureAwait(false); await channel.SendMessageAsync("`Ok.` :ok:").ConfigureAwait(false);
}); });
cgb.CreateCommand(Prefix + "goto") cgb.CreateCommand(Prefix + "goto")
@ -751,7 +751,7 @@ namespace NadekoBot.Modules.Music
if (seconds.Length == 1) if (seconds.Length == 1)
seconds = "0" + seconds; seconds = "0" + seconds;
await e.Channel.SendMessage($"`Skipped to {minutes}:{seconds}`").ConfigureAwait(false); await channel.SendMessageAsync($"`Skipped to {minutes}:{seconds}`").ConfigureAwait(false);
}); });
cgb.CreateCommand(Prefix + "getlink") cgb.CreateCommand(Prefix + "getlink")
@ -771,12 +771,12 @@ namespace NadekoBot.Modules.Music
var selSong = musicPlayer.Playlist.DefaultIfEmpty(null).ElementAtOrDefault(index - 1); var selSong = musicPlayer.Playlist.DefaultIfEmpty(null).ElementAtOrDefault(index - 1);
if (selSong == null) if (selSong == null)
{ {
await e.Channel.SendMessage("Could not select song, likely wrong index"); await channel.SendMessageAsync("Could not select song, likely wrong index");
} }
else else
{ {
await e.Channel.SendMessage($"🎶`Selected song {selSong.SongInfo.Title}:` <{selSong.SongInfo.Query}>").ConfigureAwait(false); await channel.SendMessageAsync($"🎶`Selected song {selSong.SongInfo.Title}:` <{selSong.SongInfo.Query}>").ConfigureAwait(false);
} }
} }
else else
@ -784,7 +784,7 @@ namespace NadekoBot.Modules.Music
var curSong = musicPlayer.CurrentSong; var curSong = musicPlayer.CurrentSong;
if (curSong == null) if (curSong == null)
return; return;
await e.Channel.SendMessage($"🎶`Current song:` <{curSong.SongInfo.Query}>").ConfigureAwait(false); await channel.SendMessageAsync($"🎶`Current song:` <{curSong.SongInfo.Query}>").ConfigureAwait(false);
} }
}); });
@ -800,9 +800,9 @@ namespace NadekoBot.Modules.Music
return; return;
if (!musicPlayer.ToggleAutoplay()) if (!musicPlayer.ToggleAutoplay())
await e.Channel.SendMessage("🎶`Autoplay disabled.`").ConfigureAwait(false); await channel.SendMessageAsync("🎶`Autoplay disabled.`").ConfigureAwait(false);
else else
await e.Channel.SendMessage("🎶`Autoplay enabled.`").ConfigureAwait(false); await channel.SendMessageAsync("🎶`Autoplay enabled.`").ConfigureAwait(false);
}); });
}); });
} }

View File

@ -1,127 +0,0 @@
using Discord.Commands;
using Discord.Modules;
using NadekoBot.Classes;
using NadekoBot.Modules.Permissions.Classes;
using Newtonsoft.Json.Linq;
using System;
using System.Linq;
using System.Threading.Tasks;
namespace NadekoBot.Modules.NSFW
{
internal class NSFWModule : DiscordModule
{
private readonly Random rng = new Random();
public override string Prefix { get; } = NadekoBot.Config.CommandPrefixes.NSFW;
public override void Install(ModuleManager manager)
{
manager.CreateCommands("", cgb =>
{
cgb.AddCheck(PermissionChecker.Instance);
cgb.CreateCommand(Prefix + "hentai")
.Description($"Shows a random NSFW hentai image from gelbooru and danbooru with a given tag. Tag is optional but preffered. (multiple tags are appended with +) | `{Prefix}hentai yuri+kissing`")
.Parameter("tag", ParameterType.Unparsed)
.Do(async e =>
{
var tag = e.GetArg("tag")?.Trim() ?? "";
var links = await Task.WhenAll(SearchHelper.GetGelbooruImageLink("rating%3Aexplicit+" + tag), SearchHelper.GetDanbooruImageLink("rating%3Aexplicit+" + tag)).ConfigureAwait(false);
if (links.All(l => l == null))
{
await e.Channel.SendMessage("`No results.`");
return;
}
await e.Channel.SendMessage(String.Join("\n\n", links)).ConfigureAwait(false);
});
cgb.CreateCommand(Prefix + "danbooru")
.Description($"Shows a random hentai image from danbooru with a given tag. Tag is optional but preffered. (multiple tags are appended with +) | `{Prefix}danbooru yuri+kissing`")
.Parameter("tag", ParameterType.Unparsed)
.Do(async e =>
{
var tag = e.GetArg("tag")?.Trim() ?? "";
var link = await SearchHelper.GetDanbooruImageLink(tag).ConfigureAwait(false);
if (string.IsNullOrWhiteSpace(link))
await e.Channel.SendMessage("Search yielded no results ;(");
else
await e.Channel.SendMessage(link).ConfigureAwait(false);
});
cgb.CreateCommand(Prefix + "gelbooru")
.Description($"Shows a random hentai image from gelbooru with a given tag. Tag is optional but preffered. (multiple tags are appended with +) | `{Prefix}gelbooru yuri+kissing`")
.Parameter("tag", ParameterType.Unparsed)
.Do(async e =>
{
var tag = e.GetArg("tag")?.Trim() ?? "";
var link = await SearchHelper.GetGelbooruImageLink(tag).ConfigureAwait(false);
if (string.IsNullOrWhiteSpace(link))
await e.Channel.SendMessage("Search yielded no results ;(");
else
await e.Channel.SendMessage(link).ConfigureAwait(false);
});
cgb.CreateCommand(Prefix + "rule34")
.Description($"Shows a random image from rule34.xx with a given tag. Tag is optional but preffered. (multiple tags are appended with +) | `{Prefix}rule34 yuri+kissing`")
.Parameter("tag", ParameterType.Unparsed)
.Do(async e =>
{
var tag = e.GetArg("tag")?.Trim() ?? "";
var link = await SearchHelper.GetRule34ImageLink(tag).ConfigureAwait(false);
if (string.IsNullOrWhiteSpace(link))
await e.Channel.SendMessage("Search yielded no results ;(");
else
await e.Channel.SendMessage(link).ConfigureAwait(false);
});
cgb.CreateCommand(Prefix + "e621")
.Description($"Shows a random hentai image from e621.net with a given tag. Tag is optional but preffered. Use spaces for multiple tags. | `{Prefix}e621 yuri kissing`")
.Parameter("tag", ParameterType.Unparsed)
.Do(async e =>
{
var tag = e.GetArg("tag")?.Trim() ?? "";
await e.Channel.SendMessage(await SearchHelper.GetE621ImageLink(tag).ConfigureAwait(false)).ConfigureAwait(false);
});
cgb.CreateCommand(Prefix + "cp")
.Description($"We all know where this will lead you to. | `{Prefix}cp`")
.Parameter("anything", ParameterType.Unparsed)
.Do(async e =>
{
await e.Channel.SendMessage("http://i.imgur.com/MZkY1md.jpg").ConfigureAwait(false);
});
cgb.CreateCommand(Prefix + "boobs")
.Description($"Real adult content. | `{Prefix}boobs`")
.Do(async e =>
{
try
{
var obj = JArray.Parse(await SearchHelper.GetResponseStringAsync($"http://api.oboobs.ru/boobs/{rng.Next(0, 9380)}").ConfigureAwait(false))[0];
await e.Channel.SendMessage($"http://media.oboobs.ru/{ obj["preview"].ToString() }").ConfigureAwait(false);
}
catch (Exception ex)
{
await e.Channel.SendMessage($"💢 {ex.Message}").ConfigureAwait(false);
}
});
cgb.CreateCommand(Prefix + "butts")
.Alias(Prefix + "ass", Prefix + "butt")
.Description($"Real adult content. | `{Prefix}butts` or `{Prefix}ass`")
.Do(async e =>
{
try
{
var obj = JArray.Parse(await SearchHelper.GetResponseStringAsync($"http://api.obutts.ru/butts/{rng.Next(0, 3373)}").ConfigureAwait(false))[0];
await e.Channel.SendMessage($"http://media.obutts.ru/{ obj["preview"].ToString() }").ConfigureAwait(false);
}
catch (Exception ex)
{
await e.Channel.SendMessage($"💢 {ex.Message}").ConfigureAwait(false);
}
});
});
}
}
}

View File

@ -72,7 +72,7 @@ namespace NadekoBot.Modules.Permissions.Commands
? e.Channel ? e.Channel
: PermissionHelper.ValidateChannel(e.Server, chanStr); : PermissionHelper.ValidateChannel(e.Server, chanStr);
await PermissionsHandler.SetChannelFilterInvitesPermission(chan, state).ConfigureAwait(false); await PermissionsHandler.SetChannelFilterInvitesPermission(chan, state).ConfigureAwait(false);
await e.Channel.SendMessage($"Invite Filter has been **{(state ? "enabled" : "disabled")}** for **{chan.Name}** channel.") await channel.SendMessageAsync($"Invite Filter has been **{(state ? "enabled" : "disabled")}** for **{chan.Name}** channel.")
.ConfigureAwait(false); .ConfigureAwait(false);
return; return;
} }
@ -82,13 +82,13 @@ namespace NadekoBot.Modules.Permissions.Commands
{ {
await PermissionsHandler.SetChannelFilterInvitesPermission(curChannel, state).ConfigureAwait(false); await PermissionsHandler.SetChannelFilterInvitesPermission(curChannel, state).ConfigureAwait(false);
} }
await e.Channel.SendMessage($"Invite Filter has been **{(state ? "enabled" : "disabled")}** for **ALL** channels.") await channel.SendMessageAsync($"Invite Filter has been **{(state ? "enabled" : "disabled")}** for **ALL** channels.")
.ConfigureAwait(false); .ConfigureAwait(false);
} }
catch (Exception ex) catch (Exception ex)
{ {
await e.Channel.SendMessage($"💢 Error: {ex.Message}") await channel.SendMessageAsync($"💢 Error: {ex.Message}")
.ConfigureAwait(false); .ConfigureAwait(false);
} }
}); });
@ -103,13 +103,13 @@ namespace NadekoBot.Modules.Permissions.Commands
{ {
var state = PermissionHelper.ValidateBool(e.GetArg("bool")); var state = PermissionHelper.ValidateBool(e.GetArg("bool"));
await PermissionsHandler.SetServerFilterInvitesPermission(e.Server, state).ConfigureAwait(false); await PermissionsHandler.SetServerFilterInvitesPermission(e.Server, state).ConfigureAwait(false);
await e.Channel.SendMessage($"Invite Filter has been **{(state ? "enabled" : "disabled")}** for this server.") await channel.SendMessageAsync($"Invite Filter has been **{(state ? "enabled" : "disabled")}** for this server.")
.ConfigureAwait(false); .ConfigureAwait(false);
} }
catch (Exception ex) catch (Exception ex)
{ {
await e.Channel.SendMessage($"💢 Error: {ex.Message}").ConfigureAwait(false); await channel.SendMessageAsync($"💢 Error: {ex.Message}").ConfigureAwait(false);
} }
}); });
} }

View File

@ -69,7 +69,7 @@ namespace NadekoBot.Modules.Permissions.Commands
? e.Channel ? e.Channel
: PermissionHelper.ValidateChannel(e.Server, chanStr); : PermissionHelper.ValidateChannel(e.Server, chanStr);
await PermissionsHandler.SetChannelWordPermission(chan, state).ConfigureAwait(false); await PermissionsHandler.SetChannelWordPermission(chan, state).ConfigureAwait(false);
await e.Channel.SendMessage($"Word filtering has been **{(state ? "enabled" : "disabled")}** for **{chan.Name}** channel.").ConfigureAwait(false); await channel.SendMessageAsync($"Word filtering has been **{(state ? "enabled" : "disabled")}** for **{chan.Name}** channel.").ConfigureAwait(false);
return; return;
} }
//all channels //all channels
@ -78,11 +78,11 @@ namespace NadekoBot.Modules.Permissions.Commands
{ {
await PermissionsHandler.SetChannelWordPermission(curChannel, state).ConfigureAwait(false); await PermissionsHandler.SetChannelWordPermission(curChannel, state).ConfigureAwait(false);
} }
await e.Channel.SendMessage($"Word filtering has been **{(state ? "enabled" : "disabled")}** for **ALL** channels.").ConfigureAwait(false); await channel.SendMessageAsync($"Word filtering has been **{(state ? "enabled" : "disabled")}** for **ALL** channels.").ConfigureAwait(false);
} }
catch (Exception ex) catch (Exception ex)
{ {
await e.Channel.SendMessage($"💢 Error: {ex.Message}").ConfigureAwait(false); await channel.SendMessageAsync($"💢 Error: {ex.Message}").ConfigureAwait(false);
} }
}); });
@ -99,12 +99,12 @@ namespace NadekoBot.Modules.Permissions.Commands
if (string.IsNullOrWhiteSpace(word)) if (string.IsNullOrWhiteSpace(word))
return; return;
await PermissionsHandler.AddFilteredWord(e.Server, word.ToLowerInvariant().Trim()).ConfigureAwait(false); await PermissionsHandler.AddFilteredWord(e.Server, word.ToLowerInvariant().Trim()).ConfigureAwait(false);
await e.Channel.SendMessage($"Successfully added new filtered word.").ConfigureAwait(false); await channel.SendMessageAsync($"Successfully added new filtered word.").ConfigureAwait(false);
} }
catch (Exception ex) catch (Exception ex)
{ {
await e.Channel.SendMessage($"💢 Error: {ex.Message}").ConfigureAwait(false); await channel.SendMessageAsync($"💢 Error: {ex.Message}").ConfigureAwait(false);
} }
}); });
@ -121,12 +121,12 @@ namespace NadekoBot.Modules.Permissions.Commands
if (string.IsNullOrWhiteSpace(word)) if (string.IsNullOrWhiteSpace(word))
return; return;
await PermissionsHandler.RemoveFilteredWord(e.Server, word.ToLowerInvariant().Trim()).ConfigureAwait(false); await PermissionsHandler.RemoveFilteredWord(e.Server, word.ToLowerInvariant().Trim()).ConfigureAwait(false);
await e.Channel.SendMessage($"Successfully removed filtered word.").ConfigureAwait(false); await channel.SendMessageAsync($"Successfully removed filtered word.").ConfigureAwait(false);
} }
catch (Exception ex) catch (Exception ex)
{ {
await e.Channel.SendMessage($"💢 Error: {ex.Message}").ConfigureAwait(false); await channel.SendMessageAsync($"💢 Error: {ex.Message}").ConfigureAwait(false);
} }
}); });
@ -141,12 +141,12 @@ namespace NadekoBot.Modules.Permissions.Commands
Classes.ServerPermissions serverPerms; Classes.ServerPermissions serverPerms;
if (!PermissionsHandler.PermissionsDict.TryGetValue(e.Server.Id, out serverPerms)) if (!PermissionsHandler.PermissionsDict.TryGetValue(e.Server.Id, out serverPerms))
return; return;
await e.Channel.SendMessage($"There are `{serverPerms.Words.Count}` filtered words.\n" + await channel.SendMessageAsync($"There are `{serverPerms.Words.Count}` filtered words.\n" +
string.Join("\n", serverPerms.Words)).ConfigureAwait(false); string.Join("\n", serverPerms.Words)).ConfigureAwait(false);
} }
catch (Exception ex) catch (Exception ex)
{ {
await e.Channel.SendMessage($"💢 Error: {ex.Message}").ConfigureAwait(false); await channel.SendMessageAsync($"💢 Error: {ex.Message}").ConfigureAwait(false);
} }
}); });
@ -160,13 +160,13 @@ namespace NadekoBot.Modules.Permissions.Commands
{ {
var state = PermissionHelper.ValidateBool(e.GetArg("bool")); var state = PermissionHelper.ValidateBool(e.GetArg("bool"));
await PermissionsHandler.SetServerWordPermission(e.Server, state).ConfigureAwait(false); await PermissionsHandler.SetServerWordPermission(e.Server, state).ConfigureAwait(false);
await e.Channel.SendMessage($"Word filtering has been **{(state ? "enabled" : "disabled")}** on this server.") await channel.SendMessageAsync($"Word filtering has been **{(state ? "enabled" : "disabled")}** on this server.")
.ConfigureAwait(false); .ConfigureAwait(false);
} }
catch (Exception ex) catch (Exception ex)
{ {
await e.Channel.SendMessage($"💢 Error: {ex.Message}").ConfigureAwait(false); await channel.SendMessageAsync($"💢 Error: {ex.Message}").ConfigureAwait(false);
} }
}); });
} }

View File

@ -39,7 +39,7 @@ namespace NadekoBot.Modules.Permissions
{ {
if (string.IsNullOrWhiteSpace(e.GetArg("role"))) if (string.IsNullOrWhiteSpace(e.GetArg("role")))
{ {
await e.Channel.SendMessage($"Current permissions role is `{PermissionsHandler.GetServerPermissionsRoleName(e.Server)}`").ConfigureAwait(false); await channel.SendMessageAsync($"Current permissions role is `{PermissionsHandler.GetServerPermissionsRoleName(e.Server)}`").ConfigureAwait(false);
return; return;
} }
@ -52,11 +52,11 @@ namespace NadekoBot.Modules.Permissions
catch (Exception ex) catch (Exception ex)
{ {
Console.WriteLine(ex.Message); Console.WriteLine(ex.Message);
await e.Channel.SendMessage($"Role `{arg}` probably doesn't exist. Create the role with that name first.").ConfigureAwait(false); await channel.SendMessageAsync($"Role `{arg}` probably doesn't exist. Create the role with that name first.").ConfigureAwait(false);
return; return;
} }
await PermissionsHandler.SetPermissionsRole(e.Server, role.Name).ConfigureAwait(false); await PermissionsHandler.SetPermissionsRole(e.Server, role.Name).ConfigureAwait(false);
await e.Channel.SendMessage($"Role `{role.Name}` is now required in order to change permissions.").ConfigureAwait(false); await channel.SendMessageAsync($"Role `{role.Name}` is now required in order to change permissions.").ConfigureAwait(false);
}); });
cgb.CreateCommand(Prefix + "rolepermscopy") cgb.CreateCommand(Prefix + "rolepermscopy")
@ -71,7 +71,7 @@ namespace NadekoBot.Modules.Permissions
var args = arg.Split('~').Select(a => a.Trim()).ToArray(); var args = arg.Split('~').Select(a => a.Trim()).ToArray();
if (args.Length > 2) if (args.Length > 2)
{ {
await e.Channel.SendMessage("💢Invalid number of '~'s in the argument.").ConfigureAwait(false); await channel.SendMessageAsync("💢Invalid number of '~'s in the argument.").ConfigureAwait(false);
return; return;
} }
try try
@ -80,11 +80,11 @@ namespace NadekoBot.Modules.Permissions
var toRole = PermissionHelper.ValidateRole(e.Server, args[1]); var toRole = PermissionHelper.ValidateRole(e.Server, args[1]);
await PermissionsHandler.CopyRolePermissions(fromRole, toRole).ConfigureAwait(false); await PermissionsHandler.CopyRolePermissions(fromRole, toRole).ConfigureAwait(false);
await e.Channel.SendMessage($"Copied permission settings from **{fromRole.Name}** to **{toRole.Name}**.").ConfigureAwait(false); await channel.SendMessageAsync($"Copied permission settings from **{fromRole.Name}** to **{toRole.Name}**.").ConfigureAwait(false);
} }
catch (Exception ex) catch (Exception ex)
{ {
await e.Channel.SendMessage($"💢{ex.Message}").ConfigureAwait(false); await channel.SendMessageAsync($"💢{ex.Message}").ConfigureAwait(false);
} }
}); });
cgb.CreateCommand(Prefix + "chnlpermscopy") cgb.CreateCommand(Prefix + "chnlpermscopy")
@ -99,7 +99,7 @@ namespace NadekoBot.Modules.Permissions
var args = arg.Split('~').Select(a => a.Trim()).ToArray(); var args = arg.Split('~').Select(a => a.Trim()).ToArray();
if (args.Length > 2) if (args.Length > 2)
{ {
await e.Channel.SendMessage("💢Invalid number of '~'s in the argument."); await channel.SendMessageAsync("💢Invalid number of '~'s in the argument.");
return; return;
} }
try try
@ -108,11 +108,11 @@ namespace NadekoBot.Modules.Permissions
var toChannel = PermissionHelper.ValidateChannel(e.Server, args[1]); var toChannel = PermissionHelper.ValidateChannel(e.Server, args[1]);
await PermissionsHandler.CopyChannelPermissions(fromChannel, toChannel).ConfigureAwait(false); await PermissionsHandler.CopyChannelPermissions(fromChannel, toChannel).ConfigureAwait(false);
await e.Channel.SendMessage($"Copied permission settings from **{fromChannel.Name}** to **{toChannel.Name}**.").ConfigureAwait(false); await channel.SendMessageAsync($"Copied permission settings from **{fromChannel.Name}** to **{toChannel.Name}**.").ConfigureAwait(false);
} }
catch (Exception ex) catch (Exception ex)
{ {
await e.Channel.SendMessage($"💢{ex.Message}"); await channel.SendMessageAsync($"💢{ex.Message}");
} }
}); });
cgb.CreateCommand(Prefix + "usrpermscopy") cgb.CreateCommand(Prefix + "usrpermscopy")
@ -127,7 +127,7 @@ namespace NadekoBot.Modules.Permissions
var args = arg.Split('~').Select(a => a.Trim()).ToArray(); var args = arg.Split('~').Select(a => a.Trim()).ToArray();
if (args.Length > 2) if (args.Length > 2)
{ {
await e.Channel.SendMessage("💢Invalid number of '~'s in the argument.").ConfigureAwait(false); await channel.SendMessageAsync("💢Invalid number of '~'s in the argument.").ConfigureAwait(false);
return; return;
} }
try try
@ -136,11 +136,11 @@ namespace NadekoBot.Modules.Permissions
var toUser = PermissionHelper.ValidateUser(e.Server, args[1]); var toUser = PermissionHelper.ValidateUser(e.Server, args[1]);
await PermissionsHandler.CopyUserPermissions(fromUser, toUser).ConfigureAwait(false); await PermissionsHandler.CopyUserPermissions(fromUser, toUser).ConfigureAwait(false);
await e.Channel.SendMessage($"Copied permission settings from **{fromUser.ToString()}**to * *{toUser.ToString()}**.").ConfigureAwait(false); await channel.SendMessageAsync($"Copied permission settings from **{fromUser.ToString()}**to * *{toUser.ToString()}**.").ConfigureAwait(false);
} }
catch (Exception ex) catch (Exception ex)
{ {
await e.Channel.SendMessage($"💢{ex.Message}"); await channel.SendMessageAsync($"💢{ex.Message}");
} }
}); });
@ -153,7 +153,7 @@ namespace NadekoBot.Modules.Permissions
var arg = e.GetArg("arg"); var arg = e.GetArg("arg");
var val = PermissionHelper.ValidateBool(arg); var val = PermissionHelper.ValidateBool(arg);
await PermissionsHandler.SetVerbosity(e.Server, val).ConfigureAwait(false); await PermissionsHandler.SetVerbosity(e.Server, val).ConfigureAwait(false);
await e.Channel.SendMessage($"Verbosity set to {val}.").ConfigureAwait(false); await channel.SendMessageAsync($"Verbosity set to {val}.").ConfigureAwait(false);
}); });
cgb.CreateCommand(Prefix + "srvrperms") cgb.CreateCommand(Prefix + "srvrperms")
@ -163,8 +163,8 @@ namespace NadekoBot.Modules.Permissions
{ {
var perms = PermissionsHandler.GetServerPermissions(e.Server); var perms = PermissionsHandler.GetServerPermissions(e.Server);
if (string.IsNullOrWhiteSpace(perms?.ToString())) if (string.IsNullOrWhiteSpace(perms?.ToString()))
await e.Channel.SendMessage("No permissions set for this server.").ConfigureAwait(false); await channel.SendMessageAsync("No permissions set for this server.").ConfigureAwait(false);
await e.Channel.SendMessage(perms.ToString()).ConfigureAwait(false); await channel.SendMessageAsync(perms.ToString()).ConfigureAwait(false);
}); });
cgb.CreateCommand(Prefix + "roleperms") cgb.CreateCommand(Prefix + "roleperms")
@ -182,15 +182,15 @@ namespace NadekoBot.Modules.Permissions
} }
catch (Exception ex) catch (Exception ex)
{ {
await e.Channel.SendMessage("💢 Error: " + ex.Message).ConfigureAwait(false); await channel.SendMessageAsync("💢 Error: " + ex.Message).ConfigureAwait(false);
return; return;
} }
var perms = PermissionsHandler.GetRolePermissionsById(e.Server, role.Id); var perms = PermissionsHandler.GetRolePermissionsById(e.Server, role.Id);
if (string.IsNullOrWhiteSpace(perms?.ToString())) if (string.IsNullOrWhiteSpace(perms?.ToString()))
await e.Channel.SendMessage($"No permissions set for **{role.Name}** role.").ConfigureAwait(false); await channel.SendMessageAsync($"No permissions set for **{role.Name}** role.").ConfigureAwait(false);
await e.Channel.SendMessage(perms.ToString()).ConfigureAwait(false); await channel.SendMessageAsync(perms.ToString()).ConfigureAwait(false);
}); });
cgb.CreateCommand(Prefix + "chnlperms") cgb.CreateCommand(Prefix + "chnlperms")
@ -208,14 +208,14 @@ namespace NadekoBot.Modules.Permissions
} }
catch (Exception ex) catch (Exception ex)
{ {
await e.Channel.SendMessage("💢 Error: " + ex.Message).ConfigureAwait(false); await channel.SendMessageAsync("💢 Error: " + ex.Message).ConfigureAwait(false);
return; return;
} }
var perms = PermissionsHandler.GetChannelPermissionsById(e.Server, channel.Id); var perms = PermissionsHandler.GetChannelPermissionsById(e.Server, channel.Id);
if (string.IsNullOrWhiteSpace(perms?.ToString())) if (string.IsNullOrWhiteSpace(perms?.ToString()))
await e.Channel.SendMessage($"No permissions set for **{channel.Name}** channel.").ConfigureAwait(false); await channel.SendMessageAsync($"No permissions set for **{channel.Name}** channel.").ConfigureAwait(false);
await e.Channel.SendMessage(perms.ToString()).ConfigureAwait(false); await channel.SendMessageAsync(perms.ToString()).ConfigureAwait(false);
}); });
cgb.CreateCommand(Prefix + "userperms") cgb.CreateCommand(Prefix + "userperms")
@ -232,14 +232,14 @@ namespace NadekoBot.Modules.Permissions
} }
catch (Exception ex) catch (Exception ex)
{ {
await e.Channel.SendMessage("💢 Error: " + ex.Message).ConfigureAwait(false); await channel.SendMessageAsync("💢 Error: " + ex.Message).ConfigureAwait(false);
return; return;
} }
var perms = PermissionsHandler.GetUserPermissionsById(e.Server, user.Id); var perms = PermissionsHandler.GetUserPermissionsById(e.Server, user.Id);
if (string.IsNullOrWhiteSpace(perms?.ToString())) if (string.IsNullOrWhiteSpace(perms?.ToString()))
await e.Channel.SendMessage($"No permissions set for user **{user.Name}**.").ConfigureAwait(false); await channel.SendMessageAsync($"No permissions set for user **{user.Name}**.").ConfigureAwait(false);
await e.Channel.SendMessage(perms.ToString()).ConfigureAwait(false); await channel.SendMessageAsync(perms.ToString()).ConfigureAwait(false);
}); });
cgb.CreateCommand(Prefix + "srvrmdl") cgb.CreateCommand(Prefix + "srvrmdl")
@ -255,15 +255,15 @@ namespace NadekoBot.Modules.Permissions
var state = PermissionHelper.ValidateBool(e.GetArg("bool")); var state = PermissionHelper.ValidateBool(e.GetArg("bool"));
await PermissionsHandler.SetServerModulePermission(e.Server, module, state).ConfigureAwait(false); await PermissionsHandler.SetServerModulePermission(e.Server, module, state).ConfigureAwait(false);
await e.Channel.SendMessage($"Module **{module}** has been **{(state ? "enabled" : "disabled")}** on this server.").ConfigureAwait(false); await channel.SendMessageAsync($"Module **{module}** has been **{(state ? "enabled" : "disabled")}** on this server.").ConfigureAwait(false);
} }
catch (ArgumentException exArg) catch (ArgumentException exArg)
{ {
await e.Channel.SendMessage(exArg.Message).ConfigureAwait(false); await channel.SendMessageAsync(exArg.Message).ConfigureAwait(false);
} }
catch (Exception ex) catch (Exception ex)
{ {
await e.Channel.SendMessage("Something went terribly wrong - " + ex.Message).ConfigureAwait(false); await channel.SendMessageAsync("Something went terribly wrong - " + ex.Message).ConfigureAwait(false);
} }
}); });
@ -279,15 +279,15 @@ namespace NadekoBot.Modules.Permissions
var state = PermissionHelper.ValidateBool(e.GetArg("bool")); var state = PermissionHelper.ValidateBool(e.GetArg("bool"));
await PermissionsHandler.SetServerCommandPermission(e.Server, command, state).ConfigureAwait(false); await PermissionsHandler.SetServerCommandPermission(e.Server, command, state).ConfigureAwait(false);
await e.Channel.SendMessage($"Command **{command}** has been **{(state ? "enabled" : "disabled")}** on this server.").ConfigureAwait(false); await channel.SendMessageAsync($"Command **{command}** has been **{(state ? "enabled" : "disabled")}** on this server.").ConfigureAwait(false);
} }
catch (ArgumentException exArg) catch (ArgumentException exArg)
{ {
await e.Channel.SendMessage(exArg.Message).ConfigureAwait(false); await channel.SendMessageAsync(exArg.Message).ConfigureAwait(false);
} }
catch (Exception ex) catch (Exception ex)
{ {
await e.Channel.SendMessage("Something went terribly wrong - " + ex.Message).ConfigureAwait(false); await channel.SendMessageAsync("Something went terribly wrong - " + ex.Message).ConfigureAwait(false);
} }
}); });
@ -309,23 +309,23 @@ namespace NadekoBot.Modules.Permissions
{ {
await PermissionsHandler.SetRoleModulePermission(role, module, state).ConfigureAwait(false); await PermissionsHandler.SetRoleModulePermission(role, module, state).ConfigureAwait(false);
} }
await e.Channel.SendMessage($"Module **{module}** has been **{(state ? "enabled" : "disabled")}** for **ALL** roles.").ConfigureAwait(false); await channel.SendMessageAsync($"Module **{module}** has been **{(state ? "enabled" : "disabled")}** for **ALL** roles.").ConfigureAwait(false);
} }
else else
{ {
var role = PermissionHelper.ValidateRole(e.Server, e.GetArg("role")); var role = PermissionHelper.ValidateRole(e.Server, e.GetArg("role"));
await PermissionsHandler.SetRoleModulePermission(role, module, state).ConfigureAwait(false); await PermissionsHandler.SetRoleModulePermission(role, module, state).ConfigureAwait(false);
await e.Channel.SendMessage($"Module **{module}** has been **{(state ? "enabled" : "disabled")}** for **{role.Name}** role.").ConfigureAwait(false); await channel.SendMessageAsync($"Module **{module}** has been **{(state ? "enabled" : "disabled")}** for **{role.Name}** role.").ConfigureAwait(false);
} }
} }
catch (ArgumentException exArg) catch (ArgumentException exArg)
{ {
await e.Channel.SendMessage(exArg.Message).ConfigureAwait(false); await channel.SendMessageAsync(exArg.Message).ConfigureAwait(false);
} }
catch (Exception ex) catch (Exception ex)
{ {
await e.Channel.SendMessage("Something went terribly wrong - " + ex.Message).ConfigureAwait(false); await channel.SendMessageAsync("Something went terribly wrong - " + ex.Message).ConfigureAwait(false);
} }
}); });
@ -347,23 +347,23 @@ namespace NadekoBot.Modules.Permissions
{ {
await PermissionsHandler.SetRoleCommandPermission(role, command, state).ConfigureAwait(false); await PermissionsHandler.SetRoleCommandPermission(role, command, state).ConfigureAwait(false);
} }
await e.Channel.SendMessage($"Command **{command}** has been **{(state ? "enabled" : "disabled")}** for **ALL** roles.").ConfigureAwait(false); await channel.SendMessageAsync($"Command **{command}** has been **{(state ? "enabled" : "disabled")}** for **ALL** roles.").ConfigureAwait(false);
} }
else else
{ {
var role = PermissionHelper.ValidateRole(e.Server, e.GetArg("role")); var role = PermissionHelper.ValidateRole(e.Server, e.GetArg("role"));
await PermissionsHandler.SetRoleCommandPermission(role, command, state).ConfigureAwait(false); await PermissionsHandler.SetRoleCommandPermission(role, command, state).ConfigureAwait(false);
await e.Channel.SendMessage($"Command **{command}** has been **{(state ? "enabled" : "disabled")}** for **{role.Name}** role.").ConfigureAwait(false); await channel.SendMessageAsync($"Command **{command}** has been **{(state ? "enabled" : "disabled")}** for **{role.Name}** role.").ConfigureAwait(false);
} }
} }
catch (ArgumentException exArg) catch (ArgumentException exArg)
{ {
await e.Channel.SendMessage(exArg.Message).ConfigureAwait(false); await channel.SendMessageAsync(exArg.Message).ConfigureAwait(false);
} }
catch (Exception ex) catch (Exception ex)
{ {
await e.Channel.SendMessage("Something went terribly wrong - " + ex.Message).ConfigureAwait(false); await channel.SendMessageAsync("Something went terribly wrong - " + ex.Message).ConfigureAwait(false);
} }
}); });
@ -385,28 +385,28 @@ namespace NadekoBot.Modules.Permissions
{ {
await PermissionsHandler.SetChannelModulePermission(channel, module, state).ConfigureAwait(false); await PermissionsHandler.SetChannelModulePermission(channel, module, state).ConfigureAwait(false);
} }
await e.Channel.SendMessage($"Module **{module}** has been **{(state ? "enabled" : "disabled")}** on **ALL** channels.").ConfigureAwait(false); await channel.SendMessageAsync($"Module **{module}** has been **{(state ? "enabled" : "disabled")}** on **ALL** channels.").ConfigureAwait(false);
} }
else if (string.IsNullOrWhiteSpace(channelArg)) else if (string.IsNullOrWhiteSpace(channelArg))
{ {
await PermissionsHandler.SetChannelModulePermission(e.Channel, module, state).ConfigureAwait(false); await PermissionsHandler.SetChannelModulePermission(e.Channel, module, state).ConfigureAwait(false);
await e.Channel.SendMessage($"Module **{module}** has been **{(state ? "enabled" : "disabled")}** for **{e.Channel.Name}** channel.").ConfigureAwait(false); await channel.SendMessageAsync($"Module **{module}** has been **{(state ? "enabled" : "disabled")}** for **{e.Channel.Name}** channel.").ConfigureAwait(false);
} }
else else
{ {
var channel = PermissionHelper.ValidateChannel(e.Server, channelArg); var channel = PermissionHelper.ValidateChannel(e.Server, channelArg);
await PermissionsHandler.SetChannelModulePermission(channel, module, state).ConfigureAwait(false); await PermissionsHandler.SetChannelModulePermission(channel, module, state).ConfigureAwait(false);
await e.Channel.SendMessage($"Module **{module}** has been **{(state ? "enabled" : "disabled")}** for **{channel.Name}** channel.").ConfigureAwait(false); await channel.SendMessageAsync($"Module **{module}** has been **{(state ? "enabled" : "disabled")}** for **{channel.Name}** channel.").ConfigureAwait(false);
} }
} }
catch (ArgumentException exArg) catch (ArgumentException exArg)
{ {
await e.Channel.SendMessage(exArg.Message).ConfigureAwait(false); await channel.SendMessageAsync(exArg.Message).ConfigureAwait(false);
} }
catch (Exception ex) catch (Exception ex)
{ {
await e.Channel.SendMessage("Something went terribly wrong - " + ex.Message).ConfigureAwait(false); await channel.SendMessageAsync("Something went terribly wrong - " + ex.Message).ConfigureAwait(false);
} }
}); });
@ -428,23 +428,23 @@ namespace NadekoBot.Modules.Permissions
{ {
await PermissionsHandler.SetChannelCommandPermission(channel, command, state).ConfigureAwait(false); await PermissionsHandler.SetChannelCommandPermission(channel, command, state).ConfigureAwait(false);
} }
await e.Channel.SendMessage($"Command **{command}** has been **{(state ? "enabled" : "disabled")}** on **ALL** channels.").ConfigureAwait(false); await channel.SendMessageAsync($"Command **{command}** has been **{(state ? "enabled" : "disabled")}** on **ALL** channels.").ConfigureAwait(false);
} }
else else
{ {
var channel = PermissionHelper.ValidateChannel(e.Server, e.GetArg("channel")); var channel = PermissionHelper.ValidateChannel(e.Server, e.GetArg("channel"));
await PermissionsHandler.SetChannelCommandPermission(channel, command, state).ConfigureAwait(false); await PermissionsHandler.SetChannelCommandPermission(channel, command, state).ConfigureAwait(false);
await e.Channel.SendMessage($"Command **{command}** has been **{(state ? "enabled" : "disabled")}** for **{channel.Name}** channel.").ConfigureAwait(false); await channel.SendMessageAsync($"Command **{command}** has been **{(state ? "enabled" : "disabled")}** for **{channel.Name}** channel.").ConfigureAwait(false);
} }
} }
catch (ArgumentException exArg) catch (ArgumentException exArg)
{ {
await e.Channel.SendMessage(exArg.Message).ConfigureAwait(false); await channel.SendMessageAsync(exArg.Message).ConfigureAwait(false);
} }
catch (Exception ex) catch (Exception ex)
{ {
await e.Channel.SendMessage("Something went terribly wrong - " + ex.Message).ConfigureAwait(false); await channel.SendMessageAsync("Something went terribly wrong - " + ex.Message).ConfigureAwait(false);
} }
}); });
@ -462,15 +462,15 @@ namespace NadekoBot.Modules.Permissions
var user = PermissionHelper.ValidateUser(e.Server, e.GetArg("user")); var user = PermissionHelper.ValidateUser(e.Server, e.GetArg("user"));
await PermissionsHandler.SetUserModulePermission(user, module, state).ConfigureAwait(false); await PermissionsHandler.SetUserModulePermission(user, module, state).ConfigureAwait(false);
await e.Channel.SendMessage($"Module **{module}** has been **{(state ? "enabled" : "disabled")}** for user **{user.Name}**.").ConfigureAwait(false); await channel.SendMessageAsync($"Module **{module}** has been **{(state ? "enabled" : "disabled")}** for user **{user.Name}**.").ConfigureAwait(false);
} }
catch (ArgumentException exArg) catch (ArgumentException exArg)
{ {
await e.Channel.SendMessage(exArg.Message).ConfigureAwait(false); await channel.SendMessageAsync(exArg.Message).ConfigureAwait(false);
} }
catch (Exception ex) catch (Exception ex)
{ {
await e.Channel.SendMessage("Something went terribly wrong - " + ex.Message).ConfigureAwait(false); await channel.SendMessageAsync("Something went terribly wrong - " + ex.Message).ConfigureAwait(false);
} }
}); });
@ -488,15 +488,15 @@ namespace NadekoBot.Modules.Permissions
var user = PermissionHelper.ValidateUser(e.Server, e.GetArg("user")); var user = PermissionHelper.ValidateUser(e.Server, e.GetArg("user"));
await PermissionsHandler.SetUserCommandPermission(user, command, state).ConfigureAwait(false); await PermissionsHandler.SetUserCommandPermission(user, command, state).ConfigureAwait(false);
await e.Channel.SendMessage($"Command **{command}** has been **{(state ? "enabled" : "disabled")}** for user **{user.Name}**.").ConfigureAwait(false); await channel.SendMessageAsync($"Command **{command}** has been **{(state ? "enabled" : "disabled")}** for user **{user.Name}**.").ConfigureAwait(false);
} }
catch (ArgumentException exArg) catch (ArgumentException exArg)
{ {
await e.Channel.SendMessage(exArg.Message).ConfigureAwait(false); await channel.SendMessageAsync(exArg.Message).ConfigureAwait(false);
} }
catch (Exception ex) catch (Exception ex)
{ {
await e.Channel.SendMessage("Something went terribly wrong - " + ex.Message).ConfigureAwait(false); await channel.SendMessageAsync("Something went terribly wrong - " + ex.Message).ConfigureAwait(false);
} }
}); });
@ -513,15 +513,15 @@ namespace NadekoBot.Modules.Permissions
{ {
await PermissionsHandler.SetServerModulePermission(e.Server, module.Name, state).ConfigureAwait(false); await PermissionsHandler.SetServerModulePermission(e.Server, module.Name, state).ConfigureAwait(false);
} }
await e.Channel.SendMessage($"All modules have been **{(state ? "enabled" : "disabled")}** on this server.").ConfigureAwait(false); await channel.SendMessageAsync($"All modules have been **{(state ? "enabled" : "disabled")}** on this server.").ConfigureAwait(false);
} }
catch (ArgumentException exArg) catch (ArgumentException exArg)
{ {
await e.Channel.SendMessage(exArg.Message).ConfigureAwait(false); await channel.SendMessageAsync(exArg.Message).ConfigureAwait(false);
} }
catch (Exception ex) catch (Exception ex)
{ {
await e.Channel.SendMessage("Something went terribly wrong - " + ex.Message).ConfigureAwait(false); await channel.SendMessageAsync("Something went terribly wrong - " + ex.Message).ConfigureAwait(false);
} }
}); });
@ -540,15 +540,15 @@ namespace NadekoBot.Modules.Permissions
{ {
await PermissionsHandler.SetServerCommandPermission(e.Server, command.Text, state).ConfigureAwait(false); await PermissionsHandler.SetServerCommandPermission(e.Server, command.Text, state).ConfigureAwait(false);
} }
await e.Channel.SendMessage($"All commands from the **{module}** module have been **{(state ? "enabled" : "disabled")}** on this server.").ConfigureAwait(false); await channel.SendMessageAsync($"All commands from the **{module}** module have been **{(state ? "enabled" : "disabled")}** on this server.").ConfigureAwait(false);
} }
catch (ArgumentException exArg) catch (ArgumentException exArg)
{ {
await e.Channel.SendMessage(exArg.Message).ConfigureAwait(false); await channel.SendMessageAsync(exArg.Message).ConfigureAwait(false);
} }
catch (Exception ex) catch (Exception ex)
{ {
await e.Channel.SendMessage("Something went terribly wrong - " + ex.Message).ConfigureAwait(false); await channel.SendMessageAsync("Something went terribly wrong - " + ex.Message).ConfigureAwait(false);
} }
}); });
@ -568,15 +568,15 @@ namespace NadekoBot.Modules.Permissions
await PermissionsHandler.SetChannelModulePermission(channel, module.Name, state).ConfigureAwait(false); await PermissionsHandler.SetChannelModulePermission(channel, module.Name, state).ConfigureAwait(false);
} }
await e.Channel.SendMessage($"All modules have been **{(state ? "enabled" : "disabled")}** for **{channel.Name}** channel.").ConfigureAwait(false); await channel.SendMessageAsync($"All modules have been **{(state ? "enabled" : "disabled")}** for **{channel.Name}** channel.").ConfigureAwait(false);
} }
catch (ArgumentException exArg) catch (ArgumentException exArg)
{ {
await e.Channel.SendMessage(exArg.Message).ConfigureAwait(false); await channel.SendMessageAsync(exArg.Message).ConfigureAwait(false);
} }
catch (Exception ex) catch (Exception ex)
{ {
await e.Channel.SendMessage("Something went terribly wrong - " + ex.Message).ConfigureAwait(false); await channel.SendMessageAsync("Something went terribly wrong - " + ex.Message).ConfigureAwait(false);
} }
}); });
@ -596,15 +596,15 @@ namespace NadekoBot.Modules.Permissions
{ {
await PermissionsHandler.SetChannelCommandPermission(channel, command.Text, state).ConfigureAwait(false); await PermissionsHandler.SetChannelCommandPermission(channel, command.Text, state).ConfigureAwait(false);
} }
await e.Channel.SendMessage($"All commands from the **{module}** module have been **{(state ? "enabled" : "disabled")}** for **{channel.Name}** channel.").ConfigureAwait(false); await channel.SendMessageAsync($"All commands from the **{module}** module have been **{(state ? "enabled" : "disabled")}** for **{channel.Name}** channel.").ConfigureAwait(false);
} }
catch (ArgumentException exArg) catch (ArgumentException exArg)
{ {
await e.Channel.SendMessage(exArg.Message).ConfigureAwait(false); await channel.SendMessageAsync(exArg.Message).ConfigureAwait(false);
} }
catch (Exception ex) catch (Exception ex)
{ {
await e.Channel.SendMessage("Something went terribly wrong - " + ex.Message).ConfigureAwait(false); await channel.SendMessageAsync("Something went terribly wrong - " + ex.Message).ConfigureAwait(false);
} }
}); });
@ -623,15 +623,15 @@ namespace NadekoBot.Modules.Permissions
await PermissionsHandler.SetRoleModulePermission(role, module.Name, state).ConfigureAwait(false); await PermissionsHandler.SetRoleModulePermission(role, module.Name, state).ConfigureAwait(false);
} }
await e.Channel.SendMessage($"All modules have been **{(state ? "enabled" : "disabled")}** for **{role.Name}** role.").ConfigureAwait(false); await channel.SendMessageAsync($"All modules have been **{(state ? "enabled" : "disabled")}** for **{role.Name}** role.").ConfigureAwait(false);
} }
catch (ArgumentException exArg) catch (ArgumentException exArg)
{ {
await e.Channel.SendMessage(exArg.Message).ConfigureAwait(false); await channel.SendMessageAsync(exArg.Message).ConfigureAwait(false);
} }
catch (Exception ex) catch (Exception ex)
{ {
await e.Channel.SendMessage("Something went terribly wrong - " + ex.Message).ConfigureAwait(false); await channel.SendMessageAsync("Something went terribly wrong - " + ex.Message).ConfigureAwait(false);
} }
}); });
@ -655,7 +655,7 @@ namespace NadekoBot.Modules.Permissions
await PermissionsHandler.SetRoleCommandPermission(role, command.Text, state).ConfigureAwait(false); await PermissionsHandler.SetRoleCommandPermission(role, command.Text, state).ConfigureAwait(false);
} }
} }
await e.Channel.SendMessage($"All commands from the **{module}** module have been **{(state ? "enabled" : "disabled")}** for **all roles** role.").ConfigureAwait(false); await channel.SendMessageAsync($"All commands from the **{module}** module have been **{(state ? "enabled" : "disabled")}** for **all roles** role.").ConfigureAwait(false);
} }
else else
{ {
@ -665,16 +665,16 @@ namespace NadekoBot.Modules.Permissions
{ {
await PermissionsHandler.SetRoleCommandPermission(role, command.Text, state).ConfigureAwait(false); await PermissionsHandler.SetRoleCommandPermission(role, command.Text, state).ConfigureAwait(false);
} }
await e.Channel.SendMessage($"All commands from the **{module}** module have been **{(state ? "enabled" : "disabled")}** for **{role.Name}** role.").ConfigureAwait(false); await channel.SendMessageAsync($"All commands from the **{module}** module have been **{(state ? "enabled" : "disabled")}** for **{role.Name}** role.").ConfigureAwait(false);
} }
} }
catch (ArgumentException exArg) catch (ArgumentException exArg)
{ {
await e.Channel.SendMessage(exArg.Message).ConfigureAwait(false); await channel.SendMessageAsync(exArg.Message).ConfigureAwait(false);
} }
catch (Exception ex) catch (Exception ex)
{ {
await e.Channel.SendMessage("Something went terribly wrong - " + ex.Message).ConfigureAwait(false); await channel.SendMessageAsync("Something went terribly wrong - " + ex.Message).ConfigureAwait(false);
} }
}); });
@ -690,7 +690,7 @@ namespace NadekoBot.Modules.Permissions
var usr = e.Message.MentionedUsers.First(); var usr = e.Message.MentionedUsers.First();
NadekoBot.Config.UserBlacklist.Add(usr.Id); NadekoBot.Config.UserBlacklist.Add(usr.Id);
await ConfigHandler.SaveConfig().ConfigureAwait(false); await ConfigHandler.SaveConfig().ConfigureAwait(false);
await e.Channel.SendMessage($"`Sucessfully blacklisted user {usr.Name}`").ConfigureAwait(false); await channel.SendMessageAsync($"`Sucessfully blacklisted user {usr.Name}`").ConfigureAwait(false);
}).ConfigureAwait(false); }).ConfigureAwait(false);
}); });
@ -708,11 +708,11 @@ namespace NadekoBot.Modules.Permissions
{ {
NadekoBot.Config.UserBlacklist.Remove(usr.Id); NadekoBot.Config.UserBlacklist.Remove(usr.Id);
await ConfigHandler.SaveConfig().ConfigureAwait(false); await ConfigHandler.SaveConfig().ConfigureAwait(false);
await e.Channel.SendMessage($"`Sucessfully unblacklisted user {usr.Name}`").ConfigureAwait(false); await channel.SendMessageAsync($"`Sucessfully unblacklisted user {usr.Name}`").ConfigureAwait(false);
} }
else else
{ {
await e.Channel.SendMessage($"`{usr.Name} was not in blacklist`").ConfigureAwait(false); await channel.SendMessageAsync($"`{usr.Name} was not in blacklist`").ConfigureAwait(false);
} }
}).ConfigureAwait(false); }).ConfigureAwait(false);
}); });
@ -728,7 +728,7 @@ namespace NadekoBot.Modules.Permissions
var ch = e.Message.MentionedChannels.First(); var ch = e.Message.MentionedChannels.First();
NadekoBot.Config.UserBlacklist.Add(ch.Id); NadekoBot.Config.UserBlacklist.Add(ch.Id);
await ConfigHandler.SaveConfig().ConfigureAwait(false); await ConfigHandler.SaveConfig().ConfigureAwait(false);
await e.Channel.SendMessage($"`Sucessfully blacklisted channel {ch.Name}`").ConfigureAwait(false); await channel.SendMessageAsync($"`Sucessfully blacklisted channel {ch.Name}`").ConfigureAwait(false);
}).ConfigureAwait(false); }).ConfigureAwait(false);
}); });
@ -743,7 +743,7 @@ namespace NadekoBot.Modules.Permissions
var ch = e.Message.MentionedChannels.First(); var ch = e.Message.MentionedChannels.First();
NadekoBot.Config.UserBlacklist.Remove(ch.Id); NadekoBot.Config.UserBlacklist.Remove(ch.Id);
await ConfigHandler.SaveConfig().ConfigureAwait(false); await ConfigHandler.SaveConfig().ConfigureAwait(false);
await e.Channel.SendMessage($"`Sucessfully blacklisted channel {ch.Name}`").ConfigureAwait(false); await channel.SendMessageAsync($"`Sucessfully blacklisted channel {ch.Name}`").ConfigureAwait(false);
}).ConfigureAwait(false); }).ConfigureAwait(false);
}); });
@ -762,7 +762,7 @@ namespace NadekoBot.Modules.Permissions
NadekoBot.Client.FindServers(arg.Trim()).FirstOrDefault(); NadekoBot.Client.FindServers(arg.Trim()).FirstOrDefault();
if (server == null) if (server == null)
{ {
await e.Channel.SendMessage("Cannot find that server").ConfigureAwait(false); await channel.SendMessageAsync("Cannot find that server").ConfigureAwait(false);
return; return;
} }
var serverId = server.Id; var serverId = server.Id;
@ -774,7 +774,7 @@ namespace NadekoBot.Modules.Permissions
TypingGame typeracer; TypingGame typeracer;
SpeedTyping.RunningContests.TryRemove(serverId, out typeracer); SpeedTyping.RunningContests.TryRemove(serverId, out typeracer);
await e.Channel.SendMessage($"`Sucessfully blacklisted server {server.Name}`").ConfigureAwait(false); await channel.SendMessageAsync($"`Sucessfully blacklisted server {server.Name}`").ConfigureAwait(false);
}).ConfigureAwait(false); }).ConfigureAwait(false);
}); });
@ -797,17 +797,17 @@ namespace NadekoBot.Modules.Permissions
await PermissionsHandler.SetCommandCooldown(e.Server, command, secs).ConfigureAwait(false); await PermissionsHandler.SetCommandCooldown(e.Server, command, secs).ConfigureAwait(false);
if(secs == 0) if(secs == 0)
await e.Channel.SendMessage($"Command **{command}** has no coooldown now.").ConfigureAwait(false); await channel.SendMessageAsync($"Command **{command}** has no coooldown now.").ConfigureAwait(false);
else else
await e.Channel.SendMessage($"Command **{command}** now has a **{secs} {(secs==1 ? "second" : "seconds")}** cooldown.").ConfigureAwait(false); await channel.SendMessageAsync($"Command **{command}** now has a **{secs} {(secs==1 ? "second" : "seconds")}** cooldown.").ConfigureAwait(false);
} }
catch (ArgumentException exArg) catch (ArgumentException exArg)
{ {
await e.Channel.SendMessage(exArg.Message).ConfigureAwait(false); await channel.SendMessageAsync(exArg.Message).ConfigureAwait(false);
} }
catch (Exception ex) catch (Exception ex)
{ {
await e.Channel.SendMessage("Something went terribly wrong - " + ex.Message).ConfigureAwait(false); await channel.SendMessageAsync("Something went terribly wrong - " + ex.Message).ConfigureAwait(false);
} }
}); });
@ -823,10 +823,10 @@ namespace NadekoBot.Modules.Permissions
if (!perms.CommandCooldowns.Any()) if (!perms.CommandCooldowns.Any())
{ {
await e.Channel.SendMessage("`No command cooldowns set.`").ConfigureAwait(false); await channel.SendMessageAsync("`No command cooldowns set.`").ConfigureAwait(false);
return; return;
} }
await e.Channel.SendMessage(SearchHelper.ShowInPrettyCode(perms.CommandCooldowns.Select(c=>c.Key+ ": "+c.Value+" secs"),s=>$"{s,-30}",2)).ConfigureAwait(false); await channel.SendMessageAsync(SearchHelper.ShowInPrettyCode(perms.CommandCooldowns.Select(c=>c.Key+ ": "+c.Value+" secs"),s=>$"{s,-30}",2)).ConfigureAwait(false);
}); });
}); });
} }

View File

@ -92,12 +92,12 @@ namespace NadekoBot.Modules.Pokemon
var target = e.Server.FindUsers(targetStr).FirstOrDefault(); var target = e.Server.FindUsers(targetStr).FirstOrDefault();
if (target == null) if (target == null)
{ {
await e.Channel.SendMessage("No such person.").ConfigureAwait(false); await channel.SendMessageAsync("No such person.").ConfigureAwait(false);
return; return;
} }
else if (target == e.User) else if (target == e.User)
{ {
await e.Channel.SendMessage("You can't attack yourself.").ConfigureAwait(false); await channel.SendMessageAsync("You can't attack yourself.").ConfigureAwait(false);
return; return;
} }
// Checking stats first, then move // Checking stats first, then move
@ -109,17 +109,17 @@ namespace NadekoBot.Modules.Pokemon
//User not able if HP < 0, has made more than 4 attacks //User not able if HP < 0, has made more than 4 attacks
if (userStats.Hp < 0) if (userStats.Hp < 0)
{ {
await e.Channel.SendMessage($"{e.User.Mention} has fainted and was not able to move!").ConfigureAwait(false); await channel.SendMessageAsync($"{e.User.Mention} has fainted and was not able to move!").ConfigureAwait(false);
return; return;
} }
if (userStats.MovesMade >= 5) if (userStats.MovesMade >= 5)
{ {
await e.Channel.SendMessage($"{e.User.Mention} has used too many moves in a row and was not able to move!").ConfigureAwait(false); await channel.SendMessageAsync($"{e.User.Mention} has used too many moves in a row and was not able to move!").ConfigureAwait(false);
return; return;
} }
if (userStats.LastAttacked.Contains(target.Id)) if (userStats.LastAttacked.Contains(target.Id))
{ {
await e.Channel.SendMessage($"{e.User.Mention} can't attack again without retaliation!").ConfigureAwait(false); await channel.SendMessageAsync($"{e.User.Mention} can't attack again without retaliation!").ConfigureAwait(false);
return; return;
} }
//get target stats //get target stats
@ -129,7 +129,7 @@ namespace NadekoBot.Modules.Pokemon
//If target's HP is below 0, no use attacking //If target's HP is below 0, no use attacking
if (targetStats.Hp <= 0) if (targetStats.Hp <= 0)
{ {
await e.Channel.SendMessage($"{target.Mention} has already fainted!").ConfigureAwait(false); await channel.SendMessageAsync($"{target.Mention} has already fainted!").ConfigureAwait(false);
return; return;
} }
@ -139,7 +139,7 @@ namespace NadekoBot.Modules.Pokemon
var enabledMoves = userType.Moves; var enabledMoves = userType.Moves;
if (!enabledMoves.Contains(move.ToLowerInvariant())) if (!enabledMoves.Contains(move.ToLowerInvariant()))
{ {
await e.Channel.SendMessage($"{e.User.Mention} was not able to use **{move}**, use `{Prefix}ml` to see moves you can use").ConfigureAwait(false); await channel.SendMessageAsync($"{e.User.Mention} was not able to use **{move}**, use `{Prefix}ml` to see moves you can use").ConfigureAwait(false);
return; return;
} }
@ -191,7 +191,7 @@ namespace NadekoBot.Modules.Pokemon
Stats[e.User.Id] = userStats; Stats[e.User.Id] = userStats;
Stats[target.Id] = targetStats; Stats[target.Id] = targetStats;
await e.Channel.SendMessage(response).ConfigureAwait(false); await channel.SendMessageAsync(response).ConfigureAwait(false);
}); });
cgb.CreateCommand(Prefix + "movelist") cgb.CreateCommand(Prefix + "movelist")
@ -206,7 +206,7 @@ namespace NadekoBot.Modules.Pokemon
{ {
str += $"\n{userType.Icon}{m}"; str += $"\n{userType.Icon}{m}";
} }
await e.Channel.SendMessage(str).ConfigureAwait(false); await channel.SendMessageAsync(str).ConfigureAwait(false);
}); });
cgb.CreateCommand(Prefix + "heal") cgb.CreateCommand(Prefix + "heal")
@ -220,7 +220,7 @@ namespace NadekoBot.Modules.Pokemon
var usr = e.Server.FindUsers(targetStr).FirstOrDefault(); var usr = e.Server.FindUsers(targetStr).FirstOrDefault();
if (usr == null) if (usr == null)
{ {
await e.Channel.SendMessage("No such person.").ConfigureAwait(false); await channel.SendMessageAsync("No such person.").ConfigureAwait(false);
return; return;
} }
if (Stats.ContainsKey(usr.Id)) if (Stats.ContainsKey(usr.Id))
@ -230,7 +230,7 @@ namespace NadekoBot.Modules.Pokemon
int HP = targetStats.Hp; int HP = targetStats.Hp;
if (targetStats.Hp == targetStats.MaxHp) if (targetStats.Hp == targetStats.MaxHp)
{ {
await e.Channel.SendMessage($"{usr.Name} already has full HP!").ConfigureAwait(false); await channel.SendMessageAsync($"{usr.Name} already has full HP!").ConfigureAwait(false);
return; return;
} }
//Payment~ //Payment~
@ -238,7 +238,7 @@ namespace NadekoBot.Modules.Pokemon
var pts = Classes.DbHandler.Instance.GetStateByUserId((long)e.User.Id)?.Value ?? 0; var pts = Classes.DbHandler.Instance.GetStateByUserId((long)e.User.Id)?.Value ?? 0;
if (pts < amount) if (pts < amount)
{ {
await e.Channel.SendMessage($"{e.User.Mention} you don't have enough {NadekoBot.Config.CurrencyName}s! \nYou still need {amount - pts} {NadekoBot.Config.CurrencySign} to be able to do this!").ConfigureAwait(false); await channel.SendMessageAsync($"{e.User.Mention} you don't have enough {NadekoBot.Config.CurrencyName}s! \nYou still need {amount - pts} {NadekoBot.Config.CurrencySign} to be able to do this!").ConfigureAwait(false);
return; return;
} }
var target = (usr.Id == e.User.Id) ? "yourself" : usr.Name; var target = (usr.Id == e.User.Id) ? "yourself" : usr.Name;
@ -249,16 +249,16 @@ namespace NadekoBot.Modules.Pokemon
{ {
//Could heal only for half HP? //Could heal only for half HP?
Stats[usr.Id].Hp = (targetStats.MaxHp / 2); Stats[usr.Id].Hp = (targetStats.MaxHp / 2);
await e.Channel.SendMessage($"{e.User.Name} revived {usr.Name} with one {NadekoBot.Config.CurrencySign}").ConfigureAwait(false); await channel.SendMessageAsync($"{e.User.Name} revived {usr.Name} with one {NadekoBot.Config.CurrencySign}").ConfigureAwait(false);
return; return;
} }
var vowelFirst = new[] { 'a', 'e', 'i', 'o', 'u' }.Contains(NadekoBot.Config.CurrencyName[0]); var vowelFirst = new[] { 'a', 'e', 'i', 'o', 'u' }.Contains(NadekoBot.Config.CurrencyName[0]);
await e.Channel.SendMessage($"{e.User.Name} healed {usr.Name} for {targetStats.MaxHp - HP} HP with {(vowelFirst ? "an" : "a")} {NadekoBot.Config.CurrencySign}").ConfigureAwait(false); await channel.SendMessageAsync($"{e.User.Name} healed {usr.Name} for {targetStats.MaxHp - HP} HP with {(vowelFirst ? "an" : "a")} {NadekoBot.Config.CurrencySign}").ConfigureAwait(false);
return; return;
} }
else else
{ {
await e.Channel.SendMessage($"{usr.Name} already has full HP!").ConfigureAwait(false); await channel.SendMessageAsync($"{usr.Name} already has full HP!").ConfigureAwait(false);
} }
}); });
@ -273,11 +273,11 @@ namespace NadekoBot.Modules.Pokemon
var usr = e.Server.FindUsers(usrStr).FirstOrDefault(); var usr = e.Server.FindUsers(usrStr).FirstOrDefault();
if (usr == null) if (usr == null)
{ {
await e.Channel.SendMessage("No such person.").ConfigureAwait(false); await channel.SendMessageAsync("No such person.").ConfigureAwait(false);
return; return;
} }
var pType = GetPokeType(usr.Id); var pType = GetPokeType(usr.Id);
await e.Channel.SendMessage($"Type of {usr.Name} is **{pType.Name.ToLowerInvariant()}**{pType.Icon}").ConfigureAwait(false); await channel.SendMessageAsync($"Type of {usr.Name} is **{pType.Name.ToLowerInvariant()}**{pType.Icon}").ConfigureAwait(false);
}); });
@ -292,12 +292,12 @@ namespace NadekoBot.Modules.Pokemon
var targetType = stringToPokemonType(targetTypeStr); var targetType = stringToPokemonType(targetTypeStr);
if (targetType == null) if (targetType == null)
{ {
await e.Channel.SendMessage("Invalid type specified. Type must be one of:\n" + string.Join(", ", NadekoBot.Config.PokemonTypes.Select(t => t.Name.ToUpperInvariant()))).ConfigureAwait(false); await channel.SendMessageAsync("Invalid type specified. Type must be one of:\n" + string.Join(", ", NadekoBot.Config.PokemonTypes.Select(t => t.Name.ToUpperInvariant()))).ConfigureAwait(false);
return; return;
} }
if (targetType == GetPokeType(e.User.Id)) if (targetType == GetPokeType(e.User.Id))
{ {
await e.Channel.SendMessage($"Your type is already {targetType.Name.ToLowerInvariant()}{targetType.Icon}").ConfigureAwait(false); await channel.SendMessageAsync($"Your type is already {targetType.Name.ToLowerInvariant()}{targetType.Icon}").ConfigureAwait(false);
return; return;
} }
@ -306,7 +306,7 @@ namespace NadekoBot.Modules.Pokemon
var pts = DbHandler.Instance.GetStateByUserId((long)e.User.Id)?.Value ?? 0; var pts = DbHandler.Instance.GetStateByUserId((long)e.User.Id)?.Value ?? 0;
if (pts < amount) if (pts < amount)
{ {
await e.Channel.SendMessage($"{e.User.Mention} you don't have enough {NadekoBot.Config.CurrencyName}s! \nYou still need {amount - pts} {NadekoBot.Config.CurrencySign} to be able to do this!").ConfigureAwait(false); await channel.SendMessageAsync($"{e.User.Mention} you don't have enough {NadekoBot.Config.CurrencyName}s! \nYou still need {amount - pts} {NadekoBot.Config.CurrencySign} to be able to do this!").ConfigureAwait(false);
return; return;
} }
await FlowersHandler.RemoveFlowers(e.User, $"set usertype to {targetTypeStr}", amount).ConfigureAwait(false); await FlowersHandler.RemoveFlowers(e.User, $"set usertype to {targetTypeStr}", amount).ConfigureAwait(false);
@ -327,7 +327,7 @@ namespace NadekoBot.Modules.Pokemon
//Now for the response //Now for the response
await e.Channel.SendMessage($"Set type of {e.User.Mention} to {targetTypeStr}{targetType.Icon} for a {NadekoBot.Config.CurrencySign}").ConfigureAwait(false); await channel.SendMessageAsync($"Set type of {e.User.Mention} to {targetTypeStr}{targetType.Icon} for a {NadekoBot.Config.CurrencySign}").ConfigureAwait(false);
}); });
}); });
} }

View File

@ -61,7 +61,7 @@ namespace NadekoBot.Modules.Searches.Commands
msg += curr + "; "; msg += curr + "; ";
} }
await e.Channel.SendMessage(msg).ConfigureAwait(false); await channel.SendMessageAsync(msg).ConfigureAwait(false);
}; };
private Func<CommandEventArgs, Task> ConvertFunc() => private Func<CommandEventArgs, Task> ConvertFunc() =>
@ -88,7 +88,7 @@ namespace NadekoBot.Modules.Searches.Commands
{ {
Unit inUnit = new Unit(fromCode, quantity, table); Unit inUnit = new Unit(fromCode, quantity, table);
Unit outUnit = inUnit.Convert(toCode); Unit outUnit = inUnit.Convert(toCode);
await e.Channel.SendMessage(inUnit.ToString() + " = " + outUnit.ToString()).ConfigureAwait(false); await channel.SendMessageAsync(inUnit.ToString() + " = " + outUnit.ToString()).ConfigureAwait(false);
} }
else else
{ {
@ -97,13 +97,13 @@ namespace NadekoBot.Modules.Searches.Commands
reInitCurrencyConverterTable(); reInitCurrencyConverterTable();
Unit inUnit = currTable.CreateUnit(quantity, from.ToUpperInvariant()); Unit inUnit = currTable.CreateUnit(quantity, from.ToUpperInvariant());
Unit outUnit = inUnit.Convert(currTable.CurrencyCode(to.ToUpperInvariant())); Unit outUnit = inUnit.Convert(currTable.CurrencyCode(to.ToUpperInvariant()));
await e.Channel.SendMessage(inUnit.ToString() + " = " + outUnit.ToString()).ConfigureAwait(false); await channel.SendMessageAsync(inUnit.ToString() + " = " + outUnit.ToString()).ConfigureAwait(false);
} }
} }
catch //(Exception ex) catch //(Exception ex)
{ {
//Console.WriteLine(ex.ToString()); //Console.WriteLine(ex.ToString());
await e.Channel.SendMessage("Bad input format, or sth went wrong... Try to list them with `" + Module.Prefix + "`convertlist").ConfigureAwait(false); await channel.SendMessageAsync("Bad input format, or sth went wrong... Try to list them with `" + Module.Prefix + "`convertlist").ConfigureAwait(false);
} }
}; };

View File

@ -34,10 +34,10 @@ namespace NadekoBot.Modules.Searches.Commands
string answer = Evaluate(expression); string answer = Evaluate(expression);
if (answer == null) if (answer == null)
{ {
await e.Channel.SendMessage($"Expression {expression} failed to evaluate"); await channel.SendMessageAsync($"Expression {expression} failed to evaluate");
return; return;
} }
await e.Channel.SendMessage($"⚙ `{answer}`"); await channel.SendMessageAsync($"⚙ `{answer}`");
}; };
private string Evaluate(string expression) private string Evaluate(string expression)

View File

@ -106,7 +106,7 @@ namespace NadekoBot.Modules.Searches.Commands
} }
if (data == null) if (data == null)
{ {
await e.Channel.SendMessage("💢 Data for that role does not exist.").ConfigureAwait(false); await channel.SendMessageAsync("💢 Data for that role does not exist.").ConfigureAwait(false);
return; return;
} }
} }
@ -275,7 +275,7 @@ Assists: {general["assists"]} Ban: {general["banRate"]}%
catch (Exception ex) catch (Exception ex)
{ {
Console.WriteLine(ex); Console.WriteLine(ex);
await e.Channel.SendMessage("💢 Failed retreiving data for that champion.").ConfigureAwait(false); await channel.SendMessageAsync("💢 Failed retreiving data for that champion.").ConfigureAwait(false);
} }
}); });
@ -307,11 +307,11 @@ Assists: {general["assists"]} Ban: {general["banRate"]}%
//sb.AppendLine($" ({dataList[i]["general"]["banRate"]}%)"); //sb.AppendLine($" ({dataList[i]["general"]["banRate"]}%)");
} }
await e.Channel.SendMessage(sb.ToString()).ConfigureAwait(false); await channel.SendMessageAsync(sb.ToString()).ConfigureAwait(false);
} }
catch (Exception) catch (Exception)
{ {
await e.Channel.SendMessage($":anger: Fail: Champion.gg didsabled ban data until next patch. Sorry for the inconvenience.").ConfigureAwait(false); await channel.SendMessageAsync($":anger: Fail: Champion.gg didsabled ban data until next patch. Sorry for the inconvenience.").ConfigureAwait(false);
} }
}); });
} }

View File

@ -21,7 +21,7 @@ namespace NadekoBot.Modules.Searches.Commands
.Do(async e => .Do(async e =>
{ {
int i = 0; int i = 0;
await e.Channel.SendMessage("`List Of Commands:`\n```xl\n" + await channel.SendMessageAsync("`List Of Commands:`\n```xl\n" +
string.Join("\n", JsonConvert.DeserializeObject<Dictionary<string, string>>(await SearchHelper.GetResponseStringAsync("http://memegen.link/templates/")) string.Join("\n", JsonConvert.DeserializeObject<Dictionary<string, string>>(await SearchHelper.GetResponseStringAsync("http://memegen.link/templates/"))
.Select(kvp => Path.GetFileName(kvp.Value)) .Select(kvp => Path.GetFileName(kvp.Value))
.GroupBy(item => (i++) / 4) .GroupBy(item => (i++) / 4)
@ -39,7 +39,7 @@ namespace NadekoBot.Modules.Searches.Commands
var meme = e.GetArg("meme"); var meme = e.GetArg("meme");
var top = Uri.EscapeDataString(e.GetArg("toptext").Replace(' ', '-')); var top = Uri.EscapeDataString(e.GetArg("toptext").Replace(' ', '-'));
var bot = Uri.EscapeDataString(e.GetArg("bottext").Replace(' ', '-')); var bot = Uri.EscapeDataString(e.GetArg("bottext").Replace(' ', '-'));
await e.Channel.SendMessage($"http://memegen.link/{meme}/{top}/{bot}.jpg"); await channel.SendMessageAsync($"http://memegen.link/{meme}/{top}/{bot}.jpg");
}); });
} }
} }

View File

@ -43,14 +43,14 @@ namespace NadekoBot.Modules.Searches.Commands
try try
{ {
await e.Channel.SendFile($"{e.GetArg("usr")}.png", new MemoryStream(cle.Result)).ConfigureAwait(false); await e.Channel.SendFile($"{e.GetArg("usr")}.png", new MemoryStream(cle.Result)).ConfigureAwait(false);
await e.Channel.SendMessage($"`Profile Link:`https://osu.ppy.sh/u/{Uri.EscapeDataString(e.GetArg("usr"))}\n`Image provided by https://lemmmy.pw/osusig`").ConfigureAwait(false); await channel.SendMessageAsync($"`Profile Link:`https://osu.ppy.sh/u/{Uri.EscapeDataString(e.GetArg("usr"))}\n`Image provided by https://lemmmy.pw/osusig`").ConfigureAwait(false);
} }
catch { } catch { }
}; };
} }
catch catch
{ {
await e.Channel.SendMessage("💢 Failed retrieving osu signature :\\").ConfigureAwait(false); await channel.SendMessageAsync("💢 Failed retrieving osu signature :\\").ConfigureAwait(false);
} }
} }
}); });
@ -62,7 +62,7 @@ namespace NadekoBot.Modules.Searches.Commands
{ {
if (string.IsNullOrWhiteSpace(NadekoBot.Creds.OsuAPIKey)) if (string.IsNullOrWhiteSpace(NadekoBot.Creds.OsuAPIKey))
{ {
await e.Channel.SendMessage("💢 An osu! API key is required.").ConfigureAwait(false); await channel.SendMessageAsync("💢 An osu! API key is required.").ConfigureAwait(false);
return; return;
} }
@ -79,11 +79,11 @@ namespace NadekoBot.Modules.Searches.Commands
var time = TimeSpan.FromSeconds(Double.Parse($"{obj["total_length"]}")).ToString(@"mm\:ss"); var time = TimeSpan.FromSeconds(Double.Parse($"{obj["total_length"]}")).ToString(@"mm\:ss");
sb.AppendLine($"{obj["artist"]} - {obj["title"]}, mapped by {obj["creator"]}. https://osu.ppy.sh/s/{obj["beatmapset_id"]}"); sb.AppendLine($"{obj["artist"]} - {obj["title"]}, mapped by {obj["creator"]}. https://osu.ppy.sh/s/{obj["beatmapset_id"]}");
sb.AppendLine($"{starRating} stars, {obj["bpm"]} BPM | AR{obj["diff_approach"]}, CS{obj["diff_size"]}, OD{obj["diff_overall"]} | Length: {time}"); sb.AppendLine($"{starRating} stars, {obj["bpm"]} BPM | AR{obj["diff_approach"]}, CS{obj["diff_size"]}, OD{obj["diff_overall"]} | Length: {time}");
await e.Channel.SendMessage(sb.ToString()).ConfigureAwait(false); await channel.SendMessageAsync(sb.ToString()).ConfigureAwait(false);
} }
catch catch
{ {
await e.Channel.SendMessage("Something went wrong."); await channel.SendMessageAsync("Something went wrong.");
} }
}); });
@ -95,13 +95,13 @@ namespace NadekoBot.Modules.Searches.Commands
{ {
if (string.IsNullOrWhiteSpace(NadekoBot.Creds.OsuAPIKey)) if (string.IsNullOrWhiteSpace(NadekoBot.Creds.OsuAPIKey))
{ {
await e.Channel.SendMessage("💢 An osu! API key is required.").ConfigureAwait(false); await channel.SendMessageAsync("💢 An osu! API key is required.").ConfigureAwait(false);
return; return;
} }
if (string.IsNullOrWhiteSpace(e.GetArg("usr"))) if (string.IsNullOrWhiteSpace(e.GetArg("usr")))
{ {
await e.Channel.SendMessage("💢 Please provide a username.").ConfigureAwait(false); await channel.SendMessageAsync("💢 Please provide a username.").ConfigureAwait(false);
return; return;
} }
@ -129,11 +129,11 @@ namespace NadekoBot.Modules.Searches.Commands
sb.AppendLine($"{pp + "pp",-7} | {acc + "%",-7} | {map["artist"] + "-" + map["title"] + " (" + map["version"],-40}) | /b/{item["beatmap_id"]}"); sb.AppendLine($"{pp + "pp",-7} | {acc + "%",-7} | {map["artist"] + "-" + map["title"] + " (" + map["version"],-40}) | /b/{item["beatmap_id"]}");
} }
sb.Append("```"); sb.Append("```");
await e.Channel.SendMessage(sb.ToString()).ConfigureAwait(false); await channel.SendMessageAsync(sb.ToString()).ConfigureAwait(false);
} }
catch catch
{ {
await e.Channel.SendMessage("Something went wrong."); await channel.SendMessageAsync("Something went wrong.");
} }
}); });
} }

View File

@ -34,11 +34,11 @@ namespace NadekoBot.Modules.Searches.Commands
{ {
if (kvp.Key.ToUpperInvariant() == pok.ToUpperInvariant()) if (kvp.Key.ToUpperInvariant() == pok.ToUpperInvariant())
{ {
await e.Channel.SendMessage($"`Stats for \"{kvp.Key}\" pokemon:`\n{kvp.Value}"); await channel.SendMessageAsync($"`Stats for \"{kvp.Key}\" pokemon:`\n{kvp.Value}");
return; return;
} }
} }
await e.Channel.SendMessage("`No pokemon found.`"); await channel.SendMessageAsync("`No pokemon found.`");
}); });
cgb.CreateCommand(Prefix + "pokemonability") cgb.CreateCommand(Prefix + "pokemonability")
@ -54,11 +54,11 @@ namespace NadekoBot.Modules.Searches.Commands
{ {
if (kvp.Key.ToUpperInvariant() == ab) if (kvp.Key.ToUpperInvariant() == ab)
{ {
await e.Channel.SendMessage($"`Info for \"{kvp.Key}\" ability:`\n{kvp.Value}"); await channel.SendMessageAsync($"`Info for \"{kvp.Key}\" ability:`\n{kvp.Value}");
return; return;
} }
} }
await e.Channel.SendMessage("`No ability found.`"); await channel.SendMessageAsync("`No ability found.`");
}); });
} }
} }

View File

@ -163,12 +163,12 @@ namespace NadekoBot.Modules.Searches.Commands
})); }));
if (streamStatus.Item1) if (streamStatus.Item1)
{ {
await e.Channel.SendMessage($"`Streamer {streamStatus.Item2} is online.`"); await channel.SendMessageAsync($"`Streamer {streamStatus.Item2} is online.`");
} }
} }
catch catch
{ {
await e.Channel.SendMessage("No channel found."); await channel.SendMessageAsync("No channel found.");
} }
}); });
@ -192,12 +192,12 @@ namespace NadekoBot.Modules.Searches.Commands
})); }));
if (streamStatus.Item1) if (streamStatus.Item1)
{ {
await e.Channel.SendMessage($"`Streamer {streamStatus.Item2} is online.`"); await channel.SendMessageAsync($"`Streamer {streamStatus.Item2} is online.`");
} }
} }
catch catch
{ {
await e.Channel.SendMessage("No channel found."); await channel.SendMessageAsync("No channel found.");
} }
}); });
@ -221,12 +221,12 @@ namespace NadekoBot.Modules.Searches.Commands
})); }));
if (streamStatus.Item1) if (streamStatus.Item1)
{ {
await e.Channel.SendMessage($"`Streamer {streamStatus.Item2} is online.`"); await channel.SendMessageAsync($"`Streamer {streamStatus.Item2} is online.`");
} }
} }
catch catch
{ {
await e.Channel.SendMessage("No channel found."); await channel.SendMessageAsync("No channel found.");
} }
}); });
@ -249,13 +249,13 @@ namespace NadekoBot.Modules.Searches.Commands
snc.Username.ToLower().Trim() == username); snc.Username.ToLower().Trim() == username);
if (toRemove == null) if (toRemove == null)
{ {
await e.Channel.SendMessage(":anger: No such stream.").ConfigureAwait(false); await channel.SendMessageAsync(":anger: No such stream.").ConfigureAwait(false);
return; return;
} }
config.ObservingStreams.Remove(toRemove); config.ObservingStreams.Remove(toRemove);
await ConfigHandler.SaveConfig().ConfigureAwait(false); await ConfigHandler.SaveConfig().ConfigureAwait(false);
await e.Channel.SendMessage($":ok: Removed `{toRemove.Username}`'s stream from notifications.").ConfigureAwait(false); await channel.SendMessageAsync($":ok: Removed `{toRemove.Username}`'s stream from notifications.").ConfigureAwait(false);
}); });
cgb.CreateCommand(Module.Prefix + "liststreams") cgb.CreateCommand(Module.Prefix + "liststreams")
@ -274,7 +274,7 @@ namespace NadekoBot.Modules.Searches.Commands
if (streamsArray.Length == 0) if (streamsArray.Length == 0)
{ {
await e.Channel.SendMessage("You are not following any streams on this server.").ConfigureAwait(false); await channel.SendMessageAsync("You are not following any streams on this server.").ConfigureAwait(false);
return; return;
} }
@ -288,7 +288,7 @@ namespace NadekoBot.Modules.Searches.Commands
return ""; return "";
})); }));
await e.Channel.SendMessage($"You are following **{streamsArray.Length}** streams on this server.\n\n" + text).ConfigureAwait(false); await channel.SendMessageAsync($"You are following **{streamsArray.Length}** streams on this server.\n\n" + text).ConfigureAwait(false);
}); });
} }
@ -311,7 +311,7 @@ namespace NadekoBot.Modules.Searches.Commands
var exists = config.ObservingStreams.Contains(stream); var exists = config.ObservingStreams.Contains(stream);
if (exists) if (exists)
{ {
await e.Channel.SendMessage(":anger: I am already notifying that stream on this channel.").ConfigureAwait(false); await channel.SendMessageAsync(":anger: I am already notifying that stream on this channel.").ConfigureAwait(false);
return; return;
} }
Tuple<bool, string> data; Tuple<bool, string> data;
@ -321,7 +321,7 @@ namespace NadekoBot.Modules.Searches.Commands
} }
catch catch
{ {
await e.Channel.SendMessage(":anger: Stream probably doesn't exist.").ConfigureAwait(false); await channel.SendMessageAsync(":anger: Stream probably doesn't exist.").ConfigureAwait(false);
return; return;
} }
var msg = $"Stream is currently **{(data.Item1 ? "ONLINE" : "OFFLINE")}** with **{data.Item2}** viewers"; var msg = $"Stream is currently **{(data.Item1 ? "ONLINE" : "OFFLINE")}** with **{data.Item2}** viewers";
@ -337,7 +337,7 @@ namespace NadekoBot.Modules.Searches.Commands
stream.LastStatus = data.Item1; stream.LastStatus = data.Item1;
if (!exists) if (!exists)
msg = $":ok: I will notify this channel when status changes.\n{msg}"; msg = $":ok: I will notify this channel when status changes.\n{msg}";
await e.Channel.SendMessage(msg).ConfigureAwait(false); await channel.SendMessageAsync(msg).ConfigureAwait(false);
config.ObservingStreams.Add(stream); config.ObservingStreams.Add(stream);
}; };
} }

View File

@ -29,7 +29,7 @@ namespace NadekoBot.Modules.Searches.Commands
{ {
jokes = JsonConvert.DeserializeObject<List<WoWJoke>>(File.ReadAllText("data/wowjokes.json")); jokes = JsonConvert.DeserializeObject<List<WoWJoke>>(File.ReadAllText("data/wowjokes.json"));
} }
await e.Channel.SendMessage(jokes[new Random().Next(0, jokes.Count)].ToString()); await channel.SendMessageAsync(jokes[new Random().Next(0, jokes.Count)].ToString());
}); });
} }
} }

View File

@ -59,7 +59,7 @@ namespace NadekoBot.Modules.Searches
var obj = JObject.Parse(response)["weather"]; var obj = JObject.Parse(response)["weather"];
await e.Channel.SendMessage( await channel.SendMessageAsync(
$@"🌍 **Weather for** 【{obj["target"]}】 $@"🌍 **Weather for** 【{obj["target"]}】
📏 **Lat,Long:** ({obj["latitude"]}, {obj["longitude"]}) **Condition:** {obj["condition"]} 📏 **Lat,Long:** ({obj["latitude"]}, {obj["longitude"]}) **Condition:** {obj["condition"]}
😓 **Humidity:** {obj["humidity"]}% 💨 **Wind Speed:** {obj["windspeedk"]}km/h / {obj["windspeedm"]}mph 😓 **Humidity:** {obj["humidity"]}% 💨 **Wind Speed:** {obj["windspeedk"]}km/h / {obj["windspeedm"]}mph
@ -76,11 +76,11 @@ $@"🌍 **Weather for** 【{obj["target"]}】
var link = await SearchHelper.FindYoutubeUrlByKeywords(e.GetArg("query")).ConfigureAwait(false); var link = await SearchHelper.FindYoutubeUrlByKeywords(e.GetArg("query")).ConfigureAwait(false);
if (string.IsNullOrWhiteSpace(link)) if (string.IsNullOrWhiteSpace(link))
{ {
await e.Channel.SendMessage("No results found for that query."); await channel.SendMessageAsync("No results found for that query.");
return; return;
} }
var shortUrl = await SearchHelper.ShortenUrl(link).ConfigureAwait(false); var shortUrl = await SearchHelper.ShortenUrl(link).ConfigureAwait(false);
await e.Channel.SendMessage(shortUrl).ConfigureAwait(false); await channel.SendMessageAsync(shortUrl).ConfigureAwait(false);
}); });
cgb.CreateCommand(Prefix + "ani") cgb.CreateCommand(Prefix + "ani")
@ -97,11 +97,11 @@ $@"🌍 **Weather for** 【{obj["target"]}】
} }
catch catch
{ {
await e.Channel.SendMessage("Failed to find that anime.").ConfigureAwait(false); await channel.SendMessageAsync("Failed to find that anime.").ConfigureAwait(false);
return; return;
} }
await e.Channel.SendMessage(result.ToString()).ConfigureAwait(false); await channel.SendMessageAsync(result.ToString()).ConfigureAwait(false);
}); });
cgb.CreateCommand(Prefix + "imdb") cgb.CreateCommand(Prefix + "imdb")
@ -120,11 +120,11 @@ $@"🌍 **Weather for** 【{obj["target"]}】
} }
catch catch
{ {
await e.Channel.SendMessage("Failed to find that movie.").ConfigureAwait(false); await channel.SendMessageAsync("Failed to find that movie.").ConfigureAwait(false);
return; return;
} }
await e.Channel.SendMessage(result.ToString()).ConfigureAwait(false); await channel.SendMessageAsync(result.ToString()).ConfigureAwait(false);
}); });
cgb.CreateCommand(Prefix + "mang") cgb.CreateCommand(Prefix + "mang")
@ -141,10 +141,10 @@ $@"🌍 **Weather for** 【{obj["target"]}】
} }
catch catch
{ {
await e.Channel.SendMessage("Failed to find that anime.").ConfigureAwait(false); await channel.SendMessageAsync("Failed to find that anime.").ConfigureAwait(false);
return; return;
} }
await e.Channel.SendMessage(result).ConfigureAwait(false); await channel.SendMessageAsync(result).ConfigureAwait(false);
}); });
cgb.CreateCommand(Prefix + "randomcat") cgb.CreateCommand(Prefix + "randomcat")
@ -152,7 +152,7 @@ $@"🌍 **Weather for** 【{obj["target"]}】
.Description($"Shows a random cat image. | `{Prefix}meow`") .Description($"Shows a random cat image. | `{Prefix}meow`")
.Do(async e => .Do(async e =>
{ {
await e.Channel.SendMessage(JObject.Parse( await channel.SendMessageAsync(JObject.Parse(
await SearchHelper.GetResponseStringAsync("http://www.random.cat/meow").ConfigureAwait(false))["file"].ToString()) await SearchHelper.GetResponseStringAsync("http://www.random.cat/meow").ConfigureAwait(false))["file"].ToString())
.ConfigureAwait(false); .ConfigureAwait(false);
}); });
@ -162,7 +162,7 @@ $@"🌍 **Weather for** 【{obj["target"]}】
.Description($"Shows a random dog image. | `{Prefix}woof`") .Description($"Shows a random dog image. | `{Prefix}woof`")
.Do(async e => .Do(async e =>
{ {
await e.Channel.SendMessage("http://random.dog/" + await SearchHelper.GetResponseStringAsync("http://random.dog/woof").ConfigureAwait(false)).ConfigureAwait(false); await channel.SendMessageAsync("http://random.dog/" + await SearchHelper.GetResponseStringAsync("http://random.dog/woof").ConfigureAwait(false)).ConfigureAwait(false);
}); });
cgb.CreateCommand(Prefix + "i") cgb.CreateCommand(Prefix + "i")
@ -176,17 +176,17 @@ $@"🌍 **Weather for** 【{obj["target"]}】
{ {
var reqString = $"https://www.googleapis.com/customsearch/v1?q={Uri.EscapeDataString(e.GetArg("query"))}&cx=018084019232060951019%3Ahs5piey28-e&num=1&searchType=image&fields=items%2Flink&key={NadekoBot.Creds.GoogleAPIKey}"; var reqString = $"https://www.googleapis.com/customsearch/v1?q={Uri.EscapeDataString(e.GetArg("query"))}&cx=018084019232060951019%3Ahs5piey28-e&num=1&searchType=image&fields=items%2Flink&key={NadekoBot.Creds.GoogleAPIKey}";
var obj = JObject.Parse(await SearchHelper.GetResponseStringAsync(reqString).ConfigureAwait(false)); var obj = JObject.Parse(await SearchHelper.GetResponseStringAsync(reqString).ConfigureAwait(false));
await e.Channel.SendMessage(obj["items"][0]["link"].ToString()).ConfigureAwait(false); await channel.SendMessageAsync(obj["items"][0]["link"].ToString()).ConfigureAwait(false);
} }
catch (HttpRequestException exception) catch (HttpRequestException exception)
{ {
if (exception.Message.Contains("403 (Forbidden)")) if (exception.Message.Contains("403 (Forbidden)"))
{ {
await e.Channel.SendMessage("Daily limit reached!"); await channel.SendMessageAsync("Daily limit reached!");
} }
else else
{ {
await e.Channel.SendMessage("Something went wrong."); await channel.SendMessageAsync("Something went wrong.");
} }
} }
}); });
@ -203,17 +203,17 @@ $@"🌍 **Weather for** 【{obj["target"]}】
var reqString = $"https://www.googleapis.com/customsearch/v1?q={Uri.EscapeDataString(e.GetArg("query"))}&cx=018084019232060951019%3Ahs5piey28-e&num=1&searchType=image&start={ rng.Next(1, 50) }&fields=items%2Flink&key={NadekoBot.Creds.GoogleAPIKey}"; var reqString = $"https://www.googleapis.com/customsearch/v1?q={Uri.EscapeDataString(e.GetArg("query"))}&cx=018084019232060951019%3Ahs5piey28-e&num=1&searchType=image&start={ rng.Next(1, 50) }&fields=items%2Flink&key={NadekoBot.Creds.GoogleAPIKey}";
var obj = JObject.Parse(await SearchHelper.GetResponseStringAsync(reqString).ConfigureAwait(false)); var obj = JObject.Parse(await SearchHelper.GetResponseStringAsync(reqString).ConfigureAwait(false));
var items = obj["items"] as JArray; var items = obj["items"] as JArray;
await e.Channel.SendMessage(items[0]["link"].ToString()).ConfigureAwait(false); await channel.SendMessageAsync(items[0]["link"].ToString()).ConfigureAwait(false);
} }
catch (HttpRequestException exception) catch (HttpRequestException exception)
{ {
if (exception.Message.Contains("403 (Forbidden)")) if (exception.Message.Contains("403 (Forbidden)"))
{ {
await e.Channel.SendMessage("Daily limit reached!"); await channel.SendMessageAsync("Daily limit reached!");
} }
else else
{ {
await e.Channel.SendMessage("Something went wrong."); await channel.SendMessageAsync("Something went wrong.");
} }
} }
}); });
@ -224,7 +224,7 @@ $@"🌍 **Weather for** 【{obj["target"]}】
.Do(async e => .Do(async e =>
{ {
if (e.GetArg("ffs") == null || e.GetArg("ffs").Length < 1) return; if (e.GetArg("ffs") == null || e.GetArg("ffs").Length < 1) return;
await e.Channel.SendMessage(await $"http://lmgtfy.com/?q={ Uri.EscapeUriString(e.GetArg("ffs").ToString()) }".ShortenUrl()) await channel.SendMessageAsync(await $"http://lmgtfy.com/?q={ Uri.EscapeUriString(e.GetArg("ffs").ToString()) }".ShortenUrl())
.ConfigureAwait(false); .ConfigureAwait(false);
}); });
@ -237,7 +237,7 @@ $@"🌍 **Weather for** 【{obj["target"]}】
var terms = e.GetArg("terms")?.Trim(); var terms = e.GetArg("terms")?.Trim();
if (string.IsNullOrWhiteSpace(terms)) if (string.IsNullOrWhiteSpace(terms))
return; return;
await e.Channel.SendMessage($"https://google.com/search?q={ HttpUtility.UrlEncode(terms).Replace(' ', '+') }") await channel.SendMessageAsync($"https://google.com/search?q={ HttpUtility.UrlEncode(terms).Replace(' ', '+') }")
.ConfigureAwait(false); .ConfigureAwait(false);
}); });
@ -249,7 +249,7 @@ $@"🌍 **Weather for** 【{obj["target"]}】
var arg = e.GetArg("name"); var arg = e.GetArg("name");
if (string.IsNullOrWhiteSpace(arg)) if (string.IsNullOrWhiteSpace(arg))
{ {
await e.Channel.SendMessage("💢 Please enter a card name to search for.").ConfigureAwait(false); await channel.SendMessageAsync("💢 Please enter a card name to search for.").ConfigureAwait(false);
return; return;
} }
await e.Channel.SendIsTyping().ConfigureAwait(false); await e.Channel.SendIsTyping().ConfigureAwait(false);
@ -271,14 +271,14 @@ $@"🌍 **Weather for** 【{obj["target"]}】
} }
if (items.Count > 4) if (items.Count > 4)
{ {
await e.Channel.SendMessage("⚠ Found over 4 images. Showing random 4.").ConfigureAwait(false); await channel.SendMessageAsync("⚠ Found over 4 images. Showing random 4.").ConfigureAwait(false);
} }
await e.Channel.SendFile(arg + ".png", (await images.MergeAsync()).ToStream(System.Drawing.Imaging.ImageFormat.Png)) await e.Channel.SendFile(arg + ".png", (await images.MergeAsync()).ToStream(System.Drawing.Imaging.ImageFormat.Png))
.ConfigureAwait(false); .ConfigureAwait(false);
} }
catch (Exception ex) catch (Exception ex)
{ {
await e.Channel.SendMessage($"💢 Error {ex.Message}").ConfigureAwait(false); await channel.SendMessageAsync($"💢 Error {ex.Message}").ConfigureAwait(false);
} }
}); });
@ -290,7 +290,7 @@ $@"🌍 **Weather for** 【{obj["target"]}】
var arg = e.GetArg("query"); var arg = e.GetArg("query");
if (string.IsNullOrWhiteSpace(arg)) if (string.IsNullOrWhiteSpace(arg))
{ {
await e.Channel.SendMessage("💢 Please enter a search term.").ConfigureAwait(false); await channel.SendMessageAsync("💢 Please enter a search term.").ConfigureAwait(false);
return; return;
} }
await e.Channel.SendIsTyping().ConfigureAwait(false); await e.Channel.SendIsTyping().ConfigureAwait(false);
@ -303,11 +303,11 @@ $@"🌍 **Weather for** 【{obj["target"]}】
sb.AppendLine($"`Term:` {items["list"][0]["word"].ToString()}"); sb.AppendLine($"`Term:` {items["list"][0]["word"].ToString()}");
sb.AppendLine($"`Definition:` {items["list"][0]["definition"].ToString()}"); sb.AppendLine($"`Definition:` {items["list"][0]["definition"].ToString()}");
sb.Append($"`Link:` <{await items["list"][0]["permalink"].ToString().ShortenUrl().ConfigureAwait(false)}>"); sb.Append($"`Link:` <{await items["list"][0]["permalink"].ToString().ShortenUrl().ConfigureAwait(false)}>");
await e.Channel.SendMessage(sb.ToString()); await channel.SendMessageAsync(sb.ToString());
} }
catch catch
{ {
await e.Channel.SendMessage("💢 Failed finding a definition for that term.").ConfigureAwait(false); await channel.SendMessageAsync("💢 Failed finding a definition for that term.").ConfigureAwait(false);
} }
}); });
// thanks to Blaubeerwald // thanks to Blaubeerwald
@ -319,7 +319,7 @@ $@"🌍 **Weather for** 【{obj["target"]}】
var arg = e.GetArg("query"); var arg = e.GetArg("query");
if (string.IsNullOrWhiteSpace(arg)) if (string.IsNullOrWhiteSpace(arg))
{ {
await e.Channel.SendMessage("💢 Please enter a search term.").ConfigureAwait(false); await channel.SendMessageAsync("💢 Please enter a search term.").ConfigureAwait(false);
return; return;
} }
await e.Channel.SendIsTyping().ConfigureAwait(false); await e.Channel.SendIsTyping().ConfigureAwait(false);
@ -332,11 +332,11 @@ $@"🌍 **Weather for** 【{obj["target"]}】
sb.AppendLine($"`Hashtag:` {items["defs"]["def"]["hashtag"].ToString()}"); sb.AppendLine($"`Hashtag:` {items["defs"]["def"]["hashtag"].ToString()}");
sb.AppendLine($"`Definition:` {items["defs"]["def"]["text"].ToString()}"); sb.AppendLine($"`Definition:` {items["defs"]["def"]["text"].ToString()}");
sb.Append($"`Link:` <{await items["defs"]["def"]["uri"].ToString().ShortenUrl().ConfigureAwait(false)}>"); sb.Append($"`Link:` <{await items["defs"]["def"]["uri"].ToString().ShortenUrl().ConfigureAwait(false)}>");
await e.Channel.SendMessage(sb.ToString()); await channel.SendMessageAsync(sb.ToString());
} }
catch catch
{ {
await e.Channel.SendMessage("💢 Failed finidng a definition for that tag.").ConfigureAwait(false); await channel.SendMessageAsync("💢 Failed finidng a definition for that tag.").ConfigureAwait(false);
} }
}); });
@ -345,7 +345,7 @@ $@"🌍 **Weather for** 【{obj["target"]}】
.Do(async e => .Do(async e =>
{ {
var quote = NadekoBot.Config.Quotes[rng.Next(0, NadekoBot.Config.Quotes.Count)].ToString(); var quote = NadekoBot.Config.Quotes[rng.Next(0, NadekoBot.Config.Quotes.Count)].ToString();
await e.Channel.SendMessage(quote).ConfigureAwait(false); await channel.SendMessageAsync(quote).ConfigureAwait(false);
}); });
cgb.CreateCommand(Prefix + "catfact") cgb.CreateCommand(Prefix + "catfact")
@ -355,7 +355,7 @@ $@"🌍 **Weather for** 【{obj["target"]}】
var response = await SearchHelper.GetResponseStringAsync("http://catfacts-api.appspot.com/api/facts").ConfigureAwait(false); var response = await SearchHelper.GetResponseStringAsync("http://catfacts-api.appspot.com/api/facts").ConfigureAwait(false);
if (response == null) if (response == null)
return; return;
await e.Channel.SendMessage($"🐈 `{JObject.Parse(response)["facts"][0].ToString()}`").ConfigureAwait(false); await channel.SendMessageAsync($"🐈 `{JObject.Parse(response)["facts"][0].ToString()}`").ConfigureAwait(false);
}); });
cgb.CreateCommand(Prefix + "yomama") cgb.CreateCommand(Prefix + "yomama")
@ -364,7 +364,7 @@ $@"🌍 **Weather for** 【{obj["target"]}】
.Do(async e => .Do(async e =>
{ {
var response = await SearchHelper.GetResponseStringAsync("http://api.yomomma.info/").ConfigureAwait(false); var response = await SearchHelper.GetResponseStringAsync("http://api.yomomma.info/").ConfigureAwait(false);
await e.Channel.SendMessage("`" + JObject.Parse(response)["joke"].ToString() + "` 😆").ConfigureAwait(false); await channel.SendMessageAsync("`" + JObject.Parse(response)["joke"].ToString() + "` 😆").ConfigureAwait(false);
}); });
cgb.CreateCommand(Prefix + "randjoke") cgb.CreateCommand(Prefix + "randjoke")
@ -373,7 +373,7 @@ $@"🌍 **Weather for** 【{obj["target"]}】
.Do(async e => .Do(async e =>
{ {
var response = await SearchHelper.GetResponseStringAsync("http://tambal.azurewebsites.net/joke/random").ConfigureAwait(false); var response = await SearchHelper.GetResponseStringAsync("http://tambal.azurewebsites.net/joke/random").ConfigureAwait(false);
await e.Channel.SendMessage("`" + JObject.Parse(response)["joke"].ToString() + "` 😆").ConfigureAwait(false); await channel.SendMessageAsync("`" + JObject.Parse(response)["joke"].ToString() + "` 😆").ConfigureAwait(false);
}); });
cgb.CreateCommand(Prefix + "chucknorris") cgb.CreateCommand(Prefix + "chucknorris")
@ -382,7 +382,7 @@ $@"🌍 **Weather for** 【{obj["target"]}】
.Do(async e => .Do(async e =>
{ {
var response = await SearchHelper.GetResponseStringAsync("http://api.icndb.com/jokes/random/").ConfigureAwait(false); var response = await SearchHelper.GetResponseStringAsync("http://api.icndb.com/jokes/random/").ConfigureAwait(false);
await e.Channel.SendMessage("`" + JObject.Parse(response)["value"]["joke"].ToString() + "` 😆").ConfigureAwait(false); await channel.SendMessageAsync("`" + JObject.Parse(response)["value"]["joke"].ToString() + "` 😆").ConfigureAwait(false);
}); });
cgb.CreateCommand(Prefix + "magicitem") cgb.CreateCommand(Prefix + "magicitem")
@ -393,7 +393,7 @@ $@"🌍 **Weather for** 【{obj["target"]}】
var magicItems = JsonConvert.DeserializeObject<List<MagicItem>>(File.ReadAllText("data/magicitems.json")); var magicItems = JsonConvert.DeserializeObject<List<MagicItem>>(File.ReadAllText("data/magicitems.json"));
var item = magicItems[rng.Next(0, magicItems.Count)].ToString(); var item = magicItems[rng.Next(0, magicItems.Count)].ToString();
await e.Channel.SendMessage(item).ConfigureAwait(false); await channel.SendMessageAsync(item).ConfigureAwait(false);
}); });
cgb.CreateCommand(Prefix + "revav") cgb.CreateCommand(Prefix + "revav")
@ -410,7 +410,7 @@ $@"🌍 **Weather for** 【{obj["target"]}】
if (usr == null || string.IsNullOrWhiteSpace(usr.AvatarUrl)) if (usr == null || string.IsNullOrWhiteSpace(usr.AvatarUrl))
return; return;
await e.Channel.SendMessage($"https://images.google.com/searchbyimage?image_url={usr.AvatarUrl}").ConfigureAwait(false); await channel.SendMessageAsync($"https://images.google.com/searchbyimage?image_url={usr.AvatarUrl}").ConfigureAwait(false);
}); });
cgb.CreateCommand(Prefix + "revimg") cgb.CreateCommand(Prefix + "revimg")
@ -422,7 +422,7 @@ $@"🌍 **Weather for** 【{obj["target"]}】
if (string.IsNullOrWhiteSpace(imgLink)) if (string.IsNullOrWhiteSpace(imgLink))
return; return;
await e.Channel.SendMessage($"https://images.google.com/searchbyimage?image_url={imgLink}").ConfigureAwait(false); await channel.SendMessageAsync($"https://images.google.com/searchbyimage?image_url={imgLink}").ConfigureAwait(false);
}); });
cgb.CreateCommand(Prefix + "safebooru") cgb.CreateCommand(Prefix + "safebooru")
@ -433,9 +433,9 @@ $@"🌍 **Weather for** 【{obj["target"]}】
var tag = e.GetArg("tag")?.Trim() ?? ""; var tag = e.GetArg("tag")?.Trim() ?? "";
var link = await SearchHelper.GetSafebooruImageLink(tag).ConfigureAwait(false); var link = await SearchHelper.GetSafebooruImageLink(tag).ConfigureAwait(false);
if (link == null) if (link == null)
await e.Channel.SendMessage("`No results.`"); await channel.SendMessageAsync("`No results.`");
else else
await e.Channel.SendMessage(link).ConfigureAwait(false); await channel.SendMessageAsync(link).ConfigureAwait(false);
}); });
cgb.CreateCommand(Prefix + "wiki") cgb.CreateCommand(Prefix + "wiki")
@ -447,9 +447,9 @@ $@"🌍 **Weather for** 【{obj["target"]}】
var result = await SearchHelper.GetResponseStringAsync("https://en.wikipedia.org//w/api.php?action=query&format=json&prop=info&redirects=1&formatversion=2&inprop=url&titles=" + Uri.EscapeDataString(query)); var result = await SearchHelper.GetResponseStringAsync("https://en.wikipedia.org//w/api.php?action=query&format=json&prop=info&redirects=1&formatversion=2&inprop=url&titles=" + Uri.EscapeDataString(query));
var data = JsonConvert.DeserializeObject<WikipediaApiModel>(result); var data = JsonConvert.DeserializeObject<WikipediaApiModel>(result);
if (data.Query.Pages[0].Missing) if (data.Query.Pages[0].Missing)
await e.Channel.SendMessage("`That page could not be found.`"); await channel.SendMessageAsync("`That page could not be found.`");
else else
await e.Channel.SendMessage(data.Query.Pages[0].FullUrl); await channel.SendMessageAsync(data.Query.Pages[0].FullUrl);
}); });
cgb.CreateCommand(Prefix + "clr") cgb.CreateCommand(Prefix + "clr")
@ -508,10 +508,10 @@ $@"🌍 **Weather for** 【{obj["target"]}】
var usr = e.Channel.FindUsers(e.GetArg("mention")).FirstOrDefault(); var usr = e.Channel.FindUsers(e.GetArg("mention")).FirstOrDefault();
if (usr == null) if (usr == null)
{ {
await e.Channel.SendMessage("Invalid user specified.").ConfigureAwait(false); await channel.SendMessageAsync("Invalid user specified.").ConfigureAwait(false);
return; return;
} }
await e.Channel.SendMessage(await usr.AvatarUrl.ShortenUrl()).ConfigureAwait(false); await channel.SendMessageAsync(await usr.AvatarUrl.ShortenUrl()).ConfigureAwait(false);
}); });
}); });

View File

@ -32,12 +32,12 @@ namespace NadekoBot.Modules.Translator
return; return;
string translation = await t.Translate(text, from, to).ConfigureAwait(false); string translation = await t.Translate(text, from, to).ConfigureAwait(false);
await e.Channel.SendMessage(translation).ConfigureAwait(false); await channel.SendMessageAsync(translation).ConfigureAwait(false);
} }
catch (Exception ex) catch (Exception ex)
{ {
Console.WriteLine(ex); Console.WriteLine(ex);
await e.Channel.SendMessage("Bad input format, or something went wrong...").ConfigureAwait(false); await channel.SendMessageAsync("Bad input format, or something went wrong...").ConfigureAwait(false);
} }
}; };

View File

@ -38,11 +38,11 @@ namespace NadekoBot.Modules.Translator
ret += " " + key + ";"; ret += " " + key + ";";
} }
} }
await e.Channel.SendMessage(ret).ConfigureAwait(false); await channel.SendMessageAsync(ret).ConfigureAwait(false);
} }
catch catch
{ {
await e.Channel.SendMessage("Bad input format, or sth went wrong...").ConfigureAwait(false); await channel.SendMessageAsync("Bad input format, or sth went wrong...").ConfigureAwait(false);
} }
}; };

View File

@ -82,7 +82,7 @@ namespace NadekoBot.Modules.Trello
bound = e.Channel; bound = e.Channel;
board = new Board(e.GetArg("board_id").Trim()); board = new Board(e.GetArg("board_id").Trim());
board.Refresh(); board.Refresh();
await e.Channel.SendMessage("Successfully bound to this channel and board " + board.Name); await channel.SendMessageAsync("Successfully bound to this channel and board " + board.Name);
t.Start(); t.Start();
} }
catch (Exception ex) catch (Exception ex)
@ -100,7 +100,7 @@ namespace NadekoBot.Modules.Trello
t.Stop(); t.Stop();
bound = null; bound = null;
board = null; board = null;
await e.Channel.SendMessage("Successfully unbound trello from this channel.").ConfigureAwait(false); await channel.SendMessageAsync("Successfully unbound trello from this channel.").ConfigureAwait(false);
}); });
@ -111,7 +111,7 @@ namespace NadekoBot.Modules.Trello
{ {
if (!NadekoBot.IsOwner(e.User.Id)) return; if (!NadekoBot.IsOwner(e.User.Id)) return;
if (bound == null || board == null || bound != e.Channel) return; if (bound == null || board == null || bound != e.Channel) return;
await e.Channel.SendMessage("Lists for a board '" + board.Name + "'\n" + string.Join("\n", board.Lists.Select(l => "**• " + l.ToString() + "**"))) await channel.SendMessageAsync("Lists for a board '" + board.Name + "'\n" + string.Join("\n", board.Lists.Select(l => "**• " + l.ToString() + "**")))
.ConfigureAwait(false); .ConfigureAwait(false);
}); });
@ -133,10 +133,10 @@ namespace NadekoBot.Modules.Trello
if (list != null) if (list != null)
await e.Channel.SendMessage("There are " + list.Cards.Count() + " cards in a **" + list.Name + "** list\n" + string.Join("\n", list.Cards.Select(c => "**• " + c.ToString() + "**"))) await channel.SendMessageAsync("There are " + list.Cards.Count() + " cards in a **" + list.Name + "** list\n" + string.Join("\n", list.Cards.Select(c => "**• " + c.ToString() + "**")))
.ConfigureAwait(false); .ConfigureAwait(false);
else else
await e.Channel.SendMessage("No such list.") await channel.SendMessageAsync("No such list.")
.ConfigureAwait(false); .ConfigureAwait(false);
}); });
}); });