How to request a channel's videos on ruby - ruby

im trying request a channel's videos for discord notification.
thats mean i request datas for per minute.
i just reach with search and that mean its cost 100
its just for my hobby and i dont want to pay for that.
have any idea how can i get last uploaded videos without search.
here my codes if u interest:
require "yt"
Yt.configure do |config|
config.api_key = 'mykey'
end
channel1 = Yt::Channel.new id: 'UCQjhFO_CA5e1-Ymopbfmx5Q'
videos = channel1.videos
video2 = videos.where(id:' UCQjhFO_CA5e1-Ymopbfmx5Q').map(&:id)
puts video2
thx

I solved with playlists.
firstly u should create a playlist and upload all videos on that playlist after that
u can use this codes :
Yt.configure do |config|
config.api_key = 'Yourkey'
end
item = Yt::Playlist.new(id: 'PLj-AxDUBuKVyraMkOwGloWO_zcUB0XNH-').playlist_items.first
item1 = item.video_id
it spends 5 quotas per request.

Related

How to query google analytics api using the google api ruby gem?

The documentation of the google api ruby client lacks of practical examples, it only documents the classes and methods, so it's very hard to guess how should we use the gem in real life. For example, I'm trying to obtain all purchases from enhanced ecommerce to see where they came from (Acquisition Channel or Channel Grouping), but im only interested on transactions that took 5 sessions to convert the transaction ( our unconvinced clients).
First you will need your analytics view_id, can be obtained in the url at the end, after the letter p
Then you need to export the route to the credentials:
In your terminal:
export GOOGLE_APPLICATION_CREDENTIALS = 'folder/yourproject-a91723dsa8974.json'
For more info about credentials see google-auth-gem documentation
After setting this, you can query the api like this
require 'googleauth'
require 'google/apis/analyticsreporting_v4'
scopes = ['https://www.googleapis.com/auth/analytics']
date_from = 10.days.ago
date_to = 2.days.ago
authorization = Google::Auth.get_application_default(scopes)
analytics = Google::Apis::AnalyticsreportingV4::AnalyticsReportingService.new
analytics.authorization = authorization
view_id = '189761131'
date_range = Google::Apis::AnalyticsreportingV4::DateRange.new(start_date: date_from.strftime('%Y-%m-%d'), end_date: date_to.strftime('%Y-%m-%d'))
metric = Google::Apis::AnalyticsreportingV4::Metric.new(expression: 'ga:transactions')
transaction_id_dimension = Google::Apis::AnalyticsreportingV4::Dimension.new(name: 'ga:transactionID')
adquisition_dimension = Google::Apis::AnalyticsreportingV4::Dimension.new(name: 'ga:channelGrouping')
filters = 'ga:sessionsToTransaction==5'
request = Google::Apis::AnalyticsreportingV4::GetReportsRequest.new(
report_requests: [Google::Apis::AnalyticsreportingV4::ReportRequest.new(
view_id: view_id,
metrics: [metric],
dimensions: [transaction_id_dimension, adquisition_dimension],
date_ranges: [date_range],
filters_expression: filters
)]
)
response = analytics.batch_get_reports(request)
response.reports.first.data.rows.each do |row|
dimensions = row.dimensions
puts "TransactionID: #{dimensions[0]} - Channel: #{dimensions[1]}"
end
note filters_expression: filters
Where filters variable is in the form of ga:medium==cpc,ga:medium==organic;ga:source==bing,ga:source==google
Where commas (,) mean OR and semicolons (;) mean AND (where OR takes precedence over AND)
you can check the query explorer to play around with filters.
Here is filters documentation
If the report brings more than 1000 rows (default max rows), a next_page_token attribute will appear.
response.reports.first.next_page_token
=> "1000"
You will have to store that number to use it in the next ReportRequest
next_request = Google::Apis::AnalyticsreportingV4::GetReportsRequest.new(
report_requests: [Google::Apis::AnalyticsreportingV4::ReportRequest.new(
view_id: view_id,
metrics: [metric],
dimensions: [transaction_id_dimension, adquisition_dimension],
date_ranges: [date_range],
filters_expression: filters,
page_token: "1000"
)]
)
until
next_response.reports.first.next_page_toke
=> nil
Alternatively you can change the default page size of the report request by adding
page_size: 10_000 for example.

