Skip to content

Commit 59e0d8c

Browse files
fix: tabs to spaces
1 parent 88911ee commit 59e0d8c

File tree

11 files changed

+714
-714
lines changed

11 files changed

+714
-714
lines changed

streamerbot/1.get-started/5.examples/http-post.md

Lines changed: 128 additions & 128 deletions
Original file line numberDiff line numberDiff line change
@@ -35,157 +35,157 @@ Read more about the `Execute C# Code` sub-action
3535

3636
```cs [Basic Setup]
3737
using System;
38-
using System.Text;
38+
using System.Text;
3939
using System.Threading.Tasks;
4040
using System.Net.Http;
4141
using System.Net.Http.Headers;
4242
using Newtonsoft.Json;
4343
using Newtonsoft.Json.Linq;
44-
44+
4545
public class CPHInline {
46-
// You can set the timeout to any length you need
47-
private static readonly HttpClient _httpClient = new HttpClient{Timeout = TimeSpan.FromSeconds(30)};
48-
49-
public void Init() {
50-
// Ensure we are working with a clean slate
51-
_httpClient.DefaultRequestHeaders.Clear();
52-
}
53-
54-
public void Dispose() {
55-
// Free up allocations
56-
_httpClient.Dispose();
57-
}
58-
59-
public bool Execute() {
60-
// ...
61-
return true;
62-
}
63-
}
64-
```
65-
66-
::tip{color=amber}
67-
While people using the HTTPClient in a `using` statement or creating a new one within the executed function may be a common occurence, it is heavily discouraged to do so. [Read More](https://extensions.streamer.bot/t/httpclient-and-you/1369)
68-
::
46+
// You can set the timeout to any length you need
47+
private static readonly HttpClient _httpClient = new HttpClient{Timeout = TimeSpan.FromSeconds(30)};
48+
49+
public void Init() {
50+
// Ensure we are working with a clean slate
51+
_httpClient.DefaultRequestHeaders.Clear();
52+
}
53+
54+
public void Dispose() {
55+
// Free up allocations
56+
_httpClient.Dispose();
57+
}
58+
59+
public bool Execute() {
60+
// ...
61+
return true;
62+
}
63+
}
64+
```
65+
66+
::tip{color=amber}
67+
While people using the HTTPClient in a `using` statement or creating a new one within the executed function may be a common occurence, it is heavily discouraged to do so. [Read More](https://extensions.streamer.bot/t/httpclient-and-you/1369)
68+
::
6969

7070
2. Setup the sending of your payload
7171

7272
- We are going to send a `%userName%` and `%userId%` pair (from common triggers) as `PUT` request to our fictional logging website.
7373

7474
```cs [Send PUT payload in Execute method]
75-
public bool Execute() {
76-
// Get the arguments - or abort if it does not exist
77-
if(!CPH.TryGetArg("userName", out string userName)) return false;
78-
if(!CPH.TryGetArg("userId", out string userId)) return false;
79-
80-
// Build a wrapper object as payload
81-
var data = new {
82-
id = userId,
83-
name = userName
84-
};
85-
86-
// Serialize JSON
87-
string json = JsonConvert.SerializeObject(data);
88-
89-
// Create web request payload
90-
var payload = new StringContent(json, Encoding.UTF8, "application/json");
91-
92-
// Finally, send request
93-
HttpResponseMessage response = _httpClient.PutAsync("https://my-logging-server.com", payload).GetAwaiter().GetResult();
94-
95-
// Do with the response what you need to.
96-
// ...
97-
98-
return true;
99-
}
100-
```
101-
102-
- To use different request types, simply use the methods `GetAsync()`, `PutAsync()`, `PostAsync()` or `DeleteAsync()`.
75+
public bool Execute() {
76+
// Get the arguments - or abort if it does not exist
77+
if(!CPH.TryGetArg("userName", out string userName)) return false;
78+
if(!CPH.TryGetArg("userId", out string userId)) return false;
79+
80+
// Build a wrapper object as payload
81+
var data = new {
82+
id = userId,
83+
name = userName
84+
};
85+
86+
// Serialize JSON
87+
string json = JsonConvert.SerializeObject(data);
88+
89+
// Create web request payload
90+
var payload = new StringContent(json, Encoding.UTF8, "application/json");
91+
92+
// Finally, send request
93+
HttpResponseMessage response = _httpClient.PutAsync("https://my-logging-server.com", payload).GetAwaiter().GetResult();
94+
95+
// Do with the response what you need to.
96+
// ...
97+
98+
return true;
99+
}
100+
```
101+
102+
- To use different request types, simply use the methods `GetAsync()`, `PutAsync()`, `PostAsync()` or `DeleteAsync()`.
103103

104104
3. The PATCH request
105105

106106
- Specifically the built-in handling for the `PATCH` request type may not be available in the .net versions used by StreamerBot. In this case, you need a workaround.
107-
108-
```cs [PATCH workaround]
109-
// ...
110-
111-
// Finally, send the request
112-
var request = new HttpRequestMessage(new HttpMethod("PATCH"), "https://my-logging-server.com"){
113-
Content = payload
114-
};
115-
HttpResponseMessage response = _httpClient.SendAsync(request).GetAwaiter().GetResult();
116-
117-
// ...
118-
```
119-
107+
108+
```cs [PATCH workaround]
109+
// ...
110+
111+
// Finally, send the request
112+
var request = new HttpRequestMessage(new HttpMethod("PATCH"), "https://my-logging-server.com"){
113+
Content = payload
114+
};
115+
HttpResponseMessage response = _httpClient.SendAsync(request).GetAwaiter().GetResult();
116+
117+
// ...
118+
```
119+
120120
4. Additional Headers
121121

