continued refactoring

This commit is contained in:
Master Kwoth 2016-02-29 10:59:40 +01:00
parent 3b170c283d
commit fda5755a7f
26 changed files with 129 additions and 139 deletions

View File

@ -149,7 +149,7 @@ namespace NadekoBot.Classes.Music {
byte[] buffer = new byte[blockSize]; byte[] buffer = new byte[blockSize];
int attempt = 0; int attempt = 0;
while (!cancelToken.IsCancellationRequested) { while (!cancelToken.IsCancellationRequested) {
int read = await p.StandardOutput.BaseStream.ReadAsync(buffer, 0, blockSize); int read = await p.StandardOutput.BaseStream.ReadAsync(buffer, 0, blockSize, cancelToken);
if (read == 0) if (read == 0)
if (attempt++ == 20) if (attempt++ == 20)
break; break;
@ -162,6 +162,9 @@ namespace NadekoBot.Classes.Music {
prebufferingComplete = true; prebufferingComplete = true;
} }
} }
catch {
Console.WriteLine("Buffering errored");
}
finally { finally {
if (p != null) { if (p != null) {
p.CancelOutputRead(); p.CancelOutputRead();
@ -171,7 +174,7 @@ namespace NadekoBot.Classes.Music {
p.Dispose(); p.Dispose();
} }
} }
Console.WriteLine($"Buffering done. [{songBuffer.ContentLength}]"); Console.WriteLine($"Buffering done." + $" [{songBuffer.ContentLength}]");
}); });
internal async Task Play(IAudioClient voiceClient, CancellationToken cancelToken) { internal async Task Play(IAudioClient voiceClient, CancellationToken cancelToken) {
@ -180,8 +183,9 @@ namespace NadekoBot.Classes.Music {
int waitPerAttempt = 500; int waitPerAttempt = 500;
int toAttemptTimes = SongInfo.ProviderType != MusicType.Normal ? 5 : 9; int toAttemptTimes = SongInfo.ProviderType != MusicType.Normal ? 5 : 9;
while (!prebufferingComplete && bufferAttempts++ < toAttemptTimes) { while (!prebufferingComplete && bufferAttempts++ < toAttemptTimes) {
await Task.Delay(waitPerAttempt); await Task.Delay(waitPerAttempt, cancelToken);
} }
cancelToken.ThrowIfCancellationRequested();
Console.WriteLine($"Prebuffering done? in {waitPerAttempt * bufferAttempts}"); Console.WriteLine($"Prebuffering done? in {waitPerAttempt * bufferAttempts}");
int blockSize = 3840; int blockSize = 3840;
byte[] buffer = new byte[blockSize]; byte[] buffer = new byte[blockSize];
@ -190,9 +194,9 @@ namespace NadekoBot.Classes.Music {
//Console.WriteLine($"Read: {songBuffer.ReadPosition}\nWrite: {songBuffer.WritePosition}\nContentLength:{songBuffer.ContentLength}\n---------"); //Console.WriteLine($"Read: {songBuffer.ReadPosition}\nWrite: {songBuffer.WritePosition}\nContentLength:{songBuffer.ContentLength}\n---------");
int read = songBuffer.Read(buffer, blockSize); int read = songBuffer.Read(buffer, blockSize);
if (read == 0) if (read == 0)
if (attempt++ == 10) { if (attempt++ == 20) {
voiceClient.Wait(); voiceClient.Wait();
Console.WriteLine("Playing done."); Console.WriteLine("Nothing to read.");
return; return;
} }
else else
@ -201,10 +205,11 @@ namespace NadekoBot.Classes.Music {
attempt = 0; attempt = 0;
while (this.MusicPlayer.Paused) while (this.MusicPlayer.Paused)
await Task.Delay(200); await Task.Delay(200, cancelToken);
buffer = adjustVolume(buffer, MusicPlayer.Volume); buffer = adjustVolume(buffer, MusicPlayer.Volume);
voiceClient.Send(buffer, 0, read); voiceClient.Send(buffer, 0, read);
} }
cancelToken.ThrowIfCancellationRequested();
//try { //try {
// voiceClient.Clear(); // voiceClient.Clear();
// Console.WriteLine("CLEARED"); // Console.WriteLine("CLEARED");

View File

@ -16,10 +16,10 @@ namespace NadekoBot.Classes.Music {
public async Task<SoundCloudVideo> GetVideoAsync(string url) { public async Task<SoundCloudVideo> GetVideoAsync(string url) {
if (string.IsNullOrWhiteSpace(url)) if (string.IsNullOrWhiteSpace(url))
throw new ArgumentNullException(nameof(url)); throw new ArgumentNullException(nameof(url));
if (string.IsNullOrWhiteSpace(NadekoBot.creds.SoundCloudClientID)) if (string.IsNullOrWhiteSpace(NadekoBot.Creds.SoundCloudClientID))
throw new ArgumentNullException(nameof(NadekoBot.creds.SoundCloudClientID)); throw new ArgumentNullException(nameof(NadekoBot.Creds.SoundCloudClientID));
var response = await SearchHelper.GetResponseAsync($"http://api.soundcloud.com/resolve?url={url}&client_id={NadekoBot.creds.SoundCloudClientID}"); var response = await SearchHelper.GetResponseAsync($"http://api.soundcloud.com/resolve?url={url}&client_id={NadekoBot.Creds.SoundCloudClientID}");
var responseObj = Newtonsoft.Json.JsonConvert.DeserializeObject<SoundCloudVideo>(response); var responseObj = Newtonsoft.Json.JsonConvert.DeserializeObject<SoundCloudVideo>(response);
if (responseObj?.Kind != "track") if (responseObj?.Kind != "track")
@ -39,7 +39,7 @@ namespace NadekoBot.Classes.Music {
public string Title = ""; public string Title = "";
public string FullName => User.Name + " - " + Title; public string FullName => User.Name + " - " + Title;
public bool Streamable = false; public bool Streamable = false;
public string StreamLink => $"https://api.soundcloud.com/tracks/{Id}/stream?client_id={NadekoBot.creds.SoundCloudClientID}"; public string StreamLink => $"https://api.soundcloud.com/tracks/{Id}/stream?client_id={NadekoBot.Creds.SoundCloudClientID}";
} }
public class SoundCloudUser { public class SoundCloudUser {
[Newtonsoft.Json.JsonProperty("username")] [Newtonsoft.Json.JsonProperty("username")]

View File

@ -31,8 +31,8 @@ namespace NadekoBot {
static NadekoStats() { } static NadekoStats() { }
private NadekoStats() { private NadekoStats() {
_service = NadekoBot.client.GetService<CommandService>(); _service = NadekoBot.Client.GetService<CommandService>();
_client = NadekoBot.client; _client = NadekoBot.Client;
_statsSW = new Stopwatch(); _statsSW = new Stopwatch();
_statsSW.Start(); _statsSW.Start();
@ -130,10 +130,10 @@ namespace NadekoBot {
while (true) { while (true) {
await Task.Delay(new TimeSpan(0, 30, 0)); await Task.Delay(new TimeSpan(0, 30, 0));
try { try {
var onlineUsers = await Task.Run(() => NadekoBot.client.Servers.Sum(x => x.Users.Count())); var onlineUsers = await Task.Run(() => NadekoBot.Client.Servers.Sum(x => x.Users.Count()));
var realOnlineUsers = await Task.Run(() => NadekoBot.client.Servers var realOnlineUsers = await Task.Run(() => NadekoBot.Client.Servers
.Sum(x => x.Users.Where(u => u.Status == UserStatus.Online).Count())); .Sum(x => x.Users.Where(u => u.Status == UserStatus.Online).Count()));
var connectedServers = NadekoBot.client.Servers.Count(); var connectedServers = NadekoBot.Client.Servers.Count();
Classes.DBHandler.Instance.InsertData(new Classes._DataModels.Stats { Classes.DBHandler.Instance.InsertData(new Classes._DataModels.Stats {
OnlineUsers = onlineUsers, OnlineUsers = onlineUsers,

View File

@ -1,8 +1,5 @@
using Discord.Commands.Permissions; using Discord.Commands.Permissions;
using System; using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using Discord; using Discord;
using Discord.Commands; using Discord.Commands;

View File

@ -40,7 +40,7 @@ namespace NadekoBot.Classes {
if (string.IsNullOrWhiteSpace(mod)) if (string.IsNullOrWhiteSpace(mod))
throw new ArgumentNullException(nameof(mod)); throw new ArgumentNullException(nameof(mod));
foreach (var m in NadekoBot.client.GetService<ModuleService>().Modules) { foreach (var m in NadekoBot.Client.GetService<ModuleService>().Modules) {
if (m.Name.ToLower().Equals(mod.ToLower())) if (m.Name.ToLower().Equals(mod.ToLower()))
return m.Name; return m.Name;
} }
@ -51,7 +51,7 @@ namespace NadekoBot.Classes {
if (string.IsNullOrWhiteSpace(commandText)) if (string.IsNullOrWhiteSpace(commandText))
throw new ArgumentNullException(nameof(commandText)); throw new ArgumentNullException(nameof(commandText));
foreach (var com in NadekoBot.client.GetService<CommandService>().AllCommands) { foreach (var com in NadekoBot.Client.GetService<CommandService>().AllCommands) {
if (com.Text.ToLower().Equals(commandText.ToLower())) if (com.Text.ToLower().Equals(commandText.ToLower()))
return com.Text; return com.Text;
} }

View File

@ -9,6 +9,6 @@ using System.Threading.Tasks;
namespace NadekoBot.Classes.Permissions { namespace NadekoBot.Classes.Permissions {
static class SimpleCheckers { static class SimpleCheckers {
public static Func<Command, User, Channel, bool> OwnerOnly() => public static Func<Command, User, Channel, bool> OwnerOnly() =>
(com, user, ch) => user.Id == NadekoBot.creds.OwnerID; (com, user, ch) => user.Id == NadekoBot.Creds.OwnerID;
} }
} }

View File

@ -9,23 +9,19 @@ using System.Text.RegularExpressions;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace NadekoBot.Classes { namespace NadekoBot.Classes {
static class SearchHelper { public static class SearchHelper {
public static async Task<Stream> GetResponseStream(string v) { public static async Task<Stream> GetResponseStream(string v) {
var wr = (HttpWebRequest)WebRequest.Create(v); var wr = (HttpWebRequest)WebRequest.Create(v);
try { return (await (wr).GetResponseAsync()).GetResponseStream();
return (await (wr).GetResponseAsync()).GetResponseStream();
}
catch (Exception ex) {
Console.WriteLine("error in getresponse stream " + ex);
return null;
}
} }
public static async Task<string> GetResponseAsync(string v, WebHeaderCollection headers = null) { public static async Task<string> GetResponseAsync(string v, WebHeaderCollection headers = null) {
var wr = (HttpWebRequest)WebRequest.Create(v); var wr = (HttpWebRequest)WebRequest.Create(v);
if (headers != null) if (headers != null)
wr.Headers = headers; wr.Headers = headers;
using (var sr = new StreamReader((await wr.GetResponseAsync()).GetResponseStream())) { var stream = (await wr.GetResponseAsync()).GetResponseStream();
if (stream == null) return "";
using (var sr = new StreamReader(stream)) {
return await sr.ReadToEndAsync(); return await sr.ReadToEndAsync();
} }
} }
@ -46,8 +42,7 @@ namespace NadekoBot.Classes {
rq = new RestSharp.RestRequest("anime/" + smallObj["id"]); rq = new RestSharp.RestRequest("anime/" + smallObj["id"]);
rq.AddParameter("access_token", token); rq.AddParameter("access_token", token);
return await Task.Run(() => JsonConvert.DeserializeObject<AnimeResult>(cl.Execute(rq).Content)); return await Task.Run(() => JsonConvert.DeserializeObject<AnimeResult>(cl.Execute(rq).Content));
} } catch {
catch {
return null; return null;
} }
} }
@ -66,8 +61,7 @@ namespace NadekoBot.Classes {
rq = new RestSharp.RestRequest("manga/" + smallObj["id"]); rq = new RestSharp.RestRequest("manga/" + smallObj["id"]);
rq.AddParameter("access_token", token); rq.AddParameter("access_token", token);
return await Task.Run(() => JsonConvert.DeserializeObject<MangaResult>(cl.Execute(rq).Content)); return await Task.Run(() => JsonConvert.DeserializeObject<MangaResult>(cl.Execute(rq).Content));
} } catch (Exception ex) {
catch (Exception ex) {
Console.WriteLine(ex.ToString()); Console.WriteLine(ex.ToString());
return null; return null;
} }
@ -83,8 +77,7 @@ namespace NadekoBot.Classes {
var exec = cl.Execute(rq); var exec = cl.Execute(rq);
token = JObject.Parse(exec.Content)["access_token"].ToString(); token = JObject.Parse(exec.Content)["access_token"].ToString();
} } catch (Exception ex) {
catch (Exception ex) {
Console.WriteLine($"Failed refreshing anilist token:\n {ex}"); Console.WriteLine($"Failed refreshing anilist token:\n {ex}");
} }
} }
@ -98,7 +91,7 @@ namespace NadekoBot.Classes {
} }
public static async Task<string> FindYoutubeUrlByKeywords(string v) { public static async Task<string> FindYoutubeUrlByKeywords(string v) {
if (NadekoBot.GoogleAPIKey == "" || NadekoBot.GoogleAPIKey == null) { if (string.IsNullOrWhiteSpace(NadekoBot.GoogleAPIKey)) {
Console.WriteLine("ERROR: No google api key found. Playing `Never gonna give you up`."); Console.WriteLine("ERROR: No google api key found. Playing `Never gonna give you up`.");
return @"https://www.youtube.com/watch?v=dQw4w9WgXcQ"; return @"https://www.youtube.com/watch?v=dQw4w9WgXcQ";
} }
@ -117,15 +110,14 @@ namespace NadekoBot.Classes {
dynamic obj = JObject.Parse(await sr.ReadToEndAsync()); dynamic obj = JObject.Parse(await sr.ReadToEndAsync());
return "http://www.youtube.com/watch?v=" + obj.items[0].id.videoId.ToString(); return "http://www.youtube.com/watch?v=" + obj.items[0].id.videoId.ToString();
} }
} } catch (Exception ex) {
catch (Exception ex) {
Console.WriteLine($"Error in findyoutubeurl: {ex.Message}"); Console.WriteLine($"Error in findyoutubeurl: {ex.Message}");
return string.Empty; return string.Empty;
} }
} }
public static async Task<string> GetPlaylistIdByKeyword(string v) { public static async Task<string> GetPlaylistIdByKeyword(string v) {
if (NadekoBot.GoogleAPIKey == "" || NadekoBot.GoogleAPIKey == null) { if (string.IsNullOrWhiteSpace(NadekoBot.GoogleAPIKey)) {
Console.WriteLine("ERROR: No google api key found. Playing `Never gonna give you up`."); Console.WriteLine("ERROR: No google api key found. Playing `Never gonna give you up`.");
return string.Empty; return string.Empty;
} }
@ -136,8 +128,7 @@ namespace NadekoBot.Classes {
dynamic obj = JObject.Parse(await sr.ReadToEndAsync()); dynamic obj = JObject.Parse(await sr.ReadToEndAsync());
return obj.items[0].id.playlistId.ToString(); return obj.items[0].id.playlistId.ToString();
} } catch (Exception ex) {
catch (Exception ex) {
Console.WriteLine($"Error in GetPlaylistId: {ex.Message}"); Console.WriteLine($"Error in GetPlaylistId: {ex.Message}");
return string.Empty; return string.Empty;
} }
@ -145,15 +136,17 @@ namespace NadekoBot.Classes {
public static async Task<List<string>> GetVideoIDs(string v) { public static async Task<List<string>> GetVideoIDs(string v) {
List<string> toReturn = new List<string>(); List<string> toReturn = new List<string>();
if (NadekoBot.GoogleAPIKey == "" || NadekoBot.GoogleAPIKey == null) { if (string.IsNullOrWhiteSpace(NadekoBot.GoogleAPIKey)) {
Console.WriteLine("ERROR: No google api key found. Playing `Never gonna give you up`."); Console.WriteLine("ERROR: No google api key found. Playing `Never gonna give you up`.");
return toReturn; return toReturn;
} }
try { try {
WebRequest wr = WebRequest.Create($"https://www.googleapis.com/youtube/v3/playlistItems?part=contentDetails&maxResults={30}&playlistId={v}&key={ NadekoBot.creds.GoogleAPIKey }"); WebRequest wr = WebRequest.Create($"https://www.googleapis.com/youtube/v3/playlistItems?part=contentDetails&maxResults={30}&playlistId={v}&key={ NadekoBot.creds.GoogleAPIKey }");
var response = await wr.GetResponseAsync();
var sr = new StreamReader((await wr.GetResponseAsync()).GetResponseStream()); if (response == null) return toReturn;
var responseStream = response.GetResponseStream();
if (responseStream == null) return toReturn;
var sr = new StreamReader(responseStream);
dynamic obj = JObject.Parse(await sr.ReadToEndAsync()); dynamic obj = JObject.Parse(await sr.ReadToEndAsync());
@ -161,8 +154,7 @@ namespace NadekoBot.Classes {
toReturn.Add("http://www.youtube.com/watch?v=" + item.contentDetails.videoId); toReturn.Add("http://www.youtube.com/watch?v=" + item.contentDetails.videoId);
} }
return toReturn; return toReturn;
} } catch (Exception ex) {
catch (Exception ex) {
Console.WriteLine($"Error in GetPlaylistId: {ex.Message}"); Console.WriteLine($"Error in GetPlaylistId: {ex.Message}");
return new List<string>(); return new List<string>();
} }
@ -180,8 +172,7 @@ namespace NadekoBot.Classes {
var matches = Regex.Matches(webpage, "data-large-file-url=\"(?<id>.*?)\""); var matches = Regex.Matches(webpage, "data-large-file-url=\"(?<id>.*?)\"");
return await $"http://danbooru.donmai.us{ matches[rng.Next(0, matches.Count)].Groups["id"].Value }".ShortenUrl(); return await $"http://danbooru.donmai.us{ matches[rng.Next(0, matches.Count)].Groups["id"].Value }".ShortenUrl();
} } catch {
catch {
return null; return null;
} }
} }
@ -197,8 +188,7 @@ namespace NadekoBot.Classes {
//now extract the image from post page //now extract the image from post page
var match = Regex.Match(webpage, "\"(?<url>http://simg4.gelbooru.com//images.*?)\""); var match = Regex.Match(webpage, "\"(?<url>http://simg4.gelbooru.com//images.*?)\"");
return match.Groups["url"].Value; return match.Groups["url"].Value;
} } catch {
catch {
return null; return null;
} }
} }
@ -210,32 +200,32 @@ namespace NadekoBot.Classes {
var webpage = await GetResponseAsync(url); // first extract the post id and go to that posts page var webpage = await GetResponseAsync(url); // first extract the post id and go to that posts page
var matches = Regex.Matches(webpage, "\"file_url\":\"(?<url>.*?)\""); var matches = Regex.Matches(webpage, "\"file_url\":\"(?<url>.*?)\"");
return matches[rng.Next(0, matches.Count)].Groups["url"].Value; return matches[rng.Next(0, matches.Count)].Groups["url"].Value;
} } catch {
catch {
return null; return null;
} }
} }
public static async Task<string> ShortenUrl(string url) { public static async Task<string> ShortenUrl(string url) {
if (NadekoBot.creds.GoogleAPIKey == null || NadekoBot.creds.GoogleAPIKey == "") return url; if (string.IsNullOrWhiteSpace(NadekoBot.creds.GoogleAPIKey)) return url;
try { try {
var httpWebRequest = (HttpWebRequest)WebRequest.Create("https://www.googleapis.com/urlshortener/v1/url?key=" + NadekoBot.creds.GoogleAPIKey); var httpWebRequest = (HttpWebRequest)WebRequest.Create("https://www.googleapis.com/urlshortener/v1/url?key=" + NadekoBot.creds.GoogleAPIKey);
httpWebRequest.ContentType = "application/json"; httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST"; httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(await httpWebRequest.GetRequestStreamAsync())) { using (var streamWriter = new StreamWriter(await httpWebRequest.GetRequestStreamAsync())) {
string json = "{\"longUrl\":\"" + url + "\"}"; var json = "{\"longUrl\":\"" + url + "\"}";
streamWriter.Write(json); streamWriter.Write(json);
} }
var httpResponse = (await httpWebRequest.GetResponseAsync()) as HttpWebResponse; var httpResponse = (await httpWebRequest.GetResponseAsync()) as HttpWebResponse;
using (var streamReader = new StreamReader(httpResponse.GetResponseStream())) { if (httpResponse == null) return "HTTP_RESPONSE_ERROR";
string responseText = await streamReader.ReadToEndAsync(); var responseStream = httpResponse.GetResponseStream();
string MATCH_PATTERN = @"""id"": ?""(?<id>.+)"""; if (responseStream == null) return "RESPONSE_STREAM ERROR";
return Regex.Match(responseText, MATCH_PATTERN).Groups["id"].Value; using (var streamReader = new StreamReader(responseStream)) {
var responseText = await streamReader.ReadToEndAsync();
return Regex.Match(responseText, @"""id"": ?""(?<id>.+)""").Groups["id"].Value;
} }
} } catch (Exception ex) { Console.WriteLine(ex.ToString()); return url; }
catch (Exception ex) { Console.WriteLine(ex.ToString()); return url; }
} }
} }
} }

View File

@ -52,7 +52,7 @@ namespace NadekoBot.Classes.Trivia {
await _channel.SendMessage($":question: **{CurrentQuestion.Question}**"); await _channel.SendMessage($":question: **{CurrentQuestion.Question}**");
//receive messages //receive messages
NadekoBot.client.MessageReceived += PotentialGuess; NadekoBot.Client.MessageReceived += PotentialGuess;
//allow people to guess //allow people to guess
GameActive = true; GameActive = true;
@ -71,7 +71,7 @@ namespace NadekoBot.Classes.Trivia {
GameActive = false; GameActive = false;
if (!triviaCancelSource.IsCancellationRequested) if (!triviaCancelSource.IsCancellationRequested)
await _channel.Send($":clock2: :question: **Time's up!** The correct answer was **{CurrentQuestion.Answer}**"); await _channel.Send($":clock2: :question: **Time's up!** The correct answer was **{CurrentQuestion.Answer}**");
NadekoBot.client.MessageReceived -= PotentialGuess; NadekoBot.Client.MessageReceived -= PotentialGuess;
// load next question if game is still running // load next question if game is still running
await Task.Delay(2000); await Task.Delay(2000);
} }

View File

@ -1,4 +1,5 @@
namespace NadekoBot // ReSharper disable InconsistentNaming
namespace NadekoBot.Classes
{ {
public class Credentials public class Credentials
{ {
@ -31,7 +32,8 @@
"\n`Synopsis:` " + description.Substring(0, description.Length > 500 ? 500 : description.Length) + "..." + "\n`Synopsis:` " + description.Substring(0, description.Length > 500 ? 500 : description.Length) + "..." +
"\n`img:` " + image_url_lge; "\n`img:` " + image_url_lge;
} }
class MangaResult
public class MangaResult
{ {
public int id; public int id;
public string publishing_status; public string publishing_status;

View File

@ -22,7 +22,7 @@ namespace NadekoBot
/// <param name="cb">CommandBuilder which will be modified</param> /// <param name="cb">CommandBuilder which will be modified</param>
protected DiscordCommand() protected DiscordCommand()
{ {
client = NadekoBot.client; client = NadekoBot.Client;
} }
/// <summary> /// <summary>
/// Function containing the behaviour of the command. /// Function containing the behaviour of the command.

View File

@ -42,7 +42,7 @@ namespace NadekoBot {
await Task.Run(async () => { await Task.Run(async () => {
var comToFind = e.GetArg("command"); var comToFind = e.GetArg("command");
var com = NadekoBot.client.GetService<CommandService>().AllCommands var com = NadekoBot.Client.GetService<CommandService>().AllCommands
.Where(c => c.Text.ToLower().Equals(comToFind)) .Where(c => c.Text.ToLower().Equals(comToFind))
.FirstOrDefault(); .FirstOrDefault();
if (com != null) if (com != null)

View File

@ -78,7 +78,7 @@ namespace NadekoBot.Commands {
await e.Channel.SendFile("champ.png", champ.ImageStream); await e.Channel.SendFile("champ.png", champ.ImageStream);
return; return;
} }
var allData = JArray.Parse(await Classes.SearchHelper.GetResponseAsync($"http://api.champion.gg/champion/{name}?api_key={NadekoBot.creds.LOLAPIKey}")); var allData = JArray.Parse(await Classes.SearchHelper.GetResponseAsync($"http://api.champion.gg/champion/{name}?api_key={NadekoBot.Creds.LOLAPIKey}"));
JToken data = null; JToken data = null;
if (role != null) { if (role != null) {
for (int i = 0; i < allData.Count; i++) { for (int i = 0; i < allData.Count; i++) {
@ -114,7 +114,7 @@ namespace NadekoBot.Commands {
if (roles[i] == role) if (roles[i] == role)
roles[i] = ">" + roles[i] + "<"; roles[i] = ">" + roles[i] + "<";
} }
var general = JArray.Parse(await Classes.SearchHelper.GetResponseAsync($"http://api.champion.gg/stats/champs/{name}?api_key={NadekoBot.creds.LOLAPIKey}")) var general = JArray.Parse(await Classes.SearchHelper.GetResponseAsync($"http://api.champion.gg/stats/champs/{name}?api_key={NadekoBot.Creds.LOLAPIKey}"))
.Where(jt => jt["role"].ToString() == role) .Where(jt => jt["role"].ToString() == role)
.FirstOrDefault()?["general"]; .FirstOrDefault()?["general"];
if (general == null) { if (general == null) {
@ -253,7 +253,7 @@ Assists: {general["assists"]} Ban: {general["banRate"]}%
var data = JObject.Parse( var data = JObject.Parse(
await Classes await Classes
.SearchHelper .SearchHelper
.GetResponseAsync($"http://api.champion.gg/stats/champs/mostBanned?api_key={NadekoBot.creds.LOLAPIKey}&page=1&limit={showCount}"))["data"] as JArray; .GetResponseAsync($"http://api.champion.gg/stats/champs/mostBanned?api_key={NadekoBot.Creds.LOLAPIKey}&page=1&limit={showCount}"))["data"] as JArray;
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
sb.AppendLine($"**Showing {showCount} top banned champions.**"); sb.AppendLine($"**Showing {showCount} top banned champions.**");

View File

@ -9,10 +9,10 @@ namespace NadekoBot.Commands {
class LogCommand : DiscordCommand { class LogCommand : DiscordCommand {
public LogCommand() : base() { public LogCommand() : base() {
NadekoBot.client.MessageReceived += MsgRecivd; NadekoBot.Client.MessageReceived += MsgRecivd;
NadekoBot.client.MessageDeleted += MsgDltd; NadekoBot.Client.MessageDeleted += MsgDltd;
NadekoBot.client.MessageUpdated += MsgUpdtd; NadekoBot.Client.MessageUpdated += MsgUpdtd;
NadekoBot.client.UserUpdated += UsrUpdtd; NadekoBot.Client.UserUpdated += UsrUpdtd;
} }
ConcurrentDictionary<Server, Channel> logs = new ConcurrentDictionary<Server, Channel>(); ConcurrentDictionary<Server, Channel> logs = new ConcurrentDictionary<Server, Channel>();
@ -36,7 +36,7 @@ namespace NadekoBot.Commands {
private async void MsgRecivd(object sender, MessageEventArgs e) { private async void MsgRecivd(object sender, MessageEventArgs e) {
try { try {
if (e.Server == null || e.Channel.IsPrivate || e.User.Id == NadekoBot.client.CurrentUser.Id) if (e.Server == null || e.Channel.IsPrivate || e.User.Id == NadekoBot.Client.CurrentUser.Id)
return; return;
Channel ch; Channel ch;
if (!logs.TryGetValue(e.Server, out ch) || e.Channel == ch) if (!logs.TryGetValue(e.Server, out ch) || e.Channel == ch)
@ -47,7 +47,7 @@ namespace NadekoBot.Commands {
} }
private async void MsgDltd(object sender, MessageEventArgs e) { private async void MsgDltd(object sender, MessageEventArgs e) {
try { try {
if (e.Server == null || e.Channel.IsPrivate || e.User.Id == NadekoBot.client.CurrentUser.Id) if (e.Server == null || e.Channel.IsPrivate || e.User.Id == NadekoBot.Client.CurrentUser.Id)
return; return;
Channel ch; Channel ch;
if (!logs.TryGetValue(e.Server, out ch) || e.Channel == ch) if (!logs.TryGetValue(e.Server, out ch) || e.Channel == ch)
@ -58,7 +58,7 @@ namespace NadekoBot.Commands {
} }
private async void MsgUpdtd(object sender, MessageUpdatedEventArgs e) { private async void MsgUpdtd(object sender, MessageUpdatedEventArgs e) {
try { try {
if (e.Server == null || e.Channel.IsPrivate || e.User.Id == NadekoBot.client.CurrentUser.Id) if (e.Server == null || e.Channel.IsPrivate || e.User.Id == NadekoBot.Client.CurrentUser.Id)
return; return;
Channel ch; Channel ch;
if (!logs.TryGetValue(e.Server, out ch) || e.Channel == ch) if (!logs.TryGetValue(e.Server, out ch) || e.Channel == ch)

View File

@ -13,8 +13,8 @@ namespace NadekoBot.Commands {
private static Timer timer = new Timer(12000); private static Timer timer = new Timer(12000);
private Dictionary<string, Func<string>> playingPlaceholders => new Dictionary<string, Func<string>> { private Dictionary<string, Func<string>> playingPlaceholders => new Dictionary<string, Func<string>> {
{"%servers%", ()=> NadekoBot.client.Servers.Count().ToString() }, {"%servers%", ()=> NadekoBot.Client.Servers.Count().ToString() },
{"%users%", () => NadekoBot.client.Servers.SelectMany(s=>s.Users).Count().ToString() }, {"%users%", () => NadekoBot.Client.Servers.SelectMany(s=>s.Users).Count().ToString() },
{"%playing%", () => { {"%playing%", () => {
var cnt = Modules.Music.musicPlayers.Where(kvp => kvp.Value.CurrentSong != null).Count(); var cnt = Modules.Music.musicPlayers.Where(kvp => kvp.Value.CurrentSong != null).Count();
if(cnt == 1) { if(cnt == 1) {
@ -51,7 +51,7 @@ namespace NadekoBot.Commands {
} }
if (string.IsNullOrWhiteSpace(status)) if (string.IsNullOrWhiteSpace(status))
return; return;
Task.Run(() => { try { NadekoBot.client.SetGame(status); } catch { } }); Task.Run(() => { try { NadekoBot.Client.SetGame(status); } catch { } });
} }
catch { } catch { }
}; };

View File

@ -66,7 +66,7 @@ namespace NadekoBot.Modules {
private async Task StartPoll() { private async Task StartPoll() {
started = DateTime.Now; started = DateTime.Now;
NadekoBot.client.MessageReceived += Vote; NadekoBot.Client.MessageReceived += Vote;
var msgToSend = var msgToSend =
$"📃**{e.User.Name}** from **{e.Server.Name}** server has created a poll which requires your attention:\n\n" + $"📃**{e.User.Name}** from **{e.Server.Name}** server has created a poll which requires your attention:\n\n" +
$"**{question}**\n"; $"**{question}**\n";
@ -79,7 +79,7 @@ namespace NadekoBot.Modules {
} }
public async Task StopPoll(Channel ch) { public async Task StopPoll(Channel ch) {
NadekoBot.client.MessageReceived -= Vote; NadekoBot.Client.MessageReceived -= Vote;
Poll throwaway; Poll throwaway;
PollCommand.ActivePolls.TryRemove(e.Server, out throwaway); PollCommand.ActivePolls.TryRemove(e.Server, out throwaway);
try { try {

View File

@ -73,7 +73,7 @@ namespace NadekoBot.Commands {
.Description("Deletes a request. Only owner is able to do this.") .Description("Deletes a request. Only owner is able to do this.")
.Parameter("reqNumber", ParameterType.Required) .Parameter("reqNumber", ParameterType.Required)
.Do(async e => { .Do(async e => {
if (e.User.Id == NadekoBot.OwnerID) { if (e.User.Id == NadekoBot.OwnerId) {
try { try {
if (DeleteRequest(int.Parse(e.Args[0]))) { if (DeleteRequest(int.Parse(e.Args[0]))) {
await e.Channel.SendMessage(e.User.Mention + " Request deleted."); await e.Channel.SendMessage(e.User.Mention + " Request deleted.");
@ -90,7 +90,7 @@ namespace NadekoBot.Commands {
.Description("Resolves a request. Only owner is able to do this.") .Description("Resolves a request. Only owner is able to do this.")
.Parameter("reqNumber", ParameterType.Required) .Parameter("reqNumber", ParameterType.Required)
.Do(async e => { .Do(async e => {
if (e.User.Id == NadekoBot.OwnerID) { if (e.User.Id == NadekoBot.OwnerId) {
try { try {
var sc = ResolveRequest(int.Parse(e.Args[0])); var sc = ResolveRequest(int.Parse(e.Args[0]));
if (sc != null) { if (sc != null) {

View File

@ -30,8 +30,8 @@ namespace NadekoBot.Commands {
public ServerGreetCommand() : base() { public ServerGreetCommand() : base() {
AnnouncementsDictionary = new ConcurrentDictionary<ulong, AnnounceControls>(); AnnouncementsDictionary = new ConcurrentDictionary<ulong, AnnounceControls>();
NadekoBot.client.UserJoined += UserJoined; NadekoBot.Client.UserJoined += UserJoined;
NadekoBot.client.UserLeft += UserLeft; NadekoBot.Client.UserLeft += UserLeft;
List<Classes._DataModels.Announcement> data = Classes.DBHandler.Instance.GetAllRows<Classes._DataModels.Announcement>(); List<Classes._DataModels.Announcement> data = Classes.DBHandler.Instance.GetAllRows<Classes._DataModels.Announcement>();
@ -46,7 +46,7 @@ namespace NadekoBot.Commands {
!AnnouncementsDictionary[e.Server.Id].Bye) return; !AnnouncementsDictionary[e.Server.Id].Bye) return;
var controls = AnnouncementsDictionary[e.Server.Id]; var controls = AnnouncementsDictionary[e.Server.Id];
var channel = NadekoBot.client.GetChannel(controls.ByeChannel); var channel = NadekoBot.Client.GetChannel(controls.ByeChannel);
var msg = controls.ByeText.Replace("%user%", "**" + e.User.Name + "**").Trim(); var msg = controls.ByeText.Replace("%user%", "**" + e.User.Name + "**").Trim();
if (string.IsNullOrEmpty(msg)) if (string.IsNullOrEmpty(msg))
return; return;
@ -73,7 +73,7 @@ namespace NadekoBot.Commands {
!AnnouncementsDictionary[e.Server.Id].Greet) return; !AnnouncementsDictionary[e.Server.Id].Greet) return;
var controls = AnnouncementsDictionary[e.Server.Id]; var controls = AnnouncementsDictionary[e.Server.Id];
var channel = NadekoBot.client.GetChannel(controls.GreetChannel); var channel = NadekoBot.Client.GetChannel(controls.GreetChannel);
var msg = controls.GreetText.Replace("%user%", e.User.Mention).Trim(); var msg = controls.GreetText.Replace("%user%", e.User.Mention).Trim();
if (string.IsNullOrEmpty(msg)) if (string.IsNullOrEmpty(msg))

View File

@ -39,7 +39,7 @@ namespace NadekoBot.Commands {
internal async Task<bool> Stop() { internal async Task<bool> Stop() {
if (!IsActive) return false; if (!IsActive) return false;
NadekoBot.client.MessageReceived -= AnswerReceived; NadekoBot.Client.MessageReceived -= AnswerReceived;
finishedUserIds.Clear(); finishedUserIds.Clear();
IsActive = false; IsActive = false;
sw.Stop(); sw.Stop();
@ -78,7 +78,7 @@ namespace NadekoBot.Commands {
} }
private void HandleAnswers() { private void HandleAnswers() {
NadekoBot.client.MessageReceived += AnswerReceived; NadekoBot.Client.MessageReceived += AnswerReceived;
} }
private async void AnswerReceived(object sender, MessageEventArgs e) { private async void AnswerReceived(object sender, MessageEventArgs e) {

View File

@ -436,7 +436,7 @@ namespace NadekoBot.Modules {
.Description("Clears some of Nadeko's (or some other user's if supplied) messages from the current channel.\n**Usage**: .clr @X") .Description("Clears some of Nadeko's (or some other user's if supplied) messages from the current channel.\n**Usage**: .clr @X")
.Parameter("user", ParameterType.Unparsed) .Parameter("user", ParameterType.Unparsed)
.Do(async e => { .Do(async e => {
var usrId = NadekoBot.client.CurrentUser.Id; var usrId = NadekoBot.Client.CurrentUser.Id;
if (!string.IsNullOrWhiteSpace(e.GetArg("user")) && e.User.ServerPermissions.ManageMessages) { if (!string.IsNullOrWhiteSpace(e.GetArg("user")) && e.User.ServerPermissions.ManageMessages) {
var usr = e.Server.FindUsers(e.GetArg("user")).FirstOrDefault(); var usr = e.Server.FindUsers(e.GetArg("user")).FirstOrDefault();
if (usr != null) if (usr != null)
@ -608,7 +608,7 @@ namespace NadekoBot.Modules {
.Description("Clears the message queue. **OWNER ONLY**") .Description("Clears the message queue. **OWNER ONLY**")
.AddCheck(Classes.Permissions.SimpleCheckers.OwnerOnly()) .AddCheck(Classes.Permissions.SimpleCheckers.OwnerOnly())
.Do(e => { .Do(e => {
NadekoBot.client.MessageQueue.Clear(); NadekoBot.Client.MessageQueue.Clear();
}); });
cgb.CreateCommand(".donators") cgb.CreateCommand(".donators")

View File

@ -352,7 +352,7 @@ namespace NadekoBot.Modules {
.Do(async e => { .Do(async e => {
string str = "Bye"; string str = "Bye";
foreach (var u in e.Message.MentionedUsers) { foreach (var u in e.Message.MentionedUsers) {
if (u.Id != NadekoBot.client.CurrentUser.Id) if (u.Id != NadekoBot.Client.CurrentUser.Id)
str += " " + u.Mention; str += " " + u.Mention;
} }
await e.Channel.SendMessage(str); await e.Channel.SendMessage(str);

View File

@ -22,7 +22,7 @@ namespace NadekoBot.Modules {
.Alias("-modules") .Alias("-modules")
.Description("List all bot modules.") .Description("List all bot 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))); await e.Channel.SendMessage("`List of modules:` \n• " + string.Join("\n• ", NadekoBot.Client.GetService<ModuleService>().Modules.Select(m => m.Name)));
}); });
cgb.CreateCommand(".commands") cgb.CreateCommand(".commands")
@ -30,7 +30,7 @@ namespace NadekoBot.Modules {
.Description("List all of the bot's commands from a certain module.") .Description("List all of the bot's commands from a certain module.")
.Parameter("module", ParameterType.Unparsed) .Parameter("module", ParameterType.Unparsed)
.Do(async e => { .Do(async e => {
var commands = NadekoBot.client.GetService<CommandService>().AllCommands var commands = NadekoBot.Client.GetService<CommandService>().AllCommands
.Where(c => c.Category.ToLower() == e.GetArg("module").Trim().ToLower()); .Where(c => c.Category.ToLower() == e.GetArg("module").Trim().ToLower());
if (commands == null || commands.Count() == 0) { if (commands == null || commands.Count() == 0) {
await e.Channel.SendMessage("That module does not exist."); await e.Channel.SendMessage("That module does not exist.");

View File

@ -28,7 +28,7 @@ namespace NadekoBot.Modules {
setgameTimer.Elapsed += (s, e) => { setgameTimer.Elapsed += (s, e) => {
try { try {
int num = musicPlayers.Where(kvp => kvp.Value.CurrentSong != null).Count(); int num = musicPlayers.Where(kvp => kvp.Value.CurrentSong != null).Count();
NadekoBot.client.SetGame($"{num} songs".SnPl(num) + $", {musicPlayers.Sum(kvp => kvp.Value.Playlist.Count())} queued"); NadekoBot.Client.SetGame($"{num} songs".SnPl(num) + $", {musicPlayers.Sum(kvp => kvp.Value.Playlist.Count())} queued");
} }
catch { } catch { }
}; };
@ -36,7 +36,7 @@ namespace NadekoBot.Modules {
} }
public override void Install(ModuleManager manager) { public override void Install(ModuleManager manager) {
var client = NadekoBot.client; var client = NadekoBot.Client;
manager.CreateCommands("!m", cgb => { manager.CreateCommands("!m", cgb => {

View File

@ -15,7 +15,7 @@ namespace NadekoBot.Modules {
} }
public override void Install(ModuleManager manager) { public override void Install(ModuleManager manager) {
var client = NadekoBot.client; var client = NadekoBot.Client;
manager.CreateCommands("", cgb => { manager.CreateCommands("", cgb => {
cgb.AddCheck(Classes.Permissions.PermissionChecker.Instance); cgb.AddCheck(Classes.Permissions.PermissionChecker.Instance);
@ -349,7 +349,7 @@ namespace NadekoBot.Modules {
try { try {
bool state = PermissionHelper.ValidateBool(e.GetArg("bool")); bool state = PermissionHelper.ValidateBool(e.GetArg("bool"));
foreach (var module in NadekoBot.client.GetService<ModuleService>().Modules) { foreach (var module in NadekoBot.Client.GetService<ModuleService>().Modules) {
PermsHandler.SetServerModulePermission(e.Server, module.Name, state); PermsHandler.SetServerModulePermission(e.Server, module.Name, state);
} }
await e.Channel.SendMessage($"All modules have been **{(state ? "enabled" : "disabled")}** on this server."); await e.Channel.SendMessage($"All modules have been **{(state ? "enabled" : "disabled")}** on this server.");
@ -371,7 +371,7 @@ namespace NadekoBot.Modules {
bool state = PermissionHelper.ValidateBool(e.GetArg("bool")); bool state = PermissionHelper.ValidateBool(e.GetArg("bool"));
string module = PermissionHelper.ValidateModule(e.GetArg("module")); string module = PermissionHelper.ValidateModule(e.GetArg("module"));
foreach (var command in NadekoBot.client.GetService<CommandService>().AllCommands.Where(c => c.Category == module)) { foreach (var command in NadekoBot.Client.GetService<CommandService>().AllCommands.Where(c => c.Category == module)) {
PermsHandler.SetServerCommandPermission(e.Server, command.Text, state); PermsHandler.SetServerCommandPermission(e.Server, command.Text, state);
} }
await e.Channel.SendMessage($"All commands from the **{module}** module have been **{(state ? "enabled" : "disabled")}** on this server."); await e.Channel.SendMessage($"All commands from the **{module}** module have been **{(state ? "enabled" : "disabled")}** on this server.");
@ -392,7 +392,7 @@ namespace NadekoBot.Modules {
try { try {
bool state = PermissionHelper.ValidateBool(e.GetArg("bool")); bool state = PermissionHelper.ValidateBool(e.GetArg("bool"));
Discord.Channel channel = PermissionHelper.ValidateChannel(e.Server, e.GetArg("channel")); Discord.Channel channel = PermissionHelper.ValidateChannel(e.Server, e.GetArg("channel"));
foreach (var module in NadekoBot.client.GetService<ModuleService>().Modules) { foreach (var module in NadekoBot.Client.GetService<ModuleService>().Modules) {
PermsHandler.SetChannelModulePermission(channel, module.Name, state); PermsHandler.SetChannelModulePermission(channel, module.Name, state);
} }
@ -416,7 +416,7 @@ namespace NadekoBot.Modules {
bool state = PermissionHelper.ValidateBool(e.GetArg("bool")); bool state = PermissionHelper.ValidateBool(e.GetArg("bool"));
string module = PermissionHelper.ValidateModule(e.GetArg("module")); string module = PermissionHelper.ValidateModule(e.GetArg("module"));
Discord.Channel channel = PermissionHelper.ValidateChannel(e.Server, e.GetArg("channel")); Discord.Channel channel = PermissionHelper.ValidateChannel(e.Server, e.GetArg("channel"));
foreach (var command in NadekoBot.client.GetService<CommandService>().AllCommands.Where(c => c.Category == module)) { foreach (var command in NadekoBot.Client.GetService<CommandService>().AllCommands.Where(c => c.Category == module)) {
PermsHandler.SetChannelCommandPermission(channel, command.Text, state); PermsHandler.SetChannelCommandPermission(channel, command.Text, state);
} }
await e.Channel.SendMessage($"All commands from the **{module}** module have been **{(state ? "enabled" : "disabled")}** for **{channel.Name}** channel."); await e.Channel.SendMessage($"All commands from the **{module}** module have been **{(state ? "enabled" : "disabled")}** for **{channel.Name}** channel.");
@ -437,7 +437,7 @@ namespace NadekoBot.Modules {
try { try {
bool state = PermissionHelper.ValidateBool(e.GetArg("bool")); bool state = PermissionHelper.ValidateBool(e.GetArg("bool"));
Discord.Role role = PermissionHelper.ValidateRole(e.Server, e.GetArg("role")); Discord.Role role = PermissionHelper.ValidateRole(e.Server, e.GetArg("role"));
foreach (var module in NadekoBot.client.GetService<ModuleService>().Modules) { foreach (var module in NadekoBot.Client.GetService<ModuleService>().Modules) {
PermsHandler.SetRoleModulePermission(role, module.Name, state); PermsHandler.SetRoleModulePermission(role, module.Name, state);
} }
@ -461,7 +461,7 @@ namespace NadekoBot.Modules {
bool state = PermissionHelper.ValidateBool(e.GetArg("bool")); bool state = PermissionHelper.ValidateBool(e.GetArg("bool"));
string module = PermissionHelper.ValidateModule(e.GetArg("module")); string module = PermissionHelper.ValidateModule(e.GetArg("module"));
Discord.Role role = PermissionHelper.ValidateRole(e.Server, e.GetArg("channel")); Discord.Role role = PermissionHelper.ValidateRole(e.Server, e.GetArg("channel"));
foreach (var command in NadekoBot.client.GetService<CommandService>().AllCommands.Where(c => c.Category == module)) { foreach (var command in NadekoBot.Client.GetService<CommandService>().AllCommands.Where(c => c.Category == module)) {
PermsHandler.SetRoleCommandPermission(role, command.Text, state); PermsHandler.SetRoleCommandPermission(role, command.Text, state);
} }
await e.Channel.SendMessage($"All commands from the **{module}** module have been **{(state ? "enabled" : "disabled")}** for **{role.Name}** role."); await e.Channel.SendMessage($"All commands from the **{module}** module have been **{(state ? "enabled" : "disabled")}** for **{role.Name}** role.");

View File

@ -18,7 +18,7 @@ namespace NadekoBot.Modules {
} }
public override void Install(ModuleManager manager) { public override void Install(ModuleManager manager) {
var client = NadekoBot.client; var client = NadekoBot.Client;
manager.CreateCommands("", cgb => { manager.CreateCommands("", cgb => {

View File

@ -65,7 +65,7 @@ namespace NadekoBot.Modules {
.Description("Joins a server") .Description("Joins a server")
.Parameter("code", Discord.Commands.ParameterType.Required) .Parameter("code", Discord.Commands.ParameterType.Required)
.Do(async e => { .Do(async e => {
if (e.User.Id != NadekoBot.OwnerID) return; if (e.User.Id != NadekoBot.OwnerId) return;
try { try {
await (await client.GetInvite(e.GetArg("code"))).Accept(); await (await client.GetInvite(e.GetArg("code"))).Accept();
} catch (Exception ex) { } catch (Exception ex) {
@ -77,7 +77,7 @@ namespace NadekoBot.Modules {
.Description("Bind a trello bot to a single channel. You will receive notifications from your board when something is added or edited.") .Description("Bind a trello bot to a single channel. You will receive notifications from your board when something is added or edited.")
.Parameter("board_id", Discord.Commands.ParameterType.Required) .Parameter("board_id", Discord.Commands.ParameterType.Required)
.Do(async e => { .Do(async e => {
if (e.User.Id != NadekoBot.OwnerID) return; if (e.User.Id != NadekoBot.OwnerId) return;
if (bound != null) return; if (bound != null) return;
try { try {
bound = e.Channel; bound = e.Channel;
@ -93,7 +93,7 @@ namespace NadekoBot.Modules {
cgb.CreateCommand("unbind") cgb.CreateCommand("unbind")
.Description("Unbinds a bot from the channel and board.") .Description("Unbinds a bot from the channel and board.")
.Do(async e => { .Do(async e => {
if (e.User.Id != NadekoBot.OwnerID) return; if (e.User.Id != NadekoBot.OwnerId) return;
if (bound == null || bound != e.Channel) return; if (bound == null || bound != e.Channel) return;
t.Stop(); t.Stop();
bound = null; bound = null;
@ -106,7 +106,7 @@ namespace NadekoBot.Modules {
.Alias("list") .Alias("list")
.Description("Lists all lists yo ;)") .Description("Lists all lists yo ;)")
.Do(async e => { .Do(async e => {
if (e.User.Id != NadekoBot.OwnerID) return; if (e.User.Id != NadekoBot.OwnerId) 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 e.Channel.SendMessage("Lists for a board '" + board.Name + "'\n" + string.Join("\n", board.Lists.Select(l => "**• " + l.ToString() + "**")));
}); });
@ -115,7 +115,7 @@ namespace NadekoBot.Modules {
.Description("Lists all cards from the supplied list. You can supply either a name or an index.") .Description("Lists all cards from the supplied list. You can supply either a name or an index.")
.Parameter("list_name", Discord.Commands.ParameterType.Unparsed) .Parameter("list_name", Discord.Commands.ParameterType.Unparsed)
.Do(async e => { .Do(async e => {
if (e.User.Id != NadekoBot.OwnerID) return; if (e.User.Id != NadekoBot.OwnerId) return;
if (bound == null || board == null || bound != e.Channel || e.GetArg("list_name") == null) return; if (bound == null || board == null || bound != e.Channel || e.GetArg("list_name") == null) return;
int num; int num;

View File

@ -9,53 +9,49 @@ using Discord.Audio;
using NadekoBot.Extensions; using NadekoBot.Extensions;
using System.Timers; using System.Timers;
using System.Linq; using System.Linq;
using NadekoBot.Classes;
namespace NadekoBot { namespace NadekoBot {
class NadekoBot { public class NadekoBot {
public static DiscordClient client; public static DiscordClient Client;
public static string botMention; public static string botMention;
public static string GoogleAPIKey = null; public static string GoogleAPIKey = null;
public static ulong OwnerID;
public static Channel OwnerPrivateChannel = null; public static Channel OwnerPrivateChannel = null;
public static string password;
public static string TrelloAppKey; public static string TrelloAppKey;
public static bool ForwardMessages = false; public static bool ForwardMessages = false;
public static Credentials creds; public static Credentials Creds { get; set; }
static void Main() { static void Main() {
//load credentials from credentials.json //load credentials from credentials.json
bool loadTrello = false; bool loadTrello = false;
try { try {
creds = JsonConvert.DeserializeObject<Credentials>(File.ReadAllText("credentials.json")); Creds = JsonConvert.DeserializeObject<Credentials>(File.ReadAllText("credentials.json"));
botMention = creds.BotMention; botMention = Creds.BotMention;
if (string.IsNullOrWhiteSpace(creds.GoogleAPIKey)) { if (string.IsNullOrWhiteSpace(Creds.GoogleAPIKey)) {
Console.WriteLine("No google api key found. You will not be able to use music and links won't be shortened."); Console.WriteLine("No google api key found. You will not be able to use music and links won't be shortened.");
} }
else { else {
Console.WriteLine("Google API key provided."); Console.WriteLine("Google API key provided.");
GoogleAPIKey = creds.GoogleAPIKey; GoogleAPIKey = Creds.GoogleAPIKey;
} }
if (string.IsNullOrWhiteSpace(creds.TrelloAppKey)) { if (string.IsNullOrWhiteSpace(Creds.TrelloAppKey)) {
Console.WriteLine("No trello appkey found. You will not be able to use trello commands."); Console.WriteLine("No trello appkey found. You will not be able to use trello commands.");
} }
else { else {
Console.WriteLine("Trello app key provided."); Console.WriteLine("Trello app key provided.");
TrelloAppKey = creds.TrelloAppKey; TrelloAppKey = Creds.TrelloAppKey;
loadTrello = true; loadTrello = true;
} }
if (creds.ForwardMessages != true) if (Creds.ForwardMessages != true)
Console.WriteLine("Not forwarding messages."); Console.WriteLine("Not forwarding messages.");
else { else {
ForwardMessages = true; ForwardMessages = true;
Console.WriteLine("Forwarding messages."); Console.WriteLine("Forwarding messages.");
} }
if (string.IsNullOrWhiteSpace(creds.SoundCloudClientID)) if (string.IsNullOrWhiteSpace(Creds.SoundCloudClientID))
Console.WriteLine("No soundcloud Client ID found. Soundcloud streaming is disabled."); Console.WriteLine("No soundcloud Client ID found. Soundcloud streaming is disabled.");
else else
Console.WriteLine("SoundCloud streaming enabled."); Console.WriteLine("SoundCloud streaming enabled.");
OwnerID = creds.OwnerID;
password = creds.Password;
} }
catch (Exception ex) { catch (Exception ex) {
Console.WriteLine($"Failed to load stuff from credentials.json, RTFM\n{ex.Message}"); Console.WriteLine($"Failed to load stuff from credentials.json, RTFM\n{ex.Message}");
@ -64,7 +60,7 @@ namespace NadekoBot {
} }
//create new discord client //create new discord client
client = new DiscordClient(new DiscordConfigBuilder() { Client = new DiscordClient(new DiscordConfigBuilder() {
MessageCacheSize = 20, MessageCacheSize = 20,
LogLevel = LogSeverity.Warning, LogLevel = LogSeverity.Warning,
LogHandler = (s, e) => { LogHandler = (s, e) => {
@ -93,16 +89,16 @@ namespace NadekoBot {
}); });
//reply to personal messages and forward if enabled. //reply to personal messages and forward if enabled.
client.MessageReceived += Client_MessageReceived; Client.MessageReceived += Client_MessageReceived;
//add command service //add command service
var commands = client.AddService<CommandService>(commandService); var commands = Client.AddService<CommandService>(commandService);
//create module service //create module service
var modules = client.AddService<ModuleService>(new ModuleService()); var modules = Client.AddService<ModuleService>(new ModuleService());
//add audio service //add audio service
var audio = client.AddService<AudioService>(new AudioService(new AudioServiceConfigBuilder() { var audio = Client.AddService<AudioService>(new AudioService(new AudioServiceConfigBuilder() {
Channels = 2, Channels = 2,
EnableEncryption = false, EnableEncryption = false,
EnableMultiserver = true, EnableMultiserver = true,
@ -123,9 +119,9 @@ namespace NadekoBot {
modules.Add(new NSFW(), "NSFW", ModuleFilter.None); modules.Add(new NSFW(), "NSFW", ModuleFilter.None);
//run the bot //run the bot
client.ExecuteAndWait(async () => { Client.ExecuteAndWait(async () => {
try { try {
await client.Connect(creds.Username, creds.Password); await Client.Connect(Creds.Username, Creds.Password);
} }
catch (Exception ex) { catch (Exception ex) {
Console.WriteLine($"Probably wrong EMAIL or PASSWORD.\n{ex.Message}"); Console.WriteLine($"Probably wrong EMAIL or PASSWORD.\n{ex.Message}");
@ -139,7 +135,7 @@ namespace NadekoBot {
Console.WriteLine("-----------------"); Console.WriteLine("-----------------");
try { try {
OwnerPrivateChannel = await client.CreatePrivateChannel(OwnerID); OwnerPrivateChannel = await Client.CreatePrivateChannel(OwnerId);
} }
catch { catch {
Console.WriteLine("Failed creating private channel with the owner"); Console.WriteLine("Failed creating private channel with the owner");
@ -147,7 +143,7 @@ namespace NadekoBot {
Classes.Permissions.PermissionsHandler.Initialize(); Classes.Permissions.PermissionsHandler.Initialize();
client.ClientAPI.SendingRequest += (s, e) => { Client.ClientAPI.SendingRequest += (s, e) => {
try { try {
var request = e.Request as Discord.API.Client.Rest.SendMessageRequest; var request = e.Request as Discord.API.Client.Rest.SendMessageRequest;
@ -182,7 +178,7 @@ namespace NadekoBot {
static bool repliedRecently = false; static bool repliedRecently = false;
private static async void Client_MessageReceived(object sender, MessageEventArgs e) { private static async void Client_MessageReceived(object sender, MessageEventArgs e) {
try { try {
if (e.Server != null || e.User.Id == client.CurrentUser.Id) return; if (e.Server != null || e.User.Id == Client.CurrentUser.Id) return;
if (PollCommand.ActivePolls.SelectMany(kvp => kvp.Key.Users.Select(u => u.Id)).Contains(e.User.Id)) return; if (PollCommand.ActivePolls.SelectMany(kvp => kvp.Key.Users.Select(u => u.Id)).Contains(e.User.Id)) return;
// just ban this trash AutoModerator // just ban this trash AutoModerator
// and cancer christmass spirit // and cancer christmass spirit
@ -192,9 +188,9 @@ namespace NadekoBot {
e.User.Id == 143515953525817344) e.User.Id == 143515953525817344)
return; // FU return; // FU
if (!NadekoBot.creds.DontJoinServers) { if (!NadekoBot.Creds.DontJoinServers) {
try { try {
await (await client.GetInvite(e.Message.Text)).Accept(); await (await Client.GetInvite(e.Message.Text)).Accept();
await e.Channel.SendMessage("I got in!"); await e.Channel.SendMessage("I got in!");
return; return;
} }