How can I edit an embed message multiple times? - python

How can I edit an embed message multiple times? So far, I have been able to edit an embed message once, but it won't do it again.
Here's the code:
# IMPORTING
import discord
from discord import Embed
from discord.ext import commands
TOKEN = ""
BOT_PREFIX = "!"
bot = commands.Bot(command_prefix=BOT_PREFIX)
from discord import Embed
#commands
#bot.command()
async def test(ctx):
first_embed = Embed(title='embed 1')
second_embed = Embed(title='embed 2')
third_embed = Embed(title='embed 3')
msg = await ctx.send(embed=first_embed)
msg = await msg.edit(embed=second_embed)
await msg.edit(embed=third_embed)
#running the bot
bot.run(TOKEN)
Results: (embed with the title, "embed 2") and an error: discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'NoneType' object has no attribute 'edit'
How can I make it edit the message as embed 3?

Message.edit doesn't return anything, you shouldn't assign msg again,
first_embed = Embed(title='embed 1')
second_embed = Embed(title='embed 2')
third_embed = Embed(title='embed 3')
msg = await ctx.send(embed=first_embed)
await msg.edit(embed=second_embed)
await msg.edit(embed=third_embed)

Related

Discord py: Command raised an exception: AttributeError: 'Command' object has no attribute 'CommandOnCooldown'

I need help, i have been trying to solve this for so long.
It worked before but now it does not anymore.
I want the bot to send a message if the command is still on cooldown, but it does not work anymore, all it just tells me this in the console:
**Command raised an exception: AttributeError: 'Command' object has no attribute 'CommandOnCooldown'
**
Note: this is only some part of the code, i think i do not have to include my bot token in here.
import discord
from discord.ext import commands
import random
import os
bot = commands.Bot(command_prefix="++", intents=discord.Intents.all())
#bot.event
async def on_ready():
print(f'{bot.user.name} has connected to Discord!')
await bot.change_presence(activity=discord.Activity(type=discord.ActivityType.watching, name="Dev: "))
#bot.command()
#commands.cooldown(1, 86400, commands.BucketType.user)
async def daily(ctx):
# Read balance from balances.txt
try:
with open(f'{ctx.author.id}.txt', 'r+') as f:
lines = f.readlines()
user_id = str(ctx.author.id)
balance = 0
# Get the current user's balance
for line in lines:
user_id_and_balance = line.split(':')
if user_id_and_balance[0] == user_id:
balance = int(user_id_and_balance[1])
break
# Calculate bonus
bonus = random.randint(1, 1000) * 15
# Update balance and send message
new_balance = balance + bonus
embed = discord.Embed(title=f"{ctx.author.name} claimed their daily bonus!", description=f"You earned `{bonus}`:dollar: as your daily bonus.\nYour new balance is `{new_balance}` :dollar:.\n\n*This command has a cooldown of 24 hours.*", color=0x000000)
await ctx.send(f"{ctx.author.mention}", embed=embed)
# Replace the current user's balance
for i, line in enumerate(lines):
user_id_and_balance = line.split(':')
if user_id_and_balance[0] == user_id:
lines[i] = f"{user_id}:{new_balance}\n"
break
# Write new balance to balances.txt
with open(f'{ctx.author.id}.txt', 'w+') as f:
f.writelines(lines)
except FileNotFoundError:
embed = discord.Embed(title=f"{ctx.author.name}", description=f"You do not have a balance. Please use the `++reset` command to create one.\n\n*This command has a cooldown of 24 hours.*", color=0x000000)
await ctx.send(f"{ctx.author.mention}", embed=embed)
#daily.error
async def daily_error(ctx, error):
if isinstance(error, commands.CommandOnCooldown):
remaining_time = error.retry_after
await ctx.send(f"You need to wait {remaining_time:.0f} seconds before claiming your daily bonus again.")
I tried many different things but nothing really helped, i am hoping for help.

member is a required arg that is missing

