How can i create a private message from telegram bot? - c#

I'm connecting to telegram bot with webhook and i wanted to respond in private chat through telegram but if i send UID it doesn't send any message to the user from the bot.
this is what i did.
I created a Web API Project with .net framework to connect to webhook with telegram bot.
As a user, i wrote a command that will return some list of objects.
From the WebAPI i got the command and processed correctly
on sending response back i passed this {"method":"sendMessage","chat_id":"[user's UID who sent the command]", "text":"[returning list converted as string]", "reply_to_message_id":"[message id for the command]"}
This is the actual code that i'm sending
return new TelegramResponseModel
{ method = "sendMessage", chat_id = newUpdate.message.chat.id.ToString(),
text = text, reply_to_message_id = newUpdate.message.message_id };
on telegram nothing happens!!

You can use Nuget package library for implementing integration with Telegram called Telegram.Bot. Also there is few examples how you can use this library.
For example this short program shows how you can use WebHook's
using System;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Web.Http;
using Microsoft.Owin.Hosting;
using Owin;
using Telegram.Bot.Types;
using Telegram.Bot.Types.Enums;
using File = System.IO.File;
namespace Telegram.Bot.Examples.WebHook
{
public static class Bot
{
public static readonly TelegramBotClient Api = new TelegramBotClient("Your API Key");
}
public static class Program
{
public static void Main(string[] args)
{
// Endpoint must be configured with netsh:
// netsh http add urlacl url=https://+:8443/ user=<username>
// netsh http add sslcert ipport=0.0.0.0:8443 certhash=<cert thumbprint> appid=<random guid>
using (WebApp.Start<Startup>("https://+:8443"))
{
// Register WebHook
// You should replace {YourHostname} with your Internet accessible hosname
Bot.Api.SetWebhookAsync("https://{YourHostname}:8443/WebHook").Wait();
Console.WriteLine("Server Started");
// Stop Server after <Enter>
Console.ReadLine();
// Unregister WebHook
Bot.Api.DeleteWebhookAsync().Wait();
}
}
}
public class Startup
{
public void Configuration(IAppBuilder app)
{
var configuration = new HttpConfiguration();
configuration.Routes.MapHttpRoute("WebHook", "{controller}");
app.UseWebApi(configuration);
}
}
public class WebHookController : ApiController
{
public async Task<IHttpActionResult> Post(Update update)
{
var message = update.Message;
Console.WriteLine("Received Message from {0}", message.Chat.Id);
if (message.Type == MessageType.Text)
{
// Echo each Message
await Bot.Api.SendTextMessageAsync(message.Chat.Id, message.Text);
}
else if (message.Type == MessageType.Photo)
{
// Download Photo
var file = await Bot.Api.GetFileAsync(message.Photo.LastOrDefault()?.FileId);
var filename = file.FileId + "." + file.FilePath.Split('.').Last();
using (var saveImageStream = File.Open(filename, FileMode.Create))
{
await Bot.Api.DownloadFileAsync(file.FilePath, saveImageStream);
}
await Bot.Api.SendTextMessageAsync(message.Chat.Id, "Thx for the Pics");
}
return Ok();
}
}
}

here you have a functional code on php:
<?php
$token = 'yout_boot_tocken';
$website = 'https://api.telegram.org/bot'.$token;
$input = file_get_contents('php://input');
$update = json_decode($input, TRUE);
$chatId = $update['message']['chat']['id'];
$message = $update['message']['text'];
$messageCode = strtoupper($message);
switch($messageCode) {
case 'hello':
$response = 'Hello my friend... how are you?';
sendMessage($chatId, $response);
break;
case 'address':
$response = 'Your Addres is Rosent wallet 245';
sendMessage($chatId, $response);
break;
case '/INFO':
$response = 'Hi, i am a Boot';
sendMessage($chatId, $response);
break;
case 'bye':
$response = 'it was a pleasure chat with you';
sendMessage($chatId, $response);
break;
default:
$response = 'I dont understand what do you mean with '.$messageCode;
sendMessage($chatId, $response);
break;
}
function sendMessage($chatId, $response) {
$url = $GLOBALS['website'].'/sendMessage?
chat_id='.$chatId.'&parse_mode=HTML&text='.urlencode($response);
file_get_contents($url);
}
?>

