#discord-bots
1 messages ยท Page 252 of 1
my json file look like this :
{
"219550798864973824",
"1111504619076599808"
}
mentioned_ids = [mention.id for mention in message.mentions]
if any(str(user_id) in mentioned_ids for user_id in ids):
i believe mention.id is returning integer, not string
these are strings, not ints, so indeed, you're comparing ints with strings, which will never be True
so without the quotes ?
I'd just rewrite and actually use a DB tbh
later, im just trying rn
try and see, you know the issue now
nextcord.ext.commands.errors.ExtensionFailed: Extension 'events.ping' raised an error: JSONDecodeError: Expecting property name enclosed in double quotes: line 2 column 3 (char 4)
which code exactly?
so, you can google that error actually, the answer is quite simple
How did it even run before, it's not valid json
!e
import json
print(json.loads("""
{
"219550798864973824",
"1111504619076599808"
}
"""))
@buoyant quail :x: Your 3.11 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "/home/main.py", line 2, in <module>
003 | print(json.loads("""
004 | ^^^^^^^^^^^^^^
005 | File "/usr/local/lib/python3.11/json/__init__.py", line 346, in loads
006 | return _default_decoder.decode(s)
007 | ^^^^^^^^^^^^^^^^^^^^^^^^^^
008 | File "/usr/local/lib/python3.11/json/decoder.py", line 337, in decode
009 | obj, end = self.raw_decode(s, idx=_w(s, 0).end())
010 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
011 | File "/usr/local/lib/python3.11/json/decoder.py", line 353, in raw_decode
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/vuwekurepi.txt?noredirect
probably just copied incorrectly
i know, it says its can work without quotes
i can read
Make it a list or a dict. There are no sets in json
[
219550798864973824,
1111504619076599808
]
i want to save it later
like making a command that save it (like -activate_dontpingme)
and i tried using a list but not working
like this :
ids = ["1111504619076599808"]```
the problem is here
you are still casting it to string in the any
so i need to remove it ?
const { Client, Intents } = require("discord.js");
console.log("Bot is starting...");
const client = new Client({
intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES],
});
console.log(client);
const prefix = "!";
client.on("messageCreate", (message) => {
if (!message.content.startsWith(prefix) || message.author.bot) return;
const args = message.content.slice(prefix.length).trim().split(/ +/);
const command = args.shift().toLowerCase();
if (command === "word") {
if (args.length > 0) {
const word = args[0];
message.channel.send(`The word you entered is: ${word}`);
} else {
message.channel.send("No word provided. Please enter a word after the command.");
}
}
});
client.login(token);
Bot is starting...
/Users/ericfloyd/github/Bot/src/bot.js:5
intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES],
^
TypeError: Cannot read properties of undefined (reading 'FLAGS')
at Object.<anonymous> (/Users/ericfloyd/github/Bot/src/bot.js:5:23)
at Module._compile (node:internal/modules/cjs/loader:1254:14)
at Module._extensions..js (node:internal/modules/cjs/loader:1308:10)
at Module.load (node:internal/modules/cjs/loader:1117:32)
at Module._load (node:internal/modules/cjs/loader:958:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)
at node:internal/main/run_main_module:23:47
Node.js v18.16.0
working
This is a python server
only python ^^
oops
any ts/js server?
how to respond to a non-interaction message ?
i searched the doc
if you want to send message you need abc.Messageable if you want to reply to a message you need Message and do .reply on it
!d discord.Message.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/latest/api.html#discord.abc.Messageable.send "discord.abc.Messageable.send") to reply to the [`Message`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Message "discord.Message").
New in version 1.6.
Changed in version 2.0: This function will now raise [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError "(in Python v3.11)") or [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError "(in Python v3.11)") instead of `InvalidArgument`.
await send(content=None, *, tts=False, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=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/latest/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.11)") of [`File`](https://discordpy.readthedocs.io/en/latest/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/latest/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.11)") of [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed "discord.Embed") objects. **Specifying both parameters will lead to an exception**.
** ๐
hi, so i made my bot add reactions to msgs, but how do i do this? https://gyazo.com/8163181196238c21baf1ec02262d99c4
Add buttons instead of reactions
One example is https://github.com/Rapptz/discord.py/blob/master/examples/views/confirm.py though there are other examples in the folder
# This one is similar to the confirmation button except sets the inner value to `False`
@discord.ui.button(label='Cancel', style=discord.ButtonStyle.grey)
async def cancel(self, interaction: discord.Interaction, button: discord.ui.Button):
await interaction.response.send_message('Cancelling', ephemeral=True)
self.value = False
self.stop()```
this?
The entire file is relevant
Not just "this"
oh but buttons, like, they are per user, no?
No, anyone can click them
well yes but 2 ppl can click them
they are only clickable once, no?
They're just like reactions
No, can click them indefinitely unless you set the disabled attribute to True once the user clicks on it
And once it's set to disabled, nobody can click it
okey okey
so what will be better for this scenario. I am asking something but i want like a confirmation, since when "yes" is pressed there is no way to undo. So before u had to write !yes twice, so mistakes were less likely. Now i was moving to emoji, and getting the count. But the other option is buttons. What would u use?
Buttons are much easier to work with
Not sure how different it is to reactions
In the end it's the same interaction from the user, just in a better UX way
yeah, but u dont have like a count for how many times someone pressed "yes"
with emojis, must be different ppl tho
You can, create a counter
with the !yes, same user could write it multiple times
im pretty sure with button u can count them too
So every time u press yes, i add 1 to a counter?
and u can press it again?
https://github.com/Rapptz/discord.py/blob/master/examples/views/counter.py as mentioned above, examples 
i see, so i guess buttons ๐
Much better imo, yeah
btw...
perms = ctx.channel.permissions_for(ctx.me)
if not perms.send_messages:
return```
This code is useless right?
Like, discord api will already return if bot doesnt have perms
right?
discord api will already return if bot doesnt have perms
Meaning?
if i call a command which is supposed that the bot will send "hello world"
it wont if it doesnt have the perms
It will throw an error
yeah, but only me will see such error on the console, right?
It will get logged unless you have an error handler that "eats" all errors and prevents them from being logged
i see, but bot wont disconnect, no?
so idk if those liens are good practice or useless
Nope, will not get disconnected
Usually you'd have a global error handler handling such errors
then i remove
thanks
IDE says interaction.response has no attribute edit_message
type hint your code :D
Hey this for anyone, I'm looking for people to help work on my bot, it's a multipurpose security bot and orentinated around fivem. Anyone interested it used discord.py so lmk.
how can i disable all buttons at once when certain condition is met?
loop over them
and set disabled to True
you can also set the view to None instead which sometimes looks cleaner
property children```
The list of children attached to this view.
Loop through this list (checking if each item is a button) and set disabled to True
ugg
and what if someone want to disable specific buttons only?
just don't disable that button?

but how do i know which button is what xD
it's custom_id
class Counter(discord.ui.View):
@discord.ui.button(label=str(DENIES), style=discord.ButtonStyle.danger)
async def button1(self, interaction: discord.Interaction, button: discord.ui.Button):
@discord.ui.button(label=str(APROVS), style=discord.ButtonStyle.blurple)
async def button2(self, interaction: discord.Interaction, button: discord.ui.Button):```
I have them like this now
Check the dpy server general chat, don't bother helping him
i'm not in the dpy server
mmm, children is a property, but it is a list according to docs, i still cant loop it (?)
property children
The list of children attached to this view.
Type
List[Item]
?
he is
but i dont see the point of posting that here tbh
<@&831776746206265384>
!mute 1110599386645418105 
:incoming_envelope: :ok_hand: applied timeout to @slate swan until <t:1686620865:f> (1 hour).
!ban 1110599386645418105 DMing members in this fashion is absolutely not appropriate
:incoming_envelope: :ok_hand: applied ban to @void anchor permanently.
A question is it possible to fetch the date at which a member is given the role??
If yes then how can i fetch it?
!unban 1110599386645418105 banned in error
:ok_hand: pardoned infraction ban for @void anchor.
Not without tromping through audit logs
Which I would not recommend
I believe certain events do give you which a member's roles are updated, then it would just be the current time
Yeah it would make the rate limited
So no way to find out except going through the audit logs which means that's a no
I mean, you could also listen for a on_member_update event
I believe discord.Role objects are hashable so you can set() both before.roles and after.roles and subtract them
I.e set(after.roles) - set(before.roles) should give you the roles that were added to a user
wouldn't that only fetch the roles that have been whereas I am trying to get the date at which the roles were added
The date and time that it was added is going to be datetime.now()
hmm
When dealing with the date and time what setting allows the time to be in channels?
Example ^
There's got to be a way
That's just setting the name of the channel to the current time
It's not a special Discord thing
Is there a way to change the time automatically when setting it up
await edit(*, reason=None, **options)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Edits the channel.
You must have [`manage_channels`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_channels "discord.Permissions.manage_channels") to do this.
Changed in version 1.3: The `overwrites` keyword-only parameter was added.
Changed in version 1.4: The `type` keyword-only parameter was added.
Changed in version 2.0: Edits are no longer in-place, the newly edited channel is returned instead...
Can be pretty much any discord.abc.GuildChannel iirc
Ok another thing I need help with is do you know where I can find a python code that explains how to set up anti-link , anti-raid, antispam etc
I've been searching for 2 days have not been able to locate a recent help.
The one I found has an @client error
People generally don't publish their code or their guides for these
For instance @inland quail is our security bot and it's closed source, while most of our other bots are all open source
In a way that does make sense ๐
Yeah, if people publish their security stuff it's too easy for threat actors to use that against them
So most of the time you either have to opt in to use a prebuilt security solution or try to roll your own
Thank you ๐
Np, only asking for a star in return
How to star โญ
There's that star button in repo
i've been trying to rewrite my discord bot to work in a more stateless way, but im confused on some points. if i create a view and send it to a channel, then the bot restarts, does the bot still correctly call the on_timeout method of my view class, and if so how if the instance no longer exists?
then, if i want to tie an instance of a view to a channel, such that i can retain the channel's id after a restart, what would be the best way of doing that?
If by "restart" you mean kill the process and run the script again, no, the on_timeout() will not be executed, furthermore, people won't be able to interact with the view at all. However, if it is a persistent view, it will work, but persistent views don't have timeouts
what about buttons, does the bot stop listening to non-persistent ones after restarting as well?
It's either persistent view or listening to interaction event depending on usecase
i'll try to describe my use case in a simplified way, bear with me
Lemme explain how the system works.
- You send a normal view with buttons
- Library adds components and associated callbacks to some data structure, all components have custom IDs
When user presses button
- Bot receives interaction event
- If the interacted component is found in structure I mentioned earlier, bot executes associated callback
I hope it's more clear now
When the bot restarts, all runtime data is deleted, including that mapping storing component ids and callbacks
yep, that makes sense, unfortunately its not ideal for a stateless environment
I don't really understand concept of state in context of discord views sorry
stateless in my case means i want to be able to restart the script without the bot losing its place
i.e. any data it needs to function can be retrieved at interaction time from data provided by the discord api, and in my case additionally data fetched from a database based on the previously mentioned data from the discord api
give me a second to write out an explanation of my app, hopefully it will make it more clear what im trying to do
- users interact with my bot by first running a command (
/start). - the bot responds with a view that contains some information about a "game" instance that is in its initialization phase, and a button that lets users open a "menu" message.
- this ephemeral menu message is the second view, where depending on the user's role, it shows buttons to join, leave, start, or stop the game.
- once a user presses the "start" button, the bot starts sending the third view repeatedly, which contains the actual gameplay. each of these gameplay views is simply a button that gets pressed, then the view is no longer needed, and a new one is sent
perhaps you might have some ideas on how to restructure this or point out flaws
There are two ways
Persistent view
- You define view class
- You use
bot.add_view(view) - Library adds components
- You can send view later any time, as components callbacks are registered on startup it will always respond. Just make sure that all components have
custom_idset.
Raw interactions
Suitable for things like button roles where you don't have constant view with constant components
- You send a view without callbacks, just with components, each has custom_id set
- You create that mapping of custom_id to callback or whatever you want to map it to
When user presses the component
- You receive interaction event
- You compare received
custom_idwith data in your mapping and do action based on it
At this point I don't think you need things to be persistent
maybe raw interactions would work, if i would allow me to separate the button logic from my view classes
If bot restarts it's gonna be down for a while and user will prob leave the game after they receive a couple of "application didn't respond" errors
the "state" here is basically the state of the game. i've already written some code to persist this state to a file/db/remote location so it can be retrieved after a restart
in my case, the downtime isnt really the problem (my vm or host takes a couple minutes to restart, and if the script crashes for whatever reason thats even faster). the larger problem is i might have multiple bot instances serving requests behind a load balancer, or i might even have the bot running on a serverless platform. in order to make that possible, i first need to solve the problem of allowing the bot process to restart without losing any information
You may just do restart by reloading extensions
on a serverless platform (e.g. vercel) i dont have control over how to restart it, it simply shuts down the process after the http request is complete
they're called raw components or low level components
and iirc they should only be supported by disnake in the base API
How to check a user status? like whether he's online, idle, dnd or invisible??
!d discord.User
class discord.User```
Represents a Discord user.
x == y Checks if two users are equal.
x != y Checks if two users are not equal.
hash(x) Return the userโs hash.
str(x) Returns the userโs handle (e.g. `name` or `name#discriminator`).
property status```
The memberโs overall status. If the value is unknown, then it will be a [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)") instead.
but It always returns offline
!d discord.Intents.presences iirc you need this intent
Whether guild presence related events are enabled.
This corresponds to the following events:
This also corresponds to the following attributes and classes in terms of cache...
channel = bot.get_channel(channel_to_send_messages)
em = discord.Embed(color=0xFFD700)
em.add_field(name='Current Not Expired Keys', value=f'<@{user}> key isnt expired' + "\n" + "expire date: " + expire + "\n" + "Key: " + key)
await channel.send(embed=em) ```
the code above keep sending the non expired keys non stop how can i make it send each non expired key only once?
is this codeblock inside a loop?
no.
how can i make send each one once?
oh ya mb should i just remove the while true?
well yeah, if you remove it, the lines under it will only be run once
so consider the consequences if any
so it will give only one of the Not expired keys?
yeah
do u have any ideas to fix it?
hi can someone help me with a bot i just ran and i dont know how to shut it down i was tryna make on on repl it
I do not understand your question clearly, can you please be a little more detailed about it
just click on the stop button on the top
of the replit window
yeah, it'll go offline soon but no commands will work
so the code is in while true and i need it to be in it so it gives me all of the Not expired ppl but it just repeat them non-stop with a delay of 5 seconds that i putted can u make it send the Not expired but not repeating any of the ones he already sent
oh yeah its not instant as like runiing it off a freind server
oh so you can simply use a for loop for that
can u give me a example? because i never used for loop
@upbeat otter ty for clearin tht up i was confused af
expired_keys = get_expired_keys() #This is an iterable of the expired keys
for key in expired_keys:
await send(key)
# This is the same as below but a lot cleaner
i = 0
while i < len(expired_keys):
await send(expired_keys[i])
i += 1
Hi
i just made my first discord bot, but it wont send messages
# IMPORT THE OS MODULE.
import os
# IMPORT LOAD_DOTENV FUNCTION FROM DOTENV MODULE.
from dotenv import load_dotenv
# LOADS THE .ENV FILE THAT RESIDES ON THE SAME LEVEL AS THE SCRIPT.
load_dotenv()
# GRAB THE API TOKEN FROM THE .ENV FILE.
DISCORD_TOKEN = "TOKEN GOES HERE"
# GETS THE CLIENT OBJECT FROM DISCORD.PY. CLIENT IS SYNONYMOUS WITH BOT.
bot = discord.Client(intents=discord.Intents.default())
# EVENT LISTENER FOR WHEN THE BOT HAS SWITCHED FROM OFFLINE TO ONLINE.
@bot.event
async def on_ready():
# CREATES A COUNTER TO KEEP TRACK OF HOW MANY GUILDS / SERVERS THE BOT IS CONNECTED TO.
guild_count = 0
# LOOPS THROUGH ALL THE GUILD / SERVERS THAT THE BOT IS ASSOCIATED WITH.
for guild in bot.guilds:
# PRINT THE SERVER'S ID AND NAME.
print(f"- {guild.id} (name: {guild.name})")
# INCREMENTS THE GUILD COUNTER.
guild_count = guild_count + 1
# PRINTS HOW MANY GUILDS / SERVERS THE BOT IS IN.
print("SampleDiscordBot is in " + str(guild_count) + " guilds.")
# EVENT LISTENER FOR WHEN A NEW MESSAGE IS SENT TO A CHANNEL.
@bot.event
async def on_message(message):
# CHECKS IF THE MESSAGE THAT WAS SENT IS EQUAL TO "HELLO".
if message.content.lower() == "hello":
# SENDS BACK A MESSAGE TO THE CHANNEL.
await message.channel.send("hey dirtbag")
# EXECUTES THE BOT WITH THE SPECIFIED TOKEN. TOKEN HAS BEEN REMOVED AND USED JUST AS AN EXAMPLE.
bot.run(DISCORD_TOKEN)
i copied it from some website, i just want to get basics working lol
omg
i dont get an error, it starts, says its connected but when i send hello
it doesnt do anyrhing
uh oo did i do smth wrong lol
what you're doing is all wrong ๐
lmao
by
cya later
@upbeat otter are you oneline? could you help me out a bit?
so could you tell me how to do it the right way?
or just send some resrouces or so
!resources
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
hm wait
it's full of "good" examples

Hi guys ,which discord python api wrapper is recommended to use these days?
discord.py is fine
@client.tree.command(name = "hello", description="prints hello")
async def hello(interaction: discord.Interaction):
user_id = interaction.author.id
user_name = interaction.author.name
data = {"content": f"User{user_name}({user_id}) used the /hello command."}
response = requests.post(webhook_url, json=data)
await interaction.response.send_message("Hello", ephemeral=False) ```
Can anyone please help me with this?
"this" is very informative on what doesn't work 
class discord.Interaction```
Represents a Discord interaction.
An interaction happens when a user does an action that needs to be notified. Current examples are slash commands and components.
New in version 2.0.
!d discord.Interaction.user
The user or member that sent the interaction.
But there is user ๐
And that's why people should learn to find such things themselves
i know i shouldnt be asking here but doing in discord bot
okay so what i am doing is theres a list in a['f']
i want to remove something from a['f]
when i used .remove() it returns null
the author attribute ran when using ctx, but it didn't with interaction, anywayss, thank you for telling me
As you said, wrong channel
which channel? pls help its very small stuff so not sure where to put it
Just like the other questions you've asked --> #1035199133436354600
Or just #python-discussion 
opening a thread for it seemed too much , general sounds better
In on_message_edit event is it possible to know if the message was sent when an application was executed?
If so, how can I get the user who executed the app command
Guys whats difference between slash command and tree command?
discord.py doesn't have a slash command decorator, so there can't be a difference between something that exists and something that doesn't - hence the tree command decorator represents a slash command
But why it's name is tree command
if you can make discord bot for me dm (150-200$)
no one is calling it a tree command, if you meant CommandTree, thats the object that holds all app commands (slash commands) and context menus, its just mapping, and handle proper invocation to those attached commands/menus
commands.Bot has a tree property, which is the CommandTree object that contains slash commands
how do I give my bot perms to manage messages. it cant delete messages on the main server but works in my private test server
it's a per-server permission
You need to go into the main server's role settings and enable the permission for your bot's role
ty its worked
Np
!rule 9
there are other events for that
is there a way to check what badges a user has?
nope
ok thx
you mean the badges like developer, nitro user, staff member etc...?
yes
!d discord.User.public_flags
property public_flags```
The publicly available flags the user has.
So i am having issues with my handlers for antinuke.
sends missing permissions error because is trying to ban himself (the bot)
the user was whitelisted so it wasn't supposed to be kicked
del a['f'] i believe would work
handle_whitelisted does nothing tho...
these handle functions all return None...
you probably want them to return either True or False?
yeah i was helping them in another server
hello, I want to build a discord bot in python that would allow me to display my League of Legends stats in a dedicated channel. I'm an extreme beginner in python and here's my code, no particular error message but nothing happens in the discord and on the terminal. Does anyone have a solution? Is it in the API? if someone says, you can dm me pls! thx team!!!
Your intents are the issue
Youโre missing message_content intents. Theyโre not the same as .messages Intents
!intents
Intents are a feature of Discord that tells the gateway exactly which events to send your bot. Various features of discord.py rely on having particular intents enabled, further detailed in its documentation. Since discord.py v2.0.0, it has become mandatory for developers to explicitly define the values of these intents in their code.
There are standard and privileged intents. To use privileged intents like Presences, Server Members, and Message Content, you have to first enable them in the Discord Developer Portal. In there, go to the Bot page of your application, scroll down to the Privileged Gateway Intents section, and enable the privileged intents that you need. Standard intents can be used without any changes in the developer portal.
Afterwards in your code, 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
# Enable all standard intents and message content
# (prefix commands generally require message content)
intents = Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix="!", intents=intents)
For more info about using intents, see discord.py's related guide, and for general information about them, see the Discord developer documentation on intents.
fix?
Can't help you find a fix unless you show us the code that's causing the error
!e None.url
@sick birch :x: Your 3.11 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "/home/main.py", line 1, in <module>
003 | None.url
004 | AttributeError: 'NoneType' object has no attribute 'url'
NoneType object has no attribute 'fix'
if only
it's __fix__
why buttons are slower to "process" than reactions?
ok, i change the code and i have this in my terminal now:
2023-06-13 21:40:45 INFO discord.client logging in using static token
2023-06-13 21:40:47 INFO discord.gateway Shard ID None has connected to Gateway (Session ID: e8accedf9f130078248c763a262e2e61).
Connectรฉ en tant que bot
Une erreur s'est produite : 'win_ratio'
the first 2 lines mean the bot is online
and the begining is now like this :
the others idk, cant read frrench
thats something from u, i believe
une erreur s'est produite is like "there is an error: "win_ratio"
Then go to win_ratio and check what's wrong there
it's not defined
( or the key doesnt exist , idk french)
Instead of having such abstract logging you could log the error itself
one thing. If on a view im adding buttons, can i have the stored somewhere so from 1 button i can change others?
if you're subclassing view you can simply use self.other_button_callback to access the other button, no need to store it anywhere else
what? if my button is async def button_no(self, interaction: discord.Interaction, button: discord.ui.Button): I can call it like self.button_no ????
right, self being the same View class instance
If it's in a view, yes
and then .label or .disable?? ๐ฎ
Yep, that's how OOP works
oh well, for me OOP is more like class Whatever: ... ; something = Whatever()
It is as well
i guess button_no is the constructor of such button? but like static object?
"win_ratio" just on this page, there is a probleme??? or was a probleme with the keys?
cuz everytime i call self.button_no i am refering to the same button, no? XD
button_no get's converted into a discord.ui.Button object when the discord.ui.button decorator is used on it
yeah but, what i mean is on normal OOP
x = Number(2)
y = Number(2)
x and y are totally different objects
Print the entire error or remove the try/except that hides everything useful, that'd be a good start
Classes can contain things
In that entire class you can access those entire things
That's OOP
yeah, and by doing x.label = 'hello' wont change y.label
but seems here, with buttons, doing self.button_no is always the same object (?)
๐คจ so you're trying to edit one view's button by another?
yeah
like, i am testing with a counter. When ever it reaches 0, i wanna disable the other button
just remove the try?
i could disable all children, but wanted to disable specific button
and ecept?
u can copy paste this testing code
class Counter(discord.ui.View):
def disable_button(self, custom_id):
for child in self.children:
if isinstance(child, discord.ui.Button) and child.custom_id == custom_id:
child.disabled = True
# Define the actual button
# When pressed, this increments the number displayed until it hits 5.
# When it hits 0, the counter button is disabled, and it turns green.
# note: The name of the function does not matter to the library
@discord.ui.button(label=str(DENIES), style=discord.ButtonStyle.danger, custom_id='no')
async def button_no(self, interaction: discord.Interaction, button: discord.ui.Button):
c = int(button.label) or DENIES
if c - 1 <= 0:
button.label = 'NO'
button.style = discord.ButtonStyle.red
button.disabled = True
self.disable_button('yes')
else:
button.label = str(c - 1)
# Make sure to update the message with our updated selves
await interaction.response.edit_message(view=self)
@discord.ui.button(label=str(APROVS), style=discord.ButtonStyle.blurple, custom_id='yes')
async def button_yes(self, interaction: discord.Interaction, button: discord.ui.Button):
c = int(button.label) or APROVS
if c - 1 <= 0:
button.label = 'YES'
button.style = discord.ButtonStyle.green
button.disabled = True
self.disable_button('no')
else:
button.label = str(c - 1)
# Make sure to update the message with our updated selves
await interaction.response.edit_message(view=self)```
all those buttons are in same message or not
yeah
they are, what's the issue then?
on the same View
well, i am not saying there is a problem XD just wanted to understand whats going on. When i call self.button_no i am refering to the object button_no, but i have never created such object
self there represents a View class, that store's the buttons as attributes button_no and button_yes
async def button_no(self, interaction: discord.Interaction, button: discord.ui.Button):
``` you declared it as a coroutine, the decorator converted it into a button
yeah, but i havent done anywhere x = button_no()
That's for what decorators are made for
Oh
decos create an object with the function u define as constructor?
srry never used decos before ๐ฆ
No, decorators execute the function that is defined in that decorator
aaa
!e ```py
def converter(f):
def inner(): return 1
return inner()
@converter
def foo(): print("hello")
print(foo) # foo was defined as a function but is now an int
@slate swan :white_check_mark: Your 3.11 eval job has completed with return code 0.
1
mmm not sure whats going on. foo is getting overwritten
Not the best example
Though that goes off-topic for the channel, there are some better channels if you need some better explanation of decorators - or your favorite search engine
ok ok, srry
so, a few days ago i asked chat gpt and he wrote me this
async def ui(ctx):
button1 = discord.ui.Button(style=discord.ButtonStyle.primary, label='Button 1')
button2 = discord.ui.Button(style=discord.ButtonStyle.primary, label='Button 2')
view = discord.ui.View()
view.add_item(button1)
view.add_item(button2)
i know probably u dislike AI tools, but still, this is why i asked about "storing" buttons somewhere
well, i know, but still, lets say i wanna disable 10 buttons only, what will be the best way? 10 lines calling self.button_x.disabled = True?
As you mentioned above, loop over all children
yeah srry, let say i have 20 buttons. How do i filter them?
Custom IDs
and do i have to loop over all of them to see which ones match the id or can i directly choose it?
If you know which one precisely (the function that holds the button), you can use just edit whatever you want on it
Otherwise for the custom ID yes, loop and condition
well ok, i think im not explaining myself or there is no way to do it the way i want. Imma try my best. So, when u create 10 objects, each of them is assigned to a variable. Then u can refer to certain object by its variable. Here, if i had a,b,c,d,e,f buttons, i could, inside the method for button e, call a.label="hi" and b.label = "bye". using a and b as variables, instead of self.imagine_my_button_has_a_big_name.label="hi" and self.imagine_my_button_has_a_big_name.style = discord.ButtonStyle.red. For example
How can I make a command for add roles? For example: /addrole
pretty sure u can
!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/latest/api.html#discord.Role "discord.Role")s.
You must have [`manage_roles`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_roles "discord.Permissions.manage_roles") to use this, and the added [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role "discord.Role")s must appear lower in the list of roles than the highest role of the member.
and how it's wrong in this code?
name="addrole",
description="Agregar un rol a un usuario.",
)
@commands.has_permissions(manage_roles=True)
@commands.bot_has_permissions(manage_roles=True)
@checks.not_blacklisted()
@app_commands.describe(
user="El usuario que debe tener un nuevo apodo.",
role="El rol que desea ponerle.",
)
async def addrole(self, c, m: discord.Member, role1: "<@&1115234290905653335>" = None):
member = context.guild.get_member(user.id) or await context.guild.fetch_member(
user.id
)
try:
await member.add_roles(role)
embed = discord.Embed(
description=f"El nuevo rol de **{member}** es **{role}**!",
color=0x9C84EF,
)
await context.send(embed=embed)
except:
embed = discord.Embed(
description="Ocurriรณ un error al intentar agregar el rol al usuario. Asegรบrese de que mi rol estรฉ por encima del rol del usuario al que desea agregar el rol.",
color=0xE02B2B,
)
await context.send(embed=embed)
async def setup(bot):
await bot.add_cog(Moderation(bot))
because it don't works
it should be a discord.Role object, not a string or None
can you copy my code and fix the problem please? Because I'm not very good at programation and I don't see the problem
We generally don't do that. We want you to learn from the experience.
why are u making a bot then?
because I want to learn
there are better ways to learn python tho
but I want learn discord moderation, and the bots it's the thing that I want to learn the first
well, u gotta go step by step. First learn programming in general, then specific language (python), and then move into python discord bots
can you say me any way to learn python?
u cant run before walking
well, u can go #python-discussion and ask for resources there, pretty sure ppl know good web pages
okay
But my bot is pretty good...
if it was, it would work
who wrote this?
me
the fact that you're using c in your function parameters and then use context as variable can't be right
if you understand what that means...
it works, the only thing that doesn't work is that command
? it does not work. u literally said
not works that command
but the bot have a lot of commands that yes works
I said my BOT is pretty good, not the command
yeah so u have a top tier car with awesome chasis without 1 wheel. Still pretty good car, right?
bruh
The bot have all this commands
the only command that not work is the /addrole
okey man, ur bot is pretty good ๐
Yes.
This is better?
name="addrole",
description="Agregar un rol a un usuario.",
)
@commands.has_permissions(manage_roles=True)
@commands.bot_has_permissions(manage_roles=True)
@checks.not_blacklisted()
@app_commands.describe(
user="El usuario que debe tener un nuevo apodo.",
role="El rol que desea ponerle.",
)
async def addrole(self, c, m: discord.Member, role1: "<@&1115234290905653335>" = None):
try:
await member.add_roles(role)
embed = discord.Embed(
description=f"El nuevo rol de **{member}** es **{role}**!",
color=0x9C84EF,
)
await context.send(embed=embed)
except:
embed = discord.Embed(
description="Ocurriรณ un error al intentar agregar el rol al usuario. Asegรบrese de que mi rol estรฉ por encima del rol del usuario al que desea agregar el rol.",
color=0xE02B2B,
)
await context.send(embed=embed)
async def setup(bot):
await bot.add_cog(Moderation(bot))
parameter name of context is still c...
in the docs, they use ctx
it's up to you
so use that in as parameter name
as well as ctx.send(...)
instead of context...
i think he doesnt know what is he doing, tbh
no offense, but not sure how you could make these mistakes if you already have multiple commands and cogs
Leave me alone? I have said that I do not have programming studies, I have learned based on tutorials and people with experience.
so u made 20+ commands without knowing programming? damn im jelous. I wish i could
all copied and pasted using someone else's code i'm guessing
to do that
if it were copied and pasted, I would not have the problem when doing this command
yes
He is saying that all the commands are copied and pasted
but if it were copied and pasted, I would not have the problem when doing this command
Well, since you don't help me I'm not going to argue anymore, I'd rather learn than argue with such an incompensable community
we help, we dont spoonfeed
i am not writting ur code for u
okay
I understand that
since you don't want to do it, you don't have to start to hesitate
man, this is a support server
you can ask if you get any errors, learn something you dont udnerstand etc
not for people writing you code
@slate swan because from the first message you sent me everything has been critical. Have you ever wanted to learn, just like me
Okay
someone already posted u this. U havent take a look at it at all
you're not wanting to learn though you're wanting someone to do it for you
I understand, sorry fot that
read this first
sorry, now I'm saying I need help and someone that explains me like I was a baby
yes, I looked, but I don't understanded very well
That's why I wanted someone help me
i still wonder how u managed to add some many commands without understanding very well the documentation
.
pretty sure there are tutorials about adding/removing discord roles
my code was like this but a man told me it was wrong and he corrected it for me the way i have sent before
Lets say my bot sends a message when calling a command. This message uses variables like name or index. How could I edit the message text and still have access to those variables inside a View class (when pressing a button)? For example, bot ask if name is equal to index idx, and u have 2 buttons, yes and no. If u press yes, text is changed to f"This {index} is {name}". Inside the ui.View i dont have the variables name and index
have you fixed it or?
'Perfect Choice, Please send the amount to this CashApp ', {cashapp}
TypeError: unsupported operand type(s) for +: 'set' and 'str'
ffix?
no, code
well, unsupported operand type(s) for +: 'set' and 'str'
seems u are trying to sum a set and a string
elif message.content.lower() == 'cash app':
await message.channel.send(
'Perfect Choice, Please send the amount to this CashApp ', {cashapp}
+ (message.author.mention))
why do you have {cashapp}
use + instead
and the () around message.author.mention
its a variable defined above
Didn't work
I know, why do you have {}?
new code
await coro(*args, **kwargs)
File "/home/container/soul.py", line 144, in on_message
'Perfect Choice, Please send the amount to this CashApp ' + {cashapp}
TypeError: can only concatenate str (not "set") to str
elif message.content.lower() == 'cash app':
await message.channel.send(
'Perfect Choice, Please send the amount to this CashApp ' + {cashapp}
+ (message.author.mention))
remove the {}
It worked thanks ๐
does anyone specialize in discord.py and can explain why my code isnt working? i swear its right๐ญ
You should post your code along with relevant traceback and why you think it's not working
there is no traceback but ill send code
import discord
from discord.ext import commands
from discord.ext import tasks
from itertools import cycle
import os
import asyncio
client = commands.Bot(command_prefix=',', intents=discord.Intents.all())
bot_status = (["/cancelled", "on", "top"])
status = next(iter(bot_status))
activity = discord.Streaming(name=status, url='https://twitch.tv/764')
@tasks.loop(seconds=10)
async def change_status():
await client.change_presence(activity=activity)
@client.event
async def on_ready():
print("/cancelled is online")
change_status.start()
async def load():
for filename in os.listdir("./cogs"):
if filename.endswith(".py"):
await client.load_extension(f"cogs.{filename[: -3]}")
async def main():
async with client:
await load()
await client.start('token_here')```
And what's the problem
when i run it it doesnt run the bot it just stops
Because you aren't calling the main function anywhere
oh
skull long day
now i got it working but it wont find my cogs sigh
mann idek i js want it to be good but it wont find my cogs now
in discord.py, view timeouts are facilitated by the library itself, right?
yes
just spawns a task and do a sleep at an interval until ends
import discord
from discord.ext import commands
class Mod(commands.Cog):
def __init__(self, client):
self.client = client
@commands.Cog.listener()
async def on_ready(self):
print("Mod.py is ready.")
@commands.command()
@commands.has_permissions(manage_messages=True)
async def purge(self, ctx, amnt: int):
await ctx.channel.purge(limit=amnt)
await ctx.send("purge successful gang")
async def setup(client):
await client.add_cog(Mod(client))``` this is my cog for moderation commands as of right now, when i load the bot it now runs fine, but when i run commands, it gives me an error stating the command name isnt defined.
!traceback
Please provide the full traceback for your exception in order to help us identify your issue.
While the last line of the error message tells us what kind of error you got,
the full traceback will tell us which line, and other critical information to solve your problem.
Please avoid screenshots so we can copy and paste parts of the message.
A full traceback could look like:
Traceback (most recent call last):
File "my_file.py", line 5, in <module>
add_three("6")
File "my_file.py", line 2, in add_three
a = num + 3
~~~~^~~
TypeError: can only concatenate str (not "int") to str
If the traceback is long, use our pastebin.
โ[30;1m2023-06-14 01:06:10โ[0m โ[31mERROR โ[0m โ[35mdiscord.ext.commands.botโ[0m Ignoring exception in command None
โ[31mdiscord.ext.commands.errors.CommandNotFound: Command "purge" is not foundโ[0m !!
Do you actually load the cog
!warn 858557059868000286 this isn't a place for you to advertise.
:incoming_envelope: :ok_hand: applied warning to @silk turtle.
how to make bot online forever
host it on a vps
how
Purchase a VPS
Run your bot there
Yeah first you need to get the VPS. The reputable services are listed here: https://www.pythondiscord.com/pages/guides/python-guides/vps-services/
As for free options, you can use amazon AWS free tier, microsoft azure (both last for 1 year) or digitalocean (200$ for 2 months).
I recommend getting a machine with ubuntu OS, then following this guide to setup hosting there https://www.pythondiscord.com/pages/guides/python-guides/docker-hosting-guide/
This article lists recommended VPS services and covers the disasdvantages of utilising a free hosting service to run a discord bot.
This guide shows how to host a bot with Docker and GitHub Actions on Ubuntu VPS
from discord.ext import commands
BOT_TOKEN = 'Here'
intents = discord.Intents.default()
intents.typing = False
intents.presences = False
bot = commands.Bot(command_prefix='!', intents=intents)
@bot.event
async def on_ready():
print("Bot is online and ready.")
print(f"Logged in as: {bot.user.name}")
print(f"User ID: {bot.user.id}")
@bot.command()
async def ping(ctx):
latency = bot.latency
await ctx.send(f"Pong! Latency: {latency * 1000:.2f}ms")
bot.run(BOT_TOKEN)
Bot doesnt send any message
Type a print statement after initialising the method for debugging
it doesn't send anything when i type !Ping
you need to enable message content intents
!d discord.Intents.message_content
Whether message content, attachments, embeds and components will be available in messages which do not meet the following criteria:
โข The message was sent by the client
โข The message was sent in direct messages
โข The message mentions the client
This applies to the following events...
Why not discord.Intents.all()?
Because it sucks ass if you don't really need all intents, which is 99% of the time the case for bots
yhh
does anyone have any good tips or pointers for a anti nuke in discord.py
Nuke is what
Destroying server?
You could like put limit of channels creation per minute or smth
I can't really think of anything more effective
There are millions of ways to destroy server
- Create infinite channels named "balls"
- Delete all channels
- Remove all roles
- Create infinite roles named "balls" with admin perms and give them to everyone
- Invite spam bots that would send "balls" message every second in every channel
Only 5 but trust me there are 999995 more definitely
the most effective anti-nuke is a well set up server, there's only so much bots can do, and generally speaking anti-nuke bots end up getting in the way of legitimate moderation actions during events like raids
examples/views/confirm.py lines 53 to 59
await view.wait()
if view.value is None:
print('Timed out...')
elif view.value:
print('Confirmed...')
else:
print('Cancelled...')```
examples/views/confirm.py lines 36 to 38
@discord.ui.button(label='Cancel', style=discord.ButtonStyle.grey)
async def cancel(self, interaction: discord.Interaction, button: discord.ui.Button):
await interaction.response.send_message('Cancelling', ephemeral=True)```
I did, hence my response
m just askin what should i type where these ????? are situated
Something similar to that
Or that
Do you need to send a new view? No. So remove it
Have you defined the embed object? No. So define it
can u vc pls?
To define an embed it is
embed = discord.Embed(description="whatever")
Just like you did below, shouldn't be too hard as well...
Then define an attribute in your class and pass that embed to the view class when when creating it in code e.g. view = Sell(embed) and then you can use that embed in the button callback with self.whatever and whatever being the attribute you've created
sounds good now right?
No it doesn't, you haven't defined/created the attribute
boom lol
Good you can read
OOP is a thing you must know when using libraries like discord.py https://www.w3schools.com/python/python_classes.asp
Look at the __init__ function
Oops
yes i added an anti nuke cog and now my bot brokeded >:(
!paste code and error
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.
It was nuke cog
Hey, may I ask you a question?
https://paste.pythondiscord.com/apumekazir
I have this command in my script
Its a slash command
I would like to make my commands so @everyone can't see the slash command anymore.
Is that possible?
you should use app_commands.checks.has_permissions instead
will that disable @everyone from getting the popup when typing in / ?
That works for using the command.
But I want to disable @everyone from seeing the command
hmmm i think the check is done locally
don't you have to disable the command in the server
Lets say my bot sends a message when calling a command. This message uses variables like name or index. How could I edit the message text and still have access to those variables inside a View class (when pressing a button)? For example, bot ask if name is equal to index idx, and u have 2 buttons, yes and no. If u press yes, text is changed to f"This {index} is {name}". Inside the ui.View i dont have the variables name and index
I think so, I just wanted to know if there is a chance to predifine the permissions before syncing the commands with the guild
yeah there's a way
what library are you using?
from discord import app_commands
you need to use discord.app_commands.default_permissions
!d discord.app_commands.default_permissions
@discord.app_commands.default_permissions(**perms)```
A decorator that sets the default permissions needed to execute this command.
When this decorator is used, by default users must have these permissions to execute the command. However, an administrator can change the permissions needed to execute this command using the official client. Therefore, this only serves as a hint.
Setting an empty permissions field, including via calling this with no arguments, will disallow anyone except server administrators from using the command in a guild.
This is sent to Discord server side, and is not a [`check()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.check "discord.app_commands.check"). Therefore, error handlers are not called.
Due to a Discord limitation, this decorator does nothing in subcommands and is ignored.
thank you so much, will test it when I'm done coding the new feature
await ctx.send("Saniye sayฤฑlฤฑyor...", view=View(button2))
^^^^^^^^^^^^^
TypeError: View.init() takes 1 positional argument but 2 were given
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: View.init() takes 1 positional argument but 2 were given
anybody know what this error means
A question I am using mysql so should I make a new connection to the host every time a command is used or just a make a new cursor for the command and close the cursor when the command has been completed?
Are you on MacOS?
A guide on fixing verification of an SSL certificate.
You create view instance and then add items to it using .add_item
Example of view can be found here
In this example they create the items in the View subclass which is more readable
does this repo have any example of how to edit a message embed from the ui.View when pressing buttons? if such message has variables being used and i wanna still have access to them

go check yourself under examples folder
idk what to look for xd
i belive they dont have any examples with embeds
i saw... ๐ฆ
and do u know by chance how could i do this?
save the message in a view then on button click edit it
you need to subclass view for it
yes, but if the message has variables and the message is like f'variable1: {var1} - variable2: {var2}', how can i use var1 and 2 on the View subclass?
send the varriables to view as well
how do i do that?
class MyCustomView(ui.View):
def __init__(self, var1, var2):
self.var1 = var1
self.var2 = var2
...
...
var1 = 1
var2 = 2
view = MyCustomView(var1, var2)
.send(f"{var1} {var2}", view=view)
oh
on the constructor?
yes
oooh nice, thanks ๐
keep in mind that when you override the __init__ method you need to call super().__init__()
oh true
One last thing. If i am editing the embed... Should i actually edit it or send a new embed object with same structure?
ill do that right quick
edit
i dont see any open await commands like its saying,
And could u tell me why? Like, is it easier for the bot to edit than send a new one? And if i wanna edit it... I guess it is under interaction.response, but how do i get what do i wanna edit?
discord.ext.commands.errors.ExtensionFailed: Extension 'cogs.moderation' raised an error: TypeError: object NoneType can't be used in 'await' expressionโ[0m
no you need to send message to view as well
do u know what line
it does it for every command ive tried to run,
but does it say what line does it happen
not that im aware ill run it again and send a commands
mmm ive seen there is a param called "content" inside await interaction.response.edit_message(view=self)
hm i dont think .edit_message will work
do it like this
view = ...
view.message = await .send(...)
then you have .message varriable in your view
โ[31mTraceback (most recent call last):
File "C:\Users\fake\dadat\Lol\game\Python\Python38\lib\site-packages\discord\ext\commands\bot.py", line 947, in _load_from_module_spec
await setup(self)
TypeError: object NoneType can't be used in 'await' expression
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\notreal\funny\lol\this\Python\Python38\lib\site-packages\discord\client.py", line 441, in _run_event
await coro(*args, **kwargs)
File "c:\Users\notreal\games\bot\bot.py", line 24, in on_ready
await client.load_extension("cogs.moderation")
File "C:\Users\not real\stuff\Lol\this\Python\Python38\lib\site-packages\discord\ext\commands\bot.py", line 1013, in load_extension
await self._load_from_module_spec(spec, name)
File "C:\Users\lolol\path\fake\Programs\Python\Python38\lib\site-packages\discord\ext\commands\bot.py", line 952, in _load_from_module_spec
raise errors.ExtensionFailed(key, e) from e
discord.ext.commands.errors.ExtensionFailed: Extension 'cogs.moderation' raised an error: TypeError: object NoneType can't be used in 'await' expressionโ[0m```
show the setup function for the moderation cog
its in my hastebin link
Well, i dont know exactly what is the best way to edit. There is .edit, .edit_message and .edit_original_response
try .edit_original_response it might work without sending message to view
it has to be async
client.add_cog must be awaited as well
!d discord.ext.commands.Bot.add_cog
await add_cog(cog, /, *, override=False, guild=..., guilds=...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Adds a โcogโ to the bot.
A cog is a class that has its own event listeners and commands.
If the cog is a [`app_commands.Group`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.Group "discord.app_commands.Group") then it is added to the botโs [`CommandTree`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CommandTree "discord.app_commands.CommandTree") as well.
Note
Exceptions raised inside a [`Cog`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Cog "discord.ext.commands.Cog")โs [`cog_load()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Cog.cog_load "discord.ext.commands.Cog.cog_load") method will be propagated to the caller...
so instead of just def it would be async def for my setup? and then await the slient.add_cog(coghere(client))
yes
This is a lower level interface to InteractionMessage.edit() in case you do not want to fetch the message and save an HTTP request.
This method is also the only way to edit the original message if the message sent was ephemeral.```
okay im gonna go fix right noe
what does "you do not want to fetch the message and save an HTTP request" mean?
like i said it should edit original message without needing to store it
Okey so, this is what i have now
class Counter(discord.ui.View):
def __init__(self, name=None, idx=None):
super().__init__()
# When pressed, this decrements the number displayed until it hits 0.
# When it hits 0, the counter button is disabled, and it turns green.
# note: The name of the function does not matter to the library
@discord.ui.button(label=str(DENIES), style=discord.ButtonStyle.danger)
async def button_no(self, interaction: discord.Interaction, button: discord.ui.Button):
c = int(button.label) or DENIES
if c - 1 <= 0:
button.label = 'NO'
button.style = discord.ButtonStyle.red
button.disabled = True
self.remove_item(self.button_yes)
else:
button.label = str(c - 1)
# Make sure to update the message with our updated selves
await interaction.response.edit_message(view=self)```
The last line is that updates the view, i believe. Since i only change the label of the button "no". But i believe the message itself is on interaction.response, no?
i dont have any self.message
tbh, im a bit lost between Interaction.message and .response
what is a better practice:
@client.command()
async def s(ctx):
embed1 = discord.Embed(title="Embed 1", description="This is the first embed.")
embed2 = discord.Embed(title="Embed 2", description="This is the second embed.")
embed3 = discord.Embed(title="Embed 3", description="This is the third embed.")
embeds = [embed1, embed2, embed3]
await ctx.send(embeds=embeds)
await ctx.send('-----------------')
await ctx.send(embed=embed1)
await ctx.send(embed=embed2)
await ctx.send(embed=embed3)```
sending multiple embeds on the same message, or different msgs?
Multiple in one, you won't unnecessarily hit rate limits faster by making multiple API requests
all at once
may i ask why?
cause each ctx.send is an api call
so you either call api once or 3 times
ah
i see, thanks ๐
thats why i have to interaction.message.embeds[0]
yo can someone help me, for some reason my bot goes offline, i looked in the logs nothing. its the second time now
im using nextcord
Hey, can I ask you a question?
So, i have a python script here:
https://paste.pythondiscord.com/atanenisub
at line 126 I have a context menu named "report_message"
The bot sends a message in a predifined channel
I want the bot to include 2 buttons and a dropdown menu below the embed
Buttons: Go to message (link of reported message) / claim
Dropdown: Options: ban, tempban, mute, tempmute, warn, verbal warn, nothing
When the button "CLAIM" has been clicked, it should change color from blue to green and say "claimed by (user)"
When I chose an action from the dropdown (only one should be chosen), it should say what action has been chosen
class Moderation(commands.Cog):
def __init__(self, client):
self.client = client
@nextcord.slash_command(name="moderation", dm_permission=False)
@commands.guild_only()
async def moderation_group(self, interaction: Interaction):
await Checks._defer(self, interaction)
return await interaction.followup.send("This shouldn't be able to be ran by itself, but if you're seeing this, good job!.", ephemeral=True)
@moderation_group.subcommand(name="ban", description="Allows you to ban a member for a certain reason, and time (minutes) (both optional)")
@commands.guild_only()
@commands.has_permissions(ban_members=True)
async def ban_cmd(self, interaction: Interaction, member: nextcord.Member, reason: str = None, minutes: int = 10):
await Checks._defer(self, interaction)
@moderation_group.subcommand(name="kick", description="Allows you to kick a member for a certain reason (optional)")
@commands.guild_only()
@commands.has_permissions(kick_members=True)
async def kick_cmd(self, interaction: Interaction):
await Checks._defer(self, interaction)
@commands.Cog.listener()
async def on_ready(self):
print(f"{self.__class__.__name__} loaded.")
@commands.Cog.listener()
async def on_slash_command_error(self, ctx: commands.Context, error):
if isinstance(error, nextcord.errors.MissingPermissions):
await ctx.send("You don't have the required permissions to use this command.")
def setup(client: commands.Bot):
client.add_cog(Moderation(client))
```is there any reason this cog (using nextcord) doesnt actually check if the user has permissions upon running ban or kick? im kinda confused. lmao
please also handle other errors in your command_error handler with else
else you'd be hiding them
yeah i plan on it, just didn't in that cuz i was trying to fix the problem at hand, the event its self for command error isn't even being ran
which is confusing me completely.
I don't use nextcord, so I can't really help with those slash commands there
Hey hey, I have a (hopefully not too complicated) question
I'm trying to create a button that opens a website when it gets pressed while subclassing discord.ui.View and i'm not sure where to specify the URL that is supposed to open
@discord.ui.button(label="Find websites", emoji="๐",style=discord.ButtonStyle.link)
async def find_websites_callback(self, interaction: discord.Interaction, button: discord.ui.Button):
print("hi")
you can't create a url button with the decorator
in the view init
b = ui.Button(..., url = "xyz")
self.add_item(b)```
why when editing an embed message with an image attached the image goes outside the embed but stays inside too? the image is dupped
ohh thanks a lot, it worked :D
Hey, can you help me?
https://paste.pythondiscord.com/foharozutu
I get interaction failed errors every time I press the claim button, can you help me?
how do i make multiple enimies in pygame
wrong channel and bad question
why is it bad
what's an enemy? wdym make? it gives us 0 info about what you're trying to do and we have to waste time guessing what you mean
https://paste.pythondiscord.com/foharozutu
I get interaction failed errors every time I press the claim button, can you help me?
so i have my discord bot save data to a file, but how can i make it so it doesnt keep overriding line 1, and go to the next line
I need a patner for making a bot
DiscordAPIError[50001]: Missing Access
at handleErrors (C:\Users\user\OneDrive\Documents\Discord bot\node_modules\@discordjs\rest\dist\index.js:640:13)
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
at async SequentialHandler.runRequest (C:\Users\user\OneDrive\Documents\Discord bot\node_modules\@discordjs\rest\dist\index.js:1021:23)
at async SequentialHandler.queueRequest (C:\Users\user\OneDrive\Documents\Discord bot\node_modules\@discordjs\rest\dist\index.js:862:14)
at async REST.request (C:\Users\user\OneDrive\Documents\Discord bot\node_modules\@discordjs\rest\dist\index.js:1387:22) {
requestBody: {
files: undefined,
json: [
[Object], [Object],
[Object], [Object],
[Object], [Object],
[Object], [Object],
[Object], [Object]
]
},
rawError: { message: 'Missing Access', code: 50001 },
code: 50001,
status: 403,
method: 'PUT',
url: 'https://discord.com/api/v10/applications/1107421055431225346/guilds/1107420871393542173/commands'
}```
i gave it commands.applications
and allat and it still doesnt work?
this is the python discord not js
oh mb
just wanted to tell you haha
so i have my bot read a txt file and send it, but would it be able to print a certain part? like for example:
this is what sends it
you'd split the line at a certain decorator, for example =
how would i make sure it splits when it sends
and doesnt just send the whole thing
split the data, and extract the data you need to send
To be honest, just use JSON at this point
^^
okay
yeah JSON in that case would be so much better & so much easier lmao
Quick question,
Do any of y'all use Rasberry pi for bot hosting ?
& Can it run intricate and complex bots with no issue ? "8gb ver"
does anyone have an idea of how to create a keep alive.py file so i can keep my bot running using uptimereboot
I havent created discord bots in a year I imagine many things have changed especially with discord switching over to slash commands is there anywhere I can learn it again. I dont really want to read through the docs so if anyone has any other methods please share them
thank you cheers!!
@bot.event
async def on_message(message, self, msg):
Blacklist= ["discord.gg", ".com"]
for black in Blacklist:
if black.lower() in msg.content.lower():
await msg.delete()
await msg.channel.send(f"WATCH YOUR TONE")
Why doesn't my code work
@client.event
async def on_member_join(member):
message = f"Wasg {member.mention} Thanks for joining the community gang"
print(message)
embed = discord.Embed(title="New Member Joined",
description=message, color=discord.Color.random())
embed.set_thumbnail(url=member.avatar_url)
embed.add_field(name="Join Date",
value=member.joined_at.strftime("%Y-%m-%d %H:%M:%S"), inline=False)
channel = client.get_channel(channel.id)
await channel.send(embed=embed)```
```AttributeError: 'Member' object has no attribute 'avatar_url'```
it got changed i think its member.avatar.url now
ohh ok thank you
the one i use is display_avatar
i think on_message only accepts one parameter
It alr. I made it work anyways, Iโm wondering on how to make it so it will delete any variation so like if I had scam in there it would delete scammer, scamming, scams etc
should already be doing that
You are not allowed to use that command.
Mm how would you detect scam?
I doubt if "free robux" in msg.content.lower() would work ๐ง
Ask someone if they're a scammer 
just maybe try training some 15 billion parameter model or smn ๐
Hello, in order to send a message, please verify you are not a scammer using /verify command!
reverse psychology
No I don't have nvidia a100
oof
Nobody ?
Question, so I have a curse word blocker, when the word gets deleted I want it to send to a channel saying โBad word detected and what word it isโ how can I code that
just get the channel using client.get_channel, save it assigned to a variable, and later use the .send method on the variable with the data
get_channel takes a channel id as a argument*
why not just use automod
client.application._patch(data.application);
^
TypeError: client.application._patch is not a function
at module.exports [as READY] (/Users/roopa/Desktop/projects/LLbot/node_modules/discord.js/src/client/websocket/handlers/READY.js:21:24)
at WebSocketManager.handlePacket (/Users/roopa/Desktop/projects/LLbot/node_modules/discord.js/src/client/websocket/WebSocketManager.js:354:31)
at WebSocketManager.<anonymous> (/Users/roopa/Desktop/projects/LLbot/node_modules/discord.js/src/client/websocket/WebSocketManager.js:238:12)
at WebSocketManager.emit (/Users/roopa/Desktop/projects/LLbot/node_modules/@vladfrangu/async_event_emitter/dist/index.js:282:31)
at WebSocketShard.<anonymous> (/Users/roopa/Desktop/projects/LLbot/node_modules/@discordjs/ws/dist/index.js:1103:51)
at WebSocketShard.emit (/Users/roopa/Desktop/projects/LLbot/node_modules/@vladfrangu/async_event_emitter/dist/index.js:282:31)
at WebSocketShard.onMessage (/Users/roopa/Desktop/projects/LLbot/node_modules/@discordjs/ws/dist/index.js:938:14)
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
Node.js v20.2.0
๐ internal error ๐
this is python server
anyways ._patch is not a callable
!src
i am there , no one replied ๐
k lol
Does anyone know if there is a code that makes it plausibel for clikable phone Numbers on discord
๐ง
Its like the same when you look up a company on Google and it shows a number you can click and it will Ask if you wanna call it
Can anyone help me with this ?
I want to make command which will help bot owner to invoke command behalf of other users
Here is the code I tried but does not work as i expected --
@commands.command(name="dbg")
@commands.is_owner()
async def debug_command(self, ctx, user: Optional[commands.MemberConverter], command: str = ""):
if not command:
await ctx.send(":exclamation: Please provide a command to execute.")
return
if user is None:
user = ctx.author
invoked_command = self.bot.get_command(command)
if invoked_command is None:
await ctx.send(f":exclamation: Invalid command: {command}")
return
ctx.message.author = user
await self.bot.invoke(ctx)
solved
Yaa
.
I got banned from the other serv cause they thought I was raiding jt
So here I am
did you react to your own message
Yup
lol
wanted to send you a link to js servers
but my message got removed โ ๏ธ
ik , i can see that msg
better discord ๐ง ?
i have macbook as well and i still cant see deleted messages
coz youre not using vencord ๐
mhm so it is modded discord client
ig , coz it just patched OG app
what does not work as expected?
its solved already 

main.py like a civil and respectable man
main.txt 
Bot.py users are heathens who need to be burned
eval(open("main.txt", "r", encoding="utf-8"))

Seems like a scam
Would suggest being careful
huh
there is a bunch of directory levels so
seemed appropriate
ast.literal_eval
ok but that will be 2 lines
need nitro ๐ฅน
words
you are not blue anymore
that means you are casual now
@slate swan I don't think JS Hub is a javascript discord
nvm, it is
the /js vanity used to be owned by a discord server unrelated to javascript
i have it under my programming discords folder so it has to be about js
nvm my nvm
it's not related to javascript
we've that discord server blacklisted for this very reason
well then it explains why i added it to dev servers
haha
sorry for that then
You need to change permissions to append, which is a.
E.g.
with open("file.txt", "a") as f:
f.write(f"{data}\n")
me, who uses __main__.py and python -m bot to run my bot:
๐ณ
iirc python CLI can run code from txt files
btw __main__.py is better than main.py if your project is structured like a package
i am using __main__.py 

main.py? Nah poetry run bot
no poetry run python -m bot
i know you can
Oh that's what you meant
my preferred way of running bots now is to not run bots 
ENTRYPOINT ["poetry", "run"]
CMD ["python", "-m", "bot"]
docker!?
obviously
docker my beloved
I have never had to use docker for any of my bots pepesweat
for me its just easier to set up everything in docker compose
also its easier when moving to VPS
ic, usually I just do everything in poetry, move it over from git and just poetry install
I use docker for bots mostly because when you've written like 1 python dockerfile it suddenly becomes unbelievably easy to deploy 99% of bots
I usually have a schema.sql too so setting up the database is no problem
true
i just copy paste the dockerfiles
imagine deploying bots
how can i use jishaku??
A debugging and testing cog for discord.py rewrite bots. - jishaku/README.md at master ยท Gorialis/jishaku
all i have to do is ```bot.load_extension('jishaku')
or
await bot.load_extension('jishaku')```?
if you installed it already then yes
i did
you need to use the one using async/await syntax
if i do without await it wont work?
i belive it will throw exception
can u forbide all users except the one who used a command to interact with a view?
Yes
how? is there a fancy way or u just check who reacted?
just check the user id of who you want to use it
so for the rest of users buttons will be enabled?
you can't disable buttons for a single users
you would need to check who interacted and do something if x or y
okey
if interaction.user.id == 34567890:
do stuff
else:
send error
or better way
if interaction.user.id != 17629816201:
error
return
do stuff
https://github.com/python-discord/bot/blob/main/bot/exts/info/subscribe.py#L63-L92
this is how @unkempt canyon does it for the !subscribe command
id should be the same as user used the command
so i guess it would be interaction.message.client?
check this
!d discord.Interaction
class discord.Interaction```
Represents a Discord interaction.
An interaction happens when a user does an action that needs to be notified. Current examples are slash commands and components.
New in version 2.0.
This is the essential part:
class MyView(discord.ui.View):
def __init__(self, owner):
...
self.interaction_owner = owner
async def interaction_check(self, interaction):
if interaction.user != self.interaction_owner:
# You can do something else here, this shows an ephemeral message to the user
await interaction.response.send_message(
"This is someone else's button",
ephemeral=True,
)
return False
return True
@slate swan
and where do i pass owner?
when you instantiate the view
the person who can click the button
probably ctx.author or similar
ah okey, ty
one thing i dont understand what i did
client = cmds.Bot(command_prefix=BOT_PREFIX, help_command=None,
activity=Game(name=f'{BOT_PREFIX}help'), intents=intents)
client.channels_ids = {}```
By doing this, im giving the bot an attribute called channels_ids which is a dictionary?
can i actually do that???
what does unslotted mean?
it doesn't use _slots_, which is a sequence of strings that defines what attributes an object of that class can have
Python allows you to set custom attributes to most objects, like your bot! By storing things as attributes of the bot object, you can access them anywhere you access your bot. In the discord.py library, these custom attributes are commonly known as "bot variables" and can be a lifesaver if your bot is divided into many different files. An example on how to use custom attributes on your bot is shown below:
bot = commands.Bot(command_prefix="!")
# Set an attribute on our bot
bot.test = "I am accessible everywhere!"
@bot.command()
async def get(ctx: commands.Context):
"""A command to get the current value of `test`."""
# Send what the test attribute is currently set to
await ctx.send(ctx.bot.test)
@bot.command()
async def setval(ctx: commands.Context, *, new_text: str):
"""A command to set a new value of `test`."""
# Here we change the attribute to what was specified in new_text
bot.test = new_text
This all applies to cogs as well! You can set attributes to self as you wish.
Be sure not to overwrite attributes discord.py uses, like cogs or users. Name your attributes carefully!
any idea how to make a server info command for a bot in discord.py? been stumped for hours...
What type of info u want it to display??
server name, owner, members, bots, create date
!d discord.Guild Take a look at the list of attributes here
class discord.Guild```
Represents a Discord guild.
This is referred to as a โserverโ in the official Discord UI.
x == y Checks if two guilds are equal.
x != y Checks if two guilds are not equal.
hash(x) Returns the guildโs hash.
str(x) Returns the guildโs name.
editing a msg vs deleting and sending new are the same amout of api calls?
Aren't they 3 different processes?
editing is 1, deleting+sending is 2
because each has it's own endpoint
using centos7 vm
can i make a bot with discord.py that gives a role and then removes it 10 minutes later?
yes
i linked you the tutorial to this error above
hi
What do you want
Hm?
lol
Hello community, somebody can help me with pywhatkit? or teach me another form to send whatsapp messages from python.
if there is somebody who can help you for sure not in this channel this one is related to discord bots go to #1035199133436354600 or elsewhere
Hi, i search for remove timeout with command unmute you can help me please ?
You pass in None into the timeout function
!d discord.Member.timeout
await timeout(until, /, *, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Applies a time out to a member until the specified date time or for the given [`datetime.timedelta`](https://docs.python.org/3/library/datetime.html#datetime.timedelta "(in Python v3.11)").
You must have [`moderate_members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.moderate_members "discord.Permissions.moderate_members") to do this.
This raises the same exceptions as [`edit()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member.edit "discord.Member.edit").
In duration ?
Yes
yo
does anyone know how i can code a vouch command (discord bot) im not rly sure how to start/what to do
Step 1: Choose what library you wanna use either discord.py/nextcord/pycord/disnake
Step 2: Read all their docs
Step 3: Try to understand their docs
Step 4: Practice the code you read in the docs
Step 5: WE BALLIN!!!! Make the vouch command
also You can't ask such a vague question and expect code cause literally you didn't specify alot of stuff
๐
File "/home/container/.local/lib/python3.11/site-packages/discord/app_commands/commands.py", line 842, in _do_call
return await self._callback(interaction, **params) # type: ignore
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/container/otrobot.py", line 712, in unmute
await member.timeout(duration = None, reason = None)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: Member.timeout() got an unexpected keyword argument 'duration'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/container/.local/lib/python3.11/site-packages/discord/app_commands/tree.py", line 1248, in _call
await command._invoke_with_namespace(interaction, namespace)
File "/home/container/.local/lib/python3.11/site-packages/discord/app_commands/commands.py", line 867, in _invoke_with_namespace
return await self._do_call(interaction, transformed_values)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/container/.local/lib/python3.11/site-packages/discord/app_commands/commands.py", line 856, in _do_call
raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'unmute' raised an exception: TypeError: Member.timeout() got an unexpected keyword argument 'duration'
Step 0: Take the time to learn Python and OOP
!d discord.Member.timeout
await timeout(until, /, *, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Applies a time out to a member until the specified date time or for the given [`datetime.timedelta`](https://docs.python.org/3/library/datetime.html#datetime.timedelta "(in Python v3.11)").
You must have [`moderate_members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.moderate_members "discord.Permissions.moderate_members") to do this.
This raises the same exceptions as [`edit()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member.edit "discord.Member.edit").
you need to do that on instance
As you can see, no duration only until
not the class
Pass until as None, more simple than that is hard
Traceback (most recent call last):
File "/home/container/.local/lib/python3.11/site-packages/discord/app_commands/commands.py", line 842, in _do_call
return await self._callback(interaction, **params) # type: ignore
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/container/otrobot.py", line 712, in unmute
await member.timeout(until = None, reason = None)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: Member.timeout() got some positional-only arguments passed as keyword arguments: 'until'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/container/.local/lib/python3.11/site-packages/discord/app_commands/tree.py", line 1248, in _call
await command._invoke_with_namespace(interaction, namespace)
File "/home/container/.local/lib/python3.11/site-packages/discord/app_commands/commands.py", line 867, in _invoke_with_namespace
return await self._do_call(interaction, transformed_values)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/container/.local/lib/python3.11/site-packages/discord/app_commands/commands.py", line 856, in _do_call
raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'unmute' raised an exception: TypeError: Member.timeout() got some positional-only arguments passed as keyword arguments: 'until'
You already got told above what's the issue
hello
Sry but i can't do it
assembly
!
got some positional-only arguments passed as keyword arguments: 'until'
And how is that shitpost related to the channel?
oh my bad should i delete it?
Until is not only arguments passed
@bot.tree.command(name="unmute", description="Unmute a member")
@commands.guild_only()
async def unmute(interaction, member: discord.Member):
await interaction.response.defer()
if not interaction.user.guild_permissions.kick_members:
await interaction.followup.send(f"You are not authorized to use this command {interaction.user.mention}")
return
await member.timeout(until = None, reason = None)
await interaction.followup.send(f'{member.mention} has been unmuted')```
how does that matter
Good thing people know the difference between kwarg and positional args
it tells you that until is positional only and you passed it as keyword
sry if i don't understand the doc and all your message, english is not my native langage
