#discord-bots
1 messages Β· Page 993 of 1
ah it looks like it because of the version dunder but youre right it wouldnt have so much imports lol
just dont run its src!
i do!
^
running what
How can I make it so no prefix you say the command
π
its not as said hes accessing the file which ofc it would raise an error since its a relative import it doesn't know the parent package
you're missing that , btw
Ik
and if you're not planning to use prefix
just use commands.when_mentioned or None(if it works, i'm not sure 'bout this one)
andy what is that nickname
whats that
Itβs kind of like a wildcard pointer
Itβs a pointer with no specific type
So it can really be casted to any type
What is this new app discovery thing for discord? Is it going to make places like top.gg defunct?
Set timeout=None and also bot.add_view() because views "timeout" when a bot goes offline
I say "timeout" in quotes because it doesn't really timeout, your bot just can't recognize them after it restarts
So using add_view makes it persistent
yeah.. that seems like top.gg, but on discord
just guessing tho lol
Hi, I got a small problem, the bot isn't sending the error message for some reason.
@commands.command(aliases=["ei", "ej", "einfo"])
@commands.bot_has_permissions(embed_links=True)
The permission is called embed_links isn't it?
@emojiinfo.error
async def emojiinfo_error(self, ctx, error):
if isinstance(error, commands.BotMissingPermissions):
eeembed = discord.Embed(title="Error has been issued!", description=f"`{error}`\n*Looks like the bot is missing some permissions.*", color=discord.Colour.dark_red())
eeembed.set_footer(text="commands.BotMissingPermissions")
await ctx.reply(embed=eeembed)
Definitely sounds like it. The whole voting system I'm currently setting up may be pointless af.
well, we still don't know much ppl are gonna respond to it tho
like.. most of the ppl don't really use "explore public server" discovery thingy
they just google "official discord server of xyz or whatever"
... so... let's see :")
I imagine it'll be good overall, just increase total servers that have bots
oh shit, what if they're getting all this out so they can try to monetize it
same model as top.gg uses with ads to get your server or bot seen
there is good possibility of it tho lol
true...
it is @commands.has_permissions(embed_links=True)
well it's kinda like playstore, but of discord bots
discord.bot is wrong
I see, thank you.
not sure what it's supposed to be but if you do print(str(dir(discord))) you'll get all possible attributes
@discord.ext.commands.has_permissions(**perms)```
A [`check()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") that is added that checks if the member has all of the permissions necessary.
Note that this check operates on the current channel permissions, not the guild wide permissions.
The permissions passed in must be exactly like the properties shown under [`discord.Permissions`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions "discord.Permissions").
This check raises a special exception, [`MissingPermissions`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.MissingPermissions "discord.ext.commands.MissingPermissions") that is inherited from [`CheckFailure`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure").
@dull terrace
just saw it, that's the permission for the member
yep
the error is literally saying it had no attribute bot
that not for nakime?
oh okay okay
Yea, you do not need bot in @commands.has_permissions line
bro
I do not think at least
discord.ext.commands.bot_has_permissions(**perms)
Similar to has_permissions() except checks if the bot itself has the permissions listed.This check raises a special exception, BotMissingPermissions that is inherited from CheckFailure.
i don't think any of us are going to put huge amounts of effort into this
yeah that's what i said
TYPOS
it's gonna be same as how we treat server discovery thing
!d discord.ext.commands.bot_has_permissions
@discord.ext.commands.bot_has_permissions(**perms)```
Similar to [`has_permissions()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.has_permissions "discord.ext.commands.has_permissions") except checks if the bot itself has the permissions listed.
This check raises a special exception, [`BotMissingPermissions`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.BotMissingPermissions "discord.ext.commands.BotMissingPermissions") that is inherited from [`CheckFailure`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure").
i didn't even know server discovery existed till like 2 weeks ago
π
if isinstance(error, commands.BotMissingPermissions):
Well, then why doesn't it throw the error?
@olive osprey type hint error to CommandError
will try
idk if the converter converts the type but idk i see nothing else wrong
error: CommandError
right? i think im being stupid
if you imported the class yes
Yeah for some reason it throws invalid syntax
show
in your functions parameters!
that colon should be a comma
he typehinted in the wrong place lol
why are we type hinting??
because i see no issue with his code (review it i probably missed something) and idk if the converter converts the type
how do i delete a msg?
Tried it with
async def emojiinfo_error(self, ctx, error: CommandError):
&
async def emojiinfo_error(self, ctx, error: commands.CommandError):
First one throws syntax error, and second one does the same error as before
!d discord.Message.delete
await delete(*, delay=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Deletes the message.
Your own messages could be deleted without any proper permissions. However to delete other peopleβs messages, you need the [`manage_messages`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.manage_messages "discord.Permissions.manage_messages") permission.
Changed in version 1.1: Added the new `delay` keyword-only parameter.
and what object does it take?
a message?
Pasting large amounts of code
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.
can you send a traceback
and I guess to get a message I need get_message?
i mean yes the method does return a message obj
Well it doesn't work.....
eru jsk py
_bot.get_message(967101932776865832).delete()```
unless it's provided by context, or an event
it returns None right?
https://paste.pythondiscord.com/uqamigiwad
This is my whole emojiinfo command, maybe this helps
EOF error
bro
NVM I missed a bracket
Traceback (most recent call last):
File "/app/.heroku/python/lib/python3.9/site-packages/jishaku/features/python.py", line 149, in jsk_python
async for send, result in AsyncSender(executor):
File "/app/.heroku/python/lib/python3.9/site-packages/jishaku/functools.py", line 109, in _internal
value = await base.asend(self.send_value)
File "/app/.heroku/python/lib/python3.9/site-packages/jishaku/repl/compilation.py", line 140, in traverse
async for send, result in AsyncSender(func(*self.args)):
File "/app/.heroku/python/lib/python3.9/site-packages/jishaku/functools.py", line 109, in _internal
value = await base.asend(self.send_value)
File "<repl>", line 1, in _repl_coroutine
_bot.get_message(967101932776865832).delete()
AttributeError: 'NoneType' object has no attribute 'delete'```
But now this
fetch the message
if the message isnt in cache it would return None
Discord be like
smh
@slate swan what would happen if i use except discord.Forbidden shouldn'T that work?
use else and raise the error
nah
I got the error already, it's coming out in my global error handler
eru jsk py
message = await _bot.fetch_message(967101932776865832)
message.delete()```
ah nice show
Traceback (most recent call last):
File "/app/.heroku/python/lib/python3.9/site-packages/jishaku/features/python.py", line 149, in jsk_python
async for send, result in AsyncSender(executor):
File "/app/.heroku/python/lib/python3.9/site-packages/jishaku/functools.py", line 109, in _internal
value = await base.asend(self.send_value)
File "/app/.heroku/python/lib/python3.9/site-packages/jishaku/repl/compilation.py", line 140, in traverse
async for send, result in AsyncSender(func(*self.args)):
File "/app/.heroku/python/lib/python3.9/site-packages/jishaku/functools.py", line 109, in _internal
value = await base.asend(self.send_value)
File "<repl>", line 1, in _repl_coroutine
message = await _bot.fetch_message(967101932776865832)
AttributeError: 'Bot' object has no attribute 'fetch_message'```
its a coroutine
WTF!
But for some reason it just doesn't send the error message
that doesn't apply on jsk afaik
it can't even fetch the message
try to catch that exception with the whole dir
wut
??
i swear it did
How may I ask you?
How could i get the message that an interaction is on when the interaction is interacted with
BRUHH
wait
In order to work with the library and the Discord API in general, we must first create a Discord Bot account.
Creating a Bot account is a pretty straightforward process.
omg it actually does
πΏ
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/master/api.html#discord.Message "discord.Message") from the destination.
I will fetch it from channel
@slate swan
eru jsk py
channel = _bot.get_channel(943187319064785008)
message = await channel.fetch_message(967147456892641310)
message.delete()```It doesn't delete yet!!
await message.delete()
that should be raising an error tho-
it doesn't raise any error
huh?
Yeah I figured that out myself π
well nvm it works
^
as shown here
How could I delete that message?
interaction.message.delete doesnβt do anything
thnx man
test = await ctx.send("hi")
await test.delete()
Or just do
await ctx.send("hi", delete_after=5.0)
or make the first one a one linerπ³
Oh with the curly brackets
Pasting large amounts of code
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.
^
I think I tried it once already, let me try again
Yeah same thing
Sure, where do you want me to put it? Into the error handler?
if isinstance(error, commands.errors.BotMissingPermissions)
Doesn't work
@commands.Cog.listener()
async def on_member_join(self,member:nextcord.Member):
await member.add_roles(933983900609441812)
is there anything wrong with my code? my bot isnt adding the autorole
?rtfm discord.Member.add_roles
wrong command
!d discord.Member.add_roles
await add_roles(*roles, reason=None, atomic=True)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Gives the member a number of [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role")s.
You must have the [`manage_roles`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.manage_roles "discord.Permissions.manage_roles") permission to use this, and the added [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role")s must appear lower in the list of roles than the highest role of the member.
What do you mean exactly? The type is "discord.ext.commands.errors.BotMissingPermissions"
im loving metaclasses
Is there any chance that I need to import error/s from discord.ext
well that's pretty much my code lol
tysm!!
theyre pog
Does an emojiinfo command invoke any CommandInvokeError?
how can i get role by name in a client.wait_for?
!e
def lol():
print(a)
a = 1
lol()
@slate swan :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 4, in <module>
003 | File "<string>", line 2, in lol
004 | UnboundLocalError: local variable 'a' referenced before assignment
How can I get a list of the messages in a channel
!d discord.TextChannel.history
async for ... in history(*, limit=100, before=None, after=None, around=None, oldest_first=None)```
Returns an [asynchronous iterator](https://docs.python.org/3/glossary.html#term-asynchronous-iterator "(in Python v3.10)") that enables receiving the destinationβs message history.
You must have [`read_message_history`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.read_message_history "discord.Permissions.read_message_history") permissions to use this.
Examples
Usage...
Is there any error handler for "discord.errors.Forbidden"?
what is it
Well, I was experimenting and thought that people could take the perms away for embed links from my bot yk, and well, how is my bot supposed to send an error in an embed without embed perms?
π
this chat is confusing me allot
lmfao i can't this fr was the problem 
!d discord.Permissions.embed_links
Returns True if a userβs messages will automatically be embedded by Discord.
i hate dpys abstractions
Man idk, it almost destroyed my brain so I'm happy to see it work now
Yeah, thanks to you both for trying to help, appreciate it
π
@dense swallow Per Rule 6, your invite link has been removed. If you believe this was a mistake, please let staff know!
Our server rules can be found here: https://pythondiscord.com/pages/rules
oops
hi im trying to make acknowledgements in userinfo cmd
code: ```py
async def get_acknowledgements(self, member):
bot_guild = self.bot.get_guild(764049436275114004)
staff_role = bot_guild.get_role(849669358316683284)
if member.id == self.bot.owner_id:
return [f":owner: Owner of {self.bot.user.name}"]
if staff_role in member.roles:
return [f":staff: Staff member in the [support server](link)"]
this in ui cmd
acks_list = await self.get_acknowledgements(member)
acks = "\n".join(acks_list)
errorpy
['Traceback (most recent call last):\n', ' File "C:\Users\LENOVO\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 181, in wrapped\n ret = await coro(*args, **kwargs)\n', ' File "D:\Projects\PizzaHat\PizzaHat\cogs\utility.py", line 63, in userinfo\n acks = "\n".join(acks_list)\n', 'TypeError: can only join an iterable\n', '\nThe above exception was the direct cause of the following exception:\n\n', 'Traceback (most recent call last):\n', ' File "C:\Users\LENOVO\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\bot.py", line 360, in invoke\n await ctx.command.invoke(ctx)\n', ' File "C:\Users\LENOVO\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 927, in invoke\n await injected(*ctx.args, **ctx.kwargs)\n', ' File "C:\Users\LENOVO\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 190, in wrapped\n raise CommandInvokeError(exc) from exc\n', 'discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: can only join an iterable\n']
ping me if u know the solution, thanks and gn
are you trying to use pycord on discord.py or smth
whatever, well thats not at all how you do it on dpy
you gotta make a command tree
then use @tree.command (for slash commands)
yes
but you gotta define tree as an instance of CommandTree
hello, i have a question
how i can check if a user have a role in a message event?
i try doing
if role in message.author.roles:
but isnt working is giving me this error AttributeError: 'User' object has no attribute 'roles'
This issue is due to the author being a User instance, which isn't bound to a guild unlike Member instances. You have to make sure that message.author is a Member, you can do this by isinstance or checking if message.guild is not None
for the name of the role. and then the bot gets the role by name and add to the user
Seems like this was in the context of a direct message?
anyway I could make this workpy if "COMMUNITY" in before.features or "COMMUNITY" in after.features.community: print( 'Checking "COMMUNITY" in before.features or "COMMUNITY" in after.features.community' ) elif ( "COMMUNITY" not in before.features or "COMMUNITY" not in after.features.community ): print( 'Checking "COMMUNITY" not in before.features or "COMMUNITY" not in after.features.community' )in a way that doesn't produce this errorpy Ignoring exception in on_guild_update Traceback (most recent call last): File "C:\Users\Teagan\Documents\Coding\Zupie\env\lib\site-packages\discord\client.py", line 375, in _run_event await coro(*args, **kwargs) File "C:\Users\Teagan\Documents\Coding\Zupie\bot\cogs\events.py", line 101, in on_guild_update if "COMMUNITY" in before.features or "COMMUNITY" in after.features.community: AttributeError: 'list' object has no attribute 'community'since the code I want to run only needs to run if a guild is a community server
xd i was reading the code and i forgot to turn on intents.
π
don't try to access the community attribute of the list
because it doesn't exist; removing that should fix your code
so how else can I check if a guild is a community server? since that's what I want to check as I have a piece of code that should only run if a guild is a community server
oh
Guys how do I make my bot configured to work on multiple servers with json?
so i want to make a queing systme with a json file does anyone know how i could like append stuff to the json file
and then how can a read from it and get 1 single object from it
Let's say I have memberchannel = client.get_channel(932124870173683782) defined within a command, which works fine, but it's quite messy. Is there a way that I can make a global definition to work everywhere so I don't have to keep defining that variable in every single command?
with open("logs.stonks","r") as f:
logschannel = f.read()
print(logschannel)
channel2 = self.bot.get_channel(logschannel)
embed=discord.Embed(color=0xFF0000)
embed.set_author(name=f"{member} ({memberID}) has STARTED a request", icon_url=pfp)
embed.timestamp = datetime.datetime.utcnow()
await channel2.send(f"{membermention}",embed=embed)
and then logs.stonks has 940354454983704668 in it, which is the channel id
how come it doesn't work?
Use int()
at what point
And anyone help me with discord.py views? I'm trying to just make a base view class, and then I can add different selects. This is the code:
https://mystb.in/AnaRefreshProcesses
The error I receive is Hybrid command raised an error: Command 'help' raised an exception: AttributeError: 'CogSelect' object has no attribute '_row'
The way I call it is view = HelpMenu().add_item(CogSelect(self.bot))
Any help is appreciated!
π
Well it usually happens when ur missing the super call but ur not so check if if name in os.getenv("FORBIDDEN_COGS").split(";"): return is happening
Oh hang on I just looked at the message you sent
intents = Intents.default()
intents.members = True
class logger(commands.Cog):
def init(self, bot):
self.bot = bot
@commands.Cog.listener()
async def on_message(message):
print('logger module online')
That shouldn't be a return, it should be a continue BRUH
is there something wrong in this>
please use ```py ``` btw
oh my bad
intents.members = True
class logger(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.Cog.listener()
async def on_message(message):
print('logger module online')```
the listener should take self as well as message, because it's in a class
also not sure why you're redefining intents in a cog
That's ok
It's just saying you are not using the message parameter
it will still run perfectly okay π
its not working
send code
one sec, i found this code of the internet so it probably has a lot of errors left
Hey @fervent shoal!
You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.
Don't copy code from the internet my g
You don't learn anything and you don't know how it works so it's impossible to debug
yea true
idk what that's even supposed to do but I see it everywhere
Are you trying to get logging?
@mortal dove how would i go about making something like GenAi, stuff that takes in what other people in the server are saying and uses words and says it
like if a bunch of people said "hello" over and over, the bot would take that in and say that
That's way over your head, but if you wanna do that then you should probably ask questions in #data-science-and-ml and implement what you find into python code
like from messages?
yes
That's just
@commands.Cog.lister()
async def on_message(self, message: discord.Message):
# append it to a .txt or .log file or something
should i add reaction gifs to my bot like owobot has
it would be pretty easy and i could do it better
sorry if im being really stupid rn
so I'm using a on_guild_update event and only want this guild name field to appear if the name gets chnaged but atm it's showing all the timepy if before.name is not after.name: embed.add_field(name="Name", value=f"{before.name} -> {after.name}")
.
send the rest of the code bruv
i fixed it, had to google that one
!d is
should use !=
ah okay
why am i getting this problem, its just happened, and how do i fix it
basic python
def __init__(self, bot):
self.bot = bot
self._last_member = None
class logger(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.Cog.listener()
async def on_message(self, message):
print('logger module online')
class MyClass(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.Cog.listener()
async def on_message(self, message: discord.Message):
print(message)
def setup(bot: commands.Cog):
bot.add_cog(MyClass(bot))
bot.run(TOKEN)```
its been so fine up until now
the whole thing
bro his error is in run
that is the whole thing, i scrapped the internet one
you should learn oop before using cogs
That's the whole file?
maybe im the error
mayhaps
I would recommend getting more familiar with python before making a bot. I actually admire your ambition but, bluntly, making bots is hard. You're welcome to try, but it seems like this is one of the first projects you have done.
ive done another one
it was a few months back tho
that one worked perfectly fine
You've made another bot?
yea
that one works just fine
but that aside, once i fix the bot issue will the code take in all words said in a channel with the code i have in rn or not
Well, you're asking for help with some of the most basic errors in python (ie syntax and undefined variables)
It will print all of the message objects, yeah.
all right new question, I have this if statement currently configured to add the field if either before.afk_channel or after.afk_channel exist, is there a way I can adapt this so it keeps the current functionality but also only adds the field if before.afk_channel and after.afk_channel are different?py async def channel_check(self, before, after): return f"{getattr(before, 'mention', None)} -> {getattr(after, 'mention', None)}" if before.afk_channel or after.afk_channel: embed.add_field( name="Afk channel", value=await channel_check(self, before.afk_channel, after.afk_channel), )
Guys, does someone knows how do I make my bot configured to work on multiple servers with json?
def __init__(self, bot):
self.bot = bot
@commands.Cog.listener()
async def on_message(self, message):
print('logger module online')
class MyClass(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.Cog.listener()
async def on_message(self, message: discord.Message):
await print(message)
def setup(bot: commands.Cog):
bot.add_cog(MyClass(bot))
bot.run(TOKEN)```
not printing anything at all
your not adding the logger cog class to the bot, either add a bot.add_cog(logger(bot)) into your setup or inherit logger in MyClass likepy class MyClass(logger)which will still be a cog since the logger class is inheriting from cog
logger do be not defined
Are those classes in the same file
Ignoring exception in on_member_remove
Traceback (most recent call last):
File "/home/maskuhpq/.local/lib/python3.9/site-packages/discord/client.py", line 343, in _run_event
await coro(*args, **kwargs)
TypeError: on_member_remove() takes 1 positional argument but 2 were given
@commands.Cog.listener()
async def on_member_join(self):
guild = self.client.get_guild(8048640127684977438)
channel = self.client.get_channel(966846673380556900)
await channel.edit(name=f"{len(guild.members)} Members")
@commands.Cog.listener()
async def on_member_remove(self):
guild = self.client.get_guild(8048640127684977438)
channel = self.client.get_channel(966846673380556900)
await channel.edit(name=f"{len(guild.members)} Members")```
anyone know why this doesn't mention the channel ( #discord-bots for example )
await ctx.channel.send(f"Admin speak and response channel changed to: <#{channel2}>")
but this does?
await ctx.channel.send(f"Admin speak and response channel changed to: <967189798517342248>")
and any fixes?
on_member_join and on_member_remove events pass an argument along to their handlers which contains the member object of the user who joined
!d discord.on_member_join
discord.on_member_join(member)``````py
discord.on_member_remove(member)```
Called when a [`Member`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member "discord.Member") join or leaves a [`Guild`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild "discord.Guild").
This requires [`Intents.members`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.members "discord.Intents.members") to be enabled.
i needed member :discord.member
ik i fixed it before you got back to me
Nice
What is stored in channel2?
And what does it send in the message?
'''py
with open("speak.stonks","r") as f:
newchannel = int(f.read())
f.close()
channel2 = self.bot.get_channel(newchannel)
await ctx.channel.send(f"Admin speak and response channel changed to: <#{channel2}>")'''
on mobile so formatting isn't working
channel2 has the channel id inside
channel2 needs to either contain an ID or a discord.TextChannel instance
it has the id
get_channel returns a channel object, which when converted to a string will print the channel's name, not the id. You can use channel.mention to mention it
f"{channel2.mention}"
thats the channel name
Yeah, it needs to have an ID not the channel name
Then why does it say holup?
!d discord.abc.GuildChannel.mention
property mention```
The string that allows you to mention the channel.
Doesn't look like it since you're just concatenating it using f strings
await ctx.channel.send(f"Admin speak and response channel changed to: <#{channel2}>")
This doesn't convert it to an ID from the name
im entering an id and its changing to the name
Ah, well keep it as an ID then
no but this does
Don't convert it to a name
'''py
with open("speak.stonks","r") as f:
newchannel = int(f.read())
f.close()
channel2 = self.bot.get_channel(newchannel)
await ctx.channel.send(f"Admin speak and response channel changed to: <#{channel2}>")'''
the whole point is I want it to mention the channel
Looks like you have the discord.TextChannel object, so just do channel2.mention
ok ill try that
Ty
Please tell me how to download all the images that are in the channel? With the help of a bot
That's going to be difficult and take a long time
Understood thanks
how do i put that in an f string with text around it?
non_bot_member_count = filter(...)
print(f"There are {non_bot_member_count } non-bot users in this server!")
ohhhhhh
Yeah. If you can get it into a variable, you can get it into an f string
@bot.event
async def on_member_join(member):
channel=bot.get_channel(944112299151618128)
await channel.send(f'{member.mention}, welc to saudi\n{member.guild.member_count}')
why doesn't this work?
it doesn't send anything
and there arent any errors
For slash commands and hybrid commands in discord.py, is there any way to describe an argument? Something like
async def command(
self,
ctx: Context,
arg: Option(name="name", description="A name or something", _type=str) = "Nothing"
):
you better join official discordpy server for advanced questions
bunch of guys discussed about it 2-3 days ago
Traceback (most recent call last):
File "C:\Users\mp420\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 352, in _run_event
await coro(*args, **kwargs)
File "C:\Users\mp420\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\bot.py", line 793, in on_connect
await self.register_commands()
File "C:\Users\mp420\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\bot.py", line 338, in register_commands
to_update = update_guild_commands[guild_id]
KeyError: '951383974817697793'``` how do i fix? guild id is correct, I am sure of that
What is update_guild_commands?
i saw something abt hybrid commands in the dpy changelog, what's the TL;DR of that?
what's a 'hybrid command'?
@sick birch didn't work
uhm
message command with app command
Oops. You haven't to list() it
at the same time
idk tbh
It's gonna look kind of weird, len(list(filter()))
@commands.command(name="update", description="Updates the member count!")
async def update(self, ctx):
guild = self.client.get_guild(8048546012184977438)
hannel = self.client.get_channel(967194657531402862)
annel = self.client.get_channel(9671966866644967535)
channel = self.client.get_channel(9668466745380556900)
bot_user = filter(lambda x: x.bot, guild.members)
user = filter(lambda x: not x.bot, guild.members)
await channel.edit(name=f"{len(guild.members)} Total Members")
await hannel.edit(name=f"{user} Humans")
await annel.edit(name=f"{bot_user} bots")
await ctx.send("Member count has been updated!")```
Also be aware you can only change channel name twice every 10 minutes
So it's probably better that you run a @tasks.loop with a 5 minute interval
can you help then
With making a tasks loop?
yea
no i got it from someone
@bot.event
async def on_member_join(member):
channel=bot.get_channel(944112299151618128)
await channel.send(f'{member.mention}, welc to saudi\n{member.guild.member_count}')
why doesnt this work?
!intents
Using intents in discord.py
Intents are a feature of Discord that tells the gateway exactly which events to send your bot. By default, discord.py has all intents enabled, except for the Members and Presences intents, which are needed for events such as on_member and to get members' statuses.
To enable one of these intents, you need to first go to the Discord developer portal, then to the bot page of your bot's application. Scroll down to the Privileged Gateway Intents section, then enable the intents that you need.
Next, in your bot you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:
from discord import Intents
from discord.ext import commands
intents = Intents.default()
intents.members = True
bot = commands.Bot(command_prefix="!", intents=intents)
For more info about using intents, see the discord.py docs on intents, and for general information about them, see the Discord developer documentation on intents.
Do you have member intents on
yes
Would you have another on_member_join event
You enabled them both in the dev portal and in your code?
yes
If you used list comp in the first place, you wouldnt even need to do that. list comp is significantly faster than filter(according to a lot of stuff on the internet)
Yeah that works too
f"There are {len([i for i in guild.members if not i.bot])} humans in the server"
Are you sure the event is getting triggered?
I personally prefer filter but yeah
think so
Add a print statement to it
If the print statement doesn't work then your event isn't getting triggered
Traceback (most recent call last):
File "C:\Users\mp420\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 352, in _run_event
await coro(*args, **kwargs)
File "C:\Users\mp420\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\bot.py", line 793, in on_connect
await self.register_commands()
File "C:\Users\mp420\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\bot.py", line 338, in register_commands
to_update = update_guild_commands[guild_id]
KeyError: '951383974817697793'```
show code
k
the erorr?
The code
to_update = update_guild_commands[guild_id]
KeyError: '951383974817697793'
``` from here
i mean theres a lot but okay
async for guild in self.fetch_guilds(limit=None):
update_guild_commands[guild.id] = []
for command in [
cmd
for cmd in self.pending_application_commands
if cmd.guild_ids is not None
]:
as_dict = command.to_dict()
for guild_id in command.guild_ids:
to_update = update_guild_commands[guild_id]
update_guild_commands[guild_id] = to_update + [as_dict]
for guild_id, guild_data in update_guild_commands.items():
try:
commands = await self.http.bulk_upsert_guild_commands(
self.user.id, guild_id, update_guild_commands[guild_id]
)```
args = message.content.split(' ')
if len(args) == 2:
member: Member = discord.utils.find(lambda m: args[1] in m.name, message.guild.members)
if member:
await member.ban()
await message.channel.send(f'Member {member.name} gebannt.')
else:
await message.channel.send(f'Kein User mit dem Namen {args[1]} gefunden.')```
**DOES SOME1 KNOW WHY MY BAN NOT WORKING?**
You shouldn't use on_messages for commands
Lmao you're manually finding the member
chill the tutorial they're following prolly gonna show that soon LOL
making first time a bot π₯Ί
it's not async, bot.add_cog(YourCog())
This is so much work for something that doesn't work
it is async
im not on the pypi version
Why'd you use a on_message?
Hey u can visit this its cool https://vcokltfre.dev/
A tutorial to help you make better Discord bots.
(BETTER THAN YOUTUBE)
Yeah visit vcokltfre's website
Use commands from commands.Bot
!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/master/api.html#discord.Client "discord.Client") and as a result anything that you can do with a [`discord.Client`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client "discord.Client") you can do with this bot.
This class also subclasses [`GroupMixin`](https://discordpy.readthedocs.io/en/master/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/master/api.html#discord.Client "discord.Client"), This class does not require manually setting a [`CommandTree`](https://discordpy.readthedocs.io/en/master/interactions/api.html#discord.app_commands.CommandTree "discord.app_commands.CommandTree") and is automatically set upon instantiating the class.
@vale estuary
thx
wonder if it's possible to make discord bot that can make me literally fly irl
@sick birch Traceback (most recent call last):
File "/home/maskuhpq/.local/lib/python3.9/site-packages/discord/ext/tasks/init.py", line 101, in _loop
await self.coro(*args, **kwargs)
TypeError: stats() missing 1 required positional argument: 'member'
it works great when not on a loop
@umbral night ?
You probably can control a plane with a discord bot
Can I see the code?
sure
@tasks.loop(minutes=5)
async def stats(self, member: discord.member):
guild = self.client.get_guild(80486467782184977438)
hannel = self.client.get_channel(967167619731402862)
annel = self.client.get_channel(967196586546644967535)
channel = self.client.get_channel(96686765473380556900)
bot_user = len(list(filter(lambda x: x.bot, guild.members)))
user = len(list(filter(lambda x: not x.bot, guild.members)))
await channel.edit(name=f"{len(guild.members)} Total Members")
await hannel.edit(name=f"{user} Humans")
await annel.edit(name=f"{bot_user} bots")```
(note ids not vaild)
ah loops don't take a member argument
and without
hm?
nhandled exception in internal background task 'stats'.
Traceback (most recent call last):
File "/home/maskuhpq/.local/lib/python3.9/site-packages/discord/ext/tasks/init.py", line 101, in _loop
await self.coro(*args, **kwargs)
TypeError: stats() missing 1 required positional argument: 'member'
I'm in as Bro's SMP Bot#7548!
^CTask exception was never retrieved
future: <Task finished name='Task-1' coro=<Loop._loop() done, defined at /home/maskuhpq/.local/lib/python3.9/site-packages/discord/ext/tasks/init.py:88> exception=TypeError("stats() missing 1 required positional argument: 'member'")>
Traceback (most recent call last):
File "/home/maskuhpq/.local/lib/python3.9/site-packages/discord/ext/tasks/init.py", line 125, in _loop
raise exc
File "/home/maskuhpq/.local/lib/python3.9/site-packages/discord/ext/tasks/init.py", line 101, in _loop
await self.coro(*args, **kwargs)
TypeError: stats() missing 1 required positional argument: 'member'
Probably through an api or something
Ye
self.stats.cancel()
self.stats.start()
Imagine ticket booking in discord
@sick birch
That's odd. Can I see code?
i sent you code!
That was before you removed member
@tasks.loop(minutes=5)
async def stats(self):
guild = self.client.get_guild(80486467782184977438)
hannel = self.client.get_channel(967167619731402862)
annel = self.client.get_channel(967196586546644967535)
channel = self.client.get_channel(96686765473380556900)
bot_user = len(list(filter(lambda x: x.bot, guild.members)))
user = len(list(filter(lambda x: not x.bot, guild.members)))
await channel.edit(name=f"{len(guild.members)} Total Members")
await hannel.edit(name=f"{user} Humans")
await annel.edit(name=f"{bot_user} bots")```
yes
Did you forget to remove your other command?
nope
This is the only function named "stats"?
yes
Guys how do I make my bot configured to work on multiple servers with json?
I'm not sure what else it might be
Elaborate?
read the error code
I did, but the error makes sense if you hadn't saved your code
That or there's another function called stats
How are you starting the loop?
self.stats.cancel()
self.stats.start()
hi, im currently using sqlite3 and am having some troubles with this join, it displays the member_id twice in the output. Can anyone help?
oh, this does concern my discord bot but thanks anyways
can you try it on your own bot?
Would anyone know how to have a like event where if someone is put into timeout it starts an event
Like
on_membet_ban at all? I am trying to make a logging event where if a member is put into timeout it would activate
Triple fail
lol
im going to sleepπ
as okimii pointed out it should be triggered by the~~ on_member_edit~~ on_member_update event, you can compare their timeout there
I'd prefer not to, sorry
Ahh oki thank you
can you get another prespective?
What do you mean?
#965291480992321536 perhaps
ah
how can i make the bot take a transcript of the channel and send it to a sepertate channel for logs
like ask someone else what they think is wrong
Don't have anyone like that unfortunately
okmi?
Loop through each message in the channel using .history(), send it to another channel. Be careful about ratelimits
me?
i mean, it put its into a file
Ah
tasks loop issue with member
Yeah, alright, that's fine
scrooll up for code and error codes
you know what i mean or you need a example?
I know what you mean, don't worry
Same principle, loop through, write content of message to file
do you know what i need to do?
sorry but i dont really wanna help right now im kinda tired and off today π
i dont know how to do that?
Probably might want to store it in some sort of buffer
oof it stumped robin
Sorry π¦ feel better soon
could you give me an example of what i need to do?
id try adding a print statement just before you start() the loop just to make sure your code has updated, robin's already mentioned its either not saved or is being shadowed by another method name
thanksπ
explain?
messages: list[str] = [m.content for m in await channel.history(...).flatten()]
# write `messages` to file
print('hello')
self.stats.start()``` then make sure hello shows up before the error message
Hope you get better soon okimii 
thats not really much help sorry
k
could i send you what ive got and you take a look?
awe thank you guys, you guys are very kindπ
I'm guessing you want more help on actually writing to file instead of getting the messages?
yeah
Hey @dapper tapir!
It looks like you tried to attach file type(s) that we do not allow (.html). We currently allow the following file types: .gif, .jpg, .jpeg, .mov, .mp4, .mpg, .png, .mp3, .wav, .ogg, .webm, .webp, .flac, .m4a, .csv, .json.
Feel free to ask in #community-meta if you think this is a mistake.
could you accept my friend req please
!paste I don't do dms, sorry. Use this for your code
Pasting large amounts of code
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.
if you only need to upload the transcript and not actually save it to your drive, then i would suggest an in-memory file like io.StringIO
i want to send a file
yeah good point, i'm guessing you'll just be sending that to another channel
that i cant send here
what file?
import discord
from discord.ext import commands
class MyClient(discord.Client):
async def on_ready(self):
print('Logged on as', self.user)
self
async def on_message(self, message):
# don't respond to ourselves
if message.author == self.user:
return
if "ip" in message.content:
await message.reply('``connect 61:28035``',mention_author=True)
if "hack" in message.content:
await message.reply('Please do not call out cheaters. Make a ticket here [#952679827046006804](/guild/267624335836053506/channel/952679827046006804/)', mention_author=True)
await message.delete()
if "esp" in message.content:
await message.reply('Please do not call out cheaters. Make a ticket here [#952679827046006804](/guild/267624335836053506/channel/952679827046006804/)', mention_author=True)
await message.delete()
if "giveaway" in message.content:
await message.reply('If you have recieved a dm about a giveaway it is a scam. Make a ticket here [#952679827046006804](/guild/267624335836053506/channel/952679827046006804/)', mention_author=True)
if "cheater" in message.content:
await message.reply('Please do not call out cheater. Make a ticket here [#952679827046006804](/guild/267624335836053506/channel/952679827046006804/)', mention_author=True)
await message.delete()
if "aimbot" in message.content:
await message.reply('Please do not call out cheaters. Make a ticket here [#952679827046006804](/guild/267624335836053506/channel/952679827046006804/)', mention_author=True)
await message.delete()
if "help" in message.content:
await message.reply('Please create a ticket in via out support system, [#952679827046006804](/guild/267624335836053506/channel/952679827046006804/) ',mention_author=True)
await message.delete()
if message.content == '?1':
await message.channel.send('Hey there, thanks for contacting support today. What is it that we can help you with today?')
await message.delete()
if message.content == '?upload':
await message.channel.send('Hey there, for us to be able to process your report we need to have evidence of the person that your reporting, please could you upload your clip.\nIf your clip is too large to upload to discord please upload it to https://streamable.com/ and then send the link here.\nMany thanks Swift Rust.')
await message.delete()
if message.content == '?close':
await message.channel.send('Hello thank you for opening a ticket today, we hope that we met your needs and please rate your experience with us.\nIf you have any more support needs please feel free to make another ticket.\nThis ticket will be closed in 5 minutes, so if you have any final questions please do now.\nMany thanks from the Swift Rust staff team.')
await message.delete()
client = MyClient()
client.run('')```
what the heck
but what im trying to currently is set up a system that will put all the messages into a file like this
that is not how you do commands
aws is so confusing god
it gets easier over time
ummm let me check
and thats a html file
@dapper tapir this could really benifit from a dictionary
i read somewhere you need an education email but i signed up using my personal
maybe is that why i didnt get access to the console?
wdym?
Could be. Again, I only used the non-education version so I wouldn't know haha
nope 1.7.3
ah
@sick birch
stuff = {
"ip": "something",
"hack": "something",
"esp", "something",
}
etc
Loop through that, check if message.contents has any of that
if so just do stuff["key"] and send that
instead of massive if chains that frankly are hard to read and understand
and what do i put in the "something" part?
something would be your message
that's a dictionary and it has key-value pairs
{"key": "value"}
if message.contents:
stuff = {
"ip": "Please do not call out cheaters. Make a ticket here [#952679827046006804](/guild/267624335836053506/channel/952679827046006804/)"
"hack" ....```
like this?
wait im just getting distracted atm
i need to know how to do that transcript thing
How to make the bot not delete messages two weeks ago? (ping me, please)
Yikes
do what
if "fa**ot" in message.content:
await message.delete
if "n***er" in message.content:
await message .delete```
but it can't seem to get recognized
so if i dont want to have to do this for every word
Have a list of them
do a list comprehension idk
how would i list them
bad_words = ["bad word #1", "bad word #2", "bad word #3", ...]
for bad_word in bad_words:
# check if message has a bad word, delete if so
like this
but you see how i done it
Bad word filters are pretty hard to implement perfectly considering how many workarounds there are
[word for word in bad_words if word in message.content]
or something like that idk
using levenshtein distance is a bit better
if "n54","461" in message.content:
await message.delete```
is it possible to do it like this?
how would i go around adding this to my code then?
Just follow the blueprint I gave you
You'd probably want that inside an on_message listener
!pypi better_profanity
That should go inside the for loop
this is a better idea
How would a list comprehension work here exactly?
don't
i don't know who recommended that but no
I know
uses any()
I'm asking why would they use a list comprehension for this
any()
any(i in message.content for i in list_of_swears)
would return true if a swear is detected
but ofc there are libs which do it much better
imagine using a library for just this much
lmao
just an import, and an if, not that much setup
state some benefits of breaking such stones
and it works better instead of creating every single combination of swear words
ikr
i'd rather a library now
regex>
lmao
i'll just stop saying controversial things, things sorted
i mean
one guy told me that message.startswith() in on_message() was better than bot.command() and a prefix
π for making commands?
aw, thats so uwu
Must have been hard to relate those, but I appreciate whoever that was
yeah π
π oh gawd wtf
Who
I said who
but he changed it to this when i asked him to fix it
π bro... just wanna say, that it's not a good practice
a friend
What's their username and tag
bro, don't mind.. one of his friend must have said it.. let it be like that.. :'/ let's help him now..
cristionel messialdo#0990
i wasnt lying
MESSI + RONALDO = MESSIALDO
smh
Tell him to add me
k
I'm going to ask messi why
well whatever
lmao
aee ask for his signature.. i like messi :;/ and ronaldo too
ok jk nvm
My man is a BIG football fan
Innocent
How'd you know that was my message
No friend is innocent
\π
LMAO feature?
thats love
Where he is
\π
lmaoo u going to his house? cokecake
Which window are looking at me from
lmao
No
who said it was a window
I can't open up his dms
check under your bed
send him a request
I sleep on a futon
you've windows under your bed?
then check pending
!ot ahem ahem
Off-topic channel: #ot2-never-nesterβs-nightmare
Please read our off-topic etiquette before participating in conversations.
ahem ahem
o
He has friends turned off
i sent him your user
why is friending people such a big deal
its not like they're actually your friends now
its just so they can send you a message
I just like it how y'all are making him accept Skev's friend when he can just join the server solve the issue and leave the server
oh yeah
why even join the server lmao, just help with his code :"/
π€¦ββοΈ
Bru
o
tbh, i'd scared to really add a random person who wants to talk :kek:
Hi
ooo he's here
@zenith mural your code make us cry at night
There
ok
so sad
well
i guess it could be some creep
Why use on_message for commands?
totally
but that would probably be more fun
What should I use
Why'd you add me then
Take the to an ot @regal pulsar @slate swan
love
o
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/master/api.html#discord.Client "discord.Client") and as a result anything that you can do with a [`discord.Client`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client "discord.Client") you can do with this bot.
This class also subclasses [`GroupMixin`](https://discordpy.readthedocs.io/en/master/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/master/api.html#discord.Client "discord.Client"), This class does not require manually setting a [`CommandTree`](https://discordpy.readthedocs.io/en/master/interactions/api.html#discord.app_commands.CommandTree "discord.app_commands.CommandTree") and is automatically set upon instantiating the class.
alright boomer π
This has commands
told you :/
Use them
;/
bot>client
POV: Message commands using on_message are better so that you can loop through a couple hundred conditionals to check
not really appropriate here
This reminds me of that time we we're fucking scrambling to fix some dude's 36 if statements
ctx.channel.send() >> > ctx.send()
BTW did everyone get this message from discord
But we couldn't think of shit
which one?
no i meant the channel.send thing
So i went to python general
Too long to copy paste
i got it
Is hunai verified
cool
yeah pretty sure only owners of verified bots
Prolly cz those are the ones who are getting affected the most
both works in the same way btw lol
just for verified bots
yeah
Sadge π
but .channel.send is still better
yeah
How?
how? ctx.send is a pointer to ctx.channel.send
Yea
πmy man prefers to write long code, he's koder
ctx.send also looks clean
LMAO
Answer
Definitely does not lmfao
does π²
I prefer swwet and simple, so ctx.send is one for me :>
Ctx.send looks better
ctx is... already a commands.Context object by default
yeah
why do you write it like that
but i wont get vsc's syntax highlighting otherwise
.... bruh
Why only typehint the ctx
And not the return type
see
blue and gray looks good
it doesn't make any difference anyway
Blue and yellow looks old like a old ass piece of paper that turned yellow
but yellow looks better
whatever
the green is the best imo
Is your teeth yellow
. . .
If it isn't
π
Why
thats enough ducky
oh my fucking god
Wtf
Nyx boutta fold your ass
gets people every time
lmfao
we shouldn't care about his editor anyway
LMAOOO
im just out of words bro
how is that even useful
Have you found the funny
are you that lazy that you can't just win + r > cmd > enter
no
go and touch some grass too, if possible :")
There's no grass here
Only smoke
....
try:
print("Hello World")
except:
pass
..
uhm.. nice hello world program :")
its very nice isnt it
yes :")
my best work
hello xeno :>
C=
ok but it's not related to #discord-bots ...
oh yeah
:")
I'm hoping this is a joke
yes very
tkinter.......pyautogui......keyboard...... π
Bit off topic don't you think
i just realised that there's a Library named uvloop ( which may be common to use, im learning about it late) that can speedup asyncio event loops
but sadly, it doesn't work for windows
so I have ```py
@cache(ttl=10)
async def gun_names():
async with bot.db.execute("SELECT gun FROM builds") as cursor:
data = await cursor.fetchall()
return [gun_name[0] for gun_name in data]
def needed_autocomplete(choices: typing.Callable[[], typing.List[str]], n: int = 10):
async def actual(inter, option: str):
rev = await choices
if option in rev:
return option
matches = fuzzy_match(option, choices, n=n)
return list(matches)
return actual
@bot.slash_command()
async def build(
inter: disnake.CommandInteraction,
mode : listmode,
gun: str = commands.Param(autocomplete=needed_autocomplete(gun_names)),
and it raises ``` rev = await choices
TypeError: object function can't be used in 'await' expression
oh yeah i did that and it said something like function object is not iterable
wait let me try something else
what is passed in the on_guild_channel_create ??
!d discord.on_guild_channel_create
discord.on_guild_channel_delete(channel)``````py
discord.on_guild_channel_create(channel)```
Called whenever a guild channel is deleted or created.
Note that you can get the guild from [`guild`](https://discordpy.readthedocs.io/en/master/api.html#discord.abc.GuildChannel.guild "discord.abc.GuildChannel.guild").
This requires [`Intents.guilds`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.guilds "discord.Intents.guilds") to be enabled.
!d discord.on_guild_channel_update it takes two parameters
discord.on_guild_channel_update(before, after)```
Called whenever a guild channel is updated. e.g. changed name, topic, permissions.
This requires [`Intents.guilds`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.guilds "discord.Intents.guilds") to be enabled.
async def on_guild_channel_update(before, after):
...
uh....
sheesh, why would that happen, try re-running
what's onii?
....what
onii is not defined
you want to fetch it
ah sorry mb
you could just update the table no?
onii = onii + 1
sql confusion
@client.command()
async def select(ctx):
await ctx.send(
"select Menu",
components = [
Select(
placeholder = "Select something!",
options = [
SelectOption(label = "69", value = "420"),
SelectOption(label = ":)", value = ":(")
]
)
]
)
interaction = await client.wait_for("select_option")
await interaction.send(content = f" selected!")
this is my code and the select menu is sent by the bot but upon clicking a option it says interaction failed
no errors shown in console
i seem to have an issue where my button doesn't edit my message. this is the line of code that's supposed to edit it but it doesn't seem to do anything when i click on the button. Any idea on what i did wrong?
await interaction.response.edit_message(content=client.crypto_pages[current+1])```
does your bot have the message_content intent?
is this correct?
yeah looks right. not sure why it's not working in that case. have you confirmed that the button_callback() function is getting invoked?
is there any way to check?
did u enable in dev portal
well, a print statement should work
which setting did i need to enable
what is the error
um any help?
Why doesn't it trigger the error handler when I call the class using raise MaximumValuesReached()
elif isinstance(error, MaximumValuesReached):
await inter.edit_original_message("You have reached the maximum number of notes!")
The error class
class MaximumValuesReached(Error):
def __init__(self):
super().__init__("maximum values reached")
If itβs raised within the command it will use CommandInvokeError
You can access the original error with this
!d discord.ext.commands.CommandInvokeError.original
The original exception that was raised. You can also get this via the __cause__ attribute.
hm yeah, it "is" raising that too
oh thanks
@role.group(pass_context=True)
async def delete(self, ctx, role: str):
role = discord.utils.get(ctx.guild.roles, name=role)
if role not in ctx.guild.roles:
await ctx.send(f"there is no role named **{role}**")
else:
discord.utils.get(ctx.guild.roles, name=role)
await role.delete()
await ctx.send(f"role **{role}** has been deleted π")
this give me None type back when i try to delete a role that doesnt exist
how could one make it so if you do like !role member :emoji: it gives the member the role
try using try and except
wdym
try:
await role.delete()
except:
await ctx.send("role not found")
or, if role != ctx.guild.roles
@slate swan
this won't work, still gives me the None type back when i try it
show me the code
sec
also this is just a example you gotta adjust it into your code
mhm already tried
show me the code
this was the first one
@role.group()
async def delete(self, ctx, role: str):
role = discord.utils.get(ctx.guild.roles, name=role)
try:
discord.utils.get(ctx.guild.roles, name=role)
await role.delete()
await ctx.send(f"role **{role}** has been deleted π")
except:
if role not in ctx.guild.roles:
await ctx.send(f"there is no role named **{role}**")
error?
wb
@role.group()
async def delete(self, ctx, role: str):
role = discord.utils.get(ctx.guild.roles, name=role)
try:
discord.utils.get(ctx.guild.roles, name=role)
await role.delete()
await ctx.send(f"role **{role}** has been deleted π")
except:
if role != ctx.guild.roles:
await ctx.send(f"there is no role named **{role}**")
number 2
@role.group(pass_context=True)
async def delete(self, ctx, role: str):
role = discord.utils.get(ctx.guild.roles, name=role)
if role != ctx.guild.roles:
await ctx.send(f"there is no role named **{role}**")
else:
discord.utils.get(ctx.guild.roles, name=role)
await role.delete()
await ctx.send(f"role **{role}** has been deleted π")
Wrong emoji
except:
await ctx.send("role not fohnd")
except will happen when it has a error and none tupe is a error
oh right
still gives me the same as this
append the rolename to a var then
then send the var
i mean
i already tried doing role: discord.Role
also dont work, cus thats what other people said
i got big question```py
@bot.command()
async def role(ctx, member: discord.Member, *, arg):
emoji = bot.get_emoji(967297501961015327)
if arg.content == emoji:
await member.add_roles(discord.utils.get(ctx.guild.roles, name="buyer"))
why dont you just typehint role to discord.Role?
as in role: discord.Role?
Yeah
yes
tried that
nvm
that wont even send the message
listen
that does nothing
Why to use arg.content
ctx,*,role
im new to py and wouldnt that grab the content in the arg?
role:discord.Role
try this remove str from role and add a asterisk before the argument
class discord.Role```
Represents a Discord role in a [`Guild`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild "discord.Guild")...
he is trying to get the role name to be sent in the message
bro no i want it to be the emoji gives the role π€¦
did you guys even check the code
