问题
I'm trying to make a discord bot that runs chat filter; my end goal is for a bot to have a list of words and if one of those words from the list is said, the bot will add a tally to a member and if they get like 3 then a command to kick from server will run.
Creating the list is easy and I know how to write the command to kick someone, but I am absolutely lost on how I would get the bot to track values for each member.... Would I need to set the member's ID as a variable?
Any help is appreciated, I am just absolutely stuck and have limited experience in the discord.py module.
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:
You can keep a dictionary of member ids to number of infractions. You can get the id from the message.author.id
attribute
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)
I suggest using ids as keys rather than Member
objects so that you can more easily save the file as a JSON, which will allow you to persist values when you shut off your bot. See this other answer I wrote for an example of how to do that
来源:https://stackoverflow.com/questions/50912396/referring-to-a-member-as-a-variable-in-discord-py