首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >discord.py问题与Youtube-DL,现在正在工作。知道解决办法吗?

discord.py问题与Youtube-DL,现在正在工作。知道解决办法吗?
EN

Stack Overflow用户
提问于 2020-12-20 00:35:08
回答 1查看 844关注 0票数 1

我在python中编码了我的不和谐的bot,它不起作用,我使用大树苗作为主机托管我的bot。

误差

下面的错误是join命令。

代码语言:javascript
复制
Ignoring exception in command join:
Traceback (most recent call last):
File "/home/container/discord/ext/commands/bot.py", line 903, in invoke
await ctx.command.invoke(ctx)
File "/home/container/discord/ext/commands/core.py", line 851, in invoke
await self.prepare(ctx)
File "/home/container/discord/ext/commands/core.py", line 786, in prepare
await self._parse_arguments(ctx)
File "/home/container/discord/ext/commands/core.py", line 697, in _parse_arguments
transformed = await self.transform(ctx, param)
File "/home/container/discord/ext/commands/core.py", line 542, in transform
raise MissingRequiredArgument(param)
discord.ext.commands.errors.MissingRequiredArgument: ctx is a required argument that is missing.

下面的错误是play命令。

代码语言:javascript
复制
Ignoring exception in command play:
Traceback (most recent call last):
File "/home/container/discord/ext/commands/bot.py", line 903, in invoke
await ctx.command.invoke(ctx)
File "/home/container/discord/ext/commands/core.py", line 851, in invoke
await self.prepare(ctx)
File "/home/container/discord/ext/commands/core.py", line 786, in prepare
await self._parse_arguments(ctx)
File "/home/container/discord/ext/commands/core.py", line 706, in _parse_arguments
kwargs[name] = await self.transform(ctx, param)
File "/home/container/discord/ext/commands/core.py", line 542, in transform
raise MissingRequiredArgument(param)
discord.ext.commands.errors.MissingRequiredArgument: query is a required argument that is missing.

我的机器人代码是:

代码语言:javascript
复制
# Ami Bear - 2020

import asyncio
import requests
import math
import datetime
import json
import string
import time
import os
import os.path
import traceback
import discord
import youtube_dl
import random
import ffmpeg
from discord.ext import commands

client = commands.Bot(command_prefix = 'a/')
client.remove_command('help')

# Suppress noise about console usage from errors
youtube_dl.utils.bug_reports_message = lambda: ''

ytdl_format_options = {
    'format': 'bestaudio/best',
    'outtmpl': '%(extractor)s-%(id)s-%(title)s.%(ext)s',
    'restrictfilenames': True,
    'noplaylist': True,
    'nocheckcertificate': True,
    'ignoreerrors': False,
    'logtostderr': False,
    'quiet': True,
    'no_warnings': True,
    'default_search': 'auto',
    'source_address': '0.0.0.0' # bind to ipv4 since ipv6 addresses cause issues sometimes
}

ffmpeg_options = {
    'options': '-vn'
}

ytdl = youtube_dl.YoutubeDL(ytdl_format_options)


