#discord-bots
1 messages · Page 244 of 1
How to send modal ?
i don't understand how to send
did you read the example??
Yes
class ButtonTicket(discord.ui.View):
def __init__(self):
super().__init__()
self.value = None
@discord.ui.button(label = "Open Ticket", style = discord.ButtonStyle.green)
async def open_ticket(self, interaction: discord.Interaction, button: discord.ui.Button):
guild = interaction.guild
c = discord.utils.get(guild.categories, name="TICKET")
for channel in guild.channels:
if channel.name == f"ticket-{interaction.user.name}":
await interaction.response.send_message(f"You have already a ticket <#{channel.id}>", ephemeral = True)
return
reason = discord.ui.TextInput(
label='Reason',
placeholder='Reason open ticket here...',
required=True,
max_length=300,
)
reason.send_modal(interaction)
interacted, result = await reason.wait()
if not interacted:
return
ticket_channel = await interaction.guild.create_text_channel(f'ticket-{interaction.user.name}', category = c)
overwrite = discord.PermissionOverwrite()
overwrite.send_messages = False
overwrite.read_messages = False
await ticket_channel.set_permissions(interaction.guild.get_role(interaction.guild.id), overwrite=overwrite)
await ticket_channel.set_permissions(interaction.user, read_messages=True, send_messages=True)
await interaction.response.send_message(f"Your ticket is <#{ticket_channel.id}>", ephemeral = True)
embed = discord.Embed(title="Ticket", description="Please wait support will be with you shortly.", colour=interaction.user.colour)
embed.add_field(name="Created By:", value=f"{interaction.user.name}", inline=True)
embed.add_field(name="Reason:", value=f"{result}", inline=True)
embed.set_footer(text=f"{guild.name}", icon_url=interaction.user.display_avatar)
await ticket_channel.send(f"<@{interaction.user.id}>")
await ticket_channel.send(embed=embed)
if database_ticket.get_channel(interaction.guild.id) is None:
return
channel_send = database_ticket.get_channel(interaction.guild.id)
embed_log = discord.Embed(title = f"Ticket created by {interaction.user.name}", description = f"Reason: {result}\nChannel: <#{ticket_channel.id}>")
await channel_send.send(embed=embed_log)```
This is my code
reason = discord.ui.TextInput(
label='Reason',
placeholder='Reason open ticket here...',
required=True,
max_length=300,
)
reason.send_modal(interaction)```
Where did you get this code? this is not how it works, please see the example
Hello
I don't understand example bruh
When someone explains something and you respond simply with "wdym" or "I don't understand", that is extremely unhelpful. It tells us nothing about which part you didn't understand or how we can target the explanation to help you. It roughly translates to
Please re-explain everything and pick random different words in the hopes that I get it this time.
Ask targeted questions about what you did not understand. If you didn't understand anything, split it up into individual parts and ask about one at a time specifically.
Bro i'm tired 4h morning here
then sleep???
I try resolve my bot before
ok
what dont you understand
i wanna create a channel in which a member gets banned automatically if they send a message
any idea how ?
Why 🤨
Was able to do it, But out of this how can i pull out the time the user went away? like 1 sec ago, 1 hour ago, 1 day ago, 1 month ago, 1 year ago?
for spam bots
no bruh , it is to prevent them
No one would do it like that
Pretty sure the example shows you how
You can't be sure that they will spam only invite links
examples/modals/basic.py lines 70 to 75
@client.tree.command(guild=TEST_GUILD, description="Submit feedback")
async def feedback(interaction: discord.Interaction):
# Send the modal with an instance of our `Feedback` class
# Since modals require an interaction, they cannot be done as a response to a text command.
# They can only be done as a response to either an application command or a button press.
await interaction.response.send_modal(Feedback())```
!d urllib
Source code: Lib/urllib/
urllib is a package that collects several modules for working with URLs...
Spam bots are blocked quite effectively by my AI bot
You can check its source on my github
I don't have traceback is just don't recognize
Afaik it's not a module thus can't be imported
class ButtonTicket(discord.ui.Modal, title = "Ticket"):
def __init__(self):
super().__init__()
self.value = None
reason = discord.ui.TextInput(
label='Reason',
placeholder='Reason open ticket here...',
required=True,
max_length=300,
)
buttons = [{"label": "Open Ticket"}]
async def on_submit(self, interaction: discord.Interaction):
guild = interaction.guild
c = discord.utils.get(guild.categories, name="TICKET")
for channel in guild.channels:
if channel.name == f"ticket-{interaction.user.name}":
await interaction.response.send_message(f"You have already a ticket <#{channel.id}>", ephemeral = True)
return
ticket_channel = await interaction.guild.create_text_channel(f'ticket-{interaction.user.name}', category = c)
overwrite = discord.PermissionOverwrite()
overwrite.send_messages = False
overwrite.read_messages = False
await ticket_channel.set_permissions(interaction.guild.get_role(interaction.guild.id), overwrite=overwrite)
await ticket_channel.set_permissions(interaction.user, read_messages=True, send_messages=True)
await interaction.response.send_message(f"Your ticket is <#{ticket_channel.id}>", ephemeral = True)
embed = discord.Embed(title="Ticket", description="Please wait support will be with you shortly.", colour=interaction.user.colour)
embed.add_field(name="Created By:", value=f"{interaction.user.name}", inline=True)
embed.add_field(name="Reason:", value=f"{reason}", inline=True)
embed.set_footer(text=f"{guild.name}", icon_url=interaction.user.display_avatar)
await ticket_channel.send(f"<@{interaction.user.id}>")
await ticket_channel.send(embed=embed)
if database_ticket.get_channel(interaction.guild.id) is None:
return
channel_send = database_ticket.get_channel(interaction.guild.id)
embed_log = discord.Embed(title = f"Ticket created by {interaction.user.name}", description = f"Reason: {reason}\nChannel: <#{ticket_channel.id}>")
await channel_send.send(embed=embed_log)
async def on_error(self, interaction: discord.Interaction, error: Exception) -> None:
await interaction.response.send_message('Oops! Something went wrong.', ephemeral=True)```
How can i get the output modal named reason for put in on_submit ?
You need to from discord.ui import Thing or import discord and then refer by discord.ui.Thing
ok
It's working just fine for me
Then that's further than expected for me to know
How do I get the permissions required by bot and user to run x command?
Use the table https://discord.com/developers/docs/topics/permissions#permissions-bitwise-permission-flags and determine what your bot does while using the command and match the required permissions.
For the user, it's entirely up to you - though common sense says that to use a ban command the user should have the ban members permission.
@client.tree.command(name="clear", description="clear messages (moderator only)")
@discord.app_commands.checks.has_permissions(manage_messages=True)
@app_commands.default_permissions(manage_messages=True)
async def clear(interaction: discord.Interaction, amount: int):
await interaction.response.defer()
await interaction.channel.purge(limit=amount)
await interaction.followup.send(f"deleted {amount} messages")
``` this doesnt work properly
Coolio, "don't work" is vague
Can someone help me
I Made a warning system, but i dont know how to add a clearwarnings command.
My code is: https://paste.pythondiscord.com/fexaqizono.
The system works like that: https://cdn.discordapp.com/attachments/1110101798791954493/1110102350414217256/image.png
Can anyone help??
seems pretty straightforward, just set the member's warnings to an empty list
How? (im new)
No, I mean like ctx.command.permissions.user or something like that..
Hi new
hi
Getting the permissions of the user for the current channel?
You have ctx.author.guild_permissions available
I want to get the required perms for a command like
user ran e.command info uwu
The bot would display permissions required by the user to run command uwu and permissions required by bot
Probably better to get a global error handler for that then
Then you check if the error is instance of MissingPermissions or BotMissingPermissions
There you will have the missing_permissions attribute available
Hello how to make the commands of his bot discord appear in the corresponding commands - quick commands in Python?
You mean the "try my commands" section?
https://paste.pythondiscord.com/momafecaju
I have checked that the user doesnt has the perm to ping any role. but still the role is not being replaced... but the everyone and here is being replaced
Probably because roles are not .mentionable, check if code under that condition is even executed
!d discord.Role.mentionable
Indicates if the role can be mentioned by users.
ohhh thanks
Made me write code on phone on dpy server, only to find it's already solved .-. Else was gonna mention the same thing..
Only came here by chance tbh
don't name variables ilke keywords
Error pretty much says all
class initialapplybutton(View):
def __init__(self):
super().__init__(timeout=None)
@button(label="Apply", style=discord.ButtonStyle.green, custom_id="3")
async def initialapplybutton(self, interaction: discord.Interaction, button: Button):
await interaction.response.send_message("""**PLEASE NOTE!**
In order to start your application, you will need to join our Creator Applications Discord server. Please only join the server if you are SERIOUS about applying and will actually apply!
If you join the server and don't submit an application, you will be **permanently banned** from our official Stumble Guys Discord servers and you won't be able to apply to our Content Creator Program in the future.
If you have read this and would like to proceed to apply, please click on the ✅ below this message.""", ephemeral=True, view= confirminvitebutton())
Hello, I wanted to ask how I can add another button to this other than the confirminvitebutton?
Create a view
How 😅
ah okay got it so a button in the same class instead of a whole new class
I was doing that
Tysm it works
This seems like the best place for this
Is it against TOS to write an application that changes my prescence based on what song im listening to on youtube music?
if not, what would be the proper way to set the rpc?
Ye Ik, I think input is the only one I keep doing it to, it's not really an issue cause I know thru out this project I will never be using input,
how to set perms to channel: role = interaction.guild.get_role(1106962573145940070) await interaction.channel.set_permissions(role, read_messages=False) read_messages=False not work 😦
HELP
@vocal snow
You probably want to use overwrites
its not a prefix command right ?
wait nvm
yea you use overwrites
It's totally fine
!pypi discord-rich-presence seems like an easy lib to use for presence
Mm are you sure no roles have read messages explicitly set to true?
send code please im very engry and destroy my keyboard
That's usually the case
read the example ?
yes
i mean its pretty explanatory
you edit channel and add the overwrites dict to the overwrites parameter
Use google :) https://www.google.com/search?q=discordpy+overwrites
Sometimes searching on your own is useful, especially when learning
Could you please print(interaction.channel.overwrites)?
why my clear command is not working?
What's the line of code which describes the / command
@client.tree.command(name="clear", description="clear messages (moderator only)")
@discord.app_commands.checks.has_permissions(manage_messages=True)
@app_commands.default_permissions(manage_messages=True)
async def clear(interaction: discord.Interaction, amount: int):
await interaction.response.defer()
await interaction.channel.purge(limit=amount)
await interaction.followup.send(f"deleted {amount} messages")```
this doesn't work
it sends the message but doesn't purge anything
Whats the line of code to give the slash command a description
there's a keyword-arg you can pass the @app_commands.command decorator to set it, iirc
!d discord.app_commands.command
@discord.app_commands.command(*, name=..., description=..., nsfw=False, auto_locale_strings=True, extras=...)```
Creates an application command from a regular function.
description
alright thanks
TypeError: command function must be a coroutine function
Whats this error?
nvm fixed sos
basically i have some bot code and have it on repl, how would i make the code popup that blank website thing (something along the lines of projectname.repl.co) so i can use it to host the bot on a seperate website/VPS
Hey anyone here?
Can help me?
with what
Ask your Python question, not if you can ask or if there's an expert who can help.
down do you know anything ab this
How would you make the description be at the top and have a colon after galleon price and strong scroll price?
Hmm I have made 1 mute cmd in my bot in that I have write that ctx.guild.roles(name="Muted")
And when I am running my codeit showing discord don't have any attribute guild
no idea i dont work on replit
neither do i but i just need a free VPS
Hmm?
cause im making a bot for a discord server not a public
Then your ctx var is a discord module
if you want free vps you can try trial gcp or aws
Or something, definitely not a context though
i was gonna use uptimerobot
but like i said i need to figure out the repl link thing
i wouldnt use replit at all
anyone know?
Hmm I am asking that what I have to write instead of guild cuze I have made first cmd that can manage roles or something
Don't try to use replit to host your bot
how else am i meant to host my code 24/7
a vps?
this server has a channel for everything
Even if you get it to work, you'd be rate limit someday
yes but even if it costs like 2 bucks a month
i just need it running for my server lmao
you have all in pinned messages in bot-hosting
there is also why you should not use replit to host bot
@naive briar
show code so we can help
What's even your question
Forgor to unreply
@naive briar
No, it wasn't for you
alr
@commands.command()
@commands.has_permissions(manage_roles=True)
async def mute(ctx, self, user:discord.Member, duration="1m"):
mute_role = discord.utils.get(ctx.guild.roles, name="Muted")
It's that part and see last line
i just have this at the top of my code and it seems to work, if yours isnt the same that might be why
import os
import discord
from discord.ext import commands
from discord.utils import utcnow
client = commands.Bot(command_prefix="d=", intents=discord.Intents.all())
and wait your trying to?
self always has to be the first argument in a method of a class
thats stupid ngl (i didnt even know that myself)
I seen that now 🗿
When calling a method from a class instance (ie. instance.method()), the instance itself will automatically be passed as the first argument implicitly. By convention, we call this self, but it could technically be called any valid variable name.
class Foo:
def bar(self):
print('bar')
def spam(self, eggs):
print(eggs)
foo = Foo()
If we call foo.bar(), it is equivalent to doing Foo.bar(foo). Our instance foo is passed for us to the bar function, so while we initially gave zero arguments, it is actually called with one.
Similarly if we call foo.spam('ham'), it is equivalent to
doing Foo.spam(foo, 'ham').
Why is this useful?
Methods do not inherently have access to attributes defined in the class. In order for any one method to be able to access other methods or variables defined in the class, it must have access to the instance.
Consider if outside the class, we tried to do this: spam(foo, 'ham'). This would give an error, because we don't have access to the spam method directly, we have to call it by doing foo.spam('ham'). This is also the case inside of the class. If we wanted to call the bar method inside the spam method, we'd have to do self.bar(), just doing bar() would give an error.
@naive briar what I have to write instead of guild ;-;
the guild must have a role named Muted
But I have setuped that if muted role is not their so make it
Huh ig you didn't got I am trying to say
i dont really know whats the problem here
Wait lemme explain
That 1 line
(ctx.guild.roles, name="Muted")
In this line consol is giving a error that discord have no attribute guild so I am asking that what I have to write instead of guild
how did you make discord from context
Just retry it after changing the self argument position
did you fix the self not being first argument?
I have done lemme try it
@bot.tree.command(name="suggest", description="Make a suggestion")
async def suggest(ctx: commands.Context, suggestion: str):
suggestion_channel_id = 1106959842901504060
suggestion_channel = bot.get_channel(suggestion_channel_id)
if suggestion_channel is None:
print(f"Could not find channel with ID {suggestion_channel_id}")
return
embed = discord.Embed(title="Suggestion", color=discord.Color.blurple())
embed.add_field(name="User ID", value=str(ctx.author.id))
embed.add_field(name="Suggestion", value=suggestion)
await suggestion_channel.send(embed=embed)
await ctx.send("Your suggestion has been submitted!")
When doing /suggest it says: The interaction did not respond
Error: discord.app_commands.errors.CommandInvokeError: Command 'suggest' raised an exception: AttributeError: 'Interaction' object has no attribute 'author'
does anybody know how to fix?
!d discord.Interaction.user
The user or member that sent the interaction.
Read the docs 🐈
What's so hard to understand about it
what to change

although i shouldn't be laughing, i am
first of all you dont get Context in slash commands you get Interaction
ok
@slate swan py @client.tree.command(name="clear", description="clear messages (moderator only)") @discord.app_commands.checks.has_permissions(manage_messages=True) @app_commands.default_permissions(manage_messages=True) async def clear(interaction: discord.Interaction, amount: int): await interaction.channel.purge(limit=amount) await interaction.response.defer() await interaction.followup.send(f"deleted {amount} messages") print(f"deleted {amount} messages") some reason this works
why need to defer it at all?
order: purge, defer, followup
Hey like my bot made Muted role then it have to change perms then this code will added?
for channel in ctx.guild.channels:
await channel.set_permissions(mute_role, send_messages=False)
first purge everything then send a message
try and see
cant you use timeout?
is there any need for ctx? should i replace with interaction
Delete the defer then
yeah so why defer it
I have done but it showing error ;-;
It's useless now
do u have 2.0
no its interaction
aight
Hmm I didn't got timeout step so ....
then show the error instead
Ok
for some reason it takes too long to respond
Aee
if i take it off
@bot.tree.command(name="suggest", description="Make a suggestion")
async def suggest(interaction: discord.Interaction, suggestion: str):
suggestion_channel_id = 1106959842901504060
suggestion_channel = bot.get_channel(suggestion_channel_id)
if suggestion_channel is None:
print(f"Could not find channel with ID {suggestion_channel_id}")
return
embed = discord.Embed(title="Suggestion", color=discord.Color.blurple())
embed.add_field(name="User ID", value=str(ctx.author.id))
embed.add_field(name="Suggestion", value=suggestion)
await suggestion_channel.send(embed=embed)
await interaction.response.send_message("Your suggestion has been submitted!")
Like this?
got an answer
discord.app_commands.errors.CommandInvokeError: Command 'suggest' raised an exception: NameError: name 'ctx' is not defined
??
Are you just doing something random now
Replit being replit
no? my code is above
Wdym
if you are not getting ctx you obviously cant use it
check what type mute_role is
but i didn't use it
str(ctx.author.id) yeah you for sure did not
what the heck it was working but then it stopped working i didnt change the code
python just trolling
makes no sense
Why are you keep replying to me
Huh it's a role what else, I am sooooooo confused what you saying ;-;
my bad
prove it its a role
Role object
How ?
Print it or isinstance
oh waiit it depends on how much amount i put
could i do an if statement?
i try
how could i do a if statement for more than a number
example 5 +
u could chain if elif
what is it for tho?
if number > 5: ?
thanks
oh i thought he wanted like 5 if statements
what about that pokemon model i was asking for
oh whats the issue with it?
i dont know what it should contain
just a sec ill link u
Not sure why the bot can't find the message
error: discord.app_commands.errors.CommandInvokeError: Command 'accept' raised an exception: NotFound: 404 Not Found (error code: 10008): Unknown Message
code:
@bot.tree.command(name="accept", description="Accept or decline a suggestion")
async def accept(interaction: discord.Interaction, suggestion_id: int, accepted: bool, reason: str):
suggestion_channel_id = 1106959842901504060 # Replace with the ID of the channel where suggestions were submitted
suggestion_channel = bot.get_channel(suggestion_channel_id)
if suggestion_channel is None:
print(f"Could not find channel with ID {suggestion_channel_id}")
return
# Retrieve the suggestion message based on the suggestion ID
suggestion_message = await suggestion_channel.fetch_message(suggestion_id)
if suggestion_message is None:
print(f"Could not find suggestion message with ID {suggestion_id}")
return
# Retrieve the user who made the suggestion
user = suggestion_message.author
if accepted:
acceptance_message = f"Your suggestion with ID {suggestion_id} has been accepted.\n\nReason: {reason}"
else:
acceptance_message = f"Your suggestion with ID {suggestion_id} has been declined.\n\nReason: {reason}"
# Send a direct message to the user with the acceptance/decline message and reason
await user.send(acceptance_message)
await interaction.response.send_message("Suggestion status updated and notification sent to the user!", ephemeral=True)
@client.tree.command(name="clear", description="clear messages (moderator only)")
@discord.app_commands.checks.has_permissions(manage_messages=True)
@app_commands.default_permissions(manage_messages=True)
async def clear(interaction: discord.Interaction, amount: int):
if amount < 2:
await interaction.channel.purge(limit=amount)
#await interaction.response.defer()
await interaction.response.send_message(f"deleted {amount} messages")
#await interaction.channel.send(f"{interaction.user.mention} used the clear command to delete {amount} messages")
print(f"deleted {amount} messages")
if amount > 2:
await interaction.response.defer()
await interaction.channel.purge(limit=amount)
await interaction.response.followup(f"deleted {amount} messages")
#await interaction.channel.send(f"{interaction.user.mention} used the clear command to delete {amount} messages")
print(f"deleted {amount} messages")
``` it is deleting my followup msg
!d discord.Interaction.followup
Returns the follow up webhook for follow up interactions.
@client.tree.command(name="clear", description="clear messages (moderator only)")
@discord.app_commands.checks.has_permissions(manage_messages=True)
@app_commands.default_permissions(manage_messages=True)
async def clear(interaction: discord.Interaction, amount: int):
if amount < 2:
await interaction.channel.purge(limit=amount)
#await interaction.response.defer()
await interaction.response.send_message(f"deleted {amount} messages")
#await interaction.channel.send(f"{interaction.user.mention} used the clear command to delete {amount} messages")
print(f"deleted {amount} messages")
if amount > 2:
await interaction.response.defer()
await interaction.channel.purge(limit=amount)
await interaction.followup.send(f"deleted {amount} messages")
#await interaction.channel.send(f"{interaction.user.mention} used the clear command to delete {amount} messages")
print(f"deleted {amount} messages")
``` I fixed it but it is still deleting my followup message
@client.tree.command(name="clear", description="clear messages (moderator only)")
@app_commands.checks.has_permissions(manage_messages=True)
async def clear(interaction: discord.Interaction, amount: app_commands.Range[int, 10, None]) -> None:
"""
Purge command to delete messages from a channel.
Parameters
----------
interaction: discord.Interaction
The Interaction
amount: app_commands.Range[int, 10, None]
A positive integer with minimum 10 and maximum of no limit.
"""
await interaction.response.defer()
await interaction.channel.purge(limit=amount)
await interaction.followup.send(f"deleted {amount} messages", ephemeral=True)
^^ anyone?
@slate swan can u help?
still deletes the followup
nah
its not possible cuz purge happens before message is sent
plus followup is ephemeral
ik this is what i dont get
Asher mind helping me?
a bot cannot delete ephemeral messages
no the thing is i dont want ephemeral
are u responding in 3 seconds?
ye
i just retried the command and it didn't work and ye i will do that rn
prolly not defer and edit thats much better
!d discord.Interaction.edit_original_response
await edit_original_response(*, content=..., embeds=..., embed=..., attachments=..., view=..., allowed_mentions=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Edits the original interaction response message.
This is a lower level interface to [`InteractionMessage.edit()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.InteractionMessage.edit "discord.InteractionMessage.edit") in case you do not want to fetch the message and save an HTTP request.
This method is also the only way to edit the original message if the message sent was ephemeral.
wdym
.
why would i edit it? when i want to send a accepted message to the user#
defer says to discord wait a few moments i will respond to it
edit then acts as a response to the command
404 rises in 2 cases the
- ur over 3 secs in responding
- the message was deleted
ah right, so i just need to do await edit_original_response
yeah
Quick question
where should i put that?
I built a AFK command yesterday, today i noticed an error
instead of send_message
For some reasons if 1 person goes afk, nobody can go afk because that will raise this error
cause u made guild id primary key and not user id
@slash_command()
async def afk(
self, inter: disnake.ApplicationCommandInteraction, reason: str = None
):
"""
Set your status to AFK.
Parameters
----------
reason: Reason for going AFK.
"""
if reason:
if len(reason) > 100:
embed = report_embed(
False,
description="Limit of reason lenght is at 100 characters!",
)
await inter.send(embed=embed, ephemeral=True)
return
set_reason = reason
else:
set_reason = "They went to shit."
database_guild = await fetch_db_guild(inter.guild.id)
afk = await AfkModel.get_or_none(
guild_id=database_guild, discord_id=inter.author.id
)
if afk:
await afk.update_from_dict({"reason": set_reason}) # Update
else:
await AfkModel.create(
guild_id=database_guild, discord_id=inter.author.id, reason=set_reason
)
if inter.author != inter.guild.owner:
await inter.author.edit(nick=f"[AFK]{inter.author.display_name}")
await inter.send(
f"Set your status to AFK with reason: `{set_reason}` {format_dt(utcnow(), style='R')}"
)
await interaction.response.send_message("Suggestion status updated and notification sent to the user!", ephemeral=True)
?? this?
No, look at my models
yeah
class AfkModel(Model):
"""AFK Model."""
guild_id = OneToOneField("Bot.Guild")
discord_id: int = BigIntField(null=False)
reason = TextField(null=False)
time = DatetimeField(auto_now_add=True)
It's a onetoonefield set to guild
@Cog.listener()
async def on_message(self, message: Message):
user_db = await AfkModel.get_or_none(
discord_id=message.author.id, guild_id=message.guild.id
)
if user_db:
if message.author != message.guild.owner:
await message.author.edit(nick=message.author.name)
await message.reply(
f"Welcome back {message.author.mention}! "
f"You went afk - {format_dt(user_db.time, style='R')}"
)
await user_db.delete()
if message.mentions:
if message.author.id == self.bot.application_id:
return
user = await AfkModel.get_or_none(
discord_id=message.mentions[0].id, guild_id=message.guild.id
)
if user:
member = message.guild.get_member(user.discord_id)
await message.reply(
f"**{member.display_name}** is AFK because: `{user.reason}` "
f"{format_dt(user.time, style='R')}"
)
and my on_message is pretty simple
await interaction.response.defer(ephemeral=True)
await interaction.edit_original_response(embed=embed)
@lean harbor
bro error says u have guild id set to to unique key
means only 1 per table
@bot.tree.command(name="accept", description="Accept or decline a suggestion")
async def accept(interaction: discord.Interaction, suggestion_id: int, accepted: bool, message: str):
suggestion_channel_id = 1106959842901504060 # Replace with the ID of the channel where suggestions were submitted
suggestion_channel = bot.get_channel(suggestion_channel_id)
if suggestion_channel is None:
print(f"Could not find channel with ID {suggestion_channel_id}")
return
# Retrieve the suggestion message based on the suggestion ID
suggestion_message = await suggestion_channel.fetch_message(suggestion_id)
if suggestion_message is None:
print(f"Could not find suggestion message with ID {suggestion_id}")
return
# Retrieve the user who made the suggestion
user = suggestion_message.author
if accepted:
acceptance_message = f"Your suggestion with ID {suggestion_id} has been accepted.\n\nMessage: {message}"
else:
acceptance_message = f"Your suggestion with ID {suggestion_id} has been declined.\n\nMessage: {message}"
# Send a direct message to the user with the acceptance/decline message and reason
try:
await user.send(acceptance_message)
except discord.errors.HTTPException:
print(f"Failed to send a direct message to the user with ID {user.id}")
await interaction.response.defer(ephemeral=True)
await interaction.edit_original_response(embed=embed)
Like this?
primary is unique + not null
But those are my models 😂
put the defer as first line of the function
aight
And it's not set to pk, and on tortoise docs OneToOneField won't set it automatically to pk
unsolved reference for embed
bro embed was an example replace it with ur message
sh.
Oh fuck i just noticed, look
cough cough
🗿
How can i fix this?
it doesn't work it just says Galleon is thinking
discord.app_commands.errors.CommandInvokeError: Command 'accept' raised an exception: NotFound: 404 Not Found (error code: 10008): Unknown Message
if it were me i would declare PRIMARY KEY (guild_id, user_id)
meaning there is an error somewhere
its likely from this line
suggestion_message = await suggestion_channel.fetch_message(suggestion_id)
whats the whole traceback
I don't have that much experience to do that
I didn't even know u can set 2 as primary keys
but thats in raw sql idk django or sqlalchemy
its not its a concept of grouping primary keys
yeah its as i said
Understandable but idk how to do that
but yeah i understood what u mean
how would i fix it
!d discord.TextChannel.fetch_message
await fetch_message(id, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Retrieves a single [`Message`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Message "discord.Message") from the destination.
what if i use get_or_none
its likely suggestion id is wrong
worth a try x)
If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
whats a suggestion id lmao
how else i'm i supposed to tell the bot which one to accept?
its a message id like for example message id for this reply is 1110249532249354332
lmao no
?
;-;
Asher could u help me after?
how i'm i supposed to fetch it
yeah i can
it's not stored..
write the table for it
not u
ah right
@lean harbor u need to rework ur suggestion system
i dont do dms
whats wrong
👍
i can however write a table sample and send it
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
"""
CREATE TABLE IF NOT EXISTS afk (
user_id BIGINT,
guild_id BIGINT,
reason TEXT DEFAULT "No reason provided.",
PRIMARY KEY (user_id, guild_id)
);
"""
here is a sample
i generally just use asyncpg
wish it was raw, i understand ur logic tho and i get what u mean
but using tortoise that would be harder 😂
that's what creates the shema
i use aiosqlite
postgres ftw
asher quite question, how would i make the description be above the galleon price and strong scroll price? I'm using a database to the get the description
no idea how that works u can ask in #databases
!d discord.Embed.add_field
add_field(*, name, value, inline=True)```
Adds a field to the embed object.
This function returns the class instance to allow for fluent-style chaining. Can only be up to 25 fields.
inline property
ehh, how would i implement that?
, inline=False) ?
what should I use to handle discord oauth application in my dashboard? Zuora ? Currently I use quart and better-ipc
I usually just handle oauth client-side honestly
Usually with Auth.js
i see
and sending it to the api then
Sending what to which API?
sending the information of the user to the quart api
Yeah something along those lines works
The server can also access cookies
So if you've got a JWT in there for instance, you have access
alright, ill think about that, thank you very much
if warns_amt == > 6:
await user.timeout(duration2)
await serverlog.send(embed=embed2)
```it says this is invalid syntax
how?
the if statement
the 6
it means if the varible is over 6
that is not valid python
do you mean the "=="
<= is less than or equal to
>= is greater than or equal to
this is quite essential python knowledge you should have before making a discord bot
ohhhhhhhhghhhhhhhhhhhhhhhh i understand now
How do I get a message's link that makes you jump to it in discord.py?
!d discord.Message.jump_url
property jump_url```
Returns a URL that allows the client to jump to this message.
thank you
code : ```@discord.ui.button(label='Save', style=discord.ButtonStyle.green, emoji=':page_with_curl:')
async def menu2(self, interaction, button: discord.Button):
role = discord.utils.get(interaction.guild.roles, id=826071242317627402)
if role not in interaction.user.roles:
await interaction.response.send_message("You are not staff. You can't save the ticket!",ephemeral=True)
return
emb = discord.Embed(colour=discord.Colour.random())
emb.set_author(name=f"Date: {datetime.datetime.now()}")
emb.add_field(name=interaction.channel.name, value=f'Saved by {interaction.user}')
transcript_channel_id = 893175113623695450
transcript_channel = bot.get_channel(transcript_channel_id)
messages = []
async for m in interaction.channel.history():
messages.append(f'{m.author}: {m.content}\n')
messages = numpy.flip(messages)
allMessages = ''
for msg in messages:
allMessages += msg
emb.add_field(name='Messages:', value=allMessages)
emb.set_footer(text=f"{interaction.guild.name}",icon_url={interaction.guild.icon})
await transcript_channel.send(embed=emb)
emb = discord.Embed(colour=discord.Colour.blue())
emb.set_author(name=f"ticket was saved by {interaction.user}")
await interaction.channel.send(embed=emb)``` error: ```
Traceback (most recent call last):
File "C:\Users\KokoG\PycharmProjects\Logger\venv\Lib\site-packages\discord\ui\view.py", line 427, in _scheduled_task
await item.callback(interaction)
File "C:\Users\KokoG\PycharmProjects\Logger\Tests\test2.py", line 96, in menu2
await transcript_channel.send(embed=emb)
File "C:\Users\KokoG\PycharmProjects\Logger\venv\Lib\site-packages\discord\abc.py", line 1561, in send
data = await state.http.send_message(channel.id, params=params)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^```
how to fix
Please provide the full traceback for your exception in order to help us identify your issue.
While the last line of the error message tells us what kind of error you got,
the full traceback will tell us which line, and other critical information to solve your problem.
Please avoid screenshots so we can copy and paste parts of the message.
A full traceback could look like:
Traceback (most recent call last):
File "my_file.py", line 5, in <module>
add_three("6")
File "my_file.py", line 2, in add_three
a = num + 3
~~~~^~~
TypeError: can only concatenate str (not "int") to str
If the traceback is long, use our pastebin.
Im trying to use app commands and i cant find the name of the thing when do can select from a menu within the slash command, does anyone know the name of it? would be greatly apricated.
Choices?
maybe
this can be shortened greatly
messages = []
async for m in interaction.channel.history():
messages.append(f'{m.author}: {m.content}\n')
messages = numpy.flip(messages)
allMessages = ''
for msg in messages:
allMessages += msg```
hint: instead of appending it, try to add it in front when adding
also, only the async for loop is needed...
is it possible to make the library use a custom subclass of InteractionResponse
you have three options
@app_commands.autocompletedecorator@app_commands.choicesdecoratortyping.Literalannotation
choices and literal are best for options that don't change while your program is running, and autocomplete is better from data that is dynamic such as data you get from a database
"the library" as in dpy?
I would think so, yes
I've seen devs extend Context, Bot, ... so I'd give it a go
afaik only a few classes get that sort of treatment, the rest of dpy's models cant be replaced without modifying the library directly
hmm there should be an API to manage model classes
orrrr you're having an XY problem
wouldnt play well with typehints, e.g. Client.users returns list[User] which would be incorrect if you replaced the User model
doesn't user include everything extending it
no it's just convenient
That being said, extending a user doesn't really seem something that's ever necessary, as you can't really change what you're getting from the API
from the type checker's perspective you're only allowed to use the API provided by User, even if it was a subclass at runtime
fork dpy
ah yes, and make breaking changes while doing so 🙂
i dont have much issues with dpy except i dont like its slash command impl and perhaps access or a few more additional lower level events
ive tried using generic typehints for models in a separate library of my own, but it didnt help at all and i ended up repeating all the typehints + type ignores
reinventing the wheel seems a better term
when in doubt # type: ignore
works 100%
if you really wanted to change the API i think forking is the most reasonable choice, but of course that's harder to maintain than making some wrapper class or functions for stuff you need
true
what dont you like about it? im a fan because the application command functionality is isolated from Client and doesn't bloat it with more methods than it already has
once u fork with major changes u have walked a path of no return
how they lump all the interactions together only shining point of all that is the hybrid commands plus few other stuff like disnake has a lot more raw components access like stateless views idk if thats a thing in dpy since i havent followed latest changes
hm how does disnake handle that
Summary We need a way to handle components without being forced to use a view. The Problem Currently, a huge problem left over from discord.py is the enforced usage of views. Generally, most compon...
has this issue tracking it
disnake dosent have hybrid commands thats maybe one con over dpy but it has multiple interaction classes
based on view components
oh is that it? dispatching some function based on a static custom id? why would using a view be an issue?
apparently saves memory for small views
hybrid commands

