I'm attempting to create a small program that can demonstrate some features of the Telegram API. I wish to be able to register and authenticate users via SMS. According to the user authorization guide, I need to invoke the auth.sendCode RPC. However, the codebase is inadequately documented and is proving hard to get into.
How do I send the auth.sendCode remote procedure call in Telegram? Please provide a code snippet which shows everything starting from set up and initialization.
Try Like this...
TLSentCode sentCode;
try {
sentCode = api.doRpcCallNonAuth(new TLRequestAuthSendCode(phone, 0, 5, "your app id", "en"));
} catch (RpcException e) {
if (e.getErrorCode() == 303) {
int destDC;
if (e.getErrorTag().startsWith("NETWORK_MIGRATE_")) {
destDC = Integer.parseInt(e.getErrorTag().substring("NETWORK_MIGRATE_".length()));
} else if (e.getErrorTag().startsWith("PHONE_MIGRATE_")) {
destDC = Integer.parseInt(e.getErrorTag().substring("PHONE_MIGRATE_".length()));
} else if (e.getErrorTag().startsWith("USER_MIGRATE_")) {
destDC = Integer.parseInt(e.getErrorTag().substring("USER_MIGRATE_".length()));
} else {
throw e;
}
api.switchToDc(destDC);
sentCode = api.doRpcCallNonAuth(new TLRequestAuthSendCode(phone, 0, 5, "youa app id", "en"));
} else {
throw e;
}
}
Related
As mentioned in this link, on .net core2.1 web.api application implemented the below code to track non-HTTP requests(i.e, redis calls) using Application Insights
private ReviewModel<T> GetCachedData<T>(string id)
{
try
{
var obj = default(RedisValue);
_retryPolicy.Execute(() =>
{
using (var getReviewsOperation = _telemetryClient.StartOperation<DependencyTelemetry>("RedisCall"))
{
obj = _database.StringGet(id); // external call to redis server
}
});
var review = string.IsNullOrEmpty(obj) || !obj.HasValue ?
default(ReviewModel<T>) : _serializer.Deserialize<ReviewModel<T>>(obj );
return review;
}
catch (Exception ex)
when (ex is RedisException)
{
//how to log the exception cases in dependency table of application insights log?
_log.LogError($"Redis exception occurred : ", {ex.Message});
return null;
}
}
The above code successfully log the redis call details on "dependency" table of application insights log. But how to log redis call details on "dependency" table of application insights log on exception scenarios with success property value as "false"?
You can use TrackDependency for this. TrackDependency is used to track the response times and success rates of calls to an external piece of code. The results appear in the dependency charts in the portal. The code snippet below needs to be added wherever a dependency call is made:
var success = false;
var startTime = DateTime.UtcNow;
var timer = System.Diagnostics.Stopwatch.StartNew();
try
{
success = dependency.Call();
}
catch(Exception ex)
{
success = false;
telemetry.TrackException(ex);
throw new Exception("Operation went wrong", ex);
}
finally
{
timer.Stop();
telemetry.TrackDependency("DependencyType", "myDependency", "myCall", startTime, timer.Elapsed, success);
}
The context is MS Bot Framework on Node. I need to custom validate an input from a Prompt.text or Prompt.Number. I have been taking a look at examples and docs. I have implemented a quick example with DialogAction.validatePrompt(), which works ok but has the problem that I cannot (or at least I don't know how) customize the message in case the validation fails.
The validation could fail for many reasons and it would be great to be able to choose a response message based on the failure reason.
Also I have seen the basics-custom-prompt example in: (https://github.com/Microsoft/BotBuilder/tree/master/Node/examples/basics-customPrompt) and it uses and IntentDialog to get the desired behavior. It also mentions it is a replacement for the basics-validatedPrompt example.
My questions are:
Which one is recommend to use, validatedPrompt or the IntentDialog
approach?
Is the validatedPrompt() going to be deprecated?
Does the validatedPrompt() provide a mechanism for custom message?
Microsoft Bot Framework Version 4 Prompt Validation Example link is specified in below :
https://github.com/Microsoft/BotBuilder-Samples/tree/master/samples/javascript_nodejs/10.prompt-validations
For Proper Text Prompt Validation is you create separate file which perform validation task
Code: namePrompt/index.js
const { TextPrompt } = require('botbuilder-dialogs');
module.exports.NamePrompt = class NamePrompt extends TextPrompt {
constructor(dialogId) {
super(dialogId, async (prompt) => {
if (!prompt.recognized.succeeded) {
await prompt.context.sendActivity('Please tell me your name.');
return false;
} else {
const value = prompt.recognized.value;
if (value.length < 1) {
await prompt.context.sendActivity('Your name has to include at least one character.');
return false;
} else if (value.length > 50) {
await prompt.context.sendActivity(`Sorry, but I can only handle names of up to 50 characters. Yours was ${ value.length }.`);
return false;
} else {
return true;
}
}
});
}
};
Now inside your current dialog you can import above file:
const { NamePrompt } = require('../../prompts/namePrompt');
const GET_NAME_PROMPT = 'namePrompt';
this.addDialog(new NamePrompt(GET_NAME_PROMPT));
inside your dialog step you can prompt such like this:
async promptForName(step) {
return await step.prompt(GET_NAME_PROMPT, `What is your name, human?`);
}
I'm following the very good tutorial
www.hivemq.com/mqtt-essentials-part-6-mqtt-quality-of-service-levels/
but I can't figure out to implement
Of course your application must be tolerating duplicates and process
them accordingly.
Can to give me a simple example, please ?
for instance now I've like
(I set up my deploy following https://medium.com/#lelylan/how-to-build-an-high-availability-mqtt-cluster-for-the-internet-of-things-8011a06bd000)
module.exports.authorizePublish = function(client, topic, payload, callback) {
var chunks = topic.split('/');
if(chunks.length === 4) {
Debug('AUTHORIZING SUBSCRIBE', client.device_id == chunks[1]);
Debug('NICKNAME', chunks[1]);
Debug('CHANNEL', chunks[3]);
Debug('TOPIC', chunks[2]);
Debug('PAYLOAD', payload.toString('utf8'));
var data = {
deviceNickname:chunks[1],
channel:chunks[3],
topic:chunks[2],
payload:payload.toString('utf8')
};
Message.insert(data, function (err, message) {
if (err){
Debug(err);
return;
}
Debug(message);
});
}
callback(null, client.device_id === chunks[1]);
}
I'm still rather a learner of MQTT than an expert, but my understanding of handling of duplicate messages with QoS 1 is following:
Suppose you have an application that for whatever reason needs to count messages received from a broker. However, you don't want to take duplicate messages (sent when your client didn't ACK the message in time) to be taken into account.
I use Java Paho client, so the code for it would be:
int counter = 0;
public void messageArrived(String topic, MqttMessage message) throws MqttException {
if (message.isDuplicate() == false) {
counter++;
}
}
This is my code, I am trying to connect to twitter but it is not giving error.
I am using Twitterizer2 dll in this project. Any help is greatly appreciated.
public UserOauthTokens TwitterLogin(string ConsumerKey, string ConsumerSecret)
{
UserOauthTokens utk = new UserOauthTokens();
try
{
if (HttpContext.Current.Request["oauth_token"] == null)
{
OAuthTokenResponse reqToken = OAuthUtility.GetRequestToken(ConsumerKey, ConsumerSecret, HttpContext.Current.Request.Url.AbsoluteUri);
HttpContext.Current.Response.Redirect(string.Format("http://twitter.com/oauth/authorize?oauth_token={0}", reqToken.Token));
}
else
{
utk.Oauth_Token = HttpContext.Current.Request["oauth_token"].ToString();
utk.Oauth_Verifier = HttpContext.Current.Request["oauth_verifier"].ToString();
}
return utk;
}
catch (Exception ex)
{
return utk;
}
}
The documentation says that you must use https.
Try changing the line to https://twitter.com/oauth/authorize?oauth_token={0}
Note the extra s in there.
Also, make sure you're using the latest version of the library.
I have the following code for recreating a WCf client in a non opened state
if (client.State != CommunicationState.Opened)
{
client.Abort();
client = null;
Trace.WriteLine("Client object in non opened state. Recreating object");
client = new <WCFClient>("NetTcpBindingEndpoint", ConfigurationManager.AppSettings["ServiceEndPointAddress"]);
client.Open();
}
For some reason though, as soon as this routine returns and I try to call client.Somemethod(), I get an exception and when I catch it, I see the client in a faulted state. I don't understand how this happened so quickly.
Thanks for any help in advance.
Subbu
Can you show us when you're trying to call client.SomeMethod() ?
I don't see what you're trying to achieve with the client.Open() here..... that really doesn't make any sense at all - just call the method you want to call!
try
{
var client = new <WCFClient>("NetTcpBindingEndpoint", ConfigurationManager.AppSettings["ServiceEndPointAddress"]);
client.SomeMethod();
client.Close();
}
catch(FaultException<T> exc)
{
// handle it
client.Abort();
}
catch(CommunicationException exc)
{
// handle it
client.Abort();
}
catch(EndpointNotFoundException exc)
{
// handle it
client.Abort();
}
catch(TimeoutException exc)
{
// handle it
client.Abort();
}
and maybe add some try.....catch magic around it to make it safer.... but that's really all you need - no need to first .Open() the client.....