discord.py how to connect random choices - discord.py

I'm trying to make a meme command (where random images come out) personally dedicated to the server and I would like the author of the meme to be mentioned.
But I'm afraid that if I also create images for the author other than the author.
My question is essentially:
How do I put both the image and the author in the same variable? (Sorry if I explained myself wrong)
Code
#random image embed
#client.command(aliases=["IM","im"])
async def image_embed(ctx):
tartufo=[
'https://cdn.discordapp.com/attachments/640563710104043530/731555200489357362/salvenee.jpg',
'https://cdn.discordapp.com/attachments/640563710104043530/731552604546662511/unknown.png',
'https://media.gettyimages.com/photos/rocks-balancing-on-driftwood-sea-in-background-picture-id153081592?s=612x612'
]
embed = discord.Embed(
color=discord.Colour.dark_blue()
)
embed.set_image(url=random.choice(tartufo))
embed.set_footer(text=f'Richiesto da {ctx.author.name}')
await ctx.send(embed=embed)

You can make a list of tuples where the elements of each tuple are the url and author:
images = [
('url1', 'author1'),
('url2', 'author2'),
('url3', 'author3'),
('url4', 'author4'),
]
url, author = random.choice(images)
embed.set_image(url=url)
embed.set_footer(text=f'Author is {author}')

Related

Discord Integer delete mention <#Deleted-Role>

I'm wondering if any of you guys can figure out how i could use my role : Name : Color Magenta. Id. 855179067388461076
Known Issue: Discord have limitation of integer maximum lenght. I believe.. that's what i know..
#bot.command()
async def Shop(ctx):
roleId = "855179067388461076>"
ShopEM = discord.Embed(title=f"🢃 BASIC COLORS SHOP 🢃", color=0xff5555)
ShopEM.add_field(name=f"1) Magenta", value=f'<#&' + (roleId), inline=True)
ShopEM.add_field(name=f"2) khaki ", value=f"<#&1075540590604853278>", inline=False)
ShopEM.add_field(name=f"3) Purple", value=f"<#&1075540578072273006>", inline=False)
ShopEM.add_field(name=f"4) Gray", value=f"<#&1075540541195960400>", inline=True)
ShopEM.add_field(name=f"5) Olive ", value=f"#&1075540533457461379>", inline=False)
ShopEM.add_field(name=f"6) Teal", value=f"<#&1075540547021840404>", inline=False)
ShopEM.add_field(name=f"PRICE", value="")
await ctx.send(embed=ShopEM)
Output :
Are you sure:
that the bot has permissions to mention those roles?
that those IDs are the correct roles for this server?
My code below, very similar to yours, works absolutely fine. I only got deleted-role when I entered in numbers that were made up or for roles not in this server.
#bot.command()
async def shop(ctx):
# list of tuples to iterate over with the role name and then role ID
roles = [
("bots", "1065670055507005128"),
("server booster", "1068466410612867541"),
("human", 1064550904461795018),
("admin", 813738863871787428)
]
shop_em = discord.Embed(title="🢃 BASIC COLORS SHOP 🢃", color=0xff5555)
# iterate over the roles and add them to the embed
for role in roles:
shop_em.add_field(name=role[0], value=f"<#&{role[1]}>", inline=True)
await ctx.send(embed=shop_em)
Note: Putting the IDs as ints or strings didn't matter at all. For example, I use both here and there weren't issues with either.
Example of it working:

Telegram bot convert youtube link to mp3 (Python)

