Instagram API facing error - instagram

This is my code for Instagram API which I referred in some github. But I'm getting error while running on jupyter notebook using python language.
from instagram.client import InstagramAPI
access_token = "6784563950.xxxxxxx.32e0d729b8c741508fbbcba17f8a7e57"
client_secret = "863bb1767xxxxxxx34861c31efe54104ae"
api = InstagramAPI(access_token=access_token, client_secret=client_secret)
recent_media, next_ = api.user_recent_media(user_id="67xxxx3950", count=10)
for media in recent_media: print(media)
I'm getting error
"C:\Users\Balaji\Anaconda3\lib\site-packages\instagram\models.py in
object_from_dictionary(cls, entry)
97 new_media.comment_count = entry['comments']['count']
98 new_media.comments = []
---> 99 for comment in entry['comments']['data']:
100 new_media.comments.append(Comment.object_from_dictionary(comment))
101
KeyError: 'data'.
Can anyone help me with proper code? If I write print media it says put parenthesis.

Official client is deprecated since June 2016. Use a forked and maintained client like: https://github.com/MabrianOfficial/python-instagram
To install it pip install --upgrade git+https://github.com/MabrianOfficial/python-instagram

Related

Why am I getting a keyerror when trying to import the requests module? KeyError: 'requests'

I don't understand why I am getting a KeyError. When running my code through the idle debugger.The directory with the requests module/folder is added to the PATH. Installing with pip shows that all of the dependencies are installed, and the module shows up when I run pip freeze. I'm not sure what the problem is here... Any help would be greatly appreciated.
import requests
def get_btc_price():
# Make the API call to retrieve the current price of Bitcoin
response = requests.get(
"https://api.kucoin.com/api/v1/market/orderbook/level2_100?symbol=BTC-USDT"
)
# Check if the API call was successful
if response.status_code == 200:
# Parse the JSON response
data = response.json()
# Return the current price of Bitcoin
return print(float(data["data"]["bids"][0][0]))
# If the API call was unsuccessful, return 0
return 0
get_btc_price
I think there was a conflict with an old version of Python... I deleted all PATH variables related to Python, then did an uninstall/reinstall of Python and the issue is resolved.

ModuleNotFoundError: No module named 'rfc822'

I trying to read my email python version 3.6.9 and pip3 version 9.0.1. when i run the following script it returns the error shows below. I try to install rfc822 with pip and pip3. Can you please help me to solve this issue.
Many thanks Erik
ERROR
Traceback (most recent call last):
File "/home/webapp/git/RA Functions/test.py", line 3, in <module>
import rfc822
ModuleNotFoundError: No module named 'rfc822'
CODE
import poplib
import string, random
import rfc822
from io import StringIO
def readMail():
SERVER = "pop.gmail.com"
USER = "myemail#gmail.com"
PASSWORD = "mypassword"
# connect to server
server = poplib.POP3(SERVER)
# login
server.user(USER)
server.pass_(PASSWORD)
# list items on server
resp, items, octets = server.list()
for i in range(0,10):
id, size = string.split(items[i])
resp, text, octets = server.retr(id)
text = string.join(text, "\n")
file = StringIO.StringIO(text)
message = rfc822.Message(file)
for k, v in message.items():
print(k, "=", v)
readMail()
This module is deprecated since version 2.3: The email package should be used in preference to the rfc822 module. This module is present only to maintain backward compatibility, and has been removed in Python 3.
For more information visit this : Deprecated Link
But here is another module which is plone.rfc822
This package provides primitives for turning content objects described by zope.schema fields into RFC (2)822 style messages. It utilizes the Python standard library’s email module.
For installation: pip install plone.rfc822
For information visit this: Active Link

Pyppeteer crushes after 20 seconds with pyppeteer.errors.NetworkError

During usage of pyppeteer for controlling the Chromium I have been receiving an error approximately after 20 seconds of work:
pyppeteer.errors.NetworkError: Protocol Error (Runtime.callFunctionOn): Session closed. Most likely the page has been closed.
As described here the issue is probably caused by implementation of python websockets>=7 package and by its usage within pyppeteer.
There are 3 solutions to prevent disconnection from Chromium:
- Patching the code like described here (preferable):
Run the snippet before running any other Pyppeteer commands
def patch_pyppeteer():
import pyppeteer.connection
original_method = pyppeteer.connection.websockets.client.connect
def new_method(*args, **kwargs):
kwargs['ping_interval'] = None
kwargs['ping_timeout'] = None
return original_method(*args, **kwargs)
pyppeteer.connection.websockets.client.connect = new_method
patch_pyppeteer()
- Change the trouble making library:
Downgrade websockets package to websockets-6.0 e.g via
pip3 install websockets==6.0 --force-reinstall (in your virtual environment)
- Change the code base
as described in this pull request, which will be hopefully merged soon.

