search multiple channel IDs youtube/google API - google-api

const channelIds = ['UCBi2mrWuNuyYy4gbM6fU18Q', 'UCshCsg1YVKli8yBai-wa78w', 'UCoMdktPbSTixAyNGwb-UYkQ']
const online = await fetch(
https://www.googleapis.com/youtube/v3/search?part=snippet&channelId=${channelIds}&type=video&eventType=live&key=key
)
I am trying to search multiple Channels, but this doesn't seem to work. Any ideas?

The channelId parameter for search endpoint only accepts one channelId so you would have to make a separate requests for each channel.

Related

Twilio sending multiple Images to WhatsApp

I am currently trying to send multiple pictures to WhatsApp via Twilio and got it working with one.
Already read the other Questions and this one might be an easy one.
How do I send multiple Images in one Message?
This is what I have currently and what I tried, but the second image is never sent:
exports.handler = function(context, event, callback) {
var client = context.getTwilioClient();
console.log("Sende Antwort")
client.messages.create({
to: event.From,
from: event.To,
body: "Sekunde, mache dir eben deinen Stoff klar."
}, function(err, res){
console.log("Sende Katzenbilder")
let twiml = new Twilio.twiml.MessagingResponse();
let message = twiml.message();
message.body("Hier ist dein wöchentlicher Cat-Content!")
message.media("https://images.unsplash.com/photo-1566927467984-6332be7377d0?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1350&q=80");
message.media("https://images.unsplash.com/photo-1548247416-ec66f4900b2e?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=663&q=80")
callback(null, twiml)
})
};
This is not possible via the underlying API
Sending Media Messages
https://developers.facebook.com/docs/whatsapp/api/messages/media
The above sample shows multiple different objects such as audio, document, image, sticker, and video for illustration purposes only. A valid request body contains only one of them.
Twilio developer evangelist here.
WhatsApp only supports sending one image at a time with a message.
In the Twilio API for WhatsApp documentation, this is pointed out (emphasis mine):
To send back a media in your WhatsApp reply, you need to include the media TwiML element with the URL to the media file. One media attachment is supported per message, with a size limit of 5MB.
You could try sending more than one message though, by using twiml.message more than once. Try:
exports.handler = function(context, event, callback) {
var client = context.getTwilioClient();
console.log("Sende Antwort")
client.messages.create({
to: event.From,
from: event.To,
body: "Sekunde, mache dir eben deinen Stoff klar."
}, function(err, res){
console.log("Sende Katzenbilder");
let twiml = new Twilio.twiml.MessagingResponse();
let message = twiml.message();
message.body("Hier ist dein wöchentlicher Cat-Content!");
message.media("https://images.unsplash.com/photo-1566927467984-6332be7377d0?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1350&q=80");
let message2 = twiml.message();
message2.media("https://images.unsplash.com/photo-1548247416-ec66f4900b2e?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=663&q=80");
callback(null, twiml)
})
};

Send multiple files to Slack via API