Related

I want to create a C# web API for azure speech to text console application

I have this following C# console application which uses azure speech to text service and converts speech taken from microphone input into text. I want to create a web API (using the endpoint id, subscription key and service region). Can anyone tell me how to do this?
C# code
using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CognitiveServices.Speech;
using Microsoft.CognitiveServices.Speech.Audio;
namespace Deployedsample1
{
class Program
{
static string YourSubscriptionKey = "";
static string YourServiceRegion = "centralindia";
{
static void OutputSpeechRecognitionResult(SpeechRecognitionResult
speechRecognitionResult)
{
switch (speechRecognitionResult.Reason)
{
case ResultReason.RecognizedSpeech:
Console.WriteLine($"RECOGNIZED: Text={speechRecognitionResult.Text}");
break;
case ResultReason.NoMatch:
Console.WriteLine($"NOMATCH: Speech could not be recognized.");
break;
case ResultReason.Canceled:
var cancellation = CancellationDetails.FromResult(speechRecognitionResult);
Console.WriteLine($"CANCELED: Reason={cancellation.Reason}");
if (cancellation.Reason == CancellationReason.Error)
{
Console.WriteLine($"CANCELED: ErrorCode={cancellation.ErrorCode}");
Console.WriteLine($"CANCELED: ErrorDetails={cancellation.ErrorDetails}");
Console.WriteLine($"CANCELED: Double check the speech resource key and region.");
}
break;
}
}
async static Task Main(string[] args)
{
// var speechConfig = SpeechConfig.FromSubscription(YourSubscriptionKey, YourServiceRegion);
var config = SpeechConfig.FromSubscription("", "centralindia");
config.EndpointId = "";
config.SpeechRecognitionLanguage = "en-US";
var reco = new SpeechRecognizer(config);
//To recognize speech from an audio file, use `FromWavFileInput` instead of `FromDefaultMicrophoneInput`:
//using var audioConfig = AudioConfig.FromWavFileInput("YourAudioFile.wav");
using var audioConfig = AudioConfig.FromDefaultMicrophoneInput();
using var speechRecognizer = new SpeechRecognizer(config, audioConfig);
Console.WriteLine("Speak into your microphone.");
var speechRecognitionResult = await speechRecognizer.RecognizeOnceAsync();
OutputSpeechRecognitionResult(speechRecognitionResult);
}
}
}
I want to create a web API (using the endpoint id, subscription key
and service region). Can anyone tell me how to do this?
To achieve the above requirement you can follow the below workaround to achieve it using web api:
public class Authentication
{
public static readonly string FetchTokenUri =
"https://westus.api.cognitive.microsoft.com/sts/v1.0/issueToken";
private string subscriptionKey;
private string token;
public Authentication(string subscriptionKey)
{
this.subscriptionKey = subscriptionKey;
this.token = FetchTokenAsync(FetchTokenUri, subscriptionKey).Result;
}
public string GetAccessToken()
{
return this.token;
}
private async Task<string> FetchTokenAsync(string fetchUri, string subscriptionKey)
{
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", subscriptionKey);
UriBuilder uriBuilder = new UriBuilder(fetchUri);
var result = await client.PostAsync(uriBuilder.Uri.AbsoluteUri, null);
Console.WriteLine("Token Uri: {0}", uriBuilder.Uri.AbsoluteUri);
return await result.Content.ReadAsStringAsync();
}
}
}
For complete setup please refer this MICROSOFT DOCUMENTATION .

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

How can I connect my Unity android app to a 000webhost database?

I'm making a Unity Android app that displays info from a database.
For that I used 000WebHost to make a website and a sql server. When I test the app with Unity in my computer, it works fine, a bit of loading time required, but it works perfectly.
But, when I build the apk and test it on my phone, it doesn't work. It gets stuck in the "loading text" screen I made and never loads the text from the database.
I have a log error in Unity that activates when the connection fails, and I suppose the same is happening here.
Is there a way to solve it or is it because i'm a free user?
Here are the codes:
WebTextLoader.cs (Unity/Displays text from the database)
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.UI;
public class WebTextLoader : MonoBehaviour
{
[Serializable]
public class PlaceInfo
{
public string Titulo = "";
public string Texto = "";
}
public string URL; //example: https://arguidetest.000webhostapp.com/pruebaMedieval.php
public Text TituloUI;
public Text TextoUI;
public PlaceInfo placeInfo;
public void Start()
{
if (Debug.isDebugBuild)
{
StartCoroutine(GetRequest(URL));
}
}
IEnumerator GetRequest(string uri)
{
using (UnityWebRequest webRequest = UnityWebRequest.Get(uri))
{
// Request and wait for the desired page.
yield return webRequest.SendWebRequest();
string jsonForm = uri;
if (webRequest.isNetworkError)
{
Debug.Log("Error loading");
}
else
{
try
{
placeInfo = JsonUtility.FromJson<PlaceInfo>(webRequest.downloadHandler.text);
TituloUI.text = placeInfo.Titulo;
TextoUI.text = placeInfo.Texto;
}
catch
{
Debug.Log("Error in connection");
}
}
}
}
}
pruebaMedieval.php (000webhost / turns an array of title and text into a JSon)
<?php
$server = ***;
$usuario = ***;
$pass = ***;
$database= ***;
$mysqli = new mysqli($server, $usuario, $pass, $database);
$query = $mysqli -> query("SELECT * FROM INFORMACION_EVENTOS where id = 1");
while ($valores = mysqli_fetch_array($query)) {
$titulo = $valores["titulo"];
$info = $valores["informacion"];
$array = array(
"Titulo" => $titulo,
"Texto" => $info
);
}
$result = json_encode($array);
echo $result;
?>
Also, in Unity player settings I have the internet connection as Require.
Sorry for the wall of text

Sending Message Using Twilio-C#

