10 Commits

Author SHA1 Message Date
16c06c8319 2022-05-26 19:24:18 +03:00
363c85d0b3 UI patch 2022-05-23 20:18:53 +03:00
760a840cc7 2022-05-22 19:50:43 +03:00
0160b011dd 2022-05-22 19:37:15 +03:00
6e09fa9738 Merge branch 'master' of https://github.com/Wizzy69/DiscordBotWithAPI 2022-05-22 19:21:34 +03:00
c7ae9202e6 patch 2022-05-22 19:21:26 +03:00
Wizzy69
55ac4e2b52 Update README.md 2022-05-22 16:30:37 +03:00
96b681bbda Added a minimal GUI based on Avalonia UI library for C# 2022-05-22 16:27:37 +03:00
9f656d5f3f 2022-05-20 09:57:35 +03:00
c719eaf4fd 2022-05-17 13:42:01 +03:00
37 changed files with 1458 additions and 196 deletions

Binary file not shown.

Binary file not shown.

BIN
DiscordBot.dll Normal file

Binary file not shown.

View File

@@ -71,8 +71,6 @@ namespace PluginManager.Core
commandServiceHandler = new CommandHandler(client, service, botPrefix); commandServiceHandler = new CommandHandler(client, service, botPrefix);
await commandServiceHandler.InstallCommandsAsync(); await commandServiceHandler.InstallCommandsAsync();
//wait for isReady to become true
await Task.Delay(2000); await Task.Delay(2000);
while (!isReady) ; while (!isReady) ;

View File

