Module 'discord' has no attribute 'Bot' in pycord version 2.3.2 - discord

I'm trying to switch from discord.py to pycord since I heard that they don't support slash commands, and while defining simple commands. I keep getting this great Traceback
`
Traceback (most recent call last):
File "c:\Users\****\source\repos\DBot\main.py", line 16, in <module>
bot = discord.Bot()
AttributeError: module 'discord' has no attribute 'Bot'
`
This is my code up until now.
`
import discord
import os
from dotenv import load_dotenv
# importing environmental vars
load_dotenv()
TOKEN = os.getenv("DISCORD_TOKEN")
GUILD = os.getenv("DISCORD_GUILD")
APP_ID = os.getenv("APP_ID")
PUB_KEY = os.getenv("PUBLIC_KEY")
GUILD_ID = os.getenv("GUILD_ID")
GENERAL_CHAN_ID = os.getenv("CHANNEL_GENERAL_ID")
#finished importing .env vars
#class for client
bot = discord.Bot()
#bot.slash_command()
async def hello(ctx, name: str = None):
name = name or ctx.author.name
await ctx.respond(f"Hello {name}!")
#bot.user_command(name="Say Hello")
async def hi(ctx, user):
await ctx.respond(f"{ctx.author.mention} says hello to {user.name}!")
bot.run("token")
`
I have py-cord version 2.3.2 so I know it's not version issue
I just started using py-cord so I have no idea what I'm doing except ctrl c ctrl v-ing examples from their documentation page to see if it works
Help is greatly appreciated!!!

I had the same mistake.
What fixed it for me was:
Go into your project directory.
pip install py-cord if this doesn't work, try step 3.
pip install py-cord==2.0.0rc1 this is a beta version of pycord.

Related

Cannot load extensions/cogs in Discord.py anymore on version

