Check if an ERC-20 token is a scam / Honeypot - node.js

I'm looking for a way to get the buy and sell tax of a Token and check if it can be sold once bought.
To do this, here's the method I thought about :
1-Simulate a Buy transaction on the DEX Router Contract
2-Simulate a Sell transaction on the DEX Router Contract
3-If the 2 above transaction are succesfull I can know the sale tax and Buy tax + know if the token is "sellable"
Since I'm using calls and not real transaction to simulate the buy/sell of the token, I need to make multi calls to simulate the alteration of the blockchain state.
I'm using the ethereum-multicall library to do this.
Here's my code :
const multicall = new Multicall({ethersProvider: _EVM.provider, tryAggregate: true});
let amoutIn = ethers.utils.parseUnits('300',18);
let timestamp = Date.now() + 1000 * 60 * 10;
const contractCallContext =[
{
reference: 'Router',
contractAddress: _EVM.DEX.router,
abi: JSON.parse(Router_ABI),
calls:[{reference:'foo', methodName:'swapExactTokensForTokens', methodParameters:[amoutIn,0,[ASDC, MIM],"0xa37Aa5C9A682490C64bDC32e60E627A50B66a485",timestamp]}]
}];
let result = await multicall.call(contractCallContext);
the problem is that I constantly get unsuccesfull return value from Multicall smartcontract...
Is there any other way to achieve what I'm looking for ? Or is there a problem with my code ?
Thanks in advance

