~ani, ~mang, and @nadekobot how are you are the only things that don't work now
This commit is contained in:
parent
81b27988d9
commit
ffb63f9e81
10
NadekoBot/Classes/JSONModels/Config.cs
Normal file
10
NadekoBot/Classes/JSONModels/Config.cs
Normal file
@ -0,0 +1,10 @@
|
|||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Linq;
|
||||||
|
using System.Text;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
|
||||||
|
namespace NadekoBot.Classes.JSONModels {
|
||||||
|
internal class Config {
|
||||||
|
}
|
||||||
|
}
|
@ -21,7 +21,7 @@ namespace NadekoBot.Classes.Music {
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
public class PoopyBuffer {
|
public class PoopyBuffer {
|
||||||
|
|
||||||
private byte[] ringBuffer;
|
private readonly byte[] ringBuffer;
|
||||||
|
|
||||||
public int WritePosition { get; private set; } = 0;
|
public int WritePosition { get; private set; } = 0;
|
||||||
public int ReadPosition { get; private set; } = 0;
|
public int ReadPosition { get; private set; } = 0;
|
||||||
@ -70,13 +70,13 @@ namespace NadekoBot.Classes.Music {
|
|||||||
return count;
|
return count;
|
||||||
}
|
}
|
||||||
// B: if i can't read as much, read to the end,
|
// B: if i can't read as much, read to the end,
|
||||||
int readNormaly = BufferSize - ReadPosition;
|
var readNormaly = BufferSize - ReadPosition;
|
||||||
Buffer.BlockCopy(ringBuffer, ReadPosition, buffer, 0, readNormaly);
|
Buffer.BlockCopy(ringBuffer, ReadPosition, buffer, 0, readNormaly);
|
||||||
|
|
||||||
//Console.WriteLine($"Read normaly {count}[{ReadPosition} to {ReadPosition + readNormaly}]");
|
//Console.WriteLine($"Read normaly {count}[{ReadPosition} to {ReadPosition + readNormaly}]");
|
||||||
//then read the remaining amount from the start
|
//then read the remaining amount from the start
|
||||||
|
|
||||||
int readFromStart = count - readNormaly;
|
var readFromStart = count - readNormaly;
|
||||||
Buffer.BlockCopy(ringBuffer, 0, buffer, readNormaly, readFromStart);
|
Buffer.BlockCopy(ringBuffer, 0, buffer, readNormaly, readFromStart);
|
||||||
//Console.WriteLine($"Read From start {readFromStart}[{0} to {readFromStart}]");
|
//Console.WriteLine($"Read From start {readFromStart}[{0} to {readFromStart}]");
|
||||||
ReadPosition = readFromStart;
|
ReadPosition = readFromStart;
|
||||||
@ -88,7 +88,7 @@ namespace NadekoBot.Classes.Music {
|
|||||||
if (count > buffer.Length)
|
if (count > buffer.Length)
|
||||||
throw new ArgumentException();
|
throw new ArgumentException();
|
||||||
while (ContentLength + count > BufferSize) {
|
while (ContentLength + count > BufferSize) {
|
||||||
await Task.Delay(20);
|
await Task.Delay(20, cancelToken);
|
||||||
if (cancelToken.IsCancellationRequested)
|
if (cancelToken.IsCancellationRequested)
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@ -104,12 +104,12 @@ namespace NadekoBot.Classes.Music {
|
|||||||
}
|
}
|
||||||
// otherwise, i have to write to the end, then write the rest from the start
|
// otherwise, i have to write to the end, then write the rest from the start
|
||||||
|
|
||||||
int wroteNormaly = BufferSize - WritePosition;
|
var wroteNormaly = BufferSize - WritePosition;
|
||||||
Buffer.BlockCopy(buffer, 0, ringBuffer, WritePosition, wroteNormaly);
|
Buffer.BlockCopy(buffer, 0, ringBuffer, WritePosition, wroteNormaly);
|
||||||
|
|
||||||
//Console.WriteLine($"Wrote normally {wroteNormaly}[{WritePosition} to {BufferSize}]");
|
//Console.WriteLine($"Wrote normally {wroteNormaly}[{WritePosition} to {BufferSize}]");
|
||||||
|
|
||||||
int wroteFromStart = count - wroteNormaly;
|
var wroteFromStart = count - wroteNormaly;
|
||||||
Buffer.BlockCopy(buffer, wroteNormaly, ringBuffer, 0, wroteFromStart);
|
Buffer.BlockCopy(buffer, wroteNormaly, ringBuffer, 0, wroteFromStart);
|
||||||
|
|
||||||
//Console.WriteLine($"and from start {wroteFromStart} [0 to {wroteFromStart}");
|
//Console.WriteLine($"and from start {wroteFromStart} [0 to {wroteFromStart}");
|
||||||
@ -145,27 +145,25 @@ namespace NadekoBot.Classes.Music {
|
|||||||
RedirectStandardError = false,
|
RedirectStandardError = false,
|
||||||
CreateNoWindow = true,
|
CreateNoWindow = true,
|
||||||
});
|
});
|
||||||
int blockSize = 3840;
|
var blockSize = 3840;
|
||||||
byte[] buffer = new byte[blockSize];
|
var buffer = new byte[blockSize];
|
||||||
int attempt = 0;
|
var attempt = 0;
|
||||||
while (!cancelToken.IsCancellationRequested) {
|
while (!cancelToken.IsCancellationRequested) {
|
||||||
int read = await p.StandardOutput.BaseStream.ReadAsync(buffer, 0, blockSize, cancelToken);
|
var read = await p.StandardOutput.BaseStream.ReadAsync(buffer, 0, blockSize, cancelToken);
|
||||||
if (read == 0)
|
if (read == 0)
|
||||||
if (attempt++ == 20)
|
if (attempt++ == 20)
|
||||||
break;
|
break;
|
||||||
else
|
else
|
||||||
await Task.Delay(50);
|
await Task.Delay(50, cancelToken);
|
||||||
else
|
else
|
||||||
attempt = 0;
|
attempt = 0;
|
||||||
await songBuffer.WriteAsync(buffer, read, cancelToken);
|
await songBuffer.WriteAsync(buffer, read, cancelToken);
|
||||||
if (songBuffer.ContentLength > 2.MB())
|
if (songBuffer.ContentLength > 2.MB())
|
||||||
prebufferingComplete = true;
|
prebufferingComplete = true;
|
||||||
}
|
}
|
||||||
}
|
} catch {
|
||||||
catch {
|
|
||||||
Console.WriteLine("Buffering errored");
|
Console.WriteLine("Buffering errored");
|
||||||
}
|
} finally {
|
||||||
finally {
|
|
||||||
if (p != null) {
|
if (p != null) {
|
||||||
p.CancelOutputRead();
|
p.CancelOutputRead();
|
||||||
p.StandardOutput.Dispose();
|
p.StandardOutput.Dispose();
|
||||||
@ -179,34 +177,33 @@ namespace NadekoBot.Classes.Music {
|
|||||||
|
|
||||||
internal async Task Play(IAudioClient voiceClient, CancellationToken cancelToken) {
|
internal async Task Play(IAudioClient voiceClient, CancellationToken cancelToken) {
|
||||||
var t = BufferSong(cancelToken).ConfigureAwait(false);
|
var t = BufferSong(cancelToken).ConfigureAwait(false);
|
||||||
int bufferAttempts = 0;
|
var bufferAttempts = 0;
|
||||||
int waitPerAttempt = 500;
|
const int waitPerAttempt = 500;
|
||||||
int toAttemptTimes = SongInfo.ProviderType != MusicType.Normal ? 5 : 9;
|
var toAttemptTimes = SongInfo.ProviderType != MusicType.Normal ? 5 : 9;
|
||||||
while (!prebufferingComplete && bufferAttempts++ < toAttemptTimes) {
|
while (!prebufferingComplete && bufferAttempts++ < toAttemptTimes) {
|
||||||
await Task.Delay(waitPerAttempt, cancelToken);
|
await Task.Delay(waitPerAttempt, cancelToken);
|
||||||
}
|
}
|
||||||
cancelToken.ThrowIfCancellationRequested();
|
cancelToken.ThrowIfCancellationRequested();
|
||||||
Console.WriteLine($"Prebuffering done? in {waitPerAttempt * bufferAttempts}");
|
Console.WriteLine($"Prebuffering done? in {waitPerAttempt * bufferAttempts}");
|
||||||
int blockSize = 3840;
|
var blockSize = 3840;
|
||||||
byte[] buffer = new byte[blockSize];
|
var buffer = new byte[blockSize];
|
||||||
int attempt = 0;
|
var attempt = 0;
|
||||||
while (!cancelToken.IsCancellationRequested) {
|
while (!cancelToken.IsCancellationRequested) {
|
||||||
//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);
|
var read = songBuffer.Read(buffer, blockSize);
|
||||||
if (read == 0)
|
if (read == 0)
|
||||||
if (attempt++ == 20) {
|
if (attempt++ == 20) {
|
||||||
voiceClient.Wait();
|
voiceClient.Wait();
|
||||||
Console.WriteLine("Nothing to read.");
|
Console.WriteLine("Nothing to read.");
|
||||||
return;
|
return;
|
||||||
}
|
} else
|
||||||
else
|
await Task.Delay(50, cancelToken);
|
||||||
await Task.Delay(50);
|
|
||||||
else
|
else
|
||||||
attempt = 0;
|
attempt = 0;
|
||||||
|
|
||||||
while (this.MusicPlayer.Paused)
|
while (this.MusicPlayer.Paused)
|
||||||
await Task.Delay(200, cancelToken);
|
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();
|
cancelToken.ThrowIfCancellationRequested();
|
||||||
@ -220,11 +217,11 @@ namespace NadekoBot.Classes.Music {
|
|||||||
}
|
}
|
||||||
|
|
||||||
//stackoverflow ftw
|
//stackoverflow ftw
|
||||||
private byte[] adjustVolume(byte[] audioSamples, float volume) {
|
private static byte[] AdjustVolume(byte[] audioSamples, float volume) {
|
||||||
if (volume == 1.0f)
|
if (Math.Abs(volume - 1.0f) < 0.01f)
|
||||||
return audioSamples;
|
return audioSamples;
|
||||||
byte[] array = new byte[audioSamples.Length];
|
var array = new byte[audioSamples.Length];
|
||||||
for (int i = 0; i < array.Length; i += 2) {
|
for (var i = 0; i < array.Length; i += 2) {
|
||||||
|
|
||||||
// convert byte pair to int
|
// convert byte pair to int
|
||||||
short buf1 = audioSamples[i + 1];
|
short buf1 = audioSamples[i + 1];
|
||||||
@ -233,7 +230,7 @@ namespace NadekoBot.Classes.Music {
|
|||||||
buf1 = (short)((buf1 & 0xff) << 8);
|
buf1 = (short)((buf1 & 0xff) << 8);
|
||||||
buf2 = (short)(buf2 & 0xff);
|
buf2 = (short)(buf2 & 0xff);
|
||||||
|
|
||||||
short res = (short)(buf1 | buf2);
|
var res = (short)(buf1 | buf2);
|
||||||
res = (short)(res * volume);
|
res = (short)(res * volume);
|
||||||
|
|
||||||
// convert back
|
// convert back
|
||||||
@ -254,15 +251,15 @@ namespace NadekoBot.Classes.Music {
|
|||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
if (musicType == MusicType.Local) {
|
switch (musicType) {
|
||||||
|
case MusicType.Local:
|
||||||
return new Song(new SongInfo {
|
return new Song(new SongInfo {
|
||||||
Uri = "\"" + Path.GetFullPath(query) + "\"",
|
Uri = "\"" + Path.GetFullPath(query) + "\"",
|
||||||
Title = Path.GetFileNameWithoutExtension(query),
|
Title = Path.GetFileNameWithoutExtension(query),
|
||||||
Provider = "Local File",
|
Provider = "Local File",
|
||||||
ProviderType = musicType,
|
ProviderType = musicType,
|
||||||
});
|
});
|
||||||
}
|
case MusicType.Radio:
|
||||||
else if (musicType == MusicType.Radio) {
|
|
||||||
return new Song(new SongInfo {
|
return new Song(new SongInfo {
|
||||||
Uri = query,
|
Uri = query,
|
||||||
Title = $"{query}",
|
Title = $"{query}",
|
||||||
@ -270,7 +267,7 @@ namespace NadekoBot.Classes.Music {
|
|||||||
ProviderType = musicType,
|
ProviderType = musicType,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
else if (SoundCloud.Default.IsSoundCloudLink(query)) {
|
if (SoundCloud.Default.IsSoundCloudLink(query)) {
|
||||||
var svideo = await SoundCloud.Default.GetVideoAsync(query);
|
var svideo = await SoundCloud.Default.GetVideoAsync(query);
|
||||||
return new Song(new SongInfo {
|
return new Song(new SongInfo {
|
||||||
Title = svideo.FullName,
|
Title = svideo.FullName,
|
||||||
@ -279,7 +276,6 @@ namespace NadekoBot.Classes.Music {
|
|||||||
ProviderType = musicType,
|
ProviderType = musicType,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
else {
|
|
||||||
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.");
|
||||||
@ -298,10 +294,7 @@ namespace NadekoBot.Classes.Music {
|
|||||||
Uri = video.Uri,
|
Uri = video.Uri,
|
||||||
ProviderType = musicType,
|
ProviderType = musicType,
|
||||||
});
|
});
|
||||||
|
} catch (Exception ex) {
|
||||||
}
|
|
||||||
}
|
|
||||||
catch (Exception ex) {
|
|
||||||
Console.WriteLine($"Failed resolving the link.{ex.Message}");
|
Console.WriteLine($"Failed resolving the link.{ex.Message}");
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
@ -311,8 +304,7 @@ namespace NadekoBot.Classes.Music {
|
|||||||
string file = null;
|
string file = null;
|
||||||
try {
|
try {
|
||||||
file = await SearchHelper.GetResponseStringAsync(query);
|
file = await SearchHelper.GetResponseStringAsync(query);
|
||||||
}
|
} catch {
|
||||||
catch {
|
|
||||||
return query;
|
return query;
|
||||||
}
|
}
|
||||||
if (query.Contains(".pls")) {
|
if (query.Contains(".pls")) {
|
||||||
@ -322,13 +314,12 @@ namespace NadekoBot.Classes.Music {
|
|||||||
var m = Regex.Match(file, "File1=(?<url>.*?)\\n");
|
var m = Regex.Match(file, "File1=(?<url>.*?)\\n");
|
||||||
var res = m.Groups["url"]?.ToString();
|
var res = m.Groups["url"]?.ToString();
|
||||||
return res?.Trim();
|
return res?.Trim();
|
||||||
}
|
} catch {
|
||||||
catch {
|
|
||||||
Console.WriteLine($"Failed reading .pls:\n{file}");
|
Console.WriteLine($"Failed reading .pls:\n{file}");
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
else if (query.Contains(".m3u")) {
|
if (query.Contains(".m3u")) {
|
||||||
/*
|
/*
|
||||||
# This is a comment
|
# This is a comment
|
||||||
C:\xxx4xx\xxxxxx3x\xx2xxxx\xx.mp3
|
C:\xxx4xx\xxxxxx3x\xx2xxxx\xx.mp3
|
||||||
@ -338,26 +329,24 @@ namespace NadekoBot.Classes.Music {
|
|||||||
var m = Regex.Match(file, "(?<url>^[^#].*)", RegexOptions.Multiline);
|
var m = Regex.Match(file, "(?<url>^[^#].*)", RegexOptions.Multiline);
|
||||||
var res = m.Groups["url"]?.ToString();
|
var res = m.Groups["url"]?.ToString();
|
||||||
return res?.Trim();
|
return res?.Trim();
|
||||||
}
|
} catch {
|
||||||
catch {
|
|
||||||
Console.WriteLine($"Failed reading .m3u:\n{file}");
|
Console.WriteLine($"Failed reading .m3u:\n{file}");
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
else if (query.Contains(".asx")) {
|
if (query.Contains(".asx")) {
|
||||||
//<ref href="http://armitunes.com:8000"/>
|
//<ref href="http://armitunes.com:8000"/>
|
||||||
try {
|
try {
|
||||||
var m = Regex.Match(file, "<ref href=\"(?<url>.*?)\"");
|
var m = Regex.Match(file, "<ref href=\"(?<url>.*?)\"");
|
||||||
var res = m.Groups["url"]?.ToString();
|
var res = m.Groups["url"]?.ToString();
|
||||||
return res?.Trim();
|
return res?.Trim();
|
||||||
}
|
} catch {
|
||||||
catch {
|
|
||||||
Console.WriteLine($"Failed reading .asx:\n{file}");
|
Console.WriteLine($"Failed reading .asx:\n{file}");
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
else if (query.Contains(".xspf")) {
|
if (query.Contains(".xspf")) {
|
||||||
/*
|
/*
|
||||||
<?xml version="1.0" encoding="UTF-8"?>
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
<playlist version="1" xmlns="http://xspf.org/ns/0/">
|
<playlist version="1" xmlns="http://xspf.org/ns/0/">
|
||||||
@ -368,8 +357,7 @@ namespace NadekoBot.Classes.Music {
|
|||||||
var m = Regex.Match(file, "<location>(?<url>.*?)</location>");
|
var m = Regex.Match(file, "<location>(?<url>.*?)</location>");
|
||||||
var res = m.Groups["url"]?.ToString();
|
var res = m.Groups["url"]?.ToString();
|
||||||
return res?.Trim();
|
return res?.Trim();
|
||||||
}
|
} catch {
|
||||||
catch {
|
|
||||||
Console.WriteLine($"Failed reading .xspf:\n{file}");
|
Console.WriteLine($"Failed reading .xspf:\n{file}");
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
@ -15,8 +15,8 @@ namespace NadekoBot.Classes.Permissions {
|
|||||||
public PermissionChecker() {
|
public PermissionChecker() {
|
||||||
Task.Run(async () => {
|
Task.Run(async () => {
|
||||||
while (true) {
|
while (true) {
|
||||||
//blacklist is cleared every 1.3 seconds. That is the most time anyone will be blocked for ever
|
//blacklist is cleared every 1.75 seconds. That is the most time anyone will be blocked for ever
|
||||||
await Task.Delay(1300);
|
await Task.Delay(1750);
|
||||||
timeBlackList.Clear();
|
timeBlackList.Clear();
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
@ -45,7 +45,7 @@ namespace NadekoBot.Classes.Permissions {
|
|||||||
if (user.Server.Owner.Id == user.Id || (role != null && user.HasRole(role)))
|
if (user.Server.Owner.Id == user.Id || (role != null && user.HasRole(role)))
|
||||||
return true;
|
return true;
|
||||||
ServerPermissions perms;
|
ServerPermissions perms;
|
||||||
PermissionsHandler._permissionsDict.TryGetValue(user.Server.Id, out perms);
|
PermissionsHandler.PermissionsDict.TryGetValue(user.Server.Id, out perms);
|
||||||
throw new Exception($"You don't have the necessary role (**{(perms?.PermissionsControllerRole ?? "Nadeko")}**) to change permissions.");
|
throw new Exception($"You don't have the necessary role (**{(perms?.PermissionsControllerRole ?? "Nadeko")}**) to change permissions.");
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -83,11 +83,11 @@ namespace NadekoBot.Classes.Permissions {
|
|||||||
default:
|
default:
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
if (PermissionsHandler._permissionsDict[user.Server.Id].Verbose) //if verbose - print errors
|
if (PermissionsHandler.PermissionsDict[user.Server.Id].Verbose) //if verbose - print errors
|
||||||
error = msg;
|
error = msg;
|
||||||
return false;
|
return false;
|
||||||
} catch (Exception ex) {
|
} catch (Exception ex) {
|
||||||
if (PermissionsHandler._permissionsDict[user.Server.Id].Verbose) //if verbose - print errors
|
if (PermissionsHandler.PermissionsDict[user.Server.Id].Verbose) //if verbose - print errors
|
||||||
error = ex.Message;
|
error = ex.Message;
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
@ -4,12 +4,13 @@ using System.Collections.Concurrent;
|
|||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
using System.IO;
|
using System.IO;
|
||||||
using System.Linq;
|
using System.Linq;
|
||||||
|
using System.Threading;
|
||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
using Discord.Commands;
|
using Discord.Commands;
|
||||||
|
|
||||||
namespace NadekoBot.Classes.Permissions {
|
namespace NadekoBot.Classes.Permissions {
|
||||||
public static class PermissionsHandler {
|
public static class PermissionsHandler {
|
||||||
public static ConcurrentDictionary<ulong, ServerPermissions> _permissionsDict =
|
public static ConcurrentDictionary<ulong, ServerPermissions> PermissionsDict =
|
||||||
new ConcurrentDictionary<ulong, ServerPermissions>();
|
new ConcurrentDictionary<ulong, ServerPermissions>();
|
||||||
|
|
||||||
public enum PermissionBanType {
|
public enum PermissionBanType {
|
||||||
@ -25,19 +26,18 @@ namespace NadekoBot.Classes.Permissions {
|
|||||||
foreach (var file in Directory.EnumerateFiles("data/permissions/")) {
|
foreach (var file in Directory.EnumerateFiles("data/permissions/")) {
|
||||||
try {
|
try {
|
||||||
var strippedFileName = Path.GetFileNameWithoutExtension(file);
|
var strippedFileName = Path.GetFileNameWithoutExtension(file);
|
||||||
|
if (string.IsNullOrWhiteSpace(strippedFileName)) continue;
|
||||||
var id = ulong.Parse(strippedFileName);
|
var id = ulong.Parse(strippedFileName);
|
||||||
var data = Newtonsoft.Json.JsonConvert.DeserializeObject<ServerPermissions>(File.ReadAllText(file));
|
var data = Newtonsoft.Json.JsonConvert.DeserializeObject<ServerPermissions>(File.ReadAllText(file));
|
||||||
_permissionsDict.TryAdd(id, data);
|
PermissionsDict.TryAdd(id, data);
|
||||||
} catch (Exception ex) {
|
} catch { }
|
||||||
//Console.WriteLine($"Failed getting server with id: {file}\nReason: {ex.Message}");
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
Console.WriteLine("Permission initialization complete.");
|
Console.WriteLine("Permission initialization complete.");
|
||||||
}
|
}
|
||||||
|
|
||||||
internal static Permissions GetRolePermissionsById(Server server, ulong id) {
|
internal static Permissions GetRolePermissionsById(Server server, ulong id) {
|
||||||
ServerPermissions serverPerms;
|
ServerPermissions serverPerms;
|
||||||
if (!_permissionsDict.TryGetValue(server.Id, out serverPerms))
|
if (!PermissionsDict.TryGetValue(server.Id, out serverPerms))
|
||||||
return null;
|
return null;
|
||||||
|
|
||||||
Permissions toReturn;
|
Permissions toReturn;
|
||||||
@ -47,7 +47,7 @@ namespace NadekoBot.Classes.Permissions {
|
|||||||
|
|
||||||
internal static Permissions GetUserPermissionsById(Server server, ulong id) {
|
internal static Permissions GetUserPermissionsById(Server server, ulong id) {
|
||||||
ServerPermissions serverPerms;
|
ServerPermissions serverPerms;
|
||||||
if (!_permissionsDict.TryGetValue(server.Id, out serverPerms))
|
if (!PermissionsDict.TryGetValue(server.Id, out serverPerms))
|
||||||
return null;
|
return null;
|
||||||
|
|
||||||
Permissions toReturn;
|
Permissions toReturn;
|
||||||
@ -57,7 +57,7 @@ namespace NadekoBot.Classes.Permissions {
|
|||||||
|
|
||||||
internal static Permissions GetChannelPermissionsById(Server server, ulong id) {
|
internal static Permissions GetChannelPermissionsById(Server server, ulong id) {
|
||||||
ServerPermissions serverPerms;
|
ServerPermissions serverPerms;
|
||||||
if (!_permissionsDict.TryGetValue(server.Id, out serverPerms))
|
if (!PermissionsDict.TryGetValue(server.Id, out serverPerms))
|
||||||
return null;
|
return null;
|
||||||
|
|
||||||
Permissions toReturn;
|
Permissions toReturn;
|
||||||
@ -67,32 +67,29 @@ namespace NadekoBot.Classes.Permissions {
|
|||||||
|
|
||||||
internal static Permissions GetServerPermissions(Server server) {
|
internal static Permissions GetServerPermissions(Server server) {
|
||||||
ServerPermissions serverPerms;
|
ServerPermissions serverPerms;
|
||||||
if (!_permissionsDict.TryGetValue(server.Id, out serverPerms))
|
return !PermissionsDict.TryGetValue(server.Id, out serverPerms) ? null : serverPerms.Permissions;
|
||||||
return null;
|
|
||||||
|
|
||||||
return serverPerms.Permissions;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
internal static PermissionBanType GetPermissionBanType(Command command, User user, Channel channel) {
|
internal static PermissionBanType GetPermissionBanType(Command command, User user, Channel channel) {
|
||||||
var server = user.Server;
|
var server = user.Server;
|
||||||
ServerPermissions serverPerms;
|
ServerPermissions serverPerms;
|
||||||
if (!_permissionsDict.TryGetValue(server.Id,out serverPerms)) {
|
if (!PermissionsDict.TryGetValue(server.Id, out serverPerms)) {
|
||||||
serverPerms = new ServerPermissions(server.Id, server.Name);
|
serverPerms = new ServerPermissions(server.Id, server.Name);
|
||||||
_permissionsDict.TryAdd(server.Id, serverPerms);
|
PermissionsDict.TryAdd(server.Id, serverPerms);
|
||||||
}
|
}
|
||||||
bool val;
|
bool val;
|
||||||
Permissions perm;
|
Permissions perm;
|
||||||
//server
|
//server
|
||||||
if (serverPerms.Permissions.modules.TryGetValue(command.Category, out val) && val == false)
|
if (serverPerms.Permissions.Modules.TryGetValue(command.Category, out val) && val == false)
|
||||||
return PermissionBanType.ServerBanModule;
|
return PermissionBanType.ServerBanModule;
|
||||||
if (serverPerms.Permissions.commands.TryGetValue(command.Text, out val) && val == false)
|
if (serverPerms.Permissions.Commands.TryGetValue(command.Text, out val) && val == false)
|
||||||
return PermissionBanType.ServerBanCommand;
|
return PermissionBanType.ServerBanCommand;
|
||||||
//channel
|
//channel
|
||||||
if (serverPerms.ChannelPermissions.TryGetValue(channel.Id, out perm) &&
|
if (serverPerms.ChannelPermissions.TryGetValue(channel.Id, out perm) &&
|
||||||
perm.modules.TryGetValue(command.Category, out val) && val == false)
|
perm.Modules.TryGetValue(command.Category, out val) && val == false)
|
||||||
return PermissionBanType.ChannelBanModule;
|
return PermissionBanType.ChannelBanModule;
|
||||||
if (serverPerms.ChannelPermissions.TryGetValue(channel.Id, out perm) &&
|
if (serverPerms.ChannelPermissions.TryGetValue(channel.Id, out perm) &&
|
||||||
perm.commands.TryGetValue(command.Text, out val) && val == false)
|
perm.Commands.TryGetValue(command.Text, out val) && val == false)
|
||||||
return PermissionBanType.ChannelBanCommand;
|
return PermissionBanType.ChannelBanCommand;
|
||||||
|
|
||||||
//ROLE PART - TWO CASES
|
//ROLE PART - TWO CASES
|
||||||
@ -101,17 +98,15 @@ namespace NadekoBot.Classes.Permissions {
|
|||||||
// THAT MEANS USER CANNOT RUN THIS COMMAND
|
// THAT MEANS USER CANNOT RUN THIS COMMAND
|
||||||
// IF AT LEAST ONE ROLE EXIST THAT IS NOT BANNED,
|
// IF AT LEAST ONE ROLE EXIST THAT IS NOT BANNED,
|
||||||
// USER CAN RUN THE COMMAND
|
// USER CAN RUN THE COMMAND
|
||||||
bool foundNotBannedRole = false;
|
var foundNotBannedRole = false;
|
||||||
foreach (var role in user.Roles) {
|
foreach (var role in user.Roles) {
|
||||||
//if every role is banned from using the module -> rolebanmodule
|
//if every role is banned from using the module -> rolebanmodule
|
||||||
if (serverPerms.RolePermissions.TryGetValue(role.Id, out perm) &&
|
if (serverPerms.RolePermissions.TryGetValue(role.Id, out perm) &&
|
||||||
perm.modules.TryGetValue(command.Category, out val) && val == false)
|
perm.Modules.TryGetValue(command.Category, out val) && val == false)
|
||||||
continue;
|
continue;
|
||||||
else {
|
|
||||||
foundNotBannedRole = true;
|
foundNotBannedRole = true;
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
}
|
|
||||||
if (!foundNotBannedRole)
|
if (!foundNotBannedRole)
|
||||||
return PermissionBanType.RoleBanModule;
|
return PermissionBanType.RoleBanModule;
|
||||||
|
|
||||||
@ -124,7 +119,7 @@ namespace NadekoBot.Classes.Permissions {
|
|||||||
foreach (var role in user.Roles) {
|
foreach (var role in user.Roles) {
|
||||||
//if every role is banned from using the module -> rolebanmodule
|
//if every role is banned from using the module -> rolebanmodule
|
||||||
if (serverPerms.RolePermissions.TryGetValue(role.Id, out perm) &&
|
if (serverPerms.RolePermissions.TryGetValue(role.Id, out perm) &&
|
||||||
perm.commands.TryGetValue(command.Text, out val) && val == false)
|
perm.Commands.TryGetValue(command.Text, out val) && val == false)
|
||||||
continue;
|
continue;
|
||||||
else {
|
else {
|
||||||
foundNotBannedRole = true;
|
foundNotBannedRole = true;
|
||||||
@ -136,169 +131,175 @@ namespace NadekoBot.Classes.Permissions {
|
|||||||
|
|
||||||
//user
|
//user
|
||||||
if (serverPerms.UserPermissions.TryGetValue(user.Id, out perm) &&
|
if (serverPerms.UserPermissions.TryGetValue(user.Id, out perm) &&
|
||||||
perm.modules.TryGetValue(command.Category, out val) && val == false)
|
perm.Modules.TryGetValue(command.Category, out val) && val == false)
|
||||||
return PermissionBanType.UserBanModule;
|
return PermissionBanType.UserBanModule;
|
||||||
if (serverPerms.UserPermissions.TryGetValue(user.Id, out perm) &&
|
if (serverPerms.UserPermissions.TryGetValue(user.Id, out perm) &&
|
||||||
perm.commands.TryGetValue(command.Text, out val) && val == false)
|
perm.Commands.TryGetValue(command.Text, out val) && val == false)
|
||||||
return PermissionBanType.UserBanCommand;
|
return PermissionBanType.UserBanCommand;
|
||||||
|
|
||||||
return PermissionBanType.None;
|
return PermissionBanType.None;
|
||||||
}
|
}
|
||||||
|
|
||||||
private static void WriteServerToJson(ulong serverId) {
|
private static void WriteServerToJson(ServerPermissions serverPerms) {
|
||||||
string pathToFile = $"data/permissions/{serverId}.json";
|
string pathToFile = $"data/permissions/{serverPerms}.json";
|
||||||
File.WriteAllText(pathToFile, Newtonsoft.Json.JsonConvert.SerializeObject(_permissionsDict[serverId], Newtonsoft.Json.Formatting.Indented));
|
File.WriteAllText(pathToFile,
|
||||||
|
Newtonsoft.Json.JsonConvert.SerializeObject(serverPerms, Newtonsoft.Json.Formatting.Indented));
|
||||||
}
|
}
|
||||||
|
|
||||||
public static void WriteToJson() {
|
public static void WriteToJson() {
|
||||||
Directory.CreateDirectory("data/permissions/");
|
Directory.CreateDirectory("data/permissions/");
|
||||||
foreach (var kvp in _permissionsDict) {
|
foreach (var kvp in PermissionsDict) {
|
||||||
WriteServerToJson(kvp.Key);
|
WriteServerToJson(kvp.Value);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public static string GetServerPermissionsRoleName(Server server) {
|
public static string GetServerPermissionsRoleName(Server server) {
|
||||||
ServerPermissions serverPerms = _permissionsDict.GetOrAdd(server.Id,
|
var serverPerms = PermissionsDict.GetOrAdd(server.Id,
|
||||||
serverPerms = new ServerPermissions(server.Id, server.Name));
|
new ServerPermissions(server.Id, server.Name));
|
||||||
|
|
||||||
return serverPerms.PermissionsControllerRole;
|
return serverPerms.PermissionsControllerRole;
|
||||||
}
|
}
|
||||||
|
|
||||||
internal static void SetPermissionsRole(Server server, string roleName) {
|
internal static void SetPermissionsRole(Server server, string roleName) {
|
||||||
ServerPermissions serverPerms = _permissionsDict.GetOrAdd(server.Id,
|
var serverPerms = PermissionsDict.GetOrAdd(server.Id,
|
||||||
serverPerms = new ServerPermissions(server.Id, server.Name));
|
new ServerPermissions(server.Id, server.Name));
|
||||||
|
|
||||||
serverPerms.PermissionsControllerRole = roleName;
|
serverPerms.PermissionsControllerRole = roleName;
|
||||||
Task.Run(() => WriteServerToJson(server.Id));
|
Task.Run(() => WriteServerToJson(serverPerms));
|
||||||
}
|
}
|
||||||
|
|
||||||
internal static void SetVerbosity(Server server, bool val) {
|
internal static void SetVerbosity(Server server, bool val) {
|
||||||
ServerPermissions serverPerms = _permissionsDict.GetOrAdd(server.Id,
|
var serverPerms = PermissionsDict.GetOrAdd(server.Id,
|
||||||
serverPerms = new ServerPermissions(server.Id, server.Name));
|
new ServerPermissions(server.Id, server.Name));
|
||||||
|
|
||||||
serverPerms.Verbose = val;
|
serverPerms.Verbose = val;
|
||||||
Task.Run(() => WriteServerToJson(server.Id));
|
Task.Run(() => WriteServerToJson(serverPerms));
|
||||||
}
|
}
|
||||||
|
|
||||||
public static void SetServerModulePermission(Server server, string moduleName, bool value) {
|
public static void SetServerModulePermission(Server server, string moduleName, bool value) {
|
||||||
ServerPermissions serverPerms = _permissionsDict.GetOrAdd(server.Id,
|
var serverPerms = PermissionsDict.GetOrAdd(server.Id,
|
||||||
serverPerms = new ServerPermissions(server.Id, server.Name));
|
new ServerPermissions(server.Id, server.Name));
|
||||||
var modules = serverPerms.Permissions.modules;
|
|
||||||
|
var modules = serverPerms.Permissions.Modules;
|
||||||
if (modules.ContainsKey(moduleName))
|
if (modules.ContainsKey(moduleName))
|
||||||
modules[moduleName] = value;
|
modules[moduleName] = value;
|
||||||
else
|
else
|
||||||
modules.Add(moduleName, value);
|
modules.Add(moduleName, value);
|
||||||
Task.Run(() => WriteServerToJson(server.Id));
|
Task.Run(() => WriteServerToJson(serverPerms));
|
||||||
}
|
}
|
||||||
|
|
||||||
public static void SetServerCommandPermission(Server server, string commandName, bool value) {
|
public static void SetServerCommandPermission(Server server, string commandName, bool value) {
|
||||||
ServerPermissions serverPerms = _permissionsDict.GetOrAdd(server.Id,
|
var serverPerms = PermissionsDict.GetOrAdd(server.Id,
|
||||||
serverPerms = new ServerPermissions(server.Id, server.Name));
|
new ServerPermissions(server.Id, server.Name));
|
||||||
var commands = serverPerms.Permissions.commands;
|
|
||||||
|
var commands = serverPerms.Permissions.Commands;
|
||||||
if (commands.ContainsKey(commandName))
|
if (commands.ContainsKey(commandName))
|
||||||
commands[commandName] = value;
|
commands[commandName] = value;
|
||||||
else
|
else
|
||||||
commands.Add(commandName, value);
|
commands.Add(commandName, value);
|
||||||
Task.Run(() => WriteServerToJson(server.Id));
|
Task.Run(() => WriteServerToJson(serverPerms));
|
||||||
}
|
}
|
||||||
|
|
||||||
public static void SetChannelModulePermission(Channel channel, string moduleName, bool value) {
|
public static void SetChannelModulePermission(Channel channel, string moduleName, bool value) {
|
||||||
var server = channel.Server;
|
var server = channel.Server;
|
||||||
|
|
||||||
ServerPermissions serverPerms = _permissionsDict.GetOrAdd(server.Id,
|
var serverPerms = PermissionsDict.GetOrAdd(server.Id,
|
||||||
serverPerms = new ServerPermissions(server.Id, server.Name));
|
new ServerPermissions(server.Id, server.Name));
|
||||||
|
|
||||||
if (!serverPerms.ChannelPermissions.ContainsKey(channel.Id))
|
if (!serverPerms.ChannelPermissions.ContainsKey(channel.Id))
|
||||||
serverPerms.ChannelPermissions.Add(channel.Id, new Permissions(channel.Name));
|
serverPerms.ChannelPermissions.Add(channel.Id, new Permissions(channel.Name));
|
||||||
|
|
||||||
var modules = serverPerms.ChannelPermissions[channel.Id].modules;
|
var modules = serverPerms.ChannelPermissions[channel.Id].Modules;
|
||||||
|
|
||||||
if (modules.ContainsKey(moduleName))
|
if (modules.ContainsKey(moduleName))
|
||||||
modules[moduleName] = value;
|
modules[moduleName] = value;
|
||||||
else
|
else
|
||||||
modules.Add(moduleName, value);
|
modules.Add(moduleName, value);
|
||||||
Task.Run(() => WriteServerToJson(server.Id));
|
Task.Run(() => WriteServerToJson(serverPerms));
|
||||||
}
|
}
|
||||||
|
|
||||||
public static void SetChannelCommandPermission(Channel channel, string commandName, bool value) {
|
public static void SetChannelCommandPermission(Channel channel, string commandName, bool value) {
|
||||||
var server = channel.Server;
|
var server = channel.Server;
|
||||||
ServerPermissions serverPerms = _permissionsDict.GetOrAdd(server.Id,
|
var serverPerms = PermissionsDict.GetOrAdd(server.Id,
|
||||||
serverPerms = new ServerPermissions(server.Id, server.Name));
|
new ServerPermissions(server.Id, server.Name));
|
||||||
|
|
||||||
if (!serverPerms.ChannelPermissions.ContainsKey(channel.Id))
|
if (!serverPerms.ChannelPermissions.ContainsKey(channel.Id))
|
||||||
serverPerms.ChannelPermissions.Add(channel.Id, new Permissions(channel.Name));
|
serverPerms.ChannelPermissions.Add(channel.Id, new Permissions(channel.Name));
|
||||||
|
|
||||||
var commands = serverPerms.ChannelPermissions[channel.Id].commands;
|
var commands = serverPerms.ChannelPermissions[channel.Id].Commands;
|
||||||
|
|
||||||
if (commands.ContainsKey(commandName))
|
if (commands.ContainsKey(commandName))
|
||||||
commands[commandName] = value;
|
commands[commandName] = value;
|
||||||
else
|
else
|
||||||
commands.Add(commandName, value);
|
commands.Add(commandName, value);
|
||||||
Task.Run(() => WriteServerToJson(server.Id));
|
Task.Run(() => WriteServerToJson(serverPerms));
|
||||||
}
|
}
|
||||||
|
|
||||||
public static void SetRoleModulePermission(Role role, string moduleName, bool value) {
|
public static void SetRoleModulePermission(Role role, string moduleName, bool value) {
|
||||||
var server = role.Server;
|
var server = role.Server;
|
||||||
ServerPermissions serverPerms = _permissionsDict.GetOrAdd(server.Id,
|
var serverPerms = PermissionsDict.GetOrAdd(server.Id,
|
||||||
serverPerms = new ServerPermissions(server.Id, server.Name));
|
new ServerPermissions(server.Id, server.Name));
|
||||||
|
|
||||||
if (!serverPerms.RolePermissions.ContainsKey(role.Id))
|
if (!serverPerms.RolePermissions.ContainsKey(role.Id))
|
||||||
serverPerms.RolePermissions.Add(role.Id, new Permissions(role.Name));
|
serverPerms.RolePermissions.Add(role.Id, new Permissions(role.Name));
|
||||||
|
|
||||||
var modules = serverPerms.RolePermissions[role.Id].modules;
|
var modules = serverPerms.RolePermissions[role.Id].Modules;
|
||||||
|
|
||||||
if (modules.ContainsKey(moduleName))
|
if (modules.ContainsKey(moduleName))
|
||||||
modules[moduleName] = value;
|
modules[moduleName] = value;
|
||||||
else
|
else
|
||||||
modules.Add(moduleName, value);
|
modules.Add(moduleName, value);
|
||||||
Task.Run(() => WriteServerToJson(server.Id));
|
Task.Run(() => WriteServerToJson(serverPerms));
|
||||||
}
|
}
|
||||||
|
|
||||||
public static void SetRoleCommandPermission(Role role, string commandName, bool value) {
|
public static void SetRoleCommandPermission(Role role, string commandName, bool value) {
|
||||||
var server = role.Server;
|
var server = role.Server;
|
||||||
ServerPermissions serverPerms = _permissionsDict.GetOrAdd(server.Id,
|
var serverPerms = PermissionsDict.GetOrAdd(server.Id,
|
||||||
serverPerms = new ServerPermissions(server.Id, server.Name));
|
new ServerPermissions(server.Id, server.Name));
|
||||||
|
|
||||||
if (!serverPerms.RolePermissions.ContainsKey(role.Id))
|
if (!serverPerms.RolePermissions.ContainsKey(role.Id))
|
||||||
serverPerms.RolePermissions.Add(role.Id, new Permissions(role.Name));
|
serverPerms.RolePermissions.Add(role.Id, new Permissions(role.Name));
|
||||||
|
|
||||||
var commands = serverPerms.RolePermissions[role.Id].commands;
|
var commands = serverPerms.RolePermissions[role.Id].Commands;
|
||||||
|
|
||||||
if (commands.ContainsKey(commandName))
|
if (commands.ContainsKey(commandName))
|
||||||
commands[commandName] = value;
|
commands[commandName] = value;
|
||||||
else
|
else
|
||||||
commands.Add(commandName, value);
|
commands.Add(commandName, value);
|
||||||
Task.Run(() => WriteServerToJson(server.Id));
|
Task.Run(() => WriteServerToJson(serverPerms));
|
||||||
}
|
}
|
||||||
|
|
||||||
public static void SetUserModulePermission(User user, string moduleName, bool value) {
|
public static void SetUserModulePermission(User user, string moduleName, bool value) {
|
||||||
var server = user.Server;
|
var server = user.Server;
|
||||||
ServerPermissions serverPerms = _permissionsDict.GetOrAdd(server.Id,
|
var serverPerms = PermissionsDict.GetOrAdd(server.Id,
|
||||||
serverPerms = new ServerPermissions(server.Id, server.Name));
|
new ServerPermissions(server.Id, server.Name));
|
||||||
|
|
||||||
if (!serverPerms.UserPermissions.ContainsKey(user.Id))
|
if (!serverPerms.UserPermissions.ContainsKey(user.Id))
|
||||||
serverPerms.UserPermissions.Add(user.Id, new Permissions(user.Name));
|
serverPerms.UserPermissions.Add(user.Id, new Permissions(user.Name));
|
||||||
|
|
||||||
var modules = serverPerms.UserPermissions[user.Id].modules;
|
var modules = serverPerms.UserPermissions[user.Id].Modules;
|
||||||
|
|
||||||
if (modules.ContainsKey(moduleName))
|
if (modules.ContainsKey(moduleName))
|
||||||
modules[moduleName] = value;
|
modules[moduleName] = value;
|
||||||
else
|
else
|
||||||
modules.Add(moduleName, value);
|
modules.Add(moduleName, value);
|
||||||
Task.Run(() => WriteServerToJson(server.Id));
|
Task.Run(() => WriteServerToJson(serverPerms));
|
||||||
}
|
}
|
||||||
|
|
||||||
public static void SetUserCommandPermission(User user, string commandName, bool value) {
|
public static void SetUserCommandPermission(User user, string commandName, bool value) {
|
||||||
var server = user.Server;
|
var server = user.Server;
|
||||||
ServerPermissions serverPerms = _permissionsDict.GetOrAdd(server.Id,
|
var serverPerms = PermissionsDict.GetOrAdd(server.Id,
|
||||||
serverPerms = new ServerPermissions(server.Id, server.Name));
|
new ServerPermissions(server.Id, server.Name));
|
||||||
if (!serverPerms.UserPermissions.ContainsKey(user.Id))
|
if (!serverPerms.UserPermissions.ContainsKey(user.Id))
|
||||||
serverPerms.UserPermissions.Add(user.Id, new Permissions(user.Name));
|
serverPerms.UserPermissions.Add(user.Id, new Permissions(user.Name));
|
||||||
|
|
||||||
var commands = serverPerms.UserPermissions[user.Id].commands;
|
var commands = serverPerms.UserPermissions[user.Id].Commands;
|
||||||
|
|
||||||
if (commands.ContainsKey(commandName))
|
if (commands.ContainsKey(commandName))
|
||||||
commands[commandName] = value;
|
commands[commandName] = value;
|
||||||
else
|
else
|
||||||
commands.Add(commandName, value);
|
commands.Add(commandName, value);
|
||||||
Task.Run(() => WriteServerToJson(server.Id));
|
Task.Run(() => WriteServerToJson(serverPerms));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
/// <summary>
|
/// <summary>
|
||||||
@ -312,33 +313,31 @@ namespace NadekoBot.Classes.Permissions {
|
|||||||
/// <summary>
|
/// <summary>
|
||||||
/// Module name with allowed/disallowed
|
/// Module name with allowed/disallowed
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public Dictionary<string, bool> modules { get; set; }
|
public Dictionary<string, bool> Modules { get; set; }
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Command name with allowed/disallowed
|
/// Command name with allowed/disallowed
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public Dictionary<string, bool> commands { get; set; }
|
public Dictionary<string, bool> Commands { get; set; }
|
||||||
|
|
||||||
public Permissions(string name) {
|
public Permissions(string name) {
|
||||||
Name = name;
|
Name = name;
|
||||||
modules = new Dictionary<string, bool>();
|
Modules = new Dictionary<string, bool>();
|
||||||
commands = new Dictionary<string, bool>();
|
Commands = new Dictionary<string, bool>();
|
||||||
}
|
}
|
||||||
|
|
||||||
public override string ToString() {
|
public override string ToString() {
|
||||||
string toReturn = "";
|
var toReturn = "";
|
||||||
var bannedModules = modules.Where(kvp => kvp.Value == false);
|
var bannedModules = Modules.Where(kvp => kvp.Value == false);
|
||||||
if (bannedModules.Count() > 0) {
|
var bannedModulesArray = bannedModules as KeyValuePair<string, bool>[] ?? bannedModules.ToArray();
|
||||||
|
if (bannedModulesArray.Any()) {
|
||||||
toReturn += "`Banned Modules:`\n";
|
toReturn += "`Banned Modules:`\n";
|
||||||
foreach (var m in bannedModules) {
|
toReturn = bannedModulesArray.Aggregate(toReturn, (current, m) => current + $"\t`[x] {m.Key}`\n");
|
||||||
toReturn += $"\t`[x] {m.Key}`\n";
|
|
||||||
}
|
}
|
||||||
}
|
var bannedCommands = Commands.Where(kvp => kvp.Value == false);
|
||||||
var bannedCommands = commands.Where(kvp => kvp.Value == false);
|
var bannedCommandsArr = bannedCommands as KeyValuePair<string, bool>[] ?? bannedCommands.ToArray();
|
||||||
if (bannedCommands.Count() > 0) {
|
if (bannedCommandsArr.Any()) {
|
||||||
toReturn += "`Banned Commands:`\n";
|
toReturn += "`Banned Commands:`\n";
|
||||||
foreach (var c in bannedCommands) {
|
toReturn = bannedCommandsArr.Aggregate(toReturn, (current, c) => current + $"\t`[x] {c.Key}`\n");
|
||||||
toReturn += $"\t`[x] {c.Key}`\n";
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
return toReturn;
|
return toReturn;
|
||||||
}
|
}
|
||||||
|
@ -20,18 +20,18 @@ namespace NadekoBot.Classes {
|
|||||||
|
|
||||||
public static class SearchHelper {
|
public static class SearchHelper {
|
||||||
private static DateTime lastRefreshed = DateTime.MinValue;
|
private static DateTime lastRefreshed = DateTime.MinValue;
|
||||||
private static string token = "";
|
private static string token { get; set; } = "";
|
||||||
|
|
||||||
public static async Task<Stream> GetResponseStreamAsync(string url,
|
public static async Task<Stream> GetResponseStreamAsync(string url,
|
||||||
IEnumerable<KeyValuePair<string, string>> headers = null, RequestHttpMethod method = RequestHttpMethod.Get) {
|
IEnumerable<KeyValuePair<string, string>> headers = null, RequestHttpMethod method = RequestHttpMethod.Get) {
|
||||||
if (string.IsNullOrWhiteSpace(url))
|
if (string.IsNullOrWhiteSpace(url))
|
||||||
throw new ArgumentNullException(nameof(url));
|
throw new ArgumentNullException(nameof(url));
|
||||||
using (var httpClient = new HttpClient()) {
|
var httpClient = new HttpClient();
|
||||||
switch (method) {
|
switch (method) {
|
||||||
case RequestHttpMethod.Get:
|
case RequestHttpMethod.Get:
|
||||||
if (headers != null) {
|
if (headers != null) {
|
||||||
foreach (var header in headers) {
|
foreach (var header in headers) {
|
||||||
httpClient.DefaultRequestHeaders.Add(header.Key, header.Value);
|
httpClient.DefaultRequestHeaders.TryAddWithoutValidation(header.Key, header.Value);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return await httpClient.GetStreamAsync(url);
|
return await httpClient.GetStreamAsync(url);
|
||||||
@ -46,7 +46,6 @@ namespace NadekoBot.Classes {
|
|||||||
throw new NotImplementedException("That type of request is unsupported.");
|
throw new NotImplementedException("That type of request is unsupported.");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
public static async Task<string> GetResponseStringAsync(string url,
|
public static async Task<string> GetResponseStringAsync(string url,
|
||||||
IEnumerable<KeyValuePair<string, string>> headers = null,
|
IEnumerable<KeyValuePair<string, string>> headers = null,
|
||||||
@ -64,13 +63,19 @@ namespace NadekoBot.Classes {
|
|||||||
await RefreshAnilistToken();
|
await RefreshAnilistToken();
|
||||||
|
|
||||||
var link = "http://anilist.co/api/anime/search/" + Uri.EscapeUriString(query);
|
var link = "http://anilist.co/api/anime/search/" + Uri.EscapeUriString(query);
|
||||||
|
try {
|
||||||
var headers = new Dictionary<string, string> { { "access_token", token } };
|
var headers = new Dictionary<string, string> {{"'access_token'", "'"+token+"'"}};
|
||||||
var smallContent = await GetResponseStringAsync(link, headers);
|
var smallContent = await GetResponseStringAsync(link, headers);
|
||||||
var smallObj = JArray.Parse(smallContent)[0];
|
var smallObj = JArray.Parse(smallContent)[0];
|
||||||
var content = await GetResponseStringAsync("http://anilist.co/api/anime/" + smallObj["id"], headers);
|
var content = await GetResponseStringAsync("http://anilist.co/api/anime/" + smallObj["id"], headers);
|
||||||
|
|
||||||
return await Task.Run(() => JsonConvert.DeserializeObject<AnimeResult>(content));
|
return await Task.Run(() => JsonConvert.DeserializeObject<AnimeResult>(content));
|
||||||
|
|
||||||
|
}
|
||||||
|
catch (Exception ex) {
|
||||||
|
Console.WriteLine(ex);
|
||||||
|
return new AnimeResult();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public static async Task<MangaResult> GetMangaQueryResultLink(string query) {
|
public static async Task<MangaResult> GetMangaQueryResultLink(string query) {
|
||||||
@ -90,6 +95,11 @@ namespace NadekoBot.Classes {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private static async Task RefreshAnilistToken() {
|
private static async Task RefreshAnilistToken() {
|
||||||
|
if (DateTime.Now - lastRefreshed > TimeSpan.FromMinutes(29))
|
||||||
|
lastRefreshed=DateTime.Now;
|
||||||
|
else {
|
||||||
|
return;
|
||||||
|
}
|
||||||
var headers = new Dictionary<string, string> {
|
var headers = new Dictionary<string, string> {
|
||||||
{"grant_type", "client_credentials"},
|
{"grant_type", "client_credentials"},
|
||||||
{"client_id", "kwoth-w0ki9"},
|
{"client_id", "kwoth-w0ki9"},
|
||||||
|
@ -5,6 +5,7 @@ using System.Text;
|
|||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
using Discord.Commands;
|
using Discord.Commands;
|
||||||
using System.Drawing;
|
using System.Drawing;
|
||||||
|
using NadekoBot.Classes;
|
||||||
using NadekoBot.Extensions;
|
using NadekoBot.Extensions;
|
||||||
using Newtonsoft.Json.Linq;
|
using Newtonsoft.Json.Linq;
|
||||||
|
|
||||||
@ -31,12 +32,11 @@ namespace NadekoBot.Commands {
|
|||||||
CachedChampionImages = CachedChampionImages
|
CachedChampionImages = CachedChampionImages
|
||||||
.Where(kvp => DateTime.Now - kvp.Value.AddedAt > new TimeSpan(1, 0, 0))
|
.Where(kvp => DateTime.Now - kvp.Value.AddedAt > new TimeSpan(1, 0, 0))
|
||||||
.ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
|
.ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
|
||||||
}
|
} catch { }
|
||||||
catch { }
|
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
private string[] trashTalk = new[] { "Better ban your counters. You are going to carry the game anyway.",
|
private readonly string[] trashTalk = { "Better ban your counters. You are going to carry the game anyway.",
|
||||||
"Go with the flow. Don't think. Just ban one of these.",
|
"Go with the flow. Don't think. Just ban one of these.",
|
||||||
"DONT READ BELOW! Ban Urgot mid OP 100%. Im smurf Diamond 1.",
|
"DONT READ BELOW! Ban Urgot mid OP 100%. Im smurf Diamond 1.",
|
||||||
"Ask your teammates what would they like to play, and ban that.",
|
"Ask your teammates what would they like to play, and ban that.",
|
||||||
@ -63,15 +63,14 @@ namespace NadekoBot.Commands {
|
|||||||
.Do(async e => {
|
.Do(async e => {
|
||||||
try {
|
try {
|
||||||
//get role
|
//get role
|
||||||
string role = ResolvePos(e.GetArg("position"));
|
var role = ResolvePos(e.GetArg("position"));
|
||||||
string resolvedRole = role;
|
var resolvedRole = role;
|
||||||
var name = e.GetArg("champ").Replace(" ", "");
|
var name = e.GetArg("champ").Replace(" ", "");
|
||||||
CachedChampion champ = null;
|
CachedChampion champ = null;
|
||||||
lock (cacheLock) {
|
lock (cacheLock) {
|
||||||
CachedChampionImages.TryGetValue(name + "_" + resolvedRole, out champ);
|
CachedChampionImages.TryGetValue(name + "_" + resolvedRole, out champ);
|
||||||
}
|
}
|
||||||
if (champ != null) {
|
if (champ != null) {
|
||||||
Console.WriteLine("Sending lol image from cache.");
|
|
||||||
champ.ImageStream.Position = 0;
|
champ.ImageStream.Position = 0;
|
||||||
await e.Channel.SendFile("champ.png", champ.ImageStream);
|
await e.Channel.SendFile("champ.png", champ.ImageStream);
|
||||||
return;
|
return;
|
||||||
@ -79,7 +78,7 @@ namespace NadekoBot.Commands {
|
|||||||
var allData = JArray.Parse(await Classes.SearchHelper.GetResponseStringAsync($"http://api.champion.gg/champion/{name}?api_key={NadekoBot.Creds.LOLAPIKey}"));
|
var allData = JArray.Parse(await Classes.SearchHelper.GetResponseStringAsync($"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 (var i = 0; i < allData.Count; i++) {
|
||||||
if (allData[i]["role"].ToString().Equals(role)) {
|
if (allData[i]["role"].ToString().Equals(role)) {
|
||||||
data = allData[i];
|
data = allData[i];
|
||||||
break;
|
break;
|
||||||
@ -89,8 +88,7 @@ namespace NadekoBot.Commands {
|
|||||||
await e.Channel.SendMessage("💢 Data for that role does not exist.");
|
await e.Channel.SendMessage("💢 Data for that role does not exist.");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
}
|
} else {
|
||||||
else {
|
|
||||||
data = allData[0];
|
data = allData[0];
|
||||||
role = allData[0]["role"].ToString();
|
role = allData[0]["role"].ToString();
|
||||||
resolvedRole = ResolvePos(role);
|
resolvedRole = ResolvePos(role);
|
||||||
@ -107,14 +105,14 @@ namespace NadekoBot.Commands {
|
|||||||
//name = data["title"].ToString();
|
//name = data["title"].ToString();
|
||||||
// get all possible roles, and "select" the shown one
|
// get all possible roles, and "select" the shown one
|
||||||
var roles = new string[allData.Count];
|
var roles = new string[allData.Count];
|
||||||
for (int i = 0; i < allData.Count; i++) {
|
for (var i = 0; i < allData.Count; i++) {
|
||||||
roles[i] = allData[i]["role"].ToString();
|
roles[i] = allData[i]["role"].ToString();
|
||||||
if (roles[i] == role)
|
if (roles[i] == role)
|
||||||
roles[i] = ">" + roles[i] + "<";
|
roles[i] = ">" + roles[i] + "<";
|
||||||
}
|
}
|
||||||
var general = JArray.Parse(await Classes.SearchHelper.GetResponseStringAsync($"http://api.champion.gg/stats/champs/{name}?api_key={NadekoBot.Creds.LOLAPIKey}"))
|
var general = JArray.Parse(await SearchHelper.GetResponseStringAsync($"http://api.champion.gg/stats/" +
|
||||||
.Where(jt => jt["role"].ToString() == role)
|
$"champs/{name}?api_key={NadekoBot.Creds.LOLAPIKey}"))
|
||||||
.FirstOrDefault()?["general"];
|
.FirstOrDefault(jt => jt["role"].ToString() == role)?["general"];
|
||||||
if (general == null) {
|
if (general == null) {
|
||||||
Console.WriteLine("General is null.");
|
Console.WriteLine("General is null.");
|
||||||
return;
|
return;
|
||||||
@ -122,7 +120,7 @@ namespace NadekoBot.Commands {
|
|||||||
//get build data for this role
|
//get build data for this role
|
||||||
var buildData = data["items"]["mostGames"]["items"];
|
var buildData = data["items"]["mostGames"]["items"];
|
||||||
var items = new string[6];
|
var items = new string[6];
|
||||||
for (int i = 0; i < 6; i++) {
|
for (var i = 0; i < 6; i++) {
|
||||||
items[i] = buildData[i]["id"].ToString();
|
items[i] = buildData[i]["id"].ToString();
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -147,13 +145,12 @@ namespace NadekoBot.Commands {
|
|||||||
var orderArr = (data["skills"]["mostGames"]["order"] as JArray);
|
var orderArr = (data["skills"]["mostGames"]["order"] as JArray);
|
||||||
|
|
||||||
//todo save this for at least 1 hour
|
//todo save this for at least 1 hour
|
||||||
Image img = Image.FromFile("data/lol/bg.png");
|
var img = Image.FromFile("data/lol/bg.png");
|
||||||
using (Graphics g = Graphics.FromImage(img)) {
|
using (var g = Graphics.FromImage(img)) {
|
||||||
g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
|
g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
|
||||||
//g.CompositingMode = System.Drawing.Drawing2D.CompositingMode.SourceCopy;
|
//g.CompositingMode = System.Drawing.Drawing2D.CompositingMode.SourceCopy;
|
||||||
int statsFontSize = 15;
|
const int margin = 5;
|
||||||
int margin = 5;
|
const int imageSize = 75;
|
||||||
int imageSize = 75;
|
|
||||||
var normalFont = new Font("Monaco", 8, FontStyle.Regular);
|
var normalFont = new Font("Monaco", 8, FontStyle.Regular);
|
||||||
var smallFont = new Font("Monaco", 7, FontStyle.Regular);
|
var smallFont = new Font("Monaco", 7, FontStyle.Regular);
|
||||||
//draw champ image
|
//draw champ image
|
||||||
@ -168,18 +165,26 @@ namespace NadekoBot.Commands {
|
|||||||
//todo
|
//todo
|
||||||
//draw skill order
|
//draw skill order
|
||||||
float orderFormula = 120 / orderArr.Count;
|
float orderFormula = 120 / orderArr.Count;
|
||||||
float orderVerticalSpacing = 10;
|
const float orderVerticalSpacing = 10;
|
||||||
for (int i = 0; i < orderArr.Count; i++) {
|
for (var i = 0; i < orderArr.Count; i++) {
|
||||||
float orderX = margin + margin + imageSize + orderFormula * i + i;
|
var orderX = margin + margin + imageSize + orderFormula * i + i;
|
||||||
float orderY = margin + 35;
|
float orderY = margin + 35;
|
||||||
string spellName = orderArr[i].ToString().ToLowerInvariant();
|
var spellName = orderArr[i].ToString().ToLowerInvariant();
|
||||||
|
|
||||||
if (spellName == "w")
|
switch (spellName) {
|
||||||
|
case "w":
|
||||||
orderY += orderVerticalSpacing;
|
orderY += orderVerticalSpacing;
|
||||||
else if (spellName == "e")
|
break;
|
||||||
|
case "e":
|
||||||
orderY += orderVerticalSpacing * 2;
|
orderY += orderVerticalSpacing * 2;
|
||||||
else if (spellName == "r")
|
break;
|
||||||
|
case "r":
|
||||||
orderY += orderVerticalSpacing * 3;
|
orderY += orderVerticalSpacing * 3;
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
orderY += orderVerticalSpacing * 3;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
g.DrawString(spellName.ToUpperInvariant(), new Font("Monaco", 7), Brushes.LimeGreen, orderX, orderY);
|
g.DrawString(spellName.ToUpperInvariant(), new Font("Monaco", 7), Brushes.LimeGreen, orderX, orderY);
|
||||||
}
|
}
|
||||||
@ -200,9 +205,9 @@ Assists: {general["assists"]} Ban: {general["banRate"]}%
|
|||||||
g.DrawString($"{runes}", smallFont, Brushes.WhiteSmoke, margin, margin + imageSize + margin + 40);
|
g.DrawString($"{runes}", smallFont, Brushes.WhiteSmoke, margin, margin + imageSize + margin + 40);
|
||||||
//draw counters
|
//draw counters
|
||||||
g.DrawString($"Best against", smallFont, Brushes.WhiteSmoke, margin, img.Height - imageSize + margin);
|
g.DrawString($"Best against", smallFont, Brushes.WhiteSmoke, margin, img.Height - imageSize + margin);
|
||||||
int smallImgSize = 50;
|
var smallImgSize = 50;
|
||||||
|
|
||||||
for (int i = 0; i < counters.Length; i++) {
|
for (var i = 0; i < counters.Length; i++) {
|
||||||
g.DrawImage(GetImage(counters[i]),
|
g.DrawImage(GetImage(counters[i]),
|
||||||
new Rectangle(i * (smallImgSize + margin) + margin, img.Height - smallImgSize - margin,
|
new Rectangle(i * (smallImgSize + margin) + margin, img.Height - smallImgSize - margin,
|
||||||
smallImgSize,
|
smallImgSize,
|
||||||
@ -211,8 +216,8 @@ Assists: {general["assists"]} Ban: {general["banRate"]}%
|
|||||||
//draw countered by
|
//draw countered by
|
||||||
g.DrawString($"Worst against", smallFont, Brushes.WhiteSmoke, img.Width - 3 * (smallImgSize + margin), img.Height - imageSize + margin);
|
g.DrawString($"Worst against", smallFont, Brushes.WhiteSmoke, img.Width - 3 * (smallImgSize + margin), img.Height - imageSize + margin);
|
||||||
|
|
||||||
for (int i = 0; i < countered.Length; i++) {
|
for (var i = 0; i < countered.Length; i++) {
|
||||||
int j = countered.Length - i;
|
var j = countered.Length - i;
|
||||||
g.DrawImage(GetImage(countered[i]),
|
g.DrawImage(GetImage(countered[i]),
|
||||||
new Rectangle(img.Width - (j * (smallImgSize + margin) + margin), img.Height - smallImgSize - margin,
|
new Rectangle(img.Width - (j * (smallImgSize + margin) + margin), img.Height - smallImgSize - margin,
|
||||||
smallImgSize,
|
smallImgSize,
|
||||||
@ -221,10 +226,10 @@ Assists: {general["assists"]} Ban: {general["banRate"]}%
|
|||||||
//draw item build
|
//draw item build
|
||||||
g.DrawString("Popular build", normalFont, Brushes.WhiteSmoke, img.Width - (3 * (smallImgSize + margin) + margin), 77);
|
g.DrawString("Popular build", normalFont, Brushes.WhiteSmoke, img.Width - (3 * (smallImgSize + margin) + margin), 77);
|
||||||
|
|
||||||
for (int i = 0; i < 6; i++) {
|
for (var i = 0; i < 6; i++) {
|
||||||
var inverse_i = 5 - i;
|
var inverseI = 5 - i;
|
||||||
var j = inverse_i % 3 + 1;
|
var j = inverseI % 3 + 1;
|
||||||
var k = inverse_i / 3;
|
var k = inverseI / 3;
|
||||||
g.DrawImage(GetImage(items[i], GetImageType.Item),
|
g.DrawImage(GetImage(items[i], GetImageType.Item),
|
||||||
new Rectangle(img.Width - (j * (smallImgSize + margin) + margin), 92 + k * (smallImgSize + margin),
|
new Rectangle(img.Width - (j * (smallImgSize + margin) + margin), 92 + k * (smallImgSize + margin),
|
||||||
smallImgSize,
|
smallImgSize,
|
||||||
@ -234,10 +239,8 @@ Assists: {general["assists"]} Ban: {general["banRate"]}%
|
|||||||
var cachedChamp = new CachedChampion { AddedAt = DateTime.Now, ImageStream = img.ToStream(System.Drawing.Imaging.ImageFormat.Png), Name = name.ToLower() + "_" + resolvedRole };
|
var cachedChamp = new CachedChampion { AddedAt = DateTime.Now, ImageStream = img.ToStream(System.Drawing.Imaging.ImageFormat.Png), Name = name.ToLower() + "_" + resolvedRole };
|
||||||
CachedChampionImages.Add(cachedChamp.Name, cachedChamp);
|
CachedChampionImages.Add(cachedChamp.Name, cachedChamp);
|
||||||
await e.Channel.SendFile(data["title"] + "_stats.png", cachedChamp.ImageStream);
|
await e.Channel.SendFile(data["title"] + "_stats.png", cachedChamp.ImageStream);
|
||||||
}
|
} catch {
|
||||||
catch (Exception ex) {
|
|
||||||
await e.Channel.SendMessage("💢 Failed retreiving data for that champion.");
|
await e.Channel.SendMessage("💢 Failed retreiving data for that champion.");
|
||||||
return;
|
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
@ -245,7 +248,7 @@ Assists: {general["assists"]} Ban: {general["banRate"]}%
|
|||||||
.Description("Shows top 6 banned champions ordered by ban rate. Ban these champions and you will be Plat 5 in no time.")
|
.Description("Shows top 6 banned champions ordered by ban rate. Ban these champions and you will be Plat 5 in no time.")
|
||||||
.Do(async e => {
|
.Do(async e => {
|
||||||
|
|
||||||
int showCount = 6;
|
var showCount = 6;
|
||||||
//http://api.champion.gg/stats/champs/mostBanned?api_key=YOUR_API_TOKEN&page=1&limit=2
|
//http://api.champion.gg/stats/champs/mostBanned?api_key=YOUR_API_TOKEN&page=1&limit=2
|
||||||
try {
|
try {
|
||||||
var data = JObject.Parse(
|
var data = JObject.Parse(
|
||||||
@ -253,10 +256,10 @@ Assists: {general["assists"]} Ban: {general["banRate"]}%
|
|||||||
.SearchHelper
|
.SearchHelper
|
||||||
.GetResponseStringAsync($"http://api.champion.gg/stats/champs/mostBanned?api_key={NadekoBot.Creds.LOLAPIKey}&page=1&limit={showCount}"))["data"] as JArray;
|
.GetResponseStringAsync($"http://api.champion.gg/stats/champs/mostBanned?api_key={NadekoBot.Creds.LOLAPIKey}&page=1&limit={showCount}"))["data"] as JArray;
|
||||||
|
|
||||||
StringBuilder sb = new StringBuilder();
|
var sb = new StringBuilder();
|
||||||
sb.AppendLine($"**Showing {showCount} top banned champions.**");
|
sb.AppendLine($"**Showing {showCount} top banned champions.**");
|
||||||
sb.AppendLine($"`{trashTalk[new Random().Next(0, trashTalk.Length)]}`");
|
sb.AppendLine($"`{trashTalk[new Random().Next(0, trashTalk.Length)]}`");
|
||||||
for (int i = 0; i < data.Count; i++) {
|
for (var i = 0; i < data.Count; i++) {
|
||||||
if (i % 2 == 0 && i != 0)
|
if (i % 2 == 0 && i != 0)
|
||||||
sb.AppendLine();
|
sb.AppendLine();
|
||||||
sb.Append($"`{i + 1}.` **{data[i]["name"]}** ");
|
sb.Append($"`{i + 1}.` **{data[i]["name"]}** ");
|
||||||
@ -264,8 +267,7 @@ Assists: {general["assists"]} Ban: {general["banRate"]}%
|
|||||||
}
|
}
|
||||||
|
|
||||||
await e.Channel.SendMessage(sb.ToString());
|
await e.Channel.SendMessage(sb.ToString());
|
||||||
}
|
} catch (Exception ex) {
|
||||||
catch (Exception ex) {
|
|
||||||
await e.Channel.SendMessage($"Fail:\n{ex}");
|
await e.Channel.SendMessage($"Fail:\n{ex}");
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
@ -275,7 +277,7 @@ Assists: {general["assists"]} Ban: {general["banRate"]}%
|
|||||||
Champion,
|
Champion,
|
||||||
Item
|
Item
|
||||||
}
|
}
|
||||||
private Image GetImage(string id, GetImageType imageType = GetImageType.Champion) {
|
private static Image GetImage(string id, GetImageType imageType = GetImageType.Champion) {
|
||||||
try {
|
try {
|
||||||
switch (imageType) {
|
switch (imageType) {
|
||||||
case GetImageType.Champion:
|
case GetImageType.Champion:
|
||||||
@ -284,13 +286,12 @@ Assists: {general["assists"]} Ban: {general["banRate"]}%
|
|||||||
default:
|
default:
|
||||||
return Image.FromFile($"data/lol/items/{id}.png");
|
return Image.FromFile($"data/lol/items/{id}.png");
|
||||||
}
|
}
|
||||||
}
|
} catch (Exception) {
|
||||||
catch (Exception) {
|
|
||||||
return Image.FromFile("data/lol/_ERROR.png");
|
return Image.FromFile("data/lol/_ERROR.png");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private string ResolvePos(string pos) {
|
private static string ResolvePos(string pos) {
|
||||||
if (string.IsNullOrWhiteSpace(pos))
|
if (string.IsNullOrWhiteSpace(pos))
|
||||||
return null;
|
return null;
|
||||||
switch (pos.ToLowerInvariant()) {
|
switch (pos.ToLowerInvariant()) {
|
||||||
|
@ -5,55 +5,58 @@ using System.Text;
|
|||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
using Discord.Commands;
|
using Discord.Commands;
|
||||||
using System.Timers;
|
using System.Timers;
|
||||||
|
using NadekoBot.Modules;
|
||||||
|
|
||||||
namespace NadekoBot.Commands {
|
namespace NadekoBot.Commands {
|
||||||
internal class PlayingRotate : DiscordCommand {
|
internal class PlayingRotate : DiscordCommand {
|
||||||
|
|
||||||
private static List<string> rotatingStatuses = new List<string>();
|
private static List<string> rotatingStatuses = new List<string>();
|
||||||
private static Timer timer = new Timer(12000);
|
private static readonly Timer timer = new Timer(12000);
|
||||||
|
|
||||||
private Dictionary<string, Func<string>> playingPlaceholders => new Dictionary<string, Func<string>> {
|
public static Dictionary<string, Func<string>> PlayingPlaceholders { get; } =
|
||||||
{"%servers%", ()=> NadekoBot.Client.Servers.Count().ToString() },
|
new Dictionary<string, Func<string>> {
|
||||||
{"%users%", () => NadekoBot.Client.Servers.SelectMany(s=>s.Users).Count().ToString() },
|
{"%servers%", () => NadekoBot.Client.Servers.Count().ToString()},
|
||||||
{"%playing%", () => {
|
{"%users%", () => NadekoBot.Client.Servers.SelectMany(s => s.Users).Count().ToString()}, {
|
||||||
var cnt = Modules.Music.musicPlayers.Where(kvp => kvp.Value.CurrentSong != null).Count();
|
"%playing%", () => {
|
||||||
if(cnt == 1) {
|
var cnt = Music.MusicPlayers.Count(kvp => kvp.Value.CurrentSong != null);
|
||||||
|
if (cnt != 1) return cnt.ToString();
|
||||||
try {
|
try {
|
||||||
var mp = Modules.Music.musicPlayers.FirstOrDefault();
|
var mp = Music.MusicPlayers.FirstOrDefault();
|
||||||
return mp.Value.CurrentSong.SongInfo.Title;
|
return mp.Value.CurrentSong.SongInfo.Title;
|
||||||
} catch { }
|
|
||||||
}
|
}
|
||||||
return cnt.ToString();
|
catch {
|
||||||
|
return "No songs";
|
||||||
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
{"%queued%", () => Modules.Music.musicPlayers.Sum(kvp=>kvp.Value.Playlist.Count).ToString() },
|
{"%queued%", () => Music.MusicPlayers.Sum(kvp => kvp.Value.Playlist.Count).ToString()},
|
||||||
{"%trivia%", () => Commands.Trivia.runningTrivias.Count.ToString() }
|
{"%trivia%", () => Trivia.runningTrivias.Count.ToString()}
|
||||||
};
|
};
|
||||||
private object playingPlaceholderLock => new object();
|
|
||||||
|
private readonly object playingPlaceholderLock = new object();
|
||||||
|
|
||||||
public PlayingRotate() {
|
public PlayingRotate() {
|
||||||
int i = -1;
|
var i = -1;
|
||||||
timer.Elapsed += (s, e) => {
|
timer.Elapsed += (s, e) => {
|
||||||
try {
|
try {
|
||||||
i++;
|
i++;
|
||||||
string status = "";
|
var 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) {
|
status = PlayingPlaceholders.Aggregate(status,
|
||||||
status = status.Replace(kvp.Key, kvp.Value());
|
(current, kvp) => current.Replace(kvp.Key, kvp.Value()));
|
||||||
}
|
|
||||||
}
|
}
|
||||||
if (string.IsNullOrWhiteSpace(status))
|
if (string.IsNullOrWhiteSpace(status))
|
||||||
return;
|
return;
|
||||||
Task.Run(() => { try { NadekoBot.Client.SetGame(status); } catch { } });
|
Task.Run(() => { NadekoBot.Client.SetGame(status); });
|
||||||
}
|
}
|
||||||
catch { }
|
catch {}
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -74,7 +77,8 @@ namespace NadekoBot.Commands {
|
|||||||
|
|
||||||
cgb.CreateCommand(".addplaying")
|
cgb.CreateCommand(".addplaying")
|
||||||
.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())
|
.AddCheck(Classes.Permissions.SimpleCheckers.OwnerOnly())
|
||||||
.Do(async e => {
|
.Do(async e => {
|
||||||
@ -93,16 +97,17 @@ namespace NadekoBot.Commands {
|
|||||||
.AddCheck(Classes.Permissions.SimpleCheckers.OwnerOnly())
|
.AddCheck(Classes.Permissions.SimpleCheckers.OwnerOnly())
|
||||||
.Do(async e => {
|
.Do(async e => {
|
||||||
if (rotatingStatuses.Count == 0)
|
if (rotatingStatuses.Count == 0)
|
||||||
await e.Channel.SendMessage("`There are no playing strings. Add some with .addplaying [text] command.`");
|
await e.Channel.SendMessage("`There are no playing strings. " +
|
||||||
StringBuilder sb = new StringBuilder();
|
"Add some with .addplaying [text] command.`");
|
||||||
for (int i = 0; i < rotatingStatuses.Count; i++) {
|
var sb = new StringBuilder();
|
||||||
|
for (var i = 0; i < rotatingStatuses.Count; i++) {
|
||||||
sb.AppendLine($"`{i + 1}.` {rotatingStatuses[i]}");
|
sb.AppendLine($"`{i + 1}.` {rotatingStatuses[i]}");
|
||||||
}
|
}
|
||||||
await e.Channel.SendMessage(sb.ToString());
|
await e.Channel.SendMessage(sb.ToString());
|
||||||
});
|
});
|
||||||
|
|
||||||
cgb.CreateCommand(".removeplaying")
|
cgb.CreateCommand(".removeplaying")
|
||||||
.Alias(".repl")
|
.Alias(".repl", ".rmpl")
|
||||||
.Description("Removes a playing string on a given number.")
|
.Description("Removes a playing string on a given number.")
|
||||||
.Parameter("number", ParameterType.Required)
|
.Parameter("number", ParameterType.Required)
|
||||||
.AddCheck(Classes.Permissions.SimpleCheckers.OwnerOnly())
|
.AddCheck(Classes.Permissions.SimpleCheckers.OwnerOnly())
|
||||||
|
@ -20,7 +20,8 @@ namespace NadekoBot.Commands {
|
|||||||
cgb.CreateCommand(">poll")
|
cgb.CreateCommand(">poll")
|
||||||
.Description("Creates a poll, only person who has manage server permission can do it.\n**Usage**: >poll Question?;Answer1;Answ 2;A_3")
|
.Description("Creates a poll, only person who has manage server permission can do it.\n**Usage**: >poll Question?;Answer1;Answ 2;A_3")
|
||||||
.Parameter("allargs", ParameterType.Unparsed)
|
.Parameter("allargs", ParameterType.Unparsed)
|
||||||
.Do(e => {
|
.Do(async e => {
|
||||||
|
await Task.Run(async () => {
|
||||||
if (!e.User.ServerPermissions.ManageChannels)
|
if (!e.User.ServerPermissions.ManageChannels)
|
||||||
return;
|
return;
|
||||||
if (ActivePolls.ContainsKey(e.Server))
|
if (ActivePolls.ContainsKey(e.Server))
|
||||||
@ -32,7 +33,11 @@ namespace NadekoBot.Commands {
|
|||||||
if (data.Length < 3)
|
if (data.Length < 3)
|
||||||
return;
|
return;
|
||||||
|
|
||||||
new Poll(e, data[0], data.Skip(1));
|
var poll = new Poll(e, data[0], data.Skip(1));
|
||||||
|
if (PollCommand.ActivePolls.TryAdd(e.Server, poll)) {
|
||||||
|
await poll.StartPoll();
|
||||||
|
}
|
||||||
|
});
|
||||||
});
|
});
|
||||||
cgb.CreateCommand(">pollend")
|
cgb.CreateCommand(">pollend")
|
||||||
.Description("Stops active poll on this server and prints the results in this channel.")
|
.Description("Stops active poll on this server and prints the results in this channel.")
|
||||||
@ -47,33 +52,27 @@ namespace NadekoBot.Commands {
|
|||||||
}
|
}
|
||||||
|
|
||||||
internal class Poll {
|
internal class Poll {
|
||||||
private CommandEventArgs e;
|
private readonly CommandEventArgs e;
|
||||||
private string[] answers;
|
private readonly string[] answers;
|
||||||
private ConcurrentDictionary<User, int> participants = new ConcurrentDictionary<User, int>();
|
private ConcurrentDictionary<User, int> participants = new ConcurrentDictionary<User, int>();
|
||||||
private string question;
|
private readonly string question;
|
||||||
private DateTime started;
|
private DateTime started;
|
||||||
private CancellationTokenSource pollCancellationSource = new CancellationTokenSource();
|
private CancellationTokenSource pollCancellationSource = new CancellationTokenSource();
|
||||||
|
|
||||||
public Poll(CommandEventArgs e, string v, IEnumerable<string> enumerable) {
|
public Poll(CommandEventArgs e, string question, IEnumerable<string> enumerable) {
|
||||||
this.e = e;
|
this.e = e;
|
||||||
this.question = v;
|
this.question = question;
|
||||||
this.answers = enumerable.ToArray();
|
this.answers = enumerable as string[] ?? enumerable.ToArray();
|
||||||
|
|
||||||
if (PollCommand.ActivePolls.TryAdd(e.Server, this)) {
|
|
||||||
Task.Factory.StartNew(async () => await StartPoll());
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private async Task StartPoll() {
|
public 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";
|
||||||
int num = 1;
|
var num = 1;
|
||||||
foreach (var answ in answers) {
|
msgToSend = answers.Aggregate(msgToSend, (current, answ) => current + $"`{num++}.` **{answ}**\n");
|
||||||
msgToSend += $"`{num++}.` **{answ}**\n";
|
|
||||||
}
|
|
||||||
msgToSend += "\n**Private Message me with the corresponding number of the answer.**";
|
msgToSend += "\n**Private Message me with the corresponding number of the answer.**";
|
||||||
await e.Channel.SendMessage(msgToSend);
|
await e.Channel.SendMessage(msgToSend);
|
||||||
}
|
}
|
||||||
@ -87,16 +86,16 @@ namespace NadekoBot.Commands {
|
|||||||
.ToDictionary(x => x.Key, x => x.Sum(kvp => 1))
|
.ToDictionary(x => x.Key, x => x.Sum(kvp => 1))
|
||||||
.OrderBy(kvp => kvp.Value);
|
.OrderBy(kvp => kvp.Value);
|
||||||
|
|
||||||
int totalVotesCast = results.Sum(kvp => kvp.Value);
|
var totalVotesCast = results.Sum(kvp => kvp.Value);
|
||||||
if (totalVotesCast == 0) {
|
if (totalVotesCast == 0) {
|
||||||
await ch.SendMessage("📄 **No votes have been cast.**");
|
await ch.SendMessage("📄 **No votes have been cast.**");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
var closeMessage = $"--------------**POLL CLOSED**--------------\n" +
|
var closeMessage = $"--------------**POLL CLOSED**--------------\n" +
|
||||||
$"📄 , here are the results:\n";
|
$"📄 , here are the results:\n";
|
||||||
foreach (var kvp in results) {
|
closeMessage = results.Aggregate(closeMessage, (current, kvp) => current + $"`{kvp.Key}.` **[{answers[kvp.Key - 1]}]**" +
|
||||||
closeMessage += $"`{kvp.Key}.` **[{answers[kvp.Key - 1]}]** has {kvp.Value} votes.({kvp.Value * 1.0f / totalVotesCast * 100}%)\n";
|
$" has {kvp.Value} votes." +
|
||||||
}
|
$"({kvp.Value*1.0f/totalVotesCast*100}%)\n");
|
||||||
|
|
||||||
await ch.SendMessage($"📄 **Total votes cast**: {totalVotesCast}\n{closeMessage}");
|
await ch.SendMessage($"📄 **Total votes cast**: {totalVotesCast}\n{closeMessage}");
|
||||||
} catch (Exception ex) {
|
} catch (Exception ex) {
|
||||||
@ -112,14 +111,13 @@ namespace NadekoBot.Commands {
|
|||||||
return;
|
return;
|
||||||
|
|
||||||
int vote;
|
int vote;
|
||||||
if (int.TryParse(e.Message.Text, out vote)) {
|
if (!int.TryParse(e.Message.Text, out vote)) return;
|
||||||
if (vote < 1 || vote > answers.Length)
|
if (vote < 1 || vote > answers.Length)
|
||||||
return;
|
return;
|
||||||
if (participants.TryAdd(e.User, vote)) {
|
if (participants.TryAdd(e.User, vote)) {
|
||||||
await e.User.SendMessage($"Thanks for voting **{e.User.Name}**.");
|
await e.User.SendMessage($"Thanks for voting **{e.User.Name}**.");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
catch { }
|
catch { }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -221,7 +221,8 @@ namespace NadekoBot.Modules {
|
|||||||
.Do(async e => {
|
.Do(async e => {
|
||||||
var count = 1;
|
var count = 1;
|
||||||
int.TryParse(e.Args[0], out count);
|
int.TryParse(e.Args[0], out count);
|
||||||
|
if (count == 0)
|
||||||
|
count = 1;
|
||||||
if (count < 1 || count > 12) {
|
if (count < 1 || count > 12) {
|
||||||
await e.Channel.SendMessage("Number must be between 0 and 12");
|
await e.Channel.SendMessage("Number must be between 0 and 12");
|
||||||
return;
|
return;
|
||||||
@ -257,8 +258,7 @@ namespace NadekoBot.Modules {
|
|||||||
if (invite != null) {
|
if (invite != null) {
|
||||||
try {
|
try {
|
||||||
await invite.Accept();
|
await invite.Accept();
|
||||||
}
|
} catch {
|
||||||
catch {
|
|
||||||
await e.Channel.SendMessage("Failed to accept invite.");
|
await e.Channel.SendMessage("Failed to accept invite.");
|
||||||
}
|
}
|
||||||
await e.Channel.SendMessage("I got in!");
|
await e.Channel.SendMessage("I got in!");
|
||||||
|
@ -13,10 +13,10 @@ using Timer = System.Timers.Timer;
|
|||||||
namespace NadekoBot.Modules {
|
namespace NadekoBot.Modules {
|
||||||
internal class Music : DiscordModule {
|
internal class Music : DiscordModule {
|
||||||
|
|
||||||
public static ConcurrentDictionary<Server, MusicPlayer> musicPlayers = new ConcurrentDictionary<Server, MusicPlayer>();
|
public static ConcurrentDictionary<Server, MusicPlayer> MusicPlayers = new ConcurrentDictionary<Server, MusicPlayer>();
|
||||||
public static ConcurrentDictionary<ulong, float> defaultMusicVolumes = new ConcurrentDictionary<ulong, float>();
|
public static ConcurrentDictionary<ulong, float> DefaultMusicVolumes = new ConcurrentDictionary<ulong, float>();
|
||||||
|
|
||||||
private Timer setgameTimer => new Timer();
|
private readonly Timer setgameTimer = new Timer();
|
||||||
|
|
||||||
private bool setgameEnabled = false;
|
private bool setgameEnabled = false;
|
||||||
|
|
||||||
@ -25,8 +25,8 @@ namespace NadekoBot.Modules {
|
|||||||
setgameTimer.Interval = 20000;
|
setgameTimer.Interval = 20000;
|
||||||
setgameTimer.Elapsed += (s, e) => {
|
setgameTimer.Elapsed += (s, e) => {
|
||||||
try {
|
try {
|
||||||
int num = musicPlayers.Where(kvp => kvp.Value.CurrentSong != null).Count();
|
var num = MusicPlayers.Count(kvp => kvp.Value.CurrentSong != null);
|
||||||
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 { }
|
||||||
};
|
};
|
||||||
|
|
||||||
@ -46,7 +46,7 @@ namespace NadekoBot.Modules {
|
|||||||
.Description("Goes to the next song in the queue.")
|
.Description("Goes to the next song in the queue.")
|
||||||
.Do(e => {
|
.Do(e => {
|
||||||
MusicPlayer musicPlayer;
|
MusicPlayer musicPlayer;
|
||||||
if (!musicPlayers.TryGetValue(e.Server, out musicPlayer)) return;
|
if (!MusicPlayers.TryGetValue(e.Server, out musicPlayer)) return;
|
||||||
musicPlayer.Next();
|
musicPlayer.Next();
|
||||||
});
|
});
|
||||||
|
|
||||||
@ -55,7 +55,7 @@ namespace NadekoBot.Modules {
|
|||||||
.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(async e => {
|
.Do(async e => {
|
||||||
MusicPlayer musicPlayer;
|
MusicPlayer musicPlayer;
|
||||||
if (!musicPlayers.TryGetValue(e.Server, out musicPlayer)) return;
|
if (!MusicPlayers.TryGetValue(e.Server, out musicPlayer)) return;
|
||||||
musicPlayer.Stop();
|
musicPlayer.Stop();
|
||||||
var msg = await e.Channel.SendMessage("⚠Due to music issues, NadekoBot is unable to leave voice channels at this moment.\nIf this presents inconvenience, you can use `!m mv` command to make her join your current voice channel.");
|
var msg = await e.Channel.SendMessage("⚠Due to music issues, NadekoBot is unable to leave voice channels at this moment.\nIf this presents inconvenience, you can use `!m mv` command to make her join your current voice channel.");
|
||||||
await Task.Delay(5000);
|
await Task.Delay(5000);
|
||||||
@ -69,7 +69,7 @@ namespace NadekoBot.Modules {
|
|||||||
.Description("Pauses or Unpauses the song.")
|
.Description("Pauses or Unpauses the song.")
|
||||||
.Do(async e => {
|
.Do(async e => {
|
||||||
MusicPlayer musicPlayer;
|
MusicPlayer musicPlayer;
|
||||||
if (!musicPlayers.TryGetValue(e.Server, out musicPlayer)) return;
|
if (!MusicPlayers.TryGetValue(e.Server, out musicPlayer)) return;
|
||||||
musicPlayer.TogglePause();
|
musicPlayer.TogglePause();
|
||||||
if (musicPlayer.Paused)
|
if (musicPlayer.Paused)
|
||||||
await e.Channel.SendMessage("🎵`Music musicPlayer paused.`");
|
await e.Channel.SendMessage("🎵`Music musicPlayer paused.`");
|
||||||
@ -90,11 +90,11 @@ namespace NadekoBot.Modules {
|
|||||||
.Description("Lists up to 15 currently queued songs.")
|
.Description("Lists up to 15 currently queued songs.")
|
||||||
.Do(async e => {
|
.Do(async e => {
|
||||||
MusicPlayer musicPlayer;
|
MusicPlayer musicPlayer;
|
||||||
if (!musicPlayers.TryGetValue(e.Server, out musicPlayer)) {
|
if (!MusicPlayers.TryGetValue(e.Server, out musicPlayer)) {
|
||||||
await e.Channel.SendMessage("🎵 No active music musicPlayer.");
|
await e.Channel.SendMessage("🎵 No active music musicPlayer.");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
string toSend = "🎵 **" + musicPlayer.Playlist.Count + "** `videos currently queued.` ";
|
string toSend = "🎵 **" + musicPlayer.Playlist.Count + "** `tracks currently queued.` ";
|
||||||
if (musicPlayer.Playlist.Count >= MusicPlayer.MaximumPlaylistSize)
|
if (musicPlayer.Playlist.Count >= MusicPlayer.MaximumPlaylistSize)
|
||||||
toSend += "**Song queue is full!**\n";
|
toSend += "**Song queue is full!**\n";
|
||||||
else
|
else
|
||||||
@ -108,7 +108,7 @@ namespace NadekoBot.Modules {
|
|||||||
.Description("Shows the song currently playing.")
|
.Description("Shows the song currently playing.")
|
||||||
.Do(async e => {
|
.Do(async e => {
|
||||||
MusicPlayer musicPlayer;
|
MusicPlayer musicPlayer;
|
||||||
if (!musicPlayers.TryGetValue(e.Server, out musicPlayer))
|
if (!MusicPlayers.TryGetValue(e.Server, out musicPlayer))
|
||||||
return;
|
return;
|
||||||
await e.Channel.SendMessage($"🎵`Now Playing` {musicPlayer.CurrentSong.PrettyName}");
|
await e.Channel.SendMessage($"🎵`Now Playing` {musicPlayer.CurrentSong.PrettyName}");
|
||||||
});
|
});
|
||||||
@ -118,7 +118,7 @@ namespace NadekoBot.Modules {
|
|||||||
.Parameter("val", ParameterType.Required)
|
.Parameter("val", ParameterType.Required)
|
||||||
.Do(async e => {
|
.Do(async e => {
|
||||||
MusicPlayer musicPlayer;
|
MusicPlayer musicPlayer;
|
||||||
if (!musicPlayers.TryGetValue(e.Server, out musicPlayer))
|
if (!MusicPlayers.TryGetValue(e.Server, out musicPlayer))
|
||||||
return;
|
return;
|
||||||
var arg = e.GetArg("val");
|
var arg = e.GetArg("val");
|
||||||
int volume;
|
int volume;
|
||||||
@ -141,7 +141,7 @@ namespace NadekoBot.Modules {
|
|||||||
await e.Channel.SendMessage("Volume number invalid.");
|
await e.Channel.SendMessage("Volume number invalid.");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
defaultMusicVolumes.AddOrUpdate(e.Server.Id, volume / 100, (key, newval) => volume / 100);
|
DefaultMusicVolumes.AddOrUpdate(e.Server.Id, volume / 100, (key, newval) => volume / 100);
|
||||||
await e.Channel.SendMessage($"🎵 `Default volume set to {volume}%`");
|
await e.Channel.SendMessage($"🎵 `Default volume set to {volume}%`");
|
||||||
});
|
});
|
||||||
|
|
||||||
@ -149,7 +149,7 @@ namespace NadekoBot.Modules {
|
|||||||
.Description("Sets the music volume to 0%")
|
.Description("Sets the music volume to 0%")
|
||||||
.Do(e => {
|
.Do(e => {
|
||||||
MusicPlayer musicPlayer;
|
MusicPlayer musicPlayer;
|
||||||
if (!musicPlayers.TryGetValue(e.Server, out musicPlayer))
|
if (!MusicPlayers.TryGetValue(e.Server, out musicPlayer))
|
||||||
return;
|
return;
|
||||||
musicPlayer.SetVolume(0);
|
musicPlayer.SetVolume(0);
|
||||||
});
|
});
|
||||||
@ -158,7 +158,7 @@ namespace NadekoBot.Modules {
|
|||||||
.Description("Sets the music volume to 100% (real max is actually 150%).")
|
.Description("Sets the music volume to 100% (real max is actually 150%).")
|
||||||
.Do(e => {
|
.Do(e => {
|
||||||
MusicPlayer musicPlayer;
|
MusicPlayer musicPlayer;
|
||||||
if (!musicPlayers.TryGetValue(e.Server, out musicPlayer))
|
if (!MusicPlayers.TryGetValue(e.Server, out musicPlayer))
|
||||||
return;
|
return;
|
||||||
musicPlayer.SetVolume(100);
|
musicPlayer.SetVolume(100);
|
||||||
});
|
});
|
||||||
@ -167,7 +167,7 @@ namespace NadekoBot.Modules {
|
|||||||
.Description("Sets the music volume to 50%.")
|
.Description("Sets the music volume to 50%.")
|
||||||
.Do(e => {
|
.Do(e => {
|
||||||
MusicPlayer musicPlayer;
|
MusicPlayer musicPlayer;
|
||||||
if (!musicPlayers.TryGetValue(e.Server, out musicPlayer))
|
if (!MusicPlayers.TryGetValue(e.Server, out musicPlayer))
|
||||||
return;
|
return;
|
||||||
musicPlayer.SetVolume(50);
|
musicPlayer.SetVolume(50);
|
||||||
});
|
});
|
||||||
@ -176,7 +176,7 @@ namespace NadekoBot.Modules {
|
|||||||
.Description("Shuffles the current playlist.")
|
.Description("Shuffles the current playlist.")
|
||||||
.Do(async e => {
|
.Do(async e => {
|
||||||
MusicPlayer musicPlayer;
|
MusicPlayer musicPlayer;
|
||||||
if (!musicPlayers.TryGetValue(e.Server, out musicPlayer))
|
if (!MusicPlayers.TryGetValue(e.Server, out musicPlayer))
|
||||||
return;
|
return;
|
||||||
if (musicPlayer.Playlist.Count < 2) {
|
if (musicPlayer.Playlist.Count < 2) {
|
||||||
await e.Channel.SendMessage("💢 Not enough songs in order to perform the shuffle.");
|
await e.Channel.SendMessage("💢 Not enough songs in order to perform the shuffle.");
|
||||||
@ -266,7 +266,7 @@ namespace NadekoBot.Modules {
|
|||||||
.Do(e => {
|
.Do(e => {
|
||||||
MusicPlayer musicPlayer;
|
MusicPlayer musicPlayer;
|
||||||
var voiceChannel = e.User.VoiceChannel;
|
var voiceChannel = e.User.VoiceChannel;
|
||||||
if (voiceChannel == null || voiceChannel.Server != e.Server || !musicPlayers.TryGetValue(e.Server, out musicPlayer))
|
if (voiceChannel == null || voiceChannel.Server != e.Server || !MusicPlayers.TryGetValue(e.Server, out musicPlayer))
|
||||||
return;
|
return;
|
||||||
musicPlayer.MoveToVoiceChannel(voiceChannel);
|
musicPlayer.MoveToVoiceChannel(voiceChannel);
|
||||||
});
|
});
|
||||||
@ -277,7 +277,7 @@ namespace NadekoBot.Modules {
|
|||||||
.Do(async e => {
|
.Do(async e => {
|
||||||
var arg = e.GetArg("num");
|
var arg = e.GetArg("num");
|
||||||
MusicPlayer musicPlayer;
|
MusicPlayer musicPlayer;
|
||||||
if (!musicPlayers.TryGetValue(e.Server, out musicPlayer)) {
|
if (!MusicPlayers.TryGetValue(e.Server, out musicPlayer)) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (arg?.ToLower() == "all") {
|
if (arg?.ToLower() == "all") {
|
||||||
@ -306,39 +306,40 @@ namespace NadekoBot.Modules {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
private async Task QueueSong(Channel TextCh, Channel VoiceCh, string query, bool silent = false, MusicType musicType = MusicType.Normal) {
|
private async Task QueueSong(Channel textCh, Channel voiceCh, string query, bool silent = false, MusicType musicType = MusicType.Normal) {
|
||||||
if (VoiceCh == null || VoiceCh.Server != TextCh.Server) {
|
if (voiceCh == null || voiceCh.Server != textCh.Server) {
|
||||||
if (!silent)
|
if (!silent)
|
||||||
await TextCh.SendMessage("💢 You need to be in a voice channel on this server.\n If you are already in a voice channel, try rejoining.");
|
await textCh.SendMessage("💢 You need to be in a voice channel on this server.\n If you are already in a voice channel, try rejoining.");
|
||||||
throw new ArgumentNullException(nameof(VoiceCh));
|
throw new ArgumentNullException(nameof(voiceCh));
|
||||||
}
|
}
|
||||||
if (string.IsNullOrWhiteSpace(query) || query.Length < 3)
|
if (string.IsNullOrWhiteSpace(query) || query.Length < 3)
|
||||||
throw new ArgumentException("💢 Invalid query for queue song.", nameof(query));
|
throw new ArgumentException("💢 Invalid query for queue song.", nameof(query));
|
||||||
MusicPlayer musicPlayer = null;
|
MusicPlayer musicPlayer = null;
|
||||||
if (!musicPlayers.TryGetValue(TextCh.Server, out musicPlayer)) {
|
if (!MusicPlayers.TryGetValue(textCh.Server, out musicPlayer)) {
|
||||||
float? vol = null;
|
float? vol = null;
|
||||||
float throwAway;
|
float throwAway;
|
||||||
if (defaultMusicVolumes.TryGetValue(TextCh.Server.Id, out throwAway))
|
if (DefaultMusicVolumes.TryGetValue(textCh.Server.Id, out throwAway))
|
||||||
vol = throwAway;
|
vol = throwAway;
|
||||||
musicPlayer = new MusicPlayer(VoiceCh, vol) {
|
musicPlayer = new MusicPlayer(voiceCh, vol) {
|
||||||
OnCompleted = async (song) => {
|
OnCompleted = async song => {
|
||||||
try {
|
try {
|
||||||
await TextCh.SendMessage($"🎵`Finished`{song.PrettyName}");
|
await textCh.SendMessage($"🎵`Finished`{song.PrettyName}");
|
||||||
} catch { }
|
}
|
||||||
|
catch {}
|
||||||
},
|
},
|
||||||
OnStarted = async (song) => {
|
OnStarted = async (song) => {
|
||||||
try {
|
try {
|
||||||
var msgTxt = $"🎵`Playing`{song.PrettyName} `Vol: {(int)(musicPlayer.Volume * 100)}%`";
|
var msgTxt = $"🎵`Playing`{song.PrettyName} `Vol: {(int)(musicPlayer.Volume * 100)}%`";
|
||||||
await TextCh.SendMessage(msgTxt);
|
await textCh.SendMessage(msgTxt);
|
||||||
} catch { }
|
} catch { }
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
musicPlayers.TryAdd(TextCh.Server, musicPlayer);
|
MusicPlayers.TryAdd(textCh.Server, musicPlayer);
|
||||||
}
|
}
|
||||||
var resolvedSong = await Song.ResolveSong(query, musicType);
|
var resolvedSong = await Song.ResolveSong(query, musicType);
|
||||||
resolvedSong.MusicPlayer = musicPlayer;
|
resolvedSong.MusicPlayer = musicPlayer;
|
||||||
if (!silent)
|
if (!silent)
|
||||||
await TextCh.Send($"🎵`Queued`{resolvedSong.PrettyName}");
|
await textCh.Send($"🎵`Queued`{resolvedSong.PrettyName}");
|
||||||
musicPlayer.AddSong(resolvedSong);
|
musicPlayer.AddSong(resolvedSong);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -7,11 +7,7 @@ using NadekoBot.Classes;
|
|||||||
namespace NadekoBot.Modules {
|
namespace NadekoBot.Modules {
|
||||||
internal class NSFW : DiscordModule {
|
internal class NSFW : DiscordModule {
|
||||||
|
|
||||||
private Random _r = new Random();
|
private readonly Random rng = new Random();
|
||||||
|
|
||||||
public NSFW() {
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
public override void Install(ModuleManager manager) {
|
public override void Install(ModuleManager manager) {
|
||||||
manager.CreateCommands("", cgb => {
|
manager.CreateCommands("", cgb => {
|
||||||
@ -22,9 +18,7 @@ namespace NadekoBot.Modules {
|
|||||||
.Description("Shows a random NSFW hentai image from gelbooru and danbooru with a given tag. Tag is optional but preffered. (multiple tags are appended with +)\n**Usage**: ~hentai yuri+kissing")
|
.Description("Shows a random NSFW hentai image from gelbooru and danbooru with a given tag. Tag is optional but preffered. (multiple tags are appended with +)\n**Usage**: ~hentai yuri+kissing")
|
||||||
.Parameter("tag", ParameterType.Unparsed)
|
.Parameter("tag", ParameterType.Unparsed)
|
||||||
.Do(async e => {
|
.Do(async e => {
|
||||||
string tag = e.GetArg("tag");
|
var tag = e.GetArg("tag")?.Trim() ?? "";
|
||||||
if (tag == null)
|
|
||||||
tag = "";
|
|
||||||
await e.Channel.SendMessage(":heart: Gelbooru: " + await SearchHelper.GetGelbooruImageLink(tag));
|
await e.Channel.SendMessage(":heart: Gelbooru: " + await SearchHelper.GetGelbooruImageLink(tag));
|
||||||
await e.Channel.SendMessage(":heart: Danbooru: " + await SearchHelper.GetDanbooruImageLink(tag));
|
await e.Channel.SendMessage(":heart: Danbooru: " + await SearchHelper.GetDanbooruImageLink(tag));
|
||||||
});
|
});
|
||||||
@ -32,27 +26,21 @@ namespace NadekoBot.Modules {
|
|||||||
.Description("Shows a random hentai image from danbooru with a given tag. Tag is optional but preffered. (multiple tags are appended with +)\n**Usage**: ~danbooru yuri+kissing")
|
.Description("Shows a random hentai image from danbooru with a given tag. Tag is optional but preffered. (multiple tags are appended with +)\n**Usage**: ~danbooru yuri+kissing")
|
||||||
.Parameter("tag", ParameterType.Unparsed)
|
.Parameter("tag", ParameterType.Unparsed)
|
||||||
.Do(async e => {
|
.Do(async e => {
|
||||||
string tag = e.GetArg("tag");
|
var tag = e.GetArg("tag")?.Trim() ?? "";
|
||||||
if (tag == null)
|
|
||||||
tag = "";
|
|
||||||
await e.Channel.SendMessage(await SearchHelper.GetDanbooruImageLink(tag));
|
await e.Channel.SendMessage(await SearchHelper.GetDanbooruImageLink(tag));
|
||||||
});
|
});
|
||||||
cgb.CreateCommand("~gelbooru")
|
cgb.CreateCommand("~gelbooru")
|
||||||
.Description("Shows a random hentai image from gelbooru with a given tag. Tag is optional but preffered. (multiple tags are appended with +)\n**Usage**: ~gelbooru yuri+kissing")
|
.Description("Shows a random hentai image from gelbooru with a given tag. Tag is optional but preffered. (multiple tags are appended with +)\n**Usage**: ~gelbooru yuri+kissing")
|
||||||
.Parameter("tag", ParameterType.Unparsed)
|
.Parameter("tag", ParameterType.Unparsed)
|
||||||
.Do(async e => {
|
.Do(async e => {
|
||||||
string tag = e.GetArg("tag");
|
var tag = e.GetArg("tag")?.Trim() ?? "";
|
||||||
if (tag == null)
|
|
||||||
tag = "";
|
|
||||||
await e.Channel.SendMessage(await SearchHelper.GetGelbooruImageLink(tag));
|
await e.Channel.SendMessage(await SearchHelper.GetGelbooruImageLink(tag));
|
||||||
});
|
});
|
||||||
cgb.CreateCommand("~e621")
|
cgb.CreateCommand("~e621")
|
||||||
.Description("Shows a random hentai image from e621.net with a given tag. Tag is optional but preffered. Use spaces for multiple tags.\n**Usage**: ~e621 yuri+kissing")
|
.Description("Shows a random hentai image from e621.net with a given tag. Tag is optional but preffered. Use spaces for multiple tags.\n**Usage**: ~e621 yuri+kissing")
|
||||||
.Parameter("tag", ParameterType.Unparsed)
|
.Parameter("tag", ParameterType.Unparsed)
|
||||||
.Do(async e => {
|
.Do(async e => {
|
||||||
string tag = e.GetArg("tag");
|
var tag = e.GetArg("tag")?.Trim() ?? "";
|
||||||
if (tag == null)
|
|
||||||
tag = "";
|
|
||||||
await e.Channel.SendMessage(await SearchHelper.GetE621ImageLink(tag));
|
await e.Channel.SendMessage(await SearchHelper.GetE621ImageLink(tag));
|
||||||
});
|
});
|
||||||
cgb.CreateCommand("~cp")
|
cgb.CreateCommand("~cp")
|
||||||
@ -65,12 +53,23 @@ namespace NadekoBot.Modules {
|
|||||||
.Description("Real adult content.")
|
.Description("Real adult content.")
|
||||||
.Do(async e => {
|
.Do(async e => {
|
||||||
try {
|
try {
|
||||||
var obj = JArray.Parse(await SearchHelper.GetResponseStringAsync($"http://api.oboobs.ru/boobs/{_r.Next(0, 9304)}"))[0];
|
var obj = JArray.Parse(await SearchHelper.GetResponseStringAsync($"http://api.oboobs.ru/boobs/{rng.Next(0, 9380)}"))[0];
|
||||||
await e.Channel.SendMessage($"http://media.oboobs.ru/{ obj["preview"].ToString() }");
|
await e.Channel.SendMessage($"http://media.oboobs.ru/{ obj["preview"].ToString() }");
|
||||||
} catch (Exception ex) {
|
} catch (Exception ex) {
|
||||||
await e.Channel.SendMessage($"💢 {ex.Message}");
|
await e.Channel.SendMessage($"💢 {ex.Message}");
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
cgb.CreateCommand("~butts")
|
||||||
|
.Alias("~ass","~butt")
|
||||||
|
.Description("Real adult content.")
|
||||||
|
.Do(async e => {
|
||||||
|
try {
|
||||||
|
var obj = JArray.Parse(await SearchHelper.GetResponseStringAsync($"http://api.obutts.ru/butts/{rng.Next(0, 3373)}"))[0];
|
||||||
|
await e.Channel.SendMessage($"http://media.obutts.ru/{ obj["preview"].ToString() }");
|
||||||
|
} catch (Exception ex) {
|
||||||
|
await e.Channel.SendMessage($"💢 {ex.Message}");
|
||||||
|
}
|
||||||
|
});
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -12,7 +12,7 @@ namespace NadekoBot.Modules {
|
|||||||
public PermissionModule() {
|
public PermissionModule() {
|
||||||
//Empty for now
|
//Empty for now
|
||||||
}
|
}
|
||||||
|
//todo word filtering/invite bans (?:discord(?:\.gg|app\.com\/invite)\/(?<id>([\w]{16}|(?:[\w]+-?){3})))
|
||||||
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 => {
|
||||||
@ -51,7 +51,7 @@ namespace NadekoBot.Modules {
|
|||||||
.Parameter("arg", ParameterType.Required)
|
.Parameter("arg", ParameterType.Required)
|
||||||
.Do(async e => {
|
.Do(async e => {
|
||||||
var arg = e.GetArg("arg");
|
var arg = e.GetArg("arg");
|
||||||
bool val = PermissionHelper.ValidateBool(arg);
|
var val = PermissionHelper.ValidateBool(arg);
|
||||||
PermsHandler.SetVerbosity(e.Server, val);
|
PermsHandler.SetVerbosity(e.Server, val);
|
||||||
await e.Channel.SendMessage($"Verbosity set to {val}.");
|
await e.Channel.SendMessage($"Verbosity set to {val}.");
|
||||||
});
|
});
|
||||||
@ -72,7 +72,7 @@ namespace NadekoBot.Modules {
|
|||||||
.Parameter("role", ParameterType.Unparsed)
|
.Parameter("role", ParameterType.Unparsed)
|
||||||
.Do(async e => {
|
.Do(async e => {
|
||||||
var arg = e.GetArg("role");
|
var arg = e.GetArg("role");
|
||||||
Discord.Role role = e.Server.EveryoneRole;
|
var role = e.Server.EveryoneRole;
|
||||||
if (!string.IsNullOrWhiteSpace(arg))
|
if (!string.IsNullOrWhiteSpace(arg))
|
||||||
try {
|
try {
|
||||||
role = PermissionHelper.ValidateRole(e.Server, e.GetArg("role"));
|
role = PermissionHelper.ValidateRole(e.Server, e.GetArg("role"));
|
||||||
@ -95,7 +95,7 @@ namespace NadekoBot.Modules {
|
|||||||
.Parameter("channel", ParameterType.Unparsed)
|
.Parameter("channel", ParameterType.Unparsed)
|
||||||
.Do(async e => {
|
.Do(async e => {
|
||||||
var arg = e.GetArg("channel");
|
var arg = e.GetArg("channel");
|
||||||
Discord.Channel channel = e.Channel;
|
var channel = e.Channel;
|
||||||
if (!string.IsNullOrWhiteSpace(arg))
|
if (!string.IsNullOrWhiteSpace(arg))
|
||||||
try {
|
try {
|
||||||
channel = PermissionHelper.ValidateChannel(e.Server, e.GetArg("channel"));
|
channel = PermissionHelper.ValidateChannel(e.Server, e.GetArg("channel"));
|
||||||
@ -117,7 +117,7 @@ namespace NadekoBot.Modules {
|
|||||||
.Parameter("user", ParameterType.Unparsed)
|
.Parameter("user", ParameterType.Unparsed)
|
||||||
.Do(async e => {
|
.Do(async e => {
|
||||||
var arg = e.GetArg("user");
|
var arg = e.GetArg("user");
|
||||||
Discord.User user = e.User;
|
var user = e.User;
|
||||||
if (!string.IsNullOrWhiteSpace(e.GetArg("user")))
|
if (!string.IsNullOrWhiteSpace(e.GetArg("user")))
|
||||||
try {
|
try {
|
||||||
user = PermissionHelper.ValidateUser(e.Server, e.GetArg("user"));
|
user = PermissionHelper.ValidateUser(e.Server, e.GetArg("user"));
|
||||||
@ -139,8 +139,8 @@ namespace NadekoBot.Modules {
|
|||||||
.Description("Sets a module's permission at the server level.\n**Usage**: ;sm [module_name] enable")
|
.Description("Sets a module's permission at the server level.\n**Usage**: ;sm [module_name] enable")
|
||||||
.Do(async e => {
|
.Do(async e => {
|
||||||
try {
|
try {
|
||||||
string module = PermissionHelper.ValidateModule(e.GetArg("module"));
|
var module = PermissionHelper.ValidateModule(e.GetArg("module"));
|
||||||
bool state = PermissionHelper.ValidateBool(e.GetArg("bool"));
|
var state = PermissionHelper.ValidateBool(e.GetArg("bool"));
|
||||||
|
|
||||||
PermsHandler.SetServerModulePermission(e.Server, module, state);
|
PermsHandler.SetServerModulePermission(e.Server, module, state);
|
||||||
await e.Channel.SendMessage($"Module **{module}** has been **{(state ? "enabled" : "disabled")}** on this server.");
|
await e.Channel.SendMessage($"Module **{module}** has been **{(state ? "enabled" : "disabled")}** on this server.");
|
||||||
@ -159,8 +159,8 @@ namespace NadekoBot.Modules {
|
|||||||
.Description("Sets a command's permission at the server level.\n**Usage**: ;sc [command_name] disable")
|
.Description("Sets a command's permission at the server level.\n**Usage**: ;sc [command_name] disable")
|
||||||
.Do(async e => {
|
.Do(async e => {
|
||||||
try {
|
try {
|
||||||
string command = PermissionHelper.ValidateCommand(e.GetArg("command"));
|
var command = PermissionHelper.ValidateCommand(e.GetArg("command"));
|
||||||
bool state = PermissionHelper.ValidateBool(e.GetArg("bool"));
|
var state = PermissionHelper.ValidateBool(e.GetArg("bool"));
|
||||||
|
|
||||||
PermsHandler.SetServerCommandPermission(e.Server, command, state);
|
PermsHandler.SetServerCommandPermission(e.Server, command, state);
|
||||||
await e.Channel.SendMessage($"Command **{command}** has been **{(state ? "enabled" : "disabled")}** on this server.");
|
await e.Channel.SendMessage($"Command **{command}** has been **{(state ? "enabled" : "disabled")}** on this server.");
|
||||||
@ -180,8 +180,8 @@ namespace NadekoBot.Modules {
|
|||||||
.Description("Sets a module's permission at the role level.\n**Usage**: ;rm [module_name] enable [role_name]")
|
.Description("Sets a module's permission at the role level.\n**Usage**: ;rm [module_name] enable [role_name]")
|
||||||
.Do(async e => {
|
.Do(async e => {
|
||||||
try {
|
try {
|
||||||
string module = PermissionHelper.ValidateModule(e.GetArg("module"));
|
var module = PermissionHelper.ValidateModule(e.GetArg("module"));
|
||||||
bool state = PermissionHelper.ValidateBool(e.GetArg("bool"));
|
var state = PermissionHelper.ValidateBool(e.GetArg("bool"));
|
||||||
|
|
||||||
if (e.GetArg("role")?.ToLower() == "all") {
|
if (e.GetArg("role")?.ToLower() == "all") {
|
||||||
foreach (var role in e.Server.Roles) {
|
foreach (var role in e.Server.Roles) {
|
||||||
@ -190,7 +190,7 @@ namespace NadekoBot.Modules {
|
|||||||
await e.Channel.SendMessage($"Module **{module}** has been **{(state ? "enabled" : "disabled")}** for **ALL** roles.");
|
await e.Channel.SendMessage($"Module **{module}** has been **{(state ? "enabled" : "disabled")}** for **ALL** roles.");
|
||||||
}
|
}
|
||||||
else {
|
else {
|
||||||
Discord.Role role = PermissionHelper.ValidateRole(e.Server, e.GetArg("role"));
|
var role = PermissionHelper.ValidateRole(e.Server, e.GetArg("role"));
|
||||||
|
|
||||||
PermsHandler.SetRoleModulePermission(role, module, state);
|
PermsHandler.SetRoleModulePermission(role, module, state);
|
||||||
await e.Channel.SendMessage($"Module **{module}** has been **{(state ? "enabled" : "disabled")}** for **{role.Name}** role.");
|
await e.Channel.SendMessage($"Module **{module}** has been **{(state ? "enabled" : "disabled")}** for **{role.Name}** role.");
|
||||||
@ -211,8 +211,8 @@ namespace NadekoBot.Modules {
|
|||||||
.Description("Sets a command's permission at the role level.\n**Usage**: ;rc [command_name] disable [role_name]")
|
.Description("Sets a command's permission at the role level.\n**Usage**: ;rc [command_name] disable [role_name]")
|
||||||
.Do(async e => {
|
.Do(async e => {
|
||||||
try {
|
try {
|
||||||
string command = PermissionHelper.ValidateCommand(e.GetArg("command"));
|
var command = PermissionHelper.ValidateCommand(e.GetArg("command"));
|
||||||
bool state = PermissionHelper.ValidateBool(e.GetArg("bool"));
|
var state = PermissionHelper.ValidateBool(e.GetArg("bool"));
|
||||||
|
|
||||||
if (e.GetArg("role")?.ToLower() == "all") {
|
if (e.GetArg("role")?.ToLower() == "all") {
|
||||||
foreach (var role in e.Server.Roles) {
|
foreach (var role in e.Server.Roles) {
|
||||||
@ -221,7 +221,7 @@ namespace NadekoBot.Modules {
|
|||||||
await e.Channel.SendMessage($"Command **{command}** has been **{(state ? "enabled" : "disabled")}** for **ALL** roles.");
|
await e.Channel.SendMessage($"Command **{command}** has been **{(state ? "enabled" : "disabled")}** for **ALL** roles.");
|
||||||
}
|
}
|
||||||
else {
|
else {
|
||||||
Discord.Role role = PermissionHelper.ValidateRole(e.Server, e.GetArg("role"));
|
var role = PermissionHelper.ValidateRole(e.Server, e.GetArg("role"));
|
||||||
|
|
||||||
PermsHandler.SetRoleCommandPermission(role, command, state);
|
PermsHandler.SetRoleCommandPermission(role, command, state);
|
||||||
await e.Channel.SendMessage($"Command **{command}** has been **{(state ? "enabled" : "disabled")}** for **{role.Name}** role.");
|
await e.Channel.SendMessage($"Command **{command}** has been **{(state ? "enabled" : "disabled")}** for **{role.Name}** role.");
|
||||||
@ -242,8 +242,8 @@ namespace NadekoBot.Modules {
|
|||||||
.Description("Sets a module's permission at the channel level.\n**Usage**: ;cm [module_name] enable [channel_name]")
|
.Description("Sets a module's permission at the channel level.\n**Usage**: ;cm [module_name] enable [channel_name]")
|
||||||
.Do(async e => {
|
.Do(async e => {
|
||||||
try {
|
try {
|
||||||
string module = PermissionHelper.ValidateModule(e.GetArg("module"));
|
var module = PermissionHelper.ValidateModule(e.GetArg("module"));
|
||||||
bool state = PermissionHelper.ValidateBool(e.GetArg("bool"));
|
var state = PermissionHelper.ValidateBool(e.GetArg("bool"));
|
||||||
|
|
||||||
if (e.GetArg("channel")?.ToLower() == "all") {
|
if (e.GetArg("channel")?.ToLower() == "all") {
|
||||||
foreach (var channel in e.Server.TextChannels) {
|
foreach (var channel in e.Server.TextChannels) {
|
||||||
@ -252,7 +252,7 @@ namespace NadekoBot.Modules {
|
|||||||
await e.Channel.SendMessage($"Module **{module}** has been **{(state ? "enabled" : "disabled")}** on **ALL** channels.");
|
await e.Channel.SendMessage($"Module **{module}** has been **{(state ? "enabled" : "disabled")}** on **ALL** channels.");
|
||||||
}
|
}
|
||||||
else {
|
else {
|
||||||
Discord.Channel channel = PermissionHelper.ValidateChannel(e.Server, e.GetArg("channel"));
|
var channel = PermissionHelper.ValidateChannel(e.Server, e.GetArg("channel"));
|
||||||
|
|
||||||
PermsHandler.SetChannelModulePermission(channel, module, state);
|
PermsHandler.SetChannelModulePermission(channel, module, state);
|
||||||
await e.Channel.SendMessage($"Module **{module}** has been **{(state ? "enabled" : "disabled")}** for **{channel.Name}** channel.");
|
await e.Channel.SendMessage($"Module **{module}** has been **{(state ? "enabled" : "disabled")}** for **{channel.Name}** channel.");
|
||||||
@ -273,8 +273,8 @@ namespace NadekoBot.Modules {
|
|||||||
.Description("Sets a command's permission at the channel level.\n**Usage**: ;cc [command_name] enable [channel_name]")
|
.Description("Sets a command's permission at the channel level.\n**Usage**: ;cc [command_name] enable [channel_name]")
|
||||||
.Do(async e => {
|
.Do(async e => {
|
||||||
try {
|
try {
|
||||||
string command = PermissionHelper.ValidateCommand(e.GetArg("command"));
|
var command = PermissionHelper.ValidateCommand(e.GetArg("command"));
|
||||||
bool state = PermissionHelper.ValidateBool(e.GetArg("bool"));
|
var state = PermissionHelper.ValidateBool(e.GetArg("bool"));
|
||||||
|
|
||||||
if (e.GetArg("channel")?.ToLower() == "all") {
|
if (e.GetArg("channel")?.ToLower() == "all") {
|
||||||
foreach (var channel in e.Server.TextChannels) {
|
foreach (var channel in e.Server.TextChannels) {
|
||||||
@ -283,7 +283,7 @@ namespace NadekoBot.Modules {
|
|||||||
await e.Channel.SendMessage($"Command **{command}** has been **{(state ? "enabled" : "disabled")}** on **ALL** channels.");
|
await e.Channel.SendMessage($"Command **{command}** has been **{(state ? "enabled" : "disabled")}** on **ALL** channels.");
|
||||||
}
|
}
|
||||||
else {
|
else {
|
||||||
Discord.Channel channel = PermissionHelper.ValidateChannel(e.Server, e.GetArg("channel"));
|
var channel = PermissionHelper.ValidateChannel(e.Server, e.GetArg("channel"));
|
||||||
|
|
||||||
PermsHandler.SetChannelCommandPermission(channel, command, state);
|
PermsHandler.SetChannelCommandPermission(channel, command, state);
|
||||||
await e.Channel.SendMessage($"Command **{command}** has been **{(state ? "enabled" : "disabled")}** for **{channel.Name}** channel.");
|
await e.Channel.SendMessage($"Command **{command}** has been **{(state ? "enabled" : "disabled")}** for **{channel.Name}** channel.");
|
||||||
@ -304,9 +304,9 @@ namespace NadekoBot.Modules {
|
|||||||
.Description("Sets a module's permission at the user level.\n**Usage**: ;um [module_name] enable [user_name]")
|
.Description("Sets a module's permission at the user level.\n**Usage**: ;um [module_name] enable [user_name]")
|
||||||
.Do(async e => {
|
.Do(async e => {
|
||||||
try {
|
try {
|
||||||
string module = PermissionHelper.ValidateModule(e.GetArg("module"));
|
var module = PermissionHelper.ValidateModule(e.GetArg("module"));
|
||||||
bool state = PermissionHelper.ValidateBool(e.GetArg("bool"));
|
var state = PermissionHelper.ValidateBool(e.GetArg("bool"));
|
||||||
Discord.User user = PermissionHelper.ValidateUser(e.Server, e.GetArg("user"));
|
var user = PermissionHelper.ValidateUser(e.Server, e.GetArg("user"));
|
||||||
|
|
||||||
PermsHandler.SetUserModulePermission(user, module, state);
|
PermsHandler.SetUserModulePermission(user, module, state);
|
||||||
await e.Channel.SendMessage($"Module **{module}** has been **{(state ? "enabled" : "disabled")}** for user **{user.Name}**.");
|
await e.Channel.SendMessage($"Module **{module}** has been **{(state ? "enabled" : "disabled")}** for user **{user.Name}**.");
|
||||||
@ -326,9 +326,9 @@ namespace NadekoBot.Modules {
|
|||||||
.Description("Sets a command's permission at the user level.\n**Usage**: ;uc [command_name] enable [user_name]")
|
.Description("Sets a command's permission at the user level.\n**Usage**: ;uc [command_name] enable [user_name]")
|
||||||
.Do(async e => {
|
.Do(async e => {
|
||||||
try {
|
try {
|
||||||
string command = PermissionHelper.ValidateCommand(e.GetArg("command"));
|
var command = PermissionHelper.ValidateCommand(e.GetArg("command"));
|
||||||
bool state = PermissionHelper.ValidateBool(e.GetArg("bool"));
|
var state = PermissionHelper.ValidateBool(e.GetArg("bool"));
|
||||||
Discord.User user = PermissionHelper.ValidateUser(e.Server, e.GetArg("user"));
|
var user = PermissionHelper.ValidateUser(e.Server, e.GetArg("user"));
|
||||||
|
|
||||||
PermsHandler.SetUserCommandPermission(user, command, state);
|
PermsHandler.SetUserCommandPermission(user, command, state);
|
||||||
await e.Channel.SendMessage($"Command **{command}** has been **{(state ? "enabled" : "disabled")}** for user **{user.Name}**.");
|
await e.Channel.SendMessage($"Command **{command}** has been **{(state ? "enabled" : "disabled")}** for user **{user.Name}**.");
|
||||||
@ -346,7 +346,7 @@ namespace NadekoBot.Modules {
|
|||||||
.Description("Sets permissions for all modules at the server level.\n**Usage**: ;asm [enable/disable]")
|
.Description("Sets permissions for all modules at the server level.\n**Usage**: ;asm [enable/disable]")
|
||||||
.Do(async e => {
|
.Do(async e => {
|
||||||
try {
|
try {
|
||||||
bool state = PermissionHelper.ValidateBool(e.GetArg("bool"));
|
var 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);
|
||||||
@ -367,8 +367,8 @@ namespace NadekoBot.Modules {
|
|||||||
.Description("Sets permissions for all commands from a certain module at the server level.\n**Usage**: ;asc [module_name] [enable/disable]")
|
.Description("Sets permissions for all commands from a certain module at the server level.\n**Usage**: ;asc [module_name] [enable/disable]")
|
||||||
.Do(async e => {
|
.Do(async e => {
|
||||||
try {
|
try {
|
||||||
bool state = PermissionHelper.ValidateBool(e.GetArg("bool"));
|
var state = PermissionHelper.ValidateBool(e.GetArg("bool"));
|
||||||
string module = PermissionHelper.ValidateModule(e.GetArg("module"));
|
var 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);
|
||||||
@ -389,8 +389,8 @@ namespace NadekoBot.Modules {
|
|||||||
.Description("Sets permissions for all modules at the channel level.\n**Usage**: ;acm [enable/disable] [channel_name]")
|
.Description("Sets permissions for all modules at the channel level.\n**Usage**: ;acm [enable/disable] [channel_name]")
|
||||||
.Do(async e => {
|
.Do(async e => {
|
||||||
try {
|
try {
|
||||||
bool state = PermissionHelper.ValidateBool(e.GetArg("bool"));
|
var state = PermissionHelper.ValidateBool(e.GetArg("bool"));
|
||||||
Discord.Channel channel = PermissionHelper.ValidateChannel(e.Server, e.GetArg("channel"));
|
var 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);
|
||||||
}
|
}
|
||||||
@ -412,9 +412,9 @@ namespace NadekoBot.Modules {
|
|||||||
.Description("Sets permissions for all commands from a certain module at the channel level.\n**Usage**: ;acc [module_name] [enable/disable] [channel_name]")
|
.Description("Sets permissions for all commands from a certain module at the channel level.\n**Usage**: ;acc [module_name] [enable/disable] [channel_name]")
|
||||||
.Do(async e => {
|
.Do(async e => {
|
||||||
try {
|
try {
|
||||||
bool state = PermissionHelper.ValidateBool(e.GetArg("bool"));
|
var state = PermissionHelper.ValidateBool(e.GetArg("bool"));
|
||||||
string module = PermissionHelper.ValidateModule(e.GetArg("module"));
|
var module = PermissionHelper.ValidateModule(e.GetArg("module"));
|
||||||
Discord.Channel channel = PermissionHelper.ValidateChannel(e.Server, e.GetArg("channel"));
|
var 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);
|
||||||
}
|
}
|
||||||
@ -434,8 +434,8 @@ namespace NadekoBot.Modules {
|
|||||||
.Description("Sets permissions for all modules at the role level.\n**Usage**: ;arm [enable/disable] [role_name]")
|
.Description("Sets permissions for all modules at the role level.\n**Usage**: ;arm [enable/disable] [role_name]")
|
||||||
.Do(async e => {
|
.Do(async e => {
|
||||||
try {
|
try {
|
||||||
bool state = PermissionHelper.ValidateBool(e.GetArg("bool"));
|
var state = PermissionHelper.ValidateBool(e.GetArg("bool"));
|
||||||
Discord.Role role = PermissionHelper.ValidateRole(e.Server, e.GetArg("role"));
|
var 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);
|
||||||
}
|
}
|
||||||
@ -457,9 +457,9 @@ namespace NadekoBot.Modules {
|
|||||||
.Description("Sets permissions for all commands from a certain module at the role level.\n**Usage**: ;arc [module_name] [enable/disable] [channel_name]")
|
.Description("Sets permissions for all commands from a certain module at the role level.\n**Usage**: ;arc [module_name] [enable/disable] [channel_name]")
|
||||||
.Do(async e => {
|
.Do(async e => {
|
||||||
try {
|
try {
|
||||||
bool state = PermissionHelper.ValidateBool(e.GetArg("bool"));
|
var state = PermissionHelper.ValidateBool(e.GetArg("bool"));
|
||||||
string module = PermissionHelper.ValidateModule(e.GetArg("module"));
|
var module = PermissionHelper.ValidateModule(e.GetArg("module"));
|
||||||
Discord.Role role = PermissionHelper.ValidateRole(e.Server, e.GetArg("channel"));
|
var 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);
|
||||||
}
|
}
|
||||||
|
@ -8,6 +8,7 @@ using Discord.Modules;
|
|||||||
using Discord.Audio;
|
using Discord.Audio;
|
||||||
using System.Timers;
|
using System.Timers;
|
||||||
using System.Linq;
|
using System.Linq;
|
||||||
|
using System.Text;
|
||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
using NadekoBot.Classes;
|
using NadekoBot.Classes;
|
||||||
using NadekoBot.Classes.JSONModels;
|
using NadekoBot.Classes.JSONModels;
|
||||||
@ -23,6 +24,7 @@ namespace NadekoBot {
|
|||||||
private static Channel OwnerPrivateChannel { get; set; }
|
private static Channel OwnerPrivateChannel { get; set; }
|
||||||
|
|
||||||
private static void Main() {
|
private static void Main() {
|
||||||
|
Console.OutputEncoding = Encoding.Unicode;
|
||||||
try {
|
try {
|
||||||
//load credentials from credentials.json
|
//load credentials from credentials.json
|
||||||
Creds = JsonConvert.DeserializeObject<Credentials>(File.ReadAllText("credentials.json"));
|
Creds = JsonConvert.DeserializeObject<Credentials>(File.ReadAllText("credentials.json"));
|
||||||
|
@ -118,6 +118,7 @@
|
|||||||
<Compile Include="Classes\DBHandler.cs" />
|
<Compile Include="Classes\DBHandler.cs" />
|
||||||
<Compile Include="Classes\FlowersHandler.cs" />
|
<Compile Include="Classes\FlowersHandler.cs" />
|
||||||
<Compile Include="Classes\JSONModels\AnimeResult.cs" />
|
<Compile Include="Classes\JSONModels\AnimeResult.cs" />
|
||||||
|
<Compile Include="Classes\JSONModels\Config.cs" />
|
||||||
<Compile Include="Classes\JSONModels\MangaResult.cs" />
|
<Compile Include="Classes\JSONModels\MangaResult.cs" />
|
||||||
<Compile Include="Classes\JSONModels\_JSONModels.cs" />
|
<Compile Include="Classes\JSONModels\_JSONModels.cs" />
|
||||||
<Compile Include="Classes\Music\MusicControls.cs" />
|
<Compile Include="Classes\Music\MusicControls.cs" />
|
||||||
|
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Loading…
Reference in New Issue
Block a user