@@ -13,6 +13,8 @@ using PluginManager.Online;
using System.Diagnostics; using System.Diagnostics;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Threading;
namespace DiscordBot namespace DiscordBot
{ {
public class Program public class Program
@@ -25,6 +27,7 @@ namespace DiscordBot
private static bool listLanguagAtStartup = false; private static bool listLanguagAtStartup = false;
private static bool PluginsLoaded = false; private static bool PluginsLoaded = false;
private static bool ShowStartupMessage = true;
/// <summary> /// <summary>
/// The main entry point for the application. /// The main entry point for the application.
@@ -86,12 +89,6 @@ namespace DiscordBot
await languageManager.ListAllLanguages(); await languageManager.ListAllLanguages();
Console_Utilities.ProgressBar pbar;
IProgress<float> progress = null;
Task t;
int prg = 0;
while (true) while (true)
{ {
Console.ForegroundColor = ConsoleColor.White; Console.ForegroundColor = ConsoleColor.White;
@@ -141,8 +138,10 @@ namespace DiscordBot
break; break;
} }
string path = "./Data/Plugins/" + info[0] + "s/" + name + ".dll"; 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]}";
await ServerCom.DownloadFileAsync(info[1], path); await ServerCom.DownloadFileAsync(info[1], path);
Console.WriteLine("\n"); Console.WriteLine("\n");
@@ -153,17 +152,57 @@ namespace DiscordBot
Console.WriteLine($"Downloading requirements for plugin : {name}"); Console.WriteLine($"Downloading requirements for plugin : {name}");
List<string> lines = await ServerCom.ReadTextFromFile(info[2]); List<string> lines = await ServerCom.ReadTextFromFile(info[2]);
int i = 1;
foreach (var line in lines) foreach (var line in lines)
{ {
string[] split = line.Split(','); string[] split = line.Split(',');
Console.WriteLine($"\nDownloading item: {split[1]}"); Console.WriteLine($"\nDownloading item: {split[1]}");
await ServerCom.DownloadFileAsync(split[0], "./" + split[1]); await ServerCom.DownloadFileAsync(split[0], "./" + split[1]);
Console.WriteLine(); Console.WriteLine();
i++;
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, "");
IProgress<float> extractProgress = new Progress<float>(value =>
{
proc = value;
});
new Thread(new Task(() =>
{
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");
File.Delete("./" + split[1]);
}
if (name == "DBUI")
{
Console.WriteLine("Reload with GUI ?[y/n]");
if (Console.ReadKey().Key == ConsoleKey.Y)
{
Process.Start("./DiscordBotGUI.exe");
Environment.Exit(0);
}
}
} }
Console.WriteLine(); Console.WriteLine();
break; break;
@@ -338,6 +377,7 @@ namespace DiscordBot
return false; return false;
} }
public static void SetLanguage(string LanguageName) public static void SetLanguage(string LanguageName)
{ {
string langSettings = Functions.dataFolder + "Language.txt"; string langSettings = Functions.dataFolder + "Language.txt";
@@ -370,7 +410,17 @@ namespace DiscordBot
Console.Clear(); Console.Clear();
Console.ForegroundColor = ConsoleColor.DarkYellow; Console.ForegroundColor = ConsoleColor.DarkYellow;
//Console.WriteLine("Discord BOT for Cross Platform\n\nCreated by: Wizzy\nDiscord: Wizzy#9181"); Console.WriteLine("Discord BOT for Cross Platform");
Console.WriteLine("Created by: Wizzy\nDiscord: Wizzy#9181");
if (ShowStartupMessage)
try
{
Console.WriteLine("Connecting to server ...");
List<string> 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.ForegroundColor = ConsoleColor.White;
Console.WriteLine("============================ Discord BOT - Cross Platform ============================"); Console.WriteLine("============================ Discord BOT - Cross Platform ============================");
string token = Functions.readCodeFromFile(Functions.dataFolder + "DiscordBotCore.data", "BOT_TOKEN", '='); string token = Functions.readCodeFromFile(Functions.dataFolder + "DiscordBotCore.data", "BOT_TOKEN", '=');
@@ -405,7 +455,7 @@ namespace DiscordBot
private static async Task HandleInput(string[] args) private static async Task HandleInput(string[] args)
{ {
if (args.Length > 0) /* if (args.Length > 0)
if (args[0] == "progress") if (args[0] == "progress")
{ {
Console_Utilities.ProgressBar bar = new Console_Utilities.ProgressBar(100, "Download"); Console_Utilities.ProgressBar bar = new Console_Utilities.ProgressBar(100, "Download");
@@ -417,7 +467,10 @@ namespace DiscordBot
} }
return; return;
} }
else if (args[0] == "test")
{
return;
}*/
if (args.Length == 0) if (args.Length == 0)
{ {
@@ -450,7 +503,7 @@ namespace DiscordBot
return; return;
} }
if (len > 0 && (args.Contains("--cmd") || args.Contains("--args"))) if (len > 0 && (args.Contains("--cmd") || args.Contains("--args") || args.Contains("--nomessage")))
{ {
if (args.Contains("lp") || args.Contains("loadplugins")) if (args.Contains("lp") || args.Contains("loadplugins"))
loadPluginsOnStartup = true; loadPluginsOnStartup = true;
@@ -458,12 +511,14 @@ namespace DiscordBot
listPluginsAtStartup = true; listPluginsAtStartup = true;
if (args.Contains("listlang")) if (args.Contains("listlang"))
listLanguagAtStartup = true; listLanguagAtStartup = true;
if (args.Contains("--nomessage"))
ShowStartupMessage = false;
len = 0; len = 0;
} }
if (len == 0 || args[0] != "--exec" && args[0] != "--execute") if (len == 0 || args[0] != "--exec" && args[0] != "--execute")
{ {
Boot b = await StartNoGUI(); Boot b = await StartNoGUI();

454
DiscordBotGUI/.gitignore vendored Normal file
View File

@@ -0,0 +1,454 @@
## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.
##
## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore
# User-specific files
*.rsuser
*.suo
*.user
*.userosscache
*.sln.docstates
# User-specific files (MonoDevelop/Xamarin Studio)
*.userprefs
# Mono auto generated files
mono_crash.*
# Build results
[Dd]ebug/
[Dd]ebugPublic/
[Rr]elease/
[Rr]eleases/
x64/
x86/
[Ww][Ii][Nn]32/
[Aa][Rr][Mm]/
[Aa][Rr][Mm]64/
bld/
[Bb]in/
[Oo]bj/
[Ll]og/
[Ll]ogs/
# Visual Studio 2015/2017 cache/options directory
.vs/
# Uncomment if you have tasks that create the project's static files in wwwroot
#wwwroot/
# Visual Studio 2017 auto generated files
Generated\ Files/
# MSTest test Results
[Tt]est[Rr]esult*/
[Bb]uild[Ll]og.*
# NUnit
*.VisualState.xml
TestResult.xml
nunit-*.xml
# Build Results of an ATL Project
[Dd]ebugPS/
[Rr]eleasePS/
dlldata.c
# Benchmark Results
BenchmarkDotNet.Artifacts/
# .NET Core
project.lock.json
project.fragment.lock.json
artifacts/
# Tye
.tye/
# ASP.NET Scaffolding
ScaffoldingReadMe.txt
# StyleCop
StyleCopReport.xml
# Files built by Visual Studio
*_i.c
*_p.c
*_h.h
*.ilk
*.meta
*.obj
*.iobj
*.pch
*.pdb
*.ipdb
*.pgc
*.pgd
*.rsp
*.sbr
*.tlb
*.tli
*.tlh
*.tmp
*.tmp_proj
*_wpftmp.csproj
*.log
*.vspscc
*.vssscc
.builds
*.pidb
*.svclog
*.scc
# Chutzpah Test files
_Chutzpah*
# Visual C++ cache files
ipch/
*.aps
*.ncb
*.opendb
*.opensdf
*.sdf
*.cachefile
*.VC.db
*.VC.VC.opendb
# Visual Studio profiler
*.psess
*.vsp
*.vspx
*.sap
# Visual Studio Trace Files
*.e2e
# TFS 2012 Local Workspace
$tf/
# Guidance Automation Toolkit
*.gpState
# ReSharper is a .NET coding add-in
_ReSharper*/
*.[Rr]e[Ss]harper
*.DotSettings.user
# TeamCity is a build add-in
_TeamCity*
# DotCover is a Code Coverage Tool
*.dotCover
# AxoCover is a Code Coverage Tool
.axoCover/*
!.axoCover/settings.json
# Coverlet is a free, cross platform Code Coverage Tool
coverage*.json
coverage*.xml
coverage*.info
# Visual Studio code coverage results
*.coverage
*.coveragexml
# NCrunch
_NCrunch_*
.*crunch*.local.xml
nCrunchTemp_*
# MightyMoose
*.mm.*
AutoTest.Net/
# Web workbench (sass)
.sass-cache/
# Installshield output folder
[Ee]xpress/
# DocProject is a documentation generator add-in
DocProject/buildhelp/
DocProject/Help/*.HxT
DocProject/Help/*.HxC
DocProject/Help/*.hhc
DocProject/Help/*.hhk
DocProject/Help/*.hhp
DocProject/Help/Html2
DocProject/Help/html
# Click-Once directory
publish/
# Publish Web Output
*.[Pp]ublish.xml
*.azurePubxml
# Note: Comment the next line if you want to checkin your web deploy settings,
# but database connection strings (with potential passwords) will be unencrypted
*.pubxml
*.publishproj
# Microsoft Azure Web App publish settings. Comment the next line if you want to
# checkin your Azure Web App publish settings, but sensitive information contained
# in these scripts will be unencrypted
PublishScripts/
# NuGet Packages
*.nupkg
# NuGet Symbol Packages
*.snupkg
# The packages folder can be ignored because of Package Restore
**/[Pp]ackages/*
# except build/, which is used as an MSBuild target.
!**/[Pp]ackages/build/
# Uncomment if necessary however generally it will be regenerated when needed
#!**/[Pp]ackages/repositories.config
# NuGet v3's project.json files produces more ignorable files
*.nuget.props
*.nuget.targets
# Microsoft Azure Build Output
csx/
*.build.csdef
# Microsoft Azure Emulator
ecf/
rcf/
# Windows Store app package directories and files
AppPackages/
BundleArtifacts/
Package.StoreAssociation.xml
_pkginfo.txt
*.appx
*.appxbundle
*.appxupload
# Visual Studio cache files
# files ending in .cache can be ignored
*.[Cc]ache
# but keep track of directories ending in .cache
!?*.[Cc]ache/
# Others
ClientBin/
~$*
*~
*.dbmdl
*.dbproj.schemaview
*.jfm
*.pfx
*.publishsettings
orleans.codegen.cs
# Including strong name files can present a security risk
# (https://github.com/github/gitignore/pull/2483#issue-259490424)
#*.snk
# Since there are multiple workflows, uncomment next line to ignore bower_components
# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
#bower_components/
# RIA/Silverlight projects
Generated_Code/
# Backup & report files from converting an old project file
# to a newer Visual Studio version. Backup files are not needed,
# because we have git ;-)
_UpgradeReport_Files/
Backup*/
UpgradeLog*.XML
UpgradeLog*.htm
ServiceFabricBackup/
*.rptproj.bak
# SQL Server files
*.mdf
*.ldf
*.ndf
# Business Intelligence projects
*.rdl.data
*.bim.layout
*.bim_*.settings
*.rptproj.rsuser
*- [Bb]ackup.rdl
*- [Bb]ackup ([0-9]).rdl
*- [Bb]ackup ([0-9][0-9]).rdl
# Microsoft Fakes
FakesAssemblies/
# GhostDoc plugin setting file
*.GhostDoc.xml
# Node.js Tools for Visual Studio
.ntvs_analysis.dat
node_modules/
# Visual Studio 6 build log
*.plg
# Visual Studio 6 workspace options file
*.opt
# Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
*.vbw
# Visual Studio LightSwitch build output
**/*.HTMLClient/GeneratedArtifacts
**/*.DesktopClient/GeneratedArtifacts
**/*.DesktopClient/ModelManifest.xml
**/*.Server/GeneratedArtifacts
**/*.Server/ModelManifest.xml
_Pvt_Extensions
# Paket dependency manager
.paket/paket.exe
paket-files/
# FAKE - F# Make
.fake/
# CodeRush personal settings
.cr/personal
# Python Tools for Visual Studio (PTVS)
__pycache__/
*.pyc
# Cake - Uncomment if you are using it
# tools/**
# !tools/packages.config
# Tabs Studio
*.tss
# Telerik's JustMock configuration file
*.jmconfig
# BizTalk build output
*.btp.cs
*.btm.cs
*.odx.cs
*.xsd.cs
# OpenCover UI analysis results
OpenCover/
# Azure Stream Analytics local run output
ASALocalRun/
# MSBuild Binary and Structured Log
*.binlog
# NVidia Nsight GPU debugger configuration file
*.nvuser
# MFractors (Xamarin productivity tool) working folder
.mfractor/
# Local History for Visual Studio
.localhistory/
# BeatPulse healthcheck temp database
healthchecksdb
# Backup folder for Package Reference Convert tool in Visual Studio 2017
MigrationBackup/
# Ionide (cross platform F# VS Code tools) working folder
.ionide/
# Fody - auto-generated XML schema
FodyWeavers.xsd
##
## Visual studio for Mac
##
# globs
Makefile.in
*.userprefs
*.usertasks
config.make
config.status
aclocal.m4
install-sh
autom4te.cache/
*.tar.gz
tarballs/
test-results/
# Mac bundle stuff
*.dmg
*.app
# content below from: https://github.com/github/gitignore/blob/master/Global/macOS.gitignore
# General
.DS_Store
.AppleDouble
.LSOverride
# Icon must end with two \r
Icon
# Thumbnails
._*
# Files that might appear in the root of a volume
.DocumentRevisions-V100
.fseventsd
.Spotlight-V100
.TemporaryItems
.Trashes
.VolumeIcon.icns
.com.apple.timemachine.donotpresent
# Directories potentially created on remote AFP share
.AppleDB
.AppleDesktop
Network Trash Folder
Temporary Items
.apdisk
# content below from: https://github.com/github/gitignore/blob/master/Global/Windows.gitignore
# Windows thumbnail cache files
Thumbs.db
ehthumbs.db
ehthumbs_vista.db
# Dump file
*.stackdump
# Folder config file
[Dd]esktop.ini
# Recycle Bin used on file shares
$RECYCLE.BIN/
# Windows Installer files
*.cab
*.msi
*.msix
*.msm
*.msp
# Windows shortcuts
*.lnk
# JetBrains Rider
.idea/
*.sln.iml
##
## Visual Studio Code
##
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json

7
DiscordBotGUI/App.axaml Normal file
View File

@@ -0,0 +1,7 @@
<Application xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Class="DiscordBotGUI.App">
<Application.Styles>
<FluentTheme Mode="Dark"/>
</Application.Styles>
</Application>

View File

@@ -0,0 +1,27 @@
using Avalonia;
using Avalonia.Controls.ApplicationLifetimes;
using Avalonia.Markup.Xaml;
namespace DiscordBotGUI
{
public partial class App : Application
{
public override void Initialize()
{
AvaloniaXamlLoader.Load(this);
}
public override void OnFrameworkInitializationCompleted()
{
if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop)
{
desktop.MainWindow = new AppUpdater() { Width = 300, Height = 50, WindowStartupLocation = Avalonia.Controls.WindowStartupLocation.CenterScreen };
}
base.OnFrameworkInitializationCompleted();
}
}
}

View File

@@ -0,0 +1,16 @@
<Window xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d" d:DesignWidth="250" d:DesignHeight="50"
x:Class="DiscordBotGUI.AppUpdater"
Title="AppUpdater"
Background="Transparent"
TransparencyLevelHint="AcrylicBlur"
HasSystemDecorations="False">
<StackPanel Margin="10">
<TextBlock x:Class="DiscordBotGUI.AppUpdater" x:Name="textBox1" Text="Checking for updates..." />
<ProgressBar IsIndeterminate="True" x:Class="DiscordBotGUI.AppUpdater" x:Name="progressBar1" Foreground="Yellow" />
</StackPanel>
</Window>

View File

@@ -0,0 +1,171 @@
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;
namespace DiscordBotGUI
{
public partial class AppUpdater : Window
{
private string _version;
public AppUpdater()
{
InitializeComponent();
if (!File.Exists("./Version.txt"))
{
textBox1.Text = "Checking ...";
File.WriteAllText("./Version.txt", "DiscordBotVersion=0");
//DownloadDiscordBotClientNoGUIAsDLL();
}
Updates();
}
/* private async void DownloadDiscordBotClientNoGUIAsDLL()
{
//await Task.Delay(5000);
string url_bot_dll = "https://sethdiscordbot.000webhostapp.com/Storage/Discord%20Bot/Updates/DiscordBot.dll";
IProgress<float> progress = new Progress<float>((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.dll", progress);
}
catch
{
textBox1.Text = "Error downloading DiscordBot.dll. Server is not responding.";
await Task.Delay(1000);
return;
}
//new MainWindow() { Height = 425, Width = 500 }.Show();
//Close();
}*/
private async void Updates()
{
this.progressBar1.IsIndeterminate = true;
await Task.Delay(1000);
if (!await CheckForUpdates())
{
//await Task.Delay(5000);
textBox1.Text = $"You are running on the latest version ({_version}) !";
await Task.Delay(2000);
new MainWindow() { Height = 425, Width = 650 }.Show();
this.Close();
return;
}
string file = await DownloadNewUpdate();
if (file == null)
{
textBox1.Text = "There was an error while downloading the update !";
await Task.Delay(2000);
new MainWindow() { Height = 425, Width = 650 }.Show();
this.Close();
return;
}
IProgress<float> progress = new Progress<float>((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 ...";
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<string> DownloadNewUpdate()
{
string urlNewUpdateZip = (await ServerCom.ReadTextFromFile("https://sethdiscordbot.000webhostapp.com/Storage/Discord%20Bot/Updates/Version"))[1];
int secondsPast = 0;
bool isDownloading = true;
this.progressBar1.IsIndeterminate = true;
textBox1.Text = "Downloading update ...";
IProgress<long> downloaded = new Progress<long>((bytes) =>
{
(double, string) download = Functions.ConvertBytes(bytes);
textBox1.Text = $"Downloading update ... {Math.Round(download.Item1 / secondsPast, 2)} {download.Item2}/s";
});
IProgress<float> progress = new Progress<float>((percent) =>
{
progressBar1.IsIndeterminate = false;
this.progressBar1.Value = percent;
});
string FileName = $"{urlNewUpdateZip.Split('/')[urlNewUpdateZip.Split('/').Length - 1]}";
try
{
new Thread(new Task(() =>
{
while (isDownloading)
{
Thread.Sleep(1000);
secondsPast++;
}
}).Start).Start();
await ServerCom.DownloadFileAsync(urlNewUpdateZip, FileName, progress, downloaded);
}
catch
{
textBox1.Text = "Error downloading the update. Server is not responding.";
isDownloading = false;
await Task.Delay(1000);
return null;
}
isDownloading = false;
return FileName;
}
private async Task<bool> CheckForUpdates()
{
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];
_version = latest_version;
if (current_version != latest_version)
{
return true;
}
return false;
}
catch (Exception ex)
{
textBox1.Text = "Error while checking for updates. Server is not responding.";
return false;
}
}
}
}

View File

@@ -0,0 +1,40 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>WinExe</OutputType>
<TargetFramework>net6.0</TargetFramework>
<Nullable>enable</Nullable>
<!--Avalonia doesen't support TrimMode=link currently,but we are working on that https://github.com/AvaloniaUI/Avalonia/issues/6892 -->
<TrimMode>copyused</TrimMode>
<BuiltInComInteropSupport>true</BuiltInComInteropSupport>
<BaseOutputPath>..\BUILDS\DiscordBotUI\</BaseOutputPath>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
<Optimize>False</Optimize>
</PropertyGroup>
<ItemGroup>
<AvaloniaXaml Remove="bin\**" />
<Compile Remove="bin\**" />
<EmbeddedResource Remove="bin\**" />
<None Remove="bin\**" />
</ItemGroup>
<ItemGroup>
<None Remove=".gitignore" />
</ItemGroup>
<ItemGroup>
<!--This helps with theme dll-s trimming.
If you will publish your application in self-contained mode with p:PublishTrimmed=true and it will use Fluent theme Default theme will be trimmed from the output and vice versa.
https://github.com/AvaloniaUI/Avalonia/issues/5593 -->
<TrimmableAssembly Include="Avalonia.Themes.Fluent" />
<TrimmableAssembly Include="Avalonia.Themes.Default" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Avalonia" Version="0.10.14" />
<PackageReference Include="Avalonia.Desktop" Version="0.10.14" />
<!--Condition below is needed to remove Avalonia.Diagnostics package from build output in Release configuration.-->
<PackageReference Condition="'$(Configuration)' == 'Debug'" Include="Avalonia.Diagnostics" Version="0.10.14" />
<PackageReference Include="XamlNameReferenceGenerator" Version="1.3.4" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\PluginManager\PluginManager.csproj" />
</ItemGroup>
</Project>

View File

@@ -0,0 +1,35 @@
<Window xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d" d:DesignWidth="500" d:DesignHeight="425"
x:Class="DiscordBotGUI.MainWindow"
Title="DiscordBotGUI"
Background="Transparent"
TransparencyLevelHint="AcrylicBlur"
ExtendClientAreaToDecorationsHint="True" >
<StackPanel Margin="20">
<Menu>
<MenuItem Header="Plugins">
<MenuItem Header="Commands" x:Class="DiscordBotGUI.MainWindow" x:Name="commandsSettingMenuItem" />
<MenuItem Header="Events" x:Class="DiscordBotGUI.MainWindow" x:Name="eventsSettingMenuItem" />
</MenuItem>
</Menu>
<Label x:Class="DiscordBotGUI.MainWindow" x:Name="label1" Content="Discord Token" />
<TextBox x:Class="DiscordBotGUI.MainWindow" x:Name="textBox1" IsReadOnly="True" TextAlignment="Center" Text=""/>
<Label x:Class="DiscordBotGUI.MainWindow" x:Name="label2" Content="Bot Prefix" />
<TextBox x:Class="DiscordBotGUI.MainWindow" x:Name="textBox2" TextAlignment="Center" HorizontalAlignment="Left" IsReadOnly="True" Text=""/>
<Border Background="Black" Padding="0.5" Margin="25"/>
<Label x:Class="DiscordBotGUI.MainWindow" x:Name="label3" Content="Start Arguments: " />
<TextBox x:Class="DiscordBotGUI.MainWindow" x:Name="textBox3" Width="250" TextAlignment="Center" HorizontalAlignment="Left" IsReadOnly="False" Text=""/>
<Label x:Class="DiscordBotGUI.MainWindow" x:Name="label4" Content="" Foreground="Red" Margin="10"/>
<Button x:Class="DiscordBotGUI.MainWindow" x:Name="button1" HorizontalAlignment="Center" VerticalAlignment="Bottom" HorizontalContentAlignment="Center" VerticalContentAlignment="Center" Width="200" Content="Start Bot" Margin="0,75,0,0" />
<Label x:Class="DiscordBotGUI.MainWindow" x:Name="label5" Content="" VerticalAlignment="Bottom" HorizontalAlignment="Right" Margin="0,0,0,0"/>
</StackPanel>
</Window>

View File

@@ -0,0 +1,103 @@
using Avalonia.Controls;
using System.Threading.Tasks;
using PluginManager.Others;
using System.IO;
using System;
using System.Diagnostics;
using DiscordBotGUI.Settings;
using Avalonia.Themes.Fluent;
namespace DiscordBotGUI
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
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) =>
{
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;
}
}
catch
{
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 == 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;
}
}
}

29
DiscordBotGUI/Program.cs Normal file
View File

@@ -0,0 +1,29 @@
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.ApplicationLifetimes;
using System;
using System.IO;
using System.Threading.Tasks;
namespace DiscordBotGUI
{
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)
{
BuildAvaloniaApp()
.StartWithClassicDesktopLifetime(args);
}
// Avalonia configuration, don't remove; also used by visual designer.
public static AppBuilder BuildAvaloniaApp()
=> AppBuilder.Configure<App>()
.UsePlatformDetect()
.LogToTrace();
}
}