How to make a telegram bot that converts simple youtube link (something like https://www.youtube.com/watch?v=v3F3v8yNucc) into .mp3?
Please suggest something with minimum efford
This will do the minimum job:
import os
import telebot
import youtube_dl
# get YOUR_API_KEY from #BotFather
bot = telebot.TeleBot("YOUR_API_KEY")
#bot.message_handler(commands=['start'])
def shoot(message):
bot.send_message(message.chat.id, "Gimme YouTube link")
#bot.message_handler()
def run(message):
if "https://www.youtube.com" not in message.text:
print("This is not YouTube link!")
return
bot.send_message(message.chat.id, "Please wait...")
video_info = youtube_dl.YoutubeDL().extract_info(
url = message.text, download=False
)
filename = f"{video_info['title']}.mp3"
options={
'format':'bestaudio/best',
'keepvideo':False,
'outtmpl':filename,
}
with youtube_dl.YoutubeDL(options) as ydl:
ydl.download([video_info['webpage_url']])
print("Download complete... {}".format(filename))
bot.send_audio(message.chat.id, audio=open(filename, 'rb'))
bot.polling()
Thise code will download mp3 music to your server and sends it to the user in telegram, so you might wanna delete it after you send it, or need a larger server? Up to you.

Custom help command

Hi I’m trying to code a simple discord bot using discord.py, and one of the things I want my bot to do is send a nice custom embed when a user uses the !help command. So far I know that this simple code, which some people provided in other questions on stackoverflow about custom help commands:
class help(commands.MinimalHelpCommand):
async def send_pages(self):
destination = self.get_destination()
e = discord.Embed(title="Help:", description="description", colour=discord.Colour.blurple(), timestamp=datetime.datetime.utcnow())
await destination.send(embed=e)
client.help_command = help()
works, but the thing is when someone wants to use !help on a specific command or category, the bot will only send the send_pages command. I tried modifying the code and added
async def send_page_command(self, *, command):
destination = self.get_destination
command_e = discord.Embed(title="Dogluva:robot's Help:", description=f"{command.description}", colour=discord.Colour.blurple(), timestamp=datetime.datetime.utcnow())
await destination.send(embed=command_e)
But this doesn’t help. Anyone know what I’m doing wrong here? I’ve set the description for all the commands I wrote in my cogs using commands.command(description=“description") but I don’t know how to make a custom help command access those descriptions.
First, remember to delete the default help command (discord automatically has help command), so you need to delete it first:
client.remove_command('help') # before your own "help" command
# or
client = commands.Bot(command_prefix="<your prefix>", help_command=None) # when you create client
Basic help command:
#client.command()
async def help(ctx):
embed = discord.Embed(title="Help", description="Write your own description here", colour=discord.Color.blue())
await ctx.send(embed=embed)
But you can make it even better. Read more about Embeds in the documentation and check this template:
instead of send_page_command(self, *, command): you can try using send_command_help(self, command):
https://gist.github.com/InterStella0/b78488fb28cadf279dfd3164b9f0cf96
#client.command()
async def help(ctx, *, command=None):
if command == None:
e = discord.Embed(title="Dogluva:robot:'s Help:", description=“Custom Description", colour=discord.Colour.blurple(), timestamp=datetime.datetime.utcnow())
elif command == “{command}":
e = discord.Embed(title="Dogluva:robot:'s Help:", description=“Command Description", colour=discord.Colour.blurple(), timestamp=datetime.datetime.utcnow())
await ctx.send(embed=e)
I just created different cases for each command

Need help to fix a certain bug in Rock Paper Scissors Command | Discord.py rewrite

So I have made a Rock paper Scissors command and it works almost perfectly. However, there is a bug that I need to fix it so badly. But I couldn't get any help from anywhere, unfortunately. Here's how the code works.
When you type '>rps' it sends an embed and asks to react to any of the emoji (rock, paper, or scissor). The bot has already chosen its item (with the help of random module). When I react to any emoji(rock, paper, and scissor emoji)it shows that I won, lost, or tied the match. It's all fine till here. But when you react to the same message manually(with any of the 3 emojis), the message changes again to win, lose, or draw embed. I want this to stop happening after the member has finished one match. Here's my code.
my code
Sorry for not providing raw code, because the code sample was kinda buggy. I really appreciate it if someone helps me out. Thanks :)
Don't use the event on_reaction_add, instead use a wait_for, here's an example.
def check(reaction, user):
return user == message.author and str(reaction.emoji) in ["put", "emojis", "here"]
try:
reaction, user = await client.wait_for('reaction_add', timeout=60.0, check=check)
except asyncio.TimeoutError:
await channel.send("Timed out!")
else:
if str(reaction.emoji) == rock:
...
elif str(reaction.emoji) == paper:
...
else: # Scissors
...
I also highly suggest just having one embed and editing it to fit your needs, you can define embed as
em = discord.Embed(description=f"The bot chose {x}")
# Later on in the code
if bot_won:
em.title = "You lost!"
em.color = ...
elif user_won:
em.title = "You won!"
em.color = ...
else: # Draw
em.title = "Draw!"
em.color = ...

How to download the image of an embeded message with disord.py

I am trying to be able to download the content of an embedded message.
This is what I am running so far
async def on_message(self, message):
embedFromMessage = message.embeds
print(embedFromMessage)
I would like it to output the url of the attached image and the description but is only outputting [discord.embeds.Embed object at 0x049A8990]
The discord.py API provides you a set of tools to allowing you to find what you're looking for.
Find the embed
As I see you're trying to catch an embedded message using the on_message event.
To do so we're going to use this :
#commands.Cog.listener()
async def on_message(self, message):
if(len(message.embeds) > 0):
This simple if statment will determine if the message is an embedded one or not.
If the message is an embed it will return a list of embeds.
Note that the image preview is considered as an embedded message.
Now let's catch the embed you want :
_embed = message.embeds[0] # this will return the first embed in message.embeds
Once we've stored the embed, we want to know if it contains an image :
if not _embed.image.url == discord.Embed.Empty:
image = _embed.image.url
By default, _embed.image will return an EmbedProxy which looks like that :
EmbedProxy(width=0, url='URL', proxy_url='PROXY_URL', height=0)
To access the value of url we have done _embed.image.url.
Now you have the image URL, you can download it using the aiohttp library for example.
The full code
Here is the code you can use to catch the image inside an embedded message as those that are created using the discord.Embed() class.
#commands.Cog.listener()
async def on_message(self, message):
if(len(message.embeds) > 0):
_embed = message.embeds[0]
if not _embed.image.url == discord.Embed.Empty:
image = _embed.image.url
channel = message.channel # get the channel where the embed has been sent
await channel.send(image) # send the image into the channel
Hope it helped !
Have a nice day !

Resources