Dweller
Dweller

Reputation: 15

How to ban users using discord.py?

I wanted to know how to ban members on discord server using following command $ban and then name of the user I want to ban {member.name} and then the reason why he got banned. Also send the personal bot-message to banned user with the reason why he got banned (the reason I typed in console after {member.name}). And I was thinking about making this command in on_message because I write a lot of my commands there. I tried using this (not in on_message):

@client.command(pass_context = True)
async def mute(ctx, member: discord.Member):
     if ctx.message.author.server_permissions.administrator or ctx.message.author.id == '194151340090327041':
        role = discord.utils.get(member.server.roles, name='Muted')
        await client.add_roles(member, role)
        embed=discord.Embed(title="User Muted!", description="**{0}** was muted by **{1}**!".format(member, ctx.message.author), color=0xff00f6)
        await client.say(embed=embed)
     else:
        embed=discord.Embed(title="Permission Denied.", description="You don't have permission to use this command.", color=0xff00f6)
        await client.say(embed=embed)

but I couldn't ban anyone. It doesn't seem to work. Please help me and don't delete this question.

My code here, but you will not understand anything:

import discord
import os
import requests
from server import ping
from discord.utils import get
from discord.ext import commands, tasks
import random
from asyncio import sleep
from collections import Counter
import datetime
import json

#BOT PREFIX
bot_prefix = ('$')
x = bot_prefix

#Import
intents = discord.Intents().all()
intents.members = True

#CLIENT/BOT VARIABLES
client = commands.Bot(command_prefix = '$', description = ' ', intents = intents, help_command = None)
#bot = commands.Bot(command_prefix = bot_prefix, description = '')

#if streamer is online command
#delete commands in certain channels
#make commands work after editing
# warn/ban/mute
#delete images send in channel
#leveling system

#VARIABLES
yes = 0
no = 0
question = ' '
correct_answer = 'default'
a_1 = ' '
a_2 = ' '
a_3 = ' '
msg_id = 1

quiz_score = []

#EMBED COLOR LIST
colors = [0xFFE4E1, 0x00FF7F, 0xD8BFD8, 0xDC143C, 0xFF4500, 0xDEB887, 0xADFF2F, 0x800000, 0x4682B4, 0x006400, 0x808080, 0xA0522D, 0xF08080, 0xC71585, 0xFFB6C1, 0x00CED1]

#WORD LISTS
cities = ["Tokio", "Delhi", "Shanghai", "Sao Paulo", "Mexico City", "Cairo", "Mumbai", "Moscow", "Beijing", "Dhaka", "Osaka", "New York City", "Karachi", "Buenos Aires", "Chongqing", "Amsterdam", "Istanbul", "Kolkata", "Manila", "Sydney", "Lagos", "Rio de Janeiro", "Tianjin", "Kinshasa", "Guangzhou", "Los Angeles", "Shenzhen", "Lahore", "Bangalore", "Paris", "Bogota", "Lima", "Bangkok", "Oslo", "Seoul", "Nagoya", "Hyderabad", "London", "Tehran", "Chicago", "Wuhan", "Ho Chi Minh City", "Luanda", "Ahmedabad", "Kuala Lumpur", "Riyadh", "Baghdad", "Casablanca", "Santiago", "Surat", "Brussel", "Madrid", "Pune", "Harbin", "Houston", "Toronto", "Dallas", "Dar es Salaam", "Miami", "Belo Horizonte", "Brazilia", "Singapore", "Philadelphia", "Atlanta", "Fukuoka", "Khartoum", "Barcelona", "Johannesburg", "Saint Petersburg", "Dalian", "Washington", "Yangon", "Alexandria", "Jinan", "Guadalajara"]
nl_weather_words = ["$weather Amsterdam", "$Weather amsterdam", "$weather amsterdam", "$weather Amsterdam"]
ru_weather_words = ["$weather", "$Weather","$outside", "$Outside"]

weather_words = [f"$weather {cities}", f"$Weather {cities}",f"$outside {cities}", f"$Outside {cities}"]

stream_words = ['Когда Стрим?', 'когда стрим?', 'когда стрим', 'Когда стрим?', 'когда Стрим?', 'Когда стрим', 'Когда Стрим', 'когда Стрим', 'когда-стрим?', 'в сколько стрим?', 'будет стрим?']
react_authors = []