View File

@@ -0,0 +1,21 @@
<Window xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d" d:DesignWidth="550" d:DesignHeight="200"
x:Class="DiscordBotGUI.Settings.Commands"
Title="Commands"
Background="Transparent"
TransparencyLevelHint="AcrylicBlur"
ExtendClientAreaToDecorationsHint="True">
<StackPanel x:Class="DiscordBotGUI.Settings.Commands" x:Name="stackpanel1" Margin="10">
<Label Content="Installed Commands" />
<TextBox x:Class="DiscordBotGUI.Settings.Commands" x:Name="textbox1" TextAlignment="Left" IsReadOnly="True" />
<Label Content="Install another command" />
<ComboBox x:Class="DiscordBotGUI.Settings.Commands" x:Name="comboBox1" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="0,10" Padding="200,0" />
<Button x:Class="DiscordBotGUI.Settings.Commands" x:Name="button1" HorizontalAlignment="Left" Content="Install" />
<ProgressBar x:Class="DiscordBotGUI.Settings.Commands" x:Name="progressBar1" HorizontalAlignment="Left" Margin="0,10" Foreground="Yellow" />
<Label x:Class="DiscordBotGUI.Settings.Commands" x:Name="label1" Content="" HorizontalAlignment="Left" Margin="0,10" />
</StackPanel>
</Window>

