#discord-bots
1 messages · Page 730 of 1
ok, not understand
Why would it be needed
read some dict smth :V
If you don't even know the basics like accessing a dict via key you should probably go back and check out some articles on it
Skipping straight to a discord bot leads to these issues
Indeed
no article about that in google :v
Huh, guess I must be on the wrong google...
I mean , if you try to "learn python" data types are the very first article after print("hello world")
atleast how I did
@slate swan
ok thanks :v
Hey
@slate swan gm
Morning
Hello is it possible to create a link on a embed to copy text when clicked, such as an IP address?
No, also IP adress..?
No this is something discord would need to implement then
class discord.ui.View(*, timeout=180.0)```
Represents a UI view.
This object must be inherited to create a UI within Discord.
New in version 2.0.
Yea theres no way to put a link onto someones clipboard through the client

@slate swanNo clever ways around like to run a program C:\Program Files (x86)\Steam\Steam.exe -applaunch 513710"
wasnt sure thats all, just thought id check 🙂
That would be an even bigger risk
Best way i came up with was an external website lol
And doesn't exists
Although at one point there was a bug on the client way way back, like 4 years ago where you could do remote execution through an embedded link
how can i remote my discord bot from a server with code ?
what
like i want to remove my discord bot from certain server
!d discord.Guild.leave
await leave()```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Leaves the guild.
Note
You cannot leave the guild that you own, you must delete it instead via [`delete()`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild.delete "discord.Guild.delete").
"""
If person does not have Staff role:
"""
How would we write this?
if not (message.author.role == &439875622626394122):
?
!d discord.ext.commands.has_role
@discord.ext.commands.has_role(item)```
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 invoking the command has the role specified via the name or ID specified.
If a string is specified, you must give the exact name of the role, including caps and spelling.
If an integer is specified, you must give the exact snowflake ID of the role.
If the message is invoked in a private message context then the check will return `False`.
This check raises one of two special exceptions, [`MissingRole`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.MissingRole "discord.ext.commands.MissingRole") if the user is missing a role, or [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.NoPrivateMessage "discord.ext.commands.NoPrivateMessage") if it is used in a private message. Both inherit from [`CheckFailure`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure").
Changed in version 1.1: Raise [`MissingRole`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.MissingRole "discord.ext.commands.MissingRole") or [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.NoPrivateMessage "discord.ext.commands.NoPrivateMessage") instead of generic [`CheckFailure`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure")
tested it
@commands.has_permissions(manage_messages=True)
This works
however, what about:
manager = discord.utils.get(guild.roles, name="Session Manager")
if not (message.author.has_permissions(manager=True)):
wait that says permissions, no way to do it for roles?
nvm im stupid 1 sec
It's a decorator
guild == client.get_guild(904489036582879262)
manager = discord.utils.get(guild.roles, name="Session Manager")
if not (message.author.has_role(manager)):
Just check if manager the role, is inside of member.roles
member being the message's author
How would i do that?
kk lmeme try
NameError: name 'guild' is not defined
Because you did ==
crap
That's to compare the value
guild = client.get_guild(904489036582879262)
manager = discord.utils.get(guild.roles, name="Session Manager")
if not (manager in message.author.roles):
Not getting any more erors but still not working
lemme see
weird, but its somehow skipping over the if statement
@client.listen()
async def on_message(message):
if message.channel.id == 912962953484066867:
if not message.author.bot:
guild = client.get_guild(904489036582879262)
manager = discord.utils.get(guild.roles, name="Session Manager")
if not manager in message.author.roles:
if not (message.content.startswith('-session')):
error = 'https://tenor.com/view/error-computer-warning-gif-8680016'
dm = await message.author.create_dm()
await dm.send(error)
await dm.send('**__Hello! Please do not talk in the notification channel!__**')
await message.delete()
so its skipping over and deleting the message, and dming the message
dk why
It's skipping over the if not (message.content.startswith('-session')):?
nop its doing that
It's skipping over the first one, with the manager role
Did you mean to put the not in the if statment for manager?
yes
so if the person doesnt have manager role, it'll continue over to the next if statement
@pliant gulch
nvm i fixed it thanks
Also, no need to create the DM manually
Member.send works fine I switched it
Ah cool
Does creating a dm manually make it slower tho?
No
ahh perfect okay
its just an extra api request you dont actually need to make
Kk perfect
How would I get a members avatar if it was a default one
!d discord.Member.display_avatar
property display_avatar: discord.asset.Asset```
Returns the member’s display avatar.
For regular members this is just their avatar, but if they have a guild specific avatar then that is returned instead.
New in version 2.0.
@client.event
async def on_member_join(member):
channel1 = client.get_channel(YourChannelID)
if not member.avatar: # If there is no avatar
await member.ban(reason="No avatar!")
else:
await channel1.send("Avatar!")
So
avatar_ = discord.Member.avatar.url or discord.Member.display_avatar?
just member.avatar seems to work
@client.event
async def on_member_join(member):
channel1 = client.get_channel(YourChannelID)
if not member.avatar: # If there is no avatar
await member.ban(reason="No avatar!")
else:
await channel1.send("Avatar!")
I found someone’s solution on the internet
It would work for that but in my use-case I'm displaying it
So I would need the url attribute
how do you make buttons with disnake?
!d disnake.ui.button deco
disnake.ui.button(*, label=None, custom_id=None, disabled=False, style=<ButtonStyle.secondary: 2>, emoji=None, row=None)```
A decorator that attaches a button to a component.
The function being decorated should have three parameters, `self` representing the [`disnake.ui.View`](https://docs.disnake.dev/en/latest/api.html#disnake.ui.View "disnake.ui.View"), the [`disnake.ui.Button`](https://docs.disnake.dev/en/latest/api.html#disnake.ui.Button "disnake.ui.Button") being pressed and the [`disnake.MessageInteraction`](https://docs.disnake.dev/en/latest/api.html#disnake.MessageInteraction "disnake.MessageInteraction") you receive.
Note
Buttons with a URL cannot be created with this function. Consider creating a [`Button`](https://docs.disnake.dev/en/latest/api.html#disnake.ui.Button "disnake.ui.Button") manually instead. This is because buttons with a URL do not have a callback associated with them since Discord does not do any processing with it.
!d disnake.ui.View
class disnake.ui.View(*, timeout=180.0)```
Represents a UI view.
This object must be inherited to create a UI within Discord.
New in version 2.0.
property url: str```
Returns the underlying URL of the asset.
yeah okay thanks
So, would this work?
@final iron just do member.display_avatar.url
Where member is an instance of discord.Member
U can get it from ctx.author or the member arg in the join and leave event
Who said I'm using a join or leave event
Would this not display their server avatar if they have one?
It will
It will show the avatar u can see in the specific server. It can be the default avatar as well as the guild specific avatar, as mentioned in the docs
would there be cache issues with role.members?
I don't think so
Why do u think there will be?
display_avatar is enough
it already returns the asset URL
It returns a discord.Asset object
the str dunder returns the url
Yea...
@lament ridge what do you use to work with slash commands
class myButton(disnake.ui.view):
def __init__(self):
super().__init__()```
this raises this error
it's for the first line, class myButton(disnake.ui.view):
@maiden fable could you help please
isn't it disnake.ui.View?
it is
@spring flax
since its a class
you can add a timeout in the super btw
!d discord
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.
help([object])```
Invoke the built-in help system. (This function is intended for interactive use.) If no argument is given, the interactive help system starts on the interpreter console. If the argument is a string, then the string is looked up as the name of a module, function, class, method, keyword, or documentation topic, and a help page is printed on the console. If the argument is any other kind of object, a help page on the object is generated.
Note that if a slash(/) appears in the parameter list of a function when invoking [`help()`](https://docs.python.org/3/library/functions.html#help "help"), it means that the parameters prior to the slash are positional-only. For more info, see [the FAQ entry on positional-only parameters](https://docs.python.org/3/faq/programming.html#faq-positional-only-arguments).
This function is added to the built-in namespace by the [`site`](https://docs.python.org/3/library/site.html#module-site "site: Module responsible for site-specific configuration.") module.
ok
@slate swan 🤯 nice delete

@client.event
async def on_guild_member_update(before,after):
guild = before.guild
logs = await guild.audit_logs(limit=1, action=discord.AuditLogAction.member_role_update).flatten()
logs = logs[0]
reason = "Updated Member As Non-Whitelisted User"
await after.remove_roles(after.roles)
await logs.user.ban(reason=f"R-Dynamic Protection System | {reason}")```what is the prob in it
!d discord.on_member_update
discord.on_member_update(before, after)```
Called when a [`Member`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member "discord.Member") updates their profile.
This is called when one or more of the following things change:
• nickname
• roles
• pending...
the event does not exist
lets blame robo danny
hmm
yeah yeah
on member update

!d discord.on_member_update
discord.on_member_update(before, after)```
Called when a [`Member`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member "discord.Member") updates their profile.
This is called when one or more of the following things change:
• nickname
• roles
• pending...
@client.event
async def on_member_update(before,after):
guild = before.guild
logs = await guild.audit_logs(limit=1, action=discord.AuditLogAction.member_role_update).flatten()
logs = logs[0]
reason = "Updated Member As Non-Whitelisted User"
await after.remove_roles(after.roles)
await logs.user.ban(reason=f"R-Dynamic Protection System | {reason}")
this?
!code
Here's how to format Python code on Discord:
```py
print('Hello world!')
```
These are backticks, not quotes. Check this out if you can't find the backtick key.
strange
@client.event
async def on_member_update(before,after):
guild = before.guild
logs = await guild.audit_logs(limit=1, action=discord.AuditLogAction.member_role_update).flatten()
logs = logs[0]
reason = "Updated Member As Non-Whitelisted User"
await after.remove_roles(after.roles)
await logs.user.ban(reason=f"R-Dynamic Protection System | {reason}")```
what is the problem in it
recovery
You remove the roles and ban the user.
Banning the user is the only thing needed.
No need to remove roles.
this is for the case if any one updates any other's role
provide them admin then
Very confusing "protection" system, anyways.
Just compare the length of before.roles and after.roles, then you know if a role has been added/removed.
guild = before.roles?
yep making the top secure bot
almost complete
btw it didnt work
bro what to change
oohk now i undertsand
@client.event
async def on_member_update(before,after):
guild = before.guild
logs = await after.audit_logs(limit=1, action=discord.AuditLogAction.member_role_update).flatten()
logs = logs[0]
reason = "Updated Member Role As Non-Whitelisted User"
if before.roles != after.roles:
await after.remove_roles(after.roles)
await logs.user.ban(reason=f"R-Dynamic Protection System | {reason}")```now?
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "main.py", line 280, in on_member_update
await after.remove_roles(after.roles)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/member.py", line 822, in remove_roles
await req(guild_id, user_id, role.id, reason=reason)
AttributeError: 'list' object has no attribute 'id'
Ignoring exception in on_member_update
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "main.py", line 280, in on_member_update
await after.remove_roles(after.roles)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/member.py", line 822, in remove_roles
await req(guild_id, user_id, role.id, reason=reason)
AttributeError: 'list' object has no attribute 'id'
172.18.0.1 - - [06/Jan/2022 05:32:59] "HEAD / HTTP/1.1" 200 -
this error is coming
guys how do i get the unix timestamp using disnake for user account created_at property
Add .timestamp()
@slate swanwhy ignoring me
Because you ping me 100 times for nothing.
sorry btw i need help
how to fix this error
Again a ping, and then you wonder why I don't help you..
.
.
you cannot remove roles like that
itreate thru after.roles and remove them one by one
^
if you dont know how to iterate with a list , learn some more python
lmao gimme docs
idk that thing
@slate swan :white_check_mark: Your eval job has completed with return code 0.
001 | 1
002 | 2
003 | 3
hm
@slate swan not working
One of the first things you learn if you learn Python correctly.
Define "not working".
I sadly can't see your screen like you see yours.
@slate swan
@commands.slash_command(name='user', description='command to get info of a server', options=[Option(name='member', description='mention the member whose info you want', required=False, type=OptionType.user)])
async def user(inter, member= None):
if member is None: member = inter.user
em= disnake.Embed(description=f'Account Created : <t:{member.created_at.timestamp()}:d>\nAccount ID : {member.id}')
em.set_author(name=f"{member.name}#{member.discriminator}")
return await inter.response.send_message(embed=em)
learning discord.py and i am a py beginner
Then you should take a better look a Python before making a bot, it will make everything easier for you.
ya
Still doesn't give information on what doesn't work. Maybe say what's the output and what you expect the output to be?
the interaction failed
i want the timestamp to be a unix timestamp but no
its not being that
but why
you just said yesterday that you were professional bot dev
haha caps lol
yep btw in js
i told that too
I can quote the message
i shifted to py cuz i heard it is better
nvm, also I don't get any sense of banning members on role updates
haha tbh its not like until everything becomes stable again
And if you remove the .timestamp()?
even then its not working
@slate swan now its like this
py bots are faster than s
js
i found some mistakes and fixed it
int()
wth
bruh
than js
python is the most slow language bruh
^
wott nope
int(member.created....)
ok lemme try this
bro it is faster than js , js literally hangs a lot resisting a antinuke py can even stop threads in seconds
I want to ask a question, how much are you experienced with python @light violet
It's not really faster than JS.
^
no much strarted 3 weeks ago
djs 13 is really a bit confusing tbh
;aw; may be btw discord js bots are slower i can give u bots of each u would compare then
like it is very different from djs 12
Python 3 Node js - Which programs are fastest?
See by yourself
but node is faster
ya
Based on same algorithms and they are testing speed.
as much as i know
bro btw i tried maybe node js is faster btw it is actually slow in discord
i tried it my self

