如何让 Discord 机器人自动踢用户

时间:2021-01-29 08:37:29

标签: discord.py

感谢阅读我糟糕的英语

我现在正在制作一个 Discord 机器人。我想让一个 Discord 机器人在满足特定条件时自动踢出用户。

这是我的想法。

当黑名单上的用户发送消息时->机器人检查发送消息的尝试次数->如果超过10次,机器人踢用户。如果不是删除用户的消息

我尽力了。但我找不到解决方案。

这是代码

import discord
from discord.ext import commands

bot = commands.Bot(command_prefix='!')

BanUser = {} #dictionary of banned users. Data will save as {user's name: number of attempts to send a message}
@bot.event
async def on_message(message):
    sharpPos = str(message.author).index('#') # Where the # is located
    user = str(message.author)[:sharpPos].strip() //Slice strings after # and #

    if usercode in BanUser: #if the user who tried to send a message is in BanUser list
        BanUsr[user] = BanUsr[user] + 1 #plus 1 to user's number of attempts to send a message
        if BanUsr[user] < 10: # if the user's number of attempts to send a message is less than 10
            await message.delete() #delete user's message
        else: #if the user's number of attempts to send a message is equal to 10 or greater than 10
            #code of kick user 

async def ban(ctx):
    text = str(ctx.message.content).replace("!", "", 1).replace("ban", "", 1).strip() """ For example, if user want to ban user named 'A'. Then user have to write command like '!ban A'. And then **text** will be A after this code """
        if not text in BanUser: #if the user isn't in the ban list
            BanUser[text] = 0 
            return
        else:
            return

如果用户尝试发送消息的次数等于或大于 10,如何让机器人自动踢用户?

1 个答案:

答案 0 :(得分:0)

回答您的问题,您的代码中有很多没有意义的地方:

attemps = {} # Format `{ID: attemps}` (it's better to store ID's than names)

@bot.event
async def on_message(message):
    global attemps
    # Checking if the user is in the dict & if the message is not sent in DM's
    if message.author.id in attemps and not isinstance(message.channel, discord.DMChannel): 
        # Getting the current attemps
        current_attemps = attemps[message.author.id] + 1
        if current_attemps >= 10:
            # If the user exceeded the count
            # kick the him & reset the count
            await message.author.kick()
            attemps[message.author.id] = 0

        else:
            # If the user didn't exceed 10 attemps
            # updating the count & deleting the message
            attemps[message.author.id] = current_attemps
            await message.delete()

注意:我个人会使用数据库(甚至是 JSON 文件)来处理此类事情,一旦机器人重新启动,计数就会重置并丢失