How to Code My Bot to Generate Random Images from One Command

how to code my bot to generate random images from one command

As per the documentation you can't upload an image like you would from a local source so you can either

Upload from a local source using send_file

await client.send_file(message.channel, 'my_image.png')

or

Embed the URL

import discord

embed = discord.Embed()
embed.set_image(url = random.choice([jessie1,snowy]))
await client.send_message(message.channel,embed=embed)

Make my discord.js bot to send a random picture from an array of images from my computer

setImage only allows you to add an image hosted online (i.e. you need to provide a URL that starts with http or https). Luckily, you can upload a file from your computer using the attachFiles() method instead of the setImage.

const random = (arr) => arr[Math.floor(Math.random() * arr.length)];
const images = [
'./images/avatar1.png',
'./images/avatar2.png',
'./images/avatar3.png',
'./images/avatar4.png',
];

const embed = new MessageEmbed()
.setTitle('Attach file')
.setAuthor('joBas')
.attachFiles([random(images)]);

message.channel.send(embed);

The problem with this is that it's not the same as setting the image using .setImage(). The image is not displayed in the embed, but right before it:

Sample Image

To solve this you can set the image to the newly uploaded image that can be accessed via attachment://fileName.extension. As you will need both the filename and the extension, you need to store the filenames without the path in the array and store the path in a different variable.

Check out the code below:

const random = (arr) => arr[Math.floor(Math.random() * arr.length)];
const images = [
'avatar1.png',
'avatar2.png',
'avatar3.png',
'avatar4.png',
];
// path where the images are
const path = './images/';
const randomImage = random(images);

const embed = new MessageEmbed()
.setTitle('Attach file')
.setAuthor('joBas')
.attachFiles([`${path}${randomImage}`])
.setImage(`attachment://${randomImage}`);

message.channel.send(embed);

As you can see on the image below, the attached image is no longer outside of the embed:

Sample Image

How can I get a random image from image search using a command discord.py

You can use the Unsplash Source API, as suggested by Bagle.

@command(name = "img")
async def cat(self, ctx, arg):
embed = discord.Embed(
title = 'Random Image ',
description = 'Random',
colour = discord.Colour.purple()
)
embed.set_image(url='https://source.unsplash.com/1600x900/?{}'.format(arg))
embed.set_footer(text="")
await ctx.send(embed=embed)

And execute the command with

{bot_prefix}img computers


Related Topics



Leave a reply



Submit