Why is the ffmpeg process in discordpy terminating without playing anything? - python

I'm making a discord bot for playing music (ik very unoriginal) and everytime I try to play music, it gives this error:
2023-02-18 12:31:54 INFO discord.player ffmpeg process 4024 has not terminated. Waiting to terminate...
2023-02-18 12:31:54 INFO discord.player ffmpeg process 4024 should have terminated with a return code of -9.
It is in the voice chat and didn't play anything. Here's my code if you need it:
print("defining functions")
import discord, pytube, os, threading
from moviepy import editor
from discord.ext.commands import Bot
intents=discord.Intents.default()
intents.message_content = True
intents.voice_states = True
bot = Bot("b!",intents=intents)
check = False
token = "redacted"
#bot.command()
async def play(ctx, arg):
await ctx.send("Downloading...")
try:
yt = pytube.YouTube(arg)
print("STREAM: "+str(yt.streams.filter(only_audio=True,mime_type="audio/webm",type="audio",abr="160kbps")))
def download(yt):
print("DOWNLOADING STREAM TO AUDIO.WEBM")
yt.streams.filter(only_audio=True,mime_type="audio/webm",type="audio",abr="160kbps").order_by("abr").first().download(filename="audio.webm")
print("EXPORTING TO MP3")
editor.AudioFileClip("audio.webm").write_audiofile("audio.webm"[:-5] + ".mp3")
os.remove("audio.webm")
print("DONE")
thread = threading.Thread(target=download, args=(yt,))
thread.start()
thread.join()
try:
channel = ctx.author.voice.channel
try:
vc = await channel.connect()
except Exception:
ctx.send("already in vc, one sec")
except Exception:
pass
vc.play(discord.FFmpegPCMAudio(source="audio.mp3", executable="./ffmpeg"))
except Exception:
pass
bot.run(token)
It worked on my computer in VS Code, but I wanted to test it on Replit and only there I got the error. I tried:
Reinstalling discord, pynacl, even pytube and moviepy.
Using a local copy of ffmpeg on replit, see line 36.
Adding the intents that were described in a different thread.
One thing that always happens is the exit code being -9 but the process number changing (ofc). I saw a GitHub Issue about this too which is not showing a fix so how do I fix that?

Related

Is there any way of writing a command to interrupt time.sleep for a discord music bot?

I am trying to code a music bot to play music in a discord server. The issue I am having is with the "play" command I am using, when a song is playing from this version of the play command, no other commands (e.g. ".disconnect") work. The code I have written for this is
#bot.command()
async def play(ctx,search):
query_string = urllib.parse.urlencode({'search_query': search})
htm_content = urllib.request.urlopen('http://www.youtube.com/results?'+query_string)
search_results = re.findall(r'/watch\?v=(.{11})',htm_content.read().decode())
URL = ('http://www.youtube.com/watch?v='+search_results[0])
song_queue.append(URL)
if len(song_queue)>1:
await ctx.channel.send("Song queued.")
for index in range(len(song_queue)):
yt = YouTube(song_queue[index])
video_length = yt.length
await play_song(ctx, song_queue[index])
await ctx.channel.send(song_queue[index])
del song_queue[0]
time.sleep(video_length)
I am assuming that the issue comes from the time.sleep(video_length) pausing all of the code and not just pausing the for loop that it's in.

Youtube-dl and Ffmpeg

