C
C#

Discord.Net + MagicOnion, heheh

Discord.Net + MagicOnion, heheh

SStilauGamer11/20/2023
Hey! So I am working on a discord bot that I want to intergrate into a server using websockets, I found MagicOnion and wanted to test it out, but I can only find documentation to how to use it with Asp.Net. Does anyone know how I would implement it with Discord.Net? I have a test service that uses the ServiceBase<> and IService<> This is my current code for my bot:
public static Task Main()
=> new Program().MainAsync();

private async Task MainAsync()
{
try
{
var client = new DiscordSocketClient();

using var host = Host.CreateDefaultBuilder()
.ConfigureServices((_, services) =>
{
services
.AddSingleton(client)
.AddSingleton(i => new InteractionService(i.GetRequiredService<DiscordSocketClient>()))
.AddSingleton<InteractionHandler>()
.AddTransient<ITestService, TestService>();

services.AddGrpc();
services.AddMagicOnion();
}
).Build();

await RunAsync(host);
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}

private async Task RunAsync(IHost host)
{
using var serviceScope = host.Services.CreateScope();
var serviceProvider = serviceScope.ServiceProvider;


var commands = serviceProvider
.GetRequiredService<InteractionService>();
var client = serviceProvider
.GetRequiredService<DiscordSocketClient>();

await serviceProvider
.GetRequiredService<InteractionHandler>()
.InitializeAsync();


await client.LoginAsync(TokenType.Bot, Token);
await client.StartAsync();

client.Log += Log;
client.Ready += async () =>
{
await commands.RegisterCommandsToGuildAsync(DiscordGuildId);
};

await Task.Delay(-1);
}
public static Task Main()
=> new Program().MainAsync();

private async Task MainAsync()
{
try
{
var client = new DiscordSocketClient();

using var host = Host.CreateDefaultBuilder()
.ConfigureServices((_, services) =>
{
services
.AddSingleton(client)
.AddSingleton(i => new InteractionService(i.GetRequiredService<DiscordSocketClient>()))
.AddSingleton<InteractionHandler>()
.AddTransient<ITestService, TestService>();

services.AddGrpc();
services.AddMagicOnion();
}
).Build();

await RunAsync(host);
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}

private async Task RunAsync(IHost host)
{
using var serviceScope = host.Services.CreateScope();
var serviceProvider = serviceScope.ServiceProvider;


var commands = serviceProvider
.GetRequiredService<InteractionService>();
var client = serviceProvider
.GetRequiredService<DiscordSocketClient>();

await serviceProvider
.GetRequiredService<InteractionHandler>()
.InitializeAsync();


await client.LoginAsync(TokenType.Bot, Token);
await client.StartAsync();

client.Log += Log;
client.Ready += async () =>
{
await commands.RegisterCommandsToGuildAsync(DiscordGuildId);
};

await Task.Delay(-1);
}
UUUnknown User11/20/2023
5 Messages Not Public
Sign In & Join Server To View
MMODiX11/20/2023
$mains
UUUnknown User11/20/2023
Message Not Public
Sign In & Join Server To View
MMODiX11/20/2023
The possible signatures for Main are
public static void Main() { }
public static int Main() { }
public static void Main(string[] args) { }
public static int Main(string[] args) { }
public static async Task Main() { }
public static async Task<int> Main() { }
public static async Task Main(string[] args) { }
public static async Task<int> Main(string[] args) { }
public static void Main() { }
public static int Main() { }
public static void Main(string[] args) { }
public static int Main(string[] args) { }
public static async Task Main() { }
public static async Task<int> Main() { }
public static async Task Main(string[] args) { }
public static async Task<int> Main(string[] args) { }
public is not required (can be any accessibility). Top-level statements are compiled into a Main method and will use an appropriate signature depending on the body. https://docs.microsoft.com/en-US/dotnet/csharp/fundamentals/program-structure/main-command-line
UUUnknown User11/20/2023
2 Messages Not Public
Sign In & Join Server To View
SStilauGamer11/20/2023
But idk if this solved my issue tho, having the bot be a websocket server aswell?
UUUnknown User11/20/2023
4 Messages Not Public
Sign In & Join Server To View
SStilauGamer11/20/2023
I really appreciate the tips on how to simplify the code, don't get me wrong. My original question was how I could implement MagicOnion, a websocket library into the bot. I wanted the bot to act like a websocket server for other clients to connect into if that makes sense.
UUUnknown User11/20/2023
3 Messages Not Public
Sign In & Join Server To View
SStilauGamer11/20/2023
Ahhh okay, I'll give it a try. So just try running most of it from the Main method?
UUUnknown User11/20/2023
2 Messages Not Public
Sign In & Join Server To View
SStilauGamer11/22/2023
So like this instead?
public class Program
{
public static Task Main()
=> new Program().MainAsync();

private async Task MainAsync()
{
try
{
var client = new DiscordSocketClient();

using var host = Host.CreateDefaultBuilder()
.ConfigureServices((_, services) =>
{

services.AddSingleton(client);
services.AddSingleton(i => new InteractionService(i.GetRequiredService<DiscordSocketClient>()));
services.AddHostedService<DiscordSocketClientHostedService>();
services.AddTransient<ITestService, TestService>();
services.AddSingleton<InteractionHandler>();
services.AddMagicOnion();
services.AddGrpc();
}
).Build();

await host.Services
.GetRequiredService<InteractionHandler>()
.InitializeAsync();

await host.RunAsync();
await Task.Delay(-1);
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
}

public class DiscordSocketClientHostedService : BackgroundService
{
private readonly DiscordSocketClient _client;
private readonly IServiceProvider _serviceProvider;

private const ulong DiscordGuildId = 0;
private const string Token = "NotGonnaGetTHECHANCE";

public DiscordSocketClientHostedService(
DiscordSocketClient client,
IServiceProvider serviceProvider
)
{
_client = client;
_serviceProvider = serviceProvider;
}

protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
var commands = _serviceProvider
.GetRequiredService<InteractionService>();

await _client.LoginAsync(TokenType.Bot, Token);
await _client.StartAsync();

_client.Log += Log;
_client.Ready += async () =>
{
await commands.RegisterCommandsToGuildAsync(DiscordGuildId);
};
}

private Task Log(LogMessage log)
{
Console.WriteLine(log.Message);
return Task.CompletedTask;
}
}
public class Program
{
public static Task Main()
=> new Program().MainAsync();

private async Task MainAsync()
{
try
{
var client = new DiscordSocketClient();

using var host = Host.CreateDefaultBuilder()
.ConfigureServices((_, services) =>
{

services.AddSingleton(client);
services.AddSingleton(i => new InteractionService(i.GetRequiredService<DiscordSocketClient>()));
services.AddHostedService<DiscordSocketClientHostedService>();
services.AddTransient<ITestService, TestService>();
services.AddSingleton<InteractionHandler>();
services.AddMagicOnion();
services.AddGrpc();
}
).Build();

await host.Services
.GetRequiredService<InteractionHandler>()
.InitializeAsync();

await host.RunAsync();
await Task.Delay(-1);
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
}

public class DiscordSocketClientHostedService : BackgroundService
{
private readonly DiscordSocketClient _client;
private readonly IServiceProvider _serviceProvider;

private const ulong DiscordGuildId = 0;
private const string Token = "NotGonnaGetTHECHANCE";

public DiscordSocketClientHostedService(
DiscordSocketClient client,
IServiceProvider serviceProvider
)
{
_client = client;
_serviceProvider = serviceProvider;
}

protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
var commands = _serviceProvider
.GetRequiredService<InteractionService>();

await _client.LoginAsync(TokenType.Bot, Token);
await _client.StartAsync();

_client.Log += Log;
_client.Ready += async () =>
{
await commands.RegisterCommandsToGuildAsync(DiscordGuildId);
};
}

private Task Log(LogMessage log)
{
Console.WriteLine(log.Message);
return Task.CompletedTask;
}
}
Hey! I still need some help with this. I've done some changes, but I can still not get it to work. This is my current code: https://pastecord.com/olofinitob All help is deeply appreciated. My goal is to send data from and to a game server, but I want the websocket server to be on the discord bot. So I don't need to do: - Game Server -> Magic Onion Server -> Discord Bot - Wise Versa How can I do so? It looks like Magic Onion is mostly made for Asp.Net apps, but this is a console app trollq
UUUnknown User11/22/2023
9 Messages Not Public
Sign In & Join Server To View
SStilauGamer11/22/2023
Am I able to run the bot on a ASP app?
UUUnknown User11/22/2023
6 Messages Not Public
Sign In & Join Server To View
SStilauGamer11/22/2023
I've worked with like ASP api's, etc before. But never something like this lmao
UUUnknown User11/22/2023
3 Messages Not Public
Sign In & Join Server To View
SStilauGamer11/22/2023
aahh
UUUnknown User11/22/2023
Message Not Public
Sign In & Join Server To View
SStilauGamer11/22/2023
So I was basically trying to make an ASP app in a console app ish
UUUnknown User11/22/2023
Message Not Public
Sign In & Join Server To View
SStilauGamer11/22/2023
without the web server part
UUUnknown User11/22/2023
Message Not Public
Sign In & Join Server To View
SStilauGamer11/22/2023
Does this look more correct then? https://pastecord.com/duhebusywo.cs Now its running on an asp app instead
UUUnknown User11/22/2023
3 Messages Not Public
Sign In & Join Server To View
SStilauGamer11/22/2023
But background service are basically just for starting something to run in the background right? Its just a way for it to auto load when the program starts ish?
UUUnknown User11/22/2023
9 Messages Not Public
Sign In & Join Server To View
SStilauGamer11/22/2023
Why? Whats up with using the logger?
UUUnknown User11/22/2023
Message Not Public
Sign In & Join Server To View
SStilauGamer11/22/2023
Okay, I've never actually heard abt that lmao
UUUnknown User11/22/2023
3 Messages Not Public
Sign In & Join Server To View
SStilauGamer11/22/2023
Using the $ is not recommended?
UUUnknown User11/22/2023
2 Messages Not Public
Sign In & Join Server To View
SStilauGamer11/22/2023
ahhhh
UUUnknown User11/22/2023
2 Messages Not Public
Sign In & Join Server To View
SStilauGamer11/22/2023
Ah okay, and I shouldn't be the one filling in the template {}, basically
UUUnknown User11/22/2023
7 Messages Not Public
Sign In & Join Server To View
SStilauGamer11/22/2023
Ahhhhhhh Bro is filling my mind, I feel my brain is expanding šŸ˜‚
UUUnknown User11/22/2023
2 Messages Not Public
Sign In & Join Server To View
UUUnknown User11/22/2023
2 Messages Not Public
Sign In & Join Server To View
SStilauGamer11/22/2023
And there you talk about how to do it correctly when it comes to logging?
UUUnknown User11/22/2023
2 Messages Not Public
Sign In & Join Server To View
SStilauGamer11/22/2023
Ahh okay, I'll have a read on it. I've fallen really for C# and just trying to learn as much as I can lol But its not always the easiest šŸ˜…
UUUnknown User11/22/2023
3 Messages Not Public
Sign In & Join Server To View
SStilauGamer11/22/2023
Okay wtf
UUUnknown User11/22/2023
Message Not Public
Sign In & Join Server To View
SStilauGamer11/22/2023
šŸ˜‚
UUUnknown User11/22/2023
3 Messages Not Public
Sign In & Join Server To View
SStilauGamer11/22/2023
So basically. I make a log method. Like this:
[LoggerMessage(
EventId = 20,
Level = LogLevel.Critical,
Message = "{Username} has hit an error!")]
public static partial void LogUserError(
ILogger logger, string Username);
[LoggerMessage(
EventId = 20,
Level = LogLevel.Critical,
Message = "{Username} has hit an error!")]
public static partial void LogUserError(
ILogger logger, string Username);
and when I want to use it I can do smth like: LogUserError(logger, _client.CurrentUser.UserName);
UUUnknown User11/22/2023
Message Not Public
Sign In & Join Server To View
SStilauGamer11/22/2023
Ahh, and this is the most official and recommended way of doing logging ig?
UUUnknown User11/22/2023
2 Messages Not Public
Sign In & Join Server To View
SStilauGamer11/22/2023
CustomEventName šŸ¤” So instead of doing _logger.LogInformation("{Username} has hit an error", _client.CurrentUser.UserName), I should do this.
UUUnknown User11/22/2023
3 Messages Not Public
Sign In & Join Server To View
SStilauGamer11/22/2023
šŸ„¹ So basically like this: Log.BotStarted(_logger, _client.CurrentUser.Username);
public partial class Log
{
[LoggerMessage(
Level = LogLevel.Information,
Message = "{Username} has been started!")]
public static partial void BotStarted(ILogger logger, string username);
}
public partial class Log
{
[LoggerMessage(
Level = LogLevel.Information,
Message = "{Username} has been started!")]
public static partial void BotStarted(ILogger logger, string username);
}
UUUnknown User11/22/2023
10 Messages Not Public
Sign In & Join Server To View
SStilauGamer11/22/2023
ahhh, went training so didn't see the last messsages. Basically waht it does is that the source generator detects this [LoggerMessage(.........)] and then creates the code inside the method automatically. Right?
UUUnknown User11/22/2023
Message Not Public
Sign In & Join Server To View
SStilauGamer11/23/2023
So I should make [LoggerMessage] for each logging I do?
UUUnknown User11/23/2023
2 Messages Not Public
Sign In & Join Server To View

Looking for more? Join the community!

C
C#

Discord.Net + MagicOnion, heheh

Join Server
Want results from more Discord servers?
Add your server
Recommended Posts
A question for my c# winforms projecthello guys, i have a question about my c# winforms project. So : I have 2 Projects the first ProjecYO I NEED HELP writing a code need advice not for u to write it for mewrite me a c# program that get 3 latters and tell if they are by the order like abc if they are backBlazor ServicesI dont know too much blazor, but I have a .cs file in a /Settings folder, in which I would like to aHow to optimize this?I have following: ```cs using System; namespace SquareCalculus { internal class FigureTriangle In VSCode, SDK not Recognized on ChromeOSHi. I just installed the .NET SDK and the Runtime by following the instructions for Ubuntu on the MiNito.AsyncEx vs DotNext.ThreadingWe're currently searching for a nice AsyncAutoResetEvent implementation. We found two suitable impleSequential BlinkersHello everyone! I bought these sequential blinkers that run off an stm32 blue pill board. the only pTrying to use Microsoft.Kiota namespace but not found when importingI am trying to use this method from the Microsoft.Kiota.Abstractions.Extensions namespace: ToFirstChWinUI3 Scheduler CalendarViewhello im trying to make a winui3 calendarview interactive calendar where I can predefine dates in myThe call is ambiguous between the following methods or properties: 'Thread.Thread(ThreadStart)' andi have to upload by filesHelp a noobie out with a simple hangmanHi! New to coding and I need some help to solve this problem. Shall I save the words to a list? AnyC# Image Resizing on Visual Studio CodeI've tried both ``newPic.SizeMode = PictureBoxSizeMode.StretchImage;`` and ``newPic.SizeMode = PictuI'm stuck,visual studio 22, I need help making my invaders/enemies move left to right then downIā€™m trying to get my invaders/enemies to move left to right then down like in the game space invaderāœ… Where should I store all the sensitive file on .NET project?Hello everyone, May I know where should I store all the credential files that needs to be used by .Unity CodeI have been trying to get my C# code to work in unity for about a week and I am officially lost. I'vHelp! Reporting service in dotnet Core?please don't mind my english, it is not that good. i have created 2 projects one is server -dotnetCatAPI Json deserialization issue.I'm having trouble getting my code to deserialize my json correctly. When I run my Program.cs I get āœ… Any idea why I cant use sendkey?Authorization in microservices archHello everyone, I'm quite new to the NET microservices arhitecture and right now I'm implementing a.āœ… I can't get my runButton button to work on a windows form app```cs if (e.KeyCode == Keys.Enter || (e.Modifiers == Keys.None && sender == runButton)) ``` I can s