Trying to Scrape Reddit with praw.Reddit - python

Im trying to scrape Reddit with the praw.reddit command and I keep getting the following:
prawcore.exceptions.OAuthException: unauthorized_client error processing
request (Only script apps may use password auth)
Heres the top of my code:(I removed the sensitive items)
import praw
import pandas as pd
import datetime as dt
reddit = praw.Reddit(client_id='zlpcoz08aNK8Bw', \
client_secret='', \
user_agent='comment_scraper 1.0 by /u/bullybear77777',
\
username='', \
password='')
I think it's because of my user_agent ID? I looked online and found that this appears to be the structure but im not sure. Any helps here would be greatly appreciated

This sort of error is caused by the type of app associated with that client id. Logging in with a password is restricted to script type apps.
When you create a new application, there are three types of apps to choose from:
web app: A web based application
installed app: An app intended for installation, such as on a mobile phone
script: Script for personal use. Will only have access to the developers accounts
If the application has the web app or installed app types then this form of authentication can't be used. You can't change the app type once it's created, but you can simply create a new one with a script type.

Related

SalesforceExpiredSession Error using simple_salesforce package in Python

I am trying to download a report I created on SalesForce using simple_salesforce package in python.
Below is the sample code:
from simple_salesforce import Salesforce
import requests
import pandas as pd
from io import StringIO
sf = Salesforce(username='myusername',
password='mypassword',
security_token='mytoken',
version='46.0')
report_id = 'myreportid'
sf.restful('analytics/reports/{}'.format(report_id))
However, this chunk of code yields the following error:
SalesforceExpiredSession: Expired session for https://company_name.my.salesforce.com/services/data/v46.0/analytics/reports/myreporid. Response content: [{'message': 'This session is not valid for use with the REST API', 'errorCode': 'INVALID_SESSION_ID'}]
(continuing from comments)
My bad, typo. Does your Profile have "API Enabled" checkbox ticked?
And you said you can see success in login history, active session?
What happens when you try to do same thing manually with workbench. Login, then in top menu Utilities -> REST Explorer should let you run your report.
Maybe simple is creating a SOAP session id which for whatever reason is incompatible with REST API (to be fair I thought they were pretty interchangeable, maybe your company disabled REST API, I heard it's possible to request that from SF support...)
If workbench works - you may have to login in simple different way, creating "connected app" and reading up about https://help.salesforce.com/s/articleView?id=remoteaccess_oauth_username_password_flow.htm&type=5&language=en_US for example

Slack API Events are not registering in our application

Hello Fellow Slack Bot Enthusiasts.
It's my first time to start setting up a Slack Bot (and I don't have a lot of dev experience, so I wanted to inquire!) .
For this, I used python and Slack bolt.
Background
I was trying to setup my Amazon EC2 Web Instance's Load Balancer to accept slack events from my Workspace. In the below photo, I am now able to have my Endpoint URL Verified in the Slack bot.
Next, I am trying to follow the instructions listed in the Slack Bolt homepage that told me to create the app.py test file. So I followed through on the instructions and ensured that I subscribed to below events:
app_home_opened
message.channels
message.groups
message.im
Then I created the sample app.py file from the article, that was supposed to handle the app_home_opened event.
Now I tried to run the application in my command line (I added the section for #app.event(app_home_opened), and all the other required events ), and I tried to trigger the app_home_opened, message.channels, message.im events, by opening the home page of my bot and by dm-ing the bot and inviting it to a channel and trying to talk to it - but I don't seem to be receiving any payload in the back-end.
I wanted to inquire about the "Verified" notification from the Slack Bot. Does this ensure that the connection between my chatbot code and the server are actually linked?
In addition, I wanted to inquire about ways to test this so that I can ensure that the connection is actually working as expected.
If you could share some thoughts about what I can do to test the communication, it would be much appreciated. Thank you!
Summary
TLDR:
Problem: My chatbot is not receiving any payload from Slack.
Expected: I think there should be some interaction saying HTTP / 200 response to indicate that it is OK, etc.
Actual: The chatbot just remains the same saying "⚡Bolt App is Running"
What I've tried:
Reinstalling the application to ensure that all my changes were saved and were reflected properly in my Slack Environment
Testing the communication by curling through to the URL (it responded with challenge parameter), so I thought that it was OK
Testing the communication by entering some text via DM / channel communication, and opening the homepage.
Sample Code:
import os
# Use the package we installed
from slack_bolt import App
# Initializes your app with your bot token and signing secret
app = App(
token=os.environ.get("SLACK_BOT_TOKEN"),
signing_secret=os.environ.get("SLACK_SIGNING_SECRET")
)
# Add functionality here
# #app.event("app_home_opened") ...
# added some of the code from the guide here and the other #app.events ("")
# Start your app
if __name__ == "__main__":
app.start(port=int(os.environ.get("PORT", 3000)))
slack_bolt, for some reason that escapes me, does not seem to create the event handler endpoint (/slack/events) and instead seems to prefer running the application in socket mode. It may still be worth looking into socket mode (see SocketModeHandler) but this example from slack_bolt's github repo ended up getting me to my solution: https://github.com/slackapi/bolt-python/blob/main/examples/flask/app.py
The short-ish version is you have to utilize slack_bolts's flask adapter to create a SlackRequestHandler then create a flask app, define the slack events endpoint (/slack/events) for the flask app, and pass the result to the bolt SlackRequestHandler (Events Endpoint -> Flask -> SlackRequestHandler -> Bolt):
import os
from flask import Flask, request
from slack_bolt import App
from slack_bolt.adapter.flask import SlackRequestHandler
bolt_app = App(
token=os.environ.get("SLACK_BOT_TOKEN"),
signing_secret=os.environ.get("SLACK_SIGNING_SECRET")
)
flask_app = Flask(__name__)
handler = SlackRequestHandler(bolt_app)
# Add functionality here
# #bolt_app.event("app_home_opened") ...
# added some of the code from the guide here and the other #bolt_app.events ("")
#flask_app.route("/slack/events", methods=["POST"])
def slack_events():
return handler.handle(request)
if __name__ == "__main__":
flask_app.run()
Hope this helps, cheers!

Accesing ASANA data using python requests

First of all, I'm not a Python guru as you can probably tell... So here we go.
I'm trying to use Asana's API to pull data with Python requests (Projects, tasks, etc) and doing the authentication using Oauth 2.0... I've been trying to find a simple python script to have something to begin with but I haven't had any luck and I can't find a decent and simple example!
I already created the app and got my client_secret and client_secret. But I don't really know where or how to start... Could anybody help me please?
import sys, os, requests
sys.path.append(os.path.dirname(os.path.dirname(__file__)))
import asana
import json
from six import print_
import requests_oauthlib
from requests_oauthlib import OAuth2Session
client_id=os.environ['ASANA_CLIENT_ID'],
client_secret=os.environ['ASANA_CLIENT_SECRET'],
# this special redirect URI will prompt the user to copy/paste the code.
# useful for command line scripts and other non-web apps
redirect_uri='urn:ietf:wg:oauth:2.0:oob'
if 'ASANA_CLIENT_ID' in os.environ:
#Creates a client with previously obtained Oauth credentials#
client = asana.Client.oauth(
#Asana Client ID and Secret, set as a Windows environments to avoid hardcoding variables into the script#
client_id=os.environ['ASANA_CLIENT_ID'],
client_secret=os.environ['ASANA_CLIENT_SECRET'],
# this special redirect URI will prompt the user to copy/paste the code.
# useful for command line scripts and other non-web apps
redirect_uri='urn:ietf:wg:oauth:2.0:oob'
)
print ("authorized=", client.session.authorized)
# get an authorization URL:
(url, state) = client.session.authorization_url()
try:
# in a web app you'd redirect the user to this URL when they take action to
# login with Asana or connect their account to Asana
import webbrowser
webbrowser.open(url)
except Exception as e:
print_("Open the following URL in a browser to authorize:")
print_(url)
print_("Copy and paste the returned code from the browser and press enter:")
code = sys.stdin.readline().strip()
# exchange the code for a bearer token
token = client.session.fetch_token(code=code)
#print_("token=", json.dumps(token))
print_("authorized=", client.session.authorized)
me = client.users.me()
print "Hello " + me['name'] + "\n"
params = {'client_id' : client_id, 'redirect_uri' : redirect_uri, 'response_type' : token,}
print_("*************** Request begings *******************"+"\n")
print_("r = requests.get('https://app.asana.com/api/1.0/users/me)" + "\n")
r = requests.get('https://app.asana.com/api/1.0/users/me', params)
print_(r)
print_(r.json)
print_(r.encoding)
workspace_id = me['workspaces'][0]['id']
print_("My workspace ID is" + "\n")
print_(workspace_id)
print_(client.options)
I'm not sure how to use the requests lib with Asana. Their python doc did not help me. I'm trying to pull the available projects and their code colours so I can later plot them into a web browser (For a high-level view of the different projects and their respective colours - Green, yellow or red)
When I introduce the url (https://app.asana.com/api/1.0/users/me) into a browser, it gives me back a json response with the data, but when I try to do the same with the script, it gives me back a 401 (not authorized) response.
Does anybody know what I'm missing / doing wrong?
Thank you!!!
I believe the issue is that the Requests library is a lower level library. You would need to pass all of the parameters to your requests.
Is there a reason you are not exclusively using the Asana Python client library to make requests? All of the data you are looking to fetch from Asana (projects, tasks, etc.) are accessible using the Asana Python library. You will want to look in the library to find the methods you need. For example, the methods for the tasks resource can be found here. I think this approach will be easier (and less error-prone) than switching between the Asana lib and the Requests lib. The Asana lib is actually built on top of Requests (as seen here).

Python facebook windows app not allow

My program download some infos about user and post it to the label in app.
I have a interaction/authorization problem with gui Facebook app in python. My app uses tkinter, facebook and fbconsole.
I autorized in this way.
import fbconsole as F
F.APP_ID="123"
F.AUTH_SCOPE=['publish_stream', 'publish_checkins', 'read_stream', 'offline_access']
F.ACCESS_TOKEN = "1234"
F.authenticate()
And something for show results
newsfeed = F.get('/me/home', {'fields':'from,name,description,message'})
newsfeedData = newsfeed["data"]
label.config(text=newsfeedData)
But when I run it, appear new facebook tab in browser announce: "Application configuration does not allow the use of the URL". How can I get rid of it?
Thanks!

Installing a custom app on Test Shop with GAE/Django

I'm having some troubles getting a custom app installed on my test shop using django and app engine. I downloaded the appropriate zip file on github for the app engine project (https://github.com/shopify/shopify_django_app).
I created the app on the partner admin with the callback url
http://localhost:8000/login/finalize
SHOPIFY_API_KEY = '6a17608.......'
SHOPIFY_API_SECRET = '1fddc.......'
Now I load it up and am greeted by the login page.
Now one of 2 things happen.
I enter https://crooks-and-sons5046.myshopify.com (test shop) and it sends me to the partner login form which I do and login. Then it just redirects me to my stores admin page and it doesn't bring up the install frame like I see on the online demo example.
OR I enter crooks-and-sons5046 and I get a 500 error kicked back from the server that says
Exception Value:
cannot concatenate 'str' and 'NoneType' objects
Exception Location: /Users/timwhitaker/gae/mfshopify/shopify/session.py in
__computed_password, line 87
This is the relevant line
return md5(self.secret + self.token).hexdigest()
My api key and secret key are both entered in the shopify_settings.py so this leads me to believe the token is not being created for the session.
The online demo here https://shopify-django-example.appspot.com/ works perfectly for me and I didn't mess around with any of the files that were in the included zip.
Any ideas?
Is your Shopify App configured to use Legacy or OAuth Authentication? I think the example app zip file for app engine is quite old, so probably only works with Legacy Authentication.
However, the master branch for the shopify_django_app project has been updated to support OAuth with Shopify. That along with the newer version of the shopify_python_api would be needed to be updated to use OAuth Authentication.

Categories