paranoia mode engaged. fixing instability on mono.

This commit is contained in:
Master Kwoth 2016-02-26 09:46:50 +01:00
parent 291651e26c
commit 20fa15d856
14 changed files with 264 additions and 205 deletions

View File

@ -66,8 +66,6 @@ namespace NadekoBot.Classes.Music {
Provider = "Radio Stream"; Provider = "Radio Stream";
} }
else if (SoundCloud.Default.IsSoundCloudLink(Query)) { else if (SoundCloud.Default.IsSoundCloudLink(Query)) {
if (OnResolving != null)
OnResolving();
var svideo = await SoundCloud.Default.GetVideoAsync(Query); var svideo = await SoundCloud.Default.GetVideoAsync(Query);
Title = svideo.FullName; Title = svideo.FullName;
Provider = "SoundCloud"; Provider = "SoundCloud";
@ -75,9 +73,6 @@ namespace NadekoBot.Classes.Music {
Console.WriteLine(uri); Console.WriteLine(uri);
} }
else { else {
if (OnResolving != null)
OnResolving();
var links = await SearchHelper.FindYoutubeUrlByKeywords(Query); var links = await SearchHelper.FindYoutubeUrlByKeywords(Query);
if (links == String.Empty) if (links == String.Empty)
throw new OperationCanceledException("Not a valid youtube query."); throw new OperationCanceledException("Not a valid youtube query.");
@ -105,18 +100,18 @@ namespace NadekoBot.Classes.Music {
} }
musicStreamer = new MusicStreamer(this, uri); musicStreamer = new MusicStreamer(this, uri);
if (OnQueued != null) musicStreamer.OnCompleted += () => {
OnQueued(); OnCompleted();
};
OnQueued();
} }
internal string PrintStats() => musicStreamer?.Stats(); internal string PrintStats() => musicStreamer?.Stats();
public Action OnQueued = null; public event Action OnQueued = delegate { };
public Action OnBuffering = null; public event Action OnStarted = delegate { };
public Action OnStarted = null; public event Action OnCompleted = delegate { };
public Action OnCompleted = null; public event Action<string> OnResolvingFailed = delegate { };
public Action OnResolving = null;
public Action<string> OnResolvingFailed = null;
internal void Cancel() { internal void Cancel() {
musicStreamer?.Cancel(); musicStreamer?.Cancel();
@ -126,6 +121,10 @@ namespace NadekoBot.Classes.Music {
musicStreamer?.Stop(); musicStreamer?.Stop();
} }
protected void Complete() {
OnCompleted();
}
internal async Task Start() { internal async Task Start() {
int attemptsLeft = 4; int attemptsLeft = 4;
//wait for up to 4 seconds to resolve a link //wait for up to 4 seconds to resolve a link
@ -136,6 +135,7 @@ namespace NadekoBot.Classes.Music {
throw new TimeoutException("Resolving timed out."); throw new TimeoutException("Resolving timed out.");
} }
} }
OnStarted();
await musicStreamer.StartPlayback(); await musicStreamer.StartPlayback();
} }
catch (TimeoutException) { catch (TimeoutException) {
@ -157,6 +157,8 @@ namespace NadekoBot.Classes.Music {
private bool IsCanceled { get; set; } private bool IsCanceled { get; set; }
public bool IsPaused => parent.IsPaused; public bool IsPaused => parent.IsPaused;
public event Action OnCompleted = delegate { };
StreamRequest parent; StreamRequest parent;
private readonly object _bufferLock = new object(); private readonly object _bufferLock = new object();
private bool prebufferingComplete = false; private bool prebufferingComplete = false;
@ -196,8 +198,15 @@ namespace NadekoBot.Classes.Music {
if (State == StreamState.Completed) { if (State == StreamState.Completed) {
Console.WriteLine("Buffering canceled, stream is completed."); Console.WriteLine("Buffering canceled, stream is completed.");
p.CancelOutputRead(); try {
p.Close(); p.CancelOutputRead();
}
catch { }
try {
p.Close();
}
catch { }
p.Dispose();
return; return;
} }
if (buffer.readPos > 5.MiB() && buffer.writePos > 5.MiB()) { if (buffer.readPos > 5.MiB() && buffer.writePos > 5.MiB()) {
@ -221,8 +230,15 @@ namespace NadekoBot.Classes.Music {
if (read == 0) { if (read == 0) {
if (attempt == 5) { if (attempt == 5) {
Console.WriteLine($"Didn't read anything from the stream for {attempt} attempts. {buffer.Length / 1.MB()}MB length"); Console.WriteLine($"Didn't read anything from the stream for {attempt} attempts. {buffer.Length / 1.MB()}MB length");
p.CancelOutputRead(); try {
p.Close(); p.CancelOutputRead();
}
catch { }
try {
p.Close();
}
catch { }
p.Dispose();
return; return;
} }
else { else {
@ -242,8 +258,6 @@ namespace NadekoBot.Classes.Music {
catch { } catch { }
finally { finally {
if (p != null) { if (p != null) {
p.CancelOutputRead();
p.Close();
p.Dispose(); p.Dispose();
p = null; p = null;
} }
@ -254,8 +268,6 @@ namespace NadekoBot.Classes.Music {
Console.WriteLine("Starting playback."); Console.WriteLine("Starting playback.");
if (State == StreamState.Playing) return; if (State == StreamState.Playing) return;
State = StreamState.Playing; State = StreamState.Playing;
if (parent.OnBuffering != null)
parent.OnBuffering();
Task.Factory.StartNew(async () => { Task.Factory.StartNew(async () => {
await BufferSong(); await BufferSong();
@ -283,9 +295,6 @@ namespace NadekoBot.Classes.Music {
int blockSize = 1920 * NadekoBot.client.GetService<AudioService>()?.Config?.Channels ?? 3840; int blockSize = 1920 * NadekoBot.client.GetService<AudioService>()?.Config?.Channels ?? 3840;
byte[] voiceBuffer = new byte[blockSize]; byte[] voiceBuffer = new byte[blockSize];
if (parent.OnStarted != null)
parent.OnStarted();
int attempt = 0; int attempt = 0;
while (!IsCanceled) { while (!IsCanceled) {
int readCount = 0; int readCount = 0;
@ -319,7 +328,6 @@ namespace NadekoBot.Classes.Music {
await Task.Delay(100); await Task.Delay(100);
} }
} }
parent.MusicControls.VoiceClient.Wait();
Stop(); Stop();
} }
@ -332,8 +340,7 @@ namespace NadekoBot.Classes.Music {
var oldState = State; var oldState = State;
State = StreamState.Completed; State = StreamState.Completed;
if (oldState == StreamState.Playing) if (oldState == StreamState.Playing)
if (parent.OnCompleted != null) OnCompleted();
parent.OnCompleted();
} }
//stackoverflow ftw //stackoverflow ftw
private byte[] adjustVolume(byte[] audioSamples, float volume) { private byte[] adjustVolume(byte[] audioSamples, float volume) {

View File

@ -35,7 +35,7 @@ namespace NadekoBot.Classes.Permissions {
var data = Newtonsoft.Json.JsonConvert.DeserializeObject<ServerPermissions>(File.ReadAllText(file)); var data = Newtonsoft.Json.JsonConvert.DeserializeObject<ServerPermissions>(File.ReadAllText(file));
_permissionsDict.TryAdd(server, data); _permissionsDict.TryAdd(server, data);
} catch (Exception ex) { } catch (Exception ex) {
Console.WriteLine($"Failed getting server with id: {file}\nReason: {ex.Message}"); //Console.WriteLine($"Failed getting server with id: {file}\nReason: {ex.Message}");
} }
} }
Console.WriteLine("Permission initialization complete."); Console.WriteLine("Permission initialization complete.");

View File

@ -86,34 +86,37 @@ namespace NadekoBot.Classes.Trivia {
Commands.Trivia.runningTrivias.TryRemove(_server, out throwAwayValue); Commands.Trivia.runningTrivias.TryRemove(_server, out throwAwayValue);
} }
public async void StopGame() { public async Task StopGame() {
if (!ShouldStopGame) if (!ShouldStopGame)
await _channel.SendMessage(":exclamation: Trivia will stop after this question."); await _channel.SendMessage(":exclamation: Trivia will stop after this question.");
ShouldStopGame = true; ShouldStopGame = true;
} }
private async void PotentialGuess(object sender, MessageEventArgs e) { private async void PotentialGuess(object sender, MessageEventArgs e) {
if (e.Channel.IsPrivate) return; try {
if (e.Server != _server) return; if (e.Channel.IsPrivate) return;
if (e.Server != _server) return;
bool guess = false; bool guess = false;
lock (_guessLock) { lock (_guessLock) {
if (GameActive && CurrentQuestion.IsAnswerCorrect(e.Message.Text) && !triviaCancelSource.IsCancellationRequested) { if (GameActive && CurrentQuestion.IsAnswerCorrect(e.Message.Text) && !triviaCancelSource.IsCancellationRequested) {
users.TryAdd(e.User, 0); //add if not exists users.TryAdd(e.User, 0); //add if not exists
users[e.User]++; //add 1 point to the winner users[e.User]++; //add 1 point to the winner
guess = true; guess = true;
triviaCancelSource.Cancel(); triviaCancelSource.Cancel();
} }
} }
if (guess) { if (guess) {
await _channel.SendMessage($"☑️ {e.User.Mention} guessed it! The answer was: **{CurrentQuestion.Answer}**"); await _channel.SendMessage($"☑️ {e.User.Mention} guessed it! The answer was: **{CurrentQuestion.Answer}**");
if (users[e.User] == WinRequirement) { if (users[e.User] == WinRequirement) {
ShouldStopGame = true; ShouldStopGame = true;
await _channel.Send($":exclamation: We have a winner! Its {e.User.Mention}."); await _channel.Send($":exclamation: We have a winner! Its {e.User.Mention}.");
// add points to the winner // add points to the winner
await FlowersHandler.AddFlowersAsync(e.User, "Won Trivia", 2); await FlowersHandler.AddFlowersAsync(e.User, "Won Trivia", 2);
}
} }
} }
catch { }
} }
public string GetLeaderboard() { public string GetLeaderboard() {

View File

@ -327,7 +327,7 @@ namespace NadekoBot.Commands {
bases[baseNumber] = new Caller { CallUser = u.Trim(), TimeAdded = DateTime.Now, BaseDestroyed = false }; bases[baseNumber] = new Caller { CallUser = u.Trim(), TimeAdded = DateTime.Now, BaseDestroyed = false };
} }
internal async void Start() { internal async Task Start() {
if (Started) if (Started)
throw new InvalidOperationException(); throw new InvalidOperationException();
try { try {

View File

@ -18,11 +18,14 @@ namespace NadekoBot
private async void Client_MessageReceived(object sender, Discord.MessageEventArgs e) private async void Client_MessageReceived(object sender, Discord.MessageEventArgs e)
{ {
if (string.IsNullOrWhiteSpace(e.Message.Text)) try {
return; if (string.IsNullOrWhiteSpace(e.Message.Text))
if (CopiedUsers.Contains(e.User.Id)) { return;
await e.Channel.SendMessage( e.Message.Text.Replace("@everyone","@everryone")); if (CopiedUsers.Contains(e.User.Id)) {
await e.Channel.SendMessage(e.Message.Text);
}
} }
catch { }
} }
public override Func<CommandEventArgs, Task> DoFunc() => async e => public override Func<CommandEventArgs, Task> DoFunc() => async e =>

View File

@ -34,24 +34,26 @@ namespace NadekoBot.Commands {
public PlayingRotate() { public PlayingRotate() {
int i = -1; int i = -1;
timer.Elapsed += (s, e) => { timer.Elapsed += (s, e) => {
i++; try {
Console.WriteLine("elapsed"); i++;
string status = ""; string status = "";
lock (playingPlaceholderLock) { lock (playingPlaceholderLock) {
if (playingPlaceholders.Count == 0) if (playingPlaceholders.Count == 0)
return; return;
if (i >= playingPlaceholders.Count) { if (i >= playingPlaceholders.Count) {
i = -1; i = -1;
return; return;
} }
status = rotatingStatuses[i]; status = rotatingStatuses[i];
foreach (var kvp in playingPlaceholders) { foreach (var kvp in playingPlaceholders) {
status = status.Replace(kvp.Key, kvp.Value()); status = status.Replace(kvp.Key, kvp.Value());
}
} }
if (string.IsNullOrWhiteSpace(status))
return;
Task.Run(() => { try { NadekoBot.client.SetGame(status); } catch { } });
} }
if (string.IsNullOrWhiteSpace(status)) catch { }
return;
NadekoBot.client.SetGame(status);
}; };
} }
@ -74,6 +76,7 @@ namespace NadekoBot.Commands {
.Alias(".adpl") .Alias(".adpl")
.Description("Adds a specified string to the list of playing strings to rotate. Supported placeholders: " + string.Join(", ", playingPlaceholders.Keys)) .Description("Adds a specified string to the list of playing strings to rotate. Supported placeholders: " + string.Join(", ", playingPlaceholders.Keys))
.Parameter("text", ParameterType.Unparsed) .Parameter("text", ParameterType.Unparsed)
.AddCheck(Classes.Permissions.SimpleCheckers.OwnerOnly())
.Do(async e => { .Do(async e => {
var arg = e.GetArg("text"); var arg = e.GetArg("text");
if (string.IsNullOrWhiteSpace(arg)) if (string.IsNullOrWhiteSpace(arg))
@ -110,7 +113,7 @@ namespace NadekoBot.Commands {
lock (playingPlaceholderLock) { lock (playingPlaceholderLock) {
if (!int.TryParse(arg.Trim(), out num) || num <= 0 || num > rotatingStatuses.Count) if (!int.TryParse(arg.Trim(), out num) || num <= 0 || num > rotatingStatuses.Count)
return; return;
str = rotatingStatuses[num]; str = rotatingStatuses[num - 1];
rotatingStatuses.RemoveAt(num - 1); rotatingStatuses.RemoveAt(num - 1);
} }
await e.Channel.SendMessage($"🆗 `Removed playing string #{num}`({str})"); await e.Channel.SendMessage($"🆗 `Removed playing string #{num}`({str})");

View File

@ -105,19 +105,22 @@ namespace NadekoBot.Modules {
} }
private async void Vote(object sender, MessageEventArgs e) { private async void Vote(object sender, MessageEventArgs e) {
if (!e.Channel.IsPrivate) try {
return; if (!e.Channel.IsPrivate)
if (participants.ContainsKey(e.User))
return;
int vote;
if (int.TryParse(e.Message.Text, out vote)) {
if (vote < 1 || vote > answers.Length)
return; return;
if (participants.TryAdd(e.User, vote)) { if (participants.ContainsKey(e.User))
await e.User.SendMessage($"Thanks for voting **{e.User.Name}**."); return;
int vote;
if (int.TryParse(e.Message.Text, out vote)) {
if (vote < 1 || vote > answers.Length)
return;
if (participants.TryAdd(e.User, vote)) {
await e.User.SendMessage($"Thanks for voting **{e.User.Name}**.");
}
} }
} }
catch { }
} }
} }
} }

View File

@ -41,46 +41,54 @@ namespace NadekoBot.Commands {
} }
private async void UserLeft(object sender, UserEventArgs e) { private async void UserLeft(object sender, UserEventArgs e) {
if (!AnnouncementsDictionary.ContainsKey(e.Server.Id) || try {
!AnnouncementsDictionary[e.Server.Id].Bye) return; if (!AnnouncementsDictionary.ContainsKey(e.Server.Id) ||
!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;
if (controls.ByePM) { if (controls.ByePM) {
Greeted++; Greeted++;
try { try {
await e.User.SendMessage($"`Farewell Message From {e.Server?.Name}`\n" + msg); await e.User.SendMessage($"`Farewell Message From {e.Server?.Name}`\n" + msg);
}
catch { }
}
else {
if (channel == null) return;
Greeted++;
await channel.Send(msg);
} }
catch { }
} else {
if (channel == null) return;
Greeted++;
await channel.Send(msg);
} }
catch { }
} }
private async void UserJoined(object sender, Discord.UserEventArgs e) { private async void UserJoined(object sender, Discord.UserEventArgs e) {
if (!AnnouncementsDictionary.ContainsKey(e.Server.Id) || try {
!AnnouncementsDictionary[e.Server.Id].Greet) return; if (!AnnouncementsDictionary.ContainsKey(e.Server.Id) ||
!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))
return; return;
if (controls.GreetPM) { if (controls.GreetPM) {
Greeted++; Greeted++;
await e.User.SendMessage($"`Welcome Message From {e.Server.Name}`\n" + msg); await e.User.SendMessage($"`Welcome Message From {e.Server.Name}`\n" + msg);
} else { }
if (channel == null) return; else {
Greeted++; if (channel == null) return;
await channel.Send(msg); Greeted++;
await channel.Send(msg);
}
} }
catch { }
} }
public class AnnounceControls { public class AnnounceControls {

View File

@ -82,20 +82,23 @@ namespace NadekoBot.Commands {
} }
private async void AnswerReceived(object sender, MessageEventArgs e) { private async void AnswerReceived(object sender, MessageEventArgs e) {
if (e.Channel == null || e.Channel.Id != channel.Id) return; try {
if (e.Channel == null || e.Channel.Id != channel.Id) return;
var guess = e.Message.RawText; var guess = e.Message.RawText;
var distance = currentSentence.LevenshteinDistance(guess);
var decision = Judge(distance, guess.Length);
if (decision && !finishedUserIds.Contains(e.User.Id)) {
finishedUserIds.Add(e.User.Id);
await channel.Send($"{e.User.Mention} finished in **{sw.Elapsed.Seconds}** seconds with { distance } errors, **{ currentSentence.Length / TypingGame.WORD_VALUE / sw.Elapsed.Seconds * 60 }** WPM!");
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:");
}
var distance = currentSentence.LevenshteinDistance(guess);
var decision = Judge(distance, guess.Length);
if (decision && !finishedUserIds.Contains(e.User.Id)) {
finishedUserIds.Add(e.User.Id);
await channel.Send($"{e.User.Mention} finished in **{sw.Elapsed.Seconds}** seconds with { distance } errors, **{ currentSentence.Length / TypingGame.WORD_VALUE / sw.Elapsed.Seconds * 60 }** WPM!");
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:");
} }
} }
catch { }
} }
private bool Judge(int errors, int textLength) => errors <= textLength / 25; private bool Judge(int errors, int textLength) => errors <= textLength / 25;

View File

@ -153,11 +153,11 @@ namespace NadekoBot.Modules {
if (!string.IsNullOrWhiteSpace(e.GetArg("user"))) { if (!string.IsNullOrWhiteSpace(e.GetArg("user"))) {
var usr = e.Server.FindUsers(e.GetArg("user")).FirstOrDefault(); var usr = e.Server.FindUsers(e.GetArg("user")).FirstOrDefault();
if (usr != null) { if (usr != null) {
await e.Channel.SendMessage($"`List of roles for **{usr.Name}**:` \n• " + string.Join("\n• ", usr.Roles).Replace("@everyone", "මeveryone")); await e.Channel.SendMessage($"`List of roles for **{usr.Name}**:` \n• " + string.Join("\n• ", usr.Roles));
return; return;
} }
} }
await e.Channel.SendMessage("`List of roles:` \n• " + string.Join("\n• ", e.Server.Roles).Replace("@everyone", "මeveryone")); await e.Channel.SendMessage("`List of roles:` \n• " + string.Join("\n• ", e.Server.Roles));
}); });
cgb.CreateCommand(".b").Alias(".ban") cgb.CreateCommand(".b").Alias(".ban")

View File

@ -341,7 +341,7 @@ namespace NadekoBot.Modules {
} }
} }
if (msg != null) if (msg != null)
await e.Channel.SendMessage($"Last message mentioning you was at {msg.Timestamp}\n**Message from {msg.User.Name}:** {msg.RawText.Replace("@everyone", "@everryone")}"); await e.Channel.SendMessage($"Last message mentioning you was at {msg.Timestamp}\n**Message from {msg.User.Name}:** {msg.RawText}");
else else
await e.Channel.SendMessage("I can't find a message mentioning you."); await e.Channel.SendMessage("I can't find a message mentioning you.");
}); });
@ -362,7 +362,7 @@ namespace NadekoBot.Modules {
.Description("Useless. Writes calling @X to chat.\n**Usage**: @NadekoBot call @X ") .Description("Useless. Writes calling @X to chat.\n**Usage**: @NadekoBot call @X ")
.Parameter("who", ParameterType.Required) .Parameter("who", ParameterType.Required)
.Do(async e => { .Do(async e => {
await e.Channel.SendMessage("Calling " + e.Args[0].Replace("@everyone", "[everyone]") + "..."); await e.Channel.SendMessage("Calling " + e.Args[0] + "...");
}); });
cgb.CreateCommand("hide") cgb.CreateCommand("hide")
.Description("Hides Nadeko in plain sight!11!!") .Description("Hides Nadeko in plain sight!11!!")

View File

@ -48,11 +48,14 @@ namespace NadekoBot.Modules
.Description("Ask the 8ball a yes/no question.") .Description("Ask the 8ball a yes/no question.")
.Parameter("question",Discord.Commands.ParameterType.Unparsed) .Parameter("question",Discord.Commands.ParameterType.Unparsed)
.Do(async e => { .Do(async e => {
string question = e.GetArg("question").Replace("@everyone","[everyone]"); string question = e.GetArg("question");
if (string.IsNullOrWhiteSpace(question)) if (string.IsNullOrWhiteSpace(question))
return; return;
await e.Channel.SendMessage( try {
$":question: **Question**: `{question}` \n:crystal_ball: **8Ball Answers**: `{_8BallAnswers[_r.Next(0, _8BallAnswers.Length)]}`"); await e.Channel.SendMessage(
$":question: **Question**: `{question}` \n:crystal_ball: **8Ball Answers**: `{_8BallAnswers[new Random().Next(0, _8BallAnswers.Length)]}`");
}
catch { }
}); });
cgb.CreateCommand(">") cgb.CreateCommand(">")

View File

@ -1,16 +1,16 @@
using System; using Discord;
using System.Linq;
using Discord.Modules;
using Discord.Commands;
using Discord;
using NadekoBot.Extensions;
using System.Collections.Concurrent;
using NadekoBot.Classes.Music;
using Timer = System.Timers.Timer;
using System.Threading.Tasks;
using NadekoBot.Classes;
using Discord.Audio; using Discord.Audio;
using Discord.Commands;
using Discord.Modules;
using NadekoBot.Classes;
using NadekoBot.Classes.Music;
using NadekoBot.Extensions;
using System;
using System.Collections.Concurrent;
using System.Linq;
using System.Text.RegularExpressions; using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Timer = System.Timers.Timer;
namespace NadekoBot.Modules { namespace NadekoBot.Modules {
class Music : DiscordModule { class Music : DiscordModule {
@ -40,7 +40,7 @@ namespace NadekoBot.Modules {
.Alias("next") .Alias("next")
.Description("Goes to the next song in the queue.") .Description("Goes to the next song in the queue.")
.Do(async e => { .Do(async e => {
if (musicPlayers.ContainsKey(e.Server) == false) return; if (!musicPlayers.ContainsKey(e.Server)) return;
await musicPlayers[e.Server].LoadNextSong(); await musicPlayers[e.Server].LoadNextSong();
}); });
@ -48,7 +48,7 @@ namespace NadekoBot.Modules {
.Alias("stop") .Alias("stop")
.Description("Completely stops the music, unbinds the bot from the channel, and cleans up files.") .Description("Completely stops the music, unbinds the bot from the channel, and cleans up files.")
.Do(e => { .Do(e => {
if (musicPlayers.ContainsKey(e.Server) == false) return; if (!musicPlayers.ContainsKey(e.Server)) return;
musicPlayers[e.Server].Stop(true); musicPlayers[e.Server].Stop(true);
}); });
@ -56,7 +56,7 @@ namespace NadekoBot.Modules {
.Alias("pause") .Alias("pause")
.Description("Pauses or Unpauses the song.") .Description("Pauses or Unpauses the song.")
.Do(async e => { .Do(async e => {
if (musicPlayers.ContainsKey(e.Server) == false) return; if (!musicPlayers.ContainsKey(e.Server)) return;
if (musicPlayers[e.Server].TogglePause()) if (musicPlayers[e.Server].TogglePause())
await e.Channel.SendMessage("🎵`Music player paused.`"); await e.Channel.SendMessage("🎵`Music player paused.`");
else else
@ -67,11 +67,13 @@ namespace NadekoBot.Modules {
.Alias("yq") .Alias("yq")
.Description("Queue a song using keywords or a link. Bot will join your voice channel. **You must be in a voice channel**.\n**Usage**: `!m q Dream Of Venice`") .Description("Queue a song using keywords or a link. Bot will join your voice channel. **You must be in a voice channel**.\n**Usage**: `!m q Dream Of Venice`")
.Parameter("query", ParameterType.Unparsed) .Parameter("query", ParameterType.Unparsed)
.Do(async e => await QueueSong(e,e.GetArg("query"))); .Do(async e => {
await QueueSong(e, e.GetArg("query"));
});
cgb.CreateCommand("lq") cgb.CreateCommand("lq")
.Alias("ls").Alias("lp") .Alias("ls").Alias("lp")
.Description("Lists up to 10 currently queued songs.") .Description("Lists up to 15 currently queued songs.")
.Do(async e => { .Do(async e => {
if (musicPlayers.ContainsKey(e.Server) == false) { if (musicPlayers.ContainsKey(e.Server) == false) {
await e.Channel.SendMessage("🎵 No active music player."); await e.Channel.SendMessage("🎵 No active music player.");
@ -81,19 +83,18 @@ namespace NadekoBot.Modules {
string toSend = "🎵 **" + player.SongQueue.Count + "** `videos currently queued.` "; string toSend = "🎵 **" + player.SongQueue.Count + "** `videos currently queued.` ";
if (player.SongQueue.Count >= 50) if (player.SongQueue.Count >= 50)
toSend += "**Song queue is full!**\n"; toSend += "**Song queue is full!**\n";
await e.Channel.SendMessage(toSend);
int number = 1; int number = 1;
await e.Channel.SendMessage(string.Join("\n", player.SongQueue.Take(10).Select(v => $"`{number++}.` {v.FullPrettyName}"))); await e.Channel.SendMessage(toSend + string.Join("\n", player.SongQueue.Take(15).Select(v => $"`{number++}.` {v.FullPrettyName}")));
}); });
cgb.CreateCommand("np") cgb.CreateCommand("np")
.Alias("playing") .Alias("playing")
.Description("Shows the song currently playing.") .Description("Shows the song currently playing.")
.Do(async e => { .Do(async e => {
if (musicPlayers.ContainsKey(e.Server) == false) return; if (musicPlayers.ContainsKey(e.Server) == false) return;
var player = musicPlayers[e.Server]; var player = musicPlayers[e.Server];
await e.Channel.SendMessage($"🎵`Now Playing` {player.CurrentSong.FullPrettyName}"); await e.Channel.SendMessage($"🎵`Now Playing` {player.CurrentSong.FullPrettyName}");
}); });
cgb.CreateCommand("vol") cgb.CreateCommand("vol")
.Description("Sets the music volume 0-150%") .Description("Sets the music volume 0-150%")
@ -168,8 +169,11 @@ namespace NadekoBot.Modules {
Timer setgameTimer = new Timer(); Timer setgameTimer = new Timer();
setgameTimer.Interval = 20000; setgameTimer.Interval = 20000;
setgameTimer.Elapsed += (s, e) => { setgameTimer.Elapsed += (s, e) => {
int num = musicPlayers.Where(kvp => kvp.Value.CurrentSong != null).Count(); try {
NadekoBot.client.SetGame($"{num} songs".SnPl(num) + $", {musicPlayers.Sum(kvp => kvp.Value.SongQueue.Count())} queued"); int num = musicPlayers.Where(kvp => kvp.Value.CurrentSong != null).Count();
NadekoBot.client.SetGame($"{num} songs".SnPl(num) + $", {musicPlayers.Sum(kvp => kvp.Value.SongQueue.Count())} queued");
}
catch { }
}; };
cgb.CreateCommand("setgame") cgb.CreateCommand("setgame")
.Description("Sets the game of the bot to the number of songs playing.**Owner only**") .Description("Sets the game of the bot to the number of songs playing.**Owner only**")
@ -195,7 +199,7 @@ namespace NadekoBot.Modules {
} }
var ids = await SearchHelper.GetVideoIDs(await SearchHelper.GetPlaylistIdByKeyword(e.GetArg("playlist"))); var ids = await SearchHelper.GetVideoIDs(await SearchHelper.GetPlaylistIdByKeyword(e.GetArg("playlist")));
//todo TEMPORARY SOLUTION, USE RESOLVE QUEUE IN THE FUTURE //todo TEMPORARY SOLUTION, USE RESOLVE QUEUE IN THE FUTURE
var msg = await e.Channel.SendMessage($"🎵 `Attempting to queue {ids.Count} songs".SnPl(ids.Count)+"...`"); var msg = await e.Channel.SendMessage($"🎵 `Attempting to queue {ids.Count} songs".SnPl(ids.Count) + "...`");
foreach (var id in ids) { foreach (var id in ids) {
Task.Run(async () => await QueueSong(e, id, true)).ConfigureAwait(false); Task.Run(async () => await QueueSong(e, id, true)).ConfigureAwait(false);
await Task.Delay(150); await Task.Delay(150);
@ -209,12 +213,12 @@ namespace NadekoBot.Modules {
.AddCheck(Classes.Permissions.SimpleCheckers.OwnerOnly()) .AddCheck(Classes.Permissions.SimpleCheckers.OwnerOnly())
.Do(async e => { .Do(async e => {
var arg = e.GetArg("directory"); var arg = e.GetArg("directory");
if(string.IsNullOrWhiteSpace(e.GetArg("directory"))) if (string.IsNullOrWhiteSpace(e.GetArg("directory")))
return; return;
try { try {
var fileEnum = System.IO.Directory.EnumerateFiles(e.GetArg("directory")).Take(50); var fileEnum = System.IO.Directory.EnumerateFiles(e.GetArg("directory")).Take(50);
foreach (var file in fileEnum) { foreach (var file in fileEnum) {
await Task.Run(async() => await QueueSong(e, file, true, MusicType.Local)).ConfigureAwait(false); await Task.Run(async () => await QueueSong(e, file, true, MusicType.Local)).ConfigureAwait(false);
} }
await e.Channel.SendMessage("🎵 `Directory queue complete.`"); await e.Channel.SendMessage("🎵 `Directory queue complete.`");
} }
@ -247,7 +251,7 @@ namespace NadekoBot.Modules {
.Description("Moves the bot to your voice channel. (works only if music is already playing)") .Description("Moves the bot to your voice channel. (works only if music is already playing)")
.Do(async e => { .Do(async e => {
MusicControls mc; MusicControls mc;
if (e.User.VoiceChannel == null || e.User.VoiceChannel.Server != e.Server || !musicPlayers.TryGetValue(e.Server,out mc)) if (e.User.VoiceChannel == null || e.User.VoiceChannel.Server != e.Server || !musicPlayers.TryGetValue(e.Server, out mc))
return; return;
mc.VoiceChannel = e.User.VoiceChannel; mc.VoiceChannel = e.User.VoiceChannel;
mc.VoiceClient = await mc.VoiceChannel.JoinAudio(); mc.VoiceClient = await mc.VoiceChannel.JoinAudio();
@ -255,7 +259,7 @@ namespace NadekoBot.Modules {
cgb.CreateCommand("rm") cgb.CreateCommand("rm")
.Description("Remove a song by its # in the queue, or 'all' to remove whole queue.") .Description("Remove a song by its # in the queue, or 'all' to remove whole queue.")
.Parameter("num",ParameterType.Required) .Parameter("num", ParameterType.Required)
.Do(async e => { .Do(async e => {
var arg = e.GetArg("num"); var arg = e.GetArg("num");
MusicControls mc; MusicControls mc;
@ -292,7 +296,7 @@ namespace NadekoBot.Modules {
private async Task QueueSong(CommandEventArgs e, string query, bool silent = false, MusicType musicType = MusicType.Normal) { private async Task QueueSong(CommandEventArgs e, string query, bool silent = false, MusicType musicType = MusicType.Normal) {
if (e.User.VoiceChannel?.Server != e.Server) { if (e.User.VoiceChannel?.Server != e.Server) {
if(!silent) if (!silent)
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."); 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.");
return; return;
} }
@ -331,36 +335,48 @@ namespace NadekoBot.Modules {
Message qmsg = null; Message qmsg = null;
Message msg = null; Message msg = null;
if (!silent) { if (!silent) {
qmsg = await e.Channel.SendMessage("🎵 `Searching / Resolving...`"); try {
sr.OnResolvingFailed += async (err) => { qmsg = await e.Channel.SendMessage("🎵 `Searching / Resolving...`");
await qmsg?.Edit($"💢 🎵 `Resolving failed` for **{query}**"); sr.OnResolvingFailed += async (err) => {
}; try {
sr.OnQueued += async () => { await qmsg.Edit($"💢 🎵 `Resolving failed` for **{query}**");
await qmsg?.Edit($"🎵`Queued`{sr.FullPrettyName}"); }
}; catch { }
};
sr.OnQueued += async () => {
try {
await qmsg.Edit($"🎵`Queued`{sr.FullPrettyName}");
}
catch { }
};
}
catch { }
} }
sr.OnCompleted += async () => { sr.OnCompleted += async () => {
MusicControls mc; try {
if (musicPlayers.TryGetValue(e.Server, out mc)) { MusicControls mc;
if (mc.SongQueue.Count == 0) if (musicPlayers.TryGetValue(e.Server, out mc)) {
mc.Stop(); if (mc.SongQueue.Count == 0)
mc.Stop();
}
await e.Channel.SendMessage($"🎵`Finished`{sr.FullPrettyName}");
} }
await e.Channel.SendMessage($"🎵`Finished`{sr.FullPrettyName}"); catch { }
}; };
sr.OnStarted += async () => { sr.OnStarted += async () => {
var msgTxt = $"🎵`Playing`{sr.FullPrettyName} `Vol: {(int)(player.Volume * 100)}%`"; try {
if (msg == null) var msgTxt = $"🎵`Playing`{sr.FullPrettyName} `Vol: {(int)(player.Volume * 100)}%`";
await e.Channel.SendMessage(msgTxt); if (qmsg != null)
else await qmsg.Edit(msgTxt);
await msg.Edit(msgTxt); else
qmsg?.Delete(); await e.Channel.SendMessage(msgTxt);
}; }
sr.OnBuffering += async () => { catch { }
msg = await e.Channel.SendMessage($"🎵`Buffering...`{sr.FullPrettyName}");
}; };
await sr.Resolve(); await sr.Resolve();
} catch (Exception ex) { }
Console.WriteLine(); catch (Exception ex) {
await e.Channel.SendMessage($"💢 {ex.Message}"); await e.Channel.SendMessage($"💢 {ex.Message}");
return; return;
} }
@ -378,7 +394,7 @@ namespace NadekoBot.Modules {
private async Task<string> HandleStreamContainers(string query) { private async Task<string> HandleStreamContainers(string query) {
string file = null; string file = null;
try { try {
file = await SearchHelper.GetResponseAsync(query); file = await SearchHelper.GetResponseAsync(query);
} }
catch { catch {
return query; return query;

View File

@ -66,7 +66,6 @@ namespace NadekoBot {
//create new discord client //create new discord client
client = new DiscordClient(new DiscordConfigBuilder() { client = new DiscordClient(new DiscordConfigBuilder() {
MessageCacheSize = 20, MessageCacheSize = 20,
ConnectionTimeout = 60000,
}); });
//create a command service //create a command service
@ -110,7 +109,7 @@ namespace NadekoBot {
modules.Add(new Conversations(), "Conversations", ModuleFilter.None); modules.Add(new Conversations(), "Conversations", ModuleFilter.None);
modules.Add(new Gambling(), "Gambling", ModuleFilter.None); modules.Add(new Gambling(), "Gambling", ModuleFilter.None);
modules.Add(new Games(), "Games", ModuleFilter.None); modules.Add(new Games(), "Games", ModuleFilter.None);
modules.Add(new Music(), "Music", ModuleFilter.None); //modules.Add(new Music(), "Music", ModuleFilter.None);
modules.Add(new Searches(), "Searches", ModuleFilter.None); modules.Add(new Searches(), "Searches", ModuleFilter.None);
if (loadTrello) if (loadTrello)
modules.Add(new Trello(), "Trello", ModuleFilter.None); modules.Add(new Trello(), "Trello", ModuleFilter.None);
@ -142,22 +141,30 @@ namespace NadekoBot {
Classes.Permissions.PermissionsHandler.Initialize(); Classes.Permissions.PermissionsHandler.Initialize();
client.ClientAPI.SendingRequest += (s, e) => { client.ClientAPI.SendingRequest += (s, e) => {
var request = e.Request as Discord.API.Client.Rest.SendMessageRequest; try {
if (request != null) { var request = e.Request as Discord.API.Client.Rest.SendMessageRequest;
if (string.IsNullOrWhiteSpace(request.Content)) if (request != null) {
e.Cancel = true; if (string.IsNullOrWhiteSpace(request.Content))
//else e.Cancel = true;
// Console.WriteLine("Sending request."); else
request.Content = request.Content.Replace("@everyone", "@everyοne"); Console.WriteLine("Sending request.");
request.Content = request.Content.Replace("@everyone", "@everyοne");
}
}
catch {
Console.WriteLine("SENDING REQUEST ERRORED!!!!");
} }
}; };
//client.ClientAPI.SentRequest += (s, e) => { client.ClientAPI.SentRequest += (s, e) => {
// var request = e.Request as Discord.API.Client.Rest.SendMessageRequest; try {
// if (request != null) { var request = e.Request as Discord.API.Client.Rest.SendMessageRequest;
// Console.WriteLine("Sent."); if (request != null) {
// } Console.WriteLine("Sent.");
//}; }
}
catch { Console.WriteLine("SENT REQUEST ERRORED!!!"); }
};
}); });
Console.WriteLine("Exiting..."); Console.WriteLine("Exiting...");
Console.ReadKey(); Console.ReadKey();
@ -200,9 +207,12 @@ namespace NadekoBot {
t.Interval = 2000; t.Interval = 2000;
t.Start(); t.Start();
t.Elapsed += (s, ev) => { t.Elapsed += (s, ev) => {
repliedRecently = false; try {
t.Stop(); repliedRecently = false;
t.Dispose(); t.Stop();
t.Dispose();
}
catch { }
}; };
} }
} }