Reputation: 85
I am making a discord bot that detects spam and deletes the message, it works like this:
@client.event
async def on_message(message):
global cont, msg
msg = 0
cont += 1
msg = message.author
the variable cont
counts every message and resets every 1 second, and to detect spam, I did this:
if cont > 6:
print(f'spam from {msg}')
cont -= 1
now to delete the message, I would need to delete the message, which is out of the async def
statement, so, I need to pass the variable, at first I tried to do this
var=message
but the problem is that when you make a new variable in discord.py, it is a int
, but for it to work, I need it to get it to the class discord.message.Message
, how can I do that?
Upvotes: 1
Views: 543
Reputation: 1207
you will have to store message each time when a user sends a message. and then match the new message with the old one. so create a list of users and their messages:
messages = {
users = [
]
}
and when a message is received, append to list:
@client.event
async def on_message(message):
user = message.user.id
msg = message.content
users = messages['users']:
for i in users:
if i['id'] = user:
i['msgs'].append(msg)
count = 1
for j in i['msgs']:
if j = msg:
count += 1
if count > 3:
message.author.send("you are spamming")
else:
config = {"id": user, "msgs": [msg]}
users.append(config)
I typed it directly here, so there maybe bugs, contribute to the answer to improve it.
another better way of handling spam is to use discord-anti-spam it's usage is pretty simple:
from discord.ext import commands
from AntiSpam import AntiSpamHandler
bot = commands.Bot(command_prefix="!")
bot.handler = AntiSpamHandler(bot)
@bot.event
async def on_ready():
print(f"-----\nLogged in as: {bot.user.name} : {bot.user.id}\n-----")
@bot.event
async def on_message(message):
bot.handler.propagate(message)
await bot.process_commands(message)
bot.run("Bot Token")
read it's documentation for more details on changing it's moderation level.
Upvotes: 1