diff --git a/BUILDS/net6.0/CMD_LevelingSystem.deps.json b/BUILDS/net6.0/CMD_LevelingSystem.deps.json
deleted file mode 100644
index ab0049d..0000000
--- a/BUILDS/net6.0/CMD_LevelingSystem.deps.json
+++ /dev/null
@@ -1,268 +0,0 @@
-{
- "runtimeTarget": {
- "name": ".NETCoreApp,Version=v6.0",
- "signature": ""
- },
- "compilationOptions": {},
- "targets": {
- ".NETCoreApp,Version=v6.0": {
- "CMD_LevelingSystem/1.0.0": {
- "dependencies": {
- "PluginManager": "1.0.0"
- },
- "runtime": {
- "CMD_LevelingSystem.dll": {}
- }
- },
- "Discord.Net/3.6.1": {
- "dependencies": {
- "Discord.Net.Commands": "3.6.1",
- "Discord.Net.Core": "3.6.1",
- "Discord.Net.Interactions": "3.6.1",
- "Discord.Net.Rest": "3.6.1",
- "Discord.Net.WebSocket": "3.6.1",
- "Discord.Net.Webhook": "3.6.1"
- }
- },
- "Discord.Net.Commands/3.6.1": {
- "dependencies": {
- "Discord.Net.Core": "3.6.1"
- },
- "runtime": {
- "lib/net6.0/Discord.Net.Commands.dll": {
- "assemblyVersion": "3.6.1.0",
- "fileVersion": "3.6.1.0"
- }
- }
- },
- "Discord.Net.Core/3.6.1": {
- "dependencies": {
- "Newtonsoft.Json": "13.0.1",
- "System.Collections.Immutable": "5.0.0",
- "System.Interactive.Async": "5.0.0",
- "System.ValueTuple": "4.5.0"
- },
- "runtime": {
- "lib/net6.0/Discord.Net.Core.dll": {
- "assemblyVersion": "3.6.1.0",
- "fileVersion": "3.6.1.0"
- }
- }
- },
- "Discord.Net.Interactions/3.6.1": {
- "dependencies": {
- "Discord.Net.Core": "3.6.1",
- "Discord.Net.Rest": "3.6.1",
- "Discord.Net.WebSocket": "3.6.1",
- "Microsoft.Extensions.DependencyInjection.Abstractions": "5.0.0",
- "System.Collections.Immutable": "5.0.0",
- "System.Reactive": "5.0.0"
- },
- "runtime": {
- "lib/net6.0/Discord.Net.Interactions.dll": {
- "assemblyVersion": "3.6.1.0",
- "fileVersion": "3.6.1.0"
- }
- }
- },
- "Discord.Net.Rest/3.6.1": {
- "dependencies": {
- "Discord.Net.Core": "3.6.1"
- },
- "runtime": {
- "lib/net6.0/Discord.Net.Rest.dll": {
- "assemblyVersion": "3.6.1.0",
- "fileVersion": "3.6.1.0"
- }
- }
- },
- "Discord.Net.Webhook/3.6.1": {
- "dependencies": {
- "Discord.Net.Core": "3.6.1",
- "Discord.Net.Rest": "3.6.1"
- },
- "runtime": {
- "lib/net6.0/Discord.Net.Webhook.dll": {
- "assemblyVersion": "3.6.1.0",
- "fileVersion": "3.6.1.0"
- }
- }
- },
- "Discord.Net.WebSocket/3.6.1": {
- "dependencies": {
- "Discord.Net.Core": "3.6.1",
- "Discord.Net.Rest": "3.6.1"
- },
- "runtime": {
- "lib/net6.0/Discord.Net.WebSocket.dll": {
- "assemblyVersion": "3.6.1.0",
- "fileVersion": "3.6.1.0"
- }
- }
- },
- "Microsoft.Extensions.DependencyInjection.Abstractions/5.0.0": {
- "runtime": {
- "lib/netstandard2.0/Microsoft.Extensions.DependencyInjection.Abstractions.dll": {
- "assemblyVersion": "5.0.0.0",
- "fileVersion": "5.0.20.51904"
- }
- }
- },
- "Newtonsoft.Json/13.0.1": {
- "runtime": {
- "lib/netstandard2.0/Newtonsoft.Json.dll": {
- "assemblyVersion": "13.0.0.0",
- "fileVersion": "13.0.1.25517"
- }
- }
- },
- "System.Collections.Immutable/5.0.0": {},
- "System.Interactive.Async/5.0.0": {
- "dependencies": {
- "System.Linq.Async": "5.0.0"
- },
- "runtime": {
- "lib/netcoreapp3.1/System.Interactive.Async.dll": {
- "assemblyVersion": "5.0.0.0",
- "fileVersion": "5.0.0.1"
- }
- }
- },
- "System.Linq.Async/5.0.0": {
- "runtime": {
- "lib/netcoreapp3.1/System.Linq.Async.dll": {
- "assemblyVersion": "5.0.0.0",
- "fileVersion": "5.0.0.1"
- }
- }
- },
- "System.Reactive/5.0.0": {
- "runtime": {
- "lib/net5.0/System.Reactive.dll": {
- "assemblyVersion": "5.0.0.0",
- "fileVersion": "5.0.0.1"
- }
- }
- },
- "System.ValueTuple/4.5.0": {},
- "PluginManager/1.0.0": {
- "dependencies": {
- "Discord.Net": "3.6.1"
- },
- "runtime": {
- "PluginManager.dll": {}
- }
- }
- }
- },
- "libraries": {
- "CMD_LevelingSystem/1.0.0": {
- "type": "project",
- "serviceable": false,
- "sha512": ""
- },
- "Discord.Net/3.6.1": {
- "type": "package",
- "serviceable": true,
- "sha512": "sha512-TfcL/HG57fVt//WVJ2XyF2PlytY9IYkkwwkPLIhvu5FW4wf9rm7+N8RPh4qtELLfsa5ES0FK2RbgYjABRR9AjA==",
- "path": "discord.net/3.6.1",
- "hashPath": "discord.net.3.6.1.nupkg.sha512"
- },
- "Discord.Net.Commands/3.6.1": {
- "type": "package",
- "serviceable": true,
- "sha512": "sha512-kK7m571yzSzPd93o+n8Z+TfvX62BT1HtOEZIWXKwXWO8itP/sgqBNExjWK/6DOpkbD6+khc2f3rp+TA0rJD88g==",
- "path": "discord.net.commands/3.6.1",
- "hashPath": "discord.net.commands.3.6.1.nupkg.sha512"
- },
- "Discord.Net.Core/3.6.1": {
- "type": "package",
- "serviceable": true,
- "sha512": "sha512-ibVjQiWzgqh0GyP/GXE2kv3TA/9ysmmNFG/WmRE7GepQQAXXGxVUO9IMJ8h14EvIXMQ0m0DktMe5DkUnilo3Ag==",
- "path": "discord.net.core/3.6.1",
- "hashPath": "discord.net.core.3.6.1.nupkg.sha512"
- },
- "Discord.Net.Interactions/3.6.1": {
- "type": "package",
- "serviceable": true,
- "sha512": "sha512-WGOxz6SMUu4WS5b/JdrhlwQletcplBIYqvjFBBDfnqE+uNJqcNGtAdyjLqIILfXGx8aSSSSYZSCeAUa7FZ8Yew==",
- "path": "discord.net.interactions/3.6.1",
- "hashPath": "discord.net.interactions.3.6.1.nupkg.sha512"
- },
- "Discord.Net.Rest/3.6.1": {
- "type": "package",
- "serviceable": true,
- "sha512": "sha512-T7RRThIS23roFEJwTL1l7aawjVyn7ZB5yH3tMge0d6TiCzzp4V4FAZ+ArTt19LHRFhPly90v8V3sWqmTMN+5Zg==",
- "path": "discord.net.rest/3.6.1",
- "hashPath": "discord.net.rest.3.6.1.nupkg.sha512"
- },
- "Discord.Net.Webhook/3.6.1": {
- "type": "package",
- "serviceable": true,
- "sha512": "sha512-xikKHIGAIMz0BzHkaTKb48DNpFjKW8mvJjLJSezJ1xQOu+laHNk/hav4qxVtyZz7HSI/vGTkmlq9hKVhWzpaUA==",
- "path": "discord.net.webhook/3.6.1",
- "hashPath": "discord.net.webhook.3.6.1.nupkg.sha512"
- },
- "Discord.Net.WebSocket/3.6.1": {
- "type": "package",
- "serviceable": true,
- "sha512": "sha512-hF22Xy7URlVEDQZ69INOgzPvFUsIDfd+r6U+1yF9HWdBn3d4THnvAAhkv1TraSx/T/MKS7g+jvk/HZ3mh5S3aw==",
- "path": "discord.net.websocket/3.6.1",
- "hashPath": "discord.net.websocket.3.6.1.nupkg.sha512"
- },
- "Microsoft.Extensions.DependencyInjection.Abstractions/5.0.0": {
- "type": "package",
- "serviceable": true,
- "sha512": "sha512-ORj7Zh81gC69TyvmcUm9tSzytcy8AVousi+IVRAI8nLieQjOFryRusSFh7+aLk16FN9pQNqJAiMd7BTKINK0kA==",
- "path": "microsoft.extensions.dependencyinjection.abstractions/5.0.0",
- "hashPath": "microsoft.extensions.dependencyinjection.abstractions.5.0.0.nupkg.sha512"
- },
- "Newtonsoft.Json/13.0.1": {
- "type": "package",
- "serviceable": true,
- "sha512": "sha512-ppPFpBcvxdsfUonNcvITKqLl3bqxWbDCZIzDWHzjpdAHRFfZe0Dw9HmA0+za13IdyrgJwpkDTDA9fHaxOrt20A==",
- "path": "newtonsoft.json/13.0.1",
- "hashPath": "newtonsoft.json.13.0.1.nupkg.sha512"
- },
- "System.Collections.Immutable/5.0.0": {
- "type": "package",
- "serviceable": true,
- "sha512": "sha512-FXkLXiK0sVVewcso0imKQoOxjoPAj42R8HtjjbSjVPAzwDfzoyoznWxgA3c38LDbN9SJux1xXoXYAhz98j7r2g==",
- "path": "system.collections.immutable/5.0.0",
- "hashPath": "system.collections.immutable.5.0.0.nupkg.sha512"
- },
- "System.Interactive.Async/5.0.0": {
- "type": "package",
- "serviceable": true,
- "sha512": "sha512-QaqhQVDiULcu4vm6o89+iP329HcK44cETHOYgy/jfEjtzeFy0ZxmuM7nel9ocjnKxEM4yh1mli7hgh8Q9o+/Iw==",
- "path": "system.interactive.async/5.0.0",
- "hashPath": "system.interactive.async.5.0.0.nupkg.sha512"
- },
- "System.Linq.Async/5.0.0": {
- "type": "package",
- "serviceable": true,
- "sha512": "sha512-cPtIuuH8TIjVHSi2ewwReWGW1PfChPE0LxPIDlfwVcLuTM9GANFTXiMB7k3aC4sk3f0cQU25LNKzx+jZMxijqw==",
- "path": "system.linq.async/5.0.0",
- "hashPath": "system.linq.async.5.0.0.nupkg.sha512"
- },
- "System.Reactive/5.0.0": {
- "type": "package",
- "serviceable": true,
- "sha512": "sha512-erBZjkQHWL9jpasCE/0qKAryzVBJFxGHVBAvgRN1bzM0q2s1S4oYREEEL0Vb+1kA/6BKb5FjUZMp5VXmy+gzkQ==",
- "path": "system.reactive/5.0.0",
- "hashPath": "system.reactive.5.0.0.nupkg.sha512"
- },
- "System.ValueTuple/4.5.0": {
- "type": "package",
- "serviceable": true,
- "sha512": "sha512-okurQJO6NRE/apDIP23ajJ0hpiNmJ+f0BwOlB/cSqTLQlw5upkf+5+96+iG2Jw40G1fCVCyPz/FhIABUjMR+RQ==",
- "path": "system.valuetuple/4.5.0",
- "hashPath": "system.valuetuple.4.5.0.nupkg.sha512"
- },
- "PluginManager/1.0.0": {
- "type": "project",
- "serviceable": false,
- "sha512": ""
- }
- }
-}
\ No newline at end of file
diff --git a/BUILDS/net6.0/CMD_LevelingSystem.dll b/BUILDS/net6.0/CMD_LevelingSystem.dll
deleted file mode 100644
index c69f2b3..0000000
Binary files a/BUILDS/net6.0/CMD_LevelingSystem.dll and /dev/null differ
diff --git a/BUILDS/net6.0/EVE_LevelingSystem.deps.json b/BUILDS/net6.0/EVE_LevelingSystem.deps.json
deleted file mode 100644
index 1b99176..0000000
--- a/BUILDS/net6.0/EVE_LevelingSystem.deps.json
+++ /dev/null
@@ -1,268 +0,0 @@
-{
- "runtimeTarget": {
- "name": ".NETCoreApp,Version=v6.0",
- "signature": ""
- },
- "compilationOptions": {},
- "targets": {
- ".NETCoreApp,Version=v6.0": {
- "EVE_LevelingSystem/1.0.0": {
- "dependencies": {
- "PluginManager": "1.0.0"
- },
- "runtime": {
- "EVE_LevelingSystem.dll": {}
- }
- },
- "Discord.Net/3.6.1": {
- "dependencies": {
- "Discord.Net.Commands": "3.6.1",
- "Discord.Net.Core": "3.6.1",
- "Discord.Net.Interactions": "3.6.1",
- "Discord.Net.Rest": "3.6.1",
- "Discord.Net.WebSocket": "3.6.1",
- "Discord.Net.Webhook": "3.6.1"
- }
- },
- "Discord.Net.Commands/3.6.1": {
- "dependencies": {
- "Discord.Net.Core": "3.6.1"
- },
- "runtime": {
- "lib/net6.0/Discord.Net.Commands.dll": {
- "assemblyVersion": "3.6.1.0",
- "fileVersion": "3.6.1.0"
- }
- }
- },
- "Discord.Net.Core/3.6.1": {
- "dependencies": {
- "Newtonsoft.Json": "13.0.1",
- "System.Collections.Immutable": "5.0.0",
- "System.Interactive.Async": "5.0.0",
- "System.ValueTuple": "4.5.0"
- },
- "runtime": {
- "lib/net6.0/Discord.Net.Core.dll": {
- "assemblyVersion": "3.6.1.0",
- "fileVersion": "3.6.1.0"
- }
- }
- },
- "Discord.Net.Interactions/3.6.1": {
- "dependencies": {
- "Discord.Net.Core": "3.6.1",
- "Discord.Net.Rest": "3.6.1",
- "Discord.Net.WebSocket": "3.6.1",
- "Microsoft.Extensions.DependencyInjection.Abstractions": "5.0.0",
- "System.Collections.Immutable": "5.0.0",
- "System.Reactive": "5.0.0"
- },
- "runtime": {
- "lib/net6.0/Discord.Net.Interactions.dll": {
- "assemblyVersion": "3.6.1.0",
- "fileVersion": "3.6.1.0"
- }
- }
- },
- "Discord.Net.Rest/3.6.1": {
- "dependencies": {
- "Discord.Net.Core": "3.6.1"
- },
- "runtime": {
- "lib/net6.0/Discord.Net.Rest.dll": {
- "assemblyVersion": "3.6.1.0",
- "fileVersion": "3.6.1.0"
- }
- }
- },
- "Discord.Net.Webhook/3.6.1": {
- "dependencies": {
- "Discord.Net.Core": "3.6.1",
- "Discord.Net.Rest": "3.6.1"
- },
- "runtime": {
- "lib/net6.0/Discord.Net.Webhook.dll": {
- "assemblyVersion": "3.6.1.0",
- "fileVersion": "3.6.1.0"
- }
- }
- },
- "Discord.Net.WebSocket/3.6.1": {
- "dependencies": {
- "Discord.Net.Core": "3.6.1",
- "Discord.Net.Rest": "3.6.1"
- },
- "runtime": {
- "lib/net6.0/Discord.Net.WebSocket.dll": {
- "assemblyVersion": "3.6.1.0",
- "fileVersion": "3.6.1.0"
- }
- }
- },
- "Microsoft.Extensions.DependencyInjection.Abstractions/5.0.0": {
- "runtime": {
- "lib/netstandard2.0/Microsoft.Extensions.DependencyInjection.Abstractions.dll": {
- "assemblyVersion": "5.0.0.0",
- "fileVersion": "5.0.20.51904"
- }
- }
- },
- "Newtonsoft.Json/13.0.1": {
- "runtime": {
- "lib/netstandard2.0/Newtonsoft.Json.dll": {
- "assemblyVersion": "13.0.0.0",
- "fileVersion": "13.0.1.25517"
- }
- }
- },
- "System.Collections.Immutable/5.0.0": {},
- "System.Interactive.Async/5.0.0": {
- "dependencies": {
- "System.Linq.Async": "5.0.0"
- },
- "runtime": {
- "lib/netcoreapp3.1/System.Interactive.Async.dll": {
- "assemblyVersion": "5.0.0.0",
- "fileVersion": "5.0.0.1"
- }
- }
- },
- "System.Linq.Async/5.0.0": {
- "runtime": {
- "lib/netcoreapp3.1/System.Linq.Async.dll": {
- "assemblyVersion": "5.0.0.0",
- "fileVersion": "5.0.0.1"
- }
- }
- },
- "System.Reactive/5.0.0": {
- "runtime": {
- "lib/net5.0/System.Reactive.dll": {
- "assemblyVersion": "5.0.0.0",
- "fileVersion": "5.0.0.1"
- }
- }
- },
- "System.ValueTuple/4.5.0": {},
- "PluginManager/1.0.0": {
- "dependencies": {
- "Discord.Net": "3.6.1"
- },
- "runtime": {
- "PluginManager.dll": {}
- }
- }
- }
- },
- "libraries": {
- "EVE_LevelingSystem/1.0.0": {
- "type": "project",
- "serviceable": false,
- "sha512": ""
- },
- "Discord.Net/3.6.1": {
- "type": "package",
- "serviceable": true,
- "sha512": "sha512-TfcL/HG57fVt//WVJ2XyF2PlytY9IYkkwwkPLIhvu5FW4wf9rm7+N8RPh4qtELLfsa5ES0FK2RbgYjABRR9AjA==",
- "path": "discord.net/3.6.1",
- "hashPath": "discord.net.3.6.1.nupkg.sha512"
- },
- "Discord.Net.Commands/3.6.1": {
- "type": "package",
- "serviceable": true,
- "sha512": "sha512-kK7m571yzSzPd93o+n8Z+TfvX62BT1HtOEZIWXKwXWO8itP/sgqBNExjWK/6DOpkbD6+khc2f3rp+TA0rJD88g==",
- "path": "discord.net.commands/3.6.1",
- "hashPath": "discord.net.commands.3.6.1.nupkg.sha512"
- },
- "Discord.Net.Core/3.6.1": {
- "type": "package",
- "serviceable": true,
- "sha512": "sha512-ibVjQiWzgqh0GyP/GXE2kv3TA/9ysmmNFG/WmRE7GepQQAXXGxVUO9IMJ8h14EvIXMQ0m0DktMe5DkUnilo3Ag==",
- "path": "discord.net.core/3.6.1",
- "hashPath": "discord.net.core.3.6.1.nupkg.sha512"
- },
- "Discord.Net.Interactions/3.6.1": {
- "type": "package",
- "serviceable": true,
- "sha512": "sha512-WGOxz6SMUu4WS5b/JdrhlwQletcplBIYqvjFBBDfnqE+uNJqcNGtAdyjLqIILfXGx8aSSSSYZSCeAUa7FZ8Yew==",
- "path": "discord.net.interactions/3.6.1",
- "hashPath": "discord.net.interactions.3.6.1.nupkg.sha512"
- },
- "Discord.Net.Rest/3.6.1": {
- "type": "package",
- "serviceable": true,
- "sha512": "sha512-T7RRThIS23roFEJwTL1l7aawjVyn7ZB5yH3tMge0d6TiCzzp4V4FAZ+ArTt19LHRFhPly90v8V3sWqmTMN+5Zg==",
- "path": "discord.net.rest/3.6.1",
- "hashPath": "discord.net.rest.3.6.1.nupkg.sha512"
- },
- "Discord.Net.Webhook/3.6.1": {
- "type": "package",
- "serviceable": true,
- "sha512": "sha512-xikKHIGAIMz0BzHkaTKb48DNpFjKW8mvJjLJSezJ1xQOu+laHNk/hav4qxVtyZz7HSI/vGTkmlq9hKVhWzpaUA==",
- "path": "discord.net.webhook/3.6.1",
- "hashPath": "discord.net.webhook.3.6.1.nupkg.sha512"
- },
- "Discord.Net.WebSocket/3.6.1": {
- "type": "package",
- "serviceable": true,
- "sha512": "sha512-hF22Xy7URlVEDQZ69INOgzPvFUsIDfd+r6U+1yF9HWdBn3d4THnvAAhkv1TraSx/T/MKS7g+jvk/HZ3mh5S3aw==",
- "path": "discord.net.websocket/3.6.1",
- "hashPath": "discord.net.websocket.3.6.1.nupkg.sha512"
- },
- "Microsoft.Extensions.DependencyInjection.Abstractions/5.0.0": {
- "type": "package",
- "serviceable": true,
- "sha512": "sha512-ORj7Zh81gC69TyvmcUm9tSzytcy8AVousi+IVRAI8nLieQjOFryRusSFh7+aLk16FN9pQNqJAiMd7BTKINK0kA==",
- "path": "microsoft.extensions.dependencyinjection.abstractions/5.0.0",
- "hashPath": "microsoft.extensions.dependencyinjection.abstractions.5.0.0.nupkg.sha512"
- },
- "Newtonsoft.Json/13.0.1": {
- "type": "package",
- "serviceable": true,
- "sha512": "sha512-ppPFpBcvxdsfUonNcvITKqLl3bqxWbDCZIzDWHzjpdAHRFfZe0Dw9HmA0+za13IdyrgJwpkDTDA9fHaxOrt20A==",
- "path": "newtonsoft.json/13.0.1",
- "hashPath": "newtonsoft.json.13.0.1.nupkg.sha512"
- },
- "System.Collections.Immutable/5.0.0": {
- "type": "package",
- "serviceable": true,
- "sha512": "sha512-FXkLXiK0sVVewcso0imKQoOxjoPAj42R8HtjjbSjVPAzwDfzoyoznWxgA3c38LDbN9SJux1xXoXYAhz98j7r2g==",
- "path": "system.collections.immutable/5.0.0",
- "hashPath": "system.collections.immutable.5.0.0.nupkg.sha512"
- },
- "System.Interactive.Async/5.0.0": {
- "type": "package",
- "serviceable": true,
- "sha512": "sha512-QaqhQVDiULcu4vm6o89+iP329HcK44cETHOYgy/jfEjtzeFy0ZxmuM7nel9ocjnKxEM4yh1mli7hgh8Q9o+/Iw==",
- "path": "system.interactive.async/5.0.0",
- "hashPath": "system.interactive.async.5.0.0.nupkg.sha512"
- },
- "System.Linq.Async/5.0.0": {
- "type": "package",
- "serviceable": true,
- "sha512": "sha512-cPtIuuH8TIjVHSi2ewwReWGW1PfChPE0LxPIDlfwVcLuTM9GANFTXiMB7k3aC4sk3f0cQU25LNKzx+jZMxijqw==",
- "path": "system.linq.async/5.0.0",
- "hashPath": "system.linq.async.5.0.0.nupkg.sha512"
- },
- "System.Reactive/5.0.0": {
- "type": "package",
- "serviceable": true,
- "sha512": "sha512-erBZjkQHWL9jpasCE/0qKAryzVBJFxGHVBAvgRN1bzM0q2s1S4oYREEEL0Vb+1kA/6BKb5FjUZMp5VXmy+gzkQ==",
- "path": "system.reactive/5.0.0",
- "hashPath": "system.reactive.5.0.0.nupkg.sha512"
- },
- "System.ValueTuple/4.5.0": {
- "type": "package",
- "serviceable": true,
- "sha512": "sha512-okurQJO6NRE/apDIP23ajJ0hpiNmJ+f0BwOlB/cSqTLQlw5upkf+5+96+iG2Jw40G1fCVCyPz/FhIABUjMR+RQ==",
- "path": "system.valuetuple/4.5.0",
- "hashPath": "system.valuetuple.4.5.0.nupkg.sha512"
- },
- "PluginManager/1.0.0": {
- "type": "project",
- "serviceable": false,
- "sha512": ""
- }
- }
-}
\ No newline at end of file
diff --git a/BUILDS/net6.0/EVE_LevelingSystem.dll b/BUILDS/net6.0/EVE_LevelingSystem.dll
deleted file mode 100644
index e443461..0000000
Binary files a/BUILDS/net6.0/EVE_LevelingSystem.dll and /dev/null differ
diff --git a/BUILDS/net6.0/MusicCommands.dll b/BUILDS/net6.0/MusicCommands.dll
index c9f7661..dac55eb 100644
Binary files a/BUILDS/net6.0/MusicCommands.dll and b/BUILDS/net6.0/MusicCommands.dll differ
diff --git a/BUILDS/net6.0/PluginManager.dll b/BUILDS/net6.0/PluginManager.dll
index 856115d..6be9c72 100644
Binary files a/BUILDS/net6.0/PluginManager.dll and b/BUILDS/net6.0/PluginManager.dll differ
diff --git a/BUILDS/net6.0/StartupEvents.deps.json b/BUILDS/net6.0/StartupEvents.deps.json
deleted file mode 100644
index 429d030..0000000
--- a/BUILDS/net6.0/StartupEvents.deps.json
+++ /dev/null
@@ -1,268 +0,0 @@
-{
- "runtimeTarget": {
- "name": ".NETCoreApp,Version=v6.0",
- "signature": ""
- },
- "compilationOptions": {},
- "targets": {
- ".NETCoreApp,Version=v6.0": {
- "StartupEvents/1.0.0": {
- "dependencies": {
- "PluginManager": "1.0.0"
- },
- "runtime": {
- "StartupEvents.dll": {}
- }
- },
- "Discord.Net/3.6.1": {
- "dependencies": {
- "Discord.Net.Commands": "3.6.1",
- "Discord.Net.Core": "3.6.1",
- "Discord.Net.Interactions": "3.6.1",
- "Discord.Net.Rest": "3.6.1",
- "Discord.Net.WebSocket": "3.6.1",
- "Discord.Net.Webhook": "3.6.1"
- }
- },
- "Discord.Net.Commands/3.6.1": {
- "dependencies": {
- "Discord.Net.Core": "3.6.1"
- },
- "runtime": {
- "lib/net6.0/Discord.Net.Commands.dll": {
- "assemblyVersion": "3.6.1.0",
- "fileVersion": "3.6.1.0"
- }
- }
- },
- "Discord.Net.Core/3.6.1": {
- "dependencies": {
- "Newtonsoft.Json": "13.0.1",
- "System.Collections.Immutable": "5.0.0",
- "System.Interactive.Async": "5.0.0",
- "System.ValueTuple": "4.5.0"
- },
- "runtime": {
- "lib/net6.0/Discord.Net.Core.dll": {
- "assemblyVersion": "3.6.1.0",
- "fileVersion": "3.6.1.0"
- }
- }
- },
- "Discord.Net.Interactions/3.6.1": {
- "dependencies": {
- "Discord.Net.Core": "3.6.1",
- "Discord.Net.Rest": "3.6.1",
- "Discord.Net.WebSocket": "3.6.1",
- "Microsoft.Extensions.DependencyInjection.Abstractions": "5.0.0",
- "System.Collections.Immutable": "5.0.0",
- "System.Reactive": "5.0.0"
- },
- "runtime": {
- "lib/net6.0/Discord.Net.Interactions.dll": {
- "assemblyVersion": "3.6.1.0",
- "fileVersion": "3.6.1.0"
- }
- }
- },
- "Discord.Net.Rest/3.6.1": {
- "dependencies": {
- "Discord.Net.Core": "3.6.1"
- },
- "runtime": {
- "lib/net6.0/Discord.Net.Rest.dll": {
- "assemblyVersion": "3.6.1.0",
- "fileVersion": "3.6.1.0"
- }
- }
- },
- "Discord.Net.Webhook/3.6.1": {
- "dependencies": {
- "Discord.Net.Core": "3.6.1",
- "Discord.Net.Rest": "3.6.1"
- },
- "runtime": {
- "lib/net6.0/Discord.Net.Webhook.dll": {
- "assemblyVersion": "3.6.1.0",
- "fileVersion": "3.6.1.0"
- }
- }
- },
- "Discord.Net.WebSocket/3.6.1": {
- "dependencies": {
- "Discord.Net.Core": "3.6.1",
- "Discord.Net.Rest": "3.6.1"
- },
- "runtime": {
- "lib/net6.0/Discord.Net.WebSocket.dll": {
- "assemblyVersion": "3.6.1.0",
- "fileVersion": "3.6.1.0"
- }
- }
- },
- "Microsoft.Extensions.DependencyInjection.Abstractions/5.0.0": {
- "runtime": {
- "lib/netstandard2.0/Microsoft.Extensions.DependencyInjection.Abstractions.dll": {
- "assemblyVersion": "5.0.0.0",
- "fileVersion": "5.0.20.51904"
- }
- }
- },
- "Newtonsoft.Json/13.0.1": {
- "runtime": {
- "lib/netstandard2.0/Newtonsoft.Json.dll": {
- "assemblyVersion": "13.0.0.0",
- "fileVersion": "13.0.1.25517"
- }
- }
- },
- "System.Collections.Immutable/5.0.0": {},
- "System.Interactive.Async/5.0.0": {
- "dependencies": {
- "System.Linq.Async": "5.0.0"
- },
- "runtime": {
- "lib/netcoreapp3.1/System.Interactive.Async.dll": {
- "assemblyVersion": "5.0.0.0",
- "fileVersion": "5.0.0.1"
- }
- }
- },
- "System.Linq.Async/5.0.0": {
- "runtime": {
- "lib/netcoreapp3.1/System.Linq.Async.dll": {
- "assemblyVersion": "5.0.0.0",
- "fileVersion": "5.0.0.1"
- }
- }
- },
- "System.Reactive/5.0.0": {
- "runtime": {
- "lib/net5.0/System.Reactive.dll": {
- "assemblyVersion": "5.0.0.0",
- "fileVersion": "5.0.0.1"
- }
- }
- },
- "System.ValueTuple/4.5.0": {},
- "PluginManager/1.0.0": {
- "dependencies": {
- "Discord.Net": "3.6.1"
- },
- "runtime": {
- "PluginManager.dll": {}
- }
- }
- }
- },
- "libraries": {
- "StartupEvents/1.0.0": {
- "type": "project",
- "serviceable": false,
- "sha512": ""
- },
- "Discord.Net/3.6.1": {
- "type": "package",
- "serviceable": true,
- "sha512": "sha512-TfcL/HG57fVt//WVJ2XyF2PlytY9IYkkwwkPLIhvu5FW4wf9rm7+N8RPh4qtELLfsa5ES0FK2RbgYjABRR9AjA==",
- "path": "discord.net/3.6.1",
- "hashPath": "discord.net.3.6.1.nupkg.sha512"
- },
- "Discord.Net.Commands/3.6.1": {
- "type": "package",
- "serviceable": true,
- "sha512": "sha512-kK7m571yzSzPd93o+n8Z+TfvX62BT1HtOEZIWXKwXWO8itP/sgqBNExjWK/6DOpkbD6+khc2f3rp+TA0rJD88g==",
- "path": "discord.net.commands/3.6.1",
- "hashPath": "discord.net.commands.3.6.1.nupkg.sha512"
- },
- "Discord.Net.Core/3.6.1": {
- "type": "package",
- "serviceable": true,
- "sha512": "sha512-ibVjQiWzgqh0GyP/GXE2kv3TA/9ysmmNFG/WmRE7GepQQAXXGxVUO9IMJ8h14EvIXMQ0m0DktMe5DkUnilo3Ag==",
- "path": "discord.net.core/3.6.1",
- "hashPath": "discord.net.core.3.6.1.nupkg.sha512"
- },
- "Discord.Net.Interactions/3.6.1": {
- "type": "package",
- "serviceable": true,
- "sha512": "sha512-WGOxz6SMUu4WS5b/JdrhlwQletcplBIYqvjFBBDfnqE+uNJqcNGtAdyjLqIILfXGx8aSSSSYZSCeAUa7FZ8Yew==",
- "path": "discord.net.interactions/3.6.1",
- "hashPath": "discord.net.interactions.3.6.1.nupkg.sha512"
- },
- "Discord.Net.Rest/3.6.1": {
- "type": "package",
- "serviceable": true,
- "sha512": "sha512-T7RRThIS23roFEJwTL1l7aawjVyn7ZB5yH3tMge0d6TiCzzp4V4FAZ+ArTt19LHRFhPly90v8V3sWqmTMN+5Zg==",
- "path": "discord.net.rest/3.6.1",
- "hashPath": "discord.net.rest.3.6.1.nupkg.sha512"
- },
- "Discord.Net.Webhook/3.6.1": {
- "type": "package",
- "serviceable": true,
- "sha512": "sha512-xikKHIGAIMz0BzHkaTKb48DNpFjKW8mvJjLJSezJ1xQOu+laHNk/hav4qxVtyZz7HSI/vGTkmlq9hKVhWzpaUA==",
- "path": "discord.net.webhook/3.6.1",
- "hashPath": "discord.net.webhook.3.6.1.nupkg.sha512"
- },
- "Discord.Net.WebSocket/3.6.1": {
- "type": "package",
- "serviceable": true,
- "sha512": "sha512-hF22Xy7URlVEDQZ69INOgzPvFUsIDfd+r6U+1yF9HWdBn3d4THnvAAhkv1TraSx/T/MKS7g+jvk/HZ3mh5S3aw==",
- "path": "discord.net.websocket/3.6.1",
- "hashPath": "discord.net.websocket.3.6.1.nupkg.sha512"
- },
- "Microsoft.Extensions.DependencyInjection.Abstractions/5.0.0": {
- "type": "package",
- "serviceable": true,
- "sha512": "sha512-ORj7Zh81gC69TyvmcUm9tSzytcy8AVousi+IVRAI8nLieQjOFryRusSFh7+aLk16FN9pQNqJAiMd7BTKINK0kA==",
- "path": "microsoft.extensions.dependencyinjection.abstractions/5.0.0",
- "hashPath": "microsoft.extensions.dependencyinjection.abstractions.5.0.0.nupkg.sha512"
- },
- "Newtonsoft.Json/13.0.1": {
- "type": "package",
- "serviceable": true,
- "sha512": "sha512-ppPFpBcvxdsfUonNcvITKqLl3bqxWbDCZIzDWHzjpdAHRFfZe0Dw9HmA0+za13IdyrgJwpkDTDA9fHaxOrt20A==",
- "path": "newtonsoft.json/13.0.1",
- "hashPath": "newtonsoft.json.13.0.1.nupkg.sha512"
- },
- "System.Collections.Immutable/5.0.0": {
- "type": "package",
- "serviceable": true,
- "sha512": "sha512-FXkLXiK0sVVewcso0imKQoOxjoPAj42R8HtjjbSjVPAzwDfzoyoznWxgA3c38LDbN9SJux1xXoXYAhz98j7r2g==",
- "path": "system.collections.immutable/5.0.0",
- "hashPath": "system.collections.immutable.5.0.0.nupkg.sha512"
- },
- "System.Interactive.Async/5.0.0": {
- "type": "package",
- "serviceable": true,
- "sha512": "sha512-QaqhQVDiULcu4vm6o89+iP329HcK44cETHOYgy/jfEjtzeFy0ZxmuM7nel9ocjnKxEM4yh1mli7hgh8Q9o+/Iw==",
- "path": "system.interactive.async/5.0.0",
- "hashPath": "system.interactive.async.5.0.0.nupkg.sha512"
- },
- "System.Linq.Async/5.0.0": {
- "type": "package",
- "serviceable": true,
- "sha512": "sha512-cPtIuuH8TIjVHSi2ewwReWGW1PfChPE0LxPIDlfwVcLuTM9GANFTXiMB7k3aC4sk3f0cQU25LNKzx+jZMxijqw==",
- "path": "system.linq.async/5.0.0",
- "hashPath": "system.linq.async.5.0.0.nupkg.sha512"
- },
- "System.Reactive/5.0.0": {
- "type": "package",
- "serviceable": true,
- "sha512": "sha512-erBZjkQHWL9jpasCE/0qKAryzVBJFxGHVBAvgRN1bzM0q2s1S4oYREEEL0Vb+1kA/6BKb5FjUZMp5VXmy+gzkQ==",
- "path": "system.reactive/5.0.0",
- "hashPath": "system.reactive.5.0.0.nupkg.sha512"
- },
- "System.ValueTuple/4.5.0": {
- "type": "package",
- "serviceable": true,
- "sha512": "sha512-okurQJO6NRE/apDIP23ajJ0hpiNmJ+f0BwOlB/cSqTLQlw5upkf+5+96+iG2Jw40G1fCVCyPz/FhIABUjMR+RQ==",
- "path": "system.valuetuple/4.5.0",
- "hashPath": "system.valuetuple.4.5.0.nupkg.sha512"
- },
- "PluginManager/1.0.0": {
- "type": "project",
- "serviceable": false,
- "sha512": ""
- }
- }
-}
\ No newline at end of file
diff --git a/BUILDS/net6.0/StartupEvents.dll b/BUILDS/net6.0/StartupEvents.dll
deleted file mode 100644
index c289609..0000000
Binary files a/BUILDS/net6.0/StartupEvents.dll and /dev/null differ
diff --git a/CMD_LevelingSystem/CMD_LevelingSystem.csproj b/CMD_LevelingSystem/CMD_LevelingSystem.csproj
index 61313a8..5058233 100644
--- a/CMD_LevelingSystem/CMD_LevelingSystem.csproj
+++ b/CMD_LevelingSystem/CMD_LevelingSystem.csproj
@@ -2,16 +2,9 @@
net6.0
-
-
-
- ..\BUILDS\
- DEBUG;TRACE
- prompt
- none
- false
- false
-
+ enable
+ enable
+ ..\DiscordBot\bin\Debug\net6.0\Data\Plugins\Commands\LevelingSystem
diff --git a/CMD_LevelingSystem/Commands/level.cs b/CMD_LevelingSystem/Commands/level.cs
deleted file mode 100644
index d709e67..0000000
--- a/CMD_LevelingSystem/Commands/level.cs
+++ /dev/null
@@ -1,61 +0,0 @@
-using Discord;
-using Discord.Commands;
-using Discord.WebSocket;
-
-using PluginManager.Interfaces;
-using PluginManager.LanguageSystem;
-
-using System;
-
-
-public class level : DBCommand
-{
- public string Command => "rank";
-
- public string Description => "Display your current level";
-
- public string Usage => "rank";
-
- public bool canUseDM => false;
-
- public bool canUseServer => true;
-
- public bool requireAdmin => false;
-
- public async void Execute(SocketCommandContext context, SocketMessage message, DiscordSocketClient client, bool isDM)
- {
-
- try
- {
- int cLv = Data.GetLevel(message.Author.Id);
- Int64 cEXP = Data.GetExp(message.Author.Id);
- Int64 rEXP = Data.GetReqEXP(message.Author.Id);
-
- var embed = new EmbedBuilder()
- {
- Title = "Leveling System",
- Description = message.Author.Mention
- };
- Random r = new Random();
- int _r = r.Next(0, 256);
- int _g = r.Next(0, 256);
- int _b = r.Next(0, 256);
- embed.WithColor(new Color(_r, _g, _b));
- embed.AddField("Level", cLv);
- embed.AddField("Current EXP", cEXP);
- embed.AddField("Required Exp to Level up", rEXP);
- embed.WithCurrentTimestamp();
- await message.Channel.SendMessageAsync(embed: embed.Build());
- }
- catch
- {
- if (Language.ActiveLanguage != null)
- await message.Channel.SendMessageAsync(Language.ActiveLanguage.LanguageWords["DB_COMMAND_RANK_NO_RANK"]);
- else await message.Channel.SendMessageAsync("You are unranked now. Please type a message in chat that is not a command and try again this command");
- return;
- }
-
-
- }
-}
-
diff --git a/CMD_LevelingSystem/Items/Leveling System/Core.cs b/CMD_LevelingSystem/Items/Leveling System/Core.cs
deleted file mode 100644
index 10314f4..0000000
--- a/CMD_LevelingSystem/Items/Leveling System/Core.cs
+++ /dev/null
@@ -1,62 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.IO;
-using System.Threading.Tasks;
-
-public class Core
-{
-
- public static Dictionary playerMessages = new Dictionary();
-
- private static readonly string folder = @".\Data\Resources\LevelingSystem\";
-
- public static int GetLevel(ulong id) => int.Parse(File.ReadAllText(Path.Combine(folder, id.ToString() + ".data")).Split(',')[0].Split('=')[1]);
-
-
- public static Int64 GetExp(ulong id) => Int64.Parse(File.ReadAllText(Path.Combine(folder, id.ToString() + ".data")).Split(',')[1].Split('=')[1]);
-
-
- public static Int64 GetReqEXP(ulong id) => Int64.Parse(File.ReadAllText(Path.Combine(folder, id.ToString() + ".data")).Split(',')[2].Split('=')[1]);
- public static void SaveData(ulong id, int lv, Int64 cexp, Int64 rexp)
- {
- Directory.CreateDirectory(folder);
- File.WriteAllText(Path.Combine(folder, id.ToString() + ".data"), $"Level={lv},EXP={cexp},REXP={rexp}");
- }
- private static Int64 NextLevelXP(int level)
- {
- return (level * level) + 2 * level + 75;
- }
-
- public static (bool, int) MessageSent(ulong id, int messageLength)
- {
- WaitForTimeToRemoveFromList(id, 60);
-
- if (!File.Exists(Path.Combine(folder, id.ToString() + ".data")))
- {
- SaveData(id, 0, 0, 0);
- }
- Int64 cEXp = GetExp(id);
- Int64 rExp = GetReqEXP(id);
- int random = new System.Random().Next(3, 6) + messageLength;
- cEXp += random;
- if (cEXp >= rExp)
- {
- cEXp = cEXp - rExp;
- int lv = GetLevel(id);
- rExp = NextLevelXP(lv);
- lv++;
- SaveData(id, lv, cEXp, rExp);
- return (true, lv);
- }
-
- SaveData(id, GetLevel(id), cEXp, rExp);
- return (false, -1);
- }
-
- public static async void WaitForTimeToRemoveFromList(ulong id, int time_seconds)
- {
- await Task.Delay(time_seconds * 1000);
- playerMessages.Remove(id);
- }
-
-}
\ No newline at end of file
diff --git a/CMD_LevelingSystem/Items/Leveling System/Data.cs b/CMD_LevelingSystem/Items/Leveling System/Data.cs
deleted file mode 100644
index 44ffb76..0000000
--- a/CMD_LevelingSystem/Items/Leveling System/Data.cs
+++ /dev/null
@@ -1,24 +0,0 @@
-using Discord.WebSocket;
-
-using System;
-using System.IO;
-public static class Data
-{
- private static readonly string folder = @".\Data\Resources\LevelingSystem\";
- public static void registerPlayer(SocketGuildUser user)
- {
- ulong id = user.Id;
- Directory.CreateDirectory(folder);
- File.WriteAllText(Path.Combine(folder, id.ToString() + ".data"), "Level=0,EXP=0,REXP=100");
- }
-
- public static int GetLevel(ulong id) => int.Parse(File.ReadAllText(Path.Combine(folder, id.ToString() + ".data")).Split(',')[0].Split('=')[1]);
-
-
- public static Int64 GetExp(ulong id) => Int64.Parse(File.ReadAllText(Path.Combine(folder, id.ToString() + ".data")).Split(',')[1].Split('=')[1]);
-
-
- public static Int64 GetReqEXP(ulong id) => Int64.Parse(File.ReadAllText(Path.Combine(folder, id.ToString() + ".data")).Split(',')[2].Split('=')[1]);
-
-
-}
diff --git a/CMD_LevelingSystem/Level.cs b/CMD_LevelingSystem/Level.cs
new file mode 100644
index 0000000..e11fd3f
--- /dev/null
+++ b/CMD_LevelingSystem/Level.cs
@@ -0,0 +1,48 @@
+using Discord;
+using Discord.Commands;
+using Discord.WebSocket;
+using PluginManager;
+using PluginManager.Interfaces;
+using PluginManager.Others;
+
+namespace CMD_LevelingSystem;
+
+internal class Level : DBCommand
+{
+ public string Command => "level";
+
+ public string Description => "Display tour current level";
+
+ public string Usage => "level";
+
+ public bool canUseDM => false;
+
+ public bool canUseServer => true;
+
+ public bool requireAdmin => false;
+
+ public async void Execute(SocketCommandContext context, SocketMessage message, DiscordSocketClient client, bool isDM)
+ {
+ if (!File.Exists(Config.GetValue("LevelingSystemPath") + $"/{message.Author.Id}.dat"))
+ {
+ await context.Channel.SendMessageAsync("You are now unranked !");
+ return;
+ }
+
+ var user = await Functions.ConvertFromJson(Config.GetValue("LevelingSystemPath") + $"/{message.Author.Id}.dat");
+ if (user == null)
+ {
+ await context.Channel.SendMessageAsync("You are now unranked !");
+ return;
+ }
+
+ var builder = new EmbedBuilder();
+ var r = new Random();
+ builder.WithColor(r.Next(256), r.Next(256), r.Next(256));
+ builder.AddField("Current Level", user.CurrentLevel, true)
+ .AddField("Current EXP", user.CurrentEXP, true)
+ .AddField("Required Exp", user.RequiredEXPToLevelUp, true);
+ builder.WithTimestamp(DateTimeOffset.Now);
+ await context.Channel.SendMessageAsync(embed: builder.Build());
+ }
+}
diff --git a/CMD_LevelingSystem/User.cs b/CMD_LevelingSystem/User.cs
new file mode 100644
index 0000000..bf26b87
--- /dev/null
+++ b/CMD_LevelingSystem/User.cs
@@ -0,0 +1,18 @@
+using Discord.WebSocket;
+
+namespace CMD_LevelingSystem;
+
+public class DiscordUser
+{
+ public string Username { get; set; }
+ public ushort DiscordTag { get; set; }
+ public ulong userID { get; set; }
+}
+
+public class User
+{
+ public DiscordUser user { get; set; }
+ public int CurrentLevel { get; set; }
+ public long CurrentEXP { get; set; }
+ public long RequiredEXPToLevelUp { get; set; }
+}
diff --git a/CMD_Utils/Echo.cs b/CMD_Utils/Echo.cs
index fdf7fe1..83ec899 100644
--- a/CMD_Utils/Echo.cs
+++ b/CMD_Utils/Echo.cs
@@ -1,6 +1,5 @@
using Discord.Commands;
using Discord.WebSocket;
-
using PluginManager.Interfaces;
internal class Echo : DBCommand
@@ -11,14 +10,14 @@ internal class Echo : DBCommand
public string Usage => "echo [message]";
- public bool canUseDM => true;
+ public bool canUseDM => true;
public bool canUseServer => true;
public bool requireAdmin => false;
public async void Execute(SocketCommandContext context, SocketMessage message, DiscordSocketClient client, bool isDM)
{
- string m = message.Content.Substring(6);
+ var m = message.Content.Substring(6);
await message.Channel.SendMessageAsync(m);
}
}
diff --git a/CMD_Utils/FlipCoin.cs b/CMD_Utils/FlipCoin.cs
index e84f83b..0057f33 100644
--- a/CMD_Utils/FlipCoin.cs
+++ b/CMD_Utils/FlipCoin.cs
@@ -1,37 +1,30 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-using System.Threading.Tasks;
-
-using Discord.Commands;
+using Discord.Commands;
using Discord.WebSocket;
-
using PluginManager.Interfaces;
-namespace CMD_Utils
+namespace CMD_Utils;
+
+internal class FlipCoin : DBCommand
{
- class FlipCoin : DBCommand
+ public string Command => "flip";
+
+ public string Description => "Flip a coin";
+
+ public string Usage => "flip";
+
+ public bool canUseDM => true;
+
+ public bool canUseServer => true;
+
+ public bool requireAdmin => false;
+
+ public async void Execute(SocketCommandContext context, SocketMessage message, DiscordSocketClient client, bool isDM)
{
- public string Command => "flip";
-
- public string Description => "Flip a coin";
-
- public string Usage => "flip";
-
- public bool canUseDM => true;
-
- public bool canUseServer => true;
-
- public bool requireAdmin => false;
-
- public async void Execute(SocketCommandContext context, SocketMessage message, DiscordSocketClient client, bool isDM)
- {
- System.Random random = new System.Random();
- int r = random.Next(1, 3);
- if (r == 1)
- await message.Channel.SendMessageAsync("Heads");
- else await message.Channel.SendMessageAsync("Tails");
- }
+ var random = new System.Random();
+ var r = random.Next(1, 3);
+ if (r == 1)
+ await message.Channel.SendMessageAsync("Heads");
+ else
+ await message.Channel.SendMessageAsync("Tails");
}
}
diff --git a/CMD_Utils/Poll.cs b/CMD_Utils/Poll.cs
index bf81df5..c3624c6 100644
--- a/CMD_Utils/Poll.cs
+++ b/CMD_Utils/Poll.cs
@@ -1,53 +1,45 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-using System.Threading.Tasks;
-
+using System.Collections.Generic;
using Discord;
using Discord.Commands;
using Discord.WebSocket;
-
using PluginManager.Interfaces;
+using PluginManager.Others;
-namespace CMD_Utils
+namespace CMD_Utils;
+
+public class Poll : DBCommand
{
- public class Poll : DBCommand
+ public string Command => "poll";
+
+ public string Description => "Create a poll with options";
+
+ public string Usage => "poll [This-is-question] [This-is-answer-1] [This-is-answer-2] ... ";
+
+ public bool canUseDM => false;
+
+ public bool canUseServer => true;
+
+ public bool requireAdmin => true;
+
+ public async void Execute(SocketCommandContext context, SocketMessage message, DiscordSocketClient client, bool isDM)
{
- public string Command => "poll";
+ if (isDM) return;
+ var question = message.Content.Split(' ')[1].Replace('-', ' ');
+ var answers = Functions.MergeStrings(message.Content.Split(' '), 2).Split(' ');
+ var embedBuilder = new EmbedBuilder();
+ embedBuilder.Title = question;
+ var len = answers.Length;
+ for (var i = 0; i < len; i++) embedBuilder.AddField($"Answer {i + 1}", answers[i].Replace('-', ' '), true);
+ var msg = await context.Channel.SendMessageAsync(embed: embedBuilder.Build());
- public string Description => "Create a poll with options";
+ var emotes = new List();
+ emotes.Add(Emoji.Parse(":one:"));
+ emotes.Add(Emoji.Parse(":two:"));
+ emotes.Add(Emoji.Parse(":three:"));
+ emotes.Add(Emoji.Parse(":four:"));
+ emotes.Add(Emoji.Parse(":five:"));
+ emotes.Add(Emoji.Parse(":six:"));
- public string Usage => "poll [This-is-question] [This-is-answer-1] [This-is-answer-2] ... ";
-
- public bool canUseDM => false;
-
- public bool canUseServer => true;
-
- public bool requireAdmin => true;
-
- public async void Execute(SocketCommandContext context, SocketMessage message, DiscordSocketClient client, bool isDM)
- {
- if (isDM) return;
- string question = message.Content.Split(' ')[1].Replace('-', ' ');
- string[] answers = PluginManager.Others.Functions.MergeStrings(message.Content.Split(' '), 2).Split(' ');
- EmbedBuilder embedBuilder = new EmbedBuilder();
- embedBuilder.Title = question;
- int len = answers.Length;
- for (int i = 0; i < len; i++)
- embedBuilder.AddField($"Answer {i + 1}", answers[i].Replace('-', ' '), true);
- var msg = await context.Channel.SendMessageAsync(embed: embedBuilder.Build());
-
- List emotes = new List();
- emotes.Add(Emoji.Parse(":one:"));
- emotes.Add(Emoji.Parse(":two:"));
- emotes.Add(Emoji.Parse(":three:"));
- emotes.Add(Emoji.Parse(":four:"));
- emotes.Add(Emoji.Parse(":five:"));
- emotes.Add(Emoji.Parse(":six:"));
-
- for (int i = 0; i < len; i++)
- await msg.AddReactionAsync(emotes[i]);
- }
+ for (var i = 0; i < len; i++) await msg.AddReactionAsync(emotes[i]);
}
}
diff --git a/CMD_Utils/Random.cs b/CMD_Utils/Random.cs
index 4075588..2cbc564 100644
--- a/CMD_Utils/Random.cs
+++ b/CMD_Utils/Random.cs
@@ -1,6 +1,5 @@
using Discord.Commands;
using Discord.WebSocket;
-
using PluginManager.Interfaces;
public class Random : DBCommand
@@ -11,7 +10,7 @@ public class Random : DBCommand
public string Usage => "random [number1] [number2]";
- public bool canUseDM => true;
+ public bool canUseDM => true;
public bool canUseServer => true;
public bool requireAdmin => false;
@@ -19,19 +18,18 @@ public class Random : DBCommand
{
try
{
- string msg = message.Content;
- int a = int.Parse(msg.Split(' ')[1]);
- int b = int.Parse(msg.Split(' ')[2]);
+ var msg = message.Content;
+ var a = int.Parse(msg.Split(' ')[1]);
+ var b = int.Parse(msg.Split(' ')[2]);
if (a > b)
{
- int x = a;
+ var x = a;
a = b;
b = x;
}
await message.Channel.SendMessageAsync("Your random generated number is " + new System.Random().Next(a, b));
-
}
catch
{
diff --git a/DiscordBot/App.config b/DiscordBot/App.config
index 2a5ff10..d78bbbb 100644
--- a/DiscordBot/App.config
+++ b/DiscordBot/App.config
@@ -1,4 +1,4 @@
-
-
+
+
\ No newline at end of file
diff --git a/DiscordBot/Discord/Commands/Help.cs b/DiscordBot/Discord/Commands/Help.cs
index 67840a5..11fb0f9 100644
--- a/DiscordBot/Discord/Commands/Help.cs
+++ b/DiscordBot/Discord/Commands/Help.cs
@@ -1,107 +1,100 @@
using Discord;
using Discord.Commands;
using Discord.WebSocket;
-
-using PluginManager.Loaders;
using PluginManager.Interfaces;
-using PluginManager.Others.Permissions;
+using PluginManager.Loaders;
using PluginManager.Others;
-using System.Collections.Generic;
+namespace DiscordBot.Discord.Commands;
-namespace DiscordBot.Discord.Commands
+///
+/// The help command
+///
+internal class Help : DBCommand
{
///
- /// The help command
+ /// Command name
///
- internal class Help : DBCommand
+ public string Command => "help";
+
+ ///
+ /// Command Description
+ ///
+ public string Description => "This command allows you to check all loadded commands";
+
+ ///
+ /// Command usage
+ ///
+ public string Usage => "help";
+
+ ///
+ /// Check if the command can be used />
+ ///
+ public bool canUseDM => true;
+
+ ///
+ /// Check if the command can be used in a server
+ ///
+ public bool canUseServer => true;
+
+ ///
+ /// Check if the command require administrator to be executed
+ ///
+ public bool requireAdmin => false;
+
+ ///
+ /// The main body of the command
+ ///
+ /// The command context
+ /// The command message
+ /// The discord bot client
+ /// True if the message was sent from a DM channel, false otherwise
+ public void Execute(SocketCommandContext context, SocketMessage message, DiscordSocketClient client, bool isDM)
{
- ///
- /// Command name
- ///
- public string Command => "help";
-
- ///
- /// Command Description
- ///
- public string Description => "This command allows you to check all loadded commands";
-
- ///
- /// Command usage
- ///
- public string Usage => "help";
-
- ///
- /// Check if the command can be used />
- ///
- public bool canUseDM => true;
-
- ///
- /// Check if the command can be used in a server
- ///
- public bool canUseServer => true;
-
- ///
- /// Check if the command require administrator to be executed
- ///
- public bool requireAdmin => false;
-
- ///
- /// The main body of the command
- ///
- /// The command context
- /// The command message
- /// The discord bot client
- /// True if the message was sent from a DM channel, false otherwise
- public void Execute(SocketCommandContext context, SocketMessage message, DiscordSocketClient client, bool isDM)
+ var args = Functions.GetArguments(message);
+ if (args.Count != 0)
{
- List args = Functions.GetArguments(message);
- if (args.Count != 0)
+ foreach (var item in args)
{
-
- foreach (var item in args)
- {
- var e = GenerateHelpCommand(item);
- if (e != null)
- context.Channel.SendMessageAsync(embed: e.Build());
- else
- context.Channel.SendMessageAsync("Unknown Command " + item);
- }
- return;
- }
- EmbedBuilder embedBuilder = new EmbedBuilder();
-
- string adminCommands = "";
- string normalCommands = "";
- string DMCommands = "";
-
- foreach (var cmd in PluginLoader.Plugins!)
- {
- if (cmd.canUseDM)
- DMCommands += cmd.Command + " ";
- if (cmd.requireAdmin)
- adminCommands += cmd.Command + " ";
- else if (cmd.canUseServer) normalCommands += cmd.Command + " ";
+ var e = GenerateHelpCommand(item);
+ if (e != null)
+ context.Channel.SendMessageAsync(embed: e.Build());
+ else
+ context.Channel.SendMessageAsync("Unknown Command " + item);
}
- embedBuilder.AddField("Admin Commands", adminCommands);
- embedBuilder.AddField("Normal Commands", normalCommands);
- embedBuilder.AddField("DM Commands", DMCommands);
- context.Channel.SendMessageAsync(embed: embedBuilder.Build());
-
+ return;
}
- private EmbedBuilder GenerateHelpCommand(string command)
+ var embedBuilder = new EmbedBuilder();
+
+ var adminCommands = "";
+ var normalCommands = "";
+ var DMCommands = "";
+
+ foreach (var cmd in PluginLoader.Commands!)
{
- EmbedBuilder embedBuilder = new EmbedBuilder();
- DBCommand cmd = PluginLoader.Plugins.Find(p => p.Command == command);
- if (cmd == null)
- return null;
-
- embedBuilder.AddField("Usage", cmd.Usage);
- embedBuilder.AddField("Description", cmd.Description);
-
- return embedBuilder;
+ if (cmd.canUseDM) DMCommands += cmd.Command + " ";
+ if (cmd.requireAdmin)
+ adminCommands += cmd.Command + " ";
+ else if (cmd.canUseServer) normalCommands += cmd.Command + " ";
}
+
+ embedBuilder.AddField("Admin Commands", adminCommands);
+ embedBuilder.AddField("Normal Commands", normalCommands);
+ embedBuilder.AddField("DM Commands", DMCommands);
+ context.Channel.SendMessageAsync(embed: embedBuilder.Build());
}
-}
\ No newline at end of file
+
+ private EmbedBuilder GenerateHelpCommand(string command)
+ {
+ var embedBuilder = new EmbedBuilder();
+ var cmd = PluginLoader.Commands.Find(p => p.Command == command);
+ if (cmd == null) return null;
+
+ embedBuilder.AddField("Usage", cmd.Usage);
+ embedBuilder.AddField("Description", cmd.Description);
+
+ return embedBuilder;
+ }
+}
diff --git a/DiscordBot/Discord/Commands/Restart.cs b/DiscordBot/Discord/Commands/Restart.cs
index 3808118..a567783 100644
--- a/DiscordBot/Discord/Commands/Restart.cs
+++ b/DiscordBot/Discord/Commands/Restart.cs
@@ -1,114 +1,113 @@
using System;
using System.Diagnostics;
-
using Discord.WebSocket;
+using PluginManager.Interfaces;
+using PluginManager.Others;
+using PluginManager.Others.Permissions;
using DiscordLibCommands = Discord.Commands;
using DiscordLib = Discord;
+using OperatingSystem = PluginManager.Others.OperatingSystem;
-using PluginManager.Interfaces;
-using PluginManager.Others.Permissions;
-using PluginManager.Others;
+namespace DiscordBot.Discord.Commands;
-namespace DiscordBot.Discord.Commands
+internal class Restart : DBCommand
{
- internal class Restart : DBCommand
+ ///
+ /// Command name
+ ///
+ public string Command => "restart";
+
+ ///
+ /// Command Description
+ ///
+ public string Description => "Restart the bot";
+
+ ///
+ /// Command usage
+ ///
+ public string Usage => "restart [-p | -c | -args | -cmd] ";
+
+ ///
+ /// Check if the command can be used />
+ ///
+ public bool canUseDM => false;
+
+ ///
+ /// Check if the command can be used in a server
+ ///
+ public bool canUseServer => true;
+
+ ///
+ /// Check if the command require administrator to be executed
+ ///
+ public bool requireAdmin => false;
+
+ ///
+ /// The main body of the command
+ ///
+ /// The command context
+ /// The command message
+ /// The discord bot client
+ /// True if the message was sent from a DM channel, false otherwise
+ public async void Execute(DiscordLibCommands.SocketCommandContext context, SocketMessage message, DiscordSocketClient client, bool isDM)
{
- ///
- /// Command name
- ///
- public string Command => "restart";
-
- ///
- /// Command Description
- ///
- public string Description => "Restart the bot";
-
- ///
- /// Command usage
- ///
- public string Usage => "restart [-p | -c | -args | -cmd] ";
-
- ///
- /// Check if the command can be used />
- ///
- public bool canUseDM => false;
-
- ///
- /// Check if the command can be used in a server
- ///
- public bool canUseServer => true;
-
- ///
- /// Check if the command require administrator to be executed
- ///
- public bool requireAdmin => false;
- ///
- /// The main body of the command
- ///
- /// The command context
- /// The command message
- /// The discord bot client
- /// True if the message was sent from a DM channel, false otherwise
- public async void Execute(DiscordLibCommands.SocketCommandContext context, SocketMessage message, DiscordSocketClient client, bool isDM)
+ if (!(message.Author as SocketGuildUser).hasPermission(DiscordLib.GuildPermission.Administrator)) return;
+ var args = Functions.GetArguments(message);
+ var OS = Functions.GetOperatingSystem();
+ if (args.Count == 0)
{
- if (!DiscordPermissions.hasPermission(message.Author as SocketGuildUser, DiscordLib.GuildPermission.Administrator)) return;
- var args = Functions.GetArguments(message);
- var OS = Functions.GetOperatingSystem();
- if (args.Count == 0)
+ switch (OS)
{
+ case OperatingSystem.WINDOWS:
+ Process.Start("./DiscordBot.exe");
+ break;
+ case OperatingSystem.LINUX:
+ case OperatingSystem.MAC_OS:
+ Process.Start("./DiscordBot");
+ break;
+ default:
+ return;
+ }
+
+ return;
+ }
+
+ switch (args[0])
+ {
+ case "-p":
+ case "-poweroff":
+ case "-c":
+ case "-close":
+ Environment.Exit(0);
+ break;
+ case "-cmd":
+ case "-args":
+ var cmd = "--args";
+
+ if (args.Count > 1)
+ for (var i = 1; i < args.Count; i++)
+ cmd += $" {args[i]}";
+
+
switch (OS)
{
- case PluginManager.Others.OperatingSystem.WINDOWS:
- Process.Start("./DiscordBot.exe");
+ case OperatingSystem.WINDOWS:
+ Functions.WriteLogFile("Restarting the bot with the following arguments: \"" + cmd + "\"");
+ Process.Start("./DiscordBot.exe", cmd);
break;
- case PluginManager.Others.OperatingSystem.LINUX:
- case PluginManager.Others.OperatingSystem.MAC_OS:
- Process.Start("./DiscordBot");
+ case OperatingSystem.LINUX:
+ //case PluginManager.Others.OperatingSystem.MAC_OS: ?? - not tested
+ Process.Start("./DiscordBot", cmd);
break;
default:
return;
}
- return;
- }
- switch (args[0])
- {
- case "-p":
- case "-poweroff":
- case "-c":
- case "-close":
- Environment.Exit(0);
- break;
- case "-cmd":
- case "-args":
- string cmd = "--args";
-
- if (args.Count > 1)
- for (int i = 1; i < args.Count; i++)
- cmd += $" {args[i]}";
-
-
- switch (OS)
- {
- case PluginManager.Others.OperatingSystem.WINDOWS:
- Functions.WriteLogFile("Restarting the bot with the following arguments: \"" + cmd + "\"");
- Process.Start("./DiscordBot.exe", cmd);
- break;
- case PluginManager.Others.OperatingSystem.LINUX:
- //case PluginManager.Others.OperatingSystem.MAC_OS: ?? - not tested
- Process.Start("./DiscordBot", cmd);
- break;
- default:
- return;
- }
- Environment.Exit(0);
- break;
- default:
- await context.Channel.SendMessageAsync("Invalid argument. Use `help restart` to see the usage.");
- break;
-
-
- }
+ Environment.Exit(0);
+ break;
+ default:
+ await context.Channel.SendMessageAsync("Invalid argument. Use `help restart` to see the usage.");
+ break;
}
}
}
diff --git a/DiscordBot/Discord/Commands/Settings.cs b/DiscordBot/Discord/Commands/Settings.cs
index 4b867f3..044a2fd 100644
--- a/DiscordBot/Discord/Commands/Settings.cs
+++ b/DiscordBot/Discord/Commands/Settings.cs
@@ -1,106 +1,97 @@
using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-using System.Threading.Tasks;
-
using Discord;
using Discord.Commands;
using Discord.WebSocket;
-
-using PluginManager.Core;
+using PluginManager;
using PluginManager.Interfaces;
-using PluginManager.Others;
-using PluginManager.Others.Permissions;
-namespace DiscordBot.Discord.Commands
+namespace DiscordBot.Discord.Commands;
+
+internal class Settings : DBCommand
{
- class Settings : DBCommand
+ ///
+ /// Command name
+ ///
+ public string Command => "set";
+
+ ///
+ /// Command Description
+ ///
+ public string Description => "This command allows you change all settings. Use \"set help\" to show details";
+
+ ///
+ /// Command usage
+ ///
+ public string Usage => "set [keyword] [new Value]";
+
+ ///
+ /// Check if the command can be used />
+ ///
+ public bool canUseDM => true;
+
+ ///
+ /// Check if the command can be used in a server
+ ///
+ public bool canUseServer => true;
+
+ ///
+ /// Check if the command require administrator to be executed
+ ///
+ public bool requireAdmin => true;
+
+ ///
+ /// The main body of the command
+ ///
+ /// The command context
+ /// The command message
+ /// The discord bot client
+ /// True if the message was sent from a DM channel, false otherwise
+ public async void Execute(SocketCommandContext context, SocketMessage message, DiscordSocketClient client, bool isDM)
{
-
- ///
- /// Command name
- ///
- public string Command => "set";
-
- ///
- /// Command Description
- ///
- public string Description => "This command allows you change all settings. Use \"set help\" to show details";
-
- ///
- /// Command usage
- ///
- public string Usage => "set [keyword] [new Value]";
-
- ///
- /// Check if the command can be used />
- ///
- public bool canUseDM => true;
-
- ///
- /// Check if the command can be used in a server
- ///
- public bool canUseServer => true;
-
- ///
- /// Check if the command require administrator to be executed
- ///
- public bool requireAdmin => true;
-
- ///
- /// The main body of the command
- ///
- /// The command context
- /// The command message
- /// The discord bot client
- /// True if the message was sent from a DM channel, false otherwise
- public async void Execute(SocketCommandContext context, SocketMessage message, DiscordSocketClient client, bool isDM)
+ var channel = message.Channel;
+ try
{
- var channel = message.Channel;
- try
+ var content = message.Content;
+ var data = content.Split(' ');
+ var keyword = data[1];
+ if (keyword.ToLower() == "help")
{
+ await channel.SendMessageAsync("set token [new value] -- set the value of the new token (require restart)");
+ await channel.SendMessageAsync("set prefix [new value] -- set the value of the new preifx (require restart)");
- string content = message.Content;
- string[] data = content.Split(' ');
- string keyword = data[1];
- if (keyword.ToLower() == "help")
- {
- await channel.SendMessageAsync("set token [new value] -- set the value of the new token (require restart)");
- await channel.SendMessageAsync("set prefix [new value] -- set the value of the new preifx (require restart)");
+ return;
+ }
- return;
- }
-
- switch (keyword.ToLower())
- {
- case "token":
- if (data.Length != 3)
- {
- await channel.SendMessageAsync("Invalid token !");
- return;
- }
- Functions.WriteToSettings("./Data/Resources/DiscordBotCore.data", "BOT_TOKEN", data[2], '\t');
- break;
- case "prefix":
- if (data.Length != 3)
- {
- await channel.SendMessageAsync("Invalid token !");
- return;
- }
- Functions.WriteToSettings("./Data/Resources/DiscordBotCore.data", "BOT_PREFIX", data[2], '\t');
- break;
- default:
+ switch (keyword.ToLower())
+ {
+ case "token":
+ if (data.Length != 3)
+ {
+ await channel.SendMessageAsync("Invalid token !");
return;
- }
+ }
- await channel.SendMessageAsync("Restart required ...");
- }
- catch
- {
- await channel.SendMessageAsync("Unknown usage to this command !\nUsage: " + Usage);
+ Config.SetValue("token", data[2]);
+ break;
+ case "prefix":
+ if (data.Length != 3)
+ {
+ await channel.SendMessageAsync("Invalid token !");
+ return;
+ }
+
+ Config.SetValue("token", data[2]);
+ break;
+ default:
+ return;
}
+ await channel.SendMessageAsync("Restart required ...");
+ }
+ catch (Exception ex)
+ {
+ Console.WriteLine(ex.Message);
+ await channel.SendMessageAsync("Unknown usage to this command !\nUsage: " + Usage);
}
}
}
diff --git a/DiscordBot/Discord/Core/Boot.cs b/DiscordBot/Discord/Core/Boot.cs
index af12058..ce2ad4c 100644
--- a/DiscordBot/Discord/Core/Boot.cs
+++ b/DiscordBot/Discord/Core/Boot.cs
@@ -1,150 +1,149 @@
-using Discord;
+using System;
+using System.Threading;
+using System.Threading.Tasks;
+using Discord;
using Discord.Commands;
using Discord.WebSocket;
-
-using System;
-using System.Threading.Tasks;
-
+using PluginManager;
using static PluginManager.Others.Functions;
-namespace PluginManager.Core
+namespace DiscordBot.Discord.Core;
+
+internal class Boot
{
- internal class Boot
+ ///
+ /// The bot prefix
+ ///
+ public readonly string botPrefix;
+
+ ///
+ /// The bot token
+ ///
+ public readonly string botToken;
+
+ ///
+ /// The bot client
+ ///
+ public DiscordSocketClient client;
+
+ ///
+ /// The bot command handler
+ ///
+ private CommandHandler commandServiceHandler;
+
+ ///
+ /// The command service
+ ///
+ private CommandService service;
+
+ ///
+ /// The main Boot constructor
+ ///
+ /// The bot token
+ /// The bot prefix
+ public Boot(string botToken, string botPrefix)
{
- ///
- /// The bot prefix
- ///
- public readonly string botPrefix;
-
- ///
- /// The bot token
- ///
- public readonly string botToken;
+ this.botPrefix = botPrefix;
+ this.botToken = botToken;
+ }
- ///
- /// Checks if the bot is ready
- ///
- /// true if the bot is ready, othwerwise false
- public bool isReady { get; private set; } = false;
+ ///
+ /// Checks if the bot is ready
+ ///
+ /// true if the bot is ready, othwerwise false
+ public bool isReady { get; private set; }
- ///
- /// The bot client
- ///
- public DiscordSocketClient client;
+ ///
+ /// The start method for the bot. This method is used to load the bot
+ ///
+ /// Task
+ public async Task Awake()
+ {
+ client = new DiscordSocketClient();
+ service = new CommandService();
- ///
- /// The bot command handler
- ///
- private CommandHandler commandServiceHandler;
+ CommonTasks();
- ///
- /// The command service
- ///
- private CommandService service;
+ await client.LoginAsync(TokenType.Bot, botToken);
+ await client.StartAsync();
- ///
- /// The main Boot constructor
- ///
- /// The bot token
- /// The bot prefix
- public Boot(string botToken, string botPrefix)
- {
- this.botPrefix = botPrefix;
- this.botToken = botToken;
- }
+ commandServiceHandler = new CommandHandler(client, service, botPrefix);
+ await commandServiceHandler.InstallCommandsAsync();
- ///
- /// The start method for the bot. This method is used to load the bot
- ///
- /// Task
- public async Task Awake()
- {
- client = new DiscordSocketClient();
- service = new CommandService();
+ await Task.Delay(2000);
+ while (!isReady) ;
+ }
- CommonTasks();
+ private void CommonTasks()
+ {
+ if (client == null) return;
+ client.LoggedOut += Client_LoggedOut;
+ client.Log += Log;
+ client.LoggedIn += LoggedIn;
+ client.Ready += Ready;
+ }
- await client.LoginAsync(TokenType.Bot, botToken);
- await client.StartAsync();
+ private Task Client_LoggedOut()
+ {
+ WriteLogFile("Successfully Logged Out");
+ Log(new LogMessage(LogSeverity.Info, "Boot", "Successfully logged out from discord !"));
+ return Task.CompletedTask;
+ }
- commandServiceHandler = new CommandHandler(client, service, botPrefix);
- await commandServiceHandler.InstallCommandsAsync();
+ private Task Ready()
+ {
+ Console.Title = "ONLINE";
+ isReady = true;
- await Task.Delay(2000);
- while (!isReady) ;
-
- }
-
- ///
- /// The method that stops the bot from running
- ///
- ///
- public async Task ShutDown()
- {
- if (client == null) return;
- await client.LogoutAsync();
- await client.StopAsync();
- }
-
- private void CommonTasks()
- {
- if (client == null) return;
- client.LoggedOut += Client_LoggedOut;
- client.Log += Log;
- client.LoggedIn += LoggedIn;
- client.Ready += Ready;
- }
-
- private Task Client_LoggedOut()
- {
- WriteLogFile("Successfully Logged Out");
- Log(new LogMessage(LogSeverity.Info, "Boot", "Successfully logged out from discord !"));
- return Task.CompletedTask;
- }
-
- private Task Ready()
- {
- Console.Title = "ONLINE";
- isReady = true;
- return Task.CompletedTask;
- }
-
- private Task LoggedIn()
- {
- Console.Title = "CONNECTED";
- WriteLogFile("The bot has been logged in at " + DateTime.Now.ToShortDateString() + " (" +
- DateTime.Now.ToShortTimeString() + ")");
- return Task.CompletedTask;
- }
-
- private Task Log(LogMessage message)
- {
- switch (message.Severity)
+ new Thread(() =>
{
- case LogSeverity.Error:
- case LogSeverity.Critical:
- WriteErrFile(message.Message);
-
- Console.ForegroundColor = ConsoleColor.Red;
- Console.WriteLine("[ERROR] " + message.Message);
- Console.ForegroundColor = ConsoleColor.White;
-
- break;
-
- case LogSeverity.Info:
- case LogSeverity.Debug:
- WriteLogFile(message.Message);
-
- Console.ForegroundColor = ConsoleColor.Cyan;
- Console.WriteLine("[INFO] " + message.Message);
- Console.ForegroundColor = ConsoleColor.White;
-
-
- break;
+ while (true)
+ {
+ Config.SaveConfig();
+ Thread.Sleep(10000);
+ }
}
+ ).Start();
- return Task.CompletedTask;
+ return Task.CompletedTask;
+ }
+
+ private Task LoggedIn()
+ {
+ Console.Title = "CONNECTED";
+ WriteLogFile("The bot has been logged in at " + DateTime.Now.ToShortDateString() + " (" +
+ DateTime.Now.ToShortTimeString() + ")"
+ );
+ return Task.CompletedTask;
+ }
+
+ private Task Log(LogMessage message)
+ {
+ switch (message.Severity)
+ {
+ case LogSeverity.Error:
+ case LogSeverity.Critical:
+ WriteErrFile(message.Message);
+
+ Console.ForegroundColor = ConsoleColor.Red;
+ Console.WriteLine("[ERROR] " + message.Message);
+ Console.ForegroundColor = ConsoleColor.White;
+
+ break;
+
+ case LogSeverity.Info:
+ case LogSeverity.Debug:
+ WriteLogFile(message.Message);
+
+ Console.ForegroundColor = ConsoleColor.Cyan;
+ Console.WriteLine("[INFO] " + message.Message);
+ Console.ForegroundColor = ConsoleColor.White;
+
+
+ break;
}
+
+ return Task.CompletedTask;
}
}
diff --git a/DiscordBot/Discord/Core/CommandHandler.cs b/DiscordBot/Discord/Core/CommandHandler.cs
index 5ed266b..b876858 100644
--- a/DiscordBot/Discord/Core/CommandHandler.cs
+++ b/DiscordBot/Discord/Core/CommandHandler.cs
@@ -1,136 +1,132 @@
-using Discord.Commands;
-using Discord.WebSocket;
-
-using PluginManager.Interfaces;
-
+using System.Linq;
using System.Reflection;
+using System.Threading.Tasks;
+using Discord.Commands;
+using Discord.WebSocket;
+using PluginManager.Loaders;
using PluginManager.Others;
using PluginManager.Others.Permissions;
-using PluginManager.Loaders;
-using System.Threading.Tasks;
-using System.Linq;
-using Discord;
-using System;
+namespace DiscordBot.Discord.Core;
-namespace PluginManager.Core
+internal class CommandHandler
{
- internal class CommandHandler
+ private readonly string botPrefix;
+ private readonly DiscordSocketClient client;
+ private readonly CommandService commandService;
+
+ ///
+ /// Command handler constructor
+ ///
+ /// The discord bot client
+ /// The discord bot command service
+ /// The prefix to watch for
+ public CommandHandler(DiscordSocketClient client, CommandService commandService, string botPrefix)
{
- private readonly DiscordSocketClient client;
- private readonly CommandService commandService;
- private readonly string botPrefix;
+ this.client = client;
+ this.commandService = commandService;
+ this.botPrefix = botPrefix;
+ }
- ///
- /// Command handler constructor
- ///
- /// The discord bot client
- /// The discord bot command service
- /// The prefix to watch for
- public CommandHandler(DiscordSocketClient client, CommandService commandService, string botPrefix)
- {
- this.client = client;
- this.commandService = commandService;
- this.botPrefix = botPrefix;
- }
+ ///
+ /// The method to initialize all commands
+ ///
+ ///
+ public async Task InstallCommandsAsync()
+ {
+ client.MessageReceived += MessageHandler;
+ await commandService.AddModulesAsync(Assembly.GetEntryAssembly(), null);
+ }
- ///
- /// The method to initialize all commands
- ///
- ///
- public async Task InstallCommandsAsync()
+ ///
+ /// The message handler for the bot
+ ///
+ /// The message got from the user in discord chat
+ ///
+ private async Task MessageHandler(SocketMessage Message)
+ {
+ try
{
- client.MessageReceived += MessageHandler;
- await commandService.AddModulesAsync(assembly: Assembly.GetEntryAssembly(), services: null);
- }
+ if (Message as SocketUserMessage == null) return;
- ///
- /// The message handler for the bot
- ///
- /// The message got from the user in discord chat
- ///
- private async Task MessageHandler(SocketMessage Message)
- {
- try
+ var message = Message as SocketUserMessage;
+
+ if (message == null) return;
+
+ if (!message.Content.StartsWith(botPrefix)) return;
+
+ var argPos = 0;
+
+ if (message.HasMentionPrefix(client.CurrentUser, ref argPos))
{
- if (Message as SocketUserMessage == null)
- return;
+ await message.Channel.SendMessageAsync("Can not exec mentioned commands !");
+ return;
+ }
- var message = Message as SocketUserMessage;
+ if (message.Author.IsBot) return;
- if (message == null) return;
+ var context = new SocketCommandContext(client, message);
- if (!message.Content.StartsWith(botPrefix)) return;
+ await commandService.ExecuteAsync(
+ context,
+ argPos,
+ null
+ );
- int argPos = 0;
+ var plugin = PluginLoader.Commands!.Where(p => p.Command == message.Content.Split(' ')[0].Substring(botPrefix.Length)).FirstOrDefault();
- if (message.HasMentionPrefix(client.CurrentUser, ref argPos))
+
+ if (plugin != null)
+ {
+ if (message.Channel == await message.Author.CreateDMChannelAsync())
{
- await message.Channel.SendMessageAsync("Can not exec mentioned commands !");
- return;
- }
-
- if (message.Author.IsBot) return;
-
- var context = new SocketCommandContext(client, message);
-
- await commandService.ExecuteAsync(
- context: context,
- argPos: argPos,
- services: null
- );
-
- DBCommand plugin = PluginLoader.Plugins!.Where(p => p.Command == (message.Content.Split(' ')[0]).Substring(botPrefix.Length)).FirstOrDefault();
-
-
- if (plugin != null)
- {
- if (message.Channel == await message.Author.CreateDMChannelAsync())
- {
- if (plugin.canUseDM)
- {
- if (plugin.requireAdmin)
- {
- if (message.Author.isAdmin())
- {
- plugin.Execute(context, message, client, true);
- Functions.WriteLogFile($"[{message.Author.Id}] Executed command (DM) : " + plugin.Command);
- return;
- }
- await message.Channel.SendMessageAsync("This command is for administrators only !");
- return;
- }
- plugin.Execute(context, message, client, true);
- Functions.WriteLogFile($"[{message.Author.Id}] Executed command (DM) : " + plugin.Command);
- return;
- }
-
- await message.Channel.SendMessageAsync("This command is not for DMs");
- return;
- }
- if (plugin.canUseServer)
+ if (plugin.canUseDM)
{
if (plugin.requireAdmin)
{
if (message.Author.isAdmin())
{
- plugin.Execute(context, message, client, false);
- Functions.WriteLogFile($"[{message.Author.Id}] Executed command : " + plugin.Command);
+ plugin.Execute(context, message, client, true);
+ Functions.WriteLogFile($"[{message.Author.Id}] Executed command (DM) : " + plugin.Command);
return;
}
+
await message.Channel.SendMessageAsync("This command is for administrators only !");
return;
}
- plugin.Execute(context, message, client, false);
- Functions.WriteLogFile($"[{message.Author.Id}] Executed command : " + plugin.Command);
+
+ plugin.Execute(context, message, client, true);
+ Functions.WriteLogFile($"[{message.Author.Id}] Executed command (DM) : " + plugin.Command);
return;
}
- return;
+ await message.Channel.SendMessageAsync("This command is not for DMs");
+ return;
+ }
+
+ if (plugin.canUseServer)
+ {
+ if (plugin.requireAdmin)
+ {
+ if (message.Author.isAdmin())
+ {
+ plugin.Execute(context, message, client, false);
+ Functions.WriteLogFile($"[{message.Author.Id}] Executed command : " + plugin.Command);
+ return;
+ }
+
+ await message.Channel.SendMessageAsync("This command is for administrators only !");
+ return;
+ }
+
+ plugin.Execute(context, message, client, false);
+ Functions.WriteLogFile($"[{message.Author.Id}] Executed command : " + plugin.Command);
+ return;
}
}
- catch { }
-
+ }
+ catch
+ {
}
}
-}
\ No newline at end of file
+}
diff --git a/DiscordBot/DiscordBot.csproj b/DiscordBot/DiscordBot.csproj
index 37fb607..f83d305 100644
--- a/DiscordBot/DiscordBot.csproj
+++ b/DiscordBot/DiscordBot.csproj
@@ -6,6 +6,16 @@
disable
+ False
+ True
+
+
+
+ none
+
+
+
+ none
diff --git a/DiscordBot/Program.cs b/DiscordBot/Program.cs
index 9c1a719..7a9f374 100644
--- a/DiscordBot/Program.cs
+++ b/DiscordBot/Program.cs
@@ -1,89 +1,82 @@
-using Discord;
-
+using DiscordBot.Discord.Core;
+using PluginManager;
+using PluginManager.Items;
+using PluginManager.Others;
using System;
using System.IO;
-using System.Threading.Tasks;
-
-using PluginManager.Core;
-using PluginManager.Others;
-using PluginManager.LanguageSystem;
-using PluginManager.Online;
-
-using System.Collections.Generic;
using System.Linq;
-using PluginManager.Items;
+using System.Threading.Tasks;
+using PluginManager.Online;
namespace DiscordBot
{
public class Program
{
- private static bool loadPluginsOnStartup = false;
- private static bool listPluginsAtStartup = false;
- private static bool listLanguagAtStartup = false;
-
- private static bool ShowStartupMessage = true;
+ private static bool loadPluginsOnStartup = false;
+ private static bool listPluginsAtStartup = false;
///
/// The main entry point for the application.
///
[STAThread]
[Obsolete]
-
public static void Main(string[] args)
{
Directory.CreateDirectory("./Data/Resources");
- Directory.CreateDirectory("./Data/Languages");
Directory.CreateDirectory("./Data/Plugins/Commands");
Directory.CreateDirectory("./Data/Plugins/Events");
- if (!File.Exists("./Data/Resources/DiscordBotCore.data") || (Functions.readCodeFromFile("./Data/Resources/DiscordBotCore.data", "BOT_TOKEN", '=').Length != 59 && Functions.readCodeFromFile("./Data/Resources/DiscordBotCore.data", "BOT_TOKEN", '=').Length != 70))
+ PreLoadComponents().Wait();
+
+ if (!Config.ContainsKey("token") || Config.GetValue("token") == null || Config.GetValue("token")?.Length != 70)
{
- File.WriteAllText("./Data/Resources/DiscordBotCore.data", "BOT_TOKEN=token\nBOT_PREFIX=!\n");
while (true)
{
- Console.WriteLine("Please insert your token: ");
- Console.Write("TOKEN: ");
- string botToken = Console.ReadLine();
- if (botToken.Length == 59 || botToken.Length == 70)
+ Console.WriteLine("Please insert your token");
+ Console.Write("Token = ");
+ string token = Console.ReadLine();
+ if (token?.Length == 59 || token?.Length == 70)
+ Config.AddValueToVariables("token", token, true);
+ else
{
- string prefix = Functions.readCodeFromFile("./Data/Resources/DiscordBotCore.data", "BOT_PREFIX", '=');
- if (prefix == string.Empty || prefix == null)
- prefix = "!";
- File.WriteAllText("./Data/Resources/DiscordBotCore.data", $"BOT_TOKEN={botToken}\nBOT_PREFIX={prefix}\n");
- break;
+ Console.WriteLine("Invalid token");
+ continue;
}
- else Console.WriteLine("Invalid Token !");
+
+ Console.WriteLine("Please insert your prefix (max. 1 character long):");
+ Console.WriteLine("For a prefix longer then one character, the first character will be saved and the others will be ignored.\n No spaces or numbers allowed");
+ Console.Write("Prefix = ");
+ char prefix = Console.ReadLine()![0];
+
+ if (prefix == ' ' || char.IsDigit(prefix)) continue;
+ Config.AddValueToVariables("prefix", prefix.ToString(), false);
+ break;
}
}
+ if (!Config.ContainsKey("prefix"))
+ {
+ Console.WriteLine("Please insert your prefix (max. 1 character long):");
+ Console.WriteLine("For a prefix longer then one character, the first character will be saved and the others will be ignored.\n No spaces or numbers allowed");
+ Console.Write("Prefix = ");
+ char prefix = Console.ReadLine()![0];
+
+ if (prefix == ' ' || char.IsDigit(prefix)) return;
+ Config.AddValueToVariables("prefix", prefix.ToString(), false);
+ }
+
HandleInput(args).Wait();
}
- ///
- /// Reset all settings for the bot
- ///
- private static Task ResetSettings()
- {
- string[] files = Directory.GetFiles(@"./Data/Resources");
- foreach (string file in files) File.Delete(file);
- return Task.CompletedTask;
- }
-
///
/// The main loop for the discord bot
///
/// The discord booter used to start the application
- private static async Task NoGUI(Boot discordbooter)
+ private static Task NoGUI(Boot discordbooter)
{
- Language.LoadLanguage();
-
ConsoleCommandsHandler consoleCommandsHandler = new ConsoleCommandsHandler(discordbooter.client);
- if (loadPluginsOnStartup)
- consoleCommandsHandler.HandleCommand("lp");
- if (listPluginsAtStartup)
- consoleCommandsHandler.HandleCommand("listplugs");
- if (listLanguagAtStartup)
- consoleCommandsHandler.HandleCommand("listlang");
-
+ if (loadPluginsOnStartup) consoleCommandsHandler.HandleCommand("lp");
+ if (listPluginsAtStartup) consoleCommandsHandler.HandleCommand("listplugs");
+ Config.SaveConfig();
while (true)
{
Console.ForegroundColor = ConsoleColor.White;
@@ -98,28 +91,28 @@ namespace DiscordBot
/// Returns the boot loader for the Discord Bot
private static async Task StartNoGUI()
{
-
Console.Clear();
Console.ForegroundColor = ConsoleColor.DarkYellow;
Console.WriteLine("Discord BOT for Cross Platform");
Console.WriteLine("Created by: Wizzy\nDiscord: Wizzy#9181");
- if (ShowStartupMessage)
- try
- {
- Console.WriteLine("Connecting to server ...");
- List text = await ServerCom.ReadTextFromFile("https://sethdiscordbot.000webhostapp.com/Storage/Discord%20Bot/StartupMessage");
- foreach (var t in text) Console_Utilities.WriteColorText(t);
- }
- catch { Console.WriteLine("Failed to connect to server."); }
Console.ForegroundColor = ConsoleColor.White;
Console.WriteLine("============================ Discord BOT - Cross Platform ============================");
- string token = Functions.readCodeFromFile(Functions.dataFolder + "DiscordBotCore.data", "BOT_TOKEN", '=');
- string prefix = Functions.readCodeFromFile(Functions.dataFolder + "DiscordBotCore.data", "BOT_PREFIX", '=');
- var discordbooter = new Boot(token, prefix);
- await discordbooter.Awake();
- return discordbooter;
+ try
+ {
+ string token = Config.GetValue("token");
+ string prefix = Config.GetValue("prefix");
+
+ var discordbooter = new Boot(token, prefix);
+ await discordbooter.Awake();
+ return discordbooter;
+ }
+ catch (Exception ex)
+ {
+ Console.WriteLine(ex);
+ return null;
+ }
}
///
@@ -128,8 +121,8 @@ namespace DiscordBot
/// Directory path
private static Task ClearFolder(string d)
{
- string[] files = Directory.GetFiles(d);
- int fileNumb = files.Length;
+ string[] files = Directory.GetFiles(d);
+ int fileNumb = files.Length;
for (var i = 0; i < fileNumb; i++)
{
File.Delete(files[i]);
@@ -145,16 +138,6 @@ namespace DiscordBot
/// The arguments
private static async Task HandleInput(string[] args)
{
-
- if (args.Length == 0)
- {
- if (File.Exists("./ref/startupArguments.txt"))
- {
- var lines = await File.ReadAllLinesAsync("./ref/startupArguments.txt");
- args = lines;
- }
- }
-
int len = args.Length;
if (len == 1 && args[0] == "--help")
{
@@ -164,8 +147,13 @@ namespace DiscordBot
if (len == 1 && args[0] == "--logout")
{
- File.Delete(Functions.dataFolder + "Login.dat");
- Console.WriteLine("Logged out. Please restart the application !");
+ File.Delete(Functions.dataFolder + "config.json");
+ await Task.Run(async () =>
+ {
+ await Task.Delay(1000);
+ Environment.Exit(0x08);
+ }
+ );
return;
}
@@ -177,20 +165,22 @@ namespace DiscordBot
return;
}
- if (len > 0 && (args.Contains("--cmd") || args.Contains("--args") || args.Contains("--nomessage")))
+ if (len == 3 && args[0] == "/download")
{
- if (args.Contains("lp") || args.Contains("loadplugins"))
- loadPluginsOnStartup = true;
- if (args.Contains("listplugs"))
- listPluginsAtStartup = true;
- if (args.Contains("listlang"))
- listLanguagAtStartup = true;
- if (args.Contains("--nomessage"))
- ShowStartupMessage = false;
- len = 0;
+ string url = args[1];
+ string location = args[2];
+
+ await ServerCom.DownloadFileAsync(url, location);
+
+ return;
}
-
+ if (len > 0 && (args.Contains("--cmd") || args.Contains("--args") || args.Contains("--nomessage")))
+ {
+ if (args.Contains("lp") || args.Contains("loadplugins")) loadPluginsOnStartup = true;
+ if (args.Contains("listplugs")) listPluginsAtStartup = true;
+ len = 0;
+ }
if (len == 0 || args[0] != "--exec" && args[0] != "--execute")
@@ -200,13 +190,13 @@ namespace DiscordBot
return;
}
+
Console.ForegroundColor = ConsoleColor.DarkYellow;
Console.WriteLine("Execute command interface noGUI\n\n");
Console.WriteLine(
"\tCommand name\t\t\t\tDescription\n" +
"-- help | -help\t\t ------ \tDisplay the help message\n" +
"--reset-full\t\t ------ \tReset all files (clear files)\n" +
- "--reset-settings\t ------ \tReset only bot settings\n" +
"--reset-logs\t\t ------ \tClear up the output folder\n" +
"--start\t\t ------ \tStart the bot\n" +
"exit\t\t\t ------ \tClose the application"
@@ -219,10 +209,6 @@ namespace DiscordBot
switch (message[0])
{
- case "--reset-settings":
- await ResetSettings();
- Console.WriteLine("Successfully reseted all settings !");
- break;
case "--help":
case "-help":
Console.ForegroundColor = ConsoleColor.DarkYellow;
@@ -241,7 +227,6 @@ namespace DiscordBot
await ClearFolder("./Output/Logs/");
await ClearFolder("./Output/Errors");
await ClearFolder("./Data/Languages/");
- await ClearFolder("./Data/Plugins/Addons");
await ClearFolder("./Data/Plugins/Commands");
await ClearFolder("./Data/Plugins/Events");
Console.WriteLine("Successfully cleared all folders");
@@ -259,11 +244,21 @@ namespace DiscordBot
Boot booter = await StartNoGUI();
await NoGUI(booter);
return;
+
default:
Console.WriteLine("Failed to execute command " + message[0]);
break;
}
}
}
+
+ private static async Task PreLoadComponents()
+ {
+ await Config.LoadConfig();
+ if (Config.ContainsKey("DeleteLogsAtStartup"))
+ if (Config.GetValue("DeleteLogsAtStartup"))
+ foreach (string file in Directory.GetFiles("./Output/Logs/"))
+ File.Delete(file);
+ }
}
}
diff --git a/DiscordBotGUI/App.axaml b/DiscordBotGUI/App.axaml
index 7d4aeba..49aa2e5 100644
--- a/DiscordBotGUI/App.axaml
+++ b/DiscordBotGUI/App.axaml
@@ -1,7 +1,7 @@
-
-
-
-
+
+
+
+
\ No newline at end of file
diff --git a/DiscordBotGUI/App.axaml.cs b/DiscordBotGUI/App.axaml.cs
index a3b2c89..983b886 100644
--- a/DiscordBotGUI/App.axaml.cs
+++ b/DiscordBotGUI/App.axaml.cs
@@ -1,27 +1,21 @@
using Avalonia;
+using Avalonia.Controls;
using Avalonia.Controls.ApplicationLifetimes;
using Avalonia.Markup.Xaml;
-namespace DiscordBotGUI
+namespace DiscordBotGUI;
+
+public class App : Application
{
- public partial class App : Application
+ public override void Initialize()
{
- public override void Initialize()
- {
- AvaloniaXamlLoader.Load(this);
- }
+ AvaloniaXamlLoader.Load(this);
+ }
- public override void OnFrameworkInitializationCompleted()
- {
- if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop)
- {
+ public override void OnFrameworkInitializationCompleted()
+ {
+ if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop) desktop.MainWindow = new AppUpdater { Width = 300, Height = 50, WindowStartupLocation = WindowStartupLocation.CenterScreen };
-
- desktop.MainWindow = new AppUpdater() { Width = 300, Height = 50, WindowStartupLocation = Avalonia.Controls.WindowStartupLocation.CenterScreen };
-
- }
-
- base.OnFrameworkInitializationCompleted();
- }
+ base.OnFrameworkInitializationCompleted();
}
}
diff --git a/DiscordBotGUI/AppUpdater.axaml b/DiscordBotGUI/AppUpdater.axaml
index c20c2e5..939c0d6 100644
--- a/DiscordBotGUI/AppUpdater.axaml
+++ b/DiscordBotGUI/AppUpdater.axaml
@@ -5,12 +5,13 @@
mc:Ignorable="d" d:DesignWidth="250" d:DesignHeight="50"
x:Class="DiscordBotGUI.AppUpdater"
Title="AppUpdater"
- Background="Transparent"
- TransparencyLevelHint="AcrylicBlur"
- HasSystemDecorations="False">
+ Background="Transparent"
+ TransparencyLevelHint="AcrylicBlur"
+ SystemDecorations="BorderOnly">
-
-
-
-
-
+
+
+
+
+
\ No newline at end of file
diff --git a/DiscordBotGUI/AppUpdater.axaml.cs b/DiscordBotGUI/AppUpdater.axaml.cs
index ecc5405..fcf519f 100644
--- a/DiscordBotGUI/AppUpdater.axaml.cs
+++ b/DiscordBotGUI/AppUpdater.axaml.cs
@@ -1,62 +1,65 @@
-using Avalonia;
using Avalonia.Controls;
-using Avalonia.Markup.Xaml;
-
using PluginManager.Online;
using PluginManager.Others;
using System.Threading.Tasks;
using System;
using System.IO;
using System.Threading;
-using System.Drawing;
-using Avalonia.Media;
+using PluginManager;
namespace DiscordBotGUI
{
public partial class AppUpdater : Window
{
- private string _version;
+ private string _version = "";
+
public AppUpdater()
{
InitializeComponent();
+ Config.LoadConfig().Wait();
if (!File.Exists("./Version.txt"))
{
- textBox1.Text = "Checking ...";
File.WriteAllText("./Version.txt", "DiscordBotVersion=0");
- //DownloadDiscordBotClientNoGUIAsDLL();
+ DownloadDiscordBotClientNoGUIAsDLL();
}
+ if (!File.Exists("./DiscordBot.exe")) DownloadDiscordBotClientNoGUIAsDLL();
Updates();
-
}
- /* private async void DownloadDiscordBotClientNoGUIAsDLL()
- {
+ private async void DownloadDiscordBotClientNoGUIAsDLL()
+ {
+ //await Task.Delay(5000);
+ string url_bot_dll = "https://sethdiscordbot.000webhostapp.com/Storage/Discord%20Bot/Updates/DiscordBot.zip";
+ int actiontype = 0; //0 - downolad, 1- extract
+ IProgress progress = new Progress((percent) =>
+ {
+ if (actiontype == 0)
+ textBox1.Text = "Downloading DiscordBot ... " + MathF.Round(percent, 2) + "%";
+ else
+ textBox1.Text = "Extracting package ..." + MathF.Round(percent, 2) + "%";
+ this.progressBar1.Value = percent;
+ });
- //await Task.Delay(5000);
- string url_bot_dll = "https://sethdiscordbot.000webhostapp.com/Storage/Discord%20Bot/Updates/DiscordBot.dll";
- IProgress progress = new Progress((percent) =>
- {
- textBox1.Text = "Downloading DiscordBot.dll ... " + (percent * 100).ToString() + "%";
- this.progressBar1.Value = percent * 100;
- });
+ this.progressBar1.IsIndeterminate = false;
+ try
+ {
+ await ServerCom.DownloadFileAsync(url_bot_dll, "./DiscordBot.zip", progress);
- this.progressBar1.IsIndeterminate = false;
- try
- {
- await ServerCom.DownloadFileAsync(url_bot_dll, "./DiscordBot.dll", progress);
- }
- catch
- {
- textBox1.Text = "Error downloading DiscordBot.dll. Server is not responding.";
+ actiontype++;
- await Task.Delay(1000);
- return;
- }
+ await Functions.ExtractArchive("./DiscordBot.zip", "./", progress);
+ }
+ catch
+ {
+ textBox1.Text = "Error downloading DiscordBot.dll. Server is not responding.";
- //new MainWindow() { Height = 425, Width = 500 }.Show();
- //Close();
- }*/
+ await Task.Delay(1000);
+
+ new MainWindow() { Height = 425, Width = 500 }.Show();
+ Close();
+ }
+ }
private async void Updates()
{
@@ -82,31 +85,27 @@ namespace DiscordBotGUI
return;
}
- IProgress progress = new Progress((percent) =>
- {
- this.progressBar1.Value = percent;
- });
+ IProgress progress = new Progress((percent) => { this.progressBar1.Value = percent; });
textBox1.Text = "Extracting update files ...";
await Functions.ExtractArchive(file, "./", progress);
progressBar1.IsIndeterminate = true;
- textBox1.Text = "Setting up the new version ...";
+ textBox1.Text = "Setting up the new version ...";
File.Delete(file);
File.WriteAllText("./Version.txt", "DiscordBotVersion=" + _version);
await Task.Delay(5000);
new MainWindow() { Height = 425, Width = 650 }.Show();
this.Close();
-
}
private async Task DownloadNewUpdate()
{
string urlNewUpdateZip = (await ServerCom.ReadTextFromFile("https://sethdiscordbot.000webhostapp.com/Storage/Discord%20Bot/Updates/Version"))[1];
- int secondsPast = 0;
+ int secondsPast = 0;
bool isDownloading = true;
this.progressBar1.IsIndeterminate = true;
- textBox1.Text = "Downloading update ...";
+ textBox1.Text = "Downloading update ...";
IProgress downloaded = new Progress((bytes) =>
@@ -117,14 +116,13 @@ namespace DiscordBotGUI
IProgress progress = new Progress((percent) =>
{
progressBar1.IsIndeterminate = false;
- this.progressBar1.Value = percent;
+ this.progressBar1.Value = percent;
});
string FileName = $"{urlNewUpdateZip.Split('/')[urlNewUpdateZip.Split('/').Length - 1]}";
try
{
-
new Thread(new Task(() =>
{
while (isDownloading)
@@ -142,6 +140,7 @@ namespace DiscordBotGUI
await Task.Delay(1000);
return null;
}
+
isDownloading = false;
return FileName;
}
@@ -150,20 +149,20 @@ namespace DiscordBotGUI
{
try
{
-
- string current_version = Functions.readCodeFromFile("Version.txt", "DiscordBotVersion", '=') ?? "0";
- string latest_version = (await ServerCom.ReadTextFromFile("https://sethdiscordbot.000webhostapp.com/Storage/Discord%20Bot/Updates/Version"))[0];
+ string current_version = Config.GetValue("Version");
+ if (current_version == null)
+ if (!Config.SetValue("Version", "0"))
+ Config.AddValueToVariables("Version", "0", false);
+ string latest_version = (await ServerCom.ReadTextFromFile("https://sethdiscordbot.000webhostapp.com/Storage/Discord%20Bot/Updates/Version"))[0];
_version = latest_version;
- if (current_version != latest_version)
- {
- return true;
- }
+ if (current_version != latest_version) { return true; }
return false;
}
catch (Exception ex)
{
textBox1.Text = "Error while checking for updates. Server is not responding.";
+ Functions.WriteErrFile(ex.Message);
return false;
}
}
diff --git a/DiscordBotGUI/MainWindow.axaml b/DiscordBotGUI/MainWindow.axaml
index 43854e9..c011ce7 100644
--- a/DiscordBotGUI/MainWindow.axaml
+++ b/DiscordBotGUI/MainWindow.axaml
@@ -5,31 +5,35 @@
mc:Ignorable="d" d:DesignWidth="500" d:DesignHeight="425"
x:Class="DiscordBotGUI.MainWindow"
Title="DiscordBotGUI"
- Background="Transparent"
- TransparencyLevelHint="AcrylicBlur"
- ExtendClientAreaToDecorationsHint="True" >
+ Background="Transparent"
+ TransparencyLevelHint="AcrylicBlur"
+ ExtendClientAreaToDecorationsHint="True">
-
-
-
-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
-
-
-
-
+
\ No newline at end of file
diff --git a/DiscordBotGUI/MainWindow.axaml.cs b/DiscordBotGUI/MainWindow.axaml.cs
index 00490b6..b7cf17f 100644
--- a/DiscordBotGUI/MainWindow.axaml.cs
+++ b/DiscordBotGUI/MainWindow.axaml.cs
@@ -1,103 +1,86 @@
-using Avalonia.Controls;
-
-using System.Threading.Tasks;
-
-using PluginManager.Others;
-using System.IO;
-using System;
using System.Diagnostics;
+using System.IO;
+using System.Threading.Tasks;
+using Avalonia.Controls;
using DiscordBotGUI.Settings;
-using Avalonia.Themes.Fluent;
+using PluginManager;
+using PluginManager.Others;
-namespace DiscordBotGUI
+namespace DiscordBotGUI;
+
+public partial class MainWindow : Window
{
- public partial class MainWindow : Window
+ public MainWindow()
{
- public MainWindow()
+ InitializeComponent();
+
+ LoadElements();
+ }
+
+ private void LoadElements()
+ {
+ textBox3.Watermark = "Insert start arguments";
+ if (File.Exists("./Version.txt")) label5.Content = Config.GetValue("Version");
+ button1.Click += async (sender, e) =>
{
- InitializeComponent();
+ var token = textBox1.Text;
+ var prefix = textBox2.Text;
+ var args = "--nomessage " + textBox3.Text;
- LoadElements();
-
-
- }
-
- private void LoadElements()
- {
-
-
- textBox3.Watermark = "Insert start arguments";
- if (File.Exists("./Version.txt"))
- label5.Content = Functions.readCodeFromFile("./Version.txt", "DiscordBotVersion", '=');
- button1.Click += async (sender, e) =>
+ if (!((token.Length == 70 || token.Length == 59) && prefix.Length == 1))
{
-
- string token = textBox1.Text;
- string prefix = textBox2.Text;
- string args = "--nomessage " + textBox3.Text;
-
- if (!((token.Length == 70 || token.Length == 59) && prefix.Length == 1))
- {
- label4.Content = "Invalid Token or Prefix.\n(Prefix must be 1 character long and token must be 59 or 79 characters long)";
- await Task.Delay(5000);
- label4.Content = "";
- return;
- }
-
- Functions.WriteToSettings(Functions.dataFolder + "DiscordBotCore.data", "BOT_TOKEN", token, '=');
- Functions.WriteToSettings(Functions.dataFolder + "DiscordBotCore.data", "BOT_PREFIX", prefix, '=');
- RunDiscordBot(args);
-
- };
-
- commandsSettingMenuItem.Click += (sender, e) => new Commands() /*{ Height = 200, Width = 550 }*/.ShowDialog(this);
- eventsSettingMenuItem.Click += (sender, e) => new Events() /*{ Height = 200, Width = 550 }*/.ShowDialog(this);
-
-
- string folder = $"{Functions.dataFolder}DiscordBotCore.data";
- Directory.CreateDirectory(Functions.dataFolder);
- try
- {
- string? botToken = Functions.readCodeFromFile(folder, "BOT_TOKEN", '=');
- string? botPrefix = Functions.readCodeFromFile(folder, "BOT_PREFIX", '=');
- if (botToken == null || botPrefix == null)
- {
- textBox1.IsReadOnly = false;
- textBox2.IsReadOnly = false;
- textBox1.Watermark = "Insert Bot Token Here";
- textBox2.Watermark = "Insert Bot Prefix Here";
-
- }
- else
- {
- textBox1.Text = botToken;
- textBox2.Text = botPrefix;
- }
+ label4.Content = "Invalid Token or Prefix.\n(Prefix must be 1 character long and token must be 59 or 79 characters long)";
+ await Task.Delay(5000);
+ label4.Content = "";
+ return;
}
- catch
+
+ Config.SetValue("token", token);
+ Config.SetValue("prefix", prefix);
+ RunDiscordBot(args);
+ };
+
+ commandsSettingMenuItem.Click += (sender, e) => new Commands() /*{ Height = 200, Width = 550 }*/.ShowDialog(this);
+ eventsSettingMenuItem.Click += (sender, e) => new Events() /*{ Height = 200, Width = 550 }*/.ShowDialog(this);
+ applicationVariablesMenuItem.Click += (sender, e) => new ApplicationVariables().ShowDialog(this);
+
+ var folder = $"{Functions.dataFolder}DiscordBotCore.data";
+ Directory.CreateDirectory(Functions.dataFolder);
+ try
+ {
+ var botToken = Config.GetValue("token");
+ var botPrefix = Config.GetValue("prefix");
+ if (botToken == null || botPrefix == null)
{
textBox1.IsReadOnly = false;
textBox2.IsReadOnly = false;
- textBox1.Watermark = "Insert Bot Token Here";
- textBox2.Watermark = "Insert Bot Prefix Here";
+ textBox1.Watermark = "Insert Bot Token Here";
+ textBox2.Watermark = "Insert Bot Prefix Here";
+ }
+ else
+ {
+ textBox1.Text = botToken;
+ textBox2.Text = botPrefix;
}
-
-
-
}
-
-
- private void RunDiscordBot(string args)
+ catch
{
- var os = Functions.GetOperatingSystem();
- if (os == PluginManager.Others.OperatingSystem.WINDOWS)
- Process.Start("./DiscordBot.exe", args);
- else if (os == PluginManager.Others.OperatingSystem.LINUX)
- Process.Start("./DiscordBot", args);
- else if (os == PluginManager.Others.OperatingSystem.MAC_OS)
- Process.Start("./DiscordBot.app/Contents/MacOS/DiscordBot", args);
- Close();
- return;
+ textBox1.IsReadOnly = false;
+ textBox2.IsReadOnly = false;
+ textBox1.Watermark = "Insert Bot Token Here";
+ textBox2.Watermark = "Insert Bot Prefix Here";
}
}
+
+
+ private void RunDiscordBot(string args)
+ {
+ var os = Functions.GetOperatingSystem();
+ if (os == OperatingSystem.WINDOWS)
+ Process.Start("./DiscordBot.exe", args);
+ else if (os == OperatingSystem.LINUX)
+ Process.Start("./DiscordBot", args);
+ else if (os == OperatingSystem.MAC_OS) Process.Start("./DiscordBot.app/Contents/MacOS/DiscordBot", args);
+ Close();
+ }
}
diff --git a/DiscordBotGUI/Program.cs b/DiscordBotGUI/Program.cs
index ab83d97..97ded76 100644
--- a/DiscordBotGUI/Program.cs
+++ b/DiscordBotGUI/Program.cs
@@ -1,29 +1,25 @@
-using Avalonia;
-using Avalonia.Controls;
-using Avalonia.Controls.ApplicationLifetimes;
-
using System;
-using System.IO;
-using System.Threading.Tasks;
+using Avalonia;
-namespace DiscordBotGUI
+namespace DiscordBotGUI;
+
+internal class Program
{
- internal class Program
+ // Initialization code. Don't use any Avalonia, third-party APIs or any
+ // SynchronizationContext-reliant code before AppMain is called: things aren't initialized
+ // yet and stuff might break.
+ [STAThread]
+ public static void Main(string[] args)
{
- // Initialization code. Don't use any Avalonia, third-party APIs or any
- // SynchronizationContext-reliant code before AppMain is called: things aren't initialized
- // yet and stuff might break.
- [STAThread]
- public static void Main(string[] args)
- {
- BuildAvaloniaApp()
- .StartWithClassicDesktopLifetime(args);
- }
+ BuildAvaloniaApp()
+ .StartWithClassicDesktopLifetime(args);
+ }
- // Avalonia configuration, don't remove; also used by visual designer.
- public static AppBuilder BuildAvaloniaApp()
- => AppBuilder.Configure()
- .UsePlatformDetect()
- .LogToTrace();
+ // Avalonia configuration, don't remove; also used by visual designer.
+ public static AppBuilder BuildAvaloniaApp()
+ {
+ return AppBuilder.Configure()
+ .UsePlatformDetect()
+ .LogToTrace();
}
}
diff --git a/DiscordBotGUI/Settings/ApplicationVariables.axaml b/DiscordBotGUI/Settings/ApplicationVariables.axaml
new file mode 100644
index 0000000..db6e433
--- /dev/null
+++ b/DiscordBotGUI/Settings/ApplicationVariables.axaml
@@ -0,0 +1,23 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/DiscordBotGUI/Settings/ApplicationVariables.axaml.cs b/DiscordBotGUI/Settings/ApplicationVariables.axaml.cs
new file mode 100644
index 0000000..2559134
--- /dev/null
+++ b/DiscordBotGUI/Settings/ApplicationVariables.axaml.cs
@@ -0,0 +1,41 @@
+using Avalonia.Controls;
+using PluginManager;
+
+namespace DiscordBotGUI.Settings;
+
+public partial class ApplicationVariables : Window
+{
+ public ApplicationVariables()
+ {
+ InitializeComponent();
+ Load();
+ }
+
+ private void Load()
+ {
+ ClearEverything();
+ button1.Click += (sedner, e) =>
+ {
+ var key = textBox2.Text;
+ if (Config.ContainsKey(key))
+ {
+ ClearEverything();
+ return;
+ }
+
+ var value = textBox3.Text;
+ Config.AddValueToVariables(key, value, checkBox1.IsChecked!.Value);
+ ClearEverything();
+ };
+ }
+
+ private void ClearEverything()
+ {
+ textBox1.Text = "";
+ textBox2.Text = "";
+ textBox3.Text = "";
+ checkBox1.IsChecked = false;
+ var allvars = Config.GetAllVariables();
+ foreach (var kvp in allvars) textBox1.Text += kvp.Key + " => " + kvp.Value + "\n";
+ }
+}
diff --git a/DiscordBotGUI/Settings/Commands.axaml b/DiscordBotGUI/Settings/Commands.axaml
index 86a1cd1..69ef101 100644
--- a/DiscordBotGUI/Settings/Commands.axaml
+++ b/DiscordBotGUI/Settings/Commands.axaml
@@ -5,17 +5,20 @@
mc:Ignorable="d" d:DesignWidth="550" d:DesignHeight="200"
x:Class="DiscordBotGUI.Settings.Commands"
Title="Commands"
- Background="Transparent"
- TransparencyLevelHint="AcrylicBlur"
- ExtendClientAreaToDecorationsHint="True">
-
-
-
-
-
-
-
-
-
+ Background="Transparent"
+ TransparencyLevelHint="AcrylicBlur"
+ ExtendClientAreaToDecorationsHint="True">
+
+
+
+
+
+
+
+
+
-
+
\ No newline at end of file
diff --git a/DiscordBotGUI/Settings/Commands.axaml.cs b/DiscordBotGUI/Settings/Commands.axaml.cs
index d68fd73..27291d3 100644
--- a/DiscordBotGUI/Settings/Commands.axaml.cs
+++ b/DiscordBotGUI/Settings/Commands.axaml.cs
@@ -1,95 +1,93 @@
-using Avalonia;
-using Avalonia.Controls;
-using Avalonia.Markup.Xaml;
-
-using PluginManager.Others;
-
-using System.Linq;
-using System.Collections.Generic;
-using System.Threading.Tasks;
using System;
+using System.Collections.Generic;
using System.IO;
+using System.Linq;
+using System.Threading.Tasks;
+using Avalonia.Controls;
+using PluginManager.Online;
+using PluginManager.Others;
+using OperatingSystem = PluginManager.Others.OperatingSystem;
-namespace DiscordBotGUI.Settings
+namespace DiscordBotGUI.Settings;
+
+public partial class Commands : Window
{
- public partial class Commands : Window
+ private List commands = new();
+
+ public Commands()
{
- List commands = new List();
- public Commands()
- {
- InitializeComponent();
- LoadData();
- LoadComboBox();
+ InitializeComponent();
+ LoadData();
+ LoadComboBox();
- button1.Click += async (sender, e) =>
- {
- await Download();
- };
+ button1.Click += async (sender, e) => { await Download(); };
+ }
+
+
+ private void LoadData()
+ {
+ try
+ {
+ textbox1.Text = "";
+ Directory.CreateDirectory("./Data/Plugins/Commands/");
+ var files = Directory.EnumerateFiles("./Data/Plugins/Commands/");
+ if (files == null || files.Count() < 1) return;
+ foreach (var file in files) textbox1.Text += file.Split('/')[file.Split('/').Length - 1] + "\n";
}
-
-
- private void LoadData()
+ catch
{
+ }
+ }
+
+ private async void LoadComboBox()
+ {
+ comboBox1.Items = null;
+ commands = await ServerCom.ReadTextFromFile("https://sethdiscordbot.000webhostapp.com/Storage/Discord%20Bot/Plugins");
+ if (commands == null) return;
+ var plugins = commands.ToArray();
+ string OS;
+ var OSG = Functions.GetOperatingSystem();
+ if (OSG == OperatingSystem.WINDOWS)
+ OS = "Windows";
+ else if (OSG == OperatingSystem.LINUX)
+ OS = "Linux";
+ else
+ OS = "MAC_OS";
+ var data = new List();
+ for (var i = 0; i < plugins.Length; i++)
+ {
+ if (!plugins[i].Contains(OS) || !plugins[i].Contains("Commands")) continue;
+
+ var info = plugins[i].Split(',');
try
{
- textbox1.Text = "";
- Directory.CreateDirectory("./Data/Plugins/Commands/");
- var files = System.IO.Directory.EnumerateFiles("./Data/Plugins/Commands/");
- if (files == null || files.Count() < 1) return;
- foreach (var file in files)
- textbox1.Text += file.Split('/')[file.Split('/').Length - 1] + "\n";
+ if (Directory.EnumerateFiles("./Data/Plugins/Commands/").Any(x => x.EndsWith(info[0] + ".dll"))) continue;
}
- catch { }
- }
-
- private async void LoadComboBox()
- {
- comboBox1.Items = null;
- commands = await PluginManager.Online.ServerCom.ReadTextFromFile("https://sethdiscordbot.000webhostapp.com/Storage/Discord%20Bot/Plugins");
- if (commands == null) return;
- string[] plugins = commands.ToArray();
- string OS;
- var OSG = Functions.GetOperatingSystem();
- if (OSG == PluginManager.Others.OperatingSystem.WINDOWS) OS = "Windows";
- else if (OSG == PluginManager.Others.OperatingSystem.LINUX) OS = "Linux";
- else OS = "MAC_OS";
- List data = new List();
- for (int i = 0; i < plugins.Length; i++)
+ catch
{
- if (!plugins[i].Contains(OS) || !plugins[i].Contains("Commands"))
- continue;
-
- string[] info = plugins[i].Split(',');
- try
- {
-
- if (System.IO.Directory.EnumerateFiles("./Data/Plugins/Commands/").Any(x => x.EndsWith(info[0] + ".dll")))
- continue;
- }
- catch { }
-
- data.Add($"{info[0]} - {info[1]} - {info[2]}");
}
- comboBox1.Items = data;
+ data.Add($"{info[0]} - {info[1]} - {info[2]}");
}
-
- private async Task Download()
- {
- if (comboBox1 == null || comboBox1.SelectedIndex == -1 || comboBox1.SelectedItem == null)
- return;
- string? pluginName = comboBox1?.SelectedItem?.ToString()?.Split('-')[0].Trim();
-
- if (pluginName == null) return;
- string? URL = (from s in commands
- where s.StartsWith(pluginName)
- select s.Split(',')[3].Trim()).FirstOrDefault();
-
- if (URL == null) return;
+ comboBox1.Items = data;
+ }
- IProgress progress = new Progress(async value =>
+ private async Task Download()
+ {
+ if (comboBox1 == null || comboBox1.SelectedIndex == -1 || comboBox1.SelectedItem == null) return;
+ var pluginName = comboBox1?.SelectedItem?.ToString()?.Split('-')[0].Trim();
+
+ if (pluginName == null) return;
+ var URL = (from s in commands
+ where s.StartsWith(pluginName)
+ select s.Split(',')[3].Trim()).FirstOrDefault();
+
+ if (URL == null) return;
+
+
+ IProgress progress = new Progress(async value =>
{
label1.Content = $"Downloading {pluginName} {MathF.Round(value, 2)}%";
if (value == 1f)
@@ -101,38 +99,38 @@ namespace DiscordBotGUI.Settings
await Task.Delay(5000);
label1.Content = "";
}
+
progressBar1.Value = value;
- });
-
- await PluginManager.Online.ServerCom.DownloadFileAsync(URL, "./Data/Plugins/Commands/" + pluginName + ".dll", progress);
- string? requirements = (from s in commands
- where s.StartsWith(pluginName) && s.Split(',').Length == 6
- select s.Split(',')[5].Trim()).FirstOrDefault();
-
- if (requirements == null) return;
- List req = await PluginManager.Online.ServerCom.ReadTextFromFile(requirements);
- if (req == null) return;
-
- foreach (var requirement in req)
- {
- string[] info = requirement.Split(',');
- pluginName = info[1];
- progress.Report(0);
- await PluginManager.Online.ServerCom.DownloadFileAsync(info[0], $"./{info[1]}", progress);
-
- await Task.Delay(1000);
-
- if (info[0].EndsWith(".zip"))
- {
- await Functions.ExtractArchive("./" + info[1], "./", progress);
- await Task.Delay(1000);
- }
-
}
+ );
- progress.Report(100f);
- label1.Content = "Downloaded";
- progressBar1.Value = 100;
+ await ServerCom.DownloadFileAsync(URL, "./Data/Plugins/Commands/" + pluginName + ".dll", progress);
+ var requirements = (from s in commands
+ where s.StartsWith(pluginName) && s.Split(',').Length == 6
+ select s.Split(',')[5].Trim()).FirstOrDefault();
+
+ if (requirements == null) return;
+ var req = await ServerCom.ReadTextFromFile(requirements);
+ if (req == null) return;
+
+ foreach (var requirement in req)
+ {
+ var info = requirement.Split(',');
+ pluginName = info[1];
+ progress.Report(0);
+ await ServerCom.DownloadFileAsync(info[0], $"./{info[1]}", progress);
+
+ await Task.Delay(1000);
+
+ if (info[0].EndsWith(".zip"))
+ {
+ await Functions.ExtractArchive("./" + info[1], "./", progress);
+ await Task.Delay(1000);
+ }
}
+
+ progress.Report(100f);
+ label1.Content = "Downloaded";
+ progressBar1.Value = 100;
}
}
diff --git a/DiscordBotGUI/Settings/Events.axaml b/DiscordBotGUI/Settings/Events.axaml
index c2d3077..57c0ca4 100644
--- a/DiscordBotGUI/Settings/Events.axaml
+++ b/DiscordBotGUI/Settings/Events.axaml
@@ -5,16 +5,19 @@
mc:Ignorable="d" d:DesignWidth="550" d:DesignHeight="200"
x:Class="DiscordBotGUI.Settings.Events"
Title="Events"
- Background="Transparent"
- TransparencyLevelHint="AcrylicBlur"
- ExtendClientAreaToDecorationsHint="True">
-
-
-
-
-
-
-
-
-
-
+ Background="Transparent"
+ TransparencyLevelHint="AcrylicBlur"
+ ExtendClientAreaToDecorationsHint="True">
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/DiscordBotGUI/Settings/Events.axaml.cs b/DiscordBotGUI/Settings/Events.axaml.cs
index 9a04c43..04eb48f 100644
--- a/DiscordBotGUI/Settings/Events.axaml.cs
+++ b/DiscordBotGUI/Settings/Events.axaml.cs
@@ -1,97 +1,94 @@
-using Avalonia;
-using Avalonia.Controls;
-using Avalonia.Markup.Xaml;
-
-using PluginManager.Others;
-
-using System.Collections.Generic;
using System;
-using System.Linq;
-using System.Reflection.Emit;
-using System.Threading.Tasks;
-
-using static PluginManager.Others.Console_Utilities;
+using System.Collections.Generic;
using System.IO;
+using System.Linq;
+using System.Threading.Tasks;
+using Avalonia.Controls;
+using PluginManager.Online;
+using PluginManager.Others;
+using OperatingSystem = PluginManager.Others.OperatingSystem;
-namespace DiscordBotGUI.Settings
+namespace DiscordBotGUI.Settings;
+
+public partial class Events : Window
{
- public partial class Events : Window
+ private List events = new();
+
+ public Events()
{
- List events = new List();
- public Events()
- {
- InitializeComponent();
- LoadData();
- LoadComboBox();
- button1.Click += async (sender, e) =>
- {
- await Download();
+ InitializeComponent();
+ LoadData();
+ LoadComboBox();
+ button1.Click += async (sender, e) => { await Download(); };
+ }
- };
+ private void LoadData()
+ {
+ //Read components from Commands Folder:
+ //textbox1 = new TextBox();
+ try
+ {
+ Directory.CreateDirectory("./Data/Plugins/Events/");
+ textbox1.IsReadOnly = false;
+ textbox1.Text = "";
+ var files = Directory.EnumerateFiles("./Data/Plugins/Events/");
+ if (files == null || files.Count() < 1) return;
+ foreach (var file in files) textbox1.Text += file.Split('/')[file.Split('/').Length - 1] + "\n";
}
-
- private void LoadData()
+ catch
{
- //Read components from Commands Folder:
- //textbox1 = new TextBox();
+ }
+ }
+
+ private async void LoadComboBox()
+ {
+ comboBox1.Items = null;
+ events = await ServerCom.ReadTextFromFile("https://sethdiscordbot.000webhostapp.com/Storage/Discord%20Bot/Plugins");
+ if (events == null) return;
+ var plugins = events.ToArray();
+ string OS;
+ var OSG = Functions.GetOperatingSystem();
+ if (OSG == OperatingSystem.WINDOWS)
+ OS = "Windows";
+ else if (OSG == OperatingSystem.LINUX)
+ OS = "Linux";
+ else
+ OS = "MAC_OS";
+ var data = new List();
+ for (var i = 0; i < plugins.Length; i++)
+ {
+ if (!plugins[i].Contains(OS) || !plugins[i].Contains("Event")) continue;
+
+ var info = plugins[i].Split(',');
try
{
- Directory.CreateDirectory("./Data/Plugins/Events/");
- textbox1.IsReadOnly = false;
- textbox1.Text = "";
- var files = System.IO.Directory.EnumerateFiles("./Data/Plugins/Events/");
- if (files == null || files.Count() < 1) return;
- foreach (var file in files)
- textbox1.Text += file.Split('/')[file.Split('/').Length - 1] + "\n";
+ if (Directory.EnumerateFiles("./Data/Plugins/Events/").Any(x => x.EndsWith(info[0] + ".dll"))) continue;
}
- catch { }
- }
- private async void LoadComboBox()
- {
- comboBox1.Items = null;
- events = await PluginManager.Online.ServerCom.ReadTextFromFile("https://sethdiscordbot.000webhostapp.com/Storage/Discord%20Bot/Plugins");
- if (events == null) return;
- string[] plugins = events.ToArray();
- string OS;
- var OSG = Functions.GetOperatingSystem();
- if (OSG == PluginManager.Others.OperatingSystem.WINDOWS) OS = "Windows";
- else if (OSG == PluginManager.Others.OperatingSystem.LINUX) OS = "Linux";
- else OS = "MAC_OS";
- List data = new List();
- for (int i = 0; i < plugins.Length; i++)
+ catch
{
- if (!plugins[i].Contains(OS) || !plugins[i].Contains("Event"))
- continue;
-
- string[] info = plugins[i].Split(',');
- try
- {
- if (System.IO.Directory.EnumerateFiles("./Data/Plugins/Events/").Any(x => x.EndsWith(info[0] + ".dll")))
- continue;
- }
- catch { }
-
-
- data.Add($"{info[0]} - {info[1]} - {info[2]}");
}
- comboBox1.Items = data;
+
+ data.Add($"{info[0]} - {info[1]} - {info[2]}");
}
- private async Task Download()
- {
- if (comboBox1 == null || comboBox1.SelectedIndex == -1 || comboBox1.SelectedItem == null)
- return;
- string? pluginName = comboBox1?.SelectedItem?.ToString()?.Split('-')[0].Trim();
- if (pluginName == null) return;
- string? URL = (from s in events
- where s.StartsWith(pluginName)
- select s.Split(',')[3].Trim()).FirstOrDefault();
+ comboBox1.Items = data;
+ }
- if (URL == null) return;
+ private async Task Download()
+ {
+ if (comboBox1 == null || comboBox1.SelectedIndex == -1 || comboBox1.SelectedItem == null) return;
+ var pluginName = comboBox1?.SelectedItem?.ToString()?.Split('-')[0].Trim();
+
+ if (pluginName == null) return;
+ var URL = (from s in events
+ where s.StartsWith(pluginName)
+ select s.Split(',')[3].Trim()).FirstOrDefault();
+
+ if (URL == null) return;
- IProgress progress = new Progress(async value =>
+ IProgress progress = new Progress(async value =>
{
label1.Content = $"Downloading {pluginName} {MathF.Round(value, 2)}%";
if (value == 1f)
@@ -103,37 +100,36 @@ namespace DiscordBotGUI.Settings
await Task.Delay(5000);
label1.Content = "";
}
+
progressBar1.Value = value;
- });
-
- await PluginManager.Online.ServerCom.DownloadFileAsync(URL, "./Data/Plugins/Events/" + pluginName + ".dll", progress);
- string? requirements = (from s in events
- where s.StartsWith(pluginName) && s.Split(',').Length == 6
- select s.Split(',')[5].Trim()).FirstOrDefault();
-
- if (requirements == null) return;
- List req = await PluginManager.Online.ServerCom.ReadTextFromFile(requirements);
- if (req == null) return;
-
- foreach (var requirement in req)
- {
- string[] info = requirement.Split(',');
- pluginName = info[1];
- progress.Report(0);
- await PluginManager.Online.ServerCom.DownloadFileAsync(info[0], $"./{info[1]}", progress);
-
- await Task.Delay(1000);
-
- if (info[0].EndsWith(".zip"))
- {
- await Functions.ExtractArchive("./" + info[1], "./", progress);
- await Task.Delay(1000);
- }
-
}
+ );
- label1.Content = "";
+ await ServerCom.DownloadFileAsync(URL, "./Data/Plugins/Events/" + pluginName + ".dll", progress);
+ var requirements = (from s in events
+ where s.StartsWith(pluginName) && s.Split(',').Length == 6
+ select s.Split(',')[5].Trim()).FirstOrDefault();
+ if (requirements == null) return;
+ var req = await ServerCom.ReadTextFromFile(requirements);
+ if (req == null) return;
+
+ foreach (var requirement in req)
+ {
+ var info = requirement.Split(',');
+ pluginName = info[1];
+ progress.Report(0);
+ await ServerCom.DownloadFileAsync(info[0], $"./{info[1]}", progress);
+
+ await Task.Delay(1000);
+
+ if (info[0].EndsWith(".zip"))
+ {
+ await Functions.ExtractArchive("./" + info[1], "./", progress);
+ await Task.Delay(1000);
+ }
}
+
+ label1.Content = "";
}
}
diff --git a/DiscordBotWithAPI.sln b/DiscordBotWithAPI.sln
index 3c8873a..d88b05a 100644
--- a/DiscordBotWithAPI.sln
+++ b/DiscordBotWithAPI.sln
@@ -13,18 +13,16 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Events", "Events", "{A290C0
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Commands", "Commands", "{449FA364-0B72-43FF-B3A3-806E2916200E}"
EndProject
-Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "CMD_LevelingSystem", "CMD_LevelingSystem\CMD_LevelingSystem.csproj", "{A48E8DC6-DBA2-4B47-9D59-46F4835F82CC}"
-EndProject
-Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "EVE_LevelingSystem", "EVE_LevelingSystem\EVE_LevelingSystem.csproj", "{1C1E7F3D-E05A-4A87-9789-62D98904C200}"
-EndProject
-Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "StartupEvents", "StartupEvents\StartupEvents.csproj", "{CE9DBF06-38A0-4192-8B3E-4009210D040D}"
-EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "CMD_Utils", "CMD_Utils\CMD_Utils.csproj", "{E26C87A4-3DD6-4B58-B14B-C8E086B852F9}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MusicCommands", "MusicCommands\MusicCommands.csproj", "{B1B4976E-5112-4217-B57B-3A03C5207B6E}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DiscordBotGUI", "DiscordBotGUI\DiscordBotGUI.csproj", "{7B5899F0-0218-4537-8C74-6210ED2D3690}"
EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EVE_LevelingSystem", "EVE_LevelingSystem\EVE_LevelingSystem.csproj", "{EEC445DC-0C4B-43EA-8694-606BA0390B77}"
+EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CMD_LevelingSystem", "CMD_LevelingSystem\CMD_LevelingSystem.csproj", "{1A4E49FF-9A0A-4C54-AF35-CFFBA64353D9}"
+EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
@@ -39,18 +37,6 @@ Global
{EDD4D9B3-98DD-4367-A09F-D1C5ACB61132}.Debug|Any CPU.Build.0 = Debug|Any CPU
{EDD4D9B3-98DD-4367-A09F-D1C5ACB61132}.Release|Any CPU.ActiveCfg = Release|Any CPU
{EDD4D9B3-98DD-4367-A09F-D1C5ACB61132}.Release|Any CPU.Build.0 = Release|Any CPU
- {A48E8DC6-DBA2-4B47-9D59-46F4835F82CC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
- {A48E8DC6-DBA2-4B47-9D59-46F4835F82CC}.Debug|Any CPU.Build.0 = Debug|Any CPU
- {A48E8DC6-DBA2-4B47-9D59-46F4835F82CC}.Release|Any CPU.ActiveCfg = Release|Any CPU
- {A48E8DC6-DBA2-4B47-9D59-46F4835F82CC}.Release|Any CPU.Build.0 = Release|Any CPU
- {1C1E7F3D-E05A-4A87-9789-62D98904C200}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
- {1C1E7F3D-E05A-4A87-9789-62D98904C200}.Debug|Any CPU.Build.0 = Debug|Any CPU
- {1C1E7F3D-E05A-4A87-9789-62D98904C200}.Release|Any CPU.ActiveCfg = Release|Any CPU
- {1C1E7F3D-E05A-4A87-9789-62D98904C200}.Release|Any CPU.Build.0 = Release|Any CPU
- {CE9DBF06-38A0-4192-8B3E-4009210D040D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
- {CE9DBF06-38A0-4192-8B3E-4009210D040D}.Debug|Any CPU.Build.0 = Debug|Any CPU
- {CE9DBF06-38A0-4192-8B3E-4009210D040D}.Release|Any CPU.ActiveCfg = Release|Any CPU
- {CE9DBF06-38A0-4192-8B3E-4009210D040D}.Release|Any CPU.Build.0 = Release|Any CPU
{E26C87A4-3DD6-4B58-B14B-C8E086B852F9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{E26C87A4-3DD6-4B58-B14B-C8E086B852F9}.Debug|Any CPU.Build.0 = Debug|Any CPU
{E26C87A4-3DD6-4B58-B14B-C8E086B852F9}.Release|Any CPU.ActiveCfg = Release|Any CPU
@@ -63,6 +49,14 @@ Global
{7B5899F0-0218-4537-8C74-6210ED2D3690}.Debug|Any CPU.Build.0 = Debug|Any CPU
{7B5899F0-0218-4537-8C74-6210ED2D3690}.Release|Any CPU.ActiveCfg = Release|Any CPU
{7B5899F0-0218-4537-8C74-6210ED2D3690}.Release|Any CPU.Build.0 = Release|Any CPU
+ {EEC445DC-0C4B-43EA-8694-606BA0390B77}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {EEC445DC-0C4B-43EA-8694-606BA0390B77}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {EEC445DC-0C4B-43EA-8694-606BA0390B77}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {EEC445DC-0C4B-43EA-8694-606BA0390B77}.Release|Any CPU.Build.0 = Release|Any CPU
+ {1A4E49FF-9A0A-4C54-AF35-CFFBA64353D9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {1A4E49FF-9A0A-4C54-AF35-CFFBA64353D9}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {1A4E49FF-9A0A-4C54-AF35-CFFBA64353D9}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {1A4E49FF-9A0A-4C54-AF35-CFFBA64353D9}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
@@ -70,11 +64,10 @@ Global
GlobalSection(NestedProjects) = preSolution
{A290C028-77C4-4D1D-AB43-DDFE6ABD9012} = {1862ABD5-7C30-4F15-A561-45AC8A9CA10E}
{449FA364-0B72-43FF-B3A3-806E2916200E} = {1862ABD5-7C30-4F15-A561-45AC8A9CA10E}
- {A48E8DC6-DBA2-4B47-9D59-46F4835F82CC} = {449FA364-0B72-43FF-B3A3-806E2916200E}
- {1C1E7F3D-E05A-4A87-9789-62D98904C200} = {A290C028-77C4-4D1D-AB43-DDFE6ABD9012}
- {CE9DBF06-38A0-4192-8B3E-4009210D040D} = {A290C028-77C4-4D1D-AB43-DDFE6ABD9012}
{E26C87A4-3DD6-4B58-B14B-C8E086B852F9} = {449FA364-0B72-43FF-B3A3-806E2916200E}
{B1B4976E-5112-4217-B57B-3A03C5207B6E} = {449FA364-0B72-43FF-B3A3-806E2916200E}
+ {EEC445DC-0C4B-43EA-8694-606BA0390B77} = {A290C028-77C4-4D1D-AB43-DDFE6ABD9012}
+ {1A4E49FF-9A0A-4C54-AF35-CFFBA64353D9} = {449FA364-0B72-43FF-B3A3-806E2916200E}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {3FB3C5DE-ED21-4D2E-ABDD-3A00EE4A2FFF}
diff --git a/EVE_LevelingSystem/Core.cs b/EVE_LevelingSystem/Core.cs
deleted file mode 100644
index 10314f4..0000000
--- a/EVE_LevelingSystem/Core.cs
+++ /dev/null
@@ -1,62 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.IO;
-using System.Threading.Tasks;
-
-public class Core
-{
-
- public static Dictionary playerMessages = new Dictionary();
-
- private static readonly string folder = @".\Data\Resources\LevelingSystem\";
-
- public static int GetLevel(ulong id) => int.Parse(File.ReadAllText(Path.Combine(folder, id.ToString() + ".data")).Split(',')[0].Split('=')[1]);
-
-
- public static Int64 GetExp(ulong id) => Int64.Parse(File.ReadAllText(Path.Combine(folder, id.ToString() + ".data")).Split(',')[1].Split('=')[1]);
-
-
- public static Int64 GetReqEXP(ulong id) => Int64.Parse(File.ReadAllText(Path.Combine(folder, id.ToString() + ".data")).Split(',')[2].Split('=')[1]);
- public static void SaveData(ulong id, int lv, Int64 cexp, Int64 rexp)
- {
- Directory.CreateDirectory(folder);
- File.WriteAllText(Path.Combine(folder, id.ToString() + ".data"), $"Level={lv},EXP={cexp},REXP={rexp}");
- }
- private static Int64 NextLevelXP(int level)
- {
- return (level * level) + 2 * level + 75;
- }
-
- public static (bool, int) MessageSent(ulong id, int messageLength)
- {
- WaitForTimeToRemoveFromList(id, 60);
-
- if (!File.Exists(Path.Combine(folder, id.ToString() + ".data")))
- {
- SaveData(id, 0, 0, 0);
- }
- Int64 cEXp = GetExp(id);
- Int64 rExp = GetReqEXP(id);
- int random = new System.Random().Next(3, 6) + messageLength;
- cEXp += random;
- if (cEXp >= rExp)
- {
- cEXp = cEXp - rExp;
- int lv = GetLevel(id);
- rExp = NextLevelXP(lv);
- lv++;
- SaveData(id, lv, cEXp, rExp);
- return (true, lv);
- }
-
- SaveData(id, GetLevel(id), cEXp, rExp);
- return (false, -1);
- }
-
- public static async void WaitForTimeToRemoveFromList(ulong id, int time_seconds)
- {
- await Task.Delay(time_seconds * 1000);
- playerMessages.Remove(id);
- }
-
-}
\ No newline at end of file
diff --git a/EVE_LevelingSystem/Data.cs b/EVE_LevelingSystem/Data.cs
deleted file mode 100644
index 44ffb76..0000000
--- a/EVE_LevelingSystem/Data.cs
+++ /dev/null
@@ -1,24 +0,0 @@
-using Discord.WebSocket;
-
-using System;
-using System.IO;
-public static class Data
-{
- private static readonly string folder = @".\Data\Resources\LevelingSystem\";
- public static void registerPlayer(SocketGuildUser user)
- {
- ulong id = user.Id;
- Directory.CreateDirectory(folder);
- File.WriteAllText(Path.Combine(folder, id.ToString() + ".data"), "Level=0,EXP=0,REXP=100");
- }
-
- public static int GetLevel(ulong id) => int.Parse(File.ReadAllText(Path.Combine(folder, id.ToString() + ".data")).Split(',')[0].Split('=')[1]);
-
-
- public static Int64 GetExp(ulong id) => Int64.Parse(File.ReadAllText(Path.Combine(folder, id.ToString() + ".data")).Split(',')[1].Split('=')[1]);
-
-
- public static Int64 GetReqEXP(ulong id) => Int64.Parse(File.ReadAllText(Path.Combine(folder, id.ToString() + ".data")).Split(',')[2].Split('=')[1]);
-
-
-}
diff --git a/EVE_LevelingSystem/EVE_LevelingSystem.csproj b/EVE_LevelingSystem/EVE_LevelingSystem.csproj
index 0f762e8..ce1a63c 100644
--- a/EVE_LevelingSystem/EVE_LevelingSystem.csproj
+++ b/EVE_LevelingSystem/EVE_LevelingSystem.csproj
@@ -1,17 +1,20 @@
-
+
-
- net6.0
-
+
+ net6.0
+ enable
+ enable
+ ..\DiscordBot\bin\Debug\net6.0\Data\Plugins\Events\LevelingSystem
+
-
- ..\BUILDS\
- none
- false
-
+
+
+
+
+
-
-
-
+
+
+
diff --git a/EVE_LevelingSystem/Level.cs b/EVE_LevelingSystem/Level.cs
new file mode 100644
index 0000000..f4a9c6b
--- /dev/null
+++ b/EVE_LevelingSystem/Level.cs
@@ -0,0 +1,54 @@
+using Discord;
+using Discord.WebSocket;
+using EVE_LevelingSystem.LevelingSystemCore;
+using PluginManager;
+using PluginManager.Interfaces;
+using PluginManager.Others;
+
+namespace EVE_LevelingSystem
+{
+ internal class Level : DBEvent
+ {
+ public string name => "Leveling System Event Handler";
+ public string description => "The Leveling System Event Handler";
+ internal static Settings globalSettings = new();
+
+
+ public async void Start(DiscordSocketClient client)
+ {
+ Directory.CreateDirectory("./Data/Resources/LevelingSystem");
+ Config.AddValueToVariables("LevelingSystemPath", "./Data/Resources/LevelingSystem", true);
+ Config.AddValueToVariables("LevelingSystemSettingsFile", "./Data/Resources/LevelingSystemSettings.txt", true);
+
+ if (!File.Exists(Config.GetValue("LevelingSystemSettingsFile")))
+ {
+ globalSettings = new Settings { TimeToWaitBetweenMessages = 5 };
+ await Functions.SaveToJsonFile(Config.GetValue("LevelingSystemSettingsFile"), globalSettings);
+ }
+ else
+ globalSettings = await Functions.ConvertFromJson(Config.GetValue("LevelingSystemSettingsFile"));
+
+ // Console.WriteLine(globalSettings.TimeToWaitBetweenMessages);
+ client.MessageReceived += ClientOnMessageReceived;
+ }
+
+ private async Task ClientOnMessageReceived(SocketMessage arg)
+ {
+ if (arg.Author.IsBot || arg.IsTTS || arg.Content.StartsWith(Config.GetValue("prefix"))) return;
+ string userID = arg.Author.Id.ToString();
+ User user;
+ if (File.Exists($"{Config.GetValue("LevelingSystemPath")}/{userID}.dat"))
+ {
+ user = await Functions.ConvertFromJson(Config.GetValue("LevelingSystemPath")! + $"/{userID}.dat");
+ // Console.WriteLine(Config.GetValue("LevelingSystemPath"));
+ if (user.AddEXP()) await arg.Channel.SendMessageAsync($"{arg.Author.Mention} is now level {user.CurrentLevel}");
+ await Functions.SaveToJsonFile(Config.GetValue("LevelingSystemPath") + $"/{userID}.dat", user);
+ return;
+ }
+
+ user = new User { CurrentEXP = 0, CurrentLevel = 1, RequiredEXPToLevelUp = LevelCalculator.GetNextLevelRequiredEXP(1), user = new DiscordUser { DiscordTag = arg.Author.DiscriminatorValue, userID = arg.Author.Id, Username = arg.Author.Username } };
+ if (user.AddEXP()) await arg.Channel.SendMessageAsync($"{arg.Author.Mention} is now level {user.CurrentLevel}");
+ await Functions.SaveToJsonFile($"{Config.GetValue("LevelingSystemPath")}/{userID}.dat", user);
+ }
+ }
+}
diff --git a/EVE_LevelingSystem/LevelingSystem.cs b/EVE_LevelingSystem/LevelingSystem.cs
deleted file mode 100644
index 674da2a..0000000
--- a/EVE_LevelingSystem/LevelingSystem.cs
+++ /dev/null
@@ -1,56 +0,0 @@
-using System.Threading.Tasks;
-
-using Discord.WebSocket;
-
-using PluginManager.Others;
-using PluginManager.Interfaces;
-using PluginManager.LanguageSystem;
-using PluginManager.Items;
-using System;
-
-public class LevelingSystem : DBEvent
-{
- public string name => "Leveling System";
-
- public string description => "Leveling System Event";
-
- public void Start(DiscordSocketClient client)
- {
-
- ConsoleCommandsHandler.AddCommand("lvl", "Test command", async (args) =>
- {
- Console.WriteLine("Leveling system command");
-
- });
-
- client.MessageReceived += Client_MessageReceived;
- }
-
- private async Task Client_MessageReceived(SocketMessage arg)
- {
- if (arg.Author.IsBot || arg.Attachments.Count > 0 ||
- arg.Content.StartsWith
- (
- Functions.readCodeFromFile
- (
- fileName: System.IO.Path.Combine(Functions.dataFolder, "DiscordBotCore.data"),
- Code: "BOT_PREFIX",
- separator: '='
- )
- )
- )
- return;
- //Console_Utilities.WriteColorText("Message from : " + arg.Author.Username);
- if (Core.playerMessages.ContainsKey(arg.Author.Id))
- return;
-
- (bool x, int lv) = Core.MessageSent(arg.Author.Id, arg.Content.Length);
- Core.playerMessages.Add(arg.Author.Id, arg.Content);
- if (x)
- if (Language.ActiveLanguage != null)
- await arg.Channel.SendMessageAsync(Language.ActiveLanguage.LanguageWords["DB_EVENT_LEVEL_SYSTEM_LEVEL_UP"].Replace("{0}", lv.ToString()));
- else await arg.Channel.SendMessageAsync("You've successfully leveled up to level " + lv);
-
- }
-}
-
diff --git a/EVE_LevelingSystem/LevelingSystemCore/LevelCalculator.cs b/EVE_LevelingSystem/LevelingSystemCore/LevelCalculator.cs
new file mode 100644
index 0000000..733adac
--- /dev/null
+++ b/EVE_LevelingSystem/LevelingSystemCore/LevelCalculator.cs
@@ -0,0 +1,57 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+using PluginManager;
+
+namespace EVE_LevelingSystem.LevelingSystemCore
+{
+ internal static class LevelCalculator
+ {
+ internal static List OnWaitingList = new();
+
+ internal static Int64 GetNextLevelRequiredEXP(int currentLevel)
+ {
+ return currentLevel * 8 + 24;
+ }
+
+ internal static void LevelUp(this User user)
+ {
+ user.CurrentEXP = 0;
+ user.RequiredEXPToLevelUp = GetNextLevelRequiredEXP(user.CurrentLevel);
+ user.CurrentLevel++;
+ }
+
+ internal static bool AddEXP(this User user)
+ {
+ if (OnWaitingList.Contains(user.user.userID.ToString())) return false;
+ Random r = new Random();
+ int exp = r.Next(2, 12);
+ Int64 userXP = user.CurrentEXP;
+ Int64 reqEXP = user.RequiredEXPToLevelUp;
+ if (userXP + exp >= reqEXP)
+ {
+ user.LevelUp();
+ user.CurrentEXP = exp - (reqEXP - userXP);
+ Console.WriteLine("Level up");
+ return true;
+ }
+
+ user.CurrentEXP += exp;
+
+ OnWaitingList.Add(user.user.userID.ToString());
+
+
+ new Thread(() =>
+ {
+ int minutesToWait = Level.globalSettings.TimeToWaitBetweenMessages;
+ Thread.Sleep(60000 * minutesToWait);
+ OnWaitingList.Remove(user.user.userID.ToString());
+ }
+ );
+
+ return false;
+ }
+ }
+}
diff --git a/EVE_LevelingSystem/LevelingSystemCore/User.cs b/EVE_LevelingSystem/LevelingSystemCore/User.cs
new file mode 100644
index 0000000..b857392
--- /dev/null
+++ b/EVE_LevelingSystem/LevelingSystemCore/User.cs
@@ -0,0 +1,20 @@
+using Discord;
+using Discord.WebSocket;
+
+namespace EVE_LevelingSystem.LevelingSystemCore
+{
+ public class DiscordUser
+ {
+ public string Username { get; set; }
+ public ushort DiscordTag { get; set; }
+ public ulong userID { get; set; }
+ }
+
+ public class User
+ {
+ public DiscordUser user { get; set; }
+ public int CurrentLevel { get; set; }
+ public long CurrentEXP { get; set; }
+ public long RequiredEXPToLevelUp { get; set; }
+ }
+}
\ No newline at end of file
diff --git a/EVE_LevelingSystem/Settings.cs b/EVE_LevelingSystem/Settings.cs
new file mode 100644
index 0000000..38a8caa
--- /dev/null
+++ b/EVE_LevelingSystem/Settings.cs
@@ -0,0 +1,13 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace EVE_LevelingSystem
+{
+ public class Settings
+ {
+ public int TimeToWaitBetweenMessages { get; set; }
+ }
+}
diff --git a/MusicCommands/Data.cs b/MusicCommands/Data.cs
index f2cc1de..30a79b4 100644
--- a/MusicCommands/Data.cs
+++ b/MusicCommands/Data.cs
@@ -1,15 +1,13 @@
using Discord;
using Discord.Audio;
-
using MusicCommands;
-namespace CMD_Utils.Music
-{
- internal static class Data
- {
- internal static IAudioClient audioClient = null;
- internal static IVoiceChannel voiceChannel = null;
+namespace CMD_Utils.Music;
- internal static MusicPlayer CurrentlyRunning = null;
- }
+internal static class Data
+{
+ internal static IAudioClient audioClient = null;
+ internal static IVoiceChannel voiceChannel = null;
+
+ internal static MusicPlayer CurrentlyRunning = null;
}
diff --git a/MusicCommands/Leave.cs b/MusicCommands/Leave.cs
index 1b8d221..11fb2dd 100644
--- a/MusicCommands/Leave.cs
+++ b/MusicCommands/Leave.cs
@@ -1,39 +1,31 @@
using Discord.Commands;
using Discord.WebSocket;
-
using PluginManager.Interfaces;
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-using System.Threading.Tasks;
+namespace CMD_Utils.Music;
-namespace CMD_Utils.Music
+internal class Leave : DBCommand
{
- class Leave : DBCommand
+ public string Command => "leave";
+
+ public string Description => "Leave the voice channel";
+
+ public string Usage => "leave";
+
+ public bool canUseDM => false;
+
+ public bool canUseServer => true;
+
+ public bool requireAdmin => false;
+
+ public async void Execute(SocketCommandContext context, SocketMessage message, DiscordSocketClient client, bool isDM)
{
- public string Command => "leave";
-
- public string Description => "Leave the voice channel";
-
- public string Usage => "leave";
-
- public bool canUseDM => false;
-
- public bool canUseServer => true;
-
- public bool requireAdmin => false;
-
- public async void Execute(SocketCommandContext context, SocketMessage message, DiscordSocketClient client, bool isDM)
+ if (Data.audioClient is not null && Data.voiceChannel is not null)
{
- if (Data.audioClient is not null && Data.voiceChannel is not null)
- {
- Data.CurrentlyRunning.Stop();
- Data.CurrentlyRunning = null;
- await Data.audioClient.StopAsync();
- await Data.voiceChannel.DisconnectAsync();
- }
+ Data.CurrentlyRunning.Stop();
+ Data.CurrentlyRunning = null;
+ await Data.audioClient.StopAsync();
+ await Data.voiceChannel.DisconnectAsync();
}
}
}
diff --git a/MusicCommands/MusicPlayer.cs b/MusicCommands/MusicPlayer.cs
index 7064694..e50ab8f 100644
--- a/MusicCommands/MusicPlayer.cs
+++ b/MusicCommands/MusicPlayer.cs
@@ -1,121 +1,118 @@
-using CMD_Utils.Music;
-
-using PluginManager.Others;
-
-using System;
+using System;
using System.IO;
-using System.Net;
using System.Net.Http;
-using System.Net.Http.Headers;
using System.Threading;
using System.Threading.Tasks;
+using CMD_Utils.Music;
+using PluginManager.Others;
-namespace MusicCommands
+namespace MusicCommands;
+
+internal class MusicPlayer
{
- class MusicPlayer
+ public MusicPlayer(Stream input, Stream output)
{
- public Stream inputStream { get; private set; } // from FFMPEG
- public Stream outputStream { get; private set; } // to Voice Channel
- public MusicPlayer(Stream input, Stream output)
- {
- inputStream = input;
- outputStream = output;
- }
+ inputStream = input;
+ outputStream = output;
+ }
- public MusicPlayer(Stream output)
- {
- inputStream = null;
- outputStream = output;
- }
+ public MusicPlayer(Stream output)
+ {
+ inputStream = null;
+ outputStream = output;
+ }
- public bool Paused { get; set; }
- private bool _stop { get; set; }
- public void Stop()
- {
- _stop = true;
- }
+ public Stream inputStream { get; } // from FFMPEG
+ public Stream outputStream { get; } // to Voice Channel
- public async Task StartSendAudioFromLink(string URL)
- {
+ public bool Paused { get; set; }
+ private bool _stop { get; set; }
- /* using (HttpClient client = new HttpClient())
- using (HttpResponseMessage response = await client.GetAsync(URL))
- using (var content = response.Content)
- {
- await (await content.ReadAsStreamAsync()).CopyToAsync(outputStream);
- }*/
+ public void Stop()
+ {
+ _stop = true;
+ }
-
- Stream ms = new MemoryStream();
- int bsize = 512;
- new Thread(async delegate (object o)
+ public async Task StartSendAudioFromLink(string URL)
+ {
+ /* using (HttpClient client = new HttpClient())
+ using (HttpResponseMessage response = await client.GetAsync(URL))
+ using (var content = response.Content)
{
- var response = await new HttpClient().GetAsync(URL);
- using (var stream = await response.Content.ReadAsStreamAsync())
- {
- byte[] buffer = new byte[bsize];
- int read;
- while ((read = stream.Read(buffer, 0, buffer.Length)) > 0)
- {
- var pos = ms.Position;
- ms.Position = ms.Length;
- ms.Write(buffer, 0, read);
- ms.Position = pos;
- }
- }
- }).Start();
- Console.Write("Reading data: ");
- while (ms.Length < bsize * 10)
+ await (await content.ReadAsStreamAsync()).CopyToAsync(outputStream);
+ }*/
+
+
+ Stream ms = new MemoryStream();
+ var bsize = 512;
+ new Thread(async delegate(object o)
{
- await Task.Delay(1000);
- Console.Title = "Reading data: " + ms.Length + " bytes read of " + bsize * 10;
- Console.Write(".");
+ var response = await new HttpClient().GetAsync(URL);
+ using (var stream = await response.Content.ReadAsStreamAsync())
+ {
+ var buffer = new byte[bsize];
+ int read;
+ while ((read = stream.Read(buffer, 0, buffer.Length)) > 0)
+ {
+ var pos = ms.Position;
+ ms.Position = ms.Length;
+ ms.Write(buffer, 0, read);
+ ms.Position = pos;
+ }
+ }
}
- Console.WriteLine("\nDone");
- ms.Position = 0;
-
- _stop = false;
- Paused = false;
-
- while (!_stop)
- {
- if (Paused) continue;
- byte[] buffer = new byte[bsize];
- int read = await ms.ReadAsync(buffer, 0, buffer.Length);
- if (read > 0)
- await outputStream.WriteAsync(buffer, 0, read);
- else break;
- }
-
-
+ ).Start();
+ Console.Write("Reading data: ");
+ while (ms.Length < bsize * 10)
+ {
+ await Task.Delay(1000);
+ Console.Title = "Reading data: " + ms.Length + " bytes read of " + bsize * 10;
+ Console.Write(".");
}
- public async Task StartSendAudio()
- {
- Paused = false;
- _stop = false;
- while (!_stop)
- {
- if (Paused) continue;
- int bsize = 512;
- byte[] buffer = new byte[bsize];
- var bcount = await inputStream.ReadAsync(buffer, 0, bsize);
- if (bcount <= 0)
- {
- Stop();
- Data.CurrentlyRunning = null;
- break;
- }
- try
- {
- await outputStream.WriteAsync(buffer, 0, bcount);
- }
- catch (Exception ex)
- {
- await outputStream.FlushAsync();
- Functions.WriteLogFile(ex.ToString());
- }
+ Console.WriteLine("\nDone");
+ ms.Position = 0;
+ _stop = false;
+ Paused = false;
+
+ while (!_stop)
+ {
+ if (Paused) continue;
+ var buffer = new byte[bsize];
+ var read = await ms.ReadAsync(buffer, 0, buffer.Length);
+ if (read > 0)
+ await outputStream.WriteAsync(buffer, 0, read);
+ else
+ break;
+ }
+ }
+
+ public async Task StartSendAudio()
+ {
+ Paused = false;
+ _stop = false;
+ while (!_stop)
+ {
+ if (Paused) continue;
+ var bsize = 512;
+ var buffer = new byte[bsize];
+ var bcount = await inputStream.ReadAsync(buffer, 0, bsize);
+ if (bcount <= 0)
+ {
+ Stop();
+ Data.CurrentlyRunning = null;
+ break;
+ }
+
+ try
+ {
+ await outputStream.WriteAsync(buffer, 0, bcount);
+ }
+ catch (Exception ex)
+ {
+ await outputStream.FlushAsync();
+ Functions.WriteLogFile(ex.ToString());
}
}
}
diff --git a/MusicCommands/Pause.cs b/MusicCommands/Pause.cs
index 457b8b8..035e8f7 100644
--- a/MusicCommands/Pause.cs
+++ b/MusicCommands/Pause.cs
@@ -1,27 +1,25 @@
using Discord.Commands;
using Discord.WebSocket;
-
using PluginManager.Interfaces;
-namespace CMD_Utils.Music
+namespace CMD_Utils.Music;
+
+internal class Pause : DBCommand
{
- class Pause : DBCommand
+ public string Command => "pause";
+
+ public string Description => "Pause the music";
+
+ public string Usage => "pause";
+
+ public bool canUseDM => false;
+
+ public bool canUseServer => true;
+
+ public bool requireAdmin => false;
+
+ public void Execute(SocketCommandContext context, SocketMessage message, DiscordSocketClient client, bool isDM)
{
- public string Command => "pause";
-
- public string Description => "Pause the music";
-
- public string Usage => "pause";
-
- public bool canUseDM => false;
-
- public bool canUseServer => true;
-
- public bool requireAdmin => false;
-
- public void Execute(SocketCommandContext context, SocketMessage message, DiscordSocketClient client, bool isDM)
- {
- Data.CurrentlyRunning.Paused = true;
- }
+ Data.CurrentlyRunning.Paused = true;
}
}
diff --git a/MusicCommands/Play.cs b/MusicCommands/Play.cs
index eb666c6..26d9a0f 100644
--- a/MusicCommands/Play.cs
+++ b/MusicCommands/Play.cs
@@ -1,70 +1,63 @@
-using Discord;
+using System;
+using System.Diagnostics;
+using System.IO;
+using Discord;
using Discord.Audio;
using Discord.Commands;
using Discord.WebSocket;
-
using MusicCommands;
-
using PluginManager.Interfaces;
using PluginManager.Others;
-using System;
-using System.Diagnostics;
-using System.IO;
+namespace CMD_Utils.Music;
-namespace CMD_Utils.Music
+internal class Play : DBCommand
{
- class Play : DBCommand
+ public string Command => "fplay";
+
+ public string Description => "Play music from a file";
+
+ public string Usage => "fplay [name]";
+
+ public bool canUseDM => false;
+
+ public bool canUseServer => true;
+
+ public bool requireAdmin => false;
+
+ public async void Execute(SocketCommandContext context, SocketMessage message, DiscordSocketClient client, bool isDM)
{
- public string Command => "fplay";
-
- public string Description => "Play music from a file";
-
- public string Usage => "fplay [name]";
-
- public bool canUseDM => false;
-
- public bool canUseServer => true;
-
- public bool requireAdmin => false;
-
- public async void Execute(SocketCommandContext context, SocketMessage message, DiscordSocketClient client, bool isDM)
+ var path = "./Music";
+ var FileName = Functions.GetArguments(message).ToArray().MergeStrings(0);
+ path += "/" + FileName + ".mp3";
+ if (!File.Exists(path))
{
- string path = "./Music";
- string FileName = Functions.GetArguments(message).ToArray().MergeStrings(0);
- path += "/" + FileName + ".mp3";
- if (!File.Exists(path))
- {
- Console.WriteLine("Unknown path " + path);
- return;
- }
-
-
- Data.voiceChannel = (context.User as IGuildUser)?.VoiceChannel;
- if (Data.voiceChannel == null) { await context.Channel.SendMessageAsync("User must be in a voice channel, or a voice channel must be passed as an argument."); return; }
-
- Data.audioClient = await Data.voiceChannel.ConnectAsync();
-
- using (var ffmpeg = CreateStream(path))
- using (var output = ffmpeg.StandardOutput.BaseStream)
- using (var discord = Data.audioClient.CreatePCMStream(AudioApplication.Mixed))
- {
- if (Data.CurrentlyRunning != null)
- Data.CurrentlyRunning.Stop();
- Data.CurrentlyRunning = new MusicPlayer(output, discord);
- await Data.CurrentlyRunning.StartSendAudio();
- }
+ Console.WriteLine("Unknown path " + path);
+ return;
}
- private Process CreateStream(string path)
+
+ Data.voiceChannel = (context.User as IGuildUser)?.VoiceChannel;
+ if (Data.voiceChannel == null)
{
- return Process.Start(new ProcessStartInfo
- {
- FileName = "ffmpeg",
- Arguments = $"-hide_banner -loglevel panic -i \"{path}\" -ac 2 -f s16le -ar 48000 pipe:1",
- UseShellExecute = false,
- RedirectStandardOutput = true,
- });
+ await context.Channel.SendMessageAsync("User must be in a voice channel, or a voice channel must be passed as an argument.");
+ return;
+ }
+
+ Data.audioClient = await Data.voiceChannel.ConnectAsync();
+
+ using (var ffmpeg = CreateStream(path))
+ using (var output = ffmpeg.StandardOutput.BaseStream)
+ using (var discord = Data.audioClient.CreatePCMStream(AudioApplication.Mixed))
+ {
+ if (Data.CurrentlyRunning != null) Data.CurrentlyRunning.Stop();
+ Data.CurrentlyRunning = new MusicPlayer(output, discord);
+ await Data.CurrentlyRunning.StartSendAudio();
}
}
+
+ private Process CreateStream(string path)
+ {
+ return Process.Start(new ProcessStartInfo { FileName = "ffmpeg", Arguments = $"-hide_banner -loglevel panic -i \"{path}\" -ac 2 -f s16le -ar 48000 pipe:1", UseShellExecute = false, RedirectStandardOutput = true });
+ }
}
diff --git a/MusicCommands/Unpause.cs b/MusicCommands/Unpause.cs
index e585dee..cc004c7 100644
--- a/MusicCommands/Unpause.cs
+++ b/MusicCommands/Unpause.cs
@@ -1,35 +1,26 @@
using CMD_Utils.Music;
-
using Discord.Commands;
using Discord.WebSocket;
-
using PluginManager.Interfaces;
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-using System.Threading.Tasks;
+namespace MusicCommands;
-namespace MusicCommands
+internal class Unpause : DBCommand
{
- class Unpause : DBCommand
+ public string Command => "unpause";
+
+ public string Description => "Unpause the music";
+
+ public string Usage => "unpause";
+
+ public bool canUseDM => false;
+
+ public bool canUseServer => true;
+
+ public bool requireAdmin => false;
+
+ public void Execute(SocketCommandContext context, SocketMessage message, DiscordSocketClient client, bool isDM)
{
- public string Command => "unpause";
-
- public string Description => "Unpause the music";
-
- public string Usage => "unpause";
-
- public bool canUseDM => false;
-
- public bool canUseServer => true;
-
- public bool requireAdmin => false;
-
- public void Execute(SocketCommandContext context, SocketMessage message, DiscordSocketClient client, bool isDM)
- {
- Data.CurrentlyRunning.Paused = false;
- }
+ Data.CurrentlyRunning.Paused = false;
}
}
diff --git a/MusicCommands/lplay.cs b/MusicCommands/lplay.cs
index ed006a7..14e51b3 100644
--- a/MusicCommands/lplay.cs
+++ b/MusicCommands/lplay.cs
@@ -1,52 +1,50 @@
using CMD_Utils.Music;
+using Discord;
using Discord.Audio;
using Discord.Commands;
using Discord.WebSocket;
-using Discord;
-
using PluginManager.Interfaces;
-namespace MusicCommands
+namespace MusicCommands;
+
+internal class lplay : DBCommand
{
- class lplay : DBCommand
+ public string Command => "lplay";
+
+ public string Description => "Play music from a link";
+
+ public string Usage => "lplay [url]";
+
+ public bool canUseDM => false;
+
+ public bool canUseServer => false;
+
+ public bool requireAdmin => false;
+
+ public async void Execute(SocketCommandContext context, SocketMessage message, DiscordSocketClient client, bool isDM)
{
- public string Command => "lplay";
-
- public string Description => "Play music from a link";
-
- public string Usage => "lplay [url]";
-
- public bool canUseDM => false;
-
- public bool canUseServer => false;
-
- public bool requireAdmin => false;
-
- public async void Execute(SocketCommandContext context, SocketMessage message, DiscordSocketClient client, bool isDM)
+ var URL = message.Content.Split(' ')[1];
+ if (!URL.EndsWith(".mp3") && !URL.EndsWith(".wav") && !URL.EndsWith(".flac") && !URL.EndsWith(".ogg"))
{
- string URL = message.Content.Split(' ')[1];
- if (!URL.EndsWith(".mp3") && !URL.EndsWith(".wav") && !URL.EndsWith(".flac") && !URL.EndsWith(".ogg"))
- {
- await message.Channel.SendMessageAsync("Invalid URL");
- return;
- }
-
- Data.voiceChannel = (context.User as IGuildUser)?.VoiceChannel;
- if (Data.voiceChannel == null) { await context.Channel.SendMessageAsync("User must be in a voice channel, or a voice channel must be passed as an argument."); return; }
-
- Data.audioClient = await Data.voiceChannel.ConnectAsync();
-
- using (var discord = Data.audioClient.CreatePCMStream(AudioApplication.Mixed))
- {
-
-
- await message.Channel.SendMessageAsync("Loading...");
-
- Data.CurrentlyRunning = new MusicPlayer(discord);
- await Data.CurrentlyRunning.StartSendAudioFromLink(URL);
-
- }
+ await message.Channel.SendMessageAsync("Invalid URL");
+ return;
}
+ Data.voiceChannel = (context.User as IGuildUser)?.VoiceChannel;
+ if (Data.voiceChannel == null)
+ {
+ await context.Channel.SendMessageAsync("User must be in a voice channel, or a voice channel must be passed as an argument.");
+ return;
+ }
+
+ Data.audioClient = await Data.voiceChannel.ConnectAsync();
+
+ using (var discord = Data.audioClient.CreatePCMStream(AudioApplication.Mixed))
+ {
+ await message.Channel.SendMessageAsync("Loading...");
+
+ Data.CurrentlyRunning = new MusicPlayer(discord);
+ await Data.CurrentlyRunning.StartSendAudioFromLink(URL);
+ }
}
}
diff --git a/PluginManager/BlankWindow1.xaml b/PluginManager/BlankWindow1.xaml
deleted file mode 100644
index c5e0d39..0000000
--- a/PluginManager/BlankWindow1.xaml
+++ /dev/null
@@ -1,13 +0,0 @@
-
-
-
-
-
-
diff --git a/PluginManager/Config.cs b/PluginManager/Config.cs
new file mode 100644
index 0000000..686fee4
--- /dev/null
+++ b/PluginManager/Config.cs
@@ -0,0 +1,86 @@
+using PluginManager.Others;
+using System.IO;
+using System.Linq;
+using System.Text.Json;
+using System.Threading.Tasks;
+using System.Collections.Generic;
+
+namespace PluginManager
+{
+ internal class AppConfig
+ {
+ public Dictionary ApplicationVariables { get; set; }
+ public List ProtectedKeyWords { get; set; }
+ }
+
+ public static class Config
+ {
+ private static AppConfig appConfig;
+
+ public static bool AddValueToVariables(string key, T value, bool isProtected)
+ {
+ if (appConfig.ApplicationVariables.ContainsKey(key)) return false;
+ if (value == null) return false;
+ appConfig.ApplicationVariables.Add(key, value);
+ if (isProtected) appConfig.ProtectedKeyWords.Add(key);
+ SaveConfig();
+ return true;
+ }
+
+ public static T? GetValue(string key)
+ {
+ if (!appConfig.ApplicationVariables.ContainsKey(key)) return default;
+ try
+ {
+ JsonElement element = (JsonElement)appConfig.ApplicationVariables[key];
+ return element.Deserialize();
+ }
+ catch
+ {
+ return (T)appConfig.ApplicationVariables[key];
+ }
+ }
+
+ public static bool SetValue(string key, T value)
+ {
+ if (!appConfig.ApplicationVariables.ContainsKey(key)) return false;
+ if (appConfig.ProtectedKeyWords.Contains(key)) return false;
+ if (value == null) return false;
+
+ appConfig.ApplicationVariables[key] = JsonSerializer.SerializeToElement(value);
+ SaveConfig();
+ return true;
+ }
+
+ public static bool RemoveKey(string key)
+ {
+ appConfig.ApplicationVariables.Remove(key);
+ appConfig.ProtectedKeyWords.Remove(key);
+ SaveConfig();
+ return true;
+ }
+
+ public static async void SaveConfig()
+ {
+ string path = Functions.dataFolder + "config.json";
+ await Functions.SaveToJsonFile(path, appConfig);
+ }
+
+ public static async Task LoadConfig()
+ {
+ string path = Functions.dataFolder + "config.json";
+ if (File.Exists(path))
+ {
+ appConfig = await Functions.ConvertFromJson(path);
+ Functions.WriteLogFile($"Loaded {appConfig.ApplicationVariables.Keys.Count} application variables.\nLoaded {appConfig.ProtectedKeyWords.Count} readonly variables.");
+ }
+ else
+ appConfig = new() { ApplicationVariables = new Dictionary(), ProtectedKeyWords = new List() };
+ }
+
+ public static bool ContainsValue(T value) => appConfig.ApplicationVariables.ContainsValue(value!);
+ public static bool ContainsKey(string key) => appConfig.ApplicationVariables.ContainsKey(key);
+
+ public static Dictionary GetAllVariables() => new(appConfig.ApplicationVariables);
+ }
+}
diff --git a/PluginManager/Interfaces/DBCommand.cs b/PluginManager/Interfaces/DBCommand.cs
index cd57f69..4095427 100644
--- a/PluginManager/Interfaces/DBCommand.cs
+++ b/PluginManager/Interfaces/DBCommand.cs
@@ -1,49 +1,51 @@
-namespace PluginManager.Interfaces
+using Discord.Commands;
+using Discord.WebSocket;
+
+namespace PluginManager.Interfaces;
+
+public interface DBCommand
{
- public interface DBCommand
- {
- ///
- /// Command to be executed
- /// It's CaSe SeNsItIvE
- ///
- string Command { get; }
+ ///
+ /// Command to be executed
+ /// It's CaSe SeNsItIvE
+ ///
+ string Command { get; }
- ///
- /// Command description
- ///
- string Description { get; }
+ ///
+ /// Command description
+ ///
+ string Description { get; }
- ///
- /// The usage for your command.
- /// It will be displayed when users type help
- ///
- string Usage { get; }
+ ///
+ /// The usage for your command.
+ /// It will be displayed when users type help
+ ///
+ string Usage { get; }
- ///
- /// true if the command can be used in a DM channel, otherwise false
- ///
- bool canUseDM { get; }
+ ///
+ /// true if the command can be used in a DM channel, otherwise false
+ ///
+ bool canUseDM { get; }
- ///
- /// true if the command can be used in a server, otherwise false
- ///
- bool canUseServer { get; }
+ ///
+ /// true if the command can be used in a server, otherwise false
+ ///
+ bool canUseServer { get; }
- ///
- /// true if the command requre admin, otherwise false
- ///
- bool requireAdmin { get; }
+ ///
+ /// true if the command requre admin, otherwise false
+ ///
+ bool requireAdmin { get; }
- ///
- /// The main body of the command. This is what is executed when user calls the command
- ///
- /// The disocrd Context
- /// The message that the user types
- /// The discord client of the bot
- /// true if the message was sent from DM, otherwise false. It is always false if canUseDM is false
- void Execute(Discord.Commands.SocketCommandContext context,
- Discord.WebSocket.SocketMessage message,
- Discord.WebSocket.DiscordSocketClient client,
- bool isDM);
- }
-}
\ No newline at end of file
+ ///
+ /// The main body of the command. This is what is executed when user calls the command
+ ///
+ /// The disocrd Context
+ /// The message that the user types
+ /// The discord client of the bot
+ /// true if the message was sent from DM, otherwise false. It is always false if canUseDM is false
+ void Execute(SocketCommandContext context,
+ SocketMessage message,
+ DiscordSocketClient client,
+ bool isDM);
+}
diff --git a/PluginManager/Interfaces/DBEvent.cs b/PluginManager/Interfaces/DBEvent.cs
index 77288fb..eea8f6d 100644
--- a/PluginManager/Interfaces/DBEvent.cs
+++ b/PluginManager/Interfaces/DBEvent.cs
@@ -1,23 +1,22 @@
using Discord.WebSocket;
-namespace PluginManager.Interfaces
+namespace PluginManager.Interfaces;
+
+public interface DBEvent
{
- public interface DBEvent
- {
- ///
- /// The name of the event
- ///
- string name { get; }
+ ///
+ /// The name of the event
+ ///
+ string name { get; }
- ///
- /// The description of the event
- ///
- string description { get; }
+ ///
+ /// The description of the event
+ ///
+ string description { get; }
- ///
- /// The method that is invoked when the event is loaded into memory
- ///
- /// The discord bot client
- void Start(DiscordSocketClient client);
- }
+ ///
+ /// The method that is invoked when the event is loaded into memory
+ ///
+ /// The discord bot client
+ void Start(DiscordSocketClient client);
}
diff --git a/PluginManager/Items/Command.cs b/PluginManager/Items/Command.cs
index b1292d5..6850ece 100644
--- a/PluginManager/Items/Command.cs
+++ b/PluginManager/Items/Command.cs
@@ -1,51 +1,44 @@
-using Discord.WebSocket;
-
-using PluginManager.Loaders;
+using System.Collections.Generic;
+using Discord.WebSocket;
using PluginManager.Others;
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-using System.Threading.Tasks;
+namespace PluginManager.Items;
-namespace PluginManager.Items
+internal class Command
{
- internal class Command
+ ///
+ /// The author of the command
+ ///
+ public SocketUser? Author;
+
+ ///
+ /// The Command class contructor
+ ///
+ /// The message that was sent
+ public Command(SocketMessage message)
{
- ///
- /// The author of the command
- ///
- public SocketUser? Author;
-
- ///
- /// The list of arguments
- ///
- public List Arguments { get; private set; }
-
- ///
- /// The command that is executed
- ///
- public string CommandName { get; private set; }
-
- ///
- /// The prefix that is used for the command
- ///
- public char PrefixUsed { get; private set; }
-
- ///
- /// The Command class contructor
- ///
- /// The message that was sent
- public Command(SocketMessage message)
- {
- this.Author = message.Author;
- string[] data = message.Content.Split(' ');
- if (data.Length > 1)
- this.Arguments = new List(data.MergeStrings(1).Split(' '));
- else this.Arguments = new List();
- this.CommandName = data[0].Substring(1);
- this.PrefixUsed = data[0][0];
- }
+ Author = message.Author;
+ var data = message.Content.Split(' ');
+ if (data.Length > 1)
+ Arguments = new List(data.MergeStrings(1).Split(' '));
+ else
+ Arguments = new List();
+ CommandName = data[0].Substring(1);
+ PrefixUsed = data[0][0];
}
+
+ ///
+ /// The list of arguments
+ ///
+ public List Arguments { get; }
+
+ ///
+ /// The command that is executed
+ ///
+ public string CommandName { get; }
+
+ ///
+ /// The prefix that is used for the command
+ ///
+ public char PrefixUsed { get; }
}
diff --git a/PluginManager/Items/ConsoleCommandsHandler.cs b/PluginManager/Items/ConsoleCommandsHandler.cs
index 30a8c7a..5ac5947 100644
--- a/PluginManager/Items/ConsoleCommandsHandler.cs
+++ b/PluginManager/Items/ConsoleCommandsHandler.cs
@@ -1,115 +1,89 @@
-using Discord.WebSocket;
-
+using System;
+using System.Collections.Generic;
+using System.Diagnostics;
+using System.IO;
+using System.Linq;
+using System.Threading;
+using System.Threading.Tasks;
+using Discord.WebSocket;
using PluginManager.Loaders;
using PluginManager.Online;
using PluginManager.Others;
+namespace PluginManager.Items;
-using System;
-using System.Collections.Generic;
-using System.Diagnostics;
-using System.Threading.Tasks;
-using System.Threading;
-using PluginManager.LanguageSystem;
-using System.Linq;
-using System.Reflection.Metadata.Ecma335;
-
-namespace PluginManager.Items
+public class ConsoleCommandsHandler
{
- public class ConsoleCommandsHandler
+ private static readonly PluginsManager manager = new("https://sethdiscordbot.000webhostapp.com/Storage/Discord%20Bot/Plugins");
+
+ public static List>> commandList = new();
+ private readonly DiscordSocketClient? client;
+
+ public ConsoleCommandsHandler(DiscordSocketClient client)
{
+ this.client = client;
+ InitializeBasicCommands();
+ Console.WriteLine("Initalized console command handeler !");
+ }
- private static PluginsManager manager = new PluginsManager("https://sethdiscordbot.000webhostapp.com/Storage/Discord%20Bot/Plugins");
- private static LanguageManager languageManager = new LanguageManager("https://sethdiscordbot.000webhostapp.com/Storage/Discord%20Bot/Languages");
+ private void InitializeBasicCommands()
+ {
+ var pluginsLoaded = false;
+ commandList.Clear();
-
- public static List>>? commandList = new List>>();
- private DiscordSocketClient client;
-
- public ConsoleCommandsHandler(DiscordSocketClient client)
- {
- this.client = client;
- InitializeBasicCommands();
- Console.WriteLine("Initalized console command handeler !");
- }
-
- private void InitializeBasicCommands()
- {
-
- bool pluginsLoaded = false;
- commandList.Clear();
-
- AddCommand("help", "Show help", (args) =>
+ AddCommand("help", "Show help", args =>
{
if (args.Length <= 1)
{
Console.WriteLine("Available commands:");
- foreach (var command in commandList)
- {
- Console.WriteLine("\t" + command.Item1 + " - " + command.Item2);
- }
+ foreach (var command in commandList) Console.WriteLine("\t" + command.Item1 + " - " + command.Item2);
}
else
{
foreach (var command in commandList)
- {
if (command.Item1 == args[1])
{
Console.WriteLine(command.Item2);
return;
}
- }
+
Console.WriteLine("Command not found");
}
- });
+ }
+ );
- AddCommand("lp", "Load plugins", () =>
+ AddCommand("lp", "Load plugins", () =>
{
if (pluginsLoaded) return;
var loader = new PluginLoader(client);
loader.onCMDLoad += (name, typeName, success, exception) =>
{
Console.ForegroundColor = ConsoleColor.Green;
- if (name == null || name.Length < 2)
- name = typeName;
+ if (name == null || name.Length < 2) name = typeName;
if (success)
- if (LanguageSystem.Language.ActiveLanguage == null)
- Console.WriteLine("[CMD] Successfully loaded command : " + name);
- else Console.WriteLine(LanguageSystem.Language.ActiveLanguage.FormatText(LanguageSystem.Language.ActiveLanguage.LanguageWords["COMMAND_LOAD_SUCCESS"], name));
+ Console.WriteLine("[CMD] Successfully loaded command : " + name);
else
- if (LanguageSystem.Language.ActiveLanguage == null)
- Console.WriteLine("[CMD] Failed to load command : " + name + " because " + exception.Message);
- else
- Console.WriteLine(LanguageSystem.Language.ActiveLanguage.FormatText(LanguageSystem.Language.ActiveLanguage.LanguageWords["COMMAND_LOAD_FAIL"], name, exception.Message));
+ Console.WriteLine("[CMD] Failed to load command : " + name + " because " + exception!.Message);
Console.ForegroundColor = ConsoleColor.Red;
};
loader.onEVELoad += (name, typeName, success, exception) =>
{
- if (name == null || name.Length < 2)
- name = typeName;
+ if (name == null || name.Length < 2) name = typeName;
Console.ForegroundColor = ConsoleColor.Green;
if (success)
- if (LanguageSystem.Language.ActiveLanguage == null)
- Console.WriteLine("[EVENT] Successfully loaded event : " + name);
- else
- Console.WriteLine(LanguageSystem.Language.ActiveLanguage.FormatText(LanguageSystem.Language.ActiveLanguage.LanguageWords["EVENT_LOAD_SUCCESS"], name));
+ Console.WriteLine("[EVENT] Successfully loaded event : " + name);
else
- if (LanguageSystem.Language.ActiveLanguage == null)
- Console.WriteLine("[EVENT] Failed to load event : " + name + " because " + exception.Message);
- else
- Console.WriteLine(LanguageSystem.Language.ActiveLanguage.FormatText(LanguageSystem.Language.ActiveLanguage.LanguageWords["EVENT_LOAD_FAIL"], name, exception.Message));
+ Console.WriteLine("[EVENT] Failed to load event : " + name + " because " + exception!.Message);
Console.ForegroundColor = ConsoleColor.Red;
};
loader.LoadPlugins();
pluginsLoaded = true;
- });
+ }
+ );
- AddCommand("listplugs", "list available plugins", async () =>
- {
- await manager.ListAvailablePlugins();
- });
+ AddCommand("listplugs", "list available plugins", async () => { await manager.ListAvailablePlugins(); });
- AddCommand("dwplug", "download plugin", async (args) =>
+ AddCommand("dwplug", "download plugin", async args =>
{
if (args.Length == 1)
{
@@ -117,27 +91,30 @@ namespace PluginManager.Items
return;
}
- string name = args.MergeStrings(1);
+ var name = args.MergeStrings(1);
// info[0] = plugin type
// info[1] = plugin link
// info[2] = if others are required, or string.Empty if none
- string[] info = await manager.GetPluginLinkByName(name);
+ var info = await manager.GetPluginLinkByName(name);
if (info[1] == null) // link is null
{
if (name == "")
{
- Console_Utilities.WriteColorText($"Name is invalid");
+ Console_Utilities.WriteColorText("Name is invalid");
return;
}
- Console_Utilities.WriteColorText($"Failed to find plugin &b{name} &c!" +
- $" Use &glistplugs &ccommand to display all available plugins !");
- return;
+ Console_Utilities.WriteColorText($"Failed to find plugin &b{name} &c!" +
+ " Use &glistplugs &ccommand to display all available plugins !"
+ );
+ return;
}
+
string path;
if (info[0] == "Command" || info[0] == "Event")
path = "./Data/Plugins/" + info[0] + "s/" + name + ".dll";
- else path = $"./{info[1].Split('/')[info[1].Split('/').Length - 1]}";
+ else
+ path = $"./{info[1].Split('/')[info[1].Split('/').Length - 1]}";
await ServerCom.DownloadFileAsync(info[1], path);
Console.WriteLine("\n");
@@ -147,47 +124,41 @@ namespace PluginManager.Items
{
Console.WriteLine($"Downloading requirements for plugin : {name}");
- List lines = await ServerCom.ReadTextFromFile(info[2]);
+ var lines = await ServerCom.ReadTextFromFile(info[2]);
foreach (var line in lines)
{
- string[] split = line.Split(',');
+ var split = line.Split(',');
Console.WriteLine($"\nDownloading item: {split[1]}");
await ServerCom.DownloadFileAsync(split[0], "./" + split[1]);
Console.WriteLine();
if (split[0].EndsWith(".zip"))
{
-
Console.WriteLine($"Extracting {split[1]}");
- double proc = 0d;
- bool isExtracting = true;
- Console_Utilities.ProgressBar bar = new Console_Utilities.ProgressBar(100, "");
+ var proc = 0d;
+ var isExtracting = true;
+ var bar = new Console_Utilities.ProgressBar { Max = 100, Color = ConsoleColor.Green };
- IProgress extractProgress = new Progress(value =>
- {
- proc = value;
- });
+ IProgress extractProgress = new Progress(value => { proc = value; });
new Thread(new Task(() =>
- {
- while (isExtracting)
- {
- bar.Update((int)proc);
- if (proc >= 99.9f)
- break;
- Thread.Sleep(500);
- }
- }).Start).Start();
+ {
+ while (isExtracting)
+ {
+ bar.Update((int)proc);
+ if (proc >= 99.9f) break;
+ Thread.Sleep(500);
+ }
+ }
+ ).Start
+ ).Start();
await Functions.ExtractArchive("./" + split[1], "./", extractProgress);
bar.Update(100);
isExtracting = false;
await Task.Delay(1000);
bar.Update(100);
Console.WriteLine("\n");
- System.IO.File.Delete("./" + split[1]);
-
-
-
+ File.Delete("./" + split[1]);
}
if (name == "DBUI")
@@ -200,118 +171,122 @@ namespace PluginManager.Items
}
}
}
+
Console.WriteLine();
}
+ }
+ );
- });
- AddCommand("setlang", "set language", (args) =>
+ AddCommand("value", "read value from VariableStack", args =>
{
- if (args.Length == 1)
- {
- Console.WriteLine("Please specify language");
- return;
- }
- Language.SetLanguage(args[0]);
- });
+ if (args.Length != 2) return;
+ if (!Config.ContainsKey(args[1])) return;
- AddCommand("listlang", "List all available languages", async () =>
- {
- await languageManager.ListAllLanguages();
- });
+ var data = Config.GetValue(args[1]);
+ Console.WriteLine($"{args[1]} => {data}");
+ }
+ );
- AddCommand("dwlang", "Download language", async (args) =>
+ AddCommand("add", "add variable to the system variables\nadd [key] [value] [isReadOnly=true/false]", args =>
{
- if (args.Length == 1)
- {
- Console.WriteLine("Please specify language");
- return;
- }
- string Lname = args.MergeStrings(1);
- string[] link = await languageManager!.GetDownloadLink(Lname);
+ if (args.Length < 4) return;
+ var key = args[1];
+ var value = args[2];
+ var isReadOnly = args[3].Equals("true", StringComparison.CurrentCultureIgnoreCase);
+
try
{
- if (link[0] is null || link is null)
- {
- if (Lname == "")
- {
- Console_Utilities.WriteColorText($"Name is invalid");
- return;
- }
- Console_Utilities.WriteColorText("Failed to find language &b" + Lname + " &c! Use &glistlang &ccommand to display all available languages !");
- return;
- }
- if (link[1].Contains("CrossPlatform") || link[1].Contains("cp"))
- {
-
- string path2 = Functions.langFolder + Lname + ".lng";
-
- await ServerCom.DownloadFileAsync(link[0], path2);
- Console.WriteLine("\n");
- }
- else Console_Utilities.WriteColorText("The language you are trying to download (&b" + Lname + "&c) is not compatible with the version of this bot. User &glistlang &ccommand in order to see all available languages for your current version !\n" + link[1]);
- return;
+ if (Config.ContainsKey(key)) return;
+ if (int.TryParse(value, out var intValue))
+ Config.AddValueToVariables(key, intValue, isReadOnly);
+ else if (bool.TryParse(value, out var boolValue))
+ Config.AddValueToVariables(key, boolValue, isReadOnly);
+ else if (float.TryParse(value, out var floatValue))
+ Config.AddValueToVariables(key, floatValue, isReadOnly);
+ else if (double.TryParse(value, out var doubleValue))
+ Config.AddValueToVariables(key, doubleValue, isReadOnly);
+ else if (uint.TryParse(value, out var uintValue))
+ Config.AddValueToVariables(key, uintValue, isReadOnly);
+ else if (long.TryParse(value, out var longValue))
+ Config.AddValueToVariables(key, longValue, isReadOnly);
+ else if (byte.TryParse(value, out var byteValue))
+ Config.AddValueToVariables(key, byteValue, isReadOnly);
+ else
+ Config.AddValueToVariables(key, value, isReadOnly);
+ Console.WriteLine($"Updated config file with the following command: {args[1]} => {value}");
}
- catch
+ catch (Exception ex)
{
- if (Lname == "")
- {
- Console_Utilities.WriteColorText($"Name is invalid");
- return;
- }
- Console_Utilities.WriteColorText("Failed to find language &b" + Lname + " &c! Use &glistlang &ccommand to display all available languages !");
- return;
- }
- });
-
-
- AddCommand("token", "Display the token used by the bot", () =>
- {
- if (System.IO.File.Exists("./Data/Resources/DiscordBotCore.data"))
- Console.WriteLine("Token: " + Functions.readCodeFromFile("./Data/Resources/DiscordBotCore.data", "BOT_TOKEN", '='));
- else Console.WriteLine("File could not be found. Please register token");
- });
-
-
-
- }
-
- public static void AddCommand(string command, string description, Action action)
- {
- commandList.Add(new Tuple>(command, description, action));
- Console.ForegroundColor = ConsoleColor.White;
- Console_Utilities.WriteColorText($"Command &r{command} &cadded to the list of commands");
- }
-
- public static void AddCommand(string command, string description, Action action)
- {
- AddCommand(command, description, (args) => action());
-
- /* Console.WriteLine("Added command: " + command);*/
- }
-
- public static void RemoveCommand(string command)
- {
- commandList.RemoveAll(x => x.Item1 == command);
- }
-
- public static Tuple>? SearchCommand(string command)
- {
- return commandList.FirstOrDefault(t => t.Item1 == command);
- }
-
- public void HandleCommand(string command)
- {
- string[] args = command.Split(' ');
- foreach (var item in commandList.ToList())
- {
- if (item.Item1 == args[0])
- {
- item.Item3(args);
- //Console.WriteLine($"Executing: {args[0]} with the following parameters: {args.MergeStrings(1)}");
+ Console.WriteLine(ex.ToString());
}
}
- }
+ );
+ AddCommand("remv", "remove variable from system variables", args =>
+ {
+ if (args.Length < 2) return;
+ Config.RemoveKey(args[1]);
+ }
+ );
+
+ AddCommand("vars", "Display all variables", () =>
+ {
+ var d = Config.GetAllVariables();
+ var data = new List();
+ data.Add(new[] { "-", "-" });
+ data.Add(new[] { "Key", "Value" });
+ data.Add(new[] { "-", "-" });
+ foreach (var kvp in d) data.Add(new[] { kvp.Key, kvp.Value.ToString() });
+ data.Add(new[] { "-", "-" });
+ Console_Utilities.FormatAndAlignTable(data);
+ }
+ );
+
+ AddCommand("sd", "Shuts down the discord bot", async () =>
+ {
+ if (client is null) return;
+ await client.StopAsync();
+ await client.DisposeAsync();
+ Config.SaveConfig();
+ Environment.Exit(0);
+ }
+ );
+ }
+
+ public static void AddCommand(string command, string description, Action action)
+ {
+ commandList.Add(new Tuple>(command, description, action));
+ Console.ForegroundColor = ConsoleColor.White;
+ Console_Utilities.WriteColorText($"Command &r{command} &cadded to the list of commands");
+ }
+
+ public static void AddCommand(string command, string description, Action action)
+ {
+ AddCommand(command, description, args => action());
+ }
+
+ public static void RemoveCommand(string command)
+ {
+ commandList.RemoveAll(x => x.Item1 == command);
+ }
+
+ public static bool CommandExists(string command)
+ {
+ return !(GetCommand(command) is null);
+ }
+
+ public static Tuple>? GetCommand(string command)
+ {
+ return commandList.FirstOrDefault(t => t.Item1 == command);
+ }
+
+ public void HandleCommand(string command)
+ {
+ var args = command.Split(' ');
+ foreach (var item in commandList.ToList())
+ if (item.Item1 == args[0])
+ item.Item3(args);
+ //Console.WriteLine($"Executing: {args[0]} with the following parameters: {args.MergeStrings(1)}");
}
}
diff --git a/PluginManager/Items/Spinner.cs b/PluginManager/Items/Spinner.cs
index 5485a91..910df5b 100644
--- a/PluginManager/Items/Spinner.cs
+++ b/PluginManager/Items/Spinner.cs
@@ -1,54 +1,62 @@
using System;
using System.Threading.Tasks;
+using PluginManager.Others.Exceptions;
-namespace PluginManager.Items
+namespace PluginManager.Items;
+
+public class Spinner
{
- public class Spinner
+ ///
+ /// True if active, false otherwise
+ ///
+ public bool isSpinning;
+
+ ///
+ /// The Spinner constructor
+ ///
+ public Spinner()
{
- ///
- /// True if active, false otherwise
- ///
- public bool isSpinning;
+ isSpinning = false;
+ }
- ///
- /// The Spinner constructor
- ///
- public Spinner()
+ ///
+ /// The method that is called to start spinning the spinner
+ ///
+ public async void Start()
+ {
+ isSpinning = true;
+ var cnt = 0;
+
+ while (isSpinning)
{
- isSpinning = false;
- }
-
- ///
- /// The method that is called to start spinning the spinner
- ///
- public async void Start()
- {
- isSpinning = true;
- int cnt = 0;
-
- while (isSpinning)
+ cnt++;
+ switch (cnt % 4)
{
- cnt++;
- switch (cnt % 4)
- {
- case 0: Console.Write("/"); break;
- case 1: Console.Write("-"); break;
- case 2: Console.Write("\\"); break;
- case 3: Console.Write("|"); break;
- }
- Console.SetCursorPosition(Console.CursorLeft - 1, Console.CursorTop);
- await Task.Delay(250);
+ case 0:
+ Console.Write("/");
+ break;
+ case 1:
+ Console.Write("-");
+ break;
+ case 2:
+ Console.Write("\\");
+ break;
+ case 3:
+ Console.Write("|");
+ break;
}
- }
- ///
- /// The method that is called to stop the spinner from spinning
- ///
- public void Stop()
- {
- if (!isSpinning)
- throw new Others.Exceptions.APIException("Spinner was not spinning", GetType());
- isSpinning = false;
+ Console.SetCursorPosition(Console.CursorLeft - 1, Console.CursorTop);
+ await Task.Delay(250);
}
}
-}
\ No newline at end of file
+
+ ///
+ /// The method that is called to stop the spinner from spinning
+ ///
+ public void Stop()
+ {
+ if (!isSpinning) throw new APIException("Spinner was not spinning", GetType());
+ isSpinning = false;
+ }
+}
diff --git a/PluginManager/Language System/Language.cs b/PluginManager/Language System/Language.cs
deleted file mode 100644
index 732c4ae..0000000
--- a/PluginManager/Language System/Language.cs
+++ /dev/null
@@ -1,161 +0,0 @@
-using PluginManager.Others;
-using System.Collections.Generic;
-
-using System;
-using System.IO;
-using System.Threading.Tasks;
-
-namespace PluginManager.LanguageSystem
-{
- public class Language
- {
- ///
- /// The active language
- ///
- public static Language? ActiveLanguage = null;
-
- private static readonly string LanguageFileExtension = ".lng";
-
- ///
- /// The name of the language
- ///
- public string LanguageName { get; }
-
- ///
- /// The file where the language is imported from
- ///
- public string fileName { get; }
-
- ///
- /// The dictionary of the language
- ///
- public Dictionary LanguageWords { get; }
-
- ///
- /// The Language constructor
- ///
- /// The file to import the language from
- /// The dictionary of the language
- /// The name of the language
- private Language(string fileName, Dictionary words, string LanguageName)
- {
- this.fileName = fileName;
- this.LanguageName = LanguageName;
- LanguageWords = words;
- }
-
- ///
- /// Load language from file
- ///
- /// The file path
- ///
- public static Language? CreateLanguageFromFile(string LanguageFileLocation)
- {
- if (!LanguageFileLocation.EndsWith(LanguageFileExtension))
- {
- Console.WriteLine("Failed to load language from file: " + LanguageFileLocation +
- "\nFile extension is not " + LanguageFileExtension);
- return null;
- }
-
- string[] lines = File.ReadAllLines(LanguageFileLocation);
- var languageName = "Unknown";
- var words = new Dictionary();
-
- foreach (string line in lines)
- {
- if (line.StartsWith("#") || line.Length < 4)
- continue;
- string[] sLine = line.Split('=');
-
- if (sLine[0] == "LANGUAGE_NAME")
- {
- languageName = sLine[1];
- continue;
- }
-
- words.Add(sLine[0], sLine[1]);
- }
-
- Functions.WriteLogFile("Successfully loaded language: " + languageName + " from file : " +
- LanguageFileLocation.Replace('\\', '/'));
- return new Language(LanguageFileLocation, words, languageName);
- }
-
- ///
- /// Format text by inserting parameters
- ///
- /// The raw text
- /// The arguments
- ///
- public string FormatText(string text, params string[] args)
- {
- if (ActiveLanguage == null) return text;
- int l = args.Length;
- for (var i = 0; i < l; i++) text = text.Replace($"{i}", args[i]);
- return text;
- }
-
-
- public static bool LoadLanguage()
- {
- string folder = Functions.langFolder;
- string langSettings = "./Data/Resources/Language.txt";
- if (!File.Exists(langSettings))
- File.WriteAllText(langSettings, "Language=English");
- //Load language from the specified file ...
- Language.ActiveLanguage = null;
-
- string langname = Functions.readCodeFromFile(langSettings, "Language", '=');
- if (langname == "English")
- {
- Language.ActiveLanguage = null;
- return true;
- }
- foreach (var file in Directory.GetFiles(folder))
- {
- if (Functions.readCodeFromFile(file, "LANGUAGE_NAME", '=') == langname)
- {
- Language.ActiveLanguage = Language.CreateLanguageFromFile(file);
-
- return true;
- }
- }
-
- if (Language.ActiveLanguage == null)
- {
- File.WriteAllText(langSettings, "Language=English");
- Console_Utilities.WriteColorText($"Failed to find language &r{langname} &c! Check available languages using command: &glistlang");
-
- return false;
- }
-
- return false;
- }
-
- public static void SetLanguage(string LanguageName)
- {
- string langSettings = Functions.dataFolder + "Language.txt";
- File.WriteAllText(langSettings, "Language=" + LanguageName);
-
- try
- {
- bool success = LoadLanguage();
- if (success)
- {
- Console_Utilities.WriteColorText($"Language has been setted to: &g{LanguageName}");
- return;
- }
- }
- catch (Exception ex)
- {
- Console_Utilities.WriteColorText($"Could not find language &r{LanguageName}.");
- Functions.WriteErrFile(ex.ToString());
- File.WriteAllText(langSettings, "Language=English");
- LoadLanguage();
- }
- }
-
-
- }
-}
\ No newline at end of file
diff --git a/PluginManager/Loaders/CommandsLoader.cs b/PluginManager/Loaders/CommandsLoader.cs
deleted file mode 100644
index 919fa6b..0000000
--- a/PluginManager/Loaders/CommandsLoader.cs
+++ /dev/null
@@ -1,99 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.IO;
-using System.Linq;
-using System.Reflection;
-
-using PluginManager.Interfaces;
-
-namespace PluginManager.Loaders
-{
- internal class CommandsLoader
- {
- private readonly string CMDPath;
- private readonly string CMDExtension;
-
-
- internal delegate void onCommandLoaded(string name, bool success, DBCommand? command = null, Exception? exception = null);
- internal delegate void onCommandFileLoaded(string path);
-
- ///
- /// Event fired when a command is loaded
- ///
- internal onCommandLoaded? OnCommandLoaded;
-
- ///
- /// Event fired when the file is loaded
- ///
- internal onCommandFileLoaded? OnCommandFileLoaded;
-
- ///
- /// Command Loader contructor
- ///
- /// The path to the commands
- /// The extension to search for in the
- internal CommandsLoader(string CommandPath, string CommandExtension)
- {
- CMDPath = CommandPath;
- CMDExtension = CommandExtension;
- }
-
- ///
- /// The method that loads all commands
- ///
- ///
- internal List? LoadCommands()
- {
- if (!Directory.Exists(CMDPath))
- {
- Directory.CreateDirectory(CMDPath);
- return null;
- }
- string[] files = Directory.GetFiles(CMDPath, $"*{CMDExtension}", SearchOption.AllDirectories);
-
- foreach (var file in files)
- {
- Assembly.LoadFile(Path.GetFullPath(file));
- if (OnCommandFileLoaded != null)
- OnCommandFileLoaded.Invoke(file);
- }
-
- List plugins = new List();
-
- try
- {
- Type interfaceType = typeof(DBCommand);
- Type[] types = AppDomain.CurrentDomain.GetAssemblies()
- .SelectMany(a => a.GetTypes())
- .Where(p => interfaceType.IsAssignableFrom(p) && p.IsClass)
- .ToArray();
- foreach (Type type in types)
- {
- try
- {
- DBCommand plugin = (DBCommand)Activator.CreateInstance(type)!;
- plugins.Add(plugin);
-
- if (OnCommandLoaded != null)
- OnCommandLoaded.Invoke(type.FullName!, true, plugin);
- }
- catch (Exception e)
- {
- if (OnCommandLoaded != null)
- OnCommandLoaded.Invoke(type.FullName!, false, null, e);
- }
-
- }
-
- }
- catch (Exception ex)
- {
- Console.WriteLine(ex.Message);
- return null;
- }
-
- return plugins;
-
- }
- }
-}
diff --git a/PluginManager/Loaders/EventsLoader.cs b/PluginManager/Loaders/EventsLoader.cs
deleted file mode 100644
index 28c1766..0000000
--- a/PluginManager/Loaders/EventsLoader.cs
+++ /dev/null
@@ -1,100 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.IO;
-using System.Linq;
-using System.Reflection;
-
-using PluginManager.Interfaces;
-
-namespace PluginManager.Loaders
-{
- internal class EventsLoader
- {
-
- private readonly string EVPath;
- private readonly string EVExtension;
-
- internal delegate void onEventLoad(string name, bool success, DBEvent? ev = null, Exception? e = null);
- internal delegate void onEventFileLoaded(string path);
-
- ///
- /// An event that is fired whenever a event is loaded in memory
- ///
- internal onEventLoad? EventLoad;
-
- ///
- /// An event that is fired whenever a event file is loaded
- ///
- internal onEventFileLoaded? EventFileLoaded;
-
- ///
- /// The Event Loader constructor
- ///
- /// The path to all events
- /// The extension for events
- internal EventsLoader(string path, string ext)
- {
- EVPath = path;
- EVExtension = ext;
- }
-
- ///
- /// The method that loads all events
- ///
- ///
- internal List? LoadEvents()
- {
-
- if (!Directory.Exists(EVPath))
- {
- Directory.CreateDirectory(EVPath);
- return null;
- }
-
- string[] files = Directory.GetFiles(EVPath, $"*{EVExtension}", SearchOption.AllDirectories);
-
- foreach (var file in files)
- {
- Assembly.LoadFile(Path.GetFullPath(file));
- if (EventFileLoaded != null)
- EventFileLoaded.Invoke(file);
- }
-
- List events = new List();
-
- try
- {
- Type interfaceType = typeof(DBEvent);
- Type[] types = AppDomain.CurrentDomain.GetAssemblies()
- .SelectMany(a => a.GetTypes())
- .Where(p => interfaceType.IsAssignableFrom(p) && p.IsClass)
- .ToArray();
- foreach (Type type in types)
- {
- try
- {
- DBEvent ev = (DBEvent)Activator.CreateInstance(type)!;
- events.Add(ev);
-
- if (EventLoad != null)
- EventLoad.Invoke(type.FullName!, true, ev, null);
- }
- catch (Exception e)
- {
- if (EventLoad != null)
- EventLoad.Invoke(type.FullName!, false, null, e);
- }
-
- }
- }
- catch (Exception ex)
- {
- Console.WriteLine(ex.Message);
- return null;
- }
-
- return events;
-
- }
- }
-}
\ No newline at end of file
diff --git a/PluginManager/Loaders/Loader.cs b/PluginManager/Loaders/Loader.cs
new file mode 100644
index 0000000..1198eda
--- /dev/null
+++ b/PluginManager/Loaders/Loader.cs
@@ -0,0 +1,107 @@
+using System;
+using System.Collections.Generic;
+using System.IO;
+using System.Linq;
+using System.Reflection;
+using PluginManager.Others;
+
+namespace PluginManager.Loaders;
+
+internal class LoaderArgs : EventArgs
+{
+ internal string? PluginName { get; init; }
+ internal string? TypeName { get; init; }
+ internal bool IsLoaded { get; init; }
+ internal Exception? Exception { get; init; }
+ internal object? Plugin { get; init; }
+}
+
+internal class Loader
+{
+ internal Loader(string path, string extension)
+ {
+ this.path = path;
+ this.extension = extension;
+ }
+
+
+ private string path { get; }
+ private string extension { get; }
+
+ internal event FileLoadedEventHandler? FileLoaded;
+
+ internal event PluginLoadedEventHandler? PluginLoaded;
+
+ internal List? Load()
+ {
+ var list = new List();
+ if (!Directory.Exists(path))
+ {
+ Directory.CreateDirectory(path);
+ return null;
+ }
+
+ var files = Directory.GetFiles(path, $"*.{extension}", SearchOption.AllDirectories);
+ foreach (var file in files)
+ {
+ Assembly.LoadFrom(file);
+ if (FileLoaded != null)
+ {
+ var args = new LoaderArgs
+ {
+ Exception = null,
+ TypeName = nameof(T),
+ IsLoaded = false,
+ PluginName = file,
+ Plugin = null
+ };
+ FileLoaded.Invoke(args);
+ }
+ }
+
+ try
+ {
+ var interfaceType = typeof(T);
+ var types = AppDomain.CurrentDomain.GetAssemblies()
+ .SelectMany(a => a.GetTypes())
+ .Where(p => interfaceType.IsAssignableFrom(p) && p.IsClass)
+ .ToArray();
+
+
+ list.Clear();
+ foreach (var type in types)
+ try
+ {
+ var plugin = (T)Activator.CreateInstance(type)!;
+ list.Add(plugin);
+
+
+ if (PluginLoaded != null)
+ PluginLoaded.Invoke(new LoaderArgs
+ {
+ Exception = null,
+ IsLoaded = true,
+ PluginName = type.FullName,
+ TypeName = nameof(T),
+ Plugin = plugin
+ }
+ );
+ }
+ catch (Exception ex)
+ {
+ if (PluginLoaded != null) PluginLoaded.Invoke(new LoaderArgs { Exception = ex, IsLoaded = false, PluginName = type.FullName, TypeName = nameof(T) });
+ }
+ }
+ catch (Exception ex)
+ {
+ Functions.WriteErrFile(ex.ToString());
+ }
+
+
+ return list;
+ }
+
+ internal delegate void FileLoadedEventHandler(LoaderArgs args);
+
+ internal delegate void PluginLoadedEventHandler(LoaderArgs args);
+}
diff --git a/PluginManager/Loaders/PluginLoader.cs b/PluginManager/Loaders/PluginLoader.cs
index 520112d..c848f7f 100644
--- a/PluginManager/Loaders/PluginLoader.cs
+++ b/PluginManager/Loaders/PluginLoader.cs
@@ -1,111 +1,97 @@
-using Discord.WebSocket;
-
+using System;
+using System.Collections.Generic;
+using Discord.WebSocket;
using PluginManager.Interfaces;
using PluginManager.Others;
-using System;
-using System.Collections.Generic;
-namespace PluginManager.Loaders
+namespace PluginManager.Loaders;
+
+public class PluginLoader
{
- public class PluginLoader
+ public delegate void CMDLoaded(string name, string typeName, bool success, Exception? e = null);
+
+ public delegate void EVELoaded(string name, string typeName, bool success, Exception? e = null);
+
+ private const string pluginCMDFolder = @"./Data/Plugins/Commands/";
+ private const string pluginEVEFolder = @"./Data/Plugins/Events/";
+
+ private const string pluginCMDExtension = "dll";
+ private const string pluginEVEExtension = "dll";
+ private readonly DiscordSocketClient _client;
+
+ ///
+ /// Event that is fired when a is successfully loaded into commands list
+ ///
+ public CMDLoaded? onCMDLoad;
+
+ ///
+ /// Event that is fired when a is successfully loaded into events list
+ ///
+ public EVELoaded? onEVELoad;
+
+ ///
+ /// The Plugin Loader constructor
+ ///
+ /// The discord bot client where the plugins will pe attached to
+ public PluginLoader(DiscordSocketClient discordSocketClient)
{
- private DiscordSocketClient client;
-
- ///
- /// The Plugin Loader constructor
- ///
- /// The discord bot client where the plugins will pe attached to
- public PluginLoader(DiscordSocketClient discordSocketClient)
- {
- this.client = discordSocketClient;
- }
-
- private const string pluginCMDFolder = @"./Data/Plugins/Commands/";
- private const string pluginEVEFolder = @"./Data/Plugins/Events/";
-
- private const string pluginCMDExtension = ".dll";
- private const string pluginEVEExtension = ".dll";
-
- ///
- /// A list of commands
- ///
- public static List? Plugins { get; set; }
-
- ///
- /// A list of commands
- ///
- public static List? Events { get; set; }
+ _client = discordSocketClient;
+ }
- public delegate void CMDLoaded(string name, string typeName, bool success, Exception? e = null);
- public delegate void EVELoaded(string name, string typeName, bool success, Exception? e = null);
+ ///
+ /// A list of commands
+ ///
+ public static List? Commands { get; set; }
- ///
- /// Event that is fired when a is successfully loaded into commands list
- ///
- public CMDLoaded? onCMDLoad;
+ ///
+ /// A list of commands
+ ///
+ public static List? Events { get; set; }
- ///
- /// Event that is fired when a is successfully loaded into events list
- ///
- public EVELoaded? onEVELoad;
+ ///
+ /// The main mathod that is called to load all events
+ ///
+ public void LoadPlugins()
+ {
+ Commands = new List();
+ Events = new List();
- ///
- /// The main mathod that is called to load all events
- ///
- public void LoadPlugins()
- {
+ Functions.WriteLogFile("Starting plugin loader ... Client: " + _client.CurrentUser.Username);
+ Console.WriteLine("Loading plugins");
- Plugins = new List();
- Events = new List();
+ var commandsLoader = new Loader(pluginCMDFolder, pluginCMDExtension);
+ var eventsLoader = new Loader(pluginEVEFolder, pluginEVEExtension);
- Functions.WriteLogFile("Starting plugin loader ... Client: " + client.CurrentUser.Username);
- if (LanguageSystem.Language.ActiveLanguage != null)
- Console_Utilities.WriteColorText(
- LanguageSystem.Language.ActiveLanguage.FormatText(
- LanguageSystem.Language.ActiveLanguage.LanguageWords["PLUGIN_LOADING_START"]
- )
- );
+ commandsLoader.FileLoaded += OnCommandFileLoaded;
+ commandsLoader.PluginLoaded += OnCommandLoaded;
- //Load commands
- CommandsLoader CMDLoader = new CommandsLoader(pluginCMDFolder, pluginCMDExtension);
- CMDLoader.OnCommandLoaded += OnCommandLoaded!;
- CMDLoader.OnCommandFileLoaded += OnCommandFileLoaded;
- Plugins = CMDLoader.LoadCommands();
+ eventsLoader.FileLoaded += EventFileLoaded;
+ eventsLoader.PluginLoaded += OnEventLoaded;
+ Commands = commandsLoader.Load();
+ Events = eventsLoader.Load();
+ }
- //Load Events
- EventsLoader EVLoader = new EventsLoader(pluginEVEFolder, pluginEVEExtension);
- EVLoader.EventLoad += OnEventLoaded!;
- EVLoader.EventFileLoaded += EventFileLoaded;
- Events = EVLoader.LoadEvents();
+ private void EventFileLoaded(LoaderArgs e)
+ {
+ if (e.IsLoaded) Functions.WriteLogFile($"[EVENT] Event from file [{e.PluginName}] has been successfully created !");
+ }
- }
+ private void OnCommandFileLoaded(LoaderArgs e)
+ {
+ if (e.IsLoaded) Functions.WriteLogFile($"[CMD] Command from file [{e.PluginName}] has been successfully loaded !");
+ }
- private void EventFileLoaded(string path)
- {
- if (path != null)
- Functions.WriteLogFile($"[EVENT] Event from file [{path}] has been successfully created !");
- }
+ private void OnEventLoaded(LoaderArgs e)
+ {
+ if (e.IsLoaded) ((DBEvent)e.Plugin!).Start(_client);
- private void OnCommandFileLoaded(string path)
- {
- if (path != null)
- Functions.WriteLogFile($"[CMD] Command from file [{path}] has been successfully loaded !");
- }
+ if (onEVELoad != null) onEVELoad.Invoke(((DBEvent)e.Plugin!).name, e.TypeName!, e.IsLoaded, e.Exception);
+ }
- private void OnEventLoaded(string typename, bool success, DBEvent eve, Exception exception)
- {
- if (eve != null && success)
- eve.Start(client);
- if (onEVELoad != null)
- onEVELoad.Invoke(eve!.name, typename, success, exception);
- }
-
- private void OnCommandLoaded(string name, bool success, DBCommand command, Exception exception)
- {
- if (onCMDLoad != null)
- onCMDLoad.Invoke(command.Command, name, success, exception);
- }
+ private void OnCommandLoaded(LoaderArgs e)
+ {
+ if (onCMDLoad != null) onCMDLoad.Invoke(((DBCommand)e.Plugin!).Command, e.TypeName!, e.IsLoaded, e.Exception);
}
}
diff --git a/PluginManager/Online/LanguageManager.cs b/PluginManager/Online/LanguageManager.cs
index 408315c..fc24bad 100644
--- a/PluginManager/Online/LanguageManager.cs
+++ b/PluginManager/Online/LanguageManager.cs
@@ -1,86 +1,82 @@
using System;
-using System.IO;
-using System.Threading.Tasks;
-using System.Net;
using System.Collections.Generic;
-
+using System.Threading.Tasks;
using PluginManager.Others;
-namespace PluginManager.Online
+namespace PluginManager.Online;
+
+public class LanguageManager
{
- public class LanguageManager
+ private readonly string link;
+
+ ///
+ /// The Language Manager constructor
+ ///
+ /// The link to where all the languages for the bot are stored
+ public LanguageManager(string link)
{
- private string link;
+ this.link = link;
+ }
- ///
- /// The Language Manager constructor
- ///
- /// The link to where all the languages for the bot are stored
- public LanguageManager(string link) => this.link = link;
-
- ///
- /// The method to list all languages
- ///
- ///
- public async Task ListAllLanguages()
+ ///
+ /// The method to list all languages
+ ///
+ ///
+ public async Task ListAllLanguages()
+ {
+ try
{
+ var list = await ServerCom.ReadTextFromFile(link);
+ var lines = list.ToArray();
- try
+ var info = new List();
+ info.Add(new[] { "-", "-" });
+ info.Add(new[] { "Language Name", "File Size" });
+ info.Add(new[] { "-", "-" });
+ foreach (var line in lines)
{
- List list = await ServerCom.ReadTextFromFile(link);
- string[] lines = list.ToArray();
-
- List info = new List();
- info.Add(new string[] { "-", "-" });
- info.Add(new string[] { "Language Name", "File Size" });
- info.Add(new string[] { "-", "-" });
- foreach (var line in lines)
- {
- if (line.Length <= 2) continue;
- string[] d = line.Split(',');
- if (d[3].Contains("cp") || d[3].Contains("CrossPlatform"))
- info.Add(new string[] { d[0], d[1] });
- }
- info.Add(new string[] { "-", "-" });
- Console_Utilities.FormatAndAlignTable(info);
- }
-
- catch (Exception exception)
- {
- Console.WriteLine("Failed to execute command: listlang\nReason: " + exception.Message);
- Others.Functions.WriteErrFile(exception.ToString());
+ if (line.Length <= 2) continue;
+ var d = line.Split(',');
+ if (d[3].Contains("cp") || d[3].Contains("CrossPlatform")) info.Add(new[] { d[0], d[1] });
}
+ info.Add(new[] { "-", "-" });
+ Console_Utilities.FormatAndAlignTable(info);
}
- ///
- /// A function that gets the download link for specified language
- ///
- /// The name of the language
- ///
- public async Task GetDownloadLink(string langName)
+ catch (Exception exception)
{
- try
- {
- List list = await ServerCom.ReadTextFromFile(link);
- string[] lines = list.ToArray();
-
- foreach (var line in lines)
- {
- if (line.Length <= 2) continue;
- string[] d = line.Split(',');
- if (d[0].Equals(langName) && (d[3].Contains("cp") || d[3].Contains("CrossPlatform")))
- return new string[] { d[2], d[3] };
- }
- }
- catch (Exception exception)
- {
- Console.WriteLine("Failed to execute command: listlang\nReason: " + exception.Message);
- Others.Functions.WriteErrFile(exception.ToString());
- }
-
-
- return null;
+ Console.WriteLine("Failed to execute command: listlang\nReason: " + exception.Message);
+ Functions.WriteErrFile(exception.ToString());
}
}
-}
\ No newline at end of file
+
+ ///
+ /// A function that gets the download link for specified language
+ ///
+ /// The name of the language
+ ///
+ public async Task GetDownloadLink(string langName)
+ {
+ try
+ {
+ var list = await ServerCom.ReadTextFromFile(link);
+ var lines = list.ToArray();
+
+ foreach (var line in lines)
+ {
+ if (line.Length <= 2) continue;
+ var d = line.Split(',');
+ if (d[0].Equals(langName) && (d[3].Contains("cp") || d[3].Contains("CrossPlatform"))) return new[] { d[2], d[3] };
+ }
+ }
+ catch (Exception exception)
+ {
+ Console.WriteLine("Failed to execute command: listlang\nReason: " + exception.Message);
+ Functions.WriteErrFile(exception.ToString());
+ }
+
+
+ return null;
+ }
+}
diff --git a/PluginManager/Online/PluginsManager.cs b/PluginManager/Online/PluginsManager.cs
index 1e7a7e6..5f9dad6 100644
--- a/PluginManager/Online/PluginsManager.cs
+++ b/PluginManager/Online/PluginsManager.cs
@@ -1,128 +1,118 @@
using System;
-using System.IO;
-using System.Net;
-using System.Threading.Tasks;
using System.Collections.Generic;
-
+using System.Threading.Tasks;
using PluginManager.Others;
+using OperatingSystem = PluginManager.Others.OperatingSystem;
-namespace PluginManager.Online
+namespace PluginManager.Online;
+
+public class PluginsManager
{
- public class PluginsManager
+ ///
+ /// The Plugin Manager constructor
+ ///
+ /// The link to the file where all plugins are stored
+ public PluginsManager(string link)
{
- ///
- /// The URL of the server
- ///
- public string PluginsLink { get; private set; }
+ PluginsLink = link;
+ }
- ///
- /// The Plugin Manager constructor
- ///
- /// The link to the file where all plugins are stored
- public PluginsManager(string link)
- {
- PluginsLink = link;
- }
+ ///
+ /// The URL of the server
+ ///
+ public string PluginsLink { get; }
- ///
- /// The method to load all plugins
- ///
- ///
- public async Task ListAvailablePlugins()
+ ///
+ /// The method to load all plugins
+ ///
+ ///
+ public async Task ListAvailablePlugins()
+ {
+ try
{
- try
+ var list = await ServerCom.ReadTextFromFile(PluginsLink);
+ var lines = list.ToArray();
+
+ var data = new List();
+ var op = Functions.GetOperatingSystem();
+
+ var len = lines.Length;
+ string[] titles = { "Name", "Description", "Plugin Type", "Libraries" };
+ data.Add(new[] { "-", "-", "-", "-" });
+ data.Add(titles);
+ data.Add(new[] { "-", "-", "-", "-" });
+ for (var i = 0; i < len; i++)
{
- List list = await ServerCom.ReadTextFromFile(PluginsLink);
- string[] lines = list.ToArray();
-
- List data = new List();
- var op = Functions.GetOperatingSystem();
-
- int len = lines.Length;
- string[] titles = { "Name", "Description", "Plugin Type", "Libraries" };
- data.Add(new string[] { "-", "-", "-", "-" });
- data.Add(titles);
- data.Add(new string[] { "-", "-", "-", "-" });
- for (int i = 0; i < len; i++)
+ if (lines[i].Length <= 2) continue;
+ var content = lines[i].Split(',');
+ var display = new string[4];
+ if (op == OperatingSystem.WINDOWS)
{
- if (lines[i].Length <= 2) continue;
- string[] content = lines[i].Split(',');
- string[] display = new string[4];
- if (op == Others.OperatingSystem.WINDOWS)
+ if (content[4].Contains("Windows"))
{
- if (content[4].Contains("Windows"))
- {
- display[0] = content[0];
- display[1] = content[1];
- display[2] = content[2];
- if (content.Length == 6 && (content[5] != null || content[5].Length > 2))
- display[3] = ((await ServerCom.ReadTextFromFile(content[5])).Count + 1).ToString();
+ display[0] = content[0];
+ display[1] = content[1];
+ display[2] = content[2];
+ if (content.Length == 6 && (content[5] != null || content[5].Length > 2))
+ display[3] = ((await ServerCom.ReadTextFromFile(content[5])).Count + 1).ToString();
- else display[3] = "1";
- data.Add(display);
- continue;
- }
- }
- else if (op == Others.OperatingSystem.LINUX)
- {
- if (content[4].Contains("Linux"))
- {
- display[0] = content[0];
- display[1] = content[1];
- display[2] = content[2];
- data.Add(display);
- continue;
- }
+ else
+ display[3] = "1";
+ data.Add(display);
}
}
-
- data.Add(new string[] { "-", "-", "-", "-" });
-
- Console_Utilities.FormatAndAlignTable(data);
- }
- catch (Exception exception)
- {
- Console.WriteLine("Failed to execute command: listlang\nReason: " + exception.Message);
- Others.Functions.WriteErrFile(exception.ToString());
- }
-
- }
-
- ///
- /// The method to get plugin information by its name
- ///
- /// The plugin name
- ///
- public async Task GetPluginLinkByName(string name)
- {
- try
- {
- List list = await ServerCom.ReadTextFromFile(PluginsLink);
- string[] lines = list.ToArray();
- int len = lines.Length;
- for (int i = 0; i < len; i++)
+ else if (op == OperatingSystem.LINUX)
{
- string[] contents = lines[i].Split(',');
- if (contents[0] == name)
+ if (content[4].Contains("Linux"))
{
- if (contents.Length == 6)
- return new string[] { contents[2], contents[3], contents[5] };
- else if (contents.Length == 5)
- return new string[] { contents[2], contents[3], string.Empty };
- else throw new Exception("Failed to download plugin. Invalid Argument Length");
+ display[0] = content[0];
+ display[1] = content[1];
+ display[2] = content[2];
+ data.Add(display);
}
-
}
}
- catch (Exception exception)
- {
- Console.WriteLine("Failed to execute command: listplugs\nReason: " + exception.Message);
- Others.Functions.WriteErrFile(exception.ToString());
- }
- return new string[] { null!, null!, null! };
+ data.Add(new[] { "-", "-", "-", "-" });
+
+ Console_Utilities.FormatAndAlignTable(data);
+ }
+ catch (Exception exception)
+ {
+ Console.WriteLine("Failed to execute command: listlang\nReason: " + exception.Message);
+ Functions.WriteErrFile(exception.ToString());
+ }
+ }
+
+ ///
+ /// The method to get plugin information by its name
+ ///
+ /// The plugin name
+ ///
+ public async Task GetPluginLinkByName(string name)
+ {
+ try
+ {
+ var list = await ServerCom.ReadTextFromFile(PluginsLink);
+ var lines = list.ToArray();
+ var len = lines.Length;
+ for (var i = 0; i < len; i++)
+ {
+ var contents = lines[i].Split(',');
+ if (contents[0] == name)
+ {
+ if (contents.Length == 6) return new[] { contents[2], contents[3], contents[5] };
+ if (contents.Length == 5) return new[] { contents[2], contents[3], string.Empty };
+ throw new Exception("Failed to download plugin. Invalid Argument Length");
+ }
+ }
+ }
+ catch (Exception exception)
+ {
+ Console.WriteLine("Failed to execute command: listplugs\nReason: " + exception.Message);
+ Functions.WriteErrFile(exception.ToString());
}
-
+ return new string[] { null!, null!, null! };
}
}
diff --git a/PluginManager/Online/ServerCom.cs b/PluginManager/Online/ServerCom.cs
index 84fa84d..67c2401 100644
--- a/PluginManager/Online/ServerCom.cs
+++ b/PluginManager/Online/ServerCom.cs
@@ -1,10 +1,11 @@
using PluginManager.Online.Helpers;
-
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
+using System.Threading;
using System.Threading.Tasks;
+using PluginManager.Others;
namespace PluginManager.Online
{
@@ -51,37 +52,35 @@ namespace PluginManager.Online
///
public static async Task DownloadFileAsync(string URL, string location)
{
- bool isDownloading = true;
- int c_progress = 0;
+ bool isDownloading = true;
+ int c_progress = 0;
- Others.Console_Utilities.ProgressBar pbar = new Others.Console_Utilities.ProgressBar(100, "");
+ Console_Utilities.ProgressBar pbar = new Console_Utilities.ProgressBar { Max = 100, NoColor = true };
IProgress progress = new Progress(percent =>
{
c_progress = (int)percent;
});
- Task updateProgressBarTask = new Task(() =>
- {
- while (isDownloading)
- {
- pbar.Update(c_progress);
- if (c_progress == 100)
- break;
- System.Threading.Thread.Sleep(500);
- }
- });
- new System.Threading.Thread(updateProgressBarTask.Start).Start();
+ Task updateProgressBarTask = new Task(() =>
+ {
+ while (isDownloading)
+ {
+ pbar.Update(c_progress);
+ if (c_progress == 100) break;
+ Thread.Sleep(500);
+ }
+ }
+ );
+
+ new Thread(updateProgressBarTask.Start).Start();
await DownloadFileAsync(URL, location, progress);
c_progress = 100;
pbar.Update(100);
isDownloading = false;
-
-
}
-
}
}
diff --git a/PluginManager/Others/Channels.cs b/PluginManager/Others/Channels.cs
index 89ea068..d0dbac6 100644
--- a/PluginManager/Others/Channels.cs
+++ b/PluginManager/Others/Channels.cs
@@ -1,42 +1,60 @@
+using System.Threading.Tasks;
using Discord;
-using System.Threading.Tasks;
+namespace PluginManager.Others;
-namespace PluginManager.Others
+///
+/// A class that handles the sending of messages to the user.
+///
+public static class ChannelManagement
{
///
- /// A class that handles the sending of messages to the user.
+ /// Get the text channel by name from server
///
- public static class ChannelManagement
+ /// The server
+ /// The channel name
+ ///
+ ///
+ ///
+ public static IGuildChannel GetTextChannel(this IGuild server, string name)
{
- ///
- /// Get the text channel by name from server
- ///
- /// The server
- /// The channel name
- ///
- public static IGuildChannel GetTextChannel(this IGuild server, string name) => server.GetTextChannel(name);
- ///
- /// Get the voice channel by name from server
- ///
- /// The server
- /// The channel name
- ///
- public static IGuildChannel GetVoiceChannel(this IGuild server, string name) => server.GetVoiceChannel(name);
-
- ///
- /// Get the DM channel between and
- ///
- ///
- ///
- public static async Task GetDMChannel(IGuildUser user) => await user.CreateDMChannelAsync();
-
- ///
- /// Get the channel where the message was sent
- ///
- /// The message
- ///
- public static IChannel GetChannel(IMessage message) => message.Channel;
-
+ return server.GetTextChannel(name);
}
-}
\ No newline at end of file
+
+ ///
+ /// Get the voice channel by name from server
+ ///
+ /// The server
+ /// The channel name
+ ///
+ ///
+ ///
+ public static IGuildChannel GetVoiceChannel(this IGuild server, string name)
+ {
+ return server.GetVoiceChannel(name);
+ }
+
+ ///
+ /// Get the DM channel between and
+ ///
+ ///
+ ///
+ ///
+ ///
+ public static async Task GetDMChannel(IGuildUser user)
+ {
+ return await user.CreateDMChannelAsync();
+ }
+
+ ///
+ /// Get the channel where the message was sent
+ ///
+ /// The message
+ ///
+ ///
+ ///
+ public static IChannel GetChannel(IMessage message)
+ {
+ return message.Channel;
+ }
+}
diff --git a/PluginManager/Others/Console Utilities.cs b/PluginManager/Others/Console Utilities.cs
index 1cdf29a..00dc30a 100644
--- a/PluginManager/Others/Console Utilities.cs
+++ b/PluginManager/Others/Console Utilities.cs
@@ -1,9 +1,5 @@
using System;
using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-using System.Threading;
-using System.Threading.Tasks;
namespace PluginManager.Others
{
@@ -14,20 +10,13 @@ namespace PluginManager.Others
///
public class ProgressBar
{
- public int Progress { get; set; }
- public int Max { get; set; }
- public string Message { get; set; }
+ public int Max { get; init; }
+ public ConsoleColor Color { get; init; }
+ public bool NoColor { get; init; }
- public ProgressBar(int max, string message)
+
+ public void Update(int progress, double speed = -1, string? unit = null)
{
- Max = max;
- Message = message;
- }
-
- public async void Update(int progress, double speed = -1, string? unit = null)
- {
-
- //progress bar
Console.CursorLeft = 0;
Console.Write("[");
Console.CursorLeft = 32;
@@ -39,15 +28,21 @@ namespace PluginManager.Others
for (int i = 0; i < onechunk * progress; i++)
{
- Console.BackgroundColor = ConsoleColor.Green;
- Console.CursorLeft = position++;
- Console.Write(" ");
+ if (NoColor)
+ Console.BackgroundColor = ConsoleColor.Black; //this.Color
+ else
+ Console.BackgroundColor = this.Color;
+ Console.CursorLeft = position++;
+ Console.Write("#");
}
for (int i = position; i <= 31; i++)
{
- Console.BackgroundColor = ConsoleColor.Gray;
- Console.CursorLeft = position++;
+ if (NoColor)
+ Console.BackgroundColor = ConsoleColor.Black; // background of empty bar
+ else
+ Console.BackgroundColor = ConsoleColor.DarkGray;
+ Console.CursorLeft = position++;
Console.Write(" ");
}
@@ -72,9 +67,9 @@ namespace PluginManager.Others
/// The List of arrays of strings that represent the rows.
public static void FormatAndAlignTable(List data)
{
- char tableLine = '-';
+ char tableLine = '-';
char tableCross = '+';
- char tableWall = '|';
+ char tableWall = '|';
int[] len = new int[data[0].Length];
foreach (var line in data)
@@ -130,11 +125,12 @@ namespace PluginManager.Others
ConsoleColor fg = Console.ForegroundColor;
Dictionary colors = new Dictionary()
{
- {"&g", ConsoleColor.Green },
- {"&b", ConsoleColor.Blue },
- {"&r", ConsoleColor.Red },
- {"&m", ConsoleColor.Magenta },
- {"&c", fg }
+ { "&g", ConsoleColor.Green },
+ { "&b", ConsoleColor.Blue },
+ { "&r", ConsoleColor.Red },
+ { "&m", ConsoleColor.Magenta },
+ { "&y", ConsoleColor.Yellow },
+ { "&c", fg }
};
foreach (string word in words)
{
@@ -145,7 +141,9 @@ namespace PluginManager.Others
Console.ForegroundColor = colors[prefix];
}
- string m = word.Replace("&g", "").Replace("&b", "").Replace("&r", "").Replace("&c", "").Replace("&m", "");
+ string m = word;
+ foreach (var key in colors.Keys) { m = m.Replace(key, ""); }
+
Console.Write(m + " ");
}
if (appendNewLine)
diff --git a/PluginManager/Others/Cryptography.cs b/PluginManager/Others/Cryptography.cs
index e2c13de..04864ae 100644
--- a/PluginManager/Others/Cryptography.cs
+++ b/PluginManager/Others/Cryptography.cs
@@ -1,91 +1,88 @@
using System;
+using System.IO;
+using System.Security.Cryptography;
+using System.Text;
+using System.Threading.Tasks;
-namespace PluginManager.Others
+namespace PluginManager.Others;
+
+public class Cryptography
{
- public class Cryptography
+ ///
+ /// Translate hex to string
+ ///
+ /// The encrypted string
+ ///
+ public static string FromHexToString(string hexString)
{
+ var bytes = new byte[hexString.Length / 2];
+ for (var i = 0; i < bytes.Length; i++) bytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);
- ///
- /// Translate hex to string
- ///
- /// The encrypted string
- ///
- public static string FromHexToString(string hexString)
- {
- var bytes = new byte[hexString.Length / 2];
- for (var i = 0; i < bytes.Length; i++)
- {
- bytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);
- }
-
- return System.Text.Encoding.Unicode.GetString(bytes);
- }
-
- ///
- /// Translate string to hex
- ///
- /// The string to encrypt
- ///
- public static string ToHexString(string str)
- {
- var sb = new System.Text.StringBuilder();
-
- var bytes = System.Text.Encoding.Unicode.GetBytes(str);
- foreach (var t in bytes)
- {
- sb.Append(t.ToString("X2"));
- }
-
- return sb.ToString();
- }
-
- ///
- /// Create MD5 hash
- ///
- /// The text to encrypt
- ///
- public static async System.Threading.Tasks.Task CreateMD5(string text)
- {
- string output = "";
- using (System.Security.Cryptography.MD5 md5 = System.Security.Cryptography.MD5.Create())
- {
- using (var s = GenerateStreamFromString(text))
- {
- byte[] t = await md5.ComputeHashAsync(s);
- output = System.Convert.ToBase64String(t);
- }
- }
-
- return output;
- }
-
- ///
- /// Create SHA256 hash
- ///
- /// The text to encrypt
- ///
- public static async System.Threading.Tasks.Task CreateSHA256(string text)
- {
- string output = "";
- using (System.Security.Cryptography.SHA256 sha = System.Security.Cryptography.SHA256.Create())
- {
- using (var s = GenerateStreamFromString(text))
- {
- byte[] t = await sha.ComputeHashAsync(s);
- output = System.Convert.ToBase64String(t);
- }
- }
- return output;
- }
-
- private static System.IO.Stream GenerateStreamFromString(string s)
- {
- var stream = new System.IO.MemoryStream();
- var writer = new System.IO.StreamWriter(stream);
- writer.Write(s);
- writer.Flush();
- stream.Position = 0;
- return stream;
- }
+ return Encoding.Unicode.GetString(bytes);
}
-}
\ No newline at end of file
+
+ ///
+ /// Translate string to hex
+ ///
+ /// The string to encrypt
+ ///
+ public static string ToHexString(string str)
+ {
+ var sb = new StringBuilder();
+
+ var bytes = Encoding.Unicode.GetBytes(str);
+ foreach (var t in bytes) sb.Append(t.ToString("X2"));
+
+ return sb.ToString();
+ }
+
+ ///
+ /// Create MD5 hash
+ ///
+ /// The text to encrypt
+ ///
+ public static async Task CreateMD5(string text)
+ {
+ var output = "";
+ using (var md5 = MD5.Create())
+ {
+ using (var s = GenerateStreamFromString(text))
+ {
+ var t = await md5.ComputeHashAsync(s);
+ output = Convert.ToBase64String(t);
+ }
+ }
+
+ return output;
+ }
+
+ ///
+ /// Create SHA256 hash
+ ///
+ /// The text to encrypt
+ ///
+ public static async Task CreateSHA256(string text)
+ {
+ var output = "";
+ using (var sha = SHA256.Create())
+ {
+ using (var s = GenerateStreamFromString(text))
+ {
+ var t = await sha.ComputeHashAsync(s);
+ output = Convert.ToBase64String(t);
+ }
+ }
+
+ return output;
+ }
+
+ private static Stream GenerateStreamFromString(string s)
+ {
+ var stream = new MemoryStream();
+ var writer = new StreamWriter(stream);
+ writer.Write(s);
+ writer.Flush();
+ stream.Position = 0;
+ return stream;
+ }
+}
diff --git a/PluginManager/Others/Enums.cs b/PluginManager/Others/Enums.cs
index 222e169..d8b22fb 100644
--- a/PluginManager/Others/Enums.cs
+++ b/PluginManager/Others/Enums.cs
@@ -1,20 +1,22 @@
-namespace PluginManager.Others
+namespace PluginManager.Others;
+
+///
+/// A list of operating systems
+///
+public enum OperatingSystem
{
+ WINDOWS, LINUX, MAC_OS, UNKNOWN
+}
- ///
- /// A list of operating systems
- ///
- public enum OperatingSystem
- { WINDOWS, LINUX, MAC_OS, UNKNOWN }
+///
+/// A list with all errors
+///
+public enum Error
+{
+ UNKNOWN_ERROR, GUILD_NOT_FOUND, STREAM_NOT_FOUND, INVALID_USER, INVALID_CHANNEL, INVALID_PERMISSIONS
+}
- ///
- /// A list with all errors
- ///
- public enum Error
- { UNKNOWN_ERROR, GUILD_NOT_FOUND, STREAM_NOT_FOUND, INVALID_USER, INVALID_CHANNEL, INVALID_PERMISSIONS }
-
- ///
- /// The output log type
- ///
- public enum OutputLogLevel { NONE, INFO, WARNING, ERROR, CRITICAL }
-}
\ No newline at end of file
+///
+/// The output log type
+///
+public enum OutputLogLevel { NONE, INFO, WARNING, ERROR, CRITICAL }
diff --git a/PluginManager/Others/Exceptions/APIException.cs b/PluginManager/Others/Exceptions/APIException.cs
index 990704f..37264c1 100644
--- a/PluginManager/Others/Exceptions/APIException.cs
+++ b/PluginManager/Others/Exceptions/APIException.cs
@@ -1,94 +1,91 @@
using System;
-namespace PluginManager.Others.Exceptions
+namespace PluginManager.Others.Exceptions;
+
+///
+/// Custom Exception for PluginManager
+///
+[Serializable]
+public class APIException : Exception
{
///
- /// Custom Exception for PluginManager
+ /// The APIException contructor
///
- [Serializable]
-
- public class APIException : Exception
+ /// The error message
+ /// The function where the message was triggered
+ /// The possible cause of the error
+ /// The error code
+ public APIException(string message, string? function, string possible_cause, Error error) : base(message)
{
- ///
- /// The function where the error occurred
- ///
- public string? Function { get; } = "not specified";
-
- ///
- /// The error code
- ///
- public Error? ErrorCode { get; } = Error.UNKNOWN_ERROR;
-
- ///
- /// The possible cause that determined the error
- ///
- public string? PossibleCause { get; } = "not specified";
-
- ///
- /// The APIException contructor
- ///
- /// The error message
- /// The function where the message was triggered
- /// The possible cause of the error
- /// The error code
- public APIException(string message, string? function, string possible_cause, Error error) : base(message)
- {
- ErrorCode = error;
- Function = function;
- PossibleCause = possible_cause;
- }
-
- ///
- /// The APIException contructor
- ///
- /// The error message
- /// The function where the message was triggered
- /// The error code
- public APIException(string message, string? function, Error? errorCode) : base(message)
- {
- ErrorCode = errorCode;
- Function = function;
- }
- ///
- /// The APIException contructor
- ///
- /// The error message
- /// The function where the message was triggered
- public APIException(string message, string? function) : base(message)
- {
- Function = function;
- }
- ///
- /// The APIException contructor
- ///
- /// The error message
- public APIException(string message) : base(message)
- {
-
- }
-
- ///
- /// The APIException constructor
- ///
- /// The error message
- /// The class where the error was thrown
- public APIException(string message, Type errorLocation) : base(message)
- {
- Function = errorLocation.FullName;
- }
-
- ///
- /// Method to print the error to
- ///
- public void Print()
- {
- Console.WriteLine("Message Content: " + Message);
- Console.WriteLine("Function: " + Function);
- Console.WriteLine("Error Code: " + ErrorCode.ToString());
- Console.WriteLine("Possible cause: " + PossibleCause);
- if (this.StackTrace != null)
- Functions.WriteErrFile(this.StackTrace);
- }
+ ErrorCode = error;
+ Function = function;
+ PossibleCause = possible_cause;
}
-}
\ No newline at end of file
+ ///
+ /// The APIException contructor
+ ///
+ /// The error message
+ /// The function where the message was triggered
+ /// The error code
+ public APIException(string message, string? function, Error? errorCode) : base(message)
+ {
+ ErrorCode = errorCode;
+ Function = function;
+ }
+
+ ///
+ /// The APIException contructor
+ ///
+ /// The error message
+ /// The function where the message was triggered
+ public APIException(string message, string? function) : base(message)
+ {
+ Function = function;
+ }
+
+ ///
+ /// The APIException contructor
+ ///
+ /// The error message
+ public APIException(string message) : base(message)
+ {
+ }
+
+ ///
+ /// The APIException constructor
+ ///
+ /// The error message
+ /// The class where the error was thrown
+ public APIException(string message, Type errorLocation) : base(message)
+ {
+ Function = errorLocation.FullName;
+ }
+
+ ///
+ /// The function where the error occurred
+ ///
+ public string? Function { get; } = "not specified";
+
+ ///
+ /// The error code
+ ///
+ public Error? ErrorCode { get; } = Error.UNKNOWN_ERROR;
+
+ ///
+ /// The possible cause that determined the error
+ ///
+ public string? PossibleCause { get; } = "not specified";
+
+ ///
+ /// Method to print the error to
+ ///
+ public void Print()
+ {
+ Console.WriteLine("Message Content: " + Message);
+ Console.WriteLine("Function: " + Function);
+ Console.WriteLine("Error Code: " + ErrorCode);
+ Console.WriteLine("Possible cause: " + PossibleCause);
+ if (StackTrace != null) Functions.WriteErrFile(StackTrace);
+ }
+}
diff --git a/PluginManager/Others/Functions.cs b/PluginManager/Others/Functions.cs
index 9e8091b..0857eb1 100644
--- a/PluginManager/Others/Functions.cs
+++ b/PluginManager/Others/Functions.cs
@@ -7,6 +7,8 @@ using System.Collections.Generic;
using Discord.WebSocket;
using PluginManager.Items;
using System.Threading;
+using System.Text.Json;
+using System.Text;
namespace PluginManager.Others
{
@@ -40,22 +42,6 @@ namespace PluginManager.Others
///
public static readonly string pakFolder = @"./Data/Resources/PAKS/";
- ///
- /// The mark that the line is a comment
- ///
- private static readonly char commentMark = '#';
-
- ///
- /// Read data from file
- ///
- /// File name
- /// Setting name
- /// Separator between setting key code and its value
- /// The value of the specified setting key code in the specified file ()
- public static string? readCodeFromFile(string fileName, string Code, char separator)
- => File.ReadAllLines(fileName)
- .Where(p => p.StartsWith(Code) && !p.StartsWith(commentMark.ToString()))
- .First().Split(separator)[1] ?? null;
///
/// Read data from a file that is inside an archive (ZIP format)
@@ -67,17 +53,16 @@ namespace PluginManager.Others
{
archFile = pakFolder + archFile;
Directory.CreateDirectory(pakFolder);
- if (!File.Exists(archFile))
- throw new FileNotFoundException("Failed to load file !");
+ if (!File.Exists(archFile)) throw new FileNotFoundException("Failed to load file !");
string? textValue = null;
- var fs = new FileStream(archFile, FileMode.Open);
- var zip = new ZipArchive(fs, ZipArchiveMode.Read);
+ var fs = new FileStream(archFile, FileMode.Open);
+ var zip = new ZipArchive(fs, ZipArchiveMode.Read);
foreach (var entry in zip.Entries)
{
if (entry.Name == FileName || entry.FullName == FileName)
{
- Stream s = entry.Open();
+ Stream s = entry.Open();
StreamReader reader = new StreamReader(s);
textValue = await reader.ReadToEndAsync();
reader.Close();
@@ -86,6 +71,7 @@ namespace PluginManager.Others
break;
}
}
+
return textValue;
}
@@ -96,8 +82,7 @@ namespace PluginManager.Others
public static void WriteLogFile(string LogMessage)
{
string logsPath = logFolder + "Log.txt";
- if (!Directory.Exists(logFolder))
- Directory.CreateDirectory(logFolder);
+ if (!Directory.Exists(logFolder)) Directory.CreateDirectory(logFolder);
File.AppendAllText(logsPath, LogMessage + " \n");
}
@@ -108,36 +93,10 @@ namespace PluginManager.Others
public static void WriteErrFile(string ErrMessage)
{
string errPath = errFolder + "Error.txt";
- if (!Directory.Exists(errFolder))
- Directory.CreateDirectory(errFolder);
+ if (!Directory.Exists(errFolder)) Directory.CreateDirectory(errFolder);
File.AppendAllText(errPath, ErrMessage + " \n");
}
- ///
- /// Write to settings file
- ///
- /// The settings file path
- /// The Key value of the setting
- /// The new value of the settings
- /// The separator between the key and the value
- public static void WriteToSettings(string file, string Code, string newValue, char separator)
- {
-
- string[] lines = File.ReadAllLines(file);
- File.Delete(file);
- bool ok = false;
- foreach (var line in lines)
- if (line.StartsWith(Code))
- {
- File.AppendAllText(file, Code + separator + newValue + "\n");
- ok = true;
- }
- else File.AppendAllText(file, line + "\n");
-
- if (!ok)
- File.AppendAllText(file, Code + separator + newValue + "\n");
- }
-
///
/// Merge one array of strings into one string
///
@@ -146,8 +105,8 @@ namespace PluginManager.Others
/// A string built based on the array
public static string MergeStrings(this string[] s, int indexToStart)
{
- string r = "";
- int len = s.Length;
+ string r = "";
+ int len = s.Length;
if (len <= indexToStart) return "";
for (int i = indexToStart; i < len - 1; ++i)
{
@@ -177,30 +136,6 @@ namespace PluginManager.Others
return command.Arguments;
}
-
- ///
- /// Write setting
- ///
- /// The full path to the setting
- /// The new Value
- public static void WriteToSettingsFast(string SettingName, string NewValue)
- {
-
- string path = dataFolder; // Resources/
-
- string[] args = SettingName.Split('.');
-
- int len = args.Length;
- if (len < 2) return;
- for (int i = 0; i < len - 2; i++)
- path += args[i] + "/";
- path += args[len - 2] + ".txt";
-
-
- WriteToSettings(path, args[len - 1].Replace('_', ' '), NewValue, '=');
-
- }
-
///
/// Copy one Stream to another
///
@@ -215,20 +150,15 @@ namespace PluginManager.Others
/// Triggered in is not writable
public static async Task CopyToOtherStreamAsync(this Stream stream, Stream destination, int bufferSize, IProgress? progress = null, CancellationToken cancellationToken = default)
{
- if (stream == null)
- throw new ArgumentNullException(nameof(stream));
- if (destination == null)
- throw new ArgumentNullException(nameof(destination));
- if (bufferSize <= 0)
- throw new ArgumentOutOfRangeException(nameof(bufferSize));
- if (!stream.CanRead)
- throw new InvalidOperationException("The stream is not readable.");
- if (!destination.CanWrite)
- throw new ArgumentException("Destination stream is not writable", nameof(destination));
+ if (stream == null) throw new ArgumentNullException(nameof(stream));
+ if (destination == null) throw new ArgumentNullException(nameof(destination));
+ if (bufferSize <= 0) throw new ArgumentOutOfRangeException(nameof(bufferSize));
+ if (!stream.CanRead) throw new InvalidOperationException("The stream is not readable.");
+ if (!destination.CanWrite) throw new ArgumentException("Destination stream is not writable", nameof(destination));
- byte[] buffer = new byte[bufferSize];
- long totalBytesRead = 0;
- int bytesRead;
+ byte[] buffer = new byte[bufferSize];
+ long totalBytesRead = 0;
+ int bytesRead;
while ((bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length, cancellationToken).ConfigureAwait(false)) != 0)
{
await destination.WriteAsync(buffer, 0, bytesRead, cancellationToken).ConfigureAwait(false);
@@ -246,29 +176,28 @@ namespace PluginManager.Others
///
public static async Task ExtractArchive(string zip, string folder, IProgress progress)
{
- if (!Directory.Exists(folder))
- Directory.CreateDirectory(folder);
-
-
+ if (!Directory.Exists(folder)) Directory.CreateDirectory(folder);
using (ZipArchive archive = ZipFile.OpenRead(zip))
{
- int totalZIPFiles = archive.Entries.Count();
+ int totalZIPFiles = archive.Entries.Count();
int currentZIPFile = 0;
foreach (ZipArchiveEntry entry in archive.Entries)
{
if (entry.FullName.EndsWith("/"))
- {
- currentZIPFile++;
Directory.CreateDirectory(Path.Combine(folder, entry.FullName));
- }
- else
- {
- entry.ExtractToFile(Path.Combine(folder, entry.FullName), true);
- currentZIPFile++;
- }
+ else
+ try
+ {
+ entry.ExtractToFile(Path.Combine(folder, entry.FullName), true);
+ }
+ catch
+ {
+ }
+
+ currentZIPFile++;
await Task.Delay(10);
progress.Report((float)currentZIPFile / totalZIPFiles * 100);
}
@@ -276,13 +205,76 @@ namespace PluginManager.Others
}
+ ///
+ /// Convert Bytes to highest measurement unit possible
+ ///
+ /// The amount of bytes
+ ///
public static (double, string) ConvertBytes(long bytes)
{
- if (bytes < 1024) return (bytes, "B");
- if (bytes < 1024 * 1024) return (bytes / 1024.0, "KB");
- if (bytes < 1024 * 1024 * 1024) return (bytes / 1024.0 / 1024.0, "MB");
- return (bytes / 1024.0 / 1024.0 / 1024.0, "GB");
+ List units = new List()
+ {
+ "B",
+ "KB",
+ "MB",
+ "GB",
+ "TB"
+ };
+ int i = 0;
+ while (bytes >= 1024)
+ {
+ i++;
+ bytes /= 1024;
+ }
+ return (bytes, units[i]);
+ }
+
+ ///
+ /// Save to JSON file
+ ///
+ /// The class type
+ /// The file path
+ /// The values
+ ///
+ public static async Task SaveToJsonFile(string file, T Data)
+ {
+ using (var s = File.OpenWrite(file)) await JsonSerializer.SerializeAsync(s, Data, typeof(T), new JsonSerializerOptions { WriteIndented = true });
+ }
+
+ ///
+ /// Convert json text or file to some kind of data
+ ///
+ /// The data type
+ /// The file or json text
+ ///
+ public static async Task ConvertFromJson(string input)
+ {
+ Stream text;
+ if (File.Exists(input))
+ text = File.Open(input, FileMode.OpenOrCreate);
+
+ else
+ text = new MemoryStream(Encoding.ASCII.GetBytes(input));
+ text.Position = 0;
+ var obj = await JsonSerializer.DeserializeAsync(text);
+ text.Close();
+ return obj;
+ }
+
+ public static bool TryReadValueFromJson(string input, string codeName, out JsonElement element)
+ {
+ Stream text;
+ if (File.Exists(input))
+ text = File.OpenRead(input);
+
+ else
+ text = new MemoryStream(Encoding.ASCII.GetBytes(input));
+
+ var jsonObject = JsonDocument.Parse(text);
+
+ var data = jsonObject.RootElement.TryGetProperty(codeName, out element);
+ return data;
}
}
}
diff --git a/PluginManager/Others/Permissions/DiscordPermissions.cs b/PluginManager/Others/Permissions/DiscordPermissions.cs
index be55780..e8fae3b 100644
--- a/PluginManager/Others/Permissions/DiscordPermissions.cs
+++ b/PluginManager/Others/Permissions/DiscordPermissions.cs
@@ -1,55 +1,64 @@
-using Discord;
+using System.Linq;
+using Discord;
using Discord.WebSocket;
-using System.Linq;
+namespace PluginManager.Others.Permissions;
-namespace PluginManager.Others.Permissions
+///
+/// A class whith all discord permissions
+///
+public static class DiscordPermissions
{
///
- /// A class whith all discord permissions
+ /// Checks if the role has the specified permission
///
- public static class DiscordPermissions
+ /// The role
+ /// The permission
+ ///
+ public static bool hasPermission(this IRole role, GuildPermission permission)
{
- ///
- /// Checks if the role has the specified permission
- ///
- /// The role
- /// The permission
- ///
- public static bool hasPermission(this IRole role, GuildPermission permission) => role.Permissions.Has(permission);
-
- ///
- /// Check if user has the specified role
- ///
- /// The user
- /// The role
- ///
- public static bool hasRole(this SocketGuildUser user, IRole role) => user.Roles.Contains(role);
-
- ///
- /// Check if user has the specified permission
- ///
- /// The user
- /// The permission
- ///
- public static bool hasPermission(this SocketGuildUser user, GuildPermission permission)
- => user.Roles.Where(role => role.hasPermission(permission)).Any() || user.Guild.Owner == user;
- ///
- /// Check if user is administrator of server
- ///
- /// The user
- ///
- public static bool isAdmin(this SocketGuildUser user) => user.hasPermission(GuildPermission.Administrator);
-
- ///
- /// Check if user is administrator of server
- ///
- /// The user
- ///
- public static bool isAdmin(this SocketUser user) => isAdmin((SocketGuildUser)user);
+ return role.Permissions.Has(permission);
}
+ ///
+ /// Check if user has the specified role
+ ///
+ /// The user
+ /// The role
+ ///
+ public static bool hasRole(this SocketGuildUser user, IRole role)
+ {
+ return user.Roles.Contains(role);
+ }
+ ///
+ /// Check if user has the specified permission
+ ///
+ /// The user
+ /// The permission
+ ///
+ public static bool hasPermission(this SocketGuildUser user, GuildPermission permission)
+ {
+ return user.Roles.Where(role => role.hasPermission(permission)).Any() || user.Guild.Owner == user;
+ }
+ ///
+ /// Check if user is administrator of server
+ ///
+ /// The user
+ ///
+ public static bool isAdmin(this SocketGuildUser user)
+ {
+ return user.hasPermission(GuildPermission.Administrator);
+ }
-}
\ No newline at end of file
+ ///
+ /// Check if user is administrator of server
+ ///
+ /// The user
+ ///
+ public static bool isAdmin(this SocketUser user)
+ {
+ return isAdmin((SocketGuildUser)user);
+ }
+}
diff --git a/PluginManager/PluginManager.csproj b/PluginManager/PluginManager.csproj
index 7d2d32a..7eafd1b 100644
--- a/PluginManager/PluginManager.csproj
+++ b/PluginManager/PluginManager.csproj
@@ -19,10 +19,4 @@
-
-
- MSBuild:Compile
-
-
-
diff --git a/README.md b/README.md
index 1c1fd58..5aee53e 100644
--- a/README.md
+++ b/README.md
@@ -17,6 +17,9 @@ Plugin Types:
1. Commands
2. Events
+Project Structure
+
+
### How to create a plugin
diff --git a/StartupEvents/OnUserJoin.cs b/StartupEvents/OnUserJoin.cs
deleted file mode 100644
index bb4ff5f..0000000
--- a/StartupEvents/OnUserJoin.cs
+++ /dev/null
@@ -1,57 +0,0 @@
-using PluginManager.Others;
-using PluginManager.Interfaces;
-using Discord;
-
-public class OnUserJoin : DBEvent
-{
- public string name => "OnPlayerJoin";
-
- public string description => "An event that is triggered when an user joins the server";
-
- private string UtilsPath = Functions.dataFolder + "/StartupEvents";
- private string ConfigFile = Functions.dataFolder + "/StartupEvents/" + "UserJoinEvent.txt";
-
- public async void Start(Discord.WebSocket.DiscordSocketClient client)
- {
-
- System.IO.Directory.CreateDirectory(UtilsPath);
-
- if (!System.IO.File.Exists(ConfigFile))
- {
- await System.IO.File.WriteAllTextAsync(ConfigFile,
- "Enabled=True\nEmbed=True\n" +
- "#Available placeholders:\n" +
- "#{user.Name} => Username of the user\n" +
- "#{time.date} => Current Date\n" +
- "#{time.time} => Current time (hh:mm::ss)\n" +
- "MessageTitle = Welcome {user.Name}\n" +
- "MessageDescription=Embed description\n" +
- "MessageField1Title=Custom Title\n" +
- "MessageFiled1Text=Custom Filed 1 text\n" +
- "MessageField2Title=Custom Title\n" +
- "MessageFiled2Text=Custom Filed 2 text\n" +
- "MessageFooter=Today: {time.date} at {time.time}\n");
- }
-
- if (Functions.readCodeFromFile(ConfigFile, "Enabled", '=') != "True") return;
- //System.Console.WriteLine("Awaiting user join event ...");
-
- client.UserJoined += Client_UserJoined;
-
- }
-
- private async System.Threading.Tasks.Task Client_UserJoined(Discord.WebSocket.SocketGuildUser user)
- {
- Console_Utilities.WriteColorText("A new user joins: " + user.Username);
- EmbedBuilder embed = new EmbedBuilder
- {
- Title = Functions.readCodeFromFile(ConfigFile, "MessageTitle", '='),
- Description = Functions.readCodeFromFile(ConfigFile, "MessageDescription", '=')
- };
- embed
- .AddField(Functions.readCodeFromFile(ConfigFile, "MessageField1Title", '=').Replace("{user.Name}", user.Username).Replace("{time.date}", System.DateTime.Now.ToShortDateString()).Replace("{time.time}", System.DateTime.Now.ToShortTimeString()), Functions.readCodeFromFile(ConfigFile, "MessageField1Text", '=').Replace("{user.Name}", user.Username).Replace("{time.date}", System.DateTime.Now.ToShortDateString()).Replace("{time.time}", System.DateTime.Now.ToShortTimeString()))
- .AddField(Functions.readCodeFromFile(ConfigFile, "MessageField2Title", '=').Replace("{user.Name}", user.Username).Replace("{time.date}", System.DateTime.Now.ToShortDateString()).Replace("{time.time}", System.DateTime.Now.ToShortTimeString()), Functions.readCodeFromFile(ConfigFile, "MessageField2Text", '=').Replace("{user.Name}", user.Username).Replace("{time.date}", System.DateTime.Now.ToShortDateString()).Replace("{time.time}", System.DateTime.Now.ToShortTimeString()))
- .WithFooter(Functions.readCodeFromFile(ConfigFile, "MessageFooter", '=').Replace("{user.Name}", user.Username).Replace("{time.date}", System.DateTime.Now.ToShortDateString()).Replace("{time.time}", System.DateTime.Now.ToShortTimeString()));
- await user.Guild.DefaultChannel.SendMessageAsync(embed: embed.Build());
- }
-}
\ No newline at end of file
diff --git a/StartupEvents/SetGameOnLogin.cs b/StartupEvents/SetGameOnLogin.cs
deleted file mode 100644
index 4a2d2d9..0000000
--- a/StartupEvents/SetGameOnLogin.cs
+++ /dev/null
@@ -1,48 +0,0 @@
-public class SetGameOnLogin : PluginManager.Interfaces.DBEvent
-{
- public string name => "Set Game on Startup";
- public string description => "Set Custom Game to the bot at initialization";
- public async void Start(Discord.WebSocket.DiscordSocketClient client)
- {
- string UtilsPath = PluginManager.Others.Functions.dataFolder + "StartupEvents/";
- string ConfigFile = UtilsPath + "LoginEvent.txt";
-
- System.IO.Directory.CreateDirectory(UtilsPath);
- if (!System.IO.File.Exists(ConfigFile))
- {
- System.Console.WriteLine($"First time setup. Open file: {ConfigFile} to change settings or use the following commands\nNote: For space ( ) use underline (_). Example: 'Hello_World' will output 'Hello World'");
- System.Console.WriteLine($"set-setting StartupEvents.LoginEvent.Title [Custom_Title(s)]");
- System.Console.WriteLine($"set-setting StartupEvents.LoginEvent.Dynamic_Title [True/False]");
- System.Console.WriteLine($"set-setting StartupEvents.LoginEvent.Dynamic_Title_Change_Rate [interval in milliseconds]");
- await System.IO.File.WriteAllTextAsync(ConfigFile, "Enabled=True\n\nDynamic Title=False\n#For dynamic title add titles like this:\n#Title=Hello,World,Test,Test2\nTitle=!help\nDynamic Title Change Rate=3500\n");
- }
-
- if (PluginManager.Others.Functions.readCodeFromFile(ConfigFile, "Enabled", '=') != "True")
- return;
-
- bool isDynamic = PluginManager.Others.Functions.readCodeFromFile(ConfigFile, "Dynamic Title", '=') == "True";
- string Title = PluginManager.Others.Functions.readCodeFromFile(ConfigFile, "Title", '=');
- if (Title == null || Title.Length < 2) return;
- if (!isDynamic)
- await client.SetGameAsync(Title, null, Discord.ActivityType.Playing);
- else
- {
- string[] Titles = Title.Split(',');
- int delayMS = 3500;
- try
- {
- delayMS = int.Parse(PluginManager.Others.Functions.readCodeFromFile(ConfigFile, "Dynamic Title Change Rate", '='));
- }
- catch { }
- while (true)
- {
- foreach (var title in Titles)
- {
- await client.SetGameAsync(title, null, Discord.ActivityType.Playing);
- await System.Threading.Tasks.Task.Delay(delayMS);
- }
- }
- }
-
- }
-}
\ No newline at end of file
diff --git a/StartupEvents/StartupEvents.csproj b/StartupEvents/StartupEvents.csproj
deleted file mode 100644
index aaabc01..0000000
--- a/StartupEvents/StartupEvents.csproj
+++ /dev/null
@@ -1,17 +0,0 @@
-
-
-
- net6.0
-
-
-
- ..\BUILDS\
- none
- false
-
-
-
-
-
-
-