Cannot close a running event loop. Discord bot creation - python-3.x

I tried a few different codes but they all seem to be giving me the same error.
import discord
client = discord.Client()
client.run("TheBotTokenzzzInQuotes")
And it's giving me this error
File "<ipython-input-1-1f31c2ad1160>", line 1, in <module>
runfile('C:/Users/Lenovo/Desktop/bot.py', wdir='C:/Users/Lenovo/Desktop')
File "C:\Users\Lenovo\Anaconda3\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 827, in runfile
execfile(filename, namespace)
File "C:\Users\Lenovo\Anaconda3\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 110, in execfile
exec(compile(f.read(), filename, 'exec'), namespace)
File "C:/Users/Lenovo/Desktop/bot.py", line 4, in <module>
client.run("token")
File "C:\Users\Lenovo\Anaconda3\lib\site-packages\discord\client.py", line 637, in run
_cleanup_loop(loop)
File "C:\Users\Lenovo\Anaconda3\lib\site-packages\discord\client.py", line 97, in _cleanup_loop
loop.close()
File "C:\Users\Lenovo\Anaconda3\lib\asyncio\selector_events.py", line 83, in close
raise RuntimeError("Cannot close a running event loop")
RuntimeError: Cannot close a running event loop

I have my own discord bot that I run, and the client variable for mine doesn't look anything like that if I'm being honest.
If you are not using "Discord.py Rewrite", that could be a possible reason for a failure.
Another possible reason(although very unlikely) is that you do not have aiohttp installed(which is the dependency asyncio needs for Discord.py Rewrite), you can install it by using the following command:
pip install aiohttp
If you would like an example bot to look at, I have listed one below that is directly from the developer of discord.py Rewrite(the version that is currently supported for python).
https://github.com/Rapptz/discord.py/blob/master/examples/basic_bot.py
If you were wondering what the beginning of my code looked like, I have it below this:
import discord
from discord.ext import commands
from discord.utils import get
client = commands.Bot(command_prefix = '>')

Related

UndetectedChromedriver Extension Issue

I can't use extensions on UndetectedChromedriver PYPI Package (Python). If I use it with normal selenium its works, but not with this package. I tried to install extensions directly from webstore, but Chrome Webstore Alert is not an Alert to handle with selenium is a Window Event, so we need to use AutoIT, Pyautogui, etc... To handle that.
The only thing is working is loading profiles, but... I'm working for multiprocess windows, is working, but I need to create houndred of windows and then delete them. And I can't clone profiles, because UndetectedChromedriver doesn't work, i need to create manually.
Finally i tried with Google Chrome Enterprise Bundle, then I used Extensions policy to install forced the extension for all profiles. And yes, is working, but if I enabled that, selenium, doesn't work properly.
The error traceback log is:
Exception in thread Thread-2:
Traceback (most recent call last):
File "C:\Users\andre\anaconda3\envs\selenium-env\lib\threading.py", line 950, in _bootstrap_inner
self.run()
File "C:\Users\andre\anaconda3\envs\selenium-env\lib\threading.py", line 888, in run
self._target(*self._args, **self._kwargs)
File "C:\Users\andre\OneDrive\Documentos\(A1)_Inicio\(A2)_CyberEspacio\LAB\(A1)_Programador123\(A1)_Programming_(Section)\VSCode Snippets\python\selenium\app.py", line 72, in test
seleniumCaptchaSolver.reCaptchaServiceLogin(apiKey='MYAPIKEY', solverType = SeleniumCaptchaSolverType().Capmonster)
File "C:\Users\andre\OneDrive\Documentos\(A1)_Inicio\(A2)_CyberEspacio\LAB\(A1)_Programador123\(A1)_Programming_(Section)\VSCode Snippets\python\selenium\modules\seleniumCaptchaSolver.py", line 103, in reCaptchaServiceLogin
self.__driver.get('chrome-extension://pabjfbciaedomjjfelfafejkppknjleh/popup.html')
File "C:\Users\andre\anaconda3\envs\selenium-env\lib\site-packages\undetected_chromedriver\__init__.py", line 535, in get
return super().get(url)
File "C:\Users\andre\anaconda3\envs\selenium-env\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 447, in get
self.execute(Command.GET, {'url': url})
File "C:\Users\andre\anaconda3\envs\selenium-env\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 435, in execute
self.error_handler.check_response(response)
File "C:\Users\andre\anaconda3\envs\selenium-env\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 247, in check_response
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.WebDriverException: Message: unknown error: cannot determine loading status
from disconnected: received Inspector.detached event
(Session info: chrome=103.0.5060.134)
This happen only when chrome-extension://pabjfbciaedomjjfelfafejkppknjleh/popup.html is opened to login (Send APi Key). I can login etc... But when Policy is Activated I can't because of that issue.
Anyone here know how to fix that or properly use extensions in UndetctedChromedriver?
Note: This error only happens if i load chrome-extension://pabjfbciaedomjjfelfafejkppknjleh/popup.html link, others links works.
I found this solution:
import undetected_chromedriver as uc
import os
working_dir = os.getcwd()
# Im using proxy extension
proxy_plugin = f'{working_dir}/proxy_plugin'
options = uc.ChromeOptions()
options.add_argument(f'--load-extension={proxy_plugin}')
# {proxy_plugin} path to extension folder, I tried to import .zip file
# and this doesnt working, maybe you can try import .crx file
# Also, I use extensions.ui.developer_mode
options.add_experimental_option('prefs', { 'extensions.ui.developer_mode': True })
driver = uc.Chrome(options = options)
extensions.ui.developer_mode
Yet, I seen this pages:
Load unpacked Chrome extension programmatically
Installing extension into V2