View File

@@ -0,0 +1,138 @@
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.IO;
namespace DiscordBotGUI.Settings
{
public partial class Commands : Window
{
List<string> commands = new List<string>();
public Commands()
{
InitializeComponent();
LoadData();
LoadComboBox();
button1.Click += async (sender, e) =>
{
await Download();
};
}
private void LoadData()
{
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";
}
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<string> data = new List<string>();
for (int i = 0; i < plugins.Length; i++)
{
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;
}
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;
IProgress<float> progress = new Progress<float>(async value =>
{
label1.Content = $"Downloading {pluginName} {MathF.Round(value, 2)}%";
if (value == 1f)
{
label1.Content = "Successfully Downloaded " + pluginName;
LoadData();
LoadComboBox();
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<string> 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;
}
}
}

View File

@@ -0,0 +1,20 @@
<Window xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d" d:DesignWidth="550" d:DesignHeight="200"
x:Class="DiscordBotGUI.Settings.Events"
Title="Events"
Background="Transparent"
TransparencyLevelHint="AcrylicBlur"
ExtendClientAreaToDecorationsHint="True">
<StackPanel Margin="10">
<Label Content="Installed Events" />
<TextBox x:Class="DiscordBotGUI.Settings.Events" x:Name="textbox1" TextAlignment="Left" IsReadOnly="True" />
<Label Content="Install another Events" />
<ComboBox x:Class="DiscordBotGUI.Settings.Events" x:Name="comboBox1" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="0,10" Padding="200,0" />
<Button x:Class="DiscordBotGUI.Settings.Events" x:Name="button1" HorizontalAlignment="Left" Content="Install" />
<ProgressBar x:Class="DiscordBotGUI.Settings.Events" x:Name="progressBar1" HorizontalAlignment="Left" Margin="0,10" Foreground="Yellow" />
<Label x:Class="DiscordBotGUI.Settings.Events" x:Name="label1" Content="" HorizontalAlignment="Left" Margin="0,10" />
</StackPanel>
</Window>

View File

@@ -0,0 +1,139 @@
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.IO;
namespace DiscordBotGUI.Settings
{
public partial class Events : Window
{
List<string> events = new List<string>();
public Events()
{
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 = 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";
}
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<string> data = new List<string>();
for (int i = 0; i < plugins.Length; i++)
{
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;
}
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();
if (URL == null) return;
IProgress<float> progress = new Progress<float>(async value =>
{
label1.Content = $"Downloading {pluginName} {MathF.Round(value, 2)}%";
if (value == 1f)
{
label1.Content = "Successfully Downloaded " + pluginName;
LoadData();
LoadComboBox();
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<string> 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 = "";
}
}
}

View File

@@ -23,9 +23,9 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "CMD_Utils", "CMD_Utils\CMD_
EndProject EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MusicCommands", "MusicCommands\MusicCommands.csproj", "{B1B4976E-5112-4217-B57B-3A03C5207B6E}" Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MusicCommands", "MusicCommands\MusicCommands.csproj", "{B1B4976E-5112-4217-B57B-3A03C5207B6E}"
EndProject EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Holiday events", "Holiday events\Holiday events.csproj", "{108BD621-EC08-4AC4-86D2-79B429562A90}" Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Games", "FreeGames\Games.csproj", "{7CC0819E-2BC0-44F0-8D92-EC442F36E1BB}"
EndProject EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "New User", "New User\New User.csproj", "{02217691-EF7E-4FB2-91FC-C6EF07BF6094}" Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DiscordBotGUI", "DiscordBotGUI\DiscordBotGUI.csproj", "{7B5899F0-0218-4537-8C74-6210ED2D3690}"
EndProject EndProject
Global Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution GlobalSection(SolutionConfigurationPlatforms) = preSolution
@@ -61,14 +61,14 @@ Global
{B1B4976E-5112-4217-B57B-3A03C5207B6E}.Debug|Any CPU.Build.0 = Debug|Any CPU {B1B4976E-5112-4217-B57B-3A03C5207B6E}.Debug|Any CPU.Build.0 = Debug|Any CPU
{B1B4976E-5112-4217-B57B-3A03C5207B6E}.Release|Any CPU.ActiveCfg = Release|Any CPU {B1B4976E-5112-4217-B57B-3A03C5207B6E}.Release|Any CPU.ActiveCfg = Release|Any CPU
{B1B4976E-5112-4217-B57B-3A03C5207B6E}.Release|Any CPU.Build.0 = Release|Any CPU {B1B4976E-5112-4217-B57B-3A03C5207B6E}.Release|Any CPU.Build.0 = Release|Any CPU
{108BD621-EC08-4AC4-86D2-79B429562A90}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {7CC0819E-2BC0-44F0-8D92-EC442F36E1BB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{108BD621-EC08-4AC4-86D2-79B429562A90}.Debug|Any CPU.Build.0 = Debug|Any CPU {7CC0819E-2BC0-44F0-8D92-EC442F36E1BB}.Debug|Any CPU.Build.0 = Debug|Any CPU
{108BD621-EC08-4AC4-86D2-79B429562A90}.Release|Any CPU.ActiveCfg = Release|Any CPU {7CC0819E-2BC0-44F0-8D92-EC442F36E1BB}.Release|Any CPU.ActiveCfg = Release|Any CPU
{108BD621-EC08-4AC4-86D2-79B429562A90}.Release|Any CPU.Build.0 = Release|Any CPU {7CC0819E-2BC0-44F0-8D92-EC442F36E1BB}.Release|Any CPU.Build.0 = Release|Any CPU
{02217691-EF7E-4FB2-91FC-C6EF07BF6094}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {7B5899F0-0218-4537-8C74-6210ED2D3690}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{02217691-EF7E-4FB2-91FC-C6EF07BF6094}.Debug|Any CPU.Build.0 = Debug|Any CPU {7B5899F0-0218-4537-8C74-6210ED2D3690}.Debug|Any CPU.Build.0 = Debug|Any CPU
{02217691-EF7E-4FB2-91FC-C6EF07BF6094}.Release|Any CPU.ActiveCfg = Release|Any CPU {7B5899F0-0218-4537-8C74-6210ED2D3690}.Release|Any CPU.ActiveCfg = Release|Any CPU
{02217691-EF7E-4FB2-91FC-C6EF07BF6094}.Release|Any CPU.Build.0 = Release|Any CPU {7B5899F0-0218-4537-8C74-6210ED2D3690}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection EndGlobalSection
GlobalSection(SolutionProperties) = preSolution GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE HideSolutionNode = FALSE
@@ -81,8 +81,7 @@ Global
{CE9DBF06-38A0-4192-8B3E-4009210D040D} = {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} {E26C87A4-3DD6-4B58-B14B-C8E086B852F9} = {449FA364-0B72-43FF-B3A3-806E2916200E}
{B1B4976E-5112-4217-B57B-3A03C5207B6E} = {449FA364-0B72-43FF-B3A3-806E2916200E} {B1B4976E-5112-4217-B57B-3A03C5207B6E} = {449FA364-0B72-43FF-B3A3-806E2916200E}
{108BD621-EC08-4AC4-86D2-79B429562A90} = {A290C028-77C4-4D1D-AB43-DDFE6ABD9012} {7CC0819E-2BC0-44F0-8D92-EC442F36E1BB} = {449FA364-0B72-43FF-B3A3-806E2916200E}
{02217691-EF7E-4FB2-91FC-C6EF07BF6094} = {A290C028-77C4-4D1D-AB43-DDFE6ABD9012}
EndGlobalSection EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {3FB3C5DE-ED21-4D2E-ABDD-3A00EE4A2FFF} SolutionGuid = {3FB3C5DE-ED21-4D2E-ABDD-3A00EE4A2FFF}

28
FreeGames/Game.cs Normal file
View File

@@ -0,0 +1,28 @@
using PluginManager.Interfaces;
using Games.Objects;
namespace Games;
public class Game : DBCommand
{
public string Command => "game";
public string Description => "Display info about the specified game";
public string Usage => "game <game>";
public bool canUseDM => false;
public bool canUseServer => true;
public bool requireAdmin => false;
public async void Execute(Discord.Commands.SocketCommandContext context, Discord.WebSocket.SocketMessage message,
Discord.WebSocket.DiscordSocketClient client, bool isDM)
{
string game_name = PluginManager.Others.Functions.MergeStrings(message.Content.Split(' '), 1);
string game_url = await GameData.GetSteamLinkFromGame(game_name);
if (game_url is null || game_url == null)
{
await message.Channel.SendMessageAsync("Could not find the game. Try to be more specific or check for spelling errors.");
return;
}
await context.Channel.SendMessageAsync(game_url);
}
}

View File

@@ -2,11 +2,16 @@
<PropertyGroup> <PropertyGroup>
<TargetFramework>net6.0</TargetFramework> <TargetFramework>net6.0</TargetFramework>
<RootNamespace>New_User</RootNamespace>
<ImplicitUsings>enable</ImplicitUsings> <ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable> <Nullable>enable</Nullable>
</PropertyGroup> </PropertyGroup>
<ItemGroup>
<Compile Remove="Server\**" />
<EmbeddedResource Remove="Server\**" />
<None Remove="Server\**" />
</ItemGroup>
<ItemGroup> <ItemGroup>
<ProjectReference Include="..\PluginManager\PluginManager.csproj" /> <ProjectReference Include="..\PluginManager\PluginManager.csproj" />
</ItemGroup> </ItemGroup>

View File

@@ -0,0 +1,24 @@
using PluginManager.Online;
namespace Games.Objects;
public class GameData
{
internal async static Task<string> GetSteamLinkFromGame(string GameName)
{
string URL = $"https://store.steampowered.com/search?term={GameName.Replace(" ", "+")}";
List<string> lines = await ServerCom.ReadTextFromFile(URL);
string? gameData = (
from s in lines
where s.Contains(GameName.Replace(" ", "_"), StringComparison.OrdinalIgnoreCase)
select s).FirstOrDefault();
if (gameData is null) return null;
string GameURL = gameData.Split('\"')[1].Split('?')[0];
if (GameURL == "menuitem")
return null;
return GameURL;
}
}

View File

@@ -1,14 +0,0 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<RootNamespace>Holiday_events</RootNamespace>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\PluginManager\PluginManager.csproj" />
</ItemGroup>
</Project>

View File

@@ -1,88 +0,0 @@
using Discord.WebSocket;
using Discord;
using PluginManager.Interfaces;
namespace Holiday_events
{
public class Holiday : DBEvent
{
public string name => "Holiday Events";
public string description => "Happy Holiday";
public async void Start(DiscordSocketClient client)
{
while(true)
{
if (DateTime.Today.Hour == 0 && DateTime.Today.Minute == 0)
await VerificareData(client);
await Task.Delay(1000 * 60-1);
}
}
private async Task VerificareData(DiscordSocketClient client)
{
string day = DateTime.Now.Day.ToString();
string month = DateTime.Now.Month.ToString();
if (day == "1" && month == "1")
{
EmbedBuilder builder = new EmbedBuilder();
builder.Title = "Happy New Year!";
builder.Description = $"Make way for {DateTime.Now.Year}!\nNew adventures are around the corner.";
builder.ImageUrl = "https://i.imgur.com/AWhxExZ.jpg";
builder.Color = Color.Gold;
await client.GetGuild(client.Guilds.First().Id).DefaultChannel.SendMessageAsync(embed: builder.Build());
}
else if (day == "1" && month == "5")
{
EmbedBuilder builder = new EmbedBuilder();
builder.Title = "Happy May Day!";
builder.Description = " You have worked very hard throughout the year to meet all your goals. Now it is a day to relax and rejoice.\nSending you warm wishes on International Workers Day.";
builder.ImageUrl = "https://i.imgur.com/SIIwelU.jpeg";
builder.Color = Color.LightOrange;
await client.GetGuild(client.Guilds.First().Id).DefaultChannel.SendMessageAsync(embed: builder.Build());
}
else if (day == "25" && month == "12")
{
EmbedBuilder builder = new EmbedBuilder();
builder.Title = "Happy May Day!";
builder.Description = "Wishing you and your family health, happiness, peace and prosperity this Christmas and in the coming New Year.";
builder.ImageUrl = "https://i.imgur.com/qsDOI4t.jpg";
builder.Color = Color.Red;
await client.GetGuild(client.Guilds.First().Id).DefaultChannel.SendMessageAsync(embed: builder.Build());
}
else if (day =="1" && month == "12")
{
EmbedBuilder builder = new EmbedBuilder();
builder.Title = "Romania National Day";
builder.Description = "I wish the people of Romania a happy national day and peace and prosperity in the year ahead.";
builder.ImageUrl = "https://i.imgur.com/vHQnFHp.jpg";
builder.Color = Color.Blue;
await client.GetGuild(client.Guilds.First().Id).DefaultChannel.SendMessageAsync(embed: builder.Build());
}
else if (day == "8" && month == "3")
{
EmbedBuilder builder = new EmbedBuilder();
builder.Title = "National Womens Day";
builder.Description = "Today we celebrate every woman on the planet. You bring so much love and beauty into our world just by being in it, and it makes everyone a little bit happier. The Sun shines brighter when you smile, ladies, so keep smiling! Happy Womans Day!";
builder.ImageUrl = "https://i.imgur.com/dVzQ3rp.jpg";
builder.Color = Color.Red;
await client.GetGuild(client.Guilds.First().Id).DefaultChannel.SendMessageAsync(embed: builder.Build());
}
else if (day == "31" && month == "10")
{
EmbedBuilder builder = new EmbedBuilder();
builder.Title = "Happy Halloween";
builder.Description = "This October, may your treats be many and your tricks be few. Hope you have a sweet Halloween.";
builder.ImageUrl = "https://i.imgur.com/cJf6EgI.jpg";
builder.Color = Color.Orange;
await client.GetGuild(client.Guilds.First().Id).DefaultChannel.SendMessageAsync(embed: builder.Build());
}
}
}
}

View File

@@ -83,13 +83,8 @@ namespace MusicCommands
byte[] buffer = new byte[bsize]; byte[] buffer = new byte[bsize];
int read = await ms.ReadAsync(buffer, 0, buffer.Length); int read = await ms.ReadAsync(buffer, 0, buffer.Length);
if (read > 0) if (read > 0)
{
await outputStream.WriteAsync(buffer, 0, read); await outputStream.WriteAsync(buffer, 0, read);
} else break;
else
{
break;
}
} }

View File

@@ -1,27 +0,0 @@
using Discord;
using Discord.WebSocket;
using PluginManager.Interfaces;
namespace New_User
{
public class Greeting : DBEvent
{
public string name =>"Greeting";
public string description => "Greets new users";
public void Start(DiscordSocketClient client)
{
client.UserJoined += async (arg) =>
{
IGuild? guild = client.Guilds.FirstOrDefault();
ITextChannel chn = await guild.GetDefaultChannelAsync();
await chn.SendMessageAsync($"A wild {arg.Username} has apperead!");
IRole? role = guild.Roles.FirstOrDefault(x => x.Name == "New User");
if (role == null)
await arg.Guild.CreateRoleAsync("New User", GuildPermissions.None, Color.DarkBlue);
await arg.AddRoleAsync(role);
};
}
}
}

View File

@@ -0,0 +1,13 @@
<Window
x:Class="PluginManager.BlankWindow1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:PluginManager"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d">
<Grid>
</Grid>
</Window>

View File

@@ -37,7 +37,7 @@ namespace PluginManager.Items
case 3: Console.Write("|"); break; case 3: Console.Write("|"); break;
} }
Console.SetCursorPosition(Console.CursorLeft - 1, Console.CursorTop); Console.SetCursorPosition(Console.CursorLeft - 1, Console.CursorTop);
await Task.Delay(500); await Task.Delay(250);
} }
} }
@@ -47,7 +47,7 @@ namespace PluginManager.Items
public void Stop() public void Stop()
{ {
if (!isSpinning) if (!isSpinning)
throw new Others.Exceptions.APIException("The spinner was not running", "Stop()"); throw new Others.Exceptions.APIException("Spinner was not spinning", GetType());
isSpinning = false; isSpinning = false;
} }
} }

