Python - Error in authorized client request - python

Create an "authorized_token" Token object and use that to perform Twitter API calls on behalf of user
authorized_token = oauth2.Token(access_token['oauth_token'], access_token['oauth_token_secret'])
authorized_client = oauth2.Client(consumer, authorized_token)
Make Twitter API calls!
response, content = authorized_client.request('https://api.twitter.com/1.1/search/tweets.json?q=computers+filter:images', 'GET')
if response.status != 200:
print("An error occurred when searching!")
print(content.decode('utf-8'))
Error -
Exception has occurred: AttributeError 'list' object has no attribute
'encode'
The error indicates the following code
response, content = authorized_client.request('https://api.twitter.com/1.1/search/tweets.json?q=computers+filter:images', 'GET')
Someone can explain to me why?

Related

Twitter API throws error : 'API' object has no attribute 'search'

The following code I wrote was intended to retweet tweets with #programming. But, anything I run the code I get an error "search" object is not an attribute of the Twitter API. The error is posted below the code. Thanks
import tweepy
import time
# get api code and password(secret)
comsumers_key = '#########'
comsumers_secret = '######'
token_key = '#########'
token_secret = '###########'
auth = tweepy.OAuthHandler(comsumers_key,comsumers_secret)
auth.set_access_token(token_key, token_secret)
api = tweepy.API(auth)
hashtag = "programming"
tweetNum = 20
tweets = tweepy.Cursor(api.search, hashtag).items(tweetNum)
def bot1():
for tweet in tweets:
try:
tweet.retweet()
print("retweet")
time.sleep(50)
except tweepy.TweepError as e:
print(e.reason)
time.strftime(20)
bot1()
error:
Traceback (most recent call last):
File "/Users/sonter/tweetbot/bot1.py", line 48, in <module>
tweets = tweepy.Cursor(api.search, hashtag).items(tweetNum)
AttributeError: 'API' object has no attribute 'search'
The Cursor expects a regular api method, but looking at its reference doc there is no search only, but :
search_30_day
search_full_archive
search_tweets
search_users
search_geo
Maybe you meant one of them ?

AttributeError in MessageFwdHeader telethon library

I'm getting AttributeError in my code. How can I fix it please
from telethon import events
#client.on(events.NewMessage(func=lambda e: e.is_private))
async def _(event):
x = await event.get_reply_message()
if x is None:
return
send = event.raw_text
who = event.sender_id
if x.fwd_from:
user = x.fwd_from.sender_id.user_id
else:
return
Error:
Line 11: AttributeError: 'MessageFwdHeader' object has no attribute 'sender_id'
the AttributeError usually use a not existence attribute ,check the object Attribute.
According to this and this in the docs it is possible to get the original sender ID like: message.forward.sender_id. By the way the result will be None if the sender's profile was hidden or that was a channel repost.

Python: Getting a sudden HttpError 500: "Internal error encountered"

This is my first project using API's so apologies if this is a silly question to ask!
I've written some code that has an input of a playlist url from Spotify. It then creates a new playlist on YouTube and adds the songs from the Spotify playlist into the YouTube one.
I had just got it to work perfectly. Then all I did was input a new Spotify url and it started giving me this error which I can't get rid of.
HttpError: <HttpError 500 when requesting https://www.googleapis.com/youtube/v3/playlists?part=snippet%2Cstatus&alt=json returned "Internal error encountered.">
Could anyone tell me what the problem is? Thanks so much!
**EDIT: I went to the location of the error and this is the bit of code that is giving the error (I didn't write this bit, this is from HTTP requests)
def execute(self, http=None, num_retries=0):
"""Execute the request.
Args:
http: httplib2.Http, an http object to be used in place of the
one the HttpRequest request object was constructed with.
num_retries: Integer, number of times to retry with randomized
exponential backoff. If all retries fail, the raised HttpError
represents the last request. If zero (default), we attempt the
request only once.
Returns:
A deserialized object model of the response body as determined
by the postproc.
Raises:
googleapiclient.errors.HttpError if the response was not a 2xx.
httplib2.HttpLib2Error if a transport error has occurred.
"""
if http is None:
http = self.http
if self.resumable:
body = None
while body is None:
_, body = self.next_chunk(http=http, num_retries=num_retries)
return body
# Non-resumable case.
if "content-length" not in self.headers:
self.headers["content-length"] = str(self.body_size)
# If the request URI is too long then turn it into a POST request.
# Assume that a GET request never contains a request body.
if len(self.uri) > MAX_URI_LENGTH and self.method == "GET":
self.method = "POST"
self.headers["x-http-method-override"] = "GET"
self.headers["content-type"] = "application/x-www-form-urlencoded"
parsed = urlparse(self.uri)
self.uri = urlunparse(
(parsed.scheme, parsed.netloc, parsed.path, parsed.params, None, None)
)
self.body = parsed.query
self.headers["content-length"] = str(len(self.body))
# Handle retries for server-side errors.
resp, content = _retry_request(
http,
num_retries,
"request",
self._sleep,
self._rand,
str(self.uri),
method=str(self.method),
body=self.body,
headers=self.headers,
)
for callback in self.response_callbacks:
callback(resp)
if resp.status >= 300:
raise HttpError(resp, content, uri=self.uri)
return self.postproc(resp, content)

Couldn't find Consumer method in oauth2

I am trying to connect to twitter api using oauth2. But the code is not working as it shows the error AttributeError: 'module' object has no attribute 'Consumer'
Is there any update in the oauth2 package? If there is, then what is the another way to do same?
def oauth_req(self, url, http_method="GET", post_body=None,
http_headers=None):`enter code here`
config = self.parse_config()
consumer = oauth.Consumer(key=config.get('consumer_key'), secret=config.get('consumer_secret'))
token = oauth.Token(key=config.get('access_token'), secret=config.get('access_token_secret'))
client = oauth.Client(consumer, token)
resp, content = client.request(
url,
method=http_method,
body=post_body or '',
headers=http_headers
)
return content
Any help would be really appreciated. Thanks in advance!

'module' object is not subscriptable

here is very simplified version of my code , so pleas ignore syntax errors
i have a helper function basically reading a row from database using django orm and doing some validation finally return it using a dictionary
modVerify.py
def verify(request):
try :
req = Request.objects.get(id=request.POST.get('id'))
except :
return({'stat':'er' , 'error':-12})
return({'stat':'ok' , 'req':req})
here is where i get the error when im trying to use this above app
import modVerify.view
def verify(request):
result = modVerify.views.verify(request )
if(result['status'] == 'ok'):
req = modeVerify['req']
else :
print('ERROR !')
here is my error
TypeError at /api/verify
'module' object is not subscriptable
Request Method: POST
Request URL: site.com/api/verify
Django Version: 1.9.7
Exception Type: TypeError
Exception Value:
'module' object is not subscriptable
Exception Location: /home/somedomain/project/api/views.py in verify, line 98
Python Executable: /usr/local/bin/python3
Python Version: 3.4.4
which points to this line
req = modeVerify['req']
so why im getting this and is there a way around it or should i return row id back instead and read it again from database in the caller function ?
It seems like you should be doing
req = result['req']
instead of
req = modeVerify['req']

Categories

Resources