I have a problem about sleep for loop on ruby

guys i write a chat bot for twitch in hobby. i want to spam a word in chat in a time like that write to chat"hello" and wait 10 sec then write again
i did that but in my code have a answer system like that when anyone write to chat !hey my bot answering hello to him. and when i tried in same system that not working
until #socket.eof? do
message = #socket.gets
puts message
if message.match(/PRIVMSG ##{#channel} :(.*)$/)
a = Time.now
b = Time.now + 5
while a < b do
write_to_chat("!prime")
a += 4
sleep(20)
end
end
if message.match(/PRIVMSG ##{#channel} :(.*)$/)
content = $~[1]
username = message.match(/#(.*).tmi.twitch.tv/)[1]
if content.include? 'theoSea'
write_to_chat(" theoAse theoAse theoAse")
end
i solved it with scheduler
i wanted a code for write every 5 min i tried lots of method but sleep command
and i found this link "https://github.com/jmettraux/rufus-scheduler"
all in link u can use this gem.
thx for everything guys.

Alexa - Ruby - Playing Audio Files

I am trying to play an audio file through Alexa. My backend in Ruby on Rails and I am using alexa-ruby gem.
I was able to produce speeches via ask and tell directive like this
def index
parsed_request = JSON.parse(request.body.read)
alexa = AlexaRuby.new(parsed_request)
speech = "Hey there! I am alexa"
response = alexa.response.ask!(speech)
render json: response
end
When I tried to play audio, I am getting no response. This is what I tried to do
def index
parsed_request = JSON.parse(request.body.read)
alexa = AlexaRuby.new(parsed_request)
params = { url: 'https://s3.amazonaws.com/my-ssml-samples/Flourish.mp3', token: 'flourish-token', offset: 0 }
response = alexa.response.add_audio_player_directive(:start, params)
render json: response
end
So depending on the type of audio you are trying to play you may want to try a different strategy. The audio player directive is more for playing something like a stream and gives the pause, rewind, etc type controls. It would be used if you where creating a music player or playing a long format audio file like a podcast.
From you example it looks like you are just trying to play a simple mp3. You can do this with the exact same way you did the speech using SSML.
For Example:
def index
parsed_request = JSON.parse(request.body.read)
alexa = AlexaRuby.new(parsed_request)
speech = "<speak>
Welcome to Ride Hailer.
<audio src="soundbank://soundlibrary/transportation/amzn_sfx_car_accelerate_01" />
You can order a ride, or request a fare estimate.
Which will it be?</speak>"
response = alexa.response.ask!(speech)
render json: response
end
You can find additional info here
https://developer.amazon.com/en-US/docs/alexa/custom-skills/speech-synthesis-markup-language-ssml-reference.html

Save Google Cloud Speech API operation(job) object to retrieve results later

I'm struggling to use the Google Cloud Speech Api with the ruby client (v0.22.2).
I can execute long running jobs and can get results if I use
job.wait_until_done!
but this locks up a server for what can be a long period of time.
According to the API docs, all I really need is the operation name(id).
Is there any way of creating a job object from the operation name and retrieving it that way?
I can't seem to create a functional new job object such as to use the id from #grpc_op
What I want to do is something like:
speech = Google::Cloud::Speech.new(auth_credentials)
job = speech.recognize_job file, options
saved_job = job.to_json #Or some element of that object such that I can retrieve it.
Later, I want to do something like....
job_object = Google::Cloud::Speech::Job.new(saved_job)
job.reload!
job.done?
job.results
Really hoping that makes sense to somebody.
Struggling quite a bit with google's ruby clients on the basis that everything seems to be translated into objects which are much more complex than the ones required to use the API.
Is there some trick that I'm missing here?
You can monkey-patch this functionality to the version you are using, but I would advise upgrading to google-cloud-speech 0.24.0 or later. With those more current versions you can use Operation#id and Project#operation to accomplish this.
require "google/cloud/speech"
speech = Google::Cloud::Speech.new
audio = speech.audio "path/to/audio.raw",
encoding: :linear16,
language: "en-US",
sample_rate: 16000
op = audio.process
# get the operation's id
id = op.id #=> "1234567890"
# construct a new operation object from the id
op2 = speech.operation id
# verify the jobs are the same
op.id == op2.id #=> true
op2.done? #=> false
op2.wait_until_done!
op2.done? #=> true
results = op2.results
Update Since you can't upgrade, you can monkey-patch this functionality to an older-version using the workaround described in GoogleCloudPlatform/google-cloud-ruby#1214:
require "google/cloud/speech"
# Add monkey-patches
module Google
Module Cloud
Module Speech
class Job
def id
#grpc.name
end
end
class Project
def job id
Job.from_grpc(OpenStruct.new(name: id), speech.service).refresh!
end
end
end
end
end
# Use the new monkey-patched methods
speech = Google::Cloud::Speech.new
audio = speech.audio "path/to/audio.raw",
encoding: :linear16,
language: "en-US",
sample_rate: 16000
job = audio.recognize_job
# get the job's id
id = job.id #=> "1234567890"
# construct a new operation object from the id
job2 = speech.job id
# verify the jobs are the same
job.id == job2.id #=> true
job2.done? #=> false
job2.wait_until_done!
job2.done? #=> true
results = job2.results
Ok. Have a very ugly way of solving the issue.
Get the id of the Operation from the job object
operation_id = job.grpc.grpc_op.name
Get an access token to manually use the RestAPI
json_key_io = StringIO.new(ENV["GOOGLE_CLOUD_SPEECH_JSON_KEY"])
authorisation = Google::Auth::ServiceAccountCredentials.make_creds(
json_key_io:json_key_io,
scope:"https://www.googleapis.com/auth/cloud-platform"
)
token = authorisation.fetch_access_token!
Make an api call to retrieve the operation details.
This will return with a "done" => true parameter, once results are in and will display the results. If "done" => true isn't there then you'll have to poll again later until it is.
HTTParty.get(
"https://speech.googleapis.com/v1/operations/#{operation_id}",
headers: {"Authorization" => "Bearer #{token['access_token']}"}
)
There must be a better way of doing that. Seems such an obvious use case for the speech API.
Anyone from google in the house who can explain a much simpler/cleaner way of doing it?

How get page with youtube channel's videos using google-api-client or yt gem?

Intro
Hi all! I am developing rails app, which shows table with videos from youtube channel. I may use google-api-client or yt gem.
Problem
User's channel may contain more then 100 videos, so it creates delays and O need pagination. I know that youtube API supports pagination by passing maxResults and page_token parameters with requests. But how can I do it using google-api-client gem?
Details
So, here's my code:
#client = Google::Client::Youtube.new(
key: APP_CONFIG[:youtube_auth_token],
application_name: APP_CONFIG[:youtube_app_name],
application_version: APP_CONFIG[:youtube_app_version],
authorization: nil
)
some_channel = #client.channels.first
some_channel.videos
#=> returns me a list of videos, sometimes it's ~500 videos
some_channel.videos(
page: 1,
offset: 25,
videos_on_page: 212,
how_can_do_it: "???"
)
Or with yt:
channel = Yt::Channel.new id: 'WERTYUGHgfhg'
all_videos = channel.videos
page_my_page_token = channel.videos(page_token)
page_my_page_token # => ???
Question
How to get first page with first 5 videos? than next page? and how check that page is last?
Many thanks!

Resources