Hy... I'm learning twilio rightnow, and I have seen a post here http://www.markhagan.me/Samples/Send-SMS-Using-Twilio-ASPNet
I have made my own code because in above site "sendSMSMessage" is deprecated now, but Here is my code :
using System.Text;
using System.Threading.Tasks;
using Twilio;
namespace SMSUsingTwilio
{
class Program
{
static void Main(string[] args)
{
String ACCOUNT_SID = "ACMYSID";
String AUTH_TOKEN = "40MYAUTHTOKEN";
TwilioRestClient client = new TwilioRestClient(ACCOUNT_SID, AUTH_TOKEN);
Message Response = client.SendMessage("(732)305-8856", "+6285220446195", "Hellow Hyosoka Poipo :D");
Console.WriteLine(Response.Status);
Console.WriteLine(Response.AccountSid);
Console.WriteLine("SMS Berhasil di kirim");
Console.ReadLine();
}
}
}
The problem is I don't any sms message to my phone number and even I don't get any response in my C# project:
So what's wrong here...?? Please help..Thank you so much...:)
After seeing mr.David answer, I realized that my phone number was not yet verified. So go to this link for verifying my number:
https://www.twilio.com/user/account/phone-numbers/verified
After that, I run my project agian and here is the result :
Yeeeiii...Thanks so much for your comments and answer... I really appreciate it... :)
The above looks fine:
var message = client.SendMessage("(732)305-8856", "+6285220446195", "Hellow Hyosoka Poipo :D");
Example:
static void Main(string[] args)
{
string AccountSid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
string AuthToken = "[AuthToken]";
var twilio = new TwilioRestClient(AccountSid, AuthToken);
var message = twilio.SendMessage("(732)305-8856", "+6285220446195", "Hellow Hyosoka Poipo :D");
);
Console.WriteLine(message.Sid);
}
Check this out:
https://www.twilio.com/docs/api/rest/sending-messages
I don't recognise your phone numbers, if the above example does not work it will be an issue with your account or the number format.
First of all, you need to install a Twillio NuGet package from Numget Manager
Otherwise,
You can write code Install-Package Twilio
in Package manager console.
You need to create Twillo account from https://www.twilio.com
Now you get AccountId, AuthToken etc
Then you will need to implement the following code in your project:
public async Task<string> SendTwilioSMS(string phoneNumber, string SMS)
{
string returnMessage = string.Empty;
string bodySMS = SMS;
var twilioAccountSid = "AC754fec249d22766caf0ae4e58a158271";
var twilioAuthToken = "cfecd5ff4d751677fc2e2875e3739b55";
var twilioMessagingServiceSid = "MGd57fcc863cb37dcff135aca43b4bb7d1";
var twilioPhoneNumber = "+919714285344";
bodySMS = SMS;
TwilioClient.Init(twilioAccountSid, twilioAuthToken);
try
{
MessageResource twillioResult = await MessageResource.CreateAsync(
to: new PhoneNumber(phoneNumber),
from: new PhoneNumber(twilioPhoneNumber),
body: bodySMS,
messagingServiceSid: twilioMessagingServiceSid
);
returnMessage = "Message sent";
}
catch (Exception err)
{
returnMessage = err.Message;
}
return returnMessage;
}
The value should be brought from appsettings file if using .Net Core.
public async Task SendSMS()
{
var sid = "0845-373A-90fy-5790";
var authToken = "5a983-498f94-2849o8934-28455s9";
try
{
TwilioClient.Init(sid , authToken );
var message = await MessageResource.CreateAsync(
body: "Hi",
from: new Twilio.Types.PhoneNumber("+12564598"),
to: new Twilio.Types.PhoneNumber("9467345243"));
}
catch (Exception ex)
{
//Log Exception
}
}

VersionOne: query.v1 C# OAuth2 gets 401 Unauthorized error but rest-1.oauth.v1/Data/ does work