View File

@@ -53,7 +53,7 @@ namespace PluginManager.LanguageSystem
if (!LanguageFileLocation.EndsWith(LanguageFileExtension)) if (!LanguageFileLocation.EndsWith(LanguageFileExtension))
{ {
Console.WriteLine("Failed to load language from file: " + LanguageFileLocation + Console.WriteLine("Failed to load language from file: " + LanguageFileLocation +
"\nFile extension is not .lng"); "\nFile extension is not " + LanguageFileExtension);
return null; return null;
} }

View File

@@ -84,6 +84,7 @@ namespace PluginManager.Loaders
} }
} }
} }
catch (Exception ex) catch (Exception ex)
{ {

View File

@@ -19,7 +19,7 @@ namespace PluginManager.Online.Helpers
/// <param name="cancellation">The cancellation token</param> /// <param name="cancellation">The cancellation token</param>
/// <returns></returns> /// <returns></returns>
internal static async Task DownloadFileAsync(this HttpClient client, string url, Stream destination, internal static async Task DownloadFileAsync(this HttpClient client, string url, Stream destination,
IProgress<float> progress = null, IProgress<long> downloadedBytes = null, CancellationToken cancellation = default) IProgress<float>? progress = null, IProgress<long>? downloadedBytes = null, CancellationToken cancellation = default)
{ {
using (var response = await client.GetAsync(url, HttpCompletionOption.ResponseHeadersRead)) using (var response = await client.GetAsync(url, HttpCompletionOption.ResponseHeadersRead))
{ {
@@ -40,7 +40,7 @@ namespace PluginManager.Online.Helpers
var relativeProgress = new Progress<long>(totalBytes => var relativeProgress = new Progress<long>(totalBytes =>
{ {
progress.Report((float)totalBytes / contentLength.Value * 100); progress.Report((float)totalBytes / contentLength.Value * 100);
downloadedBytes.Report(totalBytes); downloadedBytes?.Report(totalBytes);
}); });
// Use extension method to report progress while downloading // Use extension method to report progress while downloading
await download.CopyToOtherStreamAsync(destination, 81920, relativeProgress, cancellation); await download.CopyToOtherStreamAsync(destination, 81920, relativeProgress, cancellation);
@@ -62,5 +62,8 @@ namespace PluginManager.Online.Helpers
return await client.GetStringAsync(url); return await client.GetStringAsync(url);
} }
} }
} }
} }

