everyone.
I am trying to create a simple telegram bot. In my country telegram is blocked so I need to work via proxy.
from telegram.ext import Updater
from telegram.ext import CommandHandler
import os
def start(bot, update):
print("Hello")
bot.sendMessage(chat_id=512562849, text="Hello.")
REQUEST_KWARGS={
'proxy_url': 'http://93.171.217.48:10996',
'urllib3_proxy_kwargs': {
'username': '***',
'password': '***',
}
}
updater = Updater(token='<BOT_TOKEN>',
request_kwargs=REQUEST_KWARGS)
start_handler = CommandHandler('start', start)
updater.dispatcher.add_handler(start_handler)
updater.start_polling()
But I have the next log
Exception in thread updater:
...
_HTTPConnection.__init__(self, *args, **kw)
TypeError: __init__() got an unexpected keyword argument 'username'
I used the next docs.
The free proxy works ok, but for my goals, it's bad to lose connection time after time. I prefer not to work under VPN either because of some bureaucracy in my company.
Thanks in advance!
I suppose you're using a SOCKS5 proxy. If that's the case, the proxy url protocol should be socks:// instead of https://, in your example:
REQUEST_KWARGS={
'proxy_url': 'socks5://93.171.217.48:10996',
'urllib3_proxy_kwargs': {
'username': '***',
'password': '***',
}
I've just ran the same issue and came up with the following.
1) Make sure we import required function from urllib3:
from urllib3 import make_headers
2) Fill appropriate values:
REQUEST_KWARGS = {
'proxy_url': "http://ip:port",
'urllib3_proxy_kwargs': {
'proxy_headers': make_headers(proxy_basic_auth='username:password')
}
}
I used tor to connect and my problem was fixed.
Download, install and run the tor browser.
Install pysocks dependency. pip install pysocks
And in the code: REQUEST_KWARGS = { 'proxy_url': 'socks5h://127.0.0.1:9150' }
I was behind corporate https proxy with auth and I solved with Working Behind a Proxy which basically proposes this:
TOKEN='YOUR_BOT_TOKEN'
REQUEST_KWARGS={
# "USERNAME:PASSWORD#" is optional, if you need authentication:
'proxy_url': 'http://USERNAME:PASSWORD#PROXY_HOST:PROXY_PORT/',
}
updater = Updater(TOKEN, request_kwargs=REQUEST_KWARGS)
Related
I am trying to create a discord register system via Python. But hCaptcha gives the "Invalid-response" error.
Is Discord the real cause of this problem or is there a different factor?
from anticaptchaofficial.hcaptchaproxyless import *
import requests
import config
solver = hCaptchaProxyless()
solver.set_verbose(1)
solver.set_key(config.KEY)
solver.set_website_url("https://discord.com/register")
solver.set_website_key("4c672d35-0701-42b2-88c3-78380b0db560")
solver.set_user_agent(config.MY_USER_AGENT)
solver.set_soft_id(0)
g_response = solver.solve_and_return_solution()
if g_response != 0:
print("g-response: "+g_response)
else:
print("task finished with error "+solver.error_code)
register_url = "https://discord.com/api/v9/auth/register"
payload = {
"fingerprint":"",
"email":"#gmail.com",
"username":"",
"password":"",
"invite":"null",
"consent":"true",
"date_of_birth":"1990-01-01",
"gift_code_sku_id":"null",
"captcha_key":g_response,
"promotional_email_opt_in":"false"
}
r = requests.post(register_url,json=payload)
print(r.text)```
You can follow this video to solve the Hcaptcha for Discord. https://www.youtube.com/watch?v=L0ltHB75Rt0. Thanks to Exordium !!!
The Video describes a free and paid version. The free version, at least when I tested, did not work. You can use the paid version with your 2captcha or any captcha solver api key.
In my test I used Neocities as that has the captcha on the main page.
Here is my version of the app.js that works:
import puppeteer from "puppeteer-extra";
import RecaptchaPlugin from "puppeteer-extra-plugin-recaptcha";
//import bypass from "./bypass/captchaBypasser.js";
puppeteer.use(
RecaptchaPlugin({
provider: {
//fn: bypass,
id: '2captcha',
token: 'your_2captcha_api_key',
},
})
);
puppeteer.launch({headless: false}).then(async (browser) => {
const page = await browser.newPage()
await page.goto('https://neocities.org/#new')
console.log('Solving Captcha...')
await page.solveRecaptchas()
console.log('Solved Captcha')
})
If this works for you, please mark as an answer. Good Luck
Overview
When creating a post request from my website to my Python server running CherryPy, I receive the error Access to XMLHttpRequest has been blocked by CORS policy: Request header field content-type is not allowed by Access-Control-Allow-Headers in preflight response. . I was able to get away with the problem temporarily with one of the "CORS Everywhere" browser extensions, but
Due to recent updates, the extensions have not yet been updated to be working again.
The website involved needs to eventually be used by many in my local complex without the browser extension, so once the extensions get updated, it does not really matter one way or another, as I cannot rely on these extensions, and force everyone to use them (when there is obviously a fix that would make an extension not necessary).
I figure that perhaps the solutions are outdated, but am not sure.
Here is the relevant code:
On the server side (CherryPy/Python):
The CherryPy Python function being called, from the website post request
#cherrypy.expose
#cherrypy.tools.json_in()
def add_meeting(self):
data = None
id = None
start_time = None
end_time = None
title = None
userlist = None
result = {"operation": "request", "result": "success"}
if cherrypy.request.method == "POST":
data = cherrypy.request.json
id = data["id"]
start_time = data["start_time"]
end_time = data["end_time"]
title = data["title"]
userlist = data["userlist"]
# Rest of relevant code in function is left out, to take up less
# space and not post irrelevant code. That being said, I am
# positive the logic is correct, as it originally ran smoothly
# with a "Cors Everywhere" Browser Extension.
return result
Here is the area where I set up and run CherryPy
def main():
# Create the configuration file parser object and start the CherryPy server
config = ConfigParser.ConfigParser()
config.read(CONFIG_FILE)
port = config.getint('Meta', 'port')
host = config.get('Meta', 'host')
cherrypy.config.update({'server.socket_port': port,
'server.socket_host': host,
'tools.CORS.on': True})
cherrypy.quickstart(Coordinator(config))
main()
Here is the config file mentioned in the code above (CONFIG_FILE)
[Meta]
host = 0.0.0.0
port = 3000
# Rest is left out, as it is irrelevant with problem
The solutions I have tried implementing
The inclusion of the following function above the main function:
def CORS():
cherrypy.response.headers["Access-Control-Allow-Origin"] = "*"
with cherrypy.tools.CORS = cherrypy.Tool('before_handler', CORS)
2. Adding " 'cors.expose.on': True " to cherrypy.config.update above
3. Using this cherrypy-cors Python library I found online: https://pypi.org/project/cherrypy-cors/
4. The inclusion of headers in the config.update portion of the Python file
5. Adding "#cherrypy.tools.accept(media='application/json')" before "def add_meeting"
Conclusion
I've tried the solutions above together, separately, some with and without the others, and I am still stuck. Maybe some of these solutions are partially correct, and there is something extra needed with my code. I am not sure; I just cannot get it working. I do not have much experience with web development before this, so maybe (and hopefully) the solution is extremely simple. I know the code works, I just cannot get it running without a working "Cors Everywhere" browser extension for every user.
As for the versions I am running: I am using CherryPy 14.2.0 and Python 2.7.6
Any help would mean the absolute world to me, thank you.
So first, you need to set pre-flight headers when processing OPTIONS request, you can list allowed methods there.
Then, you also need to enable the cors.expose tool.
There's some usage hints in the docstring of cherrypy-cors. For example, when using a MethodDispatcher, you could just decorate an OPTIONS handler method with #cherrypy_cors.tools.preflight() instead of doing this in every HTTP handler.
Here's a simple traversal example (without a method dispatcher). To test it, visit http://127.0.0.1/ and it will make requests against http://localhost:3333/add_meeting which is a different Origin in terms of CORS ('localhost' != '127.0.0.1').
"""Example of CORS setup using cherrypy-cors library."""
import cherrypy
import cherrypy_cors
# Python 2 compat: make all classes new-style by default
__metaclass__ = type # pylint: disable=invalid-name
class WebRoot:
"""Root node for HTTP handlers."""
#cherrypy.expose
def index(self): # pylint: disable=no-self-use
"""Render a web page handling request against ``/``.
Contains client JS snippet which will query the API endpoint.
It will be executed by the browser while loading the page.
"""
return """<html>
<script type="text/javascript">
async function addMeeting() {
/*
* Example coroutine for querying /add_meeing
* HTTP endpoint. It uses localhost as in the URL.
* For testing CORS, make sure to visit
* http://127.0.0.1/ which is a different origin
* from browser's perspective.
* /
const request_payload = {
some: 'data',
listed: ['h', 'er', 'e'],
}
try {
const resp = await fetch(
'http://localhost:3333/add_meeting',
{
method: 'POST',
mode: 'cors', // Required for customizing HTTP request headers
credentials: 'same-origin',
headers: {
'Content-Type': 'application/json; charset=UTF-8', // Required for ``cherrypy.tools.json_in`` to identify JSON payload and parse it automatically
},
body: JSON.stringify(request_payload),
},
)
const json_resp = await resp.json()
console.log(json_resp) // Will print: {"method": "POST", "payload": {"listed": ["h", "er", "e"], "some": "data"}}
} catch (e) {
console.warn('Exception: ' + e)
}
}
async function main() {
await addMeeting()
}
main() // Entry point
</script>
</html>""" # noqa: E501
#cherrypy.expose
#cherrypy.tools.json_in() # turn HTTP payload into an object; also checking the Content-Type header
#cherrypy.tools.json_out() # turn ``return``ed Python object into a JSON string; also setting corresponding Content-Type
def add_meeting(self):
"""Handle HTTP requests against ``/add_meeting`` URI."""
if cherrypy.request.method == 'OPTIONS':
# This is a request that browser sends in CORS prior to
# sending a real request.
# Set up extra headers for a pre-flight OPTIONS request.
cherrypy_cors.preflight(allowed_methods=['GET', 'POST'])
if cherrypy.request.method == 'POST':
return {'method': 'POST', 'payload': cherrypy.request.json}
return {'method': 'non-POST'}
def main():
"""Set up and run the web app.
Initializes CORS tools.
Sets up web server socket.
Enables the CORS tool.
"""
cherrypy_cors.install()
cherrypy.config.update({
'server.socket_host': '127.0.0.1',
'server.socket_port': 3333,
'cors.expose.on': True,
})
cherrypy.quickstart(WebRoot())
__name__ == '__main__' and main() # pylint: disable=expression-not-assigned
Receiving the following error response when doing a basic Graph API POST using REQUESTS in Python:
{
"error": {
"code": "Authorization_RequestDenied",
"message": "Insufficient privileges to complete the operation.",
"innerError": {
"request-id": "36c01b2f-5c5c-438a-bd10-b3ebbc1a17c9",
"date": "2019-04-05T22:39:37"
}
}
}
Here is my token request and Graph request using REQUESTS in Python:
redirect_uri = "https://smartusys.sharepoint.com"
client_id = 'd259015e-****-4e99-****-aaad67057124'
client_secret = '********'
tennant_id = '15792366-ddf0-****-97cb-****'
scope = 'https://graph.microsoft.com/.default'
####GET A TOKEN
payload = "client_id="+client_id+"&scope="+scope+"&client_secret="+client_secret+"&grant_type=client_credentials"
headers = {'content-type':'application/x-www-form-urlencoded'}
tokenResponse = requests.post('https://login.microsoftonline.com/'+tennant_id+'/oauth2/v2.0/token',headers=headers, data=payload)
json_tokenObject = json.loads(tokenResponse.text)
authToken = json_tokenObject['access_token']
#### Make a call to the graph API
graphResponse = requests.get('https://graph.microsoft.com/v1.0/me/',headers={'Authorization':'Bearer '+authToken})
if tokenResponse.status_code != 200:
print('Error code: ' +graphResponse.status_code)
print(graphResponse.text)
exit()
print('Request successfull: Response: ')
print(graphResponse.text)
print('Press any key to continue...')
x=input()
According to the documentation ( https://learn.microsoft.com/en-us/graph/api/resources/users?view=graph-rest-1.0 ) for this /me call, I need just one of the following permissions:
User.ReadBasic.All
User.Read
User.ReadWrite
User.Read.All
User.ReadWrite.All
Directory.Read.All
Directory.ReadWrite.All
Directory.AccessAsUser.All
and I have all of these on both application and delegated permissions in the azure application manager.
What am I doing wrong here? I feel like it's something small but I just can't figure this out.
I decoded my token using: http://calebb.net/ and I do not see a spot for "AUD" or "role" or "scope" so maybe that is where I am doing it wrong?
I looked everywhere and can't find a resolution, any help would be VERY much appreciated.
Thank you.
This sounds like you forgot to "Grant Permissions" to your application.
See this answer.
I finally figured this out, it had to do with Admin rights that needed to be granted by the Admin for our Office 365.
it was as simple as giving my Office admin the following link and having him approve it:
https://login.microsoftonline.com/{TENNANT ID HERE}/adminconsent?client_id={CLIENT ID HERE}
Instantly worked.
I have an api that i am using for a project that I am working on. I am getting a key errror for the client Id that I have to pass in order ot call the api. THe api that i am using is Synapse. If anyone knows what is cuasing the error or how I can fix this key error, it would be a lit of help... Here is the full error.
KeyError at /
'client_id_...6YiBl'
Request Method: GET
Request URL: http://127.0.0.1:8000/
Django Version: 1.8.6
Exception Type: KeyError
Exception Value:
'client_id_...YiBl'
Exception Location: C:\Users\OmarJandali\AppData\Local\Programs\Python\Python36\lib\os.py in __getitem__, line 669
Python Executable: C:\Users\OmarJandali\AppData\Local\Programs\Python\Python36\python.exe
Python Version: 3.6.1
Python Path:
['C:\\Users\\OmarJandali\\Desktop\\opentab\\opentab',
'C:\\Users\\OmarJandali\\AppData\\Local\\Programs\\Python\\Python36\\python36.zip',
'C:\\Users\\OmarJandali\\AppData\\Local\\Programs\\Python\\Python36\\DLLs',
'C:\\Users\\OmarJandali\\AppData\\Local\\Programs\\Python\\Python36\\lib',
'C:\\Users\\OmarJandali\\AppData\\Local\\Programs\\Python\\Python36',
'C:\\Users\\OmarJandali\\AppData\\Local\\Programs\\Python\\Python36\\lib\\site-packages']
here is the code:
import os
from synapse_pay_rest import Client
args = {
'client_id': os.environ['client_id_...YiBl'],
'client_secret': os.environ['client_secret_...C3IF'],
'fingerprint': '599378e9a63ec2002d7dd48b',
'ip_address': '127.0.0.1',
'development_mode':True,
'logging':False
}
client = Client(**args)
Your code looks like it should be using the keys directly, whereas you're trying to access environment variables.
Basically, don't try to access these values via os.environ(), as it will make your application search for an environment variable named client_id_...YiBl.
from synapse_pay_rest import Client
args = {
'client_id': 'client_id_...YiBl',
'client_secret':'client_secret_...C3IF',
'fingerprint': '599378e9a63ec2002d7dd48b',
'ip_address': '127.0.0.1',
'development_mode':True,
'logging':False
}
client = Client(**args)
I am developing a RESTFUL webservice using Django. On some occassion, we need to push the server object to the connected client without client polling.
We decided to use django-websocket 0.3.0.
I am writing the test cases and tried to connect to the server using nodejs ws client module
My View Function in Django is following:
from django.http import HttpResponse
from django_websocket import accept_websocket, require_websocket
from django.views.decorators.csrf import csrf_exempt
import json, sys, os, time, datetime
#csrf_exempt
#accept_websocket
def home(request) :
if not request.is_websocket():
return HttpResponse('new message')
else:
for message in request.websocket:
message = modify_message(message)
request.websocket.send(message)
request.websocket.close()
My Client Side code in js is like this:-
//Normal Get
var request = require('request');
request('http://127.0.0.1:8000',function(err,resp,flag){
console.log(resp.body);
});
//Opening a websocket
var WebSocket = require('ws');
var ws = new WebSocket('ws://127.0.0.1:8000/', {origin: 'http://127.0.0.1:8000'});
ws.on('open', function() {
console.log('connected');
ws.send(Date.now().toString(), {mask: true});
});
ws.on('close', function() {
console.log('disconnected');
});
ws.on('message', function(data, flags) {
console.log('Roundtrip time: ' + (Date.now() - parseInt(data)) + 'ms', flags);
setTimeout(function() {
ws.send(Date.now().toString(), {mask: true});
}, 500);
});
The first option gets the message as 'new message'
On the other side the second call throws the following error on the client side. On the server side, both commands pass through a 200OK
events.js:72
throw er; // Unhandled 'error' event
^
Error: unexpected server response (200)
at ClientRequest.<anonymous> (../ws/lib/WebSocket.js:603:17)
at ClientRequest.g (events.js:175:14)
at ClientRequest.EventEmitter.emit (events.js:95:17)
at HTTPParser.parserOnIncomingClient [as onIncoming] (http.js:1689:21)
at HTTPParser.parserOnHeadersComplete [as onHeadersComplete] (http.js:120:23)
at Socket.socketOnData [as ondata] (http.js:1584:20)
at TCP.onread (net.js:525:27)
On a side note if I log the request.is_websocket() on both calls it returns false meaning on the server side it never goes into the else part.
Please help me understand what mistake I am doing here
Thank you
Well,
I downloaded their entire code (not pip install) and run the supplied example chat program. Same error. The system sends a 400 response code for any ws:// call.
The git hub project page linked on the pypi site returns a 404 error. No way I can file a bug report. Emailed the developer and didn't get any response.
Probably something should have been broken on the new Django 1.5.2 version.
I consider that this is a dead project and hence moving to a complex but working solution like gevent or twisted.
thanks for your support!!!