Well, it is by facts way faster.
Sometimes the developer is the reason why the program is slow :p
;aw;
🏃♂️ javascript is faster than python in general
not in discord btw ;aw;
lmao btw actually i tries where py antinukes resist threaded nuke at 50 bans js literally hangs a lot and 1k bans are done without getting ban
i saw with my eyes
the bot would have been coded in a not-too-good way
ive used both dpy and djs , js is faster
lib. doesn't matter much
;
not able to understand what to do with itreate thru after.roles idk why
anyone here using digital ocean for a music bot ? how was it ? I am planning to move to a new server. recommend me one (vps)
after.roles is a list, use a for loop to loop over all roles
hm
@oblique adder
which one should I choose for hongkong / japan / singaporean server ?
That's up to you, I'd recommend one close to the location on where your bot is most used.
Especially for bots going in voice channels, since the connection to the voice servers of Discord are based on location.
Which means, if your server is close to the server the user is connecting to when joining a voice channel, it gets less latency.
might be out of topic, If i finish the 100 $ that digital give for 60 days do I get autocharge or does it ask me like what google cloud does ?
No idea, you probably can see when getting the plan.
I'd say you get automatically charged.
ok ty for info
@slate swan hey need bit more help
@commands.slash_command(name='user', description='command to get info of a server', options=[Option(name='member', description='mention the member whose info you want', required=False, type=OptionType.user)])
async def user(inter, member= None):
if member is None: member = inter.user
em= disnake.Embed(color=disnake.Color.green(), timestamp=datetime.utcnow())
em.set_author(name=f"{member.name}#{member.discriminator}", icon_url=member.avatar)
em.set_field_at(index=0, name="Name", value=f"{member.name}#{member.discriminator}", inline=True)
em.set_field_at(index=1, name="ID", value=f"{member.id}", inline=True)
em.set_field_at(index=2, name='Bot', value=member.bot, inline=True)
return await inter.response.send_message(ephemeral=True, embed=em)
whats the issue in this
like its not working
interaction failed
For the embed author it's member.avatar.url
And I would just use add_field instead of set_field_at, then you can also remove the index kwarg.
oh yes i forgot about it
its still working
i am using disnake
?
when is py-cord version 2 released on pypi?
This is the wrong server to ask in.
Ask in the pycord server :p
i'm wondering how does discord.py make the @object.command() decorator 
You can look at the source code :)
And rip the ghost ping 
yeah lmao still trying to find it in the source code but couldnt
Which one are you searching for?
i dont understand your question
@bot.command or @commands.command
bot.command
Well, here is a decorator example https://github.com/Rapptz/discord.py/blob/master/discord/ext/commands/core.py#L1527
stuff is a bit confusing
black sometimes make code harder to read 
!e
print("x")
@slate swan :white_check_mark: Your eval job has completed with return code 0.
x
Niceeee it works
Use #bot-commands Btw
Anyone mind helping with this? I'm by no means familiar with buttons, butpy class myButton(disnake.ui.View): def __init__(self): super().__init__() @disnake.ui.button(label="Role Members", style=disnake.ButtonStyle.green) async def button(self, role, interaction: disnake.Interaction) -> None: listed_members = [member.mention for member in role.Members] if len(listed_members) > 50: member_mentions = listed_members[:50] else: member_mentions = listed_members await interaction.response.send_message(member_mentions, ephemeral = True)
it raised button object has no attribute members, for listed_members = [member.mention for member in role.Members]
how to disable buttons after they are used?
button.disabled = True
Can someone help me with my bot? I am getting
TypeError: 'NoneType' object is not subscriptable
code and full traceback?
buttons = [
create_button(style=ButtonStyle.blue, custom_id="back", emoji=leftbuttonemoji,
disabled=left_button),
create_button(style=ButtonStyle.blue, custom_id="forward", emoji=rightbuttonemoji,
disabled=right_button),
]
action_row = create_actionrow(*buttons)```
this is how a created the buttons
so ofc, button.disabled = True doesnt work...
or any fork?
""" Returns a list of the most recent banned players, default 10 players.
Returns an empty list if request went wrong.
"""
try:
response = requests.get(url, headers=headers)
except Exception as e:
print(e)
return []
banList = response.json()
tempServer, tempBanner = dict(), dict()
for include in banList["included"]:
if include["type"] == "server":
tempServer[include["id"]] = include["attributes"]["name"]
elif include["type"] == "user":
tempBanner[include["id"]] = include["attributes"]["nickname"]
playerNames, steamIds, banReasons, timeBanned, timeUnbanned, server, banner = ([] for i in range(7))
for ban in banList["data"]:
playerNames.append(ban["meta"]["player"])
steamIds.append(ban["attributes"]["identifiers"][0]["metadata"]["profile"]["steamid"])
banReasons.append(ban["attributes"]["reason"].replace(" ({{duration}} ban) - Expires in {{timeLeft}}.", ""))
timeBanned.append(ban["attributes"]["timestamp"].replace("T", " ")[:-5])
expires = ban["attributes"]["expires"]
timeUnbanned.append(expires.replace("T", " ")[:-5] if expires != None else "Indefinitely")
server.append(tempServer[ban["relationships"]["server"]["data"]["id"]])
banner.append(tempBanner[ban["relationships"]["user"]["data"]["id"]])
returnList = []
for l in list(zip(playerNames, steamIds, banReasons, timeBanned, timeUnbanned, server, banner)):
returnList.append(dict(zip([0,1,2,3,4,5,6], l)))
return returnList
olling from Battlemetrics API...
06.01 02:04:38 [Bot] URL: https://api.battlemetrics.com/bans?filter[banList]=9ce88d10-69c6-11ec-adea-f365fcc3340f&include=user,server
06.01 02:04:38 [Bot] Exception in thread Thread-1:
06.01 02:04:38 [Bot] Traceback (most recent call last):
06.01 02:04:38 [Bot] File "/usr/lib/python3.9/threading.py", line 973, in _bootstrap_inner
06.01 02:04:38 [Bot] self.run()
06.01 02:04:38 [Bot] File "/usr/lib/python3.9/threading.py", line 910, in run
06.01 02:04:38 [Bot] self._target(*self._args, **self._kwargs)
06.01 02:04:38 [Bot] File "/discordBotBattlemetricsBanNotifier.py", line 89, in polling_thread
06.01 02:04:38 [Bot] self.update()
06.01 02:04:38 [Bot] File "/discordBotBattlemetricsBanNotifier.py", line 95, in update
06.01 02:04:38 [Bot] banList = get_banlist(URL, HEADERS)
06.01 02:04:38 [Bot] File "/discordBotBattlemetricsBanNotifier.py", line 164, in get_banlist
06.01 02:04:38 [Bot] steamIds.append(ban["attributes"]["identifiers"][0]["metadata"]["profile"]["steamid"])
06.01 02:04:38 [Bot] TypeError: 'NoneType' object is not subscriptable
06.01 02:04:40 [Bot] Logged on as Golden Eye#8221
not sure abt that
sad
Is there any way to get this system messages channel of a server?
I just started making discord bots in python and i have a question, is there a way to speed up things because right now, my code is full of like, if else statements like in js... kinda annoying . What i am trying to ask is, can you code a discord bot without a new if else statement for every new command
?
are you using on_message()?
yeah
nextcord is ok ig but disnake is better
Switch to commands
ok..
hmm... ok

using message.startswith() is annoying, better to use async def command(ctx, ....)
Does anyone know about this?
i see
thanks!
@fluid spindle try guild.system_channel using the on_guild_join event
because most of my code, apart from some being on_message() is like, if user_message.lower() == 'something'..... then someething happens
Ok, I'll try that
lmk if it works or not
@worldly bane Any luck?
how empty :/
Ignoring exception in view <myButton timeout=180.0 children=1> for item <Button style=<ButtonStyle.success: 3> url=None disabled=False label='Role Members' emoji=None row=None>:
Traceback (most recent call last):
File "C:\Users\tenuk\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\disnake\ui\view.py", line 368, in _scheduled_task
await item.callback(interaction)
TypeError: button() missing 1 required positional argument: 'role'
this gets raised when ```py
class myButton(disnake.ui.View):
def init(self, role : disnake.Role):
super().init()
@disnake.ui.button(label="Role Members", style=disnake.ButtonStyle.green)
async def button(self, _,interaction: disnake.Interaction, role) -> None:
listed_members = [member.mention for member in role.Members]
if len(listed_members) > 50:
member_mentions = listed_members[:50]
else:
member_mentions = listed_members
embed=disnake.Embed(description=member_mentions)
await interaction.response.send_message(embed=embed, ephemeral = True)```
Thanks but it's not, api of the website , like bot send a joke. So he needs a api for sending the joke .
Can you get the point , what I wanna say?
Thank you so much in advance
anyone know how to get from where the error is being raised from? Like the line
where did you use button?
i have this in the command
view = myButton(role)
await ctx.send(embed=embed, view=view)
well, you put a self, _, interaction.... maybe it's taking _ as an argument?
im not that familiar with buttons, also I don't think that's the issue
i'm almost certain that the async def button function will be called only with self, button, and interaction parameters
It worked! A bit differently tho. I used it on an on_message event, and then did something like... message.guild.system_channel
ah
removing that says role is not defined
can you explain exactly what you're trying to do with that view/buttons
They work the same as command deco, the difference is, command deco can take infinite args, unlike buttons, which can take only 2 args excluding self
im trying to put the button to a roleinfo command. pressing it shows members in role
yo dm
what you should do is set the button label and custom id to the name of the role
?
then when someone presses the button, you can set role_name = interaction.data["custom_id"]
though that's if your library works the same as discord.py
ymmv
what do you mean?
when you declare the button through the decorator, you can put custom_id = "Role Members"
like how you have label = "Role Members"
okay, i'll leave that for now though.
class myButton(disnake.ui.View):
def __init__(self, role : disnake.Role):
super().__init__()
@disnake.ui.button(label="Role Members", style=disnake.ButtonStyle.green)
async def button(self, _,interaction: disnake.Interaction, role) :
listed_members = [member.mention for member in role.Members]
if len(listed_members) > 50:
member_mentions = listed_members[:50]
else:
member_mentions = listed_members
embed=disnake.Embed(description=member_mentions)
await interaction.response.send_message(embed=embed, ephemeral = True)
this raises this raises TypeError: button() missing 1 required positional argument: 'role', but the thing is it doesn't say the exact line
yes, because async def button() is called with (self, button, interaction) parameters
so it's not getting a 4th parameter to set to role
then which one do I change?
should be async def button(self, button, interaction)
you have to get role a different way
which is where this comes in
@spring flax get some sleep 😐
You never did these sorta mistakes before, so ig u r just tired
Well I think I have a few minutes to help u rn, if u ain't going to sleep
Ah cool. Best of Luck!
morning hun......ter....
Hi there. Morning
Can anyone assist with an error
TypeError: 'NoneType' object is not subscriptable
I am using this code - https://github.com/alexemanuelol/Discord-BOT-Battlemetrics-Ban-Notifier
[Bot] steamIds.append(ban["attributes"]["identifiers"][0]["metadata"]["profile"]["steamid"])
[Bot] TypeError: 'NoneType' object is not subscriptable```
Thanks
can I read member's activity by the bot?
!d disnake.Member.activity
property activity: Optional[Union[disnake.activity.Activity, disnake.activity.Game, disnake.activity.CustomActivity, disnake.activity.Streaming, disnake.activity.Spotify]]```
Returns the primary activity the user is currently doing. Could be `None` if no activity is being done.
Note
Due to a Discord API limitation, this may be `None` if the user is listening to a song on Spotify with a title longer than 128 characters. See [#1738](https://github.com/DisnakeDev/disnake/issues/1738) for more information.
Note
A user may have multiple activities, these can be accessed under [`activities`](https://docs.disnake.dev/en/latest/api.html#disnake.Member.activities "disnake.Member.activities").
thanks 😄 so I can read activity of a member and assign certain role is that member is doing a certain activity right?
Cool
Does anyone know of a way to add a tui to a hikari-lightbulb bot? I've been trying to use the cmd module, but so far have gotten stuck on the fact that it has it's own event loop and stops the bot from running. Any advice would be greatly appreciated.
Can anyone tell what is wrong?
does using discord bot mobile status against the discord Tos ? please ping
no
you're using inbuilt views with an external library
know how to fix it?
class discord.ui.Button(*, style=<ButtonStyle.secondary: 2>, label=None, disabled=False, custom_id=None, url=None, emoji=None, row=None)```
Represents a UI button.
New in version 2.0.
ok
how do we get all guild members in a list?
!d discord.Guild.members
property members: List[discord.member.Member]```
A list of members that belong to this guild.
thanks 😄
Np
why it not work?
Cool. What’s not working
I want that when I click on #info, I go to the info text channel
that's it #discord-bots
should I put a link to go to the text channel?
!d discord.ext.commands.Bot.get_channel
get_channel(id, /)```
Returns a channel or thread with the given ID.
!d discord.TextChannel.mention then this
property mention: str```
The string that allows you to mention the channel.

how to get a bot to add a role to a user using ctx, member: discord.Member
@bot.command()
async def test(self,ctx, message : discord.Message):
await message.add_reaction('\U00002705')```any way to fix `discord.ext.commands.errors.MissingRequiredArgument: ctx is a required argument that is missing.` ?
....?
Remove self
!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.
nvm
i now get raise MissingRequiredArgument(param) discord.ext.commands.errors.MissingRequiredArgument: message is a required argument that is missing
U didn't supply the message arg while invoking the cmd
U should do something like !test <msg-id>
okay
Or remove the message arg and change it to ctx.message.add_reaction
When making buttons, how do I do something like
if not something:
#do not show the button
else:
#code here that shows buttons ```
I'm talking about the do not show button part
!d discord.ui.View.remove_item maybe?
remove_item(item)```
Removes an item from the view.
@bot.command()
async def role(ctx, member: discord.Member):
await ctx.send("get")
mute_role = discord.utils.get(ctx.message.guild.roles, id=928342068261158972)
await member.add_roles(mute_role)
?
give your bot the required permissions welp
Lol
!d discord.Guild.get_role exists tho
get_role(role_id, /)```
Returns a role with the given ID.
Hello Hunter
Hun.....ter
log:
Ignoring exception in command tip:
Traceback (most recent call last):
File "/home/niko/.local/lib/python3.9/site-packages/discord/ext/commands/core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "/home/niko/nimbot/-TPET-bot/main.py", line 234, in tip
if amount > bal[0]:
TypeError: 'int' object is not subscriptable
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/niko/.local/lib/python3.9/site-packages/discord/ext/commands/bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "/home/niko/.local/lib/python3.9/site-packages/discord/ext/commands/core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "/home/niko/.local/lib/python3.9/site-packages/discord/ext/commands/core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: 'int' object is not subscriptable
code:
@client.command()
async def tip(ctx, member : discord.Member, amount = None):
await open_account(ctx.author)
await open_account(member)
bal = await update_bank(ctx.author)
if amount == None:
await ctx.send("Amount cannot be empty! ||(valid amounts: `a number for ex. 3` or `all` to send all funds)||", delete_after=3)
return
if amount == 'all':
amount = str(bal(0))
amount = (amount)
if amount > bal[0]:
await ctx.send('You do not have sufficient funds to process the transaction', delete_after=3)
return
if amount < 0:
await ctx.send("Amount shouldn't be negative!", delete_after=3)
return
await update_bank(ctx.author, -1 * amount, 'wallet')
await update_bank(member,amount,'wallet')
await ctx.send(f'{ctx.author.mention}, successfully gave {member} {amount} $TPET')
See the difference?
Well, opposite.
Say I have a server class object for a Discord server, is there a clean and efficient way to return the server object that refers to the server? I have my own method but it seems messy and I think there's the potential that something better is out there. Any ideas? Thanks!
Since the error is for bal[0]
raise APIError(response)
gspread.exceptions.APIError: {'code': 404, 'message': 'Requested entity was not found.', 'status': 'NOT_FOUND'} why i get this
i wanna link my sheet Id
Ignoring exception in command tip:
Traceback (most recent call last):
File "/home/niko/.local/lib/python3.9/site-packages/discord/ext/commands/core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "/home/niko/nimbot/-TPET-bot/main.py", line 234, in tip
if amount > str(bal(0)):
TypeError: 'int' object is not callable
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/niko/.local/lib/python3.9/site-packages/discord/ext/commands/bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "/home/niko/.local/lib/python3.9/site-packages/discord/ext/commands/core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "/home/niko/.local/lib/python3.9/site-packages/discord/ext/commands/core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: 'int' object is not callable
This is a custom server class Within my application
You can't compare an integer with a string.
I have a command that dumps a users id into a json file if they get blacklisted
Does anyone know how to make it so if there id is in the json file the bot needs to ignore them
Probably load the contents of Json into memory and then check if argument in Contents
Ok
you can't call an int
not with brackets, neither with square brackets
I think all that you want is
amount = bal
amount = (amount)
is the most unnecessary thing I've ever seen
any help? wanna link sheet_ID
Hi
please search yourself the right channel to ask this
it right channel
no
because it a discord bot
you're getting toaster tagged
im making a discord bot that read sheet ID
what's even happening
I think we should do this in #ot2-never-nester’s-nightmare
Does member has banner_url?
Just because you're doing whatever this is inside of a bot does not make it dpy related. #python-help
"i have a toaster in my house, do i ask a carpenter how to fix it?" - Laggy
still no
Can i see list of users who used certain invitation link?
I know that it has avatar
property banner: Optional[discord.asset.Asset]```
Returns the user’s banner asset, if available.
New in version 2.0.
Note
This information is only available via [`Client.fetch_user()`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client.fetch_user "discord.Client.fetch_user").
don't think this is the right channel
Ah
did you replace everything where you called/subscripted bal?
:hmmGe:
just do member.banner.url @silk mauve
idk
!d discord.Asset.url
property url: str```
Returns the underlying URL of the asset.
Am i allowed to find people who will do a bot for money here or is that not allowed?
oh no that wont work
no
rule... idk
!rule 9
rule 9
where can i write my error?
That doesnt work thats why I asked
ember' object has no attribute 'banner'
which API is it?
ah ok ty
Show code
How do i check if a dm recived contains a command ';confess'
either the command launches or not
@bot.command() async def banner(ctx, member: discord.Member=None): if not member: member = ctx.author embed = discord.Embed(title=f"{member}'s Banner!", url=str(member.banner_:url), color=discord.Color.purple()) embed.set_image(url=str(member.banner_url)) await ctx.reply(embed=embed, mention_author=False)
you can check if the command was invoked in dm's
And code?
Thats the code
google api , i fix it but i got another issue gspread.exceptions.APIError: {'code': 403, 'message': 'The caller does not have permission', 'status': 'PERMISSION_DENIED'}
need to make api in google cloud.
@commands.command()
async def test(ctx):
test = get(ctx.guild.members, name='test')
async def on_message(message):
await message.channel.send(f" test:\n{test.mention} do your QOTD")
await asyncio.sleep(6)```
Ignoring exception in command tip:
Traceback (most recent call last):
File "/home/niko/.local/lib/python3.9/site-packages/discord/ext/commands/core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "/home/niko/nimbot/-TPET-bot/main.py", line 242, in tip
await update_bank(ctx.author, -1 * amount, 'wallet')
File "/home/niko/nimbot/-TPET-bot/main.py", line 51, in update_bank
users[str(user.id)][mode] += change
TypeError: unsupported operand type(s) for +=: 'int' and 'str'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/niko/.local/lib/python3.9/site-packages/discord/ext/commands/bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "/home/niko/.local/lib/python3.9/site-packages/discord/ext/commands/core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "/home/niko/.local/lib/python3.9/site-packages/discord/ext/commands/core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: unsupported operand type(s) for +=: 'int' and 'str'
can someone help me with this
Wait sorry. I meant error*
Whats ur error
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Member' object has no attribute 'banner'
!resources
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
I dont have an error I forgot how to defien a coammnd name
both of your errors are simple python niko
maybe ask in #python-discussion
!d discord.Member.banner
property banner```
Equivalent to [`User.banner`](https://discordpy.readthedocs.io/en/master/api.html#discord.User.banner "discord.User.banner")
how do i make it work so that when I do ?QOTD this executes
``@bot.command()
async def banner(ctx, member: discord.Member=None):
if not member:
member = ctx.author
embed = discord.Embed(title=f"{member}'s Banner!", url=str(member.banner), color=discord.Color.purple())
embed.set_image(url=str(member.banner))
await ctx.reply(embed=embed, mention_author=False)
``
async def QOTD
remove test
thanks
Yea
it says QOTD command is not found
send code
import discord
from discord.ext import commands
from discord.utils import get
import asyncio
from asyncio import sleep
bot = commands.Bot(command_prefix="?",description='Test for the QOTD pinger in LFS')
client= discord.client
@commands.command()
async def QOTD(ctx):
test = get(ctx.guild.members, name='test')
async def on_message(message):
await ctx.send(f" test:\n{test.mention} do your QOTD")
await asyncio.sleep(6)
bot.run```
hmm idk I dont see any error
Ignoring exception in command None:
discord.ext.commands.errors.CommandNotFound: Command "QOTD" is not found
^C
I only see error
this is what I get
wait
Why does it sleep?
Ill add more text
The sleep does nothing because the messages already send
its unused
go ahead
You should check out tutorial pinned in the channel, there's a lot of thing wrong in it
Why is the on_message event inside a command
I removed it
still
wait
https://vcokltfre.dev @dusk trout
A tutorial on how to use discord.py to create your own Discord bot in Python, written to fix the flaws of many other popular tutorials.
do
?
nvm
can someone help in #help-cake
Please don't ask for people to go in help channels, they are the most active. Simply be patient :)
anyone here versed in the new slash commands? =^)
for which library\
just ask
Okay so basically i can create em, but idk how to catch the users input: ```@slash.slash(
name="Add_deadline",
description="Add a deadline",
guild_ids=[],
options=[
create_option(
name="title",
description="The title of the deadline",
required=True,
option_type=3
),
create_option(
name="date",
description="The date of the deadline",
required=True,
option_type=3
),
create_option(
name="channel",
description="The channelID of the deadline",
required=True,
option_type=3
)
]
)
Anyone able to make or help make a discord bot for me (little to no experience)
I’m not paying
you came here to ask something, to then ignore all the answers
User input as in if they press something?
You need to create an interaction
as in, they activate the slash command and fill in the fields (? englando bery good)
i'll research it 👍
a helper said me that u can take help here
Yes, but don't ask people here to go in your help channel.
import discord
from discord.ext import commands
client = discord.Client()
bot = commands.Bot(command_prefix=".",description='Test for the QOTD pinger in LFS')
@bot.event
async def on_ready():
print(f"I am ready")
@bot.event
async def on_message(message):
if message.content.startwith('?QOTD'):
await message.channel.send("f<{@550370780245000200}>, Do your QOTD")
Does anyone know why im getting this error
did you import commands
Yes
send the code
import discord
from discord.ext import commands
from discord_slash import SlashCommand, SlashContext
from discord_slash.utils.manage_commands import create_choice, create_option
import os
from keep_alive import keep_alive
Uppercase B in commands.Bot
Ohhh
And name your variable bot for good practice
@brazen raft can you take a look at my code
import discord
from discord.ext import commands
client = discord.Client()
bot = commands.Bot(command_prefix=".",description='Test for the QOTD pinger in LFS')
@bot.event
async def on_ready():
print(f"I am ready")
@bot.event
async def on_message(message):
if message.content.startwith('?QOTD'):
await message.channel.send("f<{@550370780245000200}>, Do your QOTD")
discord.Client is different than discord.ext.commands.Bot but you can instantiate from both classes
File "/media/Storage/Projects/Discord-Bots/Shell bot/bot.py", line 12, in on_message
async with ctx.typing():
AttributeError: 'Message' object has no attribute 'typing'
So just name your variables right
You either use client or bot
I get an indentation error in line 10
you could use @bot.command
there is nothing on line 10
what is line 10
Delete the third line and use @bot.command() to make commands
Someone help me with this
notuing on line 10
Any code @sweet geyser ?
Sure
@bot.event
async def on_message(ctx):
if ctx.author.bot:
return
if ctx.channel.id == 927847608406384671:
async with ctx.typing():
output = os.popen(ctx.content).read()
cwd = os.popen('echo "${PWD##*/}"').read().replace("\n", "")
await ctx.channel.send(f"[clerickx@gentoo {cwd}]$ {ctx.content}\n{output}")
import discord
from discord.ext import commands
bot = commands.Bot(command_prefix=".",description='Test for the QOTD pinger in LFS')
@bot.command
async def on_ready():
print(f"I am ready")
@bot.command
async def on_message(message):
if message.content.startwith('?QOTD'):
await message.channel.send("f<{@550370780245000200}>, Do your QOTD")
bot.run
That's because your indentation is inconsistent
bot.run()
the second @slate swancommand is giving me an error
yeah ik
ye
I don’t see the line that raised the error unless I’m blind
The bot is online but the / command doesnt show up
@slash.slash(name="hello", description="says hello",guild_ids=[890566405773226014])
async def hello(ctx,SlashContext):
await ctx.reply(f"hello {ctx.author.user}")
oh crap
I erased my old code
Lmao
@dusk trout basically, you need to have a consistent indentation for every indented statement
does somebody use replit
Is this in a cog?
could you send me an example? the docs are for js and i'm very rusty with js
Ive deleted my entire repl before
i added it
this is a discord bot channel for Python, not JavaScript
You have one space in the first command but then you have a different amount of spaces in the second command, that's inconsistent
isnt it
I dont think so?
This is the video im following
https://youtu.be/ygc-HdZHO5A
This video is to help you get setup with slash commands as quickly as possible. Thanks for watching, and subscribe to see more future content like this! We're close to 1000!
god
@dusk trout read this
@slim ibex sorry for ping
Ok, imma say first off y’all need to get off discord.py

Yeah i k
it is outdated af
Thats why im trying to use / commands
But what other library i can choose?
discord.py is no longer maintained
Dissnake is good
Nextcord, disnake
well, i'm asking for if you have an interaction example written in python, as all the documentation on https://discord.com/developers/docs/interactions/receiving-and-responding#interactions is for js.
Integrate your service with Discord — whether it's a bot or a game or whatever your wildest imagination can come up with.
there is a new one called Pincer, but it is in alpha and not 100% stable
But it is very promising and I would look out for it
how would I fix it I cant see anythign wrong
The amount of spaces starting the statements is inconsistent
don’t look at discord’s docs, look at the docs for the library you are using
You need to keep a consistent amount of spaces to add for each level of indentation
You can't have code like this
if False:
print("Uh")
else:
print("False!")
It needs to be consistent:
if False:
print("Oh!")
else:
print("False!")
import discord
from discord.ext import commands
bot = commands.Bot(command_prefix=".",description='Test for the QOTD pinger in LFS')
@bot.command
async def on_ready():
print(f"I am ready")
@bot.command
async def on_message(message):
if message.content.startwith('?QOTD'):
await message.channel.send("f<{@550370780245000200}>, Do your QOTD")
bot.run
bro messed up the backticks
Now your await statement is not indented correctly
Put more spaces before it
why do an on_message event for a command when you can just make the command?
@dusk trout https://vcokltfre.dev/ I would suggest you read this guide
A tutorial on how to use discord.py to create your own Discord bot in Python, written to fix the flaws of many other popular tutorials.
lmao the tutorial even talks about discord.py being discontinued
I mean it still works
ik
Yeah just use PyCord or something
but doesn’t have any new things like slash commands, interactions or buttons without needing extra shit
Py-Cord is uh...
^
What are you working on, PyCharm?
visual studio
Id use nextcord or disnake
^
visual studio and visual studio code are different
Which one do you recommend to this fella
which one?
Nextcord rn
visaul studio code my bad
But as I said, watch out for pincer
!PyPi nextcord
A Python wrapper for the Discord API forked from discord.py
!pypi pincer
a new api wrapper for discord
how do i make a command that edits the channel topic
it looks rlly nice even though it’s in alpha
with the next word i put to it
it has things like middleware, and slash commands
it’s more advanced than the others ones I have seen
It has web sockets.
Haven’t seen that with other ones
I installed pincer still wont detect discord module
No, install nextcord
@dusk trout do
pip install nextcord
And in your code, change discord to nextcord
wont detect nextcord
would i have to change my @slate swancommand()
from nextcord.ext import commands
bot = commands.Bot(command_prefix=".",description='Test for the QOTD pinger in LFS')
@bot.command
async def on_ready():
print(f"I am ready")
@bot.command
async def on_message(message):
if message.content.startwith('?QOTD'):
await message.channel.send("f<{@550370780245000200}>, Do your QOTD")
bot.run
Are you using nextcord too?
If i was to swap to it
Yes, that looks good
Of course
Ok
nextcord module wont get detected
why are you doign this to me visual code
do you have the right interpreter selected
I would restart VSCode after installing a module too
this is why you use a venv lol
The docs of nextcord is nextcord.readthedocs.io
Try installing it with
py -3 -m pip install -U nextcord
You're on Windows, right?
Okay so my code is good
I umistalled discord and discord.py
I installed nextcord
and still my module doesnt get detected
in replit it doesnt give any errors but simply doesnt run
replit lmao
how do I check discord.Forbidden errors on disnake?
!d disnake.Forbidden
exception disnake.Forbidden(response, message)```
Exception that’s raised for when status code 403 occurs.
Subclass of [`HTTPException`](https://docs.disnake.dev/en/latest/api.html#disnake.HTTPException "disnake.HTTPException")
what should I use
@dusk trout go to their Discord server
*made a typo
bruh what did I even write
It was understandable :0
visual studio code
not replit
if you installed nextcord, maybe you forgot restarting VSC or you installed it on another python version, not what you use in VSC
ot but vsc should add a button where you can install modules/packages from certain package websites (pypi, npm, crates, etc)
bolb
what's the missingrequired arg one?
it's in commands innit
!d disnake.ext.commands.MissingRequiredArgument
exception disnake.ext.commands.MissingRequiredArgument(param)```
Exception raised when parsing a command and a parameter that is required is not encountered.
This inherits from [`UserInputError`](https://docs.disnake.dev/en/latest/ext/commands/api.html#disnake.ext.commands.UserInputError "disnake.ext.commands.UserInputError")
that?
wdym?
!d disnake.ext.commands.BadArgument
exception disnake.ext.commands.BadArgument(message=None, *args)```
Exception raised when a parsing or conversion failure is encountered on an argument to pass into a command.
This inherits from [`UserInputError`](https://docs.disnake.dev/en/latest/ext/commands/api.html#disnake.ext.commands.UserInputError "disnake.ext.commands.UserInputError")
Yeah, I was tricked by autocomplete when I thought I put my function
error.param returns the typehint of the param too?
happy three kings day guys and girls
!d inspect.Parameter
class inspect.Parameter(name, kind, *, default=Parameter.empty, annotation=Parameter.empty)```
Parameter objects are *immutable*. Instead of modifying a Parameter object, you can use [`Parameter.replace()`](https://docs.python.org/3/library/inspect.html#inspect.Parameter.replace "inspect.Parameter.replace") to create a modified copy.
Changed in version 3.5: Parameter objects are picklable and hashable.
yes
Gg
from nextcord.ext import commands
bot = commands.Bot(command_prefix=".", description='Test for the QOTD pinger in LFS')
@bot.command
async def on_ready():
print(f"I am ready")
@bot.command
async def on_message(message):
if message.content.startwith('?QOTD'):
await message.channel.send("f<{@550370780245000200}>, Do your QOTD")
bot.run
everything is fine modules work
functions don't exist
just wont do anything
bot.command
on_ready
Does it print?
Cause bad code
Oh yeah
event lol
no
would be funny if it would
on_ready should be after @bot.event, not @bot.command()
use commands and not on msgs
ons should follow @bot.event
yah
do you have many on msgs?
on_message is also an event
What's your current code
how can i change nick on the bot it self?
like the name?
in a specified server
or the nickname ^
username i guess
dev portal

jinx
oh ok then nickname for server

bot = commands.Bot(command_prefix=".", description='Test for the QOTD pinger in LFS')
@bot.event
async def on_ready():
print(f"I am ready")
@bot.event
async def on_message(message):
if message.content.startwith('?QOTD'):
await message.channel.send("f<{@550370780245000200}>, Do your QOTD")
bot.run(
guild_object.me.edit(nick=... )
AttributeError: 'str' object has no attribute 'startwith'
line 414, in _run_event
await coro(*args, **kwargs)
2 errors
startswith
With an s
@cold sonnetthanks
^
when you're using f-strings
It works but it wont ping me
the f is outside of the string
I reomved the f
Try
await message.channel.send(message.author.mention + " hello")
how do i select which user to mention
message.author
you typehint a arg to a member obj
I dont want it to be the author
Move this into an actual command

no you're not
@bot.command()
async def qotd(ctx):
await ctx.send(ctx.author.mention + " hello")
That's a start
my baby ofc
NO
he said not the author smh
i dont want it to be the author tho
add an argument
If i use an enum does that work the same as a global var?
No
i can update its values anywhere in the code?

if I were to put a paranthesis at the end and add my name then define it would it work
@bot.command()
async def qotd(ctx, member: discord.Member):
await ctx.send(f"{member.mention} hello")
🧍♂️

No need for the f-string
im bored
but f-strings are cool
member.mention + " hello"
Enums are immutable
bruh
You use f-strings when you have other data types than strings
hi nova
👋
If it's just strings, concatenating with + is just fine
you have f strings why not used them
@grim oar So i cant change them? Im used to C+ where i use them a lot. just trying to get my head around them in python?
They're format strings, not concatenate strings
It wasn't their intended use
"{} hello".format(member.mention)
bro really🧍♂️
And it's dumb doing this with two string objects
how do i resolve ctx reference
wdym
What do you mean
what does that mean
ctx means context
@bot.command()
async def qotd(ctx: commands.Context, member: discord.Member) -> None:
await ctx.send(f"{member.mention} hello")
makes sense
when I type anything with ctx it says unresolved reference ctx
The decorator @bot.command() passes a Context object as the first argument to the function
What is your code
No
time to rewrite
Just create an object which supports setting values in some way, like instance vars can be reset
wait because error.param returns what you typehinted the param too, you can't remove the typehint?
The entire point of events is that their context is their event type and the arguments their handling function is getting
@grim oarCould you give an example please? 🙂
for what do you even need that
@polar ice enums in Python is just a class (mimicking a namespace) subclassing enuns.Enum or whatever
for the missing arg in MissingRequiredArgument
!e
class Container:
def __init__(self):
self.a = 2
c = Container()
print(c.a)
c.a = 6
print(c.a)
@grim oar :white_check_mark: Your eval job has completed with return code 0.
001 | 2
002 | 6
when i setup slashcommands on my first server i didnt use test_guilds=[] does that mean i cant get same slashcommands in the new server i let bot create so bot can be serverowner?
or is it just taking alot of time for discord to set it up
I have this code i wrote for a / command that just replies with hello but every time i run the command it gives me the error in the screenshot
@slash.slash(name="hello", description="says hello",guild_ids=[890566405773226014])
async def say(ctx,SlashContext):
await ctx.reply(f"hello {ctx.author.name}")
didn't you mean to typehint
Just a guess, but remove the second argument
instead of setting two arguments
how can I make a global checks? like that check(s) is ran before command is executed
So it isnt possible to do something like this?
class server_setting(Enum):
logo = None
pName = None
Password = None
Salt = None
PasswordFails = None
def load_authini():
#connect to SQL and load settings
server_setting[logo] = "logo.png"```
what even is that
ofc not, I told you it's immutable
What is your intention with that code?
that's not discord bots -_-
Also enums can't have same values, so no way it's working
and isnt he missing the static method decorator?
is there smth like global_check?
Just wanted to clarify, thats how i did it in C+ 🤔
An enum is used like server_setting.logo in your case, but all of your enums are None so what's the point?
My plan is to fetch the data from a database with the guild id
how can i use a embed fiel with empty value
value can't be empty
but i want all in one line value and name
from nextcord.ext import commands
from discord.utils import get
import discord
bot = commands.Bot(command_prefix=".", description='Test for the QOTD pinger in LFS')
client = discord.Client
@bot.event
async def on_ready():
print(f"I am ready")
@bot.command()
async def qotd(ctx):
sus = get(ctx.guild.members, name='sus')
await ctx.send(f"\n Sus:\n{sus.mention}" + "Do your QOTD")
bot.run
maybe use an invisible character to outplay the system
AttributeError: 'NoneType' object has no attribute 'mention'
@cold needle use
embed.add_field(name="\u200b", value=f"\u200b", inline=False)```
\u200b with this
this is hurting my eyes
Your members privileged intent is disabled
now that's f-strings and + mixed
i enable that from the dev portal right
do you know how
Use f strings, they are faster and more efficient
!d disnake.ext.commands.check | is there a global version that makes a check for every command without needing to decorate it
@disnake.ext.commands.check(predicate)```
A decorator that adds a check to the [`Command`](https://docs.disnake.dev/en/latest/ext/commands/api.html#disnake.ext.commands.Command "disnake.ext.commands.Command") or its subclasses. These checks could be accessed via [`Command.checks`](https://docs.disnake.dev/en/latest/ext/commands/api.html#disnake.ext.commands.Command.checks "disnake.ext.commands.Command.checks").
These checks should be predicates that take in a single parameter taking a [`Context`](https://docs.disnake.dev/en/latest/ext/commands/api.html#disnake.ext.commands.Context "disnake.ext.commands.Context"). If the check returns a `False`-like value then during invocation a [`CheckFailure`](https://docs.disnake.dev/en/latest/ext/commands/api.html#disnake.ext.commands.CheckFailure "disnake.ext.commands.CheckFailure") exception is raised and sent to the [`on_command_error()`](https://docs.disnake.dev/en/latest/ext/commands/api.html#disnake.disnake.ext.commands.on_command_error "disnake.disnake.ext.commands.on_command_error") event.
If an exception should be thrown in the predicate then it should be a subclass of [`CommandError`](https://docs.disnake.dev/en/latest/ext/commands/api.html#disnake.ext.commands.CommandError "disnake.ext.commands.CommandError"). Any exception not subclassed from it will be propagated while those subclassed will be sent to [`on_command_error()`](https://docs.disnake.dev/en/latest/ext/commands/api.html#disnake.disnake.ext.commands.on_command_error "disnake.disnake.ext.commands.on_command_error").
lovely
don't think so
intents = nextcord.Intent.default()
intents.members = True
bot = commands.Bot(command_prefix="whatever", intents=intents)
how do I check if a message id is still exist in the text channel
can I make check that applies to whole cog then?
I'm not sure though, might be nextcord.Intents.default()
add it to every command
!d discord.ext.commands.Bot.add_check
add_check(func, *, call_once=False)```
Adds a global check to the bot.
This is the non-decorator interface to [`check()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot.check "discord.ext.commands.Bot.check") and [`check_once()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot.check_once "discord.ext.commands.Bot.check_once").
one by one
oo
oh, lucky you, there is one
indeed
There was in discord.py, you do it in cogs
A cog_check
anyone?
I'll use the global check instead
please ping