You can find an example Python code here to check for any transfer fees.
def estimate_token_taxes(
uniswap: UniswapV2Deployment,
base_token: HexAddress,
quote_token: HexAddress,
buy_account: HexAddress,
sell_account: HexAddress,
buy_amount: float,
approve=True,
quote_token_details: Optional[TokenDetails] = None,
base_token_details: Optional[TokenDetails] = None,
gas_limit: Optional[int] = None,
gas_price: Optional[int] = None,
) -> TokenTaxInfo:
"""Estimates different token taxes for a token by running Ganache simulations for it.
:param uniswap:
Uniswap deployment on a Ganache mainnet fork.
Set up prior calling this function.
See `ganache.py` and `test_ganache.py` for more details.
:param base_token:
The token of which tax properties we are figuring out.
:param quote_token:
Address of the quote token used for the trading pair. E.g. `BUDS`, `WBNB`
Based on this information we can derive Uniswap trading pair address.
:param buy_account:
The account that does initial buy to measure the buy tax.
This account must be loaded with gas money (ETH/BNB) and `quote_token`
for a purchase.
:param sell_account:
The account that receives the token transfer and does the sell to measure the sell tax.
This account must be loaded with gas money for the sell.
:param approve:
Perform quote token approval before wap test
:param base_token_details:
Pass base token details. If not given automatically fetch.
:param quote_token_details:
Pass quote token details. If not given automatically fetch.
:param gas_limit:
Use this gas limit for all transactions, so that
we do not need to call eth_estimateGas on the node.
:param gas_price:
Use this gas price for all transactions, so that
we do not need to call eth_estimateGas on the node.
:return:
ToxTaxInfo tells us what we figure out about taxes.
This can be later recorded to a database.
"""
web3: Web3 = uniswap.web3
router = uniswap.router
if not quote_token_details:
# No need to consider brokeness of token metadata
# when calculating tax
quote_token_details = fetch_erc20_details(web3, quote_token, raise_on_error=False)
quote_token = quote_token_details.contract
if not base_token_details:
# No need to consider brokeness of token metadata
# when calculating tax
base_token_details = fetch_erc20_details(web3, base_token, raise_on_error=False)
base_token = base_token_details.contract
if gas_limit:
# Try to eliminate some RPC calls by not doing gas oracle requests
# https://web3js.readthedocs.io/en/v1.2.11/web3-eth.html#sendtransaction
generic_tx_params = {
"gas": gas_limit,
"gasPrice": gas_price,
}
else:
generic_tx_params = {}
# approve router to spend tokens
if approve:
quote_token.functions.approve(router.address, quote_token_details.convert_to_raw(buy_amount)).transact(
{"from": buy_account} | generic_tx_params)
path = [quote_token.address, base_token.address]
amountIn = quote_token_details.convert_to_raw(buy_amount)
# Figure out base_token/quote_token trading pair
initial_base_bal = base_token.functions.balanceOf(buy_account).call()
# Buy base_token with buy_account
try:
logger.info("Attempting to buy for path %s", path)
router.functions.swapExactTokensForTokensSupportingFeeOnTransferTokens(
amountIn,
0,
path,
buy_account,
FOREVER_DEADLINE
).transact({"from": buy_account} | generic_tx_params)
except ContractLogicError as e:
msg = str(e)
if "TRANSFER_FAILED" in msg:
raise TransferFromError(f"Token does not co-operate:{base_token_details.symbol} - {quote_token_details.symbol}, {e} to router {router.address}") from e
raise
except Exception as e:
raise SwapError(f"swapExactTokensForTokensSupportingFeeOnTransferTokens() buy failed:{base_token_details.symbol} - {quote_token_details.symbol}, {e} to router {router.address}") from e
received_amt = base_token.functions.balanceOf(buy_account).call() - initial_base_bal
if received_amt == 0:
# Nothing was received when we bought the token, so assume 100% tax
# Would cause division by zero later
return TokenTaxInfo(base_token.address, quote_token.address, 1.0, 1.0, 1.0)
uniswap_price = router.functions.getAmountsOut(amountIn, path).call()[1]
# Measure the loss as "buy tax"
buy_tax_percent = (uniswap_price - received_amt) / uniswap_price
# Transfer tokens to sell_account
# Measure the loss as "transfer tax"
try:
base_token.functions.transfer(sell_account, received_amt).transact({"from": buy_account} | generic_tx_params)
except ValueError as e:
if "out of gas" in str(e):
raise OutOfGasDuringTransfer(f"Out of gas during transfer: {e}") from e
else:
raise TransferFailure(f"Transfer failure: {e}") from e
received_amt_by_seller = base_token.functions.balanceOf(sell_account).call()
transfer_tax_percent = (received_amt - received_amt_by_seller) / received_amt
# Sell tokens
try:
base_token.functions.approve(router.address, received_amt_by_seller).transact({"from": sell_account} | generic_tx_params)
except ValueError as e:
if "out of gas" in str(e):
raise ApprovalFailure() from e
path = [base_token.address, quote_token.address]
sell_tax = 0
sell_tax_percent = 0
try:
# this method will revert in case of low liquidity of the token
logger.info("Attempting to see for path %s", path)
router.functions.swapExactTokensForTokensSupportingFeeOnTransferTokens(
received_amt_by_seller,
0,
path,
sell_account,
FOREVER_DEADLINE
).transact({"from": sell_account} | generic_tx_params)
except ValueError as e:
if "VM Exception while processing transaction: revert" in str(e):
raise SellFailed(f"Could not sell {base_token_details.symbol} - {quote_token_details.symbol}: {e}") from e
elif "out of gas" in str(e):
raise OutOfGasDuringTransfer() from e
raise
except Exception as e:
raise SwapError(f"Sell failed. swapExactTokensForTokensSupportingFeeOnTransferTokens() method failed: {base_token_details.symbol} - {quote_token_details.symbol}: {e}") from e
# Measure the loss as "sell tax"
received_amt_after_sell = quote_token.functions.balanceOf(sell_account).call()
uniswap_price = router.functions.getAmountsOut(received_amt_by_seller, path).call()[1]
if received_amt_after_sell > 0:
sell_tax = uniswap_price - received_amt_after_sell
sell_tax_percent = (sell_tax / uniswap_price) if uniswap_price > 0 else 0
return TokenTaxInfo(base_token.address, quote_token.address, buy_tax_percent, transfer_tax_percent,
sell_tax_percent)
You can also find the API and dataset dump for existing token tax data here

I am interested in the answer too. Maybe you can check out honeypot.is and see anything helps there (I am not affiliated with them). I am kind of new to writing bots and just happen to bump into their site. Let me know what you find!

Related

AttributeError: 'ChatForbidden' object has no attribute 'access_hash'