asyncio import issues - no attribute 'StreamReader'

I have had asyncio and websockets work fine several times, but for some reason it sometimes refuses to run and will refuse to ever run again. I have had this happen across multiple devices, with code as simple as just imports:
import asyncio
import json
import websockets
Interestingly, when using Pydroid3 on Android, any code I write with asyncio works fine, but only until I save it to a file. Once it's been saved, it stops working. I can copy all the text and paste it to a new, unsaved file and it again works fine until saved. This awful solution does not work for Windows, unfortunately. I am using Python 3.9.0 for Windows. The stacktrace produced by running the code shown above is as follows:
Traceback (most recent call last):
File "C:\Users\user\Documents\AtomTests\socket.py", line 1, in <module>
import asyncio
File "C:\Users\user\AppData\Local\Programs\Python\Python39\lib\asyncio\__init__.py", line 8, in <module>
from .base_events import *
File "C:\Users\user\AppData\Local\Programs\Python\Python39\lib\asyncio\base_events.py", line 23, in <module>
import socket
File "C:\Users\user\Documents\AtomTests\socket.py", line 3, in <module>
import websockets
File "C:\Users\user\AppData\Local\Programs\Python\Python39\lib\site-packages\websockets\__init__.py", line 3, in <module>
from .auth import * # noqa
File "C:\Users\user\AppData\Local\Programs\Python\Python39\lib\site-packages\websockets\auth.py", line 12, in <module>
from .exceptions import InvalidHeader
File "C:\Users\user\AppData\Local\Programs\Python\Python39\lib\site-packages\websockets\exceptions.py", line 33, in <module>
from .http import Headers, HeadersLike
File "C:\Users\user\AppData\Local\Programs\Python\Python39\lib\site-packages\websockets\http.py", line 70, in <module>
async def read_request(stream: asyncio.StreamReader) -> Tuple[str, "Headers"]:
AttributeError: partially initialized module 'asyncio' has no attribute 'StreamReader' (most likely due to a circular import)
[Finished in 0.158s]
I've searched a bit for this error, but either it's uncommon or I'm just blind, because I couldn't find anything. Has anyone else had this happen to them?
Your local socket.py file is shadowing Python’s socket module. Rename your file and your imports will work.

Selenium code running locally but not on server

