PRAW Errors updating to new Python Distro - python

So I am trying to create a bot that cross posts from a sub (r/pics) to (r/polpics) using a bit of code from u/GoldenSights. I upgraded to a new python distro and I get a ton of errors, I don't even know where to begin. Here is the code (formatting off, error lines bold):
Traceback (most recent call last):
File "C:\Users\tonyc\AppData\Local\Programs\Python\Python36-32\Lib\site-
packages\praw\subdump.py", line 84, in <module>
r = praw.Reddit(USERAGENT)
File "C:\Users\tonyc\AppData\Local\Programs\Python\Python36-32\lib\site-
packages\praw\reddit.py", line 150, in __init__
raise ClientException(required_message.format(attribute))
praw.exceptions.ClientException: Required configuration setting 'client_id'
missing.
This setting can be provided in a praw.ini file, as a keyword argument to the `Reddit` class constructor, or as an environment variable.
This seems to be related to USERAGENT setting. I don't think I have that configured right.
USERAGENT = ""
# This is a short description of what the bot does. For example
"/u/GoldenSights' Newsletter bot"
SUBREDDIT = "pics"
# This is the sub or list of subs to scan for new posts.
# For a single sub, use "sub1".
# For multiple subs, use "sub1+sub2+sub3+...".
# For all use "all"
KEYWORDS = ["It looks like this post is about US Politics."]
# Any comment containing these words will be saved.
KEYDOMAINS = []
# If non-empty, linkposts must have these strings in their URL
This is the error line:
print('Logging in')
r = praw.Reddit(USERAGENT) <--here, this is error line 84
r.set_oauth_app_info(APP_ID, APP_SECRET, APP_URI)
r.refresh_access_information(APP_REFRESH)
Also in Reddit.py :
raise ClientException(required_message.format(attribute)) <--- error
praw.exceptions.ClientException: Required configuration setting 'client_id'
missing.
This setting can be provided in a praw.ini file, as a keyword argument to
the `Reddit` class constructor, or as an environment variable.

Firstly, you're going to want to have your API credentials stored externally in your praw.ini file. This makes things a lot more secure, and looks like it might go some way to fixing your issue. Here's what a completed praw.ini file looks like, including the useragent, so try to replicate this.
[DEFAULT]
# A boolean to indicate whether or not to check for package updates.
check_for_updates=True
# Object to kind mappings
comment_kind=t1
message_kind=t4
redditor_kind=t2
submission_kind=t3
subreddit_kind=t5
# The URL prefix for OAuth-related requests.
oauth_url=https://oauth.reddit.com
# The URL prefix for regular requests.
reddit_url=https://www.reddit.com
# The URL prefix for short URLs.
short_url=https://redd.it
[appname]
client_id=IE*******T14_w
client_secret=SW***********************CLY
password=******************
username=appname
user_agent=web:appname:1.0.0 (by /u/username)
Let me know how things go after you sort this out.

Related

reading configuration file entries with dynamic names in python

i am new to python but already programmed much in PHP. And here is my problem cause both languages use a bit different spelling and usage.
when i want to access a variable in PHP with a dynamic content i can do $array_name[$variable_name]
but how can i do this in python when i do not know the content of $variable_name?
My actual problem:
get a ini entry by variable with dynamic content. In my python script the variable "mode_name" is dynamically filled by an API request. so i do not know the content. The script is checking if this content of "mode_name" is listed in "config/modes" in the ini File. When it is listed, then there is a ini category with the same name and this should be returned in the API request. But see below the code, may be it explains it better.
i shortened the code a bit, cause everything else is working. and the dynamic var gets the correct name ("trafficlight") so it should work (in PHP) but i just getting an error.
python script:
import configparser
configfile = 'setup.ini'
config = configparser.ConfigParser()
config.read(configfile)
if mode_name in config['config']['modes']:
ret = config[mode_name]
return jsonify({'mode_name':ret})
ini file:
[config]
modes = 'trafficlight, record'
[trafficlight]
title = 'trafficlight'
lights = 'red, yellow, green'
gpio_red = 17
gpio_yellow = false
gpio_green = 18
[record]
title = 'recording'
gpio = 17
running this ends up in the following error:
File "app.py", line 6
ret = config[mode_name]
^
TabError: inconsistent use of tabs and spaces in indentation
What am doing wrong here? Thanks in advance!