#HELLO WORLD PROGRAMM
@client.event 
async def on_ready():
  print('logged in as {0.user}'.format(client))

  await client.change_presence(activity=discord.Activity(type=discord.ActivityType.playing,name="уничтожение вселенной"))

  print(requests.get('https://api.twitch.tv/turb4ik/streams/'))
  print(discord.__version__)

'''@tasks.loop(seconds = 3)
async def stream():
  #guild = client.guild
  #igor = get(guild.users, name = 'Dweller_Igor#3291')

  while True:
    await client.change_presence(activity = discord.Streaming(name = 'Dweller Igor', url = 'https://www.twitch.tv/dwellerigor')) #change my status

@client.event
async def on_connect():
  stream.start()'''

@client.event 
async def on_message(message):

  '''with open('users.json', 'r') as f:
   users = json.load(f)

  with open('users.json', 'w') as f:
    json.dump(users, f)'''

  global yes
  global no
  global msg_id
  global msg
  global question
  global correct_answer
  global a_1
  global a_2
  global a_3
  global msg_id

  if message.author == client.user:
    pass

  else:
    word = message.content
    author_roles = [role.name for role in message.author.roles]

  def load_question():

    global question
    global correct_answer
    global a_1
    global a_2
    global a_3
    global quiz_embed

    response = requests.get('https://opentdb.com/api.php?amount=1&category=11&difficulty=easy&type=multiple')

    response = response.json()

    question = response['results'][0]['question'] #- str('"') ???
    correct_answer = response['results'][0]['correct_answer']
    a_1 = response['results'][0]['incorrect_answers'][0]
    a_2 = response['results'][0]['incorrect_answers'][1]
    a_3 = response['results'][0]['incorrect_answers'][2]

    ans_list = [correct_answer, a_1, a_2, a_3]
    random.shuffle(ans_list)

    #incorrect_list = [a_1, a_2, a_3]

    quiz_embed = discord.Embed(title = 'Film Quiz',
    description = question,
    color = 0xfbb304)

    quiz_embed.add_field(
    name = 'Answers',
    value = ans_list,
    inline = True,
    )

  if message.content.startswith('$quiz'):

    words = message.content.split()

    if words[1].lower() == 'films':

      load_question()

      msg = await message.channel.send(embed = quiz_embed)
      
      msg_id = msg.id
      print('message 1 id: ' + str(msg_id))
      
      print(correct_answer)

  if correct_answer.lower() in message.content.lower():

    quiz_score.append(message.author.name)

    print(quiz_score)
    print(type(quiz_score))
    cnt = Counter(quiz_score)
    user_score = cnt[str(message.author.name)]

    await message.channel.send(str(message.author.name) + ' got it right! \n Your score is: ' + str(user_score))

  if message.content.startswith('$next'):
    load_question()
    msg = await message.channel.send(embed = quiz_embed)
    print(correct_answer)
  
  #channel_names = [channel.name for role in message.author.roles]
  channel = discord.utils.get(message.guild.channels)

  #GIFs
  if message.content == (str(x) + 'fbi'):
    if channel.name != '🧪токсик' and channel.name != '🤖комaнды-ботов':
      await message.channel.send(os.getenv('fbi'))
      await message.delete()

  if message.content == str(x) + 'ban' and 'КРЧ, ОДМЕН' in author_roles :
    await message.channel.send(os.getenv('ban'))
    await message.delete()

  if message.content == (str(x) + 'naked'):
    if channel.name != '🧪токсик' and channel.name != '🤖комaнды-ботов':
      await message.channel.send(os.getenv('gandalf'))
      await message.delete()

  if message.content == (str(x) + 'hide'):
    await message.channel.send(os.getenv('hide')) #gifenv[3]
    await message.delete()

  if message.content == (str(x) + 'woo'):
    await message.channel.send(os.getenv('woo')) #gifenv[3]
    await message.delete()

  if word == '$hi':
    await message.channel.send(' Hi, ' + str(message.author.mention) + ' ! ' + 'I am just waiting for the moment to snap you out of here!')

  if word in nl_weather_words: # and 'Pro Tamer' in author_roles ,if only some roles can use this command
                              
    weather_key = os.getenv('key')

    response = requests.get(f'http://api.openweathermap.org/data/2.5/weather?q=Amsterdam,nl&APPID={weather_key}&units=metric')    

    data = response.json()
                              
    curr_temp = data['main']['temp']
    curr_feels_like = data['main']['feels_like']
                              
    if curr_feels_like < 10:
      dress_code = "warm"

    else:
      dress_code = "light"

    payload = f'Right now it is {curr_temp} ° Celcius, but it feels like {curr_feels_like} ° Celcius, I recommend wearing {dress_code} clothes outside.'

    weather_embed = discord.Embed(
      title = 'Current weather in Amsterdam', 
      description = payload,
      color = 0xfbb304
    )

    weather_embed.set_author(
      name = str(message.author),
      icon_url = message.author.avatar_url
    )

    await message.channel.send(embed = weather_embed)
    await message.delete()

  if word in ru_weather_words:
                              
    key1 = os.getenv('key1')

    response = requests.get(f'http://api.openweathermap.org/data/2.5/weather?q=Moscow,ru&APPID={key1}&units=metric')    

    data = response.json()
                              
    curr_temp = data['main']['temp']
    curr_feels_like = data['main']['feels_like']
                              
    if curr_feels_like < 10:
      dress_code = "warm"

    else:
      dress_code = "light"

    payload = f'Right now it is {curr_temp} ° Celcius, but it feels like {curr_feels_like} ° Celcius, I recommend wearing {dress_code} clothes outside.'

    weather_embed = discord.Embed(
      title = 'Current weather in Moscow', 
      description = payload,
      color = 0xd90c21
    )

    weather_embed.set_author(
      name = str(message.author),
      icon_url = message.author.avatar_url
    )

    await message.channel.send(embed = weather_embed)
    await message.delete()

  '''if word in weather_words:
                              
    key1 = os.getenv('key1')

    response = requests.get(f'http://api.openweathermap.org/data/2.5/weather?q={cities}&APPID={key1}&units=metric')    

    data = response.json()
                              
    curr_temp = data['main']['temp']
    curr_feels_like = data['main']['feels_like']
                              
    if curr_feels_like < 10:
      dress_code = "warm"

    else:
      dress_code = "light"

    payload = f'Right now it is {curr_temp} ° Celcius, but it feels like {curr_feels_like} ° Celcius, I recommend wearing {dress_code} clothes outside.'

    weather_embed = discord.Embed(
      title = 'Current weather in ', 
      description = payload,
      color = random.choice(colors)
    )

    weather_embed.set_author(
      name = str(message.author),
      icon_url = message.author.avatar_url
    )

    await message.channel.send(embed = weather_embed)
    await message.delete()'''
  
  '''if message.content.startswith('%purge'):
    word_list = message.content.split()
    num = word_list[1]
    message.channel.purge(limit = num)'''

  if word in stream_words:
  
    #emoji = get(ctx.message.server.emojis, name = 'facepalm' ) #help!

    answer = str(message.author.mention)+ ' ' + ' <:facepaml:798992254739415071> ' + ', как можно не знать? Стрим будет тогда, когда Антон его начнёт!'

    stream_embed = discord.Embed(
      title = 'Ответ на всем известный вопрос', 
      description = answer, # + thanos gif
      color = random.choice(colors)
    )

    stream_embed.set_image(url = 'https://media1.tenor.com/images/d8bac012ba263cf0af2f179d2235afb0/tenor.gif?itemid=14046382')

    await message.channel.send(embed = stream_embed) 

  if word.startswith(str(x) + 'stream'):

    yes = 0
    no = 0

    say = 'У вас есть только один голос, используйте его разумно'

    stream_embed = discord.Embed(
      title = 'Сегодня будет стим?',
      description = say,
      color = 0xf85611
    )

    stream_embed.add_field(
      name = 'Да ✔️',
      value = yes, 
      inline = True
    )

    stream_embed.add_field(
      name = 'Нет ❌',
      value = no, 
      inline = True
    )

    msg = await message.channel.send(embed = stream_embed)

    msg_id = msg.id
    print('embed id: ' + str(msg_id))

    await msg.add_reaction('✔️')
    await msg.add_reaction('❌') 
    await message.delete()

    target_channel_id = 797130143793414165

    @tasks.loop(hours=24)
    async def called_once_a_day():
        message_channel = client.get_channel(target_channel_id)
        print(f"Got channel {message_channel}")
        await message_channel.send(msg)   #??????????????????????????????????????????????

    @called_once_a_day.before_loop #does this work?
    async def before():
        await client.wait_until_ready()
        print("Finished waiting")

  ctx = await client.get_context(message)
  split = message.content.split()
  if split[0] == "$clear" and 'КРЧ, ОДМЕН' or 'КРЧ, МОДЕР' in author_roles:
      if len(split) == 2: #Detecting if the split method is in the proper 
                          #syntax, you can also detect if the second item is 
                          #a num as the method I did won't check all 
                          #scenarios
          num = int(split[1])
          await ctx.channel.purge(limit = num)
      else:
          message.channel.send("Please enter the command as $clear <amount>")

