【问题标题】:Discord Bot, how do I take this code and try to make it work in videos links as well?Discord Bot, how do I take this code and try to make it work in videos links as well?
【发布时间】:2022-12-26 17:06:25
【问题描述】:

My Issue

The code at the bottom works perfectly but it only works with channels. I understand why it's not working but I can't find the right values for the yson decoding.

The code directly below this paragraph is the code that needs changing a bit I think.


                        
                        # Finds channel information #
                        channel_id   = json_data["header"]["c4TabbedHeaderRenderer"]["channelId"]
                        channel_name = json_data["header"]["c4TabbedHeaderRenderer"]["title"]
                        channel_logo = json_data["header"]["c4TabbedHeaderRenderer"]["avatar"]["thumbnails"][2]["url"]
                        channel_id_link = "https://www.youtube.com/channel/"+channel_id
                        # Prints Channel information to console #

What I've done

However I have tried to follow the JSON formatting of a video link and filled in the headers with ["subscribeButton"], ["subscribeButtonRenderer"] and ["channelId"] for example but it still comes back with this error.

Error

  File "c:\Users\tom87\test\youtube video.py", line 63, in on_message
    channel_id   = json_data["subscribeButton"]["subscribeButtonRenderer"]["channelId"]
                   ~~~~~~~~~^^^^^^^^^^^^^^^^^^^

Does anyone have any idea what entries would I use to have this work? Please keep in mind this is my first every script to the code is terrible. Thank you for your help

JSON File

Here is the json code that I'm using to find what I need. https://pastebin.com/XmSy4SP3

Code

import re
from re import search
from urllib.request import urlopen
from bs4 import BeautifulSoup
import requests
import re
import json
import base64
import os
import webbrowser
import pyperclip
import win32com.client as comclt
import time
import pyautogui
from configparser import ConfigParser
import discord

intents = discord.Intents.all()
client = discord.Client(command_prefix='/', intents=intents)


# Creates or checks for config
if os.path.exists(os.getcwd() + "/config.json"):
    with open("./config.json") as f:
        configData = json.load(f) 
else:
    print("Please enter your token and the channel ID of the Discord channel you'd like to use.")
    print("If left blank, you'll need to go to the config.json to set them.")
    token = str(input("Bot Token: ") or "token goes here...")
    discordChannel = str(input("Channel ID:  ") or "000000000000000000")
    configTemplate = {"Token": (token), "Prefix": "!","discordChannel": (discordChannel)}
    print("The script will now crash and show an error. Run 'python QualityYouTube.py' again.")
    with open(os.getcwd() + "/config.json", "w+") as f:
        json.dump(configTemplate, f) 
token = configData["Token"]
prefix = configData["Prefix"]
discordChannel = configData["discordChannel"]
# Boots up the bot 
@client.event
async def on_ready():
    print('We have logged in as {0.user}'.format(client))
# Bot is checking messages
@client.event
async def on_message(message):
    if message.author == client.user:
       return    
    if re.search("http", message.content):
        print (message.content)
        channelURL = message.content
        print(channelURL)
        discordChannelInt = int(discordChannel)
        if (discordChannelInt == message.channel.id):
            if re.search("http", channelURL):
                if re.search("://", channelURL):
                    if re.search("youtu", channelURL):
                        
                        await message.delete()
                        soup = BeautifulSoup(requests.get(channelURL, cookies={'CONSENT': 'YES+1'}).text, "html.parser")
                        data = re.search(r"var ytInitialData = ({.*});", str(soup.prettify())).group(1)
                        json_data = json.loads(data)
                        
                        # Finds channel information #
                        channel_id   = json_data["header"]["c4TabbedHeaderRenderer"]["channelId"]
                        channel_name = json_data["header"]["c4TabbedHeaderRenderer"]["title"]
                        channel_logo = json_data["header"]["c4TabbedHeaderRenderer"]["avatar"]["thumbnails"][2]["url"]
                        channel_id_link = "https://www.youtube.com/channel/"+channel_id
                        # Prints Channel information to console #
                        print("Channel ID: "+channel_id)
                        print("Channel Name: "+channel_name)
                        print("Channel Logo: "+channel_logo)
                        print("Channel ID: "+channel_id_link)
                        author = message.author
                        #Messages
                        Message_1 = channel_name+" was posted by "+(author.mention)+"(now.shifttime(""))"+""
                        timeOutMessage10 = " This message will be deleted in 10 seounds."
                        timeOutMessage60 = " This message will be deleted in 60 seounds."
                        noURL = " This does not contain a URL."
                        invalidURL = " This URL is not supported. Please enter a valid URL."
                        notChannel =  """Make sure the channel follows one of the following formats starting with http or https. 
                        \r - http:://youtube.com/user/username
                        \r - http://youtube.com/channel/username
                        \r - http://youtube.com/@username\r\r
                        ***We hope to add video support soon***"""
                        num60 = 60
                        num10 = 10
                        
                        
                        
                        await message.channel.send(channel_name+" - "+channel_id_link)
                    elif message.content.endswith('.com/'):
                        await message.channel.send(author.mention+notChannel+timeOutMessage60, delete_after=num60)
                    elif not message.content.includes('channel') or message.content('user') or message.content('@'):
                        author = message.author
                        await message.channel.send(author.mention+invalidURL+timeOutMessage60, delete_after=num60)
                    elif message.content.excludes('.com') or message.content.excludes('wwww') or message.content.excludes(''):
                        author = message.author
                        await message.channel.send(author.mention+noURL+timeOutMessage10, delete_after=num10)
            else:
                
                print("incorrect channel")
                

    

client.run(token)

What I've done

However I have tried to follow the JSON formatting of a video link and filled in the headers with ["subscribeButton"], ["subscribeButtonRenderer"] and ["channelId"] for example but it still comes back with this error.

Error

  File "c:\Users\tom87\test\youtube video.py", line 63, in on_message
    channel_id   = json_data["subscribeButton"]["subscribeButtonRenderer"]["channelId"]

What I was expected

I was expecting it to feed back the channelid to the script.

【问题讨论】:

    标签: python beautifulsoup discord discord.py


    【解决方案1】:

    To get the channel ID of a youtube video, use the owner key in the json data. For example:

    channel_id = json_data["header"]["c4TabbedHeaderRenderer"]["owner"]["channelId"]
    

    This should work. If the "owner" key is incorrect, you can try getting the entire json data and checking which key refers to the channel ID.

    【讨论】:

      【解决方案2】:

      I resolved the issue by adding pytube support. You can see how I did it here.

      https://github.com/flyinggoatman/YouTube-Link-Extractor

      I imported the module called Pytube which allows me to extract information from videos and channel pages.

      This is the code I implemented to find the information I wanted..

      YTV = YouTube(channelURL)
      channel_id = YTV.channel_id
      channel_id_link = YTV.channel_url
      
      c = Channel(channel_id_link)
      channel_name = c.channel_name
                      
      print("Channel ID: "+channel_id)
      print("Channel Name: "+channel_name)
      print("Channel ID: "+channel_id_link)
      

      I followed this tutorial for understanding the code https://youtu.be/p2IKvHnzyS8

      【讨论】:

        猜你喜欢
        • 2022-12-19
        • 2022-01-04
        • 2022-08-17
        • 2022-12-02
        • 1970-01-01
        • 2022-12-27
        • 1970-01-01
        • 2022-12-01
        • 2022-12-02
        相关资源
        最近更新 更多