I have made a telegram member scraper and inviter with Python. It was successful on some tests, but there are times my accounts get banned with upon seeing this error message:
AttributeError: 'ChatForbidden' object has no attribute 'access_hash'
I'm not sure why would it show ChatForbidden if I am already an admin of a group. It's hard to test these as I had to buy new phone numbers every time.
Here's a sample and explanation of my code to invite members to a group:
# Log in into the telegram account
client = TelegramClient('Tg_scraper', api_id, api_hash)
chats = []
last_date = None
chunk_size = 200
groups = []
hash_list = []
# Get all the groups/channel of the account
result = client(GetDialogsRequest(
offset_date=last_date,
offset_id=0,
offset_peer=InputPeerEmpty(),
limit=chunk_size,
hash=0
))
chats.extend(result.chats)
# Puts all the group/channel into a list
i = 0
print('Enter a NUMBER to choose a group where the members will be invited into:')
for chat in chats:
try:
groups.append(chat)
hash_list.append(chat.access_hash)
print(f"({i})" + ' - ' + chat.title)
i += 1
except:
continue
g_index = input("Enter a Number: ")
target_group = groups[int(g_index)]
target_group_entity = InputPeerChannel(target_group.id, target_group.access_hash)
Upon the last line, target_group_entity = InputPeerChannel(target_group.id, target_group.access_hash) is where I encounter the error I have stated above. Upon receiving that error, I get banned.
Does this have something to do with permissions? Do new accounts get banned for botting? It works on my first few tests, but then now I can't invite. Thank you so much for anyone who could help in advance.
I am already an admin of a group
This error is unrelated to your permission level.
Upon the last line is where I encounter the error
Wrong. you encounter this error because you're not coding it right with types in mind, expecting all your .chats are groups. Telegram doesn't tell you what fields exactly have, as you see in this error.
You must use type checking to limit your chats objects to only what you expect, your try block is appending then erroring, so, rather than a plain:
except:
continue
you need to actually confirm it won't error when accessing fields.
print('Enter a NUMBER to choose a group where the members will be invited into:')
i = 0
for chat in chats:
if isinstance(chat, telethon.types.Channel):
if chat.broadcast: continue # ignore non-group
groups.append(chat)
hash_list.append(chat.access_hash)
print(f"({i})" + ' - ' + chat.title)
i += 1
g_index = input("Enter a Number: ")
target_group = groups[int(g_index)]

Odoo 13: Creating invoice from purchase order in odoo via api

I am brand new to odoo! On odoo 13 EE I am trying to create and confirm a vendor bill after importing a purchase order and the item receipts. I can create an invoice directly, but haven't been able to link that to the PO/receipt?
Sadly under purchase.order the method action_create_invoice seems hidden from the API
order_id = PurchaseOrder.create(po)
purchaseorder = PurchaseOrder.browse([order_id])
print("Before validating:", purchaseorder.name, purchaseorder.state) # draft
odoo.env.context['check_move_validity'] = True
purchaseorder.button_confirm()
purchaseorder = PurchaseOrder.browse([order_id])
picking_count = purchaseorder.picking_count
print("After Post:", purchaseorder.name, purchaseorder.state, "picking_count = ", purchaseorder.picking_count)
if picking_count == 0:
print("Nothing to receive. Straight to to Billing.") # ok so far
tryme = purchaseorder.action_view_invoice()
## Error => odoorpc.error.RPCError: type object 'purchase.order' has no attribute 'action_create_invoice'
SO I tried overriding/extending this way
class PurchaseOrder(models.Model):
_inherit = 'purchase.order'
#api.model
def create_invoice(self, context=None):
# try 1 => odoorpc.error.RPCError: 'super' object has no attribute # 'action_create_invoice'
rtn = super().action_create_invoice(self)
# try2 => odoorpc.error.RPCError: name 'action_create_invoice' is # not defined
# rtn = action_create_invoice(self)
# try3 => Error %s 'super' object has no attribute ' # action_create_invoice'
# rtn = super(models.Model, self).action_create_invoice(self)
return rtn
I hope somebody can suggest a solution! Thank you.
Please dont customize it without having a functional knowledge in odoo. In odoo, if you go to purchase settings, you can find billing options under invoicing where you can find 2 options, ordered quantity and received quantity. if it is ordered quantity, then you can create invoice after confirming the Purchase order. if it is received quantity, then after confirming the purchase order, a incoming shipment will be created and after the incoming shipment is processed, you can find the create invoice button in purchase order
If you can do it from the browser client, than you should just look what API commands the browser sends to the odoo server (in Chrome by enabling the debug view by pressing F12, and looking in the network tab), so that you just need to copy that communication.

When working with the Stripe API, is it better to sort each request or store locally and perform queries?

