我为discord机器人(Python3.6和discord.py 1.2.3中的程序)创建了一个新齿轮。 我的代码可以正常唤醒,但是对于某些音乐标题,该机器人应该无法识别某些字符和错误。
python
import discord
from discord.ext import commands
from discord.utils import get
import youtube_dl
import os
import shutil
from os import system
class musique(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.Cog.listener()
async def on_ready(self):
print('-----------------')
print('Le fichier musique est chargé! --> OK')
print('-----------------')
@commands.command(pass_context=True, aliases=['j', 'joi'])
async def join(self, ctx):
global voice
channel = ctx.message.author.voice.channel
voice = get(self.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()
print(f"The bot has connected to {channel}\n")
await ctx.send(f"Joined {channel}")
@commands.command(pass_context=True, aliases=['l', 'lea'])
async def leave(self, ctx):
channel = ctx.message.author.voice.channel
voice = get(self.bot.voice_clients, guild=ctx.guild)
if voice and voice.is_connected():
await voice.disconnect()
print(f"The bot has left {channel}")
await ctx.send(f"Left {channel}")
else:
print("Bot was told to leave voice channel, but was not in one")
await ctx.send("Don't think I am in a voice channel")
@commands.command(pass_context=True, aliases=['p', 'pla'])
async def play(self, ctx, url: str):
def check_queue():
Queue_infile = os.path.isdir("C:/Users/Theo/Desktop/projet bot discord/test/cogs.//Queue")
if Queue_infile is True:
DIR = os.path.abspath(os.path.realpath("Queue"))
length = len(os.listdir(DIR))
still_q = length - 1
try:
first_file = os.listdir(DIR)[0]
except:
print("No more queued song(s)\n")
queues.clear()
return
main_location = os.path.dirname(os.path.realpath(__file__))
song_path = os.path.abspath(os.path.realpath("Queue") + "\\" + first_file)
if length != 0:
print("Song done, playing next queued\n")
print(f"Songs still in queue: {still_q}")
song_there = os.path.isfile("song.mp3")
if song_there:
os.remove("song.mp3")
shutil.move(song_path, main_location)
for file in os.listdir("./"):
if file.endswith(".mp3"):
os.rename(file, 'song.mp3')
voice.play(discord.FFmpegPCMAudio("song.mp3"), after=lambda e: check_queue())
voice.source = discord.PCMVolumeTransformer(voice.source)
voice.source.volume = 0.30
else:
queues.clear()
return
else:
queues.clear()
print("No songs were queued before the ending of the last song\n")
song_there = os.path.isfile("song.mp3")
try:
if song_there:
os.remove("song.mp3")
queues.clear()
print("Removed old song file")
except PermissionError:
print("Trying to delete song file, but it's being played")
await ctx.send("ERROR: Music playing")
return
Queue_infile = os.path.isdir("./Queue")
try:
Queue_folder = "./Queue"
if Queue_infile is True:
print("Removed old Queue Folder")
shutil.rmtree(Queue_folder)
except:
print("No old Queue folder")
await ctx.send("Getting everything ready now")
voice = get(self.bot.voice_clients, guild=ctx.guild)
ydl_opts = {
'format': 'bestaudio/best',
'quiet': True,
'postprocessors': [{
'key': 'FFmpegExtractAudio',
'preferredcodec': 'mp3',
'preferredquality': '192',
}],
}
try:
with youtube_dl.YoutubeDL(ydl_opts) as ydl:
print("Downloading audio now\n")
ydl.download([url])
except:
print("FALLBACK: youtube-dl does not support this URL, using Spotify (This is normal if spotify URL)")
c_path = os.path.dirname(os.path.realpath(__file__))
system("spotdl -f " + '"' + c_path + '"' + " -s " + url) # make sure there are spaces in the -s
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: check_queue())
voice.source = discord.PCMVolumeTransformer(voice.source)
voice.source.volume = 0.30
nname = name.rsplit("-", 2)
await ctx.send(f"Playing: {nname[0]}")
print("playing\n")
@commands.command(pass_context=True, aliases=['pa', 'pau'])
async def pause(self, ctx):
voice = get(self.bot.voice_clients, guild=ctx.guild)
if voice and voice.is_playing():
print("Music paused")
voice.pause()
await ctx.send("Music paused")
else:
print("Music not playing failed pause")
await ctx.send("Music not playing failed pause")
@commands.command(pass_context=True, aliases=['r', 'res'])
async def resume(self, ctx):
voice = get(self.bot.voice_clients, guild=ctx.guild)
if voice and voice.is_paused():
print("Resumed music")
voice.resume()
await ctx.send("Resumed music")
else:
print("Music is not paused")
await ctx.send("Music is not paused")
@commands.command(pass_context=True, aliases=['s', 'sto'])
async def stop(self, ctx):
voice = get(self.bot.voice_clients, guild=ctx.guild)
queues.clear()
if voice and voice.is_playing():
print("Music stopped")
voice.stop()
await ctx.send("Music stopped")
else:
print("No music playing failed to stop")
await ctx.send("No music playing failed to stop")
queues = {}
@commands.command(pass_context=True, aliases=['q', 'que'])
async def queue(self, ctx, url: str):
Queue_infile = os.path.isdir("C:/Users/Theo/Desktop/projet bot discord/test/cogs/./Queue")
if Queue_infile is False:
os.mkdir("Queue")
DIR = os.path.abspath(os.path.realpath("Queue"))
q_num = len(os.listdir(DIR))
q_num += 1
add_queue = True
while add_queue:
if q_num in queues:
q_num += 1
else:
add_queue = False
queues[q_num] = q_num
queue_path = os.path.abspath(os.path.realpath("Queue") + f"\song{q_num}.%(ext)s")
ydl_opts = {
'format': 'bestaudio/best',
'quiet': True,
'outtmpl': queue_path,
'postprocessors': [{
'key': 'FFmpegExtractAudio',
'preferredcodec': 'mp3',
'preferredquality': '192',
}],
}
try:
with youtube_dl.YoutubeDL(ydl_opts) as ydl:
print("Downloading audio now\n")
ydl.download([url])
except:
print("FALLBACK: youtube-dl does not support this URL, using Spotify (This is normal if spotify URL)")
q_path = os.path.abspath(os.path.realpath("Queue"))
system(f"spotdl -ff song{q_num} -f " + '"' + q_path + '"' + " -s " + url)
await ctx.send("Adding song " + str(q_num) + " to the queue")
print("Song added to queue\n")
def setup(bot):
bot.add_cog(musique(bot))
我希望所有字符都能被识别。
我的错误代码是:
忽略命令播放中的异常:
比赛(最近通话最近一次):
文件“ C:\ Users \ Theo \ AppData \ Local \ Programs \ Python \ Python37-32 \ lib \ site-packages \ discord \ ext \ commands \ core.py”,
第79行,在包装好的ret = await coro(* args,** kwargs)
文件“ C:\ Users \ Theo \ Desktop \ projet bot discord \ test \ testmusic.py”,
第143行,正在播放中打印(f“重命名的文件:{file} \ n”)
文件“ C:\ Users \ Theo \ AppData \ Local \ Programs \ Python \ Python37-32 \ lib \ encodings \ cp1252.py”,
第19行,以编码返回codecs.charmap_encode(input,self.errors,encoding_table)[0] UnicodeEncodeError:'charmap'编解码器无法编码字符'\ u0300'
在位置38:字符映射到
<undefined>