How can I make a discord timeout command with discord.net C# - c#

Im trying to make a Discord C# Command That uses Discords new Timeout function using discord.NET
I tried using HTTP Requests instead cause i couldnt find a discord.NET function but It returns an unauthorized error
public static async Task PatchData(string url, string data, string token)
{
// Create a new HttpClient instance
using var httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Authorization",token);
httpClient.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
var content = new StringContent(data, Encoding.UTF8, "application/json");
var response = await httpClient.PatchAsync(url, content);
if (response.IsSuccessStatusCode)
{
Console.WriteLine("Data patched successfully!");
}
else
{
Console.WriteLine(response.StatusCode);
}
}
and for the execution
await Patch.PatchData($"https://discord.com/api/v9/guilds/{Context.Guild.Id}/members/{user.Id}",
"{\"communication_disabled_until\": "
+ current_time + time_in_minutes + "}",botToken);

Related

C# - How to I get the HTTP Status Code from a http request

I have the below code, working as expected (given correct URL etc) as a POST request. Seems I have a problem reading the Status Code (I receive a successful 201, and based on that number I need to continue processing). Any idea how to get the status code?
static async Task CreateConsentAsync(Uri HTTPaddress, ConsentHeaders cconsentHeaders, ConsentBody cconsent)
{
HttpClient client = new HttpClient();
try
{
client.BaseAddress = HTTPaddress;
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("*/*"));
client.DefaultRequestHeaders.Add("Connection", "keep-alive");
client.DefaultRequestHeaders.Add("Cache-Control", "no-cache");
client.DefaultRequestHeaders.Add("otherHeader", myValue);
//etc. more headers added, as needed...
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, client.BaseAddress);
request.Content = new StringContent(JsonConvert.SerializeObject(cconsent, Formatting.Indented), System.Text.Encoding.UTF8, "application/json");
Console.WriteLine("\r\n" + "POST Request:\r\n" + client.DefaultRequestHeaders + "\r\nBody:\r\n" + JsonConvert.SerializeObject(cconsent, Formatting.Indented) + "\r\n");
await client.SendAsync(request).ContinueWith
(
responseTask =>
{
Console.WriteLine("Response: {0}", responseTask.Result + "\r\nBody:\r\n" + responseTask.Result.Content.ReadAsStringAsync().Result);
}
);
Console.ReadLine();
}
catch (Exception e)
{
Console.WriteLine("Error in " + e.TargetSite + "\r\n" + e.Message);
Console.ReadLine();
}
}
There is a Status code in your Result.
responseTask.Result.StatusCode
Or even better
var response = await client.SendAsync(request);
var statusCode = response.StatusCode;
It helps to avoid using ContinueWith if you're already inside an async function because you can use the (much cleaner) await keyword.
If you await the SendAsync call you'll get a HttpResponseMessage object you can get the status code from:
Also, wrap your IDisposable objects in using() blocks (except HttpClient - which should be a static singleton or better yet, use IHttpClientFactory).
Don't use HttpClient.DefaultRequestHeaders for request-specific headers, use HttpRequestMessage.Headers instead.
The Connection: Keep-alive header will be sent by HttpClientHandler automatically for you.
Are you sure you need to send Cache-control: no-cache in the request? If you're using HTTPS then it's almost guaranteed that there won't be any proxy-caches causing any issues - and HttpClient does not use the Windows Internet Cache either.
Don't use Encoding.UTF8 because it adds a leading byte-order-mark. Use a private UTF8Encoding instance instead.
Always use .ConfigureAwait(false) with every await on code that does not run in a thread-sensitive context (such as WinForms and WPF).
private static readonly HttpClient _httpClient = new HttpClient();
private static readonly UTF8Encoding _utf8 = new UTF8Encoding( encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true );
static async Task CreateConsentAsync( Uri uri, ConsentHeaders cconsentHeaders, ConsentBody cconsent )
{
using( HttpRequestMessage req = new HttpRequestMessage( HttpMethod.Post, uri ) )
{
req.Headers.Accept.Add( new MediaTypeWithQualityHeaderValue("*/*") );
req.Headers.Add("Cache-Control", "no-cache");
req.Headers.Add("otherHeader", myValue);
//etc. more headers added, as needed...
String jsonObject = JsonConvert.SerializeObject( cconsent, Formatting.Indented );
request.Content = new StringContent( jsonObject, _utf8, "application/json");
using( HttpResponseMessage response = await _httpClient.SendAsync( request ).ConfigureAwait(false) )
{
Int32 responseHttpStatusCode = (Int32)response.StatusCode;
Console.WriteLine( "Got response: HTTP status: {0} ({1})", response.StatusCode, responseHttpStatusCode );
}
}
}
You could simply check the StatusCode property of the response:
https://learn.microsoft.com/en-us/previous-versions/visualstudio/hh159080(v=vs.118)?redirectedfrom=MSDN
static async void dotest(string url)
{
using (HttpClient client = new HttpClient())
{
HttpResponseMessage response = await client.GetAsync(url);
if (response.IsSuccessStatusCode)
{
Console.WriteLine(response.StatusCode.ToString());
}
else
{
// problems handling here
Console.WriteLine(
"Error occurred, the status code is: {0}",
response.StatusCode
);
}
}
}
#AthanasiosKataras is correct for returning the status code itself but if you would also like to return the status code value (ie 200, 404). You can do the following:
var response = await client.SendAsync(request);
int statusCode = (int)response.StatusCode
The above will give you the int 200.
EDIT:
Is there no reason why you cannot do the following?
using (HttpResponseMessage response = await client.SendAsync(request))
{
// code
int code = (int)response.StatusCode;
}

