I am trying to make a command which will load a certain cogs from cog folder.
I have followed a youtube tutorial
https://youtu.be/vQw8cFfZPx0
but I am getting some errors and I don't know how to fix it
import discord
import os
from discord.ext import commands
client = commands.Bot(command_prefix= "#")
#client.command()
async def load(ctx, extension):
client.load_extension(f'cogs.{extension}')
#client.command()
async def unload(ctx, extension):
client.unload_extension(f"cogs.{extension}")
#client.command
async def reload(ctx, extension):
client.reload_extension(f"cogs.{extension}")
for filename in os.listdir('./cogs'):
if filename.endswith('.py'):
client.load_extension(f'cogs.{filename[:-3]}')
client.run('token')
and this is my cog file
import discord
from discord.ext import commands
class Example(commands.cog):
def __init__(self, client):
self.client = client
#event
#commands.Cog.listener()
async def on_ready(self):
print("bot is online")
#commands.command()
async def ping(self, ctx):
await ctx.send("pong")
def setup(client):
client.add_cog(Example(client))
and this is the error I am getting
Traceback (most recent call last):
File "c:\Users\...\Discord bot\cogs\ping.py", line 4, in <module>
class Example(commands.cog):
TypeError: module() takes at most 2 arguments (3 given)
btw I am new to python so I may have done very silly mistake
Since Cog is a class, and classes use the CapWords convention:
class Example(commands.Cog): # instead of class Example(commands.cog):
commands.cog should be commands.Cog
The c in Cog has to be capital
Related
i tried
# -*- coding: utf-8 -*-
from discord.ext import commands
import discord
import random
import asyncio,json
from discord.ext.commands import clean_content
from datetime import datetime
import aiohttp
from discord.ext import tasks
class Test(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.test1.start()
#tasks.loop(minutes=1.0)
async def test1(self):
channel=bot.get_channel(927612404056092702)
channel.send(mensagem)
def setup(bot):
bot.add_cog(Test(bot))
using
channel=self.bot.get_channel(927612404056092702)
return AttributeError: 'NoneType' object has no attribute 'send'
and using
channel=bot.get_channel(927612404056092702)
return NameError: name 'bot' is not defined
bot.get_channel method retrives channel from cache. You can properly do it only after on_ready event:
class Test(commands.Cog):
def __init__(self, bot):
self.bot = bot
#tasks.loop(minutes=1.0)
async def test1(self):
channel=bot.get_channel(927612404056092702)
channel.send(mensagem)
#commands.Cog.listener()
async def on_ready(self):
if not self.test1.is_running():
self.test1.start()
def setup(bot):
bot.add_cog(Test(bot))
I'm trying to make a discord.py bot with the help of nextcord and i've come far enough to make the code work in theory but nothing happens when i try to kick / ban, it just throws an
nextcord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Context' object has no attribute 'ban'
and i have no idea why it does so, i want it to work as inteded.
Note, the command(s) are class commands so the main bot loads in the command from another file.
Main Bot Script
# import nextcord
from nextcord.ext import commands
# import asyncio
import json
# Import all of the commands
from cogs.ban import ban
from cogs.hello import hello
from cogs.help import help
from cogs.info import info
from cogs.kick import kick
from cogs.test import test
#Define bot prefix and also remove the help command built in.
bot = commands.Bot(command_prefix=json.load(open("config.json"))["prefix"])
bot.remove_command("help")
#bot.event
async def on_ready():
print(f'Logged in as {bot.user}')
bot.add_cog(hello(bot))
bot.add_cog(help(bot))
bot.add_cog(info(bot))
bot.add_cog(test(bot))
bot.add_cog(ban(bot))
bot.add_cog(kick(bot))
bot.run(json.load(open("config.json"))["token"])
Problematic command
import discord
from nextcord.ext import commands
from nextcord.ext.commands import has_permissions, CheckFailure
bot = commands.bot
class ban(commands.Cog):
def __init__(self, client):
self.client = client
self._last_member = None
#commands.Cog.listener()
async def on_ready(self):
print('ban Cog Ready')
#commands.command()
#has_permissions(ban_members=True)
async def ban(ctx, user: discord.Member = None, *, Reason = None):
if user == None:
await ctx.send("Could you please enter a valid user?")
return
try:
await user.ban(reason=Reason)
await ctx.send(f'**{0}** has been banned.'.format(str(user)))
except Exception as error:
if isinstance(error, CheckFailure):
await ctx.send("Looks like you don't have the permissions to use this command.")
else:
await ctx.send(error)
You are doing:
user: discord.Member
You need to use nextcord instead.
user: nextcord.Member
#commands.command()
#has_permissions(ban_members=True)
async def ban(ctx, user: nextcord.Member = None, *, Reason = None):#
#The rest of your code here
You can do the following
For Normal bot
#client.command(name="ban", aliases=["modbancmd"], description="Bans the mentioned user.")
#commands.has_permissions(ban_members=True)
async def ban(self, ctx, member: nextcord.Member, *, reason=None):
# Code for embed (optional)
await member.ban(reason=reason)
# (optional) await ctx.send(embed=banembed)
You can do the following
For Cogs
#commands.command(name="ban", aliases=["modbancmd"], description="Bans the mentioned user.")
#commands.has_permissions(ban_members=True)
async def ban(self, ctx, member: nextcord.Member, *, reason=None):
# Code for embed (optional)
await member.ban(reason=reason)
# (optional) await ctx.send(embed=banembed)
Well, here are the problems:
Your command is in a cog therefore you need to say (self, ctx, and so on)
You need to change the discord to nextcord
You should change the commands.bot to commands.Bot()
And if I'm correct, you should change the self.client to self.bot since your commands.Bot() is defined as bot
And uhh yeah it should work perfectly after you fix those.
I am facing an issue while migrating my python code to discord.py.
The issue is, I don't know how to use client. variables in discord.py cogs like client.sniped_messages = {}...
It shows an error -
Traceback (most recent call last):
File "C:\Users\arjun\Documents\Arjun\Python\discord.py\swayde\main.py", line 55, in <module>
client.load_extension(f"cogs.{filename[:-3]}")
File "C:\Users\arjun\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\bot.py", line 678, in load_extension
self._load_from_module_spec(spec, name)
File "C:\Users\arjun\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\bot.py", line 609, in _load_from_module_spec
raise errors.ExtensionFailed(key, e) from e
discord.ext.commands.errors.ExtensionFailed: Extension 'cogs.Utility' raised an error: NameError: name 'self' is not defined
Here's the code -
import discord
from discord.ext import commands
import random
import datetime
class Utility(commands.Cog):
def __init__(self, client):
self.client = client
self.client.sniped_messages = {}
#commands.Cog.listener()
async def on_message_delete(self,message):
self.client.sniped_messages[message.guild.id] = (message.content, message.author, message.channel.name, message.created_at)
#commands.command()
async def snipe(self, ctx):
try:
contents, author, channel_name, time = self.client.sniped_messages[ctx.guild.id]
except:
await ctx.channel.send("Couldn't find a message to snipe!")
return
embed = discord.Embed(description=contents, color=discord.Color.purple(), timestamp=time)
embed.set_author(name=f"{author.name}#{author.discriminator}", icon_url=author.avatar_url)
embed.set_footer(text=f"Deleted in : #{channel_name}")
await ctx.channel.send(embed=embed)
def setup(client):
client.add_cog(Utility(client))
Now, when I delete the variable client.sniped_messages = {}, The code runs perfectly.
Please tell me how I can resolve this issue and how to use .client variables in cogs.
Thanks in advance!
You have to indent self.client.sniped_messages = {} so it's inside the __init__ method
def __init__(self, client):
self.client = client
self.client.sniped_messages = {}
A straight Forward question - How to import a function from a different file and use that in discord.py cuz i tried that and failed for example there is file a and b which looks like
a.py:
async def joke(ctx):
joke = 'Your mama so fat boy'
await ctx.send(joke)
and i want to use the joke function from file a to file b and the code i write was:
from a import joke
from discord.ext import commands
#some discord code
TOKEN = 'My_Secret_Token'
GUILD = 'My_Guild'
client = commands.Bot(command_prefix='!')
#client.command(name='joke', help='This will return a joke')
joke()
client.run(TOKEN)
And the line joke() is returning me error
File "main.py", line 31
joke()
^
SyntaxError: invalid syntax
And i am here confused that why it is returning me error and how can i pass the argument ctx. So please come up with a solution for me.
Edit: After debugging and scratching my head for hours i came up with a solution which is also not working that i modified my b.py a little bit :
from a import joke
from discord.ext import commands
#some discord code
TOKEN = 'My_Secret_Token'
GUILD = 'My_Guild'
client = commands.Bot(command_prefix='!')
#client.command(name='joke', help='This will return a joke')
async def my_function(ctx):
joke(ctx)
client.run(TOKEN)
You can use cogs for this. Docs: https://discordpy.readthedocs.io/en/latest/ext/commands/cogs.html
Here is an Example:
Your main.py
import discord
from discord.ext import commands
import os
client = commands.Bot(command_prefix='!')
for file in os.listdir("cogs"):
if file.endswith(".py"):
name = file[:-3]
client.load_extension(f"cogs.{name}")
client.run(TOKEN)
Make a secound /cogs/joke.py
import discord
from discord.ext import commands
import random
class joke(commands.Cog):
def __init__(self, bot):
self.bot = bot
#commands.command()
async def joke(self, ctx):
jokes = [
'Your mama so fat boy',
'joke2',
'joke3',
'joke4',
'joke5'
]
answer = random.choice(jokes)
await ctx.send(answer)
def setup(bot):
bot.add_cog(joke(bot))
i tried to make cog for organize my bot but i have an error that i dont find how to fix. The bot successful find command in cog but when i write the command i have this error:
Could you help me pls ? Here is my code:
import discord
import asyncio
import re
import os
import random
from discord.ext import commands
class Moderation(commands.Cog):
def __init__(self, bot):
self.bot = bot
#Purge
#commands.command()
async def purge(ctx, amount=10):
await ctx.channel.purge(limit=amount)
Your first parameter must be self.
class Moderation(commands.Cog):
def __init__(self, bot):
self.bot = bot
#Purge
#commands.command()
async def purge(self, ctx, amount=10):
await ctx.channel.purge(limit=amount)
Add self as parameter in purge function.
async def purge(self,ctx,amount=10):
await ctx.channel.purge(limit=amount)