class YTDLSource(discord.PCMVolumeTransformer):
    def __init__(self, source, *, data, volume=0.5):
        super().__init__(source, volume)

        self.data = data

        self.title = data.get('title')
        self.url = data.get('url')

    @classmethod
    async def from_url(cls, url, *, loop=None, stream=False):
        loop = loop or asyncio.get_event_loop()
        data = await loop.run_in_executor(None, lambda: ytdl.extract_info(url, download=not stream))

        if 'entries' in data:
            # take first item from a playlist
            data = data['entries'][0]

        filename = data['url'] if stream else ytdl.prepare_filename(data)
        return cls(discord.FFmpegPCMAudio(filename, **ffmpeg_options), data=data)


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

    @client.command()
    async def join(self, ctx, *, channel: discord.VoiceChannel):
        """Joins a voice channel"""

        if ctx.voice_client is not None:
            return await ctx.voice_client.move_to(channel)

        await channel.connect()

    @client.command()
    async def play(self, ctx, *, query):
        """Plays a file from the local filesystem"""

        source = discord.PCMVolumeTransformer(discord.FFmpegPCMAudio(query))
        ctx.voice_client.play(source, after=lambda e: print('Player error: %s' % e) if e else None)

        await ctx.send('Now playing: {}'.format(query))

    @client.command()
    async def yt(self, ctx, *, url):
        """Plays from a url (almost anything youtube_dl supports)"""

        async with ctx.typing():
            player = await YTDLSource.from_url(url, loop=self.bot.loop)
            ctx.voice_client.play(player, after=lambda e: print('Player error: %s' % e) if e else None)

        await ctx.send('Now playing: {}'.format(player.title))

    @client.command()
    async def stream(self, ctx, *, url):
        """Streams from a url (same as yt, but doesn't predownload)"""

        async with ctx.typing():
            player = await YTDLSource.from_url(url, loop=self.bot.loop, stream=True)
            ctx.voice_client.play(player, after=lambda e: print('Player error: %s' % e) if e else None)

        await ctx.send('Now playing: {}'.format(player.title))

    @client.command()
    async def volume(self, ctx, volume: int):
        """Changes the player's volume"""

        if ctx.voice_client is None:
            return await ctx.send("Not connected to a voice channel.")

        ctx.voice_client.source.volume = volume / 100
        await ctx.send("Changed volume to {}%".format(volume))

    @client.command()
    async def stop(self, ctx):
        """Stops and disconnects the bot from voice"""

        await ctx.voice_client.disconnect()

    @play.before_invoke
    @yt.before_invoke
    @stream.before_invoke
    async def ensure_voice(self, ctx):
        if ctx.voice_client is None:
            if ctx.author.voice:
                await ctx.author.voice.channel.connect()
            else:
                await ctx.send("You are not connected to a voice channel.")
                raise commands.CommandError("Author not connected to a voice channel.")
        elif ctx.voice_client.is_playing():
            ctx.voice_client.stop()


@client.command()
async def anime(ctx):
    embed=discord.Embed(title="Fun - Animo", description="Fun Commands for Animo", colour=0x63FFDD)
    embed.add_field(name="Naruto", value="a/naruto (Broken)")
    embed.add_field(name="Fruits Basket", value="a/fr (Broken)")
    embed.add_field(name="Pokemon", value="a/pokemon")
    await ctx.send(embed=embed)
    
@client.command()
async def naruto(ctx):
    choices = ["https://occ-0-2794-2219.1.nflxso.net/dnm/api/v6/E8vDc_W8CLv7-yMQu8KMEC7Rrr8/AAAABYQp33Z3D9uGJK0IZsYfvENQpSz4zoSrjb8v5CCl4UTiFDe7Z_yovhieDFhJtGm2Rh4LoleJfHwHdyRDMtezwqojkDXH.jpg?r=77f", "https://i.kym-cdn.com/entries/icons/facebook/000/015/163/narutoooh.jpg", "https://pyxis.nymag.com/v1/imgs/76f/5a1/f1a0e3c7158a1f63046196b0f1048d9d69-22-naruto-run.rsocial.w1200.jpg"]
    embed=discord.Embed(title="Naruto", description="Awoooooooo", colour=0x63FFDD)
    embed.add_field(name="Here is you Naruto Image", value=":D")
    embed.set_image(url=random.choices(choices))
    await ctx.send(embed=embed)
    
@client.command()
async def fr(ctx):
    choices = ["https://cdn.vox-cdn.com/thumbor/wR_hrZicIIBA2zuN_HBtxdjPRsA=/0x0:724x1024/1200x800/filters:focal(331x321:445x435)/cdn.vox-cdn.com/uploads/chorus_image/image/62358424/Fruits_Basket_protagonists_with_credit_embargo_till_00h00m_20_Nov_2018_JST_1_724x1024.0.png", "https://cdn.episode.ninja/file/episodeninja/7847806.jpg", "https://news.otakukart.com/wp-content/uploads/2019/07/Fruits-Basket-2019-Episode-16-1.jpg"]
    embed=discord.Embed(title="Fruits Basket", description="Awoooooooo", colour=0x63FFDD)
    embed.add_field(name="Here is you Fruits Basket Image", value=":D")
    embed.set_image(url=random.choices(choices))
    await ctx.send(embed=embed)
    
@client.command(pass_context = True)
async def mute(ctx, member: discord.Member):
     if ctx.message.author.server_permissions.administrator:
        role = discord.utils.get(member.server.roles, name='Muted')
        await ctx.add_roles(member, role)
        embed=discord.Embed(title="User Muted!", description="**{0}** was muted by **{1}**!".format(member, ctx.message.author), color=0x00FF00)
        await ctx.send(embed=embed)
     else:
        embed=discord.Embed(title="Permission Denied.", description="You don't have permission to use this command.", color=0xFF0000)
        await ctx.send(embed=embed)
        