According to Slack's documentation is only possible to send one file per time via API. The method is this: https://api.slack.com/methods/files.upload.
Using Slack's desktop and web applications we can send multiple files at once, which is useful because the files are grouped, helping in the visualization when we have more than one image with the same context. See the example below:
Do you guys know if it's possible, via API, to send multiple files at once or somehow achieve the same results as the image above?
Thanks in advance!
I've faced with the same problem. But I've tried to compose one message with several pdf files.
How I solved this task
Upload files without setting channel parameter(this prevents publishing) and collect permalinks from response. Please, check file object ref. https://api.slack.com/types/file. Via "files.upload" method you can upload only one file. So, you will need to invoke this method as many times as you have files to upload.
Compose message using Slack markdown <{permalink1_from_first_step}| ><{permalink2_from_first_step}| > - Slack parse links and automatically reformat message
Here is an implementation of the procedure recommended in the other answer in python
def postMessageWithFiles(message,fileList,channel):
import slack_sdk
SLACK_TOKEN = "slackTokenHere"
client = slack_sdk.WebClient(token=SLACK_TOKEN)
for file in fileList:
upload=client.files_upload(file=file,filename=file)
message=message+"<"+upload['file']['permalink']+"| >"
outP = client.chat_postMessage(
channel=channel,
text=message
)
postMessageWithFiles(
message="Here is my message",
fileList=["1.jpg", "1-Copy1.jpg"],
channel="myFavoriteChannel",
)
A Node.JS (es6) example using Slack's Bolt framework
import pkg from '#slack/bolt';
const { App } = pkg;
import axios from 'axios'
// In Bolt, you can get channel ID in the callback from the `body` argument
const channelID = 'C000000'
// Sample Data - URLs of images to post in a gallery view
const imageURLs = ['https://source.unsplash.com/random', 'https://source.unsplash.com/random']
const uploadFile = async (fileURL) {
const image = await axios.get(fileURL, { responseType: 'arraybuffer' });
return await app.client.files.upload({
file: image.data
// Do not use "channels" here for image gallery view to work
})
}
const permalinks = await Promise.all(imageURLs.map(async (imageURL) => {
return (await uploadImage(imageURL)).file.permalink
}))
const images = permalinks.map((permalink) => `<${permalink}| >`).join('')
const message = `Check out the images below: ${images}`
// Post message with images in a "gallery" view
// In Bolt, this is the same as doing `await say({`
// If you use say(, you don't need a channel param.
await app.client.chat.postMessage({
text: message,
channel: channelID,
// Do not use blocks here for image gallery view to work
})
The above example includes some added functionality - download images from a list of image URLs and then upload those images to Slack. Note that this is untested, I trimmed down the fully functioning code I'm using.
Slack's image.upload API docs will mention that the file format needs to be in multipart/form-data. Don't worry about that part, Bolt (via Slack's Node API), will handle that conversion automatically (and may not even work if you feed it FormData). It accepts file data as arraybuffer (used here), stream, and possibly other formats too.
If you're uploading local files, look at passing an fs readstream to the Slack upload function.
For Python you can use:
permalink_list = []
file_list=['file1.csv', 'file2.csv', 'file3.csv']
for file in file_list:
response = client.files_upload(file=file)
permalink = response['file']['permalink']
permalink_list.append(permalink)
text = ""
for permalink in permalink_list:
text_single_link = "<{}| >".format(permalink)
text = text + text_single_link
response = client.chat_postMessage(channel=channelid, text=text)
Here you can play around with the link logic - Slack Block Kit Builder
Python solution using new recommended client.files_upload_v2 (tested on slack-sdk-3.19.5 on 2022-12-21):
import slack_sdk
def slack_msg_with_files(message, file_uploads_data, channel):
client = slack_sdk.WebClient(token='your_slack_bot_token_here')
upload = client.files_upload_v2(
file_uploads=file_uploads_data,
channel=channel,
initial_comment=message,
)
print("Result of Slack send:\n%s" % upload)
file_uploads = [
{
"file": path_to_file1,
"title": "My File 1",
},
{
"file": path_to_file2,
"title": "My File 2",
},
]
slack_msg_with_files(
message='Text to add to a slack message along with the files',
file_uploads_data=file_uploads,
channel=SLACK_CHANNEL_ID # can be found in Channel settings in Slack. For some reason the channel names don't work with `files_upload_v2` on slack-sdk-3.19.5
)
(some additional error handling would not hurt)
Simply use Slack Blocks: Block Kit Builder. Great feature for the message customizations.

ServiceUrl "https://smba.trafficmanager.net/apac/" is not working

I have a MS Teams bot. I have installed the bot for couple of users in tenant. Now when I'm starting conversation, for few users it is responding and few it is not.
I investigated further and found out that for users who are getting reply from bot, the serviceurl is "https://smba.trafficmanager.net/in/".
For users who are not getting reply from bot, the serviceurl is "https://smba.trafficmanager.net/apac/".
Exception message: Operation returned an invalid status code 'NotFound'
private async Task MessageReceivedAsync(IDialogContext context, IAwaitable<object> result)
{
var activity = await result as Activity;
var reply = activity.CreateReply();
reply.Text = "Hi there";
await context.PostAsync(reply);
}
This sounds like it's possibly a TrustServiceUrl Issue (despite the 500 vs 401 error message).
You can fix it by adding all of your ServiceUrls to the list of trusted URLs:
private async Task MessageReceivedAsync(IDialogContext context, IAwaitable<object> result)
{
var activity = await result as Activity;
var serviceUrl = activity.ServiceUrl;
MicrosoftAppCredentials.TrustServiceUrl(serviceUrl);
var reply = activity.CreateReply();
reply.Text = "Hi there";
await context.PostAsync(reply);
}
This should ensure that your bot "trusts" the ServiceUrl of any message that it receives.
Let me know how that goes. I'm 90% sure this is the issue, but it might not be.
Here's a link to the library, if that helps. Otherwise, browsing these issues should help.
Note to others:
This "Trust Service URL Issue" doesn't apply to just Teams. This happens for lots of other URLs when trying to use Proactive messaging. Just replace serviceUrl with whatever is appropriate for your use case. And yes, if you're using multiple channels, you can add multiple URLs when using MicrosoftAppCredentials.TrustServiceUrl() by calling it multiple times.
Here's the method definition. Note: you can add expiration for this, as well.
I've submitted a PR for this, which so far has resulted in some updated docs

slack api to find existing channel

I am playing with slack apis to create an integration. I am able to sucessfully create a slack channel using
this.http.post(slackApiHost + '/channels.create', payload, {headers: headers})
.subscribe(
res => {
console.log(res);
resolve(res)
},
err => {
console.log('error:' + err)
}
)
})
the payload looks like
var payload = {
"name" : channelName
};
So, it will fail with name_taken if the channel already exists. which is great. However, I need to find the channel id of the existing channel so that i can then use it for my purpose. how do i go about it?
To get a list of all existing channel you can use conversations.list. This is the most flexible approach and allows you to retrieve any type of channel if you so choose.
If you are looking for a channel by a specific name you will need to first retrieve the list of all channels and then run your own name matching against the full list. An API method which allows you to directly search for a channel by name does not exist.
Note that if you are looking for private channels this method will only retrieve channels that you (the installer of your Slack app / your bot user) has been invited to.
There's currently no direct Slack API to find a slack channel by its name. But you can use conversations.list to handle this and here's the right code to use:
const slack = new SlackWebClient(token);
const channelNameToFind = "test";
for await (const page of slack.paginate("conversations.list", {
limit: 50,
})) {
for (const channel of page.channels) {
if (channel.name === channelNameToFind) {
console.log(`Found ${channelNameToFind} with slack id ${channel.id}`);
break;
}
}
}
This is the right way™️ to do it since it will ensure you stop listing channels as soon as you found the right one.
Good luck!
You can use built-in admin.conversations.search
and then iterate found results.
One more kind of fast tricky solution:
try to send chat.scheduleMessage and then if it was sent chat.deleteScheduledMessage or catch error.
Ruby example:
def channel_exists?(channel)
begin
response = #slack_client.chat_scheduleMessage(channel: channel, text: '', post_at: Time.now.to_i + 100)
#slack_client.chat_deleteScheduledMessage(channel: channel, scheduled_message_id: response.scheduled_message_id)
return true
rescue Slack::Web::Api::Errors::ChannelNotFound
return false
end
end

google rest api reverse image search

I am trying to do a reverse image search with the Google REST API with an image stored locally. I am using the new--not deprecated--REST API. I can do a text search and get results. I can not do a search with a local image. I can do a reverse image search on the image and get a result. Any suggestions?
My https string is:
https://www.googleapis.com/customsearch/v1?key=A******&cx=0****&q=file:///home/givonz/donald-trump-voicemail-feature.jpg
Also, tried this https string, which doesn't work either:
https://www.googleapis.com/customsearch/v1?key=A******&cx=0****&searchType=image&q=file:///home/givonz/donald-trump-voicemail-feature.jpg
This text string search works:
https://www.googleapis.com/customsearch/v1?key=A******&cx=0****&q=Some+String
It seems the service is deprecated and no longer available as an API and; it always needed a link (URL). There are a few services on the web that seem to provide the function. Bing, in spite of appearing to do so, doesn't seem to. Yahoo does a reverse image search, but, I couldn't find an API. "Incandescent" does provide this service and with an API.
This should work. Make sure you pass your key in the header.
var path = #"YOUR_IMAGE_PATH";
var url = "https://api.cognitive.microsoft.com/bing/v7.0/images/details?modules=similarimages";
using (var client = new HttpClient())
using (Stream imageFileStream = File.OpenRead(path))
{
var content = new MultipartFormDataContent();
var strContent = new StreamContent(imageFileStream);
strContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data") { FileName = "anynameworks" };
content.Add(strContent);
var message = await client.PostAsync(url, content);
return await message.Content.ReadAsStringAsync();
}

Resources