C
C#โ€ข2y 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 TCCOPโ€ข2y 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โ€ข2y ago
Message Not Public
Sign In & Join Server To View
ero
eroโ€ข2y ago
if you know it downloads a wav file, why are you saving it as an mp3 lol
Thinker
Thinkerโ€ข2y 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โ€ข2y ago
using on the first 2
Thinker
Thinkerโ€ข2y ago
afaik you shouldn't be using an HttpClient
ero
eroโ€ข2y ago
you should that's why it implements idisposable so you can dispose it
Thinker
Thinkerโ€ข2y ago
anyway, that's how you should do it
ero
eroโ€ข2y 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โ€ข2y 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โ€ข2y ago
Message Not Public
Sign In & Join Server To View
Chris TCC
Chris TCCOPโ€ข2y 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โ€ข2y ago
Message Not Public
Sign In & Join Server To View
Chris TCC
Chris TCCOPโ€ข2y ago
huh? just declaring it like this works? I thought you had to call a method or something
Pobiega
Pobiegaโ€ข2y ago
there are method calls in that snippet
Thinker
Thinkerโ€ข2y ago
Well you still call a method
FusedQyou
FusedQyouโ€ข2y 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โ€ข2y ago
no, it has to do with connection pool exhaustion its not performance related
ero
eroโ€ข2y ago
the usage guideline they sent says it's just a get?
Unknown User
Unknown Userโ€ข2y ago
Message Not Public
Sign In & Join Server To View
Chris TCC
Chris TCCOPโ€ข2y 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โ€ข2y ago
Message Not Public
Sign In & Join Server To View
ero
eroโ€ข2y ago
Unknown User
Unknown Userโ€ข2y ago
Message Not Public
Sign In & Join Server To View
Chris TCC
Chris TCCOPโ€ข2y 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โ€ข2y ago
well start out small, with a console app that just makes a request and shows the response
Chris TCC
Chris TCCOPโ€ข2y ago
the link generates a wav file
Pobiega
Pobiegaโ€ข2y ago
then go from there
Chris TCC
Chris TCCOPโ€ข2y 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โ€ข2y ago
start out small dont start with going for the end goal learn the components first
Chris TCC
Chris TCCOPโ€ข2y ago
uh huh? so I make a standalone C# script first? or how does that work
Unknown User
Unknown Userโ€ข2y ago
Message Not Public
Sign In & Join Server To View
Pobiega
Pobiegaโ€ข2y ago
sure, a standalone console app.
Chris TCC
Chris TCCOPโ€ข2y ago
I've only ever used C# as a scripting language so... for unity and now for an app called StreamerBot
Pobiega
Pobiegaโ€ข2y ago
perhaps a good time to learn how to use it properly then?
Thinker
Thinkerโ€ข2y ago
Also for one, you cannot make a "standalone C# script"
Chris TCC
Chris TCCOPโ€ข2y 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โ€ข2y ago
I mean, its not hard to make a blank console app its... 3-4 button clicks in VS
Chris TCC
Chris TCCOPโ€ข2y ago
I use notepad
Pobiega
Pobiegaโ€ข2y ago
stop using notepad
Thinker
Thinkerโ€ข2y ago
or like two console commands how tf do you get anything done...?
Chris TCC
Chris TCCOPโ€ข2y ago
it works fine darkmode, autocomplete, that is sufficient for me
Thinker
Thinkerโ€ข2y ago
you'e been missing out if you've been using that for years
Chris TCC
Chris TCCOPโ€ข2y 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โ€ข2y ago
How fun is it to fix errors in Notepad?
Chris TCC
Chris TCCOPโ€ข2y 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โ€ข2y ago
ah, write everything correctly the first time catsip
Chris TCC
Chris TCCOPโ€ข2y ago
and that has a built-in compiler hell naw I make worse code than anyone I know
Thinker
Thinkerโ€ข2y 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 TCCOPโ€ข2y 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 TCCOPโ€ข2y ago
Chris TCC
Chris TCCOPโ€ข2y 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โ€ข2y 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โ€ข2y ago
591 lines left ๐Ÿ‘
Thinker
Thinkerโ€ข2y ago
Have you checked $helloworld?
Chris TCC
Chris TCCOPโ€ข2y ago
uh
Chris TCC
Chris TCCOPโ€ข2y ago
I don't think I have the time for this...
Thinker
Thinkerโ€ข2y 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โ€ข2y ago
certainly feels like they want spoonfeeding
Chris TCC
Chris TCCOPโ€ข2y 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โ€ข2y ago
then go right ahead, you've been given all the information you need already
Chris TCC
Chris TCCOPโ€ข2y ago
this?
Pobiega
Pobiegaโ€ข2y ago
you need to make a HttpClient instance and use the methods on that thats the basics
Chris TCC
Chris TCCOPโ€ข2y 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โ€ข2y ago
(and also maybe look into async and await a bit)
Chris TCC
Chris TCCOPโ€ข2y ago
I'll give it a shot and get back with my attempt
ero
eroโ€ข2y ago
i mean we also have to consider what version of .net this streamerbot thing supports right
Chris TCC
Chris TCCOPโ€ข2y ago
I have absolutely no idea
Pobiega
Pobiegaโ€ข2y ago
its gonna be .net 4.7 or later, so httpclient will still be the way to go
Thinker
Thinkerโ€ข2y ago
What are you even running your code through? You said it was some "Streamerbot" program?
Chris TCC
Chris TCCOPโ€ข2y ago
yup
Thinker
Thinkerโ€ข2y ago
Do you have a link to this program/service?
Chris TCC
Chris TCCOPโ€ข2y 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 TCCOPโ€ข2y 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 TCCOPโ€ข2y ago
sorry I linked the docs page
ero
eroโ€ข2y ago
ero
eroโ€ข2y ago
??? .Parse in one example, Convert in the other
Thinker
Thinkerโ€ข2y ago
that page reads like it itself doesn't know what it's talking about
Chris TCC
Chris TCCOPโ€ข2y 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โ€ข2y ago
no clue what it does, but it seems like an ambitious project by a single person?
Thinker
Thinkerโ€ข2y ago
What's SB?
ero
eroโ€ข2y ago
so it's gonna be rough
Thinker
Thinkerโ€ข2y ago
Ah just StreamerBot
ero
eroโ€ข2y ago
streamerbot lol
Thinker
Thinkerโ€ข2y ago
yea
Chris TCC
Chris TCCOPโ€ข2y ago
yep I can understand that the C# implementation is very wonky but it's the most powerful thing that's available
Thinker
Thinkerโ€ข2y ago
The project unfortunately doesn't seem to be open-source
Chris TCC
Chris TCCOPโ€ข2y 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โ€ข2y ago
oof
Chris TCC
Chris TCCOPโ€ข2y 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โ€ข2y ago
Also since I assume this is for Twitch or something, you can make Twitch bots in C# without this thing
Chris TCC
Chris TCCOPโ€ข2y ago
I guess... but then you'd have to re-write it for youtube
Thinker
Thinkerโ€ข2y ago
yeah ig :/
Chris TCC
Chris TCCOPโ€ข2y 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 TCCOPโ€ข2y ago
this is what he told me about the API thing from streamerbot
Pobiega
Pobiegaโ€ข2y ago
Execute is a sync method. ouch
Thinker
Thinkerโ€ข2y ago
oof
Pobiega
Pobiegaโ€ข2y ago
big oof
Thinker
Thinkerโ€ข2y 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 TCCOPโ€ข2y 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โ€ข2y ago
yeah :/ I feel your pain
Chris TCC
Chris TCCOPโ€ข2y ago
Chris TCC
Chris TCCOPโ€ข2y 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โ€ข2y ago
Message Not Public
Sign In & Join Server To View
ero
eroโ€ข2y ago
sucks that this is closed source that alone would make me not even consider using it
Chris TCC
Chris TCCOPโ€ข2y 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 TCCOPโ€ข2y ago
but most of em do their stuff like this
Chris TCC
Chris TCCOPโ€ข2y 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โ€ข2y 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โ€ข2y ago
i don't think that's possible unfortunately
Pobiega
Pobiegaโ€ข2y ago
yep, as far as I can tell streamerbots API is entirely synchronous
Unknown User
Unknown Userโ€ข2y ago
Message Not Public
Sign In & Join Server To View
Chris TCC
Chris TCCOPโ€ข2y 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โ€ข2y ago
Message Not Public
Sign In & Join Server To View
ero
eroโ€ข2y ago
they were asking whether GetAudioFile().GetAwaiter().GetResult() was "merging three into a single step"
Chris TCC
Chris TCCOPโ€ข2y ago
,yup
Unknown User
Unknown Userโ€ข2y ago
Message Not Public
Sign In & Join Server To View
Accord
Accordโ€ข2y 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