首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >生成队列命令的Discord.py

生成队列命令的Discord.py
EN

Stack Overflow用户
提问于 2020-12-25 20:13:26
回答 1查看 516关注 0票数 1

我正在制作一个discord.py音乐机器人(我的第一个),我想知道如何排队。我猜想这与asyncio命令(import asyncio)有关,但我真的不知道。

代码语言:javascript
复制
from discord.ext import commands
from discord.utils import get
import asyncio
import youtube_dl
import os

bot = commands.Bot(command_prefix='>')
bot.remove_command('help')

@bot.event
async def on_ready():
    await bot.change_presence(activity=discord.Activity(type=discord.ActivityType.listening, name=">help"))
    print("Bot is online! Logged in as: " + bot.user.name + "\n")

@bot.command(pass_context=True)
async def ping(ctx):
    await ctx.send(f'**Pong!** Latency: {round(bot.latency * 1000)}ms')

@bot.command(pass_context=True, aliases=['j'])
async def join(ctx):
    channel = ctx.message.author.voice.channel
    voice = get(bot.voice_clients, guild=ctx.guild)

    if voice and voice.is_connected():
        await voice.move_to(channel)
    else:
        voice = await channel.connect()

    await voice.disconnect()

    if voice and voice.is_connected():
        await voice.move_to(channel)
    else:
        voice = await channel.connect()


@bot.command(pass_context=True, aliases=['l'])
async def leave(ctx):
    channel = ctx.message.author.voice.channel
    voice = get(bot.voice_clients, guild=ctx.guild)

    if voice and voice.is_connected():
        await voice.disconnect()
    else:
        print("Bot was told to leave voice channel, but was not in one.")
        await ctx.send("OneBeat is not connected to a voice channel. Connect OneBeat to a voice channel before using this command.")


@bot.command(pass_context=True, aliases=['p'])
async def play(ctx, url: str):
    channel = ctx.message.author.voice.channel
    voice = get(bot.voice_clients, guild=ctx.guild)

    if voice and voice.is_connected():
        await voice.move_to(channel)
    else:
        voice = await channel.connect()

    await voice.disconnect()

    if voice and voice.is_connected():
        await voice.move_to(channel)
    else:
        voice = await channel.connect()

    song_there = os.path.isfile("song.mp3")
    try:
        if song_there:
            os.remove("song.mp3")
            print("Removed old song file.")
    except PermissionError:
        print("Trying to delete song file, but it's being played")
        await ctx.send("Error: Music is already playing (Queue feature coming soon).")
        return
    await ctx.send("One second...")

    voice = get(bot.voice_clients, guild=ctx.guild)

    ydl_opts = {
        'format': 'bestaudio/best',
        'postprocessors': [{
            'key': 'FFmpegExtractAudio',
            'preferredcodec': 'mp3',
            'preferredquality': '192',
        }],
    }

    with youtube_dl.YoutubeDL(ydl_opts) as ydl:
        print("Downloading audio now\n")
        ydl.download([url])

    for file in os.listdir("./"):
        if file.endswith(".mp3"):
            name = file
            print(f"Renamed File: {file}\n")
            os.rename(file, "song.mp3")

    voice.play(discord.FFmpegPCMAudio("song.mp3"), after=lambda e: print("Song done!"))
    voice.source = discord.PCMVolumeTransformer(voice.source)
    voice.source.volume = 0.5

    nname = name.rsplit("-", 2)
    await ctx.send(f"Now playing: {nname[0]}")
    print("Playing\n")

bot.run('token')
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-12-29 11:55:22

不怎么有意思!我不知道如何使用异步,我仍然设法建立队列。我的方法是有一个包含字典和列表的json文件。看起来是这样的:

代码语言:javascript
复制
{
    "queueskey": [
        {
            "channelid": [],
            "queue": [],
            "status": []
        },
        {
            "channelid": [],
            "queue": [],
            "status": []
        },
        {
            "channelid": [],
            "queue": [],
            "status": []
        }
    ]
}

就像这样一遍又一遍地重复。你也可以有额外的信息,以及与之一起存储。虽然调试和工作花费了我相当长的时间,但我认为这是最简单的方法之一。

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

https://stackoverflow.com/questions/65451428

复制
相关文章

相似问题

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