How to use PyGitHib repo.create_file - python

I am trying to use PyGitHub to automate updating files in a special repository. This special repo consists of parts of several other repos so I am using a GitHub webhook to cause it to be updated whenever any of the other repos are updated. I am running into a problem when a file is added to any of the other repos. In this case, I need to add a file to the special repo. Here is a snippet of the code
from github import GitHub
ACCESS_TOKEN = '...'
ORGANIZATION = '...'
REPONAME = '...'
gh = Github(ACCESS_TOKEN)
org = gh.get_organization(ORGANIZATION)
repo = org.get_repo(REPONAME)
path = <path-to-file-in-special-repo>
message = <commit-message-for-create-file>
contents = OtherRepo.get_contents(<<path-to-file-in-other-repo>).decoded_content.decode('utf-8')
repo.create_file(path, message, contents)
This is giving me the following error:
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "/usr/local/lib/python3.9/site-packages/github/Repository.py", line 2090, in create_file
headers, data = self._requester.requestJsonAndCheck(
File "/usr/local/lib/python3.9/site-packages/github/Requester.py", line 353, in requestJsonAndCheck
return self.__check(
File "/usr/local/lib/python3.9/site-packages/github/Requester.py", line 378, in __check
raise self.__createException(status, responseHeaders, output)
github.GithubException.GithubException: 422 {"message": "Invalid request.\n\n\"sha\" wasn't supplied.", "documentation_url": "https://docs.github.com/rest/reference/repos#create-or-update-file-contents"}
If I just do:
repo.create_file(path, 'test', 'test')
it works.
Can anyone tell me what I am doing wrong?

I have discovered what the problem is.
Because of the way I was testing my program the file I was trying to create was one previously deleted from the repo. What I needed to do was repo.update_file and, not repo.create_file.

Related

api key reading config file - binance trading bot python: SyntaxError: (unicode error)

I've just started today to code! so please be kind! :D
After a long we to install programs and libraries in coding my fist "trading bot"
I'm trying to connect to my test-api in Binance but I have an issue.
Here my lines of coding
Here my error that i cant fix [syntax error][2]
Ive already done:
uninstall and install again pip python-binance
install conda twisted
install pip update same packages
Any suggestions?
Many thanks
--- edit
photo of errors
ive tried all 3 types of suggestion
now pythons tell me there there is no module named 'binance' how is possible?
- relevant code
# Importing libraries
from binance.client import Client
import configparser
# Loading keys from config file
config = configparser.ConfigParser()
config.read_file(open('<C:\\Users\\ssida\\OneDrive\\Documenti\\GitHub\\AI7XF205SS\\secret.cfg>'))
test_api_key = config.get('BINANCE', 'TEST_API_KEY')
test_secret_key = config.get('BINANCE', 'TEST_SECRET_KEY')
client = Client(test_api_key, test_secret_key)
client.API_URL = 'https://testnet.binance.vision/api' # To change endpoint URL for test account
info = client.get_account() # Getting account info
print(info)
edit 2x ---
i think che path now works, but now i have a new issue... PI Error (code+-2014).. gonna search what is that..
seems that API key format is invalid :(
[Running] python -u "c:\Users\ssida\OneDrive\Documenti\GitHub\AI7XF205SS\getting_account_info.py"
Traceback (most recent call last):
File "c:\Users\ssida\OneDrive\Documenti\GitHub\AI7XF205SS\getting_account_info.py", line 15, in <module>
info = client.get_account() # Getting account info
File "C:\Users\ssida\anaconda3\lib\site-packages\binance\client.py", line 1822, in get_account
return self._get('account', True, data=params)
File "C:\Users\ssida\anaconda3\lib\site-packages\binance\client.py", line 292, in _get
return self._request_api('get', path, signed, version, **kwargs)
File "C:\Users\ssida\anaconda3\lib\site-packages\binance\client.py", line 242, in _request_api
return self._request(method, uri, signed, **kwargs)
File "C:\Users\ssida\anaconda3\lib\site-packages\binance\client.py", line 237, in _request
return self._handle_response()
File "C:\Users\ssida\anaconda3\lib\site-packages\binance\client.py", line 285, in _handle_response
raise BinanceAPIException(self.response)
binance.exceptions.BinanceAPIException: APIError(code=-2014): API-key format invalid.
[Done] exited with code=1 in 1.944 seconds
The problem is the backslash is a special character (ex \n marks a new line)
You can fix this by either adding r before the path
r'C:\Users\...'
or change the backslash with double ones
'C:\\Users\\...'
or replace with '/'
'C:/Users/...'
EDIT
Remove the '<>' from the start and end of the path because open takes it as it is

Python - Get Instagram API Access Token

I am trying to call the Instagram Basic API to get the user info. However, I need to fetch the access token first for the authentication.
I have implemented the code for getting the same in python but I am only able to fetch the re-direct uri. Now, as a manual step we execute that uri on browser and get the code from the url.
But in case of programming how can I get the access token?
In below code: I am getting error
from instagram_basic_display.InstagramBasicDisplay import InstagramBasicDisplay
from flask import request
instagram_basic_display = InstagramBasicDisplay(app_id='5163403347035424', app_secret='80473de6ad506c837969e03b8ccdb4cb', redirect_url='https://mycogito.me/')
print(instagram_basic_display.get_login_url()) # Returns login URL you need to follow
code = request.args.get('code')
print(code)
Error
Traceback (most recent call last):
File "D:\Work Backup\Development\Workspaces\python\SocialMedia\src\com\social\media\HelloWorld.py", line 9, in <module>
https://api.instagram.com/oauth/authorize?client_id=5163403347035424&redirect_uri=https%3A%2F%2Fmycogito.me%2F&scope=user_profile%2Cuser_media&response_type=code
code = request.args.get('code')
File "C:\Users\HP\AppData\Local\Programs\Python\Python36\lib\site-packages\werkzeug\local.py", line 347, in __getattr__
return getattr(self._get_current_object(), name)
File "C:\Users\HP\AppData\Local\Programs\Python\Python36\lib\site-packages\werkzeug\local.py", line 306, in _get_current_object
return self.__local()
File "C:\Users\HP\AppData\Local\Programs\Python\Python36\lib\site-packages\flask\globals.py", line 38, in _lookup_req_object
raise RuntimeError(_request_ctx_err_msg)
RuntimeError: Working outside of request context.
There is a package when you want to get data from instagram and written in python click.

ConfigParser raise KeyError(key) Python 3.8

i am trying to make a config file using ConfigParser in python 3.
I get this error when trying to run the script
C:\Users\Deagan>"C:\Users\Deagan\Desktop\Hypixel Rich Presence\Main.py"
Traceback (most recent call last):
File "C:\Users\Deagan\Desktop\Hypixel Rich Presence\Main.py", line 10, in <mod
ule>
APIKEY = config['DEFAULT']['secretid']
File "C:\Users\Deagan\AppData\Local\Programs\Python\Python38\lib\configparser.
py", line 1254, in __getitem__
raise KeyError(key)
KeyError: 'secretid'
Here is my config file:
[DEFAULT]
secretid = 'XXXXXXXXXX'
username = 'XXXX'
client_id = 'XXXXXXXX'
Here is the Main.py script file
config = ConfigParser()
config.read('config.ini')
APIKEY = config['DEFAULT']['secretid']
client_id = config['DEFAULT']['client_id']
username = config['DEFAULT']['username']
print(config.sections())
Am i doing something wrong?
Currently File not found error is not handled in config parser, check here https://github.com/jaraco/configparser/issues/53
Please check the config file is present in the same directory of python code.
To check file is present / not Move this Line to top,
print(config.sections())
If sections are printed then your file is ok check for typo in the section names and keys
Make sure the files are in the same folder and the name assigned to config.read('xxxxxx.ini') matches the one you created.

OAuthAccessTokenException-The access_token provided is invalid

I am trying to follow along with the Python-Instagram simple example on their readme:
api = InstagramAPI(client_id=client_id, client_secret=client_secret)
popular_media = api.media_popular(count=20)
for media in popular_media:
print media.images['standard_resolution'].url
However, every time I try with my own client_id and client_secret I get the following error and have been unable to figure out how to solve it:
Traceback (most recent call last):
File "/Users/PycharmProjects/Instagram API/InstaApiTest.py", line 10, in <module>
popular_media = api.media_popular(count=20)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/instagram/bind.py", line 197, in _call
return method.execute()
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/instagram/bind.py", line 189, in execute
content, next = self._do_api_request(url, method, body, headers)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/instagram/bind.py", line 163, in _do_api_request
raise InstagramAPIError(status_code, content_obj['meta']['error_type'], content_obj['meta']['error_message'])
instagram.bind.InstagramAPIError: (400) OAuthAccessTokenException-The access_token provided is invalid.
Can anyone help me solve this issue?
This is likely due to the tutorial being out of date. Note that the README file in the tutorial repo (which hasn't been updated in years) warns:
This project is not actively maintained. Proceed at your own risk!
Instagram doesn't even list media/popular/ on their media endpoints official documentation anymore. Even when it was a thing, there's some indication that you needed an actual access token, even a couple of years back, contrary to what the tutorial you're following states.
TL;DR - Look for a different tutorial, this endpoint is either changed or requires full authentication.

API Python smartsheet can't connect with SDK

I'm pretty new to Python and I'm trying to connect to smartsheet with API.
I have ran "pip install smartsheet-python-sdk" and it installed smartsheet as I can find it under "lib"
This is code I have found and supposed to work(I replaced the token with the token)
# Import.
import smartsheet
# Instantiate smartsheet and specify access token value.
smartsheet = smartsheet.Smartsheet('Token_here')
# Get all columns.
action = smartsheet.Sheets.get_columns('Template for Bram', include_all=True)
columns = action.data
# For each column, print Id and Title.
for col in columns:
print(col.id)
print(col.title)
print('')
It shows this error:
Traceback (most recent call last):
File "C:\Users\bram\Desktop\smartsheet.py", line 2, in <module>
import smartsheet
File "C:\Users\bram\Desktop\smartsheet.py", line 5, in <module>
smartsheet = smartsheet.Smartsheet('token_here')
AttributeError: 'module' object has no attribute 'Smartsheet'
Now I'm not sure what my next step is. I think I have followed all of the appropriate steps. When I run import smartsheet by itself it won't error out.
What am I doing wrong?
Thank you
Update***
After using the code from the github page and implementing my token and sheet id I get this error:
Traceback (most recent call last):
File "C:\Users\bvanhout\Desktop\test23.py", line 58, in <module>
sheet = ss.Sheets.get_sheet(sheet_id)
File "C:\Python27\lib\site-packages\smartsheet\sheets.py", line 460, in get_sheet
response = self._base.request(prepped_request, expected, _op)
File "C:\Python27\lib\site-packages\smartsheet\smartsheet.py", line 178, in request
res = self.request_with_retry(prepped_request, operation)
File "C:\Python27\lib\site-packages\smartsheet\smartsheet.py", line 242, in request_with_retry
return self._request(prepped_request, operation)
File "C:\Python27\lib\site-packages\smartsheet\smartsheet.py", line 210, in _request
raise UnexpectedRequestError(rex.request, rex.response)
UnexpectedRequestError: (<PreparedRequest [GET]>, None)
# TODO: Update this with the ID of your sheet to update
sheet_id = 48568543424234
I printed ss and ss.Sheets and both do not reflect the actual token or sheet_id
>>> print (ss.Sheets)
<smartsheet.sheets.Sheets object at 0x0000000003874438>
I suspect the problem is that you are using a local variable with the same name as the module ('smartsheet')
Please take a look at the sample here: https://github.com/smartsheet-samples/python-read-write-sheet

Categories

Resources