send Youtube videos to telegram - python

i wrote this program :
import scrapetube
import hashlib
import telegram
import requests
import json
from pytube import YouTube
from time import sleep
import os
bot_token = 'my token'
bot_chatID = '#PinkPanthersShow'
bot = telegram.Bot(token=f'{bot_token}')
c_videos = scrapetube.get_channel("UC1fIyfhQtm1fSljyKBf2uKA")
videos = list()
for video in c_videos:
videos.append(f"https://www.youtube.com/watch?v={str(video['videoId'])}")
videos.reverse()
def upload_video(title, desc):
bot.send_video(chat_id=bot_chatID, video=open(fr'{title}.mp4', 'rb'),caption=f"{desc}", supports_streaming=True)
for i in list(range(len(videos))):
yt = YouTube(videos[i])
print(f"{yt.title} : {videos[i]}")
ys = yt.streams.get_highest_resolution()
ys.download()
upload_video(str(yt.title), str(yt.description))
#print (list(videos)[0])
#links.reverse()
#print(links)
#print(title)
#print(videos)
input()
When my program gets to the video The Pink Panther Show Episode 4 - Dial" P "for Pink: https://www.youtube.com/watch?v=tOaakSDwuZE, it gives this error:
Traceback (most recent call last):
File "g:\yta\bot.py", line 43, in <module>
upload_video(str(yt.title), str(yt.description))
File "g:\yta\bot.py", line 37, in upload_video
bot.send_video(chat_id=bot_chatID, video=open(fr'{title}.mp4', 'rb'),caption=f"{desc}", supports_streaming=True)
OSError: [Errno 22] Invalid argument: 'The Pink Panther Show Episode 4 - Dial "P" for Pink.mp4'
What can I do to avoid this error?

If you want To send All videos Of a Youtube channel to telegram, you can use ytt, which is a module I have written:
https://nimafanniasl.github.io/py_youtube_to_telegram/
If you want to use an app , You can use ytt app, but if you want to use it in python, you can use ytt module, example:
pip install ytt
python app:
from ytt import ytt
ytt.start_all(YouTube_channel_id,telegram_bot_token,bot_chatID,send_channel_or_group_id=None)
# :)
More information: https://github.com/nimafanniasl/py_youtube_to_telegram/tree/main/module

from pytube import YouTube
from telebot import TeleBot
yt = YouTube("https://www.youtube.com/watch?v=lOUsz0ggDsk")
video = yt.streams.filter(file_extension="mp4").get_by_resolution("360p").download("./tmp")
bot = TeleBot("Telegram Token")
bot.send_video(230967203, open(video, 'rb'))

Related

trouble importing enums from google.cloud.speech_v1

I have this code:
from google.cloud import speech_v1
from google.cloud.speech_v1 import enums
import os
import importlib
# Import the enums module from the google.cloud.speech_v1 package
enums = importlib.import_module("google.cloud.speech_v1.enums")
# Set your Google Cloud project and service account credentials
os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = "creds.json"
# Create a client for the Google Cloud Speech-to-Text API
stt_client = speech_v1.SpeechClient()
# Transcribe the audio data
response = stt_client.recognize(
audio=speech_v1.types.RecognitionAudio(uri="gs://focus-0/speech-to-text-sample.wav"),
config=speech_v1.types.RecognitionConfig(
encoding=enums.RecognitionConfig.AudioEncoding.FLAC,
sample_rate_hertz=48000,
language_code="en-US"
)
)
# Print the transcribed text
for result in response.results:
print("Transcription: {}".format(result.alternatives[0].transcript))
When I run it, I get this:
Traceback (most recent call last):
File "/Users/dir/git/fp-scrapers/speech/1-STT.py", line 5, in <module>
from google.cloud.speech_v1 import enums
ImportError: cannot import name 'enums' from 'google.cloud.speech_v1' (/opt/homebrew/lib/python3.9/site-packages/google/cloud/speech_v1/__init__.py)
I have tried several ways to import enums, but none of them have worked.
Does anyone see what I'm doing wrong?
enums and types have been removed in the 2.x versions of the library
Mentioned in this github.Refer to this migration guide. You can refer to this quick start for setup instructions and an updated client library
Before:
from google.cloud import speech
encoding = speech.enums.RecognitionConfig.AudioEncoding.LINEAR16
audio = speech.types.RecognitionAudio(content=content)
After:
from google.cloud import speech
encoding = speech.RecognitionConfig.AudioEncoding.LINEAR16
audio = speech.RecognitionAudio(content=content)

AttributeError: module 'wsgi' has no attribute 'application'

app.py file code:
import webbrowser
import time
#!/usr/bin/env python
try:
# For Python 3.0 and later
from urllib.request import urlopen
except ImportError:
# Fall back to Python 2's urllib2
from urllib2 import urlopen
import certifi
import json
def get_jsonparsed_data(url):
"""
Receive the content of ``url``, parse it as JSON and return the object.
Parameters
----------
url : str
Returns
-------
dict
"""
response = urlopen(url, cafile=certifi.where())
data = response.read().decode("utf-8")
return json.loads(data)
url = ("https://financialmodelingprep.com/api/v3/quote/AAPL,FB?apikey=d099f1f81bf9a62d0f16b90c3dc3f718")
print(get_jsonparsed_data(url))
country = get_jsonparsed_data(url)
count = 0
for result in country:
if count == 0:
header = result.keys()
for head in header:
html_content = f"<div> {head} </div>"
count += 1
with open("index.html", "w") as html_file:
html_file.write(html_content)
print("Html file created successfully !!")
time.sleep(2)
webbrowser.open_new_tab("index.html")
passenger_wsgi.py file code:
import imp
import os
import sys
sys.path.insert(0, os.path.dirname(__file__))
wsgi = imp.load_source('wsgi', 'app.py')
application = wsgi.application
Error:
Traceback (most recent call last):
File "/home/stockpee/staging/passenger_wsgi.py", line 9, in <module>
application = wsgi.application
AttributeError: module 'wsgi' has no attribute 'application'
Traceback (most recent call last):
File "/home/stockpee/staging/passenger_wsgi.py", line 9, in <module>
application = wsgi.application
AttributeError: module 'wsgi' has no attribute 'application'
Hi,
Everyone, I am new in Python. I have develop a basic application on my local machine. But when I deployed it on A2Host hosting server. I am facing above error when I run my application in web browser.
Is anyone help me to fix above issue. I will be very thankful for that person.
I will applogize in advance for my brief answer. But it has to do with the fact that you have not established a whisky app.
You need to make sure in your main application file app.py you establish your application.
def app(environ, start_response):
pprint("whoo hooo. ")
I hope this helps.

Error 263 for command: open Welcome.mp3 The specified device is not open or is not recognized by MCI