How do I delete a video in my Vimeo account?

How do I delete a video in my Vimeo account using the Vimeo API using C# in .Net Core?
The following works if you have a Vimeo account (at least it works at the Plus level and above) and have created an app, given that app permission to delete, gotten an access token for that app, and have a video number for the video you want to delete.
Within a class put the following code:
HttpClient httpClient = new HttpClient();
public async Task deleteVideo(string videoNumber, string accessToken)
{
try
{
string vimeoApiUrl = "https://api.vimeo.com/videos/" + videoNumber; // Vimeo URL
var body = "{}";
HttpContent content = new StringContent(body);
using (var requestMessage = new HttpRequestMessage(HttpMethod.Delete, vimeoApiUrl))
{
requestMessage.Headers.Authorization =
new AuthenticationHeaderValue("Bearer", accessToken);
requestMessage.Headers.Add("Accept", "application/vnd.vimeo.*+json;version=3.4");
requestMessage.Headers.Add("ContentType", "application/x-www-form-urlencoded");
requestMessage.Content = content;
var response = await httpClient.SendAsync(requestMessage).ConfigureAwait(false);
response.EnsureSuccessStatusCode();
}
}
catch (Exception err)
{
var errMessage = err.Message;
Console.WriteLine("In deleteVideo() error: " + err.Message);
}
}
To call it from within that class:
await deleteVideo(videoNumber, accessToken).ConfigureAwait(false);

Unable to send string as HTTPContent

I have created an API, which shall have the capability to connect to en external API via POST and with a request body in form of a string.
I am able to connect directly to the API from Postman without trouble.. But it does not work via my own API.
Any ideas?
This is the Pastebin.
private string EncodeExternalApiLink = "https://blabla.dk";
private string EncodeExternalApiLinkPostFilter = "searchstring/blabla/api/search";
[HttpPost("getdata/filtered")]
public async Task<IActionResult> GetDataFromExternalFiltered([FromBody] string filter)
{
var filterString = new StringContent(filter);
EncodeExternalToken token = GetExternalToken().Result;
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(EncodeExternalApiLink);
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("text/plain"));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token.access_token);
using (var response = await client.PostAsync(EncodeExternalApiLinkPostFilter, filterString))
{
return Json(response);
if (response.IsSuccessStatusCode)
{
string content = await response.Content.ReadAsStringAsync();
return Content(content, "application/json");
}
else
{
return NotFound();
}
}
}
}
Salutations. You might need to add a "/" to the end of your base address EncodeExternalApiLink or to the beginning of EncodeExternalApiLinkPostFilter.

Error on ConfigureAwait(false)

I am trying to retrieve some data from an API, the following is my piece of code that makes the request after authenticating and assigning the completed URL.
public async Task<T> GetAPIData<T>(string url)
{
using (var client = HttpClientSetup())
{
var response = await client.GetAsync(url).ConfigureAwait(false);
var JsonResponse = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
return JsonConvert.DeserializeObject<T>(JsonResponse);
}
}
private HttpClient HttpClientSetup()
{
var client = new HttpClient { BaseAddress = new Uri(apiBaseUrl) };
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Authorization = authenticationHeader;
return client;
}
I am getting an error on the line with ConfigureAwait(false);
as
"HTTPResponseMessage does not contain a definition for ConfigureAwait"
. Could anyone help me as to what might be going wrong?

500 Server Error when calling REST API over HTTPS

I'm using this code to POST XML to a REST webservice, but am just getting a vague '500 Server Error'. If I paste the same XML into Fiddler it works perfectly, so what am I doing wrong?
using (var client = new HttpClient())
{
var httpContent = new StringContent(doc.ToString(), Encoding.UTF8, "text/xml");
var response = client.PostAsync(new Uri("httpsapiurl"),httpContent).Result;
if (response.IsSuccessStatusCode)
{
// EDITED: this isn't hit as IsSuccessStatusCode is always false
//Stream stream = await response.Content.ReadAsStreamAsync();
}
}
Could it be that you need to set the Content type on the request?
try
{
var httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("text/xml"));
HttpRequestMessage req = new HttpRequestMessage(HttpMethod.Post, URL);
req.Content = new StringContent(doc.ToString(), Encoding.UTF8, "text/xml");
await httpClient.SendAsync(req).ContinueWith(async respTask =>
{
Debug.WriteLine(req.Content.ReadAsStringAsync());
};
}
catch (Exception ex)
{
}
Especially this line is important. I had similar problem with an API that refused to spit anything back when not setting the Content-Type header correct.
req.Content = new StringContent(doc.ToString(), Encoding.UTF8, "text/xml");
Don't know if it can help.

Categories

Resources