(Apr-23-2021, 11:37 AM)aliwien Wrote: Hello I'm trying to create a discord bot and I'm stuck one subject. I want to share a random photo from a folder when someone write in the chat specific words. For example when someone write 'dog', ı want to share a dog photo from a folder. I'll show my basic code I hope you will help me.
import os
import random
import discord
from discord.ext import commands
my_files = [discord.File('A:\\ma\\1.jpg'), discord.File('A:\\ma\\2.jpg')]
bat = ['dog', 'cat']
.
.
.
if any(word in msg for word in bat):
await message.channel.send(files=my_files)
Well, first, it is not a "random" photo, it is a specific photo. What I would do is tag the metadata of each photo with the tags that would include it. I would write a program that I would run every so often (once a month, maybe) that opened each photo and read the metadata, and found the tags. It would then create a dictionary of tag : (photo1, photo2, ..., photoN). I would save this dictionary to a disk file. When I ran the Python program, it would start up by reading this dictionary in. Then, when it found a tag in the chat that matched a tag in the dictionary, it would select one of the photos in the list, and in this case it might choose, if > 1 photos, a photo randomly of that set. This way, I don't have to create a list of the photos by hand in the source code. I might use a program that let me add captions to a photo, and I might add a caption like
Fido and I at the beach :dog: :beach:
The format for metadata in photos (particularly JPEG) is documented; there may even be a place for a text caption and for keywords, in which case the syntax I just gave may not be necessary. This means that if you want to remove a tag, you can do it easily, rerun the indexing program, and that photo is no longer in the set. I would never consider any solution that required I build a table on my own, separate from the photos.
I'm not sure what discord.File() does, but it strikes me that if you had a thousand photos, this involves reading all thousand photos in when the program starts. Having two tables, "my_files" and "bat", is insane and unmaintainable once the quantity of photos hits two digits. I would store just the filenames, and not apply discord.File() until I knew which photo I was going to send.
I worry about things like "await" applied to something that could take a long, possibly unbounded, time. This is frequently bad style, because it makes an assumption which might frequently be invalid: that the operation will complete quickly. This is a dangerous assumption.