Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const apiKey = '';
- const cx = '';
- const query = 'george costanza'; // Modify this to curate the type of images you want
- const url = `https://www.googleapis.com/customsearch/v1?q=${encodeURIComponent(query)}&cx=${cx}&key=${apiKey}&searchType=image&fileType=jpg&imgSize=large&imgType=photo`;
- const widget = await createWidget();
- if (!config.runsInWidget) {
- await widget.presentLarge();
- }
- Script.setWidget(widget);
- Script.complete();
- async function createWidget() {
- let widget = new ListWidget();
- let selection = await getRandomImage();
- if (!selection || !selection.image) {
- console.error("Selection is undefined or does not have an image.");
- let errorText = widget.addText("Failed to load image");
- errorText.textColor = Color.red();
- errorText.font = Font.boldSystemFont(16);
- return widget;
- }
- let imageStack = widget.addStack();
- let image = selection.image;
- let img = imageStack.addImage(image);
- img.centerAlignImage();
- img.imageSize = new Size(800, 400); // Adjust the size as needed to fit the widget
- widget.addSpacer();
- let gradient = new LinearGradient();
- gradient.colors = [new Color("#000000", 0), new Color("#000000", 0.5)];
- gradient.locations = [0, 1];
- let titleStack = widget.addStack();
- titleStack.backgroundGradient = gradient;
- titleStack.addSpacer();
- let titleText = titleStack.addText(selection.title);
- titleText.font = Font.boldSystemFont(16);
- titleText.textColor = Color.white();
- titleText.rightAlignText();
- let interval = 1000 * 60 * 15; // Refresh every 15 minutes
- widget.refreshAfterDate = new Date(Date.now() + interval);
- return widget;
- }
- async function getRandomImage() {
- try {
- let response = await new Request(url).loadJSON();
- console.log('API Response:', JSON.stringify(response, null, 2)); // Log the response for debugging
- if (!response.items || response.items.length === 0) {
- console.error("No images found in the response.");
- return null;
- }
- let images = response.items;
- let num = Math.floor(Math.random() * images.length);
- let image = images[num];
- let imgRequest = new Request(image.link);
- let img = await imgRequest.loadImage();
- return { image: img, title: image.title };
- } catch (e) {
- console.error('Error:', e);
- if (e.response) {
- let errorText = await e.response.text();
- console.error('Error Response:', errorText); // Log the detailed error response
- }
- return null;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement