discord.py FFMPEG Option reconnect not found - ffmpeg

I'm working on a music bot using discord.py, I've looked online and found that I needed to pass in ffmpeg options into discord.FFmpegPCMAudio() for the bot to not stop half way through the song. However it returns an error "Option reconnect not found."
vc = await ctx.message.author.voice.channel.connect()
ydl_opts = {
'format': 'bestaudio/best',
'outtmpl': 'C:/Luke/YoutubeDLAudio/audio.mp3',
'postprocessors': [{
'key': 'FFmpegExtractAudio',
'preferredcodec': 'mp3',
'preferredquality': '192'
}],
'prefer_ffmpeg': True,
'keepvideo': True
}
ffmpeg_opts = {'before_options': '-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5','options': '-vn'} # <---------------
with youtube_dl.YoutubeDL(ydl_opts) as ydl:
ydl.download([url])
vc.play(discord.FFmpegPCMAudio(executable="C:/Luke/ffmpeg/bin/ffmpeg.exe", source="C:/Luke/YoutubeDLAudio/audio.mp3", **ffmpeg_opts)) <--------------
Does anyone know the problem? Thanks for any help.

Related

Playing a stream by my discord bot on heroku doesnt work

I want to make a Bot, that plays a livestream of an online radio. I use Discord JS v13.
On Heroku I have installed the following buildpacks:
heroku/nodejs
https://github.com/jonathanong/heroku-buildpack-ffmpeg-latest.git
https://github.com/xrisk/heroku-opus.git
https://github.com/OnlyNoob/heroku-buildpack-libsodium.git
My code is the following:
let voiceChn = message.member.voice.channel;
const connection = joinVoiceChannel({
channelId: message.member.voice.channel.id,
guildId: message.member.voice.channel.guildId,
adapterCreator: message.guild.voiceAdapterCreator,
selfDeaf: true
});
const player = createAudioPlayer();
let resource = createAudioResource(STREAM_URL);
connection.subscribe(player);
connection.on(VoiceConnectionStatus.Ready, () => {
player.play(resource);
});
It does work running on my pc but it does not run on Heroku.
These are the packages I have installed:
"#discordjs/opus": "^0.5.3"
"#discordjs/rest": "^0.5.0"
"#discordjs/voice": "^0.10.0"
"discord-api-types": "^0.36.0"
"discord.js": "^13.8.1"
"ffmpeg-static": "^4.4.1"
"libsodium-wrappers": "^0.7.10"
I do get the following error: The player immediately emits the idle event and thats logged:
{
status: 'playing',
missedFrames: 0,
playbackDuration: 120,
resource: AudioResource {
playStream: OggDemuxer {
_readableState: [ReadableState],
_events: [Object: null prototype],
_eventsCount: 5,
_maxListeners: undefined,
_writableState: [WritableState],
allowHalfOpen: true,
_remainder: null,
_head: null,
_bitstream: null,
[Symbol(kCapture)]: false,
[Symbol(kCallback)]: null
},
edges: [ [Object], [Object] ],
metadata: null,
volume: undefined,
encoder: undefined,
audioPlayer: undefined,
playbackDuration: 0,
started: true,
silencePaddingFrames: 5,
silenceRemaining: 0
},
onStreamError: [Function: onStreamError]
}
Not sure about the error, but I believe I had the same problem and fixed it.
Didn't test if all the changes are needed, but here goes:
Instead of your heroku-buildpack-libsodium package, I use:
https://github.com/Crazycatz00/heroku-buildpack-libopus
Changed every URLs 'https' with 'http'
Use a DNS lookup tool to change domain name with IPV4 form
'https://stream.skymedia.ee/live/NRJdnb' becomes 'http://185.31.240.229:8888/NRJdnb'
Deploy slash commands after you change their code

I get too often the HTTP error 403 Forbidden using discord.py and ytdl

