I just wanted to create a command where if my bot restarts it will still unban members.
here is my code:
#commands.command() # kihagyva
async def tempban(self, ctx, member: discord.Member,seconds: int, d,*,reason=None):
embed = discord.Embed(title="TempBanned",
description=f"{member.mention} has been tempbanned",
colour=discord.Colour.blue())
embed.add_field(name="reason:", value=reason, inline=False)
embed.add_field(name="time left for the ban:", value=f"{seconds}{d}", inline=False)
await ctx.send(embed=embed)
if d == "s":
await asyncio.sleep(seconds*1)
if d == "m":
await asyncio.sleep(seconds*60)
if d == "h":
await asyncio.sleep(seconds*60*60)
if d == "d":
await asyncio.sleep(seconds*60*60*24)
await member.unban()
embed = discord.Embed(title="unbanned (temp) ", description=f"unbanned {member.mention} ", colour=discord.Colour.blue())
await ctx.send(embed=embed)
So you can store it in a database such as sqlite, mysql/mariadb or mongodb.
In MongoDB you would have a collection that is like a table filled with user and guild ids and when the ban expires.
You would use a Task to loop either every minute or 30 seconds or can be longer. Iterate through a database and check if the time now and the time stored is less than the time now. Then unban them.
Related
I have this code for my discord.py bot, for my tempmute command:
#bot.command()
async def tempmute(ctx, member: discord.Member, time: int, d, *, reason=None):
guild = ctx.guild
mutedRole = discord.utils.get(guild.roles, name="Muted")
if not mutedRole:
mutedRole = await guild.create_role(name="Muted")
for channel in guild.channels:
await channel.set_permissions(mutedRole, speak=False, send_messages=False)
for role in guild.roles:
if role.name == "Muted":
await member.add_roles(role)
embed = discord.Embed(title="TempMuted!", description=f"{member.mention} has been tempmuted.", colour=discord.Colour.red())
embed.add_field(name="Reason:", value=reason, inline=False)
embed.add_field(name="Time for the mute:", value=f"{time}{d}", inline=False)
await ctx.send(embed=embed)
if d == "s":
await asyncio.sleep(time)
if d == "m":
await asyncio.sleep(time*60)
if d == "h":
await asyncio.sleep(time*60*60)
if d == "d":
await asyncio.sleep(time*60*60*24)
await member.remove_roles(role)
embed = discord.Embed(title="Unmute (temp mute expired) ", description=f"Unmuted -{member.mention} ", colour=discord.Colour.light_gray())
await ctx.send(embed=embed)
return
However, when using the command, it has to be typed like this: "!tempmute #user 10 m" if I wanted a 10 minute mute. Notice how it is "10 m". How would I make it so "10m" would work (without a space). So "!tempmute #user 10m"? If a user writes it without a space at the moment, the error "discord.ext.commands.errors.BadArgument: Converting to "int" failed for parameter "time"." occurs, probably as it isn't recognising a number with the letter at the end. Thanks
The best way to solve this would be to create your own Converter and typehint the class in the argument. As documented here
So instead of converting your time in your command function, you would do it in the converter making the syntax more cleaner.
Example of a converter
time_regex = re.compile(r"(\d{1,5}(?:[.,]?\d{1,5})?)([smhd])")
time_dict = {"h":3600, "s":1, "m":60, "d":86400}
class TimeConverter(commands.Converter):
async def convert(self, ctx, argument):
matches = time_regex.findall(argument.lower())
time = 0
for v, k in matches:
try:
time += time_dict[k]*float(v)
except KeyError:
raise commands.BadArgument(f"{k} is an invalid time-key! h/m/s/d are valid!")
except ValueError:
raise commands.BadArgument(f"{v} is not a number!")
return time
This is an example of a Time converter, where it will use a regex and converts it into an int in seconds. Which accepts <number><smhd>, example 2d.
The library calls TimeConverter().convert during the command invocation, hence we create a method called convert, which accepts Context object and arguments as str. All you have to do is return something, or raise an error if there is an error.
In order to use this, you would do it as follows
#bot.command()
async def tempmute(ctx, member: discord.Member, time: TimeConverter, *, reason=None):
...
await member.add_roles(role)
await asyncio.sleep(time)
await member.remove_roles(role)
...
The command invocation would be
!tempmute #user 2d here's the reason
I have been working on a tempmute command myself. I would say the command would work fine with a simple dictionary. If you want to convert time units a simple dictionary would do it and you wouldn't require a hell lot of code.
First I would add the code and then give a brief explanation.
Code:
#MyBot.command()
#commands.has_permissions(manage_roles=True)
async def tempmute(ctx, member: discord.Member, time, *, reason=None):
await ctx.message.delete()
if member.guild_permissions.administrator:
ifadmin_embed = discord.Embed(title='Member is Administrator!', description=f'The user, {member.mention} can\'t be muted as he/she is an administrator.', color=0xff0000)
ifadmin_embed.set_author(name='NucleoBot')
ifadmin_embed.set_footer(text=ctx.author)
await ctx.channel.send(embed=ifadmin_embed, delete_after=10.0)
else:
if discord.utils.get(ctx.guild.roles, name='Muted'):
muted_role = discord.utils.get(ctx.guild.roles, name='Muted')
else:
perms = discord.Permissions(send_messages=False, add_reactions=False, connect=False, speak=False)
await ctx.guild.create_role(name='Muted', permissions=perms)
muted_role = discord.utils.get(ctx.guild.roles, name='Muted')
time_convert = {'s' : 1 , 'm' : 60 , 'h' : 3600 , 'd' : 86400, 'y' : 31536000}
mute_time = int(time[0]) * time_convert[time[-1]]
await ctx.message.delete()
role_if_muted = discord.utils.find(lambda r: r.name == 'Muted', ctx.guild.roles)
if role_if_muted in member.roles:
alreadymuted_embed = discord.Embed(title='Already Muted!', description=f'The user, {member.mention} is already muted for {mute_time} seconds.', color=0xff0000)
alreadymuted_embed.set_footer(text=ctx.author)
alreadymuted_embed.set_author(name='NucleoBot')
await ctx.channel.send(embed=alreadymuted_embed, delete_after=10.0)
else:
if reason == None:
await member.add_roles(muted_role)
tempmuted_embed = discord.Embed(title='Temporary Mute Successfull!', description=f'{member.mention} has been muted for {mute_time} seconds successfully! \n \n Reason: No reason given.', color=0x4fff4d)
tempmuted_embed.set_author(name='NucleoBot')
tempmuted_embed.set_footer(text=ctx.author)
else:
await member.add_roles(muted_role)
tempmuted_embed = discord.Embed(title='Temporary Mute Successfull!', description=f'{member.mention} has been muted for {mute_time} seconds successfully! \n \n Reason: {reason}', color=0x4fff4d)
tempmuted_embed.set_author(name='NucleoBot')
tempmuted_embed.set_footer(text=ctx.author)
await ctx.channel.send(embed=tempmuted_embed, delete_after=10.0)
await asyncio.sleep(mute_time)
await member.remove_roles(muted_role)
Explanation:
My code has almost everything here that you need for a mute command. Only the members with roles that have manage_role permissions to execute this command. Also if someone try to mute a member who is an administrator of the server, an embed would pop up to say, Member is an admin.
The code also has the aspect that if no reason is given it would not show any error but post an embed made for No Reason command, i.e., if no reason is mentioned. It also checks that if the server doesn't have a role named Muted. It the role exist it would simply use it otherwise first it would create a role named Muted with denial of important permissions and use it for the mute.
Now the time conversion. The line which is used for this:
time_convert = {'s' : 1 , 'm' : 60 , 'h' : 3600 , 'd' : 86400, 'y' : 31536000}
This command takes second as basic value for the conversion then converts every other unit in terms of seconds. Here s is equated to 1 and m is equated to 60 as I minute is equal to 60 seconds. Similarly doing that same with other units we derive everything to seconds. This dictionary turns everything to seconds and using asyncio we create a timer for mute.
Hope this helps, if you still get any doubt, please feel free to ask me.
Thank You!
how are you doing today i sure hope your doing great im sorry for the spam on other account i apologize. ok so my problem is that i switched from client to bot basically bot = commands.Bot i tried renaming all the commmands to bot.event or bot.command can someone pls help me pls i would appreciate it thank you here is the code :)
#bot.command()
async def ping(ctx):
await ctx.send(f'Pong!\n`{round(client.latency*1000)}ms`')
#bot.command(aliases=['8ball'])
async def _8ball(ctx, *, question):
responses = [ "It is certain.",
"As I see it, yes",
"Ask again later.",
"Better not tell you now.",
"Cannot predict now.",
"Concentrate and ask again.",
"Don't count it",
"It is certain.",
"It is decidedly so.",
"Most likely.",
"My reply is no."
"My sources say no.",
"Outlook not so good.",
"Outlook good.",
"Reply hazy, try again.",
"Signs point to yes.",
"Very doubtful.",
"Without a doubt.",
"Yes.",
"Yes – definitely.",
"You may rely on it." ]
await ctx.send(f'Question: {question}\nAnswer: {random.choice(responses)}')
#commands.has_permissions(ban_members=True)
#bot.command()
async def kick(ctx, user: discord.Member, *, reason="No reason provided"):
await user.ban(reason=reason)
kick = discord.Embed(title=f":boom: Kicked {user.name}!", description=f"Reason: {reason}\nBy: {ctx.author.mention}")
await ctx.message.delete()
await ctx.channel.send(embed=kick)
await user.send(embed=kick)
#commands.has_permissions(ban_members=True)
#bot.command()
async def ban(ctx, user: discord.Member, *, reason="No reason provided"):
await user.ban(reason=reason)
ban = discord.Embed(title=f":boom: Banned {user.name}!", description=f"Reason: {reason}\nBy: {ctx.author.mention}")
await ctx.message.delete()
await ctx.channel.send(embed=ban)
await user.send(embed=ban)
#bot.command()
async def unban(ctx, *, member):
banned_users = await ctx.guild.bans()
member_name, member_discriminator = member.split('#')
for ban_entry in banned_users:
user = ban_entry.user
if (user.name, user.discriminator) == (member_name, member_discriminator):
await ctx.guild.unban(user)
await ctx.channel.send(f"Unbanned: {user.mention}")
#bot.command(pass_context = True)
async def mute(ctx, user_id, userName: discord.User):
if ctx.message.author.server_permissions.administrator:
user = ctx.message.author
role = discord.utils.get(user.server.roles, name="Muted")
#bot.command()
async def serverinfo(ctx):
name = str(ctx.guild.name)
description = str(ctx.guild.description)
owner = str(ctx.guild.owner)
id = str(ctx.guild.id)
region = str(ctx.guild.region)
memberCount = str(ctx.guild.member_count)
icon = str(ctx.guild.icon_url)
embed = discord.Embed(
title=name + " Server Information",
description=description,
color=discord.Color.blue()
)
embed.set_thumbnail(url=icon)
embed.add_field(name="Owner", value=owner, inline=True)
embed.add_field(name="Server ID", value=id, inline=True)
embed.add_field(name="Region", value=region, inline=True)
embed.add_field(name="Member Count", value=memberCount, inline=True)
await ctx.send(embed=embed)
await client.add_roles(user, role)
#bot.command()
async def setdelay(ctx, seconds: int):
await ctx.channel.edit(slowmode_delay=seconds)
await ctx.send(f"Set the slowmode delay in this channel to {seconds} seconds!")
#bot.command()
async def afk(ctx, mins):
current_nick = ctx.author.nick
await ctx.send(f"{ctx.author.mention} has gone afk for {mins} minutes.")
await ctx.author.edit(nick=f"{ctx.author.name} [AFK]")
counter = 0
while counter <= int(mins):
counter += 1
await asyncio.sleep(60)
if counter == int(mins):
await ctx.author.edit(nick=current_nick)
await ctx.send(f"{ctx.author.mention} is no longer AFK")
break
def setup(bot):
bot.add_cog(Afk(bot))
def user_is_me(ctx):
return ctx.message.author.id == "Your ID"
def convert(time):
pos = ["s","m","h","d"]
time_dict = {"s" : 1, "m" : 60, "h" : 3600, "d": 3600*24}
unit = time[-1]
if unit not in pos:
return -1
try:
val = int(time[:-1])
except:
return -2
return val * time_dict[unit]
#bot.command()
#commands.has_permissions(kick_members=True)
async def giveaway(ctx):
await ctx.send("Let's start with this giveaway! Answer these questions within 15 seconds!")
questions = ["Which channel should it be hosted in?", "What should be the duration of the giveaway? (s|m|h|d)", "What is the prize of the giveaway?"]
answers = []
def check(m):
return m.author == ctx.author and m.channel == ctx.channel
for i in questions:
await ctx.send(i)
try:
msg = await bot.wait_for('messsage', timeout=15.0, check=check)
except asyncio.TimeoutError:
await ctx.send('You didn\'t answer in time, please be quicker next time!')
return
else:
answers.append(msg.content)
try:
c_id = int(answers[0][2:-1])
except:
await ctx.send(f"You didn't mention a channel properly. Do it like this {ctx.channel.mention} next time.")
return
channel = bot.get_channel(c_id)
time = convert(answers[1])
if time == -1:
await ctx.send(f"You didn't answer with a proper unit. Use (s|m|h|d) next time!")
return
elif time == -2:
await ctx.send(f"The time just be an integer. Please enter an integer next time.")
return
prize = answers[2]
await ctx.send(f"The giveaway will be in {channel.mention} and will last {answers[1]} seconds!")
embed = discord.embed(title = "Giveaway!", description = f"{prize}", color = ctx.author.color)
embed.add_field(name = "Hosted by:", value = ctx.author.mention)
embed.set_footer(text = f"Ends {answers[1]} from now!")
my_msg = await channel.send(embed = embed)
await my_msg.add_reaction("🎉")
await asyncio.sleep(time)
new_msg = await channel.fetch_message(my_msg.id)
users = await new_msg.reactions[0].users().flatten()
users.pop(users.index(bot.user))
winner = random.choice(users)
await channel.send(f"Congratulations! {winner.mention} won the prize: {prize}!")
#bot.command()
#commands.has_permissions(kick_members=True)
async def reroll(ctx, channel : discord.TextChannel, id_ : int):
try:
new_msg = await channel.fetch_message(id_)
except:
await ctx.send("The ID that was entered was incorrect, make sure you have entered the correct giveaway message ID.")
users = await new_msg.reactions[0].users().flatten()
users.pop(users.index(bot.user))
winner = random.choice(users)
await channel.send(f"Congratulations the new winner is: {winner.mention} for the giveaway rerolled!")
if you want me to answer anything to help you solve it feel free to comment thank you so much have a great day!
It seems like you copied most of the code from the internet and bashed it together to create a bot or a cog (based on your question I would guess a bot).
Assuming this is a snippet of your main bot file and not a cog there are a couple of things that could be different:
Put your utility functions in one place (peferably after your import statatements). It's good practise overall and makes more readeable code.
Unless you have a cog class in the same file as your bot instance (which is bad practise) you shouldn't need this:
def setup(bot):
bot.add_cog(Afk(bot))
If there is a cog class named Afk you should move it into a separate file (putting the cog class into the main bot file defeats the purpose of the cog)
In your mute command you have pass_context = True. This is from the old version of discord.py and is no longer needed.
I can't tell you much more since there's no point in trying to debug your code since you didn't give us any errors or stacktrace to work with.
It is very exhausting, so you can just leave client in every command, just write this client = commands.Bot(command_prefix = 'your prefix') it is the same bot, but it just has a different name.
If you meant that, because i didn't really understand what you need
I have a working suspension command but cannot have the bot repeat the reason and the duration, then delete the trigger. I also have no idea how to make the bot automatically unrole after the suspension duration. Here's my code:
#bot.command(pass_ctx=True)
#commands.has_any_role('✪ Commissioner ✪', '✪ Vice Commissioner ✪', '✪ Board of Directors ✪')
async def suspend(ctx, *, member:discord.Member):
guild = bot.get_guild(766292887914151949)
role_name = 'Suspended'
role = discord.utils.get(guild.roles, name='Suspended')
embed = discord.Embed(
colour = discord.Colour.red())
[
embed.add_field(name='<a:CheckMark:768095274949935146> **Success!**', value=f'{member.mention} has been successfully suspended.')]
await ctx.send(embed=embed)
await member.add_roles(role)
One way of doing this is by using the asyncio module. You could replace your current code to:
import asyncio
#bot.command(pass_ctx=True)
#commands.has_any_role('✪ Commissioner ✪', '✪ Vice Commissioner ✪', '✪ Board of Directors ✪')
async def suspend(ctx, time, *, member:discord.Member):
guild = bot.get_guild(766292887914151949)
role_name = 'Suspended'
role = discord.utils.get(guild.roles, name='Suspended')
embed = discord.Embed(colour = discord.Colour.red())
[
embed.add_field(name='<a:CheckMark:768095274949935146> **Success!**', value=f'{member.mention} has been successfully suspended.')]
await ctx.send(embed=embed)
await member.add_roles(role)
# Using asyncio module to wait
await asycio.sleep(time)
await member.remove_roles(role)
And you would use the command like: [prefix]suspend({time}, {member})
--EDIT--
I noticed that you didn't define role variable. You could do that like:
role = ctx.guild.get_role(roleID)
So now, your command should look like:
#bot.command(pass_ctx=True)
#commands.has_any_role('✪ Commissioner ✪', '✪ Vice Commissioner ✪', '✪ Board of Directors ✪')
async def suspend(ctx, time, *, member:discord.Member):
guild = bot.get_guild(766292887914151949)
role_name = 'Suspended'
role = discord.utils.get(guild.roles, name='Suspended')
embed = discord.Embed(colour = discord.Colour.red())
[
embed.add_field(name='<a:CheckMark:768095274949935146> **Success!**', value=f'{member.mention} has been successfully suspended.')]
# Defile the "role" variable
role = ctx.guild.get_role(roleID)
await ctx.send(embed=embed)
await member.add_roles(role)
# Using asyncio module to wait
await asycio.sleep(time)
await member.remove_roles(role)
Ok so I'm working on one of my older bots and am attempting to rewrite my custom help command to be a bit less manual. However, I'm not sure how to get this working as intended.
My issues are as follows:
It keeps responding with the I can't send embeds exception
There's no error showing up in the console logs
Can anyone help me figure this out?
Here is my custom Help command.
#commands.command(name="help", aliases=["Help", "H", "h"])
#commands.has_permissions(add_reactions=True, embed_links=True)
async def help(self, ctx, *cog):
"""Gets all cogs and commands.
Alt : h, H, Help
Usage : [h]elp <cog or command>"""
try:
if not cog:
"""Cog listing. What more?"""
embed = discord.Embed(color=discord.Color.dark_gold(),
title='Cog Listing and Uncatergorized Commands',
description=f'Use `{prefix}help <cog>` to find out more about them!\nNote: The Cog Name Must Be in Title Case, Just Like this Sentence.',
timestamp=ctx.message.created_at)
embed.set_author(name=self.client.user.name, icon_url=self.client.user.avatar_url)
cogs_desc = ''
for x in self.client.cogs:
cogs_desc += ('{} - {}'.format(x, self.client.cogs[x].__doc__) + '\n')
embed.add_field(name='Cogs', value=cogs_desc[0:len(cogs_desc) - 1], inline=False)
cmds_desc = ''
for y in self.client.walk_commands():
if not y.cog_name and not y.hidden:
cmds_desc += ('{} - {}'.format(y.name, y.help) + '\n')
embed.add_field(name='Uncatergorized Commands', value=cmds_desc[0:len(cmds_desc) - 1], inline=False)
await ctx.send('', embed=embed)
else:
"""Helps me remind you if you pass too many args."""
if len(cog) > 1:
embed = discord.Embed(color=discord.Color.dark_red(), timestamp=ctx.message.created_at)
embed.set_author(name="Command Failed", icon_url=self.client.user.avatar_url)
embed.add_field(name="Error", value="Too many cogs", inline=False)
await ctx.send('', embed=embed)
else:
"""Command listing within a cog."""
found = False
for x in self.client.cogs:
for y in cog:
if x == y:
embed = discord.Embed(color=discord.Color.dark_gold(), timestamp=ctx.message.created_at, title=cog[0] + ' Command Listing', description=self.client.cogs[cog[0]].__doc__)
for c in self.client.get_cog(y).get_commands():
if not c.hidden:
embed.add_field(name=c.name, value=c.help, inline=False)
found = True
if not found:
"""Reminds you if that cog doesn't exist."""
embed = discord.Embed(color=discord.Color.dark_red(), timestamp=ctx.message.created_at)
embed.set_author(name="Command Failed", icon_url=self.client.user.avatar_url)
embed.add_field(name="Error", value='Can not use "' + cog[0] + '"?', inline=False)
else:
await ctx.send('', embed=embed)
except:
await ctx.send("I can't send embeds.")
I'm using discord.py-rewrite if it helps.
---EDIT---
I gave up on the above code due to countless issues with it. And went for the following code. I'd still like it to be less manual but for now this one actually posts.
#commands.command(name="Help", aliases=["help", "h", "H"])
async def _help(self, ctx):
"""Displays all available commands"""
msg = ctx.message
await msg.delete()
contents = [
f"```css\nAdministrator Commands\n\nBroadcast: [B]roadcast <message>\nPurge: [p]urge <1-100>\nBan: [B]an <user> [reason]\nUnban: [U]nban <user>\nKick: [K]ick <user> [reason]\n\nOptional arguments are represented with []\nRequired arguments are represented with <>\nDo not include the [] or <> flags in the command\n ```",
f"```css\nModerator Commands!\n\nAnnounce: [ann]ounce <message>\nClean: [C]lean <1-100>\n\nOptional arguments are represented with []\nRequired arguments are represented with <>\nDo not include the [] or <> flags in the command\n ```",
f"```css\nFun Commands\n\nGiphy: [ ] < >\nTenor: [ ] < >\n\nOptional arguments are represented with []\nRequired arguments are represented with <>\nDo not include the [] or <> flags in the command\n ```",
f"```css\nUtility Commands\n\nPing: ping\nJoined: [J]oined [user]\nTopRole: [top]role [user]\nPerms: perms [user]\nHelp: [H]elp [command]\n\nOptional arguments are represented with []\nRequired arguments are represented with <>\nDo not include the [] or <> flags in the command\n ```"
]
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 self.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 the loop if user doesn't react after x seconds
#_help.error
async def _help_error(self, ctx, error):
if isinstance(error, commands.MissingRequiredArgument):
guild = ctx.guild
embed = discord.Embed(
color=discord.Color.dark_red(), timestamp=ctx.message.created_at)
embed.set_author(name="Command Failed",
icon_url=self.client.user.avatar_url)
embed.add_field(name="Missing Required arguments",
value="Please pass in all required arguments.", inline=False)
embed.set_thumbnail(url=self.client.user.avatar_url)
embed.set_footer(text=f"{guild.name}", icon_url=guild.icon_url)
await ctx.message.add_reaction(emoji="⚠️️")
await ctx.message.author.send(embed=embed)
print("[ERROR] Missing Required Arguments")
elif isinstance(error, commands.MissingPermissions):
guild = ctx.guild
embed = discord.Embed(
color=discord.Color.dark_red(), timestamp=ctx.message.created_at)
embed.set_author(name="Access denied",
icon_url=self.client.user.avatar_url)
embed.add_field(name="Insufficient Permissions",
value="You do not have permission to use this command.", inline=False)
embed.set_thumbnail(url=self.client.user.avatar_url)
embed.set_footer(text=f"{guild.name}", icon_url=guild.icon_url)
await ctx.message.add_reaction(emoji="🚫")
await ctx.message.author.send(embed=embed)
print("[ERROR] Insufficient Permissions")
But yes, if anyone knows how to make it so the commands are read from the cogs instead of manually typed into the help command's response any tips would be very helpful.
Hello so i am trying to create a report system where when a report is created it is report #0001 when a new one is it is report #0002 here is my code so far.
#commands.command()
async def report(self, ctx, member : discord.Member, reason=None):
await ctx.send(f'{member} has been reported!')
channel = discord.utils.get(ctx.guild.text_channels, name='reports')
embed = discord.Embed(name=f'Report incoming! #0001 ')
embed.add_field(name='Member', value=f'{member}', inline=False)
embed.add_field(name='Member who reported them', value=f'{ctx.author}', inline=False)
embed.add_field(name='Reason', value=f'{reason}', inline=False)
embed.add_field(name='Channel', value=f'{ctx.channel}', inline=False)
await channel.send(content=None, embed=embed)
Does anyone know how if so please respond to this thanks!
If you sure that there will be no internet problem or some other problems that will prevent the boat from running, you can simply do
count = 0
#commands.command()
async def report(self, ctx, member : discord.Member, reason=None):
count += 1
#the rest of the command
Then you can change the embed name like this
embed = discord.Embed(name=f'Report incoming! #{count}')
But if you are not completely sure that the bot will have not any problem,
you can save the numbers in a file like txt, json or yaml. I'd prefer txt in that case because you just need to save one line of text. So you can do this:
with open('counts.txt', 'r+') as file:
number = file.read()
if number == '':
file.write('0')
#commands.command()
async def report(self, ctx, member : discord.Member, reason=None):
with open('counts.txt', 'w+') as file:
count = file.read()
file.write(int(count)+1)
embed = discord.Embed(name=f'Report incoming! #{count}')
Well, you have to store the report count somewhere, preferably a proper database. For this example you can use a json file, however, keep in mind that a json file as a database is fundamentally flawed due to its lack of atomic writes which can result in data corruption and loss.
import json
#commands.command()
async def report(self, ctx, member: discord.Member, reason=None):
# Get currect report number
with open('reports.json', 'r', encoding='utf-8') as counts:
data = json.load(counts)
counter = data['count']
await ctx.send(f'{member} has been reported!')
data = {"count": counter + 1} # Add 1 everytime a report is invoked
with open('reports.json', 'w', encoding='utf-8') as f:
json.dump(data, f, ensure_ascii=False, indent=4)
channel = discord.utils.get(ctx.guild.text_channels, name='reports')
embed = discord.Embed(title=f'Report incoming! #{counter} ')
embed.add_field(name='Member', value=f'{member}', inline=False)
embed.add_field(name='Member who reported them', value=f'{ctx.author}', inline=False)
embed.add_field(name='Reason', value=f'{reason}', inline=False)
embed.add_field(name='Channel', value=f'{ctx.channel}', inline=False)
await channel.send(content=None, embed=embed)
reports.json
{
"count": 0
}