如何“临时禁止”有discord.py的人?

时间:2019-03-06 21:23:52

标签: python-3.x scheduled-tasks discord python-asyncio discord.py

我正在使用discord.py做一个管理discord机器人,所以我意识到我需要添加一条命令来临时禁止某人一段时间,此禁止可以通过角色或将成员踢出渠道然后禁止他,但我不知道该怎么做。有人能帮我吗?

2 个答案:

答案 0 :(得分:2)

经过反复尝试,我终于明白了!鉴于下面是一个discord.py机器人,它具有一个命令来暂时禁止一个用户,并且可以用于多个用户

import discord
from discord.ext import commands
import asyncio

TOKEN=""

client=commands.Bot(command_prefix=".")

ban_list=[]
day_list=[]
server_list=[]

#This is a background process
async def countdown():
    await client.wait_until_ready()
    while not client.is_closed:
        await asyncio.sleep(1)
        day_list[:]=[x-1 for x in day_list]
        for day in day_list:
            if day<=0:
                try:
                    await client.unban(server_list[day_list.index(day)],ban_list[day_list.index(day)])
                except:
                    print('Error! User already unbanned!')
                del ban_list[day_list.index(day)]
                del server_list[day_list.index(day)]
                del day_list[day_list.index(day)]

#Command starts here
@client.command(pass_context=True)
async def ban(ctx,member:discord.Member,days=1):
    if str(ctx.message.author.id)=='<You ID goes here>':
        try:
            await client.ban(member,delete_message_days=0)
            await client.say('User banned for **'+str(days)+' day(s)**')
            ban_list.append(member)
            day_list.append(days*24*60*60)
            server_list.append(ctx.message.server)
        except:
            await client.say('Error! User not active')
    else:
        await client.say('You do not have permission to ban users!')

client.loop.create_task(countdown())
client.run(TOKEN)

enter image description here

  

我通过禁止三个用户使用不同的时间来测试了该程序,它的工作原理很吸引人。请注意,时间可能不太准确。您选择的时间越长,错误就越大。

由于某些原因,Bot无法禁止处于脱机状态的用户。

该机器人必须全天候在线,这样才能正常工作...如果重新启动该机器人或该机器人崩溃,则所有列表都将被清除。

答案 1 :(得分:0)

这取决于您所说的“临时禁令”。

您是要让用户实际上在某个时间段内被踢出并禁止其进入服务器,还是要暂时限制该用户使用某些权限(例如聊天)?

我建议使用后者,并使用API​​的Discord rewrite branch,该API是经过改进的新功能。

通过角色分配限制成员,并在x秒后取消限制:

@bot.command()
async def restrict(ctx, member:discord.Member, duration: int):
    role = discord.utils.get(ctx.guild.roles, name="Restricted")
    await member.add_roles(role)
    await asyncio.sleep(duration)
    await member.remove_roles(role)

禁止用户并在x秒后取消禁止:

@bot.command()
async def ban(ctx, user:discord.User, duration: int):
    await ctx.guild.ban(user)
    await asyncio.sleep(duration)
    await ctx.guild.unban(user)

请记住,如果您的机器人在休眠以解除禁止用户状态时崩溃或出于任何原因脱机,则该机器在恢复后将不会解除对用户的禁止操作,因此考虑使用的可能是数据库并存储禁令的结束时间。然后,您可以在漫游器启动过程中查询所有保存的日期,以计算睡眠时间。另外,您将必须获取其User对象而不是Member对象,因为它们不再是公会的一部分。