thats one another bad experience i have had was previously during developement they left a memory leak which they only found out after a few months
with the views
oh wait did disnake actually implement a convenient API for having state in custom id?
i spent so much time messing with gc
also, things like ctx.defer() should definitely not exist
i dont believe that because you only need a single persistent view to dispatch for all messages, assuming the custom ID is static
prolly yeah since they are persistent
yeah but with the view lib handles gateway events that dosent happen stateless
u gotta do it urself
i dont get what you mean
with views the lib stores more method calls attributes and data in short
not that much of a difference but yeah slight memory saving
for the first statement persistency is different from dynamic custom ids, persistent views have existed for a while but afaik dynamic ids havent escaped dpy's bikeshedding phase
in the order of bytes maybe, but ig whatever happened with the memory leak would have been a bug in the viewstore i assume
u mean dpy? wait a sec lemme get the message link it was announced in announcement channel
well at least part of the problem was in ViewStore so not a bad guess
https://github.com/Rapptz/discord.py/commit/6cb9a848988f2d9bf88893eae5548cf42795068c
gnighty
like you would rather have the method only exist in some hybrid-specific context class?
I need help with one of my parameters for creating an automod rule.
the trigger parameter.
what about it? yknow people can't know to fix the exact problem till u say it :P
What do I need to pass into the trigger parameter.
Im reading the docs and it is referencing a AutoModRuleTriggerType
so I passed it that, but it isn't the AutoModTrigger type that they are asking for
it looks like AutoModRuleTriggerType is just an enum for specifying what sorta filter it is exactly
and the docs for AutoModTrigger seem to specify which params are actually important for each trigger type
AutoModTrigger(
type=AutoModRuleTriggerType.keyword,
keyword_filter="badword"
)
Yes. But I have to pass a trigger object, which contains the trigger type, no?
Oh.
Where did you find that? I didn't see it in docs.
Yeah wait, there isn't a rule arg.
class discord.AutoModTrigger(*, type=None, keyword_filter=None, presets=None, allow_list=None, mention_limit=None, regex_patterns=None)```
Represents a trigger for an auto moderation rule.
The following table illustrates relevant attributes for each [`AutoModRuleTriggerType`](https://discordpy.readthedocs.io/en/latest/api.html#discord.AutoModRuleTriggerType "discord.AutoModRuleTriggerType")...
also i meant type
There is no rule arg...
https://discordpy.readthedocs.io/en/stable/api.html?highlight=guild#discord.Guild.create_automod_rule
the trigger kwarg is of the AutoModTrigger type, which in turn uses the AutoModRuleTriggerType enum to specify its type
Traceback (most recent call last):
File "C:\Users\hgold\PycharmProjects\lang_bot\venv\lib\site-packages\discord\app_commands\commands.py", line 841, in _do_call
return await self._callback(self.binding, interaction, **params) # type: ignore
File "C:\Users\hgold\PycharmProjects\lang_bot\lang\ext\cogs\automod.py", line 14, in spam
await interaction.guild.create_automod_rule(name="Spam",
File "C:\Users\hgold\PycharmProjects\lang_bot\venv\lib\site-packages\discord\guild.py", line 4024, in create_automod_rule
actions=[a.to_dict() for a in actions],
File "C:\Users\hgold\PycharmProjects\lang_bot\venv\lib\site-packages\discord\guild.py", line 4024, in <listcomp>
actions=[a.to_dict() for a in actions],
AttributeError: '_EnumValue_AutoModRuleActionType' object has no attribute 'to_dict'```
@group.command(name="spam")
async def spam(self, interaction: Interaction, enabled: bool) -> None:
await interaction.guild.create_automod_rule(name="Spam",
event_type=AutoModRuleEventType.message_send,
trigger=AutoModTrigger(type=AutoModRuleTriggerType.spam),
actions=[AutoModRuleActionType.block_message], enabled=enabled)
i think it wants actions to be of type AutoModRuleAction, rather than AutoModRuleActionType
oh hm you can just pass AutoModRuleAction()
Oh shoot ur right, I didn't realize there was a differnet error message.
(and looking at the d.py source, the type actually gets decided by which kwargs you pass)
Interesting.
Oh wait yeah I read that like a couple of hours ago.
If I want it to block the message, I think u just don't provide any params right?
seems that's how you do it yeah
huh that's kind of a weird default
why doesn't it just default to[AutoModRuleAction()] then
Aight got it to work.
@bot.listen('on_message_edit')
async def on_message_edit(before, after):
if "swear word" in after.content:
await message.delete()
I'm pretty new to python, how would I fix this so that when a message is edited to a certain word, the message is deleted?
that should work
ok new problem pertaining to async functions
so I set up a function which basically counts until it reaches a set value
problem is, this is at the end of an iterated function
and the function doesn't move on to the next iteration
Tysm
Also, how can I add a description to the params in a slash command?
!d discord.app_commands.describe
@discord.app_commands.describe(**parameters)```
Describes the given parameters by their name using the key of the keyword argument as the name.
Example:
```py
@app_commands.command(description='Bans a member')
@app_commands.describe(member='the member to ban')
async def ban(interaction: discord.Interaction, member: discord.Member):
await interaction.response.send_message(f'Banned {member}')
``` Alternatively, you can describe parameters using Google, Sphinx, or Numpy style docstrings...
kk tysm
message isn't defined and it doesn't seem to pick up the swear word in the edited message
oh it should be after.delete then
ok so my bot is iterating a function and the function ends with an async function. The async function is preventing the iteration from ending and starting the next
how can I run the async function while still moving to the next iteration
!e ```py
import asyncio
async def fn_taking_time():
await asyncio.sleep(5)
print("time taking")
async def other_fn():
print("other")
fns = [fn_taking_time(), other_fn()]
async def main():
for coro in fns:
asyncio.create_task(coro)
asyncio.run(main())
@slate swan :white_check_mark: Your 3.11 eval job has completed with return code 0.
other
^
how will this new change to discord names affect discordpy?
they'll probably just remove the .discriminator attribute after deprecating it to return 0 for a while
import discord
def run_discord_bot():
TOKEN = '**************************'
client = discord.Client()
client.run(TOKEN)
@bot.listen('on_message_edit')
async def on_message_edit(before, after):
if "swear word" in after.content:
await after.delete()
What do i need to do to define bot?
!d discord.ext.commands.Bot
and you shouldnt have both client and bot instances
class discord.ext.commands.Bot(command_prefix, *, help_command=<default-help-command>, tree_cls=<class 'discord.app_commands.tree.CommandTree'>, description=None, intents, **options)```
Represents a Discord bot.
This class is a subclass of [`discord.Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client") and as a result anything that you can do with a [`discord.Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client") you can do with this bot.
This class also subclasses [`GroupMixin`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.GroupMixin "discord.ext.commands.GroupMixin") to provide the functionality to manage commands.
Unlike [`discord.Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client"), this class does not require manually setting a [`CommandTree`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CommandTree "discord.app_commands.CommandTree") and is automatically set upon instantiating the class.
async with x Asynchronously initialises the bot and automatically cleans up.
New in version 2.0.
ok ty
Yeah I think old API versions will just return 0 not to break stuff that works on them and new ones will get rid of it completely
Hey can anyone tell me why this error is coming??????
Remove the brackets after @bot.event
Ok
also its not on_message_edit in listen() u prolly need message_edit or just leave it empty
gather be like 💀
Why
I see nothing wrong
i just leave it empty usually if i have the function name
I mean, why do you need to remove the on before the event name
how do i bypass a global check for some commands?
dosent the bot dispatch with bot.dispatch("event", ...
and we listen on_event
i thought on was removed 😔 i am too lazy to open source
!d discord.ext.commands.Bot.listen
@listen(name=None)```
A decorator that registers another function as an external event listener. Basically this allows you to listen to multiple events from different places e.g. such as [`on_ready()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_ready "discord.on_ready")
The functions being listened to must be a [coroutine](https://docs.python.org/3/library/asyncio-task.html#coroutine "(in Python v3.11)").
Example...
@bot.listen('on_message')
async def my_message(message):
print('two')

It's personal preference, I guess
!d disnake.Event
class disnake.Event(value)```
Represents all the events of the library.
These offer to register listeners/events in a more pythonic way; additionally autocompletion and documentation are both supported.
New in version 2.8.
Disnake best

trying to implement ui stuff and got flashbacks from when I first started trying slash commands
await timeout(until, /, *, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Applies a time out to a member until the specified date time or for the given [`datetime.timedelta`](https://docs.python.org/3/library/datetime.html#datetime.timedelta "(in Python v3.11)").
You must have [`moderate_members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.moderate_members "discord.Permissions.moderate_members") to do this.
This raises the same exceptions as [`edit()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member.edit "discord.Member.edit").
@north kiln hey can you explain it please I dont get it
is on_message the only way to listen to messages? I'm interested in messages from only one channel.
yes, on_message will listen to messages from all visible channels
there's no way for a single channel listener, just use an if statement
okay, so now I've another question if you dont mind, how can I know what decorator to use, I'm in a cog
and standard @bot.event wont work
!d discord.ext.commands.Cog.listener
classmethod listener(name=...)```
A decorator that marks a function as a listener.
This is the cog equivalent of [`Bot.listen()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.listen "discord.ext.commands.Bot.listen").
thanks, worked 🙂
is it possible to get the channel id with the name channel
cause on message - message.channel gives you the name of the channel
not the id
message.channel.id
oh
async def on_message(self, message):
if message.author == self.bot:
``` isnt this enough to avoid message recursion?
cause it doesnt seem to work
what's inside the if statement?
return
No full code moment
mb
What doesn't work
avoiding recursion
if the bot is the author, I want to ignore the message by returning
from discord_slash import SlashCommand
ModuleNotFoundError: No module named 'discord_slash
i installed it many times
i updated too
Just use discord.py's app_commands
someone can help?
if message.author == self.bot:
this condition is not met
im beginner, how?
!d discord.app_commands.CommandTree
class discord.app_commands.CommandTree(client, *, fallback_to_global=True)```
Represents a container that holds application command information.
Try self.bot.user
``import discord
from discord.ext import commands
from discord_slash import SlashCommand
intents = discord.Intents.default()
intents.typing = False
intents.presences = False
bot = commands.Bot(command_prefix='!', intents=intents)
slash = SlashCommand(bot, sync_commands=True)
@bot.event
async def on_ready():
print(f'Zalogowano jako {bot.user.name}')
@slash.slash(name="hello", description="test")
async def przywitaj(ctx):
await ctx.send('witaj! <3.')
@bot.event
async def on_slash_command(ctx):
await bot.process_commands(ctx)
bot.run('censored)``
where i can add it?
add what
You should at least have basic knowledge of Python to be comfortable with discord.py
Or whatever fork you maybe using
ok
and where should i override and add this command?
Are there any bots in this server in #bot-commands that work using Python? I’d be interested to try them out
I don't understand what you're saying
You mean, are they written in Python?
Yeah
!source
I want to see what a Python bot does
you can see the code for @unkempt canyon there ^
Perfect, thanks
🐈
So that bot is coded in Python, and helps the Python server 😎
A bot written in python will do the same as one written in another language,
is it just me or do you guys also have this after discord update?
that discord doesn’t process the * and the _ in the text?
can you share the exact text you used in your description? i cant reproduce it
fyi
- 1
- 2
both - and * can be used for unordered lists
either that's the reason or u made some mistake with formatting
embed = nextcord.Embed(
title="Verification BirdSupply",
description=
"By clicking the verify button down below you agree that: \n \n - You agree with [#1054496495937794149](/guild/267624335836053506/channel/1054496495937794149/) \n - When trying to mislead us, we will ban you. \n - You follow the rules of discord [ToS](https://discord.com/terms). \n \n **The password to enter the server is __birdsupply__**",
color=0x2f3136)
embed.set_footer(text="Make sure to verify yourself within 1 day, else you will get kicked!", icon_url="https://cdn.discordapp.com/icons/1000710577716469820/535923a1c6dc11930b821a3ef0e82167.png?size=4096")
await verificationChannel.send(embed=embed, view=view)```
ye I have no clue how, but on my laptop I see this while on my phone I see -1 *2
just remove the space between \n and **The password
let me try, thanks
lol
thanks
tried every single configuration to repro that tbh
@app_commands.command(name="move", description="Moves the inputted number of messages to the inputted thread.")
@app_commands.describe(number="The number of messages to move.")
@app_commands.describe(thread="The name of the thread to move the messages to.")
async def move(interaction: discord.Interaction, number: int, thread: str):```
If my commands are formatted like this, how should I be auto syncing in setup_hook?
I havent coded bots in a while
I am trying to make one with out cogs
Do you want these to be global or synced to a specific guild?
Yeah should just be a await bot.tree.sync() then
However be advised these may take up to one hour to propagate
that's what I am doing
You're good then
@client.event
async def setup_hook():
await client.tree.sync()
I am wanting to test it but it is taking forever to load
Are you sure I am doing it right
Yeah like I mentioned global commands take up to an hour to propagate
That's old, nowadays it's instant
Oh is it?
Took up to an hour few years ago
yeah that's what happened with my other bots
I was using files to organize my commands in
Try syncing it to a specific guild, then
async def setup_hook():
guild = discord.Object(id=123)
client.tree.copy_global_to(guild=guild)
await client.tree.sync(guild=guild)
iirc
Also you can use describe with commas and describe multiple parameters in a single decorator
oh
is there a max amount of parameters for a slash command?
25
alr thanks
gather doesnt process in order @shrewd apex
at most is the bot sending the same messages in a thread I guess
you can't really "move" them
I though there was a way
did they ask for order?
time to scroll
how can i check has role in ctx?
i only know how to do that in tree
@commands.check_has.role(role id)
like that?
have you tried it?
it was @commands.has_role
yup
someone know why i'm getting the error: 'NoneType' object has no attribute 'url'?
server = bot.get_guild(123456789...)
embed = discord.Embed(title='...')
embed.set_author(name='...')
embed.set_thumbnail(url=server.icon.url)
sounds like i cant set the icons of guilds as thumbnails of embeds anymore
is that your actual code?
server.icon is None
!d discord.Guild.icon
property icon```
Returns the guild’s icon asset, if available.
Optional[Asset]
!d discord.Member.remove_roles
await remove_roles(*roles, reason=None, atomic=True)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Removes [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role "discord.Role")s from this member.
You must have [`manage_roles`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_roles "discord.Permissions.manage_roles") to use this, and the removed [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role "discord.Role")s must appear lower in the list of roles than the highest role of the member.
kk ty
not defined
oh nvm
mb im dumb
await discord.Member.remove_roles(role_name)
it dont remove the role
then what do i use
can u give me a example?
consider showin full code tho
u need to fetch the role with id
ok hold up lemme try
await delete(*, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Deletes the role.
You must have [`manage_roles`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_roles "discord.Permissions.manage_roles") to do this.
Is there a channel where I can advertise my Python to Rust discord bot translation service?
its saying expired and remove from the mongo data base but it dont remove the role from the member
??
no
so they can be blazing fast and fearlessly concurrent !
Hi

@bot.tree.command(name = "add-scamlist", description = "Add user in scamlist")
async def add_scamlist(interaction, member: discord.User, reason: str):
if (interaction.user.id == 944574924234846298):
await interaction.response.defer()
try:
with open("scamlist.json", "r") as f:
exist = json.load(f)
identifiant = exist.get('id')
reason_exist = exist.get('reason')
if (member.id == identifiant):
embed_exist = discord.Embed(title = "Member is already in scamlist", description = f"Reason: {reason_exist}")
await interaction.followup.send(embed=embed_exist)
return
else:
with open("scamlist.json", "w") as f:
data = {
"id": member.id,
"name": member.name,
"reason": reason,
"server": interaction.guild
}
json.dump(data, f)
embed = discord.Embed(title = "User add in Scamlist", description = f"{member} add in scamlist for {reason}")
await interaction.followup.send(embed=embed)
except:
embed_error = discord.Embed(title = "Error", description = "An error has occurred please try again later")
await interaction.response.send_message(embed=embed_error)
else:
await interaction.response.send_message("Only owner bot can use this command")```
I search check if member.id already exist in scamlist.json but i don't know how i can check for all id in .json
Are id's ordered?
If not just loop over id's and check one by one
Yes is ordered
Does scamlist only contain ids?
{"id": 944574924234846298, "name": "icetea࿐#2752", "reason": "test", "server": "My server"}
oh alright
You'll need to serialize objects with id and check each
I'd recommend pre serializing objects and creating a list with the ids
Then doing user_id in id_list
How to create a list ?
[] or list()
How i can while in json for get only all id ?
You can use a set as well
what do you mean by this
do you want to get all IDs from your JSON file?
yes
do you have these sub-dicts inside a list in your JSON?
if so, just use a for loop and append the id key of each item to a list
a list comprehension would be a short way of doing it
[item["id"] for item in data]
if you haven't used list comprehensions before it might be better to stick to a normal for loop to avoid confusing yourself
yo would this work l = ["q", "w", "e", "r", "t", "y", "u", "i", "o", "p", "a", "s", "d", "f", "g", "h", "j", "k", "l", "z", "x", "c", "v", "b", "n", "m", "!", ",", ".", "?", "_", "-", "+", "/", " "] blockedwords = ["idiot", f"i{l}d{l}i{l}o{l}t", "dum", f"d{l}u{l}m", "stupi", f"s{l}t{l}u{l}p{l}i", "fat", f"f{l}a{l}t", "sucker", f"s{l}u{l}c{l}k{l}e{l}r", "loser", f"l{l}o{l}s{l}e{l}r", "nerd", f"n{l}e{l}r{l}d"]
Why would it
i thought i would
Unless you want to block
'i[q", "w", "e", "r", "t", "y", "u", "i", "o", "p", "a", "s", "d", "f", "g", "h", "j", "k", "l", "z", "x", "c", "v", "b", "n", "m", "!", ",", ".", "?", "_", "-", "+", "/", " "]d [q", "w", "e", "r", "t", "y", "u", "i", "o", "p", "a", "s", "d", "f", "g", "h", "j", "k", "l", "z", "x", "c", "v", "b", "n", "m", "!", ",", ".", "?", "_", "-", "+", "/", " "]i [q", "w", "e", "r", "t", "y", "u", "i", "o", "p", "a", "s", "d", "f", "g", "h", "j", "k", "l", "z", "x", "c", "v", "b", "n", "m", "!", ",", ".", "?", "_", "-", "+", "/", " "]o [q", "w", "e", "r", "t", "y", "u", "i", "o", "p", "a", "s", "d", "f", "g", "h", "j", "k", "l", "z", "x", "c", "v", "b", "n", "m", "!", ",", ".", "?", "_", "-", "+", "/", " "]t'
import string left the chat
ohh string yes
would there be another way
How i can all info for one id in my .json ?
{"id": 944574924234846298, "name": "icetea࿐#2752", "reason": "test", "server": "My server"}
you're probably looking for regex
Wdym
@bot.tree.command(name="remove-scamlist", description="Remove user in scamlist")
async def remove_scamlist(interaction, id: str, reason: str):
if interaction.user.id == 944574924234846298:
await interaction.response.defer()
try:
with open("scamlist.json", "r+") as f:
scamlist_data = json.load(f)
if id in [entry["id"] for entry in scamlist_data]:
scamlist_data = [entry for entry in scamlist_data if entry["id"] != id]
json.dump(scamlist_data, f, indent=4)
embed_remove = discord.Embed(title="Member is removed from scamlist", description=f"Reason: {reason}")
await interaction.followup.send(embed=embed_remove)
guild_id = interaction.guild.id
if database_scamlist.get_channel(guild_id) is None:
return
channel_send = database_scamlist.get_channel(guild_id)
embed_rm = discord.Embed(title = "User remove in ScamList", description = f"<@{id}> is removed in ScamList")
embed_rm.add_field(name = "Reason:", value = f"{reason}")
channel_send.send_message(embed=embed_rm)
else:
embed = discord.Embed(title="Member not found in scamlist", description=f"ID: {id}")
await interaction.followup.send(embed=embed)
except:
embed_error = discord.Embed(title="Error", description="An error has occurred, please try again later")
await interaction.followup.send(embed=embed_error)
else:
await interaction.response.send_message("Only the bot owner can use this command")```
2023-05-23 20:57:22 ERROR discord.app_commands.tree Ignoring exception in command 'remove-scamlist'
Traceback (most recent call last):
File "/home/container/otrobot.py", line 503, in remove_scamlist
scamlist_data = json.load(f)
^^^^^^^^^^^^
File "/usr/local/lib/python3.11/json/init.py", line 293, in load
return loads(fp.read(),
^^^^^^^^^^^^^^^^
File "/usr/local/lib/python3.11/json/init.py", line 346, in loads
return _default_decoder.decode(s)
^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/usr/local/lib/python3.11/json/decoder.py", line 340, in decode
raise JSONDecodeError("Extra data", s, end)
json.decoder.JSONDecodeError: Extra data: line 3 column 2 (char 8)
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/home/container/.local/lib/python3.11/site-packages/discord/app_commands/commands.py", line 842, in _do_call
return await self._callback(interaction, **params) # type: ignore
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/container/otrobot.py", line 524, in remove_scamlist
await interaction.response.send_message(embed=embed_error)
File "/home/container/.local/lib/python3.11/site-packages/discord/interactions.py", line 751, in send_message
raise InteractionResponded(self._parent)
discord.errors.InteractionResponded: This interaction has already been responded to before
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/container/.local/lib/python3.11/site-packages/discord/app_commands/tree.py", line 1248, in _call
await command._invoke_with_namespace(interaction, namespace)
File "/home/container/.local/lib/python3.11/site-packages/discord/app_commands/commands.py", line 867, in _invoke_with_namespace
return await self._do_call(interaction, transformed_values)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/container/.local/lib/python3.11/site-packages/discord/app_commands/commands.py", line 860, in _do_call
raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'remove-scamlist' raised an exception: InteractionResponded: This interaction has already been responded to before
This interaction has already been responded to before
This interaction has already been responded to before
@shrewd vapor
await interaction.response.send_message(embed=embed_error)
!d discord.Interaction.followup
Returns the follow up webhook for follow up interactions.
Yes i have see i have changed
do a followup or edit it
error with json i need help
It's not a JSON error though
Traceback (most recent call last):
File "/home/container/otrobot.py", line 503, in remove_scamlist
scamlist_data = json.load(f)
^^^^^^^^^^^^
File "/usr/local/lib/python3.11/json/init.py", line 293, in load
return loads(fp.read(),
^^^^^^^^^^^^^^^^
File "/usr/local/lib/python3.11/json/init.py", line 346, in loads
return _default_decoder.decode(s)
^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/usr/local/lib/python3.11/json/decoder.py", line 340, in decode
raise JSONDecodeError("Extra data", s, end)
json.decoder.JSONDecodeError: Extra data: line 3 column 2 (char 8)
During handling of the above exception, another exception occurred:
line 3 column 2 (char 8) check whats on this position
Its error json
{
}{"id": 1108857720100114434, "name": "Azalee", "reason": "test", "server": "\ud83c\udf19\u30fbMoonGen"}
Bruh
He write after }
Also next time use a pastebin to send your super long traceback 
Yes sry lol
you need commas after objects in json
And you'll need to make it a list
[
{
"blah": "blah"
},
{
"bleh": "bleh"
}
]
https://jsonformatter.curiousconcept.com/# this one is nice it fixes 99.99% json errors
Ok i go see
i mean usually with quotes and stuff pretty neat as a formatter my go to is this and one more site called jsoncrack for visualization purposes
Ok thanks
with open('blocked words.txt') as blockedwords:
if msg in blockedwords.read():
await message.delete()
await message.channel.send(f"{message.author.mention}", embed=embed, delete_after=10)
```my bot is deleting embeds
@bot.tree.command(name = "add-scamlist", description = "Add user in scamlist")
async def add_scamlist(interaction, member: discord.User, reason: str):
if (interaction.user.id == 944574924234846298):
await interaction.response.defer()
try:
with open("scamlist.json", "r+") as f:
exist = json.load(f)
identifiant = exist.get('id')
reason_exist = exist.get('reason')
if identifiant in [item["id"] for item in exist]:
if (member.id == identifiant):
embed_exist = discord.Embed(title = "Member is already in scamlist", description = f"Reason: {reason_exist}")
await interaction.followup.send(embed=embed_exist)
return
else:
data = {
"id": member.id,
"name": member.name,
"reason": reason,
"server": interaction.guild.name,
}
json.dump(data, f)
f.write(f",")
embed = discord.Embed(title = "User add in Scamlist", description = f"{member} add in scamlist for {reason}")
await interaction.followup.send(embed=embed)
guild_id = interaction.guild.id
if database_scamlist.get_channel(guild_id) is None:
return
channel_send = database_scamlist.get_channel(guild_id)
embed_log = discord.Embed(title = "New user in ScamList", description = f"<@{member.id}> is added in ScamList")
embed_log.add_field(name = "Reason:", value = f"{reason}")
channel_send.send_message(embed=embed_log)
except:
embed_error = discord.Embed(title = "Error", description = "An error has occurred please try again later")
await interaction.followup.send(embed=embed_error)
else:
await interaction.response.send_message("Only owner bot can use this command")```
If you can help me i don't have traceback
That is because you eat the entire error
can someone help me
except Exception as e:
print(e)
Then you'll get an error in the console with your try/except
'list' object has no attribute 'get'
check if the msg is an embed @formal basin
yeah because it's a List...
ok
How i can get in a list ?
should i return false
what are you trying to do?
why would you return false?
like how would i ignore it
Get id in my json for check if member i try enter in scamlist exist already or not with ID
you index it
how can i check for a embed using a if statement
if len(message.embeds) > 0:
for embed in message.embeds:
# Check if the message contains an embed
if isinstance(embed, discord.Embed):
# do something here
thanks
why the isinstance check?
how would i ignore it
embeds definitely will be a list of embed objects, redundant check
why not just if message.embeds ?
I don't understand
it's an old code I wrote for a bot I just copied and pasted it
but yeah that is far more efficient
are you loading the json file with the json module? it represents json contents as python dicts
and then you can access these dictionaries to get your ID
not really
A structure like
[
{
"a": "a"
},
{
"a": "b"
}
]
is totally valid JSON, and what they have iirc.
You will not have a dict for that, they'll have to make key:value in the JSON before
btw opening and reading a file are blocking operations, additionally it seems like you're trying to use a json file as a database; just use a database
you mean dict[0]["a"]?
would i return it
And that's what they don't do
if message.embeds:
pass

They try list.get(...) thinking it's a key:value when it's a list
oh pass
for some reason it is still deleting embeds
show me your entire code
of the event
yeah
@client.listen("on_message")
async def coolmessage(message):
if message.author.id == client.user.id:
return
message.content
embed = discord.Embed(title="please dont say that", color=discord.Color.blue())
msg = message.content.lower()
with open('blocked words.txt') as blockedwords:
if msg in blockedwords.read():
await message.delete()
await message.channel.send(f"{message.author.mention}", embed=embed, delete_after=10)
if message.embeds:
pass
```
Bruh my bot write this in json
[
]{"id": 1108857720100114434, "name": "Azalee", "reason": "test", "server": "\ud83c\udf19\u30fbMoonGen"},```
he don't write in []
he write after
put if message.embeds: after if message.author.id == client.user.id:
ok
@shrewd vapor
@client.listen("on_message")
async def coolmessage(message):
if message.author.id == client.user.id:
return message.content
if message.embeds:
pass
else:
with open('blocked words.txt') as blockedwords:
if msg in blockedwords.read():
await message.delete()
await message.channel.send(f"{message.author.mention}", embed=embed, delete_after=10)
I don't want use database for the moment
this isn't formatted correct but you get the idea
ok
My code need a big update for only use database
it deletes it but doesnt send the message
i fixed it
because you're returning message.content
no i was doing else on the embed]
Yes i know, i have only one file json only for scamlist i update after if i have the time
Traceback (most recent call last):
File "/home/runner/zag/venv/lib/python3.10/site-packages/discord/client.py", line 441, in _run_event
await coro(*args, **kwargs)
File "main.py", line 191, in coolmessage
if msg in blockedwords.read():
UnboundLocalError: local variable 'msg' referenced before assignment```im getting this error when a embed is sent.
error says it all
fixed it
You pretty much copied that code without looking at it again

Also return message.content makes no sense
Just return and that's it
Yoo, I'm trying to get my bot to tag another bot(it's a music bot) to play something, it does return the message. But the other bot doesn't accept it. Is it possible to do something like this, or not possible at all?
No
I see.
Most bots ignore messages from other bots in case you're wondering why
Yeah, was making sure. Tyty
can someone pls help me with my discord bot i am trying to make a music bot and it joins vc but it just doesn't play any audio
Send the code that plays the audio
Evening lads im struggling with adding cogs to my bot. Am i alright to send the entire code here or do you require it in a codedump? Thanks 🙂
Can you send just the part that's responsible for adding the cogs?
If it's small you can send it directly here
of course lad.. so in the "main.py" file ive just got "bot.load_extension('MathCog')"... at the bottom the "mathcog.py" ive set it up as def setup(bot): bot.add_cog(MathCog(bot))"
is your file called MathCog.py?
What's your discord.py version? (pip show discord.py)
its lowercase. ive just tried it like that and the same error
2.2.3
Loading extensions and adding cogs is done asynchronously in 2.0+
it is case sensitive
awh... thank youu
@bot.event
async def setup_hook() -> None:
await bot.load_extension("mathcog")
im sorry im new to all this lad.. give me a second to try and process 🙂 appreiciate you all
How to make the commands visible only to people with permissions ?
which commands
what type though
slash commands prefix commands
I am sorry, im struggling with this. so what code do i need to have inside the cog and which code do i need to have inside the main.py file. Sorry if its a stupid question 🙂 thanks
slash command
!d discord.app_commands.checks.has_permissions
@discord.app_commands.checks.has_permissions(**perms)```
A [`check()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.check "discord.app_commands.check") that is added that checks if the member has all of the permissions necessary.
Note that this check operates on the permissions given by [`discord.Interaction.permissions`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Interaction.permissions "discord.Interaction.permissions").
The permissions passed in must be exactly like the properties shown under [`discord.Permissions`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions "discord.Permissions").
This check raises a special exception, [`MissingPermissions`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.MissingPermissions "discord.app_commands.MissingPermissions") that is inherited from [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CheckFailure "discord.app_commands.CheckFailure").
New in version 2.0...
I check already if he have permission just i search for people don't have permission he can't see the command
i'd recommend looking at this, also make sure to not confuse extension and cog
okay danke 🙂
Default permission?
!d discord.app_commands.Command.default_permissions
The default permissions that can execute this command on Discord. Note that server administrators can override this value in the client. Setting an empty permissions field will disallow anyone except server administrators from using the command in a guild.
Due to a Discord limitation, this does not work on subcommands.
can someone help me turn this tool into a discord bot?
I love "this tool", lots of information 
Why is it sending like this
random.choices returns a list
use random.choice
This is deleting random embeds
!e print("" in "some random words")
@vocal snow :white_check_mark: Your 3.11 eval job has completed with return code 0.
True
message.content.lower() would be an empty string if there is no content (like when an embed is sent)
Yeah isn’t it empty
Yeah, it's an empty string
^^
So is it deleting embeds then?
well, yeah, if the message doesn't have any text, then the check will be True, leading to the message's deletion
The if statement executes because an empty string is always in a non empty string, hence the message is deleted
Ohh I see
So what would I do?
How would you ensure that the string is not empty?
An if statement?
Right, but which condition would you check?
If the message is empty
Or no string
The correct way would be to split the text into a list of strings
Have you used str.split() before?
Nope
Where do I put it?
don't you wanna be checking whether any of the blocked words are in the message, rather than if the message itself is in the list of blocked words? since otherwise, your filter won't be catching any blocked words within a longer sentence, anyway
Yes
Hello, any free hosting site for bots?
What do I do?
How can I do that
All of the words are seperated by a space right?
No a list going down
It’s a list going down
Like
Word1
Word2
Word3
What should I do
so roughly, you wanna do something like:
- take those words, and split them up into a list of each individual word (using something like
.split("\n")) - for each of those words, check to see if its contained within the message
- if any word is, then take whatever actions you want to deal with it
if you wanna be efficient, that first step could be something that's done once when your bot is starting up, rather than every time the command is ran, but it'll work either way
Traceback (most recent call last):
File "f:\mlenv\lib\asyncio\proactor_events.py", line 116, in __del__
self.close()
File "f:\mlenv\lib\asyncio\proactor_events.py", line 108, in close
self._loop.call_soon(self._call_connection_lost, None)
File "f:\mlenv\lib\asyncio\base_events.py", line 719, in call_soon
self._check_closed()
File "f:\mlenv\lib\asyncio\base_events.py", line 508, in _check_closed
raise RuntimeError('Event loop is closed')
RuntimeError: Event loop is closed
``` how to fix this?
Is that the whole traceback
yes
Can you show your code?
@client.event
async def on_ready():
print(f'{client.user} has connected to Discord!')
print(f'{client.user.id}')
print(f'{client.user.name}')
print(f'{client.user.discriminator}')
@client.event
async def on_message(message):
if message.author == client.user:
return
else:
try:
data = query(message.content)
conversation = data["conversation"]["generated_responses"][0]
await message.channel.typing()
await message.channel.send(conversation)
except:
await message.channel.typing()
await message.channel.send("I don't understand")
client.run(DISCORD_TOKEN)```
Do it shows error in client.run?
no when i do keywordinteruption only that time it shows me this error
^C?
yup
So do this error creates any trouble for you?
i guess no
hmm still it need to be fixed
this is the real error
Which code editor you using?
vscode
Hmm imma find solution to it , give me some time
Don't use request
then what to use?
Whats the query?

