Change discord.py embed field position - discord.py

Is it possible to change the position of an embed field in discord.py?
Here is my more detailed problem:
I have an embed, but I have to make it modular, which means that with a command we can either add a field or delete one. The delete command works and the add command works, but now I need to be able to change the position of the field to be the same as the position of the role (because each field corresponds to a role).
How can I do that?

We can't edit embed field's position, but we can try to add every fields in the good ordor so we don't have to edit the field's position !
Here are my codes (working):
import asyncio
import discord
from discord.ext import commands
from datetime import datetime
intents = discord.Intents.all()
bot = commands.Bot(command_prefix = "!1789", help_command = None, intents=intents)
async def get_hour():
now = ""
now = datetime.now()
hour = now.strftime("%H:%M")
return hour
async def role_members_mention(role: discord.Role, emoji):
role_str = ""
if len(role.members):
for member in role.members:
role_str += f"**|** {emoji} **➜** {member.mention}\n"
role_str[:-1]
return role_str
async def soon(role, emoji, max):
soon = f"**|** {emoji} **➜ Soon**\n" * (int(max[role.name].replace("/", "")) - len(role.members))
soon[:-1]
return soon
async def get_all_roles():
guild = bot.get_guild(966749409314504774)
global ceo_aceo_roles_dict
ceo_aceo_roles_dict = {}
ceo = discord.utils.get(guild.roles, id = 966749523949023262)
aceo = discord.utils.get(guild.roles, id = 992137775883243530)
global all_roles_dict
all_roles_dict = {}
all_roles_dict[ceo.position] = ceo
all_roles_dict[aceo.position] = aceo
ceo_aceo_roles_dict[ceo.position] = ceo
ceo_aceo_roles_dict[aceo.position] = aceo
async def update_effective():
ceo_aceo = ""
embed = discord.Embed(title = "**E͟͟͟F͟͟͟F͟͟͟E͟͟͟C͟͟͟T͟͟͟I͟͟͟F͟͟͟ S͟͟͟T͟͟͟A͟͟͟F͟͟͟F͟͟͟**. <:3446blurplecertifiedmoderator:1001403463214825542>", description = "", color = 0x000000)
max = {}
total = {}
effectif_staff_emojis = ["<:adcrown:1001400557073866762>", "<:bluesettings:1001472768161894532>", "<:diplome:1001472522811883621>", "<:5961blurpleemployee:1001403806828994570>"]
roles_staff_emojis = ["<:5961blurpleemployee:1001403806828994570>", "<:Dev:1001412860091580487>", "<:direction:1001476149051924591>", "<:bluevoicechannel:1001473637091659836", "<:direction:1001476149051924591>", "<:spideyn7:996331019735158864>", "<:logo_twitch:1005196891010629702>"]
all_roles = sorted(all_roles_dict)
ceo_aceo_roles = sorted(ceo_aceo_roles_dict)
all_roles.reverse()
ceo_aceo_roles.reverse()
x = -1
for role in all_roles:
x += 1
all_roles[x] = all_roles_dict[role]
x = -1
for role in ceo_aceo_roles:
x += 1
ceo_aceo_roles[x] = ceo_aceo_roles_dict[role]
for role in all_roles:
number = 0
for car in role.name:
if car == "‎":
number += 1
max[role.name] = "/" + str(number)
if len(role.members) >= int(max[role.name].replace("/", "")):
total[role.name] = f"🔒 **{str(len(role.members))} {max[role.name]}**"
else:
total[role.name] = f"🔓 **{str(len(role.members))} {max[role.name]}**"
message = await (await get_effective_staff_channel()).fetch_message(1059250505689337998)
for role in ceo_aceo_roles:
ceo_aceo += f"{role.mention} {total[role.name]}\n{await role_members_mention(role, effectif_staff_emojis[0])}{await soon(role, effectif_staff_emojis[0], max)}\n\n"
embed.add_field(name = "**C.E.O & A.C.E.O** <:adcrown:1001400557073866762>", value = ceo_aceo, inline = False)
embed.set_thumbnail(url = "https://media.discordapp.net/attachments/1001404772496187392/1059246720669733014/Picsart_22-10-19_21-20-35-971.jpg?width=1326&height=529")
embed.set_image(url = "https://media.discordapp.net/attachments/1001404772496187392/1059246720875241542/Picsart_22-10-13_21-14-41-363.jpg?width=618&height=618")
await message.edit(embed = embed)
async def delete_messages(ctx, number_of_message_to_delete = 1, time_to_wait = 0):
await asyncio.sleep(time_to_wait)
await ctx.channel.purge(limit=number_of_message_to_delete)
#bot.event
async def on_ready():
print(f"[{await get_hour()}] Ready !\n Username: {bot.user.name}\n----------------------------------------------------")
await get_all_roles()
await update_effective()
while True:
await asyncio.sleep(600)
await update_effective()
#bot.command()
#commands.has_permissions(administrator = True)
async def addeffectifstaff(ctx, role: discord.Role, number = 1):
await delete_messages(ctx)
role = discord.utils.get(ctx.guild.roles, id = role.id)
if role in all_roles_dict.values():
await ctx.send("Désolé mais ce rôle est déjà dans l'effectif.")
else:
ceo_aceo_roles_dict[role.position] = role
all_roles_dict[role.position] = role
await update_effective()
await ctx.send(f"Bien ! Le rôle {role.name} a été ajouté à l'effectif !")
await delete_messages(ctx, 1, 3)
print(f'[{await get_hour()}] {ctx.author.name} used the command "addeffectifstaff" to make me add the role "{role.name}" to the effective message.')
#bot.command()
#commands.has_permissions(administrator = True)
async def deleffectif(ctx, role: discord.Role):
await delete_messages(ctx)
role = discord.utils.get(ctx.guild.roles, id = role.id)
if not role in all_roles_dict.values():
await ctx.send("Désolé mais ce rôle n'est déjà pas dans l'effectif.")
else:
ceo_aceo_roles_dict.pop(role.position)
all_roles_dict.pop(role.position)
await update_effective()
await ctx.send(f"Bien ! Le rôle {role.name} a été supprimé de l'effectif !")
await delete_messages(ctx, 1, 3)
print(f'[{await get_hour()}] {ctx.author.name} used the command "deleffectif" to make me remove the role "{role.name}" to the effective message.')
bot.run(token)

