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;
namespace NadekoBot.Classes {
class DBHandler {
internal class DBHandler {
private static readonly DBHandler _instance = new DBHandler();
public static DBHandler Instance => _instance;

View File

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

View File

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

View File

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

View File

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

View File

@ -5,46 +5,57 @@ using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Security.Authentication;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using NadekoBot.Classes.JSONModels;
namespace NadekoBot.Classes {
public static class SearchHelper {
public static async Task<Stream> GetResponseStream(string v) {
var wr = (HttpWebRequest)WebRequest.Create(v);
return (await (wr).GetResponseAsync()).GetResponseStream();
public enum RequestHttpMethod {
Get, Post
}
public static async Task<string> GetResponseAsync(string v, WebHeaderCollection headers = null) {
var wr = (HttpWebRequest)WebRequest.Create(v);
if (headers != null)
wr.Headers = headers;
var stream = (await wr.GetResponseAsync()).GetResponseStream();
if (stream == null) return "";
using (var sr = new StreamReader(stream)) {
return await sr.ReadToEndAsync();
public static class SearchHelper {
public static async Task<Stream> GetResponseStream(string query, RequestHttpMethod method = RequestHttpMethod.Get) {
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 url, RequestHttpMethod method = RequestHttpMethod.Get, params Tuple<string,string>[] headers) {
using (var httpClient = new HttpClient()) {
if (headers != null) {
foreach (var header in headers) {
httpClient.DefaultRequestHeaders.Add(header.Key, header.Value);
}
}
return await httpClient.GetStringAsync(url);
}
}
private static string token = "";
public static async Task<AnimeResult> GetAnimeQueryResultLink(string query) {
try {
var cl = new RestSharp.RestClient("http://anilist.co/api");
var rq = new RestSharp.RestRequest("/auth/access_token", RestSharp.Method.POST);
if (string.IsNullOrWhiteSpace(query))
throw new ArgumentNullException(nameof(query));
RefreshAnilistToken();
rq = new RestSharp.RestRequest("/anime/search/" + Uri.EscapeUriString(query));
rq.AddParameter("access_token", token);
var link = "http://anilist.co/api/anime/search/" + Uri.EscapeUriString(query);
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"]);
rq.AddParameter("access_token", token);
return await Task.Run(() => JsonConvert.DeserializeObject<AnimeResult>(cl.Execute(rq).Content));
} catch {
return null;
}
return await Task.Run(() => JsonConvert.DeserializeObject<AnimeResult>(content));
}
//todo kick out RestSharp and make it truly async
public static async Task<MangaResult> GetMangaQueryResultLink(string query) {
@ -83,33 +94,37 @@ namespace NadekoBot.Classes {
}
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.");
return false;
}
return true;
}
public static async Task<string> FindYoutubeUrlByKeywords(string v) {
if (string.IsNullOrWhiteSpace(NadekoBot.GoogleAPIKey)) {
Console.WriteLine("ERROR: No google api key found. Playing `Never gonna give you up`.");
return @"https://www.youtube.com/watch?v=dQw4w9WgXcQ";
}
try {
public static async Task<string> FindYoutubeUrlByKeywords(string keywords) {
if (string.IsNullOrWhiteSpace(NadekoBot.Creds.GoogleAPIKey))
throw new InvalidCredentialException("Google API Key is missing.");
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(v);
var match = new Regex("(?:youtu\\.be\\/|v=)(?<id>[\\da-zA-Z\\-_]*)").Match(keywords);
if (match.Length > 1) {
string str = $"http://www.youtube.com?v={ match.Groups["id"].Value }";
return str;
return $"http://www.youtube.com?v={ match.Groups["id"].Value }";
}
WebRequest wr = WebRequest.Create("https://www.googleapis.com/youtube/v3/search?part=snippet&maxResults=1&q=" + Uri.EscapeDataString(v) + "&key=" + NadekoBot.GoogleAPIKey);
using (var sr = new StreamReader((await wr.GetResponseAsync()).GetResponseStream())) {
var wr =
WebRequest.Create(
$"https://www.googleapis.com/youtube/v3/search?part=snippet&maxResults=1&q={Uri.EscapeDataString(keywords)}&key={NadekoBot.Creds.GoogleAPIKey}");
try {
using (var response = await wr.GetResponseAsync())
using (var stream = response.GetResponseStream()) {
try {
using (var sr = new StreamReader(stream)) {
dynamic obj = JObject.Parse(await sr.ReadToEndAsync());
return "http://www.youtube.com/watch?v=" + obj.items[0].id.videoId.ToString();
}
} catch (Exception ex) {
ex.Message
}
}
} catch (Exception ex) {
Console.WriteLine($"Error in findyoutubeurl: {ex.Message}");
return string.Empty;
@ -117,12 +132,12 @@ namespace NadekoBot.Classes {
}
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`.");
return string.Empty;
}
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());
@ -136,12 +151,12 @@ namespace NadekoBot.Classes {
public static async Task<List<string>> GetVideoIDs(string v) {
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`.");
return toReturn;
}
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();
if (response == null) return toReturn;
var responseStream = response.GetResponseStream();
@ -206,9 +221,9 @@ namespace NadekoBot.Classes {
}
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 {
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.Method = "POST";

View File

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

View File

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

View File

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

View File

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

View File

@ -7,10 +7,10 @@ using System.Collections.Concurrent;
using NadekoBot.Extensions;
namespace NadekoBot {
class DrawCommand : DiscordCommand {
internal class DrawCommand : DiscordCommand {
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;
namespace NadekoBot {
class FlipCoinCommand : DiscordCommand {
internal class FlipCoinCommand : DiscordCommand {
private Random _r;
public FlipCoinCommand() : base() {
public FlipCoinCommand() {
_r = new Random();
}

View File

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

View File

@ -9,7 +9,7 @@ using NadekoBot.Extensions;
using Newtonsoft.Json.Linq;
namespace NadekoBot.Commands {
class LoLCommands : DiscordCommand {
internal class LoLCommands : DiscordCommand {
private class CachedChampion {
public System.IO.Stream ImageStream { get; set; }
@ -22,7 +22,7 @@ namespace NadekoBot.Commands {
private System.Timers.Timer clearTimer { get; } = new System.Timers.Timer();
public LoLCommands() : base() {
public LoLCommands() {
clearTimer.Interval = new TimeSpan(0, 10, 0).TotalMilliseconds;
clearTimer.Start();
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.",
"DONT READ BELOW! Ban Urgot mid OP 100%. Im smurf Diamond 1.",
"Ask your teammates what would they like to play, and ban that.",
@ -47,7 +47,7 @@ namespace NadekoBot.Commands {
throw new NotImplementedException();
}
class MatchupModel {
private class MatchupModel {
public int Games { get; set; }
public float WinRate { get; set; }
[Newtonsoft.Json.JsonProperty("key")]
@ -270,7 +270,8 @@ Assists: {general["assists"]} Ban: {general["banRate"]}%
}
});
}
enum GetImageType {
private enum GetImageType {
Champion,
Item
}

View File

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

View File

@ -7,7 +7,7 @@ using Discord.Commands;
using System.Timers;
namespace NadekoBot.Commands {
class PlayingRotate : DiscordCommand {
internal class PlayingRotate : DiscordCommand {
private static List<string> rotatingStatuses = new List<string>();
private static Timer timer = new Timer(12000);

View File

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

View File

@ -21,13 +21,13 @@ public class AsyncLazy<T> : Lazy<Task<T>>
*/
namespace NadekoBot.Commands {
class ServerGreetCommand : DiscordCommand {
internal class ServerGreetCommand : DiscordCommand {
public static ConcurrentDictionary<ulong, AnnounceControls> AnnouncementsDictionary;
public static long Greeted = 0;
public ServerGreetCommand() : base() {
public ServerGreetCommand() {
AnnouncementsDictionary = new ConcurrentDictionary<ulong, AnnounceControls>();
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;
public SpeedTyping() : base() {
public SpeedTyping() {
runningContests = new Dictionary<ulong, TypingGame>();
}

View File

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

View File

@ -6,15 +6,15 @@ using System.Collections.Concurrent;
using Discord;
namespace NadekoBot.Commands {
class VoiceNotificationCommand : DiscordCommand {
internal class VoiceNotificationCommand : DiscordCommand {
public VoiceNotificationCommand() : base() {
public VoiceNotificationCommand() {
//NadekoBot.client.
}
//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 => {
var arg = e.GetArg("voice_name");

View File

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

View File

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

View File

@ -2,10 +2,11 @@
using Discord.Modules;
using NadekoBot.Extensions;
using System.Linq;
using Discord;
namespace NadekoBot.Modules
{
class Gambling : DiscordModule
internal class Gambling : DiscordModule
{
public Gambling() {
@ -33,33 +34,16 @@ namespace NadekoBot.Modules
return;
}
var members = role.Members.Where(u => u.Status == Discord.UserStatus.Online); // only online
try {
var usr = members.ToArray()[new System.Random().Next(0, members.Count())];
var membersArray = members as User[] ?? members.ToArray();
var usr = membersArray[new System.Random().Next(0, membersArray.Length)];
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("$$$")
.Description("Check how many NadekoFlowers you have.")
.Do(async e => {
var pts = Classes.DBHandler.Instance.GetStateByUserId((long)e.User.Id)?.Value ?? 0;
string str = $"`You have {pts} NadekoFlowers".SnPl((int)pts)+"`\n";
for (int i = 0; i < pts; i++) {
var str = $"`You have {pts} NadekoFlowers".SnPl((int)pts)+"`\n";
for (var i = 0; i < pts; i++) {
str += "🌸";
}
await e.Channel.SendMessage(str);

View File

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

View File

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

View File

@ -11,16 +11,16 @@ using System.Threading.Tasks;
using Timer = System.Timers.Timer;
namespace NadekoBot.Modules {
class Music : DiscordModule {
internal class Music : DiscordModule {
public static ConcurrentDictionary<Server, MusicPlayer> musicPlayers = new ConcurrentDictionary<Server, MusicPlayer>();
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.Elapsed += (s, e) => {

View File

@ -5,11 +5,11 @@ using Newtonsoft.Json.Linq;
using NadekoBot.Classes;
namespace NadekoBot.Modules {
class NSFW : DiscordModule {
internal class NSFW : DiscordModule {
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;
namespace NadekoBot.Modules {
class PermissionModule : DiscordModule {
string prefix = ";";
public PermissionModule() : base() {
internal class PermissionModule : DiscordModule {
private const string prefix = ";";
public PermissionModule() {
//Empty for now
}
@ -135,7 +136,7 @@ namespace NadekoBot.Modules {
cgb.CreateCommand(prefix + "sm").Alias(prefix + "servermodule")
.Parameter("module", 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 => {
try {
string module = PermissionHelper.ValidateModule(e.GetArg("module"));
@ -155,7 +156,7 @@ namespace NadekoBot.Modules {
cgb.CreateCommand(prefix + "sc").Alias(prefix + "servercommand")
.Parameter("command", 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 => {
try {
string command = PermissionHelper.ValidateCommand(e.GetArg("command"));
@ -176,7 +177,7 @@ namespace NadekoBot.Modules {
.Parameter("module", ParameterType.Required)
.Parameter("bool", ParameterType.Required)
.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 => {
try {
string module = PermissionHelper.ValidateModule(e.GetArg("module"));
@ -207,7 +208,7 @@ namespace NadekoBot.Modules {
.Parameter("command", ParameterType.Required)
.Parameter("bool", ParameterType.Required)
.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 => {
try {
string command = PermissionHelper.ValidateCommand(e.GetArg("command"));
@ -238,7 +239,7 @@ namespace NadekoBot.Modules {
.Parameter("module", ParameterType.Required)
.Parameter("bool", ParameterType.Required)
.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 => {
try {
string module = PermissionHelper.ValidateModule(e.GetArg("module"));
@ -269,7 +270,7 @@ namespace NadekoBot.Modules {
.Parameter("command", ParameterType.Required)
.Parameter("bool", ParameterType.Required)
.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 => {
try {
string command = PermissionHelper.ValidateCommand(e.GetArg("command"));
@ -300,7 +301,7 @@ namespace NadekoBot.Modules {
.Parameter("module", ParameterType.Required)
.Parameter("bool", ParameterType.Required)
.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 => {
try {
string module = PermissionHelper.ValidateModule(e.GetArg("module"));
@ -322,7 +323,7 @@ namespace NadekoBot.Modules {
.Parameter("command", ParameterType.Required)
.Parameter("bool", ParameterType.Required)
.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 => {
try {
string command = PermissionHelper.ValidateCommand(e.GetArg("command"));
@ -342,7 +343,7 @@ namespace NadekoBot.Modules {
cgb.CreateCommand(prefix + "asm").Alias(prefix + "allservermodules")
.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 => {
try {
bool state = PermissionHelper.ValidateBool(e.GetArg("bool"));
@ -363,7 +364,7 @@ namespace NadekoBot.Modules {
cgb.CreateCommand(prefix + "asc").Alias(prefix + "allservercommands")
.Parameter("module", 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 => {
try {
bool state = PermissionHelper.ValidateBool(e.GetArg("bool"));
@ -385,7 +386,7 @@ namespace NadekoBot.Modules {
cgb.CreateCommand(prefix + "acm").Alias(prefix + "allchannelmodules")
.Parameter("bool", ParameterType.Required)
.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 => {
try {
bool state = PermissionHelper.ValidateBool(e.GetArg("bool"));
@ -408,7 +409,7 @@ namespace NadekoBot.Modules {
.Parameter("module", ParameterType.Required)
.Parameter("bool", ParameterType.Required)
.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 => {
try {
bool state = PermissionHelper.ValidateBool(e.GetArg("bool"));
@ -430,7 +431,7 @@ namespace NadekoBot.Modules {
cgb.CreateCommand(prefix + "arm").Alias(prefix + "allrolemodules")
.Parameter("bool", ParameterType.Required)
.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 => {
try {
bool state = PermissionHelper.ValidateBool(e.GetArg("bool"));
@ -453,7 +454,7 @@ namespace NadekoBot.Modules {
.Parameter("module", ParameterType.Required)
.Parameter("bool", ParameterType.Required)
.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 => {
try {
bool state = PermissionHelper.ValidateBool(e.GetArg("bool"));

View File

@ -10,16 +10,14 @@ using NadekoBot.Classes;
using NadekoBot.Commands;
namespace NadekoBot.Modules {
class Searches : DiscordModule {
private Random _r;
public Searches() : base() {
internal class Searches : DiscordModule {
private readonly Random rng;
public Searches() {
commands.Add(new LoLCommands());
_r = new Random();
rng = new Random();
}
public override void Install(ModuleManager manager) {
var client = NadekoBot.Client;
manager.CreateCommands("", cgb => {
cgb.AddCheck(Classes.Permissions.PermissionChecker.Instance);
@ -34,14 +32,14 @@ namespace NadekoBot.Modules {
var str = await SearchHelper.ShortenUrl(await SearchHelper.FindYoutubeUrlByKeywords(e.GetArg("query")));
if (string.IsNullOrEmpty(str.Trim())) {
await e.Channel.SendMessage("Query failed");
await e.Channel.SendMessage("Query failed.");
return;
}
await e.Channel.SendMessage(str);
});
cgb.CreateCommand("~ani")
.Alias("~anime").Alias("~aq")
.Alias("~anime", "~aq")
.Parameter("query", ParameterType.Unparsed)
.Description("Queries anilist for an anime and shows the first result.")
.Do(async e => {
@ -75,11 +73,8 @@ namespace NadekoBot.Modules {
.Description("Shows a random cat image.")
.Do(async e => {
try {
await e.Channel.SendMessage(JObject.Parse(new StreamReader(
WebRequest.Create("http://www.random.cat/meow")
.GetResponse()
.GetResponseStream())
.ReadToEnd())["file"].ToString());
await e.Channel.SendMessage(JObject.Parse(
await SearchHelper.GetResponseAsync("http://www.random.cat/meow"))["file"].ToString());
}
catch {}
});
@ -91,11 +86,10 @@ namespace NadekoBot.Modules {
if (string.IsNullOrWhiteSpace(e.GetArg("query")))
return;
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));
await e.Channel.SendMessage(obj["items"][0]["link"].ToString());
}
catch (Exception ex) {
} catch (Exception ex) {
await e.Channel.SendMessage($"💢 {ex.Message}");
}
});
@ -107,11 +101,10 @@ namespace NadekoBot.Modules {
if (string.IsNullOrWhiteSpace(e.GetArg("query")))
return;
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));
await e.Channel.SendMessage(obj["items"][0]["link"].ToString());
}
catch (Exception ex) {
} catch (Exception ex) {
await e.Channel.SendMessage($"💢 {ex.Message}");
}
});
@ -134,8 +127,7 @@ namespace NadekoBot.Modules {
return;
}
await e.Channel.SendIsTyping();
var headers = new WebHeaderCollection();
headers.Add("X-Mashape-Key", NadekoBot.creds.MashapeKey);
var headers = new WebHeaderCollection {{"X-Mashape-Key", NadekoBot.Creds.MashapeKey}};
var res = await SearchHelper.GetResponseAsync($"https://omgvamp-hearthstone-v1.p.mashape.com/cards/search/{Uri.EscapeUriString(arg)}", headers);
try {
var items = JArray.Parse(res);
@ -155,11 +147,8 @@ namespace NadekoBot.Modules {
if (items.Count > 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));
Console.WriteLine("Finish");
}
catch (Exception ex) {
} catch (Exception ex) {
await e.Channel.SendMessage($"💢 Error {ex.Message}");
}
});
@ -180,11 +169,9 @@ namespace NadekoBot.Modules {
try {
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`");
}
catch { }
} catch { }
};
}
catch {
} catch {
await e.Channel.SendMessage("💢 Failed retrieving osu signature :\\");
}
}
@ -201,7 +188,7 @@ namespace NadekoBot.Modules {
}
await e.Channel.SendIsTyping();
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);
try {
var items = JObject.Parse(res);
@ -210,8 +197,7 @@ namespace NadekoBot.Modules {
sb.AppendLine($"`Definition:` {items["list"][0]["definition"].ToString()}");
sb.Append($"`Link:` <{await items["list"][0]["permalink"].ToString().ShortenUrl()}>");
await e.Channel.SendMessage(sb.ToString());
}
catch {
} catch {
await e.Channel.SendMessage("💢 Failed finding a definition for that term.");
}
});
@ -227,7 +213,7 @@ namespace NadekoBot.Modules {
}
await e.Channel.SendIsTyping();
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);
try {
var items = JObject.Parse(res);
@ -236,8 +222,7 @@ namespace NadekoBot.Modules {
sb.AppendLine($"`Definition:` {items["defs"]["def"]["text"].ToString()}");
sb.Append($"`Link:` <{await items["defs"]["def"]["uri"].ToString().ShortenUrl()}>");
await e.Channel.SendMessage(sb.ToString());
}
catch {
} catch {
await e.Channel.SendMessage("💢 Failed finidng a definition for that tag.");
}
});

View File

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

View File

@ -21,7 +21,7 @@ namespace NadekoBot {
private static Channel OwnerPrivateChannel { get; set; }
static void Main() {
private static void Main() {
try {
//load credentials from credentials.json
Creds = JsonConvert.DeserializeObject<Credentials>(File.ReadAllText("credentials.json"));