i have made a music bot with discord.py, but i get this info thing and it doesnt work anymore error [youtube] QxYdBvB8sOY: Downloading webpage 985104597242773505 [2022-06-25 07:45:51] [INFO ] discord.player: Preparing to terminate ffmpeg process 37580. [2022-06-25 07:45:51] [INFO ] discord.player: ffmpeg process 37580 has not terminated. Waiting to terminate... [2022-06-25 07:45:51] [INFO ] discord.player: ffmpeg process 37580 should have terminated with a return code of 1. this is my code
import discord
import os
import asyncio
import youtube_dl
from discord import *
token = "token is here"
prefix = "j!"
blocked_words = ["blocked words are here"]
voice_clients = {}
yt_dl_opts = {'format': 'bestaudio/best'}
ytdl = youtube_dl.YoutubeDL(yt_dl_opts)
ffmpeg_options = {'options': "-vn"}
intents = discord.Intents.default()
intents.message_content = True
client = discord.Client(intents=intents)
programmer_role = "987018590152699964"
#client.event
async def on_ready():
print(f"Bot logged in as {client.user}")
#client.event
async def on_message(msg):
if msg.author != client.user:
if msg.content.lower().startswith(f"{prefix}info"):
await msg.channel.send(f"Hi, Im JoksysBot Made By Joksy!")
for text in blocked_words:
if text in str(msg.content.lower()):
await msg.delete()
await msg.channel.send("Hey, Dont Say That!")
return
if msg.content.startswith(f"{prefix}play"):
try:
voice_client = await msg.author.voice.channel.connect()
voice_clients[voice_client.guild.id] = voice_client
except:
print("error")
try:
url = msg.content.split()[1]
loop = asyncio.get_event_loop()
data = await loop.run_in_executor(None, lambda: ytdl.extract_info(url, download=False))
song = data['url']
player = discord.FFmpegPCMAudio(song, **ffmpeg_options, executable="C:\\Users\\jonas\\Documents\\ffmpeg-2022-06-16-git-5242ede48d-full_build\\ffmpeg-2022-06-16-git-5242ede48d-full_build\\bin\\ffmpeg.exe")
voice_clients[msg.guild.id].play(player)
except Exception as err:
print(err)
if msg.content.startswith(f"{prefix}pause"):
try:
voice_clients[msg.guild.id].pause()
except Exception as err:
print(err)
if msg.content.startswith(f"{prefix}resume"):
try:
voice_clients[msg.guild.id].resume()
except Exception as err:
print(err)
if msg.content.startswith(f"{prefix}stop"):
try:
voice_clients[msg.guild.id].stop()
await voice_clients[msg.guild.id].disconnect()
except Exception as err:
print(err)
client.run(token)
its weird since all the other code in my bot works fine like the !info command, so it must be an error with either youtube-dl or ffmpeg. But then again it doesnt join the voice call in the first place so that might be the error. i added ffmpeg to path but i still wrote the path to it here player = discord.FFmpegPCMAudio(song, **ffmpeg_options, executable="C:\\Users\\jonas\\Documents\\ffmpeg-2022-06-16-git-5242ede48d-full_build\\ffmpeg-2022-06-16-git-5242ede48d-full_build\\bin\\ffmpeg.exe"). i followed this tutorial for the bot https://www.youtube.com/watch?v=Q8wxin72h50&t=1040s i did everything he did but it didnt work. My discord.py version is 2.0.0 my Python version is 3.10.5 and my youtube_dl version is 2021.12.17 my ffmpeg download is ffmpeg-2022-06-16-git-5242ede48d-full_build. I tested it on discord.py 1.73 and it worked fine. This was in intellij though whilst my main program is in Visual Studio Code but i couldnt see it making any big difference so it could be the intents that makes the program not work.I couldnt see any mistakes in the code but im new to discord.py, youtube_dl and ffmpeg stuff so unless visual studio code showed me what i did wrong, i wouldnt notice. But what did i do wrong and how can i fix it?
So for anybody having this issue here ya go: So the issue was connecting to the voice call. Make sure you have these intents
intents = discord.Intents.default()
intents.message_content = True
intents.voice_states = True
if it still doesnt work make sure you have PyNaCl installed. you can do it in a terminal with this code pip install pynacl you need to have python installed for this though. and that should be the fix

discord.ext problems with sending in right channel and setting status

I'm using discord.py, and from there the discord.ext module. I have a quite long selenium code running in a while True loop. Here's part of it:
#bot.command()
async def start(ctx):
driver.install_addon(r'some_extension.xpi')
channel = bot.get_channel(791352165393498203)
user = bot.get_user(257428782233812993)
while True:
await bot.change_presence(status=Status.online)
driver.get('some_link')
driver.maximize_window()
time.sleep(5)
try:
driver.find_element_by_xpath('//*[#id="pageSize"]').click()
except NoSuchElementException:
await ctx.channel.send(f" We had an Exception, please go check")
time.sleep(60)
driver.refresh()
time.sleep(5)
driver.find_element_by_xpath('//*[#id="pageSize"]').click()
time.sleep(1)
await ctx.channel.send(f"Problem solved")
Most of this code works fine, but there are two main problems, and I don't get an exception.
Firstly, the await ctx.channel.send(f"We had an Exception, please go check") should be sent in the channel I stated above, but it
doesn't. pycharm says that the channel variable is never used,
which shouldn't be the case.
Secondly, the await bot.change_presence(status=Status.online) doesn't keep the bot
permanently displayed as online.
Just use channel.send() without ctx, ctx is a bunch of info about used command (author, channel, etc.).
You don't need to change status to online, it's automatically setting when you launch the bot.
Oh, and i recommend to use asyncio.sleep() instead of time.sleep() because, when u use time.sleep() the bot will stop working in this time, and will not responding to any command/event.

