All v4 Requests are Giving Error Code 403 (Forbidden) - python

I'm working with the Python Bit.ly API and trying to convert it to work with v4. Has anyone had any success with this? Specifically, I'm trying to pull the data for a user (specifically groups) which only v4 supports, so I cannot use the v3 API. This is the function (located in the bitly_api.py file):
def user_info(self, **kwargs):
"""return or update info about a user"""
#data = self._call_oauth2("v3/user/info", kwargs)
data = self._call_oauth2("v4/groups", kwargs)
return data
The #data = self.... line works correctly, but returns the wrong information. The next line gives me the forbidden error. Does anyone have any idea of what else might need to be changed?
Python API link: https://github.com/bitly/bitly-api-python

Related

Tweepy does not return includes object using StreamingClient

I am using tweepy 4.10.1 to fetch Tweets using StreamingClient, but I am unable to load any media info or even includes object itself. I have tried the similar code using get_tweet() method and media and includes were received fine.
The code:
class TweetPrinter(tweepy.StreamingClient):
def on_tweet(self, tweet):
print(tweet.includes)
streaming_client = TweetPrinter('bearer-token')
streaming_client.add_rules(tweepy.StreamRule("from:xxxyyy"))
streaming_client.filter(tweet_fields=['author_id', 'created_at'],
media_fields=['preview_image_url', 'url'],
expansions=['attachments.media_keys'])
print(tweet.includes)
I am receiving following error:
raise AttributeError from None
When I use the same tweet id with get_tweet() method, I can retrieve media from includes fine.
client = tweepy.Client(config.BEARER)
ID = 'xxxxyyyy'
tweet = client.get_tweet(ID,
tweet_fields=['author_id', 'created_at'],
media_fields=['preview_image_url', 'url'],
expansions=['attachments.media_keys'])
print(tweet.includes)
According to Google, official docs and FAQ, I have tried all recommended steps I found
Why am I not getting expansions or fields data with API v2 using Client?
tweepy.StreamingClient.filter allows media_fields and expansions
Tweepy does not return url media field while using Twitter API v2 methods
tweepy.StreamingClient.on_includes this valides that includes should be available
What am I missing here?
EDIT
I have discovered that using on_data() is the proper way how to retrieve all data from tweet. It covers all tweet, includes and other objects.
So the proper code should looks like this:
import orjson
class TweetPrinter(tweepy.StreamingClient):
def on_data(self, raw_data):
# Received as bytes, needs to be loaded by json (I use orjson)
raw_data = orjson.loads(raw_data)
print("data")
print(raw_data.get('data', None))
print("media")
print(raw_data.get('includes', None))
Deprecated solution
The TweetPrinter class should contain function to handle when includes received like this:
class TweetPrinter(tweepy.StreamingClient):
def on_tweet(self, tweet):
print(tweet.data)
def on_includes(self, includes):
print(includes)
Thanks to this article, it helped me to find the proper solution :)

How to get the status of the pull request of an issue in jira via python

I am not able to understand how to fetch the status of the pull request via Python jira API.
I have gone through https://jira.readthedocs.io/en/latest/examples.html,
and searched the internet for it. But I was not able to link the jira issue with the pull request, I saw that the pull request is linked to jira issue id, but was not able to understand how to implement it.
I am using python 3.7
from jira import JIRA
issue = auth_jira.issue('XYZ-000')
pull_request = issue.id.pullrequest
I am getting this error:
AttributeError: 'str' object has no attribute 'pullrequest'
I am not sure how to access pullrequest data in jira.
Any leads would help.
I did something similar with another python wrapper for the jira-API: atlassian-python-api.
Look if it works in your case:
from atlassian import Jira
from pprint import pprint
import json
jira = Jira(
url='https://your.jira.url',
username=user,
password=pwd)
issue = jira.get_issue(issue_key)
# get the custom field ref of the "Development" field (I don't know if it's always the same):
dev_field_string = issue["fields"]["customfield_13900"]
# the value of this field is a huge string containing a json, that we must parse ourselves:
json_str = dev_field_string.split("devSummaryJson=")[1][:-1]
# we load it with the json module (this ensures json is converted as dict, i.e. 'true' is interpreted as 'True'...)
devSummaryJson = json.loads(json_str)
# the value of interest are under cachedValue/summary:
dev_field_dic = devSummaryJson["cachedValue"]["summary"]
pprint(dev_field_dic)
# you can now access the status of your pull requests (actually only the last one):
print(dev_field_dic['pullrequest']['overall']['state'])

Using Slack RTM API with Django 2.0

