这能够将验证命令限制到特定频道并检查作者是否具有成员角色。我想在写 .verify
时给他们角色,不知道该怎么做。
这是齿轮
from discord.ext import commands
import time
from discord.utils import get
class Bot(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.command()
async def verify(self, ctx):
roles = []
for role in ctx.author.roles:
roles.append(role)
isMember = "??????" in roles
if ctx.channel.id == 802969634801188884 and isMember == False:
await ctx.send(f'<@{ctx.author.id}>, you are now verified.')
time.sleep(3)
await ctx.channel.purge(limit = 2)
else:
await ctx.send(f'{ctx.message.content} is not a command')
def setup(bot):
bot.add_cog(Bot(bot))```
答案 0 :(得分:1)
您的代码中有几处错误,还有几处您可以优化。
async def verify(self, ctx):
# You don't need the for loop and appending to the `roles` list
# `ctx.author.roles` already a list of roles
roles = ctx.author.roles
# There was another issue, `roles` is now a list of `discord.Role` instances
# so if you do `"Member" in roles` will always be False, even if the member has the role
# to fix you can either get the role object, or convert the `roles` list to a list of the role names
role_names = [role.name for role in roles]
is_member = "Member" in role_names
if is_member: # Exiting if the user already has the role
return await ctx.send("You are already verified")
if ctx.channel.id != 802969634801188884: # Exiting as well if it's not the correct channel
return await ctx.send(f"{ctx.message.content} is not a command")
# Getting the role and adding it
member_role = discord.utils.get(ctx.guild.roles, name="Member") # I'm guessing the name of the role is `Member`, otherwise change it accordingly
# You can also use `ctx.guild.get_role(ROLE_ID)` if you want to get the role by ID
# Adding the roles
await ctx.author.add_roles(member_role)
await ctx.send(f"{ctx.author.mention} you are now verified")
await asyncio.sleep(3) # `time.sleep` is blocking, you should never use it within your asynchronous code, also remember to `import asyncio`
await ctx.channel.purge(limit=2)
我已尝试在代码中添加尽可能多的注释以供您理解,如果您有任何疑问,请随时在下面的注释中提问。