C# Discord Notification: Message Not Sending on Specific Event

Hey everyone, I’m trying to set up a C# program that sends a message to a Discord server when a certain event happens. I’ve got the event detection working, but the message isn’t showing up in Discord. Here’s what I’ve tried:

var client = new HttpClient();
var message = new Dictionary<string, string> { { "content", "Event triggered!" } };
var content = new FormUrlEncodedContent(message);
var webhook = new Uri("discord_webhook_url_here");
await client.PostAsync(webhook, content);

I know the webhook works because I tested it with Python:

import requests

webhook = 'discord_webhook_url_here'
data = { "content": "Event triggered!" }
requests.post(webhook, data=data)

The Python version sends the message fine. What am I missing in the C# version? I’ve also tried using WebClient with UploadString, but no luck. Any ideas? Thanks!

I encountered a similar issue in my project. The problem likely stems from the content type. Discord’s webhook API expects JSON, not form-encoded data. Here’s a solution that worked for me:

var client = new HttpClient();
var message = new { content = "Event triggered!" };
var jsonContent = JsonSerializer.Serialize(message);
var stringContent = new StringContent(jsonContent, Encoding.UTF8, "application/json");
await client.PostAsync(webhook, stringContent);

Make sure to add the necessary using statements for System.Text.Json and System.Text.Encoding. This approach ensures the correct content type is sent. If you’re still having issues, double-check your webhook URL and network connectivity.

hey tom, i had a similar issue. try using JsonContent instead of FormUrlEncodedContent. something like this:

var jsonContent = JsonContent.Create(new { content = “Event triggered!” });
await client.PostAsync(webhook, jsonContent);

discord’s api expects JSON, so that might fix it. lmk if it works!

I’ve dealt with Discord webhooks in C# before, and there’s a neat library that can simplify this process for you. It’s called Discord.Net, and it handles a lot of the low-level stuff automatically.

Here’s how you could use it:

using Discord.Webhook;

var webhook = new DiscordWebhookClient("your_webhook_url_here");
await webhook.SendMessageAsync("Event triggered!");

This approach is more straightforward and less error-prone than manually constructing HTTP requests. It also handles things like rate limiting and retries for you.

If you prefer not to use an external library, make sure you’re setting the correct Content-Type header to ‘application/json’ in your HTTP request. That’s often the culprit when webhook messages fail to send.