Ban and Unban commands to work in all servers - discord.py

I've been programming a discord bot letely, and for its ban command here is the code i use:
#client.command(aliases=['Ban'])
async def ban(ctx, member: discord.Member, days: int = 1):
if get(ctx.author.roles, id=548841535223889923):
await member.ban(delete_message_days=days)
await ctx.send("Banned {}".format(ctx.author))
else:
await ctx.send(ctx.author.mention + " you don't have permission to use this command.".format(ctx.author))
However, if i try to use this on other servers, it just tells me i dont have the required role..
So how do I get the role ID for a new server the bot joins automatically or is there some other way to make this work?

You can use a check for permissions instead of looking for a specific role ID
import discord
from discord.ext import commands
#client.command(aliases=["Ban"])
#commands.has_permission(ban_members=True)
async def...

you can use a has_permission, like this:
#client.command(aliases=["Ban"])
#commands.has_permission(administrator=True)
async def ban(ctx, member: discord.Member, days: int = 1):
await member.ban(delete_message_days=days)
await ctx.send("Banned {}".format(ctx.author))
You can then add a missing permissions error handler:
#client.event
async def on_command_error(ctx, error):
if isinstance(error, commands.MissingPermissions):
await ctx.send("You do not have the permissions required for this command.")
return
raise error

Related

I want to improve my kick command in discord.py

