Google Speech API using NuGet packages - c#

I was trying to use google speech to text API and i read about the NuGet Google APIs packages that can be helpful in speech recognition. Here is the link complete package my code based on documentation provide on https://developers.google.com/api-client-library/dotnet/get_started
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Google.Apis.CloudSpeechAPI.v1beta1.Data;
using Google.Apis.CloudSpeechAPI.v1beta1;
using Google.Apis.Services;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Cloud Speech Api");
try
{
new Program().Run().Wait();
}
catch(AggregateException ex)
{
foreach (var e in ex.InnerExceptions)
{
Console.WriteLine("Error: "+ e.Message);
}
}
Console.WriteLine("Press any key to continue");
Console.ReadKey();
}
private async Task Run()
{
var service = new CloudSpeechAPIService(new BaseClientService.Initializer
{
ApplicationName ="Speech Recognition",
ApiKey="Api key",
});
Console.WriteLine("Executing a list request...");
var result = await service.Apis.List().ExecuteAsync();
if (result.Items != null)
{
foreach (DirectoryList.ItemsData api in result.Items)
{
Console.WriteLine(api.Id + " - " + api.Title);
}
}
}
}
}
code is showing error in line
var result = await service.Apis.List().ExecuteAsync(); //Error:'APIS ' definition not exist
also i am not sure that code is correct. please help

Related

lavalink not working when making discord bot with DSharpPlus. not throwing any errors