Why does the program run in command line but not with IDLE?

The code uses a Reddit wrapper called praw
Here is part of the code:
import praw
from praw.models import MoreComments
username = 'myusername'
userAgent = 'MyAppName/0.1 by ' + username
clientId = 'myclientID'
clientSecret = 'myclientSecret'
threadId = input('Enter your thread id: ');
reddit = praw.Reddit(user_agent=userAgent, client_id=clientId, client_secret=clientSecret)
submission = reddit.submission(id=threadId)
subredditName = submission.subreddit
subredditName = str(subredditName)
act = input('type in here what you want to see: ')
comment_queue = submission.comments[:] # Seed with top-level
submission.comments.replace_more(limit=None)
def dialogues():
for comment in submission.comments.list():
if comment.body.count('"')>7 or comment.body.count('\n')>3:
print(comment.body + '\n \n \n')
def maxLen():
res = 'abc'
for comment in submission.comments.list():
if len(comment.body)>len(res):
res=comment.body
print(res)
#http://code.activestate.com/recipes/269708-some-python-style-switches/
eval('%s()'%act)
Since I am new to Python and don't really get programming in general, I am surprised to see that the every bit of code in the commandline works but I get an error in IDLE on the first line saying ModuleNotFoundError: No module named 'praw'
you have to install praw using the command
pip install praw which install latest version of praw in the environment
What must be happening is that your cmd and idle are using different python interpreters i.e., you have two different modules which can execute python code. It can either be different versions of python or it can be the same version but, installed in different locations in your machine.
Let's call the two interpreters as PyA and PyB for now. If you have pip install praw in PyA, only PyA will be able to import and execute functions from that library. PyB still has no idea what praw means.
What you can do is install the library for PyB and everything will be good to go.

Python3.6 how to install libtorrent?

Does libtorrent support python3 now? if supported how to install it .
I want to code a DHT Crawler with python3 , i don't know why my code alaways got Connection reset by peer error , so i want to use libtorrent , if there are another lib , i'm happy to use it . My biggest problem is , conversing the infohash to torrent file . Could it be a code problem?
class Crawler(Maga):
async def handler(self, infohash, addr):
fetchMetadata(infohash, addr)
def fetchMetadata(infohash, addr, timeout=5):
tcpServer = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
tcpServer.settimeout(timeout)
if tcpServer.connect_ex(addr) == 0:
try:
# handshake
send_handshake(tcpServer, infohash)
packet = tcpServer.recv(4096)
# handshake error
if not check_handshake(packet, infohash):
return
# ext handshake
send_ext_handshake(tcpServer)
packet = tcpServer.recv(4096)
# get ut_metadata and metadata_size
ut_metadata, metadata_size = get_ut_metadata(packet), get_metadata_size(packet)
# request each piece of metadata
metadata = []
for piece in range(int(math.ceil(metadata_size / (16.0 * 1024)))):
request_metadata(tcpServer, ut_metadata, piece)
packet = recvall(tcpServer, timeout) # the_socket.recv(1024*17) #
metadata.append(packet[packet.index("ee") + 2:])
metadata = "".join(metadata)
logging.info(bencoder.bdecode(metadata))
except ConnectionResetError as e:
logging.error(e)
except Exception as e:
logging.error(e)
finally:
tcpServer.close()
Yes, libtorrent (is supposed to) support python 3.
The basic way to build and install the python binding is by running the setup.py. That requires that all dependencies are properly installed where distutils expects them though. If this works it's probably the simplest way so it's worth a shot. I believe you'll have to invoke this python script using python3, if that's what you're building for.
To build using the main build system (and install the resulting module manually) you can follow the steps in the .travis file (for unix) or the appeyor file for windows.
In your case you want to specify a 3.x version of python, but the essence of it is:
brew install boost-python
echo "using python : 2.7 ;" >> ~/user-config.jam
cd bindings/python
bjam -j3 stage_module libtorrent-link=static boost-link=static
To test:
python test.py
Note, in the actual build step you may want to link shared against boost if you already have that installed, and shared against libtorrent if you have that installed, or will install it too.
On windows:
add the following to $HOMEPATH\user-config.jam:
using msvc : 14.0 ;
using gcc : : : <cxxflags>-std=c++11 ;
using python : 3.5 : c:\\Python35-x64 : c:\\Python35-x64\\include : c:\\Python35-x64\\libs ;
Then run:
b2.exe --hash openssl-version=pre1.1 link=shared libtorrent-link=shared stage_module stage_dependencies
To test:
c:\Python35-x64\python.exe test.py

Resources