import speech_recognition as sr
import requests
from gtts import gTTS
from playsound import playsound
import os
import subprocess
bot_message = ""
message = ""
myobj = gTTS(text="Hello I am Shilpa Sheety Speak Anything I am Listening", lang='en', tld='com.au')
myobj.save("starting.mp3")
playsound("starting.mp3")
while bot_message !="Bye":
r = sr.Recognizer()
with sr.Microphone() as source:
audio = r.listen(source)
try:
message = r.recognize_google(audio)
print("You said : {}".format(message))
except:
print("Sorry Could not recognize your voice")
if len(message) == 0:
continue
print("Sending Message Now")
r = requests.post("http://localhost:5002/webhooks/rest/webhook", json={'message':message})
print("Bot Says,", end=' ')
for i in r.json():
bot_message = i['text']
print(f"{i['text']}")
myobj = gTTS(text=bot_message)
myobj.save("Welcome.mp3")
playsound("Welcome.mp3")
In above program I am playing welcome.mp3 in a loop. It is working fine for first 2 iterations but in 3rd iteration of for loop I am getting the following error:
Error 263 for command:
open Welcome.mp3
The specified device is not open or is not recognized by MCI.
Error 263 for command:
close Welcome.mp3
The specified device is not open or is not recognized by MCI. Failed to close the file: Welcome.mp3 Traceback (most recent call last): File "Voice_bot.py", line 31, in <module>
playsound("Welcome.mp3") File "C:\Users\DJ9004\anaconda4\lib\site-packages\playsound.py", line 72, in _playsoundWin
winCommand(u'open {}'.format(sound)) File "C:\Users\DJ9004\anaconda4\lib\site-packages\playsound.py", line 64, in winCommand
raise PlaysoundException(exceptionMessage) playsound.PlaysoundException:
Error 263 for command:
open Welcome.mp3
The specified device is not open or is not recognized by MCI.*
It worked for me when I uninstalled playsound module and installed sn older version like this:
pip uninstall playsound
pip install playsound==1.2.2
It works when I install the version of playsound by uninstalling the previous version like this
pip uninstall playsound
pip install playsound==1.2.2
Try it
I had the same issue, it looks like the file is still being saved when you are trying to open it.
I added a couple of lines and it worked just fine:
for i in r.json():
bot_message = i['text']
print(f"{i['text']}")
myobj = gTTS(text=bot_message)
os.remove('Welcome.mp3') #LINE ADDED
myobj.save("Welcome.mp3")
time.sleep(1) #LINE ADDED
playsound("Welcome.mp3")
I had the same error as you and not finding answers I started to do tests. The way I found is not very practical, but it works for me. In a new file I wrote this piece of code (For the example we will call the 'function_sound_file' file):
from playsound import playsound
def function_sound():
playsound('complete/path/file.wav')
And in the file where I had the problem, I call the function I created after importing it (below).
from function_sound_file import function_sound
function_sound()
I tried an illogical solution but it worked every time.
just change the name of your audio file to 'audio.mp3'
and don't forget to close it by using "os.close('audio.mp3')" .
The code below never worked:
from gtts import gTTS
import os
#greetings
def start():
tts = gTTS(text="hi, its kate here! how may i help you?", lang='en' ,
slow=False)
tts.save('lol.mp3')
from playsound import playsound
playsound('lol.mp3')
os.remove('lol.mp3')
start()
But it worked every time:
from gtts import gTTS
import os
#greetings
def start():
tts = gTTS(text="hi, its kate here! how may i help you?", lang='en' ,
slow=False)
tts.save('audio.mp3')
from playsound import playsound
playsound('audio.mp3')
os.remove('audio.mp3')
start()
As you can see I just changed 'lol.mp3' to 'audio.mp3'.
Hope it works.

Telebot package problem with importing "Types"

When i want to run my bot in pycharm, I receive this error:
\Desktop\st\taxi\taxi.py", line 5, in <module>
from telebot import types
ImportError: cannot import name 'types' from 'telebot' (C:\Users\User\Desktop\st\taxi\venv\lib\site-packages\telebot\__init__.py)
Here is my code:
import config
from telebot import TeleBot, types
bot = TeleBot(config.TELEGRAM_BOT_TOKEN)
#bot.message_handler(commands=['location']) #Запрос локации
def request_location(message):
keyboard = types.ReplyKeyboardMarkup(row_width=1, resize_keyboard=True)
button_geo = types.KeyboardButton(text="Отправить местоположение", request_l
ocation=True)
keyboard.add(button_geo)
bot.send_message(message.chat.id, "Поделись местоположением", reply_markup=k
eyboard)
if __name__ == "__main__":
bot.polling()
How to fix this?

ImportError: No module named 'google.cloud.proto.vision'

Code :
from google.cloud import vision
import google.cloud.proto.vision.v1.image_annotator_pb2 as pvv
import io
client = vision.ImageAnnotatorClient()
def mkrl(imageStr):
im_obj = pvv.Image(content = imageStr)
return pvv.AnnotateImageRequest(image = im_obj, features = [{"type": "TEXT_DETECTION"}])
def getR(imageList):
req = map(mkrl,imageList)
response = client.batch_annotate_images(req)
return response
I'm trying to extract text from an image using the google vision api. I need to send a batch of images - things were working fine but now there is this error:
ImportError: No module named 'google.cloud.proto.vision'
this has been solved.....
the correct way to import this is :
import google.cloud.vision_v1.proto.image_annotator_pb2 as pvv
or
from google.cloud.vision_v1.proto import image_annotator_pb2 as pvv

Categories

Resources