Code (most of it is hidden):
import discord
from discord import app_commands
from discord.ext import commands
intents = discord.Intents.default()
bot = discord.Client(
intents=intents,
description='REDACTED',
case_insensitive=True,
owner_id=REDACTED
)
#bot.event
async def on_ready():
print(f'Logged in as {bot.user.name} - {bot.user.id}')
bot.load_extension(cogs.Mod)
bot.run("token")
Error:
Traceback (most recent call last):
File "C:\Users\Personal\discord-bots\quantum.py\quantum.py", line 18, in <module>
bot.load_extension(cogs.Mod)
^^^^^^^^^^^^^^^^^^
AttributeError: 'Client' object has no attribute 'load_extension'
I was trying to be able to use the <bot/client>.load_<extension/cog>() prompt, but it didn't work all of a sudden.
On the current version of discord.py (2.1.0), you can only call load_extension on a discord.ext.commands.Bot (see https://discordpy.readthedocs.io/en/stable/ext/commands/api.html?highlight=load_extension#discord.ext.commands.Bot.load_extension)
As per the API documentation:
This class is a subclass of discord.Client and as a result anything that you can do with a discord.Client you can do with this bot.
So you shouldn't have any trouble replacing discord.Client with a commands.Bot in your existing code.

Discord.py Buttons Error unexpected keyword

Here is my code:
async def test(ctx):
await ctx.send(
"Discord Buttons!",
components=[
[Button(style=ButtonStyle.red, label="Red"),
Button(style=ButtonStyle.red, label="Red", disabled=True),
Button(style=ButtonStyle.URL, label="Youtube", url="https://youtube.com")],
Button(style=ButtonStyle.blue, label="Blue", emoji="😅"),
],
)
res = await bot.wait_for("button_click")
if res.channel == ctx.message.channel:
await res.repond(
type=InteractionType.ChannelMessageWithSource,
content=f"Pressed!"
)
And here is the error it keeps on giving:
Command raised an exception: TypeError: send() got an unexpected keyword argument 'components'
I am trying to make a command where if you say $test, it responds with Buttons: https://support.discord.com/hc/article_attachments/1500019725621/buttons.png
It seems like you are trying to use discord-components. For this, you will need to install the package with pip install discord-components and then add the following to your code if you haven't done so.
from discord.ext.commands import Bot
from discord_components import DiscordComponents, Button
bot = Bot('$') # Prefix
#bot.event
async def on_ready():
DiscordComponents(bot)
# ...
# ...
Then from there you should be able to add a components field to send with Buttons in it.

Connecting with linux sFTP server using Groovy

I am trying to run the following Groovy scripts which intends to alter file permissions to 777 on a linux server -
#GrabConfig(systemClassLoader = true)
#Grab(group="com.jcraft", module="jsch", version="0.1.46")
import com.jcraft.jsch.*;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.ChannelSession;
import java.io.InputStream;
import java.io.File;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Vector;
java.util.Properties config = new java.util.Properties()
config.put "StrictHostKeyChecking", "no"
JSch ssh = new JSch();
Session session = null;
Session sess = ssh.getSession ("USERNAME", "HOST", 22);
sess.with {
setConfig config
setPassword ("PASSWORD");
connect()
Channel chan = openChannel ("sftp");
chan.connect()
ChannelSftp sftp = (ChannelSftp) chan;
"chmod 777".execute(null, new File("WORKING DIRECTORY\Test_ftpuser_place.txt"))
chan.disconnect()
disconnect()
}
Furthermore, I tried with the following command instead of Chmod, but still it didn't work.
builder = new AntBuilder()
builder.chmod(dir:"WORKING DIRECTORY", perm:'+rwxrwxrwx', includes:'Test_ftpuser.txt')
And im getting this error on running the former part of the script -
java.io.IOException: Cannot run program "chmod": CreateProcess error=2, The system cannot find the file specified
at java_lang_Runtime$exec$0.call(Unknown Source)
at ConsoleScript45$_run_closure1.doCall(ConsoleScript45:45)
at ConsoleScript45.run(ConsoleScript45:18)
Caused by: java.io.IOException: CreateProcess error=2, The system cannot find the file specified
... 3 more
Could someone please help me out with this.
Thank you!
See this line:
"chmod 777".execute(null, new File("WORKING DIRECTORY\Test_ftpuser_place.txt"))
The second parameter in the "execute" method represents the current working directory (see the docs here). You're using it to represent the file you're looking to change, which I don't think is what it was intended for.
Try creating the file first, and then changing its permissions. You can also use methods on the File object to set these, without having to use "process".execute():
def myFile = new File("path/to/file")
myFile.write("Hello World")
myFile.setReadable(true, false)
myFile.setWritable(true, false)
myFile.setExecutable(true, false)

NDB Async access compatibility with Flask in Google App Engine GAE

I have been going through the google cloud NDB Async examles tutorials
https://cloud.google.com/appengine/docs/standard/python/ndb/async
You can specify a whole WSGIApplication as ndb.toplevel. This makes
sure that each of the WSGIApplication's handlers waits for all async
requests before returning. (It does not "toplevel" all the
WSGIApplication's handlers.)
app = ndb.toplevel(webapp2.WSGIApplication([('/', MyRequestHandler)]))
Is this same functionality compatible with Flask? For example my code
app = Flask(__name__)
app.config.update(DEBUG = not SERVER_ISPRODUCTION)
app = ndb.toplevel(app)
...
#app.route('/test')
def testBackfill():
Gives me error
Traceback (most recent call last):
File "/base/data/home/runtimes/python27_experiment/python27_lib/versions/1/google/appengine/runtime/wsgi.py", line 240, in Handle
handler = _config_handle.add_wsgi_middleware(self._LoadHandler())
File "/base/data/home/runtimes/python27_experiment/python27_lib/versions/1/google/appengine/runtime/wsgi.py", line 299, in _LoadHandler
handler, path, err = LoadObject(self._handler)
File "/base/data/home/runtimes/python27_experiment/python27_lib/versions/1/google/appengine/runtime/wsgi.py", line 85, in LoadObject
obj = __import__(path[0])
#app.route('/test')
AttributeError: 'function' object has no attribute 'route'
This error goes away when I move the toplevel back directly to the request handler.
I feel either flask doesn't work with this functionality, or I'm doing something wrong in how I'm using toplevel.
My intention is for each of my request handlers within my application to wait for all of my async Google DataStore calls to finish before exiting (I'm using yield statements and tasklets within my request handlers).
The error is kind of expected: app is no longer the Flask app you created. I see 2 options to try:
rename the top level app (you need to match the change in the app.yaml config file as well):
app = Flask(__name__)
app.config.update(DEBUG = not SERVER_ISPRODUCTION)
my_app = ndb.toplevel(app) # change .app -> .my_app app.yaml
rename the flask app and all its references:
flask_app = Flask(__name__)
flask_app.config.update(DEBUG = not SERVER_ISPRODUCTION)
app = ndb.toplevel(flask_app)
...
#flask_app.route('/test')
def testBackfill(): **strong text**
Note: I'm not a Flask user, this may fix the missing route attribute error but I don't know if it will ultimately make the top level stuff work. But I can't write this as a comment.

Writing files to Dropbox account from GAE

I am trying to create files in a Dropbox.com folder from a GAE application.
I have done all the steps the register a Dropbox application and installed the Python SDK from Dropbox locally on my development machine. (see dropbox.com API).
It all works perfectly when I use the cli_client.py test script in the dropbox SDK on my local machine to access dropbox - can 'put' files etc.
I now want to start working in GAE environment, so things get a bit tricky.
Some help would be useful.
For those familiar with the Dropbox API code, I had the following issues thus far:
Issue 1
The rest.py Dropbox API module uses pkg_resources to get the certs installed in site-packages of a local machine installation.
I replaced
TRUSTED_CERT_FILE = pkg_resources.resource_filename(__name__, 'trusted-certs.crt')
with
TRUSTED_CERT_FILE = file('trusted-certs.crt')
and placed the cert file in my GAE application directory. Perhaps this is not quite right; see my authentication error code below.
Issue 2
The session.py Dropbox API module uses oauth module, so I changed the include to appengine oauth.
But raised an exception that GAE's oauth does not have OAuthConsumer method used by the Dropbox session.py module. So i downloaded oauth 1.0 and added to my application an now import this instead of GAE oauth.
Issue 3
GAE ssl module does not seem to have CERT_REQUIRED property.
This is a constant, so I changed
self.cert_reqs = ssl.CERT_REQUIRED
to
self.cert_reqs = 2
This is used when calling
ssl.wrap_socket(sock, cert_reqs=self.cert_reqs, ca_certs=self.ca_certs)
Authentication Error
But I still can't connect to Dropbox:
Status: 401
Reason: Unauthorized
Body: {"error": "Authentication failed"}
Headers: [('date', 'Sun, 19 Feb 2012 15:11:12 GMT'), ('transfer-encoding', 'chunked'), ('connection', 'keep-alive'), ('content-type', 'application/json'), ('server', 'dbws')]
Here's my patched version of Dropbox Python SDK 1.4 which works well for me with Python 2.7 GAE: dropbox_python_sdk_gae_patched.7z.base64. No extra third-party libraries needed, only those provided by GAE environment.
Only file uploading (put_file) is tested. Here're setup steps:
Unpack archive to the root folder of GAE application (if main app is in the root folder). You can decode BASE64 using Base64 Encoder/Decoder: base64.exe -d dropbox_python_sdk_gae_patched.7z.base64 dropbox_python_sdk_gae_patched.7z.
Setup APP_KEY, APP_SECRET, ACCESS_TYPE, ACCESS_TOKEN_KEY, ACCESS_TOKEN_SECRET. First three are configured at dropbox application creation time. Last two are obtained when granting application access to specific dropbox account, you can get them through cli_client.py (from DB Python SDK) from token_store.txt file.
Use in the code like this:
import dropbox
# ...
def DropboxUpload(path, data):
sess = dropbox.session.DropboxSession(APP_KEY, APP_SECRET, ACCESS_TYPE)
sess.set_token(ACCESS_TOKEN_KEY, ACCESS_TOKEN_SECRET)
cli = dropbox.client.DropboxClient(sess)
data_file = StringIO.StringIO(data)
return cli.put_file(path, data_file)
# ...
import json
class DropboxUploadHandlerExample(webapp2.RequestHandler):
def get(self):
url = "http://www.google.com/"
result = urlfetch.fetch(url)
self.response.headers['Content-Type'] = 'application/json'
self.response.out.write(json.dumps(DropboxUpload('/fetch_result.dat', result.content)))
I successfully uploaded from Google Appengine to Dropbox with my own patched version
of the Dropbox SDK: https://github.com/cklein/dropbox-client-python
The usage of urllib2 was replaced by huTools.http: https://github.com/hudora/huTools/
This is the code that is called in a request handler:
db_client = dropbox.get_dropbox_client(consumer_key='', consumer_secret='', access_token_key='', access_token_secret='')
fileobj = StringIO.StringIO(data)
path = '/some/path/filename'
resp = db_client.put_file(path, fileobj)
fileobj.close()
As of April 2016, none of the other suggestions work. (Dropbox API version 2, Python SDK version 6.2).
If you only need a few of the SDK functions, I found it easiest to just use the HTTP API directly:
def files_upload(f, path, mode='add', autorename=False, mute=False):
args = {
'path': path,
'mode': mode,
'autorename': autorename,
'mute': mute,
}
headers = {
'Authorization': 'Bearer {}'.format(ACCESS_TOKEN),
'Dropbox-API-Arg': json.dumps(args),
'Content-Type': 'application/octet-stream',
}
request = urllib2.Request('https://content.dropboxapi.com/2/files/upload', f, headers=headers)
r = urllib2.urlopen(request)
I have patched the Dropbox Python SDK version 2.2 to work on Google App Engine. Please find the relevant code here:
https://github.com/duncanhawthorne/gae-dropbox-python
The relevant code patch (copied from github) for rest.py is here:
import io
import pkg_resources
-import socket
+#import socket
import ssl
import sys
import urllib
+import urllib2
+def mock_urlopen(method,url,body,headers,preload_content):
+ request = urllib2.Request(url, body, headers=headers)
+ r = urllib2.urlopen(request)
+ return r
+
try:
import json
except ImportError:
## -23,7 +29,10 ##
SDK_VERSION = "2.2.0"
-TRUSTED_CERT_FILE = pkg_resources.resource_filename(__name__, 'trusted-certs.crt')
+try:
+ TRUSTED_CERT_FILE = pkg_resources.resource_filename(__name__, 'trusted-certs.crt')
+except:
+ TRUSTED_CERT_FILE = file('trusted-certs.crt')
class RESTResponse(io.IOBase):
## -125,6 +134,7 ## def flush(self):
pass
def create_connection(address):
+ return
host, port = address
err = None
for res in socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM):
## -152,7 +162,7 ## def json_loadb(data):
class RESTClientObject(object):
- def __init__(self, max_reusable_connections=8, mock_urlopen=None):
+ def __init__(self, max_reusable_connections=8, mock_urlopen=mock_urlopen):
"""
Parameters
max_reusable_connections
## -206,7 +216,7 ## def request(self, method, url, post_params=None, body=None, headers=None, raw_re
raise ValueError("headers should not contain newlines (%s: %s)" %
(key, value))
- try:
+ if True:
# Grab a connection from the pool to make the request.
# We return it to the pool when caller close() the response
urlopen = self.mock_urlopen if self.mock_urlopen else self.pool_manager.urlopen
## -217,14 +227,14 ## def request(self, method, url, post_params=None, body=None, headers=None, raw_re
headers=headers,
preload_content=False
)
- r = RESTResponse(r) # wrap up the urllib3 response before proceeding
- except socket.error as e:
- raise RESTSocketError(url, e)
- except urllib3.exceptions.SSLError as e:
- raise RESTSocketError(url, "SSL certificate error: %s" % e)
+ #r = RESTResponse(r) # wrap up the urllib3 response before proceeding
+ #except socket.error as e:
+ # raise RESTSocketError(url, e)
+ #except urllib3.exceptions.SSLError as e:
+ # raise RESTSocketError(url, "SSL certificate error: %s" % e)
- if r.status not in (200, 206):
- raise ErrorResponse(r, r.read())
+ #if r.status not in (200, 206):
+ # raise ErrorResponse(r, r.read())
return self.process_response(r, raw_response)
## -321,10 +331,11 ## def PUT(cls, *n, **kw):
return cls.IMPL.PUT(*n, **kw)
-class RESTSocketError(socket.error):
+class RESTSocketError():
"""A light wrapper for ``socket.error`` that adds some more information."""
def __init__(self, host, e):
+ return
msg = "Error connecting to \"%s\": %s" % (host, str(e))
socket.error.__init__(self, msg)

Resources