Related

I need my bot to delete links and videos sent by a certain discord user

I have the link part down but it gives me a 400 Bad Request (error code: 50006): Cannot send an empty message error when i send a link the main problem is that if i try any other methods of writing this code for example i copied some code that deletes all of the messages sent in a chat but it still gives me the same error.
import discord
import responses
async def send_message(message, user_message, is_private):
try:
response = responses.get_response(user_message)
await message.author.send(response) if is_private else await message.channel.send(response)
except Exception as e:
print(e)
def run_discord_bot():
TOKEN = ''
intents = discord.Intents.default()
intents.messages = True
intents.message_content = True
client = discord.Client(intents=intents)
#client.event
async def on_ready():
print(f'{client.user} is now running!')
#client.event
async def on_message(message):
if message.author == client.user:
return
if message.author.id == 0000000000000 and message.startswith("https"):
await message.delete()
# can return here as we deleted message - no need to process anything else
return
username = message.author.name
user_message = message.content
channel = message.channel.name
print(f'{username} said: "{user_message}" ({channel})')
if user_message[0] == '?':
user_message = user_message[1:]
await send_message(message, user_message, is_private=True)
else:
await send_message(message, user_message, is_private=False)
#client.event
async def on_message(message):
if message.author == client.user:
return
username = str(message.author)
user_message = str(message.content)
channel = str(message.channel)
print(f'{username} said: "{user_message}" ({channel})')
if user_message[0] == '?':
user_message = user_message[1:]
await send_message(message, user_message, is_private=True)
else:
await send_message(message, user_message, is_private=False)
client.run('')
Turning my comments into an answer;
Firstly, you need to enable the message_content intent to be able to see message content. You will need to enable the message_content Privileged intent in the Discord developer portal as well.
intents = discord.Intents.default()
intents.messages = True
intents.message_content = True
client = discord.Client(intents=intents)
Then, there should only be one on_message event. But we can merge them.
#client.event
async def on_message(message):
if message.author == client.user:
return
if message.author.id == 0000000000000 and message.startswith("https"):
await message.delete()
# can return here as we deleted message - no need to process anything else
return
username = message.author.name
user_message = message.content
channel = message.channel.name
print(f'{username} said: "{user_message}" ({channel})')
if user_message[0] == '?':
user_message = user_message[1:]
await send_message(message, user_message, is_private=True)
else:
await send_message(message, user_message, is_private=False)
I also changed the user ID to an int - as message.author.id is an int. And changed stop of the str() calls to using the name properties as well.

im making a economy bot like owo but im getting operand errors

i cant figure out the error
it just says discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: unsupported operand type(s) for +=: 'int' and 'str'
what can i do here?
here is my code -
import discord
from discord.ext import commands
import json
import random
client = commands.Bot(command_prefix="owo ", intents=discord.Intents.all())
#client.event
async def on_ready():
print("Logged in as {} lets rock!".format(client.user))
#client.command(aliases=['c'])
async def cash(ctx):
await open_account(ctx.author)
user = ctx.author
users = await get_bank_data()
wallet_amt = users[str(user.id)]["wallet"]
await ctx.send(f"<:cowoncy:1048582461610799116> **|** {ctx.author.name} you currently have **__{wallet_amt}__** **cowoncy**!")
# await ctx.send(embed= em)
#client.command(aliases=['sm'])
async def give(ctx,member : discord.Member,amount = None):
await open_account(ctx.author)
await open_account(member)
if amount == None:
await ctx.send(f"🚫 | {ctx.author.name}, Invalid arguments! :c", delete_after=5)
return
bal = await update_bank(ctx.author)
amount = int(amount)
if amount > bal[0]:
await ctx.send(f'🚫 **|** {ctx.author.name}, you silly hooman! You don\'t have enough cowoncy!')
return
await update_bank(ctx.author,-1*amount,'wallet')
await update_bank(member,amount,'wallet')
await ctx.send(f'<:CreditCard:1048583346453757992> **|** **{ctx.author.name}** sent **{amount}')
#client.command(aliases=['d'])
async def add(ctx,member : discord.Member, amount):
await open_account(ctx.author)
await open_account(member)
bal = await update_bank(member)
await update_bank(member, amount,'wallet')
await ctx.send(f'<:CreditCard:1048583346453757992> **|** {member} **{amount}** coins has been added to your balance!')
async def open_account(user):
users = await get_bank_data()
if str(user.id) in users:
return False
else:
users[str(user.id)] = {}
users[str(user.id)]["wallet"] = 0
users[str(user.id)]["bank"] = 0
with open('mainbank.json','w') as f:
json.dump(users,f)
return True
async def get_bank_data():
with open('mainbank.json','r') as f:
users = json.load(f)
return users
async def update_bank(user,change=0,mode = 'wallet'):
users = await get_bank_data()
users[str(user.id)][mode] += change
with open('mainbank.json','w') as f:
json.dump(users,f)
bal = users[str(user.id)]['wallet'],users[str(user.id)]['bank']
return bal
client.run("TOKEN")
i was making a economy bot and i got operand error what can i do here????
any type of help will be appreciated!
also you can dm me here 𓆩†𓆪 𝐌𝐓メ ☯ɪ ᴀᴍ ɢᴏᴋᴜ☯†ᴰᶜ#0001 if you want to ask something about the code...
This is mainly because of your amount argument in the command callback. Since it doesn't have a type annotation (or typehint), it will always be a string.
Lines 62 and 63
users[str(user.id)]["wallet"] = 0
users[str(user.id)]["bank"] = 0
The values you gave them are integers, but the change argument you passed into the update_bank in lines 41, 42, and 51 is a string; you can't add a string to an integer.
This can be fixed by adding int as the type annotation to the argument, so the library will convert the user input into an integer.
Line 26
async def give(ctx,member: discord.Member, amount: int = None):
Line 46
async def add(ctx, member: discord.Member, amount: int):

discord py 'keyerror' (discord components, slash commands)

I'm trying to use the bot by adding a slash command and a button. For once, the slash command is working as intended. But every time I run the command, I get a warning like that. I'm not sure what the problem is. It's a part of the code.
Ignoring exception in on_socket_response
Traceback (most recent call last):
File "/home/yuna21724/.local/lib/python3.8/site-packages/discord/client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "/home/yuna21724/.local/lib/python3.8/site-packages/discord_buttons_plugin/__main__.py", line 17, in soclistener
await self.emit(data["data"]["custom_id"], data)
KeyError: 'custom_id'
import discord
import asyncio
import SeagamiCommandsListening
import SeagamiNotice
import SeagamiCharacter
from discord_buttons_plugin import *
from discord.ext import commands
from discord_buttons_plugin import *
from discord_slash import SlashCommand
from discord import Intents
from discord_components.client import DiscordComponents
token = ""
seagami = commands.Bot(command_prefix='.', intents = Intents.all())
slash = SlashCommand(seagami, sync_commands = True)
buttons = ButtonsClient(seagami)
#seagami.event
async def on_ready():
DiscordComponents(seagami)
await seagami.change_presence(status=discord.Status.online)
print('[알림]디스코드 봇 서비스가 시작되었습니다...',
seagami.user.name)
while True:
if SeagamiNotice.a['title'] == SeagamiNotice.b['title']:
print('')
else:
embed = discord.Embed(color = 0x2F3136)
embed.add_field(name = "```🌷로스트아크 공지사항```",
value = "``🌷로스트아크 점검 시, 봇의 기능이 제한됩니다.``", inline =
False)
embed.add_field(name = f"```👑
{SeagamiNotice.a['title']}```", value = '``📕 추가 정보를 확인하려면
아래의 바로가기 버튼을 눌러주세요.``', inline = False)
components_notice = [Button(label = "바로가기", style =
5, url = f"{SeagamiNotice.a['Link']}")]
await
seagami.get_channel(int(878004091505221643)).send(embed = embed,
components = components_notice)
await asyncio.sleep(335)
#seagami.event
async def on_member_join(member):
message_ = "<#{}>".format(str(member.id))
embed = discord.Embed(color = 0x2F3136)
embed.add_field(name = "```🌷환영해요.```", value = f"``🌷
``{message_}``님, 새가미와 아이들에 오신 걸 환영합니다.``", inline =
False)
buttons = [Button(label = "역할 받기", style = 2, custom_id =
"role")]
await seagami.get_channel(int(879993490996600852)).send(embed =
embed, components = buttons)
await
member.add_roles(seagami.get_guild(int(870543165004849152)).get_role(int(
870552731419566111)))
#slash.slash(name="입장", description="새가미 봇이 음성채널로 이동합니
다.", guild_ids=[870543165004849152])
async def in_voice(ctx: SlashCommand):
try:
if (ctx.channel.id == int(878003511961464883)):
await
SeagamiCommandsListening.commands_Listening.in_(ctx)
await ctx.reply('``🌷``새가미 봇이 음성채널로 이동하였습니
다.')
except:
await ctx.reply('``🌷``해당 명령어는 여기서 사용할 수 없습니
다.')
#slash.slash(name="퇴장", description="새가미 봇이 음성채널에서 퇴장
합니다.", guild_ids=[870543165004849152])
async def out_voice(ctx: SlashCommand):
try:
if (ctx.channel.id == int(878003511961464883)):
await
`enter code here`SeagamiCommandsListening.commands_Listening.out_(ctx)
await ctx.reply('``🌷``새가미 봇이 음성채널에서 퇴장하였습
니다.')
except:
await ctx.reply('``🌷``해당 명령어는 여기서 사용할 수 없습니
다.')
#slash.slash(name="재생", description="새가미 봇을 통해 노래를 재생할
수 있습니다.", guild_ids=[870543165004849152])
async def play_voice(ctx: SlashCommand, 링크):
try:
if (ctx.channel.id == int(878003511961464883)):
await
SeagamiCommandsListening.commands_Listening.play_(ctx, 링크)
await ctx.reply('``🌷``신청하신 노래를 ``1회``재생 합니
다.')
await buttons.send(
content = "아래의 버튼을 눌러 ``👑명령어``를 사용하실 수 있습니다.",
channel = ctx.channel.id,
components = [
ActionRow([
Button(label = "일시 정지", style = 1, custom_id = "button_pause"),
Button(label = "다시 듣기", style = 3, custom_id = "button_resume"),
Button(label = "그만 듣기", style = 4, custom_id = "button_stop")
]
)])
except:
await ctx.reply('해당 명령어는 여기서 사용할 수 없습니다.')
#slash.slash(name="반복재생", description="새가미 봇을 통해 노래를 반복 재생할 수 있습니다.", guild_ids=[870543165004849152])
async def replay_voice(ctx: SlashCommand, 링크):
try:
if (ctx.channel.id == int(878003511961464883)):
await SeagamiCommandsListening.commands_Listening.replay_(ctx, 링크)
await ctx.reply('``🌷``신청하신 노래를 반복 재생 합니다.')
await buttons.send(
content = "아래의 버튼을 눌러 ``👑명령어``를 사용하실 수 있습니다.",
channel = ctx.channel.id,
components = [
ActionRow([
Button(label = "일시 정지", style = 1, custom_id = "button_pause"),
Button(label = "다시 듣기", style = 3, custom_id = "button_resume"),
Button(label = "그만 듣기", style = 4, custom_id = "button_stop")
]
)])
except:
await ctx.reply('해당 명령어는 여기서 사용할 수 없습니다.')
#slash.slash(name="검색", description="캐릭터 정보를 검색 할 수 있습니다.", guild_ids=[870543165004849152])
async def search_(ctx: SlashCommand, 캐릭터명):
if (ctx.channel.id == int(882916863779168267)):
await SeagamiCharacter.search_info.info_(ctx, 캐릭터명)
if SeagamiCharacter.code['code'] != '100':
embed = discord.Embed(color = 0x2F3136)
embed.add_field(name = f"> ```🌷{SeagamiCharacter.name_['name']}```", value = f"> ``🌷{SeagamiCharacter.class_info['class']}``", inline = False)
embed.add_field(name = "```📕캐릭터 레벨```", value = f"``Lv. {SeagamiCharacter.Level_['Level'][8:]}``", inline = True)
embed.add_field(name = "```📕원정대 레벨```", value = f"``Lv. {SeagamiCharacter.expedition_Level['expedition'][9:]}``", inline = True)
embed.add_field(name = "```📕아이템 레벨```", value = f"``Lv. {SeagamiCharacter.item_Level['item_Level'][12:]}``", inline = True)
embed.add_field(name = "> ```🔯특성```", value = "> ``🔯펫 효과가 적용 된 특성입니다.``", inline = False)
embed.add_field(name = "```🔯치명```", value = f"``{SeagamiCharacter.ability_battle['ability_battle1']}``", inline = True)
embed.add_field(name = "```🔯특화```", value = f"``{SeagamiCharacter.ability_battle['ability_battle3']}``", inline = True)
embed.add_field(name = "```🔯제압```", value = f"``{SeagamiCharacter.ability_battle['ability_battle5']}``", inline = True)
embed.add_field(name = "```🔯신속```", value = f"``{SeagamiCharacter.ability_battle['ability_battle7']}``", inline = True)
embed.add_field(name = "```🔯인내```", value = f"``{SeagamiCharacter.ability_battle['ability_battle9']}``", inline = True)
embed.add_field(name = "```🔯숙련```", value = f"``{SeagamiCharacter.ability_battle['ability_battle11']}``", inline = True)
embed.add_field(name = "> ```👑각인```", value = "> ``👑현재 사용중인 각인입니다.``", inline = False)
try:
for count in range(8):
embed.add_field(name = "```👑각인```", value = f"``{SeagamiCharacter.ability_engrave[f'ability_engrave{count}']}``", inline = True)
except:
components_ = [[
Button(label = "바로가기", style = 5, url = f'https://lostark.game.onstove.com/Profile/Character/{캐릭터명}')
]]
await ctx.reply(f'``🌷{캐릭터명}``검색이 완료되었습니다.')
await seagami.get_channel(int(882916863779168267)).send(embed = embed, components = components_)
else:
await ctx.reply('``🌷``로스트아크 점검 중 입니다.')
SeagamiCharacter.code['code'] = '200'
else:
await ctx.reply('해당 명령어는 여기서 사용할 수 없습니다.')
#buttons.click
async def button_pause(ctx):
await SeagamiCommandsListening.commands_Listening.pause_()
await ctx.reply('``🌷``노래가 일시 정지 되었습니다.')
#buttons.click
async def button_resume(ctx):
await SeagamiCommandsListening.commands_Listening.resume_()
await ctx.reply('``🌷``노래가 다시 재생 되고 있습니다.')
#buttons.click
async def button_stop(ctx):
await SeagamiCommandsListening.commands_Listening.stop_()
await ctx.reply('``🌷``재생중인 노래를 종료 하였습니다.')
seagami.run(token)
enter image description here
enter image description here
enter image description here
enter image description here
A KeyError is raised when a mapping (dictionary) key is not found in the set of existing keys.
If you're unsure why you're getting a KeyError, here are some things you can do
Print out the dictionary to see what's in it
Check that the key is what you intend it to be
If you want to provide a default for a value when the key isn't in the dictionary, you can use dict.get which defaults to None
>>> person["pets"]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'pets'
>>> person.get("pets")
>>> person.get("pets", [])
[]
Docs:
https://docs.python.org/3/library/exceptions.html#KeyError%3E
https://docs.python.org/3/library/stdtypes.html#dict.get%3E
Helpful link: https://realpython.com/python-keyerror/%3E
I believe the cause of your error was the 3rd party package you installed called discord_buttons_plugin, which as far as I can tell requires you to add a custom_id to all buttons except the ButtonType().Link. In your _search command, you've forgot to add it, which causes an error in the package's code. Try adding a custom_id to the button there.
Long Story Short
Try adding a custom_id in your button component in the _search command.

Error Implementing free dictionary Api in discord.py

I am trying to implement this api but the code says error every single time.
My code so far:
#client.command()
async def mean(ctx,word):
response = requests.get(f"https://api.dictionaryapi.dev/api/v2/entries/en/{word}")
if response.status_code == 404:
await ctx.send("No such word")
return
else:
wordx = response.json()
the_dictionary = wordx[0]
meanings = the_dictionary['meanings']
definitions = meanings[0]
definition = definitions['definitions']
meaningg = definition[0]
meaning = meaningg['definition']
example = meaningg.get('example',['None'])
synonymslist = meaningg.get("synonyms",['None'])
if isinstance(synonymslist,str):
synonymslist = [synonymslist]
pass
synonyms = ','.join(synonymslist)
deffinal= discord.Embed(title=f"`{word.upper()}`")
deffinal.add_field(name = "Definition", value=f"{meaning}")
deffinal.add_field(name = 'Example', value = f"{example}")
deffinal.add_field(name = "Synonyms", value = f"{synonyms}")
await ctx.channel.send(embed = deffinal)
Here is the error message:
Your error does not come from the API call to the dictionary api, but rather from your call to the discord api.
The error message says discord.errors.HTTPException: [...] In embed.fields.2.value: This field is required.
So the error comes from an empty field in your embed! The field has index 2 so it is actually the third field (Synonyms) which is causing the problem.
You can simply check if a string is empty, before even adding the field. And if it is empty, just don't add it.
deffinal= discord.Embed(title=f"`{word.upper()}`")
if meaning:
deffinal.add_field(name = "Definition", value=f"{meaning}")
if example:
deffinal.add_field(name = 'Example', value = f"{example}")
if synonyms:
deffinal.add_field(name = "Synonyms", value = f"{synonyms}")
#client.command()
async def mean(ctx,word):
response = requests.get(f"https://api.dictionaryapi.dev/api/v2/entries/en/{word}")
if response.status_code == 404:
await ctx.send("No such word")
return
else:
wordx = response.json()
the_dictionary = wordx[0]
meanings = the_dictionary['meanings']
definitions = meanings[0]
definition = definitions['definitions']
meaningg = definition[0]
meaning = meaningg['definition']
example = meaningg.get('example',['None'])
synonymslist = meaningg.get("synonyms",['None'])
if isinstance(synonymslist,str):
synonymslist = [synonymslist]
pass
synonyms = ','.join(synonymslist)
deffinal= discord.Embed(title=f"`{word.upper()}`")
if meaning:
deffinal.add_field(name = "Definition", value=f"{meaning}")
if example:
deffinal.add_field(name = 'Example', value = f"{example}")
if synonyms:
deffinal.add_field(name = "Synonyms", value = f"{synonyms}")
await ctx.channel.send(embed = deffinal)
Adding to itzFlubby answer, using requests will be blocking read more which means if you block for too long then your bot will freeze since it has not stopped the function’s execution at that point to do other things.
Here is the final code, also I changed the format a bit to make it easier to read.
# import aiohttp
#bot.command()
async def mean(ctx, word):
async with aiohttp.ClientSession() as session:
async with session.get(f"https://api.dictionaryapi.dev/api/v2/entries/en/{word}") as r:
if r.status == 200:
info = await r.json()
else:
return await ctx.reply("No such word")
the_dictionary = info[0]['meanings'][0]['definitions'][0]
definition = the_dictionary.get('definition')
example = the_dictionary.get('example')
synonymslist = the_dictionary.get("synonyms")
# if only one synonym is avaliable
if isinstance(synonymslist, str):
synonymslist = [synonymslist]
synonyms = '\n'.join(synonymslist)
deffinal = discord.Embed(title=f"`{word.upper()}`")
if definition:
deffinal.add_field(name="Definition", value=f"```{definition}```")
if example:
deffinal.add_field(name='Example', value=f"```{example}```")
if synonyms:
deffinal.add_field(name="Synonyms", value=f"```{synonyms}```")
await ctx.reply(embed=deffinal)

How do I lower case the response discord.py

So basicly the person is trying to guess whats the name of the anime! What I want it to do is to ingore the case sentativity! How can I do that? Here is the code:
#client.command()
async def work(ctx):
await open_account(ctx.author)
users = await get_bank_data()
user = ctx.author
def check(m):
return m.author.id == ctx.author.id
Question1 = 'https://upload.wikimedia.org/wikipedia/en/thumb/d/dc/DARLING_in_the_FRANXX%2C_second_key_visual.jpg/220px-DARLING_in_the_FRANXX%2C_second_key_visual.jpg'
Question2 = 'http://www.j1studios.com/wordpress/wp-content/uploads/Trinity-Seven-Header-001-20160707.jpg'
Question3 = 'https://www.animenewsnetwork.com/hotlink/images/encyc/A18170-2511174083.1466822675.jpg'
Question4 = 'https://www.animenewsnetwork.com/hotlink/images/encyc/A16344-911899268.1425205899.jpg'
Question5 = 'https://www.theanimedaily.com/wp-content/uploads/2020/06/20061004422210.jpg'
Question6 = 'https://th.bing.com/th/id/OIP.zvtbvP4JZNrrlAKPnclMpwHaEK?pid=Api&rs=1&adlt=strict'
Question7 = 'https://mangathrill.com/wp-content/uploads/2020/01/pjimage-1-4.jpg'
Question8 = 'https://th.bing.com/th/id/OIP.xV_2srfdOhEre9Vua-u6zAHaFb?pid=Api&rs=1&adlt=strict'
Question9 = 'https://img1.looper.com/img/gallery/the-untold-truth-of-hunter-x-hunter/intro-1591800144.jpg'
Question10 = 'https://i1.wp.com/static.anidub.com/blog/2014/09/Seirei-Tsukai-no-Blade-Dance.jpg'
questionlist = [Question1, Question2, Question3, Question4, Question5, Question6, Question7, Question8, Question9, Question10]
question = random.choice(questionlist)
await ctx.send("What is the title name of this anime?")
await asyncio.sleep(1)
await ctx.send(question)
msg = await client.wait_for('message', check=check)
await msg.lower()
if question == Question1:
if msg.content == "darling in the franxx":
earnings = random.randrange(300, 500)
await ctx.send(f"You did good! You got an earning of **{earnings}** coins!")
else:
earnings = random.randrange(0, 200)
await ctx.send(f"Did you even try? You got **{earnings}** coins!")
msg = await client.wait_for('message', check=check) returns you the discord.Message class. And discord.Message has no attribute lower(). But it has content, content returns the string value of the message.
And also await msg.lower() is a weird usage, it's not a coroutine so you can't await it.
So you can simply do:
msg = await client.wait_for('message', check=check)
msg_content = msg.content.lower()
if question == Question1:
if msg_content == "darling in the franxx":
earnings = random.randrange(300, 500)
await ctx.send(f"You did good! You got an earning of **{earnings}** coins!")
else:
earnings = random.randrange(0, 200)
await ctx.send(f"Did you even try? You got **{earnings}** coins!")
And also, I suggest you to put questions and question list out of the command, it becomes more optimized.

Resources