twitter.search() query giving error in ipython - twitter

I am quite new to the concept of ipython and twython .However i want to retrieve some data using twitter.search query .But when i use it it gives me the following error
In [3]: search_results = twitter.search(q="#india", rpp="50")
---------------------------------------------------------------------------
TwythonError Traceback (most recent call last)
/home/vishal/<ipython-input-3-241f789b11cc> in <module>()
----> 1 search_results = twitter.search(q="#india", rpp="50")
/usr/local/lib/python2.7/dist-packages/twython-2.5.5-py2.7.egg/twython/twython.pyc in search(self, **kwargs)
365 """
366
--> 367 return self.get('https://api.twitter.com/1.1/search/tweets.json', params=kwargs)
368
369 def searchGen(self, search_query, **kwargs):
/usr/local/lib/python2.7/dist-packages/twython-2.5.5-py2.7.egg/twython/twython.pyc in get(self, endpoint, params, version)
236
237 def get(self, endpoint, params=None, version='1.1'):
--> 238 return self.request(endpoint, params=params, version=version)
239
240 def post(self, endpoint, params=None, files=None, version='1.1'):
/usr/local/lib/python2.7/dist-packages/twython-2.5.5-py2.7.egg/twython/twython.pyc in request(self, endpoint, method, params, files, version)
231 url = '%s/%s.json' % (self.api_url % version, endpoint)
232
--> 233 content = self._request(url, method=method, params=params, files=files, api_call=url)
234
235 return content
/usr/local/lib/python2.7/dist-packages/twython-2.5.5-py2.7.egg/twython/twython.pyc in _request(self, url, method, params, files, api_call)
208 raise exceptionType(error_msg,
209 error_code=response.status_code,
--> 210 retry_after=response.headers.get('retry-after'))
211
212 # if we have a json error here, then it's not an official TwitterAPI error
TwythonError: 'Bad Request: The request was invalid. An accompanying error message will explain why. This is the status code will be returned during rate limiting. -- An error occurred processing your request
what could be the issue.
Does it requires authentication
Thanks

Twitter API v1 search didn't not need authentication, however; the Twitter search API now requires authentication in v1.1. (https://dev.twitter.com/docs/api/1.1/get/search/tweets)
Thanks for using Twython!

For me this code works:
from twython import Twython
twitter = Twython()
search_results = twitter.search(q="#india", rpp="50")
for tweet in search_results["results"]:
print "Tweet from#%s Date: %s" % (tweet['from_user'].encode('utf-8'),tweet['created_at'])
print tweet['text'].encode('utf-8'),"\n"

Related

Where do i set up the OTRS redirect URI for oAuth?

i'm trying to set up oAUT for incomingen mails in OTRS CE 6.
I completed the setup steps discribed in the manual https://otrscommunityedition.com/news/2022-10-28/o-auth2-authentication-for-email-accounts-in-otrs-ce/
But when authenticating I get the following:
Request Id: 2612ca88-32c6-40b2-b20e-..........
Correlation Id: 42440fe1-a06e-47a6-.........
Timestamp: 2022-11-04T15:53:04Z
Message: AADSTS50011: The redirect URI 'http://_______.________.be/otrs/get-oauth2-token-by-authorization-code.pl' specified in the request does not match the redirect URIs configured for the application '99fe24c1-036a-4e31-b80a-5dce3220fef3'. Make sure the redirect URI sent in the request matches one added to your application in the Azure portal. Navigate to https://aka.ms/redirectUriMismatchError to learn more about how to fix this.
It seems to redirect to http instead of https. But when i change the url to https it still does not work.
Backend ERROR: OTRS-CGI-20 Perl: 5.26.1 OS: linux Time: Mon Nov 7 10:10:28 2022
Message: Failed to get response for token request by authorization code for OAuth2 token configuration with ID 1.
RemoteAddress: 109.135.15.48
RequestURI: /otrs/get-oauth2-token-by-authorization-code.pl?code=0.ATsAKmbiQA8SC0-TSPotY_1GiMEk_plqAzFOuApdzjIg_vM7AI4.AgABAAIAAAD--DLA3VO7QrddgJg7WevrAgDs_wQA9P-lFxUR0K8wRyUgurdKYmyVfbMWKTtnfp5Vja-sFQUlkJvPTpV6JQPBpqOQGFp8vjKJ9fwnnqTbppSVODOTUzBuIsO3UbeeqRysUEIILvS6hfSdkxES8rG_BxS7eUZOgyRd_ZP8efnhejl51L_4DABMkLJ83Z4QG_p0xQBTcmoMRBwpNMHG5cuNRctvHnaC87SLx2snqTJ8olb8D5oWid1xcFpx68urHjH68-ALJ5BVW9dKtmqjgkWJSG4yoK9NQvxJk-wD_uzihUdTTPhsibv8G0Q-tlToaOgdnoOApFBRPb9YpG1oukfo5wfHVBuObcppyQqPO12iSPTwiiDR4xOTtbcydmS3cn8xqs0N2_ivCha1cUIUMb4_1XzzcWEWBZGejsQs5nYEKAurVeLhv8quZ5wLIn1H9bVYSmmQKe61H4XwFBAuLinv2BttuqSmA29wfSl6TG_HAuWBHCZ5FfFswrsg-0j889LHMi-cWwe16nWcLg2er6sDsugYDGL4d_8C2MQ9lZB7SqDcCG5UYP7vmxN6HEQzlTjsOSZuonjt6vP1SJb4PpjYQ-EKb9Dn0Zppi46G5hValc_CGfMGZNkT3lHaZVhek5nh5VOtjUKaJVP08n3rHcplpWPMNwRWgBcME0UshUhimePLwolXUmY1rVreIl8_i2V3q0JcfWBv-xYipirn80yt3VplfdEchcJPS_fglC2nSBTf7J0y_M5n-YqvJIctkHX8ZuSTvpcL8CwOSIRe9MbNbwc9xjmP9buOMMCEloZZjCwAslXbnetaefarfExS0evW8ME&state=ConfigID1&session_state=c69356ad-cdd3-4fc7-a7d4-b756f5134ac7
Traceback (14240):
Module: Kernel::System::OAuth2Token::RequestTokenByAuthorizationCode Line: 776
Module: Kernel::Modules::AdminOAuth2TokenConfig::_RequestTokenByAuthorizationCode Line: 410
Module: Kernel::Modules::AdminOAuth2TokenConfig::Run Line: 52
Module: Kernel::System::Web::InterfaceAgent::Run Line: 1172
Module: ModPerl::ROOT::ModPerl::Registry::opt_otrs_bin_cgi_2dbin_get_2doauth2_2dtoken_2dby_2dauthorization_2dcode_2epl::handler Line: 50
Module: (eval) (v1.99) Line: 207
Module: ModPerl::RegistryCooker::run (v1.99) Line: 207
Module: ModPerl::RegistryCooker::default_handler (v1.99) Line: 173
Module: ModPerl::Registry::handler (v1.99) Line: 32
How can i fix this?
Best regards,
Tim
I have the same error from hour production OTRS.
After configuring OTRS for HTTPS (OTRS force HTTPS + Apache), I had to modify the file /opt/otrs/Kernel/Config.pm and add the line :
$Self->{HttpType} = 'https';
(within the my "sub Load {...}" part).
Then I requested a new token, this in the URL, I had the corrected "https://" and the token request finally successed !
Hope it will help you.

EOFError: end of file reached calling a SOAP API via Savon ruby client

The mentioned error comes calling an API behind a firewall but and I am trying to access the API from an EngineYard instance. The EngineYard instances IPs are white listed in their firewall.
client = Savon.client(wsdl: "https://amagentostore.com/api/v2_soap?wsdl", read_timeout: 300, follow_redirects: true)
products = client.
call(:dcapimodule_product_list, message: { session_id: session_id, additional_attributes: #additional_attributes }).
body[:dcapimodule_product_list_response][:products][:item]
I get the following error
File "/usr/lib64/ruby/2.3.0/openssl/buffering.rb" line 178 in sysread_nonblock
File "/usr/lib64/ruby/2.3.0/openssl/buffering.rb" line 178 in read_nonblock
File "/data/feed_champion/shared/bundled_gems/ruby/2.3.0/gems/excon-0.59.0/lib/excon/socket.rb" line 46 in readline
File "/data/feed_champion/shared/bundled_gems/ruby/2.3.0/gems/excon-0.59.0/lib/excon/response.rb" line 63 in parse
File "/data/feed_champion/shared/bundled_gems/ruby/2.3.0/gems/excon-0.59.0/lib/excon/middlewares/response_parser.rb" line 7 in response_call
File "/data/feed_champion/shared/bundled_gems/ruby/2.3.0/gems/excon-0.59.0/lib/excon/connection.rb" line 389 in response
File "/data/feed_champion/shared/bundled_gems/ruby/2.3.0/gems/excon-0.59.0/lib/excon/connection.rb" line 253 in request
File "/data/feed_champion/shared/bundled_gems/ruby/2.3.0/gems/excon-0.59.0/lib/excon/connection.rb" line 314 in post
File "/data/feed_champion/shared/bundled_gems/ruby/2.3.0/gems/httpi-2.4.2/lib/httpi/adapter/excon.rb" line 25 in request
File "/data/feed_champion/shared/bundled_gems/ruby/2.3.0/gems/httpi-2.4.2/lib/httpi.rb" line 161 in request
File "/data/feed_champion/shared/bundled_gems/ruby/2.3.0/gems/httpi-2.4.2/lib/httpi.rb" line 133 in post
File "/data/feed_champion/shared/bundled_gems/ruby/2.3.0/gems/savon-2.11.2/lib/savon/operation.rb" line 94 in block in call_with_logging
File "/data/feed_champion/shared/bundled_gems/ruby/2.3.0/gems/savon-2.11.2/lib/savon/request_logger.rb" line 12 in log
File "/data/feed_champion/shared/bundled_gems/ruby/2.3.0/gems/savon-2.11.2/lib/savon/operation.rb" line 94 in call_with_logging
File "/data/feed_champion/shared/bundled_gems/ruby/2.3.0/gems/savon-2.11.2/lib/savon/operation.rb" line 54 in call
File "/data/feed_champion/shared/bundled_gems/ruby/2.3.0/gems/savon-2.11.2/lib/savon/client.rb" line 36 in call
File "/data/feed_champion/releases/20180110042633/app/services/magento/product.rb" line 84 in products
Any idea?
The problem was #additional_attributes was being nil while the WSDL was expecting an array.

How to send a request to twitter using a proxy?

I'm trying to extract data from twitter. When I use the code in my home network, it works very well, but in my university we use a proxy server. So I need to configure the request. I'm not specialised on computer science, so I don't know how to modify the request.
I read the documentation in https://dev.twitter.com/ but I couldn't find a solution!
This is an exemple of code :
import tweepy
from tweepy import OAuthHandler
consumer_key = 'XXXXXXXXXX'
consumer_secret = 'XXXXXXXXXXXX'
access_token = 'XXXXXXXXXXXXXXXXXXXX'
access_secret = 'XXXXXXXXXXXXXXXXXXXXXXXXXXX'
auth = OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_secret)
api = tweepy.API(auth)
for status in tweepy.Cursor(api.home_timeline).items(100):
# Process a single status
print(status.text)
This is the error I got:
Traceback (most recent call last):
File "D:\formation\python\github tools\fbp.py", line 14, in <module>
for status in tweepy.Cursor(api.home_timeline).items(100):
File "C:\Anaconda\lib\site-packages\tweepy\cursor.py", line 197, in next
self.current_page = self.page_iterator.next()
File "C:\Anaconda\lib\site-packages\tweepy\cursor.py", line 108, in next
data = self.method(max_id=self.max_id, parser=RawParser(), *self.args, **self.kargs)
File "C:\Anaconda\lib\site-packages\tweepy\binder.py", line 245, in _call
return method.execute()
File "C:\Anaconda\lib\site-packages\tweepy\binder.py", line 189, in execute
raise TweepError('Failed to send request: %s' % e)
TweepError: Failed to send request: HTTPSConnectionPool(host='api.twitter.com', port=443): Max retries exceeded with url: /1.1/statuses/home_timeline.json (Caused by ProxyError('Cannot connect to proxy.', error('Tunnel connection failed: 407 Authentification proxy requise',)))
You can add a proxy using the follow code:
api =tweepy.API(auth,proxy="127.0.0.1:1080")
It works on my computer. You can try to modify you code like this.

Event Sync Token (412 response status )

I'm using RestTemplate to make the GET call to asana's REST Api.
By using postmen when i'm calling:
https://app.asana.com/api/1.0/events?resource=PROJECT_ID
I'm getting a message and a sync token ( this is the same case when the sync token is too old and needs to be renewed ).
By using the RestTemplate, when the sync token is too old \ its the first call i'm making and I need a sync token, I'm getting a 412 response "Prediction Faild".
This happens also in postman, but i'm getting along with the "error" message the new sync token.
With the RestTemplate all i'm getting is this error:
Aug 06, 2015 3:56:55 PM org.springframework.web.client.RestTemplate handleResponseError
WARNING: GET request foPROJECT_ID21650756795165" resulted in 412 (Precondition Failed); invoking error handler
Exception in thread "main" org.springframework.web.client.HttpClientErrorException: 412 Precondition Failed
at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:90)
at org.springframework.web.client.RestTemplate.handleResponseError(RestTemplate.java:494)
at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:451)
at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:409)
at org.springframework.web.client.RestTemplate.exchange(RestTemplate.java:385)
at availo.worker.asana.MainTask.getEvents(MainTask.java:86)
at availo.worker.asana.MainTask.getProjects(MainTask.java:76)
at availo.worker.asana.MainTask.main(MainTask.java:115)
Any suggestions?
Thanks!
This worked for me. It lets you read the message that comes with the error:
restTemplate.setErrorHandler(new DefaultResponseErrorHandler(){
protected boolean hasError(HttpStatus statusCode) {
return false;
}});
When first subscribing to Events on a resource you will receive a 412 Precondition Failed response code due to the fact that there is no sync token established yet. You should extract that sync token and use it in your next request to begin receiving events.
It looks like RestTemplate is invoking an error handler due to the 412 response code, which is understandable as a 412 is an error code.
If you can override DefaultResponseErrorHandler.handleError(), check that the response is a 412, then extract the sync token you could pass that in your next request to get events on the resource.
Another option is to use our Java client library, which should handle all of this for you.
This is what it might look like using our client:
System.out.println("Watching for events on project: " + project.name);
for (Event event : client.events.get(project.id)) {
System.out.println("User: " + event.user.name + "\nAction: " + event.action + "\nResource: " + event.resource);
}

Probe auth on Github with DotNetOpenAuth 3.5.0 library

Unexpected response Content-Type text/html
DotNetOpenAuth.DLL!DotNetOpenAuth.Messaging.ErrorUtilities.VerifyProtocol(bool condition, string message, object[] args) Line 237 C#
DotNetOpenAuth.DLL!DotNetOpenAuth.Messaging.ErrorUtilities.ThrowProtocol(string message, object[] args) Line 257 C#
DotNetOpenAuth.DLL!DotNetOpenAuth.OAuth2.ChannelElements.OAuth2ClientChannel.ReadFromResponseCore(DotNetOpenAuth.Messaging.IncomingWebResponse response) Line 67 + 0x1a4 bytes C#
DotNetOpenAuth.DLL!DotNetOpenAuth.Messaging.Channel.RequestCore(DotNetOpenAuth.Messaging.IDirectedProtocolMessage request) Line 659 + 0xe bytes C#
DotNetOpenAuth.DLL!DotNetOpenAuth.Messaging.Channel.Request(DotNetOpenAuth.Messaging.IDirectedProtocolMessage requestMessage) Line 477 + 0xe bytes C#
DotNetOpenAuth.DLL!DotNetOpenAuth.OAuth2.ClientBase.UpdateAuthorizationWithResponse(DotNetOpenAuth.OAuth2.IAuthorizationState authorizationState, DotNetOpenAuth.OAuth2.Messages.EndUserAuthorizationSuccessAuthCodeResponse authorizationSuccess) Line 204 + 0x19 bytes C#
DotNetOpenAuth.DLL!DotNetOpenAuth.OAuth2.WebServerClient.ProcessUserAuthorization(DotNetOpenAuth.Messaging.HttpRequestInfo request) Line 118 + 0xf bytes C#
By the looks of it, either the server is buggy, or it's running an incompatible version of OAuth 2.0 (there are only 13 drafts of that unfinalized spec out there in use today). This is one reason to not use OAuth 2.0 in production until it's finalized.

Resources