discord - 如何禁止用户使用 discord.py?
问题描述
我想知道如何使用以下命令禁止不和谐服务器上的成员$ban
,然后是我要禁止的用户的名称,{member.name}
然后是他被禁止的原因。还将个人机器人消息发送给被禁止的用户,说明他被禁止的原因(我在控制台之后输入的原因{member.name}
)。我正在考虑制作这个命令,on_message
因为我在那里写了很多命令。我尝试使用这个(不在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)
但我不能禁止任何人。它似乎不起作用。请帮助我,不要删除这个问题。
我的代码在这里,但你什么都不会理解:
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'))
解决方案
我会给你代码,里面有注释,告诉你它的用途。
这是我使用的机器人的代码。
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.')
以下是用于确认的图像:
对于 DM 中的禁令确认,我从一个共同服务器中禁止了我的 alt 帐户,然后检查了 DM:
我在代码的注释中添加了命令的使用。如果仍然需要帮助,可以在这里问我。我很乐意回答。:)
谢谢你!:D
推荐阅读
- ios - 后续视图控制器上缺少选项卡栏控制器
- php - 我想按类别显示金额 贷方或借方 我只收到贷方金额
- django - “NoneType”对象没有属性“_meta”
- angular - 如何在Angular7中访问对象数组内的数组?
- c# - 如何为文档创建第三个签名
- variables - 如何将存储变量的值传递给jmeter中的另一个请求
- java - 两个线程是否有可能面对单个对象实例的死锁?
- machine-learning - 具有单个时间信号输入的 LSTM 多步预测
- ajax - 通过 AJAX 在 Yii2 中验证 Select2
- android-gradle-plugin - 由于“无法从...加载 Maven 元数据”,Gradle 同步失败,但我可以通过浏览器下载文件