在我的discord.py机器人中,我正在尝试创建一个函数,该函数运行该机器人加入语音通道,播放音频文件然后离开的必要代码。我正在执行此操作,因此不必为要执行的每个语音命令复制并粘贴相同的代码。但是,我无法运行该功能。
我尝试使用异步def和await函数来运行我的函数,但是它似乎不起作用。我一无所知,因为当我运行代码时,我不会收到任何错误。
async def voiceCommand(ctx, message, file, time, cmd):
channel = ctx.message.author.voice.voice_channel
if channel == None: # If the user who sent the voice command isn't in a voice channel.
await client.say('You are not in a voice channel, therefore I cannot run this command.')
return
else: # If the user is in a voice channel
print(executed(cmd, message.author))
voice = await client.join_voice_channel(channel)
server = ctx.message.server
voice_client = client.voice_client_in(server)
player = voice.create_ffmpeg_player(file) # Uses ffmpeg to create a player, however it makes a pop up when it runs.
player.start()
time.sleep(float(time))
await voice_client.disconnect() # Disconnects WingBot from the voice channel.
和
@client.command(pass_context = True)
async def bigbruh(ctx):
voiceCommand(ctx, message, 'bigbruh.mp3', '0.5', 'bigbruh')
这些是我试图用来运行该功能的代码片段。
此处是完整的源代码:https://pastebin.com/bv86jSvk
答案 0 :(得分:0)
您可以使用以下几种方法在python中运行异步功能
async def print_id():
print(bot.user.id)
@bot.event
async def on_ready():
bot.loop.create_task(print_id()) #this will run the print_id function
print(bot.user.name)
async def not_me(msg):
await bot.send_message(msg.message.channel,"You are not me")
async def greet():
print("Hi")
@bot.command(pass_context=True)
async def me(msg):
if msg.message.author.id == '123123':
await bot.say("Hello there") #await is used to run async function inside another async function
else:
await not_me(msg)
#To run the async function without it being inside another async function you have to use this method or something similar to it
import asyncio
# asyncio.get_event_loop().run_until_complete(the_function_name())
#in this case it's `greet`
asyncio.get_event_loop().run_until_complete(greet())