Telegram bot aiogram erros - bots

mistakes
mistakes 2
photo
https://github.com/mahenzon/aiogram-lessons/tree/master/lesson-02
I can't understand why my code isn't working. I took code from here and only change file config.py, change token and MY_ID.
executor.py [ LINE:362 ]# INFO [2021-08-12 14:43:46,938] Bot: lap156 [#lab156_bot]
dispatcher.py [ LINE:360 ]# INFO [2021-08-12 14:43:46,938] Start polling.
base_events.py [ LINE:1738 ]# ERROR [2021-08-12 14:47:59,585] Task exception was never retrieved
future: <Task finished name='Task-24' coro=<Dispatcher._process_polling_updates() done, defined at C:\Users\Zver\AppData\Local\Programs\Python\Python39\lib\site-packages\aiogram\dispatcher\dispatcher.py:409> exception=WrongFileIdentifier('Wrong file identifier/http url specified')>
Traceback (most recent call last):
File "C:\Users\Zver\AppData\Local\Programs\Python\Python39\lib\site-packages\aiogram\dispatcher\dispatcher.py", line 417, in _process_polling_updates
for responses in itertools.chain.from_iterable(await self.process_updates(updates, fast)):
File "C:\Users\Zver\AppData\Local\Programs\Python\Python39\lib\site-packages\aiogram\dispatcher\dispatcher.py", line 238, in process_updates
return await asyncio.gather(*tasks)
File "C:\Users\Zver\AppData\Local\Programs\Python\Python39\lib\site-packages\aiogram\dispatcher\handler.py", line 116, in notify
response = await handler_obj.handler(*args, **partial_data)
File "C:\Users\Zver\AppData\Local\Programs\Python\Python39\lib\site-packages\aiogram\dispatcher\dispatcher.py", line 259, in process_update
return await self.message_handlers.notify(update.message)
File "C:\Users\Zver\AppData\Local\Programs\Python\Python39\lib\site-packages\aiogram\dispatcher\handler.py", line 116, in notify
response = await handler_obj.handler(*args, **partial_data)
File "C:\Users\Zver\aiogram-lessons\lesson-02\bot.py", line 55, in process_photo_command
await bot.send_photo(message.from_user.id, CAT_BIG_EYES,
File "C:\Users\Zver\AppData\Local\Programs\Python\Python39\lib\site-packages\aiogram\bot\bot.py", line 482, in send_photo
result = await self.request(api.Methods.SEND_PHOTO, payload, files)
File "C:\Users\Zver\AppData\Local\Programs\Python\Python39\lib\site-packages\aiogram\bot\base.py", line 208, in request
return await api.make_request(self.session, self.server, self.__token, method, data, files,
File "C:\Users\Zver\AppData\Local\Programs\Python\Python39\lib\site-packages\aiogram\bot\api.py", line 140, in make_request
return check_result(method, response.content_type, response.status, await response.text())
File "C:\Users\Zver\AppData\Local\Programs\Python\Python39\lib\site-packages\aiogram\bot\api.py", line 115, in check_result
exceptions.BadRequest.detect(description)
File "C:\Users\Zver\AppData\Local\Programs\Python\Python39\lib\site-packages\aiogram\utils\exceptions.py", line 140, in detect
raise err(cls.text or description)
aiogram.utils.exceptions.WrongFileIdentifier: Wrong file identifier/http url specified
base_events.py [ LINE:1738 ]# ERROR [2021-08-12 14:48:03,624] Task exception was never retrieved
future: <Task finished name='Task-32' coro=<Dispatcher._process_polling_updates() done, defined at C:\Users\Zver\AppData\Local\Programs\Python\Python39\lib\site-packages\aiogram\dispatcher\dispatcher.py:409> exception=WrongFileIdentifier('Wrong file identifier/http url specified')>
Traceback (most recent call last):
File "C:\Users\Zver\AppData\Local\Programs\Python\Python39\lib\site-packages\aiogram\dispatcher\dispatcher.py", line 417, in _process_polling_updates
for responses in itertools.chain.from_iterable(await self.process_updates(updates, fast)):
File "C:\Users\Zver\AppData\Local\Programs\Python\Python39\lib\site-packages\aiogram\dispatcher\dispatcher.py", line 238, in process_updates
return await asyncio.gather(*tasks)
File "C:\Users\Zver\AppData\Local\Programs\Python\Python39\lib\site-packages\aiogram\dispatcher\handler.py", line 116, in notify
response = await handler_obj.handler(*args, **partial_data)
File "C:\Users\Zver\AppData\Local\Programs\Python\Python39\lib\site-packages\aiogram\dispatcher\dispatcher.py", line 259, in process_update
return await self.message_handlers.notify(update.message)
File "C:\Users\Zver\AppData\Local\Programs\Python\Python39\lib\site-packages\aiogram\dispatcher\handler.py", line 116, in notify
response = await handler_obj.handler(*args, **partial_data)
File "C:\Users\Zver\aiogram-lessons\lesson-02\bot.py", line 73, in process_note_command
await bot.send_video_note(message.from_user.id, VIDEO_NOTE)
File "C:\Users\Zver\AppData\Local\Programs\Python\Python39\lib\site-packages\aiogram\bot\bot.py", line 963, in send_video_note
result = await self.request(api.Methods.SEND_VIDEO_NOTE, payload, files)
File "C:\Users\Zver\AppData\Local\Programs\Python\Python39\lib\site-packages\aiogram\bot\base.py", line 208, in request
return await api.make_request(self.session, self.server, self.__token, method, data, files,
File "C:\Users\Zver\AppData\Local\Programs\Python\Python39\lib\site-packages\aiogram\bot\api.py", line 140, in make_request
return check_result(method, response.content_type, response.status, await response.text())
File "C:\Users\Zver\AppData\Local\Programs\Python\Python39\lib\site-packages\aiogram\bot\api.py", line 115, in check_result
exceptions.BadRequest.detect(description)
File "C:\Users\Zver\AppData\Local\Programs\Python\Python39\lib\site-packages\aiogram\utils\exceptions.py", line 140, in detect
raise err(cls.text or description)
aiogram.utils.exceptions.WrongFileIdentifier: Wrong file identifier/http url specified
base_events.py [ LINE:1738 ]# ERROR [2021-08-12 14:48:06,943] Task exception was never retrieved
future: <Task finished name='Task-37' coro=<Dispatcher._process_polling_updates() done, defined at C:\Users\Zver\AppData\Local\Programs\Python\Python39\lib\site-packages\aiogram\dispatcher\dispatcher.py:409> exception=WrongFileIdentifier('Wrong file identifier/http url specified')>
Traceback (most recent call last):
File "C:\Users\Zver\AppData\Local\Programs\Python\Python39\lib\site-packages\aiogram\dispatcher\dispatcher.py", line 417, in _process_polling_updates
for responses in itertools.chain.from_iterable(await self.process_updates(updates, fast)):
File "C:\Users\Zver\AppData\Local\Programs\Python\Python39\lib\site-packages\aiogram\dispatcher\dispatcher.py", line 238, in process_updates
return await asyncio.gather(*tasks)
File "C:\Users\Zver\AppData\Local\Programs\Python\Python39\lib\site-packages\aiogram\dispatcher\handler.py", line 116, in notify
response = await handler_obj.handler(*args, **partial_data)
File "C:\Users\Zver\AppData\Local\Programs\Python\Python39\lib\site-packages\aiogram\dispatcher\dispatcher.py", line 259, in process_update
return await self.message_handlers.notify(update.message)
File "C:\Users\Zver\AppData\Local\Programs\Python\Python39\lib\site-packages\aiogram\dispatcher\handler.py", line 116, in notify
response = await handler_obj.handler(*args, **partial_data)
File "C:\Users\Zver\aiogram-lessons\lesson-02\bot.py", line 55, in process_photo_command
await bot.send_photo(message.from_user.id, CAT_BIG_EYES,
File "C:\Users\Zver\AppData\Local\Programs\Python\Python39\lib\site-packages\aiogram\bot\bot.py", line 482, in send_photo
result = await self.request(api.Methods.SEND_PHOTO, payload, files)
File "C:\Users\Zver\AppData\Local\Programs\Python\Python39\lib\site-packages\aiogram\bot\base.py", line 208, in request
return await api.make_request(self.session, self.server, self.__token, method, data, files,
File "C:\Users\Zver\AppData\Local\Programs\Python\Python39\lib\site-packages\aiogram\bot\api.py", line 140, in make_request
return check_result(method, response.content_type, response.status, await response.text())
File "C:\Users\Zver\AppData\Local\Programs\Python\Python39\lib\site-packages\aiogram\bot\api.py", line 115, in check_result
exceptions.BadRequest.detect(description)
File "C:\Users\Zver\AppData\Local\Programs\Python\Python39\lib\site-packages\aiogram\utils\exceptions.py", line 140, in detect
raise err(cls.text or description)
aiogram.utils.exceptions.WrongFileIdentifier: Wrong file identifier/http url specified
base_events.py [ LINE:1738 ]# ERROR [2021-08-12 14:48:15,298] Task exception was never retrieved
future: <Task finished name='Task-41' coro=<Dispatcher._process_polling_updates() done, defined at C:\Users\Zver\AppData\Local\Programs\Python\Python39\lib\site-packages\aiogram\dispatcher\dispatcher.py:409> exception=WrongFileIdentifier('Wrong file identifier/http url specified')>
Traceback (most recent call last):
File "C:\Users\Zver\AppData\Local\Programs\Python\Python39\lib\site-packages\aiogram\dispatcher\dispatcher.py", line 417, in _process_polling_updates
for responses in itertools.chain.from_iterable(await self.process_updates(updates, fast)):
File "C:\Users\Zver\AppData\Local\Programs\Python\Python39\lib\site-packages\aiogram\dispatcher\dispatcher.py", line 238, in process_updates
return await asyncio.gather(*tasks)
File "C:\Users\Zver\AppData\Local\Programs\Python\Python39\lib\site-packages\aiogram\dispatcher\handler.py", line 116, in notify
response = await handler_obj.handler(*args, **partial_data)
File "C:\Users\Zver\AppData\Local\Programs\Python\Python39\lib\site-packages\aiogram\dispatcher\dispatcher.py", line 259, in process_update
return await self.message_handlers.notify(update.message)
File "C:\Users\Zver\AppData\Local\Programs\Python\Python39\lib\site-packages\aiogram\dispatcher\handler.py", line 116, in notify
response = await handler_obj.handler(*args, **partial_data)
File "C:\Users\Zver\aiogram-lessons\lesson-02\bot.py", line 73, in process_note_command
await bot.send_video_note(message.from_user.id, VIDEO_NOTE)
File "C:\Users\Zver\AppData\Local\Programs\Python\Python39\lib\site-packages\aiogram\bot\bot.py", line 963, in send_video_note
result = await self.request(api.Methods.SEND_VIDEO_NOTE, payload, files)
File "C:\Users\Zver\AppData\Local\Programs\Python\Python39\lib\site-packages\aiogram\bot\base.py", line 208, in request
return await api.make_request(self.session, self.server, self.__token, method, data, files,
File "C:\Users\Zver\AppData\Local\Programs\Python\Python39\lib\site-packages\aiogram\bot\api.py", line 140, in make_request
return check_result(method, response.content_type, response.status, await response.text())
File "C:\Users\Zver\AppData\Local\Programs\Python\Python39\lib\site-packages\aiogram\bot\api.py", line 115, in check_result
exceptions.BadRequest.detect(description)
File "C:\Users\Zver\AppData\Local\Programs\Python\Python39\lib\site-packages\aiogram\utils\exceptions.py", line 140, in detect
raise err(cls.text or description)
aiogram.utils.exceptions.WrongFileIdentifier: Wrong file identifier/http url specified

I guess the error it seems that one running terminal of the bot is already running when you run your code. So Terminate all running terminals/processes and try again.

Related

Shiny for Python: Clearing Local Files on Session Close

How Do I Delete Local Files on Session Close?
My app allows users to upload a file and request some server-side stuff be done to it. Awesome. However, I don't want these files to stay there. Looking at the documentation, something like this should work (sanitized to protect the innocent)...
from shiny import App, reactive, render, ui
import os
def server(input, output, session):
def delete_uploaded_file():
try:
os.remove('file.xlsx')))
except:
# If there isn't a file, it's not really a problem
pass
# This triggers at the end of a session
session.on_ended(delete_uploaded_file())
# this closes the session when the user exits out on their browser
#reactive.Effect
#reactive.event(input.close)
async def _():
await session.close()
app = App(app_ui, server)
but it yields an 'Exception in ASGI application' and a 'TypeError,' all without triggering any of the above code. Everything in the traceback seems to point to shiny, so what am I doing wrong here?
ERROR: Exception in ASGI application
Traceback (most recent call last):
File "C:\Users\username\AppData\Roaming\Python\Python39\site-packages\uvicorn\protocols\websockets\websockets_impl.py", line 238, in run_asgi
result = await self.app(self.scope, self.asgi_receive, self.asgi_send)
File "C:\Users\e365627\AppData\Roaming\Python\Python39\site-packages\uvicorn\middleware\proxy_headers.py", line 78, in __call__
return await self.app(scope, receive, send)
File "C:\Users\username\AppData\Roaming\Python\Python39\site-packages\shiny\_app.py", line 220, in __call__
await self.starlette_app(scope, receive, send)
File "C:\Users\username\AppData\Roaming\Python\Python39\site-packages\starlette\applications.py", line 124, in __call__
await self.middleware_stack(scope, receive, send)
File "C:\Users\username\AppData\Roaming\Python\Python39\site-packages\starlette\middleware\errors.py", line 149, in __call__
await self.app(scope, receive, send)
File "C:\Users\username\AppData\Roaming\Python\Python39\site-packages\shiny\_autoreload.py", line 114, in __call__
return await self.app(scope, receive, send)
File "C:\Users\username\AppData\Roaming\Python\Python39\site-packages\starlette\middleware\exceptions.py", line 79, in __call__
raise exc
File "C:\Users\username\AppData\Roaming\Python\Python39\site-packages\starlette\middleware\exceptions.py", line 68, in __call__
await self.app(scope, receive, sender)
File "C:\Users\username\AppData\Roaming\Python\Python39\site-packages\starlette\routing.py", line 706, in __call__
await route.handle(scope, receive, send)
File "C:\Users\username\AppData\Roaming\Python\Python39\site-packages\starlette\routing.py", line 341, in handle
await self.app(scope, receive, send)
File "C:\Users\username\AppData\Roaming\Python\Python39\site-packages\starlette\routing.py", line 82, in app
await func(session)
File "C:\Users\username\AppData\Roaming\Python\Python39\site-packages\shiny\_app.py", line 294, in _on_connect_cb
await session._run()
File "C:\Users\username\AppData\Roaming\Python\Python39\site-packages\shiny\session\_session.py", line 326, in _run
self._run_session_end_tasks()
File "C:\Users\username\AppData\Roaming\Python\Python39\site-packages\shiny\session\_session.py", line 228, in _run_session_end_tasks
self._on_ended_callbacks.invoke()
File "C:\Users\username\AppData\Python\Python39\site-packages\shiny\_utils.py", line 335, in invoke
fn()
TypeError: 'NoneType' object is not callable
INFO: connection closed

FastAPI FileResponse not entering the except block

Good afternoon friends.
I am having issues with FastApi's FileResponse and catching FileNotFoundError (or any, really) exceptions.
Here's my script:
import os
import sys
from fastapi import FastAPI, HTTPException, File, UploadFile
from fastapi.responses import FileResponse, JSONResponse
from fastapi.encoders import jsonable_encoder
#app.get("/download/{namespace}/{file_name}", response_class=FileResponse)
async def processed_file(namespace: str, file_name: str):
try:
logger.info("About to return file")
return FileResponse(
path=f'{data/{namespace}/{file_name}',
media_type="application/pdf",
filename=file_name,
)
except:
logger.info("Should log this, it doesn't")
raise HTTPException(status_code=404, detail="File not found")
If I call the API endpoint with a path to a non-existing file (which the user can do just by changing one letter in the name of the file, hence the need for this exception),
I can read in the console the following stack trace error:
[2022-10-17 21:00:24 +0000] [8] [ERROR] Exception in ASGI application
Traceback (most recent call last):
File "/opt/venv/lib/python3.9/site-packages/uvicorn/protocols/http/h11_impl.py", line 404, in run_asgi
result = await app( # type: ignore[func-returns-value]
File "/opt/venv/lib/python3.9/site-packages/uvicorn/middleware/proxy_headers.py", line 78, in __call__
return await self.app(scope, receive, send)
File "/opt/venv/lib/python3.9/site-packages/fastapi/applications.py", line 199, in __call__
await super().__call__(scope, receive, send)
File "/opt/venv/lib/python3.9/site-packages/sentry_sdk/integrations/starlette.py", line 293, in _sentry_patched_asgi_app
return await middleware(scope, receive, send)
File "/opt/venv/lib/python3.9/site-packages/sentry_sdk/integrations/asgi.py", line 138, in _run_asgi3
return await self._run_app(scope, lambda: self.app(scope, receive, send))
File "/opt/venv/lib/python3.9/site-packages/sentry_sdk/integrations/asgi.py", line 187, in _run_app
raise exc from None
File "/opt/venv/lib/python3.9/site-packages/sentry_sdk/integrations/asgi.py", line 182, in _run_app
return await callback()
File "/opt/venv/lib/python3.9/site-packages/starlette/applications.py", line 112, in __call__
await self.middleware_stack(scope, receive, send)
File "/opt/venv/lib/python3.9/site-packages/sentry_sdk/integrations/starlette.py", line 98, in _create_span_call
await old_call(*args, **kwargs)
File "/opt/venv/lib/python3.9/site-packages/starlette/middleware/errors.py", line 181, in __call__
raise exc from None
File "/opt/venv/lib/python3.9/site-packages/starlette/middleware/errors.py", line 159, in __call__
await self.app(scope, receive, _send)
File "/opt/venv/lib/python3.9/site-packages/sentry_sdk/integrations/asgi.py", line 138, in _run_asgi3
return await self._run_app(scope, lambda: self.app(scope, receive, send))
File "/opt/venv/lib/python3.9/site-packages/sentry_sdk/integrations/asgi.py", line 148, in _run_app
raise exc from None
File "/opt/venv/lib/python3.9/site-packages/sentry_sdk/integrations/asgi.py", line 145, in _run_app
return await callback()
File "/opt/venv/lib/python3.9/site-packages/sentry_sdk/integrations/starlette.py", line 191, in _sentry_exceptionmiddleware_call
await old_call(self, scope, receive, send)
File "/opt/venv/lib/python3.9/site-packages/sentry_sdk/integrations/starlette.py", line 98, in _create_span_call
await old_call(*args, **kwargs)
File "/opt/venv/lib/python3.9/site-packages/starlette/exceptions.py", line 82, in __call__
raise exc from None
File "/opt/venv/lib/python3.9/site-packages/starlette/exceptions.py", line 71, in __call__
await self.app(scope, receive, sender)
File "/opt/venv/lib/python3.9/site-packages/starlette/routing.py", line 580, in __call__
await route.handle(scope, receive, send)
File "/opt/venv/lib/python3.9/site-packages/starlette/routing.py", line 241, in handle
await self.app(scope, receive, send)
File "/opt/venv/lib/python3.9/site-packages/starlette/routing.py", line 55, in app
await response(scope, receive, send)
File "/opt/venv/lib/python3.9/site-packages/starlette/responses.py", line 286, in __call__
raise RuntimeError(f"File at path {self.path} does not exist.")
RuntimeError: File at path /app/src/../data/new-namespace/wrong.pdf does not exist.
Note: I originally had except FileNotFoundError: instead of the general exception, still nothing works.
The log file correctly shows the "About to return file" entry, it never reaches the exception with the "should log this...". It also, obviously, does not return the 404 HTTPException. The stack trace error never gets to "my own" file, they are exceptions that are all within the site-packages folder.
I am baffled by this as I would have hoped that my solution would catch any exception. Still, the process is not doing what I was expecting. I have a hunch that I'm missing something obvious.
Thanks for any help, best regards,
Rafa.
The exception is raised after the return - i.e. the exception doesn't get raised when you create FileResponse - it gets raised when Starlette (the library under FastAPI) tries to read the file and return it.
Since it never gets raised in your code, there is nothing for you to catch.
Instead you could validate that whether the requested file is valid or not yourself - Starlette calls os.stat on the file and checks whether the result is None - you could do that (it's probably a good idea to validate that the filename is among the allowed files instead of blindly trusting information from a user) - or you could wrap the existing FileResponse and handle the exception there (in your own implementation of __call__ that calls into the parent class).

FastAPI Raises Missing Positional Argument Error

The following code raises the following exception.
I'm not sure I fully understand how FastAPI works. Could someone help me understand?
from fastapi import FastAPI
from fastapi import BackgroundTasks
from fastapi import Request
app = FastAPI()
async def parse_request(req: Request):
print(req)
print(req.client.host)
#app.route("/endpoint")
async def endpoint(request: Request, background_tasks: BackgroundTasks):
background_tasks.add_task(parse_request, request)
return {"msg": "ok"}
Exception:
Traceback (most recent call last):
File "/home/user/repos/fastapi_pg/env_39/lib/python3.9/site-packages/uvicorn/protocols/http/h11_impl.py", line 396, in run_asgi
result = await app(self.scope, self.receive, self.send)
File "/home/user/repos/fastapi_pg/env_39/lib/python3.9/site-packages/uvicorn/middleware/proxy_headers.py", line 45, in __call__
return await self.app(scope, receive, send)
File "/home/user/repos/fastapi_pg/env_39/lib/python3.9/site-packages/fastapi/applications.py", line 199, in __call__
await super().__call__(scope, receive, send)
File "/home/user/repos/fastapi_pg/env_39/lib/python3.9/site-packages/starlette/applications.py", line 112, in __call__
await self.middleware_stack(scope, receive, send)
File "/home/user/repos/fastapi_pg/env_39/lib/python3.9/site-packages/starlette/middleware/errors.py", line 181, in __call__
raise exc from None
File "/home/user/repos/fastapi_pg/env_39/lib/python3.9/site-packages/starlette/middleware/errors.py", line 159, in __call__
await self.app(scope, receive, _send)
File "/home/user/repos/fastapi_pg/env_39/lib/python3.9/site-packages/starlette/exceptions.py", line 82, in __call__
raise exc from None
File "/home/user/repos/fastapi_pg/env_39/lib/python3.9/site-packages/starlette/exceptions.py", line 71, in __call__
await self.app(scope, receive, sender)
File "/home/user/repos/fastapi_pg/env_39/lib/python3.9/site-packages/starlette/routing.py", line 580, in __call__
await route.handle(scope, receive, send)
File "/home/user/repos/fastapi_pg/env_39/lib/python3.9/site-packages/starlette/routing.py", line 241, in handle
await self.app(scope, receive, send)
File "/home/user/repos/fastapi_pg/env_39/lib/python3.9/site-packages/starlette/routing.py", line 52, in app
response = await func(request)
TypeError: endpoint() missing 1 required positional argument: 'background_tasks'
I've gotten this to work without the Request param when I pass in my own variable in the route path:
#app.get("/test/{input_str}")
async def test(input_str: str, background_tasks: BackgroundTasks):
background_tasks.add_task(do_stuff, input_str)
return {"Hello": "World"}
Seems like Starlette doesn't know how to handle multiple of these params being passed so you can't mix and match. Ideal I'd be able to take the Request and Header objects and pass them to a background task for processing.
The decorator #app.route seems to be the problem. (see: https://github.com/tiangolo/fastapi/issues/912) Use #app.api_route instead or even better #app.get or #app.post.

Python3 + selenium + PhantomJS UnicodeDecodeError

ENV
PhantomJS2.1.1;Windows10;selenium-3.8.0;python3
CODE
browser = webdriver.PhantomJS() //throw a UnicodeDecodeError
Problem
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xbd in position
2: invalid start byte
Details
Traceback (most recent call last):
File "d:/devtools/phantomjs-2.1.1-windows/bin/IndustryLeaderSpider.py",
line 20, in
browser = webdriver.PhantomJS('D:/phantomjs.exe')
File "D:\Continuum\Anaconda3\lib\site-packages\selenium\webdriver\phantomjs\webdriver.py",
line 58, in init
desired_capabilities=desired_capabilities)
File "D:\Continuum\Anaconda3\lib\site-packages\selenium\webdriver\remote\webdriver.py",
line 154, in init
self.start_session(desired_capabilities, browser_profile)
File "D:\Continuum\Anaconda3\lib\site-packages\selenium\webdriver\remote\webdriver.py",
line 243, in start_session
response = self.execute(Command.NEW_SESSION, parameters)
File "D:\Continuum\Anaconda3\lib\site-packages\selenium\webdriver\remote\webdriver.py",
line 309, in execute
response = self.command_executor.execute(driver_command, params)
File "D:\Continuum\Anaconda3\lib\site-packages\selenium\webdriver\remote\remote_connection.py",
line 460, in execute
return self._request(command_info[0], url, body=data)
File "D:\Continuum\Anaconda3\lib\site-packages\selenium\webdriver\remote\remote_connection.py",
line 522, in _request
resp = opener.open(request, timeout=self._timeout)
File "D:\Continuum\Anaconda3\lib\urllib\request.py", line 526, in open
response = self._open(req, data)
File "D:\Continuum\Anaconda3\lib\urllib\request.py", line 544, in _open
'_open', req)
File "D:\Continuum\Anaconda3\lib\urllib\request.py", line 504, in _call_chain
result = func(*args)
File "D:\Continuum\Anaconda3\lib\urllib\request.py", line 806, in
meth(r, proxy, type))
File "D:\Continuum\Anaconda3\lib\urllib\request.py", line 814, in proxy_open
if req.host and proxy_bypass(req.host):
File "D:\Continuum\Anaconda3\lib\urllib\request.py", line 2739, in proxy_bypass
return proxy_bypass_registry(host)
File "D:\Continuum\Anaconda3\lib\urllib\request.py", line 2706, in proxy_bypass_registry
fqdn = socket.getfqdn(rawHost)
File "D:\Continuum\Anaconda3\lib\socket.py", line 673, in getfqdn
hostname, aliases, ipaddrs = gethostbyaddr(name)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xbd in position 2: invalid start byte
Do someone have this problem? How to fix it?
Your main error seems to be :
File "D:\Continuum\Anaconda3\lib\site-packages\selenium\webdriver\remote\remote_connection.py", line 460, in execute return self._request(command_info[0], url, body=data) File "D:\Continuum\Anaconda3\lib\site-packages\selenium\webdriver\remote\remote_connection.py", line 522, in _request resp = opener.open(request, timeout=self._timeout) File "D:\Continuum\Anaconda3\lib\urllib\request.py", line 526, in open response = self._open(req, data)
Try the following steps :
Run CCleaner tool to wipe off all the OS chores.
Take a System Reboot.
While you initiate PhantomJS() provide the absolute path of the phantomjs binary as follows :
driver = webdriver.PhantomJS(executable_path=r'C:\path\to\phantomjs.exe')
Ensure that there is no unnecessary imports in your script. Example : urllib.request
Execute your Test.

Authorization error from Python twitter tools

Trying to use Python Twitter Tools to search for the tweeets containing a hashtag. (On a raspberry Pi with python3).
from twitter import *
token = "token"
token_key = "token_key"
con_secret = "con_secret"
con_secret_key = "con_secret_key"
t = Twitter(
auth=OAuth(token, token_key, con_secret, con_secret_key))
print(t.search.tweets(q="#test"))
But I always get a Authorization error.
Traceback (most recent call last):
File "/usr/local/lib/python3.4/dist-packages/twitter/api.py", line 319, in _handle_response
handle = urllib_request.urlopen(req, **kwargs)
File "/usr/lib/python3.4/urllib/request.py", line 153, in urlopen
return opener.open(url, data, timeout)
File "/usr/lib/python3.4/urllib/request.py", line 461, in open
response = meth(req, response)
File "/usr/lib/python3.4/urllib/request.py", line 571, in http_response
'http', request, response, code, msg, hdrs)
File "/usr/lib/python3.4/urllib/request.py", line 499, in error
return self._call_chain(*args)
File "/usr/lib/python3.4/urllib/request.py", line 433, in _call_chain
result = func(*args)
File "/usr/lib/python3.4/urllib/request.py", line 579, in http_error_default
raise HTTPError(req.full_url, code, msg, hdrs, fp)
urllib.error.HTTPError: HTTP Error 401: Authorization Required
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "twitter-test.py", line 10, in <module>
print(t.search.tweets(q="#test"))
File "/usr/local/lib/python3.4/dist-packages/twitter/api.py", line 312, in __call__
return self._handle_response(req, uri, arg_data, _timeout)
File "/usr/local/lib/python3.4/dist-packages/twitter/api.py", line 345, in _handle_response
raise TwitterHTTPError(e, uri, self.format, arg_data)
twitter.api.TwitterHTTPError: Twitter sent status 401 for URL: 1.1/search/tweets.json using parameters: (oauth_consumer_key=**key**&oauth_nonce=**nonce**&oauth_signature_method=HMAC-SHA1&oauth_timestamp=1438333973&oauth_token=**token**&oauth_version=1.0&q=%23test&oauth_signature=**signature**)
details: {'errors': [{'code': 32, 'message': 'Could not authenticate you.'}]}
I have tried checking my time (and changing the timezone).
I have tried putting in a callback URL into the app settings and regenerating the keys.
Any help appreciated
Thanks
Couldn't fix this so moved to tweepy library which works a treat!

Resources