View File

@@ -30,7 +30,7 @@ namespace PluginManager.Online
/// <param name="location">The location where to store the downloaded data</param> /// <param name="location">The location where to store the downloaded data</param>
/// <param name="progress">The <see cref="IProgress{T}"/> to track the download</param> /// <param name="progress">The <see cref="IProgress{T}"/> to track the download</param>
/// <returns></returns> /// <returns></returns>
public static async Task DownloadFileAsync(string URL, string location, IProgress<float> progress, IProgress<long> downloadedBytes) public static async Task DownloadFileAsync(string URL, string location, IProgress<float> progress, IProgress<long>? downloadedBytes = null)
{ {
using (var client = new System.Net.Http.HttpClient()) using (var client = new System.Net.Http.HttpClient())
{ {
@@ -54,8 +54,6 @@ namespace PluginManager.Online
bool isDownloading = true; bool isDownloading = true;
int c_progress = 0; int c_progress = 0;
//long m_dwBytes = 0;
Others.Console_Utilities.ProgressBar pbar = new Others.Console_Utilities.ProgressBar(100, ""); Others.Console_Utilities.ProgressBar pbar = new Others.Console_Utilities.ProgressBar(100, "");
IProgress<float> progress = new Progress<float>(percent => IProgress<float> progress = new Progress<float>(percent =>
@@ -63,12 +61,7 @@ namespace PluginManager.Online
c_progress = (int)percent; c_progress = (int)percent;
}); });
IProgress<long> progress_downloaded = new Progress<long>(downloadedBytes => Task updateProgressBarTask = new Task(() =>
{
//m_dwBytes = downloadedBytes;
});
Task updateProgressBarTask = new Task(async () =>
{ {
while (isDownloading) while (isDownloading)
{ {
@@ -80,12 +73,15 @@ namespace PluginManager.Online
}); });
new System.Threading.Thread(updateProgressBarTask.Start).Start(); new System.Threading.Thread(updateProgressBarTask.Start).Start();
await DownloadFileAsync(URL, location, progress, progress_downloaded); await DownloadFileAsync(URL, location, progress);
isDownloading = false;
c_progress = 100; c_progress = 100;
pbar.Update(100); pbar.Update(100);
isDownloading = false;
} }
} }
} }

