Twitter: Error sending Direct message with quick reply buttons - twitter

I need to send a Twitter DM with quick reply.
I use Tweetinvi, that at the moment does not support quick replies, therefore I tried to alter the query in Tweetinvi code at the lovest possible level: just before it is sent to Twitter.
If I send this (basic message)
https://api.twitter.com/1.1/direct_messages/new.json?text=hello&user_id=999999999
It works
When I send is this
https://api.twitter.com/1.1/direct_messages/new.json?text=MessageToUserId&user_id=999999999&quick_reply&type=options&options=[label=RedBird&description=Adescriptionabouttheredbird.&metadata=external_id_1]
I get status 401 Web request failed.
To build my request I tried to simplify this example:
https://developer.twitter.com/en/docs/direct-messages/quick-replies/api-reference/options
But I am missing something. I suppose it is a trivial mistake in the query. I tried several variations, but I cannot get a better result. Of course in my code I use a real userId, that here I masked with 9.
Can you suggest me a working correction to my query? (maybe with examples using multiple labels)
Update.
I tried to use TwitterAccessor (without hacks in Tweetinvi code) and improved the json
Here is my updated code
Auth.SetUserCredentials(consumerKey, consumerSecret, userAccessToken, userAccessSecret);
var authenticatedUser = User.GetAuthenticatedUser();
var qString = JsonConvert.DeserializeObject("{ 'event': { 'type': 'message_create', 'message_create': { 'target': { 'recipient_id': '123456789' }, 'sender_id': '987654321', 'message_data': { 'text': 'option?', 'quick_reply': { 'type': 'options', 'options': [ { 'label': 'option 1', 'metadata': 'val1', 'description': 'option 2' }, { 'label': 'val2', 'metadata': 'option 3', 'description': 'val3' } ] } } } } }");
var strEncoded = WebUtility.HtmlEncode(qString.ToString());
var url = "https://api.twitter.com/1.1/direct_messages/events/new.json";
var result = TwitterAccessor.TryExecutePOSTQuery($"{url}?{strEncoded}");
Now I have error 401, with this description:
"Unauthorized - Authentication credentials were missing or incorrect."
Which is much better. Probably I just need to add credential headers using TwitterAccessor, but I need help about this.
I suppose that adding something TwitterAccessor. Method to create credentials headers before the post should do the job.

Related

Can't place GraphQL custom type as a Postman variable

Has anyone had luck with placing a GraphQL custom type argument as a Postman or Graphql variable? I'm kinda spinning in circles right now, I hope a fresh pair of eyes could point me in the right direction.
What I'm trying to do is to send a mutation request using Postman. The problem I'm having is that the method I'm calling is taking a custom type as an argument. Placing the content of that variable as GraphQL variable or Postman variable is giving me a headache. I can't embedd pictures yet, so here are the links (they are safe).
Schema
This custom type is a JSON-like structure, consisting of two enums and a set of primitive types (strings, ints...). I can screenshot the entire thing but basically that's it: two enums followed by strings, ints...
Custom type definition
What I've tried so far:
Simply hardcoding the request in Postman works but I wish to send multiple requests with varying data
Placing it in a GraphQL variable results in error message
{
"errors": [
{
"message": "Bad request - invalid request body.",
"locations": []
}
],
"data": null
}
Placing the custom type content as a Postman environment variable works, but I'm getting a syntax error (although the request passes...).
Request body is below. Hardcoding it and using a Postman variable produces the same request body, apart from the syntax error.
query: "mutation {
createApplication(request: {
applicationKind: NEW_ISSUANCE,
documentKind: REGULAR_PASSPORT,
personalData: {
timestamp: null,
firstname: "NAME",
lastname: "LASTNAME",
middlename: "MIDDLENAME",
dateOfBirth: "2011-09-28",
citizenshipCountryCode: "USA",
gender: MALE,
personalNumber: "3344",
placeOfBirth: "CHICAGO",
municipalityOfBirth: "SOUTH",
countryCodeOfBirth: "USA"},
addressData:{
street: "WEST",
municipality: "EAST",
place: "CHICAGO",
country: {
code: "USA",
name: null
},
entrance: "б",
flat: "13",
number: "35"}
})
{
__typename
... on AsyncTaskStatus {
taskID
state
payload {
... on ApplicationUpdated {
applicationID
applicationNumber
__typename
}
__typename
}
__typename
}
... on Error {
...errorData
__typename
}
}
}
fragment errorData on Error {
__typename
code
message
}"
Postman variable with a squiggly line
I'm spinning in circles right now. Has anyone had any luck with Postman requests of this kind?
I can post more info, screenshots...just let me know. I'll be watching this topic closely and provide feedback.
Thank you for your time.
please add a the variable in variable section as :
{
"request": {{request}}
}
and then refer this in your query as
$request

How can I send a POST request to start a password reset flow using axios