@client.event
async def on_reaction_add(reaction, user):

  global msg_id
  global yes
  global no
  global poll_embed
  global msg
  global react_authors

  say = 'У вас есть только один голос, используйте его разумно'

  react_id = reaction.message.id
  print('print ' + str(react_id))

  check_mark = '✔️'
  cross_mark = '❌'

  if react_id == msg_id:
    print('new reaction')

    if user.name not in react_authors:
      if user.name != reaction.message.author.name:
        react_authors.append(user.name)

        if reaction.emoji == check_mark:
          yes += 1
          print(yes) 

        if react_id == msg_id:
          print('cross reaction')

          if reaction.emoji == cross_mark:
            no += 1
            print(no)

          cross_embed = discord.Embed(
            title = 'Сегодня будет стим?',
            description = say,
            color = 0xf85611
          )

          cross_embed.add_field(
            name = 'Да ✔️',
            value = yes, 
            inline = True
          )

          cross_embed.add_field(
            name = 'Нет ❌',
            value = no, 
            inline = True
          )

          await msg.edit(embed = cross_embed)

'''@client.event
async def on_member_join(member):
    await member.create_dm()
    await member.dm_channel.send.format(member.name)(
        'Hi {member.name}, welcome to our Discord server! Get ready for war!')'''

@client.command()
@commands.has_permissions(kick_members=True, ban_members=True, manage_roles=True) # Setting permissions that a user should have to execute this command.
async def ban(ctx, member: discord.Member, *, reason=None):
    if member.guild_permissions.administrator: # To check if the member we are trying to mute is an admin or not.
        await ctx.channel.send(f'Hi {ctx.author.name}! The member you are trying to mute is a server Administrator. Please don\'t try this on them else they can get angry! :person_shrugging:')

    else:
        if reason is None: # If the moderator did not enter any reason.
            # This command sends DM to the user about the BAN!
            await member.send(f'Hi {member.name}! You have been banned from {ctx.channel.guild.name}. You must have done something wrong. VERY BAD! :angry: :triumph: \n \nReason: Not Specified')
            # This command sends message in the channel for confirming BAN!
            await ctx.channel.send(f'Hi {ctx.author.name}! {member.name} has been banner succesfully from this server! \n \nReason: Not Specified')
            await member.ban() # Bans the member.
        
        else: # If the moderator entered a reason.
            # This command sends DM to the user about the BAN!
            await member.send(f'Hi {member.name}! You have been banned from {ctx.channel.guild.name}. You must have done something wrong. VERY BAD! :angry: :triumph: \n \nReason: {reason}')
            # This command sends message in the channel for confirming BAN!
            await ctx.channel.send(f'Hi {ctx.author.name}! {member.name} has been banner succesfully from this server! \n \nReason: {reason}')
            await member.ban() # Bans the member.

