向Discord频道发送消息
c#
我想要达到的目标:
我想在外部程序执行 console_app.exe 时在 Discord 频道上发送消息,所以我决定使用纯休息:
我通过 https://discord.com/developers/applications
我有 ClientId 和 ClientSecret,现在我想从代码登录并在特定频道上发送消息
我正在获取令牌而没有响应问题,例如:
{
"access_token": "6qrZcUqja781...HBFG",
"token_type": "Bearer",
"expires_in": 604800,
"scope": "identify connections"
}
但是当我尝试发送消息(函数WriteMessage)时,我Unauthorized出于某种原因
整个代码:
private static readonly RestClient client = new RestClient("https://discord.com");
public string Perform()
{
client.Authenticator = new HttpBasicAuthenticator(_config.ClientId, _config.ClientSecret);
var token = GetToken();
client.Authenticator = null;
return WriteMessage(token);
}
private string GetToken()
{
var signInRequest = new RestRequest("/api/v6/oauth2/token", Method.POST);
signInRequest.AddHeader("content-type", "application/x-www-form-urlencoded");
signInRequest.AddParameter("grant_type", "client_credentials");
signInRequest.AddParameter("scope", "identify connections");
var result = client.Execute<AuthResult>(signInRequest);
return result.Data.access_token;
}
private string WriteMessage(string token)
{
var request = new RestRequest("/api/v8/channels/.../messages", Method.POST);
request.AddHeader("Authorization", $"Bearer {token}");
//request.AddHeader("Authorization", $"{token}");
var msg = new DiscordMessage
{
content = "Test",
nonce = "78714914815023104",
tts = false
};
request.AddJsonBody(msg);
IRestResponse response = client.Execute(request);
var content = response.Content;
Console.WriteLine(response.StatusCode); // Unauthorized
Console.WriteLine(response.Content);
return content;
}
我可能做错了什么?
回答
使用这个在 github 上非常流行的 C# API 可能更容易:https : //github.com/discord-net/Discord.Net
从头开始编写身份验证可能会很痛苦。
值得花几分钟尝试一下这个库,也许它可以正常工作。您需要阅读自述文件,因为还有 4 个您可能感兴趣的附加 nuget 软件包。