@client.command(pass_context = True)
async def unmute(ctx, member: discord.Member):
     if ctx.message.author.server_permissions.administrator:
        role = discord.utils.get(member.server.roles, name='Muted')
        await ctx.remove_roles(member, role)
        embed=discord.Embed(title="User un-muted!", description="**{0}** was un-muted by **{1}**!".format(member, ctx.message.author), colour=0x00FF00)
        await ctx.send(embed=embed)
     else:
        embed=discord.Embed(title="Permission Denied.", description="You don't have permission to use this command.", color=0xFF0000)
        await ctx.send(embed=embed)        

@client.command()
async def help(ctx):
    embed=discord.Embed(title="Help - Animo", description="Help Commands for Animo", colour=0x63FFDD)
    embed.add_field(name="Fun", value="a/fun")
    embed.add_field(name="Moderation", value="a/moderation **OR** a/mod")
    embed.add_field(name="Utility", value="a/utility **OR** a/util")
    embed.add_field(name="Image", value="a/image")
    embed.add_field(name="Anime", value="a/anime")
    await ctx.send(embed=embed)
    
@client.command()
async def fun(ctx):
    embed=discord.Embed(title="Fun - Animo", description="Fun Commands for Animo", colour=0x63FFDD)
    embed.add_field(name="Rock, Paper, Scissors", value="a/rps [r, p, s]")
    embed.add_field(name="Meme", value="a/meme")
    embed.add_field(name="Pun", value="a/pun")
    await ctx.send(embed=embed)
    
@client.command()
async def mod(ctx):
    embed=discord.Embed(title="Moderation - Animo", description="Moderation Commands for Animo", colour=0x63FFDD)
    embed.add_field(name="Ban", value="a/ban [User]")
    embed.add_field(name="Kick", value="a/kick [User]")
    embed.add_field(name="Mute", value="a/mute [User]")
    embed.add_field(name="Un-Mute", value="a/unmute [User]")
    embed.add_field(name="Purge", value="a/purge [1-100]")
    await ctx.send(embed=embed)
    
@client.command()
async def moderation(ctx):
    embed=discord.Embed(title="Moderation - Animo", description="Moderation Commands for Animo", colour=0x63FFDD)
    embed.add_field(name="Ban", value="a/ban [User]")
    embed.add_field(name="Kick", value="a/kick [User]")
    embed.add_field(name="Mute", value="a/mute [User]")
    embed.add_field(name="Un-Mute", value="a/unmute [User]")
    embed.add_field(name="Purge", value="a/purge [1-100]")
    await ctx.send(embed=embed)
    
@client.command()
async def util(ctx):
    embed=discord.Embed(title="Utility - Animo", description="Utility Commands for Animo", colour=0x63FFDD)
    embed.add_field(name="Bot/Server Owner", value="a/owner [bot, server *]")
    embed.add_field(name="Coin Flip", value="a/coinflip")
    embed.add_field(name="Ping", value="a/ping")
    embed.add_field(name="Support", value="a/Support")
    await ctx.send(embed=embed)
    
@client.command()
async def image(ctx):
    embed=discord.Embed(title="Image - Animo", description="Image Commands for Animo", colour=0x63FFDD)
    embed.add_field(name="Cat", value="a/cats")
    embed.add_field(name="Red Panda", value="a/redpanda")
    await ctx.send(embed=embed)

@client.command()
async def utility(ctx):
    embed=discord.Embed(title="Utility - Animo", description="Utility Commands for Animo", colour=0x63FFDD)
    embed.add_field(name="Bot/Server Owner", value="a/owner [bot, server *]")
    embed.add_field(name="Coin Flip", value="a/coinflip")
    embed.add_field(name="Ping", value="a/ping")
    embed.add_field(name="Support", value="a/Support")
    await ctx.send(embed=embed)


@client.group()
async def rps(ctx):
    if ctx.invoked_subcommand is None:
        await ctx.send('Please state what you want to use. E.g. `a/rps rock`')

@rps.command()
async def r(ctx):
    choices = ["I use Rock, it's a draw!", "I use Paper, I win!", "I use scissors, you win!"]
    await ctx.send(random.choice(choices))
    
@rps.command()
async def p(ctx):
    choices = ["I use Rock, you win!", "I use Paper, it's a draw!", "I use scissors, I win!"]
    await ctx.send(random.choice(choices))
    
