#discord-bots
1 messages ยท Page 264 of 1
that too
Even if bot got that wouldn't he need to be higher in hierarchy?
Welp error says it
change your bots permissions and make sure its role is above the users role who ur trying to edit
make sure his permissions are correct, and can edit users
Welp I'd suggest not giving your but admin perms
And try changing name of someone else other than yourself
Cuz i think bots can't change server owner name not sure tho
class discord.Member```
Represents a Discord member to a [`Guild`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild "discord.Guild").
This implements a lot of the functionality of [`User`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User "discord.User").
x == y Checks if two members are equal. Note that this works with [`User`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User "discord.User") instances too.
x != y Checks if two members are not equal. Note that this works with [`User`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User "discord.User") instances too.
hash(x) Returns the memberโs hash.
str(x) Returns the memberโs handle (e.g. `name` or `name#discriminator`).
what bot should I make
huh
what
whats the point in that
i dont understand what it does
oh
its pointless
ig
user_perms = []
perms_list = list(GuildChannel.permissions_for(member))
for perms in perms_list:
user_perms.append(perms)
Error occured: Command raised an exception: TypeError: GuildChannel.permissions_for() missing 1 required positional argument: 'obj'
im not making it
arent we supposed to just give member or role as obj?
any1?
I do hope you're not importing GuildChannel and that GuildChannel is just a badly named variable
oh well
i did import it
There we go, OOP 
well
still same problem
perms_list = list(discord.abc.GuildChannel.permissions_for(member))
My guy
Maube time to learn OOP
discord.abc.GuildChannel must be replaced by an instance of such an object
E.g. ctx.channel, message.channel or interaction.channel, etc.
o
if f'antibadwords:{after.guild.id}' not in r2:
return
if after.id == client.user.id:
return
if after.nick == "Bad word name":
pass
else:
words = after.nick
if not profanity.contains_profanity(after.nick):
return
if any(word in profanity.CENSOR_WORDSET and word in after.nick.lower() for word in after.nick.lower().split()):
new_nickname = "Bad word name"
await after.edit(nick=new_nickname)
log = r.get(f"log {str(after.guild.id)}")
embed = discord.Embed(title="nickname changed", description=f"{after.mention}'s nickname was changed")
embed.add_field(name="Reason", value="contained bad words")
embed.set_footer(text="Censored by better_profanity")
log2 = int(log.decode("utf-8"))
logging = client.get_channel(log2) or await client.fetch_channel(log2)
await logging.send(embed=embed)
print(f"bad word detected logs: {after.guild.id}")
``` this code
is changing any nickname I want it to only change it if the nickname contains profanity.CENSOR_WORDSET
import discord
from discord.ext import commands
import wavelink
class Music(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.bot.loop.create_task(self.node_connect())
async def node_connect(self):
await self.bot.wait_until_ready()
await wavelink.NodePool.create_node(bot=self.bot, host="lavalinkinc.ml", port=443, password="incognito", https=True)
@commands.Cog.listener()
async def on_wavelink_node_ready(self, node: wavelink.Node):
print(f"Node <{node.identifier}> is ready!")
@commands.command()
async def play(self, ctx, *, search: wavelink.YouTubeTrack):
if not ctx.voice_client:
vc: wavelink.Player = await ctx.author.voice.channel.connect(cls=wavelink.Player)
else:
vc: wavelink.Player = ctx.voice_client
vc.play(search)
async def setup(bot):
await bot.add_cog(Music(bot))
Traceback (most recent call last):
File "C:\Users\91767\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ext\commands\bot.py", line 947, in _load_from_module_spec
await setup(self)
File "D:\OneDrive\Desktop\Saste Nashe\Coding ke Nashe\Discord ke Nashe\cogs\music.py", line 28, in setup
await bot.add_cog(Music(bot))
^^^^^^^^^^
File "D:\OneDrive\Desktop\Saste Nashe\Coding ke Nashe\Discord ke Nashe\cogs\music.py", line 8, in init
self.bot.loop.create_task(self.node_connect())
^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\91767\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\client.py", line 140, in getattr
raise AttributeError(msg)
AttributeError: loop attribute cannot be accessed in non-async contexts. Consider using either an asynchronous main function and passing it to asyncio.run or using asynchronous initialisation hooks such as Client.setup_hook
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "D:\OneDrive\Desktop\Saste Nashe\Coding ke Nashe\Discord ke Nashe\main.py", line 52, in <module>
asyncio.run(main())
File "C:\Users\91767\AppData\Local\Programs\Python\Python311\Lib\asyncio\runners.py", line 190, in run
return runner.run(main)
^^^^^^^^^^^^^^^^
File "C:\Users\91767\AppData\Local\Programs\Python\Python311\Lib\asyncio\runners.py", line 118, in run
return self._loop.run_until_complete(task)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\91767\AppData\Local\Programs\Python\Python311\Lib\asyncio\base_events.py", line 653, in run_until_complete
return future.result()
^^^^^^^^^^^^^^^
File "D:\OneDrive\Desktop\Saste Nashe\Coding ke Nashe\Discord ke Nashe\main.py", line 18, in main
await bot.load_extension(f'cogs.{file[:-3]}')
File "C:\Users\91767\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ext\commands\bot.py", line 1013, in load_extension
await self._load_from_module_spec(spec, name)
File "C:\Users\91767\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ext\commands\bot.py", line 952, in _load_from_module_spec
raise errors.ExtensionFailed(key, e) from e
discord.ext.commands.errors.ExtensionFailed: Extension 'cogs.music' raised an error: AttributeError: loop attribute cannot be accessed in non-async contexts. Consider using either an asynchronous main function and passing it to asyncio.run or using asynchronous initialisation hooks such as Client.setup_hook
Unclosed client session
client_session: <aiohttp.client.ClientSession object at 0x00000115FEE46D90>
any idea on why i am getting this error? setup function is working fine btw
hmmm alright thx
Make that node connection somewhere else
alright
can i loop it in setup function?
We can, but we won't. We don't code for you, we help you fix your issues.
That one is async so most likely
Otherwise there may be some async function you can overwrite for an event emitted when the cog is loaded
still getting the same thing, cannot be accessed in non-async contexts
first i thought of setting up the loop using a listener but it wasnt working
alright still thx for the info
@commands.command()
async def bal(self, ctx):
id = ctx.author.id
data = {}
if id not in data:
with open('data.json', 'w') as f:
data[id]['name'] = ctx.author.name
data[id]['balance'] = 0
json.dump(data, f, indent = 4)
with open('data.json', 'r') as f:
name = json.load(data[id]['name'], f)
Error occured: Command raised an exception: KeyError: 967397351159390218
Key does not exist
yea but I want the bot to write the key in such case
@commands.command()
async def bal(self, ctx):
id = ctx.author.id
with open('data.json', 'r') as f:
data = f.read()
if id not in data:
with open('data.json', 'w') as f:
data[id] = {}
data[id]['name'] = ctx.author.name
data[id]['balance'] = 0
json.dump(data, f, indent = 4)
with open('data.json', 'r') as f:
name = json.load(data[id]['name'], f)
await ctx.send(name)
Error occured: Command raised an exception: TypeError: 'in <string>' requires string as left operand, not int
i tried that but it showed another error
Send the another error then
str obj doesnt support item assignment
Show your current code
@commands.command()
async def bal(self, ctx):
id = str(ctx.author.id)
with open('data.json', 'r') as f:
data = f.read()
if id not in data:
with open('data.json', 'w') as f:
data[id] = {}
data[id]['name'] = ctx.author.name
data[id]['balance'] = 0
json.dump(data, f, indent = 4)
with open('data.json', 'r') as f:
name = json.load(data[id]['name'], f)
await ctx.send(name)
!traceback
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.
Always send the full traceback
ok wait lemme print it first
Error occured: Command raised an exception: TypeError: 'str' object does not support item assignment
Full traceback
wont print
i mean it wont show
Average error handler eating everything
That explains it
Who
bot ofc
How would your bot tell you to change something to integer
{error}
Show the error then
Error occured: Command raised an exception: TypeError: string indices must be integers, not 'str'
What are you trying to do now
Convert
As simple as that
member is an ID, whereas when you ban it must be something like a User that has an ID attribute
So i should make member variable like member = entry.user?
So first of all await guild.ban(entry.user, reason="NULL")
Gotcha
Thanks
if after.nick == "Bad word name":
pass
else:
if after.id == client.user.id:
return
if f'antibadwords:{after.guild.id}' not in r2:
return
message_content = after.nick.lower()
words = message_content.split()
for word in words:
if re.search(r"\w\W+\w", word) and (word.lower() in words for word in profanity.CENSOR_WORDSET):
if any (word in after.nick.lower() for word in "ass"):
pass
else:
new_nickname = "Bad word name"
await after.edit(nick=new_nickname)
log = r.get(f"logs:{str(after.guild.id)}")
embed = discord.Embed(title="nickname changed", description=f"{after.mention}'s nickname was changed")
embed.add_field(name="Reason", value="contained bad words")
embed.set_footer(text="Censored by better_profanity")
log2 = int(log.decode("utf-8"))
logging = client.get_channel(log2) or await client.fetch_channel(log2)
await logging.send(embed=embed)
print(f"2bad word detected logs: {after.guild.id}")
``` this code is changing usernames with special characters I only want it to change it if it has special characters between the letters in profanity.CENSOR_WORDSET
!e
i = 53055
print(f"{i:,}")
@slate swan :white_check_mark: Your 3.11 eval job has completed with return code 0.
53,055
f"{data[id]['balance']}" can i do that in this line as well?
cuz fetching the bal from datafile
okay ty
i try make modal in youtube help me .-.
well there is no folder named cogs
I copied it on youtube .-.
That's what happens
thats why you should not
Line 8 already shows the tutorial is most likely shit
Same for line 6
no line 6 more
ohhh
Hey @slate swan, do you know about discord presence in vs code?
you talking about this?
yes
its extension to vs code
yes ik in #editors-ides i showed a problem i have been encountering, could you please check it out?
anyone has idea on how to call the display username of a user, like before the discord update of new usernames, we would call the user using message.author.name and it would just use the name part and avoid the discrimnator and # sign,
I think user.name can now get new usernames after latest updates
!d discord.Member.display_name
property display_name```
Returns the userโs display name.
For regular users this is just their global name or their username, but if they have a guild specific nickname then that is returned instead.
Like this?
i was trying to get the name which shows up in chat, so couldn't find the specific name which comes after message.author but finally got it
yes yes thanks a lot appreciate the help
Mb
I thought u were trying to ask how to get new user names as discriminators are gone
depends what database also its not really related to this channel topic
well this could be for anything but the question is related to databases
Is there any audit log broadcast event
discord.on_audit_log_entry_create(entry)```
Called when a [`Guild`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild "discord.Guild") gets a new audit log entry. You must have [`view_audit_log`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.view_audit_log "discord.Permissions.view_audit_log") to receive this.
This requires [`Intents.moderation`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.moderation "discord.Intents.moderation") to be enabled.
New in version 2.2.
Warning
Audit log entries received through the gateway are subject to data retrieval from cache rather than REST. This means that some data might not be present when you expect it to be. For example, the [`AuditLogEntry.target`](https://discordpy.readthedocs.io/en/latest/api.html#discord.AuditLogEntry.target "discord.AuditLogEntry.target") attribute will usually be a [`discord.Object`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Object "discord.Object") and the [`AuditLogEntry.user`](https://discordpy.readthedocs.io/en/latest/api.html#discord.AuditLogEntry.user "discord.AuditLogEntry.user") attribute will depend on user and member cache.
To get the user ID of entry, [`AuditLogEntry.user_id`](https://discordpy.readthedocs.io/en/latest/api.html#discord.AuditLogEntry.user_id "discord.AuditLogEntry.user_id") can be used instead.
How do I use it is there any example?
Like any other events
What do I put in (entry)?
What?
It has entry parameter ryt
Yes?
how do we get specific event from it?
What specific event
discord.AuditLogAction.ban
Then just check it
using if statement
Shouldn't the Authorization data be sent in the headers and not data?
Not fully sure though ๐
same
so cooool
Hello!
My bot keeps crashing when it tries to reply to a deleted message. How do I make it so it still sends the message without replying to the original command but still mentioning the command's author?
For clarification: I still want it to reply when the message has not been deleted.
Ping them?
!d discord.User.mention
property mention```
Returns a string that allows you to mention the given user.
It currently does both. I want it to recognize when there's no message to reply to so it only pings. Right now it just crashes the whole bot when that happens.
Why was the message deleted anyway
Sometimes people do that when they make a typo or want to hide their command. It's rare but I don't want to restart my bot every time it happens.
quick question Is it legal to sell discord bots that can play songs from youtube?
I highly doubt it considering they have taken down bots like that before.
damn alright
I sometimes get an Unknown Interaction error in random commands that work normally most of the other time, any idea why this might be?
I notice that it happens when there is some other action processing in the background like something in the on_message event
What are you looking for? Here is an example:
guild = ctx.guild
bans = []
async for entry in guild.audit_logs(action=discord.AuditLogAction.ban, limit=10):
bans.append(entry)
if not bans:
await ctx.send("No recent bans found.")
else:
embed = discord.Embed(title="Recent Bans", color=discord.Color.red())
for entry in bans:
embed.add_field(name="Banned User", value=entry.target)
embed.add_field(name="Reason", value=entry.reason or "No reason provided")
embed.set_footer(text=f"Banned by {entry.user} at {entry.created_at}")
await ctx.send(embed=embed)```
Shows the most recent 10 bans in the server
Does that "on_message" have async on it?
yep
I suspect it might be that some of the commands take more than 3 seconds at times, so the interaction fails
I am gonna try and defer all interactions first and then followup response, on all of them
hopefully this fix works
Well i was looking for this but thanks anyway
@bot.event
async def on_audit_log_entry_create(entry):
if entry.action == discord.AuditLogAction.ban:
if entry.target is not None and isinstance(entry.target, discord.Member):
banned_member = entry.target
guild = entry.guild
moderator = entry.user
reason = entry.reason
In discord.py, can I use interaction.followup.send to send ephemeral messages?
yes iirc
Oh oh thx
does it answer ur question?
when deferring, if you set ephemeral to True, your first followup will be ephemeral regardless of what you pass to the ephemeral kwarg of followup.send. If you have ephemeral set to False, your first followup won't be ephemeral. - Main point for u
thx, I am gonna to try it
ok
what permission do you need to use fetch_channel?
discord.Permissions.view_channel
how would I give that to my bot, im a little slow rn. Like is there a role perm I can give it?
you need to edit the channel's perms too to let the role access the channel
ah ok
!d discord.Guild.icon
property icon```
Returns the guildโs icon asset, if available.
can someone help me
but how would i specify the id
can u show me an example
!d discord.Guild.icon
property icon```
Returns the guildโs icon asset, if available.
Is it possible to send a modal with a followup to an interaction?
await interaction.followup.send(emailinputmodal())
This doesn't work
no sending modal is only available via interaction.response.send_modal
Hello, I wanted to know if someone could help me with an automated message in discord.py. I have this setup but doesn't work and I get no errors. Let me know, thank you.
@tasks.loop(seconds=10)
async def auto_send(channel : discord.TextChannel):
embed = discord.Embed(colour=0x182D9F)
embed.set_author(name="Just Some Subtle Reminders")
embed.description = f"-n Be sure to use `.register` to register yourself to earn **Raneon** and buy **rewards**! \n *Do .help in #โcommands \n \n Learn how to join our team over here #โhow-to-join"
embed.set_image(url="https://cdn.discordapp.com/attachments/1074138997498052760/1125310614147973130/HEADER_22.png")
await channel.send(embed=embed, delete_after=60)
did you start this task?
is there a way to detect if the user isn't in the server anymore because I have a list of user ids and need to remove the ids from the list that aren't in the discord server anymore
iterate through your list, use guild.get_member to check if the member is in the guild, if it is then pop
Add in another method
@auto_send.before_loop
set the channel and run the auto send with the channel as the args
tried that, it is returning and saying all members are "None" yet some of them I know are in the server
toRemove = []
for i in old:
member = guild.get_member(int(i))
print(guild, int(i), member)
if member is None:
toRemove.append(i)
for index in toRemove:
del old[index]```
you can use on_member_remove so when they leave it does something
but if the member is already gone but in the list, it wouldn't do anything
true
Okay, thank you.
how would I do that?
!d discord.ext.tasks.Loop.start
start(*args, **kwargs)```
Starts the internal task in the event loop.
ty
how can i make my bot uh log the user who adds a reaction and sends the reaction they put and the user in a log channel
when I print guild.members, it sends SequenceProxy(dict_values([])), how can I iterate through this?
!d discord.Guild.members
property members```
A list of members that belong to this guild.
just a sequence of members, how do I iterate through a sequence
like you would normally? using for loop
it doesn't do anything. Its like guild.members is empty
show code
here @slate swan
that's the old one
oh.
if role in interaction.user.roles:
old = None
await interaction.response.defer()
with open(f"{file}", "r") as vouchFile:
old = json.load(vouchFile)
members = guild.members
memberIds = []
print(guild.members)
for i in members:
memberIds.append(i.id)
print(memberIds)
for i in old.copy():
if not i in memberIds:
del old[i]
with open(f"{file}", "w") as vouchFile:
json.dump(old, vouchFile, indent=4)```
there is no guild.members used
apologies for formatting
and what you you get when you print i inside for loop
it doesn't print anything, basically if you try to do
a = []
for i in a:
print(i)```
and guild is not None, i've tried printing it
based on this representation there are no members in the guild
ok
ask here i have no idea why its empty then
do u have server members intent enabled?
yeah, I got it fixed, thank you though.
Could someone help me point out the issue here?
!indent
Indentation is leading whitespace (spaces and tabs) at the beginning of a line of code. In the case of Python, they are used to determine the grouping of statements.
Spaces should be preferred over tabs. To be clear, this is in reference to the character itself, not the keys on a keyboard. Your editor/IDE should be configured to insert spaces when the TAB key is pressed. The amount of spaces should be a multiple of 4, except optionally in the case of continuation lines.
Example
def foo():
bar = 'baz' # indented one level
if bar == 'baz':
print('ham') # indented two levels
return bar # indented one level
The first line is not indented. The next two lines are indented to be inside of the function definition. They will only run when the function is called. The fourth line is indented to be inside the if statement, and will only run if the if statement evaluates to True. The fifth and last line is like the 2nd and 3rd and will always run when the function is called. It effectively closes the if statement above as no more lines can be inside the if statement below that line.
Indentation is used after:
1. Compound statements (eg. if, while, for, try, with, def, class, and their counterparts)
2. Continuation lines
More Info
1. Indentation style guide
2. Tabs or Spaces?
3. Official docs on indentation
So the only way is for me to hope the process doesn't ever go over 3 seconds otherwise the interaction fails
You can always defer the interaction
Well yeah, but sometimes it's like a check I wanna do to see if I wanna send them the modal at all or not
Which usually does not take more than 3 seconds, but for some reason when there is a lot of other stuff going on too I get Unknown Interaction errors so that's why I was deferring everything to be safe
But I guess for this one I will hope it doesn't
So, with the last line being the issue. Should removing the indent fix it?
Hello!
I have a bot that crashes when it tries to reply to a message, which was deleted in the mean time. Can I somehow make it so the bot sends the message anyway but doesn't reply? (only when the message was deleted)
i just defer everything by default to be safe ๐
you are supposed to read this
try except
and apply changes to your code
try reply if error just send it
check if message exists or just catch errors
I tried that and it crashed the same way anyways, even when the except was just: print("nope")
I did, but I only sort of understand it
the problem with your code is that you are inconsistent with using indentation
try:
await ctx.reply()
except discord.HTTPException:
await ctx.send()
@full cosmos
the issue was that he was using client.fetch_guild
!d discord.Client.fetch_guild
await fetch_guild(guild_id, /, *, with_counts=True)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Retrieves a [`Guild`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild "discord.Guild") from an ID.
Note
Using this, you will **not** receive [`Guild.channels`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild.channels "discord.Guild.channels"), [`Guild.members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild.members "discord.Guild.members"), [`Member.activity`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member.activity "discord.Member.activity") and [`Member.voice`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member.voice "discord.Member.voice") per [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member "discord.Member").
Note
This method is an API call. For general usage, consider [`get_guild()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.get_guild "discord.Client.get_guild") instead...
read the note under it
ic
yeah i didnt know it until now
Hi all, im creating a leaderboard command to show every users level and xp in their current server. However i keep getting the error nontype has no attribute name anyone know why?
Code:
async def leaderboard(ctx):
if str(ctx.guild.id) not in level_data:
await ctx.send('No recorded levels in this server.')
return
sorted_data = sorted(level_data[str(ctx.guild.id)].items(), key=lambda x: x[1], reverse=True)
leaderboard_embed = discord.Embed(title='Level Leaderboard', color=discord.Color.gold())
for i, (user_id, xp) in enumerate(sorted_data[:10]):
user = ctx.guild.get_member(int(user_id))
leaderboard_embed.add_field(name=f'{i+1}. {user.name}', value=f'XP: {xp}', inline=False)
await ctx.send(embed=leaderboard_embed)```
but fetch_guild like that would raise tracemalloc and not empty iterator
get_guild if not changed will just return None
it did return a guild but the members list is just empty
!e None.name
@shrewd apex :x: Your 3.11 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "/home/main.py", line 1, in <module>
003 | None.name
004 | AttributeError: 'NoneType' object has no attribute 'name'
user is prolly None
yes that exact error
!d discord.Guild.fetch_member
await fetch_member(member_id, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Retrieves a [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member "discord.Member") from a guild ID, and a member ID.
Note
This method is an API call. If you have [`Intents.members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.members "discord.Intents.members") and member cache enabled, consider [`get_member()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild.get_member "discord.Guild.get_member") instead.
Changed in version 2.0: `member_id` parameter is now positional-only.
riiight i see
Hmm now it works. ๐
๐
I swear I tried that exact same thing earlier and it didn't work
happens to the best of us :p altho u prolly made some error somewhere else
definitely
Okay, so this works...
But this doesn't.
"ValueError: I/O operation on closed file"
what file_objects are?
Oh it's the same error as before ("In message_reference: Unknown message") but During handling of it, the "I/O operation" error happens as well.
a bunch of pictures
definition ...
HELP Me pls #1125532999857999992
its been over 24 hours and i still cant get the badge
anyone know why>
i used the / command
{
"1045803353155829800": [
"946756183862169600",
"381633823181373443",
"1028821837964124180"
],
"1008022430620594237": [
"442012110525038605"
],
"640043175536230411": [
"915402921590525993",
"442012110525038605",
"916151031547723836",
"954582529065746484",
"1078907660914671738",
"1115434227270430830",
"593837065171632130",
"498206212270194689",
"824869231530082334",
"1011213610548203550",
"381712712755052544",
"381712712755052544",
"1119855238095065198"
]
}```
How can I detect duplicates with this in this when its converted into a python dict using `json.load` (used for a discord bot)
Check the requirements
yeah i did, made sure it was a community server, made sure it was a slash command (global command) and waited 24 hours
this is the second time i tried
Has anybody used the slash command?
Detect what duplicate
A json file acts similar to a python dictionary, so the keys cant be duplicated. However the values can be duplicated.
One method you could consider is sorting the values in each key list, and just doing a simple comparison..
Ok, thanks
Alternatively, before you append to the list you make sure the value isnt already in the list
if not x in mylist: mylist.append(x)
set moment
Dont come @ me with your silliness
What?
**CAn anyone help me Why the emoji's are not showing in embed , tho I have picked all the emoji from the server in which my discord bot is already in **
how do I get the id of the current channel
Code?
channel_id = message.channel.id
print(f"The ID of the current channel is: {channel_id}")
can it be done in js
Yes, I don't code in js though and this is the python server
can you just make an exception in my dms then ๐
oh wait
you dont code nvm I didnt see that
its fine
ok
Are they in code blocks
:pithink:
Why are u putting the emojis in a block?
oh got it
tq
I keep getting the any for the varible no matter witch i try
I think we all know why 
yes they were executed
Cause you cant put Emoji in code block
not sure what you mean by that
@commands.has_permissions(kick_members=True)
async def kick(ctx, member: discord.Member, *, reason=None):
if member == ctx.author:
raise commands.BadArgument("You cannot kick yourself.")
if member is None:
raise commands.BadArgument("You need to mention a user you want to kick.")
await member.kick(reason=reason)
await ctx.send(f'{member} has been kicked.')
mod_log_channel = bot.get_channel(mod_log_channel_id)
await mod_log_channel.send(f'{member} has been kicked. Reason: {reason}')
@kick.error
async def kick_error(ctx, error):
if isinstance(error, commands.BadArgument):
await ctx.send(error)
elif isinstance(error, commands.MissingPermissions):
await ctx.send("You don't have permission to kick members.")
else:
# Handle other errors here
pass```
No error message appears in the console, but when a user inputs `?kick` without mentioning a user, the custom error message `You need to mention a user you want to kick.` does not appear.
if member is None:
raise commands.BadArgument("You need to mention a user you want to kick.")
``` this will never be raised since if member is not specified `MissingRequiredArgument` will be raised
does that mean i have to change BadArgument to MissingRequiredArgument?
no when user does not pass the member it doesnt even go into the command code
it goes to error handler directly so you need to add this case to your handler
right i see
Is it possible for channel.fetched_message(message_id) to delete a ephemeral message?
Can somebody please take a look at this? I still haven't been able to figure out what is wrong. โน๏ธ
Why does it give me an error message saying: "In message_reference: Unknown message" only when the file objects are attached to the message in the "except" part?
slash.command doesn't work for me, its weird
is this the right code?
@bot.slash_command() async def epic(ctx): await ctx.respond(f"epic !")
error: slash_commands it not a real thing do you mean add_command?
what library are you using
my code
`import discord
from discord.ext import commands
import json
bot = commands.Bot(command_prefix="/", intents=discord.Intents.all())
@bot.slash_command()
async def epic(ctx):
await ctx.respond(f"epic !")
bot.run("bro thought i would show my token ๐")`
there is no such decorator like .slash_command in discord.py
@bot.command()
async def epic(ctx):
try that
alright
- its not slash command
- why spoon feed
oh yeah
It's a help channel is it not?
to create slash commands you dont set prefix as /
oh
then how to do it?
yeah its supposed to be for helping not giving away straight answers
bro someone grabbed my token from it
and raided my discordi
when did i tell you to use replit?
oops
i thought it was replit ๐
sorry
it worked thanks ๐
how do i get guild icon as an url?
!d discord.Guild
class discord.Guild```
Represents a Discord guild.
This is referred to as a โserverโ in the official Discord UI.
x == y Checks if two guilds are equal.
x != y Checks if two guilds are not equal.
hash(x) Returns the guildโs hash.
str(x) Returns the guildโs name.
docs exist for a reason
help server exist for a reason
i tried
guild = ctx.guild
guild_icon = guild.icon.url```
but its not working
await injected(*ctx.args, **ctx.kwargs) # type: ignore
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\jpash\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ext\commands\core.py", line 244, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'NoneType' object has no attribute 'url' ```
what is not working show actual error
icon is None cause it can be
Default icons are considered as None?
yes
eh
thats not good
discord should change this
File "C:\Users\jpash\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ext\commands\bot.py", line 1350, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\jpash\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ext\commands\core.py", line 1029, in invoke
await injected(*ctx.args, **ctx.kwargs) # type: ignore
File "C:\Users\jpash\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ext\commands\core.py", line 244, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'str' object has no attribute 'url'```
when i tried it after putting an icon
discord.py version?
2.3.1
code?
Version: 2.3.1
Summary: A Python wrapper for the Discord API
Home-page: https://github.com/Rapptz/discord.py
Author: Rapptz
Author-email:
License: MIT
Location: C:\Users\jpash\AppData\Local\Programs\Python\Python311\Lib\site-packages
Requires: aiohttp
Required-by:```
@bot.command(aliases=["si"])
async def serverinfo(ctx):
guild = ctx.guild
total_members = guild.member_count
text_channels = len(guild.text_channels)
voice_channels = len(guild.voice_channels)
categories = len(guild.categories)
server_owner = guild.owner
created_at = guild.created_at
guild_icon = guild.icon.url
embed = discord.Embed(title=f"Server Info - {guild.name}", color=discord.Color.blue())
embed.set_thumbnail(url=guild_icon)
embed.add_field(name="Server Owner", value=server_owner.mention, inline=False)
embed.add_field(name="Total Members", value=str(total_members), inline=False)
embed.add_field(name="Text Channels", value=str(text_channels), inline=False)
embed.add_field(name="Voice Channels", value=str(voice_channels), inline=False)
embed.add_field(name="Categories", value=str(categories), inline=False)
embed.add_field(name="Created At", value=str(created_at), inline=False)
await ctx.send(embed=embed)```
what do you get when you do type(guild.icon)
hmm
interesting question
it works
when i do guild.icon
but url is icon.url in discord.Guild
@tasks.loop(seconds=30)
async def temp_ban(self):
await self.bot.cursor.execute("""SELECT * FROM temp_ban""")
data = await self.bot.cursor.fetchall()
print(data)```
Can someone explain why fetchall returning me empty list? I have data in database.
Can anyone tell me how to Highlight a coding thing
its more related to #databases
!code
I feel it's ext.tasks problem bc when i use same code somewhere else ( like commands) it works fine
Why would it be
all the tasks does is run it in intervals
Yea that's why i said this question
@commands.command()
async def test(self, ctx):
await self.bot.cursor.execute("""SELECT * FROM temp_ban""")
data = await self.bot.cursor.fetchall()
print(data)
Like, this work fine
It's literally the same code
how do you define bot.cursor
self.db_connection : aiosqlite.Connection = await aiosqlite.connect("./database.db")
self.cursor : aiosqlite.Cursor = await self.db_connection.cursor()```
and that is inside Bot subclass?
Ye
and where is task located
Cog
since it takes self
try adding this py @temp_ban.before_loop async def _before(self): await self.bot.wait_until_ready()
Did this already
then no idea 

Can you show your cog's full code
you start the task right?
Yes
!paste
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.
Does discord.py have modal support?
!d discord.ui.Modal
class discord.ui.Modal(*, title=..., timeout=None, custom_id=...)```
Represents a UI modal.
This object must be inherited to create a modal popup window within discord.
New in version 2.0.
Examples...
Interesting, after 5 call it return the actual data
.
[]
.
[]
.
[]
.
[(123, "d", 10, 111)]
.
hmm
what happens when you do !help or whatever your prefix is
there is a built in help command does this command appear here
hm fair enough
well how about you add print("Im here") print at top of your command
does it prints in console
ah so it works just not for you?
the voice_channel does not have .owner attribute
!d discord.VoiceChannel
class discord.VoiceChannel```
Represents a Discord guild voice channel.
x == y Checks if two channels are equal.
x != y Checks if two channels are not equal.
hash(x) Returns the channelโs hash.
str(x) Returns the channelโs name.
no there are no owners of voice channels on discord
Do what
use database i would say
your global error handler is silencing the errors either comment it out for debugging or add else: print(error) or smth like that so if the error is not handled it is shown in console
(or just re-raise it)
yeah
class ErrorNotHandled(Exception):
pass
raise ErrorNotHandled() from error
``` i wonder if that would work and make sense
Should be fine
You're getting the owner of the guild
And there's no such thing as an owner of a voice channel
if thats how you want to handle it 
then only the guild owner will be available to delete channels
i suppose you have a command to create a channel as well
if so you could do as follows:
- on creating channel save who created a channel and what is the channel id to database
- on removing channel check if the person trying to remove the channel did create it
no json file is not a good idea for database
im talking about a real database ile mysql or mongodb
there is easiest way
but it has one con
if you restart the bot all data is gone
you could use bot varriables
and store it in dictionary
!botvar
Python allows you to set custom attributes to most objects, like your bot! By storing things as attributes of the bot object, you can access them anywhere you access your bot. In the discord.py library, these custom attributes are commonly known as "bot variables" and can be a lifesaver if your bot is divided into many different files. An example on how to use custom attributes on your bot is shown below:
bot = commands.Bot(command_prefix="!")
# Set an attribute on our bot
bot.test = "I am accessible everywhere!"
@bot.command()
async def get(ctx: commands.Context):
"""A command to get the current value of `test`."""
# Send what the test attribute is currently set to
await ctx.send(ctx.bot.test)
@bot.command()
async def setval(ctx: commands.Context, *, new_text: str):
"""A command to set a new value of `test`."""
# Here we change the attribute to what was specified in new_text
bot.test = new_text
This all applies to cogs as well! You can set attributes to self as you wish.
Be sure not to overwrite attributes discord.py uses, like cogs or users. Name your attributes carefully!
but like i said when you restart the bot all data is gone
client = commands.Bot(command_prefix=".", owner_id = [ID1, ID2], intents=discord.Intents.all())
why cant i use owner commands now
owner_ids
oh is that it?
yes.
i guess i am dumb xD
!d discord.ext.commands.Bot
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.
hello i am an probleme with my bot discord ```py
import discord
from discord import app_commands
from discord.ext import commands
intents = discord.Intents().all() # Crรฉe une instance des intents par dรฉfaut
bot = commands.Bot(command_prefix="!", intents=intents)
intents.message_content = True
intents.guilds = True
intents.members = True
@bot.event
async def on_ready():
print("go")
@bot.command
async def bonjour(ctx):
await ctx.send("bonjour")
you update intents after you already passed them to Bot
Nice
@bot.command() call it
and these 3 lines are useless ```py
intents.message_content = True
intents.guilds = True
intents.members = True
discord.ext.commands.errors.CommandNotFound: Command "bonjour" is not found
discord.Intents().all() this correct syntax for class method?
!e
class A:
def __init__(self):
self.a = 0
@classmethod
def dumb(cls):
cls.a = 1
return cls()
a = A()
print(a.a)
b = A().dumb()
print(b.a)
@naive briar :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | 0
002 | 0
!e ```py
class A:
@classmethod
def all(cls):
return cls()
A.all()
A().all()
@slate swan :warning: Your 3.11 eval job has completed with return code 0.
[No output]
Why
They will not be able to make prefix commands
maybe for your use case its good
Just think for a second
Call the @bot.command

what
Sigh
sorry I am French and I start in Discord bot so I do not understand everything
@bot.command
@bot.command()
see the difference between?
soryr
its is good

How can I set one of the arguments in a command to have certain options in python?
Anyone know why on the discord.py docs doesn't work in vs code (slash command)
Just tell me like the function name, and I can read up on the docs
Can I see the code?
ok
@client.slash_command() async def commandName(ctx): await ctx.respond(f"Hello !")
i got it from docs
What docs
Try this:
@commands.hybrid_command(
name="hello", #What you have to type in to run the command
description="say hello", #desc of the command
)
async def group_info(self, context: Context): #Function for the command
await context.send("Hello") #Code to run for the command vvvv
client.slash_command doesn't exist
But, that will get member count
That is for using inside a class
Yea
ok
are you putting all of this into a class?
idk im new
to coding and stuff ๐
Screenshot the code
ok
Like the full thing
here
hi how can i generate a new random number between 1 and 2 for every command call
because i don't want to get the same random number for all called commands (casino game)
bro uhh...
hm ?
Hey guys what happens if automod reaches 100 rules?
@client.command() async def my_command(ctx): random_number = random.randint(1, 2) await ctx.send(f"The random number is: {random_number}")
make sure to import random or install random using pip install random i frogot i got it from the code in my bot idk if it works
yeah but random_number value will be the same for all commands ig
is discord.py the best lib to use? as in most up-to-date and most actively developed
compared to like nextcord, pycord, disnake, etc
all of those are actively developed
the "best" one depends on whether you like the way the library has implemented something
Though I would recommend discord.py simply because it has the most support
anyone know how to import commands from different files to main python file (discord.py library)
why dont you check docs
!d discord.Guild.roles
property roles```
Returns a sequence of the guildโs roles in hierarchy order.
The first element of this sequence will be the lowest role in the hierarchy.
how would i wait for someone to click my button
what do you wanna do cause you can use callback to do something on button click
im making a bot that needs to associate people across servers as the same person the best way to do this is by getting the username instead of the nick right? how can i do that?
i want to wait for when they click then i proceed
Use their IDs
Users can change their usernames however they can't change their ID
Hyo, I'm trying to make a music bot (basic) for personal use and I'm having an error when trying to play the music, when I put the name everything goes has expected, the bot searchs for the song, enters the VC, aaaand, nothing happens, the console says this:
[download] Downloading playlist: Light Switch
[youtube:search] query "Light Switch": Downloading page 1
[youtube:search] playlist Light Switch: Downloading 1 videos
[download] Downloading video 1 of 1
[youtube] WFsAon_TWPQ: Downloading webpage
[download] Finished downloading playlist: Light Switch
2023-07-04 15:46:41 INFO discord.voice_client Connecting to voice...
2023-07-04 15:46:41 INFO discord.voice_client Starting voice handshake... (connection attempt 1)
2023-07-04 15:46:42 INFO discord.voice_client Voice handshake complete. Endpoint found st-pete4186.discord.media
2023-07-04 15:46:45 INFO discord.player ffmpeg process 7584 successfully terminated with return code of 1.
Any idea what it is?
!ytdl
Per Python Discord's Rule 5, we are unable to assist with questions related to youtube-dl, pytube, or other YouTube video downloaders, as their usage violates YouTube's Terms of Service.
For reference, this usage is covered by the following clauses in YouTube's TOS, as of 2021-03-17:
The following restrictions apply to your use of the Service. You are not allowed to:
1. access, reproduce, download, distribute, transmit, broadcast, display, sell, license, alter, modify or otherwise use any part of the Service or any Content except: (a) as specifically permitted by the Service; (b) with prior written permission from YouTube and, if applicable, the respective rights holders; or (c) as permitted by applicable law;
3. access the Service using any automated means (such as robots, botnets or scrapers) except: (a) in the case of public search engines, in accordance with YouTubeโs robots.txt file; (b) with YouTubeโs prior written permission; or (c) as permitted by applicable law;
9. use the Service to view or listen to Content other than for personal, non-commercial use (for example, you may not publicly screen videos or stream music from the Service)
Oh
It isn't possible so
Rule 9 says i can use it for personal use
._.
nevermind
hey! im using this to send reactions to a log channel, but i was wondering if i could blacklist certain reactions from getting sent to the log channel.
https://paste.pythondiscord.com/zecikufogu
from discord.ext import commands
intents = discord.Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix='!', intents=intents)
extracted_messages = 0
@bot.event
async def on_ready():
print(f'Logged in as {bot.user.name} ({bot.user.id})')
@bot.event
async def on_message(message):
global extracted_messages
if isinstance(message.channel, discord.TextChannel):
if message.channel.id == 1234567890: # Replace with your channel ID
extracted_text = message.content
save_to_file(extracted_text)
extracted_messages += 1
print_extracted_messages()
def save_to_file(text):
with open('output.txt', 'a', encoding='utf-8') as file:
file.write(text + '\n')
def print_extracted_messages():
global extracted_messages
print(f'Extracted messages: {extracted_messages}')
def run_bot():
bot.run('YOUR_BOT_TOKEN') # Replace with your bot token
run_bot()```
can someone help im trying to make that it would extract all the messages from discord channel and it doesnt work
i did everything correct asked chatgpt and more
still the same issue
it should even show a extracted messages counter
but it just shows this
sorry im new
don't
what do you expect it to show instead?
run_bot()
useless function
you're missing message_content intents
It should show the extracted message counter and it should be saved to output.txt but it doesnt work
what should i write to have a discord bot play audio? (ideally using .play (file))
there's an example either on the docs or on their github > examples for this use case
did you enable message_content intents in the discord dev portal too?
print the message content before you write it to the txt file, you'll see
could i have a link to that? also here's some of the code i have so far and it works but i have to type in .play1(song) and it's only for one and i was wondering if there's a way to have it so i do .play space (any song i have on the directory) i tried arg already but it didn't work.
@client.command(pass_context = True)
async def play1example(ctx):
voice = ctx.guild.voice_client
source = FFmpegPCMAudio('discord bot\example.wav')
player = voice.play(source)
I want you to look for it first, then I'll give you the link
Yeah
proof?
what you're actually looking for is arguments
https://discordpy.readthedocs.io/en/stable/ext/commands/commands.html#parameters
print the message content in on_message
see if that gets printed
Alright ill try tomorrow
@client.command(pass_context = True)
async def play(ctx, arg):
voice = ctx.guild.voice_client
source = FFmpegPCMAudio(arg + '.wav')
player = voice.play(source)
this is the code i tried with arg, ffmpeg outputed a return code of 1
that's simple because
arg + '.wav'
isn't the path to your audio file
but if i play a play command for example, wouldn't it only play 1 audio file?
why would it?
did you write this code?
if your arg specifies a different audio file, it'll play that different audio file
at least, if you specified the PATH to it correctly
cause the pass_context = True does not exist any more
oh, it worked for me before
it was changed in v1
and its 2.3.1 already long time ago
if i specify the file path, wouldn't it only play that one file?
that's where arg comes in
sorry if i'm not getting some basic concepts i'm very new to most python
<your audio files directory> + filename + .wav
@client.command(pass_context = True)
async def play(ctx, arg):
voice = ctx.guild.voice_client
source = FFmpegPCMAudio('discord bot' + 'filename' + '.wav')
player = voice.play(source)
i probably did it wrong
you're guessing
make a separate variable for the file path, print it and see if you think it's correct
spoiler, it's not
I'm new to python so I'm just assuming what I have to do.
@client.command(pass_context = True)
async def play(ctx):
voice = ctx.guild.voice_client
source = FFmpegPCMAudio(file + '.wav')
player = voice.play(source)
file = 'discord bot\pvzm.wav'
print(file)
put the lines under voice
and put the file path in the FFmpegPCMAudio ofc
like this?
@client.command(pass_context = True)
async def play(ctx):
voice = ctx.guild.voice_client
source = FFmpegPCMAudio(file + '.wav')
file = 'discord bot\pvzm.wav'
player = voice.play(source)
what i undestood from variable is that file = 'discord bot/pvzm.wav' and in ffmpegpcmaudio it is doing discord bot/pvzm.wav + '.wav'
did you put it under voice? you didn't
this is what imported btw
import discord
from discord.ext import commands
from discord import FFmpegPCMAudio
not relevant ๐
@client.command(pass_context = True)
async def play(ctx):
voice = ctx.guild.voice_client
file= 'discord bot\pvzm.wav'
source = FFmpegPCMAudio(file + '.wav')
player = voice.play(source)
i'm not sure if you meant literally under like under the line or under like inside
alr, now put only the file in FFmpegPCMAudio
beause ofc ...wav.wav makes no sense
and you completely removed the arg, not great
ah i see, so it would be somebody types for example trumpet and trumpet is a variable and it's in the source
this is closer than anything you had before
we only want the filepath in the FF....Audio, we can change the filepath based on the argument
@client.command(pass_context = True)
async def play(ctx, arg):
voice = ctx.guild.voice_client
file= 'discord bot\pvzm.wav'
source = FFmpegPCMAudio(file)
player = voice.play(source)
Like this? i put the arg after ctx
there we go
now all that's left for you is to actually use that arg variable of yours
should i put a bunch of variables under voice like pvzm = file for example
so change the file variable correctly, so it actually uses the arg variable to create the filepath
nope
this works for one variable, but what should i do for multiple? should i put
source = FFmpegPCMAudio(A, B, C)
or
source = FFmpegPCMAudio(arg)
read this again
@client.command(pass_context = True)
async def play(ctx, arg):
voice = ctx.guild.voice_client
arg= 'discord bot\pvzm.wav'
source = FFmpegPCMAudio(arg)
player = voice.play(source)
hmm
I'll just give it to you for now, as this will probably take too much time for something quite simple
file_path = "discord_bot\\" + arg + ".wav"
source = ...Audio(file_path)```
is "file_path a variable?
correct
if you want to make it actually work:
from pathlib import Path
# ...
current_file_directory = Path(__file__).parent
audio_file_path = current_file_directory / f"{arg}.wav"
source = ...Audio(audio_file_path)```
what is ...audio?
vs code is giving me some errors with ...audio
that's FFmpegAudio
I'm just lazy of typing it all out
I hoped you'd understand, so you wouldn't copy paste
I guess you did

the arg isn't regonized by pylance for some reason
because you probably either didn't even put it in the command
or you just removed that arg...
yeah it works, thank you, i appreciate the patience with me lol.
gl hf
hey! im trying to get my bot to send a message when a thread is created, but i cant get it to work
async def on_thread_create(Thread, ctx):
owner_name = Thread.owner
embed = discord.Embed(title=f"Thank you {owner_name} for creating a suggestion!",
description="All suggestions help us improve the server.",
colour=discord.Colour.yellow())
embed.add_field(name="**Remember to:**", value="โข **Explain** as much as you can, don't have short answers; they dont help.", inline=False)
embed.add_field(name=None, value="โข **Show** an example of your suggestion if possible.", inline=False)
embed.set_author(name="Suggestion channel opened.", icon_url="blob:https://www.remove.bg/17c608e7-3960-4ec6-b775-8bc0ea33ab99")
await ctx.send(embed=embed)
see how the @unkempt canyon bot does it
async def scanTrade(channel):
tradeCorrect = False
while not tradeCorrect:
assetIdList = await scanner()
print(assetIdList)
imageTrade = await drawTable(assetIdList)
trade_embed = discord.Embed(title="Is This The Correct Trade?", description="**Sender - ** `Neweraside`", color=discord.Color.blue())
trade_embed.set_image(url="attachment://new.png")
class TradeView(View):
def __init__(self):
super().__init__()
self.verify_button = Button(style=discord.ButtonStyle.success, label="Correct", custom_id="verify_trade_button")
self.incorrect_button = Button(style=discord.ButtonStyle.danger, label="Incorrect", custom_id="incorrect_trade_button")
self.add_item(self.verify_button)
self.add_item(self.incorrect_button)
trade_view = TradeView()
trade_message = await channel.send(embed=trade_embed, file=imageTrade, view=trade_view)
try:
interaction = await bot.wait_for("component", check=lambda i: i.channel == channel and i.message == trade_message)
custom_id = interaction.data["custom_id"]
if custom_id == "verify_trade_button":
tradeCorrect = True
await acceptTrade()
await interaction.response.send_message("Trade completed!", ephemeral=True)
elif custom_id == "incorrect_trade_button":
await interaction.response.send_message("Continuing to scan for new trades...", ephemeral=True)
except asyncio.TimeoutError:
await channel.send("No response received. Continuing to scan for new trades...")```
could anyone help
when clicking incorrect or correct button nothing happens
async def announce(ctx, title, color= discord.Color,*args):
description = ''.join(args)
embed = discord.Embed(title=title, color=color, description=description)
channel = bot.get_channel(anc)
channel.send(embed=embed)```
its giving an error about the color
Show the actual error ..
^
Cause default value of color is set to Color class
You prolly want to annotate it as Color class
how do i annotate it as a class
@slash_command(dm_permission=False)
async def afk(
self,
interaction: CommandInteraction,
reason: str = Param(max_length=100),
):
"""
Set your status to AFK.
Parameters
----------
reason: Reason for going AFK.
"""
if "[AFK]" in interaction.author.display_name:
embed = report_embed(
False,
description="AFK detected in name, aborting...",
)
await interaction.send(embed=embed, ephemeral=True)
return
await interaction.response.defer()
afk = await AfkModel.get_or_none(
discord_id=interaction.author.id, guild_id=interaction.guild.id
)
if not afk:
await AfkModel.create(
discord_id=interaction.author.id,
guild_id=interaction.guild.id,
reason=reason,
)
else:
embed = report_embed(
False,
description="You are already afk!",
)
await interaction.send(embed=embed, ephemeral=True) # FIXME
return
if (
interaction.author != interaction.guild.owner
and interaction.author.top_role < interaction.guild.me.top_role
and interaction.guild.me.guild_permissions.manage_nicknames
):
await interaction.author.edit(nick=f"[AFK]{interaction.author.display_name}")
await interaction.send(
f"Set your status to AFK with reason: `{reason}` {format_dt(utcnow(), style='R')}"
)
else:
embed = report_embed(
False,
description="You are already afk!",
)
await interaction.send(embed=embed, ephemeral=True) # FIXME
return
Why this part is not being send as ephemeral?
I know it happens because of interaction.response.defer But i don't want
await interaction.send(
f"Set your status to AFK with reason: `{reason}` {format_dt(utcnow(), style='R')}"
)
to be ephemeral too
how can i check if a member has a certain role
if "Chairman" in ctx.author.roles.name():
it says list has no attribute name
because name is an attribute of discord.Role
It's not of list
does this not work?
โฆ
user_has_role = any(role.name == โnameOfRoleโ for role in member.roles)
โฆ
I just did
Any good recommendations for bot hosting taking into consideration active development? I'm still working on my bot and am pushing out new commands everyday but I want it to be up 24/7 when I'm not working.
anyone know how to make button roles in discord.py
make it so when the button is clicked role is added
can you help me fix it?
if "Chairman" in ctx.author.roles.name():
it says list has no attribute name
can someone help me fix this
uhh idk how to import the actual button
what do you want this command to do actually/
if "Chairman" in ctx.author.roles.name():
it says list has no attribute name
can someone help me fix this
In the docs its Role.name
i figured it out
thanks tho
description = ' '.join(args)
embed = discord.Embed(title=title, color=color, description=description)
channel = bot.get_channel(anc) # Replace CHANNEL_ID with the actual channel ID
if description.__contains__('@everyone'):
await channel.send(embed=embed, content="@everyone", allowed_mentions=discord.AllowedMentions(everyone=True))
else:
await channel.send(embed=embed)
else:
await ctx.send("You need to have the chairman role to do this")```
its not working even tho i have a role named Chairman
you gotta be a dick?
How so
It's just commonsense
@naive briar please try to help without being condescending.
U will have to first fetch the role using utils.get and then use that to check if the user has that role or not
Like
role = discord.utils.get(ctx.guild.roles, name='role_name')
If role in ctx.author.roles:
You could just use discord.utils.get on ctx.author.roles directly btw
Welp yeah that works too
lmao
can someone here help me regarding dpy json?
@commands.command()
async def gchannel(self, ctx, channel: discord.TextChannel):
gid = ctx.guild.id
if gid not in data:
with open('logs_data.json', 'w') as f:
data[gid] = {}
data[gid]['cid'] = channel.id
json.dump(data, f, indent = 4)
else:
data[gid]['cid'] = channel.id
await ctx.reply(f'{channel.mention} has been set as greet channel.')
so when i did for general, it set the gchannel to general and added its id in the json file
First, the gid is an int, JSON keys can only be strings
but when i did for sexy channel
cid wasnt updated in the file
@naive briar
nvm
figured it out
from discord import app_commands
from discord.ext import commands
intents = discord.Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix=',', intents=intents)
@bot.event
async def on_ready():
print('metal is online')
try:
synced = await bot.tree.sync()
print(f"Synced {len(synced)} command(s)")
except Exception as e:
print(e)
@bot.tree.command(name="send")
async def send(interaction: discord.Interaction):
await interaction.response.send_message(f"hey",
ephemeral=True)
@bot.command()
async def ping(ctx):
await ctx.reply('**pong**')
bot.run('')```
Can someone help me
show code
@turbid condor
just remove the from discord import app_commands
yea of role cmd
yea i did that and got this
my bad leave this as it is
oh okay
u sure that u gave correct role name while using the cmd?
u are have py-cord whereas the code u are using is for discord.py
how do i check my discord py version?
import discord
print(discord.__version__)```
use pip freeze
or that
discord.py==1.7.3
Try using utils.get to get the role and then remove it
send ss of the role u are trying to give to the user
update it
use pip --upgrade discord.py
and then run your code that should solve the problem
remove it from the user
role = discord.utils.get(ctx.guild.roles, name=f'{role}')
If role in member.roles:
Edit: don't add remove in member.roles.remove that will fetch an error
pip3 install -U discord.py
set ephemeral to False
oh ye ur right
i put true for some reason
now im gonna try to have it add a button to a message i will be here if i need any help xd
๐
In case you need examples
Check this out
Buttons (or components) are now in the 2.0a version of the library which is only obtainable from GitHub, see ?tag dins for how to install this version.
If you wish to use Buttons (and Selects/Dropdowns), please view the documentation for discord.ui here:
https://discordpy.readthedocs.io/en/latest/interactions/api.html#bot-ui-kit
You can also view examples in the repo: https://github.com/Rapptz/discord.py/tree/master/examples/views
I want to make a link box like this lol
its included in the gist
wdym Idk which type of button that is called
the link button
yeah
i only see cmds
that's how you create buttons the are called views in discord.py
those are examples on how to create them and then send them with your message
githubs confuse me very much so ill just see if there's something on yt ican check out
ik how to make the button link just dont know how to make all that into an slash command
welp I'd still suggest checking the gist since its in accordance with latest version as turtorial are not
its pretty simple let me fetch the link.py from the gist
i'll try explaining
# This example requires the 'message_content' privileged intent to function.
from discord.ext import commands
import discord
from urllib.parse import quote_plus
class GoogleBot(commands.Bot):
def __init__(self):
intents = discord.Intents.default()
intents.message_content = True
super().__init__(command_prefix=commands.when_mentioned_or('$'), intents=intents)
async def on_ready(self):
print(f'Logged in as {self.user} (ID: {self.user.id})')
print('------')
# Define a simple View that gives us a google link button.
# We take in `query` as the query that the command author requests for
class Google(discord.ui.View):
def __init__(self, query: str):
super().__init__()
# we need to quote the query string to make a valid url. Discord will raise an error if it isn't valid.
query = quote_plus(query)
url = f'https://www.google.com/search?q={query}'
# Link buttons cannot be made with the decorator
# Therefore we have to manually create one.
# We add the quoted url to the button, and add the button to the view.
self.add_item(discord.ui.Button(label='Click Here', url=url))
bot = GoogleBot()
@bot.command()
async def google(ctx: commands.Context, *, query: str):
"""Returns a google link for a query"""
await ctx.send(f'Google Result for: `{query}`', view=Google(query))
bot.run('token')```
Huh?
u see the Google class it contains a View(basically a button) which contains
I see but I'm not using cogs
There's a class though
I wouldn't know how to take that and make a slashcommand with a link button
interactionn
but what would i put above that I'm very confused ๐
class Google(discord.ui.View):
def __init__(self, query: str):
super().__init__()
# we need to quote the query string to make a valid url. Discord will raise an error if it isn't valid.
query = quote_plus(query)
url = f'https://www.google.com/search?q={query}'
# Link buttons cannot be made with the decorator
# Therefore we have to manually create one.
# We add the quoted url to the button, and add the button to the view.
self.add_item(discord.ui.Button(label='Click Here', url=url))
you can change the class name the link and label
I have this
async def send(interaction: discord.Interaction):
await interaction.response.send_message(f"https://restorecord.com/verify/1125684013672181801",
ephemeral=False)```
What I'm confused about is how to add a link button to a message
and yeah no need for that query line
class XYZ(discord.ui.View):
def __init__(self, query: str):
super().__init__()
url = 'Your Link Here'
self.add_item(discord.ui.Button(label='Button_Name', url=url))
Then you can send it like
await interanction.response.send_message('Your_message_here', view=XYZ)````
This will send the button
how would i make it no message could i leave it blank
for example
just remove the message
why do you think this "error" occurs?
ik why i just sent
because he said remove message
you have to do that in your command
you even copy pasted his typo :/
and I fixed
command?
when do you want to send that button?
as soon as I use the slash command /send
then why u asking me the command
I have been saying slash command no?
and from when did prefix commands start using interaction?
hello I make a bot dicord and the I make a system of economy like 1 message reports a number on 10 pieces but when I restart the bot more nobody has piece I was told to make a SQL database but we were obliged?
yes, store the economy values in database
async def purge(self, ctx, amount: int, target = None):
description = f"**Purged by:** {ctx.author.mention}\n**Amount:** {amount} messages"
embed = discord.Embed(title = "Purged Successfully!", description = description, colour = colour)
if target == 'bot':
def check(message):
return message.author.bot
elif target == 'attachments':
def check(message):
return message.attachments
elif target == 'human':
def check(message):
return not message.author.bot
await ctx.channel.purge(limit = amount+1, check = check)
await ctx.send(embed = embed, delete_after = 5)
bot wont delete msg when I do $purge amt bot
but sends the embed
and when i do $purge amt attachments, it won't delete the msg used for invoking it
yes
because you coded it to
it will delete only messages containing attachments
what do you want to do
how do I fix the problem
!d discord.ext.commands.Context.message
The message that triggered the command being executed.
Note
In the case of an interaction based context, this message is โsyntheticโ and does not actually exist. Therefore, the ID on it is invalid similar to ephemeral messages.
delete the message yourself
no another problem ๐
how am i supposed to know
this
it deletes the messages only from the bot accounts
also when what attribute is used for determining if the author is human
Yes but it is not deleting
when i execute it just sends the embed and does nothing
!d discord.User.bot
Specifies if the user is a bot account.
!d discord.TextChannel.purge
await purge(*, limit=100, check=..., before=None, after=None, around=None, oldest_first=None, bulk=True, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Purges a list of messages that meet the criteria given by the predicate `check`. If a `check` is not provided then all messages are deleted without discrimination.
You must have [`manage_messages`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_messages "discord.Permissions.manage_messages") to delete messages even if they are your own. Having [`read_message_history`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.read_message_history "discord.Permissions.read_message_history") is also needed to retrieve message history.
Changed in version 2.0: The `reason` keyword-only parameter was added.
Examples
Deleting botโs messages...
see what it returns and see what it does for you
when i did purge 2, it purged 0 msg and when i did 10, it purged 1
Is this a good way to implement a ping command for the bot?
message = await ctx.channel.send("Pong!") # Send initial "Pong!" message
latency = int(client.latency * 1000)
await message.edit(content=f"Pong! `{latency}ms`") # Edit message with actual latency```
Why are u editing the message??
When u can get the latency before the message and send it in the message
I noticed other bots do that as well
Welp u could have sent it in the first message
You are sending an extra request when it's not needed
Yeah
well it will work but is prolly not what you want to achieve cause it wont edit the message after the desired amount of latency it will just edit it right away so in this case its better to send message with ping at once
can anyone help me on making a pokemon bot?
@shrewd apex
can any1 help me?? been looking into the same code for an hour, still can't figure out what's wrong
Could you explain why other bots employ this method of sending the message first and then editing it with a ping?
It's their choice nothing else we can say
But yeah I'll stick with down since the message will be edited almost instantaneously so no need to send an extra req
they possibly gather the latency by sending the first message and then update it with gathered latency
..
limit is the number of messages to search through, not necessarily the number of messages being deleted

limit (Optional[int]) โ The number of messages to search through. This is not the number of messages that will be deleted, though it can be.
Write some code that determines the purge limit from the target & the count
Is that not what my code is doing as well?
No its not
I see. So how is my code any different?
you are getting overall latency between HEARTBEAT and a HEARTBEAT_ACK
so thats not how long it took to send a message via api
Any ideas on how I can accomplish that?
start_time = ctx.message.created_at
message = await ctx.channel.send("Pong!") # Send initial "Pong!" message
end_time = message.created_at
latency = int((end_time - start_time).total_seconds() * 1000)
await message.edit(content=f"Pong! `{latency}ms`") # Edit message with actual latency```
Or would you have done it differently?
!e ```py
import datetime
import time
start = datetime.datetime.now()
do something
time.sleep(1)
end = datetime.datetime.now()
print(f"Took: {end - start}")
@slate swan :white_check_mark: Your 3.11 eval job has completed with return code 0.
Took: 0:00:01.000097
Thank you
My code:
start_time = datetime.datetime.now()
# message = send message
end_time = datetime.datetime.now()
latency = int((end_time - start_time).total_seconds() * 1000)
# edit message with latency```
should be good
!d time.perf_counter me when
time.perf_counter() โ float```
Return the value (in fractional seconds) of a performance counter, i.e. a clock with the highest available resolution to measure a short duration. It does include time elapsed during sleep and is system-wide. The reference point of the returned value is undefined, so that only the difference between the results of two calls is valid.
Use [`perf_counter_ns()`](https://docs.python.org/3/library/time.html#time.perf_counter_ns "time.perf_counter_ns") to avoid the precision loss caused by the [`float`](https://docs.python.org/3/library/functions.html#float "float") type.
New in version 3.3.
Changed in version 3.10: On Windows, the function is now system-wide.

!di discord.waitfor
ยป dict-get
ยป iterate-dict
ยป dictcomps
ยป discord-bot-hosting
could anyone tell me how i can wait for a button click
yes like 2 buttons and waiting for them to click
Buttons (or components) are now in the 2.0a version of the library which is only obtainable from GitHub
If you wish to use Buttons (and Selects/Dropdowns), please view the documentation for discord.ui here:
https://discordpy.readthedocs.io/en/latest/interactions/api.html#bot-ui-kit
You can also view examples in the repo: https://github.com/Rapptz/discord.py/tree/master/examples/views
Try looking at the gist
You need to define a button and then send it with your message
And button uses interaction
help
it's outside
There is not such events as on_button_click
Someone sent the example of discord.ui.View, look at it
hi
does anyone uses nextcord? uhh on_command_error doesn't work properly
Can someone help me ? I've been trying to run my bot and this is the error:
https://paste.pythondiscord.com/hibudotuxu
it seems your certificates aren't getting verified
u can try using another device to run your bot
help me .-.
A guide on fixing verification of an SSL certificate.
what lib are u using?
if it's discord.py then dpy doesn't have anything like slash_commands
Hey guys can you help me im running into this error:
split = content.split(".")
author = split[0].lower()
item = split[1]
amount = split[1]
``` this is the code
i use this
import discord
from discord.ext import commands
this is the error:
2023-07-05 18:35:16 ERROR discord.client Ignoring exception in on_message
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/discord/client.py", line 441, in _run_event
await coro(*args, **kwargs)
File "/Users/mac/Desktop/GrowBet/main.py", line 47, in on_message
item = split[1]
~~~~~^^^
IndexError: list index out of range
then where did u get the slash_command from?
dpy doesn't have anything like that
im struggling a lot honestly..
what lib can i get slash_cammand .-.
dpy also has slash commands but the are not defined using slash_commands
so please stop using old tutorials and guides or gpt for coding
Use this instead
Here is a short example of how to use discord.py's slash commands as well as general information on them:
https://gist.github.com/AbstractUmbra/a9c188797ae194e592efe05fa129c57f
This currently covers free commands and groups at the Bot level, as well as within Cog classes.
It also includes information and gotchas relating to syncing and whatnot.
NOTE: This will be migrating to https://about.abstractumbra.dev/ as soon as I can be bothered to finish it.
discord.py 2.0+ slash command info and examples. GitHub Gist: instantly share code, notes, and snippets.
My site for random things and stuff. Including a custom pip index and walkthroughs, both for discord.py!
thanks you
@bot.command()
async def ping(ctx):
XXX
XXX```
I can't type commands right now.
before.
What has changed in Discord?
Can someone type $ping?
What
?
selfbot 
where
Traceback (most recent call last):
File "main.py", line 11, in <module>
import cfscrape
File "/home/runner/XTool/venv/lib/python3.10/site-packages/cfscrape/__init__.py", line 19, in <module>
from urllib3.util.ssl_ import create_urllib3_context, DEFAULT_CIPHERS
ImportError: cannot import name 'DEFAULT_CIPHERS' from 'urllib3.util.ssl_' (/home/runner/XTool/venv/lib/python3.10/site-packages/urllib3/util/ssl_.py)
import cfscrape
"Hello, can someone help me? I would like my bot to respond to a person when someone writes on the server. The bot doesn't have any issues, but it's not responding. Thank you."
is this related to discord bots?
i have no udea
doesnt look like it is
do you have message content intents enabled? Do you have another on_message event?
yes a have another on_message event
the event decorator will override the internal event handler of your bot instance, hence you can only have one
it's better to use a listener instead

!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
async def join(ctx):
channel = bot.get_channel(join)
await ctx.send("To join the party, go to" + channel.mention + "!")```
its saying nonetype has no attribute mention
i double checked and join is the id of the channel
cause you pass join to .get_channel but join is name of the command
oops
guys having trouble with commands
the command keeps on getting registered as a message
@bot.command(name="hello") async def hello(ctx, arg: str): await ctx.channel.send("hello")
Discord.py uses bot.tree.command() for slash commands. Use that instead of bot.user_command().
dude silly please help
Remove arg from the following:
async def hello(ctx, arg: str)
tried with and without arg
Use bot.tree.command instead
ah ok
and add the following to your on_ready function:
try:
synced = await bot.tree.sync()
print(f"Synced {len(synced)} command(s)")
except Exception as e:
print(f"Houston, we have a problem.....\n\nException upon syncing commands: {e}")
@worthy ridge
how do i make it guild independent
you mean global?
yea
await sync(*, guild=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Syncs the application commands to Discord.
This also runs the translator to get the translated strings necessary for feeding back into Discord.
This must be called for the application commands to show up.
guild (Optional[Snowflake]) โ The guild to sync the commands to. If None then it syncs all global commands instead.
ahhhh
await ctx.send('**ROLES**\nl\nlFounder - The Founder is the Founder of the whole party.\nlChairman - The Chairman mkes decisions for the party, Chairman is the party leader.\nlAdmin - Admin Means that you help with the party and the Discord server.\nlCampaign Manager - Campaign Manager is the position that gets supporters for the party.\nlParty Member - A party member means you are a member of the DMP\nlVisitor - Visitor means you are visiting our discord server, maybe reading policies.\nl\nl**POLICIES**\nl\nlView Crime Policies - View all of our policies about Crime\nlView Government Policies - View all of our policies about Government\nlView Business Policies - View all of our policies about Business\nl\nl' + ctx.author.mention)
why is it doing that
i fixed the POLICIES cus i didnt close it
but i dont understand why all the l's
isnt that the newline
\n is
Same