Nextcord Ban & Kick issue - python-3.x

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.

Related

How make a typo message?

I want to add a similar commands suggestion when the user make a typo.
Example: Right command: clear // User input: Cler // Bot response: Did you mean 'clear'?
I'm heard about difflib.get_close_matches and I'm be able to make this works in a .py script but not with discord.py
You wanna have a list of all your bot commands.
Then you test with the on command error event if the command wasnt found. If it wasnt test for similar commands (Levenshtein distance: http://en.wikipedia.org/wiki/Levenshtein_distance). Then send the user a message with the expected command if similar commands are found. Here is an example of how I would do it):
import discord
from discord.ext import commands
from difflib import SequenceMatcher
BOT_PREFIX = '!'
bot = discord.Client(intents=discord.Intents.all(), status=discord.Status.dnd)
bot = commands.Bot(command_prefix=BOT_PREFIX)
bot_commands = [] # all cmd names
#bot.event
async def on_ready():
global bot_commands
bot_commands = [cmd.name for cmd in bot.commands]
#bot.event
async def on_message(message):
if message.author.id == bot.user.id:
return
await bot.process_commands(message)
#bot.event
async def on_command_error(ctx, error): #catch error
if isinstance(error, commands.CommandNotFound):
for i in bot_commands: #Looking for close matches in commands
if float(SequenceMatcher(a=str(ctx.message.content).replace(BOT_PREFIX, '').lower(), b=i.lower()).ratio()) > float(0.67): #You can adjust the second float
await ctx.send(f'Did you mean {i}?') #Your message
break #Ignore similiar matches
#raise error (optional)
bot.run('token')

Simplest way to check the users in channel with discord.py

I am making a simple bot, all I want it to do is wait for me to type a command with an argument (a vc), so for example when I type !channel general, the bot will return a list of the members in that channel. So if Bob and Jeff are in General the bot will return member_list = ['Bob', 'Jeff'] Any easy way to do that?
Update:
import discord
import os
from discord.ext import commands
client = discord.Client()
bot = commands.Bot(command_prefix='$')
#client.event
async def on_ready():
print('We have logged in as {0.user}'.format(client))
#bot.command()
async def members(ctx, channel: discord.VoiceChannel):
member_list = [i.name for i in channel.members]
print(member_list)
await ctx.send(member_list) # or return member_list whatever you want
client.run(os.getenv('TOKEN'))
Here's my code up above, when I run bot it does not do anything when I type $members general, anyone know what I'm doing wrong?
Use VoiceChannel.members
#bot.command()
async def members(ctx, channel: discord.VoiceChannel):
member_list = [i.name for i in channel.members]
await ctx.send(member_list) # or return member_list whatever you want

AttributeError: 'Moderation' object has no attribute 'channel'

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)

Simple bot command is not working in discord.py

I want to know in which text channels admin want to enable my bot functions. But in this case my code is not working.
The main idea was when admin typing !enable in text-chat, bot reacts to it and add text-chat id, guild id(ctx.channel.id) to the list, then bot responds in chat with bot has been enabled.
code where this command is not working:
channel = []
#bot.command()
async def enable(ctx):
global channel
print("Debug")
await ctx.send('Restriction bot has been enabled for this text channel.')
channel.append(ctx.channel.id)
full bot code:
import discord
from discord.ext import commands
bot = commands.Bot(command_prefix='!')
#bot.event
async def on_ready():
print(f'We have logged in as {bot.user.name}.')
channel = []
#bot.command()
async def enable(ctx):
global channel
print("Debug")
await ctx.send('Restriction bot has been enabled for this text channel.')
channel.append(ctx.channel.id)
#bot.event
async def on_message(ctx):
if ctx.author == bot.user:
return
#if ctx.channel.id != [for channnels in channel]:
# return
if ctx.attachments[0].height:
await ctx.author.send('Your media file is restricted!')
await ctx.delete()
The channel variable is initialized in your program so each time you will restart your bot, it will be emptied. One way you can solve your problem is by storing them in a file. The easiest way to do it would be to use the json library. You'll need to create a channels.json file.
The code :
from json import loads, dumps
def get_data():
with open('channels.json', 'r') as file:
return loads(file.read())
def set_data(chan):
with open('channels.json', 'w') as file:
file.write(dumps(chan, indent=2))
#bot.command()
async def enable(ctx):
channels = get_data()
channels.append(ctx.channel.id)
set_data(channels)
await ctx.send('Restriction bot has been enabled for this text channel.')
The channels.json file :
[]

Tons of Cog errors

In discord.py 1.0.1 (Only version Repl.it has), the cogs are giving me a hard time.
import discord
from discord.ext import commands
class Coding(commands, Cog):
def __init__(self, client):
self.client = client
#commands.Cog.listener()
async def on_ready(self):
print("Kahoot Bot 0.1 ALPHA")
client.remove_command("help")
#commands.command()
async def clear(self, ctx, amount = 5):
await ctx.channel.purge(limit = amount + 1)
#commands.command()
async def ping(self, ctx):
await ctx.send(f"Pong! {round(client.latency * 1000)}ms.")
#client.command(pass_context = True, aliases = ["print"])
async def printing(ctx, *, what_to_print):
await ctx.send(what_to_print)
print(what_to_print)
def setup(client):
client.add_cog(Coding(client))
The gist of the errors is:
A) client is not defined
B) init() should return None, not coroutine
I've tried changing all my code to bot and back to client, but nothing's helped. No idea what's going on.
You do the inheritance wrong. You dont inherit from class: "commands" and "Cog". You inherit from class: "commands.Cog". thus changing: class Coding(commands, Cog): to class Coding(commands.Cog): will fix some of the errors.
You also do the following wrong (the "client does not exist" error):
#commands.Cog.listener()
async def on_ready(self):
print("Kahoot Bot 0.1 ALPHA")
client.remove_command("help") # this line
When we want to access a class variable we use self. in the beginning of that variable to indicate that we are using the class variable. This case you dont use self.client. but client.
As client is not defined in that function it will give an error. But it is defined as a class variable (the "init" function). To access it use: self.client.

Resources