#discord-bots
1 messages · Page 518 of 1
hm
What's the error?
TypeError: 'Int64' object is not subscriptable
Nvm, I gotta go. @patent lark do u mind helping them?
what data type does price have?
int
Hi,
Did discord.py find a new collaborator?
can i see the full code?
as far as i'm aware, no.
sure
@commands.command()
async def buy(self,ctx,item_name,amount = 1):
data = loadf('databases/shop1.json')
item_name = item_name.lower()
name_ = None
for item in data["content"]:
name = item['id'].lower()
if name == item_name:
name_ = name
for item_pos, item in enumerate(data['content']):
if item_name == data['content'][item_pos]['id'].lower():
price = item['price']
print(price)
buyer_money = user_balance.find_one({'_id': ctx.author.id})
buyer_cash = buyer_money['balance']['cash']
if price > buyer_cash['balance']['cash']:
await ctx.send('You Don\'t Even Have That Much Money Idiot 😛')
return
else:
user_balance.update_one(buyer_cash, {"$inc": {
'balance.cash': -price}})
user_inventory.insert_one({'_id': ctx.author.id, 'items': {
name_: amount
}})
await ctx.send(f'You have successfully bought {amount} {name_}')```
Solo?
it is too sad :/
is it fixable?
Is there a reason you do ["cash"] when ["balance"] already returns an int?
Just remove that part and compare it to the price
how do i make a developer only command
I was going to say it
ok
Somehow, somewhere you you turned balance into an int rather then a dictionary ¯_(ツ)_/¯
I'm only going off what the error says
Oh, wait
is it fine?
Well, you overwritten your original dictionary with an int
Doesn't seem like you use the dictionary again after accessing the cash the user has so
ye?
Ye, what?
idk im dumb asf
I just showed you the problem
Just use the variable you assigned and compare to price, don't try to access anything on it as its an int now, not a dictionary
How to create a sticky message?
whats a sticky message?
what's more concerning here is how you managed to get your error to mention Int64
Ikr
bot will send any message you give it to the bottom of a channel meaning every time a message is sent in the channel the bot will send the sticky message in the channel the bot will also delete its last sticky message everytime it sends a new one
silly question, how can iterate over a sqlite db query? I know I can use for row but I am unsure of what to do next. Trying to display 3 different columns as embeds
i have the id of a message
i want to get the instance of that message
how do i do that?
^
!d discord.TextChannel.fetch_message
await fetch_message(id, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Retrieves a single [`Message`](https://discordpy.readthedocs.io/en/master/api.html#discord.Message "discord.Message") from the destination.
the perm check
thanks
Plz help with this
What is a "sticky message"?
Read the last line.
you would have to use on_message events
and store channel id , along with the message you want to stay
ugh
show code
muted_roles variable is not defined
installing packages gone wrong
THeres a typo in ur code
muted_role = ctx.guild.get_role(881206952460451920) #muted_role
await member.add_roles(muted_roles) #u did muted_roles here
oh
no problem
whats wrong with it? :p
lol
oh yeah discord.py , discord they are basically same
i test my projects on that repl
Ay repl bro
what
I also use replit
and i keep forgetting that theres a million packages from days ago
Replit is op because it's free 24/7 bot
People ask how my bot is 24/7 and I tell them it's a secret lolll
yes but u need premium to make your codes private, otherwise ur token itself is leaked
yes, the owner stopped working on it
No I used the environment thingy I can hide my token
its like 20 installs and updates when you run a repl for discord bot lol
It doesn't matter if it's a Discord bot or not. Defining a variable is a Python thing, and programming in general. If you don't have enough knowledge in Python, do not jump into Discord bot development too early. Have some time to earn experience first so you won't be confused.
!resources
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
Use YouTube
Oh well but your codes are still public
https://vcokltfre.dev has a good tutorial
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.
So if you have for EG: TOKEN, you can hide your token by writing the value TOKEN which = your actual token in the thing
replit aint a hosting site.
There are multiple free hosting services. I can recommend you some if you want.
Wrong server
this is not dpy
That's in discord.gg/dpy not Python.
Yes please
Ohhh lol yeah
Can u recommend me some
Are those better than replit
Of course.
how do i get the guilds vanity url(if there is one)
And safer as well.
They use https://pterodactyl.io as their game panel.
Pterodactyl is an open-source game server management panel built with PHP 7, React, and Go. Designed with security in mind, Pterodactyl runs all game servers in isolated Docker containers while exposing a beautiful and intuitive UI to end users.
?
ctx.guild.vanity_url ddint work
You should not use Repl.it to host your bot.
While this may seem like a nice and free service, it has a lot more caveats than you might think, such as:
-
The machines are super underpowered.
-
- This means your bot will lag a lot as it gets bigger.
-
You need to run a webserver alongside your bot to prevent it from being shut off.
-
- This isn't a trivial task, and eats more of the machines power.
-
Repl.it uses an ephemeral file system.
-
- This means any file you saved via your bot will be overwritten when you next launch.
-
They use a shared IP for everything running on the service.
This one is important - if someone is running a user bot on their service and gets banned, everyone on that IP will be banned. Including you.
Please avoid using repl.it to host your bot. It's not worth the trouble.
!d discord.Guild.vanity_invite
await vanity_invite()```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Returns the guild’s special vanity invite.
The guild must have `VANITY_URL` in [`features`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild.features "discord.Guild.features").
You must have the [`manage_guild`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.manage_guild "discord.Permissions.manage_guild") permission to use this as well.
We literally can host it on a website, close tabs and it will work
yeah but the bots lags a lot when your bots gets bigger and bigger
My bot is in 20 servers and is doing just fine
I meant by the "number of commands" term
I have 50+ commands
and memory consuption
replit wont provide more than 500mbs
Yeah
I know replit isnt the best I'm just not gonna stop using it for my tiny bots
Ok
This bot is replit so it's pog:D
(private testing server)
Private testing server doesn't change the fact that it will get API banned lol
i.e meaning your bot is banned for a certain amount of time
I'm not even talking about that
Y'all gotta stop shitting on replit ik it sucks but it's really not bad for beginners
Just curious did you code the bot from beginning on your own

It was never meant to be hosting discord bots lol
Nope I used a tutorial
This is totally out of scope for beginners anyhow
I meant you didn't fork any reply and change the token right
beginners should use a real ide to learn how it works instead of learning it later

Music bots are banned?
This keeps happening
?ytdl
No I used codes from the internet and put it together
Yeah, that's why I asked him did he fork a reply or coded by himself
Copy paste ?
Because it was js and I donno js
Not all of it lol
I saw somewhere
Wha
IDE =/= VPS
VS code is not an hosting service
??????
Ic
Lol typo XD
You 2 are saying different things
typo
It is a place where you write your code for your bot (IDE)
yeah, coz there are many tutorials on YT, telling how to make a discord bot by forking a reply and changing the token of the bot
Ohh

Oh well u used discord.ui or any 3rd party lib?
Wat
Lol

