如何禁止用户使用discord.py?

如何禁止用户使用discord.py?,discord,discord.py,bots,Discord,Discord.py,Bots,我想知道如何使用以下命令禁止discord服务器上的成员$ban,然后是我要禁止的用户的姓名{member.name},然后是他被禁止的原因。还将个人bot消息发送给被禁止的用户,并说明他被禁止的原因(我在控制台{member.name}之后键入的原因)。我正在考虑在消息上的中生成这个命令,因为我在那里写了很多命令。我试过使用这个(不是在消息上的): 但我不能禁止任何人。它似乎不起作用。请帮助我,不要删除这个问题 我的代码在这里,但您不会理解任何内容: import discord import

我想知道如何使用以下命令禁止discord服务器上的成员
$ban
,然后是我要禁止的用户的姓名
{member.name}
,然后是他被禁止的原因。还将个人bot消息发送给被禁止的用户,并说明他被禁止的原因(我在控制台
{member.name}
之后键入的原因)。我正在考虑在消息上的
中生成这个命令,因为我在那里写了很多命令。我试过使用这个(不是在消息上的
):

但我不能禁止任何人。它似乎不起作用。请帮助我,不要删除这个问题

我的代码在这里,但您不会理解任何内容:

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 != '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.')
导入不一致
导入操作系统
导入请求
从服务器导入ping
从discord.utils导入获取
从discord.ext导入命令、任务
随机输入
从异步导入睡眠
从收款进口柜台
导入日期时间
导入json
#机器人前缀
bot_前缀=(“$”)
x=bot_前缀
#进口
intents=discord.intents().all()
intents.members=True
#客户端/BOT变量
client=commands.Bot(命令\前缀='$',描述='',意图=意图,帮助\命令=无)
#bot=commands.bot(command\u prefix=bot\u prefix,description='')
#如果拖缆处于联机状态,则命令
#删除某些频道中的命令
#使命令在编辑后工作
#警告/禁止/静音
#删除在频道中发送的图像
#水准测量系统
#变数
是=0
否=0
问题=“”
正确答案='default'
a_1=''
a_2=''
a_3=''
msg_id=1
测验分数=[]
#嵌入颜色列表
颜色=[0xFFE4E1、0x00FF7F、0xD8BFD8、0xDC143C、0xFF4500、0xDEB887、0xADFF2F、0x800000、0x4682B4、0x006400、0x808080、0xA0522D、0xF08080、0xC71585、0xFFB6C1、0x00CED1]
#词表
城市=[“东京”、“德里”、“上海”、“圣保罗”、“墨西哥城”、“开罗”、“孟买”、“莫斯科”、“北京”、“达卡”、“大阪”、“纽约市”、“卡拉奇”、“布宜诺斯艾利斯”、“重庆”、“阿姆斯特丹”、“伊斯坦布尔”、“加尔各答”、“马尼拉”、“悉尼”、“拉各斯”、“里约热内卢”、“天津”、“金沙萨”、“广州”、“洛杉矶”、“深圳”、“拉合尔”、“班加罗尔”“巴黎”、“波哥大”、“利马”、“曼谷”、“奥斯陆”、“首尔”、“名古屋”、“海得拉巴”、“伦敦”、“德黑兰”、“芝加哥”、“武汉”、“胡志明市”、“罗安达”、“艾哈迈达巴德”、“吉隆坡”、“利雅得”、“巴格达”、“卡萨布兰卡”、“圣地亚哥”、“苏拉特”、“布鲁塞尔”、“马德里”、“浦那”、“哈尔滨”、“休斯顿”、“多伦多”、“达拉斯”、“达累斯萨拉姆”、“迈阿密”、“贝洛奥里藏特”,“巴西”、“新加坡”、“费城”、“亚特兰大”、“福冈”、“喀土穆”、“巴塞罗那”、“约翰内斯堡”、“圣彼得堡”、“大连”、“华盛顿”、“仰光”、“亚历山大”、“济南”、“瓜达拉哈拉”]
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}”]
溪流词=[“κГааСааааааСаааааааааааааааааааааааааааааааааа1072
react_authors=[]
#你好世界节目
@客户端事件
_ready()上的异步定义:
打印('以{0.user}身份登录'。格式(客户端))
等待客户。改变状态(活动=不和谐。活动(类型=不和谐。活动类型。播放,名称=“不和谐”)
打印(请求.get()https://api.twitch.tv/turb4ik/streams/'))
打印(不一致的版本)
''@tasks.loop(秒=3)
异步def流():
#guild=client.guild
#igor=get(guild.users,name='alinter#u igor#3291')
尽管如此:
等待客户。更改状态(活动=不和谐。流媒体(名称='Resident Igor',url='https://www.twitch.tv/dwellerigor“)#更改我的状态
@客户端事件
_connect()上的异步定义:
stream.start()“”
@客户端事件
异步def on_消息(消息):
以open('users.json','r')作为f:
users=json.load(f)
将open('users.json','w')作为f:
json.dump(用户,f)“”
全球是
全球编号
全局msg_id
全球味精
全球问题
全局正确答案
全球a_1
全球a_2
全球a_3
全局msg_id
如果message.author==client.user:
通过
其他:
word=message.content
author\u roles=[message.author.roles中角色的role.name]
def load_question():
全球问题
全局正确答案
全球a_1
全球a_2
全球a_3
全球测验嵌入
response=requests.get('https://opentdb.com/api.php?amount=1&category=11&difficulty=easy&type=multiple')
response=response.json()
问题=回答['results'][0]['question']#-str(''“')???
正确答案=回答['results'][0]['correct\u answer']
a_1=响应['results'][0]['error_answers'][0]
a_2=响应['results'][0]['error_answers'][1]
a_3=响应['results'][0]['error_answers'][2]
答案列表=[正确答案,a_1,a_2,a_3]
随机。随机(ANSU列表)
#不正确的_列表=[a_1,a_2,a_3]
quick_embed=discord.embed(标题=‘电影测验’,
描述=问题,
颜色=0xfbb304)
测验\嵌入。添加\字段(
名称='答案',
值=ans_列表,
inline=True,
)
如果message.content.startswith(“$quick”):
words=message.content.split()
如果单词[1].lower()=='films':
加载问题()
msg=wait message.channel.send(嵌入=quick\u嵌入)
msg_id=msg.id
打印('message1id:'+str(msg_id))
打印(正确答案)
如果正确,请在message.content.lower()中回答.lower():
测验分数.append(message.author.name)
打印(测验分数)
打印(键入(测验分数))
cnt=计数器(测验分数)
user_score=cnt[str(message.author.name)]
wait message.channel.send(str(message.author.name)+‘搞定了!\n您的分数是:’+str(user_分数))
如果message.content.startswith(“$next”):
负载
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 != '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.')
@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}"''')