@rps.command()
async def s(ctx):
    choices = ["I use Rock, I win!", "I use Paper, you win!", "I use Scissors, it's a draw!"]
    await ctx.send (random.choice(choices))


@client.group()
async def owner(ctx):
        if ctx.invoked_subcommand is None:
            await ctx.send("Please retry this command with `bot` or `server (temp not working)` at the end of the command (e.g. `b>owner bot`)")
    
    
@owner.command()
async def bot(ctx):
    await ctx.send("Ami Bear#3455")

@owner.command()
async def server(ctx):
    await ctx.send(ctx.guild.owner.name)

@client.event
async def on_ready():
    number_of_servers = len(client.guilds)
    await client.change_presence(activity=discord.Activity(type=discord.ActivityType.listening, name='to a/help, Watching {} servers'.format(number_of_servers)))
    
@client.command(pass_context=True)
async def status(ctx, *, message): #Changing the playing status of bot with a command
    if str(ctx.message.author.id) == '722716320549961789': #Only the bot owner can use this command
        if message == "servers": # Use the '!status servers' command to set the playing status back to number of servers the bot is on.
            number_of_servers = len(client.guilds)
            await client.change_presence(activity=discord.Activity(type=discord.ActivityType.listening, name='a/help, Watching {} servers'.format(number_of_servers)))
        elif message == "members":
            guild_members = len(set(client.get_all_members()))
            await client.change_presence(activity=discord.Activity(type=discord.ActivityType.listening, name='over {} users'.format(guild_members)))
        else:
            await client.change_presence(activity=discord.Activity(type=discord.ActivityType.listening, name='{}'.format(message)))
    else:
        userID = ctx.message.author.id
        await ctx.send("<@%s>: ⛔️ | Bot owner only!" % (userID))
        



@client.command(pass_context=True)
async def ping(ctx):
    #await bot.edit_message(pinger, 'ℹ️ | **Pong!** ``' + ping + 'ms``') # you can edit this to say whatever you want really. Hope this helps.
    embed = discord.Embed(colour=discord.Colour(0x989898))

    embed.add_field(name="Animo Ping", value="Ping: **{0}ms** ".format(round(client.latency, 1)))
    await ctx.send(embed=embed)
    

# Kick:
@client.command()
@commands.has_permissions(kick_members=True)
async def kick(ctx, member : discord.Member, *, reason=None):
    await member.kick(reason=reason)

# Ban:
@client.command()
@commands.has_permissions(ban_members=True)
async def ban(ctx, member : discord.Member, *, reason=None):
    await member.ban(reason=reason)

# Purge:
@client.command()
@commands.has_permissions(manage_messages=True)
async def purge(ctx, amount=100):
    await ctx.channel.purge(limit=amount)        
        
@client.command()
async def pokemon(ctx):
    choices = ["https://compote.slate.com/images/18ba92e4-e39b-44a3-af3b-88f735703fa7.png?width=780&height=520&rect=1560x1040&offset=0x0", "https://oyster.ignimgs.com/mediawiki/apis.ign.com/pokemon-switch/e/ea/Grookey.jpg"]
    embed = discord.Embed(
        colour = discord.Colour.blue())
    embed.set_author(name='Here is your Pokémon image!')
    embed.set_image(url=random.choice(choices))
    await ctx.send(embed=embed)


@client.event
async def on_member_join(member):
    print(f'{member} has joined a server')

@client.event
async def on_member_remove(member):
    print(f'{member} has left the server.')

    
@client.command()
async def meme(ctx):
    choices = ["https://cdn.discordapp.com/attachments/753022422122364991/753804091444166746/o.jpg", "https://everything-pr.com/wp-content/uploads/2010/08/Funny-Meme.jpg", "https://sayingimages.com/wp-content/uploads/but-i-dont-want-internet-memes.jpg"]
    await ctx.send(random.choice(choices))


@client.command()
async def support(ctx):
    await ctx.send(f'https://discord.gg/QhS3MzbPC6')


