将成员称为Discord.py中的变量

我正在尝试制作一个运行聊天过滤器的discord bot;我的最终目标是让机器人有一个单词列表,如果列出了列表中的其中一个单词,机器人会向成员添加一个计数器,如果它们变为3,那么将从服务器启动命令 .

创建列表很容易,我知道如何编写命令来踢某人,但我完全迷失了如何让机器人跟踪每个成员的值....我是否需要将成员的ID设置为变量?

任何帮助表示赞赏,我只是完全陷入困境,并且在discord.py模块中经验有限 .

import asyncio
import json
import discord
from discord.ext import commands
from discord.ext.commands import Bot

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

infractions = {}
blacklist = ["bad", "word"]
limit = 5


@bot.event
async def on_ready():
    print('Logged in as')
    print(bot.user.name)
    print(bot.user.id)
    print('------')


@bot.event
async def on_ready():
    global infractions
    try:
        with open('infractions.json') as f:
            infractions = json.load(f)
    except FileNotFoundError:
        print("Could not load infractions.json")
        infractions = {}


@bot.event
async def on_message(message):
    content = message.content.lower()
    if any(word in content for word in blacklist):
        id = message.author.id
        infractions[id] = infractions.get(id, 0) + 1
        if infractions[id] >= limit:
            await bot.kick(message.author)
        else:
            warning = f"{message.author.mention} this is your {infractions[id]} warning"
            await bot.send_message(message.channel, warning)
    await bot.process_commands(message)


@bot.command()
async def save():
    with open('infractions.json', 'w+') as f:
        json.dump(infractions, f)

回答(1)

2 years ago

您可以将成员ID的字典保存为违规次数 . 您可以从 message.author.id 属性中获取ID

from discord.ext import commands

infractions = {}
blacklist = ["bad", "word"]
limit = 5

bot = commands.Bot('!')    

@bot.event
async def on_message(message):
    content = message.content.lower()
    if any(word in content for word in blacklist):
        id = message.author.id
        infractions[id] = infractions.get(id, 0) + 1
        if infractions[id] >= limit:
            await bot.kick(message.author)
        else:
            warning = f"{message.author.mention} this is your {infractions[id]} warning"
            await bot.send_message(message.channel, warning)
    await bot.process_commands(message)

我建议使用id作为键而不是 Member 对象,以便您可以更轻松地将文件保存为JSON,这将允许您在关闭机器人时保留值 . See this other answer I wrote for an example of how to do that