more work, repo DOES NOT BUILD

This commit is contained in:
Master Kwoth 2016-03-01 12:44:30 +01:00
parent 874eefdf89
commit 1f2b9cd3d3
32 changed files with 194 additions and 224 deletions

View File

@ -6,7 +6,7 @@ using System;
using System.Linq.Expressions; using System.Linq.Expressions;
namespace NadekoBot.Classes { namespace NadekoBot.Classes {
class DBHandler { internal class DBHandler {
private static readonly DBHandler _instance = new DBHandler(); private static readonly DBHandler _instance = new DBHandler();
public static DBHandler Instance => _instance; public static DBHandler Instance => _instance;

View File

@ -1,7 +1,7 @@
using System.Threading.Tasks; using System.Threading.Tasks;
namespace NadekoBot.Classes { namespace NadekoBot.Classes {
static class FlowersHandler { internal static class FlowersHandler {
public static async Task AddFlowersAsync(Discord.User u, string reason, int amount) { public static async Task AddFlowersAsync(Discord.User u, string reason, int amount) {
if (amount <= 0) if (amount <= 0)
return; return;

View File

@ -299,7 +299,7 @@ namespace NadekoBot.Classes.Music {
public long readPos; public long readPos;
public long writePos; public long writePos;
public DualStream() : base() { public DualStream() {
readPos = writePos = 0; readPos = writePos = 0;
} }

View File

@ -6,7 +6,7 @@ using Discord.Commands;
using System.Collections.Concurrent; using System.Collections.Concurrent;
namespace NadekoBot.Classes.Permissions { namespace NadekoBot.Classes.Permissions {
class PermissionChecker : IPermissionChecker { internal class PermissionChecker : IPermissionChecker {
public static readonly PermissionChecker _instance = new PermissionChecker(); public static readonly PermissionChecker _instance = new PermissionChecker();
public static PermissionChecker Instance => _instance; public static PermissionChecker Instance => _instance;

View File

@ -5,7 +5,7 @@ using System.Linq;
using Discord; using Discord;
namespace NadekoBot.Classes { namespace NadekoBot.Classes {
static class PermissionHelper { internal static class PermissionHelper {
public static bool ValidateBool(string passedArg) { public static bool ValidateBool(string passedArg) {
if (string.IsNullOrWhiteSpace(passedArg)) { if (string.IsNullOrWhiteSpace(passedArg)) {
throw new ArgumentException("No value supplied! Missing argument"); throw new ArgumentException("No value supplied! Missing argument");

View File

@ -5,46 +5,57 @@ using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.IO; using System.IO;
using System.Net; using System.Net;
using System.Net.Http;
using System.Security.Authentication;
using System.Text.RegularExpressions; using System.Text.RegularExpressions;
using System.Threading.Tasks; using System.Threading.Tasks;
using NadekoBot.Classes.JSONModels;
namespace NadekoBot.Classes { namespace NadekoBot.Classes {
public enum RequestHttpMethod {
Get, Post
}
public static class SearchHelper { public static class SearchHelper {
public static async Task<Stream> GetResponseStream(string v) {
var wr = (HttpWebRequest)WebRequest.Create(v); public static async Task<Stream> GetResponseStream(string query, RequestHttpMethod method = RequestHttpMethod.Get) {
return (await (wr).GetResponseAsync()).GetResponseStream(); if (string.IsNullOrWhiteSpace(query))
throw new ArgumentNullException(nameof(query));
var wr = (HttpWebRequest)WebRequest.Create(query);
using (var response = await wr.GetResponseAsync()) {
var stream = response?.GetResponseStream();
if (stream == null)
throw new InvalidOperationException("Did not receive a response.");
return stream;
}
} }
public static async Task<string> GetResponseAsync(string v, WebHeaderCollection headers = null) { public static async Task<string> GetResponseAsync(string url, RequestHttpMethod method = RequestHttpMethod.Get, params Tuple<string,string>[] headers) {
var wr = (HttpWebRequest)WebRequest.Create(v); using (var httpClient = new HttpClient()) {
if (headers != null) if (headers != null) {
wr.Headers = headers; foreach (var header in headers) {
var stream = (await wr.GetResponseAsync()).GetResponseStream(); httpClient.DefaultRequestHeaders.Add(header.Key, header.Value);
if (stream == null) return ""; }
using (var sr = new StreamReader(stream)) { }
return await sr.ReadToEndAsync(); return await httpClient.GetStringAsync(url);
} }
} }
private static string token = ""; private static string token = "";
public static async Task<AnimeResult> GetAnimeQueryResultLink(string query) { public static async Task<AnimeResult> GetAnimeQueryResultLink(string query) {
try { if (string.IsNullOrWhiteSpace(query))
var cl = new RestSharp.RestClient("http://anilist.co/api"); throw new ArgumentNullException(nameof(query));
var rq = new RestSharp.RestRequest("/auth/access_token", RestSharp.Method.POST);
RefreshAnilistToken(); RefreshAnilistToken();
rq = new RestSharp.RestRequest("/anime/search/" + Uri.EscapeUriString(query)); var link = "http://anilist.co/api/anime/search/" + Uri.EscapeUriString(query);
rq.AddParameter("access_token", token);
var smallObj = JArray.Parse(cl.Execute(rq).Content)[0]; Dictionary<string, string> headers = new {"access_token" = token};
var smallContent = await GetResponseAsync(link, headers);
var smallObj = JArray.Parse(await httpClient.GetStringAsync(link))[0];
var content = await httpClient.GetStringAsync("anime/" + smallObj["id"]);
rq = new RestSharp.RestRequest("anime/" + smallObj["id"]); return await Task.Run(() => JsonConvert.DeserializeObject<AnimeResult>(content));
rq.AddParameter("access_token", token);
return await Task.Run(() => JsonConvert.DeserializeObject<AnimeResult>(cl.Execute(rq).Content));
} catch {
return null;
}
} }
//todo kick out RestSharp and make it truly async //todo kick out RestSharp and make it truly async
public static async Task<MangaResult> GetMangaQueryResultLink(string query) { public static async Task<MangaResult> GetMangaQueryResultLink(string query) {
@ -83,32 +94,36 @@ namespace NadekoBot.Classes {
} }
public static async Task<bool> ValidateQuery(Discord.Channel ch, string query) { public static async Task<bool> ValidateQuery(Discord.Channel ch, string query) {
if (string.IsNullOrEmpty(query.Trim())) { if (!string.IsNullOrEmpty(query.Trim())) return true;
await ch.Send("Please specify search parameters."); await ch.Send("Please specify search parameters.");
return false; return false;
}
return true;
} }
public static async Task<string> FindYoutubeUrlByKeywords(string v) { public static async Task<string> FindYoutubeUrlByKeywords(string keywords) {
if (string.IsNullOrWhiteSpace(NadekoBot.GoogleAPIKey)) { if (string.IsNullOrWhiteSpace(NadekoBot.Creds.GoogleAPIKey))
Console.WriteLine("ERROR: No google api key found. Playing `Never gonna give you up`."); throw new InvalidCredentialException("Google API Key is missing.");
return @"https://www.youtube.com/watch?v=dQw4w9WgXcQ"; if (keywords.Length > 150)
throw new ArgumentException("Query is too long.");
//maybe it is already a youtube url, in which case we will just extract the id and prepend it with youtube.com?v=
var match = new Regex("(?:youtu\\.be\\/|v=)(?<id>[\\da-zA-Z\\-_]*)").Match(keywords);
if (match.Length > 1) {
return $"http://www.youtube.com?v={ match.Groups["id"].Value }";
} }
var wr =
WebRequest.Create(
$"https://www.googleapis.com/youtube/v3/search?part=snippet&maxResults=1&q={Uri.EscapeDataString(keywords)}&key={NadekoBot.Creds.GoogleAPIKey}");
try { try {
//maybe it is already a youtube url, in which case we will just extract the id and prepend it with youtube.com?v= using (var response = await wr.GetResponseAsync())
var match = new Regex("(?:youtu\\.be\\/|v=)(?<id>[\\da-zA-Z\\-_]*)").Match(v); using (var stream = response.GetResponseStream()) {
if (match.Length > 1) { try {
string str = $"http://www.youtube.com?v={ match.Groups["id"].Value }"; using (var sr = new StreamReader(stream)) {
return str; dynamic obj = JObject.Parse(await sr.ReadToEndAsync());
} return "http://www.youtube.com/watch?v=" + obj.items[0].id.videoId.ToString();
}
WebRequest wr = WebRequest.Create("https://www.googleapis.com/youtube/v3/search?part=snippet&maxResults=1&q=" + Uri.EscapeDataString(v) + "&key=" + NadekoBot.GoogleAPIKey); } catch (Exception ex) {
ex.Message
using (var sr = new StreamReader((await wr.GetResponseAsync()).GetResponseStream())) { }
dynamic obj = JObject.Parse(await sr.ReadToEndAsync());
return "http://www.youtube.com/watch?v=" + obj.items[0].id.videoId.ToString();
} }
} catch (Exception ex) { } catch (Exception ex) {
Console.WriteLine($"Error in findyoutubeurl: {ex.Message}"); Console.WriteLine($"Error in findyoutubeurl: {ex.Message}");
@ -117,12 +132,12 @@ namespace NadekoBot.Classes {
} }
public static async Task<string> GetPlaylistIdByKeyword(string v) { public static async Task<string> GetPlaylistIdByKeyword(string v) {
if (string.IsNullOrWhiteSpace(NadekoBot.GoogleAPIKey)) { if (string.IsNullOrWhiteSpace(NadekoBot.Creds.GoogleAPIKey)) {
Console.WriteLine("ERROR: No google api key found. Playing `Never gonna give you up`."); Console.WriteLine("ERROR: No google api key found. Playing `Never gonna give you up`.");
return string.Empty; return string.Empty;
} }
try { try {
WebRequest wr = WebRequest.Create($"https://www.googleapis.com/youtube/v3/search?part=snippet&maxResults=1&q={Uri.EscapeDataString(v)}&type=playlist&key={NadekoBot.creds.GoogleAPIKey}"); WebRequest wr = WebRequest.Create($"https://www.googleapis.com/youtube/v3/search?part=snippet&maxResults=1&q={Uri.EscapeDataString(v)}&type=playlist&key={NadekoBot.Creds.GoogleAPIKey}");
var sr = new StreamReader((await wr.GetResponseAsync()).GetResponseStream()); var sr = new StreamReader((await wr.GetResponseAsync()).GetResponseStream());
@ -136,12 +151,12 @@ namespace NadekoBot.Classes {
public static async Task<List<string>> GetVideoIDs(string v) { public static async Task<List<string>> GetVideoIDs(string v) {
List<string> toReturn = new List<string>(); List<string> toReturn = new List<string>();
if (string.IsNullOrWhiteSpace(NadekoBot.GoogleAPIKey)) { if (string.IsNullOrWhiteSpace(NadekoBot.Creds.GoogleAPIKey)) {
Console.WriteLine("ERROR: No google api key found. Playing `Never gonna give you up`."); Console.WriteLine("ERROR: No google api key found. Playing `Never gonna give you up`.");
return toReturn; return toReturn;
} }
try { try {
WebRequest wr = WebRequest.Create($"https://www.googleapis.com/youtube/v3/playlistItems?part=contentDetails&maxResults={30}&playlistId={v}&key={ NadekoBot.creds.GoogleAPIKey }"); WebRequest wr = WebRequest.Create($"https://www.googleapis.com/youtube/v3/playlistItems?part=contentDetails&maxResults={30}&playlistId={v}&key={ NadekoBot.Creds.GoogleAPIKey }");
var response = await wr.GetResponseAsync(); var response = await wr.GetResponseAsync();
if (response == null) return toReturn; if (response == null) return toReturn;
var responseStream = response.GetResponseStream(); var responseStream = response.GetResponseStream();
@ -206,9 +221,9 @@ namespace NadekoBot.Classes {
} }
public static async Task<string> ShortenUrl(string url) { public static async Task<string> ShortenUrl(string url) {
if (string.IsNullOrWhiteSpace(NadekoBot.creds.GoogleAPIKey)) return url; if (string.IsNullOrWhiteSpace(NadekoBot.Creds.GoogleAPIKey)) return url;
try { try {
var httpWebRequest = (HttpWebRequest)WebRequest.Create("https://www.googleapis.com/urlshortener/v1/url?key=" + NadekoBot.creds.GoogleAPIKey); var httpWebRequest = (HttpWebRequest)WebRequest.Create("https://www.googleapis.com/urlshortener/v1/url?key=" + NadekoBot.Creds.GoogleAPIKey);
httpWebRequest.ContentType = "application/json"; httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST"; httpWebRequest.Method = "POST";

View File

@ -9,7 +9,7 @@ using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace NadekoBot.Classes.Trivia { namespace NadekoBot.Classes.Trivia {
class TriviaGame { internal class TriviaGame {
private readonly object _guessLock = new object(); private readonly object _guessLock = new object();
private Server _server { get; } private Server _server { get; }

View File

@ -7,7 +7,7 @@ using System.Collections.Concurrent;
using System.Threading; using System.Threading;
namespace NadekoBot.Commands { namespace NadekoBot.Commands {
class ClashOfClans : DiscordCommand { internal class ClashOfClans : DiscordCommand {
private static string prefix = ","; private static string prefix = ",";
@ -15,7 +15,7 @@ namespace NadekoBot.Commands {
private object writeLock { get; } = new object(); private object writeLock { get; } = new object();
public ClashOfClans() : base() { public ClashOfClans() {
} }

View File

@ -5,11 +5,11 @@ using Discord.Commands;
namespace NadekoBot namespace NadekoBot
{ {
class CopyCommand : DiscordCommand internal class CopyCommand : DiscordCommand
{ {
private List<ulong> CopiedUsers; private List<ulong> CopiedUsers;
public CopyCommand() : base() public CopyCommand()
{ {
CopiedUsers = new List<ulong>(); CopiedUsers = new List<ulong>();
client.MessageReceived += Client_MessageReceived; client.MessageReceived += Client_MessageReceived;

View File

@ -8,8 +8,8 @@ using System.Drawing.Imaging;
using NadekoBot.Extensions; using NadekoBot.Extensions;
namespace NadekoBot { namespace NadekoBot {
class DiceRollCommand : DiscordCommand { internal class DiceRollCommand : DiscordCommand {
public DiceRollCommand() : base() { } public DiceRollCommand() { }
public override Func<CommandEventArgs, Task> DoFunc() { public override Func<CommandEventArgs, Task> DoFunc() {
Random r = new Random(); Random r = new Random();

View File

@ -7,10 +7,10 @@ using System.Collections.Concurrent;
using NadekoBot.Extensions; using NadekoBot.Extensions;
namespace NadekoBot { namespace NadekoBot {
class DrawCommand : DiscordCommand { internal class DrawCommand : DiscordCommand {
private static ConcurrentDictionary<Discord.Server, Cards> AllDecks = new ConcurrentDictionary<Discord.Server, Cards>(); private static ConcurrentDictionary<Discord.Server, Cards> AllDecks = new ConcurrentDictionary<Discord.Server, Cards>();
public DrawCommand() : base() { public DrawCommand() {
} }

View File

@ -5,10 +5,10 @@ using NadekoBot.Extensions;
using System.Drawing; using System.Drawing;
namespace NadekoBot { namespace NadekoBot {
class FlipCoinCommand : DiscordCommand { internal class FlipCoinCommand : DiscordCommand {
private Random _r; private Random _r;
public FlipCoinCommand() : base() { public FlipCoinCommand() {
_r = new Random(); _r = new Random();
} }

View File

@ -6,7 +6,7 @@ using System.IO;
using System.Linq; using System.Linq;
namespace NadekoBot { namespace NadekoBot {
class HelpCommand : DiscordCommand { internal class HelpCommand : DiscordCommand {
public override Func<CommandEventArgs, Task> DoFunc() => async e => { public override Func<CommandEventArgs, Task> DoFunc() => async e => {
#region OldHelp #region OldHelp
/* /*

View File

@ -9,7 +9,7 @@ using NadekoBot.Extensions;
using Newtonsoft.Json.Linq; using Newtonsoft.Json.Linq;
namespace NadekoBot.Commands { namespace NadekoBot.Commands {
class LoLCommands : DiscordCommand { internal class LoLCommands : DiscordCommand {
private class CachedChampion { private class CachedChampion {
public System.IO.Stream ImageStream { get; set; } public System.IO.Stream ImageStream { get; set; }
@ -22,7 +22,7 @@ namespace NadekoBot.Commands {
private System.Timers.Timer clearTimer { get; } = new System.Timers.Timer(); private System.Timers.Timer clearTimer { get; } = new System.Timers.Timer();
public LoLCommands() : base() { public LoLCommands() {
clearTimer.Interval = new TimeSpan(0, 10, 0).TotalMilliseconds; clearTimer.Interval = new TimeSpan(0, 10, 0).TotalMilliseconds;
clearTimer.Start(); clearTimer.Start();
clearTimer.Elapsed += (s, e) => { clearTimer.Elapsed += (s, e) => {
@ -36,7 +36,7 @@ namespace NadekoBot.Commands {
}; };
} }
string[] trashTalk = new[] { "Better ban your counters. You are going to carry the game anyway.", private string[] trashTalk = new[] { "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.",
@ -47,7 +47,7 @@ namespace NadekoBot.Commands {
throw new NotImplementedException(); throw new NotImplementedException();
} }
class MatchupModel { private class MatchupModel {
public int Games { get; set; } public int Games { get; set; }
public float WinRate { get; set; } public float WinRate { get; set; }
[Newtonsoft.Json.JsonProperty("key")] [Newtonsoft.Json.JsonProperty("key")]
@ -270,7 +270,8 @@ Assists: {general["assists"]} Ban: {general["banRate"]}%
} }
}); });
} }
enum GetImageType {
private enum GetImageType {
Champion, Champion,
Item Item
} }

View File

@ -5,19 +5,19 @@ using Discord.Commands;
using Discord; using Discord;
namespace NadekoBot.Commands { namespace NadekoBot.Commands {
class LogCommand : DiscordCommand { internal class LogCommand : DiscordCommand {
public LogCommand() : base() { public LogCommand() {
NadekoBot.Client.MessageReceived += MsgRecivd; NadekoBot.Client.MessageReceived += MsgRecivd;
NadekoBot.Client.MessageDeleted += MsgDltd; NadekoBot.Client.MessageDeleted += MsgDltd;
NadekoBot.Client.MessageUpdated += MsgUpdtd; NadekoBot.Client.MessageUpdated += MsgUpdtd;
NadekoBot.Client.UserUpdated += UsrUpdtd; NadekoBot.Client.UserUpdated += UsrUpdtd;
} }
ConcurrentDictionary<Server, Channel> logs = new ConcurrentDictionary<Server, Channel>(); private ConcurrentDictionary<Server, Channel> logs = new ConcurrentDictionary<Server, Channel>();
ConcurrentDictionary<Server, Channel> loggingPresences = new ConcurrentDictionary<Server, Channel>(); private ConcurrentDictionary<Server, Channel> loggingPresences = new ConcurrentDictionary<Server, Channel>();
// //
ConcurrentDictionary<Channel, Channel> voiceChannelLog = new ConcurrentDictionary<Channel, Channel>(); private ConcurrentDictionary<Channel, Channel> voiceChannelLog = new ConcurrentDictionary<Channel, Channel>();
public override Func<CommandEventArgs, Task> DoFunc() => async e => { public override Func<CommandEventArgs, Task> DoFunc() => async e => {
if (!NadekoBot.IsOwner(e.User.Id) || if (!NadekoBot.IsOwner(e.User.Id) ||

View File

@ -7,7 +7,7 @@ using Discord.Commands;
using System.Timers; using System.Timers;
namespace NadekoBot.Commands { namespace NadekoBot.Commands {
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 Timer timer = new Timer(12000);

View File

@ -4,7 +4,7 @@ using Discord.Commands;
using NadekoBot.Extensions; using NadekoBot.Extensions;
namespace NadekoBot.Commands { namespace NadekoBot.Commands {
class RequestsCommand : DiscordCommand { internal class RequestsCommand : DiscordCommand {
public void SaveRequest(CommandEventArgs e, string text) { public void SaveRequest(CommandEventArgs e, string text) {
Classes.DBHandler.Instance.InsertData(new Classes._DataModels.Request { Classes.DBHandler.Instance.InsertData(new Classes._DataModels.Request {
RequestText = text, RequestText = text,

View File

@ -21,13 +21,13 @@ public class AsyncLazy<T> : Lazy<Task<T>>
*/ */
namespace NadekoBot.Commands { namespace NadekoBot.Commands {
class ServerGreetCommand : DiscordCommand { internal class ServerGreetCommand : DiscordCommand {
public static ConcurrentDictionary<ulong, AnnounceControls> AnnouncementsDictionary; public static ConcurrentDictionary<ulong, AnnounceControls> AnnouncementsDictionary;
public static long Greeted = 0; public static long Greeted = 0;
public ServerGreetCommand() : base() { public ServerGreetCommand() {
AnnouncementsDictionary = new ConcurrentDictionary<ulong, AnnounceControls>(); AnnouncementsDictionary = new ConcurrentDictionary<ulong, AnnounceControls>();
NadekoBot.Client.UserJoined += UserJoined; NadekoBot.Client.UserJoined += UserJoined;

View File

@ -105,11 +105,11 @@ namespace NadekoBot.Commands {
} }
class SpeedTyping : DiscordCommand { internal class SpeedTyping : DiscordCommand {
private static Dictionary<ulong, TypingGame> runningContests; private static Dictionary<ulong, TypingGame> runningContests;
public SpeedTyping() : base() { public SpeedTyping() {
runningContests = new Dictionary<ulong, TypingGame>(); runningContests = new Dictionary<ulong, TypingGame>();
} }

View File

@ -6,7 +6,7 @@ using Discord;
using TriviaGame = NadekoBot.Classes.Trivia.TriviaGame; using TriviaGame = NadekoBot.Classes.Trivia.TriviaGame;
namespace NadekoBot.Commands { namespace NadekoBot.Commands {
class Trivia : DiscordCommand { internal class Trivia : DiscordCommand {
public static ConcurrentDictionary<Server, TriviaGame> runningTrivias = new ConcurrentDictionary<Server, TriviaGame>(); public static ConcurrentDictionary<Server, TriviaGame> runningTrivias = new ConcurrentDictionary<Server, TriviaGame>();
public override Func<CommandEventArgs, Task> DoFunc() => async e => { public override Func<CommandEventArgs, Task> DoFunc() => async e => {

View File

@ -6,15 +6,15 @@ using System.Collections.Concurrent;
using Discord; using Discord;
namespace NadekoBot.Commands { namespace NadekoBot.Commands {
class VoiceNotificationCommand : DiscordCommand { internal class VoiceNotificationCommand : DiscordCommand {
public VoiceNotificationCommand() : base() { public VoiceNotificationCommand() {
//NadekoBot.client. //NadekoBot.client.
} }
//voicechannel/text channel //voicechannel/text channel
ConcurrentDictionary<Channel, Channel> subscribers = new ConcurrentDictionary<Channel, Channel>(); private ConcurrentDictionary<Channel, Channel> subscribers = new ConcurrentDictionary<Channel, Channel>();
public override Func<CommandEventArgs, Task> DoFunc() => async e => { public override Func<CommandEventArgs, Task> DoFunc() => async e => {
var arg = e.GetArg("voice_name"); var arg = e.GetArg("voice_name");

View File

@ -15,9 +15,9 @@ using NadekoBot.Properties;
using NadekoBot.Commands; using NadekoBot.Commands;
namespace NadekoBot.Modules { namespace NadekoBot.Modules {
class Conversations : DiscordModule { internal class Conversations : DiscordModule {
private string firestr = "🔥 ด้้้้้็็็็็้้้้้็็็็็้้้้้้้้็็็็็้้้้้็็ด้้้้้็็็็็้้้้้็็็็็้้้้้้้้็็็็็้้้้้็็็็็้้้้้้้้็็็ด้้้้้็็็็็้้้้้็็็็็้้้้้้้้็็็็็้้้้้็็็็็้้้้ 🔥"; private string firestr = "🔥 ด้้้้้็็็็็้้้้้็็็็็้้้้้้้้็็็็็้้้้้็็ด้้้้้็็็็็้้้้้็็็็็้้้้้้้้็็็็็้้้้้็็็็็้้้้้้้้็็็ด้้้้้็็็็็้้้้้็็็็็้้้้้้้้็็็็็้้้้้็็็็็้้้้ 🔥";
public Conversations() : base() { public Conversations() {
commands.Add(new CopyCommand()); commands.Add(new CopyCommand());
commands.Add(new RequestsCommand()); commands.Add(new RequestsCommand());
} }

View File

@ -1,14 +1,11 @@
using Discord.Modules; using Discord.Modules;
using System.Collections.Generic; using System.Collections.Generic;
namespace NadekoBot.Modules namespace NadekoBot.Modules {
{ internal abstract class DiscordModule : IModule {
abstract class DiscordModule : IModule protected List<DiscordCommand> commands = new List<DiscordCommand>();
{
public List<DiscordCommand> commands;
protected DiscordModule() { protected DiscordModule() {
commands = new List<DiscordCommand>();
} }
public abstract void Install(ModuleManager manager); public abstract void Install(ModuleManager manager);

View File

@ -2,10 +2,11 @@
using Discord.Modules; using Discord.Modules;
using NadekoBot.Extensions; using NadekoBot.Extensions;
using System.Linq; using System.Linq;
using Discord;
namespace NadekoBot.Modules namespace NadekoBot.Modules
{ {
class Gambling : DiscordModule internal class Gambling : DiscordModule
{ {
public Gambling() { public Gambling() {
@ -33,33 +34,16 @@ namespace NadekoBot.Modules
return; return;
} }
var members = role.Members.Where(u => u.Status == Discord.UserStatus.Online); // only online var members = role.Members.Where(u => u.Status == Discord.UserStatus.Online); // only online
try { var membersArray = members as User[] ?? members.ToArray();
var usr = members.ToArray()[new System.Random().Next(0, members.Count())]; var usr = membersArray[new System.Random().Next(0, membersArray.Length)];
await e.Channel.SendMessage($"**Raffled user:** {usr.Name} (id: {usr.Id})"); await e.Channel.SendMessage($"**Raffled user:** {usr.Name} (id: {usr.Id})");
}
catch { }
}); });
/*
cgb.CreateCommand("$$")
.Description("Add moneyz")
.Parameter("val", ParameterType.Required)
.Do(e => {
var arg = e.GetArg("val");
var num = int.Parse(arg);
Classes.DBHandler.Instance.InsertData(
new Classes._DataModels.CurrencyTransaction {
Value = num,
Reason = "Money plz",
UserId = (long)e.User.Id,
});
});
*/
cgb.CreateCommand("$$$") cgb.CreateCommand("$$$")
.Description("Check how many NadekoFlowers you have.") .Description("Check how many NadekoFlowers you have.")
.Do(async e => { .Do(async e => {
var pts = Classes.DBHandler.Instance.GetStateByUserId((long)e.User.Id)?.Value ?? 0; var pts = Classes.DBHandler.Instance.GetStateByUserId((long)e.User.Id)?.Value ?? 0;
string str = $"`You have {pts} NadekoFlowers".SnPl((int)pts)+"`\n"; var str = $"`You have {pts} NadekoFlowers".SnPl((int)pts)+"`\n";
for (int i = 0; i < pts; i++) { for (var i = 0; i < pts; i++) {
str += "🌸"; str += "🌸";
} }
await e.Channel.SendMessage(str); await e.Channel.SendMessage(str);

View File

@ -6,14 +6,12 @@ using Newtonsoft.Json.Linq;
using System.IO; using System.IO;
//🃏 //🃏
//🏁 //🏁
namespace NadekoBot.Modules namespace NadekoBot.Modules {
{ internal class Games : DiscordModule {
class Games : DiscordModule private readonly string[] _8BallAnswers;
{ private Random rng = new Random();
private string[] _8BallAnswers;
private Random _r = new Random();
public Games() : base() { public Games() {
commands.Add(new Trivia()); commands.Add(new Trivia());
commands.Add(new SpeedTyping()); commands.Add(new SpeedTyping());
commands.Add(new PollCommand()); commands.Add(new PollCommand());
@ -22,8 +20,7 @@ namespace NadekoBot.Modules
_8BallAnswers = JArray.Parse(File.ReadAllText("data/8ball.json")).Select(t => t.ToString()).ToArray(); _8BallAnswers = JArray.Parse(File.ReadAllText("data/8ball.json")).Select(t => t.ToString()).ToArray();
} }
public override void Install(ModuleManager manager) public override void Install(ModuleManager manager) {
{
manager.CreateCommands("", cgb => { manager.CreateCommands("", cgb => {
cgb.AddCheck(Classes.Permissions.PermissionChecker.Instance); cgb.AddCheck(Classes.Permissions.PermissionChecker.Instance);
@ -40,39 +37,35 @@ namespace NadekoBot.Modules
var list = arg.Split(';'); var list = arg.Split(';');
if (list.Count() < 2) if (list.Count() < 2)
return; return;
await e.Channel.SendMessage(list[new Random().Next(0, list.Length)]); await e.Channel.SendMessage(list[rng.Next(0, list.Length)]);
}); });
cgb.CreateCommand(">8ball") cgb.CreateCommand(">8ball")
.Description("Ask the 8ball a yes/no question.") .Description("Ask the 8ball a yes/no question.")
.Parameter("question",Discord.Commands.ParameterType.Unparsed) .Parameter("question", Discord.Commands.ParameterType.Unparsed)
.Do(async e => { .Do(async e => {
string question = e.GetArg("question"); var question = e.GetArg("question");
if (string.IsNullOrWhiteSpace(question)) if (string.IsNullOrWhiteSpace(question))
return; return;
try { try {
await e.Channel.SendMessage( await e.Channel.SendMessage(
$":question: **Question**: `{question}` \n:crystal_ball: **8Ball Answers**: `{_8BallAnswers[new Random().Next(0, _8BallAnswers.Length)]}`"); $":question: **Question**: `{question}` \n:crystal_ball: **8Ball Answers**: `{_8BallAnswers[rng.Next(0, _8BallAnswers.Length)]}`");
} } catch { }
catch { }
}); });
cgb.CreateCommand(">") cgb.CreateCommand(">")
.Description("Attack a person. Supported attacks: 'splash', 'strike', 'burn', 'surge'.\n**Usage**: > strike @User") .Description("Attack a person. Supported attacks: 'splash', 'strike', 'burn', 'surge'.\n**Usage**: > strike @User")
.Parameter("attack_type",Discord.Commands.ParameterType.Required) .Parameter("attack_type", Discord.Commands.ParameterType.Required)
.Parameter("target",Discord.Commands.ParameterType.Required) .Parameter("target", Discord.Commands.ParameterType.Required)
.Do(async e => .Do(async e => {
{
var usr = e.Server.FindUsers(e.GetArg("target")).FirstOrDefault(); var usr = e.Server.FindUsers(e.GetArg("target")).FirstOrDefault();
var usrType = GetType(usr.Id); var usrType = GetType(usr.Id);
string response = ""; var response = "";
int dmg = GetDamage(usrType, e.GetArg("attack_type").ToLowerInvariant()); var dmg = GetDamage(usrType, e.GetArg("attack_type").ToLowerInvariant());
response = e.GetArg("attack_type") + (e.GetArg("attack_type") == "splash" ? "es " : "s ") + $"{usr.Mention}{GetImage(usrType)} for {dmg}\n"; response = e.GetArg("attack_type") + (e.GetArg("attack_type") == "splash" ? "es " : "s ") + $"{usr.Mention}{GetImage(usrType)} for {dmg}\n";
if (dmg >= 65) if (dmg >= 65) {
{
response += "It's super effective!"; response += "It's super effective!";
} } else if (dmg <= 35) {
else if (dmg <= 35) {
response += "Ineffective!"; response += "Ineffective!";
} }
await e.Channel.SendMessage($"{ e.User.Mention }{GetImage(GetType(e.User.Id))} {response}"); await e.Channel.SendMessage($"{ e.User.Mention }{GetImage(GetType(e.User.Id))} {response}");
@ -81,11 +74,11 @@ namespace NadekoBot.Modules
cgb.CreateCommand("poketype") cgb.CreateCommand("poketype")
.Parameter("target", Discord.Commands.ParameterType.Required) .Parameter("target", Discord.Commands.ParameterType.Required)
.Description("Gets the users element type. Use this to do more damage with strike!") .Description("Gets the users element type. Use this to do more damage with strike!")
.Do(async e => .Do(async e => {
{
var usr = e.Server.FindUsers(e.GetArg("target")).FirstOrDefault(); var usr = e.Server.FindUsers(e.GetArg("target")).FirstOrDefault();
if (usr == null) { if (usr == null) {
await e.Channel.SendMessage("No such person."); await e.Channel.SendMessage("No such person.");
return;
} }
var t = GetType(usr.Id); var t = GetType(usr.Id);
await e.Channel.SendMessage($"{usr.Name}'s type is {GetImage(t)} {t}"); await e.Channel.SendMessage($"{usr.Name}'s type is {GetImage(t)} {t}");
@ -104,7 +97,8 @@ namespace NadekoBot.Modules
🐛 Insect 🐛 Insect
🌟 or 💫 or Fairy 🌟 or 💫 or Fairy
*/ */
string GetImage(PokeType t) {
private string GetImage(PokeType t) {
switch (t) { switch (t) {
case PokeType.WATER: case PokeType.WATER:
return "💦"; return "💦";
@ -119,11 +113,9 @@ namespace NadekoBot.Modules
} }
} }
private int GetDamage(PokeType targetType, string v) private int GetDamage(PokeType targetType, string v) {
{
var rng = new Random(); var rng = new Random();
switch (v) switch (v) {
{
case "splash": //water case "splash": //water
if (targetType == PokeType.FIRE) if (targetType == PokeType.FIRE)
return rng.Next(65, 100); return rng.Next(65, 100);
@ -166,21 +158,16 @@ namespace NadekoBot.Modules
var remainder = id % 10; var remainder = id % 10;
if (remainder < 3) if (remainder < 3)
return PokeType.WATER; return PokeType.WATER;
else if (remainder >= 3 && remainder < 5) else if (remainder >= 3 && remainder < 5) {
{
return PokeType.GRASS; return PokeType.GRASS;
} } else if (remainder >= 5 && remainder < 8) {
else if (remainder >= 5 && remainder < 8)
{
return PokeType.FIRE; return PokeType.FIRE;
} } else {
else {
return PokeType.ELECTRICAL; return PokeType.ELECTRICAL;
} }
} }
private enum PokeType private enum PokeType {
{
WATER, GRASS, FIRE, ELECTRICAL WATER, GRASS, FIRE, ELECTRICAL
} }
} }

View File

@ -3,9 +3,9 @@ using Discord.Modules;
using Discord.Commands; using Discord.Commands;
namespace NadekoBot.Modules { namespace NadekoBot.Modules {
class Help : DiscordModule { internal class Help : DiscordModule {
public Help() : base() { public Help() {
commands.Add(new HelpCommand()); commands.Add(new HelpCommand());
} }

View File

@ -11,16 +11,16 @@ using System.Threading.Tasks;
using Timer = System.Timers.Timer; using Timer = System.Timers.Timer;
namespace NadekoBot.Modules { namespace NadekoBot.Modules {
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>();
Timer setgameTimer => new Timer(); private Timer setgameTimer => new Timer();
bool setgameEnabled = false; private bool setgameEnabled = false;
public Music() : base() { public Music() {
setgameTimer.Interval = 20000; setgameTimer.Interval = 20000;
setgameTimer.Elapsed += (s, e) => { setgameTimer.Elapsed += (s, e) => {

View File

@ -5,11 +5,11 @@ using Newtonsoft.Json.Linq;
using NadekoBot.Classes; using NadekoBot.Classes;
namespace NadekoBot.Modules { namespace NadekoBot.Modules {
class NSFW : DiscordModule { internal class NSFW : DiscordModule {
private Random _r = new Random(); private Random _r = new Random();
public NSFW() : base() { public NSFW() {
} }

View File

@ -6,9 +6,10 @@ using PermsHandler = NadekoBot.Classes.Permissions.PermissionsHandler;
using System.Linq; using System.Linq;
namespace NadekoBot.Modules { namespace NadekoBot.Modules {
class PermissionModule : DiscordModule { internal class PermissionModule : DiscordModule {
string prefix = ";"; private const string prefix = ";";
public PermissionModule() : base() {
public PermissionModule() {
//Empty for now //Empty for now
} }
@ -135,7 +136,7 @@ namespace NadekoBot.Modules {
cgb.CreateCommand(prefix + "sm").Alias(prefix + "servermodule") cgb.CreateCommand(prefix + "sm").Alias(prefix + "servermodule")
.Parameter("module", ParameterType.Required) .Parameter("module", ParameterType.Required)
.Parameter("bool", ParameterType.Required) .Parameter("bool", ParameterType.Required)
.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")); string module = PermissionHelper.ValidateModule(e.GetArg("module"));
@ -155,7 +156,7 @@ namespace NadekoBot.Modules {
cgb.CreateCommand(prefix + "sc").Alias(prefix + "servercommand") cgb.CreateCommand(prefix + "sc").Alias(prefix + "servercommand")
.Parameter("command", ParameterType.Required) .Parameter("command", ParameterType.Required)
.Parameter("bool", ParameterType.Required) .Parameter("bool", ParameterType.Required)
.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")); string command = PermissionHelper.ValidateCommand(e.GetArg("command"));
@ -176,7 +177,7 @@ namespace NadekoBot.Modules {
.Parameter("module", ParameterType.Required) .Parameter("module", ParameterType.Required)
.Parameter("bool", ParameterType.Required) .Parameter("bool", ParameterType.Required)
.Parameter("role", ParameterType.Unparsed) .Parameter("role", ParameterType.Unparsed)
.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")); string module = PermissionHelper.ValidateModule(e.GetArg("module"));
@ -207,7 +208,7 @@ namespace NadekoBot.Modules {
.Parameter("command", ParameterType.Required) .Parameter("command", ParameterType.Required)
.Parameter("bool", ParameterType.Required) .Parameter("bool", ParameterType.Required)
.Parameter("role", ParameterType.Unparsed) .Parameter("role", ParameterType.Unparsed)
.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")); string command = PermissionHelper.ValidateCommand(e.GetArg("command"));
@ -238,7 +239,7 @@ namespace NadekoBot.Modules {
.Parameter("module", ParameterType.Required) .Parameter("module", ParameterType.Required)
.Parameter("bool", ParameterType.Required) .Parameter("bool", ParameterType.Required)
.Parameter("channel", ParameterType.Unparsed) .Parameter("channel", ParameterType.Unparsed)
.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")); string module = PermissionHelper.ValidateModule(e.GetArg("module"));
@ -269,7 +270,7 @@ namespace NadekoBot.Modules {
.Parameter("command", ParameterType.Required) .Parameter("command", ParameterType.Required)
.Parameter("bool", ParameterType.Required) .Parameter("bool", ParameterType.Required)
.Parameter("channel", ParameterType.Unparsed) .Parameter("channel", ParameterType.Unparsed)
.Description("Sets a command's permission at the channel level.\n**Usage**: ;cm 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")); string command = PermissionHelper.ValidateCommand(e.GetArg("command"));
@ -300,7 +301,7 @@ namespace NadekoBot.Modules {
.Parameter("module", ParameterType.Required) .Parameter("module", ParameterType.Required)
.Parameter("bool", ParameterType.Required) .Parameter("bool", ParameterType.Required)
.Parameter("user", ParameterType.Unparsed) .Parameter("user", ParameterType.Unparsed)
.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")); string module = PermissionHelper.ValidateModule(e.GetArg("module"));
@ -322,7 +323,7 @@ namespace NadekoBot.Modules {
.Parameter("command", ParameterType.Required) .Parameter("command", ParameterType.Required)
.Parameter("bool", ParameterType.Required) .Parameter("bool", ParameterType.Required)
.Parameter("user", ParameterType.Unparsed) .Parameter("user", ParameterType.Unparsed)
.Description("Sets a command's permission at the user level.\n**Usage**: ;uc <module_command> 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")); string command = PermissionHelper.ValidateCommand(e.GetArg("command"));
@ -342,7 +343,7 @@ namespace NadekoBot.Modules {
cgb.CreateCommand(prefix + "asm").Alias(prefix + "allservermodules") cgb.CreateCommand(prefix + "asm").Alias(prefix + "allservermodules")
.Parameter("bool", ParameterType.Required) .Parameter("bool", ParameterType.Required)
.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")); bool state = PermissionHelper.ValidateBool(e.GetArg("bool"));
@ -363,7 +364,7 @@ namespace NadekoBot.Modules {
cgb.CreateCommand(prefix + "asc").Alias(prefix + "allservercommands") cgb.CreateCommand(prefix + "asc").Alias(prefix + "allservercommands")
.Parameter("module", ParameterType.Required) .Parameter("module", ParameterType.Required)
.Parameter("bool", ParameterType.Required) .Parameter("bool", ParameterType.Required)
.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")); bool state = PermissionHelper.ValidateBool(e.GetArg("bool"));
@ -385,7 +386,7 @@ namespace NadekoBot.Modules {
cgb.CreateCommand(prefix + "acm").Alias(prefix + "allchannelmodules") cgb.CreateCommand(prefix + "acm").Alias(prefix + "allchannelmodules")
.Parameter("bool", ParameterType.Required) .Parameter("bool", ParameterType.Required)
.Parameter("channel", ParameterType.Unparsed) .Parameter("channel", ParameterType.Unparsed)
.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")); bool state = PermissionHelper.ValidateBool(e.GetArg("bool"));
@ -408,7 +409,7 @@ namespace NadekoBot.Modules {
.Parameter("module", ParameterType.Required) .Parameter("module", ParameterType.Required)
.Parameter("bool", ParameterType.Required) .Parameter("bool", ParameterType.Required)
.Parameter("channel", ParameterType.Unparsed) .Parameter("channel", ParameterType.Unparsed)
.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")); bool state = PermissionHelper.ValidateBool(e.GetArg("bool"));
@ -430,7 +431,7 @@ namespace NadekoBot.Modules {
cgb.CreateCommand(prefix + "arm").Alias(prefix + "allrolemodules") cgb.CreateCommand(prefix + "arm").Alias(prefix + "allrolemodules")
.Parameter("bool", ParameterType.Required) .Parameter("bool", ParameterType.Required)
.Parameter("role", ParameterType.Unparsed) .Parameter("role", ParameterType.Unparsed)
.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")); bool state = PermissionHelper.ValidateBool(e.GetArg("bool"));
@ -453,7 +454,7 @@ namespace NadekoBot.Modules {
.Parameter("module", ParameterType.Required) .Parameter("module", ParameterType.Required)
.Parameter("bool", ParameterType.Required) .Parameter("bool", ParameterType.Required)
.Parameter("channel", ParameterType.Unparsed) .Parameter("channel", ParameterType.Unparsed)
.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")); bool state = PermissionHelper.ValidateBool(e.GetArg("bool"));

View File

@ -10,16 +10,14 @@ using NadekoBot.Classes;
using NadekoBot.Commands; using NadekoBot.Commands;
namespace NadekoBot.Modules { namespace NadekoBot.Modules {
class Searches : DiscordModule { internal class Searches : DiscordModule {
private Random _r; private readonly Random rng;
public Searches() : base() { public Searches() {
commands.Add(new LoLCommands()); commands.Add(new LoLCommands());
_r = new Random(); rng = new Random();
} }
public override void Install(ModuleManager manager) { public override void Install(ModuleManager manager) {
var client = NadekoBot.Client;
manager.CreateCommands("", cgb => { manager.CreateCommands("", cgb => {
cgb.AddCheck(Classes.Permissions.PermissionChecker.Instance); cgb.AddCheck(Classes.Permissions.PermissionChecker.Instance);
@ -34,14 +32,14 @@ namespace NadekoBot.Modules {
var str = await SearchHelper.ShortenUrl(await SearchHelper.FindYoutubeUrlByKeywords(e.GetArg("query"))); var str = await SearchHelper.ShortenUrl(await SearchHelper.FindYoutubeUrlByKeywords(e.GetArg("query")));
if (string.IsNullOrEmpty(str.Trim())) { if (string.IsNullOrEmpty(str.Trim())) {
await e.Channel.SendMessage("Query failed"); await e.Channel.SendMessage("Query failed.");
return; return;
} }
await e.Channel.SendMessage(str); await e.Channel.SendMessage(str);
}); });
cgb.CreateCommand("~ani") cgb.CreateCommand("~ani")
.Alias("~anime").Alias("~aq") .Alias("~anime", "~aq")
.Parameter("query", ParameterType.Unparsed) .Parameter("query", ParameterType.Unparsed)
.Description("Queries anilist for an anime and shows the first result.") .Description("Queries anilist for an anime and shows the first result.")
.Do(async e => { .Do(async e => {
@ -75,13 +73,10 @@ namespace NadekoBot.Modules {
.Description("Shows a random cat image.") .Description("Shows a random cat image.")
.Do(async e => { .Do(async e => {
try { try {
await e.Channel.SendMessage(JObject.Parse(new StreamReader( await e.Channel.SendMessage(JObject.Parse(
WebRequest.Create("http://www.random.cat/meow") await SearchHelper.GetResponseAsync("http://www.random.cat/meow"))["file"].ToString());
.GetResponse()
.GetResponseStream())
.ReadToEnd())["file"].ToString());
} }
catch { } catch {}
}); });
cgb.CreateCommand("~i") cgb.CreateCommand("~i")
@ -91,11 +86,10 @@ namespace NadekoBot.Modules {
if (string.IsNullOrWhiteSpace(e.GetArg("query"))) if (string.IsNullOrWhiteSpace(e.GetArg("query")))
return; return;
try { try {
var reqString = $"https://www.googleapis.com/customsearch/v1?q={Uri.EscapeDataString(e.GetArg("query"))}&cx=018084019232060951019%3Ahs5piey28-e&num=1&searchType=image&fields=items%2Flink&key={NadekoBot.creds.GoogleAPIKey}"; var reqString = $"https://www.googleapis.com/customsearch/v1?q={Uri.EscapeDataString(e.GetArg("query"))}&cx=018084019232060951019%3Ahs5piey28-e&num=1&searchType=image&fields=items%2Flink&key={NadekoBot.Creds.GoogleAPIKey}";
var obj = JObject.Parse(await SearchHelper.GetResponseAsync(reqString)); var obj = JObject.Parse(await SearchHelper.GetResponseAsync(reqString));
await e.Channel.SendMessage(obj["items"][0]["link"].ToString()); await e.Channel.SendMessage(obj["items"][0]["link"].ToString());
} } catch (Exception ex) {
catch (Exception ex) {
await e.Channel.SendMessage($"💢 {ex.Message}"); await e.Channel.SendMessage($"💢 {ex.Message}");
} }
}); });
@ -107,11 +101,10 @@ namespace NadekoBot.Modules {
if (string.IsNullOrWhiteSpace(e.GetArg("query"))) if (string.IsNullOrWhiteSpace(e.GetArg("query")))
return; return;
try { try {
var reqString = $"https://www.googleapis.com/customsearch/v1?q={Uri.EscapeDataString(e.GetArg("query"))}&cx=018084019232060951019%3Ahs5piey28-e&num=1&searchType=image&start={ _r.Next(1, 150) }&fields=items%2Flink&key={NadekoBot.creds.GoogleAPIKey}"; var reqString = $"https://www.googleapis.com/customsearch/v1?q={Uri.EscapeDataString(e.GetArg("query"))}&cx=018084019232060951019%3Ahs5piey28-e&num=1&searchType=image&start={ rng.Next(1, 150) }&fields=items%2Flink&key={NadekoBot.Creds.GoogleAPIKey}";
var obj = JObject.Parse(await SearchHelper.GetResponseAsync(reqString)); var obj = JObject.Parse(await SearchHelper.GetResponseAsync(reqString));
await e.Channel.SendMessage(obj["items"][0]["link"].ToString()); await e.Channel.SendMessage(obj["items"][0]["link"].ToString());
} } catch (Exception ex) {
catch (Exception ex) {
await e.Channel.SendMessage($"💢 {ex.Message}"); await e.Channel.SendMessage($"💢 {ex.Message}");
} }
}); });
@ -134,8 +127,7 @@ namespace NadekoBot.Modules {
return; return;
} }
await e.Channel.SendIsTyping(); await e.Channel.SendIsTyping();
var headers = new WebHeaderCollection(); var headers = new WebHeaderCollection {{"X-Mashape-Key", NadekoBot.Creds.MashapeKey}};
headers.Add("X-Mashape-Key", NadekoBot.creds.MashapeKey);
var res = await SearchHelper.GetResponseAsync($"https://omgvamp-hearthstone-v1.p.mashape.com/cards/search/{Uri.EscapeUriString(arg)}", headers); var res = await SearchHelper.GetResponseAsync($"https://omgvamp-hearthstone-v1.p.mashape.com/cards/search/{Uri.EscapeUriString(arg)}", headers);
try { try {
var items = JArray.Parse(res); var items = JArray.Parse(res);
@ -155,11 +147,8 @@ namespace NadekoBot.Modules {
if (items.Count > 4) { if (items.Count > 4) {
await e.Channel.SendMessage("⚠ Found over 4 images. Showing random 4."); await e.Channel.SendMessage("⚠ Found over 4 images. Showing random 4.");
} }
Console.WriteLine("Start");
await e.Channel.SendFile(arg + ".png", (await images.MergeAsync()).ToStream(System.Drawing.Imaging.ImageFormat.Png)); await e.Channel.SendFile(arg + ".png", (await images.MergeAsync()).ToStream(System.Drawing.Imaging.ImageFormat.Png));
Console.WriteLine("Finish"); } catch (Exception ex) {
}
catch (Exception ex) {
await e.Channel.SendMessage($"💢 Error {ex.Message}"); await e.Channel.SendMessage($"💢 Error {ex.Message}");
} }
}); });
@ -180,11 +169,9 @@ namespace NadekoBot.Modules {
try { try {
await e.Channel.SendFile($"{e.GetArg("usr")}.png", new MemoryStream(cle.Result)); await e.Channel.SendFile($"{e.GetArg("usr")}.png", new MemoryStream(cle.Result));
await e.Channel.SendMessage($"`Profile Link:`https://osu.ppy.sh/u/{Uri.EscapeDataString(e.GetArg("usr"))}\n`Image provided by https://lemmmy.pw/osusig`"); await e.Channel.SendMessage($"`Profile Link:`https://osu.ppy.sh/u/{Uri.EscapeDataString(e.GetArg("usr"))}\n`Image provided by https://lemmmy.pw/osusig`");
} } catch { }
catch { }
}; };
} } catch {
catch {
await e.Channel.SendMessage("💢 Failed retrieving osu signature :\\"); await e.Channel.SendMessage("💢 Failed retrieving osu signature :\\");
} }
} }
@ -201,7 +188,7 @@ namespace NadekoBot.Modules {
} }
await e.Channel.SendIsTyping(); await e.Channel.SendIsTyping();
var headers = new WebHeaderCollection(); var headers = new WebHeaderCollection();
headers.Add("X-Mashape-Key", NadekoBot.creds.MashapeKey); headers.Add("X-Mashape-Key", NadekoBot.Creds.MashapeKey);
var res = await SearchHelper.GetResponseAsync($"https://mashape-community-urban-dictionary.p.mashape.com/define?term={Uri.EscapeUriString(arg)}", headers); var res = await SearchHelper.GetResponseAsync($"https://mashape-community-urban-dictionary.p.mashape.com/define?term={Uri.EscapeUriString(arg)}", headers);
try { try {
var items = JObject.Parse(res); var items = JObject.Parse(res);
@ -210,8 +197,7 @@ namespace NadekoBot.Modules {
sb.AppendLine($"`Definition:` {items["list"][0]["definition"].ToString()}"); sb.AppendLine($"`Definition:` {items["list"][0]["definition"].ToString()}");
sb.Append($"`Link:` <{await items["list"][0]["permalink"].ToString().ShortenUrl()}>"); sb.Append($"`Link:` <{await items["list"][0]["permalink"].ToString().ShortenUrl()}>");
await e.Channel.SendMessage(sb.ToString()); await e.Channel.SendMessage(sb.ToString());
} } catch {
catch {
await e.Channel.SendMessage("💢 Failed finding a definition for that term."); await e.Channel.SendMessage("💢 Failed finding a definition for that term.");
} }
}); });
@ -227,7 +213,7 @@ namespace NadekoBot.Modules {
} }
await e.Channel.SendIsTyping(); await e.Channel.SendIsTyping();
var headers = new WebHeaderCollection(); var headers = new WebHeaderCollection();
headers.Add("X-Mashape-Key", NadekoBot.creds.MashapeKey); headers.Add("X-Mashape-Key", NadekoBot.Creds.MashapeKey);
var res = await SearchHelper.GetResponseAsync($"https://tagdef.p.mashape.com/one.{Uri.EscapeUriString(arg)}.json", headers); var res = await SearchHelper.GetResponseAsync($"https://tagdef.p.mashape.com/one.{Uri.EscapeUriString(arg)}.json", headers);
try { try {
var items = JObject.Parse(res); var items = JObject.Parse(res);
@ -236,8 +222,7 @@ namespace NadekoBot.Modules {
sb.AppendLine($"`Definition:` {items["defs"]["def"]["text"].ToString()}"); sb.AppendLine($"`Definition:` {items["defs"]["def"]["text"].ToString()}");
sb.Append($"`Link:` <{await items["defs"]["def"]["uri"].ToString().ShortenUrl()}>"); sb.Append($"`Link:` <{await items["defs"]["def"]["uri"].ToString().ShortenUrl()}>");
await e.Channel.SendMessage(sb.ToString()); await e.Channel.SendMessage(sb.ToString());
} } catch {
catch {
await e.Channel.SendMessage("💢 Failed finidng a definition for that tag."); await e.Channel.SendMessage("💢 Failed finidng a definition for that tag.");
} }
}); });

View File

@ -8,7 +8,7 @@ using System.Timers;
using NadekoBot.Extensions; using NadekoBot.Extensions;
namespace NadekoBot.Modules { namespace NadekoBot.Modules {
class Trello : DiscordModule { internal class Trello : DiscordModule {
public override void Install(ModuleManager manager) { public override void Install(ModuleManager manager) {
var client = manager.Client; var client = manager.Client;

View File

@ -21,7 +21,7 @@ namespace NadekoBot {
private static Channel OwnerPrivateChannel { get; set; } private static Channel OwnerPrivateChannel { get; set; }
static void Main() { private static void Main() {
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"));