首页 > 解决方案 > 将消息变量从 discord.py 中的 async def 中传递出去

问题描述

我正在制作一个检测垃圾邮件并删除邮件的不和谐机器人,它的工作原理如下:

@client.event
async def on_message(message):
    global cont, msg
    msg = 0
    cont += 1
    msg = message.author

该变量cont计算每条消息并每 1 秒重置一次,为了检测垃圾邮件,我这样做了:

if cont > 6:
    print(f'spam from {msg}')
    cont -= 1

现在要删除消息,我需要删除async def语句之外的消息,所以,我需要传递变量,起初我尝试这样做

var=message

但问题是,当您在 discord.py 中创建一个新变量时,它是一个int,但要让它工作,我需要它才能将它带到课堂discord.message.Message上,我该怎么做?

标签: pythondiscorddiscord.py

解决方案


每次用户发送消息时,您都必须存储消息。然后将新消息与旧消息匹配。所以创建一个用户列表和他们的消息:

messages = {
    users = [
    ]
}

当收到消息时,追加到列表:

@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)

我直接在这里输入,所以可能有错误,有助于改进它的答案。

处理垃圾邮件的另一种更好的方法是使用discord-anti-spam ,它的用法非常简单:

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")

阅读它的文档以获取有关更改其审核级别的更多详细信息。


推荐阅读