gpt4 book ai didi

python - 如何在给定时间后插入用于随机化和操作的命令

转载 作者:行者123 更新时间:2023-12-04 23:20:37 26 4
gpt4 key购买 nike

现在在我的代码中,我将它写出来以在 !join 命令之后播放音频文件。我想将它更改为每 40 分钟后的命令,并且我希望能够从列表中选择一个随机文件来播放。关于如何调整我的代码的帮助会很棒!
我的代码:

from discord.ext import commands
from discord import FFmpegPCMAudio

client = commands.Bot(command_prefix = '!')
@client.command(pass_context=True)
async def join(ctx):
if (ctx.author.voice):
channel = ctx.message.author.voice.channel
voice = await channel.connect()
source = FFmpegPCMAudio('AUDIO FILE')
player = voice.play(source)
else:
await ctx.send("User not in a voice channel, unable to connect.")

@client.command(pass_context=True)
async def leave(ctx):
if (ctx.voice_client):
await ctx.guild.voice_client.disconnect()
await ctx.send("I have left the voice channel.")
else:
await ctx.send("I am not in a voice channel.")



client.run('BOT TOKEN')```

最佳答案

首先,在代码顶部添加:

from discord.ext import tasks 
import random
然后,在代码中的任意位置添加:
@tasks.loop(minutes=40)
async def play_random_song():
for channel in voicechannels: #voicechannels is your list of voicechannels where a random song should be played every 40 minutes
song = random.choice(list_of_songs) #list_of_songs is your list of all the songs audio files you want to be able to be randomly played
voice = await channel.connect()
source = FFmpegPCMAudio(song)
player = voice.play(source)
然后启动您在 on_ready 中创建的任务:
@client.event
async def on_ready():
play_random_song.start()
这意味着您的最终代码是:
from discord.ext import commands
from discord import FFmpegPCMAudio
from discord.ext import tasks
import random

client = commands.Bot(command_prefix = '!')
@client.command(pass_context=True)
async def join(ctx):
if (ctx.author.voice):
channel = ctx.message.author.voice.channel
voice = await channel.connect()
source = FFmpegPCMAudio('AUDIO FILE')
player = voice.play(source)
else:
await ctx.send("User not in a voice channel, unable to connect.")

@client.command(pass_context=True)
async def leave(ctx):
if (ctx.voice_client):
await ctx.guild.voice_client.disconnect()
await ctx.send("I have left the voice channel.")
else:
await ctx.send("I am not in a voice channel.")


@tasks.loop(minutes=40)
async def play_random_song():
for channel in voicechannels: #voicechannels is your list of voicechannels where a random song should be played every 40 minutes
song = random.choice(list_of_songs) #list_of_songs is your list of all the songs audio files you want to be able to be randomly played
voice = await channel.connect()
source = FFmpegPCMAudio(song)
player = voice.play(source)

@client.event
async def on_ready():
play_random_song.start()

client.run('BOT TOKEN')
引用: random.choice : https://docs.python.org/3/library/random.html#random.choice discord.ext.tasks : discord.ext.tasks

关于python - 如何在给定时间后插入用于随机化和操作的命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67256333/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com