Created
November 16, 2022 12:43
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# | |
# 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