I am able to do queries using OAuth2 and this:
/rest-1.oauth.v1/Data/Story?sel=Name,Number&Accept=text/json
However I am unable to get the OAuth2 and the new query1.v1 to work against the Sumnmer2013 VersionOne. I am getting (401) Unauthorized and specified method is not supported using two different URLs.
Here is the code that includes the working /rest-1.oauth.v1 and the non-working query1.v1 and non-working query.legacy.v1. Scroll towards the bottom of the code to see the Program Main (starting point of code)
Please advise on what I am missing here.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using OAuth2Client;
namespace ExampleMemberListCSharp
{
class Defaults
{
public static string Scope = "apiv1";
//public static string EndpointUrl = "http://localhost/VersionOne.Web";
public static string EndpointUrl = "https://versionone-test.web.acme.com/summer13_demo";
public static string ApiQueryWorks = "/rest-1.oauth.v1/Data/Member?Accept=text/json";
public static string ApiQuery = "/rest-1.oauth.v1/Data/Story?sel=Name,Number&Accept=text/json";
}
static class WebClientExtensions
{
public static string DownloadStringOAuth2(this WebClient client, IStorage storage, string scope, string path)
{
var creds = storage.GetCredentials();
client.AddBearer(creds);
try
{
return client.DownloadString(path);
}
catch (WebException ex)
{
if (ex.Status == WebExceptionStatus.ProtocolError)
{
if (((HttpWebResponse)ex.Response).StatusCode != HttpStatusCode.Unauthorized)
throw;
var secrets = storage.GetSecrets();
var authclient = new AuthClient(secrets, scope);
var newcreds = authclient.refreshAuthCode(creds);
var storedcreds = storage.StoreCredentials(newcreds);
client.AddBearer(storedcreds);
return client.DownloadString(path);
}
throw;
}
}
public static string UploadStringOAuth2(this WebClient client, IStorage storage
, string scope, string path, string pinMethod, string pinQueryBody)
{
var creds = storage.GetCredentials();
client.AddBearer(creds);
client.UseDefaultCredentials = true;
try
{
return client.UploadString(path, pinMethod, pinQueryBody);
}
catch (WebException ex)
{
if (ex.Status == WebExceptionStatus.ProtocolError)
{
if (((HttpWebResponse)ex.Response).StatusCode != HttpStatusCode.Unauthorized)
throw;
var secrets = storage.GetSecrets();
var authclient = new AuthClient(secrets, scope);
var newcreds = authclient.refreshAuthCode(creds);
var storedcreds = storage.StoreCredentials(newcreds);
client.AddBearer(storedcreds);
client.UseDefaultCredentials = true;
return client.UploadString(path, pinMethod, pinQueryBody);
}
throw;
}
}
}
class AsyncProgram
{
private static async Task<string> DoRequestAsync(string path)
{
var httpclient = HttpClientFactory.WithOAuth2("apiv1");
var response = await httpclient.GetAsync(Defaults.EndpointUrl + Defaults.ApiQuery);
var body = await response.Content.ReadAsStringAsync();
return body;
}
public static int MainAsync(string[] args)
{
var t = DoRequestAsync(Defaults.EndpointUrl + Defaults.ApiQuery);
Task.WaitAll(t);
Console.WriteLine(t.Result);
return 0;
}
}
class Program
{
static void Main(string[] args)
{
IStorage storage = Storage.JsonFileStorage.Default;
using (var webclient = new WebClient())
{
// this works:
var body = webclient.DownloadStringOAuth2(storage, "apiv1", Defaults.EndpointUrl + Defaults.ApiQuery);
Console.WriteLine(body);
}
IStorage storage2 = Storage.JsonFileStorage.Default;
using (var webclient2 = new WebClient())
{
// This does NOT work. It throws an exception of (401) Unauthorized:
var body2 = webclient2.UploadStringOAuth2(storage2, "apiv1", Defaults.EndpointUrl + "/query.v1", "SEARCH", QueryBody);
// This does NOT work. It throws an exception of The remote server returned an error: (403): Forbidden."
var body3 = webclient2.UploadStringOAuth2(storage2, "apiv1", Defaults.EndpointUrl + "/query.legacy.v1", "SEARCH", QueryBody);
// These do NOT work. Specified method is not supported:
var body4 = webclient2.UploadStringOAuth2(storage2, "apiv1", Defaults.EndpointUrl + "/oauth.v1/query.legacy.v1", "SEARCH", QueryBody);
var body5 = webclient2.UploadStringOAuth2(storage2, "apiv1", Defaults.EndpointUrl + "/oauth.v1/query.legacy.v1", "SEARCH", QueryBody);
}
Console.ReadLine();
AsyncProgram.MainAsync(args);
}
public const string QueryBody = #"
from: Story
select:
- Name
";
}
}
At this time, the query.v1 endpoint requires the query-api-1.0 scope to be granted.
You'll have to add that to your scope list (it can be simply space-separated e.g. apiv1 query-api-1.0) and visit the grant URL again to authorize the permissions.
This somewhat vital piece of information doesn't seem to appear in the docs on community.versionone.com, so it looks like an update is in order.
Also, only the rest-1.oauth.v1 and query.v1 endpoints respond to OAuth2 headers at this time. A future release will see it apply to all endpoints and remove the endpoint duplication for the two types of authentication
I have had problems in the past trying to use an HTTP method other than POST to transmit the query. Security software, IIS settings, and proxies may all handle such requests in unexpected ways.

Categories

Resources