You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用C#将Roblox用户的用户名与ID发送至Discord Webhook?

Adding Discord Webhook Integration to Your Roblox User Lookup Code

Got it, let's add that Discord Webhook functionality to your existing code. I'll walk you through creating a reusable method to send the username and ID to your webhook, then plug it into your existing key-down handler.

First, make sure you have the Newtonsoft.Json NuGet package installed (you're already using it for Roblox API deserialization). For modern .NET versions, HttpClient is included in the base framework; if you're on older .NET Framework, you may need to reference the System.Net.Http package.

Step 1: Create a Reusable Webhook Sender Method

Add this method to your class (outside the materialSingleLineTextField1_KeyDown handler):

private async Task SendToDiscordWebhook(string username, string userId)
{
    // Replace with your actual Discord Webhook URL
    string webhookUrl = "https://discordapp.com/api/webhooks/450790622446485525/HW8nYfZ39J0VPKDcxEuLoYpwVbBt8qxF4uM1SMJGp8WXIlZ33jlqzSvMThM7rSoxJUJU";

    // Build a clean Discord message payload
    var payload = new
    {
        content = $"New Roblox User Lookup:\n**Username**: {username}\n**User ID**: {userId}"
    };

    // Convert payload to JSON format Discord expects
    string jsonPayload = JsonConvert.SerializeObject(payload);

    using (HttpClient client = new HttpClient())
    {
        try
        {
            StringContent requestContent = new StringContent(jsonPayload, Encoding.UTF8, "application/json");
            HttpResponseMessage response = await client.PostAsync(webhookUrl, requestContent);
            
            // Optional: Verify the request succeeded
            response.EnsureSuccessStatusCode();
            Console.WriteLine("Successfully sent user data to Discord.");
        }
        catch (HttpRequestException ex)
        {
            // Handle errors (log them or show a user-friendly message)
            Console.WriteLine($"Failed to send to Discord: {ex.Message}");
            // You could also update a label in your UI to notify the user:
            // materialLabel5.Text = $"Discord Error: {ex.Message}";
        }
    }
}

Step 2: Update Your Existing Key-Down Handler

Modify your event handler to call the new webhook method after retrieving the user ID. We'll mark the method as async to support awaited HTTP requests (safe for UI event handlers):

// Add 'async' to the method signature
private async void materialSingleLineTextField1_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.Enter)
    {
        userName = materialSingleLineTextField1.Text;
        rapcount(userName); // Assuming this is your existing helper method
        
        materialLabel2.Text = "Username: " + materialSingleLineTextField1.Text;
        
        var client = new WebClient();
        var text = client.DownloadString("https://api.roblox.com/users/get-by-username?username=" + materialSingleLineTextField1.Text);
        Post post = JsonConvert.DeserializeObject<Post>(text);
        Id = post.Id;
        
        materialLabel3.Text = "ID: " + post.Id;
        materialLabel4.Text = "Online: " + post.IsOnline;
        
        // Fetch and display the avatar
        var request = WebRequest.Create($"https://www.roblox.com/headshot-thumbnail/image?userId={Id}&width=420&height=420&format=png");
        using (var response = request.GetResponse())
        using (var stream = response.GetResponseStream())
        {
            pictureBox1.Image = Bitmap.FromStream(stream);
        }
        
        // Send username and ID to Discord Webhook
        await SendToDiscordWebhook(userName, Id.ToString());
        
        materialSingleLineTextField1.Text = "";
    }
}

Bonus: Enhance the Discord Message (Optional)

If you want a more polished message with embeds (including the user's avatar), update the payload in SendToDiscordWebhook:

var payload = new
{
    embeds = new[]
    {
        new
        {
            title = "Roblox User Lookup",
            color = 0x00ff00, // Green color (hex code)
            fields = new[]
            {
                new { name = "Username", value = username, inline = true },
                new { name = "User ID", value = userId, inline = true },
                new { name = "Online Status", value = post.IsOnline ? "✅ Online" : "❌ Offline", inline = true }
            },
            thumbnail = new { url = $"https://www.roblox.com/headshot-thumbnail/image?userId={userId}&width=420&height=420&format=png" }
        }
    }
};

Key Notes:

  • Async/Await: Using async/await prevents blocking your UI while sending the webhook request.
  • Error Handling: The method includes basic error catching to avoid crashing your app if the Discord API is unreachable.
  • Legacy WebClient: You could refactor your Roblox API call to use HttpClient instead of WebClient for consistency (it's the modern recommended approach).

内容的提问来源于stack exchange,提问作者Aatroxon

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 07:44:56