Both the server and my computer have geckodriver 0.26.0, Firefox 71, and Selenium 3.141.0.
My computer has MacOS Mojave with python 3.8 and the server is CentOS 7 with python 3.7. The code runs perfectly on my computer, but it returns errors on the server.
I don't remember how, but I have been getting different errors depending on if I add breakpoints to it, or if I run it in terminal or submit the job in SLURM.
On terminal:
File "Main.py", line 230, in <module>
main()
File "Main.py", line 179, in main
dfs=get_data(stations, inidate, findate)
File "Main.py", line 113, in get_data
list_files=return_list_day(date)
File "Main.py", line 66, in return_list_day
driver.get(webdir)
File "/home/user/.local/lib/python3.7/site-packages/selenium/webdriver/remote/webdriver.py", line 333, in get
self.execute(Command.GET, {'url': url})
File "/home/user/.local/lib/python3.7/site-packages/selenium/webdriver/remote/webdriver.py", line 321, in execute
self.error_handler.check_response(response)
File "/home/user/.local/lib/python3.7/site-packages/selenium/webdriver/remote/errorhandler.py", line 242, in check_response
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.WebDriverException: Message: Failed to decode response from marionette
or
Submitted on SLURM (and most often error):
Traceback (most recent call last):
File "Main.py", line 230, in <module>
main()
File "Main.py", line 179, in main
dfs=get_data(stations, inidate, findate)
File "Main.py", line 113, in get_data
list_files=return_list_day(date)
File "Main.py", line 66, in return_list_day
driver.get(webdir)
File "/home/user/.local/lib/python3.7/site-packages/selenium/webdriver/remote/webdriver.py", line 333, in get
self.execute(Command.GET, {'url': url})
File "/home/user/.local/lib/python3.7/site-packages/selenium/webdriver/remote/webdriver.py", line 321, in execute
self.error_handler.check_response(response)
File "/home/user/.local/lib/python3.7/site-packages/selenium/webdriver/remote/errorhandler.py", line 242, in check_response
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.TimeoutException: Message: Timeout loading page after 300000ms
I can use Selenium without issues in another unrelated code that finishes perfectly fine. So I don't understand why Selenium is having a hard time here or where it comes from.
The code fails here:
## Commented parts are cuz I tried running with the MOZ_HEADLESS tag on terminal
## Didnt make a difference as far as I could tell.
#options = Options()
#options.headless = True
driver = webdriver.Firefox()#options=options)
driver.get(webdir) ##<-- HERE
## Added these because of other replies to this issue I found
driver.implicitly_wait(7)
time.sleep(3)
.
.
.
driver.close()
That bit of codes retrieves a list from the webpage and is ran inside a for-loop. The error is not in the retrieving part, is in driver.get(webdir). I can't share the website since it's literally like looking into the server of a partner institution. webdir is a directory and I am basically waiting till its contents are loaded so I can retrieve its file names.
I know you can't help much without a website, but do the errors I've shown give any indication as to what the problem might be?. Can the retrieving of a specific website behave differently based on OS? I have googled the errors, found questions here, read through them and applied them to see how it changed, and nothing did or I got a different error (either one of the two above).
I found this that states incompatibility between gecko and Mozilla, but since I can successfully run another (unrelated) code with the exact calling and usage of Selenium (only different URL given) then I don't think that's my issue.
Thanks for any help! Let me know what other information I could give that might help.
Edit:
It is not the same as the question that was linked, since I have given it sleep time and didn't change anything. It has 40 GB of ram allocated so its not dying out of too little memory. Which are the solutions shown in this question.
For anyone with this issue, the server updated Firefox to version 79.0 and now it works without any issues. Nothing else was changed as far as I was let known.
I assume the version change fixed it but I don't know exactly how. It's worth a try if anyone else was experiencing the same as I was with different errors depending on how it was run.

Can't create s3 resource/client in boto3