View File

@@ -66,6 +66,17 @@ namespace PluginManager.Others.Exceptions
{ {
} }
/// <summary>
/// The APIException constructor
/// </summary>
/// <param name="message">The error message</param>
/// <param name="errorLocation">The class where the error was thrown</param>
public APIException(string message, Type errorLocation) : base(message)
{
Function = errorLocation.FullName;
}
/// <summary> /// <summary>
/// Method to print the error to <see cref="Console"/> /// Method to print the error to <see cref="Console"/>
/// </summary> /// </summary>

View File

@@ -129,7 +129,8 @@ namespace PluginManager.Others
foreach (var line in lines) foreach (var line in lines)
if (line.StartsWith(Code)) if (line.StartsWith(Code))
{ {
File.AppendAllText(file, Code + separator + newValue + "\n"); ok = true; File.AppendAllText(file, Code + separator + newValue + "\n");
ok = true;
} }
else File.AppendAllText(file, line + "\n"); else File.AppendAllText(file, line + "\n");
@@ -212,7 +213,7 @@ namespace PluginManager.Others
/// <exception cref="ArgumentOutOfRangeException">Triggered if <paramref name="bufferSize"/> is less then or equal to 0</exception> /// <exception cref="ArgumentOutOfRangeException">Triggered if <paramref name="bufferSize"/> is less then or equal to 0</exception>
/// <exception cref="InvalidOperationException">Triggered if <paramref name="stream"/> is not readable</exception> /// <exception cref="InvalidOperationException">Triggered if <paramref name="stream"/> is not readable</exception>
/// <exception cref="ArgumentException">Triggered in <paramref name="destination"/> is not writable</exception> /// <exception cref="ArgumentException">Triggered in <paramref name="destination"/> is not writable</exception>
public static async Task CopyToOtherStreamAsync(this Stream stream, Stream destination, int bufferSize, IProgress<long> progress = null, CancellationToken cancellationToken = default) public static async Task CopyToOtherStreamAsync(this Stream stream, Stream destination, int bufferSize, IProgress<long>? progress = null, CancellationToken cancellationToken = default)
{ {
if (stream == null) if (stream == null)
throw new ArgumentNullException(nameof(stream)); throw new ArgumentNullException(nameof(stream));
@@ -236,5 +237,52 @@ namespace PluginManager.Others
} }
} }
/// <summary>
/// Extract zip to location
/// </summary>
/// <param name="zip">The zip location</param>
/// <param name="folder">The target location</param>
/// <returns></returns>
public static async Task ExtractArchive(string zip, string folder, IProgress<float> progress)
{
if (!Directory.Exists(folder))
Directory.CreateDirectory(folder);
using (ZipArchive archive = ZipFile.OpenRead(zip))
{
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++;
}
await Task.Delay(10);
progress.Report((float)currentZIPFile / totalZIPFiles * 100);
}
}
}
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");
}
} }
} }

