Resolve Discord-Tag get Discord-ID programmatically - api

I want to add a function to my userprofiles where users can enter their discord tag and if they do so, I want to resolve this to a link to their discordprofile so that users only have to click on the discordtag to open the profile in discord.
For that I need the ID. What Request do I need to send to the discord api in order to get the user ID for the entered tag?

After some experiments with discord friend sending. I found out that you can actually obtain user the user ID by sending friend request.
Here's how:
Make a add request friend request to example#1234
Make another request to the relationship(AKA friend) list to get all pending "friends" with ID, username, avatar... This list actually contains all of the actual friends from the person that sent a friend request.
To find the requested username in the friend list, all you need is a loop searching for the corresponding username + discriminator.
Output the ID(if that's what you wanted), after the username and discriminator match.
Delete the pending request.
Here's a python script I wrote that will output the ID of the user with inputs of username, discriminator, and an user token(used for sending an authorized friend request):
import requests
import json
# inputs
username = 'asdf'
discriminator = '1234'
TOKEN = 'ONLY USER TOKEN'
url = 'https://discord.com/api/v8/users/#me/relationships'
headers = {
"authorization": TOKEN
}
# setting up a payload for sending friend request.
payload = {
'username': username,
'discriminator': discriminator
}
requests.post(url, json=payload, headers=headers) # step 1
result = requests.get(url, headers=headers).json() # step 2
if hasattr(result, 'message'):
print('Invalid user token')
else:
user_id = None
for client in result: # step 3: a loop for finding the the username in the friend list
if f'{client["user"]["username"]}#{client["user"]["discriminator"]}' == f'{username}#{discriminator}':
user_id = client['id'] # step 4: save the user ID after finding it in the friend list
break
if user_id is None: # if no match is found then the user with that username and discriminator does not exist.
print('user not found')
else:
url = f'https://discord.com/api/v8/users/#me/relationships/{user_id}'
requests.delete(url, headers=headers) # step 5: delete the pending request
print(user_id) # print out the user ID
And here's the data structure of the requested json from step 2:
[
{
"id": "12345678901",
"type": 1,
"nickname": null,
"user": {
"id": "12345678901",
"username": "example1",
"avatar": "1234567890abcdef",
"discriminator": "1234",
"public_flags": 123
}
},
{
"id": "12345678902",
"type": 1,
"nickname": null,
"user": {
"id": "12345678902",
"username": "example2",
"avatar": "1234567890abcdef",
"discriminator": "1234",
"public_flags": 123
}
},
{
"id": "12345678903",
"type": 1,
"nickname": null,
"user": {
"id": "12345678903",
"username": "example3",
"avatar": "1234567890abcdef",
"discriminator": "1234",
"public_flags": 123
}
}
]
Downside:
You have to use an user token for sending the friend request.
Updates:
10/4/2020: Added in error detection for invalid token and invalid username.

Related

AWS Cognito: How to get the user pool username form an identity ID of an identity pool?

We allow our users to upload data to a S3 bucket, which then triggers a Python lambda which again updates a DynamoDB entry based on the uploaded file. In the lambda, we struggle to get the username of the user who put the item. Since the Lambda is triggered by the put event from the S3 storage, we don't have the authorizer information available in the request context. The username is required as it needs to be part of the database record.
Here some more background: Every user should only have access to her own files, so we use this IAM policy (created with CDK):
new iam.PolicyStatement({
effect: iam.Effect.ALLOW,
actions: ['s3:PutObject', 's3:GetObject'],
resources: [
bucket.arnForObjects(
'private/${cognito-identity.amazonaws.com:sub}/*'
),
],
})
Since the IAM policy validates the cognito-identity.amazonaws.com:sub field (which translates to the identity ID) we should be able to trust this value. This is the Python lambda and an example of a record we receive:
import json
import boto3
'''
{
"Records": [
{
"eventVersion": "2.1",
"eventSource": "aws:s3",
"awsRegion": "my-region-1",
"eventTime": "2023-02-13T19:50:56.886Z",
"eventName": "ObjectCreated:Put",
"userIdentity": {
"principalId": "AWS:XXXX:CognitoIdentityCredentials"
},
"requestParameters": {
"sourceIPAddress": "XXX"
},
"responseElements": {
"x-amz-request-id": "XXX",
"x-amz-id-2": "XX"
},
"s3": {
"s3SchemaVersion": "1.0",
"configurationId": "XXX",
"bucket": {
"name": "XXX",
"ownerIdentity": {
"principalId": "XXX"
},
"arn": "arn:aws:s3:::XXX"
},
"object": {
"key": "private/my-region-1%00000000-0000-0000-0000-000000000/my-file",
"size": 123,
"eTag": "XXX",
"sequencer": "XXX"
}
}
}
]
}
'''
print('Loading function')
dynamodb = boto3.client('dynamodb')
cognito = boto3.client('cognito-idp')
cognito_id = boto3.client('cognito-identity')
print("Created clients")
def handler(event, context):
# context.identity returns None
print("Received event: " + json.dumps(event, indent=2))
for record in event['Records']:
time = record['eventTime']
key = record['s3']['object']['key']
identityId = key.split('/')[1]
# How to get the username from the identityId?
return "Done"
Things we tried:
Try to find an alternative to cognito-identity.amazonaws.com:sub which validates the username, but from the documentation there is no option for that
Encode the username in the bucket key, but this opens a security hole as then a client can pretend to have a different username
Make a lookup with https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/cognito-identity.html to find the username for an identity ID, but so far we haven't found anything there
Tried to follow How to get user attributes (username, email, etc.) using cognito identity id, but in the Lambda we don't have an ID or access token available
Getting cognito user pool username from cognito identity pool identityId, but since the Lambda is triggered by a S3 put event, we don't have an authorizer context
We could store the identity ID as custom attribute of every Cognito user (as suggested here How to map Cognito (federated) identity ID to Cognito user pool ID?), but before I do that I would like to be sure that there isn't a better option as I fear that the duplication of this information could lead to issues in the long run.

Add value to select list in Jira cloud using python and API

I'm trying to add new values to a multiple select custom field.
I'm getting 401 response.
The code taken from Atlassian documentation .
Anyone knows why? maybe it is something with the authentication method?
import requests
from requests.auth import HTTPBasicAuth
import json
customers_id = "10163"
contextId = "int64"
url = "https://MY_DOMAIN.atlassian.net/rest/api/3/field/{customers_id}/context/{contextId}/option"
auth = HTTPBasicAuth("MY_EMAIL", "MY_API_TOKEN")
headers = {
"Accept": "application/json",
"Content-Type": "application/json"
}
payload = json.dumps( {
"options": [
{
"disabled": "false",
"value": "Manhattan"
},
{
"disabled": "false",
"value": "The Electric City"
}
]
} )
response = requests.request(
"POST",
url,
data=payload,
headers=headers,
auth=auth
)
print(json.dumps(json.loads(response.text), sort_keys=True, indent=4, separators=(",",": ")))
You have "int64" which is a string, it should be 12345 or whatever your contextID is.
There might be something else going on here also:
401 is Returned if the authentication credentials are incorrect or missing.
Is this your own Jira Cloud instance or one managed by someone else as you need the following permissions - Permissions required: Administer Jira global permission. So you may not have sufficient rights to make this call?

<title>404 - File or directory not found.</title> in Karate for swagger api [duplicate]

I have an endpoint URL, within Swagger I must pass certain fields to test the POST method. I was wondering if anyone had an example of how to set up a Karate test for a POST method?
Yes, there are plenty in the documentation: https://github.com/intuit/karate
If you follow the quickstart, you will get a sample project with a working POST: https://github.com/intuit/karate#quickstart
Scenario: create a user and then get it by id
* def user =
"""
{
"name": "Test User",
"username": "testuser",
"email": "test#user.com",
"address": {
"street": "Has No Name",
"suite": "Apt. 123",
"city": "Electri",
"zipcode": "54321-6789"
}
}
"""
Given url 'https://jsonplaceholder.typicode.com/users'
And request user
When method post
Then status 201

url to access data from foursquare API does not work

I want to access data throughthe foursquare API using the foursquare ID of a given establishement. I have the following data:
client_ip = "AAA"
client_secret = "BBB"
id_place = "4c4192d5d7fad13a8cb807da"
Why the next URL does not access the data for this particular establishment?
https://api.foursquare.com/v2/venues/explore?client_id=AAA&client_secret=BBB/4c4192d5d7fad13a8cb807da
What I get is the following
{
"meta": {
"code": 400,
"errorType": "invalid_auth",
"errorDetail": "Missing access credentials. See https://developer.foursquare.com/docs/oauth.html for details.",
"requestId": "5900bcf84c1f6734f1ee6b02"
},
"response": {}
}
You should read through the Foursquare documentation on venue details. Your request is not formatted correctly.
The following request should get you the details for that venue:
https://api.foursquare.com/v2/venues/4c4192d5d7fad13a8cb807da?client_id=AAA&client_secret=BBB&v=20170101

Foursquare API - Tastes

When I try to send a GET request to Foursquare API below, I get "No matching endpoint." error.
I have validated my tokens and everything seems normal. Any advices?
REQUEST URL
https://api.foursquare.com/v2/users/USER_ID/tastes
RESPONSE MESSAGE
{
"meta": {
"code": 404,
"errorType": "endpoint_error",
"errorDetail": "No matching endpoint"
},
"notifications": [
{
"type": "notificationTray",
"item": {
"unreadCount": 0
}
}
],
"response": {}
}
FoursquareAPI twitter account has told me that I needed to pass m=foursquare in addition to version information.
The correct endpoint information is like
https://api.foursquare.com/v2/users/USER_ID/tastes?oauth_token=TOKEN&v=20150420&m=foursquare
The detailed information about v and m parameters are below.
https://developer.foursquare.com/overview/versioning