Conversations cleaned up completely

This commit is contained in:
Master Kwoth 2016-02-29 18:28:16 +01:00
parent fda5755a7f
commit 874eefdf89
42 changed files with 382 additions and 561 deletions

View File

@ -5,7 +5,6 @@ using System.Threading.Tasks;
using System.Security.Cryptography;
using Discord.Commands;
using Discord;
using NadekoBot.Modules;
using System.IO;
using System.Drawing;
using NadekoBot.Classes;

View File

@ -1,8 +1,4 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading.Tasks;
namespace NadekoBot.Classes {
static class FlowersHandler {

View File

@ -0,0 +1,20 @@
namespace NadekoBot.Classes.JSONModels
{
public class AnimeResult
{
public int id;
public string airing_status;
public string title_english;
public int total_episodes;
public string description;
public string image_url_lge;
public override string ToString() =>
"`Title:` **" + title_english +
"**\n`Status:` " + airing_status +
"\n`Episodes:` " + total_episodes +
"\n`Link:` http://anilist.co/anime/" + id +
"\n`Synopsis:` " + description.Substring(0, description.Length > 500 ? 500 : description.Length) + "..." +
"\n`img:` " + image_url_lge;
}
}

View File

@ -0,0 +1,22 @@
namespace NadekoBot.Classes.JSONModels
{
public class MangaResult
{
public int id;
public string publishing_status;
public string image_url_lge;
public string title_english;
public int total_chapters;
public int total_volumes;
public string description;
public override string ToString() =>
"`Title:` **" + title_english +
"**\n`Status:` " + publishing_status +
"\n`Chapters:` " + total_chapters +
"\n`Volumes:` " + total_volumes +
"\n`Link:` http://anilist.co/manga/" + id +
"\n`Synopsis:` " + description.Substring(0, description.Length > 500 ? 500 : description.Length) + "..." +
"\n`img:` " + image_url_lge;
}
}

View File

@ -0,0 +1,18 @@
// ReSharper disable InconsistentNaming
namespace NadekoBot.Classes.JSONModels
{
public class Credentials
{
public string Username;
public string Password;
public string BotId;
public string GoogleAPIKey;
public ulong[] OwnerIds;
public string TrelloAppKey;
public bool? ForwardMessages;
public string SoundCloudClientID;
public string MashapeKey;
public string LOLAPIKey;
public bool DontJoinServers = false;
}
}

View File

@ -1,9 +1,5 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;
namespace NadekoBot.Classes.Music {
public class SoundCloud {

View File

@ -1,7 +1,6 @@
using Discord;
using Discord.Commands;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using NadekoBot.Extensions;
@ -10,43 +9,38 @@ using System.Reflection;
namespace NadekoBot {
public class NadekoStats {
public string BotVersion { get; } = $"{Assembly.GetExecutingAssembly().GetName().Name} v{Assembly.GetExecutingAssembly().GetName().Version.ToString()}";
public static NadekoStats Instance { get; } = new NadekoStats();
private static readonly NadekoStats _instance = new NadekoStats();
public static NadekoStats Instance => _instance;
private readonly CommandService commandService;
private CommandService _service;
private DiscordClient _client;
public string BotVersion => $"{Assembly.GetExecutingAssembly().GetName().Name} v{Assembly.GetExecutingAssembly().GetName().Version}";
private int _commandsRan = 0;
private string _statsCache = "";
private Stopwatch _statsSW = new Stopwatch();
private readonly Stopwatch statsStopwatch = new Stopwatch();
public int ServerCount { get; private set; } = 0;
public int TextChannelsCount { get; private set; } = 0;
public int VoiceChannelsCount { get; private set; } = 0;
List<string> messages = new List<string>();
static NadekoStats() { }
private NadekoStats() {
_service = NadekoBot.Client.GetService<CommandService>();
_client = NadekoBot.Client;
commandService = NadekoBot.Client.GetService<CommandService>();
_statsSW = new Stopwatch();
_statsSW.Start();
_service.CommandExecuted += StatsCollector_RanCommand;
statsStopwatch = new Stopwatch();
statsStopwatch.Start();
commandService.CommandExecuted += StatsCollector_RanCommand;
Task.Run(() => StartCollecting());
Task.Run(StartCollecting);
Console.WriteLine("Logging enabled.");
ServerCount = _client.Servers.Count();
var channels = _client.Servers.SelectMany(s => s.AllChannels);
TextChannelsCount = channels.Where(c => c.Type == ChannelType.Text).Count();
ServerCount = NadekoBot.Client.Servers.Count();
var channels = NadekoBot.Client.Servers.SelectMany(s => s.AllChannels);
TextChannelsCount = channels.Count(c => c.Type == ChannelType.Text);
VoiceChannelsCount = channels.Count() - TextChannelsCount;
_client.JoinedServer += (s, e) => {
NadekoBot.Client.JoinedServer += (s, e) => {
try {
ServerCount++;
TextChannelsCount += e.Server.TextChannels.Count();
@ -54,7 +48,7 @@ namespace NadekoBot {
}
catch { }
};
_client.LeftServer += (s, e) => {
NadekoBot.Client.LeftServer += (s, e) => {
try {
ServerCount--;
TextChannelsCount -= e.Server.TextChannels.Count();
@ -62,7 +56,7 @@ namespace NadekoBot {
}
catch { }
};
_client.ChannelCreated += (s, e) => {
NadekoBot.Client.ChannelCreated += (s, e) => {
try {
if (e.Channel.IsPrivate)
return;
@ -73,7 +67,7 @@ namespace NadekoBot {
}
catch { }
};
_client.ChannelDestroyed += (s, e) => {
NadekoBot.Client.ChannelDestroyed += (s, e) => {
try {
if (e.Channel.IsPrivate)
return;
@ -98,20 +92,15 @@ namespace NadekoBot {
Task.Run(() => {
var sb = new System.Text.StringBuilder();
sb.AppendLine("`Author: Kwoth` `Library: Discord.Net`");
//$"\nDiscord.Net version: {DiscordConfig.LibVersion}" +
//$"\nRuntime: {_client.GetRuntime()}" +
sb.AppendLine($"`Bot Version: {BotVersion}`");
//$"\nLogged in as: {_client.CurrentUser.Name}" +
sb.AppendLine($"`Bot id: {_client.CurrentUser.Id}`");
sb.AppendLine($"`Owner id: {NadekoBot.OwnerID}`");
sb.AppendLine($"`Bot id: {NadekoBot.Client.CurrentUser.Id}`");
sb.AppendLine($"`Owner id: {(NadekoBot.Creds.OwnerIds.FirstOrDefault())}`");
sb.AppendLine($"`Uptime: {GetUptimeString()}`");
sb.Append($"`Servers: {ServerCount}");
sb.Append($" | TextChannels: {TextChannelsCount}");
sb.AppendLine($" | VoiceChannels: {VoiceChannelsCount}`");
//$"\nUsers: {_client.Servers.SelectMany(x => x.Users.Select(y => y.Id)).Count()} (non-unique)" +
//sb.AppendLine($"`Heap: {} MB`");
sb.AppendLine($"`Commands Ran this session: {_commandsRan}`");
sb.AppendLine($"`Message queue size:{_client.MessageQueue.Count}`");
sb.AppendLine($"`Message queue size:{NadekoBot.Client.MessageQueue.Count}`");
sb.AppendLine($"`Greeted {Commands.ServerGreetCommand.Greeted} times.`");
_statsCache = sb.ToString();
});
@ -119,10 +108,9 @@ namespace NadekoBot {
public string Heap() => Math.Round((double)GC.GetTotalMemory(true) / 1.MiB(), 2).ToString();
public async Task<string> GetStats() {
if (_statsSW.Elapsed.Seconds > 5) {
await LoadStats();
_statsSW.Restart();
}
if (statsStopwatch.Elapsed.Seconds <= 5) return _statsCache;
await LoadStats();
statsStopwatch.Restart();
return _statsCache;
}
@ -132,7 +120,7 @@ namespace NadekoBot {
try {
var onlineUsers = await Task.Run(() => NadekoBot.Client.Servers.Sum(x => x.Users.Count()));
var realOnlineUsers = await Task.Run(() => NadekoBot.Client.Servers
.Sum(x => x.Users.Where(u => u.Status == UserStatus.Online).Count()));
.Sum(x => x.Users.Count(u => u.Status == UserStatus.Online)));
var connectedServers = NadekoBot.Client.Servers.Count();
Classes.DBHandler.Instance.InsertData(new Classes._DataModels.Stats {
@ -165,7 +153,7 @@ namespace NadekoBot {
});
}
catch {
Console.WriteLine("Parse error in ran command.");
Console.WriteLine("Error in ran command DB write.");
}
}
}

View File

@ -1,11 +1,7 @@
using Discord.Commands;
using Discord.Modules;
using NadekoBot.Extensions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Discord;
namespace NadekoBot.Classes {

View File

@ -1,11 +1,9 @@
using Discord;
using Discord.Commands.Permissions;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Discord.Commands;

View File

@ -1,14 +1,28 @@
using Discord;
using Discord.Commands;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Discord.Commands.Permissions;
namespace NadekoBot.Classes.Permissions {
static class SimpleCheckers {
public static class SimpleCheckers
{
public static ManageRoles CanManageRoles { get; } = new ManageRoles();
public static Func<Command, User, Channel, bool> OwnerOnly() =>
(com, user, ch) => user.Id == NadekoBot.Creds.OwnerID;
(com, user, ch) => NadekoBot.IsOwner(user.Id);
public static Func<Command, User, Channel, bool> ManageMessages() =>
(com, user, ch) => NadekoBot.IsOwner(user.Id);
public class ManageRoles :IPermissionChecker
{
public bool CanRun(Command command, User user, Channel channel, out string error) {
error = string.Empty;
if(user.ServerPermissions.ManageRoles)
return true;
error = "You do not have a permission to manage roles.";
return false;
}
}
}
}

View File

@ -3,7 +3,6 @@ using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using NadekoBot.Extensions;
namespace NadekoBot.Classes.Trivia {
public class TriviaQuestionPool {

View File

@ -1,8 +1,7 @@
using Newtonsoft.Json;
using System;
namespace NadekoBot.Classes._DataModels {
class Announcement : IDataModel {
internal class Announcement : IDataModel {
public long ServerId { get; set; } = 0;
public bool Greet { get; set; } = false;
public bool GreetPM { get; set; } = false;

View File

@ -1,7 +1,5 @@
using System;
namespace NadekoBot.Classes._DataModels {
class Command : IDataModel {
namespace NadekoBot.Classes._DataModels {
internal class Command : IDataModel {
public long UserId { get; set; }
public string UserName { get; set; }
public long ServerId { get; set; }

View File

@ -1,5 +1,5 @@
namespace NadekoBot.Classes._DataModels {
class CurrencyState : IDataModel {
internal class CurrencyState : IDataModel {
public long Value { get; set; }
[SQLite.Unique]
public long UserId { get; set; }

View File

@ -1,5 +1,5 @@
namespace NadekoBot.Classes._DataModels {
class CurrencyTransaction : IDataModel {
internal class CurrencyTransaction : IDataModel {
public string Reason { get; set; }
public int Value { get; set; }
public long UserId { get; set; }

View File

@ -1,11 +1,5 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NadekoBot.Classes._DataModels {
class Donator : IDataModel {
namespace NadekoBot.Classes._DataModels {
internal class Donator : IDataModel {
public long UserId { get; set; }
public string UserName { get; set; }
public int Amount { get; set; }

View File

@ -2,7 +2,7 @@
using System;
namespace NadekoBot.Classes._DataModels {
abstract class IDataModel {
internal abstract class IDataModel {
[PrimaryKey, AutoIncrement]
public int Id { get; set; }
[Newtonsoft.Json.JsonProperty("createdAt")]

View File

@ -1,5 +1,5 @@
namespace NadekoBot.Classes._DataModels {
class Request : IDataModel {
internal class Request : IDataModel {
public string UserName { get; set; }
public long UserId { get; set; }
public string ServerName { get; set; }

View File

@ -1,7 +1,7 @@
using System;
namespace NadekoBot.Classes._DataModels {
class Stats : IDataModel {
internal class Stats : IDataModel {
public int ConnectedServers { get; set; }
public int OnlineUsers { get; set; }
public TimeSpan Uptime { get; set; }

View File

@ -1,5 +1,5 @@
namespace NadekoBot.Classes._DataModels {
class TypingArticle : IDataModel {
internal class TypingArticle : IDataModel {
public string Text { get; set; }
}
}

View File

@ -1,11 +1,5 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NadekoBot.Classes._DataModels {
class UserQuote : IDataModel {
namespace NadekoBot.Classes._DataModels {
internal class UserQuote : IDataModel {
public string UserName { get; set; }
public string Keyword { get; set; }
public string Text { get; set; }

View File

@ -1,55 +0,0 @@
// ReSharper disable InconsistentNaming
namespace NadekoBot.Classes
{
public class Credentials
{
public string Username;
public string Password;
public string BotMention;
public string GoogleAPIKey;
public ulong OwnerID;
public string TrelloAppKey;
public bool? ForwardMessages;
public string SoundCloudClientID;
public string MashapeKey;
public string LOLAPIKey;
public bool DontJoinServers = false;
}
public class AnimeResult
{
public int id;
public string airing_status;
public string title_english;
public int total_episodes;
public string description;
public string image_url_lge;
public override string ToString() =>
"`Title:` **" + title_english +
"**\n`Status:` " + airing_status +
"\n`Episodes:` " + total_episodes +
"\n`Link:` http://anilist.co/anime/" + id +
"\n`Synopsis:` " + description.Substring(0, description.Length > 500 ? 500 : description.Length) + "..." +
"\n`img:` " + image_url_lge;
}
public class MangaResult
{
public int id;
public string publishing_status;
public string image_url_lge;
public string title_english;
public int total_chapters;
public int total_volumes;
public string description;
public override string ToString() =>
"`Title:` **" + title_english +
"**\n`Status:` " + publishing_status +
"\n`Chapters:` " + total_chapters +
"\n`Volumes:` " + total_volumes +
"\n`Link:` http://anilist.co/manga/" + id +
"\n`Synopsis:` " + description.Substring(0, description.Length > 500 ? 500 : description.Length) + "..." +
"\n`img:` " + image_url_lge;
}
}

View File

@ -1,11 +1,9 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Discord.Commands;
using System.Collections.Concurrent;
using Discord;
using System.Threading;
namespace NadekoBot.Commands {

View File

@ -2,7 +2,6 @@
using System.Collections.Generic;
using System.Threading.Tasks;
using Discord.Commands;
using NadekoBot.Extensions;
namespace NadekoBot
{

View File

@ -1,7 +1,6 @@
using System;
using System.Threading.Tasks;
using Discord.Commands;
using Discord.Legacy;
using NadekoBot.Extensions;
using System.Drawing;

View File

@ -35,22 +35,21 @@ namespace NadekoBot {
#endregion OldHelp
if (string.IsNullOrWhiteSpace(e.GetArg("command"))) {
await e.User.Send("**LIST OF COMMANDS CAN BE FOUND ON THIS LINK**\n\n <https://github.com/Kwoth/NadekoBot/blob/master/commandlist.md>");
await e.User.Send(HelpString);
return;
}
else {
await Task.Run(async () => {
var comToFind = e.GetArg("command");
await Task.Run(async () => {
var comToFind = e.GetArg("command");
var com = NadekoBot.Client.GetService<CommandService>().AllCommands
.Where(c => c.Text.ToLower().Equals(comToFind))
.FirstOrDefault();
if (com != null)
await e.Channel.SendMessage($"`Help for '{com.Text}:'` **{com.Description}**");
});
}
var com = NadekoBot.Client.GetService<CommandService>().AllCommands
.FirstOrDefault(c => c.Text.ToLower().Equals(comToFind));
if (com != null)
await e.Channel.SendMessage($"`Help for '{com.Text}:'` **{com.Description}**");
});
};
public static string HelpString => "**LIST OF COMMANDS CAN BE FOUND ON THIS LINK**\n\n <https://github.com/Kwoth/NadekoBot/blob/master/commandlist.md>";
public Action<CommandEventArgs> DoGitFunc() => e => {
string helpstr =
$@"######For more information and how to setup your own NadekoBot, go to: **http://github.com/Kwoth/NadekoBot/**

View File

@ -4,11 +4,9 @@ using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Discord.Commands;
using NadekoBot;
using System.Drawing;
using NadekoBot.Extensions;
using Newtonsoft.Json.Linq;
using System.Collections.Concurrent;
namespace NadekoBot.Commands {
class LoLCommands : DiscordCommand {

View File

@ -3,7 +3,6 @@ using System.Collections.Concurrent;
using System.Threading.Tasks;
using Discord.Commands;
using Discord;
using System.Collections.Generic;
namespace NadekoBot.Commands {
class LogCommand : DiscordCommand {
@ -21,7 +20,7 @@ namespace NadekoBot.Commands {
ConcurrentDictionary<Channel, Channel> voiceChannelLog = new ConcurrentDictionary<Channel, Channel>();
public override Func<CommandEventArgs, Task> DoFunc() => async e => {
if (e.User.Id != NadekoBot.OwnerID ||
if (!NadekoBot.IsOwner(e.User.Id) ||
!e.User.ServerPermissions.ManageServer)
return;
Channel ch;
@ -116,7 +115,7 @@ namespace NadekoBot.Commands {
cgb.CreateCommand(".userpresence")
.Description("Starts logging to this channel when someone from the server goes online/offline/idle. BOT OWNER ONLY. SERVER OWNER ONLY.")
.Do(async e => {
if (e.User.Id != NadekoBot.OwnerID ||
if (!NadekoBot.IsOwner(e.User.Id) ||
!e.User.ServerPermissions.ManageServer)
return;
Channel ch;
@ -130,9 +129,9 @@ namespace NadekoBot.Commands {
});
cgb.CreateCommand(".voicepresence")
.Description("Toggles logging to this channel whenever someone joins or leaves a voice channel you are in right now.")
.Description("Toggles logging to this channel whenever someone joins or leaves a voice channel you are in right now. BOT OWNER ONLY. SERVER OWNER ONLY.")
.Do(async e => {
if (e.User.Id != NadekoBot.OwnerID ||
if (!NadekoBot.IsOwner(e.User.Id) ||
!e.User.ServerPermissions.ManageServer)
return;

View File

@ -73,7 +73,7 @@ namespace NadekoBot.Commands {
.Description("Deletes a request. Only owner is able to do this.")
.Parameter("reqNumber", ParameterType.Required)
.Do(async e => {
if (e.User.Id == NadekoBot.OwnerId) {
if (NadekoBot.IsOwner(e.User.Id)) {
try {
if (DeleteRequest(int.Parse(e.Args[0]))) {
await e.Channel.SendMessage(e.User.Mention + " Request deleted.");
@ -90,7 +90,7 @@ namespace NadekoBot.Commands {
.Description("Resolves a request. Only owner is able to do this.")
.Parameter("reqNumber", ParameterType.Required)
.Do(async e => {
if (e.User.Id == NadekoBot.OwnerId) {
if (NadekoBot.IsOwner(e.User.Id)) {
try {
var sc = ResolveRequest(int.Parse(e.Args[0]));
if (sc != null) {

View File

@ -151,7 +151,7 @@ namespace NadekoBot.Commands {
.Description("Adds a new article to the typing contest. Owner only.")
.Parameter("text", ParameterType.Unparsed)
.Do(async e => {
if (e.User.Id != NadekoBot.OwnerID || string.IsNullOrWhiteSpace(e.GetArg("text"))) return;
if (!NadekoBot.IsOwner(e.User.Id) || string.IsNullOrWhiteSpace(e.GetArg("text"))) return;
Classes.DBHandler.Instance.InsertData(new Classes._DataModels.TypingArticle {
Text = e.GetArg("text"),

View File

@ -1,7 +1,6 @@
using System;
using System.Threading.Tasks;
using Discord.Commands;
using NadekoBot.Extensions;
using System.Collections.Concurrent;
using Discord;
using TriviaGame = NadekoBot.Classes.Trivia.TriviaGame;

View File

@ -2,9 +2,7 @@
using Discord.Commands;
using Discord;
using System;
using System.Diagnostics;
using System.Linq;
using System.Timers;
using NadekoBot.Extensions;
using System.Threading.Tasks;
using NadekoBot.Commands;
@ -12,13 +10,13 @@ using System.IO;
using System.Collections.Concurrent;
using Newtonsoft.Json.Linq;
using System.Collections.Generic;
using NadekoBot.Classes.Permissions;
using NadekoBot.Classes._DataModels;
using System.Threading;
using Timer = System.Timers.Timer;
namespace NadekoBot.Modules {
class Administration : DiscordModule {
public Administration() : base() {
internal class Administration : DiscordModule {
public Administration() {
commands.Add(new ServerGreetCommand());
commands.Add(new LogCommand());
commands.Add(new PlayingRotate());
@ -27,7 +25,7 @@ namespace NadekoBot.Modules {
public override void Install(ModuleManager manager) {
manager.CreateCommands("", cgb => {
cgb.AddCheck(Classes.Permissions.PermissionChecker.Instance);
cgb.AddCheck(PermissionChecker.Instance);
var client = manager.Client;
@ -37,27 +35,34 @@ namespace NadekoBot.Modules {
.Description("Sets a role for a given user.\n**Usage**: .sr @User Guest")
.Parameter("user_name", ParameterType.Required)
.Parameter("role_name", ParameterType.Unparsed)
.AddCheck(SimpleCheckers.CanManageRoles)
.Do(async e => {
if (!e.User.ServerPermissions.ManageRoles ||
string.IsNullOrWhiteSpace(e.GetArg("role_name"))) return;
var usr = e.Server.FindUsers(e.GetArg("user_name")).FirstOrDefault();
var userName = e.GetArg("user_name");
var roleName = e.GetArg("role_name");
if (string.IsNullOrWhiteSpace(roleName)) return;
if (!e.User.ServerPermissions.ManageRoles) {
await e.Channel.SendMessage("You have insufficient permissions.");
}
var usr = e.Server.FindUsers(userName).FirstOrDefault();
if (usr == null) {
await e.Channel.SendMessage("You failed to supply a valid username");
return;
}
var role = e.Server.FindRoles(e.GetArg("role_name")).FirstOrDefault();
var role = e.Server.FindRoles(roleName).FirstOrDefault();
if (role == null) {
await e.Channel.SendMessage("You failed to supply a valid role");
return;
}
try {
await usr.AddRoles(new Role[] { role });
await usr.AddRoles(role);
await e.Channel.SendMessage($"Successfully added role **{role.Name}** to user **{usr.Name}**");
}
catch (Exception ex) {
await e.Channel.SendMessage("Failed to add roles. Most likely reason: Insufficient permissions.\n");
} catch (Exception ex) {
await e.Channel.SendMessage("Failed to add roles. Bot has insufficient permissions.\n");
Console.WriteLine(ex.ToString());
}
});
@ -66,28 +71,29 @@ namespace NadekoBot.Modules {
.Description("Removes a role from a given user.\n**Usage**: .rr @User Admin")
.Parameter("user_name", ParameterType.Required)
.Parameter("role_name", ParameterType.Unparsed)
.AddCheck(SimpleCheckers.CanManageRoles)
.Do(async e => {
if (!e.User.ServerPermissions.ManageRoles ||
string.IsNullOrWhiteSpace("role_name")) return;
var userName = e.GetArg("user_name");
var roleName = e.GetArg("role_name");
var usr = e.Server.FindUsers(e.GetArg("user_name")).FirstOrDefault();
if (string.IsNullOrWhiteSpace(roleName)) return;
var usr = e.Server.FindUsers(userName).FirstOrDefault();
if (usr == null) {
await e.Channel.SendMessage("You failed to supply a valid username");
return;
}
var role = e.Server.FindRoles(e.GetArg("role_name")).FirstOrDefault();
var role = e.Server.FindRoles(roleName).FirstOrDefault();
if (role == null) {
await e.Channel.SendMessage("You failed to supply a valid role");
return;
}
try {
await usr.RemoveRoles(new Role[] { role });
await usr.RemoveRoles(role);
await e.Channel.SendMessage($"Successfully removed role **{role.Name}** from user **{usr.Name}**");
}
catch (InvalidOperationException) {
}
catch {
} catch {
await e.Channel.SendMessage("Failed to remove roles. Most likely reason: Insufficient permissions.");
}
});
@ -95,21 +101,20 @@ namespace NadekoBot.Modules {
cgb.CreateCommand(".r").Alias(".role").Alias(".cr")
.Description("Creates a role with a given name.**Usage**: .r Awesome Role")
.Parameter("role_name", ParameterType.Unparsed)
.AddCheck(SimpleCheckers.CanManageRoles)
.Do(async e => {
if (!e.User.ServerPermissions.ManageRoles) return;
if (string.IsNullOrWhiteSpace(e.GetArg("role_name")))
return;
try {
var r = await e.Server.CreateRole(e.GetArg("role_name"));
await e.Channel.SendMessage($"Successfully created role **{r.Name}**.");
}
catch (Exception ex) {
} catch (Exception) {
await e.Channel.SendMessage(":warning: Unspecified error.");
}
});
cgb.CreateCommand(".rolecolor").Alias(".rc")
.Parameter("Rolename", ParameterType.Required)
.Parameter("role_name", ParameterType.Required)
.Parameter("r", ParameterType.Optional)
.Parameter("g", ParameterType.Optional)
.Parameter("b", ParameterType.Optional)
@ -120,47 +125,44 @@ namespace NadekoBot.Modules {
return;
}
var args = e.Args.Where(s => s != String.Empty);
var args = e.Args.Where(s => s != string.Empty);
if (args.Count() != 2 && args.Count() != 4) {
await e.Channel.SendMessage("The parameters are invalid.");
return;
}
Role role = e.Server.FindRoles(e.Args[0]).FirstOrDefault();
var role = e.Server.FindRoles(e.Args[0]).FirstOrDefault();
if (role == null) {
await e.Channel.SendMessage("That role does not exist.");
return;
}
try {
bool rgb = args.Count() == 4;
var rgb = args.Count() == 4;
byte red = Convert.ToByte(rgb ? int.Parse(e.Args[1]) : Convert.ToInt32(e.Args[1].Substring(0, 2), 16));
byte green = Convert.ToByte(rgb ? int.Parse(e.Args[2]) : Convert.ToInt32(e.Args[1].Substring(2, 2), 16));
byte blue = Convert.ToByte(rgb ? int.Parse(e.Args[3]) : Convert.ToInt32(e.Args[1].Substring(4, 2), 16));
var red = Convert.ToByte(rgb ? int.Parse(e.Args[1]) : Convert.ToInt32(e.Args[1].Substring(0, 2), 16));
var green = Convert.ToByte(rgb ? int.Parse(e.Args[2]) : Convert.ToInt32(e.Args[1].Substring(2, 2), 16));
var blue = Convert.ToByte(rgb ? int.Parse(e.Args[3]) : Convert.ToInt32(e.Args[1].Substring(4, 2), 16));
await role.Edit(color: new Color(red, green, blue));
await e.Channel.SendMessage($"Role {role.Name}'s color has been changed.");
}
catch (Exception ex) {
await e.Channel.SendMessage(":warning: Unspecified error, please report this.");
} catch (Exception ex) {
await e.Channel.SendMessage("Error occured, most likely invalid parameters.");
Console.WriteLine($".rolecolor error: {ex}");
}
});
cgb.CreateCommand(".roles")
.Description("List all roles on this server or a single user if specified.")
.Parameter("user", ParameterType.Unparsed)
.Do(async e => {
if (!string.IsNullOrWhiteSpace(e.GetArg("user"))) {
var usr = e.Server.FindUsers(e.GetArg("user")).FirstOrDefault();
if (usr != null) {
await e.Channel.SendMessage($"`List of roles for **{usr.Name}**:` \n• " + string.Join("\n• ", usr.Roles));
return;
}
if (usr == null) return;
await e.Channel.SendMessage($"`List of roles for **{usr.Name}**:` \n• " + string.Join("\n• ", usr.Roles));
return;
}
await e.Channel.SendMessage("`List of roles:` \n• " + string.Join("\n• ", e.Server.Roles));
});
@ -175,8 +177,7 @@ namespace NadekoBot.Modules {
await usr.Server.Ban(usr);
await e.Channel.SendMessage("Banned user " + usr.Name + " Id: " + usr.Id);
}
}
catch (Exception ex) { }
} catch (Exception ex) { }
});
cgb.CreateCommand(".ub").Alias(".unban")
@ -189,8 +190,7 @@ namespace NadekoBot.Modules {
await usr.Server.Unban(usr);
await e.Channel.SendMessage("Unbanned user " + usr.Name + " Id: " + usr.Id);
}
}
catch { }
} catch { }
});
cgb.CreateCommand(".k").Alias(".kick")
@ -203,8 +203,7 @@ namespace NadekoBot.Modules {
await e.Message.MentionedUsers.First().Kick();
await e.Channel.SendMessage("Kicked user " + usr.Name + " Id: " + usr.Id);
}
}
catch {
} catch {
await e.Channel.SendMessage("No sufficient permissions.");
}
});
@ -223,8 +222,7 @@ namespace NadekoBot.Modules {
await u.Edit(isMuted: true);
}
await e.Channel.SendMessage("Mute successful");
}
catch {
} catch {
await e.Channel.SendMessage("I do not have permission to do that most likely.");
}
});
@ -244,8 +242,7 @@ namespace NadekoBot.Modules {
await u.Edit(isMuted: false);
}
await e.Channel.SendMessage("Unmute successful");
}
catch {
} catch {
await e.Channel.SendMessage("I do not have permission to do that most likely.");
}
});
@ -266,8 +263,7 @@ namespace NadekoBot.Modules {
await u.Edit(isDeafened: true);
}
await e.Channel.SendMessage("Deafen successful");
}
catch {
} catch {
await e.Channel.SendMessage("I do not have permission to do that most likely.");
}
});
@ -288,8 +284,7 @@ namespace NadekoBot.Modules {
await u.Edit(isDeafened: false);
}
await e.Channel.SendMessage("Undeafen successful");
}
catch {
} catch {
await e.Channel.SendMessage("I do not have permission to do that most likely.");
}
});
@ -303,8 +298,7 @@ namespace NadekoBot.Modules {
await e.Server.FindChannels(e.GetArg("channel_name"), ChannelType.Voice).FirstOrDefault()?.Delete();
await e.Channel.SendMessage($"Removed channel **{e.GetArg("channel_name")}**.");
}
}
catch {
} catch {
await e.Channel.SendMessage("Insufficient permissions.");
}
});
@ -318,8 +312,7 @@ namespace NadekoBot.Modules {
await e.Server.CreateChannel(e.GetArg("channel_name"), ChannelType.Voice);
await e.Channel.SendMessage($"Created voice channel **{e.GetArg("channel_name")}**.");
}
}
catch {
} catch {
await e.Channel.SendMessage("Insufficient permissions.");
}
});
@ -333,8 +326,7 @@ namespace NadekoBot.Modules {
await e.Server.FindChannels(e.GetArg("channel_name"), ChannelType.Text).FirstOrDefault()?.Delete();
await e.Channel.SendMessage($"Removed text channel **{e.GetArg("channel_name")}**.");
}
}
catch {
} catch {
await e.Channel.SendMessage("Insufficient permissions.");
}
});
@ -348,8 +340,7 @@ namespace NadekoBot.Modules {
await e.Server.CreateChannel(e.GetArg("channel_name"), ChannelType.Text);
await e.Channel.SendMessage($"Added text channel **{e.GetArg("channel_name")}**.");
}
}
catch {
} catch {
await e.Channel.SendMessage("Insufficient permissions.");
}
});
@ -361,8 +352,7 @@ namespace NadekoBot.Modules {
try {
if (e.User.ServerPermissions.ManageChannels)
await e.Channel.Edit(topic: e.GetArg("topic"));
}
catch { }
} catch { }
});
cgb.CreateCommand(".uid").Alias(".userid")
@ -399,7 +389,7 @@ namespace NadekoBot.Modules {
cgb.CreateCommand(".leaveall")
.Description("Nadeko leaves all servers **OWNER ONLY**")
.Do(e => {
if (e.User.Id == NadekoBot.OwnerID)
if (NadekoBot.IsOwner(e.User.Id))
NadekoBot.client.Servers.ForEach(async s => { if (s.Name == e.Server.Name) return; await s.Leave(); });
});
*/
@ -422,7 +412,7 @@ namespace NadekoBot.Modules {
.Alias(".graceful")
.Description("Works only for the owner. Shuts the bot down and notifies users about the restart.")
.Do(async e => {
if (e.User.Id == NadekoBot.OwnerID) {
if (NadekoBot.IsOwner(e.User.Id)) {
Timer t = new Timer();
t.Interval = 2000;
t.Elapsed += (s, ev) => { Environment.Exit(0); };
@ -447,8 +437,7 @@ namespace NadekoBot.Modules {
foreach (var m in msgs) {
try {
await m.Delete();
}
catch { }
} catch { }
await Task.Delay(200);
}
@ -460,9 +449,9 @@ namespace NadekoBot.Modules {
.Description("Give the bot a new name.")
.Parameter("new_name", ParameterType.Unparsed)
.Do(async e => {
if (e.User.Id != NadekoBot.OwnerID || e.GetArg("new_name") == null) return;
if (!NadekoBot.IsOwner(e.User.Id) || e.GetArg("new_name") == null) return;
await client.CurrentUser.Edit(NadekoBot.password, e.GetArg("new_name"));
await client.CurrentUser.Edit(NadekoBot.Creds.Password, e.GetArg("new_name"));
});
cgb.CreateCommand(".newavatar")
@ -470,7 +459,7 @@ namespace NadekoBot.Modules {
.Description("Sets a new avatar image for the NadekoBot.")
.Parameter("img", ParameterType.Unparsed)
.Do(async e => {
if (e.User.Id != NadekoBot.OwnerID || string.IsNullOrWhiteSpace(e.GetArg("img")))
if (!NadekoBot.IsOwner(e.User.Id) || string.IsNullOrWhiteSpace(e.GetArg("img")))
return;
// Gather user provided URL.
string avatarAddress = e.GetArg("img");
@ -484,7 +473,7 @@ namespace NadekoBot.Modules {
System.Drawing.Image image = System.Drawing.Image.FromStream(webResponse.GetResponseStream());
// Save the image to disk.
image.Save("data/avatar.png", System.Drawing.Imaging.ImageFormat.Png);
await client.CurrentUser.Edit(NadekoBot.password, avatar: image.ToStream());
await client.CurrentUser.Edit(NadekoBot.Creds.Password, avatar: image.ToStream());
// Send confirm.
await e.Channel.SendMessage("New avatar set.");
});
@ -493,7 +482,7 @@ namespace NadekoBot.Modules {
.Description("Sets the bots game.")
.Parameter("set_game", ParameterType.Unparsed)
.Do(e => {
if (e.User.Id != NadekoBot.OwnerID || e.GetArg("set_game") == null) return;
if (e.User.Id != NadekoBot.Creds.OwnerID || e.GetArg("set_game") == null) return;
client.SetGame(e.GetArg("set_game"));
});
@ -517,13 +506,12 @@ namespace NadekoBot.Modules {
.Description("Sets a user for through-bot communication. Only works if server is set. Resets commschannel.**Owner only**.")
.Parameter("name", ParameterType.Unparsed)
.Do(async e => {
if (e.User.Id != NadekoBot.OwnerID) return;
if (!NadekoBot.IsOwner(e.User.Id)) return;
commsUser = commsServer?.FindUsers(e.GetArg("name")).FirstOrDefault();
if (commsUser != null) {
commsChannel = null;
await e.Channel.SendMessage("User for comms set.");
}
else
} else
await e.Channel.SendMessage("No server specified or user.");
});
@ -531,7 +519,7 @@ namespace NadekoBot.Modules {
.Description("Sets a server for through-bot communication.**Owner only**.")
.Parameter("server", ParameterType.Unparsed)
.Do(async e => {
if (e.User.Id != NadekoBot.OwnerID) return;
if (!NadekoBot.IsOwner(e.User.Id)) return;
commsServer = client.FindServers(e.GetArg("server")).FirstOrDefault();
if (commsServer != null)
await e.Channel.SendMessage("Server for comms set.");
@ -543,13 +531,12 @@ namespace NadekoBot.Modules {
.Description("Sets a channel for through-bot communication. Only works if server is set. Resets commsuser.**Owner only**.")
.Parameter("ch", ParameterType.Unparsed)
.Do(async e => {
if (e.User.Id != NadekoBot.OwnerID) return;
if (!NadekoBot.IsOwner(e.User.Id)) return;
commsChannel = commsServer?.FindChannels(e.GetArg("ch"), ChannelType.Text).FirstOrDefault();
if (commsChannel != null) {
commsUser = null;
await e.Channel.SendMessage("Server for comms set.");
}
else
} else
await e.Channel.SendMessage("No server specified or channel is invalid.");
});
@ -557,7 +544,7 @@ namespace NadekoBot.Modules {
.Description("Send a message to someone on a different server through the bot.**Owner only.**\n **Usage**: .send Message text multi word!")
.Parameter("msg", ParameterType.Unparsed)
.Do(async e => {
if (e.User.Id != NadekoBot.OwnerID) return;
if (!NadekoBot.IsOwner(e.User.Id)) return;
if (commsUser != null)
await commsUser.SendMessage(e.GetArg("msg"));
else if (commsChannel != null)
@ -593,7 +580,7 @@ namespace NadekoBot.Modules {
cgb.CreateCommand(".parsetosql")
.Description("Loads exported parsedata from /data/parsedata/ into sqlite database.")
.Do(async e => {
if (e.User.Id != NadekoBot.OwnerID)
if (!NadekoBot.IsOwner(e.User.Id))
return;
await Task.Run(() => {
SaveParseToDb<Announcement>("data/parsedata/Announcements.json");
@ -631,7 +618,7 @@ namespace NadekoBot.Modules {
.Parameter("amount")
.Do(e => {
try {
if (NadekoBot.OwnerID != e.User.Id)
if (!NadekoBot.IsOwner(e.User.Id))
return;
var donator = e.Server.FindUsers(e.GetArg("donator")).FirstOrDefault();
var amount = int.Parse(e.GetArg("amount"));
@ -641,8 +628,7 @@ namespace NadekoBot.Modules {
UserId = (long)e.User.Id
});
e.Channel.SendMessage("Successfuly added a new donator. 👑");
}
catch (Exception ex) {
} catch (Exception ex) {
Console.WriteLine(ex);
Console.WriteLine("---------------\nInner error:\n" + ex.InnerException);
}
@ -662,8 +648,7 @@ namespace NadekoBot.Modules {
foreach (var usr in allUsrs) {
await usr.SendMessage(str);
}
}
catch (Exception ex) {
} catch (Exception ex) {
Console.WriteLine(ex);
}
});
@ -679,8 +664,7 @@ namespace NadekoBot.Modules {
objects.Add(obj.ToObject<T>());
}
Classes.DBHandler.Instance.InsertMany(objects);
}
catch { }
} catch { }
}
}
}

View File

@ -23,42 +23,34 @@ namespace NadekoBot.Modules {
}
public override void Install(ModuleManager manager) {
Random rng = new Random();
var rng = new Random();
manager.CreateCommands("", cgb => {
cgb.AddCheck(Classes.Permissions.PermissionChecker.Instance);
var client = manager.Client;
cgb.CreateCommand("\\o\\")
.Description("Nadeko replies with /o/")
.Do(async e => {
await e.Channel.SendMessage(e.User.Mention + "/o/");
});
.Do(async e => await e.Channel.SendMessage(e.User.Mention + "/o/"));
cgb.CreateCommand("/o/")
.Description("Nadeko replies with \\o\\")
.Do(async e => {
await e.Channel.SendMessage(e.User.Mention + "\\o\\");
});
.Do(async e => await e.Channel.SendMessage(e.User.Mention + "\\o\\"));
cgb.CreateCommand("..")
.Description("Adds a new quote with the specified name (single word) and message (no limit).\n**Usage**: .. abc My message")
.Parameter("keyword", ParameterType.Required)
.Parameter("text", ParameterType.Unparsed)
.Do(async e => {
var keyword = e.GetArg("keyword");
var text = e.GetArg("text");
if (string.IsNullOrWhiteSpace(text) || string.IsNullOrWhiteSpace(keyword))
if (string.IsNullOrWhiteSpace(text))
return;
Classes.DBHandler.Instance.InsertData(new Classes._DataModels.UserQuote() {
DateAdded = DateTime.Now,
Keyword = keyword.ToLowerInvariant(),
Text = text,
UserName = e.User.Name,
});
await Task.Run(() =>
Classes.DBHandler.Instance.InsertData(new Classes._DataModels.UserQuote() {
DateAdded = DateTime.Now,
Keyword = e.GetArg("keyword").ToLowerInvariant(),
Text = text,
UserName = e.User.Name,
}));
await e.Channel.SendMessage("`New quote added.`");
});
@ -71,17 +63,18 @@ namespace NadekoBot.Modules {
if (string.IsNullOrWhiteSpace(keyword))
return;
var quote = Classes.DBHandler.Instance.GetRandom<Classes._DataModels.UserQuote>(uqm => uqm.Keyword == keyword);
var quote =
Classes.DBHandler.Instance.GetRandom<Classes._DataModels.UserQuote>(
uqm => uqm.Keyword == keyword);
if (quote != null)
await e.Channel.SendMessage($"📣 {quote.Text}");
else
await e.Channel.SendMessage("💢`No quote found.`");
});
});
manager.CreateCommands(NadekoBot.botMention, cgb => {
manager.CreateCommands(NadekoBot.BotMention, cgb => {
var client = manager.Client;
cgb.AddCheck(Classes.Permissions.PermissionChecker.Instance);
@ -92,76 +85,28 @@ namespace NadekoBot.Modules {
.Description("Shows how long Nadeko has been running for.")
.Do(async e => {
var time = (DateTime.Now - Process.GetCurrentProcess().StartTime);
string str = "I have been running for " + time.Days + " days, " + time.Hours + " hours, and " + time.Minutes + " minutes.";
var str = "I have been running for " + time.Days + " days, " + time.Hours + " hours, and " + time.Minutes + " minutes.";
await e.Channel.SendMessage(str);
});
cgb.CreateCommand("die")
.Description("Works only for the owner. Shuts the bot down.")
.Do(async e => {
if (e.User.Id == NadekoBot.OwnerID) {
Timer t = new Timer();
t.Interval = 2000;
t.Elapsed += (s, ev) => { Environment.Exit(0); };
t.Start();
if (NadekoBot.IsOwner(e.User.Id)) {
await e.Channel.SendMessage(e.User.Mention + ", Yes, my love.");
await Task.Delay(5000);
Environment.Exit(0);
} else
await e.Channel.SendMessage(e.User.Mention + ", No.");
});
Stopwatch randServerSW = new Stopwatch();
randServerSW.Start();
cgb.CreateCommand("randserver")
.Description("Generates an invite to a random server and prints some stats.")
.Do(async e => {
if (client.Servers.Count() < 10) {
await e.Channel.SendMessage("I need to be connected to at least 10 servers for this command to work.");
return;
}
var randServerSw = new Stopwatch();
randServerSw.Start();
if (randServerSW.Elapsed.Seconds < 1800) {
await e.Channel.SendMessage("You have to wait " + (1800 - randServerSW.Elapsed.Seconds) + " more seconds to use this function.");
return;
}
randServerSW.Restart();
while (true) {
var server = client.Servers.OrderBy(x => rng.Next()).FirstOrDefault();
if (server == null)
continue;
try {
var inv = await server.CreateInvite(100, 5);
await e.Channel.SendMessage("**Server:** " + server.Name +
"\n**Owner:** " + server.Owner.Name +
"\n**Channels:** " + server.AllChannels.Count() +
"\n**Total Members:** " + server.Users.Count() +
"\n**Online Members:** " + server.Users.Where(u => u.Status == UserStatus.Online).Count() +
"\n**Invite:** " + inv.Url);
break;
} catch { continue; }
}
});
/*
cgb.CreateCommand("avalanche!")
.Description("Mentions a person in every channel of the server, then deletes it")
.Parameter("name", ParameterType.Required)
.Do(e => {
var usr = e.Server.FindUsers(e.GetArg("name")).FirstOrDefault();
if (usr == null) return;
e.Server.AllChannels.ForEach(async c => {
try {
var m = await c.SendMessage(usr.Mention);
await m.Delete();
} catch (Exception ex) {
Console.WriteLine(ex);
}
});
});
*/
cgb.CreateCommand("do you love me")
.Description("Replies with positive answer only to the bot owner.")
.Do(async e => {
if (e.User.Id == NadekoBot.OwnerID)
if (NadekoBot.IsOwner(e.User.Id))
await e.Channel.SendMessage(e.User.Mention + ", Of course I do, my Master.");
else
await e.Channel.SendMessage(e.User.Mention + ", Don't be silly.");
@ -170,15 +115,15 @@ namespace NadekoBot.Modules {
cgb.CreateCommand("how are you")
.Description("Replies positive only if bot owner is online.")
.Do(async e => {
if (e.User.Id == NadekoBot.OwnerID) {
if (NadekoBot.IsOwner(e.User.Id)) {
await e.Channel.SendMessage(e.User.Mention + " I am great as long as you are here.");
return;
}
var kw = e.Server.GetUser(NadekoBot.Creds.OwnerIds[0]);
if (kw != null && kw.Status == UserStatus.Online) {
await e.Channel.SendMessage(e.User.Mention + " I am great as long as " + kw.Mention + " is with me.");
} else {
var kw = e.Server.GetUser(NadekoBot.OwnerID);
if (kw != null && kw.Status == UserStatus.Online) {
await e.Channel.SendMessage(e.User.Mention + " I am great as long as " + kw.Mention + " is with me.");
} else {
await e.Channel.SendMessage(e.User.Mention + " I am sad. My Master is not with me.");
}
await e.Channel.SendMessage(e.User.Mention + " I am sad. My Master is not with me.");
}
});
@ -186,33 +131,31 @@ namespace NadekoBot.Modules {
.Parameter("mention", ParameterType.Required)
.Description("Insults @X person.\n**Usage**: @NadekoBot insult @X.")
.Do(async e => {
List<string> insults = new List<string> { " You are a poop.", " You're a jerk.", " I will eat you when I get my powers back." };
Random r = new Random();
var insults = new List<string> { " You are a poop.", " You're a jerk.", " I will eat you when I get my powers back." };
var u = e.Channel.FindUsers(e.GetArg("mention")).FirstOrDefault();
if (u == null) {
await e.Channel.SendMessage("Invalid user specified.");
return;
}
if (u.Id == NadekoBot.OwnerID) {
if (NadekoBot.IsOwner(u.Id)) {
await e.Channel.SendMessage("I would never insult my master <3");
return;
}
await e.Channel.SendMessage(u.Mention + insults[r.Next(0, insults.Count)]);
await e.Channel.SendMessage(u.Mention + insults[rng.Next(0, insults.Count)]);
});
cgb.CreateCommand("praise")
.Description("Praises @X person.\n**Usage**: @NadekoBot praise @X.")
.Parameter("mention", ParameterType.Required)
.Do(async e => {
List<string> praises = new List<string> { " You are cool.",
var praises = new[] { " You are cool.",
" You are nice!",
" You did a good job.",
" You did something nice.",
" is awesome!",
" Wow."};
Random r = new Random();
var u = e.Channel.FindUsers(e.GetArg("mention")).FirstOrDefault();
if (u == null) {
@ -220,11 +163,11 @@ namespace NadekoBot.Modules {
return;
}
if (u.Id == NadekoBot.OwnerID) {
if (NadekoBot.IsOwner(u.Id)) {
await e.Channel.SendMessage(e.User.Mention + " I don't need your permission to praise my beloved Master <3");
return;
}
await e.Channel.SendMessage(u.Mention + praises[r.Next(0, praises.Count)]);
await e.Channel.SendMessage(u.Mention + praises[rng.Next(0, praises.Length)]);
});
cgb.CreateCommand("pat")
@ -232,28 +175,28 @@ namespace NadekoBot.Modules {
.Parameter("user", ParameterType.Unparsed)
.Do(async e => {
var user = e.GetArg("user");
if (user == null || e.Message.MentionedUsers.Count() == 0) return;
string[] pats = new string[] { "http://i.imgur.com/IiQwK12.gif",
"http://i.imgur.com/JCXj8yD.gif",
"http://i.imgur.com/qqBl2bm.gif",
"http://i.imgur.com/eOJlnwP.gif",
"https://45.media.tumblr.com/229ec0458891c4dcd847545c81e760a5/tumblr_mpfy232F4j1rxrpjzo1_r2_500.gif",
"https://media.giphy.com/media/KZQlfylo73AMU/giphy.gif",
"https://media.giphy.com/media/12hvLuZ7uzvCvK/giphy.gif",
"http://gallery1.anivide.com/_full/65030_1382582341.gif",
"https://49.media.tumblr.com/8e8a099c4eba22abd3ec0f70fd087cce/tumblr_nxovj9oY861ur1mffo1_500.gif ",
if (string.IsNullOrWhiteSpace(user) || !e.Message.MentionedUsers.Any()) return;
string[] pats = { "http://i.imgur.com/IiQwK12.gif",
"http://i.imgur.com/JCXj8yD.gif",
"http://i.imgur.com/qqBl2bm.gif",
"http://i.imgur.com/eOJlnwP.gif",
"https://45.media.tumblr.com/229ec0458891c4dcd847545c81e760a5/tumblr_mpfy232F4j1rxrpjzo1_r2_500.gif",
"https://media.giphy.com/media/KZQlfylo73AMU/giphy.gif",
"https://media.giphy.com/media/12hvLuZ7uzvCvK/giphy.gif",
"http://gallery1.anivide.com/_full/65030_1382582341.gif",
"https://49.media.tumblr.com/8e8a099c4eba22abd3ec0f70fd087cce/tumblr_nxovj9oY861ur1mffo1_500.gif ",
};
await e.Channel.SendMessage($"{e.Message.MentionedUsers.First().Mention} {pats[new Random().Next(0, pats.Length)]}");
await e.Channel.SendMessage($"{e.Message.MentionedUsers.First().Mention} {pats[rng.Next(0, pats.Length)]}");
});
cgb.CreateCommand("cry")
.Description("Tell Nadeko to cry. You are a heartless monster if you use this command.")
.Do(async e => {
string[] pats = new string[] { "http://i.imgur.com/Xg3i1Qy.gif",
"http://i.imgur.com/3K8DRrU.gif",
"http://i.imgur.com/k58BcAv.gif",
"http://i.imgur.com/I2fLXwo.gif" };
await e.Channel.SendMessage($"(•̥́ _•ૅ。)\n{pats[new Random().Next(0, pats.Length)]}");
string[] pats = { "http://i.imgur.com/Xg3i1Qy.gif",
"http://i.imgur.com/3K8DRrU.gif",
"http://i.imgur.com/k58BcAv.gif",
"http://i.imgur.com/I2fLXwo.gif" };
await e.Channel.SendMessage($"(•̥́ _•ૅ。)\n{pats[rng.Next(0, pats.Length)]}");
});
cgb.CreateCommand("are you real")
@ -264,7 +207,7 @@ namespace NadekoBot.Modules {
cgb.CreateCommand("are you there")
.Description("Checks if Nadeko is operational.")
.Alias(new string[] { "!", "?" })
.Alias("!", "?")
.Do(SayYes());
cgb.CreateCommand("draw")
@ -276,16 +219,16 @@ namespace NadekoBot.Modules {
.Description("Shows a unicode fire message. Optional parameter [x] tells her how many times to repeat the fire.\n**Usage**: @NadekoBot fire [x]")
.Parameter("times", ParameterType.Optional)
.Do(async e => {
int count = 0;
if (e.Args?.Length > 0)
int.TryParse(e.Args[0], out count);
var count = 1;
int.TryParse(e.Args[0], out count);
if (count < 1)
count = 1;
else if (count > 12)
count = 12;
string str = "";
for (int i = 0; i < count; i++) {
if (count < 1 || count > 12) {
await e.Channel.SendMessage("Number must be between 0 and 12");
return;
}
var str = "";
for (var i = 0; i < count; i++) {
str += firestr;
}
await e.Channel.SendMessage(str);
@ -299,25 +242,32 @@ namespace NadekoBot.Modules {
if (string.IsNullOrWhiteSpace(e.GetArg("user")))
return;
var usr = e.Channel.FindUsers(e.GetArg("user")).FirstOrDefault();
string text = "";
var text = "";
text = usr?.Name ?? e.GetArg("user");
await e.Channel.SendFile("ripzor_m8.png", RipName(text, e.GetArg("year") == "" ? null : e.GetArg("year")));
await
e.Channel.SendFile("ripzor_m8.png",
RipName(text, string.IsNullOrWhiteSpace(e.GetArg("year")) ? null : e.GetArg("year")));
});
if (!NadekoBot.creds.DontJoinServers) {
if (!NadekoBot.Creds.DontJoinServers) {
cgb.CreateCommand("j")
.Description("Joins a server using a code.")
.Parameter("id", ParameterType.Required)
.Do(async e => {
try {
await (await client.GetInvite(e.Args[0])).Accept();
var invite = await client.GetInvite(e.Args[0]);
if (invite != null) {
try {
await invite.Accept();
}
catch {
await e.Channel.SendMessage("Failed to accept invite.");
}
await e.Channel.SendMessage("I got in!");
return;
}
catch {
await e.Channel.SendMessage("Invalid code.");
}
await e.Channel.SendMessage("Invalid code.");
});
}
cgb.CreateCommand("slm")
.Description("Shows the message where you were last mentioned in this channel (checks last 10k messages)")
.Do(async e => {
@ -329,7 +279,7 @@ namespace NadekoBot.Modules {
if (msgs.Count() > 0)
msg = msgs.First();
else {
int attempt = 0;
var attempt = 0;
Message lastMessage = null;
while (msg == null && attempt++ < 5) {
var msgsarr = await e.Channel.DownloadMessages(100, lastMessage?.Id);
@ -350,7 +300,7 @@ namespace NadekoBot.Modules {
.Description("Says bye to someone. **Usage**: @NadekoBot bb @X")
.Parameter("ppl", ParameterType.Unparsed)
.Do(async e => {
string str = "Bye";
var str = "Bye";
foreach (var u in e.Message.MentionedUsers) {
if (u.Id != NadekoBot.Client.CurrentUser.Id)
str += " " + u.Mention;
@ -367,8 +317,8 @@ namespace NadekoBot.Modules {
cgb.CreateCommand("hide")
.Description("Hides Nadeko in plain sight!11!!")
.Do(async e => {
using (Stream ms = Resources.hidden.ToStream(ImageFormat.Png)) {
await client.CurrentUser.Edit(NadekoBot.password, avatar: ms);
using (var ms = Resources.hidden.ToStream(ImageFormat.Png)) {
await client.CurrentUser.Edit(NadekoBot.Creds.Password, avatar: ms);
}
await e.Channel.SendMessage("*hides*");
});
@ -376,8 +326,8 @@ namespace NadekoBot.Modules {
cgb.CreateCommand("unhide")
.Description("Unhides Nadeko in plain sight!1!!1")
.Do(async e => {
using (FileStream fs = new FileStream("data/avatar.png", FileMode.Open)) {
await client.CurrentUser.Edit(NadekoBot.password, avatar: fs);
using (var fs = new FileStream("data/avatar.png", FileMode.Open)) {
await client.CurrentUser.Edit(NadekoBot.Creds.Password, avatar: fs);
}
await e.Channel.SendMessage("*unhides*");
});
@ -385,16 +335,16 @@ namespace NadekoBot.Modules {
cgb.CreateCommand("dump")
.Description("Dumps all of the invites it can to dump.txt.** Owner Only.**")
.Do(async e => {
if (NadekoBot.OwnerID != e.User.Id) return;
int i = 0;
int j = 0;
string invites = "";
if (!NadekoBot.IsOwner(e.User.Id)) return;
var i = 0;
var j = 0;
var invites = "";
foreach (var s in client.Servers) {
try {
var invite = await s.CreateInvite(0);
invites += invite.Url + "\n";
i++;
} catch {
} catch {
j++;
continue;
}
@ -407,8 +357,8 @@ namespace NadekoBot.Modules {
.Description("Try to get 'abalabahaha'")
.Do(async e => {
string[] strings = { "ba", "la", "ha" };
string construct = "@a";
int cnt = rng.Next(4, 7);
var construct = "@a";
var cnt = rng.Next(4, 7);
while (cnt-- > 0) {
construct += strings[rng.Next(0, strings.Length)];
}
@ -426,65 +376,31 @@ namespace NadekoBot.Modules {
}
await e.Channel.SendMessage(await usr.AvatarUrl.ShortenUrl());
});
/*
string saved = "";
cgb.CreateCommand("save")
.Description("Saves up to 5 last messages as a quote")
.Parameter("number", ParameterType.Required)
.Do(e => {
var arg = e.GetArg("number");
int num;
if (!int.TryParse(arg, out num) || num < 1 || num > 5)
num = 1;
saved = string.Join("\n", e.Channel.Messages.Skip(1).Take(num));
});
cgb.CreateCommand("quote")
.Description("Shows the previously saved quote")
.Parameter("arg", ParameterType.Required)
.Do(async e => {
var arg = e.GetArg("arg");
await e.Channel.SendMessage("```"+saved+"```");
});
*/
//TODO add eval
/*
cgb.CreateCommand(">")
.Parameter("code", ParameterType.Unparsed)
.Do(async e =>
{
if (e.Message.User.Id == NadekoBot.OwnerId)
{
var result = await CSharpScript.EvaluateAsync(e.Args[0]);
await e.Channel.SendMessage( result?.ToString() ?? "null");
return;
}
});*/
});
}
public Stream RipName(string name, string year = null) {
Bitmap bm = Resources.rip;
var bm = Resources.rip;
int offset = name.Length * 5;
var offset = name.Length * 5;
int fontSize = 20;
var fontSize = 20;
if (name.Length > 10) {
fontSize -= (name.Length - 10) / 2;
}
//TODO use measure string
Graphics g = Graphics.FromImage(bm);
var g = Graphics.FromImage(bm);
g.DrawString(name, new Font("Comic Sans MS", fontSize, FontStyle.Bold), Brushes.Black, 100 - offset, 200);
g.DrawString((year == null ? "?" : year) + " - " + DateTime.Now.Year, new Font("Consolas", 12, FontStyle.Bold), Brushes.Black, 80, 235);
g.DrawString((year ?? "?") + " - " + DateTime.Now.Year, new Font("Consolas", 12, FontStyle.Bold), Brushes.Black, 80, 235);
g.Flush();
g.Dispose();
return bm.ToStream(ImageFormat.Png);
}
private Func<CommandEventArgs, Task> SayYes()
private static Func<CommandEventArgs, Task> SayYes()
=> async e => await e.Channel.SendMessage("Yes. :)");
}
}

View File

@ -1,7 +1,6 @@
using System;
using System.Linq;
using Discord.Modules;
using NadekoBot.Extensions;
using NadekoBot.Commands;
using Newtonsoft.Json.Linq;
using System.IO;

View File

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

View File

@ -1,5 +1,4 @@
using Discord;
using Discord.Audio;
using Discord.Commands;
using Discord.Modules;
using NadekoBot.Classes;
@ -8,7 +7,6 @@ using NadekoBot.Extensions;
using System;
using System.Collections.Concurrent;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Timer = System.Timers.Timer;

View File

@ -1,6 +1,5 @@
using System;
using Discord.Modules;
using NadekoBot.Extensions;
using Discord.Commands;
using Newtonsoft.Json.Linq;
using NadekoBot.Classes;

View File

@ -1,11 +1,9 @@
using System;
using Discord.Modules;
using Discord.Commands;
using NadekoBot.Extensions;
using NadekoBot.Classes;
using PermsHandler = NadekoBot.Classes.Permissions.PermissionsHandler;
using System.Linq;
using System.Text;
namespace NadekoBot.Modules {
class PermissionModule : DiscordModule {

View File

@ -65,7 +65,7 @@ namespace NadekoBot.Modules {
.Description("Joins a server")
.Parameter("code", Discord.Commands.ParameterType.Required)
.Do(async e => {
if (e.User.Id != NadekoBot.OwnerId) return;
if (!NadekoBot.IsOwner(e.User.Id)) return;
try {
await (await client.GetInvite(e.GetArg("code"))).Accept();
} catch (Exception ex) {
@ -77,7 +77,7 @@ namespace NadekoBot.Modules {
.Description("Bind a trello bot to a single channel. You will receive notifications from your board when something is added or edited.")
.Parameter("board_id", Discord.Commands.ParameterType.Required)
.Do(async e => {
if (e.User.Id != NadekoBot.OwnerId) return;
if (!NadekoBot.IsOwner(e.User.Id)) return;
if (bound != null) return;
try {
bound = e.Channel;
@ -93,7 +93,7 @@ namespace NadekoBot.Modules {
cgb.CreateCommand("unbind")
.Description("Unbinds a bot from the channel and board.")
.Do(async e => {
if (e.User.Id != NadekoBot.OwnerId) return;
if (!NadekoBot.IsOwner(e.User.Id)) return;
if (bound == null || bound != e.Channel) return;
t.Stop();
bound = null;
@ -106,7 +106,7 @@ namespace NadekoBot.Modules {
.Alias("list")
.Description("Lists all lists yo ;)")
.Do(async e => {
if (e.User.Id != NadekoBot.OwnerId) return;
if (!NadekoBot.IsOwner(e.User.Id)) return;
if (bound == null || board == null || bound != e.Channel) return;
await e.Channel.SendMessage("Lists for a board '" + board.Name + "'\n" + string.Join("\n", board.Lists.Select(l => "**• " + l.ToString() + "**")));
});
@ -115,7 +115,7 @@ namespace NadekoBot.Modules {
.Description("Lists all cards from the supplied list. You can supply either a name or an index.")
.Parameter("list_name", Discord.Commands.ParameterType.Unparsed)
.Do(async e => {
if (e.User.Id != NadekoBot.OwnerId) return;
if (!NadekoBot.IsOwner(e.User.Id)) return;
if (bound == null || board == null || bound != e.Channel || e.GetArg("list_name") == null) return;
int num;

View File

@ -6,69 +6,54 @@ using Discord.Commands;
using NadekoBot.Modules;
using Discord.Modules;
using Discord.Audio;
using NadekoBot.Extensions;
using System.Timers;
using System.Linq;
using System.Threading.Tasks;
using NadekoBot.Classes;
using NadekoBot.Classes.JSONModels;
namespace NadekoBot {
public class NadekoBot {
public static DiscordClient Client;
public static string botMention;
public static string GoogleAPIKey = null;
public static Channel OwnerPrivateChannel = null;
public static string TrelloAppKey;
public static bool ForwardMessages = false;
public static Credentials Creds { get; set; }
public static string BotMention { get; set; } = "";
private static Channel OwnerPrivateChannel { get; set; }
static void Main() {
//load credentials from credentials.json
bool loadTrello = false;
try {
//load credentials from credentials.json
Creds = JsonConvert.DeserializeObject<Credentials>(File.ReadAllText("credentials.json"));
botMention = Creds.BotMention;
if (string.IsNullOrWhiteSpace(Creds.GoogleAPIKey)) {
Console.WriteLine("No google api key found. You will not be able to use music and links won't be shortened.");
}
else {
Console.WriteLine("Google API key provided.");
GoogleAPIKey = Creds.GoogleAPIKey;
}
if (string.IsNullOrWhiteSpace(Creds.TrelloAppKey)) {
Console.WriteLine("No trello appkey found. You will not be able to use trello commands.");
}
else {
Console.WriteLine("Trello app key provided.");
TrelloAppKey = Creds.TrelloAppKey;
loadTrello = true;
}
if (Creds.ForwardMessages != true)
Console.WriteLine("Not forwarding messages.");
else {
ForwardMessages = true;
Console.WriteLine("Forwarding messages.");
}
if (string.IsNullOrWhiteSpace(Creds.SoundCloudClientID))
Console.WriteLine("No soundcloud Client ID found. Soundcloud streaming is disabled.");
else
Console.WriteLine("SoundCloud streaming enabled.");
}
catch (Exception ex) {
} catch (Exception ex) {
Console.WriteLine($"Failed to load stuff from credentials.json, RTFM\n{ex.Message}");
Console.ReadKey();
return;
}
//create new discord client
Console.WriteLine(string.IsNullOrWhiteSpace(Creds.GoogleAPIKey)
? "No google api key found. You will not be able to use music and links won't be shortened."
: "Google API key provided.");
Console.WriteLine(string.IsNullOrWhiteSpace(Creds.TrelloAppKey)
? "No trello appkey found. You will not be able to use trello commands."
: "Trello app key provided.");
Console.WriteLine(Creds.ForwardMessages != true
? "Not forwarding messages."
: "Forwarding private messages to owner.");
Console.WriteLine(string.IsNullOrWhiteSpace(Creds.SoundCloudClientID)
? "No soundcloud Client ID found. Soundcloud streaming is disabled."
: "SoundCloud streaming enabled.");
BotMention = $"<@{Creds.BotId}>";
//create new discord client and log
Client = new DiscordClient(new DiscordConfigBuilder() {
MessageCacheSize = 20,
LogLevel = LogSeverity.Warning,
LogHandler = (s, e) => {
try {
Console.WriteLine($"Severity: {e.Severity}\nMessage: {e.Message}\nExceptionMessage: {e.Exception?.Message ?? "-"}");//\nException: {(e.Exception?.ToString() ?? "-")}");
}
catch { }
}
LogHandler = (s, e) =>
Console.WriteLine($"Severity: {e.Severity}" +
$"Message: {e.Message}" +
$"ExceptionMessage: {e.Exception?.Message ?? "-"}"),
});
//create a command service
@ -77,14 +62,13 @@ namespace NadekoBot {
CustomPrefixHandler = m => 0,
HelpMode = HelpMode.Disabled,
ErrorHandler = async (s, e) => {
if (e.ErrorType != CommandErrorType.BadPermissions)
return;
if (string.IsNullOrWhiteSpace(e.Exception?.Message))
return;
try {
if (e.ErrorType != CommandErrorType.BadPermissions)
return;
if (string.IsNullOrWhiteSpace(e.Exception.Message))
return;
await e.Channel.SendMessage(e.Exception.Message);
}
catch { }
} catch { }
}
});
@ -92,13 +76,13 @@ namespace NadekoBot {
Client.MessageReceived += Client_MessageReceived;
//add command service
var commands = Client.AddService<CommandService>(commandService);
Client.AddService<CommandService>(commandService);
//create module service
var modules = Client.AddService<ModuleService>(new ModuleService());
//add audio service
var audio = Client.AddService<AudioService>(new AudioService(new AudioServiceConfigBuilder() {
Client.AddService<AudioService>(new AudioService(new AudioServiceConfigBuilder() {
Channels = 2,
EnableEncryption = false,
EnableMultiserver = true,
@ -114,16 +98,15 @@ namespace NadekoBot {
modules.Add(new Games(), "Games", ModuleFilter.None);
modules.Add(new Music(), "Music", ModuleFilter.None);
modules.Add(new Searches(), "Searches", ModuleFilter.None);
if (loadTrello)
modules.Add(new Trello(), "Trello", ModuleFilter.None);
modules.Add(new NSFW(), "NSFW", ModuleFilter.None);
if (!string.IsNullOrWhiteSpace(Creds.TrelloAppKey))
modules.Add(new Trello(), "Trello", ModuleFilter.None);
//run the bot
Client.ExecuteAndWait(async () => {
try {
await Client.Connect(Creds.Username, Creds.Password);
}
catch (Exception ex) {
} catch (Exception ex) {
Console.WriteLine($"Probably wrong EMAIL or PASSWORD.\n{ex.Message}");
Console.ReadKey();
Console.WriteLine(ex);
@ -135,47 +118,36 @@ namespace NadekoBot {
Console.WriteLine("-----------------");
try {
OwnerPrivateChannel = await Client.CreatePrivateChannel(OwnerId);
}
catch {
Console.WriteLine("Failed creating private channel with the owner");
OwnerPrivateChannel = await Client.CreatePrivateChannel(Creds.OwnerIds[0]);
} catch {
Console.WriteLine("Failed creating private channel with the first owner listed in credentials.json");
}
Classes.Permissions.PermissionsHandler.Initialize();
Client.ClientAPI.SendingRequest += (s, e) => {
try {
var request = e.Request as Discord.API.Client.Rest.SendMessageRequest;
if (request != null) {
//@everyοne
request.Content = request.Content?.Replace("@everyone", "@everryone") ?? "_error_";
if (string.IsNullOrWhiteSpace(request.Content))
e.Cancel = true;
//else
// Console.WriteLine("Sending request");
}
}
catch {
Console.WriteLine("SENDING REQUEST ERRORED!!!!");
}
var request = e.Request as Discord.API.Client.Rest.SendMessageRequest;
if (request == null) return;
request.Content = request.Content?.Replace("@everyone", "@everyοne") ?? "_error_";
if (string.IsNullOrWhiteSpace(request.Content))
e.Cancel = true;
};
//client.ClientAPI.SentRequest += (s, e) => {
// try {
// var request = e.Request as Discord.API.Client.Rest.SendMessageRequest;
// if (request != null) {
// Console.WriteLine("Sent.");
// }
// }
// catch { Console.WriteLine("SENT REQUEST ERRORED!!!"); }
//};
});
Console.WriteLine("Exiting...");
Console.ReadKey();
}
static bool repliedRecently = false;
public static bool IsOwner(ulong id) => Creds.OwnerIds.Contains(id);
public static bool IsOwner(User u) => IsOwner(u.Id);
public async Task SendMessageToOwner(string message) {
if (ForwardMessages && OwnerPrivateChannel != null)
await OwnerPrivateChannel.SendMessage(message);
}
private static bool repliedRecently = false;
private static async void Client_MessageReceived(object sender, MessageEventArgs e) {
try {
if (e.Server != null || e.User.Id == Client.CurrentUser.Id) return;
@ -187,14 +159,13 @@ namespace NadekoBot {
e.User.Id == 119174277298782216 ||
e.User.Id == 143515953525817344)
return; // FU
if (!NadekoBot.Creds.DontJoinServers) {
try {
await (await Client.GetInvite(e.Message.Text)).Accept();
await e.Channel.SendMessage("I got in!");
return;
}
catch {
} catch {
if (e.User.Id == 109338686889476096) { //carbonitex invite
await e.Channel.SendMessage("Failed to join the server.");
return;
@ -205,23 +176,15 @@ namespace NadekoBot {
if (ForwardMessages && OwnerPrivateChannel != null)
await OwnerPrivateChannel.SendMessage(e.User + ": ```\n" + e.Message.Text + "\n```");
if (!repliedRecently) {
if (repliedRecently) return;
repliedRecently = true;
await e.Channel.SendMessage(HelpCommand.HelpString);
await Task.Run(async () => {
await Task.Delay(2000);
repliedRecently = true;
await e.Channel.SendMessage("**FULL LIST OF COMMANDS**:\n❤ <https://gist.github.com/Kwoth/1ab3a38424f208802b74> ❤\n\n⚠**COMMANDS DO NOT WORK IN PERSONAL MESSAGES**\n\n\n**Bot Creator's server:** <https://discord.gg/0ehQwTK2RBjAxzEY>");
Timer t = new Timer();
t.Interval = 2000;
t.Start();
t.Elapsed += (s, ev) => {
try {
repliedRecently = false;
t.Stop();
t.Dispose();
}
catch { }
};
}
}
catch { }
});
} catch { }
}
}
}

View File

@ -117,6 +117,9 @@
<ItemGroup>
<Compile Include="Classes\DBHandler.cs" />
<Compile Include="Classes\FlowersHandler.cs" />
<Compile Include="Classes\JSONModels\AnimeResult.cs" />
<Compile Include="Classes\JSONModels\MangaResult.cs" />
<Compile Include="Classes\JSONModels\_JSONModels.cs" />
<Compile Include="Classes\Music\MusicControls.cs" />
<Compile Include="Classes\Music\Song.cs" />
<Compile Include="Classes\Music\StreamRequest.cs" />
@ -147,7 +150,6 @@
<Compile Include="Commands\RequestsCommand.cs" />
<Compile Include="Commands\ServerGreetCommand.cs" />
<Compile Include="Commands\SpeedTyping.cs" />
<Compile Include="Classes\_JSONModels.cs" />
<Compile Include="Classes\Cards.cs" />
<Compile Include="Classes\Extensions.cs" />
<Compile Include="Commands\CopyCommand.cs" />

View File

@ -1,5 +1,4 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following