I have made a bot in discord.py which has a kick command. But I want the bot to say "please tell me whom to kick" when someone uses the command without saying whom to kick. I mean if someone uses the kick command without mentioning whom to kick, the bot will say "please tell me whom to kick".
I am trying to make a good bot so please help me.
async def kick(ctx, member : discord.Member, *, reason=None):
if (ctx.message.author.permissions_in(ctx.message.channel).kick_members):
await member.kick(reason=reason)
await ctx.send(f"{member.mention} has successfully been kickded for {reason}")
if not (ctx.message.author.permissions_in(ctx.message.channel).kick_members):
await ctx.send("You don't perms to play football with Araforce and kick them. Sed")
if not user:
await ctx.message.delete()
msg = await ctx.send("You are a bit idiot, don't you know I can't kick anyone if you don't tell whom to kick? Tell me whom to kick and the go away.")
await sleep(4.7)
await msg.delete()
return
if not reason:
await ctx.message.delete()
msg2 = await ctx.send("Hmm.. Why I will kick him? Specify a reason please.")
await sleep(4.7)
await msg2.delete()
return```
async def kick(ctx, user: discord.User = None, *, reason=None):
if not user:
await ctx.message.delete()
msg = await ctx.send("You must specify a user.")
await sleep(4.7)
await msg.delete()
return
if not reason:
await ctx.message.delete()
msg2 = await ctx.send("You must specify a reason.")
await sleep(4.7)
await msg2.delete()
return
I changed ifs to the error handler, which is necessary because if you won't pass one of the arguments (user or reason) you would get an error.
Full code:
#client.command()
async def kick(ctx, member: discord.Member, *, reason): #if you will change "member" and "reason" to something else remember to also change it in error handler
await member.kick(reason=reason)
await ctx.send(f"{member.mention} has successfully been kicked for {reason}")
#kick.error #cool mini error handler
async def kick_error(ctx, error):
if isinstance(error, discord.ext.commands.errors.MissingRequiredArgument):
if str(error) == "member is a required argument that is missing.": #change this if you changed "member"
await ctx.message.delete()
await ctx.send("You are a bit idiot, don't you know I can't kick anyone if you don't tell whom to kick? Tell me whom to kick and then go away.", delete_after=4.7) #you don't have to use "await sleep" you can use "delete_after" parameter
elif str(error) == "reason is a required argument that is missing.": #change this if you changed "reason"
await ctx.message.delete()
await ctx.send("Hmm.. Why I will kick him? Specify a reason please.", delete_after=4.7)
elif isinstance(error, discord.ext.commands.errors.MissingPermissions):
await ctx.send("You don't have perms to play football with Araforce and kick them. Sed")
Discord error handling example

Discord.py echo command

So I am trying to make a discord.py echo/say command, but no response or errors are happening, if you know how to fix this please help me out!
import discord, os, keep_alive, asyncio, datetime, pytz, requests
from discord.ext import tasks, commands
client = commands.Bot(
command_prefix=':',
self_bot=True
)
async def on_ready():
client.remove_command('help')
await client.change_presence(status=discord.Status.online, activity=discord.Game("TEST"))
#client.command()
async def echo(ctx, *,args):
if ctx.message.author.id in [782258096210051102]:
await ctx.send(args)
await ctx.message.delete()
else:
await ctx.send("Bot developers only :<")
keep_alive.keep_alive()
client.run(os.getenv("TOKEN"), bot=False)
It's not working because the ctx.author is None, to fix that enable intents.members
intents = discord.Intents.default()
intents.members = True
client = commands.Bot(..., intents=intents)
Also make sure to enable them in the developer portal
Reference
Uhhhhhh it is better to do something like
#bot.command()
async def echo(ctx,*,arg):
#the star is required
if ctx.authir.id==782258096210051102:
await ctx.send(arg)
else:
await ctx.send("devs only :<")
You can use ' '.join(ctx.message.content.split()[1:]) to join all words after the first space. So something like:
#client.command()
async def echo(ctx, *args):
await ctx.send(' '.join(ctx.message.content.split()[1:]))
To See Where The Problem Is From First Try:
#client.command()
async def echo(ctx, *,args):
await ctx.send(args[0])
await ctx.message.delete()
Ok so actually you have need to do this:
#client.command(name='echo')
async def echo(ctx, *, what_bot_need_to_say: str):
if ctx.message.author.id == 782258096210051102:
await ctx.channel.purge(limit=1) # This delete an message in the channel
await ctx.send(what_bot_need_to_say) # This the echo
else:
await ctx.send("Bot developers only :<")
#bot.command()
async def say(ctx, *, msg):
await ctx.send(msg)
Just copy me it is the simplest and gives the correct format
import discord
from discord.ext import commands
bot = commands.Bot('?')
#bot.command()
async def repeat(ctx,*,repeat:str):
if ctx.author.id == 782258096210051102:
await ctx.send(f"{repeat}")
await ctx.message.delete()
return
else:
await ctx.send("Only devs")
return
#bot.event
async def on_ready():
print("bot online")
bot.run("YOUR_TOKEN_HERE")
try this:
import discord, os, keep_alive, asyncio, datetime, pytz, requests
from discord.ext import tasks, commands
client = commands.Bot(
command_prefix=':',
self_bot=True
)
async def on_ready():
client.remove_command('help')
await client.change_presence(status=discord.Status.online, activity=discord.Game("TEST"))
#client.command()
async def echo(ctx, *,args):
if ctx.author.id in [782258096210051102]:
await ctx.send(args)
# await ctx.message.delete() # i am not sure of delete you can add it if you want
else:
await ctx.send("Bot developers only :<")
keep_alive.keep_alive()
client.run(os.getenv("TOKEN"), bot=False)

Discord.py error handling not outputting a message?

I have tried making an error message when a user does not have the permissions to use the command, this is because I kept getting an error in the console the code is supposed to send a message in chat when the user doesn't have permissions to use it, the error has disappeared from the console but it does not output a message
#client.command()
#has_permissions(manage_messages=True)
async def clear(ctx, limit: int):
await ctx.channel.purge(limit = limit)
await ctx.send('Cleared by {}'.format(ctx.author.mention))
#clear.error
async def clear_error(error, ctx):
if isinstance(error, MissingPermissions):
await ctx.send('Sorry, you do not have permissions to do that!')
When you're using an error handling function, you have to do async def clear_error(ctx, error):. Basically you just have to swap the parameters' places.
#clear.error
async def clear_error(ctx, error):
if isinstance(error, MissingPermissions):
await ctx.send('Sorry, you do not have permissions to do that!')

on_typing not responding to typing discord.py

I am attempting to have a bot recognise when a user is typing and if that user is me, it sends a message. I don't know if I'm using this wrong but I read the API and at still doesn't make sense to me. the bot is not responding to any typing that I do in the default chat of my discord test server. I tried simplifying it to make sure that it actually wasn't seeing my typing and it still doesn't work, any ideas. the code is below.
import discord
from discord.ext import commands
token = ('~my token~')
client = commands.Bot(command_prefix = '.')
client.case_insensitive = (True)
#client.event
async def on_ready():
print('Ready')
#client.event
async def on_member_join(user):
print(f'~Temp~ {user} joined the server.')
#client.event
async def on_guild_join(server):
print(f'~Temp~ {server} joined')
#client.event
async def on_typing(channel, user, when):
print('Ready')
'''
if user.id == id1:
await channel.send('1')
elif user.id == id2:
await channel.send('2')
else:
await channel.send('3')
'''
#client.event
async def on_message(message):
print('~Temp~ Message found')
client.run(token)
You need to enable intents in order to work
intents = discord.Intents.default()
client = commands.Bot(.., intents=intents)
A Primer to Gateway Intents

"Error 'Self' is not defined" in member.edit

I'm having issues with my code saying
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: edit() missing 1 required positional argument: 'self'
when I run the command. Self shouldn't need to be defined, right?
Also, when I do add self I get an issue with ctx.
The code:
import discord
from discord.ext import commands
client = commands.Bot(command_prefix="/")
#client.command(pass_context=True)
async def join(ctx, member=discord.Member):
channel = ctx.author.voice.channel
await channel.connect()
await member.edit(mute=True)
#client.command(pass_context=True)
async def leave(ctx):
await ctx.voice_client.disconnect()
client.run("Token")
I Managed to find the problem and fixed it.
import discord
from discord.ext import commands
client = commands.Bot(command_prefix="/")
#client.command()
async def join(ctx):
channel = ctx.author.voice.channel
await channel.connect()
await ctx.author.edit(mute=True)
#client.command()
async def leave(ctx):
await ctx.voice_client.disconnect()
client.run("Token")
the problem is, you included member on your funcion. If you want it to send, edit, or do something with the message author just do ctx.author and it will be set on the author of the message.

Resources