I have a problem with my bot because I don't want to load certain variables that are specified. If you see any errors in the code, I'd be very grateful if you could help.
Error: discord.ext.commands.errors.MissingRequiredArgument: member is a required argument that is missing.
Here is code:
#!/usr/bin/python
import os
import discord
from discord.ext import commands
from discord.ext.commands import Bot
from dotenv import load_dotenv
load_dotenv()
TOKEN = os.getenv('')
bot = commands.Bot(command_prefix = "/")
client = commands.Bot(command_prefix = "/")
#bot.event
async def on_ready():
print("----------------------")
print("Zalogowano jako:")
print("Użytkownik: %s"%client.user.name)
print("ID: %s"%client.user.id)
print("----------------------")
#bot.command(name='tutorial', help='Tutorial')
async def tutorial(ctx, member: discord.Member):
message = await ctx.send('flag_gb In which language do you want to receive the instructions?')
message = await ctx.send('flag_gb W jakim języku chcesz otrzymać instrukcje?')
flag_pl = 'flag_pl'
flag_gb = 'flag_gb'
await message.add_reaction(flag_pl)
await message.add_reaction(flag_gb)
def check(reaction, user):
return user == ctx.author and str(
reaction.emoji) in [flag_pl, flag_gb]
member = ctx.author
while True:
try:
reaction, user = await client.wait_for("reaction_add", timeout=10.0, check=check)
if str(reaction.emoji) == flag_pl:
em = discord.Embed(tittle = "flag_pl", description = "**1**")
em.add_field(name = "Opcja 1", value = "Link" );
await member.send(embed=em)
if str(reaction.emoji) == flag_gb:
em = discord.Embed(tittle = "flag_gb", description = "**2**")
em.add_field(name = "Opcja 2", value = "Link" );
await member.send(embed=em)
except:
print("Wystapil blad!")
bot.run('TOKEN')
discord.ext.commands.errors.MissingRequiredArgument: member is a required argument that is missing means that you have to put the name of the member after the command (e.g. /tutorial user123 instead of /tutorial #user123). Also, an error you made is in
flag_pl = 'flag_pl'
and
flag_gb = 'flag_gb'
The emojis in discord always begin and end with :, so it should be
flag_gb = ':flag_gb:'
and
flag_pl = ':flag_pl:'

discord.py bot random image from a folder but each file can only be shown once

I'm fairly new to python and I can't seem to figure out how to make this work. any help?
I'm trying to make a command that makes my discord bot display a random image from a folder. There are around 2000 images in the folder. I want everyone to be able to use the command only once. The images are all unique and I don't want people getting the same image. how would I do this?
# Import Discord Package
import discord
from discord.ext import commands
# Client
client = commands.Bot(command_prefix='/')
# Display random image
# Command that shows Mintbot's version
#client.command(name='version')
async def version(context):
myEmbed = discord.Embed(title="Mintbot", description="Test version", color=800080)
myEmbed.add_field(name="Version Code", value="v1.0.0", inline=False)
myEmbed.set_footer(text="Work In Progress!")
await context.message.channel.send(embed=myEmbed)
# Welcome Message
#client.event
async def on_ready():
general_channel = client.get_channel(931259149260554283)
await general_channel.send('Hello, Mintbot here!')
# Disconnect message
#client.event
async def on_disconnect():
general_channel = client.get_channel(931259149260554283)
await general_channel.send('Turning Off')
# Mintbot Version - Embed
#client.event
async def on_message(message):
if message.content == 'what version is mintbot?':
general_channel = client.get_channel(931259149260554283)
myEmbed = discord.Embed(title="Mintbot", description="Test version", color=800080)
myEmbed.add_field(name="Version Code", value="v1.0.0", inline=False)
myEmbed.set_footer(text="Work In Progress!")
await general_channel.send(embed=myEmbed)
await client.process_commands(message)
# Run the client on the server
client.run('mytoken')
Make sure that you have a json file named " list.json ".
import discord
from discord.ext import commands
import os
import json
import random
# Client
client = commands.Bot(command_prefix='/')
# Reading images
directory = "images" # Change this to your folder directory without / on the end
img = []
total_img = -1
for filename in os.listdir(directory):
img += [filename]
total_img += 1
# Display random image
#client.command()
async def image(context):
with open("list.json", "r") as f:
sent = json.load(f)
if not str("sent") in sent:
sent = {}
sent["sent"] = []
with open("list.json", "w") as f:
json.dump(sent, f , indent=4)
with open("list.json", "r") as f:
sent = json.load(f)
if not str(context.author.id) in sent:
sent[str(context.author.id)] = True
with open("list.json", "w") as f:
json.dump(sent, f , indent=4)
data = sent["sent"]
random_number = None
tries = 0
while random_number == None:
tries += 1
number = random.randint(0, total_img)
if not number in data:
random_number = number
if int(tries + 1) == total_img:
await context.send("All pictures has been sent")
return
file = discord.File(f"{directory}/{img[random_number]}")
await context.send(file=file)
sent["sent"] += [random_number]
with open("list.json", "w") as f:
json.dump(sent, f , indent=4)
# Command that shows Mintbot's version
#client.command(name='version')
async def version(context):
myEmbed = discord.Embed(title="Mintbot", description="Test version", color=800080)
myEmbed.add_field(name="Version Code", value="v1.0.0", inline=False)
myEmbed.set_footer(text="Work In Progress!")
await context.message.channel.send(embed=myEmbed)
# Welcome Message
#client.event
async def on_ready():
general_channel = client.get_channel(931259149260554283)
await general_channel.send('Hello, Mintbot here!')
# Disconnect message
#client.event
async def on_disconnect():
general_channel = client.get_channel(931259149260554283)
await general_channel.send('Turning Off')
# Mintbot Version - Embed
#client.event
async def on_message(message):
if message.content == 'what version is mintbot?':
general_channel = client.get_channel(931259149260554283)
myEmbed = discord.Embed(title="Mintbot", description="Test version", color=800080)
myEmbed.add_field(name="Version Code", value="v1.0.0", inline=False)
myEmbed.set_footer(text="Work In Progress!")
await general_channel.send(embed=myEmbed)
await client.process_commands(message)
# Run the client on the server
client.run(token)

How do I get the message content of a channel in discord.py

This is my code but it is returning the message id's instead of the message content
#bot.command(name="jpg")
async def jpg_File(message):
channel = bot.get_channel(699577970117050399)
messages = await channel.history(limit=500).flatten()
print(messages)
This is what I get from printing messages: <Message id=937077040878866442 channel=<TextChannel id=699577970117050399 name='memes' position=2 nsfw=False news=False category_id=699624938583359608
You need to access the content attribute of the message object.
async def jpg_File(message):
channel = bot.get_channel(699577970117050399)
messages = await channel.history(limit=500).flatten()
print(messages)
for i in messages:
print(i.content)
#client.event
async def on_message(message: discord.Message):
channel = discord.utils.get(message.guild.text_channels, name="general")
messages = await channel.history(limit=500).flatten()
for message in messages:
if not message.attachments:
print(message.author, message.content)
else:
print(message.author, message.attachments)

AttributeError: 'NoneType' object has no attribute 'remove_roles'

So, I'm making a reaction role command and it keeps giving me the same error,I have enabled intents. members, everything I need but still it gives me the same error.I dont know why its giving me this error,maybe its a bug or somethng??. Well I hope I cant get a answer from here it only hope rn >.<.(this is just to fill the "please add more details thing..sefsdfysdhfjawsdygdefshdgf)
The code :
import discord
from discord.ext import commands
import random
from io import BytesIO
import DiscordUtils
from discord.utils import get
import os
import asyncio as asyncio
import aiohttp
import datetime
import json
intents = discord.Intents.all()
intents.members = True
client = discord.Client(intents=intents)
client = commands.Bot(command_prefix="?",case_insensitive = True)
client.remove_command("help")
#client.event
async def on_raw_reaction_add(payload):
if payload.member.bot:
pass
else:
with open('reactrole.json') as react_file:
data = json.load(react_file)
for x in data:
if x['emoji'] == payload.emoji.name:
role = discord.utils.get(client.get_guild(
payload.guild_id).roles, id=x['role_id'])
await payload.member.add_roles(role)
#client.event
async def on_raw_reaction_remove(payload):
guild = client.get_guild(payload.guild_id)
print("Guild checked.")
member = guild.get_member(payload.user_id)
print("Member checked.")
with open('reactrole.json') as react_file:
data = json.load(react_file)
for x in data:
if x['emoji'] == payload.emoji.name:
role = discord.utils.get(client.get_guild(payload.guild_id).roles, id=x['role_id'])
print("got the role")
await member.remove_roles(role)
#client.command(aliases = ['rr'])
#commands.has_permissions(administrator=True, manage_roles=True)
async def reactrole(ctx, emoji, role: discord.Role, *, message):
emb = discord.Embed(title = "REACTION ROLE !",description=message,timestamp = datetime.datetime.utcnow(),color = 0xADD8E6)
emb.set_thumbnail(url = "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQPiUxyDTBu4dkC8f3tBeOzM8b0sEnK_8iLUg&usqp=CAU")
emb.set_footer(icon_url = ctx.author.avatar_url, text = f"reactrole embed created by : {ctx.author.name}")
emb.set_image(url = "https://www.logolynx.com/images/logolynx/f8/f843b4dd5ec5dc4e56a3f5639341516a.png")
msg = await ctx.channel.send(embed=emb)
await msg.add_reaction(emoji)
with open('reactrole.json') as json_file:
data = json.load(json_file)
new_react_role = {'role_name': role.name,
'role_id': role.id,
'emoji': emoji,
'message_id': msg.id}
data.append(new_react_role)
with open('reactrole.json', 'w') as f:
json.dump(data, f, indent=4) ```
and heres the error:
Guild checked.
Member checked.
got the role
Ignoring exception in on_raw_reaction_remove
Traceback (most recent call last):
File "C:\Users\pangh\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\discord\client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "C:\Users\pangh\Desktop\Engineer\Engineer.py", line 256, in on_raw_reaction_remove
await member.remove_roles(role)
AttributeError: 'NoneType' object has no attribute 'remove_roles'
The member attribute isn't available in the on_raw_reaction_remove event.
What you can do instead is
Figure out whether to give or remove the role both in on_raw_reaction_add, when a user reacts check if they have the role, if not add if they do then remove the role. Then remove their reaction from the message. This would essentially be a toggle reaction role.
OR
Use the payload.user_id and fetch the member using await fetch_user(user_id).

Categories