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

View File

@ -16,10 +16,10 @@ namespace NadekoBot.Classes.Music {
public async Task<SoundCloudVideo> GetVideoAsync(string url) {
if (string.IsNullOrWhiteSpace(url))
throw new ArgumentNullException(nameof(url));
if (string.IsNullOrWhiteSpace(NadekoBot.creds.SoundCloudClientID))
throw new ArgumentNullException(nameof(NadekoBot.creds.SoundCloudClientID));
if (string.IsNullOrWhiteSpace(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);
if (responseObj?.Kind != "track")
@ -39,7 +39,7 @@ namespace NadekoBot.Classes.Music {
public string Title = "";
public string FullName => User.Name + " - " + Title;
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 {
[Newtonsoft.Json.JsonProperty("username")]

View File

@ -31,8 +31,8 @@ namespace NadekoBot {
static NadekoStats() { }
private NadekoStats() {
_service = NadekoBot.client.GetService<CommandService>();
_client = NadekoBot.client;
_service = NadekoBot.Client.GetService<CommandService>();
_client = NadekoBot.Client;
_statsSW = new Stopwatch();
_statsSW.Start();
@ -130,10 +130,10 @@ namespace NadekoBot {
while (true) {
await Task.Delay(new TimeSpan(0, 30, 0));
try {
var onlineUsers = await Task.Run(() => NadekoBot.client.Servers.Sum(x => x.Users.Count()));
var realOnlineUsers = await Task.Run(() => NadekoBot.client.Servers
var onlineUsers = await Task.Run(() => NadekoBot.Client.Servers.Sum(x => x.Users.Count()));
var realOnlineUsers = await Task.Run(() => NadekoBot.Client.Servers
.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 {
OnlineUsers = onlineUsers,

View File

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

View File

@ -40,7 +40,7 @@ namespace NadekoBot.Classes {
if (string.IsNullOrWhiteSpace(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()))
return m.Name;
}
@ -51,7 +51,7 @@ namespace NadekoBot.Classes {
if (string.IsNullOrWhiteSpace(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()))
return com.Text;
}

View File

@ -9,6 +9,6 @@ using System.Threading.Tasks;
namespace NadekoBot.Classes.Permissions {
static class SimpleCheckers {
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;
namespace NadekoBot.Classes {
static class SearchHelper {
public static class SearchHelper {
public static async Task<Stream> GetResponseStream(string v) {
var wr = (HttpWebRequest)WebRequest.Create(v);
try {
return (await (wr).GetResponseAsync()).GetResponseStream();
}
catch (Exception ex) {
Console.WriteLine("error in getresponse stream " + ex);
return null;
}
return (await (wr).GetResponseAsync()).GetResponseStream();
}
public static async Task<string> GetResponseAsync(string v, WebHeaderCollection headers = null) {
var wr = (HttpWebRequest)WebRequest.Create(v);
if (headers != null)
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();
}
}
@ -46,8 +42,7 @@ namespace NadekoBot.Classes {
rq = new RestSharp.RestRequest("anime/" + smallObj["id"]);
rq.AddParameter("access_token", token);
return await Task.Run(() => JsonConvert.DeserializeObject<AnimeResult>(cl.Execute(rq).Content));
}
catch {
} catch {
return null;
}
}
@ -66,8 +61,7 @@ namespace NadekoBot.Classes {
rq = new RestSharp.RestRequest("manga/" + smallObj["id"]);
rq.AddParameter("access_token", token);
return await Task.Run(() => JsonConvert.DeserializeObject<MangaResult>(cl.Execute(rq).Content));
}
catch (Exception ex) {
} catch (Exception ex) {
Console.WriteLine(ex.ToString());
return null;
}
@ -83,8 +77,7 @@ namespace NadekoBot.Classes {
var exec = cl.Execute(rq);
token = JObject.Parse(exec.Content)["access_token"].ToString();
}
catch (Exception ex) {
} catch (Exception ex) {
Console.WriteLine($"Failed refreshing anilist token:\n {ex}");
}
}
@ -98,7 +91,7 @@ namespace NadekoBot.Classes {
}
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`.");
return @"https://www.youtube.com/watch?v=dQw4w9WgXcQ";
}
@ -117,15 +110,14 @@ namespace NadekoBot.Classes {
dynamic obj = JObject.Parse(await sr.ReadToEndAsync());
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}");
return string.Empty;
}
}
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`.");
return string.Empty;
}
@ -136,8 +128,7 @@ namespace NadekoBot.Classes {
dynamic obj = JObject.Parse(await sr.ReadToEndAsync());
return obj.items[0].id.playlistId.ToString();
}
catch (Exception ex) {
} catch (Exception ex) {
Console.WriteLine($"Error in GetPlaylistId: {ex.Message}");
return string.Empty;
}
@ -145,15 +136,17 @@ namespace NadekoBot.Classes {
public static async Task<List<string>> GetVideoIDs(string v) {
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`.");
return toReturn;
}
try {
WebRequest wr = WebRequest.Create($"https://www.googleapis.com/youtube/v3/playlistItems?part=contentDetails&maxResults={30}&playlistId={v}&key={ NadekoBot.creds.GoogleAPIKey }");
var sr = new StreamReader((await wr.GetResponseAsync()).GetResponseStream());
var response = await wr.GetResponseAsync();
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());
@ -161,8 +154,7 @@ namespace NadekoBot.Classes {
toReturn.Add("http://www.youtube.com/watch?v=" + item.contentDetails.videoId);
}
return toReturn;
}
catch (Exception ex) {
} catch (Exception ex) {
Console.WriteLine($"Error in GetPlaylistId: {ex.Message}");
return new List<string>();
}
@ -180,8 +172,7 @@ namespace NadekoBot.Classes {
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();
}
catch {
} catch {
return null;
}
}
@ -197,8 +188,7 @@ namespace NadekoBot.Classes {
//now extract the image from post page
var match = Regex.Match(webpage, "\"(?<url>http://simg4.gelbooru.com//images.*?)\"");
return match.Groups["url"].Value;
}
catch {
} catch {
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 matches = Regex.Matches(webpage, "\"file_url\":\"(?<url>.*?)\"");
return matches[rng.Next(0, matches.Count)].Groups["url"].Value;
}
catch {
} catch {
return null;
}
}
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 {
var httpWebRequest = (HttpWebRequest)WebRequest.Create("https://www.googleapis.com/urlshortener/v1/url?key=" + NadekoBot.creds.GoogleAPIKey);
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(await httpWebRequest.GetRequestStreamAsync())) {
string json = "{\"longUrl\":\"" + url + "\"}";
var json = "{\"longUrl\":\"" + url + "\"}";
streamWriter.Write(json);
}
var httpResponse = (await httpWebRequest.GetResponseAsync()) as HttpWebResponse;
using (var streamReader = new StreamReader(httpResponse.GetResponseStream())) {
string responseText = await streamReader.ReadToEndAsync();
string MATCH_PATTERN = @"""id"": ?""(?<id>.+)""";
return Regex.Match(responseText, MATCH_PATTERN).Groups["id"].Value;
if (httpResponse == null) return "HTTP_RESPONSE_ERROR";
var responseStream = httpResponse.GetResponseStream();
if (responseStream == null) return "RESPONSE_STREAM ERROR";
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}**");
//receive messages
NadekoBot.client.MessageReceived += PotentialGuess;
NadekoBot.Client.MessageReceived += PotentialGuess;
//allow people to guess
GameActive = true;
@ -71,7 +71,7 @@ namespace NadekoBot.Classes.Trivia {
GameActive = false;
if (!triviaCancelSource.IsCancellationRequested)
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
await Task.Delay(2000);
}

View File

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

View File

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

View File

@ -42,7 +42,7 @@ namespace NadekoBot {
await Task.Run(async () => {
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))
.FirstOrDefault();
if (com != null)

View File

@ -78,7 +78,7 @@ namespace NadekoBot.Commands {
await e.Channel.SendFile("champ.png", champ.ImageStream);
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;
if (role != null) {
for (int i = 0; i < allData.Count; i++) {
@ -114,7 +114,7 @@ namespace NadekoBot.Commands {
if (roles[i] == role)
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)
.FirstOrDefault()?["general"];
if (general == null) {
@ -253,7 +253,7 @@ Assists: {general["assists"]} Ban: {general["banRate"]}%
var data = JObject.Parse(
await Classes
.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();
sb.AppendLine($"**Showing {showCount} top banned champions.**");

View File

@ -9,10 +9,10 @@ namespace NadekoBot.Commands {
class LogCommand : DiscordCommand {
public LogCommand() : base() {
NadekoBot.client.MessageReceived += MsgRecivd;
NadekoBot.client.MessageDeleted += MsgDltd;
NadekoBot.client.MessageUpdated += MsgUpdtd;
NadekoBot.client.UserUpdated += UsrUpdtd;
NadekoBot.Client.MessageReceived += MsgRecivd;
NadekoBot.Client.MessageDeleted += MsgDltd;
NadekoBot.Client.MessageUpdated += MsgUpdtd;
NadekoBot.Client.UserUpdated += UsrUpdtd;
}
ConcurrentDictionary<Server, Channel> logs = new ConcurrentDictionary<Server, Channel>();
@ -36,7 +36,7 @@ namespace NadekoBot.Commands {
private async void MsgRecivd(object sender, MessageEventArgs e) {
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;
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) {
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;
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) {
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;
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 Dictionary<string, Func<string>> playingPlaceholders => new Dictionary<string, Func<string>> {
{"%servers%", ()=> NadekoBot.client.Servers.Count().ToString() },
{"%users%", () => NadekoBot.client.Servers.SelectMany(s=>s.Users).Count().ToString() },
{"%servers%", ()=> NadekoBot.Client.Servers.Count().ToString() },
{"%users%", () => NadekoBot.Client.Servers.SelectMany(s=>s.Users).Count().ToString() },
{"%playing%", () => {
var cnt = Modules.Music.musicPlayers.Where(kvp => kvp.Value.CurrentSong != null).Count();
if(cnt == 1) {
@ -51,7 +51,7 @@ namespace NadekoBot.Commands {
}
if (string.IsNullOrWhiteSpace(status))
return;
Task.Run(() => { try { NadekoBot.client.SetGame(status); } catch { } });
Task.Run(() => { try { NadekoBot.Client.SetGame(status); } catch { } });
}
catch { }
};

View File

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

View File

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

View File

@ -30,8 +30,8 @@ namespace NadekoBot.Commands {
public ServerGreetCommand() : base() {
AnnouncementsDictionary = new ConcurrentDictionary<ulong, AnnounceControls>();
NadekoBot.client.UserJoined += UserJoined;
NadekoBot.client.UserLeft += UserLeft;
NadekoBot.Client.UserJoined += UserJoined;
NadekoBot.Client.UserLeft += UserLeft;
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;
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();
if (string.IsNullOrEmpty(msg))
return;
@ -73,7 +73,7 @@ namespace NadekoBot.Commands {
!AnnouncementsDictionary[e.Server.Id].Greet) return;
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();
if (string.IsNullOrEmpty(msg))

View File

@ -39,7 +39,7 @@ namespace NadekoBot.Commands {
internal async Task<bool> Stop() {
if (!IsActive) return false;
NadekoBot.client.MessageReceived -= AnswerReceived;
NadekoBot.Client.MessageReceived -= AnswerReceived;
finishedUserIds.Clear();
IsActive = false;
sw.Stop();
@ -78,7 +78,7 @@ namespace NadekoBot.Commands {
}
private void HandleAnswers() {
NadekoBot.client.MessageReceived += AnswerReceived;
NadekoBot.Client.MessageReceived += AnswerReceived;
}
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")
.Parameter("user", ParameterType.Unparsed)
.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) {
var usr = e.Server.FindUsers(e.GetArg("user")).FirstOrDefault();
if (usr != null)
@ -608,7 +608,7 @@ namespace NadekoBot.Modules {
.Description("Clears the message queue. **OWNER ONLY**")
.AddCheck(Classes.Permissions.SimpleCheckers.OwnerOnly())
.Do(e => {
NadekoBot.client.MessageQueue.Clear();
NadekoBot.Client.MessageQueue.Clear();
});
cgb.CreateCommand(".donators")

View File

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

View File

@ -22,7 +22,7 @@ namespace NadekoBot.Modules {
.Alias("-modules")
.Description("List all bot modules.")
.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")
@ -30,7 +30,7 @@ namespace NadekoBot.Modules {
.Description("List all of the bot's commands from a certain module.")
.Parameter("module", ParameterType.Unparsed)
.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());
if (commands == null || commands.Count() == 0) {
await e.Channel.SendMessage("That module does not exist.");

View File

@ -28,7 +28,7 @@ namespace NadekoBot.Modules {
setgameTimer.Elapsed += (s, e) => {
try {
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 { }
};
@ -36,7 +36,7 @@ namespace NadekoBot.Modules {
}
public override void Install(ModuleManager manager) {
var client = NadekoBot.client;
var client = NadekoBot.Client;
manager.CreateCommands("!m", cgb => {

View File

@ -15,7 +15,7 @@ namespace NadekoBot.Modules {
}
public override void Install(ModuleManager manager) {
var client = NadekoBot.client;
var client = NadekoBot.Client;
manager.CreateCommands("", cgb => {
cgb.AddCheck(Classes.Permissions.PermissionChecker.Instance);
@ -349,7 +349,7 @@ namespace NadekoBot.Modules {
try {
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);
}
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"));
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);
}
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 {
bool state = PermissionHelper.ValidateBool(e.GetArg("bool"));
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);
}
@ -416,7 +416,7 @@ namespace NadekoBot.Modules {
bool state = PermissionHelper.ValidateBool(e.GetArg("bool"));
string module = PermissionHelper.ValidateModule(e.GetArg("module"));
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);
}
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 {
bool state = PermissionHelper.ValidateBool(e.GetArg("bool"));
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);
}
@ -461,7 +461,7 @@ namespace NadekoBot.Modules {
bool state = PermissionHelper.ValidateBool(e.GetArg("bool"));
string module = PermissionHelper.ValidateModule(e.GetArg("module"));
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);
}
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) {
var client = NadekoBot.client;
var client = NadekoBot.Client;
manager.CreateCommands("", cgb => {

View File

@ -65,7 +65,7 @@ namespace NadekoBot.Modules {
.Description("Joins a server")
.Parameter("code", Discord.Commands.ParameterType.Required)
.Do(async e => {
if (e.User.Id != NadekoBot.OwnerID) return;
if (e.User.Id != NadekoBot.OwnerId) return;
try {
await (await client.GetInvite(e.GetArg("code"))).Accept();
} 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.")
.Parameter("board_id", Discord.Commands.ParameterType.Required)
.Do(async e => {
if (e.User.Id != NadekoBot.OwnerID) return;
if (e.User.Id != NadekoBot.OwnerId) return;
if (bound != null) return;
try {
bound = e.Channel;
@ -93,7 +93,7 @@ namespace NadekoBot.Modules {
cgb.CreateCommand("unbind")
.Description("Unbinds a bot from the channel and board.")
.Do(async e => {
if (e.User.Id != NadekoBot.OwnerID) return;
if (e.User.Id != NadekoBot.OwnerId) return;
if (bound == null || bound != e.Channel) return;
t.Stop();
bound = null;
@ -106,7 +106,7 @@ namespace NadekoBot.Modules {
.Alias("list")
.Description("Lists all lists yo ;)")
.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;
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.")
.Parameter("list_name", Discord.Commands.ParameterType.Unparsed)
.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;
int num;

View File

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