EDIT: I believe this traceback stems from some sort of issue with the dependencies. Using pip to upgrade the packages didn't work but I created a new folder and installed from scratch and that worked out
I'm a Python novice so I'm struggling to debug an AWS Lambda I'm writing.
I've narrowed it down to this line of code s3_client = botoSession.resource('s3'), which is giving a long traceback with Syntax Error: invalid syntax. The botoSession variable is just for the credentials - botoSession = boto3.session.Session(aws_access_token, aws_secret_access_token).
I've also tried s3_client = boto3.client('s3'), s3_client = boto3.resource('s3'), s3_client = botoSession.resource('s3').
When I used botoSession.client('ses', region) I had no issues sending emails.
I found Error: client = boto3.client('s3') | AWS Elastic Beanstalk Worker Environment which appeared to be a similar issue, but it appeared to be fairly old and I wasn't able to figure out what the solution was. I tried adding
import sys
sys.path = [p for p in sys.path if not p.endswith('futures-3.0.3-py3.4.egg')]
to the top of my file which didn't seem to work.
The entire traceback is as follows:
Traceback (most recent call last):
File "smartsheetExporter.py", line 45, in <module>
s3_client = botoSession.resource('s3')
File "/Users/nihar/LocalDocs/PythonPractice/Smartsheet-Emailer-Lambda/boto3/session.py", line 389, in resource
aws_session_token=aws_session_token, config=config)
File "/Users/nihar/LocalDocs/PythonPractice/Smartsheet-Emailer-Lambda/boto3/session.py", line 263, in client
aws_session_token=aws_session_token, config=config)
File "/Users/nihar/LocalDocs/PythonPractice/Smartsheet-Emailer-Lambda/botocore/session.py", line 836, in create_client
client_config=config, api_version=api_version)
File "/Users/nihar/LocalDocs/PythonPractice/Smartsheet-Emailer-Lambda/botocore/client.py", line 65, in create_client
cls = self._create_client_class(service_name, service_model)
File "/Users/nihar/LocalDocs/PythonPractice/Smartsheet-Emailer-Lambda/botocore/client.py", line 90, in _create_client_class
base_classes=bases)
File "/Users/nihar/LocalDocs/PythonPractice/Smartsheet-Emailer-Lambda/botocore/hooks.py", line 227, in emit
return self._emit(event_name, kwargs)
File "/Users/nihar/LocalDocs/PythonPractice/Smartsheet-Emailer-Lambda/botocore/hooks.py", line 210, in _emit
response = handler(**kwargs)
File "/Users/nihar/LocalDocs/PythonPractice/Smartsheet-Emailer-Lambda/boto3/utils.py", line 61, in _handler
module = import_module(module)
File "/Users/nihar/LocalDocs/PythonPractice/Smartsheet-Emailer-Lambda/boto3/utils.py", line 52, in import_module
__import__(name)
File "/Users/nihar/LocalDocs/PythonPractice/Smartsheet-Emailer-Lambda/boto3/s3/inject.py", line 15, in <module>
from boto3.s3.transfer import create_transfer_manager
File "/Users/nihar/LocalDocs/PythonPractice/Smartsheet-Emailer-Lambda/boto3/s3/transfer.py", line 127, in <module>
from s3transfer.exceptions import RetriesExceededError as \
File "/Users/nihar/LocalDocs/PythonPractice/Smartsheet-Emailer-Lambda/s3transfer/__init__.py", line 134, in <module>
import concurrent.futures
File "/Users/nihar/LocalDocs/PythonPractice/Smartsheet-Emailer-Lambda/concurrent/futures/__init__.py", line 8, in <module>
from concurrent.futures._base import (FIRST_COMPLETED,
File "/Users/nihar/LocalDocs/PythonPractice/Smartsheet-Emailer-Lambda/concurrent/futures/_base.py", line 381
raise exception_type, self._exception, self._traceback
^
SyntaxError: invalid syntax
Whenever strange things are happening, it's always a good idea to update things:
sudo pip install pip --upgrade
sudo pip install boto --upgrade
sudo pip install boto3 --upgrade
sudo pip install awscli --upgrade
If you're using Python 3, try pip3 instead of pip.
I just had this same issue with boto3 and ended up having to downgrade the Python version that my lambda was running from Python 3.6 to Python 2.7. If you're using Serverless Framework for this, your serverless.yml file looks like this.
provider:
name: aws
runtime: python3.6
memorySize: 3008
cool_function:
name: cool-function
description: This lambda goes and performs magic.
handler: cool_function.lambda_handler
runtime: python2.7
- schedule:
rate: rate(4 hours)
timeout: 180
I had the same problem with python 3.6 and AWS Lambda.
I found another answer that helped me here.
You should use futures==2.2.0
If you are running your code on an Amazon EC2 instance with a Role assigned to the instance, then you only need this:
import boto3
s3_client = boto3.client('s3')
s3_resource = boto3.resource('s3') # Pick whichever is wish to use
If you are not on an Amazon EC2 instance, this works:
import boto3
session = boto3.Session(aws_access_key_id='AKIAxxx',aws_secret_access_key='yyy')
s3_client = session.client('s3')
s3_resource = session.resource('s3')
Of course, you should never put your credentials in the code file. Instead, put them in a credentials file (easiest is via aws configure) or in Environment Variables. That way, they won't be copied into any code repository.
See: Boto3 credentials

Pyramid mongodb scaffold failing on Python 3 due to Paste

Environment:
Python 3.2.3 (using virtualenv)
Pyramid 1.4
pyramid_mongodb scaffold
After installing myproject using pyramid_mongodb scaffold I ran python setup.py test -q and it's failing with below errors.
running build_ext
Traceback (most recent call last):
File "setup.py", line 33, in <module>
""",
File "/usr/lib/python3.2/distutils/core.py", line 148, in setup
dist.run_commands()
File "/usr/lib/python3.2/distutils/dist.py", line 917, in run_commands
self.run_command(cmd)
File "/usr/lib/python3.2/distutils/dist.py", line 936, in run_command
cmd_obj.run()
File "/root/App/Big3/lib/python3.2/site-packages/distribute-0.6.24-py3.2.egg/setuptools /command/test.py", line 137, in run
self.with_project_on_sys_path(self.run_tests)
File "/root/App/Big3/lib/python3.2/site-packages/distribute-0.6.24-py3.2.egg/setuptools /command/test.py", line 117, in with_project_on_sys_path
func()
File "/root/App/Big3/lib/python3.2/site-packages/distribute-0.6.24-py3.2.egg/setuptools /command/test.py", line 146, in run_tests
testLoader = loader_class()
File "/usr/lib/python3.2/unittest/main.py", line 123, in __init__
self.parseArgs(argv)
File "/usr/lib/python3.2/unittest/main.py", line 191, in parseArgs
self.createTests()
File "/usr/lib/python3.2/unittest/main.py", line 198, in createTests
self.module)
File "/usr/lib/python3.2/unittest/loader.py", line 132, in loadTestsFromNames
suites = [self.loadTestsFromName(name, module) for name in names]
File "/usr/lib/python3.2/unittest/loader.py", line 132, in <listcomp>
suites = [self.loadTestsFromName(name, module) for name in names]
File "/usr/lib/python3.2/unittest/loader.py", line 91, in loadTestsFromName
module = __import__('.'.join(parts_copy))
File "/root/App/Big3/Lime/lime/__init__.py", line 1, in <module>
from pyramid.config import Configurator
File "/root/App/Big3/lib/python3.2/site-packages/pyramid-1.4.1-py3.2.egg/pyramid/config /__init__.py", line 10, in <module>
from webob.exc import WSGIHTTPException as WebobWSGIHTTPException
File "/root/App/Big3/lib/python3.2/site-packages/WebOb-1.2.3-py3.2.egg/webob/exc.py", line 1115, in <module>
from paste import httpexceptions
File "/root/App/Big3/lib/python3.2/site-packages/Paste-1.7.5.1-py3.2.egg/paste /httpexceptions.py", line 634
except HTTPException, exc:
^
SyntaxError: invalid syntax
I understand the error, that Paste is not python3 compatible. I also know how to fix it but that would essentially mean porting Paste to python3 (which is something I don't want to do), so can anyone tell what I can do?
From the error stack I see that webob/exc.py is doing from paste import httpexceptions but when I checked the code I see that the import is under a try except block (without raising any error in except), so I even tried the test after removing paste from the lib but then when I run the test, I see that the setup.py is installing paste again
running test
Checking .pth file support in .
/root/App/Big3/bin/python -E -c pass
Searching for Paste>=1.7.1
I checked .pth files and removed reference to paste and then started re-installation of project but somehow it still sees paste as required
Installed /root/App/Big3/Myproject
Processing dependencies for Myproject==0.0
Searching for Paste>=1.7.1
Reading http://pypi.python.org/simple/Paste/
My setup.py file is same as this
Can someone tell me where is this paste dependency coming into my project.
I didn't intend to answer my own question but since I have made changes which are working for me, I thought I will share it here (assuming that there would be other folks wanting to have pyramid_mongodb scaffold work on python3)
Changes in development. ini
Removed
[pipeline:main]
pipeline =
egg:WebError#evalerror
{{project}}
Changed
[app:{{project}}] to [app:main]
Added (optional)
pyramid.includes =
pyramid_debugtoolbar
Changed server (from paste to waitress)
[server:main]
use = egg:waitress#main
host = 0.0.0.0
port = 6543
Changes in Setup.py
changed requires from
requires = ['pyramid', 'WebError', 'pymongo']
to
requires = ['pyramid', 'pyramid_debugtoolbar', 'pymongo', 'uwsgi', 'waitress']
It's important to remove webError
The application is now working...

Resources