This is my first post, I've been lurking for a while.
Some context to my question;
I'm working with the Stripe API to pull transaction data and match these with booking numbers from another API source. (property reservations --> funds received for reconciliation)
I started by just making calls to the API and sorting the data in place using python 3, however it started to get very complicated and I thought I should persist the data in a mongodb stored on localhost. I began to do this, however I decided that storing the sorted data was still just as complicated and the request times were getting quite long, I thought, maybe I should pull all the stripe data and store it locally and then query whatever I needed.
So here I am, with a bunch of code I've written for both and still not alot of progress. I'm a bit lost with the next move. I feel like I should probably pick a path and stick with it. I'm a little unsure what is the "best practise" when working with API's, usually I would turn to YouTube, but I haven't been able to find a video which covers this specific scenario. The amount of data being pulled from the API would be around 100kb per request.
Here is the original code which would grab each query. Recently I've learnt I can use the expand method (I think this is what it's called) so I don't need to dig down so many levels in my for loop.
The goal was to get just the metadata which contains the booking reference numbers that can then be match against a response from my property management systems API. My code is a bit embarrassing, I've kinda just learnt it over the last little while in my downtime from work.
import csv
import datetime
import os
import pymongo
import stripe
"""
We need to find a Valid reservation_ref or reservation_id in the booking.com Metadata. Then we need to match this to a property ID from our list of properties in the book file.
"""
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
stripe_payouts = mydb["stripe_payouts"]
stripe.api_key = "sk_live_thisismyprivatekey"
r = stripe.Payout.list(limit=4)
payouts = []
for data in r['data']:
if data['status'] == 'paid':
p_id = data['id']
amount = data['amount']
meta = []
txn = stripe.BalanceTransaction.list(payout=p_id)
amount_str = str(amount)
amount_dollar = str(amount / 100)
txn_len = len(txn['data'])
for x in range(txn_len):
if x != 0:
charge = (txn['data'][x]['source'])
if charge.startswith("ch_"):
meta_req = stripe.Charge.retrieve(charge)
meta = list(meta_req['metadata'])
elif charge.startswith("re_"):
meta_req = stripe.Refund.retrieve(charge)
meta = list(meta_req['metadata'])
if stripe_payouts.find({"_id": p_id}).count() == 0:
payouts.append(
{
"_id": str(p_id),
"payout": str(p_id),
"transactions": txn['data'],
"metadata": {
charge: [meta]
}
}
)
# TODO: Add error exception to check for po id already in the database.
if len(payouts) != 0:
x = stripe_payouts.insert_many(payouts)
print("Inserted into Database ", len(x.inserted_ids), x.inserted_ids)
else:
print("No entries made")
"_id": str(p_id),
"payout": str(p_id),
"transactions": txn['data'],
"metadata": {
charge: [meta]
This last section doesn't work properly, this is kinda where I stopped and starting calling all the data and storing it in mongodb locally.
I appreciate if you've read this wall of text this far.
Thanks
EDIT:
I'm unsure what the best practise is for adding additional information, but I've messed with the code below per the answer given. I'm now getting a "Key error" when trying to insert the entries into the database. I feel like It's duplicating keys somehow.
payouts = []
def add_metadata(payout_id, transaction_type):
transactions = stripe.BalanceTransaction.list(payout=payout_id, type=transaction_type, expand=['data.source'])
for transaction in transactions.auto_paging_iter():
meta = [transaction.source.metadata]
if stripe_payouts.Collection.count_documents({"_id": payout_id}) == 0:
payouts.append(
{
transaction.id: transaction
}
)
for data in r['data']:
p_id = data['id']
add_metadata(p_id, 'charge')
add_metadata(p_id, 'refund')
# TODO: Add error exception to check for po id already in the database.
if len(payouts) != 0:
x = stripe_payouts.insert_many(payouts)
#print(payouts)
print("Inserted into Database ", len(x.inserted_ids), x.inserted_ids)
else:
print("No entries made")```
To answer your high level question. If you're frequently accessing the same data and that data isn't changing much then it can make sense to try to keep your local copy of the data in sync and make your frequent queries against your local data.
No need to be embarrassed by your code :) we've all been new at something at some point.
Looking at your code I noticed a few things:
Rather than fetch all payouts, then use an if statement to skip all except paid, instead you can pass another filter to only query those paid payouts.
r = stripe.Payout.list(limit=4, status='paid')
You mentioned the expand [B] feature of the API, but didn't use it so I wanted to share how you can do that here with an example. In this case, you're making 1 API call to get the list of payouts, then 1 API call per payout to get the transactions, then 1 API call per charge or refund to get the metadata for charges or metadata for refunds. This results in 1 * (n payouts) * (m charges or refunds) which is a pretty big number. To cut this down, let's pass expand=['data.source'] when fetching transactions which will include all of the metadata about the charge or refund along with the transaction.
transactions = stripe.BalanceTransaction.list(payout=p_id, expand=['data.source'])
Fetching the BalanceTransaction list like this will only work as long as your results fit on one "page" of results. The API returns paginated [A] results, so if you have more than 10 transactions per payout, this will miss some. Instead, you can use an auto-pagination feature of the stripe-python library to iterate over all results from the BalanceTransaction list.
for transaction in transactions.auto_paging_iter():
I'm not quite sure why we're skipping over index 0 with if x != 0: so that may need to be addressed elsewhere :D
I didn't see how or where amount_str or amount_dollar was actually used.
Rather than determining the type of the object by checking the ID prefix like ch_ or re_ you'll want to use the type attribute. Again in this case, it's better to filter by type so that you only get exactly the data you need from the API:
transactions = stripe.BalanceTransaction.list(payout=p_id, type='charge', expand=['data.source'])
I'm unable to test because I lack the same database that you have, but wanted to share a refactoring of your code that you may consider.
r = stripe.Payout.list(limit=4, status='paid')
payouts = []
for data in r['data']:
p_id = data['id']
amount = data['amount']
meta = []
amount_str = str(amount)
amount_dollar = str(amount / 100)
transactions = stripe.BalanceTransaction.list(payout=p_id, type='charge', expand=['data.source'])
for transaction in transactions.auto_paging_iter():
meta = list(transaction.source.metadata)
if stripe_payouts.find({"_id": p_id}).count() == 0:
payouts.append(
{
"_id": str(p_id),
"payout": str(p_id),
"transactions": transactions,
"metadata": {
charge: [meta]
}
}
)
transactions = stripe.BalanceTransaction.list(payout=p_id, type='refund', expand=['data.source'])
for transaction in transactions.auto_paging_iter():
meta = list(transaction.source.metadata)
if stripe_payouts.find({"_id": p_id}).count() == 0:
payouts.append(
{
"_id": str(p_id),
"payout": str(p_id),
"transactions": transactions,
"metadata": {
charge: [meta]
}
}
)
# TODO: Add error exception to check for po id already in the database.
if len(payouts) != 0:
x = stripe_payouts.insert_many(payouts)
print("Inserted into Database ", len(x.inserted_ids), x.inserted_ids)
else:
print("No entries made")
Here's a further refactoring using functions defined to encapsulate just the bit adding to the database:
r = stripe.Payout.list(limit=4, status='paid')
payouts = []
def add_metadata(payout_id, transaction_type):
transactions = stripe.BalanceTransaction.list(payout=payout_id, type=transaction_tyep, expand=['data.source'])
for transaction in transactions.auto_paging_iter():
meta = list(transaction.source.metadata)
if stripe_payouts.find({"_id": payout_id}).count() == 0:
payouts.append(
{
"_id": str(payout_id),
"payout": str(payout_id),
"transactions": transactions,
"metadata": {
charge: [meta]
}
}
)
for data in r['data']:
p_id = data['id']
add_metadata('charge')
add_metadata('refund')
# TODO: Add error exception to check for po id already in the database.
if len(payouts) != 0:
x = stripe_payouts.insert_many(payouts)
print("Inserted into Database ", len(x.inserted_ids), x.inserted_ids)
else:
print("No entries made")
[A] https://stripe.com/docs/api/pagination
[B] https://stripe.com/docs/api/expanding_objects

It is possible to upload a YouTube video description file with the Google python script?

I am using the Google python script to upload videos.
#!/usr/bin/python
import http.client #httplib
import httplib2
import os
import random
import sys
import time
from apiclient.discovery import build
from apiclient.errors import HttpError
from apiclient.http import MediaFileUpload
from oauth2client.client import flow_from_clientsecrets
from oauth2client.file import Storage
from oauth2client.tools import argparser, run_flow
# Explicitly tell the underlying HTTP transport library not to retry, since
# we are handling retry logic ourselves.
httplib2.RETRIES = 1
# Maximum number of times to retry before giving up.
MAX_RETRIES = 10
# Always retry when these exceptions are raised.
RETRIABLE_EXCEPTIONS = (httplib2.HttpLib2Error, IOError, http.client.NotConnected,
http.client.IncompleteRead, http.client.ImproperConnectionState,
http.client.CannotSendRequest, http.client.CannotSendHeader,
http.client.ResponseNotReady, http.client.BadStatusLine)
# Always retry when an apiclient.errors.HttpError with one of these status
# codes is raised.
RETRIABLE_STATUS_CODES = [500, 502, 503, 504]
# The CLIENT_SECRETS_FILE variable specifies the name of a file that contains
# the OAuth 2.0 information for this application, including its client_id and
# client_secret. You can acquire an OAuth 2.0 client ID and client secret from
# the Google Developers Console at
# https://console.developers.google.com/.
# Please ensure that you have enabled the YouTube Data API for your project.
# For more information about using OAuth2 to access the YouTube Data API, see:
# https://developers.google.com/youtube/v3/guides/authentication
# For more information about the client_secrets.json file format, see:
# https://developers.google.com/api-client-library/python/guide/aaa_client_secrets
CLIENT_SECRETS_FILE = "client_secrets.json"
# This OAuth 2.0 access scope allows an application to upload files to the
# authenticated user's YouTube channel, but doesn't allow other types of access.
YOUTUBE_UPLOAD_SCOPE = "https://www.googleapis.com/auth/youtube.upload"
YOUTUBE_API_SERVICE_NAME = "youtube"
YOUTUBE_API_VERSION = "v3"
# This variable defines a message to display if the CLIENT_SECRETS_FILE is
# missing.
MISSING_CLIENT_SECRETS_MESSAGE = """
WARNING: Please configure OAuth 2.0
To make this sample run you will need to populate the client_secrets.json file
found at:
%s
with information from the Developers Console
https://console.developers.google.com/
For more information about the client_secrets.json file format, please visit:
https://developers.google.com/api-client-library/python/guide/aaa_client_secrets
""" % os.path.abspath(os.path.join(os.path.dirname(__file__),
CLIENT_SECRETS_FILE))
VALID_PRIVACY_STATUSES = ("public", "private", "unlisted")
def get_authenticated_service(args):
flow = flow_from_clientsecrets(CLIENT_SECRETS_FILE,
scope=YOUTUBE_UPLOAD_SCOPE,
message=MISSING_CLIENT_SECRETS_MESSAGE)
storage = Storage("%s-oauth2.json" % sys.argv[0])
credentials = storage.get()
if credentials is None or credentials.invalid:
credentials = run_flow(flow, storage, args)
return build(YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION,
http=credentials.authorize(httplib2.Http()))
def initialize_upload(youtube, options):
tags = None
if options.keywords:
tags = options.keywords.split(",")
body=dict(
snippet=dict(
title=options.title,
description=options.description,
tags=tags,
categoryId=options.category
),
status=dict(
privacyStatus=options.privacyStatus
)
)
# Call the API's videos.insert method to create and upload the video.
insert_request = youtube.videos().insert(
part=",".join(body.keys()),
body=body,
# The chunksize parameter specifies the size of each chunk of data, in
# bytes, that will be uploaded at a time. Set a higher value for
# reliable connections as fewer chunks lead to faster uploads. Set a lower
# value for better recovery on less reliable connections.
#
# Setting "chunksize" equal to -1 in the code below means that the entire
# file will be uploaded in a single HTTP request. (If the upload fails,
# it will still be retried where it left off.) This is usually a best
# practice, but if you're using Python older than 2.6 or if you're
# running on App Engine, you should set the chunksize to something like
# 1024 * 1024 (1 megabyte).
media_body=MediaFileUpload(options.file, chunksize=-1, resumable=True)
)
resumable_upload(insert_request)
# This method implements an exponential backoff strategy to resume a
# failed upload.
def resumable_upload(insert_request):
response = None
error = None
retry = 0
while response is None:
try:
print ("Uploading file...")
status, response = insert_request.next_chunk()
if 'id' in response:
print ("Video id '%s' was successfully uploaded." % response['id'])
else:
exit("The upload failed with an unexpected response: %s" % response)
except HttpError as e:
if e.resp.status in RETRIABLE_STATUS_CODES:
error = "A retriable HTTP error %d occurred:\n%s" % (e.resp.status,
e.content)
else:
raise
except RETRIABLE_EXCEPTIONS as e:
error = "A retriable error occurred: %s" % e
if error is not None:
print (error)
retry += 1
if retry > MAX_RETRIES:
exit("No longer attempting to retry.")
max_sleep = 2 ** retry
sleep_seconds = random.random() * max_sleep
print ("Sleeping %f seconds and then retrying..." % sleep_seconds)
time.sleep(sleep_seconds)
if __name__ == '__main__':
argparser.add_argument("--file", required=True, help="Video file to upload")
argparser.add_argument("--title", help="Video title", default="Test Title")
argparser.add_argument("--description", help="Video description",
default="Test Description")
argparser.add_argument("--category", default="22",
help="Numeric video category. " +
"See https://developers.google.com/youtube/v3/docs/videoCategories/list")
argparser.add_argument("--keywords", help="Video keywords, comma separated",
default="")
argparser.add_argument("--privacyStatus", choices=VALID_PRIVACY_STATUSES,
default=VALID_PRIVACY_STATUSES[0], help="Video privacy status.")
args = argparser.parse_args()
if not os.path.exists(args.file):
exit("Please specify a valid file using the --file= parameter.")
youtube = get_authenticated_service(args)
try:
initialize_upload(youtube, args)
except HttpError as e:
print ("An HTTP error %d occurred:\n%s" % (e.resp.status, e.content))
The problem is the --description parameter. Only allow put one text line. And i need to put several lines with line jumps ('\n'). ¿it is possible to do this from another way?
Will be wonderful if this parameter (or other param) would allow a file text path to upload the description, like the "--file" parameter does.
There is something i can i do to solve this?
Or maybe one place where i'll can to contact with google developers to ask them if is posible to reimplement the initialize_upload(youtube, args) function to get it works like i say?
Yes it is possible!!
We have to add the --description-file option.
Google please, do a complete manual of your API!!!

How to reference/return a value from SignalR?

This is the code I have:
from signalr_aio import Connection
if __name__ == "__main__":
# Create connection
# Users can optionally pass a session object to the client, e.g a cfscrape session to bypass cloudflare.
connection = Connection('https://beta.bittrex.com/signalr', session=None)
hub = connection.register_hub('c2')
hub.server.invoke('GetAuthContext', API_KEY) #Invoke 0 Creates the challenge that needs to be signed by the create_signature coroutine
signature = await create_signature(API_SECRET, challenge) #Creates the signature that needs to authenticated in the Authenticate query
hub.server.invoke('Authenticate', API_KEY, signature) #Invoke 1 authenticates user to account level information
connection.start()
What I have to do is verify my identity by getting a string-type challenge by the GetAuthContext call, then create a string-type signature using that challenge, and then pass that signature to the Authenticatecall. The problem I'm having is that that I need to enter the return value of the GetAuthContext into the challenge parameter of the create_signature coroutine. I'm guessing from the comment next to the below example that every invoke method gets marked as I([index of method]), so I would have to do signature = await create_signature(API_SECRET, 'I(0)')
async def on_debug(**msg):
# In case of `queryExchangeState` or `GetAuthContext`
if 'R' in msg and type(msg['R']) is not bool:
# For the simplicity of the example I(1) corresponds to `Authenticate` and I(0) to `GetAuthContext`
# Check the main body for more info.
if msg['I'] == str(2):
decoded_msg = await process_message(msg['R'])
print(decoded_msg)
elif msg['I'] == str(3):
signature = await create_signature(API_SECRET, msg['R'])
hub.server.invoke('Authenticate', API_KEY, signature)
Later this example gets assigned to connection.received ( connection.received += on_debug ) so I'm guessing that after connection.start() I have to put connection.recieved() to call the on_debug coroutine which will verify me, but for now I just want to understand how to reference the .invoke() methods to use within a function or coroutine.
I am far from an expert, but the feed from Bittrex is indeed a Dictionary.
for i in range(0, len(decoded_msg['D'])):
print('The Currency pair is:{0} the Bid is:{1} and the Ask is :{2}'.format(decoded_msg['D'][i]['M'], decoded_msg['D'][i]['B'], decoded_msg['D'][i]['A']))

Resources