I built a discord bot using ytdl, it works fine but randomly, I get this error and I can't figure out the cause: (I truncated the link with ... because it was too long)
[https # 000001ead63ee980] HTTP error 403 Forbidden
https://rr2---sn-uxaxpu5ap5-jp5l.googlevideo.com/videoplayback?expire=...: Server returned 403 Forbidden (access denied)
I thought the problem was this portion of code:
with youtube_dl.YoutubeDL(ytdlopts) as ydl:
ydl.cache.remove()
info = ydl.extract_info(search_query, download=False)
So I put it inside a try/catch, but it doesn't catch the error.
I tried also:
ydl.cache.remove()
But the problem still there, in the odious event that the problem is not in my code but on the server side, is there a way to fix or mitigate the problem?
These are my ffmpeg/ytdl options:
ytdlopts = {
'format': 'bestaudio/best',
'outtmpl': 'downloads/%(extractor)s-%(id)s-%(title)s.%(ext)s',
'restrictfilenames': True,
'nocheckcertificate': True,
'ignoreerrors': False,
'logtostderr': False,
'quiet': True,
'extract_flat': True,
'skip_download': True,
'default_search': 'auto',
'source_address': '0.0.0.0' # ipv6 addresses cause issues sometimes
}
ffmpegopts = {'before_options': '-nostdin','options': '-vn'}
opts = {'extract_flat': True, 'skip_download': True}
ytdl = YoutubeDL(ytdlopts)
```
try doing ipv4: True and 'cachedir': False in ytdlopts, doing this, you force ipv4 and clear cache, I'm not sure it works but on me works fine.
ytdlopts = {
'format': 'bestaudio/best',
'outtmpl': 'downloads/%(extractor)s-%(id)s-%(title)s.%(ext)s',
'restrictfilenames': True,
'nocheckcertificate': True,
'ignoreerrors': False,
'logtostderr': False,
'quiet': True,
'extract_flat': True,
'skip_download': True,
'default_search': 'auto',
'source_address': '0.0.0.0' # ipv6 addresses cause issues sometimes
'force-ipv4': True,
'cachedir': False
}

ConversationHandler not working when deployed on Heroku but is working good when running on local machine

I am using Python Telegram Bot library to make a bot that has a conversation which let's users name their project, payment plans etc. The conversation consists of MessageHandlers and CallBackQueryHandlers. Thr problem I'm facing is, this conversation was working fine when I was using this bot from my local machine, but when I deployed it to heroku, I can't have the full conversation, it would become unresponsive at some point and I would have to cancel the conversation(which surprisingly, works at lightning bolt speed). All other handlers of my application work as expected and respond quickly.
I am using webhook in this application.
The ConversationHandler:
add_project_handler = ConversationHandler(
entry_points=[CallbackQueryHandler(project_name, pattern="add_project")],
states={
PROJECT_NAME: [MessageHandler(Filters.regex(".*"), store_name_maybe_project_type)],
PROJECT_TYPE: [CallbackQueryHandler(store_type_maybe_admin)],
ADMIN:[CallbackQueryHandler(connect_channel)],
CONNECT:[MessageHandler(Filters.regex(".*"), connect_channel_add_currency)],
CURRENCY:[CallbackQueryHandler(store_currency_maybe_frequency)],
FREQUENCY:[CallbackQueryHandler(store_frequency_maybe_amount)],
MONEY:[MessageHandler(Filters.regex(".*"), store_amount_maybe_bot)],
TOKEN:[MessageHandler(Filters.regex(".*"), store_bot_show_links)],
PAY_SETUP:[CallbackQueryHandler(setup_payment)],
PAYPAL:[MessageHandler(Filters.regex(".*"), handle_client_id)],
CLIENT_ID:[MessageHandler(Filters.regex(".*"), handle_client_secret)],
},
fallbacks=[CommandHandler('cancel', cancel)],
)
handlers.append(add_project_handler)
EDIT:
So I checked out the logs, and I saw some really weird behavior, so it recieves an update, and right now, the state of the conversation should have been 1, but it says 'selecting conversation with state None'. That too it does three times.
2021-10-01T16:55:59.411864+00:00 heroku[router]: at=info method=POST path="/1967487217:AAGDmzoxPPlB386VuEYr4s8dPM50fr49d84" host=invitememberbot.herokuapp.com request_id=6d10ee36-ebe4-40de-91b3-48c5e33d6172 fwd="91.108.6.63" dyno=web.1 connect=0ms service=2ms status=200 bytes=154 protocol=https
2021-10-01T16:55:59.415201+00:00 app[web.1]: 2021-10-01 16:55:59,414 - telegram.ext.dispatcher - DEBUG - Processing Update: {'callback_query': {'chat_instance': '1523769404808794079', 'id': '4756348607585474313', 'data': 'channel', 'message': {'delete_chat_photo': False, 'chat': {'id': 1107423707, 'first_name': 'Palash', 'type': 'private', 'username': 'raghu_palash', 'last_name': 'Raghuwanshi'}, 'channel_chat_created': False, 'date': 1633106830, 'supergroup_chat_created': False, 'reply_markup': {'inline_keyboard': [[{'callback_data': 'channel', 'text': 'Paid Telegram Channel'}]]}, 'group_chat_created': False, 'photo': [], 'caption_entities': [], 'new_chat_members': [], 'message_id': 2657, 'entities': [], 'text': 'What do you want to make?', 'new_chat_photo': [], 'from': {'id': 1967487217, 'first_name': 'InviteMemberBot', 'username': 'InviteMemberFiverrBot', 'is_bot': True}}, 'from': {'language_code': 'en', 'last_name': 'Raghuwanshi', 'id': 1107423707, 'first_name': 'Palash', 'username': 'raghu_palash', 'is_bot': False}}, 'update_id': 334393256}
2021-10-01T16:55:59.415374+00:00 app[web.1]: 2021-10-01 16:55:59,415 - telegram.ext.conversationhandler - DEBUG - selecting conversation (1107423707, 1107423707) with state None
2021-10-01T16:55:59.415584+00:00 app[web.1]: 10.1.90.119 - - [01/Oct/2021:16:55:59 +0000] "POST /1967487217:AAGDmzoxPPlB386VuEYr4s8dPM50fr49d84 HTTP/1.1" 200 2 "-" "-"
2021-10-01T16:55:59.415742+00:00 app[web.1]: 2021-10-01 16:55:59,415 - telegram.ext.conversationhandler - DEBUG - selecting conversation (1107423707, 1107423707) with state None
2021-10-01T16:55:59.415867+00:00 app[web.1]: 2021-10-01 16:55:59,415 - telegram.ext.conversationhandler - DEBUG - selecting conversation (1107423707, 1107423707) with state None
And here's something more weird, when I click the button twice rapidly, it takes me to the next state.
2021-10-01T17:15:24.421256+00:00 heroku[router]: at=info method=POST path="/1967487217:AAGDmzoxPPlB386VuEYr4s8dPM50fr49d84" host=invitememberbot.herokuapp.com request_id=ea099aff-e9dd-46fa-8516-958677290171 fwd="91.108.6.63" dyno=web.1 connect=0ms service=6ms status=200 bytes=154 protocol=https
2021-10-01T17:15:24.420031+00:00 app[web.1]: 2021-10-01 17:15:24,419 - telegram.ext.dispatcher - DEBUG - Processing Update: {'callback_query': {'chat_instance': '1523769404808794079', 'id': '4756348606350994438', 'data': 'channel_done', 'message': {'delete_chat_photo': False, 'chat': {'id': 1107423707, 'first_name': 'Palash', 'type': 'private', 'username': 'raghu_palash', 'last_name': 'Raghuwanshi'}, 'channel_chat_created': False, 'date': 1633107558, 'supergroup_chat_created': False, 'reply_markup': {'inline_keyboard': [[{'callback_data': 'channel_done', 'text': 'Done'}]]}, 'group_chat_created': False, 'photo': [], 'caption_entities': [], 'new_chat_members': [], 'message_id': 2659, 'entities': [], 'text': "Please create a private Telegram channel and click Done when it's ready:", 'new_chat_photo': [], 'from': {'id': 1967487217,
'first_name': 'InviteMemberBot', 'username': 'InviteMemberFiverrBot', 'is_bot': True}}, 'from': {'language_code': 'en',
'last_name': 'Raghuwanshi', 'id': 1107423707, 'first_name': 'Palash', 'username': 'raghu_palash', 'is_bot': False}}, 'update_id': 334393260}
2021-10-01T17:15:24.420209+00:00 app[web.1]: 2021-10-01 17:15:24,420 - telegram.ext.conversationhandler - DEBUG - selecting conversation (1107423707, 1107423707) with state 1
I don't understand why it worked fine when I ran it on my own machine, but does this on heroku.
Additional Information -
These are the functions that are involved in this log:
def store_type_maybe_admin(update, context):
# Open db connection
conn = DB_POOL.getconn()
cur = conn.cursor()
# stores project type and conditonally asks for making admin
query = update.callback_query
query.answer()
keyboard = [[InlineKeyboardButton("Done", callback_data="channel_done")]]
reply_markup = InlineKeyboardMarkup(keyboard)
if query.data != "channel_done":
context.user_data["project_type"] = query.data
q = "UPDATE project SET project_type = %s WHERE id = %s"
cur.execute(q, (query.data, context.user_data["project_id"]))
conn.commit()
message = f"Please create a private Telegram {query.data} and click Done when it's ready:"
video = "BAACAgUAAxkDAAICCGFK8ud7FDZ2qbzOkQfrDId-abgXAAKqAwAC-KBYVquzwMps2x7GIQQ"
return_value = PROJECT_TYPE
else:
message = "Please add this bot (#InviteMemberFiverrBot) to the channel admins. It needs Add Subscribers permission.\n\nPress Done when it's ready:"
video = "BAACAgUAAxkDAAICFmFK9GB185nfUvTeE6P3ZTnEp1YEAAKxAwAC-KBYVtfAgpeMwSB0IQQ"
return_value = ADMIN
# Send a video
context.bot.send_video(chat_id=update.effective_chat.id, video=video)
context.bot.send_message(chat_id=update.effective_chat.id ,text=message, reply_markup=reply_markup, parse_mode="markdown")
DB_POOL.putconn(conn)
return return_value # will be either PROJECT_TYPE = 1 or ADMIN = 2
def connect_channel(update, context):
query = update.callback_query
query.answer()
video = "BAACAgUAAxkDAAICGWFK9ShTxKcIN32o9njkIQMCXcwoAAKyAwAC-KBYVi7hYk0auE7IIQQ"
context.bot.send_video(chat_id=update.effective_chat.id, video=video)
context.bot.send_message(
chat_id=update.effective_chat.id,
text=f"To connect the channel, please forward a message (any) from the channel to this bot."
)
return CONNECT
This is how I have setup my bot:
bot = telegram.Bot(token=TOKEN)
dispatcher = setup(bot, db_pool)
#app.route(f"/{TOKEN}", methods=["POST"])
def respond():
"""Run the bot."""
update = telegram.Update.de_json(request.get_json(force=True), bot)
dispatcher.process_update(update)
return "ok"
the setup function:
def setup(bot, db_pool):
# Create bot, update queue and dispatcher instances
dispatcher = Dispatcher(bot, None, workers=0)
##### Register handlers here #####
initialize_bot_handlers = initialize_bot(db_pool) # initialize_bot returns a list of handlers
for handler in initialize_bot_handlers:
dispatcher.add_handler(handler)
return dispatcher
The conversation handler is inside the initialize_bot function.

Google Cloud Speech API. Help getting Google's own example to work

Trying to get hints to work with Google Cloud Speech API. However, I can not get Google's own example to work for me. I get the same result with and without hints. I believe the following code is what the documentation is recommending:
Here is my script:
#!/usr/bin/python
import os
import base64
import googleapiclient.discovery
speech_file = os.path.join(
os.path.dirname(__file__),
'resources',
'shwazil_hoful.flac')
with open(speech_file, 'rb') as speech:
b64speech = base64.urlsafe_b64encode(speech.read())
service = googleapiclient.discovery.build('speech', 'v1')
service_request = service.speech().recognize(
body={
"config": {
"encoding": "FLAC", # raw 16-bit signed LE samples
"sampleRateHertz": 16000, # 16 khz
"languageCode": "en-US", # a BCP-47 language tag
"speechContexts": [{
"phrases": ["hoful","shwazil"]
}]
},
"audio": {
"content": b64speech
#"uri":"gs://cloud-samples-tests/speech/brooklyn.flac"
}
})
response = service_request.execute()
recognized_text = 'Transcribed Text: \n'
for i in range(len(response['results'])):
recognized_text += response['results'][i]['alternatives'][0]['transcript']
print(recognized_text)
Output:
it's a swazzle Hopple day
I was expecting:
it's a swazzle hoful day
Is there anything I am doing wrong?
I've tried both Python2 and Python3

Download rtmp stream

Hi a friend of ours mother just passed and they'd like the recording of the wedding so they can keep it on a flash drive. I played for about a half hour but have been unsuccessful. After looking at the pages source I fount the following javascript
if ( hasProductInstall && !hasRequestedVersion ) {
// DO NOT MODIFY THE FOLLOWING FOUR LINES
// Location visited after installation is complete if installation is required
var MMPlayerType = (isIE == true) ? "ActiveX" : "PlugIn";
var MMredirectURL = window.location;
document.title = document.title.slice(0, 47) + " - Flash Player Installation";
var MMdoctitle = document.title;
AC_FL_RunContent(
"src", "http://AbrahamLGreenandSonSympathyNet.ezwebcast.com/player/playerProductInstall",
"FlashVars", "MMredirectURL="+MMredirectURL+'&MMplayerType='+MMPlayerType+'&MMdoctitle='+MMdoctitle+"",
"width", "483",
"height", "416",
"align", "middle",
"id", "FlashPlayer",
"allowFullScreen","true",
"quality", "high",
"bgcolor", "#FFFFFF",
"name", "FlashPlayer",
"allowScriptAccess","always",
"type", "application/x-shockwave-flash",
"pluginspage", "http://www.adobe.com/go/getflashplayer"
);
} else if (hasRequestedVersion) {
// if we've detected an acceptable version
// embed the Flash Content SWF when all tests are passed
AC_FL_RunContent(
"src", "http://AbrahamLGreenandSonSympathyNet.ezwebcast.com/player/player",
"FlashVars","isDebug=0&mv=rtmp://fms35.ezwebcast.com/play/6/recorded_streams/3208/stream15989&user_id=32125&movie_id=14275",
"width", "483",
"height", "416",
"align", "middle",
"id", "FlashPlayer",
"allowFullScreen","true",
"quality", "high",
"bgcolor", "#FFFFFF",
"name", "FlashPlayer",
"allowScriptAccess","always",
"type", "application/x-shockwave-flash",
"pluginspage", "http://www.adobe.com/go/getflashplayer"
);
}
The line of interest at least in my opinion is rtmp://fms35.ezwebcast.com/play/6/recorded_streams/3208/stream15989&user_id=32125&movie_id=14275 I'm assuming that's what I need to download however when I downloaded rtmpdump and tried to run it I get the following and I haven't been able to figure out how to load the library or get this stream downloaded. Any help is greatly appreciated!
USERs-MacBook-Pro:Desktop user$ rtmpdump -r rtmp://fms35.ezwebcast.com/play/2/recorded_streams/3208/stream15989 -W "http://media.kelbymediagroup.com/players/player-4.6-licensed.swf" -o ./funeral.flv
dyld: Library not loaded: /usr/local/lib/librtmp.dylib
Referenced from: /usr/local/bin/rtmpdump
Reason: no suitable image found. Did find:
/usr/local/lib/librtmp.dylib: stat() failed with errno=13
/usr/local/lib/librtmp.dylib: stat() failed with errno=13
Trace/BPT trap: 5

Resources