如何防止机器人发送垃圾邮件?不和谐.py

Posted

技术标签:

【中文标题】如何防止机器人发送垃圾邮件?不和谐.py【英文标题】:How to prevent bot from spamming embeds? Discord.py 【发布时间】:2021-08-11 11:21:06 【问题描述】:

我有 discord bot,它会检查流媒体是否直播。而且我有一个功能可以防止它在有人活着时发送垃圾邮件:

if status is True:
                    async for message in channel.history(limit=2000):
                        if message.content == f"`Hey @everyone, twitch_name is live! Check it out:" + f"https://www.twitch.tv/twitch_name`":
                            break
                        else:
                            async for member in guild.fetch_members(limit=None):

                                if member.id == int(user_id):
                                    await member.add_roles(role)
                            
                            await channel.send(f"`Hey @everyone, twitch_name is live! Check it out:" + f"https://www.twitch.tv/twitch_name`")

                            print(f"user started streaming. Sending a notification.")
                            break

我想知道是否有办法对嵌入做同样的事情,但不知道该用什么。我虽然可以使用if embed = twitch_embed: break 而不是if message.content。 我想同时发送消息和嵌入,当有人像 mee6 一样每个流直播一次时:

我想在代码中结合消息和嵌入反垃圾邮件功能。请帮忙!如果您需要,我的所有代码都在这里:

import os
import json
import discord
import requests
from discord.ext import tasks, commands
from server import ping
from twitchAPI.twitch import Twitch
from discord.utils import get

intents = discord.Intents.all()
bot = commands.Bot(command_prefix='$', intents=intents)

# Authentication with Twitch API.
client_id = os.getenv('client_id')
client_secret = os.getenv('Dweller_token')
twitch = Twitch(client_id, client_secret)
twitch.authenticate_app([])
TWITCH_STREAM_API_ENDPOINT_V5 = "https://api.twitch.tv/kraken/streams/"
API_HEADERS = 
    'Client-ID': client_id,
    'Accept': 'application/vnd.twitchtv.v5+json',


user_info = twitch.get_users(logins=['turb4ik'])
user_id = user_info['data'][0]['id']

print(user_info)


# Returns true if online, false if not.
def checkuser(user):
    try:
        userid = twitch.get_users(logins=[user])['data'][0]['id']
        url = TWITCH_STREAM_API_ENDPOINT_V5.format(userid)
        try:
            req = requests.Session().get(url, headers=API_HEADERS)
            jsondata = req.json()
            if 'stream' in jsondata:
                if jsondata['stream'] is not None:
                    return True
                else:
                    return False
        except Exception as e:
            print("Error checking user: ", e)
            return False
    except IndexError:
        return False


