【问题标题】:Is there a way to detect a link in a message? (or can someone help me with my code)有没有办法检测消息中的链接? (或者有人可以帮我写代码)
【发布时间】:2021-08-22 10:33:56
【问题描述】:

嘿,我目前正在开发一个 NSFW 检测不和谐机器人。但是现在我被困住了,我知道如何扫描附件,但是我的链接检测有问题我希望如果消息没有以image_types 中的参数结尾,机器人不会发送 api 请求。但是 atm 机器人会为某人发送的每条消息发送一个 api 请求。我希望你们能理解我的意思并能帮助我。

import discord
from discord.ext import commands
import requests
import os


class NSFW(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

    @commands.Cog.listener()
    async def on_message(self, message: discord.Message):
        
        image_types = ["png", "jpeg", "jpg", "jfif", "tiff",
                       "nef", "ai", "orf", "indd", "eps", "cr2", "psd"]
        for type in image_types:
            if message.channel.is_nsfw():
                return
            elif any(type.endswith(image) for image in image_types):
                r = requests.post(
                    "https://api.deepai.org/api/nsfw-detector",
                    data={
                        'image': f'{message.content}',
                    },
                    headers={'api-key': os.environ["DEEPAPI-KEY"]}
                )

                nsfw = r.json()
                nsfw_score = nsfw['output']['nsfw_score']
                print(nsfw)
                print(nsfw_score)
                if nsfw_score >= 0.80:
                        await message.delete()
                        await message.channel.send(
                            f"{message.author.mention} This image is to {nsfw_score:,.2f}% nsfw (0.1=10%)")
                        db["count"] = db["count"] + 1
                else:
                    return
            else:
                return


def setup(bot):
    bot.add_cog(NSFW(bot))

【问题讨论】:

    标签: python api request discord discord.py


    【解决方案1】:

    看起来只是一个简单的编码错误;)

    您正在迭代 image_types(用于 image_types 中的类型),然后将其与 any(type.endswith(image) 用于 image_types 中的图像)中的相同值进行比较。

    这就是它总是返回 true 的原因。

    【讨论】:

    • 顺便说一句,我建议你重命名 image_type 中的类型或类似的东西,因为 type 是 python 内置的,并且命名变量与内置相同通常被认为是一种不好的做法 ;)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多