I am using Discord.py, and while making a command handler using COG, I got this error.
This is the main.py (main bot file)
# Command Handler: Import cog files.
for file in os.listdir("./cogs"): # lists all the cog files inside the cog folder.
if file.endswith(".py"): # It gets all the cogs that ends with a ".py".
name = file[:-3] # It gets the name of the file removing the ".py"
client.load_extension(f"cogs.{name}") # This loads the cog.
Here is the link to the only file I have in my ./cog/ directory, named "Hellgoodbye.py".
https://pastebin.com/TdE8FPxq
The error I get when I do "python .\main.py" in my VSCode terminal, I get the following error:
Traceback (most recent call last):
File "C:\Users\quinn\AppData\Local\Programs\Python\Python37\lib\site-packages\discord\ext\commands\bot.py", line 612, in _load_from_module_spec
setup = getattr(lib, 'setup')
AttributeError: module 'cogs.Hellogoodbye' has no attribute 'setup'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File ".\main.py", line 141, in <module>
client.load_extension(f"cogs.{name}") # This loads the cog.
File "C:\Users\quinn\AppData\Local\Programs\Python\Python37\lib\site-packages\discord\ext\commands\bot.py", line 678, in load_extension
self._load_from_module_spec(spec, name)
File "C:\Users\quinn\AppData\Local\Programs\Python\Python37\lib\site-packages\discord\ext\commands\bot.py", line 615, in _load_from_module_spec
raise errors.NoEntryPointError(key)
discord.ext.commands.errors.NoEntryPointError: Extension 'cogs.Hellogoodbye' has no 'setup' function
Can someone help me fix the error. i really do not know what is going on.
As the error says you don't have setup function. It is necesary for an extension to load.
import discord
from discord.ext import commands
class Name(commands.Cog):
def __init__(self, bot):
self.bot = bot
def setup(bot):
bot.add_cog(Name(bot))
This is an example of a cog file. As you can see at the very end of the code there is the setup function. It should be a standalone function which is not defined inside of the class.
Answer:
I moved
def setup(bot)
bot.add_cog(Hellogoodbye(bot))
To the end of the file, and it is working now, besides the fact I have some other issues, but the error I asked about is fixed by this.
Related
https://nats-io.github.io/nats.py/modules.html
Traceback (most recent call last):
File "c:\Users\lb\nats.py", line 22, in <module>
asyncio.run(main())
File "D:\anaconda\lib\asyncio\runners.py", line 44, in run
return loop.run_until_complete(main)
File "D:\anaconda\lib\asyncio\base_events.py", line 616, in run_until_complete
return future.result()
File "c:\Users\lb\nats.py", line 6, in main
nc = await nats.connect(servers=["nats://216.48.189.5:4222"])
AttributeError: module 'nats' has no attribute 'connect'
An Attribute error: I am not able to figure out what is the issue with 'connect'.
import asyncio
import nats
async def main():
# Connect to NATS!
nc = await nats.connect(servers=["nats://216.48.189.5:4222"])
# Receive messages on 'foo'
sub = await nc.subscribe("foo")
# Publish a message to 'foo'
await nc.publish("foo", b'Hello from Python!')
# Process a message
msg = await sub.next_msg()
print("Received:", msg)
# Close NATS connection
await nc.close()
if __name__ == '__main__':
asyncio.run(main())
Help me with this connect issue, please.
The solution is to rename your file to anything else.
When you type import nats python recursively tries to find a file or folder named nats. In this case the first file if will find is nats.py.
You never define a function named connect in your nats.py so that fails. You want to instead let the recursive import continue upto site_packages where the actual nats folder is that contains the connect function.
For example, if you name this file hello.py:
import hello
print(hello.hello)
print(hello)
print(hello.hello.hello)
You will see that all 3 print statements print the same thing, since hello will be the file itself.
Simply renaming your file anything else will prevent python from finding the module too soon and will keep searching till it find the correct module.
I just ran your code and got no error.
Try uninstalling and reinstalling nats:
pip install nats-py
I want the bot make this command operational if the user has permission to ban members but when I'm running the code I'm getting error because of this line in the code below #commands.has_permissions(ban_member=True) which is line 42 in my code
If I remove #commands.has_permissions(ban_member=True) it is working but then anyone can modify the json file which I don't want to happen.
How to fix this error?
def write_json(data,filename="blacklistedWords.json"):
with open(filename,"w") as f:
json.dump(data,f,indent=4)
#bot.command(aliases=['awb'])
#commands.has_permissions(ban_member=True)
async def addtoblacklist(ctx,*,word):
with open("blacklistedWords.json") as json_file:
data = json.load(json_file)
temp = data["blacklistedWords"]
temp.append(word)
write_json(data)
Traceback (most recent call last):
File "C:\Users\ACER\Desktop\Json read write\botRead.py", line 42, in <module>
#commands.has_permissions(ban_member=True)
File "C:\Users\ACER\AppData\Roaming\Python\Python39\site-packages\discord\ext\commands\core.py", line 1779, in has_permissions
raise TypeError('Invalid permission(s): %s' % (', '.join(invalid)))
TypeError: Invalid permission(s): ban_member
The permission may be incorrect, there is a permission ban_members (note plural) https://discordpy.readthedocs.io/en/stable/api.html#discord.Permissions.ban_members
I have tracked my error to this code, which is in a cog:
#cog_ext.cog_slash(name="help")
async def help_slash(self, ctx, Command_Name=None):
await helpMethod(ctx, Command_Name)
Here is the full error:
Traceback (most recent call last):
File "main.py", line 102, in <module>
class bot(commands.Cog):
File "main.py", line 110, in bot
async def help_slash(self, ctx, Command_Name=None):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord_slash/cog_ext.py", line 63, in wrapper
opts = manage_commands.generate_options(cmd, desc, connector)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord_slash/utils/manage_commands.py", line 313, in generate_options
SlashCommandOptionType.from_type(param.annotation) or SlashCommandOptionType.STRING
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord_slash/model.py", line 488, in from_type
and isinstance(t, typing._UnionGenericAlias) # noqa
AttributeError: module 'typing' has no attribute '_UnionGenericAlias'
My research suggests this may be an error with Python itself. If so, is there a way to circumvent the problem? I have tested helpMethod: the error comes from the declaration of the slash command.
Thanks so much for reading.
Look at Python 3.8 typing library code, you can see _UnionGenericAlias is not defined.
However, in Python 3.9, it is defined.
So the solution is you have to upgrade your Python version.
I have two .py scripts on the same folder, and I have a function like this on one:
def combat_menu():
exec("combat.py")
Theese scripts are named dungeon.py(the one im executing from) and combat.py.
When I execute this function this error appears:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\hp\AppData\Local\Programs\Python\Python38-32\lib\tkinter\__init__.py", line 1883, in __call__
return self.func(*args)
File "C:\Users\hp\Documents\piton\Dungeon\dungeon_Data\dungeon.py", line 25, in combat_menu
exec("combat.py")
File "<string>", line 1, in <module>
NameError: name 'combat' is not defined
I execute this function from a tkinter button widget like this:
event_button = t.Button(root, text="Open CM", command=combat_menu)
I have tried importing the code, but this gives ImportError.
The exec() function supports dynamic execution of Python code. It is not executing a shell command. To execute a shell command, in your case calling another python file. Instead you can use for example:
os.system(*cmd*) ->
os.system('combat.py')
I am trying to trigger a python script from a controller.
I have defined the follwing function in the controller:
private
def update_product_count(skus, qty)
system "python2 /home/nish/stuff/repos/Untitled/voylla_staging_changes/app/models/ReviseItem.py
skus qty > output"
end
Calling this function in another method of the same controller:
def show
//some code
update_product_count(#skus, #qty)
end
When I run the script manually, from my console, it runs fine. But i get this error when run from the controller:
Traceback (most recent call last):
File "/home/nish/stuff/repos/Untitled/voylla_staging_changes/app/models/ReviseItem.py", line 24, in <module>
devID = config.get("Keys", "Developer")
File "/usr/lib/python2.7/ConfigParser.py", line 607, in get
raise NoSectionError(section)
ConfigParser.NoSectionError: No section: 'Keys'
The most likely cause is that you are opening the config file using a relative path, and the controller has a different current directory to your console.
You should either use an absolute path to the config file, or have the script work out the directory it is executing in, and prepend that to the file name.