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
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 am making a command that will randomly pick a user from a message's reaction (similar to giveaway command). I tried to add a feature that will remove the chosen user's reaction once the user is chosen by the bot but it didn't work. I am new to the world of discord bot, please help me.
Here are the codes:
#client.command()
async def king(ctx):
time = 10
embed = nextcord.Embed(title="King's Game", description="React to join.")
embed.set_footer(text=f"Ends in {time}s")
kmsg = await ctx.send(embed=embed)
await kmsg.add_reaction("π")
await asyncio.sleep(time)
new_msg = await ctx.channel.fetch_message(kmsg.id)
players = await new_msg.reactions[0].users().flatten()
players.pop(players.index(client.user))
print (players)
king = random.choice(players)
tembed = nextcord.Embed(title="Time is up!", description="Get ready to obey the king.")
kembed = nextcord.Embed(title="King", description=f"{king.mention} is the king!")
await ctx.send(embed=tembed)
ktime = 2
await asyncio.sleep(ktime)
await ctx.send(embed=kembed)
kingid = get(king.user.id)
await kmsg.remove_reaction(kingid)
You should read about await remove_reaction(emoji, member) from the official documentation.
You have to simply specify the member of which remove the reaction.
I am currently trying to edit an embed with a command. The edited embed has a clear structure. It is supposed to be an evaluation of the suggestion. For this I need the author and his suggestion from the previous command. Is it possible to take the content of the old embed and transfer it to the edited embed if you have two commands? In addition, it would be good to still count and insert the reactions at the message.
Here are my working approaches, except for the missing parts:
##commands.cooldown(1, 100, BucketType.user)
#commands.command(usage="<text>")
async def suggest(self, ctx, *, text: str = None):
"""This is the command for suggestions."""
if text is None:
await ctx.send("**You need to insert a text.**")
return self.suggest.reset_cooldown(ctx)
channel1 = self.bot.get_channel(812284187427864616)
if channel1 == ctx.channel:
channel = self.bot.get_channel(812283430707920906)
e = discord.Embed(color=discord.Colour.green())
e.description = f "**__submitter:__**\n {ctx.author}"
e.add_field(name="__Suggestion:__", value=f"{text}")
e.set_thumbnail(url=ctx.message.author.avatar_url)
e.timestamp = datetime.utcnow()
e.set_footer(text=f "UID: {ctx.author.id}")
feedback = await channel.send(embed=e)
await feedback.add_reaction("β
")
await feedback.add_reaction("β")
await ctx.message.add_reaction("β
")
The approve command which actually edits the old embed and should insert "Suggestion", "Submitter" and count the reactions.
#commands.command()
async def approve(self, ctx, msg_id: int = None, channel: discord.TextChannel = None):
if not msg_id:
channel = self.bot.get_channel(812283430707920906) # the message's channel
msg_id = 998877665544332211 # the message's id
elif not channel:
channel = ctx.channel
msg = await channel.fetch_message(msg_id)
embed = discord.Embed()
embed.title = "Suggestion accepted"
embed.description = "*Here are all the important information*"
embed.add_field(name="Results", value="β
: MISSING COUNT / β: MISSING COUNT")
embed.add_field(name="Suggestion", value=f"MISSING SUGGESTION TEXT")
embed.add_field(name="Submitter:", value=f"MISSING SUBMITTER")
embed.add_field(name="Approved by:", value=f"{ctx.author.mention}")
await msg.edit(embed=embed)
await msg.clear_reactions()
To count the reactions I would use something like:
total_count = 0
for r in message.reactions:
total_count += r.count
EDIT:
This is the embed right now with showing Suggestion two times in different ways.
#commands.command()
async def approve(self, ctx, channel: discord.TextChannel, msgID: int):
try:
msg = await channel.fetch_message(msgID)
embed = msg.embeds[0]
submitter = embed.description[embed.description.find('\n'):]
suggestion = embed.fields[0].value
embed.title = "Suggestion accepted"
embed.description = "*Here are all the important information*"
embed.add_field(name="Results", value="β
: Test/ β: Test", inline=False)
embed.add_field(name="Suggestion", value=f"{suggestion}", inline=False)
embed.add_field(name="Submitter", value=f"{submitter}", inline=False)
embed.add_field(name="Approved by", value=f"{ctx.author.mention}", inline=False)
await msg.edit(embed=embed, reference=msgID)
await msg.clear_reactions()
except:
pass
msg = await channel.fetch_message(msg_id)
You can use the fetched message to get details about it.
try:
msg = await channel.fetch_message(msg_id)
embed = msg.embeds[0]
submitter = embed.description[embed.description.find('/n'):] # get submitter name
suggestion = embed.fields[0].value
# other stuff
except:
pass
# possible exceptions message not found, list index out of range(if wrong msg id with no embeds passed as arg)
References:
fetch_message
embeds
message
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
I have the following code to generate embed from a message , it works fine now what I want is after creating embed the bot should ask the user to mention a channel and after the user mentions a channel , the bot should send that embed there. How do I do it?
#bot.command()
async def embed(ctx):
await ctx.send("Enter title for embed:")
e = await get_input_of_type(str, ctx)
await ctx.send("Enter the content for embed:")
c = await get_input_of_type(str, ctx)
embed = discord.Embed(
title = e,
description = c,
color = 0x03f8fc,
timestamp= ctx.message.created_at
)
embed.set_thumbnail(url = ctx.guild.icon_url)
await ctx.channel.send(embed=embed)
Using wait_for() and TextChannelConverter
#bot.command()
async def embed(ctx):
def check(m):
return m.author == ctx.author and m.channel == ctx.channel
await ctx.send("Enter title for embed:")
e = await get_input_of_type(str, ctx)
await ctx.send("Enter the content for embed:")
c = await get_input_of_type(str, ctx)
embed = discord.Embed(
title = e,
description = c,
color = 0x03f8fc,
timestamp= ctx.message.created_at
)
embed.set_thumbnail(url = ctx.guild.icon_url)
channel = await bot.wait_for("message", check=check)
channel = await commands.TextChannelConverter().convert(ctx, channel.content)
await channel.send(embed=embed)
I used the Client.wait_for() coroutine to wait for a message from the user. Then I formatted the message.content string to get just the ID of the channel. Then I used the discord.utils.get method to get the channel using just the ID.
# at the top of the file
from discord.utils import get
#client.command()
async def embed(ctx):
# embed stuff here
def check(msg):
# make sure the author of the message we're waiting for is the same user that invoked the command
return ctx.author == msg.author
await ctx.send("mention a channel to send to")
msg = await client.wait_for('message', timeout=60.0, check=check)
msg = msg.content.split("#")[1].split('>')[0]
"""
over here we are spliting the '#' from the message content first and index just the ID with the '>'
(if the message is just a channel mention it shoud be something like this: <#000000000000000000>)
then we split the '>' from the string and index just the ID part and now we have the ID of the channel
"""
channel = get(ctx.guild.channels, id=int(msg))
await channel.send(f'{words}')