@client.event
async def on_member_join(member):
  await sleep(10)

  '''with open('users.json', 'r') as f:
    users = json.load(f)
    
  #await update_data(users, member)

  with open('users.json', 'w') as f:
    json.dump(users, f)'''

  for channel in member.guild.channels:
    if channel.name.startswith('📊 Все участники:'):
      await channel.edit(name = f'📊 Все участники: {member.guild.member_count}')

  role_channel = client.get_channel(785511190725656606)
  rule_channel = client.get_channel(798160390441009183)
  welcome = f'Добро пожаловать на сервер "{member.guild.name}" {member.mention}!  Советую вам заглянуть в канал {role_channel.mention} и {rule_channel.mention}! Я надеюсь ты к нам надолго...'

  if member.guild.name == 'КРЧ ИГРЫ!':  #type your server name
      welcome_embed = discord.Embed(title=f'Приветствую тебя {member.name} !',
      description = welcome,
      color= random.choice(colors),
      font_size=200)

      #await client.get_channel(798118587906785300).send(f"{member.mention}")
      await client.get_channel(798118587906785300).send(embed = welcome_embed)
      #role = discord.utils.get(member.guild.roles, name="Community")
      #await member.add_roles(role)
      await member.send('Hi there! I hope you will stay here for a long time...')

  else:
      return