Upload file to CKAN with ckanapi (Python)

import ckanapi
try:
ckan = ckanapi.RemoteCKAN(serverurl,
apikey='myapikeyhere',
user_agent='useragenthere')
res = ckan.action.resource_create(
package_id='2ad3c9de-502c-403a-8b03-bfc619697ff2',
#url='url',
#revision_id='revid',
description='my first upload with CKANAPI',
upload=open('./upload.csv')
)
except Exception as e:
raise Exception(str(e.error_dict))
It fails with:
Field errors: {u'url': [u'Missing value'], u'__type': u'Validation Error'}
They made url a required attribute in this discussion on GitHub:
https://github.com/ckan/ckan/pull/1641
So what is the expected value of the url attribute?
If it's expecting the url to the local file, it's not hosted.
And I cannot supply the url of the file on CKAN, because the resourceid was not created, yet.
PS: When passing an arbitrary value for the url attribute, the upload succeeds.
It makes no sense to require the url attribute. Can anybody explain?
That's, in my opinion, a bug in CKAN. I've created a issue to track it at https://github.com/ckan/ckan/issues/2769. I've also wrote a pull request on ckanapi to abstract this bug at https://github.com/ckan/ckanapi/pull/74.
As a workaround in the mean time, you can set the url to an empty string.

Skype4Py - How to successfully add a contact?

I'm working to implement a few fun features with a SkypeBot, and one of the features I'd like to implement is the ability to add a new contact. While reviewing the Skype4Py docs, I note this method:
http://skype4py.sourceforge.net/doc/html/Skype4Py.client.Client-class.html#OpenAddContactDialog
I am using the following code to try to access this:
sky = Skype4Py.Skype()
client = Skype4Py.client.Client(sky)
sky.Attach()
client.OpenAddContactDialog("test")
However, when trying to utilize almost anything from Skype4py.client.Client I get a timeout with the traceback:
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "build/bdist.macosx-10.8-intel/egg/Skype4Py/client.py", line 164, in OpenDialog
self._Skype._DoCommand('OPEN %s' % tounicode(' '.join(params)))
File "build/bdist.macosx-10.8-intel/egg/Skype4Py/skype.py", line 276, in _DoCommand
self.SendCommand(command)
File "build/bdist.macosx-10.8-intel/egg/Skype4Py/skype.py", line 778, in SendCommand
self._Api.send_command(Command)
File "build/bdist.macosx-10.8-intel/egg/Skype4Py/api/darwin.py", line 395, in send_command
raise SkypeAPIError('Skype command timeout')
SkypeAPIError: Skype command timeout
I receive this timeout error on every method I try to access within the client class. (ie:
OpenAuthorizationDialog, OpenCallHistoryTab, OpenContactsTab). Am I accessing this method incorrectly, or perhaps the method is not supported for newer versions of Skype? Any help with getting this working, or a method that adds contacts via Skype4Py successfully will be very appreciated.
sky = Skype4Py.Skype()
sky.Attach()
client = Skype4Py.client.Client(sky)
client.OpenAddContactDialog("Torxed")
Trying a few things out but i'm 99% sure that's the order in which you have to do things.
Otherwise you will time out because the attachment needs time to attach before you start executing things towards the API.
Also take a look at:
http://skype4py.sourceforge.net/doc/html/Skype4Py.user.User-class.html#SetBuddyStatusPendingAuthorization
http://skype4py.sourceforge.net/doc/html/Skype4Py.skype.SkypeEvents-class.html#UserAuthorizationRequestReceived
Also you might be going about this the wrong way.
Adding a skype user directly, is not how Skype works.
search
request add with a message
wait for authorization
So, try one of the following:
(one is a asyncore way of searching and adding as they pop up, the other will bunch your results)
http://skype4py.sourceforge.net/doc/html/Skype4Py.skype.Skype-class.html#AsyncSearchUsers
http://skype4py.sourceforge.net/doc/html/Skype4Py.skype.Skype-class.html#SearchForUsers
So try:
sky = Skype4Py.Skype()
sky.Attach()
print skyp.SearchForUsers('Torxed')
Should get you a handle to add me for instance.
Within the object that you recieve, there will be an option to add me for instance.
#Torxed's answer was right, but here's more information in case anyone wasn't able to make it the last mile.
I was able to add a contact in this way:
import Skype4Py
sky = Skype4Py.Skype()
sky.Attach()
requestMessage = "Please accept my request!"
searchResults = sky.SearchForUsers('echo123')
firstResult = searchResults[0]
firstResult.SetBuddyStatusPendingAuthorization(requestMessage)
Do be careful, though as this merely adds the FIRST result returned by the search. If you have the username exact, it should be fine.

