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
}
}
Related
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 .
I am using InstagramApiSharp
Here is my code :
public static async void CreateAccount()
{
var _instaApi = InstaApiBuilder.CreateBuilder().Build();
var email = "ramtinaaka#live.com";
var username = "rmt40306";
var password = "rmt122345678";
var firstName = "Ramtiinnn";
var checkEmail = await _instaApi.CheckEmailAsync(email);
if(checkEmail.Succeeded && checkEmail.Value.Available)
{
var create = await _instaApi.CreateNewAccountAsync(username, password, email, firstName);
if (create.Succeeded)
{
Console.WriteLine("Success");
return;
}
Console.WriteLine("Error");
}
return;
}
I get Error printed on console when I call CreateAccount method as well as no account created.
Create Account Wiki
I believe I gave all needed info, I don't think there is anything else to add.
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);
}
?>
I am working on an MVC5 project, the client is interested in using MailChimp for sending emails. I have explored the MailChimp and wrappers ( MailChimp.NET ) and tried in my project as well. I tested the REST API as well and it seems to work , for example; I was able to grab lists and templates using REST API. But, still I am having issues with sending email through MailChimp.
So far, I have tried the following code and its working. Now I want to send an email to a newly registered user. Kindly give me detailed code example that How can I achieve this, because I am totally struck here..
var apiKey = "myapikey-us11";
var listId = "mylistid";
var subscribeRequest = new
{
apikey = apiKey,
id = listId,
email = new
{
email = "muhammad.waqas#seventechnology.co.uk"
},
double_optin = true,
};
var requestJson = JsonConvert.SerializeObject(subscribeRequest);
var reqresult = CallMailChimpApi("lists/", requestJson);
CallMailChimApi
private static string CallMailChimpApi(string method, string requestJson)
{
var endpoint = String.Format("https://{0}.api.mailchimp.com/3.0/{1}", "us11", method);
var wc = new WebClient();
try
{
return wc.UploadString(endpoint, requestJson);
}
catch (WebException we)
{
using (var sr = new StreamReader(we.Response.GetResponseStream()))
{
return sr.ReadToEnd();
}
}
}
I Use this function and it work successfully
public void SendEmailByApiMailChimp ()
{
try
{
string UserEmail = " Exemple#gmail.com ";
MailChimpManager mc = new MailChimpManager("16d***********-us14");
EmailParameter email = new EmailParameter()
{
Email = UserEmail
};
EmailParameter resulte = mc.Subscribe("yourlistnumber", email);
var test = resulte;
}
catch (Exception ex)
{
var ters = ex;
}
}
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.