View File

@@ -11,8 +11,18 @@
<DebugSymbols>false</DebugSymbols> <DebugSymbols>false</DebugSymbols>
</PropertyGroup> </PropertyGroup>
<ItemGroup>
<None Remove="BlankWindow1.xaml" />
</ItemGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="Discord.Net" Version="3.6.1" /> <PackageReference Include="Discord.Net" Version="3.6.1" />
</ItemGroup> </ItemGroup>
<ItemGroup>
<Page Include="BlankWindow1.xaml">
<Generator>MSBuild:Compile</Generator>
</Page>
</ItemGroup>
</Project> </Project>

View File

@@ -1,7 +1,11 @@
# Seth Discord Bot # Seth Discord Bot
This is a Discord Bot made with C# that accepts plugins as extensions for more commands and events. All basic commands are built in already in the PluginManager class library. This is a Discord Bot made with C# that accepts plugins as extensions for more commands and events. All basic commands are built in already in the PluginManager class library.
This project is based on .NET 6 (C#) and [Discord.Net](https://github.com/discord-net/Discord.Net) This project is based on:
- [.NET 6 (C#)](https://dotnet.microsoft.com/en-us/download/dotnet/6.0)
- [Discord.Net](https://github.com/discord-net/Discord.Net)
- [Avalonia UI](https://avaloniaui.net/) for `DiscordBotUI` extension
## Plugins ## Plugins

1
Version.txt Normal file
View File

@@ -0,0 +1 @@
0