Using the recommended python parse.com library to wrap their REST api, why does the following occur

Code:
for k in dir(parse_rest.User):
print parse_rest.User[k]
Error:
Traceback (most recent call last):
File "/home/ntresch/Development/webapp/appcode.py", line 53, in <module>
for k in dir(parse_rest.User):
AttributeError: 'module' object has no attribute 'User'
The docs show the following:
#Users
#You can sign up, log in, modify or delete users as well, using the User object. You sign a user up as follows:
u = parse_rest.User.signup("dhelmet", "12345", phone="555-555-5555")
#or log in an existing user with
u = parse_rest.User.login("dhelmet", "12345")
# Once a User has been logged in, it saves its session so that it can be edited or deleted:
u.highscore = 300
u.save()
u.delete()
I really want to know what all I can do with the user object. This behavior seems wonky.
This was a case of (at the time) out-of-date documentation, fixed as of 3/11/2013. The way to access the User class is not parse_rest.User but:
from parse_rest.user import User
The answer is don't use that library. My colleague has one we home rolled checked into our source tree and we're planning on releasing one. When we do I will post a link here for completeness. :)

pyfacebook + Google App Engine: can't find new functions in facebook.py

I'm trying to use the pyfacebook functions (https://github.com/sciyoshi/pyfacebook/) in a Google app engine project. I've followed the advice on the Facebook developer forum (http://forum.developers.facebook.net/viewtopic.php?pid=164613) and added the additional functions to the __init__.py file, copied that file to the root directory of my project and renamed it facebook.py. Having imported facebook.py I added the following to the get(self) method for the Python class for the page:
facebookapi = facebook.Facebook(API_KEY, SECRET)
if not facebookapi.check_connect_session(self.request):
path = os.path.join(os.path.dirname(__file__), 'templates/login.html')
self.response.out.write(template.render(path, {'apikey': API_KEY}))
return
user = facebookapi.users.getInfo(
[facebookapi.uid],
['uid', 'name', 'birthday', 'relationship_status'])[0]
template_values = {
'name': user['name'],
'birthday': user['birthday'],
'relationship_status': user['relationship_status'],
'uid': user['uid'],
'apikey': API_KEY
}
path = os.path.join(os.path.dirname(__file__), 'templates/index.html')
self.response.out.write(template.render(path, template_values))
When running it I get the following error:
File "\much\baw08u\Private\IDS\helloworld\helloworld.py", line 54, in get
if not facebookapi.check_connect_session(self.request):
AttributeError: 'Facebook' object has no attribute 'check_connect_session'
So it seems to be loading the facebook API fine, but not the new methods I've added. I copied and pasted the code from the developer forum at the bottom of the Facebook class definition, and made sure all the indentation was right but it still doesn't seem to be picking them up. Does anyone know what might be the problem?
Thanks
Ben
You believe the Facebook class has a certain method but Python is sure it hasn't. Why? Maybe you misspelled the method name, maybe you did not get the indentation right - hard to say without seeing the code.
You could try poking around to validate your assumptions:
import facebook
import logging
logging.warn('Facebook class: %r', dir(facebook.Facebook))
logging.warn('facebook module: %r', dir(facebook))
If you are sure you are operating on the correct file, the you should expect to see check_connect_session as a method of Facebook. If you didn't add enough indentation then you expect to see check_connect_method as a function defined in the facebook module. Too much indentation would make check_connect_method a sub function of which ever method precedes it and it won't show up in the above logging. Pay close attention to indentation.
However, a better way to add some custom methods might be:
import facebook
class Facebook(facebook.Facebook):
def check_connect_session(request):
pass
facebookapi = Facebook(API_KEY, SECRET)
if not facebookapi.check_connect_session(...):
...
Now when Facebook update their code you simply copy the new file into place - no need to merge your customisations.

Categories

Resources