command class, no errors when running
using DSharpPlus;
using DSharpPlus.CommandsNext;
using DSharpPlus.CommandsNext.Attributes;
using DSharpPlus.Entities;
using DSharpPlus.Lavalink;
namespace MusicBot
{
public class MediaCommands : BaseCommandModule
{
[Command("join"), Description("joins user voice channel")]
public async Task JoinVC(CommandContext ctx, DiscordChannel chn)
{
var lava = ctx.Client.GetLavalink();
if (!lava.ConnectedNodes.Any())
{
await ctx.RespondAsync("The Lavalink connection is not established");
return;
}
var node = lava.ConnectedNodes.Values.First();
if (chn.Type != ChannelType.Voice)
{
await ctx.RespondAsync("Not a valid voice channel");
return;
}
await node.ConnectAsync(chn);
await ctx.RespondAsync($"Joined {chn}");
}
program class no error when running
using System;
using DSharpPlus;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using DSharpPlus.CommandsNext;
using DSharpPlus.Lavalink;
using DSharpPlus.Net;
using LortBasic;
using LortMusic;
namespace Lort
{
class Program
{
static void Main(string[] args)
{
MainAsync().GetAwaiter().GetResult();
}
static async Task MainAsync()
{
var LortBot = new DiscordClient(new DiscordConfiguration()
{
Token = "mytoken",
TokenType = TokenType.Bot,
Intents = DiscordIntents.All,
MinimumLogLevel = LogLevel.Debug
});
//lavalink
var endpoint = new ConnectionEndpoint
{
Hostname = "127.0.0.1",
Port = 25565
};
var lavalinkconfig = new LavalinkConfiguration
{
Password = "youshallnotpass",
RestEndpoint = endpoint,
SocketEndpoint = endpoint,
};
var lavalink = LortBot.UseLavalink();
await LortBot.ConnectAsync();
await lavalink.ConnectAsync(lavalinkconfig);
await Task.Delay(-1);
I'm following this guide to make a discord bot with c# using DSharpPlus https://dsharpplus.github.io/articles/audio/lavalink/setup.html and everything works up until trying to get the bot to join a voice channel. it has admin rights and no errors in lavalink console, bot console, vs, none anywhere. nothing happens though... at all

Youtube Data API C# - use without requesting user credentials

I would like to use the YouTubeData API in C# - .Net Core - without requesting user credentials.
The only thing I need from this API is to retrieve the information of a playlist, but always when I use it on localhost it is requesting the user's credential.
How can I use this API without any request for credential or using my own token?
If you want to retrieve information (title, thumbnail) of a public playlist, you only need an API key. You only need to authenticate the user if you want to create or edit playlists.
This sample program retrieves the title and the thumbnail of a playlist by id.
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Google.Apis.Services;
using Google.Apis.YouTube.v3;
namespace YtbExample
{
internal class PlayList
{
[STAThread]
static void Main(string[] args)
{
try
{
new PlayList().Run().Wait();
}
catch (AggregateException ex)
{
foreach (var e in ex.InnerExceptions)
{
Console.WriteLine("Error: " + e.Message);
}
}
Console.WriteLine("Press any key to continue...");
Console.ReadKey();
}
private async Task Run()
{
var youtubeService = new YouTubeService(new BaseClientService.Initializer()
{
ApiKey = "YOUR_API_KEY",
ApplicationName = this.GetType().ToString()
});
var listRequest = youtubeService.Playlists.List("snippet");
listRequest.Id = "PLdo4fOcmZ0oXzJ3FC-ApBes-0klFN9kr9";
//Get playlists by channel id
//listRequest.ChannelId = "";
listRequest.MaxResults = 50;
var listResponse = await listRequest.ExecuteAsync();
List<string> playlists = new List<string>();
// Add each result to the list, and then display the lists of
// matching playlists.
foreach (var result in listResponse.Items)
{
playlists.Add(String.Format("Title: {0}, Id: {1}, Thumbnail: {2}", result.Snippet.Title, result.Id, result.Snippet.Thumbnails.Medium.Url));
}
Console.WriteLine(String.Format("{0}\n", string.Join("\n", playlists)));
}
}
}
I hope I could help you!

Using Google shortenurl API to make short urls

I am trying to use google shorten url to shorten a lot of urls for our project and keep getting an HTTPRequestException unhandled error. The first time I ran it it was asking to locate a .cs file which was not there so I am guessing it is due to that. I just used nugget installer to get this in visual studio. Any ideas?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Google.Apis.Urlshortener.v1;
using Google.Apis.Oauth2;
using Google.Apis.Services;
using System.Net;
using System.IO;
using System.Text.RegularExpressions;
namespace ShortenURL
{
class Program
{
static void Main(string[] args)
{
var originalURL = "https://www.google.com/maps/place/Desert+Christian+Schools/#32.2367293,-110.8339121,16.75z/data=!4m7!1m4!3m3!1s0x86d66f1806d996d7:0xe8ac20e8cebb38b9!2s7525+E+Speedway+Blvd,+Tucson,+AZ+85710!3b1!3m1!1s0x86d66f1806d996d7:0x7b90764e4e6a25d8";
string shortUrl = Shorten(originalURL);
Console.WriteLine(shortUrl);
Console.WriteLine("FINISHED");
Console.ReadLine();
}
private const string key = "AIzaSyB3pfstkvAZzEVOy4dNHaKTuNmtDaG3XsI";
public static string Shorten(string url)
{
UrlshortenerService service = new UrlshortenerService(new BaseClientService.Initializer()
{
ApiKey = key,
ApplicationName = "ShortenUrlAHLI"
});
var m = new Google.Apis.Urlshortener.v1.Data.Url();
m.LongUrl = url;
return service.Url.Insert(m).Execute().Id;
}
}
}
//The code workable in my case :)
//VS2017
private static string shorten(string url)
{
UrlshortenerService service = new UrlshortenerService(
new BaseClientService.Initializer() {
ApiKey = "<google-api-key>",
ApplicationName = "<google-app-id>", });
var m = new Google.Apis.Urlshortener.v1.Data.Url();
m.LongUrl = url;
return service.Url.Insert(m).Execute().Id;
}

How can i make that when searching for youtube uploads using google api v3 it will show more then 50 results?

If i make the max results to be 400 it will make exception since it should be between 0-50 to 400.
So for now for testing i did it 50.
How can i make somehow that when it found 50 results and added them to the List it will make then another search for the next 50 results and so on until the end ?
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System;
using System.IO;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Services;
using Google.Apis.Upload;
using Google.Apis.Util.Store;
using Google.Apis.YouTube.v3;
using Google.Apis.YouTube.v3.Data;
namespace Automatic_Record
{
class Youtube_Retrieve_Uploads
{
public Youtube_Retrieve_Uploads()
{
test();
/*try
{
Run().Wait();
}
catch (AggregateException ex)
{
foreach (var e in ex.InnerExceptions)
{
Console.WriteLine("Error: " + e.Message);
}
}*/
}
private void test()
{
YouTubeService yt = new YouTubeService(new BaseClientService.Initializer() { ApiKey = "AIzaSyDcqx8nMWQL9wshpAs0Q-h0twpGd6R1BJM" });
List<string> videos = new List<string>();
var searchListRequest = yt.Search.List("snippet");
searchListRequest.ChannelId = "UCUE_2qgW-nJOjOlO28uZHtQ";//"UCbe-iLd-TEl3_YQaNSm8dng";
searchListRequest.MaxResults = 50;
var searchListResult = searchListRequest.Execute();
foreach (var item in searchListResult.Items)
{
if (item.Snippet.Title.StartsWith("Gta"))
{
videos.Add("ID: " + item.Id.VideoId);
videos.Add("SNIPPET: " + item.Snippet.Title);
}
}
}
This is working fine but i'm getting only 50 results. I want to get the whole videos starts with Gta but in general i want to get the first 50 results then the next 50 then the next 50 until there are no more results.
You need to loop through pages by using a token to identify which page you're on.
Follow the nextPageToken variable through this example:
var nextPageToken = "";
while (nextPageToken != null)
{
var playlistItemsListRequest = youtubeService.PlaylistItems.List("snippet");
playlistItemsListRequest.PlaylistId = uploadsListId;
playlistItemsListRequest.MaxResults = 50;
playlistItemsListRequest.PageToken = nextPageToken;
// Retrieve the list of videos uploaded to the authenticated user's channel.
var playlistItemsListResponse = await playlistItemsListRequest.ExecuteAsync();
foreach (var playlistItem in playlistItemsListResponse.Items)
{
// Print information about each video.
Console.WriteLine("{0} ({1})", playlistItem.Snippet.Title, playlistItem.Snippet.ResourceId.VideoId);
}
nextPageToken = playlistItemsListResponse.NextPageToken;
}
See this link for more help and examples:
https://developers.google.com/youtube/v3/code_samples/dotnet

GooglePlus Authentication in Windows Phone 8.1

I am writing a Windows Phone 8.1 App (WINRT).
How to do GooglePlus Authentication (SignIn via GooglePlus) in Windows Phone 8.1 App** without using MVVM/MVC**?
I used Web Authentication via Webbrowser control in Windows Phone 8.0 App but Windows Phone 8.1 WebView Control does not have Navigating event.
Can anyone help me?
According to Mr. Filip Skakun, I wrote:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Threading.Tasks;
using Windows.ApplicationModel.Activation;
using Windows.Data.Json;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.Security.Authentication.Web;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using Windows.Web.Http;
namespace webbrokerFinal
{
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
Connect();
this.NavigationCacheMode = NavigationCacheMode.Required;
}
string FacebookClientIDString = "000000000000";
string FacebookCallbackUrlString = " https://www.facebook.com/connect/login_success.html";
private void Connect()
{
try
{
String FacebookURL = "https://www.facebook.com/dialog/oauth?client_id=" + FacebookClientIDString + "&redirect_uri=" + Uri.EscapeUriString(FacebookCallbackUrlString) + "&scope=read_stream&display=popup&response_type=token";
System.Uri StartUri = new Uri(FacebookURL);
System.Uri EndUri = new Uri(FacebookCallbackUrlString);
WebAuthenticationBroker.AuthenticateAndContinue(StartUri, EndUri, null, WebAuthenticationOptions.None);
}
catch (Exception Error) >> The remote procedure call failed. (Exception from HRESULT: 0x800706BE)
{
//
// Bad Parameter, SSL/TLS Errors and Network Unavailable errors are to be handled here.
//
}
}
public async void ContinueWebAuthentication(WebAuthenticationBrokerContinuationEventArgs args)
{
WebAuthenticationResult result = args.WebAuthenticationResult;
if (result.ResponseStatus == WebAuthenticationStatus.Success)
{
await GetFacebookUserNameAsync(result.ResponseData.ToString());
}
else if (result.ResponseStatus == WebAuthenticationStatus.ErrorHttp)
{
}
else
{
}
}
private async Task GetFacebookUserNameAsync(string webAuthResultResponseData)
{
//Get Access Token first
string responseData = webAuthResultResponseData.Substring(webAuthResultResponseData.IndexOf("access_token"));
String[] keyValPairs = responseData.Split('&');
string access_token = null;
string expires_in = null;
for (int i = 0; i < keyValPairs.Length; i++)
{
String[] splits = keyValPairs[i].Split('=');
switch (splits[0])
{
case "access_token":
access_token = splits[1]; //you may want to store access_token for further use. Look at Scenario5 (Account Management).
break;
case "expires_in":
expires_in = splits[1];
break;
}
}
//Request User info.
HttpClient httpClient = new HttpClient();
string response = await httpClient.GetStringAsync(new Uri("https://graph.facebook.com/me?access_token=" + access_token));
JsonObject value = JsonValue.Parse(response).GetObject();
string facebookUserName = value.GetNamedString("name");
}
}
}
But giving me error:
The remote procedure call failed. (Exception from HRESULT: 0x800706BE)
I'd start with WebAuthenticationBroker. It's a sort of wrapper around WebView you use for all OAuth.

Categories

Resources