@client.event
async def on_member_remove(member):
  await sleep(10)
  for channel in member.guild.channels:
    if channel.name.startswith('📊 Все участники:'):
      await channel.edit(name = f'📊 Все участники: {member.guild.member_count}')
      
  bye = f'Прощай {member.mention}! Надеюсь ты хорошенько подумаешь и вернешься!'

  if member.guild.name == 'КРЧ ИГРЫ!':  #type your server name
      bye_embed = discord.Embed(title=f'До свидания {member.name} !',
      description = bye,
      color= random.choice(colors),
      font_size=200)

      await client.get_channel(798118587906785300).send(embed = bye_embed)

  else:
      return

@client.command(pass_context = True)
async def mute(ctx, member: discord.Member):
     if ctx.message.author.server_permissions.administrator or ctx.message.author.id == '194151340090327041':
        role = discord.utils.get(member.server.roles, name='Muted')
        await client.add_roles(member, role)
        embed=discord.Embed(title="User Muted!", description="**{0}** was muted by **{1}**!".format(member, ctx.message.author), color=0xff00f6)
        await client.say(embed=embed)
     else:
        embed=discord.Embed(title="Permission Denied.", description="You don't have permission to use this command.", color=0xff00f6)
        await client.say(embed=embed)

ping()
client.run(os.getenv('token'))

Upvotes: 1

Views: 4528

Answers (2)

Botolog_E
Botolog_E

Reputation: 15

try this code to ban:

@client.command(alaises=['Ban'])
async def ban(ctx, member: discord.Member, *, reason=None):
    await member.ban(reason=reason)
    await ctx.send(f'''"{member}" has been kicked by "{ctx.author}" with the reason "{reason}"''')

Upvotes: 0

Bhavyadeep Yadav
Bhavyadeep Yadav

Reputation: 831

I would be giving you the code with comments inside telling the use of it.

This is the code for the bot that I used.

import discord
from discord.ext import commands

mybot = commands.Bot(command_prefix='$',
                    help_command=None) # help_command to disable the default one created by this library.

@mybot.event
async def on_ready(): # To confirm that BOT is online.
    print('I am not online. Let\'s try not to crash today, shall we?')

@mybot.command()
@commands.has_permissions(kick_members=True, ban_members=True, manage_roles=True) # Setting permissions that a user should have to execute this command.
async def ban(ctx, member: discord.Member, *, reason=None):
    if member.guild_permissions.administrator: # To check if the member we are trying to mute is an admin or not.
        await ctx.channel.send(f'Hi {ctx.author.name}! The member you aer trying to mute is a server Administrator. Please don\'t try this on them else they can get angry! :person_shrugging:')

    else:
        if reason is None: # If the moderator did not enter any reason.
            # This command sends DM to the user about the BAN!
            await member.send(f'Hi {member.name}! You have been banned from {ctx.channel.guild.name}. You must have done something wrong. VERY BAD! :angry: :triumph: \n \nReason: Not Specified')
            # This command sends message in the channel for confirming BAN!
            await ctx.channel.send(f'Hi {ctx.author.name}! {member.name} has been banner succesfully from this server! \n \nReason: Not Specified')
            await member.ban() # Bans the member.
        
        else: # If the moderator entered a reason.
            # This command sends DM to the user about the BAN!
            await member.send(f'Hi {member.name}! You have been banned from {ctx.channel.guild.name}. You must have done something wrong. VERY BAD! :angry: :triumph: \n \nReason: {reason}')
            # This command sends message in the channel for confirming BAN!
            await ctx.channel.send(f'Hi {ctx.author.name}! {member.name} has been banner succesfully from this server! \n \nReason: {reason}')
            await member.ban() # Bans the member.


mybot.run('ENTER YOU BOT\'S TOKEN HERE.')

Here are the images for the confirmation:

For ban confirmation in the server I used my main ID to execute the command: Ban command execution from my main account!

For ban confirmation in the DM I banned my alt account from a mutual server and then checked the DM: DM to my alt account!


I have added the use of the commands in the comments in the code. If still you need help, you can ask me here. I would be glad to answer. :)

Thank You! :D

Upvotes: 2

Related Questions