I am a beginner to the Django framework and I am building a Django app that uses the Slack RTM API.
I have a coded a program in python that performs the OAuth authentication process like so :
def initialize():
url="https://slack.com/api/rtm.connect"
payload={"token":"xxx"}
r=requests.post(url,payload)
res=json.loads(r.text)
url1=res['url']
ws = create_connection(url1)
return ws
My Requirement:
The stream of events I receive (from my slack channel that my slack app is added to) is processed to filter out events of the type - message ,then match the message with a regex pattern and then store the matched string in a database.
As a stand alone python program I am receiving the stream of events from my channel.
My questions:
How do I successfully integrate this code to Django so that I can
fulfill my requirement?
Do I put the code in templates/views? What is the
recommended method to process this stream of data?
def initialize():
url = "https://slack.com/api/rtm.connect"
r = requests.get(url, params={'token': '<YOUR TOKEN>'})
res = r.json()
url1=res['url']
ws = create_connection(url1) #Note: There is no function called create_connnection() so it will raise an error
return ws
if you read the API web methods, you see :
Preferred HTTP method: GET
See here: Slack rtm.connect method
look at the comment, and thats the right code, see the differences between this code and yours.
basically to get JSON from a request don't use json.loads because this search your local computer not the request
use r.json() so it call the json you got from r.
Note that r.text will return raw text output so when you want to get url it will not be identified, with r.json you can call the object url as stated about
Hope this help.
and please could you tell us more what you wanna do with this in view ? because template is a directory which contains all the HTML files which you don't need to work with.
but why views.py ?

PyBingSearch Module: Bing API error

I am trying to use the PyBingSearch module from https://github.com/tristantao/py-bing-search to use the Bing API to return search results. In the github page they have an example of how to use it that goes.
from py_bing_search import PyBingWebSearch
search_term = "Python Software Foundation"
bing_web = PyBingWebSearch('Your-Api-Key-Here', search_term, web_only=False) # web_only is optional, but should be true to use your web only quota instead of your all purpose quota
first_fifty_result= bing_web.search(limit=50, format='json') #1-50
When I try and run the line that declares first_fifity_result I get an error stating Request returned with code 401, error msg: The authorization type you provided is not supported. Only Basic and OAuth are supported
Why do I get this error? In my code I made sure to change Your-Api-Key-Here to my API key.
Did you swap your API key? Where is says "Your-API-Key-Here"
bing_web = PyBingWebSearch('Your-Api-Key-Here', search_term, web_only=False) # web_only is optional, but should be true to use your web only quota instead of your all purpose quota

Boto method for Amazon MWS GetLowestPricedOffersForSKU

Boto provides access to most Amazon MWS APIs, but not for GetLowestPricedOffersForSKU. I tried to hack one, but it generates an Invalid MarketplaceId error.
Boto has code for a very similarly structured API -- GetLowestOfferListingsForSKU:
#requires(['MarketplaceId', 'SellerSKUList'])
#structured_lists('SellerSKUList.SellerSKU')
#api_action('Products', 20, 5, 'GetLowestOfferListingsForSKU')
def get_lowest_offer_listings_for_sku(self, request, response, **kw):
"""Returns the lowest price offer listings for a specific
product by item condition and SellerSKUs.
"""
return self._post_request(request, kw, response)
So I modified the #api_action to change the MWS Operation to GetLowestPricedOffersForSKU:
### MINE ###
#requires(['MarketplaceId', 'SellerSKUList'])
#structured_lists('SellerSKUList.SellerSKU')
#api_action('Products', 20, 5, 'GetLowestPricedOffersForSKU')
def get_lowest_priced_offers_for_sku(self, request, response, **kw):
return self._post_request(request, kw, response)
I call this method as follows:
conn = connection.MWSConnection(
aws_access_key_id=ACCESS_KEY,
aws_secret_access_key=SECRET_KEY,
Merchant=ACCOUNT_ID
)
response = conn.get_lowest_priced_offers_for_sku(
MarketplaceId=marketplace_id, SellerSKUList=sku_list, ItemCondition=condition
)
When I call get_lowest_priced_offers_for_sku, I get an Invalid MarketplaceId error. If the only change I make is to call get_lowest_offer_listings_for_sku -- leaving every variable identical -- the code works find and return a valid response object. This works just fine:
response = conn.get_lowest_offer_listings_for_sku(
MarketplaceId=marketplace_id, SellerSKUList=sku_list, ItemCondition=condition
)
What do I need to do to access the Amazon MWS GetLowestPricedOffersForSKU via boto?
Not sure and neither I am python programmer, but In PHP AmazonMWS API I use code below where I use setMarketplaceId()
$request = new MarketplaceWebServiceProducts_Model_GetLowestPricedOffersForSKURequest();
$request->setSellerId($this->seller_id);
$request->setMarketplaceId($this->marketplace_id);
$request->setItemCondition("New");
Boto2 doesnt support GetLowestPricedOffersForSKU as you can see from the documentation http://docs.pythonboto.org/en/latest/ref/mws.html

Categories