I'm implementing the Forgot password feature using truevault API. Now, I've been testing the requests following the flow with Postman, and it works, but, when I started coding using axios, it keeps throwing issues about authentication. I've tried several combinations (logical ones, not just random craziness).
Also, worth mentioning that I was able to list my truevault users from UI (not only postman), and tried to mimic the same principle to the post request, but it didn't work
Here is the postman request that worked for me:
for the url request, method is: POST
url: https://api.truevault.com/v1/password_reset_flows
For the Authorization tab, I filled the "username" field with the truevault user API Key, and left the "password" field empty
And the "Body" tab, I filled it with a Json text, and for radio button options, I selected raw, and picked json as the format. (these are the only tabs being used)
The json body is as follow
{
"name":"XXXXX password reset",
"sg_template_id":"XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXcf42",
"sg_api_key":"XX.XXXXXXXXXXXXXXXXXXXXXX.XXXXXX_XXXX_XXXXXXXXXXXXXXXXXXXXXXXXXXZftJo",
"user_email_value_spec":{
"system_field":"username"
},
"from_email_value_spec":{
"literal_value":"do-not-reply#XXXXXX.com"
},
"substitutions":{
"{{FIRST_NAME}}":{
"user_attribute":"first_name"
}
}
}
And the result was successful,
Now, when I tried with axios, I kept getting the auth error. Code is as follows:
createPasswordResetFlow()
{
axios.defaults.headers.common["Authorization"] = "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXX27"; //tv user API KEY
axios.defaults.headers.post["Content-Type"] = "application/json";
var request = axios.post("https://api.truevault.com/v1/password_reset_flows",
{
auth:
{
username: 'XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXX27',
password: ""
},
data:
{
"name": "XXXXX password reset",
"sg_template_id": "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXcf42",
"sg_api_key": "XX.XXXXXXXXXXXXXXXXXXXXXX.XXXXXX_XXXX_XXXXXXXXXXXXXXXXXXXXXXXXXXZftJo",
"user_email_value_spec":
{
"system_field": "username"
},
"from_email_value_spec":
{
"literal_value": "do-not-reply#XXXXXX.com"
},
"substitutions":
{
"{{FIRST_NAME}}":
{
"user_attribute": "first_name"
}
}
}
})
.then((res) =>
{
console.log(res);
return res.data.users;
})
.catch(error =>
{
console.log('error', error);
return error;
});
}
As mentioned also earlier, I've been researching and trying, but to no avail, if someone could help me please.
There are two issues with the JS code you shared which are causing the problem:
The line where you set the default Auth header looks like this: axios.defaults.headers.common["Authorization"] = "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXX27"; //tv user API KEY. Note that the Authorization header is being set to the API key, not an HTTP Basic Auth header value. If you want to set the default auth header this way, you need to set it to base64(API_KEY:) rather than just API_KEY.
According to the axios docs the post method has the signature .post(url, data, config). As a result, your code is POSTing a JSON object that looks like {auth: ..., data: ...}.
Try removing the line where you set the authorization header, and changing the post call to look something like this:
axios.post("https://api.truevault.com/v1/password_reset_flows",
{
"name": "XXXXX password reset",
"sg_template_id": "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXcf42",
"sg_api_key": "XX.XXXXXXXXXXXXXXXXXXXXXX.XXXXXX_XXXX_XXXXXXXXXXXXXXXXXXXXXXXXXXZftJo",
"user_email_value_spec":
{
"system_field": "username"
},
"from_email_value_spec":
{
"literal_value": "do-not-reply#XXXXXX.com"
},
"substitutions":
{
"{{FIRST_NAME}}":
{
"user_attribute": "first_name"
}
}
}
}, {
username: 'XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXX27',
password: ""
})

query params dependent on other query params in hapi-swagger

I am building a hapi-swagger interface to my api. One of the query params, type, has another query param subtype that depends on the former. I have figured out how to implement Joi validation for it successfully but am not so successful with the interface. My validation code is
{
type: Joi.string()
.valid('image', 'publication', 'dataset')
.optional(),
subtype: Joi.string()
.optional()
.when('type', {is: 'image', then: Joi.valid('png', 'jpg')})
.when('type', {is: 'publication', then: Joi.valid('newspaper', 'book')})
.description('subtype based on the file_type')
}
But the interface shows only png and jpg for subtype. Suggestions on how I could implement this so the correct subtype shows when the respective type is chosen?
I tried something similar and it works fine for me. Please checkout my code below:
Joi.object().keys({
billFormat: Joi.string().valid('sms', 'email').required(),
email: Joi.string()
.when('ebillFormat', { is: 'sms', then: Joi.valid('a', 'b') })
.when('ebillFormat', { is: 'email', then: Joi.valid('c', 'd') }),
});
And my payload looks like below:
{
"ebillFormat": "email",
"email": "hello"
}
The error I get is as follows:
{
"statusCode": 400,
"error": "Bad Request",
"message": "child \"email\" fails because [\"email\" must be one of [c, d]]",
"validation": {
"source": "payload",
"keys": [
"email"
]
}
}
Please let me know what exactly you are trying to achieve and what issue are you facing.

