Skip to content

Instantly share code, notes, and snippets.

@mgiugliano
Created November 16, 2022 12:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mgiugliano/25428789c00b8ba1c1073c3e3f2f8294 to your computer and use it in GitHub Desktop.
Save mgiugliano/25428789c00b8ba1c1073c3e3f2f8294 to your computer and use it in GitHub Desktop.
Minimal Python3 code example (for Discord.py BOT library) for playing an audio file in a voice channel
#
# Minimal code for an audio file player BOT in a voice channel
#
# Entirely based on the example from Rapptz (that was NOT working for me)
# https://github.com/Rapptz/discord.py/blob/master/examples/basic_voice.py
#
# Nov 15 2022
import asyncio
import discord
from discord.ext import commands
from config_private import * # Import private credentials (prefs.py)
ffmpeg_options = { # type > ffmpeg --help, to list options
'options': '-vn', # disable video
}
class AudioTest(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.command()
async def testme(self, ctx):
"""USAGE !testme (joins the voice chan specified by CHANNEL, and plays a file)"""
# This is the filename to play
filename = './a.mp3' # it works with *.wav files too
channel = await self.bot.fetch_channel(CHANNEL)
vc = await channel.connect()
await ctx.send(f'Connected!')
vc.play(discord.FFmpegPCMAudio(filename))
vc.source = discord.PCMVolumeTransformer(vc.source)
vc.source.volume = 0.5
while vc.is_playing():
await ctx.send(f'Still playing...')
await asyncio.sleep(0.5)
await vc.disconnect(force=True)
await ctx.send(f'Disconnected!')
intents = discord.Intents.default()
intents.message_content = True
bot = commands.Bot(
command_prefix=commands.when_mentioned_or("!"),
description='Minimal audio-file player bot example',
intents=intents,
)
@bot.event
async def on_ready():
print(f'Logged in as {bot.user} (ID: {bot.user.id})')
print('------')
async def main():
async with bot:
await bot.add_cog(AudioTest(bot))
await bot.start(TOKEN)
asyncio.run(main())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment