What I'm trying to do: Learning to make a proper help menu for my discord.py bot by having the ctx.message.author react to the message with the reactions given. The bot checks if they've been reacted to, then edits the message. If the ctx.message.author un-reacts, it goes back to the first menu (menuu).
Problem(s): I'm not sure how to loop through this until the timeout runs out. I'm also not sure how to check if the user un-reacts to the message.
Error(s): No errors.
#client.command()
async def menuu(ctx):
#what reaction goes where menuu
menuu = discord.Embed(title="menuu", color=0x8d78d9)
menuu.add_field(name="Topics: ", value="React with <:oneone:772681764321099827>", inline=False)
menuu.add_field(name="Games: ", value="React with <:twotwo:772681764271423528>", inline=False)
menuu.add_field(name="Misc: ", value="React with <:threethree:772681763939024897>", inline=False)
menuu.set_footer(text=f"Ensure you drink some water today, you're doing so well {ctx.message.author}")
#topics menuu
topics = discord.Embed(title="Topics", color=0x8d78d9)
topics.add_field(name="`bl!topic`: ", value="Friend makers and ice breakers", inline=False)
topics.add_field(name="`bl!debate`: ", value="menuu not complete sorry haha")
topics.set_footer(text="Never forget to believe in yourself, because I do!")
#game menuu
games = discord.Embed(title="Games", color=0x8d78d9)
games.add_field(name="`nothing here`: ", value="Technically there is but still", inline=False)
games.set_footer(text="Eat some food, take a nap, good luck on the journey ahead")
#misc menuu
misc = discord.Embed(title="Misc", color=0x8d78d9)
misc.add_field(name="`miscmimscimc`: ", value="aeaeaeaeaeaeeae", inline=False)
misc.set_footer(text="You look lovely today, you're rocking this look")
msg = await ctx.send(embed=menuu)#send message
#add reactions things
await msg.add_reaction("<:oneone:772681764321099827>")
await msg.add_reaction("<:twotwo:772681764271423528>")
await msg.add_reaction("<:threethree:772681763939024897>")
await msg.add_reaction("<:stop:773054889685024768>")
try:
def check(reaction, user):
return user == ctx.message.author and str(reaction.emoji) in ["<:oneone:772681764321099827>","<:twotwo:772681764271423528>","<:threethree:772681763939024897>"]
reaction, user = await client.wait_for("reaction_add", timeout=60, check=check)
if str(reaction.emoji) == "<:oneone:772681764321099827>":
await msg.edit(embed=topics)
await msg.remove_reaction("<:oneone:772681764321099827>", ctx.message.author)
if str(reaction.emoji) == "<:twotwo:772681764271423528>":
await msg.edit(embed=games)
await msg.remove_reaction("<:twotwo:772681764271423528>", ctx.message.author)
if str(reaction.emoji) == "<:threethree:772681763939024897>":
await msg.edit(embed=misc)
await msg.remove_reaction("<:threethree:772681763939024897>", ctx.message.author)
if str(reaction.emoji) == "<:stop:773054889685024768>":
await msg.edit(embed=menuu)
await msg.remove_reaction("<:stop:773054889685024768>", ctx.message.author)
except asyncio.TimeoutError:
await ctx.send("Time has run out, message no work now")
```
I've created an easy enough to use 'book-manager'. If you put all of your menuus into a list called pages you can use this function:
async def createbook(bot, ctx, title, pages, **kwargs):
header = kwargs.get("header", "") # String
results = kwargs.get("results", 0) # Int
pagenum = 1
def get_results():
results_min = (pagenum - 1) * 8 + 1
if pagenum == len(pages): results_max = results
else: results_max = pagenum * 8
return f"Showing {results_min} - {results_max} results out of {results}"
pagemax = len(pages)
if results:
header = get_results()
if len(pages) == 0: pagemax = 1
embed = discord.Embed(title=title, description=f"{header}\n\n{pages[pagenum - 1]}", colour=0xF42F42)
embed.set_footer(text=f"Page {pagenum}/{pagemax}", icon_url=fboturl)
msg = await ctx.send(embed=embed)
await msg.add_reaction("⬅️")
await msg.add_reaction("➡")
def check(reaction, user):
return user == ctx.author and str(reaction.emoji) in ["⬅️", "➡"]
while True:
try:
reaction, user = await bot.wait_for("reaction_add", timeout = 60, check=check)
await msg.remove_reaction(reaction, user)
if str(reaction.emoji) == "⬅️":
pagenum -= 1
if pagenum < 1: pagenum = len(pages)
elif str(reaction.emoji) == "➡":
pagenum += 1
if pagenum > len(pages): pagenum = 1
header = get_results() if results else header
if str(reaction.emoji) == "⬅️" or str(reaction.emoji) == "➡":
embed = discord.Embed(title=title, description=f"{header}\n\n{pages[pagenum - 1]}", colour=0xF42F42)
embed.set_footer(text=f"Page {pagenum}/{len(pages)}", icon_url=fboturl)
await msg.edit(embed=embed)
except:
header = get_results() if results else header
embed = discord.Embed(title="FBot Server Status", description=f"{header}\n\n{pages[pagenum - 1]}", colour=0xF42F42)
embed.set_footer(text=f"Request timed out", icon_url=fboturl)
await msg.edit(embed=embed)
break
(I avoid using numbers purely because books with more than 10 pages are annoying to manage)
So after a really long time of trial and error, I have figured out my own method based off of Judev1's create-book thing. I incorporated the way the page number changes, as well as the wait_for and time out things.
#client.command(aliases=["help"])
async def menuu(ctx):
#first just giving all the embeds a purpose and a place to exist
user = ctx.author
menuu = discord.Embed(title="Help Menuu", color=0x8d78d9)
menuu.add_field(name="How to navigate : ", value="```Use the arrow reactions below to navigate this menuu```", inline=False)
menuu.add_field(name="How to invite bot : ", value="```Use bl!invite to invite this bot and join our support server!```", inline=True)
menuu.set_footer(text=f"Ensure you drink some water today, you're doing so well {ctx.message.author}")
#topics menuu
topics = discord.Embed(title="Topics", color=0x8d78d9)
topics.add_field(name="bl!topic : ", value="```Friend makers and ice breakers```", inline=False)
topics.add_field(name="bl!debate : ", value="```Sends a debate topic (Trigger Warning: Some topics may trigger certain individuals. Please tread with caution when using this command)```", inline=False)
topics.add_field(name="bl!wyr : ", value="```Would you rather questions```", inline = False)
topics.add_field(name="bl!place : ", value="```So many places in the world, so little time```", inline = True)
topics.set_footer(text="Never forget to believe in yourself, because I do!")
#game menuu
games = discord.Embed(title="Games", color=0x8d78d9)
games.add_field(name=f"bl!powpow `#blitz` : ", value="```Who will win? You, or that person you mentioned?```", inline=False)
games.add_field(name=f"bl!battle `#blitz` : ", value="```Basically powpow but less work```", inline=True)
games.set_footer(text="Eat some food, take a nap, good luck on the journey ahead")
#pics menuu
pics = discord.Embed(title="Picture Things:tm:", color=0x8d78d9)
pics.add_field(name="bl!avatar `#blitz` : ", value="```Get the profile picture of the mentioned person```", inline=False)
pics.add_field(name="bl!hug `#blitz` : ", value="```Hugs, many hug gifs :)```", inline= True)
pics.add_field(name="bl!slap `#blitz` : ", value="```Slap whoever you want without the pain```", inline=False)
pics.set_footer(text="You look lovely today, you're rocking this look")
##send message##
msg = await ctx.send(embed=menuu)
pages = 1 #page it's currently on
left = "<a:totheleft:767541559440572427>" #left arrow reaction
right = "<a:totheright:767541574287884309>" #right arrow reaction
await msg.add_reaction(left) #add reaction to send menuu
await msg.add_reaction(right) #and again
def check(reaction, user): #checking if user is author and the reaction is either left or right (as defined earlier)
return user == ctx.author and str(reaction.emoji) in [left, right]
while True:
try:
reaction, user = await client.wait_for("reaction_add", timeout = 120, check=check)
await msg.remove_reaction(reaction, user)
if str(reaction.emoji) == left:
pages = pages - 1
if pages < 1:
pages = 4 #if pages is less than 1, go straight to 4
if str(reaction.emoji) == right:
pages = pages + 1
if pages > 4:
pages = 1 #if pages is more than 4, go back to 1
#if this is the page number, edit so it's this embed instead
if pages == 1:
await msg.edit(embed=menuu)
elif pages == 2:
await msg.edit(embed=topics)
elif pages == 3:
await msg.edit(embed=games)
elif pages == 4:
await msg.edit(embed=pics)
except: #timeout error handling
embed = discord.Embed(title="Run command again to use", description="Have a good day {ctx.author.display_name}! `bl!menuu`")
await msg.edit(embed=embed)
break
Related
I have been using this function before Discord forced everyone to switch to slash commands. Now, when I move it to slash command format, it doesn't work.
What used to work, now doesn't. I'm using this inside a cogs file. If that helps, great. If not, sorry.
async def combat_shop(self, ctx):
member_id = ctx.author.id
await utils.refresh_active(ctx, member_id, ctx.author.name)
bancheck = await utils.ban_check(ctx)
if bancheck is True:
await ctx.send("<:BanHammer_:957349442573467708>┃You've been banned from using Daddy Bot. Take this to the support server: <https://discord.gg/SbMyaxWFr9> \nRemember: Being rude/commanding ***will not*** do you any good. Be kind and respectful.")
return
await utils.leveling_system(ctx, 5)
dec = "buy: `daddy buy >id<`\ndismantle: `daddy dismantle >id<`\n\n`r-combat`┃Random Combat Item┃<:Dollar:952432145270452244> 250k"
page1CS = embed = discord.Embed(title = "**The Weapon Store<:D_Axe:998668619561046077>**", description = f"{dec}", color = discord.Colour.teal())
embed.add_field(name="Basic Weapons", value="`long_sword`┃<:D_LongSword:1001951918706397235> **Long Sword**┃<:D_WeaponParts:998668591174000690> 10\n`short_sword`┃<:D_ShortSword:998668579207663616>**Short Sword**┃<:D_WeaponParts:998668591174000690> 20\n`halberd`┃<:D_Halberd:1001951880215277738>**Halberd**┃<:D_WeaponParts:998668591174000690>50\n`axe`┃<:D_Axe:998668619561046077>**Axe**┃<:D_WeaponParts:998668591174000690> 35\n`gun`┃<:D_Gun:1002626237618995351>**Gun**┃<:D_WeaponParts:998668591174000690> 20\n`star_blaster`┃<:D_StarBlaster:1001951963828715641>**Star Blaster**┃<:D_WeaponParts:998668591174000690> 150", inline=True)
embed.add_field(name="Patreon Weapons", value="`lightning_spear`┃<:D_LightningSpear:998668565408403526>**Lightning Spear**┃<:D_WeaponParts:998668591174000690> 50\n`potato_bomb`┃<:D_PotatoBomb:998668568755445830>**Potato Bomb**┃<:D_WeaponParts:998668591174000690> 100\n`shadow_dagger`┃<:D_ShadowDagger:998668575747358810>**Shadow Dagger**┃<:D_WeaponParts:998668591174000690> 50", inline=True)
embed.set_footer(text="page 1/5")
page2CS = embed = discord.Embed(title = "**The Armor Store<:D_ShadowHelmet:998668576930152508>**", description = f"{dec}", color = discord.Colour.teal())
embed.add_field(name="Basic Armor Sets", value="`speedy_helmet`┃<:D_SpeedyHelmet:998668582777008238>**Speedy Helmet**┃<:D_ArmorParts:998668617866559519> 15\n`speedy_armor`┃<:D_SpeedyArmor:998668581917184090>**Speedy Armor**┃<:D_ArmorParts:998668617866559519> 20\n`turtle_shell_helmet`┃<:D_TurtleShellHelmet:998668588107968522>**Turtle Helmet**┃<:D_ArmorParts:998668617866559519>25\n`turtle_shell_armor`┃<:D_TurtleShellArmor:998668586749010081>**Turtle Armor**┃<:D_ArmorParts:998668617866559519> 30\n`leather_helmet`┃<:D_LeatherHelmet:998668559632842873>**Leather Helmet**┃<:D_ArmorParts:998668617866559519> 20\n`leather_armor`┃<:D_LeatherArmor:998668558299041812>**Leather Armor**┃<:D_ArmorParts:998668617866559519> 25", inline=True)
embed.add_field(name="Patreon Armor Sets", value="`shadow_helmet`┃<:D_ShadowHelmet:998668576930152508>**Shadow Helmet**┃<:D_ArmorParts:998668617866559519> 50\n`shadow_armor`┃<:D_ShadowArmor:998668574631661608>**Shadow Armor**┃<:D_ArmorParts:998668617866559519> 60\n`potato_helmet`┃<:D_PotatoHelmet:998668571683078225>**Potato Helmet**┃<:D_ArmorParts:998668617866559519> 150\n`potato_armor`┃<:D_PotatoArmor:998668567673323590>**Potato Armor**┃<:D_ArmorParts:998668617866559519> 200\n`zeus_helmet`┃<:D_ZeusHelmet:998668593363423322>**Zeus Helmet**┃<:D_ArmorParts:998668617866559519> 50\n`zeus_armor`┃<:D_ZeusArmor:998668592126115973>**Zeus Armor**┃<:D_ArmorParts:998668617866559519> 60", inline=True)
embed.set_footer(text="page 2/5")
page3CS = embed = discord.Embed(title = "**The Secondary Store<:D_HealingPotion:998668556856197291>**", description = f"{dec}", color = discord.Colour.teal())
embed.add_field(name="Basic Secondary", value="`strength_staff`┃<:D_StrengthStaff:998668583959810088>**Strength Staff**┃<:D_WeaponParts:998668591174000690> 50\n`defense_staff`┃<:D_DefenseStaff:998668620823531531>**Defense Staff**┃<:D_WeaponParts:998668591174000690> 50\n`shield`┃<:D_Shield:998668578091970580>**Shield**┃<:D_WeaponParts:998668591174000690> 50", inline=True)
embed.add_field(name="Patreon Secondary", value="`walking_cane`┃<:D_WalkingCane:998668589747945562>**Walking Cane**┃<:D_WeaponParts:998668591174000690> 75\n`potato_buddy`┃<:D_PotatoBuddy:998668569946620045>**Potato Buddy**┃<:D_WeaponParts:998668591174000690> 150\n`thunder_rod`┃<:D_ThunderRod:998668564196241418>**Thunder Rod**┃<:D_WeaponParts:998668591174000690> 75", inline=True)
embed.set_footer(text="page 3/5")
page4CS = embed = discord.Embed(title = "**The Special Store<:D_PotatoParty:998668573004284008>**", description = f"{dec}", color = discord.Colour.teal())
embed.add_field(name="Basic Specials", value="`earthquake`┃<:D_Earthquake:998668623512084560>**Earthquake**┃<:Dollar:952432145270452244> 1m\n`life_steal`┃<:D_LifeSteal:998668560706572458>**Life Steal**┃<:Dollar:952432145270452244> 1m", inline=True)
embed.add_field(name="Patreon Specials", value="`nightmare`┃<:D_Nightmare:998668566146592795>**Nightmare**┃<:Dollar:952432145270452244> 1m\n`potato_party`┃<:D_PotatoParty:998668573004284008>**Potato Party**┃<:Dollar:952432145270452244> 1m\n`thunderstorm`┃<:D_ThunderStorm:998675226743275530>**Thunderstorm**┃<:Dollar:952432145270452244> 1m\n`healing_orb`┃<:D_HealingOrb:998668625097543750>**Healing Orb**┃<:Dollar:952432145270452244> 1m", inline=True)
embed.set_footer(text="page 4/5")
page5CS = embed = discord.Embed(title = "**The Items Store<:D_HealingPotion:998668556856197291>**", description = f"{dec}", color = discord.Colour.teal())
embed.add_field(name="Items", value="`healing_potion`┃<:D_HealingPotion:998668556856197291>**Healing Potion**┃<:Dollar:952432145270452244> 50k\n`bomb`┃<:D_Bomb:1001952068837330984>**Bomb**┃<:Dollar:952432145270452244> 50k\n`damage_upgrade`┃<:D_DamageUpgradeStone:998668585251651735>**Damage Upgrade**┃<:Dollar:952432145270452244> 250k\n`defense_upgrade`┃<:D_DefenseUpgradeStone:998668621951795281>**Defense Upgrade**┃<:Dollar:952432145270452244> 250k\n`speed_upgrade`┃<:D_SpeedUpgradeStone:998668580902150144>**Speed Upgrade**┃<:Dollar:952432145270452244> 250k")
embed.set_footer(text="page 5/5")
test_pages_shop = [page1CS, page2CS, page3CS, page4CS, page5CS]
buttons_shop = ["◀", "▶"]
current_shop = 0
msg = await ctx.send(embed=test_pages_shop[current_shop])
for button in buttons_shop:
await msg.add_reaction(button)
while True:
try:
reaction, user = await self.bot.wait_for("reaction_add", check=lambda reaction, user: user == ctx.author and reaction.message == msg and reaction.emoji in buttons_shop, timeout=25)
except asyncio.TimeoutError:
await msg.clear_reactions()
break
return
else:
previous_pages = current_shop
if reaction.emoji == "◀":
if current_shop > 0:
current_shop -= 1
elif reaction.emoji == "▶":
if current_shop < len(test_pages_shop) - 1:
current_shop += 1
for button in buttons_shop:
await msg.remove_reaction(button, ctx.author)
if current_shop != previous_pages:
await msg.edit(embed=test_pages_shop[current_shop])
Keep in mind that I removed the #cog_ext.cog_slash part because that's not the issue. I've been doing testing beforehand and I found that it gets stuck on the #cog_ext.cog_slash part.
To convert this command, you'll need these changes to the function definition
#app_commands.command(name="combat_shop", description="The Combat shop")
async def combat_shop(self, interaction : discord.Interaction):
You'll also need to adapt your code to deal with a discord.Interaction instead of a discord.ext.commands.Context.
That includes switching:
ctx.send to interaction.response.send_message
Switching the msg.edit to one of the interaction edits (e.g. interaction.edit_original_response)
ctx.author to interaction.user
I found out the issue after another hour of testing. In slash commands, it has to be reaction.message.id == msg.id for that check to work.
I'm going to need some help with this, as I don't understand it.
I have a code which turns the page of what the bots says through reactions, the code is below:
client.command()
async def help2(ctx):
contents = ["This is page 1!", "This is page 2!", "This is page 3!", "This is page 4!"]
pages = 4
cur_page = 1
message = await ctx.send(f"Page {cur_page}/{pages}:\n{contents[cur_page-1]}")
# getting the message object for editing and reacting
await message.add_reaction("◀️")
await message.add_reaction("▶️")
def check(reaction, user):
return user == ctx.author and str(reaction.emoji) in ["◀️", "▶️"]
# This makes sure nobody except the command sender can interact with the "menu"
while True:
try:
reaction, user = await client.wait_for("reaction_add", timeout=60, check=check)
# waiting for a reaction to be added - times out after x seconds, 60 in this
# example
if str(reaction.emoji) == "▶️" and cur_page != pages:
cur_page += 1
await message.edit(content=f"Page {cur_page}/{pages}:\n{contents[cur_page-1]}")
await message.remove_reaction(reaction, user)
elif str(reaction.emoji) == "◀️" and cur_page > 1:
cur_page -= 1
await message.edit(content=f"Page {cur_page}/{pages}:\n{contents[cur_page-1]}")
await message.remove_reaction(reaction, user)
else:
await message.remove_reaction(reaction, user)
# removes reactions if the user tries to go forward on the last page or
# backwards on the first page
except asyncio.TimeoutError:
await message.delete()
break
# ending
So this is the code, however I want to make it an embed that can be used as a help page with reactions (setfooter and author too)!
Sorry as I'm new at this!
I'm not particularly good at python either but I found this worked for me:
client = commands.Bot(command_prefix = "!", help_command = None)
#client.command()
async def help(ctx):
pages = 4
cur_page = 1
contents = ["This is page 1!", "This is page 2!", "This is page 3!", "This is page 4!"]
embed=discord.Embed(title="Help page", description=(f"Page {cur_page}/{pages}:\n{contents[cur_page-1]}"), color=0x00ffc8)
embed.set_author(name=ctx.author.display_name,icon_url=ctx.author.avatar_url)
embed.set_footer(text="footer")
message = await ctx.send(embed=embed)
# getting the message object for editing and reacting
await message.add_reaction("◀️")
await message.add_reaction("▶️")
def check(reaction, user):
return user == ctx.author and str(reaction.emoji) in ["◀️", "▶️"]
# This makes sure nobody except the command sender can interact with the "menu"
while True:
try:
reaction, user = await client.wait_for("reaction_add", timeout=60, check=check)
# waiting for a reaction to be added - times out after x seconds, 60 in this
# example
if str(reaction.emoji) == "▶️" and cur_page != pages:
cur_page += 1
new_embed=discord.Embed(title="Help page", description=(f"Page {cur_page}/{pages}:\n{contents[cur_page-1]}"), color=0x00ffc8)
new_embed.set_author(name=ctx.author.display_name,icon_url=ctx.author.avatar_url)
new_embed.set_footer(text="footer")
await message.edit(embed=new_embed)
await message.remove_reaction(reaction, user)
elif str(reaction.emoji) == "◀️" and cur_page > 1:
cur_page -= 1
new_embed=discord.Embed(title="Help page", description=(f"Page {cur_page}/{pages}:\n{contents[cur_page-1]}"), color=0x00ffc8)
new_embed.set_author(name=ctx.author.display_name,icon_url=ctx.author.avatar_url)
new_embed.set_footer(text="footer")
await message.edit(embed=new_embed)
await message.remove_reaction(reaction, user)
else:
await message.remove_reaction(reaction, user)
# removes reactions if the user tries to go forward on the last page or
# backwards on the first page
except asyncio.TimeoutError:
await message.delete()
break
# ending
I'm making a poll command for my discord bot. I use emojis to vote for poll options.
I want my bot to show the results of the poll after some period of time (I didn't implement timeout yet). But to do it I need to count each emoji. Is there anyway of doing it?
My code so far:
#bot.command(name='poll')
async def poll(ctx, question, option1 = None, option2 = None):
if option1 == None and option2 == None:
embed = discord.Embed(
title="Poll",
description=f"{question}",
color = discord.Color.blue()
)
msg = await ctx.channel.send(embed=embed)
message = await ctx.channel.fetch_message(msg.id)
await message.add_reaction("👍")
await message.add_reaction("👎")
embed = discord.Embed(
title="Poll",
description=f"{question}",
color=discord.Color.blue()
)
embed.add_field(name=f"{option1}", inline=False)
embed.add_field(name=f"{option2}", inline=False)
msg = await ctx.channel.send(embed=embed)
message = await ctx.channel.fetch_message(msg.id)
await message.add_reaction("👍")
await message.add_reaction("👎")
Emoji are just characters, like any other:
>>> st="The quick brown fox👍 jumped over the lazy dog👍"
>>> st.count("👍")
2
and in case you don't have a fancy emoji-keyboard (ord() is the inverse of chr()):
>>> ord("👍")
128077
>>> ord("👎")
128078
Update - try:
for reaction in message.reactions:
if reaction.emoji == "👍":
counts["👍"] += reaction.count
based on these:
https://discordpy.readthedocs.io/en/stable/api.html#discord.Message.reactions
https://discordpy.readthedocs.io/en/stable/api.html#discord.Reaction
#bot.command()
async def suggest(ctx,*,suggestion):
# await ctx.channel.purge(limit = 1)
emojis = ['✅','❌']
channel = bot.get_channel(xxxxxxxxxxxx)
await ctx.send('Your Suggestion has been sent, will be reviewed by admin shortly')
suggestEmbed = discord.Embed(colour=0x28da5b)
suggestEmbed=discord.Embed(title="Suggestion Bot", description="Please mark ✅ or ❌ depending on whether you want to take this suggestion or not", color=0x28da5b)
message = await channel.send(embed = suggestEmbed)
await message.add_reaction('✅')
await message.add_reaction('❌')
sendEmbed = discord.Embed(colour = 0x28da5b)
sendEmbed.add_field(name = 'New Suggestion!', value = f'{suggestion}')
try:
reaction, user = await bot.wait_for('reaction_add')
while reaction.message == message:
if str(reaction.emoji) == "✅":
await ctx.send("🚀🚀🚀 Yay! Your suggestion has been approved, We thank you for your valuable time!")
await ctx.send("Your Suggestion was: ")
message1 = await ctx.send(embed = sendEmbed)
await channel.send("The above suggestion has been approved, this post will no longer be active")
return
if str(reaction.emoji) == "❌":
await ctx.send("🙇♀️🙇♀️ Sorry! Your suggestion has not been approved, We thank you for your valuable time!")
await ctx.send("Your Suggestion was: ")
message1 = await ctx.send(embed = sendEmbed)
await channel.send("The above suggestion has not been approved, this post will no longer be active")
return
except Exception:
return
I want my code to suggest something, it will go to another channel, where the admin would have the access to either click on the tick or wrong button. when tick clicks, it should send that suggestion has been accepted. it runs fine for the first time, but when I run it for the second time, it doesn't require interaction, it automatically clicks on random emoji out of the 2 and sends it back.
since you haven't defined a check, it's also taking the bot's input of reactions. defined a check function
def check (reaction, user):
return not user.bot and message == reaction.message #checks if the reacting user isn't a bot (inside the command)
#use this with check kwarg inside wait_for
reaction, user = await bot.wait_for('reaction_add', check=check)
final code:
bot.remove_command("suggest")
#bot.command()
async def suggest(ctx,*,suggestion):
# await ctx.channel.purge(limit = 1)
emojis = ['✅','❌']
channel = ctx.channel
await ctx.send('Your Suggestion has been sent, will be reviewed by admin shortly')
suggestEmbed = discord.Embed(colour=0x28da5b)
suggestEmbed=discord.Embed(title="Suggestion Bot", description="Please mark ✅ or ❌ depending on whether you want to take this suggestion or not", color=0x28da5b)
message = await channel.send(embed = suggestEmbed)
await message.add_reaction('✅')
await message.add_reaction('❌')
sendEmbed = discord.Embed(colour = 0x28da5b)
sendEmbed.add_field(name = 'New Suggestion!', value = f'{suggestion}')
def check (reaction, user):
return not user.bot and message == reaction.message
try:
reaction, user = await bot.wait_for('reaction_add', check=check)
while reaction.message == message:
if str(reaction.emoji) == "✅":
await ctx.send("🚀🚀🚀 Yay! Your suggestion has been approved, We thank you for your valuable time!")
await ctx.send("Your Suggestion was: ")
message1 = await ctx.send(embed = sendEmbed)
await channel.send("The above suggestion has been approved, this post will no longer be active")
return
if str(reaction.emoji) == "❌":
await ctx.send("🙇♀️🙇♀️ Sorry! Your suggestion has not been approved, We thank you for your valuable time!")
await ctx.send("Your Suggestion was: ")
message1 = await ctx.send(embed = sendEmbed)
await channel.send("The above suggestion has not been approved, this post will no longer be active")
return
except Exception:
return
i am working on a python bot but i've come across a syntax error with ELIF and IF statements, and ive tried fiddling around changing the elif around, and adding an else instead n such, but i can't get it to work, so that's why i come on here to see if anyone has a solution for my problem, thanks.
My code:
#bot.command()
async def linkdiscord(ctx, token):
author = ctx.message.author
author2 = str(ctx.message.author)
discordid = ctx.message.author.id
response = json.loads(requests.get(forumurl + f"/api?action=linkdiscord&key=SECRET&token={token}&discordid={discordid}").text)
if response["status"] == 200:
embed=discord.Embed(title="Linker System", color=0xcd65f0)
embed.add_field(name="Linked Discord", value="Yes", inline=True)
embed.set_footer(text="Successfully linked " + author2 + " to forum account: " + response["username"])
elif response["status"] == 400:
embed=discord.Embed(title="Linker System", color=0xff0000)
embed.add_field(name="Unexpected error", value="True", inline=True)
embed.add_field(name="Message", value= response["message"], inline=True)
embed.set_footer(text="Error")
await ctx.send(embed=embed)
await ctx.message.delete()
elif response["status"] == 420:
server_id = 741131311467516961
server = client.get_guild(server_id)
member = server.get_member(ctx.message.author.id)
await ctx.guild.ban(member, reason=response["reason"])
Regards.
Python scope is determined by whitespace; The await calls should be in the elif scope.
Also, it's considered best practice to use 4 spaces for each indent. See PEP8 for more details.
#bot.command()
async def linkdiscord(ctx, token):
author = ctx.message.author
author2 = str(ctx.message.author)
discordid = ctx.message.author.id
response = json.loads(requests.get(forumurl + f"/api?action=linkdiscord&key=SECRET&token={token}&discordid={discordid}").text)
if response["status"] == 200:
embed=discord.Embed(title="Linker System", color=0xcd65f0)
embed.add_field(name="Linked Discord", value="Yes", inline=True)
embed.set_footer(text="Successfully linked " + author2 + " to forum account: " + response["username"])
elif response["status"] == 400:
embed=discord.Embed(title="Linker System", color=0xff0000)
embed.add_field(name="Unexpected error", value="True", inline=True)
embed.add_field(name="Message", value= response["message"], inline=True)
embed.set_footer(text="Error")
await ctx.send(embed=embed) # Now I'm in the correct scope!
await ctx.message.delete() # Me too!
elif response["status"] == 420:
server_id = 741131311467516961
server = client.get_guild(server_id)
member = server.get_member(ctx.message.author.id)
await ctx.guild.ban(member, reason=response["reason"])