diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index b03b75a..505588d 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1,44 +1,44 @@ -name: FosscordSharp CI - -on: - push: - branches: [ master ] - pull_request: - branches: [ master ] - -jobs: - build: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v2 - - name: Setup .NET Core - uses: actions/setup-dotnet@v1 - with: - dotnet-version: '5.0.x' - - name: Discord webhook - run: | - curl -i -H "Accept: application/json" -H "Content-Type: application/json" -X POST --data "{\"content\": \"<:fox_wave_duckmaster:900151686616715306> New commit by $GITHUB_ACTOR: [commit]($GITHUB_SERVER_URL/$GITHUB_REPOSITORY/commit/$GITHUB_SHA), [run](<$GITHUB_SERVER_URL/$GITHUB_REPOSITORY/actions/runs/$GITHUB_RUN_ID?check_suite_focus=true>)\"}" ${{ secrets.DISCORD_WEBHOOK }} - curl -i -H "Accept: application/json" -H "Content-Type: application/json" -X POST --data "{\"content\": \"<:fox_wave_duckmaster:900151686616715306> New commit by $GITHUB_ACTOR: [commit]($GITHUB_SERVER_URL/$GITHUB_REPOSITORY/commit/$GITHUB_SHA), [run](<$GITHUB_SERVER_URL/$GITHUB_REPOSITORY/actions/runs/$GITHUB_RUN_ID?check_suite_focus=true>)\"}" ${{ secrets.DISCORD_WEBHOOK2 }} - - name: Install dependencies - run: dotnet restore - - name: Build - run: dotnet build --configuration Release --no-restore - - name: Test - run: dotnet test - - name: Publish - run: | - rm -rf *.nupkg - dotnet pack --nologo --version-suffix preview$GITHUB_RUN_ID.$(git rev-parse --short HEAD) -o . FosscordSharp - dotnet nuget push $(ls *.nupkg) -k ${{ secrets.NUGET_KEY }} --source https://api.nuget.org/v3/index.json --skip-duplicate - if: ${{ success() }} - - name: Publish success - run: | - curl -i -H "Accept: application/json" -H "Content-Type: application/json" -X POST --data "{\"content\": \"<:foxSip:899416354728329217> Build, test and publish successful! ([See run](<$GITHUB_SERVER_URL/$GITHUB_REPOSITORY/actions/runs/$GITHUB_RUN_ID?check_suite_focus=true>))\"}" ${{ secrets.DISCORD_WEBHOOK }} - curl -i -H "Accept: application/json" -H "Content-Type: application/json" -X POST --data "{\"content\": \"<:foxSip:899416354728329217> Build, test and publish successful! ([See run](<$GITHUB_SERVER_URL/$GITHUB_REPOSITORY/actions/runs/$GITHUB_RUN_ID?check_suite_focus=true>))\"}" ${{ secrets.DISCORD_WEBHOOK2 }} - if: ${{ success() }} - - name: Publish failure - run: | - curl -i -H "Accept: application/json" -H "Content-Type: application/json" -X POST --data "{\"content\": \"<:fox_cry_storfus:900093667405070396> Build, test or publish failed! ([See run](<$GITHUB_SERVER_URL/$GITHUB_REPOSITORY/actions/runs/$GITHUB_RUN_ID?check_suite_focus=true>))\"}" ${{ secrets.DISCORD_WEBHOOK }} - curl -i -H "Accept: application/json" -H "Content-Type: application/json" -X POST --data "{\"content\": \"<:fox_cry_storfus:900093667405070396> Build, test or publish failed! ([See run](<$GITHUB_SERVER_URL/$GITHUB_REPOSITORY/actions/runs/$GITHUB_RUN_ID?check_suite_focus=true>))\"}" ${{ secrets.DISCORD_WEBHOOK2 }} - if: ${{ failure() }} +name: FosscordSharp CI + +on: + push: + branches: [ master ] + pull_request: + branches: [ master ] + +jobs: + build: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + - name: Setup .NET Core + uses: actions/setup-dotnet@v1 + with: + dotnet-version: '5.0.x' + - name: Discord webhook + run: | + curl -i -H "Accept: application/json" -H "Content-Type: application/json" -X POST --data "{\"content\": \"<:fox_wave_duckmaster:900151686616715306> New commit by $GITHUB_ACTOR: [commit]($GITHUB_SERVER_URL/$GITHUB_REPOSITORY/commit/$GITHUB_SHA), [run](<$GITHUB_SERVER_URL/$GITHUB_REPOSITORY/actions/runs/$GITHUB_RUN_ID?check_suite_focus=true>)\"}" ${{ secrets.DISCORD_WEBHOOK }} + curl -i -H "Accept: application/json" -H "Content-Type: application/json" -X POST --data "{\"content\": \"<:fox_wave_duckmaster:900151686616715306> New commit by $GITHUB_ACTOR: [commit]($GITHUB_SERVER_URL/$GITHUB_REPOSITORY/commit/$GITHUB_SHA), [run](<$GITHUB_SERVER_URL/$GITHUB_REPOSITORY/actions/runs/$GITHUB_RUN_ID?check_suite_focus=true>)\"}" ${{ secrets.DISCORD_WEBHOOK2 }} + - name: Install dependencies + run: dotnet restore + - name: Build + run: dotnet build --configuration Release --no-restore + - name: Test + run: dotnet test + - name: Publish + run: | + rm -rf *.nupkg + dotnet pack --nologo --version-suffix preview$GITHUB_RUN_ID.$(git rev-parse --short HEAD) -o . FosscordSharp + dotnet nuget push $(ls *.nupkg) -k ${{ secrets.NUGET_KEY }} --source https://api.nuget.org/v3/index.json --skip-duplicate + if: ${{ success() }} + - name: Publish success + run: | + curl -i -H "Accept: application/json" -H "Content-Type: application/json" -X POST --data "{\"content\": \"<:foxSip:899416354728329217> Build, test and publish successful! ([See run](<$GITHUB_SERVER_URL/$GITHUB_REPOSITORY/actions/runs/$GITHUB_RUN_ID?check_suite_focus=true>))\"}" ${{ secrets.DISCORD_WEBHOOK }} + curl -i -H "Accept: application/json" -H "Content-Type: application/json" -X POST --data "{\"content\": \"<:foxSip:899416354728329217> Build, test and publish successful! ([See run](<$GITHUB_SERVER_URL/$GITHUB_REPOSITORY/actions/runs/$GITHUB_RUN_ID?check_suite_focus=true>))\"}" ${{ secrets.DISCORD_WEBHOOK2 }} + if: ${{ success() }} + - name: Publish failure + run: | + curl -i -H "Accept: application/json" -H "Content-Type: application/json" -X POST --data "{\"content\": \"<:fox_cry_storfus:900093667405070396> Build, test or publish failed! ([See run](<$GITHUB_SERVER_URL/$GITHUB_REPOSITORY/actions/runs/$GITHUB_RUN_ID?check_suite_focus=true>))\"}" ${{ secrets.DISCORD_WEBHOOK }} + curl -i -H "Accept: application/json" -H "Content-Type: application/json" -X POST --data "{\"content\": \"<:fox_cry_storfus:900093667405070396> Build, test or publish failed! ([See run](<$GITHUB_SERVER_URL/$GITHUB_REPOSITORY/actions/runs/$GITHUB_RUN_ID?check_suite_focus=true>))\"}" ${{ secrets.DISCORD_WEBHOOK2 }} + if: ${{ failure() }} \ No newline at end of file diff --git a/.gitignore b/.gitignore index 679e883..9650b34 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,3 @@ -.idea/ -obj/ -bin/ +.idea/ +obj/ +bin/ diff --git a/FosscordSharp.ExampleBot/FosscordSharp.ExampleBot.csproj b/FosscordSharp.ExampleBot/FosscordSharp.ExampleBot.csproj index 97d415e..036b381 100644 --- a/FosscordSharp.ExampleBot/FosscordSharp.ExampleBot.csproj +++ b/FosscordSharp.ExampleBot/FosscordSharp.ExampleBot.csproj @@ -1,17 +1,17 @@ - - - - Exe - net5.0 - - - - - - - - - - - - + + + + Exe + net5.0 + + + + + + + + + + + + diff --git a/FosscordSharp.ExampleBot/Program.cs b/FosscordSharp.ExampleBot/Program.cs index ad66824..f2c1fdf 100644 --- a/FosscordSharp.ExampleBot/Program.cs +++ b/FosscordSharp.ExampleBot/Program.cs @@ -1,175 +1,183 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Threading; -using System.Threading.Tasks; -using FosscordSharp.Entities; -using FosscordSharp.EventArgs; -using Microsoft.VisualBasic; - -namespace FosscordSharp.ExampleBot -{ - class Program - { - private static Dictionary clients = new(); - static void Main(string[] args) - { - if(!File.Exists("instances.txt")) File.WriteAllText("instances.txt", "https://dev.fosscord.com\nhttps://fosscord.thearcanebrony.net\n"); - foreach (var inst in File.ReadAllLines("instances.txt")) - { - Run(inst); - } - Thread.Sleep(int.MaxValue); - } - static async void Run(string endpoint) - { - FosscordClient client; - clients.Add(endpoint, client = new FosscordClient(new() - { - // Email = $"FosscordSharp{Environment.TickCount64}@example.com", - Email = $"FosscordSharpDev@example.com", - Password = "FosscordSharp", - // Endpoint = "https://dev.fosscord.com", - // Endpoint = "https://fosscord.thearcanebrony.net", - Endpoint = endpoint, - Verbose = false, - ShouldRegister = true, - RegistrationOptions = - { - Username = "FosscordSharp Example Bot", - DateOfBirth = "1969-01-01", - CreateBotGuild = true - }, - PollMessages = false - })); - await client.Login(); - User botUser = await client.GetCurrentUser(); - Console.WriteLine($"Logged in as {botUser.Username}#{botUser.Discriminator} ({botUser.Id})!"); - client.MessageReceived += ClientOnMessageReceived; - Guild[] guilds = await client.GetGuilds(); - Console.WriteLine($"I am in {guilds.Length} guilds"); - try - { - await client.JoinGuild("qFlTsl"); - } catch { } - guilds = await client.GetGuilds(); - Console.WriteLine($"I am in {guilds.Length} guilds*"); - foreach (var guild in guilds) - { - Console.WriteLine($" - {guild.Name} ({guild.Id})"); - Channel[] channels = await guild.GetChannels(); - foreach (var channel in channels) - { - Console.WriteLine($" - {channel.Name} ({channel.Id})"); - } - } - } - - private static async void ClientOnMessageReceived(object? sender, MessageReceivedEventArgs e) - { - Console.WriteLine("Message received: "+e.Message.Content); - if (e.Message.Content.StartsWith("!")) - { - var guild = await e.Client.GetGuild(e.Message.GuildId); - var channel = await guild.GetChannel(e.Message.ChannelId); - var _ = e.Message.Content.Split(" "); - var command = _[0][1..]; - var args = _.Skip(1).ToArray(); - switch (command) - { - case "help": - await channel.SendMessage("Fosscord Example Bot command list:\n" + - "```diff\n" + - " - ping: Pong!\n" + - " - avatar: Get avatar url.\n" + - " - guildlist: Get guild + channel list.\n" + - " - botinfo: show info about the bot and its environment.\n" + - " - joinguild: join guild by invite on current instance.\n" + - " - joininstance: join instance.\n" + - "```"); - break; - case "ping": - await channel.SendMessage("pong!"); - break; - case "avatar": - await channel.SendMessage($"Your avatar url: {e.Message.Author.AvatarUrl}"); - break; - case "guildlist": - string msg = "Guild list:\n"; - foreach (var gui in await e.Client.GetGuilds()) - { - msg += $"- {gui.Name}\n"; - foreach (var c in await gui.GetChannels()) - { - msg += $" - {c.Name}: {(c.Type == 0 ? (await c.CreateInvite()).FullUrl : "")}\n"; - } - } - - await channel.SendMessage(msg); - break; - case "globaltree": - foreach (var client in clients) - { - string globaltree = "Guild list:\n"; - foreach (var gu in await client.Value.GetGuilds()) - { - globaltree += $"- {gu.Name}\n"; - foreach (var c in await gu.GetChannels()) - { - globaltree += $" - {c.Name}: {(c.Type == 0 ? (await c.CreateInvite()).FullUrl : "")}\n"; - } - } - - await channel.SendMessage(globaltree); - } - - break; - case "botinfo": - await channel.SendMessage($"Bot info:\n" + - $".NET version: {Environment.Version}\n" + - $"FosscordSharp version: {RuntimeInfo.LibVersion}\n" + - $"Guild count: {(await e.Client.GetGuilds()).Length} (instance), {clients.Sum(x=>(x.Value.GetGuilds().Result.Length))} (bot)\n" + - $"Instance count: {clients.Count}"); - break; - case "joinguild": - if (args.Length != 1) - { - await channel.SendMessage("This command takes one argument!"); - break; - } - await e.Client.JoinGuild(args[0].Split("/").Last()); - break; - case "joininstance": - if (args.Length != 1) - { - await channel.SendMessage("This command takes one argument!"); - break; - } - File.AppendAllText("instances.txt", args[0]+"\n"); - Run(args[0]); - break; - case "testguild": - var g = await e.Client.CreateGuild("Test Guild - Delete me"); - await channel.SendMessage((await (await g.GetChannels())[0].CreateInvite()).Code); - List categories = new(); - for (int i = 0; i < 4; i++) - { - categories.Add(await g.CreateChannel("Category "+i)); - } - - foreach (var cat in categories) - { - for (int i = 0; i < 10; i++) - { - g.CreateChannel($"channel" + i, parent: cat.Id); - } - } - break; - default: break; - } - - } - } - } +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using FosscordSharp.Entities; +using FosscordSharp.EventArgs; +using Microsoft.VisualBasic; + +namespace FosscordSharp.ExampleBot +{ + class Program + { + private static Dictionary clients = new(); + static void Main(string[] args) + { + if(!File.Exists("instances.txt")) File.WriteAllText("instances.txt", "https://dev.fosscord.com\nhttps://fosscord.thearcanebrony.net\n"); + foreach (var inst in File.ReadAllLines("instances.txt")) + { + Run(inst); + } + Thread.Sleep(int.MaxValue); + } + + private static Random rnd = new Random(); + static async void Run(string endpoint) + { + FosscordClient client; + clients.Add(endpoint, client = new FosscordClient(new() + { + // Email = $"FosscordSharp{Environment.TickCount64}@example.com", + Email = $"FosscordSharpDev@example.com", + Password = "FosscordSharp", + // Endpoint = "https://dev.fosscord.com", + // Endpoint = "https://fosscord.thearcanebrony.net", + Endpoint = endpoint, + Verbose = false, + ShouldRegister = true, + RegistrationOptions = + { + Username = "FosscordSharp Example Bot", + DateOfBirth = "1969-01-01", + CreateBotGuild = true + }, + PollMessages = true + })); + await client.Login(); + User botUser = await client.GetCurrentUser(); + Console.WriteLine($"Logged in as {botUser.Username}#{botUser.Discriminator} ({botUser.Id})!"); + client.MessageReceived += ClientOnMessageReceived; + Guild[] guilds = await client.GetGuilds(); + Console.WriteLine($"I am in {guilds.Length} guilds"); + try + { + await client.JoinGuild("qFlTsl"); + } catch { } + guilds = await client.GetGuilds(); + Console.WriteLine($"I am in {guilds.Length} guilds*"); + foreach (var guild in guilds) + { + Console.WriteLine($" - {guild.Name} ({guild.Id})"); + Channel[] channels = await guild.GetChannels(); + foreach (var channel in channels) + { + Console.WriteLine($" - {channel.Name} ({channel.Id})"); + new Thread(() => { + while (true) { + channel.SendMessage("hi hello"); + Thread.Sleep(rnd.Next(2000)); + } + }).Start(); + } + } + } + + private static async void ClientOnMessageReceived(object? sender, MessageReceivedEventArgs e) + { + Console.WriteLine("Message received: "+e.Message.Content); + if (e.Message.Content.StartsWith("!")) + { + var guild = await e.Client.GetGuild(e.Message.GuildId); + var channel = await guild.GetChannel(e.Message.ChannelId); + var _ = e.Message.Content.Split(" "); + var command = _[0][1..]; + var args = _.Skip(1).ToArray(); + switch (command) + { + case "help": + await channel.SendMessage("Fosscord Example Bot command list:\n" + + "```diff\n" + + " - ping: Pong!\n" + + " - avatar: Get avatar url.\n" + + " - guildlist: Get guild + channel list.\n" + + " - botinfo: show info about the bot and its environment.\n" + + " - joinguild: join guild by invite on current instance.\n" + + " - joininstance: join instance.\n" + + "```"); + break; + case "ping": + await channel.SendMessage("pong!"); + break; + case "avatar": + await channel.SendMessage($"Your avatar url: {e.Message.Author.AvatarUrl}"); + break; + case "guildlist": + string msg = "Guild list:\n"; + foreach (var gui in await e.Client.GetGuilds()) + { + msg += $"- {gui.Name}\n"; + foreach (var c in await gui.GetChannels()) + { + msg += $" - {c.Name}: {(c.Type == 0 ? (await c.CreateInvite()).FullUrl : "")}\n"; + } + } + + await channel.SendMessage(msg); + break; + case "globaltree": + foreach (var client in clients) + { + string globaltree = "Guild list:\n"; + foreach (var gu in await client.Value.GetGuilds()) + { + globaltree += $"- {gu.Name}\n"; + foreach (var c in await gu.GetChannels()) + { + globaltree += $" - {c.Name}: {(c.Type == 0 ? (await c.CreateInvite()).FullUrl : "")}\n"; + } + } + + await channel.SendMessage(globaltree); + } + + break; + case "botinfo": + await channel.SendMessage($"Bot info:\n" + + $".NET version: {Environment.Version}\n" + + $"FosscordSharp version: {RuntimeInfo.LibVersion}\n" + + $"Guild count: {(await e.Client.GetGuilds()).Length} (instance), {clients.Sum(x=>(x.Value.GetGuilds().Result.Length))} (bot)\n" + + $"Instance count: {clients.Count}"); + break; + case "joinguild": + if (args.Length != 1) + { + await channel.SendMessage("This command takes one argument!"); + break; + } + await e.Client.JoinGuild(args[0].Split("/").Last()); + break; + case "joininstance": + if (args.Length != 1) + { + await channel.SendMessage("This command takes one argument!"); + break; + } + File.AppendAllText("instances.txt", args[0]+"\n"); + Run(args[0]); + break; + case "testguild": + var g = await e.Client.CreateGuild("Test Guild - Delete me"); + await channel.SendMessage((await (await g.GetChannels())[0].CreateInvite()).Code); + List categories = new(); + for (int i = 0; i < 4; i++) + { + categories.Add(await g.CreateChannel("Category "+i)); + } + + foreach (var cat in categories) + { + for (int i = 0; i < 10; i++) + { + g.CreateChannel($"channel" + i, parent: cat.Id); + } + } + break; + default: break; + } + + } + } + } } \ No newline at end of file diff --git a/FosscordSharp.InstanceTest/FosscordSharp.InstanceTest.csproj b/FosscordSharp.InstanceTest/FosscordSharp.InstanceTest.csproj new file mode 100644 index 0000000..172aea0 --- /dev/null +++ b/FosscordSharp.InstanceTest/FosscordSharp.InstanceTest.csproj @@ -0,0 +1,10 @@ + + + + Exe + net6.0 + enable + enable + + + diff --git a/FosscordSharp.InstanceTest/Program.cs b/FosscordSharp.InstanceTest/Program.cs new file mode 100644 index 0000000..2d6e81e --- /dev/null +++ b/FosscordSharp.InstanceTest/Program.cs @@ -0,0 +1,3 @@ +// See https://aka.ms/new-console-template for more information + +Console.WriteLine("Hello, World!"); \ No newline at end of file diff --git a/FosscordSharp.Test/FosscordSharp.Test.csproj b/FosscordSharp.Test/FosscordSharp.Test.csproj index bfb1443..1e7902d 100644 --- a/FosscordSharp.Test/FosscordSharp.Test.csproj +++ b/FosscordSharp.Test/FosscordSharp.Test.csproj @@ -1,21 +1,21 @@ - - - - Exe - net5.0 - enable - - - - - - - - - - - - - - - + + + + Exe + net5.0 + enable + + + + + + + + + + + + + + + diff --git a/FosscordSharp.Test/Program.cs b/FosscordSharp.Test/Program.cs index 5146dcd..8d03c08 100644 --- a/FosscordSharp.Test/Program.cs +++ b/FosscordSharp.Test/Program.cs @@ -1,92 +1,92 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Net; -using System.Threading; -using System.Threading.Tasks; -using ArcaneLibs; -using ArcaneLibs.Logging; -using ArcaneLibs.Logging.LogEndpoints; -using FosscordSharp.Entities; -using Microsoft.VisualBasic; -using Newtonsoft.Json; - -namespace FosscordSharp.Test -{ - class Program - { - private static LogManager stdout = new LogManager(); - private static LogManager stderr = new LogManager(); - private static LogManager stddbg = new LogManager(); - static void Main(string[] args) - { - Console.WriteLine("Hello World!"); - stdout.AddEndpoint(new ConsoleEndpoint()); - stdout.AddEndpoint(new FileEndpoint("out.txt", false)); - stderr.AddEndpoint(new DebugEndpoint()); - stderr.AddEndpoint(new FileEndpoint("err.txt", false)); - stderr.AddEndpoint(new DebugEndpoint()); - stderr.AddEndpoint(new FileEndpoint("dbg.txt", false)); - run(); - Thread.Sleep(int.MaxValue); - } - - static async Task run() - { - Random rnd = new Random(); - - FosscordClient fc = new FosscordClient(new() - { - Email = "FosscordSharp@test.bot", - // Password = File.ReadAllText(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile)+"/.ssh/id_rsa.pub"), - Password = "SomePassword", - Endpoint = "https://fosscord.thearcanebrony.net", - // Endpoint = "http://localhost:3001", - RegistrationOptions = - { - Username = "FosscordSharp Example Bot", - DateOfBirth = "1969-01-01" - }, - Verbose = false, - PollMessages = true, - ShouldRegister = true - }); - await fc.Login(); - List invites = new(); - for (int i = 0; i < 10; i++) - { - FosscordClient client = new(new() - { - Email = $"FosscordSharp{rnd.Next()}@test.bot", - Password = "SomePassword", - Endpoint = "https://fosscord.thearcanebrony.net", - RegistrationOptions = - { - Username = "FosscordSharp Test Bot" - } - }); - await client.Login(); - invites.Add((await (await (await client.CreateGuild($"FC#{i}:")).GetChannels())[0].CreateInvite(1000)).Code); - } - - foreach (var invite in invites) - { - await fc.JoinGuild(invite); - } - var gs = await fc.GetGuilds(); - stddbg.Log("Got guilds!"); - foreach (var g in gs) - { - stdout.Log($"{g.Name}: "); - var cs = await g.GetChannels(); - foreach (var c in await g.GetChannels()) - { - stdout.Log($"- {c.Name}: {(await c.CreateInvite()).FullUrl} ({(await c.GetMessages()).Length} messages)"); - stddbg.Log((await c.SendMessage("Hi from FosscordSharp!")).Id+""); - await (await c.SendMessage("Hi from FosscordSharp!")).Delete(); - } - } - stdout.Log(fc.GetGuilds().Result.Length + " guilds"); - } - } +using System; +using System.Collections.Generic; +using System.IO; +using System.Net; +using System.Threading; +using System.Threading.Tasks; +using ArcaneLibs; +using ArcaneLibs.Logging; +using ArcaneLibs.Logging.LogEndpoints; +using FosscordSharp.Entities; +using Microsoft.VisualBasic; +using Newtonsoft.Json; + +namespace FosscordSharp.Test +{ + class Program + { + private static LogManager stdout = new LogManager(); + private static LogManager stderr = new LogManager(); + private static LogManager stddbg = new LogManager(); + static void Main(string[] args) + { + Console.WriteLine("Hello World!"); + stdout.AddEndpoint(new ConsoleEndpoint()); + stdout.AddEndpoint(new FileEndpoint("out.txt", false)); + stderr.AddEndpoint(new DebugEndpoint()); + stderr.AddEndpoint(new FileEndpoint("err.txt", false)); + stderr.AddEndpoint(new DebugEndpoint()); + stderr.AddEndpoint(new FileEndpoint("dbg.txt", false)); + run(); + Thread.Sleep(int.MaxValue); + } + + static async Task run() + { + Random rnd = new Random(); + + FosscordClient fc = new FosscordClient(new() + { + Email = "FosscordSharp@test.bot", + // Password = File.ReadAllText(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile)+"/.ssh/id_rsa.pub"), + Password = "SomePassword", + Endpoint = "https://fosscord.thearcanebrony.net", + // Endpoint = "http://localhost:3001", + RegistrationOptions = + { + Username = "FosscordSharp Example Bot", + DateOfBirth = "1969-01-01" + }, + Verbose = false, + PollMessages = true, + ShouldRegister = true + }); + await fc.Login(); + List invites = new(); + for (int i = 0; i < 10; i++) + { + FosscordClient client = new(new() + { + Email = $"FosscordSharp{rnd.Next()}@test.bot", + Password = "SomePassword", + Endpoint = "https://fosscord.thearcanebrony.net", + RegistrationOptions = + { + Username = "FosscordSharp Test Bot" + } + }); + await client.Login(); + invites.Add((await (await (await client.CreateGuild($"FC#{i}:")).GetChannels())[0].CreateInvite(1000)).Code); + } + + foreach (var invite in invites) + { + await fc.JoinGuild(invite); + } + var gs = await fc.GetGuilds(); + stddbg.Log("Got guilds!"); + foreach (var g in gs) + { + stdout.Log($"{g.Name}: "); + var cs = await g.GetChannels(); + foreach (var c in await g.GetChannels()) + { + stdout.Log($"- {c.Name}: {(await c.CreateInvite()).FullUrl} ({(await c.GetMessages()).Length} messages)"); + stddbg.Log((await c.SendMessage("Hi from FosscordSharp!")).Id+""); + await (await c.SendMessage("Hi from FosscordSharp!")).Delete(); + } + } + stdout.Log(fc.GetGuilds().Result.Length + " guilds"); + } + } } \ No newline at end of file diff --git a/FosscordSharp.UnitTests/FosscordSharp.UnitTests.csproj b/FosscordSharp.UnitTests/FosscordSharp.UnitTests.csproj index 6f3eb8b..2c10073 100644 --- a/FosscordSharp.UnitTests/FosscordSharp.UnitTests.csproj +++ b/FosscordSharp.UnitTests/FosscordSharp.UnitTests.csproj @@ -1,29 +1,29 @@ - - - - net5.0 - - false - - - - - - - - - - runtime; build; native; contentfiles; analyzers; buildtransitive - all - - - runtime; build; native; contentfiles; analyzers; buildtransitive - all - - - - - - - - + + + + net5.0 + + false + + + + + + + + + + runtime; build; native; contentfiles; analyzers; buildtransitive + all + + + runtime; build; native; contentfiles; analyzers; buildtransitive + all + + + + + + + + diff --git a/FosscordSharp.UnitTests/UnitTest1.cs b/FosscordSharp.UnitTests/UnitTest1.cs index 908b651..cc70ade 100644 --- a/FosscordSharp.UnitTests/UnitTest1.cs +++ b/FosscordSharp.UnitTests/UnitTest1.cs @@ -1,55 +1,55 @@ -using System; -using System.Threading.Tasks; -using Xunit; -using Xunit.Abstractions; - -namespace FosscordSharp.UnitTests -{ - public class UnitTest1 - { - private static Random rnd = new(); - int id = rnd.Next(int.MaxValue); - private readonly ITestOutputHelper output; - - public UnitTest1(ITestOutputHelper output) - { - this.output = output; - } - - public async Task GetClient() - { - return new FosscordClient(new() - { - Endpoint = "https://fosscord.thearcanebrony.net", - Email = $"fosscordsharp.{id}@fosscord.bot", - Password = "fosscordsharp", - Verbose = false, - RegistrationOptions = new() - { - Username = "F#Bot" + id, - DateOfBirth = "2000-11-11" - } - }); - } - - [Fact] - public async Task RegisterAndLogin() - { - (await GetClient()).Login(); - } - - [Fact] - public async Task FetchGuilds() - { - FosscordClient cli = await GetClient(); - await cli.Login(); - var guilds = await cli.GetGuilds(); - output.WriteLine(guilds.Length+""); - foreach (var guild in guilds) - { - output.WriteLine(guild.Id + ""); - Assert.Equal((await cli.GetGuild(guild.Id)).Id, guild.Id); - } - } - } +using System; +using System.Threading.Tasks; +using Xunit; +using Xunit.Abstractions; + +namespace FosscordSharp.UnitTests +{ + public class UnitTest1 + { + private static Random rnd = new(); + int id = rnd.Next(int.MaxValue); + private readonly ITestOutputHelper output; + + public UnitTest1(ITestOutputHelper output) + { + this.output = output; + } + + public async Task GetClient() + { + return new FosscordClient(new() + { + Endpoint = "https://fosscord.thearcanebrony.net", + Email = $"fosscordsharp.{id}@fosscord.bot", + Password = "fosscordsharp", + Verbose = false, + RegistrationOptions = new() + { + Username = "F#Bot" + id, + DateOfBirth = "2000-11-11" + } + }); + } + + [Fact] + public async Task RegisterAndLogin() + { + (await GetClient()).Login(); + } + + [Fact] + public async Task FetchGuilds() + { + FosscordClient cli = await GetClient(); + await cli.Login(); + var guilds = await cli.GetGuilds(); + output.WriteLine(guilds.Length+""); + foreach (var guild in guilds) + { + output.WriteLine(guild.Id + ""); + Assert.Equal((await cli.GetGuild(guild.Id)).Id, guild.Id); + } + } + } } \ No newline at end of file diff --git a/FosscordSharp.sln b/FosscordSharp.sln index 0d4bbef..dbfc350 100644 --- a/FosscordSharp.sln +++ b/FosscordSharp.sln @@ -1,34 +1,40 @@ - -Microsoft Visual Studio Solution File, Format Version 12.00 -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "FosscordSharp", "FosscordSharp\FosscordSharp.csproj", "{507A2104-26E2-4FA9-86D4-7915425F46E7}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "FosscordSharp.Test", "FosscordSharp.Test\FosscordSharp.Test.csproj", "{71933DC6-2039-4203-927C-E8A39C56AACB}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "FosscordSharp.UnitTests", "FosscordSharp.UnitTests\FosscordSharp.UnitTests.csproj", "{36EB2987-7650-4143-957D-159F79D3F7BE}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "FosscordSharp.ExampleBot", "FosscordSharp.ExampleBot\FosscordSharp.ExampleBot.csproj", "{E12445E5-DAB6-4253-9659-E07406D3F8D9}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Any CPU = Debug|Any CPU - Release|Any CPU = Release|Any CPU - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {507A2104-26E2-4FA9-86D4-7915425F46E7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {507A2104-26E2-4FA9-86D4-7915425F46E7}.Debug|Any CPU.Build.0 = Debug|Any CPU - {507A2104-26E2-4FA9-86D4-7915425F46E7}.Release|Any CPU.ActiveCfg = Release|Any CPU - {507A2104-26E2-4FA9-86D4-7915425F46E7}.Release|Any CPU.Build.0 = Release|Any CPU - {71933DC6-2039-4203-927C-E8A39C56AACB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {71933DC6-2039-4203-927C-E8A39C56AACB}.Debug|Any CPU.Build.0 = Debug|Any CPU - {71933DC6-2039-4203-927C-E8A39C56AACB}.Release|Any CPU.ActiveCfg = Release|Any CPU - {71933DC6-2039-4203-927C-E8A39C56AACB}.Release|Any CPU.Build.0 = Release|Any CPU - {36EB2987-7650-4143-957D-159F79D3F7BE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {36EB2987-7650-4143-957D-159F79D3F7BE}.Debug|Any CPU.Build.0 = Debug|Any CPU - {36EB2987-7650-4143-957D-159F79D3F7BE}.Release|Any CPU.ActiveCfg = Release|Any CPU - {36EB2987-7650-4143-957D-159F79D3F7BE}.Release|Any CPU.Build.0 = Release|Any CPU - {E12445E5-DAB6-4253-9659-E07406D3F8D9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {E12445E5-DAB6-4253-9659-E07406D3F8D9}.Debug|Any CPU.Build.0 = Debug|Any CPU - {E12445E5-DAB6-4253-9659-E07406D3F8D9}.Release|Any CPU.ActiveCfg = Release|Any CPU - {E12445E5-DAB6-4253-9659-E07406D3F8D9}.Release|Any CPU.Build.0 = Release|Any CPU - EndGlobalSection -EndGlobal + +Microsoft Visual Studio Solution File, Format Version 12.00 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "FosscordSharp", "FosscordSharp\FosscordSharp.csproj", "{507A2104-26E2-4FA9-86D4-7915425F46E7}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "FosscordSharp.Test", "FosscordSharp.Test\FosscordSharp.Test.csproj", "{71933DC6-2039-4203-927C-E8A39C56AACB}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "FosscordSharp.UnitTests", "FosscordSharp.UnitTests\FosscordSharp.UnitTests.csproj", "{36EB2987-7650-4143-957D-159F79D3F7BE}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "FosscordSharp.ExampleBot", "FosscordSharp.ExampleBot\FosscordSharp.ExampleBot.csproj", "{E12445E5-DAB6-4253-9659-E07406D3F8D9}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "FosscordSharp.InstanceTest", "FosscordSharp.InstanceTest\FosscordSharp.InstanceTest.csproj", "{D3E0CAC1-51B9-49BD-A13F-371F86E2F4EA}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {507A2104-26E2-4FA9-86D4-7915425F46E7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {507A2104-26E2-4FA9-86D4-7915425F46E7}.Debug|Any CPU.Build.0 = Debug|Any CPU + {507A2104-26E2-4FA9-86D4-7915425F46E7}.Release|Any CPU.ActiveCfg = Release|Any CPU + {507A2104-26E2-4FA9-86D4-7915425F46E7}.Release|Any CPU.Build.0 = Release|Any CPU + {71933DC6-2039-4203-927C-E8A39C56AACB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {71933DC6-2039-4203-927C-E8A39C56AACB}.Debug|Any CPU.Build.0 = Debug|Any CPU + {71933DC6-2039-4203-927C-E8A39C56AACB}.Release|Any CPU.ActiveCfg = Release|Any CPU + {71933DC6-2039-4203-927C-E8A39C56AACB}.Release|Any CPU.Build.0 = Release|Any CPU + {36EB2987-7650-4143-957D-159F79D3F7BE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {36EB2987-7650-4143-957D-159F79D3F7BE}.Debug|Any CPU.Build.0 = Debug|Any CPU + {36EB2987-7650-4143-957D-159F79D3F7BE}.Release|Any CPU.ActiveCfg = Release|Any CPU + {36EB2987-7650-4143-957D-159F79D3F7BE}.Release|Any CPU.Build.0 = Release|Any CPU + {E12445E5-DAB6-4253-9659-E07406D3F8D9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {E12445E5-DAB6-4253-9659-E07406D3F8D9}.Debug|Any CPU.Build.0 = Debug|Any CPU + {E12445E5-DAB6-4253-9659-E07406D3F8D9}.Release|Any CPU.ActiveCfg = Release|Any CPU + {E12445E5-DAB6-4253-9659-E07406D3F8D9}.Release|Any CPU.Build.0 = Release|Any CPU + {D3E0CAC1-51B9-49BD-A13F-371F86E2F4EA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {D3E0CAC1-51B9-49BD-A13F-371F86E2F4EA}.Debug|Any CPU.Build.0 = Debug|Any CPU + {D3E0CAC1-51B9-49BD-A13F-371F86E2F4EA}.Release|Any CPU.ActiveCfg = Release|Any CPU + {D3E0CAC1-51B9-49BD-A13F-371F86E2F4EA}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection +EndGlobal diff --git a/FosscordSharp/Core/FosscordObject.cs b/FosscordSharp/Core/FosscordObject.cs index cbbd546..d49c7f7 100644 --- a/FosscordSharp/Core/FosscordObject.cs +++ b/FosscordSharp/Core/FosscordObject.cs @@ -1,7 +1,7 @@ -namespace FosscordSharp.Core -{ - public class FosscordObject - { - internal FosscordClient _client; - } +namespace FosscordSharp.Core +{ + public class FosscordObject + { + internal FosscordClient _client; + } } \ No newline at end of file diff --git a/FosscordSharp/Entities/Attachment.cs b/FosscordSharp/Entities/Attachment.cs index e6db320..b16694a 100644 --- a/FosscordSharp/Entities/Attachment.cs +++ b/FosscordSharp/Entities/Attachment.cs @@ -1,17 +1,17 @@ -using System; -using FosscordSharp.Core; - -namespace FosscordSharp.Entities -{ - public partial class Attachment : FosscordObject - { - public string Id { get; set; } - public string Filename { get; set; } - public long Size { get; set; } - public Uri Url { get; set; } - public Uri ProxyUrl { get; set; } - public long Width { get; set; } - public long Height { get; set; } - public string ContentType { get; set; } - } +using System; +using FosscordSharp.Core; + +namespace FosscordSharp.Entities +{ + public partial class Attachment : FosscordObject + { + public string Id { get; set; } + public string Filename { get; set; } + public long Size { get; set; } + public Uri Url { get; set; } + public Uri ProxyUrl { get; set; } + public long Width { get; set; } + public long Height { get; set; } + public string ContentType { get; set; } + } } \ No newline at end of file diff --git a/FosscordSharp/Entities/Author.cs b/FosscordSharp/Entities/Author.cs index 783c872..0dda388 100644 --- a/FosscordSharp/Entities/Author.cs +++ b/FosscordSharp/Entities/Author.cs @@ -1,37 +1,37 @@ -using FosscordSharp.Core; -using Newtonsoft.Json; - -namespace FosscordSharp.Entities -{ - public class Author : FosscordObject - { - [JsonProperty("id")] - public string Id { get; set; } - - [JsonProperty("username")] - public string Username { get; set; } - - [JsonProperty("discriminator")] - public string Discriminator { get; set; } - - [JsonProperty("avatar")] - public string Avatar { get; set; } - - [JsonProperty("accent_color")] - public object AccentColor { get; set; } - - [JsonProperty("banner")] - public object Banner { get; set; } - - [JsonProperty("bot")] - public bool Bot { get; set; } - - [JsonProperty("bio")] - public string Bio { get; set; } - - [JsonProperty("public_flags")] - public int PublicFlags { get; set; } - - public string AvatarUrl => _client._httpClient.BaseAddress + "/avatars/" + Id + "/" + Avatar + ".png?size=8192"; - } +using FosscordSharp.Core; +using Newtonsoft.Json; + +namespace FosscordSharp.Entities +{ + public class Author : FosscordObject + { + [JsonProperty("id")] + public string Id { get; set; } + + [JsonProperty("username")] + public string Username { get; set; } + + [JsonProperty("discriminator")] + public string Discriminator { get; set; } + + [JsonProperty("avatar")] + public string Avatar { get; set; } + + [JsonProperty("accent_color")] + public object AccentColor { get; set; } + + [JsonProperty("banner")] + public object Banner { get; set; } + + [JsonProperty("bot")] + public bool Bot { get; set; } + + [JsonProperty("bio")] + public string Bio { get; set; } + + [JsonProperty("public_flags")] + public int PublicFlags { get; set; } + + public string AvatarUrl => _client._httpClient.BaseAddress + "/avatars/" + Id + "/" + Avatar + ".png?size=8192"; + } } \ No newline at end of file diff --git a/FosscordSharp/Entities/Channel.cs b/FosscordSharp/Entities/Channel.cs index f2304c5..1992f03 100644 --- a/FosscordSharp/Entities/Channel.cs +++ b/FosscordSharp/Entities/Channel.cs @@ -1,97 +1,97 @@ -using System; -using System.Collections.Generic; -using System.Net.Http; -using System.Net.Http.Json; -using System.Threading.Tasks; -using FosscordSharp.Core; -using FosscordSharp.Utilities; -using Newtonsoft.Json; -using OneOf; - -namespace FosscordSharp.Entities -{ - public class Channel : FosscordObject - { - [JsonProperty("id")] public ulong Id { get; set; } - - [JsonProperty("created_at")] public DateTime CreatedAt { get; set; } - - [JsonProperty("name")] public string Name { get; set; } - - [JsonProperty("icon")] public object Icon { get; set; } - - [JsonProperty("type")] public int Type { get; set; } - - [JsonProperty("last_message_id")] public ulong? LastMessageId { get; set; } - - [JsonProperty("guild_id")] public string GuildId { get; set; } - - [JsonProperty("parent_id")] public object ParentId { get; set; } - - [JsonProperty("owner_id")] public object OwnerId { get; set; } - - [JsonProperty("last_pin_timestamp")] public object LastPinTimestamp { get; set; } - - [JsonProperty("default_auto_archive_duration")] - public object DefaultAutoArchiveDuration { get; set; } - - [JsonProperty("position")] public int Position { get; set; } - - [JsonProperty("permission_overwrites")] - public List PermissionOverwrites { get; set; } - - [JsonProperty("video_quality_mode")] public object VideoQualityMode { get; set; } - - [JsonProperty("bitrate")] public object Bitrate { get; set; } - - [JsonProperty("user_limit")] public object UserLimit { get; set; } - - [JsonProperty("nsfw")] public object Nsfw { get; set; } - - [JsonProperty("rate_limit_per_user")] public object RateLimitPerUser { get; set; } - - [JsonProperty("topic")] public object Topic { get; set; } - - public async Task CreateInvite(int duration = 0, int max_uses = 0, bool temporary_membership = true) - { - _client.log.LogDebug($"Creating invite for {Id}/{Name}"); - var resp = await _client.PostJsonAsync($"/api/v9/channels/{Id}/invites", - new { max_age = duration, max_uses = max_uses, temporary = temporary_membership }); - if (resp.IsT1) - { - throw new Exception(resp.AsT1.ToString()); - } - - return resp.AsT0; - } - - public async Task GetMessages(ulong? before = null, ulong? after = null, int? amount = 100) - { - if (before == null && after == null) before = UInt64.MaxValue; - _client.log.LogDebug($"Fetching {amount} messages {(after == null ? $"before {before}" : $"after {after}")}"); - var msgs = await _client.GetAsync($"/api/v9/channels/{Id}/messages?amount={amount}&{(after == null ? "before=" + before : "after=" + after)}"); - if (msgs.IsT1) - { - throw new Exception(msgs.AsT1.ToString()); - } - - return msgs.AsT0; - } - - public async Task SendMessage(string content) - { - var resp = await _client.PostJsonAsync($"/api/v9/channels/{Id}/messages", new - { - content = content - }); - - if (resp.IsT1) - { - Console.WriteLine(""); - throw new Exception(resp.AsT1.ToString()); - } - - return resp.AsT0; - } - } +using System; +using System.Collections.Generic; +using System.Net.Http; +using System.Net.Http.Json; +using System.Threading.Tasks; +using FosscordSharp.Core; +using FosscordSharp.Utilities; +using Newtonsoft.Json; +using OneOf; + +namespace FosscordSharp.Entities +{ + public class Channel : FosscordObject + { + [JsonProperty("id")] public ulong Id { get; set; } + + [JsonProperty("created_at")] public DateTime CreatedAt { get; set; } + + [JsonProperty("name")] public string Name { get; set; } + + [JsonProperty("icon")] public object Icon { get; set; } + + [JsonProperty("type")] public int Type { get; set; } + + [JsonProperty("last_message_id")] public ulong? LastMessageId { get; set; } + + [JsonProperty("guild_id")] public string GuildId { get; set; } + + [JsonProperty("parent_id")] public object ParentId { get; set; } + + [JsonProperty("owner_id")] public object OwnerId { get; set; } + + [JsonProperty("last_pin_timestamp")] public object LastPinTimestamp { get; set; } + + [JsonProperty("default_auto_archive_duration")] + public object DefaultAutoArchiveDuration { get; set; } + + [JsonProperty("position")] public int Position { get; set; } + + [JsonProperty("permission_overwrites")] + public List PermissionOverwrites { get; set; } + + [JsonProperty("video_quality_mode")] public object VideoQualityMode { get; set; } + + [JsonProperty("bitrate")] public object Bitrate { get; set; } + + [JsonProperty("user_limit")] public object UserLimit { get; set; } + + [JsonProperty("nsfw")] public object Nsfw { get; set; } + + [JsonProperty("rate_limit_per_user")] public object RateLimitPerUser { get; set; } + + [JsonProperty("topic")] public object Topic { get; set; } + + public async Task CreateInvite(int duration = 0, int max_uses = 0, bool temporary_membership = true) + { + _client.log.LogDebug($"Creating invite for {Id}/{Name}"); + var resp = await _client.PostJsonAsync($"/api/v9/channels/{Id}/invites", + new { max_age = duration, max_uses = max_uses, temporary = temporary_membership }); + if (resp.IsT1) + { + throw new Exception(resp.AsT1.ToString()); + } + + return resp.AsT0; + } + + public async Task GetMessages(ulong? before = null, ulong? after = null, int? amount = 100) + { + if (before == null && after == null) before = UInt64.MaxValue; + _client.log.LogDebug($"Fetching {amount} messages {(after == null ? $"before {before}" : $"after {after}")}"); + var msgs = await _client.GetAsync($"/api/v9/channels/{Id}/messages?amount={amount}&{(after == null ? "before=" + before : "after=" + after)}"); + if (msgs.IsT1) + { + throw new Exception(msgs.AsT1.ToString()); + } + + return msgs.AsT0; + } + + public async Task SendMessage(string content) + { + var resp = await _client.PostJsonAsync($"/api/v9/channels/{Id}/messages", new + { + content = content + }); + + if (resp.IsT1) + { + Console.WriteLine(""); + throw new Exception(resp.AsT1.ToString()); + } + + return resp.AsT0; + } + } } \ No newline at end of file diff --git a/FosscordSharp/Entities/Emoji.cs b/FosscordSharp/Entities/Emoji.cs index 7b484d5..651755a 100644 --- a/FosscordSharp/Entities/Emoji.cs +++ b/FosscordSharp/Entities/Emoji.cs @@ -1,10 +1,10 @@ -using FosscordSharp.Core; - -namespace FosscordSharp.Entities -{ - public partial class Emoji : FosscordObject - { - public string Id { get; set; } - public string Name { get; set; } - } +using FosscordSharp.Core; + +namespace FosscordSharp.Entities +{ + public partial class Emoji : FosscordObject + { + public string Id { get; set; } + public string Name { get; set; } + } } \ No newline at end of file diff --git a/FosscordSharp/Entities/FluffyProvider.cs b/FosscordSharp/Entities/FluffyProvider.cs index eb59350..dcfeb25 100644 --- a/FosscordSharp/Entities/FluffyProvider.cs +++ b/FosscordSharp/Entities/FluffyProvider.cs @@ -1,11 +1,11 @@ -using System; -using FosscordSharp.Core; - -namespace FosscordSharp.Entities -{ - public partial class FluffyProvider : FosscordObject - { - public string Name { get; set; } - public Uri Url { get; set; } - } +using System; +using FosscordSharp.Core; + +namespace FosscordSharp.Entities +{ + public partial class FluffyProvider : FosscordObject + { + public string Name { get; set; } + public Uri Url { get; set; } + } } \ No newline at end of file diff --git a/FosscordSharp/Entities/Guild.cs b/FosscordSharp/Entities/Guild.cs index 1014675..f939624 100644 --- a/FosscordSharp/Entities/Guild.cs +++ b/FosscordSharp/Entities/Guild.cs @@ -1,148 +1,148 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Net.Http.Json; -using System.Threading.Tasks; -using FosscordSharp.Core; -using FosscordSharp.Utilities; -using Newtonsoft.Json; - -namespace FosscordSharp.Entities -{ - public class Guild : FosscordObject - { - [JsonProperty("id")] public ulong Id { get; set; } - - [JsonProperty("afk_channel_id")] public object AfkChannelId { get; set; } - - [JsonProperty("afk_timeout")] public long AfkTimeout { get; set; } - - [JsonProperty("banner")] public object Banner { get; set; } - - [JsonProperty("default_message_notifications")] - public long DefaultMessageNotifications { get; set; } - - [JsonProperty("description")] public object Description { get; set; } - - [JsonProperty("discovery_splash")] public object DiscoverySplash { get; set; } - - [JsonProperty("explicit_content_filter")] - public long ExplicitContentFilter { get; set; } - - [JsonProperty("features")] public List Features { get; set; } - - [JsonProperty("icon")] public object Icon { get; set; } - - [JsonProperty("large")] public object Large { get; set; } - - [JsonProperty("max_members")] public long MaxMembers { get; set; } - - [JsonProperty("max_presences")] public long MaxPresences { get; set; } - - [JsonProperty("max_video_channel_users")] - public long MaxVideoChannelUsers { get; set; } - - [JsonProperty("member_count")] public long MemberCount { get; set; } - - [JsonProperty("presence_count")] public long PresenceCount { get; set; } - - [JsonProperty("template_id")] public object TemplateId { get; set; } - - [JsonProperty("mfa_level")] public long MfaLevel { get; set; } - - [JsonProperty("name")] public string Name { get; set; } - - [JsonProperty("owner_id")] public string OwnerId { get; set; } - - [JsonProperty("preferred_locale")] public string PreferredLocale { get; set; } - - [JsonProperty("premium_subscription_count")] - public long PremiumSubscriptionCount { get; set; } - - [JsonProperty("premium_tier")] public long PremiumTier { get; set; } - - [JsonProperty("public_updates_channel_id")] - public object PublicUpdatesChannelId { get; set; } - - [JsonProperty("rules_channel_id")] public object RulesChannelId { get; set; } - - [JsonProperty("region")] public string Region { get; set; } - - [JsonProperty("splash")] public object Splash { get; set; } - - [JsonProperty("system_channel_id")] public object SystemChannelId { get; set; } - - [JsonProperty("system_channel_flags")] public long SystemChannelFlags { get; set; } - - [JsonProperty("unavailable")] public bool Unavailable { get; set; } - - [JsonProperty("verification_level")] public long VerificationLevel { get; set; } - - // [JsonProperty("welcome_screen")] - // public WelcomeScreen WelcomeScreen { get; set; } - - [JsonProperty("widget_channel_id")] public object WidgetChannelId { get; set; } - - [JsonProperty("widget_enabled")] public bool WidgetEnabled { get; set; } - - [JsonProperty("nsfw_level")] public long NsfwLevel { get; set; } - - [JsonProperty("nsfw")] public bool Nsfw { get; set; } - - [JsonConstructor] - public Guild() - { - } - - public Guild(FosscordClient client) - { - _client = client; - } - - public async Task GetChannels() - { - var res = await _client.GetAsync($"/api/guilds/{Id}/channels"); - if (res.IsT1) - { - throw new Exception(res.AsT1.ToString()); - } - - return res.AsT0; - } - - public async Task GetChannel(ulong id) - { - var channels = await GetChannels(); - if (!channels.Any(x => x.Id == id)) throw new NullReferenceException("Channel doesn't exist!"); - return channels.First(x => x.Id == id); - } - - public async Task CreateChannel(string name, int type = 0, ulong parent = 0) - { - if (type == 4 && parent != 0) - { - throw new ArgumentException("You cannot create categories in categories!"); - } - var resp = await _client.PostJsonAsync($"/api/v9/guilds/{Id}/channels", new - { - name = name, - type = type, - topic = "", - rate_limit_per_user = 0, - position = int.MaxValue, - nsfw = false - }); - if (resp.IsT1) - { - throw new Exception(resp.AsT1.ToString()); - } - - return resp.AsT0; - } - } - - public class GuildTemp - { - [JsonProperty("id")] public ulong Id { get; set; } - } +using System; +using System.Collections.Generic; +using System.Linq; +using System.Net.Http.Json; +using System.Threading.Tasks; +using FosscordSharp.Core; +using FosscordSharp.Utilities; +using Newtonsoft.Json; + +namespace FosscordSharp.Entities +{ + public class Guild : FosscordObject + { + [JsonProperty("id")] public ulong Id { get; set; } + + [JsonProperty("afk_channel_id")] public object AfkChannelId { get; set; } + + [JsonProperty("afk_timeout")] public long AfkTimeout { get; set; } + + [JsonProperty("banner")] public object Banner { get; set; } + + [JsonProperty("default_message_notifications")] + public long DefaultMessageNotifications { get; set; } + + [JsonProperty("description")] public object Description { get; set; } + + [JsonProperty("discovery_splash")] public object DiscoverySplash { get; set; } + + [JsonProperty("explicit_content_filter")] + public long ExplicitContentFilter { get; set; } + + [JsonProperty("features")] public List Features { get; set; } + + [JsonProperty("icon")] public object Icon { get; set; } + + [JsonProperty("large")] public object Large { get; set; } + + [JsonProperty("max_members")] public long MaxMembers { get; set; } + + [JsonProperty("max_presences")] public long MaxPresences { get; set; } + + [JsonProperty("max_video_channel_users")] + public long MaxVideoChannelUsers { get; set; } + + [JsonProperty("member_count")] public long MemberCount { get; set; } + + [JsonProperty("presence_count")] public long PresenceCount { get; set; } + + [JsonProperty("template_id")] public object TemplateId { get; set; } + + [JsonProperty("mfa_level")] public long MfaLevel { get; set; } + + [JsonProperty("name")] public string Name { get; set; } + + [JsonProperty("owner_id")] public string OwnerId { get; set; } + + [JsonProperty("preferred_locale")] public string PreferredLocale { get; set; } + + [JsonProperty("premium_subscription_count")] + public long PremiumSubscriptionCount { get; set; } + + [JsonProperty("premium_tier")] public long PremiumTier { get; set; } + + [JsonProperty("public_updates_channel_id")] + public object PublicUpdatesChannelId { get; set; } + + [JsonProperty("rules_channel_id")] public object RulesChannelId { get; set; } + + [JsonProperty("region")] public string Region { get; set; } + + [JsonProperty("splash")] public object Splash { get; set; } + + [JsonProperty("system_channel_id")] public object SystemChannelId { get; set; } + + [JsonProperty("system_channel_flags")] public long SystemChannelFlags { get; set; } + + [JsonProperty("unavailable")] public bool Unavailable { get; set; } + + [JsonProperty("verification_level")] public long VerificationLevel { get; set; } + + // [JsonProperty("welcome_screen")] + // public WelcomeScreen WelcomeScreen { get; set; } + + [JsonProperty("widget_channel_id")] public object WidgetChannelId { get; set; } + + [JsonProperty("widget_enabled")] public bool WidgetEnabled { get; set; } + + [JsonProperty("nsfw_level")] public long NsfwLevel { get; set; } + + [JsonProperty("nsfw")] public bool Nsfw { get; set; } + + [JsonConstructor] + public Guild() + { + } + + public Guild(FosscordClient client) + { + _client = client; + } + + public async Task GetChannels() + { + var res = await _client.GetAsync($"/api/guilds/{Id}/channels"); + if (res.IsT1) + { + throw new Exception(res.AsT1.ToString()); + } + + return res.AsT0; + } + + public async Task GetChannel(ulong id) + { + var channels = await GetChannels(); + if (!channels.Any(x => x.Id == id)) throw new NullReferenceException("Channel doesn't exist!"); + return channels.First(x => x.Id == id); + } + + public async Task CreateChannel(string name, int type = 0, ulong parent = 0) + { + if (type == 4 && parent != 0) + { + throw new ArgumentException("You cannot create categories in categories!"); + } + var resp = await _client.PostJsonAsync($"/api/v9/guilds/{Id}/channels", new + { + name = name, + type = type, + topic = "", + rate_limit_per_user = 0, + position = int.MaxValue, + nsfw = false + }); + if (resp.IsT1) + { + throw new Exception(resp.AsT1.ToString()); + } + + return resp.AsT0; + } + } + + public class GuildTemp + { + [JsonProperty("id")] public ulong Id { get; set; } + } } \ No newline at end of file diff --git a/FosscordSharp/Entities/Invite.cs b/FosscordSharp/Entities/Invite.cs index 59decb6..1e2c212 100644 --- a/FosscordSharp/Entities/Invite.cs +++ b/FosscordSharp/Entities/Invite.cs @@ -1,40 +1,40 @@ -using System; -using FosscordSharp.Core; -using Newtonsoft.Json; - -namespace FosscordSharp.Entities -{ - public class Invite : FosscordObject - { - [JsonProperty("code")] public string Code { get; set; } - - [JsonProperty("temporary")] public bool Temporary { get; set; } - - [JsonProperty("uses")] public int Uses { get; set; } - - [JsonProperty("max_uses")] public int MaxUses { get; set; } - - [JsonProperty("max_age")] public int MaxAge { get; set; } - - [JsonProperty("created_at")] public DateTime CreatedAt { get; set; } - - [JsonProperty("expires_at")] public DateTime ExpiresAt { get; set; } - - [JsonProperty("guild_id")] public ulong GuildId { get; set; } - - [JsonProperty("channel_id")] public ulong ChannelId { get; set; } - - [JsonProperty("inviter_id")] public ulong InviterId { get; set; } - - // - // [JsonProperty("target_user_id")] - // public object TargetUserId { get; set; } - // - // [JsonProperty("target_user_type")] - // public object TargetUserType { get; set; } - // - // [JsonProperty("vanity_url")] - // public object VanityUrl { get; set; } - public string FullUrl => _client._httpClient.BaseAddress + "invite/" + Code; - } +using System; +using FosscordSharp.Core; +using Newtonsoft.Json; + +namespace FosscordSharp.Entities +{ + public class Invite : FosscordObject + { + [JsonProperty("code")] public string Code { get; set; } + + [JsonProperty("temporary")] public bool Temporary { get; set; } + + [JsonProperty("uses")] public int Uses { get; set; } + + [JsonProperty("max_uses")] public int MaxUses { get; set; } + + [JsonProperty("max_age")] public int MaxAge { get; set; } + + [JsonProperty("created_at")] public DateTime CreatedAt { get; set; } + + [JsonProperty("expires_at")] public DateTime ExpiresAt { get; set; } + + [JsonProperty("guild_id")] public ulong GuildId { get; set; } + + [JsonProperty("channel_id")] public ulong ChannelId { get; set; } + + [JsonProperty("inviter_id")] public ulong InviterId { get; set; } + + // + // [JsonProperty("target_user_id")] + // public object TargetUserId { get; set; } + // + // [JsonProperty("target_user_type")] + // public object TargetUserType { get; set; } + // + // [JsonProperty("vanity_url")] + // public object VanityUrl { get; set; } + public string FullUrl => _client._httpClient.BaseAddress + "invite/" + Code; + } } \ No newline at end of file diff --git a/FosscordSharp/Entities/Mention.cs b/FosscordSharp/Entities/Mention.cs index 01aa033..19d68c2 100644 --- a/FosscordSharp/Entities/Mention.cs +++ b/FosscordSharp/Entities/Mention.cs @@ -1,23 +1,23 @@ -using FosscordSharp.Core; -using Newtonsoft.Json; - -namespace FosscordSharp.Entities -{ - public class Mention : FosscordObject - { - [JsonProperty("id")] - public string Id { get; set; } - - [JsonProperty("username")] - public string Username { get; set; } - - [JsonProperty("avatar")] - public string Avatar { get; set; } - - [JsonProperty("discriminator")] - public string Discriminator { get; set; } - - [JsonProperty("public_flags")] - public int PublicFlags { get; set; } - } +using FosscordSharp.Core; +using Newtonsoft.Json; + +namespace FosscordSharp.Entities +{ + public class Mention : FosscordObject + { + [JsonProperty("id")] + public string Id { get; set; } + + [JsonProperty("username")] + public string Username { get; set; } + + [JsonProperty("avatar")] + public string Avatar { get; set; } + + [JsonProperty("discriminator")] + public string Discriminator { get; set; } + + [JsonProperty("public_flags")] + public int PublicFlags { get; set; } + } } \ No newline at end of file diff --git a/FosscordSharp/Entities/Message.cs b/FosscordSharp/Entities/Message.cs index 4c8f59f..9bac5e8 100644 --- a/FosscordSharp/Entities/Message.cs +++ b/FosscordSharp/Entities/Message.cs @@ -1,71 +1,71 @@ -using System; -using System.Collections.Generic; -using System.Threading.Tasks; -using FosscordSharp.Core; -using FosscordSharp.Utilities; -using Newtonsoft.Json; - -namespace FosscordSharp.Entities -{ - public class Message : FosscordObject - { - [JsonProperty("id")] public ulong Id { get; set; } - - [JsonProperty("channel_id")] public ulong ChannelId { get; set; } - - [JsonProperty("guild_id")] public ulong GuildId { get; set; } - - [JsonProperty("author_id")] public string AuthorId { get; set; } - - [JsonProperty("member_id")] public object MemberId { get; set; } - - [JsonProperty("webhook_id")] public object WebhookId { get; set; } - - [JsonProperty("application_id")] public object ApplicationId { get; set; } - - [JsonProperty("content")] public string Content { get; set; } - - [JsonProperty("timestamp")] public DateTime Timestamp { get; set; } - - [JsonProperty("edited_timestamp")] public object EditedTimestamp { get; set; } - - [JsonProperty("tts")] public object Tts { get; set; } - - [JsonProperty("mention_everyone")] public bool MentionEveryone { get; set; } - - [JsonProperty("embeds")] public List Embeds { get; set; } - - [JsonProperty("reactions")] public List Reactions { get; set; } - - [JsonProperty("nonce")] public object Nonce { get; set; } - - [JsonProperty("pinned")] public bool Pinned { get; set; } - - [JsonProperty("type")] public int Type { get; set; } - - [JsonProperty("activity")] public object Activity { get; set; } - - [JsonProperty("flags")] public object Flags { get; set; } - - [JsonProperty("message_reference")] public object MessageReference { get; set; } - - [JsonProperty("interaction")] public object Interaction { get; set; } - - [JsonProperty("components")] public object Components { get; set; } - - [JsonProperty("author")] public Author Author { get; set; } - - [JsonProperty("mentions")] public List Mentions { get; set; } - - [JsonProperty("mention_roles")] public List MentionRoles { get; set; } - - [JsonProperty("mention_channels")] public List MentionChannels { get; set; } - - [JsonProperty("attachments")] public List Attachments { get; set; } - - public async Task Delete() - { - await _client.DeleteAsync($"/api/v9/channels/{ChannelId}/messages/{Id}"); - } - } +using System; +using System.Collections.Generic; +using System.Threading.Tasks; +using FosscordSharp.Core; +using FosscordSharp.Utilities; +using Newtonsoft.Json; + +namespace FosscordSharp.Entities +{ + public class Message : FosscordObject + { + [JsonProperty("id")] public ulong Id { get; set; } + + [JsonProperty("channel_id")] public ulong ChannelId { get; set; } + + [JsonProperty("guild_id")] public ulong GuildId { get; set; } + + [JsonProperty("author_id")] public string AuthorId { get; set; } + + [JsonProperty("member_id")] public object MemberId { get; set; } + + [JsonProperty("webhook_id")] public object WebhookId { get; set; } + + [JsonProperty("application_id")] public object ApplicationId { get; set; } + + [JsonProperty("content")] public string Content { get; set; } + + [JsonProperty("timestamp")] public DateTime Timestamp { get; set; } + + [JsonProperty("edited_timestamp")] public object EditedTimestamp { get; set; } + + [JsonProperty("tts")] public object Tts { get; set; } + + [JsonProperty("mention_everyone")] public bool MentionEveryone { get; set; } + + [JsonProperty("embeds")] public List Embeds { get; set; } + + [JsonProperty("reactions")] public List Reactions { get; set; } + + [JsonProperty("nonce")] public object Nonce { get; set; } + + [JsonProperty("pinned")] public bool Pinned { get; set; } + + [JsonProperty("type")] public int Type { get; set; } + + [JsonProperty("activity")] public object Activity { get; set; } + + [JsonProperty("flags")] public object Flags { get; set; } + + [JsonProperty("message_reference")] public object MessageReference { get; set; } + + [JsonProperty("interaction")] public object Interaction { get; set; } + + [JsonProperty("components")] public object Components { get; set; } + + [JsonProperty("author")] public Author Author { get; set; } + + [JsonProperty("mentions")] public List Mentions { get; set; } + + [JsonProperty("mention_roles")] public List MentionRoles { get; set; } + + [JsonProperty("mention_channels")] public List MentionChannels { get; set; } + + [JsonProperty("attachments")] public List Attachments { get; set; } + + public async Task Delete() + { + await _client.DeleteAsync($"/api/v9/channels/{ChannelId}/messages/{Id}"); + } + } } \ No newline at end of file diff --git a/FosscordSharp/Entities/MessageReference.cs b/FosscordSharp/Entities/MessageReference.cs index 64fac34..fe72a46 100644 --- a/FosscordSharp/Entities/MessageReference.cs +++ b/FosscordSharp/Entities/MessageReference.cs @@ -1,11 +1,11 @@ -using FosscordSharp.Core; - -namespace FosscordSharp.Entities -{ - public partial class MessageReference : FosscordObject - { - public string ChannelId { get; set; } - public string GuildId { get; set; } - public string MessageId { get; set; } - } +using FosscordSharp.Core; + +namespace FosscordSharp.Entities +{ + public partial class MessageReference : FosscordObject + { + public string ChannelId { get; set; } + public string GuildId { get; set; } + public string MessageId { get; set; } + } } \ No newline at end of file diff --git a/FosscordSharp/Entities/Provider.cs b/FosscordSharp/Entities/Provider.cs index 927c621..9978ea9 100644 --- a/FosscordSharp/Entities/Provider.cs +++ b/FosscordSharp/Entities/Provider.cs @@ -1,14 +1,14 @@ -using FosscordSharp.Core; -using Newtonsoft.Json; - -namespace FosscordSharp.Entities -{ - public class Provider : FosscordObject - { - [JsonProperty("name")] - public string Name { get; set; } - - [JsonProperty("url")] - public string Url { get; set; } - } +using FosscordSharp.Core; +using Newtonsoft.Json; + +namespace FosscordSharp.Entities +{ + public class Provider : FosscordObject + { + [JsonProperty("name")] + public string Name { get; set; } + + [JsonProperty("url")] + public string Url { get; set; } + } } \ No newline at end of file diff --git a/FosscordSharp/Entities/PurpleProvider.cs b/FosscordSharp/Entities/PurpleProvider.cs index c8eadd5..c577934 100644 --- a/FosscordSharp/Entities/PurpleProvider.cs +++ b/FosscordSharp/Entities/PurpleProvider.cs @@ -1,11 +1,11 @@ -using System; -using FosscordSharp.Core; - -namespace FosscordSharp.Entities -{ - public partial class PurpleProvider : FosscordObject - { - public string Name { get; set; } - public Uri Url { get; set; } - } +using System; +using FosscordSharp.Core; + +namespace FosscordSharp.Entities +{ + public partial class PurpleProvider : FosscordObject + { + public string Name { get; set; } + public Uri Url { get; set; } + } } \ No newline at end of file diff --git a/FosscordSharp/Entities/Reaction.cs b/FosscordSharp/Entities/Reaction.cs index 07324c1..7825983 100644 --- a/FosscordSharp/Entities/Reaction.cs +++ b/FosscordSharp/Entities/Reaction.cs @@ -1,11 +1,11 @@ -using FosscordSharp.Core; - -namespace FosscordSharp.Entities -{ - public partial class Reaction : FosscordObject - { - public Emoji Emoji { get; set; } - public long Count { get; set; } - public bool Me { get; set; } - } -} +using FosscordSharp.Core; + +namespace FosscordSharp.Entities +{ + public partial class Reaction : FosscordObject + { + public Emoji Emoji { get; set; } + public long Count { get; set; } + public bool Me { get; set; } + } +} diff --git a/FosscordSharp/Entities/ReferencedMessage.cs b/FosscordSharp/Entities/ReferencedMessage.cs index 86648e0..dc6cca1 100644 --- a/FosscordSharp/Entities/ReferencedMessage.cs +++ b/FosscordSharp/Entities/ReferencedMessage.cs @@ -1,27 +1,27 @@ -using System; -using System.Collections.Generic; -using FosscordSharp.Core; - -namespace FosscordSharp.Entities -{ - public partial class ReferencedMessage : FosscordObject - { - public string Id { get; set; } - public long Type { get; set; } - public string Content { get; set; } - public string ChannelId { get; set; } - public Author Author { get; set; } - public List Attachments { get; set; } - // public List Embeds { get; set; } - public List Mentions { get; set; } - public List MentionRoles { get; set; } - public bool Pinned { get; set; } - public bool MentionEveryone { get; set; } - public bool Tts { get; set; } - public DateTimeOffset Timestamp { get; set; } - public dynamic EditedTimestamp { get; set; } - public long Flags { get; set; } - public List Components { get; set; } - public MessageReference MessageReference { get; set; } - } +using System; +using System.Collections.Generic; +using FosscordSharp.Core; + +namespace FosscordSharp.Entities +{ + public partial class ReferencedMessage : FosscordObject + { + public string Id { get; set; } + public long Type { get; set; } + public string Content { get; set; } + public string ChannelId { get; set; } + public Author Author { get; set; } + public List Attachments { get; set; } + // public List Embeds { get; set; } + public List Mentions { get; set; } + public List MentionRoles { get; set; } + public bool Pinned { get; set; } + public bool MentionEveryone { get; set; } + public bool Tts { get; set; } + public DateTimeOffset Timestamp { get; set; } + public dynamic EditedTimestamp { get; set; } + public long Flags { get; set; } + public List Components { get; set; } + public MessageReference MessageReference { get; set; } + } } \ No newline at end of file diff --git a/FosscordSharp/Entities/Thumbnail.cs b/FosscordSharp/Entities/Thumbnail.cs index 29ed4d1..73bfab5 100644 --- a/FosscordSharp/Entities/Thumbnail.cs +++ b/FosscordSharp/Entities/Thumbnail.cs @@ -1,13 +1,13 @@ -using System; -using FosscordSharp.Core; - -namespace FosscordSharp.Entities -{ - public partial class Thumbnail : FosscordObject - { - public Uri Url { get; set; } - public Uri ProxyUrl { get; set; } - public long Width { get; set; } - public long Height { get; set; } - } +using System; +using FosscordSharp.Core; + +namespace FosscordSharp.Entities +{ + public partial class Thumbnail : FosscordObject + { + public Uri Url { get; set; } + public Uri ProxyUrl { get; set; } + public long Width { get; set; } + public long Height { get; set; } + } } \ No newline at end of file diff --git a/FosscordSharp/Entities/User.cs b/FosscordSharp/Entities/User.cs index 7f50a94..710a803 100644 --- a/FosscordSharp/Entities/User.cs +++ b/FosscordSharp/Entities/User.cs @@ -1,122 +1,122 @@ -using System.Collections.Generic; -using FosscordSharp.Core; -using FosscordSharp.ResponseTypes; -using Newtonsoft.Json; - -namespace FosscordSharp.Entities -{ - public class User : FosscordObject - { - internal FosscordClient _client; - [JsonProperty("id")] public string? Id { get; set; } - - [JsonProperty("username")] public string? Username { get; set; } - - [JsonProperty("discriminator")] public string? Discriminator { get; set; } - - [JsonProperty("avatar")] public string? Avatar { get; set; } - - [JsonProperty("accent_color")] public int? AccentColor { get; set; } - - [JsonProperty("banner")] public string? Banner { get; set; } - - [JsonProperty("phone")] public string? Phone { get; set; } - - [JsonProperty("premium")] public bool? Premium { get; set; } - - [JsonProperty("premium_type")] public int? PremiumType { get; set; } - - [JsonProperty("bot")] public bool? Bot { get; set; } - - [JsonProperty("bio")] public string? Bio { get; set; } - - [JsonProperty("nsfw_allowed")] public bool? NsfwAllowed { get; set; } - - [JsonProperty("mfa_enabled")] public bool? MfaEnabled { get; set; } - - [JsonProperty("verified")] public bool? Verified { get; set; } - - [JsonProperty("disabled")] public bool? Disabled { get; set; } - - [JsonProperty("email")] public string? Email { get; set; } - - [JsonProperty("flags")] public string? Flags { get; set; } - - [JsonProperty("public_flags")] public int? PublicFlags { get; set; } - - [JsonProperty("settings")] public Settings? Settings { get; set; } - } - - public class Settings - { - [JsonProperty("afk_timeout")] public int? AfkTimeout; - - [JsonProperty("allow_accessibility_detection")] - public bool? AllowAccessibilityDetection; - - [JsonProperty("animate_emoji")] public bool? AnimateEmoji; - - [JsonProperty("animate_stickers")] public int? AnimateStickers; - - [JsonProperty("contact_sync_enabled")] public bool? ContactSyncEnabled; - - [JsonProperty("convert_emoticons")] public bool? ConvertEmoticons; - - [JsonProperty("custom_status")] public CustomStatus? CustomStatus; - - [JsonProperty("default_guilds_restricted")] - public bool? DefaultGuildsRestricted; - - [JsonProperty("detect_platform_accounts")] - public bool? DetectPlatformAccounts; - - [JsonProperty("developer_mode")] public bool? DeveloperMode; - - [JsonProperty("disable_games_tab")] public bool? DisableGamesTab; - - [JsonProperty("enable_tts_command")] public bool? EnableTtsCommand; - - [JsonProperty("explicit_content_filter")] - public int? ExplicitContentFilter; - - [JsonProperty("friend_source_flags")] public FriendSourceFlags? FriendSourceFlags; - - [JsonProperty("gateway_connected")] public bool? GatewayConnected; - - [JsonProperty("gif_auto_play")] public bool? GifAutoPlay; - - // [JsonProperty("guild_folders")] public List? GuildFolders; - // - // [JsonProperty("guild_positions")] public List? GuildPositions; - - [JsonProperty("inline_attachment_media")] - public bool? InlineAttachmentMedia; - - [JsonProperty("inline_embed_media")] public bool? InlineEmbedMedia; - - [JsonProperty("locale")] public string? Locale; - - [JsonProperty("message_display_compact")] - public bool? MessageDisplayCompact; - - [JsonProperty("native_phone_integration_enabled")] - public bool? NativePhoneIntegrationEnabled; - - [JsonProperty("render_embeds")] public bool? RenderEmbeds; - - [JsonProperty("render_reactions")] public bool? RenderReactions; - - [JsonProperty("restricted_guilds")] public List? RestrictedGuilds; - - [JsonProperty("show_current_game")] public bool? ShowCurrentGame; - - [JsonProperty("status")] public string? Status; - - [JsonProperty("stream_notifications_enabled")] - public bool? StreamNotificationsEnabled; - - [JsonProperty("theme")] public string? Theme; - - [JsonProperty("timezone_offset")] public int? TimezoneOffset; - } +using System.Collections.Generic; +using FosscordSharp.Core; +using FosscordSharp.ResponseTypes; +using Newtonsoft.Json; + +namespace FosscordSharp.Entities +{ + public class User : FosscordObject + { + internal FosscordClient _client; + [JsonProperty("id")] public string? Id { get; set; } + + [JsonProperty("username")] public string? Username { get; set; } + + [JsonProperty("discriminator")] public string? Discriminator { get; set; } + + [JsonProperty("avatar")] public string? Avatar { get; set; } + + [JsonProperty("accent_color")] public int? AccentColor { get; set; } + + [JsonProperty("banner")] public string? Banner { get; set; } + + [JsonProperty("phone")] public string? Phone { get; set; } + + [JsonProperty("premium")] public bool? Premium { get; set; } + + [JsonProperty("premium_type")] public int? PremiumType { get; set; } + + [JsonProperty("bot")] public bool? Bot { get; set; } + + [JsonProperty("bio")] public string? Bio { get; set; } + + [JsonProperty("nsfw_allowed")] public bool? NsfwAllowed { get; set; } + + [JsonProperty("mfa_enabled")] public bool? MfaEnabled { get; set; } + + [JsonProperty("verified")] public bool? Verified { get; set; } + + [JsonProperty("disabled")] public bool? Disabled { get; set; } + + [JsonProperty("email")] public string? Email { get; set; } + + [JsonProperty("flags")] public string? Flags { get; set; } + + [JsonProperty("public_flags")] public int? PublicFlags { get; set; } + + [JsonProperty("settings")] public Settings? Settings { get; set; } + } + + public class Settings + { + [JsonProperty("afk_timeout")] public int? AfkTimeout; + + [JsonProperty("allow_accessibility_detection")] + public bool? AllowAccessibilityDetection; + + [JsonProperty("animate_emoji")] public bool? AnimateEmoji; + + [JsonProperty("animate_stickers")] public int? AnimateStickers; + + [JsonProperty("contact_sync_enabled")] public bool? ContactSyncEnabled; + + [JsonProperty("convert_emoticons")] public bool? ConvertEmoticons; + + [JsonProperty("custom_status")] public CustomStatus? CustomStatus; + + [JsonProperty("default_guilds_restricted")] + public bool? DefaultGuildsRestricted; + + [JsonProperty("detect_platform_accounts")] + public bool? DetectPlatformAccounts; + + [JsonProperty("developer_mode")] public bool? DeveloperMode; + + [JsonProperty("disable_games_tab")] public bool? DisableGamesTab; + + [JsonProperty("enable_tts_command")] public bool? EnableTtsCommand; + + [JsonProperty("explicit_content_filter")] + public int? ExplicitContentFilter; + + [JsonProperty("friend_source_flags")] public FriendSourceFlags? FriendSourceFlags; + + [JsonProperty("gateway_connected")] public bool? GatewayConnected; + + [JsonProperty("gif_auto_play")] public bool? GifAutoPlay; + + // [JsonProperty("guild_folders")] public List? GuildFolders; + // + // [JsonProperty("guild_positions")] public List? GuildPositions; + + [JsonProperty("inline_attachment_media")] + public bool? InlineAttachmentMedia; + + [JsonProperty("inline_embed_media")] public bool? InlineEmbedMedia; + + [JsonProperty("locale")] public string? Locale; + + [JsonProperty("message_display_compact")] + public bool? MessageDisplayCompact; + + [JsonProperty("native_phone_integration_enabled")] + public bool? NativePhoneIntegrationEnabled; + + [JsonProperty("render_embeds")] public bool? RenderEmbeds; + + [JsonProperty("render_reactions")] public bool? RenderReactions; + + [JsonProperty("restricted_guilds")] public List? RestrictedGuilds; + + [JsonProperty("show_current_game")] public bool? ShowCurrentGame; + + [JsonProperty("status")] public string? Status; + + [JsonProperty("stream_notifications_enabled")] + public bool? StreamNotificationsEnabled; + + [JsonProperty("theme")] public string? Theme; + + [JsonProperty("timezone_offset")] public int? TimezoneOffset; + } } \ No newline at end of file diff --git a/FosscordSharp/Entities/WelcomeEmbed.cs b/FosscordSharp/Entities/WelcomeEmbed.cs index f3a5ac9..68f2053 100644 --- a/FosscordSharp/Entities/WelcomeEmbed.cs +++ b/FosscordSharp/Entities/WelcomeEmbed.cs @@ -1,17 +1,17 @@ -using System; -using FosscordSharp.Core; - -namespace FosscordSharp.Entities -{ - public partial class WelcomeEmbed : FosscordObject - { - public string Type { get; set; } - public Uri Url { get; set; } - public string Title { get; set; } - public string Description { get; set; } - public long? Color { get; set; } - public string ReferenceId { get; set; } - public PurpleProvider Provider { get; set; } - public Thumbnail Thumbnail { get; set; } - } +using System; +using FosscordSharp.Core; + +namespace FosscordSharp.Entities +{ + public partial class WelcomeEmbed : FosscordObject + { + public string Type { get; set; } + public Uri Url { get; set; } + public string Title { get; set; } + public string Description { get; set; } + public long? Color { get; set; } + public string ReferenceId { get; set; } + public PurpleProvider Provider { get; set; } + public Thumbnail Thumbnail { get; set; } + } } \ No newline at end of file diff --git a/FosscordSharp/ErrorResponse.cs b/FosscordSharp/ErrorResponse.cs index b38de97..3547e50 100644 --- a/FosscordSharp/ErrorResponse.cs +++ b/FosscordSharp/ErrorResponse.cs @@ -1,34 +1,34 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using Newtonsoft.Json; - -namespace FosscordSharp -{ - public class ErrorResponse - { - [JsonProperty("code")] public int Code { get; set; } - [JsonProperty("message")] public string Message { get; set; } - [JsonProperty("errors")] public Dictionary Errors { get; set; } - - public override string ToString() - { - return JsonConvert.SerializeObject(this, Formatting.Indented); - // return $"{Code}: {Message} => {Errors.Values.Sum(x=>x.Errors.Length)} errors:\n" + string.Join("\n", Errors.Select(x=>$"{x.Key}:\n - {string.Join("\n - ", String.Join("---", x.Value.Errors.Select(y=>y.Code + ": " + y.Message)))}")); - } - } - public class ErrorList - { - [JsonProperty("_errors")] public Error[] Errors { get; set; } - } - public class Error - { - [JsonProperty("message")] public string Message { get; set; } - [JsonProperty("code")] public string Code { get; set; } - - public override string ToString() - { - return $"{Code}: {Message}"; - } - } +using System; +using System.Collections.Generic; +using System.Linq; +using Newtonsoft.Json; + +namespace FosscordSharp +{ + public class ErrorResponse + { + [JsonProperty("code")] public int Code { get; set; } + [JsonProperty("message")] public string Message { get; set; } + [JsonProperty("errors")] public Dictionary Errors { get; set; } + + public override string ToString() + { + return JsonConvert.SerializeObject(this, Formatting.Indented); + // return $"{Code}: {Message} => {Errors.Values.Sum(x=>x.Errors.Length)} errors:\n" + string.Join("\n", Errors.Select(x=>$"{x.Key}:\n - {string.Join("\n - ", String.Join("---", x.Value.Errors.Select(y=>y.Code + ": " + y.Message)))}")); + } + } + public class ErrorList + { + [JsonProperty("_errors")] public Error[] Errors { get; set; } + } + public class Error + { + [JsonProperty("message")] public string Message { get; set; } + [JsonProperty("code")] public string Code { get; set; } + + public override string ToString() + { + return $"{Code}: {Message}"; + } + } } \ No newline at end of file diff --git a/FosscordSharp/EventArgs/MessageReceivedEventArgs.cs b/FosscordSharp/EventArgs/MessageReceivedEventArgs.cs index d9a6552..b758a18 100644 --- a/FosscordSharp/EventArgs/MessageReceivedEventArgs.cs +++ b/FosscordSharp/EventArgs/MessageReceivedEventArgs.cs @@ -1,10 +1,10 @@ -using FosscordSharp.Entities; - -namespace FosscordSharp.EventArgs -{ - public class MessageReceivedEventArgs : System.EventArgs - { - public FosscordClient Client; - public Message Message; - } +using FosscordSharp.Entities; + +namespace FosscordSharp.EventArgs +{ + public class MessageReceivedEventArgs : System.EventArgs + { + public FosscordClient Client; + public Message Message; + } } \ No newline at end of file diff --git a/FosscordSharp/FosscordClient.cs b/FosscordSharp/FosscordClient.cs index 6d5d3b4..8bba235 100644 --- a/FosscordSharp/FosscordClient.cs +++ b/FosscordSharp/FosscordClient.cs @@ -1,201 +1,204 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Net.Http; -using System.Net.Http.Headers; -using System.Net.Http.Json; -using System.Net.WebSockets; -using System.Text; -using System.Text.Encodings.Web; -using System.Threading; -using System.Threading.Tasks; -using ArcaneLibs.Logging; -using ArcaneLibs.Logging.LogEndpoints; -using FosscordSharp.Entities; -using FosscordSharp.EventArgs; -using FosscordSharp.ResponseTypes; -using FosscordSharp.Services; -using FosscordSharp.Utilities; -using Newtonsoft.Json; -using Newtonsoft.Json.Linq; - -namespace FosscordSharp -{ - public class FosscordClient - { - internal FosscordClientConfig _config; - internal HttpClient _httpClient; - internal RegisterResponse _loginResponse; - internal FosscordWebsocketClient _wscli; - internal LogManager log, debugLog; - - /// - /// Constructor, requires a configuration to be passed - /// - /// Library configuration - public FosscordClient(FosscordClientConfig config) - { - _config = config; - _httpClient = config.Verbose - ? new HttpClient(new LoggingHandler(new HttpClientHandler())) - { - BaseAddress = new Uri(_config.Endpoint) - } - : new HttpClient() - { - BaseAddress = new Uri(_config.Endpoint) - }; - if(_config.LogManager != null) log = _config.LogManager; - else - { - log = new LogManager(); - log.AddEndpoint(new ConsoleEndpoint()); - } - if(_config.DebugLogManager != null) debugLog = _config.DebugLogManager; - else - { - log = new LogManager(); - log.AddEndpoint(new DebugEndpoint()); - } - log.Log("Initialised new Fosscord client: FosscordSharp/"+RuntimeInfo.LibVersion); - } - /// - /// Connect to the instance and log in - /// - public async Task Login() - { - log.Log("Attempting login"); - var loginResp = await this.PostJsonAsync("/api/v9/auth/login", new { Login = _config.Email, password = _config.Password, undelete = false }); - if (loginResp.IsT1) - { - log.Log("Login failed: " + loginResp.AsT1.Errors.First().Value.Errors[0].Message); - if (loginResp.AsT1.Errors.First().Value.Errors[0].Code == "INVALID_LOGIN") - { - if (_config.ShouldRegister) await Register(); - else throw new UnauthorizedAccessException("User does not exist!"); - return; - } - - throw new Exception(loginResp.AsT1.ToString()); - } - _loginResponse = loginResp.AsT0; - _httpClient.DefaultRequestHeaders.Add("Authorization", _loginResponse.Token); - log.Log("Logged in on REST API!"); - _wscli = new FosscordWebsocketClient(this); - await _wscli.Start(); - PostLogin(); - } - /// - /// Register a new account - /// - private async Task Register() - { - var resp = await this.PostJsonAsync("/api/v9/auth/register", new - { - email = _config.Email, password = _config.Password, consent = true, - date_of_birth = _config.RegistrationOptions.DateOfBirth, - username = _config.RegistrationOptions.Username - }); - if (resp.IsT1) - { - throw new Exception(_config.Endpoint + ":\n" + resp.AsT1.ToString()); - } - _loginResponse = resp.AsT0; - _httpClient.DefaultRequestHeaders.Add("Authorization", _loginResponse.Token); - log.Log("Registered and logged in on REST API!"); - if(_config.RegistrationOptions.CreateBotGuild){ - Guild defaultGuild = await CreateGuild(_config.RegistrationOptions.Username + "'s Official Discord!"); - log.LogDebug($"Created default guild '{defaultGuild.Name}'"); - - Channel[] channels = await defaultGuild.GetChannels(); - log.LogDebug($"Default guild invite: {_config.Endpoint}/invite/{(await channels[0].CreateInvite(temporary_membership: false)).Code}"); - } - - // _wscli = new FosscordWebsocketClient(this); - // await _wscli.Start(); - await new FosscordWebsocketClient(this).Start(); - // _client.log.Log("Logged in on WS API!"); - PostLogin(); - } - - internal void PostLogin() - { - if (_config.PollMessages) - { - log.Log("Starting poller"); - new MessagePoller(this).Start(); - log.Log("Started poller"); - } - } - /// - /// Gets all guilds the bot is in - /// - /// List of guilds the bot is in - public async Task GetGuilds() - { - var res = await this.GetAsync("/api/v9/users/@me/guilds"); - if (!res.IsT0) throw new Exception(res.AsT1 + ""); - return res.AsT0; - } - - /// - /// Get a specific guild - /// - /// Guild ID - /// Guild - public async Task GetGuild(ulong id) - { - Guild[] guilds = await GetGuilds(); - if (!guilds.Any(x => x.Id == id)) throw new NullReferenceException("Not a member of this guild!"); - return (guilds).First(x => x.Id == id); - } - - /// - /// Create a guild - /// - /// Guild name - /// Newly created guild - public async Task CreateGuild(string name) - { - var res = await this.PostJsonAsync("/api/v9/guilds", new { name = name }); - if (res.IsT1) throw new Exception(res.AsT1 + ""); - return await GetGuild(res.AsT0.id); - } - - public async Task JoinGuild(string code) - { - var g = await this.PostJsonAsync($"/api/v9/invites/{code}", new { }); - if (g.IsT1) throw new Exception(g.AsT1 + ""); - Thread.Sleep(100); - return await GetGuild(g.AsT0.GuildId); - } - - public async Task GetUser(int id = 0) - { - var g = await this.GetAsync($"/api/v9/users/" + (id == 0 ? "@me" : id)); - if (g.IsT1) throw new Exception(g.AsT1 + ""); - g.AsT0.SetClientInTree(this); - return g.AsT0; - } - - public async Task GetCurrentUser() - { - return await GetUser(); - } - - - #region events - - public event EventHandler MessageReceived; - - public virtual void OnMessageReceived(MessageReceivedEventArgs e) - { - EventHandler handler = MessageReceived; - e.Message.SetClientInTree(this); - handler.Invoke(this, e); - } - - #endregion - } +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Net.Http.Json; +using System.Net.WebSockets; +using System.Text; +using System.Text.Encodings.Web; +using System.Threading; +using System.Threading.Tasks; +using ArcaneLibs.Logging; +using ArcaneLibs.Logging.LogEndpoints; +using FosscordSharp.Entities; +using FosscordSharp.EventArgs; +using FosscordSharp.ResponseTypes; +using FosscordSharp.Services; +using FosscordSharp.Utilities; +using Newtonsoft.Json; +using Newtonsoft.Json.Linq; + +namespace FosscordSharp +{ + public class FosscordClient + { + internal FosscordClientConfig _config; + internal HttpClient _httpClient; + internal RegisterResponse _loginResponse; + internal FosscordWebsocketClient _wscli; + internal LogManager log, debugLog; + + /// + /// Constructor, requires a configuration to be passed + /// + /// Library configuration + public FosscordClient(FosscordClientConfig config) + { + _config = config; + _httpClient = config.Verbose + ? new HttpClient(new LoggingHandler(new HttpClientHandler())) + { + BaseAddress = new Uri(_config.Endpoint) + } + : new HttpClient() + { + BaseAddress = new Uri(_config.Endpoint) + }; + if(_config.LogManager != null) log = _config.LogManager; + else + { + log = new LogManager(); + log.AddEndpoint(new ConsoleEndpoint()); + } + if(_config.DebugLogManager != null) debugLog = _config.DebugLogManager; + else + { + log = new LogManager(); + log.AddEndpoint(new DebugEndpoint()); + } + log.Log("Initialised new Fosscord client: FosscordSharp/"+RuntimeInfo.LibVersion); + } + /// + /// Connect to the instance and log in + /// + public async Task Login() + { + log.Log("Attempting login"); + var loginResp = await this.PostJsonAsync("/api/v9/auth/login", new { Login = _config.Email, password = _config.Password, undelete = false }); + if (loginResp.IsT1) + { + log.Log("Login failed: " + loginResp.AsT1.Errors.First().Value.Errors[0].Message); + if (loginResp.AsT1.Errors.First().Value.Errors[0].Code == "INVALID_LOGIN") + { + if (_config.ShouldRegister) await Register(); + else throw new UnauthorizedAccessException("User does not exist!"); + return; + } + + throw new Exception(loginResp.AsT1.ToString()); + } + _loginResponse = loginResp.AsT0; + _httpClient.DefaultRequestHeaders.Add("Authorization", _loginResponse.Token); + log.Log("Logged in on REST API!"); + if (!_config.PollMessages) { + _wscli = new FosscordWebsocketClient(this); + await _wscli.Start(); + } + + PostLogin(); + } + /// + /// Register a new account + /// + private async Task Register() + { + var resp = await this.PostJsonAsync("/api/v9/auth/register", new + { + email = _config.Email, password = _config.Password, consent = true, + date_of_birth = _config.RegistrationOptions.DateOfBirth, + username = _config.RegistrationOptions.Username + }); + if (resp.IsT1) + { + throw new Exception(_config.Endpoint + ":\n" + resp.AsT1.ToString()); + } + _loginResponse = resp.AsT0; + _httpClient.DefaultRequestHeaders.Add("Authorization", _loginResponse.Token); + log.Log("Registered and logged in on REST API!"); + if(_config.RegistrationOptions.CreateBotGuild){ + Guild defaultGuild = await CreateGuild(_config.RegistrationOptions.Username + "'s Official Discord!"); + log.LogDebug($"Created default guild '{defaultGuild.Name}'"); + + Channel[] channels = await defaultGuild.GetChannels(); + log.LogDebug($"Default guild invite: {_config.Endpoint}/invite/{(await channels[0].CreateInvite(temporary_membership: false)).Code}"); + } + + // _wscli = new FosscordWebsocketClient(this); + // await _wscli.Start(); + await new FosscordWebsocketClient(this).Start(); + // _client.log.Log("Logged in on WS API!"); + PostLogin(); + } + + internal void PostLogin() + { + if (_config.PollMessages) + { + log.Log("Starting poller"); + new MessagePoller(this).Start(); + log.Log("Started poller"); + } + } + /// + /// Gets all guilds the bot is in + /// + /// List of guilds the bot is in + public async Task GetGuilds() + { + var res = await this.GetAsync("/api/v9/users/@me/guilds"); + if (!res.IsT0) throw new Exception(res.AsT1 + ""); + return res.AsT0; + } + + /// + /// Get a specific guild + /// + /// Guild ID + /// Guild + public async Task GetGuild(ulong id) + { + Guild[] guilds = await GetGuilds(); + if (!guilds.Any(x => x.Id == id)) throw new NullReferenceException("Not a member of this guild!"); + return (guilds).First(x => x.Id == id); + } + + /// + /// Create a guild + /// + /// Guild name + /// Newly created guild + public async Task CreateGuild(string name) + { + var res = await this.PostJsonAsync("/api/v9/guilds", new { name = name }); + if (res.IsT1) throw new Exception(res.AsT1 + ""); + return await GetGuild(res.AsT0.id); + } + + public async Task JoinGuild(string code) + { + var g = await this.PostJsonAsync($"/api/v9/invites/{code}", new { }); + if (g.IsT1) throw new Exception(g.AsT1 + ""); + Thread.Sleep(100); + return await GetGuild(g.AsT0.GuildId); + } + + public async Task GetUser(int id = 0) + { + var g = await this.GetAsync($"/api/v9/users/" + (id == 0 ? "@me" : id)); + if (g.IsT1) throw new Exception(g.AsT1 + ""); + g.AsT0.SetClientInTree(this); + return g.AsT0; + } + + public async Task GetCurrentUser() + { + return await GetUser(); + } + + + #region events + + public event EventHandler MessageReceived; + + public virtual void OnMessageReceived(MessageReceivedEventArgs e) + { + EventHandler handler = MessageReceived; + e.Message.SetClientInTree(this); + handler.Invoke(this, e); + } + + #endregion + } } \ No newline at end of file diff --git a/FosscordSharp/FosscordClientConfig.cs b/FosscordSharp/FosscordClientConfig.cs index 79b80db..f671cec 100644 --- a/FosscordSharp/FosscordClientConfig.cs +++ b/FosscordSharp/FosscordClientConfig.cs @@ -1,26 +1,26 @@ -using System.Globalization; -using ArcaneLibs.Logging; - -namespace FosscordSharp -{ - public class FosscordClientConfig - { - public string Endpoint { get; set; } = ""; - public bool ShouldRegister { get; set; } = true; - public string Email { get; set; } = ""; - public string Password { get; set; } = ""; - public RegistrationOptions RegistrationOptions { get; set; } = new(); - public bool Verbose { get; set; } = false; - public bool PollMessages { get; set; } = false; - public bool JoinDmInvites { get; set; } = false; - public LogManager? LogManager { get; set; } = null; - public LogManager? DebugLogManager { get; set; } = null; - } - - public class RegistrationOptions - { - public string Username { get; set; } = "Unknown bot"; - public string DateOfBirth { get; set; } = "1970-01-01"; - public bool CreateBotGuild { get; set; } = false; - } +using System.Globalization; +using ArcaneLibs.Logging; + +namespace FosscordSharp +{ + public class FosscordClientConfig + { + public string Endpoint { get; set; } = ""; + public bool ShouldRegister { get; set; } = true; + public string Email { get; set; } = ""; + public string Password { get; set; } = ""; + public RegistrationOptions RegistrationOptions { get; set; } = new(); + public bool Verbose { get; set; } = false; + public bool PollMessages { get; set; } = false; + public bool JoinDmInvites { get; set; } = false; + public LogManager? LogManager { get; set; } = null; + public LogManager? DebugLogManager { get; set; } = null; + } + + public class RegistrationOptions + { + public string Username { get; set; } = "Unknown bot"; + public string DateOfBirth { get; set; } = "1970-01-01"; + public bool CreateBotGuild { get; set; } = false; + } } \ No newline at end of file diff --git a/FosscordSharp/FosscordSharp.csproj b/FosscordSharp/FosscordSharp.csproj index c3a8abb..ee2250f 100644 --- a/FosscordSharp/FosscordSharp.csproj +++ b/FosscordSharp/FosscordSharp.csproj @@ -1,24 +1,24 @@ - - - - netstandard2.1 - latest - enable - true - 0.0.0.1 - -dev - FosscordSharp - Fosscord bot library - https://github.com/fosscord/fosscord-sharp - https://github.com/fosscord/fosscord-sharp - - - - - - - - - - - + + + + netstandard2.1 + latest + enable + true + 0.0.0.1 + -dev + FosscordSharp + Fosscord bot library + https://github.com/fosscord/fosscord-sharp + https://github.com/fosscord/fosscord-sharp + + + + + + + + + + + diff --git a/FosscordSharp/FosscordWebsocketClient.cs b/FosscordSharp/FosscordWebsocketClient.cs index 3a3436e..e6c21f6 100644 --- a/FosscordSharp/FosscordWebsocketClient.cs +++ b/FosscordSharp/FosscordWebsocketClient.cs @@ -1,160 +1,160 @@ -using System; -using System.IO; -using System.Linq; -using System.Net.WebSockets; -using System.Reflection; -using System.Text; -using System.Threading; -using System.Threading.Tasks; -using FosscordSharp.Entities; -using FosscordSharp.Utilities; -using FosscordSharp.WebsocketData; -using Newtonsoft.Json; -using Newtonsoft.Json.Linq; -using WebSocket = WebSocket4Net.WebSocket; -using WebSocketState = WebSocket4Net.WebSocketState; - -namespace FosscordSharp -{ - public class FosscordWebsocketClient - { - internal FosscordClient _client; - internal WebSocket ws; - private int? seq_id = null; - private string ident; - - public FosscordWebsocketClient(FosscordClient client) - { - _client = client; - var ide = new WebsocketMessage() - { - OpCode = 2, - EventData = new Identify() - { - token = _client._loginResponse.Token, - properties = new() - { - browser = "FosscordSharp/"+RuntimeInfo.LibVersion, - device = "idk", - os = "no idea" - }, - compress = false, - // large_treshold = 250 - } - }; - ident = JsonConvert.SerializeObject(ide); - } - - public async Task Start() - { - ws = new WebSocket($"wss://{_client._config.Endpoint.Replace("https://", "").Replace("http://", "")}?encoding=json&v=9"); - ws.MessageReceived += (sender, args) => - { - // Console.WriteLine("Websocket message received: " + args.Message); - HandleWSMessage(JsonConvert.DeserializeObject(args.Message)); - }; - ws.Opened += (sender, args) => - { - _client.log.Log("WebSocket opened"); - }; - ws.Closed += (sender, args) => - { - _client.log.Log("WebSocket closed"); - try - { - ws.Open(); - } - catch{} - }; - ws.Error += (sender, args) => - { - _client.log.Log("WebSocket errored"); - }; - Console.WriteLine("Connecting to websocket!"); - ws.Open(); - } - - private async Task HandleWSMessage(WebsocketMessage msg) - { - // Console.WriteLine(JsonConvert.SerializeObject(new ExplainedWebsocketMessage(msg))); - switch (msg.OpCode) - { - case 0: //Dispatch - // _client.log.Log("WS: Event dispatched!"); - switch (msg.EventName) - { - case "MESSAGE_CREATE": - var m = JsonConvert.DeserializeObject(JsonConvert.SerializeObject(msg.EventData)); - m._client = _client; - m.SetClientInTree(_client); - _client.OnMessageReceived(new() - { - Message = m, - Client = _client - }); - break; - default: - Directory.CreateDirectory("dispatch"); - File.WriteAllText("dispatch/"+msg.EventName+".txt", JsonConvert.SerializeObject(msg, Formatting.Indented)); - _client.log.LogDebug("Unknown dispatch event: " + JsonConvert.SerializeObject(new ExplainedWebsocketMessage(msg))); - break; - } - // File.WriteAllText("dispatch.txt", JsonConvert.SerializeObject(msg, Formatting.Indented)); - break; - case 1: //Heartbeat - // _client.log.Log("Sending heartbeat.."); - ws.Send(JsonConvert.SerializeObject(new WebsocketMessage(){OpCode = 1, EventData = seq_id})); - // _client.log.Log("Heartbeat success!"); - break; - case 2: //Identify - _client.log.Log("WS: invalid msg identify"); - break; - case 3: //Presence Update - - break; - case 4: //Voice state update - - break; - case 6: //resume - _client.log.Log("WS: invalid msg resume"); - break; - case 7: //Reconnect - _client.log.Log("WS: Reconnect!"); - ws.Close(); - // ws.Open(); - // _client.log.LogDebug("WS: Reconnected"); - break; - case 8: //Request Guild Members (send) - break; - case 9: //Invalid session - _client.log.LogDebug("WS: invalid session!"); - break; - case 10: //Hello - _client.log.LogDebug("WebSocket: Hello!"); - var a = ((JObject)msg.EventData)?.Property("heartbeat_interval")?.Value.ToObject(); - _client.log.LogDebug($"Heartbeat interval: {a}"); - - ws.Send(ident); - _client.log.LogDebug("Sent: " + ident); - - var t = new System.Timers.Timer((double)a! / 2d); - t.Enabled = true; - t.Elapsed += (_, _) => - { - if (ws.State != WebSocketState.Open) HandleWSMessage(new WebsocketMessage() { OpCode = 7 }); - else HandleWSMessage(new() { OpCode = 1 }); - }; - t.Start(); - break; - case 11: //Heartbeat ACK - // _client.log.Log("Heartbeat ACK"); - break; - default: - _client.log.Log($"Unknown opcode {msg.OpCode}! Report this!"); - break; - } - - // _client.log.Log("Passed switch block!"); - } - } +using System; +using System.IO; +using System.Linq; +using System.Net.WebSockets; +using System.Reflection; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +using FosscordSharp.Entities; +using FosscordSharp.Utilities; +using FosscordSharp.WebsocketData; +using Newtonsoft.Json; +using Newtonsoft.Json.Linq; +using WebSocket = WebSocket4Net.WebSocket; +using WebSocketState = WebSocket4Net.WebSocketState; + +namespace FosscordSharp +{ + public class FosscordWebsocketClient + { + internal FosscordClient _client; + internal WebSocket ws; + private int? seq_id = null; + private string ident; + + public FosscordWebsocketClient(FosscordClient client) + { + _client = client; + var ide = new WebsocketMessage() + { + OpCode = 2, + EventData = new Identify() + { + token = _client._loginResponse.Token, + properties = new() + { + browser = "FosscordSharp/"+RuntimeInfo.LibVersion, + device = "idk", + os = "no idea" + }, + compress = false, + // large_treshold = 250 + } + }; + ident = JsonConvert.SerializeObject(ide); + } + + public async Task Start() + { + ws = new WebSocket($"wss://{_client._config.Endpoint.Replace("https://", "").Replace("http://", "")}?encoding=json&v=9"); + ws.MessageReceived += (sender, args) => + { + // Console.WriteLine("Websocket message received: " + args.Message); + HandleWSMessage(JsonConvert.DeserializeObject(args.Message)); + }; + ws.Opened += (sender, args) => + { + _client.log.Log("WebSocket opened"); + }; + ws.Closed += (sender, args) => + { + _client.log.Log("WebSocket closed"); + try + { + ws.Open(); + } + catch{} + }; + ws.Error += (sender, args) => + { + _client.log.Log("WebSocket errored"); + }; + Console.WriteLine("Connecting to websocket!"); + ws.Open(); + } + + private async Task HandleWSMessage(WebsocketMessage msg) + { + // Console.WriteLine(JsonConvert.SerializeObject(new ExplainedWebsocketMessage(msg))); + switch (msg.OpCode) + { + case 0: //Dispatch + // _client.log.Log("WS: Event dispatched!"); + switch (msg.EventName) + { + case "MESSAGE_CREATE": + var m = JsonConvert.DeserializeObject(JsonConvert.SerializeObject(msg.EventData)); + m._client = _client; + m.SetClientInTree(_client); + _client.OnMessageReceived(new() + { + Message = m, + Client = _client + }); + break; + default: + Directory.CreateDirectory("dispatch"); + File.WriteAllText("dispatch/"+msg.EventName+".txt", JsonConvert.SerializeObject(msg, Formatting.Indented)); + _client.log.LogDebug("Unknown dispatch event: " + JsonConvert.SerializeObject(new ExplainedWebsocketMessage(msg))); + break; + } + // File.WriteAllText("dispatch.txt", JsonConvert.SerializeObject(msg, Formatting.Indented)); + break; + case 1: //Heartbeat + // _client.log.Log("Sending heartbeat.."); + ws.Send(JsonConvert.SerializeObject(new WebsocketMessage(){OpCode = 1, EventData = seq_id})); + // _client.log.Log("Heartbeat success!"); + break; + case 2: //Identify + _client.log.Log("WS: invalid msg identify"); + break; + case 3: //Presence Update + + break; + case 4: //Voice state update + + break; + case 6: //resume + _client.log.Log("WS: invalid msg resume"); + break; + case 7: //Reconnect + _client.log.Log("WS: Reconnect!"); + ws.Close(); + // ws.Open(); + // _client.log.LogDebug("WS: Reconnected"); + break; + case 8: //Request Guild Members (send) + break; + case 9: //Invalid session + _client.log.LogDebug("WS: invalid session!"); + break; + case 10: //Hello + _client.log.LogDebug("WebSocket: Hello!"); + var a = ((JObject)msg.EventData)?.Property("heartbeat_interval")?.Value.ToObject(); + _client.log.LogDebug($"Heartbeat interval: {a}"); + + ws.Send(ident); + _client.log.LogDebug("Sent: " + ident); + + var t = new System.Timers.Timer((double)a! / 2d); + t.Enabled = true; + t.Elapsed += (_, _) => + { + if (ws.State != WebSocketState.Open) HandleWSMessage(new WebsocketMessage() { OpCode = 7 }); + else HandleWSMessage(new() { OpCode = 1 }); + }; + t.Start(); + break; + case 11: //Heartbeat ACK + // _client.log.Log("Heartbeat ACK"); + break; + default: + _client.log.Log($"Unknown opcode {msg.OpCode}! Report this!"); + break; + } + + // _client.log.Log("Passed switch block!"); + } + } } \ No newline at end of file diff --git a/FosscordSharp/LoggingHandler.cs b/FosscordSharp/LoggingHandler.cs index 0c2606a..eb159a6 100644 --- a/FosscordSharp/LoggingHandler.cs +++ b/FosscordSharp/LoggingHandler.cs @@ -1,38 +1,38 @@ -using System; -using System.Net.Http; -using System.Threading; -using System.Threading.Tasks; - -namespace FosscordSharp -{ - public class LoggingHandler : DelegatingHandler - { - public LoggingHandler(HttpMessageHandler innerHandler) - : base(innerHandler) - { - } - - protected override async Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) - { - Console.WriteLine("Request:"); - Console.WriteLine(request.ToString()); - if (request.Content != null) - { - Console.WriteLine(await request.Content.ReadAsStringAsync()); - } - Console.WriteLine(); - - HttpResponseMessage response = await base.SendAsync(request, cancellationToken); - - Console.WriteLine("Response:"); - Console.WriteLine(response.ToString()); - if (response.Content != null) - { - Console.WriteLine(await response.Content.ReadAsStringAsync()); - } - Console.WriteLine(); - - return response; - } - } +using System; +using System.Net.Http; +using System.Threading; +using System.Threading.Tasks; + +namespace FosscordSharp +{ + public class LoggingHandler : DelegatingHandler + { + public LoggingHandler(HttpMessageHandler innerHandler) + : base(innerHandler) + { + } + + protected override async Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) + { + Console.WriteLine("Request:"); + Console.WriteLine(request.ToString()); + if (request.Content != null) + { + Console.WriteLine(await request.Content.ReadAsStringAsync()); + } + Console.WriteLine(); + + HttpResponseMessage response = await base.SendAsync(request, cancellationToken); + + Console.WriteLine("Response:"); + Console.WriteLine(response.ToString()); + if (response.Content != null) + { + Console.WriteLine(await response.Content.ReadAsStringAsync()); + } + Console.WriteLine(); + + return response; + } + } } \ No newline at end of file diff --git a/FosscordSharp/ResponseTypes/CustomStatus.cs b/FosscordSharp/ResponseTypes/CustomStatus.cs index 1488240..581ad42 100644 --- a/FosscordSharp/ResponseTypes/CustomStatus.cs +++ b/FosscordSharp/ResponseTypes/CustomStatus.cs @@ -1,6 +1,6 @@ -namespace FosscordSharp.ResponseTypes -{ - public class CustomStatus - { - } +namespace FosscordSharp.ResponseTypes +{ + public class CustomStatus + { + } } \ No newline at end of file diff --git a/FosscordSharp/ResponseTypes/Error.cs b/FosscordSharp/ResponseTypes/Error.cs index e0fa064..a7b9148 100644 --- a/FosscordSharp/ResponseTypes/Error.cs +++ b/FosscordSharp/ResponseTypes/Error.cs @@ -1,7 +1,7 @@ -namespace FosscordSharp.ResponseTypes -{ - public class Error - { - - } +namespace FosscordSharp.ResponseTypes +{ + public class Error + { + + } } \ No newline at end of file diff --git a/FosscordSharp/ResponseTypes/FriendSourceFlags.cs b/FosscordSharp/ResponseTypes/FriendSourceFlags.cs index c970784..15a1975 100644 --- a/FosscordSharp/ResponseTypes/FriendSourceFlags.cs +++ b/FosscordSharp/ResponseTypes/FriendSourceFlags.cs @@ -1,10 +1,10 @@ -using Newtonsoft.Json; - -namespace FosscordSharp.ResponseTypes -{ - public class FriendSourceFlags - { - [JsonProperty("all")] - public bool All; - } +using Newtonsoft.Json; + +namespace FosscordSharp.ResponseTypes +{ + public class FriendSourceFlags + { + [JsonProperty("all")] + public bool All; + } } \ No newline at end of file diff --git a/FosscordSharp/ResponseTypes/GuildCreatedResponse.cs b/FosscordSharp/ResponseTypes/GuildCreatedResponse.cs index d8d81d6..25e27ab 100644 --- a/FosscordSharp/ResponseTypes/GuildCreatedResponse.cs +++ b/FosscordSharp/ResponseTypes/GuildCreatedResponse.cs @@ -1,9 +1,9 @@ -using FosscordSharp.Core; - -namespace FosscordSharp.ResponseTypes -{ - public class GuildCreatedResponse : FosscordObject - { - public ulong id { get; set; } = 0; - } +using FosscordSharp.Core; + +namespace FosscordSharp.ResponseTypes +{ + public class GuildCreatedResponse : FosscordObject + { + public ulong id { get; set; } = 0; + } } \ No newline at end of file diff --git a/FosscordSharp/ResponseTypes/LoginResponse.cs b/FosscordSharp/ResponseTypes/LoginResponse.cs index 222b48b..0c17971 100644 --- a/FosscordSharp/ResponseTypes/LoginResponse.cs +++ b/FosscordSharp/ResponseTypes/LoginResponse.cs @@ -1,18 +1,18 @@ -using System.Text.Json.Serialization; -using FosscordSharp.Core; -using FosscordSharp.Entities; -using Newtonsoft.Json; - -namespace FosscordSharp.ResponseTypes -{ - public class RegisterResponse : FosscordObject - { - [JsonProperty("token")] - public string Token; - } - public class LoginResponse : RegisterResponse - { - [JsonProperty("settings")] - public Settings Settings; - } +using System.Text.Json.Serialization; +using FosscordSharp.Core; +using FosscordSharp.Entities; +using Newtonsoft.Json; + +namespace FosscordSharp.ResponseTypes +{ + public class RegisterResponse : FosscordObject + { + [JsonProperty("token")] + public string Token; + } + public class LoginResponse : RegisterResponse + { + [JsonProperty("settings")] + public Settings Settings; + } } \ No newline at end of file diff --git a/FosscordSharp/ResponseTypes/RateLimitResponse.cs b/FosscordSharp/ResponseTypes/RateLimitResponse.cs index 4be3f8d..95d6b12 100644 --- a/FosscordSharp/ResponseTypes/RateLimitResponse.cs +++ b/FosscordSharp/ResponseTypes/RateLimitResponse.cs @@ -1,16 +1,16 @@ -using Newtonsoft.Json; - -namespace FosscordSharp.ResponseTypes -{ - public class RateLimitResponse - { - [JsonProperty("message")] - public string Message { get; set; } - - [JsonProperty("retry_after")] - public double RetryAfter { get; set; } - - [JsonProperty("global")] - public bool Global { get; set; } - } +using Newtonsoft.Json; + +namespace FosscordSharp.ResponseTypes +{ + public class RateLimitResponse + { + [JsonProperty("message")] + public string Message { get; set; } + + [JsonProperty("retry_after")] + public double RetryAfter { get; set; } + + [JsonProperty("global")] + public bool Global { get; set; } + } } \ No newline at end of file diff --git a/FosscordSharp/ResponseTypes/RegisterResponse.cs b/FosscordSharp/ResponseTypes/RegisterResponse.cs index 9272caf..26d3454 100644 --- a/FosscordSharp/ResponseTypes/RegisterResponse.cs +++ b/FosscordSharp/ResponseTypes/RegisterResponse.cs @@ -1,10 +1,10 @@ -using System.Text.Json.Serialization; -using FosscordSharp.Core; -using Newtonsoft.Json; - -namespace FosscordSharp.ResponseTypes -{ - - - +using System.Text.Json.Serialization; +using FosscordSharp.Core; +using Newtonsoft.Json; + +namespace FosscordSharp.ResponseTypes +{ + + + } \ No newline at end of file diff --git a/FosscordSharp/RuntimeInfo.cs b/FosscordSharp/RuntimeInfo.cs index d013586..c54c978 100644 --- a/FosscordSharp/RuntimeInfo.cs +++ b/FosscordSharp/RuntimeInfo.cs @@ -1,10 +1,10 @@ -using System; -using System.Reflection; - -namespace FosscordSharp -{ - public class RuntimeInfo - { - public static Version LibVersion => Assembly.GetExecutingAssembly().GetName().Version; - } +using System; +using System.Reflection; + +namespace FosscordSharp +{ + public class RuntimeInfo + { + public static Version LibVersion => Assembly.GetExecutingAssembly().GetName().Version; + } } \ No newline at end of file diff --git a/FosscordSharp/Services/MessagePoller.cs b/FosscordSharp/Services/MessagePoller.cs index fd31505..7fc3243 100644 --- a/FosscordSharp/Services/MessagePoller.cs +++ b/FosscordSharp/Services/MessagePoller.cs @@ -1,50 +1,50 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading; -using System.Threading.Tasks; -using FosscordSharp.Entities; - -namespace FosscordSharp.Services -{ - internal class MessagePoller - { - internal FosscordClient _client; - - public MessagePoller(FosscordClient client) - { - _client = client; - } - - internal Dictionary LastCheckedMessages = new(); - internal void Start() - { - Task.Run(async () => - { - while (true) - { - Guild[] guilds = await _client.GetGuilds(); - foreach (var guild in guilds) - { - Channel[] channels = await guild.GetChannels(); - foreach (var channel in channels) - { - string key = $"{guild.Id}/{channel.Id}"; - if (!LastCheckedMessages.ContainsKey(key)) - LastCheckedMessages.Add(key, channel.LastMessageId??0); - foreach (var message in await channel.GetMessages(after: LastCheckedMessages[key])) - { - _client.OnMessageReceived(new() - { - Message = message - }); - LastCheckedMessages[key] = Math.Max(message.Id, LastCheckedMessages[key]); - } - } - } - Thread.Sleep(1000); - } - }); - } - } +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using FosscordSharp.Entities; + +namespace FosscordSharp.Services +{ + internal class MessagePoller + { + internal FosscordClient _client; + + public MessagePoller(FosscordClient client) + { + _client = client; + } + + internal Dictionary LastCheckedMessages = new(); + internal void Start() + { + Task.Run(async () => + { + while (true) + { + Guild[] guilds = await _client.GetGuilds(); + foreach (var guild in guilds) + { + Channel[] channels = await guild.GetChannels(); + foreach (var channel in channels) + { + string key = $"{guild.Id}/{channel.Id}"; + if (!LastCheckedMessages.ContainsKey(key)) + LastCheckedMessages.Add(key, channel.LastMessageId??0); + foreach (var message in await channel.GetMessages(after: LastCheckedMessages[key])) + { + _client.OnMessageReceived(new() + { + Message = message + }); + LastCheckedMessages[key] = Math.Max(message.Id, LastCheckedMessages[key]); + } + } + } + Thread.Sleep(1000); + } + }); + } + } } \ No newline at end of file diff --git a/FosscordSharp/Utilities/ClientExtensions.cs b/FosscordSharp/Utilities/ClientExtensions.cs index c0c1f28..e9a8f66 100644 --- a/FosscordSharp/Utilities/ClientExtensions.cs +++ b/FosscordSharp/Utilities/ClientExtensions.cs @@ -1,189 +1,189 @@ -using System; -using System.Collections; -using System.Collections.Generic; -using System.Diagnostics; -using System.Net; -using System.Net.Http; -using System.Net.Http.Json; -using System.Threading; -using System.Threading.Tasks; -using FosscordSharp.Core; -using FosscordSharp.ResponseTypes; -using Newtonsoft.Json; -using OneOf; - -namespace FosscordSharp.Utilities -{ - public static class ClientExtensions - { - public static async Task> GetAsync(this FosscordClient cli, string url) where T : class - { - var _resp = await cli._httpClient.GetAsync(url); - var resp = await _resp.Content.ReadAsStringAsync(); - if(cli._config.Verbose) cli.debugLog.Log(resp); - if (!_resp.IsSuccessStatusCode) - { - if (_resp.StatusCode == HttpStatusCode.TooManyRequests) - { - var ratelimit = JsonConvert.DeserializeObject(resp); - Console.WriteLine($"Ratelimited, trying again in {ratelimit.RetryAfter} seconds (endpoint: {url})"); - Thread.Sleep((int)(ratelimit.RetryAfter*1000)); - return await GetAsync(cli, url); - } - return JsonConvert.DeserializeObject(resp); - } - object obj = JsonConvert.DeserializeObject(resp); - if (obj.GetType().IsArray) - { - foreach (var a in (IEnumerable)obj) - { - ((a as FosscordObject)!)._client = cli; - } - } - else - { - ((obj as FosscordObject)!)._client = cli; - } - return (T)obj; - } - public static async Task> PostJsonAsync(this FosscordClient cli, string url, object data) - { - try - { - var _resp = await cli._httpClient.PostAsJsonAsync(url, data); - var resp = await _resp.Content.ReadAsStringAsync(); - if (cli._config.Verbose) cli.debugLog.Log(resp); - if (!_resp.IsSuccessStatusCode) - { - if (_resp.StatusCode == HttpStatusCode.TooManyRequests) - { - var ratelimit = JsonConvert.DeserializeObject(resp); - Console.WriteLine($"Ratelimited, trying again in {ratelimit.RetryAfter} seconds (endpoint: {url})"); - Thread.Sleep((int)(ratelimit.RetryAfter*1000)); - return await PostJsonAsync(cli, url, data); - } - try - { - return JsonConvert.DeserializeObject(resp); - } - catch (Exception e) - { - Console.WriteLine(e); - - } - } - - try { - var obj = JsonConvert.DeserializeObject(resp); - if (obj.GetType().IsArray) { - // _client.log.Log("obj is array"); - foreach (var a in obj as T[]) { - // _client.log.Log("obj[] setting client"); - ((a as FosscordObject)!)._client = cli; - } - } - else { - // _client.log.LogDebugStdout("obj is not array"); - ((obj as FosscordObject)!)._client = cli; - // _client.log.LogDebugStdout("Set _client"); - } - - return obj; - } - catch (Exception e) { - throw new Exception($"Post request failed on {cli._config.Endpoint}/{url}: ", e); - } - - } - catch(Exception e) - { - Console.WriteLine(new Exception($"Post request failed on {cli._config.Endpoint}/{url}: ", e)); - throw; - } - } - public static async Task> DeleteAsync(this FosscordClient cli, string url) where T : class - { - var _resp = await cli._httpClient.DeleteAsync(url); - var resp = await _resp.Content.ReadAsStringAsync(); - if(cli._config.Verbose) cli.log.Log(resp); - if (!_resp.IsSuccessStatusCode) - { - if (_resp.StatusCode == HttpStatusCode.TooManyRequests) - { - var ratelimit = JsonConvert.DeserializeObject(resp); - Console.WriteLine($"Ratelimited, trying again in {ratelimit.RetryAfter} seconds (endpoint: {url})"); - Thread.Sleep((int)(ratelimit.RetryAfter*1000)); - return await GetAsync(cli, url); - } - return JsonConvert.DeserializeObject(resp); - } - object obj = JsonConvert.DeserializeObject(resp); - if (obj.GetType().IsArray) - { - foreach (var a in (IEnumerable)obj) - { - ((a as FosscordObject)!)._client = cli; - } - } - else - { - ((obj as FosscordObject)!)._client = cli; - } - return (T)obj; - } - public static async Task> PostFileWithDataAsync(this FosscordClient cli, string url, object data, object file) - { - try { - var f = new MultipartFormDataContent(); - // f.Add(new StringContent()); - - - var _resp = await cli._httpClient.PostAsJsonAsync(url, data); - var resp = await _resp.Content.ReadAsStringAsync(); - if (cli._config.Verbose) cli.debugLog.Log(resp); - if (!_resp.IsSuccessStatusCode) - { - if (_resp.StatusCode == HttpStatusCode.TooManyRequests) - { - var ratelimit = JsonConvert.DeserializeObject(resp); - Console.WriteLine($"Ratelimited, trying again in {ratelimit.RetryAfter} seconds (endpoint: {url})"); - Thread.Sleep((int)(ratelimit.RetryAfter*1000)); - return await PostJsonAsync(cli, url, data); - } - try - { - return JsonConvert.DeserializeObject(resp); - } - catch (Exception e) - { - Console.WriteLine(e); - - } - } - var obj = JsonConvert.DeserializeObject(resp); - if (obj.GetType().IsArray) - { - // _client.log.Log("obj is array"); - foreach (var a in obj as T[]) - { - // _client.log.Log("obj[] setting client"); - ((a as FosscordObject)!)._client = cli; - } - } - else - { - // _client.log.LogDebugStdout("obj is not array"); - ((obj as FosscordObject)!)._client = cli; - // _client.log.LogDebugStdout("Set _client"); - } - - return obj; - } - catch(Exception e) - { - Console.WriteLine(e); - throw; - } - } - } +using System; +using System.Collections; +using System.Collections.Generic; +using System.Diagnostics; +using System.Net; +using System.Net.Http; +using System.Net.Http.Json; +using System.Threading; +using System.Threading.Tasks; +using FosscordSharp.Core; +using FosscordSharp.ResponseTypes; +using Newtonsoft.Json; +using OneOf; + +namespace FosscordSharp.Utilities +{ + public static class ClientExtensions + { + public static async Task> GetAsync(this FosscordClient cli, string url) where T : class + { + var _resp = await cli._httpClient.GetAsync(url); + var resp = await _resp.Content.ReadAsStringAsync(); + if(cli._config.Verbose) cli.debugLog.Log(resp); + if (!_resp.IsSuccessStatusCode) + { + if (_resp.StatusCode == HttpStatusCode.TooManyRequests) + { + var ratelimit = JsonConvert.DeserializeObject(resp); + Console.WriteLine($"Ratelimited, trying again in {ratelimit.RetryAfter} seconds (endpoint: {url})"); + Thread.Sleep((int)(ratelimit.RetryAfter*1000)); + return await GetAsync(cli, url); + } + return JsonConvert.DeserializeObject(resp); + } + object obj = JsonConvert.DeserializeObject(resp); + if (obj.GetType().IsArray) + { + foreach (var a in (IEnumerable)obj) + { + ((a as FosscordObject)!)._client = cli; + } + } + else + { + ((obj as FosscordObject)!)._client = cli; + } + return (T)obj; + } + public static async Task> PostJsonAsync(this FosscordClient cli, string url, object data) + { + try + { + var _resp = await cli._httpClient.PostAsJsonAsync(url, data); + var resp = await _resp.Content.ReadAsStringAsync(); + if (cli._config.Verbose) cli.debugLog.Log(resp); + if (!_resp.IsSuccessStatusCode) + { + if (_resp.StatusCode == HttpStatusCode.TooManyRequests) + { + var ratelimit = JsonConvert.DeserializeObject(resp); + Console.WriteLine($"Ratelimited, trying again in {ratelimit.RetryAfter} seconds (endpoint: {url})"); + Thread.Sleep((int)(ratelimit.RetryAfter*1000)); + return await PostJsonAsync(cli, url, data); + } + try + { + return JsonConvert.DeserializeObject(resp); + } + catch (Exception e) + { + Console.WriteLine(e); + + } + } + + try { + var obj = JsonConvert.DeserializeObject(resp); + if (obj.GetType().IsArray) { + // _client.log.Log("obj is array"); + foreach (var a in obj as T[]) { + // _client.log.Log("obj[] setting client"); + ((a as FosscordObject)!)._client = cli; + } + } + else { + // _client.log.LogDebugStdout("obj is not array"); + ((obj as FosscordObject)!)._client = cli; + // _client.log.LogDebugStdout("Set _client"); + } + + return obj; + } + catch (Exception e) { + throw new Exception($"Post request failed on {cli._config.Endpoint}/{url}: ", e); + } + + } + catch(Exception e) + { + Console.WriteLine(new Exception($"Post request failed on {cli._config.Endpoint}/{url}: ", e)); + throw; + } + } + public static async Task> DeleteAsync(this FosscordClient cli, string url) where T : class + { + var _resp = await cli._httpClient.DeleteAsync(url); + var resp = await _resp.Content.ReadAsStringAsync(); + if(cli._config.Verbose) cli.log.Log(resp); + if (!_resp.IsSuccessStatusCode) + { + if (_resp.StatusCode == HttpStatusCode.TooManyRequests) + { + var ratelimit = JsonConvert.DeserializeObject(resp); + Console.WriteLine($"Ratelimited, trying again in {ratelimit.RetryAfter} seconds (endpoint: {url})"); + Thread.Sleep((int)(ratelimit.RetryAfter*1000)); + return await GetAsync(cli, url); + } + return JsonConvert.DeserializeObject(resp); + } + object obj = JsonConvert.DeserializeObject(resp); + if (obj.GetType().IsArray) + { + foreach (var a in (IEnumerable)obj) + { + ((a as FosscordObject)!)._client = cli; + } + } + else + { + ((obj as FosscordObject)!)._client = cli; + } + return (T)obj; + } + public static async Task> PostFileWithDataAsync(this FosscordClient cli, string url, object data, object file) + { + try { + var f = new MultipartFormDataContent(); + // f.Add(new StringContent()); + + + var _resp = await cli._httpClient.PostAsJsonAsync(url, data); + var resp = await _resp.Content.ReadAsStringAsync(); + if (cli._config.Verbose) cli.debugLog.Log(resp); + if (!_resp.IsSuccessStatusCode) + { + if (_resp.StatusCode == HttpStatusCode.TooManyRequests) + { + var ratelimit = JsonConvert.DeserializeObject(resp); + Console.WriteLine($"Ratelimited, trying again in {ratelimit.RetryAfter} seconds (endpoint: {url})"); + Thread.Sleep((int)(ratelimit.RetryAfter*1000)); + return await PostJsonAsync(cli, url, data); + } + try + { + return JsonConvert.DeserializeObject(resp); + } + catch (Exception e) + { + Console.WriteLine(e); + + } + } + var obj = JsonConvert.DeserializeObject(resp); + if (obj.GetType().IsArray) + { + // _client.log.Log("obj is array"); + foreach (var a in obj as T[]) + { + // _client.log.Log("obj[] setting client"); + ((a as FosscordObject)!)._client = cli; + } + } + else + { + // _client.log.LogDebugStdout("obj is not array"); + ((obj as FosscordObject)!)._client = cli; + // _client.log.LogDebugStdout("Set _client"); + } + + return obj; + } + catch(Exception e) + { + Console.WriteLine(e); + throw; + } + } + } } \ No newline at end of file diff --git a/FosscordSharp/Utilities/DependencyTreeTools.cs b/FosscordSharp/Utilities/DependencyTreeTools.cs index e78a3cf..c9960ef 100644 --- a/FosscordSharp/Utilities/DependencyTreeTools.cs +++ b/FosscordSharp/Utilities/DependencyTreeTools.cs @@ -1,32 +1,32 @@ -using System; -using FosscordSharp.Core; - -namespace FosscordSharp.Utilities -{ - internal static class DependencyTreeTools - { - public static void SetClient(this FosscordObject str, FosscordClient cli) - { - str._client = cli; - } - - public static void SetClientInTree(this FosscordObject obj, FosscordClient cli) - { - obj._client = cli; - Type type = obj.GetType(); - var pl = type.GetProperties(); - foreach (var p in pl) - { - if(p.PropertyType.IsSubclassOf(typeof(FosscordObject))) - { - // Console.WriteLine("found property " + p.Name + ": " + p.PropertyType.Name); - ((FosscordObject)p.GetValue(obj)).SetClientInTree(cli); - } - else - { - // Console.WriteLine("not " + p.Name + ": " + p.PropertyType.Name); - } - } - } - } +using System; +using FosscordSharp.Core; + +namespace FosscordSharp.Utilities +{ + internal static class DependencyTreeTools + { + public static void SetClient(this FosscordObject str, FosscordClient cli) + { + str._client = cli; + } + + public static void SetClientInTree(this FosscordObject obj, FosscordClient cli) + { + obj._client = cli; + Type type = obj.GetType(); + var pl = type.GetProperties(); + foreach (var p in pl) + { + if(p.PropertyType.IsSubclassOf(typeof(FosscordObject))) + { + // Console.WriteLine("found property " + p.Name + ": " + p.PropertyType.Name); + ((FosscordObject)p.GetValue(obj)).SetClientInTree(cli); + } + else + { + // Console.WriteLine("not " + p.Name + ": " + p.PropertyType.Name); + } + } + } + } } \ No newline at end of file diff --git a/FosscordSharp/Utilities/StringExtensions.cs b/FosscordSharp/Utilities/StringExtensions.cs index a968031..cc1c1e0 100644 --- a/FosscordSharp/Utilities/StringExtensions.cs +++ b/FosscordSharp/Utilities/StringExtensions.cs @@ -1,19 +1,19 @@ -using System; -using System.Text; - -namespace FosscordSharp.Utilities -{ - internal static class StringExtensions - { - public static byte[] ToUTF8ByteArray(this string str) - { - return Encoding.UTF8.GetBytes(str); - } - - public static ArraySegment ToArraySegment(this string str) - { - var barr = str.ToUTF8ByteArray(); - return new(barr, 0, barr.Length); - } - } +using System; +using System.Text; + +namespace FosscordSharp.Utilities +{ + internal static class StringExtensions + { + public static byte[] ToUTF8ByteArray(this string str) + { + return Encoding.UTF8.GetBytes(str); + } + + public static ArraySegment ToArraySegment(this string str) + { + var barr = str.ToUTF8ByteArray(); + return new(barr, 0, barr.Length); + } + } } \ No newline at end of file diff --git a/FosscordSharp/WebsocketData/Identify.cs b/FosscordSharp/WebsocketData/Identify.cs index 0ff2c3f..5b41f9e 100644 --- a/FosscordSharp/WebsocketData/Identify.cs +++ b/FosscordSharp/WebsocketData/Identify.cs @@ -1,21 +1,21 @@ -using System; -using Newtonsoft.Json; - -namespace FosscordSharp.WebsocketData -{ - internal class Identify - { - public string token; - - public Properties properties; - public bool compress; - // public int large_treshold; - - internal class Properties - { - [JsonProperty("$os")] public string os; - [JsonProperty("$browser")] public string browser; - [JsonProperty("$device")] public string device; - } - } +using System; +using Newtonsoft.Json; + +namespace FosscordSharp.WebsocketData +{ + internal class Identify + { + public string token; + + public Properties properties; + public bool compress; + // public int large_treshold; + + internal class Properties + { + [JsonProperty("$os")] public string os; + [JsonProperty("$browser")] public string browser; + [JsonProperty("$device")] public string device; + } + } } \ No newline at end of file diff --git a/FosscordSharp/WebsocketMessage.cs b/FosscordSharp/WebsocketMessage.cs index 4c69c67..b07dbd0 100644 --- a/FosscordSharp/WebsocketMessage.cs +++ b/FosscordSharp/WebsocketMessage.cs @@ -1,40 +1,40 @@ -using Newtonsoft.Json; -using Newtonsoft.Json.Linq; - -namespace FosscordSharp -{ - public class WebsocketMessage - { - [JsonProperty("op")] public int OpCode { get; set; } = 0; - [JsonProperty("d")] public object? EventData { get; set; } - - [JsonProperty("s")] public int? SequenceNum { get; set; } - - [JsonProperty("t")] public string? EventName { get; set; } - } - - public class ExplainedWebsocketMessage - { - public WebsocketMessage _msg; - - public ExplainedWebsocketMessage(WebsocketMessage msg) - { - _msg = msg; - } - public string EventDesc => _msg.OpCode switch - { - 0 => "Dispatch", - 1 => "Heartbeat", - 2 => "Identify", - 3 => "Presence Update", - 4 => "Voice State Update", - 6 => "Resume", - 7 => "Reconnect", - 8 => "Request Guild Members (send)", - 9 => "Invalid Session", - 10 => "Hello", - 11 => "Heartbeat ACK", - _ => "Unknown" - }; - } +using Newtonsoft.Json; +using Newtonsoft.Json.Linq; + +namespace FosscordSharp +{ + public class WebsocketMessage + { + [JsonProperty("op")] public int OpCode { get; set; } = 0; + [JsonProperty("d")] public object? EventData { get; set; } + + [JsonProperty("s")] public int? SequenceNum { get; set; } + + [JsonProperty("t")] public string? EventName { get; set; } + } + + public class ExplainedWebsocketMessage + { + public WebsocketMessage _msg; + + public ExplainedWebsocketMessage(WebsocketMessage msg) + { + _msg = msg; + } + public string EventDesc => _msg.OpCode switch + { + 0 => "Dispatch", + 1 => "Heartbeat", + 2 => "Identify", + 3 => "Presence Update", + 4 => "Voice State Update", + 6 => "Resume", + 7 => "Reconnect", + 8 => "Request Guild Members (send)", + 9 => "Invalid Session", + 10 => "Hello", + 11 => "Heartbeat ACK", + _ => "Unknown" + }; + } } \ No newline at end of file diff --git a/README.MD b/README.MD index e424b86..82f0e9a 100644 --- a/README.MD +++ b/README.MD @@ -1,2 +1,2 @@ -# Fosscord-Sharp +# Fosscord-Sharp Fosscord API wrapper for C# \ No newline at end of file