I am using discord_slash.utils.manage_components for help commands. I am trying to create help command in python.
https://cdn.discordapp.com/attachments/908053630425366538/940270195040198696/unknown.png
This my code
from discord_slash.utils.manage_components import create_select, create_select_option, create_actionrow
#cog_ext.cog_slash(name="help", description="Get the list of commands")
async def _help(self, ctx: SlashContext):
select = create_select(
options=[
create_select_option("General", value="General", emoji="🌐", default=True),
create_select_option("Fun", value="Fun", emoji="😄", default=False),
create_select_option("Admin", value="Admin", emoji="🛡️", default=False)
],
placeholder="Choose your option",
min_values=1, # the minimum number of options a user must select
max_values=1 # the maximum number of options a user can select
)
action_row = create_actionrow(select)
# Embed general
embed1 = discord.Embed(
title=
"<:mephisto:940249600969801748> **Mephisto General Commands**",
color=0xDC0000)
embed1.add_field(name="`/ping`", value="Return websocket ping")
embed1.add_field(name="`/invite`",
value="Invite bot to your server")
embed1.add_field(name="`/user-info [member]`",
value="Get a someone info")
embed1.add_field(
name="`/weather-info [city]`",
value="Tell us the weather of the city you want to know")
embed1.add_field(name="`/donut`",
value="Send ASCII art donut spinning")
embed1.add_field(name="`/server-info`", value="Server info")
embed1.add_field(name="`/info`",
value="Get information about Mephisto bot")
# Embed fun
embed2 = discord.Embed(
title=
"<:mephisto:940249600969801748> **Mephisto Fun Commands**",
color=0xDC0000)
embed2.add_field(name="`/joke`", value="Get a random joke")
embed2.add_field(name="`/meme`",
value="Get a random meme")
# Embed admin
embed3 = discord.Embed(
title=
"<:mephisto:940249600969801748> **Mephisto Admin Commands**",
color=0xDC0000)
embed3.add_field(name="`/clear [amount]`", value="Clear messages")
embed3.add_field(name="`/ban`",
value="Ban someone user")
embed3.add_field(name="`/Kick`",
value="Kick someone user")
pages = [embed1]
page0 = [embed1]
page1 = [embed2]
page2 = [embed3]
total_pages = [page0, page1, page2]
page = 0
category="General 🌐"
message = await ctx.send(embed=pages[page], components=[action_row])
while True:
try:
interaction = await self.bot.wait_for(
'interaction',
check=lambda inter: inter.message.id == message.id,
timeout=60
)
except asyncio.TimeoutError:
for row in action_row:
row.disable_components()
return await message.edit(content='Timed out!', components=action_row)
if isinstance(interaction.component, create_select):
action_row[0][0].default=False
create_select_option.default=True
pages=page1
page=0
try:
action_row[1][0].disabled=True
action_row[1][1].disabled=True
print("check")
except:
pass
await interaction.edit_origin(embed=pages[page], components = action_row)
Select option doesn't working
I couldn't understand what is the problem. Someone help me to solve this problem.
Related
#bot.tree.command(name="user", description="Shows some informations about the mentioned user.")
async def user(interaction: discord.Interaction, member:discord.Member=None):
if member == None:
member = interaction.user
roles = [role for role in member.roles if role.name != "#everyone"]
embed = discord.Embed(title=f"Details about the user, {member.name}",color=0xdaddd8, timestamp = datetime.datetime.utcnow())
embed.set_thumbnail(url=member.avatar) # Avatar Thumbnail
embed.add_field(name="👤 Name", value = f"{member.name}#{member.discriminator}") # Embeds
embed.add_field(name="🏷️ Nickname", value = member.display_name)
embed.add_field(name="🆔 User ID", value = member.id)
embed.add_field(name="📆 Created at", value = member.created_at.strftime("%D \n%I:%M %p"))
embed.add_field(name="👋🏻 Joined at", value = member.joined_at.strftime("%D \n%I:%M %p"))
embed.add_field(name="🟢 Status", value = member.status) #this line is'nt working as it should
embed.add_field(name="❤️🔥 Top role", value = member.top_role.mention)
bot_status = "Yes, it is" if member.bot else "No, They'snt"
embed.add_field(name="🤖 Bot?", value = bot_status)
embed.set_footer(text = interaction.user.name,icon_url = interaction.user.avatar)
await interaction.response.send_message(embed=embed)
I made a User information command and this command shows every person offline even itself how can i fix it?
This is likely due to lack of intents.
Add in your code, under the intents you define:
intents.members = True
intents.presences = True
Use member.raw_status instead of member.status. It will return a string value such as 'online', 'offline' or 'idle'.
So i have an embed system working in the below code:
#client.event
async def on_message(message):
if message.content.startswith('!emsay'):
embedVar = discord.Embed(title="Title", description="desc", color=0x00ff00)
await message.channel.send(embed=embedVar)
My problem is yes when i do !emsay it dose put the embed in but is there a way that after i put !emsay i can change the title and description without going into python to type out a whole new embed?
This is what i currently have:(im fine with this)Discord screenshot of embed I would like to make it so after i use the command !emsay i can enter a title and description through discord.
Thanks : )
sorry if iv overcomplicated this
Try this:
#client.event
async def on_message(message):
if message.content.startswith('!emsay'):
count = 0
def check(author):
def inner_check(message):
if message.author != author:
return False
return inner_check
while count < 2:
if (count == 0):
await message.channel.send("Write a title for embed")
title = await client.wait_for("message", check=check, timeout=30)
elif (count == 1):
await message.channel.send("Write a desc for embed")
desc = await client.wait_for("message", check=check, timeout=30)
count += 1
embedVar = discord.Embed(title = title.content, description = desc.content, color = 0x00ff00)
await message.channel.send(embed=embedVar)
If you don't write title and desc, you can get a TimeoutError and you can change timeout if you want.
How to use?
I'm making discord bot with python. I was making leveling system using database (https://account.mongodb.com/) and I got this syntax error: pymongo.errors.ConfigurationError: A DNS label is empty. Please help me.
main.py:
import os
import discord
import datetime
import levelsys
intents = discord.Intents.all()
bot = commands.Bot(command_prefix='$', intents=intents)
cogs = [levelsys]
for i in range(len(cogs)):
cogs[i].setup(bot)
# Setting permissions that a user should have to execute this command.
print('Server Running')
bot.run(os.getenv('token'))
levelsys.py:
import discord
from discord.ext import commands
from pymongo import MongoClient
import urllib.parse
bot_channel = 798127930295058442
talk_channels = [690995360834912327]
level = ['new', 'old_new', 'Master Oogway']
levelnum = [5, 15, 30]
intents = discord.Intents.all()
bot = commands.Bot(command_prefix='$', intents=intents)
cluster = MongoClient("mongodb+srv://Myself:" + urllib.parse.quote("stackoverflow") + "#cluster0.4h226.mongodb.n...")
leveling = cluster["discord"]["leveling"]
class levelsys(commands.Cog):
def __init__(self, bot):
self.bot = bot
#commands.Cog.listener()
async def on_ready(self):
print('ready!')
#commands.Cog.listener()
async def on_message(self, message):
if message.channel.id in talk_channels:
stats = leveling.find_one({"id": message.author.id})
if not message.author.bot:
if stats is None:
newuser = {"id": message.auhor.id, "xp": 100}
leveling.insert_one(newuser)
else:
xp = stats["xp"] + 5
leveling.update_one({"id": message.author.id}, {"set":{"xp":xp}})
lvl = 0
while True:
if xp < ((50*(lvl**2))+(50*(lvl-1))):
break
lvl += 1
xp -= ((50*(lvl**2))+(50*(lvl-1)))
if xp == 0:
await message.channel.send(f"Well done {message.author.mention}: you advanced to **level: {lvl}**!")
for i in range(len(level)):
if lvl == levelnum[1]:
await message.author.add_roles(discord.utils.get(message.author.guild.roles, name=level[i]))
embed = discord.Embed(
description= f"{message.author.mention} you have gotten role **{level[i]}**!!!"
)
embed.set_thumbnail(url=message.author.avatar_url)
await message.channel.send(embed=embed)
#commands.command()
async def rank(self, ctx):
if ctx.channel.id == bot_channel:
stats = leveling.find_one({"id": ctx.author.id})
if stats is None:
embed = discord.Embed(description="You need to write more messages to get the rank!")
await ctx.channel.send(embed=embed)
else:
xp = stats["xp"]
lvl = 0
rank = 0
while True:
if xp < ((50*(lvl**2))+(50*lvl)):
break
lvl += 1
xp -= ((50*((lvl-1)**2))+(50*(lvl-1)))
boxes = int((xp/(200*((1/2)*lvl)))*20)
rankings = leveling.find().sort("xp",-1)
for x in rankings:
rank += 1
if stats["id"] == x["id"]:
break
embed = discord.Embed(title="{}'s level stats".format(ctx.author.name))
embed.add_field(name="Name", value=ctx.author.mention, inline=True)
embed.add_field(name="Xp", value=f"{xp}/{int(200*((1/2)*lvl))}", inline=True)
embed.add_field(name="Rank", value=f"{rank}/{ctx.guild.member_count}", inline=True)
embed.add_field(name="Level Bar", value=boxes*":blue_square:"+ (20-boxes)* ":white_large_square:", inline=False)
embed.set_thumbnail(url=ctx.author.avatar_url)
await ctx.channel.send(embed=embed)
#commands.command()
async def leaderboard(self, ctx):
if (ctx.channel.id == bot_channel):
rankings = leveling.find().sort("xp",-1)
i=1
embed = discord.Embed(title="Rankings:")
for x in rankings:
try:
temp = ctx.quild.get_member(x["id"])
tempxp = x["xp"]
embed.add_field(name=f"{i}: {temp.name}", value=f"Total XP: {tempxp}", inline= False)
i+=1
except:
pass
if i == 11:
break
await ctx.channel.send(embed=embed)
def setup(bot):
bot.add_cog(levelsys(bot))
error:
pymongo.errors.ConfigurationError: A DNS label is empty.
Please help me a little and tell me if there are other errors I need to fix. Thank you very much!
At a guess your issue is with the connection string; mongodb in "SRV" mode uses DNS to determine the replicaset / shard details.
I have imported everything needed for the command.
So, the issue here is, in the condition for executing the command (checking if the user said yes/no or something weird which terminates the command)
#commands.command()
#commands.has_permissions(manage_channels=True)
async def nuke(self, ctx,*, channel = None, reason = None):
if reason is None:
reason = "No reason was specified!"
if channel is None:
channel = ctx.channel
p = time.strftime(f'Today at %H:%M %p')
embei = discord.Embed(color=0xa3a3ff, title = ":warning: ALERT ALERT ALERT :warning: ", description=f"{ctx.author.mention} Are you sure you want to delete {ctx.channel.mention}? y/n")
await ctx.send(embed=embei)
msg = await self.client.wait_for('message', check=lambda message:message.author == ctx.author and message.channel.id == ctx.channel.id)
if msg.content.lower in ("y", "yes"):
embedis = discord.Embed(color=0xa3a3ff, title=f"Channel ({ctx.channel.name}) has been nuked :boom:", description=f"Nuked by: {ctx.author.name}#{ctx.author.discriminator} \n **Reason:** {reason}")
embedis.set_image(url = "https://66.media.tumblr.com/23dad7011515a9c21647fefb07e1c0e0/dd0cbd9bb94e2a45-1e/s640x960/a02fc34abff6953c59adafc190de6e5276969175.gif")
embedis.set_footer(text=f"Rylie - Thanks for using this bot! - {p} - {self.client.version}", icon_url = str(self.client.user.avatar_url))
await ctx.channel.delete(reason=reason)
channel = await ctx.channel.clone()
await channel.send(embed=embedis)
elif msg.content.lower in ("n", "no"):
embegs = discord.Embed(color=0xa3a3ff, title = ":red_circle: NOTICE :red_circle:", description = f"{ctx.channel.mention} was not nuked!")
embegs.set_footer(text=f"Rylie - Thanks for using this bot! - {p} - {self.client.version}", icon_url = str(self.client.user.avatar_url))
await ctx.send(embed=embegs)
else:
embers = discord.Embed(color=0xa3a3ff, title = ":red_circle: NOTICE :red_circle:", description = "No proper response was given, action was terminated")
embers.set_footer(text=f"Rylie - Thanks for using this bot! - {p} - {self.client.version}", icon_url = str(self.client.user.avatar_url))
await ctx.send(embed=embers)
The part with the issue
msg = await self.client.wait_for('message', check=lambda message:message.author == ctx.author and message.channel.id == ctx.channel.id)
if msg.content.lower in ("y", "yes"):
embedis = discord.Embed(color=0xa3a3ff, title=f"Channel ({ctx.channel.name}) has been nuked :boom:", description=f"Nuked by: {ctx.author.name}#{ctx.author.discriminator} \n **Reason:** {reason}")
embedis.set_image(url = "https://66.media.tumblr.com/23dad7011515a9c21647fefb07e1c0e0/dd0cbd9bb94e2a45-1e/s640x960/a02fc34abff6953c59adafc190de6e5276969175.gif")
embedis.set_footer(text=f"Rylie - Thanks for using this bot! - {p} - {self.client.version}", icon_url = str(self.client.user.avatar_url))
await ctx.channel.delete(reason=reason)
channel = await ctx.channel.clone()
await channel.send(embed=embedis)
elif msg.content.lower in ("n", "no"):
embegs = discord.Embed(color=0xa3a3ff, title = ":red_circle: NOTICE :red_circle:", description = f"{ctx.channel.mention} was not nuked!")
embegs.set_footer(text=f"Rylie - Thanks for using this bot! - {p} - {self.client.version}", icon_url = str(self.client.user.avatar_url))
await ctx.send(embed=embegs)
else:
embers = discord.Embed(color=0xa3a3ff, title = ":red_circle: NOTICE :red_circle:", description = "No proper response was given, action was terminated")
embers.set_footer(text=f"Rylie - Thanks for using this bot! - {p} - {self.client.version}", icon_url = str(self.client.user.avatar_url))
await ctx.send(embed=embers)
when I execute the command, it does ask me for the confirmation as expected, however, the reply here doesn't matter as it always executes the else statement. I thought the issue was with indentation and so I tried fixing that but that too didn't work. Does anyone know about the issue here I might be facing?
Extra: Before Adding user confirmation, the code was working absolutely fine! (It created a clone of the channel, sent the embed there saying it nuked the original channel, and deleted the original channel)
For this question of mine, the string.lower() is a method which I need to call, which was mentioned to me by Lukasz. I was using the string.lower() in the wrong way.
To Fix the problem I had, I declared two lists a and b
a=["y", "yes"]
b = ["n", "no"]
and changed
if msg.content.lower in ("y", "yes"):
elif msg.content.lower in ("n", "no"):
to
if msg.content in a:
elif msg.content in b:
and the issue was fixed.
So, I've made a help that works, but I want it to say something if the category that the user entered is invalid. I got a working code without the error if the category is invalid. The code:
#client.command()
async def help(ctx, *, category = None):
if category is not None:
if category == 'mod' or 'moderation' or 'Mod' or 'Moderation':
modhelpembed = discord.Embed(
title="Moderation Help",
timestamp=datetime.datetime.now(),
colour=discord.Color.green()
)
modhelpembed.add_field(name='kick', value="Kicks a member from the server", inline=False)
modhelpembed.add_field(name='ban', value='bans a member from the server', inline=False)
modhelpembed.add_field(name='unban', value='unbans a member from the server', inline=False)
modhelpembed.add_field(name="nuke", value="Nukes a channel :>", inline=False)
modhelpembed.add_field(name='mute', value="Mute a member", inline=False)
modhelpembed.add_field(name="purge", value='purges (deletes) a certain number of messages', inline=False)
await ctx.send(f'{ctx.author.mention}')
await ctx.send(embed=modhelpembed)
elif category == 'fun' or 'Fun':
funembed = discord.Embed(
title="Fun Help",
timestamp=datetime.datetime.now(),
colour=discord.Color.green()
)
funembed.add_field(name='meme', value='shows a meme from r/memes', inline=False)
funembed.add_field(name='waifu', value='shows a waifu (pic or link) from r/waifu', inline=False)
funembed.add_field(name='anime', value='shows a anime (image or link) from r/anime', inline=False)
funembed.add_field(name='spotify', value='Tells you the targeted user listening on', inline=False)
funembed.add_field(name="song", value="Tells you the whats the targeted user listening in Spotify", inline=False)
funembed.add_field(name="album", value="Tells you whats the targeted user album", inline=False)
funembed.add_field(name="timer", value="Sets a Timer for you.", inline=False)
await ctx.send(f'{ctx.author.mention}')
await ctx.send(embed=funembed)
else:
nonembed = discord.Embed(
title="Help list",
timestamp=datetime.datetime.now(),
colour=discord.Color.green(),
description='Category:\nmod\nfun'
)
await ctx.send(f'{ctx.author.mention}')
await ctx.send(embed=nonembed)
It works, but when i tried inputing a invalid category it sends Moderation.
You erros comes from your second if statement. You just have to replace it with either:
if category == ('mod' or 'moderation' or 'Mod' or 'Moderation'):
if category in ['mod', 'moderation', 'Mod', 'Moderation']:
Here's why your statement is triggered when you input an invalid category:
An empty string returns False (eg. "") and a string returns True (eg. "TEST").
If you don't put brackets, it will separate each or as a condition (if category == 'mod' / if 'mod' / if 'moderation' / if 'Mod' / if 'Moderation').
Since a non empty string returns True, when you input an invalid category, your second if statement gets triggered and it gives you the Moderation help message.
You can also use commands.Command attributes to make some refactoring:
#client.command(description='Say hi to the bot')
async def hello(ctx):
await ctx.send(f'Hi {ctx.author.mention}')
#client.command(description='Test command')
async def test(ctx):
await ctx.send('TEST')
#client.command()
async def help(ctx, *, category = None):
categories = {
'fun': ['hello',],
'testing': ['test',],
}
if category is None:
desc = '\n'.join(categories.keys())
embed = discord.Embed(
title="Help list",
timestamp=datetime.datetime.now(),
colour=discord.Color.green(),
description=f'Categories:\n{desc}'
)
else:
category = category.lower()
if not category in categories.keys():
await ctx.send('Category name is invalid!')
return
embed = discord.Embed(
title=f"{category.capitalize()} Help",
timestamp=datetime.datetime.now(),
colour=discord.Color.green()
)
for cmd in categories[category]:
cmd = client.get_command(cmd)
embed.add_field(name=cmd.name, value=cmd.description)
await ctx.send(ctx.author.mention, embed=embed)