Cannot create batch work items using batch operations in TFS

I am getting below errors while trying to create workitems with batch creation method
Error 1
"Message":"No MediaTypeFormatter is available to read an object of type 'JsonBatchHttpRequest' from content with media type 'application/json-patch+json'."
Error 2
{"count":1,"value":{"Message":"One or more errors occurred."}}
I have referred to this documentation https://www.visualstudio.com/en-us/docs/integrate/api/wit/batch from Microsoft . and my question on stackoverflaw Create Large Amount of Work Items in TFS Using Javascript REST API
I have tried to send data as below methods
"json: x"
"body: x:"
"body:JSON.stringify(x)"
"json:[body:x]"
I have tried both "application/json-patch+json" and "application/json"(recommended as MIcrosoft documentation) as Content-Types
I have tired both Post (recommended as MIcrosoft documentation) and Patch methods
There is no references available for this error hence I have sucked at this point.What could be possibly wrong here please help..
public batchOperation( ):q.Promise<boolean>{
let deferred = q.defer<boolean>();
try {
var batchCreateUrl = this.collectionURL+"/_apis/wit/$batch?api-version=1.0";
var x= {
method:"PATCH",
uri:"/VSTS_TFS_Test/_apis/wit/workItems/$Bug?api-version=1.0",
headers:{
"Content-Type":"application/json-patch+json"
},
body:[
{ "op":"add",
"path": "/fields/System.Tags",
"value":"tg;tg1;tg2"
},
{
"op": "add",
"path": "/fields/System.Title",
"value": "Some Title Text "
},
{
"op": "add",
"path": "/fields/System.Description",
"value":"this is description"
}
]
}
var options = {
url: batchCreateUrl,
username: this.username,
password: this.password,
domain: this.domain,
method: 'PATCH',
headers: {
'Content-Type': 'application/json-patch+json'
},
body: x
};
httpntlm.patch(options, function(err,res) {
if(err) {
return deferred.reject(false);}
else{
console.log("Patch Complete");
console.log(res.body);
deferred.resolve(true);
}
});
} catch (error) {
console.log("Failed to Perform Batch Operation ")
deferred.reject(false);
}
return deferred.promise;
}
You need to use "application/json" as Content-Types and the post method just like the tutorial of Microsoft documentation described.
Since you are using httpntlm, you can include the following options:
json: if you want to send json directly (content-type is set to
application/json)
files: an object of files to upload (content-type is set to
multipart/form-data; boundary=xxx)
body: custom body content you want to send. If used, previous
options will be ignored and your custom body will be sent.
(content-type will not be set)
Source Link
If you are using body, your previous options will be ignored(content-type will lose), this may cause the issue. Give a try with directly using json.

full email validation on Meteor using Mandrill

I have read several SO posts about using Mandrill with Meteor.js for email validation, yet I've found a problem no others seem to face.
Ultimately, I want the verified property of a user to be set to true after clicking the email validation url. I am using Mandrill to send customized email templates containing a verification_url. I have the accounts-password and accounts-ui packages added. My code looks like this:
if (Meteor.isServer) {
Meteor.startup(function () {
Mandrill.config({
username: process.env.MANDRILL_API_USER,
key: process.env.MANDRILL_API_KEY
// port: 587, // defaults to 465 for SMTP over TLS
// host: 'smtp.mandrillapp.com', // the SMTP host
// baseUrl: 'https://mandrillapp.com/api/1.0/' // update this in case Mandrill changes its API endpoint URL or version
});
Accounts.config({
sendVerificationEmail: true
});
Accounts.emailTemplates.verifyEmail.html = function (user, url) {
var referralCode = Random.id();
var result;
try {
result = Mandrill.templates.render({
template_name: 'email-verification',
template_content: [],
merge_vars: [
{
name: 'SUBJECT',
content: 'my fancy subject'
},
{ name: 'EMAIL',
content: 'my fancy email'
},
{
name: 'VERIFICATION_URL',
content: 'http://localhost:3000/?ref=' + referralCode
}
]
});
} catch (error) {
console.error('Error while rendering Mandrill template', error);
}
return result.data.html;
};
});
When I create a user the verification email is correctly sent, however when I click the verification link within the email, nothing is done on the server, i.e. I look at my app's MongoDB and see on the user document still have the property verified: false. I've tried to work with onEmailVerificationLink (http://docs.meteor.com/#/full/Accounts-onEmailVerificationLink) but I get an error in the console saying onEmailVerificationLink has already been called, which happens because accounts-ui is apparently calling it for me. How do I do proper email verification in Meteor.js using Mandrill?
Finally figured it out. Instead of the line
content: 'http://localhost:3000/?ref=' + referralCode
I should replace it with
content: url
since Meteor is already creating the validation url for me, and passing it in through the "url" argument of the function. Clearly I didn't need referralCode either

Resources