I created a ban all discord command by using a few tutorials on stack overflow but the problem is the bot attempts to ban itself and prioritizes that first, making the bot completely not work, any suggestions? Here's my code:
async def ban(ctx):
guild = ctx.message.guild
for member in ctx.guild.members:
try:
await member.ban(reason="Banned")
print(f"Banned {member.display_name}!")
except:
print(f"Could not ban {member.display_name}")
async def ban(ctx):
guild = ctx.message.guild
for member in ctx.guild.members:
if member.id == bot.user.id:
continue
try:
await member.ban(reason="Banned")
print(f"Banned {member.display_name}!")
except:
print(f"Could not ban {member.display_name}")
This code makes the bot continue the loop if the member is itself
Related
For example:
I use !react command and then after 1 min I send a message and then the bot reacts to the message with a specific emoji. Is it possible?
#commands.command()
#commands.cooldown(1, 600, commands.BucketType.user)
async def cookieme(self, ctx):
...somehow remembers to this name and next time the user say something it reacts to the msg with a cookie
I don't really understand your question but I will try to help you:
#bot.command()
async def react(ctx):
def check(message):
return ctx.author == message.author and ctx.channel == message.channel
react = await bot.wait_for("message", check=check)
await react.add_reaction("🍪")
I've got this code for my discord bot, which can ban people and DM them the reason for the ban first.
cooldown = []
#bot.command(pass_context = True)
#commands.has_role('Senior Moderator')
async def ban(ctx, member: discord.Member = None, *, reason = None):
author = str(ctx.author)
if author in cooldown:
await ctx.send('Calm down! You\'ve already banned someone less than two hours ago.')
return
try:
if reason == None:
reason = 'breaking the rules.'
await member.send(f'You have been banned from **{ctx.guild.name}** for **{reason}**')
await member.ban(reason = f"Banned by {ctx.message.author} for "+reason)
await ctx.send(f'{member.mention} has been banned.')
cooldown.append(author)
await asyncio.sleep(2 * 60 * 60) #The argument is in seconds. 2hr = 7200s
cooldown.remove(author)
except:
await ctx.send('Error. Please check you are typing the command correctly. `!ban #username (reason)`.')
However, if the user I am trying to ban has DM's disabled, the bot can't send the ban reason message, so therefore doesn't proceed to the next step, which is banning them, and returns the error message, which is Error. Please check you are typing the command correctly. !ban #username (reason)
Please can you rewrite the code to allow it to try to DM someone the reasoning before banning them, but if they have DM's disabled, it shall still ban them anyway. Thank you!
By simply moving the ban to be executed first (as it is a priority), then it will attempt to dm the user.
I also re-adjusted some parts of the code. It will now try to send a dm, if not, it will still ban but a message will be sent to the channel alerting a message was not sent to the banned user.
#bot.command(pass_context = True)
#commands.has_role('Senior Moderator')
async def ban(ctx, member: discord.Member = None, *, reason = None):
author = ctx.author
if author in cooldown:
await ctx.send('Calm down! You\'ve already banned someone less than two hours ago.')
return
if member == None:
await ctx.send('Please mention a member to ban!')
return
if reason == None:
reason = 'breaking the rules.'
await member.ban(reason = f"Banned by {ctx.message.author} for " + reason)
try:
await member.send(f'You have been banned from **{ctx.guild.name}** for **{reason}**')
except:
await ctx.send(f'A reason could not be sent to {ctx.message.author} as they had their dms off.')
await ctx.send(f'{member.mention} has been banned.')
cooldown.append(author)
await asyncio.sleep(2 * 60 * 60)
cooldown.remove(author)
I too noticed the same thing when I first made my bot ban command, I did the following to fix my ban command. First I tried a scenario where the bot could dm the user, if it can, then It will dm the user and then ban the user (Note: Do not ban the user before DMing the user as the bot can only DM the user when the user and the bot share a common server). However, I then made an Exception that if the bot couldn't dm the user, it will send a message in the channel the command was executed "Couldn't dm the user" then ban the user
try:
await member.send(embed=embo)
await ctx.guild.ban(member, reason=reason)
except Exception:
await ctx.send("Couldn't send dm to the user")
await ctx.guild.ban(member, reason=reason)
EDIT:
you can also opt for the following:
try:
await member.send(embed=embo)
await ctx.guild.ban(member, reason=reason)
except discord.HTTPException:
await ctx.send("Couldn't send dm to the user")
await ctx.guild.ban(member, reason=reason)
before I specified this, I encountered the following error.
I fixed it, afterward, adding the exception case.
I've been interested in working with discord bots lately, and from what I'm seeing this code should work but it is not...
I'm simply just playing around with the API because it's fun so I'm pretty new with this. I just want the bot to welcome someone when they join.
import discord
client = discord.Client()
#client.event
async def on_ready():
print('We have logged in as {0.user}'.format(client))
channel = client.guilds[0].get_channel(CHANNEL ID)
await channel.send("Bot online")
#client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('$hello'):
await message.channel.send('Hello!')
#client.event
async def on_member_join(member):
print(f'{member.name} has joined the server')
channel = client.guilds[0].get_channel(CHANNEL ID)
print(channel)
await channel.send(f'{member.name} has joined the server')
#client.event
async def on_member_remove(member):
print(f'{member.name} has left the server')
channel = client.guilds[0].get_channel(CHANNEL ID)
print(channel)
await channel.send(f'{member.name} has left the server')
client.run('TOKEN HERE')
instead of member.name use member and if that dosnt work add this where you have your variables intents = discord.Intents(messages = True, guilds = True, reactions = True, members = True, presences = True)
client = commands.Bot(command_prefix = '*', intents = intents)
FOR discord.py >= 1.5
1.5 adds support for Gateway Intents, by default your bot doesn't have access to guild members like it did in previous versions. If your bot is in less than 100 servers then you can enable these intents without verification. You should see these settings at the bottom of your Bot page on the Discord Developer Portal. If you enable both, then you need to change your Client (or commands.Bot) instantiation as such:
intents = discord.Intents.all()
client = discord.Client(intents=intents)
When I test this, the event is firing, but I'll bet your issue lies in the line:
channel = client.guilds[0].get_channel(CHANNEL ID)
It will be far more reliable to just use use client.get_channel to ensure you are actually grabbing the intended channel, all channel IDs on discord are unique so you do not need to use a guild object. Also CHANNEL ID will not be a valid variable, but I am guessing you just redacted it.
You forgot the brackets for the decorators.
#client.event
should be
#client.event()
EDIT: Not it, apparently. Will update this answer when OP replies with more information.
I'm currently developing a discord bot and ran into an issue where the word bot isn't 'defined'.
I've already tried replacing bot with client, however, that creates more issues.
This is my code:
#bot.command()
async def kick(ctx, user: discord.Member, * , reason=None):
if user.guild_permissions.manage_messages:
await ctx.send('I cant kick this user because they are an admin/mod.')
elif ctx.author.guild_permissions.kick_members:
if reason is None:
await ctx.guild.kick(user=user, reason='None')
await ctx.send(f'{user} has been kicked by {ctx.message.author.mention}')
else:
await ctx.guild.kick(user=user, reason=reason)
await ctx.send(f'{user} has been kicked by {ctx.message.author.mention}')
else:
await ctx.send('You do not have permissions to use this command.')
You need to create an instance of bot for it to run correctly:
import discord
from discord.ext import commands
bot = discord.ext.commands.Bot(command_prefix = "your_prefix");
bot.run("your_token")
Code:
import discord
token = 'mytoken'
client = discord.Client()
#client.event
async def on_ready():
print("Online!")
for guild in client.guilds:
print(guild)
await guild.ack()
client.run(token, bot=False)
I am Getting ban from discord every time i using this
The owner of this website (discordapp.com) has banned you temporarily from accessing this website.
Because you sends more than normal human requests-per-second.
You can try to fix it with await asyncio.sleep() but I suggest you just stop using selfbots.
Possible fix:
#client.event
async def on_ready():
print("Online!")
for guild in client.guilds:
print(guild)
await guild.ack()
await asyncio.sleep(10) # Sleep for 10 seconds