C
C#โ€ข16mo ago
Chris TCC

โ” how to make an API call

I have tried looking up tutorials but they ended up making me more confused. I want to take a string, generate an API call from that, then download the response. The API takes a URL-encoded string, and returns a link to a wav file, which I'd like to download. Is that possible? here's the link to the API I'd like to try using: https://tts.cyzon.us/ https://github.com/calzoneman/aeiou/blob/master/docs/usage-guidelines.md
GitHub
aeiou/usage-guidelines.md at master ยท calzoneman/aeiou
node.js web interface to silly text to speech things - aeiou/usage-guidelines.md at master ยท calzoneman/aeiou
120 Replies
Chris TCC
Chris TCCโ€ข16mo ago
someone sent me this, which is what they personally use to interact with a different API. Could this potentially be adapted for my use? I've tried understanding it but I can't...
public bool Execute()
{
string url = "URL here";

var ttsRequest = (HttpWebRequest)WebRequest.Create(url);
ttsRequest.ContentType = "application/json";
ttsRequest.Method = "POST";

JObject postJson = new JObject(); //"{text:\"This is a test message\", voice:\"en_us_001\"}";
postJson["text"] = args["rawInput"].ToString(); //This is another test message.";
postJson["voice"] = "en_male_m03_lobby";

using (var client = new StreamWriter(ttsRequest.GetRequestStream()))
{
client.Write(postJson.ToString());
}

var ttsResponse = (HttpWebResponse)ttsRequest.GetResponse();
using (var streamReader = new StreamReader(ttsResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
JObject ttsData = JObject.Parse(result);

Byte[] audioBytes = Convert.FromBase64String(ttsData.Value<string>("data"));
File.WriteAllBytes("./tts.mp3", audioBytes);
CPH.Wait(1000);
CPH.PlaySound("./tts.mp3", 1.0f, true);
}
return true;
}
public bool Execute()
{
string url = "URL here";

var ttsRequest = (HttpWebRequest)WebRequest.Create(url);
ttsRequest.ContentType = "application/json";
ttsRequest.Method = "POST";

JObject postJson = new JObject(); //"{text:\"This is a test message\", voice:\"en_us_001\"}";
postJson["text"] = args["rawInput"].ToString(); //This is another test message.";
postJson["voice"] = "en_male_m03_lobby";

using (var client = new StreamWriter(ttsRequest.GetRequestStream()))
{
client.Write(postJson.ToString());
}

var ttsResponse = (HttpWebResponse)ttsRequest.GetResponse();
using (var streamReader = new StreamReader(ttsResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
JObject ttsData = JObject.Parse(result);

Byte[] audioBytes = Convert.FromBase64String(ttsData.Value<string>("data"));
File.WriteAllBytes("./tts.mp3", audioBytes);
CPH.Wait(1000);
CPH.PlaySound("./tts.mp3", 1.0f, true);
}
return true;
}
Unknown User
Unknown Userโ€ข16mo ago
Message Not Public
Sign In & Join Server To View
ero
eroโ€ข16mo ago
if you know it downloads a wav file, why are you saving it as an mp3 lol
Thinker
Thinkerโ€ข16mo ago
HttpClient client = new();
var response = await client.GetAsync(url);
var bytes = await response.Content.ReadAsBytesAsync();
// ...
HttpClient client = new();
var response = await client.GetAsync(url);
var bytes = await response.Content.ReadAsBytesAsync();
// ...
ero
eroโ€ข16mo ago
using on the first 2
Thinker
Thinkerโ€ข16mo ago
afaik you shouldn't be using an HttpClient
ero
eroโ€ข16mo ago
you should that's why it implements idisposable so you can dispose it
Thinker
Thinkerโ€ข16mo ago
anyway, that's how you should do it
ero
eroโ€ข16mo ago
the idea is to not create a new client every time if you do a lot of requests so you create one static long running client for the whole app
Pobiega
Pobiegaโ€ข16mo ago
Very bad idea to phrase it like this. MS docs repeatedly show that you should not be using HttpClient client = new(), as that pattern is never the correct one for httpclients. You should have a static one, or use the factory.
Unknown User
Unknown Userโ€ข16mo ago
Message Not Public
Sign In & Join Server To View
Chris TCC
Chris TCCโ€ข16mo ago
that's what someone sent me as their own version not made for me but for me to use as a base
Unknown User
Unknown Userโ€ข16mo ago
Message Not Public
Sign In & Join Server To View
Chris TCC
Chris TCCโ€ข16mo ago
huh? just declaring it like this works? I thought you had to call a method or something
Pobiega
Pobiegaโ€ข16mo ago
there are method calls in that snippet
Thinker
Thinkerโ€ข16mo ago
Well you still call a method
FusedQyou
FusedQyouโ€ข16mo ago
I think the reason why they advice against is is because it is bad performance wise do constantly make a new HttpClient, and you should reuse the same client. Because it does stuff in the background when you create one But don't quote me on that
Pobiega
Pobiegaโ€ข16mo ago
no, it has to do with connection pool exhaustion its not performance related
ero
eroโ€ข16mo ago
the usage guideline they sent says it's just a get?
Unknown User
Unknown Userโ€ข16mo ago
Message Not Public
Sign In & Join Server To View
Chris TCC
Chris TCCโ€ข16mo ago
I have no idea what your words mean... so... I set up the variables with the info I need then call a method?
Unknown User
Unknown Userโ€ข16mo ago
Message Not Public
Sign In & Join Server To View
ero
eroโ€ข16mo ago
Unknown User
Unknown Userโ€ข16mo ago
Message Not Public
Sign In & Join Server To View
Chris TCC
Chris TCCโ€ข16mo ago
which is why I'm asking for help lol... this is my first time doing anything related to API https://tts.cyzon.us/tts?text=hello+world like this
Pobiega
Pobiegaโ€ข16mo ago
well start out small, with a console app that just makes a request and shows the response
Chris TCC
Chris TCCโ€ข16mo ago
the link generates a wav file
Pobiega
Pobiegaโ€ข16mo ago
then go from there
Chris TCC
Chris TCCโ€ข16mo ago
I'm integrating this into another app - the C# code is just a script so idk how to even open a console
Pobiega
Pobiegaโ€ข16mo ago
start out small dont start with going for the end goal learn the components first
Chris TCC
Chris TCCโ€ข16mo ago
uh huh? so I make a standalone C# script first? or how does that work
Unknown User
Unknown Userโ€ข16mo ago
Message Not Public
Sign In & Join Server To View
Pobiega
Pobiegaโ€ข16mo ago
sure, a standalone console app.
Chris TCC
Chris TCCโ€ข16mo ago
I've only ever used C# as a scripting language so... for unity and now for an app called StreamerBot
Pobiega
Pobiegaโ€ข16mo ago
perhaps a good time to learn how to use it properly then?
Thinker
Thinkerโ€ข16mo ago
Also for one, you cannot make a "standalone C# script"
Chris TCC
Chris TCCโ€ข16mo ago
uh... I wonder if I have the patience to learn it properly at this point tbh I've been using C# for years now in unity
Pobiega
Pobiegaโ€ข16mo ago
I mean, its not hard to make a blank console app its... 3-4 button clicks in VS
Chris TCC
Chris TCCโ€ข16mo ago
I use notepad
Pobiega
Pobiegaโ€ข16mo ago
stop using notepad
Thinker
Thinkerโ€ข16mo ago
or like two console commands how tf do you get anything done...?
Chris TCC
Chris TCCโ€ข16mo ago
it works fine darkmode, autocomplete, that is sufficient for me
Thinker
Thinkerโ€ข16mo ago
you'e been missing out if you've been using that for years
Chris TCC
Chris TCCโ€ข16mo ago
oh nah nah I use notepad for my Streamerbot scripting since the in-app editor stinks it doesn't even properly handle [tab] inputs
Thinker
Thinkerโ€ข16mo ago
How fun is it to fix errors in Notepad?
Chris TCC
Chris TCCโ€ข16mo ago
I don't get any I mean - the errors I get are very minor ones like typos I use notepad to write the code then I copy paste it into the streamerbot editor
Thinker
Thinkerโ€ข16mo ago
ah, write everything correctly the first time catsip
Chris TCC
Chris TCCโ€ข16mo ago
and that has a built-in compiler hell naw I make worse code than anyone I know
Thinker
Thinkerโ€ข16mo ago
well you're only doing yourself a disservice by not using any kind of IDE, but you do you I guess
Chris TCC
Chris TCCโ€ข16mo ago
basically, C# is used as a scripting language with its own methods but if you import other stuff you can do stuff normal C# can like open new windows I got someone else's script which opens an admin window
Chris TCC
Chris TCCโ€ข16mo ago
Chris TCC
Chris TCCโ€ข16mo ago
that's besides the point here - I'm just curious if I could make an API call, and if anyone would be able to help me learn the fundimentals because online tutorials ain't making it clear to me consider me baby at understanding this crap...
Pobiega
Pobiegaโ€ข16mo ago
well, if you make a new blank hello world console app as step 1 and then make THAT make the request... then you should be able to tweak it so your bot or whatever can do it
ero
eroโ€ข16mo ago
591 lines left ๐Ÿ‘
Thinker
Thinkerโ€ข16mo ago
Have you checked $helloworld?
Chris TCC
Chris TCCโ€ข16mo ago
uh
Chris TCC
Chris TCCโ€ข16mo ago
I don't think I have the time for this...
Thinker
Thinkerโ€ข16mo ago
Thrn how do you expect to learn anything...? That's the absolute basics though, but it's kind of unclear what exactly you're looking for
Pobiega
Pobiegaโ€ข16mo ago
certainly feels like they want spoonfeeding
Chris TCC
Chris TCCโ€ข16mo ago
I mean... my way of learning so far was to try and figure out things as I go I was using arrays before I knew what a class was still kinda don't know what it is
Pobiega
Pobiegaโ€ข16mo ago
then go right ahead, you've been given all the information you need already
Chris TCC
Chris TCCโ€ข16mo ago
this?
Pobiega
Pobiegaโ€ข16mo ago
you need to make a HttpClient instance and use the methods on that thats the basics
Chris TCC
Chris TCCโ€ข16mo ago
HttpClient Class (System.Net.Http)
Provides a class for sending HTTP requests and receiving HTTP responses from a resource identified by a URI.
Thinker
Thinkerโ€ข16mo ago
(and also maybe look into async and await a bit)
Chris TCC
Chris TCCโ€ข16mo ago
I'll give it a shot and get back with my attempt
ero
eroโ€ข16mo ago
i mean we also have to consider what version of .net this streamerbot thing supports right
Chris TCC
Chris TCCโ€ข16mo ago
I have absolutely no idea
Pobiega
Pobiegaโ€ข16mo ago
its gonna be .net 4.7 or later, so httpclient will still be the way to go
Thinker
Thinkerโ€ข16mo ago
What are you even running your code through? You said it was some "Streamerbot" program?
Chris TCC
Chris TCCโ€ข16mo ago
yup
Thinker
Thinkerโ€ข16mo ago
Do you have a link to this program/service?
Chris TCC
Chris TCCโ€ข16mo ago
usually the scripts I make are to clean up logic, because logic via the GUI sucks so it's just a simple if/else or switch script of around 40 lines or so then return true this is my first time doing something this complex here
Chris TCC
Chris TCCโ€ข16mo ago
https://streamer.bot this is the main app btw
Streamer.bot
Supercharge your Live Stream | Streamer.bot
Supercharge your live stream with Streamer.bot! The most powerful stream bot with Twitch and YouTube support.
Chris TCC
Chris TCCโ€ข16mo ago
sorry I linked the docs page
ero
eroโ€ข16mo ago
ero
eroโ€ข16mo ago
??? .Parse in one example, Convert in the other
Thinker
Thinkerโ€ข16mo ago
that page reads like it itself doesn't know what it's talking about
Chris TCC
Chris TCCโ€ข16mo ago
I am confused myself at how the variables get converted from SB to C# variables but it's worked so far so...
ero
eroโ€ข16mo ago
no clue what it does, but it seems like an ambitious project by a single person?
Thinker
Thinkerโ€ข16mo ago
What's SB?
ero
eroโ€ข16mo ago
so it's gonna be rough
Thinker
Thinkerโ€ข16mo ago
Ah just StreamerBot
ero
eroโ€ข16mo ago
streamerbot lol
Thinker
Thinkerโ€ข16mo ago
yea
Chris TCC
Chris TCCโ€ข16mo ago
yep I can understand that the C# implementation is very wonky but it's the most powerful thing that's available
Thinker
Thinkerโ€ข16mo ago
The project unfortunately doesn't seem to be open-source
Chris TCC
Chris TCCโ€ข16mo ago
the GUI is super restrictive - if/else blocks can only either break out of the current action, or call another action meaning in code you have if then else, but in the GUI variant you must have 3 different methods that it jumps between so I always prefer code because it's cleaner afaik it's closed-source
Thinker
Thinkerโ€ข16mo ago
oof
Chris TCC
Chris TCCโ€ข16mo ago
man... I'll just pray the guy inside the SB help channel is able to come to my rescue he's the one who made his own TTS via API system, and he's the one who shared the above code with me that's what he uses and it works
Thinker
Thinkerโ€ข16mo ago
Also since I assume this is for Twitch or something, you can make Twitch bots in C# without this thing
Chris TCC
Chris TCCโ€ข16mo ago
I guess... but then you'd have to re-write it for youtube
Thinker
Thinkerโ€ข16mo ago
yeah ig :/
Chris TCC
Chris TCCโ€ข16mo ago
also I'd have no idea how to listen to the api calls and stuff that twitch fires out and ofc they keep changing their API so keeping up with that is a pain, SB does that for me with app updates
Chris TCC
Chris TCCโ€ข16mo ago
this is what he told me about the API thing from streamerbot
Pobiega
Pobiegaโ€ข16mo ago
Execute is a sync method. ouch
Thinker
Thinkerโ€ข16mo ago
oof
Pobiega
Pobiegaโ€ข16mo ago
big oof
Thinker
Thinkerโ€ข16mo ago
ambitious project developed by a single person with mediocre docs, bad practices, and supposedly not very good code sounds about right
Chris TCC
Chris TCCโ€ข16mo ago
sounds about right but it's the most powerful but still user-friendly thing I could find going custom takes a lot of upkeep and knowhow, and is difficult to develop
Thinker
Thinkerโ€ข16mo ago
yeah :/ I feel your pain
Chris TCC
Chris TCCโ€ข16mo ago
Chris TCC
Chris TCCโ€ข16mo ago
this is a part of a script I wrote myself for SB it's... not a very good script but it works
Unknown User
Unknown Userโ€ข16mo ago
Message Not Public
Sign In & Join Server To View
ero
eroโ€ข16mo ago
sucks that this is closed source that alone would make me not even consider using it
Chris TCC
Chris TCCโ€ข16mo ago
this app has a good amount of support it's the most powerful tool streamers have at their disposal (besides going custom of course)
Chris TCC
Chris TCCโ€ข16mo ago
but most of em do their stuff like this
Chris TCC
Chris TCCโ€ข16mo ago
very few actually code in C# so I guess that's why the implementation might be wonky... not enough people use it to warrant making it proper, but just keep it up-to-date and functional enough wellp, someone from the SB discord helped me out and I got something that works still don't know how it works though, I don't understand most of what was written here:
using System;
using System.Threading.Tasks;
using System.IO;
using System.Net.Http;
using System.Web;

public class CPHInline
{
HttpClient client = new HttpClient();

public bool Execute()
{
try
{
var task = GetAudioFile();
task.Wait();

string audioFileName = task.Result;

CPH.PlaySound(audioFileName, 1.0f, true);
} catch (Exception e)
{
CPH.LogDebug($"Something wrong: {e.Message}");
return false;
}

return true;
}

async Task<string> GetAudioFile()
{
var ttsText = args["ttsText"].ToString();
var fileName = args["fileName"].ToString();

var URI = new Uri($"https://tts.cyzon.us/tts?text={HttpUtility.UrlEncode(ttsText)}");

var responseStream = await client.GetStreamAsync(URI);

using (var fs = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None))
{
await responseStream.CopyToAsync(fs);
}

return fileName;
}
}
using System;
using System.Threading.Tasks;
using System.IO;
using System.Net.Http;
using System.Web;

public class CPHInline
{
HttpClient client = new HttpClient();

public bool Execute()
{
try
{
var task = GetAudioFile();
task.Wait();

string audioFileName = task.Result;

CPH.PlaySound(audioFileName, 1.0f, true);
} catch (Exception e)
{
CPH.LogDebug($"Something wrong: {e.Message}");
return false;
}

return true;
}

async Task<string> GetAudioFile()
{
var ttsText = args["ttsText"].ToString();
var fileName = args["fileName"].ToString();

var URI = new Uri($"https://tts.cyzon.us/tts?text={HttpUtility.UrlEncode(ttsText)}");

var responseStream = await client.GetStreamAsync(URI);

using (var fs = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None))
{
await responseStream.CopyToAsync(fs);
}

return fileName;
}
}
Angius
Angiusโ€ข16mo ago
var task = GetAudioFile();
task.Wait();
var task = GetAudioFile();
task.Wait();
should just be
await GetAudioFile();
await GetAudioFile();
and the Execute method should be async Task<bool>
ero
eroโ€ข16mo ago
i don't think that's possible unfortunately
Pobiega
Pobiegaโ€ข16mo ago
yep, as far as I can tell streamerbots API is entirely synchronous
Unknown User
Unknown Userโ€ข16mo ago
Message Not Public
Sign In & Join Server To View
Chris TCC
Chris TCCโ€ข16mo ago
from what I understand that's merging three into a single step, right? and yes it has to be inside a bool
Unknown User
Unknown Userโ€ข16mo ago
Message Not Public
Sign In & Join Server To View
ero
eroโ€ข16mo ago
they were asking whether GetAudioFile().GetAwaiter().GetResult() was "merging three into a single step"
Chris TCC
Chris TCCโ€ข16mo ago
,yup
Unknown User
Unknown Userโ€ข16mo ago
Message Not Public
Sign In & Join Server To View
Accord
Accordโ€ข16mo ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.
Want results from more Discord servers?
Add your server
More Posts
โ” Best approach to share several properties application-wide in a WinUI3 project?Hi, I am looking for the preferred way, following the best practices for a small scale desktop appliโ” Blazor communicate with WebAPI on localhost serverHello, I want to start making a staging environment for my application, I got a WebAPI ready and worโ” Get Pixels cords from Image by their colorHey, I'm writing a game and I need to get the pixels cords by their colors from an Image, I tried usโ” Storing & retrieving face encodings to compareWhat's the best way to store face encodings (an array of size 128 and type float64) in a database anโ” New to C# and am trying to make a Minesweeper console appI am having trouble with my "UpdateBoard" method and I can not seem to figure out what the problem iโ” System.Data.OleDb.OleDbException: 'Could not find installable ISAM.' errorHi anyone can help me? i start the test and i got System.Data.OleDb.OleDbException: 'Could not find โ” Accounting for Daylight Savings Time skips at runtimeMy Discord bot I am developing has a reminder system which utilizes <https://github.com/robbell/nChrโœ… I need to put an invalid choice in my programI need to make the program repeat if they did not input a valid response of yes or noโ” My project runs successfully but doesn't load ( works fine when I run it without debugging )my project was working fine but suddenly whenever I run it it keeps loading without showing anythingOnly assignment, call, increment, decrement, await, and new object expressions can be used as a statim a noob and why cant i make my console make a beep sound? I didnt understand the error msg