122122
- If you need to additionally include specific headers - like submitting an authorization token for the Twitch API or Discord API - make sure to clear and set the headers on each call you make.
123-
1. You can also send individual headers with each request itself, but that requires you to always use the `SendAsync` method and building your own `HttpRequestMessage`.
124-
125-
- If your code only does a static request whose headers never change, resetting the headers is **not strictly necessary**. But it's good practice to not forget later when you need it.
126-
127-
```cs [Header management]
128-
public bool Execute() {
129-
// Making a call to the Twitch API to get all currently live streams
130-
string token = CPH.TwitchOAuthToken;
131-
string clientId = CPH.TwitchClientId;
132-
133-
// Clear our old headers
134-
_httpClient.DefaultRequestHeaders.Clear();
135-
136-
// Now set your Twitch API authorization
137-
_httpClient.DefaultRequestHeaders.Add("Authorization", "Bearer "+token);
138-
_httpClient.DefaultRequestHeaders.Add("Client-Id", clientId);
139-
140-
// Send your request
141-
HttpResponseMessage response = _httpClient.GetAsync("https://api.twitch.tv/helix/streams").GetAwaiter().GetResult();
142-
143-
// Do with the response what you need to.
144-
// ...
145-
146-
return true;
147-
}
148-
```
149-
123+
1. You can also send individual headers with each request itself, but that requires you to always use the `SendAsync` method and building your own `HttpRequestMessage`.
124+
125+
- If your code only does a static request whose headers never change, resetting the headers is **not strictly necessary**. But it's good practice to not forget later when you need it.
126+
127+
```cs [Header management]
128+
public bool Execute() {
129+
// Making a call to the Twitch API to get all currently live streams
130+
string token = CPH.TwitchOAuthToken;
131+
string clientId = CPH.TwitchClientId;
132+
133+
// Clear our old headers
134+
_httpClient.DefaultRequestHeaders.Clear();
135+
136+
// Now set your Twitch API authorization
137+
_httpClient.DefaultRequestHeaders.Add("Authorization", "Bearer "+token);
138+
_httpClient.DefaultRequestHeaders.Add("Client-Id", clientId);
139+
140+
// Send your request
141+
HttpResponseMessage response = _httpClient.GetAsync("https://api.twitch.tv/helix/streams").GetAwaiter().GetResult();
142+
143+
// Do with the response what you need to.
144+
// ...
145+
146+
return true;
147+
}
148+
```
149+
150150
5. Handling the response
151151

152152
- Since you have to do the entire request handling yourself, that includes handling the response.
153-
1. If you don't need to know what the server responded, you can ignore it like in the examples above.
154-
2. If you need to know if the request succeeded or are expecting data in return, follow the below example.
155-
156-
```cs [Response handling]
157-
public bool Execute() {
158-
// ...all your data preparation
159-
160-
HttpResponseMessage response = _httpClient.GetAsync("https://api.twitch.tv/helix/streams").GetAwaiter().GetResult();
161-
162-
// Check if our request was successful
163-
try {
164-
if(!response.IsSuccessStatusCode) {
165-
// It was not. Abort.
166-
CPH.LogError($"{response.StatusCode} - {response.ReasonPhrase}");
167-
return false;
168-
}
169-
170-
// Get the response data
171-
string content = response.Content.ReadAsStringAsync().GetAwaiter().GetResult();
172-
173-
// Usually, data is JSON. So you would decode it now.
174-
JObject parsed = JObject.Parse(content);
175-
176-
// And then do with the data whatever you need.
177-
// ...
178-
179-
return true;
180-
} catch (Exception e) {
181-
// Something went wrong
182-
CPH.LogError(e.Message);
183-
return false;
184-
}
185-
}
186-
```
153+
1. If you don't need to know what the server responded, you can ignore it like in the examples above.
154+
2. If you need to know if the request succeeded or are expecting data in return, follow the below example.
155+
156+
```cs [Response handling]
157+
public bool Execute() {
158+
// ...all your data preparation
159+
160+
HttpResponseMessage response = _httpClient.GetAsync("https://api.twitch.tv/helix/streams").GetAwaiter().GetResult();
161+
162+
// Check if our request was successful
163+
try {
164+
if(!response.IsSuccessStatusCode) {
165+
// It was not. Abort.
166+
CPH.LogError($"{response.StatusCode} - {response.ReasonPhrase}");
167+
return false;
168+
}
169+
170+
// Get the response data
171+
string content = response.Content.ReadAsStringAsync().GetAwaiter().GetResult();
172+
173+
// Usually, data is JSON. So you would decode it now.
174+
JObject parsed = JObject.Parse(content);
175+
176+
// And then do with the data whatever you need.
177+
// ...
178+
179+
return true;
180+
} catch (Exception e) {
181+
// Something went wrong
182+
CPH.LogError(e.Message);
183+
return false;
184+
}
185+
}
186+
```
187187

188188
## Tips & Tricks
189189

190190
- Wrapping sensitive parts of code, especially when using web requests, into `try` `catch` blocks is good practice and prevents potential unexpected bigger issues you do not anticipate.
191-
1. Of course, proper error handling is always better, but not always necessary.
191+
1. Of course, proper error handling is always better, but not always necessary.

0 commit comments

Comments
 (0)