Discord.py || How to loop a part of Program infinite times without crashing it eventually?

I am Trying to Make a 24/7 Streaming Discord Bot using while(True): Infinite Loop,
But I think that the while(True): will get crashed by the OS (Using Heroku for Hosting) or Some kind of threads problem
#commands.command(name='play',aliases=["p"])
async def _play(self, ctx: commands.Context):
i = 0
while(True): #Infinite While Loop
search = URL[i] #URL is the List of Musics I What to Stream 24/7
if not ctx.voice_state.voice:
await ctx.invoke(self._join) #joins the voice channel if not in voice channel previously
async with ctx.typing():
try:
source = await YTDLSource.create_source(ctx, search, loop=self.bot.loop)
#Sets the Status of the Bot to What Music it is Playing Currently
await self.bot.change_presence(activity=discord.Activity(type=discord.ActivityType.listening, name=f"{source.title}"))
except YTDLError as e:
await ctx.send('An error occurred while processing this request: {}'.format(str(e)))
else:
song = Song(source)
await ctx.voice_state.songs.put(song) #Enqueue the Song
i = (i + 1) % len(URL) # Updates the Index of URL
await asyncio.sleep(source.DURATION) #Gets the Lenght of the Music in int and Sleeps
I thought of using Asyncio Event Loops but Can't Figure it Out How to Use it Because my Function Has Parameters/Arguments like context (ctx)
I have Also thought of Cleaning the Memory stack after each songs play... But is it possible ??? If yes can we use it to fix my problem
So Is there anyway to Loop The above Mentioned Block or Code Infinitely without crashing it eventually
Thanks in advance !!!
I have a Out of Topic Query... Can we Use the ability of Context (ctx) without passing it as a Argument.
If we Can then I might be able to use asyncio_event_loop, I suppose

Why is my discord bot only executing my command one time and one time only?

I'm in the process of finishing a simple sound clip Discord bot I made by recycling a basic music bot example in python. All I want the bot to do is enter the voice channel of the user who called the command (!womble), play a random sound clip from a folder of sound clips, then leave the voice channel.
"Simple, right?" Of course it isn't, not with this API apparently.
After a BUNCH of trial and error, looking to at least 3 API revisions I got the bot to actually perform the command.....one time. Any further prompts of the command are met with crickets. I can do a !summon and it bring the bot into the channel, but the !womble command no longer works.
def bot_leave(self, ctx):
state = self.get_voice_state(ctx.message.server)
coro = state.voice.disconnect()
fut = asyncio.run_coroutine_threadsafe(coro, state.voice.loop)
try:
fut.result()
except:
# an error happened sending the message
pass
#commands.command(pass_context=True, no_pm=True)
async def womble(self, ctx):
state = self.get_voice_state(ctx.message.server)
opts = {
'default_search': 'auto',
'quiet': True,
}
if state.voice is None:
success = await ctx.invoke(self.summon)
if not success:
return
try:
random_clip = clip_dir + "\\" + random.choice(os.listdir(clip_dir))
player = state.voice.create_ffmpeg_player(random_clip, after=lambda: self.bot_leave(ctx))
player.start()
except Exception as e:
fmt = 'An error occurred while processing this request: ```py\n{}: {}\n```'
await self.bot.send_message(ctx.message.channel, fmt.format(type(e).__name__, e))
I have tried going into the python chat is the Discord API server, but much like my bot, I'm met with crickets. (Guess that's what I get trying to seek support from a chat that already has 4 conversations going.)
I'm guessing you might not need help anymore but just in case you should try removing the coroutine.result() and run it directly. I.e change:
def bot_leave(self, ctx):
state = self.get_voice_state(ctx.message.server)
coro = state.voice.disconnect()
fut = asyncio.run_coroutine_threadsafe(coro, state.voice.loop)
try:
fut.result()
except:
# an error happened sending the message
pass
to:
def bot_leave(self, ctx):
state = self.get_voice_state(ctx.message.server)
coro = state.voice.disconnect()
try:
asyncio.run_coroutine_threadsafe(coro, state.voice.loop)
except:
# an error happened sending the message
pass
That's the only thing I could think of seeing your code snippet, but the problem may lie elsewhere in the code.

Categories