@client.command(pass_context=True)
async def cats(ctx):
    facts = ["A house cat’s genome is 95.6 percent tiger, and they share many behaviors with their jungle ancestors. These behaviors include scent marking by scratching, prey play, prey stalking, pouncing, chinning, and urine marking.", "Cats can jump up to six times their length.", "Cats have 230 bones, while humans only have 206."]
    choices = ["https://ichef.bbci.co.uk/news/976/cpsprodpb/12A9B/production/_111434467_gettyimages-1143489763.jpg", "https://img.webmd.com/dtmcms/live/webmd/consumer_assets/site_images/article_thumbnails/other/cat_relaxing_on_patio_other/1800x1200_cat_relaxing_on_patio_other.jpg", "https://img.webmd.com/dtmcms/live/webmd/consumer_assets/site_images/article_thumbnails/reference_guide/outdoor_cat_risks_ref_guide/1800x1200_outdoor_cat_risks_ref_guide.jpg", "https://www.cardinia.vic.gov.au/images/cats_sml.jpg", "https://encrypted-tbn0.gstatic.com/images?q=tbn%3AANd9GcRUeB4aArDOntl48L6LFkyWtIf4nhH0YGYqmg&usqp=CAU", "https://encrypted-tbn0.gstatic.com/images?q=tbn%3AANd9GcT6fH4WcqPLntpPILC1Ag-_D7dkrljytz9iNg&usqp=CAU"]
    embed = discord.Embed(
        colour = discord.Colour.purple())
    embed.set_author(name=f"Here is your cat. Also, why not enjoy a cat fact: " + random.choice(facts) + " :D")
    embed.set_image(url=random.choice(choices))
    await ctx.send(embed=embed)

@client.command()
async def pun(ctx):
    choices = ["You can tune a guitar, but you can't tuna fish. Unless, of course, you play bass.", "Time flies like an arrow. Fruit flies like a banana.", "Hanging is too good for a man who makes puns; he should be drawn and quoted.", "I saw a documentary on how ships are kept together. Riveting!", "I Renamed my iPod The Titanic, so when I plug it in, it says “The Titanic is syncing.”", "I was wondering why the ball was getting bigger. Then it hit me", "Two windmills are standing in a wind farm. One asks, “What’s your favorite kind of music?” The other says, “I’m a big metal fan.”"]
    await ctx.send(random.choice(choices))

@client.command()
async def coinflip(ctx):
    choices = ["It is... Heads!", "It is... Tails!"]
    await ctx.send(random.choice(choices))

@client.command(pass_context=True)
async def redpanda(ctx):
    choices = ["https://cdn.vox-cdn.com/thumbor/1mxkqqttp-h6NTQ9fF6wbcXMcdg=/12x0:4907x3263/1400x1050/filters:focal(12x0:4907x3263):format(jpeg)/cdn.vox-cdn.com/uploads/chorus_image/image/49388585/16071828377_85109fdee4_o.0.0.jpg", "https://static.scientificamerican.com/blogs/cache/file/8DB2EE5F-C195-4F57-9080554453E3E3C8.jpg", "https://www.nationalgeographic.com/content/dam/animals/thumbs/rights-exempt/mammals/r/red-panda_thumb.ngsversion.1485895956258.adapt.1900.1.JPG", "https://encrypted-tbn0.gstatic.com/images?q=tbn%3AANd9GcThuWBqK4bsJVLgyjeCGLEBn1rOtb6boxDPpQ&usqp=CAU", "https://encrypted-tbn0.gstatic.com/images?q=tbn%3AANd9GcSZAzAxVvW6_XWSPs7mkXIoiai53LGbEUpxJw&usqp=CAU", "https://img.huffingtonpost.com/asset/5cd3b3ab2100003000d403ac.jpeg?ops=1778_1000"]
    embed = discord.Embed(
        colour = discord.Colour.purple())
    embed.set_author(name='Here is your Red Panda!')
    embed.set_image(url=random.choice(choices))
    await ctx.send(embed=embed)


client.run('token')

我正在使用Python3.8.5和PIP 20.3。如果你能帮忙的话,请帮我!

EN

回答 1

Stack Overflow用户

发布于 2021-01-05 00:14:38

您的cog命令需要使用@commands.command而不是@client.command

示例:

代码语言:javascript
复制
@client.command()
async def join(self, ctx, *, channel: discord.VoiceChannel):
        """Joins a voice channel"""

        if ctx.voice_client is not None:
            return await ctx.voice_client.move_to(channel)

        await channel.connect()

应:

代码语言:javascript
复制
@commands.command() # This changed...
async def join(self, ctx, *, channel: discord.VoiceChannel):
        """Joins a voice channel"""

        if ctx.voice_client is not None:
            return await ctx.voice_client.move_to(channel)

        await channel.connect()

记住,只在齿轮上这样做!

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65375887

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档