My Current Project
I am currently trying to make a cog for a Discord bot in Python 3 that, when running, plays a specific audio file when someone joins a specific Discord voice channel.
My Problem
I already have the code for my project(credit: Tabulate), but I don't know how to
- Convert it to a cog, and
- Make it work for a specific voice channel, and not every one in the Discord server.
Here's my code:
import discord
from discord.ext import commands
from time import sleep
rpgmusicpath = r"C:\Users\lones\OneDrive\Desktop\Bot\music\rpgmusic.mp3"
class VoiceChannelIntro(commands.Cog):
def __init__(self, client):
self.bot = client
@commands.Cog.listener()
async def on_ready(self):
print('Channel Intro cog successfully loaded.')
@commands.Cog.event
async def on_voice_state_update(member: discord.Member, before, after):
#replace this with the path to your audio file
path = r"path\to\music.mp3"
vc_before = before.channel
vc_after = after.channel
if vc_before == vc_after:
return
elif vc_before is None:
channel = member.voice.channel
vc = await channel.connect()
vc.play(discord.FFmpegPCMAudio(path))
with audioread.audio_open(path) as f:
#Start Playing
sleep(f.duration)
await vc.disconnect()
elif vc_after is None:
return
else:
channel = member.voice.channel
vc = await channel.connect()
vc.play(discord.FFmpegPCMAudio(path))
with audioread.audio_open(path) as f:
#Start Playing
sleep(f.duration)
await vc.disconnect()
def setup(bot):
bot.add_cog(VoiceChannelIntro(bot))