# Executes when bot is started
@bot.event
async def on_ready():
    # Defines a loop that will run every 10 seconds (checks for live users every 10 seconds).
    @tasks.loop(seconds=10)
    async def live_notifs_loop():
        # Opens and reads the json file
        with open('streamers.json', 'r') as file:
            streamers = json.loads(file.read())
        # Makes sure the json isn't empty before continuing.
        if streamers is not None:
            # Gets the guild, 'twitch streams' channel, and streaming role.
            guild = bot.get_guild(690995360411156531)
            channel = bot.get_channel(785523710362124298)
            role = get(guild.roles, id=835581408272580649)
            # Loops through the json and gets the key,value which in this case is the user_id and twitch_name of
            # every item in the json.
            for user_id, twitch_name in streamers.items():
                print("checking" + " " + str(twitch_name))
                # Takes the given twitch_name and checks it using the checkuser function to see if they're live.
                # Returns either true or false.
                status = checkuser(twitch_name)
                # Gets the user using the collected user_id in the json
                user = bot.get_user(int(user_id))
                # Makes sure they're live
                if status is True:
                    # Checks to see if the live message has already been sent.
                    #limit = 0
                    #limit += 1
                    async for message in channel.history(limit=2000):
                        # If it has, break the loop (do nothing).
                        if message.content == f"`Hey @everyone, twitch_name is live! Check it out:" + f"https://www.twitch.tv/twitch_name`":
                            break
                        # If it hasn't, assign them the streaming role and send the message.
                        else:
                            # Gets all the members in your guild.
                            async for member in guild.fetch_members(limit=None):
                                # If one of the id's of the members in your guild matches the one from the json and
                                # they're live, give them the streaming role.
                                if member.id == int(user_id):
                                    await member.add_roles(role)
                            # Sends the live notification to the 'twitch streams' channel then breaks the loop.
                            '''twitch_embed = discord.Embed(
                                title=f":red_circle: **LIVE**\nuser.name is now streaming on Twitch!",
                                color=0xac1efb
                            )'''

                            #twitch_embed.add_field(name='**Game**', value='add value',inline=True)
                            #twitch_embed.add_field(name='**Viewers**', value='add value',inline=True)
                            #twitch_embed.set_image(url=f'\nhttps://www.twitch.tv/twitch_name')
                            
                            await channel.send(f"`Hey @everyone, twitch_name is live! Check it out:" + f"https://www.twitch.tv/twitch_name`")
                            #await channel.send(embed=twitch_embed)

                            print(f"user started streaming. Sending a notification.")
                            break
                # If they aren't live do this:
                else:
                    # Gets all the members in your guild.
                    async for member in guild.fetch_members(limit=None):
                        # If one of the id's of the members in your guild matches the one from the json and they're not
                        # live, remove the streaming role.
                        if member.id == int(user_id):
                            await member.remove_roles(role)
                    # Checks to see if the live notification was sent.
                    async for message in channel.history(limit=200):
                        # If it was, delete it.
                        if str(user.mention) in message.content and "is now streaming" in message.content:
                            await message.delete()
    # Start your loop.
    live_notifs_loop.start()


# Command to add Twitch usernames to the json.
@bot.command(name='addtwitch', help='Adds your Twitch to the live notifs.', pass_context=True)
@commands.has_permissions(administrator = True)
async def addtwitch(ctx, twitch_name):
    # Opens and reads the json file.
    with open('streamers.json', 'r') as file:
        streamers = json.loads(file.read())
    
    # Gets the users id that called the command.
    user_id = ctx.author.id
    # Assigns their given twitch_name to their discord id and adds it to the streamers.json.
    streamers[user_id] = twitch_name
    
    # Adds the changes we made to the json file.
    with open('streamers.json', 'w') as file:
        file.write(json.dumps(streamers))
    # Tells the user it worked.
    await ctx.send(f"Added twitch_name for ctx.author to the notifications list.")


ping()
bot.run(os.getenv('token'))

编辑: 如果有什么不对或者你不明白这个问题,请说出来,而不是直接关闭它。

【问题讨论】:

【参考方案1】:

要在同一条消息中发送嵌入,您可以使用 content 示例:

await channel.send(content=f"`Hey @everyone, twitch_name is live! Check it out:" + f"https://www.twitch.tv/twitch_name`", embed=twitch_embed)

您的检查功能不会发生变化,因为 message.content 将是相同的文本消息,只是带有嵌入。

您真的应该通过网络抓取或某些 API 来检查流是否已完成,而不是检查消息内容。如果直播在 3 小时前结束,但您只检查了 2 个直播者,除非您已经想到这一点,否则不会有任何变化。

【讨论】:

以上是关于如何防止机器人发送垃圾邮件?不和谐.py的主要内容,如果未能解决你的问题,请参考以下文章

如何改进反垃圾邮件功能 discord.py?

如何修复不和谐的 jda bot 垃圾邮件

我如何 DM 将直接消息放入公共频道而不发送垃圾邮件的机器人

如何删除垃圾邮件?

Discord.js - 如何在文本频道中发送垃圾邮件?

javascript 不和谐表情符号垃圾邮件发送者