Whats the point of using external libraries to handle components for discord.py excluding slash commands
Just use v2.0
Or use a fork. Either work.
Yea
Yeah, but why wait until you've got only one month left to change your whole code when you can do it from now?
plus the forks are bad
I've tried about 3 forks until now and none of them is bad. Just different syntax and you can get used to them easily.
A months time is long enough for me to migrate if discord rolls any breaking changes
They will announce said changes anyhow so
I mean, if you're just starting then you can just start with a fork. Though, it's totally up to you.
Learning something new isn't that bad.
I'm not talking about forks when I said learning something new.
I didn't clear what I meant correctly, that's my bad.
I meant, using the API itself or making your own library from scratch, which I tried to do.
I seriously do not recommend you do that.
I literally have made my own minimal library already
post code
!paste
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.
Because when you mention someone member doesn't become None. Which triggers the raise errors.
you should do if member != None
You can instead do:
member = member or ctx.author
Which if member is None then member will be equal to ctx.author.
No you should do is vs != when comparing objects to None as != compares the value while is checks if the object is the same as the other
Better practice to use is here
not sure why it works in the server that i have it live it
in*
but raises an error in my test server
sure then you could do is not
doesnt comparing the value compare the object type though or am i being slow currently?
still getting the same error
!paste
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.
Paste your code there and send the URL here.
!e
foo = None
if not foo:
print("foo is nothing!")
else:
print("foo is not nothing!")
@dapper cobalt :white_check_mark: Your eval job has completed with return code 0.
foo is nothing!
hm
the indent looks screwed in there but its fine in vs
if not checks if the variable is None, same as if var == None and if var is None. I do prefer if not var, though.
whats "errors"
How do you stop FFmpeg PCM audio streams? I'm trying to make a bot play something and I don't know how to stop it with a different command
i just use the operators makes it easier for me 🤷♂️
errors is never defined
@commands.command(aliases=["whois"])
@commands.has_guild_permissions(send_messages = True)
async def userinfo(self, ctx, member: discord.Member = None):
member = member or ctx.author
# make the embed and other things here.
@covert igloo That's all, no need for if nor else.
thank u
No problem. 
even if has a mention, it is using ctx.author
Then?
Try to change the parameter to user:discord.Member=None instead of member:discord.Member=None.
that changes nothing
Not sure if that will work, but no harm of trying.
Yeah I guessed so.
the previous code i sent u works fine in this server
but when i use the same cmd in my test server, it raises the error
That's confusing. I don't know if you have member intents or not as it works in a server but not in another.
But do you have member intents enabled?
dont think so
!intents make sure they're enabled and try again.
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.
esnipe_message_before = {}
esnipe_message_after = {}
esnipe_message_author = {}
snipe_message_author = {}
snipe_message_content = {}
@client.event
async def on_message_edit(before, after):
snipe_message_author[before.channel.id] = before.content
snipe_message_author[before.channel.id] = before.author
@client.command()
async def editsnipe(ctx):
channel = ctx.channel
try:
editsnipeembed = discord.Embed(description=snipe_message_content[channel.id], timestamp=ctx.message.created_at)
editsnipeembed.set_author(name=snipe_message_author[channel.id])
await ctx.send(embed=editsnipeembed)
except:
await ctx.send(f"There is no edit to snipe")```
just shows there is no edit to snipe
where do i set it then?
i just copied the code that was in my github repo and it works now
even tho its the same code lol
Great!
I am guessing this line should be referencing snipe_message_content instead
snipe_message_author[before.channel.id] = before.content
Also, why not just combine them all into 1 dictionary
yeah ig i should do that
@bot.listen()
async def on_message(message):
if bot.user.mentioned_in(message):
embed= discord.Embed(title= '**Close Combat Esports®**', description= '**\nMy prefix is `+`\n\nType `+help` for more info.**', color=0x00FFFF)
await message.channel.send(embed=embed)
How can I stop it to respond on @ everyone @ here or reply @on ?
Check if the bot.user.mention is in the message's content.
!d discord.User.mention
property mention: str```
Returns a string that allows you to mention the given user.
!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.
Could name be nil in add_field?
No
A space like name = " " will work?
you can use an invis character
What is that?
Nope
\u200b works I think
wait it doesnt
i forgot the name
I think you are trying to have some text without creating a field, right?
You can use the description kwarg in discord.Embed.
!d discord.Embed.description
The description of the embed. This can be set during initialisation.
guys is there anything like message.created_at
!d discord.Message.created_at
property created_at: datetime.datetime```
The message’s creation time in UTC.
thanks
Nope, i am wanting what i asked
Use an invisible character then. But why do you want to add a field if it doesn't have a name?
My embed passes thr word limit for which i had to make multiple fields
I dont want to name the additional fields
You're aware that field values characters limit is 6,000 yeah?
I have a question,
Is there a way to make a bot create a role or atleast just move it down some placements in the rankings
If yes how (please ping me so i get a notification since its 1 am i have school tmrw not normal school as a 5/6 yo to 15/16 yo)
If no have a great day / night wherever you are
ctx.guild.create_role
Ignoring exception in command shop:
Traceback (most recent call last):
File "C:\Users\Orange\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\discord\ext\commands\core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "c:\Users\Orange\Desktop\codes\eco\main.py", line 197, in shop
price = item["price"]
KeyError: 'price'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\Orange\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\discord\ext\commands\bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\Orange\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\discord\ext\commands\core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\Orange\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\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: KeyError: 'price'```what is wrong
mainshop = [{"name":"Watch","price :HypesHaLfcurrency: ":100,"description":"Time"},
{"name":"Laptop","price :HypesHaLfcurrency: ":1000,"description":"Work"},
{"name":"PC","price :HypesHaLfcurrency: ":10000,"description":"Gaming"},
{"name":"Ferrari :HypesHaLfcurrency: ","price":99999,"description":"Sports Car"},
{"name":"House ","price :HypesHaLfcurrency: ": 100000, "description":"mansion"} ]
``` see
@client.command()
async def shop(ctx):
em = discord.Embed(title = "Shop")
for item in mainshop:
name = item["name"]
price = item["price"]
desc = item["description"]
em.add_field(name = name, value = f"${price} | {desc}")
await ctx.send(embed = em)
your key is not "price"
Is fields. In fields have 15 players per field
It basically classifies players and places them 15 per field.
Embed have max 25 fields. A field's name is limited to 256 characters and its value to 1024 characters.
Hi
Anyone knows how to do pagination with emoji
Like ➡️
U know? @slate swan
Lol we same cmd using economy
You can use library for make pages
Is more easy if you dont know how works
Idk all I'm new to py
Hm
How
is possible to join in vocal channel to let bot create another vocal channel, but in another category?
Yes
package
A library to create a discord.py paginator. Supports pagination with Discords Buttons feature and reactions.
so how it can be done? there's some repo?
Click on the title
Can't get
Didn't woks
reactionmenu v2.0.3
Only this
!py buttonmenu
!d discord.Guild.create_voice_channel it takes a category argument
await create_voice_channel(name, *, reason=None, category=None, position=..., bitrate=..., user_limit=..., rtc_region=..., video_quality_mode=..., overwrites=...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
This is similar to [`create_text_channel()`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild.create_text_channel "discord.Guild.create_text_channel") except makes a [`VoiceChannel`](https://discordpy.readthedocs.io/en/master/api.html#discord.VoiceChannel "discord.VoiceChannel") instead.
!d discord.on_voice_state_update
discord.on_voice_state_update(member, before, after)```
Called when a [`Member`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member "discord.Member") changes their [`VoiceState`](https://discordpy.readthedocs.io/en/master/api.html#discord.VoiceState "discord.VoiceState").
The following, but not limited to, examples illustrate when this event is called...
Huh just click on the blue text in the embed
But didn't get link bro
A library to create a discord.py paginator. Supports pagination with Discords Buttons feature and reactions.
Ok
...
If your under 75 guilds you can just use message intents and your fine haha
I am using dislash
code:
options=[Option("user" "select the user", OptionType.USER, required=True),
Option("channel" "select the channel", OptionType.CHANNEL, required=False)])
error:
[WARNING] Failed to overwrite commands in <Guild id=CENSORED_FOR_NOW> due to 400 Bad Request (error code: 50035): Invalid Form Body
In 7.options.0.name: String value did not match validation regex.
In 7.options.1.name: String value did not match validation regex.
why??
@ me in response
Oh ok thx i will try
Thats if your over 75 guilds, at that point yes you need to use slash commands
You must do something like that
async def on_voice_state_update(member, before, after):
if after.channel.id == join to create channel id:
category = define the category
channel = create the channel in category
And if you want move the member in the new channel (if channel is voice)
You can do:
await member.move_to(channel)
anyone?
Do you need , between your two first strings?
no
oh wait
u do
OMG LOL I AM SO DUMB
ty for pointing that out
👍 you know best haha
why on member join is not working
Do you have intents turned on ?
!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.
why r u using the class name is that allowed?
Option("channel", "select the channel you want to add the user to", OptionType.CHANNEL, required=False)
it is not required so i thought text channel will be best
o 2.0
code:
@inter_client.slash_command(guild_ids=test_guilds, description="Adds a user to this channel",
options=[Option("user", "select the user you want to add to this channel", OptionType.USER,
required=True)])
async def add(inter, user, channel: discord.TextChannel):
await discord.TextChannel.set_permissions(channel, user, reason="Bot command", view_channel=True,
send_messages=True)
await inter.channel.send(f"Added {user.name} to this channel")
error:
File "C:\Users\USER\Desktop\FOLDER\FOLDER\FOLDER\FOLDER\dislash\application_commands\core.py", line 72, in __call__
return await self.func(*args, **kwargs)
TypeError: add() missing 1 required positional argument: 'channel'
WHYYYYYYYYYYYYY??????????
@ me in response
await channels.set_permissions()
??
!d discord.TextChannel.set_permissions
await set_permissions(target, *, overwrite=see - below, reason=None, **permissions)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Sets the channel specific permission overwrites for a target in the channel.
The `target` parameter should either be a [`Member`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member "discord.Member") or a [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role") that belongs to guild.
The `overwrite` parameter, if given, must either be `None` or [`PermissionOverwrite`](https://discordpy.readthedocs.io/en/master/api.html#discord.PermissionOverwrite "discord.PermissionOverwrite"). For convenience, you can pass in keyword arguments denoting [`Permissions`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions "discord.Permissions") attributes. If this is done, then you cannot mix the keyword arguments with the `overwrite` parameter.
If the `overwrite` parameter is `None`, then the permission overwrites are deleted.
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...
wdym
ok
wdym
can you explain in simple words what you are trying to explain?
Helloooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
anyone there???
lol
I mean we both coding economy
oh pls show yours
i mean code not that
what commands do you have
Yes error
can anyone give me a clear explanation to this?
idk do you want a mute command take my
@client.command(description="Mute a person lol")
@commands.has_permissions(manage_messages=True, manage_roles=True)
async def mute(ctx,member: discord.Member, *, reason=None):
guild = ctx.guild
mutedRole = discord.utils.get(guild.roles, name="muted")
if not mutedRole:
mutedRole = await guild.create_role(name="muted")
for channel in guild.channels:
await channel.set_permissions(mutedRole, speak=False, send_messages=False, read_message_history=False, read_messages=False)
await member.add_roles(mutedRole, reason=reason)
await ctx.send(f"mute {member.mention} for reason {reason}")
embed=discord.Embed(title=" you have been muted", color = discord.Colour.red())
embed.add_field(name="Why were you muted", value=f"you were from {guild} because of {reason}")
await member.send(embed=embed)
As long as they have manage role perms yeah
no imean i am muted
i am muted
Type
async def mute(ctx,member : discord. member)
Or use
async def mute(ctx,member : discord_member)
@slate swan
yes it is
wdym
Always welcome try working or not I'm using like that
eh
this is a cmd
Yh
but i am muted
Ik
Lol
how will i exicute it?
Not defence it's an auto-correct by my keyboard use def
i just wanna escape a mute with my bot
do on_message event so whenever someone else speaks to mute u this command triggers and unmutes u
can give me a code example
pls
or just add a check to the mute command to see if it mutes the bots owner
It was my keyboard auto correct ssry really sry
bruh someone tell me how to use this thing
!d discord.on_message
discord.on_message(message)```
Called when a [`Message`](https://discordpy.readthedocs.io/en/master/api.html#discord.Message "discord.Message") is created and sent.
This requires [`Intents.messages`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.messages "discord.Intents.messages") to be enabled.
Warning
Your bot’s own messages and private messages are sent through this event. This can lead cases of ‘recursion’ depending on how your bot was programmed. If you want the bot to not reply to itself, consider checking the user IDs. Note that [`Bot`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot "discord.ext.commands.Bot") does not have this problem.
everyone else using looks cool and i look dumb while trying
it's clear enough, isn't it?
i mean i am new i dont understand it
Someone know how to do pagination /reaction menu?
you can wrap over menus with discord-ext menus-views
trust me it's easy
Then just don’t dodge a mute 🤷♂️
anyone??
IDK can u explain me by codes
🤔 #help-bagel i made a function in a discord.py fork to allow you to generate a snowflake/user id by passing datetime or the utc time of the time the function was ran, I think it's accurate, but I am not sure if people enjoy it
someone know the answer?
@light night can u explain using codes
!pagination
hold on
read from their doc page: https://github.com/Rapptz/discord-ext-menus
https://github.com/oliver-ni/discord-ext-menus-views
A simple layer over discord.ext.menus using the new discord.ui components in discord.py v2.0. - GitHub - oliver-ni/discord-ext-menus-views: A simple layer over discord.ext.menus using the new disco...
there
im tryna do a currency heist command, when someone runs %heist it runs a heist and anyone who sends join heist within 30 seconds will be stored in a list full of their ids, i tried this
@client.command()
async def heist(ctx):
await ctx.send('A heist has started, type join heist within 30 seconds')
users = []
def check():
return msg.content.lower() == 'join heist'
while True:
try:
msg = await client.wait_for_message(timeout= 30,check=check)
users.append(str(msg.author.id))
except:
break
but then it just restarts the 30 second timer when someone says join heist, anyone know how to get by this?
OK. Thnx
well
will my code code work to prevent mute?
async def on_message(message):
user.id == 760010546728402975
if message.content == "!mute @Riad#1922":
await user.remove_roles("Muted")```
uh you can make a task that sleeps for 30 seconds and keep checking if its done or not
That's full of problems.
!d asyncio.create_task
asyncio.create_task(coro, *, name=None)```
Wrap the *coro* [coroutine](https://docs.python.org/3.10/library/asyncio-task.html#coroutine) into a [`Task`](https://docs.python.org/3.10/library/asyncio-task.html#asyncio.Task "asyncio.Task") and schedule its execution. Return the Task object.
If *name* is not `None`, it is set as the name of the task using [`Task.set_name()`](https://docs.python.org/3.10/library/asyncio-task.html#asyncio.Task.set_name "asyncio.Task.set_name").
The task is executed in the loop returned by [`get_running_loop()`](https://docs.python.org/3.10/library/asyncio-eventloop.html#asyncio.get_running_loop "asyncio.get_running_loop"), [`RuntimeError`](https://docs.python.org/3.10/library/exceptions.html#RuntimeError "RuntimeError") is raised if there is no running loop in current thread.
This function has been **added in Python 3.7**. Prior to Python 3.7, the low-level [`asyncio.ensure_future()`](https://docs.python.org/3.10/library/asyncio-future.html#asyncio.ensure_future "asyncio.ensure_future") function can be used instead...
First of all, user is not defined; therefore you cannot define user.id.
oh
Second of all, discord.Member.remove_roles() takes a role ID and not a role name.
!d discord.Member.remove_roles
await remove_roles(*roles, reason=None, atomic=True)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Removes [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role")s from this member.
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 removed [`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.
ok
Oh, right. My bad.
8:32 AM brain is to blame. Haha.
thn how can i prevent a mute?
!reaction menu
pls teach me someone
@bot.event
async def on_message(message):
if message.content == "!mute @dim cedar":
await user.remove_roles("Muted")
i have mostly fixed it lol
Well, does the command take only usernames or a discord.Member object in general?
discord.ext.commands
Use from discord.ext import commands
nope
user is still not defined
What
ik but i tried
Wait
!resources if you don't have much knowledge about Python, please do not jump into discord.py too soon. Learn some basics first so you would know what you're doing.
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
you asked where to put an import
if you really did, you would’ve known
@slate swan
that’s not an excuse
I don't think staying up till 1 AM could make you forget how to import if you actually did know about Python?
why is my ide suddenly blue after this async thing
stop copying code
Are you using discord.Client?
why.. you ask
oh ya forgot the in
code:
@inter_client.slash_command(guild_ids=test_guilds, description="Adds a user to this channel",
options=[Option("user", "select the user you want to add to this channel", OptionType.USER,
required=True)])
async def add(inter, user, channel: discord.TextChannel):
await discord.TextChannel.set_permissions(channel, user, reason="Bot command", view_channel=True,
send_messages=True)
await inter.channel.send(f"Added {user.name} to this channel")
error:
File "C:\Users\USER\Desktop\FOLDER\FOLDER\FOLDER\FOLDER\dislash\application_commands\core.py", line 72, in __call__
return await self.func(*args, **kwargs)
TypeError: add() missing 1 required positional argument: 'channel'
why?
@ me in response
yeah you clearly dont know python
ctx.channel.history not ctx.history.
!d discord.TextChannel.history
async for ... in history(*, limit=100, before=None, after=None, around=None, oldest_first=None)```
Returns an [`AsyncIterator`](https://discordpy.readthedocs.io/en/master/api.html#discord.AsyncIterator "discord.AsyncIterator") 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...
!resources
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
using dislash
Use from discord.ext import commands (use command(s) commands
@slate swan
Show ur code
I can fix
If u like
member:discord.Member
#bot-commands
that autocorrect?
why
Are you coding on mobile?
Idont have pc
buy one
Yes
Easy to say, hard to do. Haha.
After 1 year idk my parents will buy one for me when the time arrives
well python doesn’t require you to have 32gb of ram
Not sure why, but I consider coding on mobile a crime. But yeah it's completely fine.
you could find a cheap pc
yes right
A $200 laptop could do the job.
less even
Why
You don't need more than 4GB of RAM to code.
!ot
Off-topic channels
There are three off-topic channels:
• #ot0-psvm’s-eternal-disapproval
• #ot1-perplexing-regexing
• #ot2-never-nester’s-nightmare
Their names change randomly every 24 hours, but you can always find them under the OFF-TOPIC/GENERAL category in the channel list.
Please read our off-topic etiquette before participating in conversations.
Here rate different Im from India and a better lap costs 25000
What's the issue again?
yes 25k in your currency
Ye
!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.
lmao
well why it doesnt work?
Add a prefic
Well, could you please take a look at the docs, and see if discord.Client has a command method?
Capital m for Member in discord. Member
I don't think it does.
!code reactionmenu
That's not even what's causing the error.
what are you trying to do
Reaction menu /paginator
!d discord.member
No documentation found for the requested symbol.
you were saying?
!d discord.Member
class discord.Member```
Represents a Discord member to a [`Guild`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild "discord.Guild").
This implements a lot of the functionality of [`User`](https://discordpy.readthedocs.io/en/master/api.html#discord.User "discord.User").
x == y Checks if two members are equal. Note that this works with [`User`](https://discordpy.readthedocs.io/en/master/api.html#discord.User "discord.User") instances too.
x != y Checks if two members are not equal. Note that this works with [`User`](https://discordpy.readthedocs.io/en/master/api.html#discord.User "discord.User") instances too.
hash(x) Returns the member’s hash.
str(x) Returns the member’s name with the discriminator.
discord.member is a module
And read his error.
isn't python case sensitive
since when
He's using discord.Client instead of commands.Bot().
Copying code is okay till you’re actually learning hoe it’s working
or right
How*
i read that as case insensitive
from discord.ext import commands
Do you have a prefix
!d discord.ext.commands.Bot
class discord.ext.commands.Bot(command_prefix, help_command=<default-help-command>, description=None, **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.
my god
Bru
I'm having a stroke reading all those wrong answers, lmfao.
I just said it, twice.
You are using discord.Client and not commands.Bot.
Don't use discord.Client.
It's bad.
Unless you want to work with only events.
Sorry, just trying to help
nope
Do you want an example?
bruh
its fine
!d discord.on_message_delete
discord.ext.commands is an extension so dw about rewriting your code
import discord
from discord.ext import commands
intents = discord.Intents.default()
# intents.members = True (remove the comment if you've enabled it on the dev portal)
bot = commands.Bot(command_prefix="your_prefix", intents=intents)
@bot.event
async def on_ready():
print(f"{bot.user} is online.")
@bot.command()
async def ping(ctx):
await ctx.send("Pong!")
bot.run("YOUR BOT TOKEN")
Just spent 15 seconds typing.
Never seen an example on the docs, lmao.
there is
@slate swan
Yeah, but I never check for examples.
from discord.ext import commands
bot = commands.Bot(command_prefix='$')
@bot.command()
async def test(ctx):
pass
# or:
@commands.command()
async def test(ctx):
pass
bot.add_command(test)
you could do this to save some lines 👍
bot = commands.Bot(command_prefix="your_prefix", intents=discord.Intents.default())
any mistake i have done? it is giving me command not found error. tis is the cog
Read the comment.
Imagine not using the first one.
the cog is in a folder called commands
you aren’t decorating correctly
which line?
the command
the first two lines of the command
doesn't*
yes sorry
async def on_message(message):
if message.content == "!mute @Riad#1922":
guild = ctx.guild
mutedrole = discord.utils.get(guild.roles, name = "Muted")
await user.remove_roles(mutedrole)
await ctx.send("Did you just escaped a Mute @Riad#1922")```
what is wrong with my code now?
ctx not defined
user is not defined same goes for ctx
how to define thm?
use the message param
!d discord.on_message_edit
Why are you using events? This isn't discord.gg/djs .
What does that have to do with his code?
He's using message events to make commands instead of a bot.command decorator.
I know that but does djs do that too?
Nope.
Discord.js is only message events.
client.on("message", (message) => {
if (message.content === "!ping") {
message.channel.send("Pong!")
}
})
I'll be right back. Gotta feed my cat.
@client.command()
async def event(ctx):
embed = discord.Embed(title='Event Started',description=f'React to join the event within 30 seconds!',color=discord.Color.random())
msg = await ctx.send(embed=embed)
await msg.add_reaction('🎉')
users = []
await asyncio.sleep(30)
msg = await ctx.channel.fetch_message(msg.id)
reaction = [i for i in msg.reactions]
for i in reaction.users:
users.append(i.id)
print(users)
I am trying to make a event command but doing this doesnt print the user ids so i cant do what i want with them
is there like after.action on the member update event so i can tell what changed on there profile or like what changed
What does it print?
nothing
Not even []?
thats a problem
Try to print i.
Ok I wanted a message with embeds, buttons and select menu but a error was occurring Positional argument cannot appear after keyword arguments for FS to solve this I did FS=FS but now it gives me send() got an unexpected keyword argument 'FS' how do I solve this ? here is the code: py @client.group(invoke_without_command=True) async def feedback(ctx, *, text = None,): try: text = text.split("|") report=discord.Embed(color=0xfff868) report.add_field(name='Pending Confirmation', value=f"{text[1]} #Tittle \r {text[2]} #Description") FB=[[Button(style=ButtonStyle.red, label="Discard", custom_id="n"), Button(style=ButtonStyle.green, label="Send", custom_id="y")]] FS=Select(placeholder = 'Where to post',options = [SelectOption(label="Bugs", value="value1"),SelectOption(label="Commands", value="value2"),SelectOption(label="Suggestions", value="value3"),SelectOption(label = "Other", value = "value4")]) await ctx.channel.send(embed=report,components=FB, FS=FS) except: await ctx.reply("Please enter `/feedback format` to check how to format.")
nothing and i found asolution on stack overflow
whats fs meant to be? never seen it on send before
FS is select menu
im working on trying to fix your code
!d discord.TextChannel.send
await send(content=None, *, tts=None, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, mention_author=None, view=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Sends a message to the destination with the content given.
The content must be a type that can convert to a string through `str(content)`. If the content is set to `None` (the default), then the `embed` parameter must be provided.
To upload a single file, the `file` parameter should be used with a single [`File`](https://discordpy.readthedocs.io/en/master/api.html#discord.File "discord.File") object. To upload multiple files, the `files` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.9)") of [`File`](https://discordpy.readthedocs.io/en/master/api.html#discord.File "discord.File") objects. **Specifying both parameters will lead to an exception**.
To upload a single embed, the `embed` parameter should be used with a single [`Embed`](https://discordpy.readthedocs.io/en/master/api.html#discord.Embed "discord.Embed") object. To upload multiple embeds, the `embeds` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.9)") of [`Embed`](https://discordpy.readthedocs.io/en/master/api.html#discord.Embed "discord.Embed") objects. **Specifying both parameters will lead to an exception**.
ok
havent used them yet but i think u have to create a View and add the Select and Buttons to it
then use await message.channel.send(embed = report, view = view)
Thank you
on_reaction is an event?
First by learning how to type, 2nd, you have payload.member_id or some shit like that, read the docs smh
Nope
payload is only in on_raw_reaction ?
Never used the one that's not raw but shouldn't be that different
First read the docs, they're very useful and give you the answer you need
ok
show code?
Self :monkas:
The whole cog?
import discord
from datetime import datetime
from discord.ext import commands
class Help(commands.Cog):
def __init__(self, bot):
self.bot = bot
class MyNewHelp(commands.MinimalHelpCommand):
async def send_pages(self):
destination = self.get_destination()
for page in self.paginator.pages:
embed = discord.Embed(description=page)
embed.timestamp=datetime.utcnow()
embed.set_author(name=self.context.author, icon_url=self.context.author.display_avatar)
embed.set_footer(text='Minimal Help Command', icon_url=self.context.author.display_avatar)
await destination.send(embed=embed)
async def send_command_help(self, command):
embed = discord.Embed(title=self.get_command_signature(command))
command_has_alias = command.aliases
command_has_help = command.help
if command_has_help:
embed.add_field(name="Help", value=command.help)
if command_has_alias:
embed.add_field(name="Aliases", value=", ".join(command.aliases), inline=False)
channel = self.get_destination()
await channel.send(embed=embed)
async def send_error_message(self, error):
embed = discord.Embed(title="Error", description=error)
channel = self.get_destination()
await channel.send(embed=embed)
self.bot.help_command = MyNewHelp()
def setup(bot):
bot.add_cog(Help(bot))
uhh, just where you put the bot.help_command =
oh
wot
nested class
hmmm
import discord
from datetime import datetime
from discord.ext import commands
class MyNewHelp(commands.MinimalHelpCommand):
async def send_pages(self):
destination = self.get_destination()
for page in self.paginator.pages:
embed = discord.Embed(description=page)
embed.timestamp=datetime.utcnow()
embed.set_author(name=self.context.author, icon_url=self.context.author.display_avatar)
embed.set_footer(text='Minimal Help Command', icon_url=self.context.author.display_avatar)
await destination.send(embed=embed)
async def send_command_help(self, command):
embed = discord.Embed(title=self.get_command_signature(command))
command_has_alias = command.aliases
command_has_help = command.help
if command_has_help:
embed.add_field(name="Help", value=command.help)
if command_has_alias:
embed.add_field(name="Aliases", value=", ".join(command.aliases), inline=False)
channel = self.get_destination()
await channel.send(embed=embed)
async def send_error_message(self, error):
embed = discord.Embed(title="Error", description=error)
channel = self.get_destination()
await channel.send(embed=embed)
class Help(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.bot.help_command = MyNewHelp()
def setup(bot):
bot.add_cog(Help(bot))
```do this
*indent still messy
o ok
how to get the user who reacted in msg?
i want to check if the user who reacted is in the list?
list = [me , u , everyone]
in this list :/
async def on_reaction_add(reaction,user):
if user.id in list?
if any(user in list for user in await message.reactions[0].users.flatten())
Traceback (most recent call last):
File "C:\Users\kusha\PycharmProjects\pythonProject\project 1 month.py", line 61, in <module>
inpiration()
File "C:\Users\kusha\PycharmProjects\pythonProject\project 1 month.py", line 53, in inpiration
@client.event(youtubepy)
File "C:\Users\kusha\PycharmProjects\pythonProject\venv\lib\site-packages\discord\client.py", line 1015, in event
raise TypeError('event registered must be a coroutine function')
TypeError: event registered must be a coroutine function
so what should i do o correct my code
for on_reaction_add, sure
and how i can get guild id ?
make your function a coroutine
async def...
in?
oh
thx
on_reaction_add
nope
still showing error
@client.event(youtubepy)
async def on_lisening(youtube):
if youtube.message.content == audio_source():
await youtube.channel.send(audio_source())
ohh ok
if you're ever stuck finding attrs, look on the docs and just scroll through them, you'll usually find what you need
Reaction menu
yelp need an embed but its saying unident error pylance
! @commands.command()
@commands.has_permissions(manage_roles=True)
async def addrole(self, ctx, *, name):
guild = ctx.guild
await guild.create_role(name=name)
embed= discord.Embed(description=f"**Role {name} has been created without any Permissions !! **")
await ctx.send(embed=embed)
!code @commands.command()
@commands.has_permissions(manage_roles=True)
async def addrole(self, ctx, *, name):
guild = ctx.guild
await guild.create_role(name=name)
embed= discord.Embed(description=f"**Role {name} has been created without any Permissions !! **")
await ctx.send(embed=embed)
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.
!dumb
Dunder methods
Double-underscore methods, or "dunder" methods, are special methods defined in a class that are invoked implicitly. Like the name suggests, they are prefixed and suffixed with dunders. You've probably already seen some, such as the __init__ dunder method, also known as the "constructor" of a class, which is implicitly invoked when you instantiate an instance of a class.
When you create a new class, there will be default dunder methods inherited from the object class. However, we can override them by redefining these methods within the new class. For example, the default __init__ method from object doesn't take any arguments, so we almost always override that to fit our needs.
Other common dunder methods to override are __str__ and __repr__. __repr__ is the developer-friendly string representation of an object - usually the syntax to recreate it - and is implicitly called on arguments passed into the repr function. __str__ is the user-friendly string representation of an object, and is called by the str function. Note here that, if not overriden, the default __str__ invokes __repr__ as a fallback.
class Foo:
def __init__(self, value): # constructor
self.value = value
def __str__(self):
return f"This is a Foo object, with a value of {self.value}!" # string representation
def __repr__(self):
return f"Foo({self.value!r})" # way to recreate this object
bar = Foo(5)
# print also implicitly calls __str__
print(bar) # Output: This is a Foo object, with a value of 5!
# dev-friendly representation
print(repr(bar)) # Output: Foo(5)
Another example: did you know that when you use the <left operand> + <right operand> syntax, you're implicitly calling <left operand>.__add__(<right operand>)? The same applies to other operators, and you can look at the operator built-in module documentation for more information!
!test @commands.command()
@commands.has_permissions(manage_roles=True)
async def addrole(self, ctx, *, name):
guild = ctx.guild
await guild.create_role(name=name)
embed= discord.Embed(description=f"**Role {name} has been created without any Permissions !! **")
await ctx.send(embed=embed)
!work @commands.command()
@commands.has_permissions(manage_roles=True)
async def addrole(self, ctx, *, name):
guild = ctx.guild
await guild.create_role(name=name)
embed= discord.Embed(description=f"**Role {name} has been created without any Permissions !! **")
await ctx.send(embed=embed)
heyo how to test
?
!eval @commands.command()
@commands.has_permissions(manage_roles=True)
async def addrole(self, ctx, *, name):
guild = ctx.guild
await guild.create_role(name=name)
embed= discord.Embed(description=f"**Role {name} has been created without any Permissions !! **")
await ctx.send(embed=embed)
@slate swan :x: Your eval job has completed with return code 1.
001 | File "<string>", line 2
002 | @commands.has_permissions(manage_roles=True)
003 | IndentationError: unexpected indent
anyone
ohk but whai in capital
Idk
it means ur using spaces & indents in the file
then
a way to fix it is to not do that and just use tabs or spaces and not both
kk
@boreal ravine u know to make pagination
Or like that
pagination for what
Shop cmd in economy
I need bunttons or emoji anything
Can u join my code in Replit and show?
h
no
What is that?
you used message as the param use it to replace context?
message.guild?
learn python?
yes
XD
You mixed up tabs and spaces together.
That's not a thing, and the error has nothing to do with methods nor attributes.
ohk got it thnx but still not getting
let it be
XD
guys what kind of error is this i mean why is it occuring discord.ext.commands.errors.CommandInvokeError: Command raised an exception: ServerSelectionTimeoutError: cluster1-shard-00-00.teqte.mongodb.net:27017: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: certificate has expired (_ssl.c:1129),cluster1-shard-00-01.teqte.mongodb.net:27017: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: certificate has expired (_ssl.c:1129),cluster1-shard-00-02.teqte.mongodb.net:27017: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: certificate has expired (_ssl.c:1129)
You didn't pass a correct username/password.
👀
code?
python
bruh i asked for the code
ooo
show me import part
Give me a few minutes. I will make a public GitHub repository for that.
commands.Cog
MAIN.PY
import discord
import random
import os
from discord.ext import commands
client = commands.Bot(command_prefix = '.')
@client.command()
async def load(ctx, extension):
client.load_extension(f'cogs.{extension}')
@client.command()
async def unload(ctx, extension):
client.unload_extension(f'cogs.{extension}')
for filename in os.listdir('./cogs'):
if filename.endswith('.py'):
client.load_extension(f'cogs.{filename[: -3]}')
client.run('token')
in cogs folder ( example .py )
class Example(commands.Cogs):
def init(self, client):
self.client = client
@commands.Cog.listener()
async def on_ready(self):
print('Bot is online.')
@command.command()
async def ping(self, ctx):
await ctx.send('Pong!')
def setup(client):
client.add_cog(Example(client))
Its Cog not Cogs
send code @solar pike
MAIN.PY
import discord
import os
from discord.ext import commands
client = commands.Bot(command_prefix = '.')
@client.command()
async def load(ctx, extension):
client.load_extension(f'cogs.{extension}')
@client.command()
async def unload(ctx, extension):
client.unload_extension(f'cogs.{extension}')
for filename in os.listdir('./cogs'):
if filename.endswith('.py'):
client.load_extension(f'cogs.{filename[: -3]}')
client.run('Token here')
import discord
from discord.ext import commands
class Example(commands.Cog):
def init(self, client):
self.client = client
@commands.Cog.listener()
async def on_ready(self):
print('Bot is online.')
@command.command()
async def ping(self, ctx):
await ctx.send('Pong!')
def setup(client):
client.add_cog(Example(client))
@slate swan https://github.com/ScopesCodez/discordpy-pagination 😄
@scenic wren
!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.
See the difference?
And how can i define user
whats user in this case?
Im making a bot with the new structural pattern matching, can someone answer my question here?
#help-cherries message
import discord
from discord.ext import commands
class Example(commands.Cog):
def init(self, client):
self.client = client
@commands.Cog.listener()
async def on_ready(self):
print('Bot is online.')
@commands.command()
async def ping(self, ctx):
await ctx.send(f'Pong! {round(client.latency * 1000)}ms')
def setup(client):
client.add_cog(Example(client))
You defined client as self.client so use that
k
k
User is me
I want to remove the muted role from myself
message.author I guess?
yes
And how can i do that?
!d discord.Guild.fetch_member
await fetch_member(member_id, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Retrieves a [`Member`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member "discord.Member") from a guild ID, and a member ID.
Note
This method is an API call. If you have [`Intents.members`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.members "discord.Intents.members") and member cache enabled, consider [`get_member()`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild.get_member "discord.Guild.get_member") instead.
user = message.guild.fetch_member(1234567891234)
``` I guess
Ok i'll try
how could i make a global wait time for welcome dms
so i dont have the event been triggered across multiple servers and dms sent to fast and bot risked being flagged
import discord
from discord.ext import commands
class Example(commands.Cog):
def init(self, client):
self.client = client
@commands.command()
async def _8ball(self, ctx, *, question):
responses = ['it is certain.',
'it is decidedly so.',
'whithout a doubt.',
'yes - defenitely',
'you may rely on it.',
'as i see it, yes.',
'most likely.',
'outlook good.',
'yes.',
'Signs point to yes.',
'reply hazy, try again',
'ask again later',
'better not tell you now',
'cannot predict now.',
'concentrate and ask again.',
"don't count on it.",
'My reply is no.',
'my sources say no',
'outlook not so good',
'very doubtfull.', ]
await ctx.send(f'Question: {question}\nAnswer: {random.choice(responses)}')
!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.
?
first sate what are you trying to do
im searching for somebody to help me with webhooks and bots for my dc server
dm if u are able to help
(its a fortnite server) just to mention since people hate on fortnite
!indent
Indentation
Indentation is leading whitespace (spaces and tabs) at the beginning of a line of code. In the case of Python, they are used to determine the grouping of statements.
Spaces should be preferred over tabs. To be clear, this is in reference to the character itself, not the keys on a keyboard. Your editor/IDE should be configured to insert spaces when the TAB key is pressed. The amount of spaces should be a multiple of 4, except optionally in the case of continuation lines.
Example
def foo():
bar = 'baz' # indented one level
if bar == 'baz':
print('ham') # indented two levels
return bar # indented one level
The first line is not indented. The next two lines are indented to be inside of the function definition. They will only run when the function is called. The fourth line is indented to be inside the if statement, and will only run if the if statement evaluates to True. The fifth and last line is like the 2nd and 3rd and will always run when the function is called. It effectively closes the if statement above as no more lines can be inside the if statement below that line.
Indentation is used after:
1. Compound statements (eg. if, while, for, try, with, def, class, and their counterparts)
2. Continuation lines
More Info
1. Indentation style guide
2. Tabs or Spaces?
3. Official docs on indentation
Indents
@bot.command()
async def pog(ctx):
role = discord.utils.get(ctx.guild.roles,id = 882504055866396682)
await ctx.send(f'{role.mention}')```
i use this it mention role but not ping why?
wdym by it mentions it but doesnt ping?
isnt that the same thing
@bot.event
async def on_message(message):
if message.content == "!mute @Riad#1922":
user = message.guild.fetch_member(760010546728402975)
guild = message.guild
mutedrole = discord.utils.get(guild.roles, name = "Muted")
await user.remove_roles(mutedrole)
await message.send("Did you just escaped a Mute @Riad#1922")```
can anyone explain me?
why this code is not preventing me from getting muted
Hm
?
attempt to make a bot and am stuck on a few things, the main one is converting an sqlite query to a vertical list instead of its current output of [[1, 2, 3]].
I have put in py def results(): with conn: cur = conn.cursor() cur.execute("SELECT seriesName from sonarr") rows = cur.fetchall() result = rows(cur) return(result)
and converted it to a list, however i keep getting the error TypeError: 'list' object is not callable and I am very confused
Error?
import discord
from discord.ext import commands
class Example(commands.Cog):
def init(self, client):
self.client = client
@commands.command(aliases=['8ball', 'test'])
async def _8ball(self, ctx, *, question):
responses = ['it is certain.',
'it is decidedly so.',
'whithout a doubt.',
'yes - defenitely',
'you may rely on it.',
'as i see it, yes.',
'most likely.',
'outlook good.',
'yes.',
'Signs point to yes.',
'reply hazy, try again',
'ask again later',
'better not tell you now',
'cannot predict now.',
'concentrate and ask again.',
"don't count on it.",
'My reply is no.',
'my sources say no',
'outlook not so good',
'very doubtfull.',
'Ask my creator SHOTO :))']
await ctx.send(f'Question: {question}\nAnswer: {random.choice(responses)}')
that client
why
use bot, self.bot etc
don't use client/self.client
none
also your list isn't indented correctly
@Riad#1922 will never match
ur indents
amm no errors there
it only @dim cedar but when i turn it into a code block the tag appears as well
the actual message will be !mute @dim cedar or !mute @dim cedar (can be either and it's not exactly consistent) and thus will never match with your current code
Guys, can I stop this link from embedding?
await ctx.send("https://www.google.com")
put it in <>
i tried, but can you give me an example
oh oh okay, thanx
if you want to use commands: #bot-commands
hm
It's discord.abc.Messageable.send
not working
how can i make it work?
hm cool discord://-/settings
Yeah but kind of useless to be fair xD
e
Just saying 'not working' doesn't give any information
what you said is "i have issue what is solution?"
i don't know the issue
so i don't know the solution
!d discord.abc.Messageable.send
but the muted role is not getting removed
from me
And please don't make commands in events..
you are aware on_message triggers WAY before any command? so it will try to remove it, then invoke the muted command and then apply the muted role?

You can do the same a lot easier using commands
also you could just add an if statement to your mute command that checks if you are getting muted instead of having an on_message
maybe because of hierachy
so is there any way to to escape a mute?
@dim cedar
can u show me how to create the check?
not a check
literally just an if statement
it's first ctx then error in your arguments
with your if isinstance you're comparing error to the MissingPermissions, but error is context, and ctx is error
i'm not spoonfeeding, if you are doing discord.py you should know how to make an if statement
also use ctx.reply
not ctx.message.reply
!d discord.ext.commands.Context.reply
await reply(content=None, **kwargs)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
A shortcut method to [`abc.Messageable.send()`](https://discordpy.readthedocs.io/en/master/api.html#discord.abc.Messageable.send "discord.abc.Messageable.send") to reply to the [`Message`](https://discordpy.readthedocs.io/en/master/api.html#discord.Message "discord.Message").
New in version 1.6.
i know but idk how make the checks if i am getting muted
!d discord.ext.commands.Context read these attributes. Ctx has a LOT of attributes. It's a very powerful thing
class discord.ext.commands.Context(*, message, bot, view, args=..., kwargs=..., prefix=None, command=None, invoked_with=None, invoked_parents=..., invoked_subcommand=None, ...)```
Represents the context in which a command is being invoked under.
This class contains a lot of meta data to help you understand more about the invocation context. This class is not created manually and is instead passed around to commands as the first parameter.
This class implements the [`Messageable`](https://discordpy.readthedocs.io/en/master/api.html#discord.abc.Messageable "discord.abc.Messageable") ABC.
get your muted command. Start with an if statement if it's you, if yes, don't mute, if it's not you, proceed with the mute
well if i am getting muted by an other bot which is not made by me
then on_message won't help because that is more likely to fire WAY before any other bot will fire the muted command
so it will first try removing the muted role, then after a delay the other bot starts working and you get the muted role
so in this case you want to have a on_member_update where it checks for role changes, and if it's you and the role is muted role, then remove it
Anyone know how to add buttons when clicked shows another embed?
!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...
!pypi dislash.py for buttons. It's a great package.
dpy master branch has it too
Which one should use?
It's slash cmd right?
why its say invalid syntax on async def 8ball(ctx, *, question)
Pass a name kwarg to the decorator and change the function's name to _8ball instead.
and how can i
insert hyperlink
@bot.command(name="8ball")
async def _8ball(ctx, *, question):
...
a function cannot start with a digit for the name
[text](url) just like markdown.
not "just like markdown" because discord uses markdown lol
so it is markdown
Well, Discord doesn't use markdown exactly.
So, if I do:
| title1 | title2 |
|---|---|
| header1 | header2 |
| text1 | text2 |
it won't become a table.
there are a few limits yeah but they tried to follow the standards and even call it markdown in their guides
It's Discord's markdown, but it's not markdown itself.
Would be very cool if Discord used markdown itself, though! Imagine how easier it would be to make your text look more organized.
discord.py + typing:
i have some command:
@commands.command()
async def ...(self, ctx, args: typing.Literal["test"]):
...
How do i make args work with Test?
discord.py only converts Union and Optional
oh didnt know
hi is logging all used commands allowed? just wanted to check before i did something
i mean you're allowed to log whatever you want with your bot
but isnt logging message in a gray area-ish
alr
Thnx buddy it works very very Thnx I'm now glad that u helped me it's not a small help it a big big big help Thnx brother/sister very much I was getting headache with that Thnx very much
or maybe it was added to nextcord
no i just checked, its new in 2.0
i didnt find in discord.py docs
your bot is missing permissions to do thsi action
!d discord.ext.commands.BadLiteralArgument
exception discord.ext.commands.BadLiteralArgument(param, literals, errors)```
Exception raised when a [`typing.Literal`](https://docs.python.org/3/library/typing.html#typing.Literal "(in Python v3.9)") converter fails for all its associated values.
This inherits from [`UserInputError`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.UserInputError "discord.ext.commands.UserInputError")
New in version 2.0.
!d typing.Literal
typing.Literal```
A type that can be used to indicate to type checkers that the corresponding variable or function parameter has a value equivalent to the provided literal (or one of several literals). For example:
```py
def validate_simple(data: Any) -> Literal[True]: # always returns True
...
MODE = Literal['r', 'rb', 'w', 'wb']
def open_helper(file: str, mode: MODE) -> str:
...
open_helper('/some/path', 'r') # Passes type check
open_helper('/other/path', 'typo') # Error in type checker
```...
No problem. 
And I'm a guy, btw.
then the bot doesn't have permission in that guild
but how i can make option.lower() here?
Oh OK ok
role hierarchy?
server owner?
or someone with the same role
if 2 people both have the highest role they cannot affect each o ther
this is the line of error in your code
it's not allowed to add a reaction
import discord
from discord.ext import commands
class Ban(commands.Cog):
def init(self, client):
self.client = client
@commands.command()
async def ban(self, ctx, member : discord.Member, *, reason=None):
await member.ban(reason=reason)
await ctx.send(f'Banned {member.mention}')
def setup(client):
client.add_cog(ban(self.client))
!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.
client.add_cog(Ban(client))
Ban isnt a subclass of Cog
❔
when making a cog you need to subclass commands.Cog
class Ban(commands.Cog):
...
have any of you even looked at his code
typo
yes
u did ban in setup but u did Ban in the class name
he did what you told him to do
you did Ban not ban
and the error occured
capitalisation
^
? you're telling him to do something he has clearly done, so this isn't needed at all
got it
read the error
ty
I don't know since when did Discord start changing capitalisation on its own.
?
their code has the cog Ban but in their setup they do ban
@solar pike
ye ye got it
twy6t
I did it with a small b but Discord changed it to a capital one somehow.
I don't see what that has to do with Python?
Access Denied?
Does the bot have manage messages permissions?
how to use discord.on_member_update(before, after)
to prevent mute
What does member update has to do with preventing a mute?
Try to remove the check.
maybe check if the muted role is in after.roles, idk how else you want to do it
check=is_me.
what is the code?
it might be because your top role is higher than the bots top role, or it just doesn't have the correct permission
Did you include the application.commands scope when adding your bot to the server?
What is user_roles?
It's obviously a purge command.
oh fuck
but he is also giving a check to that
wrong chat
Try to use a normal check. @commands.has_permissions(manage_messages=True) instead of an if statement.
the check is to validate that the user has the correct roles
let me help u
@bot.command()
@commands.has_permissions(administrator=True)
async def clear(ctx, amount= 1):
await ctx.channel.purge(limit=amount)
or just use commands.has_permissions
amount would be str if you don't convert it
it works. trust me 😉
if the user changes the value from the default 1 then it would be a str, you need to specify the type or convert it. either use amount: int = 1 or purge(limit=int(amount))
!d discord.TextChannel.purge
i added intents for on_member_join but now if i am adding link to dm someone else bot is doing dm to itself help pls
eh
U don't have access to do that
it works for me tho
.....?
like i have command await member.send("hi")
it was working well but after i added intents = discord.Intents.all() it is doing dm to itself :(
has the bot got the add reactions permission?
Can't happen... A member can't DM himself
not member bot is doing dm to itself
