如何在流媒体直播时发送消息和嵌入? |错误 | Discord.py

问题描述

我已经编写了代码来检查 Twitch 流媒体是否是生命,如果是,则发送消息,但我找不到检查生命通知(消息和嵌入)是否已发送的方法。所以我尝试了不同的检查嵌入标题方法if discord.Embed(title=f":red_circle: **LIVE**\n{user.name} is Now streaming on Twitch! \n \n {stream_data['data'][0]['title']}") == embed:if discord.Embed(title=f":red_circle: **LIVE**\n{user.name} is Now streaming on Twitch! \n \n {stream_data['data'][0]['title']}"):。但在第一种情况下,bot 是垃圾邮件,在第二种情况下,bot 不会激活 else 语句(我需要发送通知),所以我收到了垃圾邮件,或者 bot 根本不发送任何内容。请帮助我:我需要平衡,当流媒体直播时发送一个通知然后break(然后只检查必须防止机器人发送垃圾邮件的语句。这是代码。我建议您查看第 74 行和119. 特别是第 99 行的 if 语句。

import os
import json
import discord
import requests
from discord.ext import tasks,commands
from discord.utils import get
from server import ping
from Time import mytimemy

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

TOKEN = os.getenv('token')

# Authentication with Twitch API.
client_id = os.getenv('client_id')
client_secret = os.getenv('Dweller_token')
body = {
    'client_id': client_id,'client_secret': client_secret,"grant_type": 'client_credentials'
}
r = requests.post('https://id.twitch.tv/oauth2/token',body)
keys = r.json()
headers = {
    'Client-ID': client_id,'Authorization': 'Bearer ' + keys['access_token']
}

'''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(streamer_name):
    stream = requests.get('https://api.twitch.tv/helix/streams?user_login=' + streamer_name,headers=headers)
    stream_data = stream.json()

    if len(stream_data['data']) == 1:
        return True,stream_data
    else:
        return False,stream_data


# 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():
        # username = stream_data['data'][0]['user_name']
        # stream_title = stream_data['data'][0]['title']
        # game_being_played = stream_data['data'][0]['game_name']

        # 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) + " Current time: " + str(mytimemy()))
                # Takes the given twitch_name and checks it using the checkuser function to see if they're live.
                # Returns either true or false.
                status,stream_data = 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.
                  async for message in channel.history(limit=200):
                      twitch_embed = discord.Embed(
                                title=f":red_circle: **LIVE**\n{user.name} is Now streaming on Twitch! \n \n {stream_data['data'][0]['title']}",color=0xac1efb,url=f'\nhttps://www.twitch.tv/{twitch_name}'
                          )
                      twitch_embed.add_field(
                            name = '**Game**',value = stream_data['data'][0]['game_name'],inline = True
                          )
                      twitch_embed.add_field(
                            name = '**Viewers**',value = stream_data['data'][0]['viewer_count'],inline = True
                          )
                      twitch_embed.set_author(
                              name = str(twitch_name),icon_url = stream_data['data'][0]['thumbnail_url']
                                                          )
                      twitch_embed.set_image(url = f'https://www.twitch.tv/{twitch_name}')
                      embeds = message.embeds
                      for embed in embeds:
                        if discord.Embed(title=f":red_circle: **LIVE**\n{user.name} is Now streaming on Twitch! \n \n {stream_data['data'][0]['title']}") == embed:
                          try:
                              embed_title = twitch_embed.title
                              embed_description = twitch_embed.description
                          except Exception as e:
                              break
                          print(f"Already sent for {user.name} at {mytimemy()}!") #just sending the time and name
                          break

                        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.
                          await channel.send(
                              content = f"hey @everyone! {user.name} is Now streaming on Twitch! Go check it out: https://www.twitch.tv/{twitch_name}",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):
                        try:
                            embed_title = message.embeds[0].title
                            embed_description = message.embeds[0].description
                        except Exception as e:
                            break
                        # If it was,delete it.
                        if str(user.name) in embed_title and "is Now streaming" in embed_title:
                            print(f"{user} stopped streaming. Removing the notification.")
                            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)
async def add_twitch(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()

print('Server Running')
bot.run(TOKEN)

很难解释和理解,但请帮助我。我需要在有人流式传输时检查嵌入内容,因此每个流发送一次嵌入和消息并且没有垃圾邮件。当流结束时忘记嵌入内容,因此下次也可以发送嵌入内容。如果您有什么不明白的地方,请询问。我的不和谐以防万一:Dweller_Igor#3291。请有人编辑问题,如果它有助于您更好地理解它。

最小可重复示例(嵌入、if 语句和 else 语句):

if status is True:
                    # Checks to see if the live message has already been sent.
                  async for message in channel.history(limit=200):
                      twitch_embed = discord.Embed(
                                title=f":red_circle: **LIVE**\n{user.name} is Now streaming on Twitch! \n \n {stream_data['data'][0]['title']}",embed=twitch_embed)
                          print(f"{user} started streaming. Sending a notification.")
                          break

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)