#discord-bots
1 messages ยท Page 370 of 1
are you defining the function below your client?
yeah
one sec
hello everyone i lf store data for each of my user for start i make something like this
global donnees
ID = ctx.author.id
if ID not in donnees:
donnees[ID] = {
'Inventaire': ["breche commune"],
'personnages': [],
'equipements':[],
'argent': 0,
'prime': 0,
'elo': 0,
'pv': 0,
'fragementCommun': 0,
'fragementInhabituel': 0,
'fragementRare': 0,
'fragementMystique': 0,
'fragementDivin': 0
}
but i loose the data at each restart of my bot i think i need to use database but how can i made for use it and can i recycle my code with my dictionary or i need to remove it and make the same with database ? thanks
NameError: name 'get_prefix' is not defined```
sending the error one more time
what do i do
some sort of import?
where did you define your prefix ?
you need to make something like that at the start of your code intents = discord.Intents.default()
client = discord.Client(intents=intents)
client = commands.Bot(command_prefix='!', intents = discord.Intents.all())
but go watch tutorial for make discord bot i think for get the basic
im trying to make a code to change prefix when you're in another discord server
oh i see
^
client = commands.Bot(command_prefix = get_prefix, help_command=None, intents = discord.Intents.all())
and says get_prefix is not defined
can you send your entire code
althought i believe it should have been correct
!paste
If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.
of the whole bot?
btw if someone can help me
of the file where client = ... is
I mean, you'd usually want a database for storing data persistantly between restarts
you need to put your function above the client definition:
def get_prefix(client, message):
with open('prefixes.json', 'r') as f:
prefixes = json.load(f)
return prefixes[str(message.guild.id)]
client = commands.Bot(command_prefix = get_prefix, help_command=None, intents = discord.Intents.all())
so i need to remove all my code with my dictionary ?
or i can use it with db
also i'd reccomend using an actual database instead of a json file, but that's a different topic
depends on what db you use, but it's usually structured differently, yes.
i cant just save my dictionary ๐ญ ?
you can
because i make all my current code with dictionary
and i am really lazy to remake all
how?
using json files
what is your use case?
i want to store inventory and other information of every user
this is my dictionary : ID = ctx.author.id if ID not in donnees: donnees[ID] = { 'Inventaire': ["breche commune"], 'personnages': [], 'equipements':[], 'argent': 0, 'prime': 0, 'elo': 0, 'pv': 0, 'fragementCommun': 0, 'fragementInhabituel': 0, 'fragementRare': 0, 'fragementMystique': 0, 'fragementDivin': 0 }
how can i save it in a json so ?
make a json file, and save the dictionary to it ;)
!d json.dumps
json.dumps(obj, *, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, default=None, sort_keys=False, **kw)```
Serialize *obj* to a JSON formatted [`str`](https://docs.python.org/3/library/stdtypes.html#str) using this [conversion table](https://docs.python.org/3/library/json.html#py-to-json-table). The arguments have the same meaning as in [`dump()`](https://docs.python.org/3/library/json.html#json.dump).
Note
Keys in key/value pairs of JSON are always of the type [`str`](https://docs.python.org/3/library/stdtypes.html#str). When a dictionary is converted into JSON, all the keys of the dictionary are coerced to strings. As a result of this, if a dictionary is converted into JSON and then back into a dictionary, the dictionary may not equal the original one. That is, `loads(dumps(x)) != x` if x has non-string keys.
and write to file
alright !
use a proper db
json not work ?
its not the best practice to use json as a 'db'
json isn't a db
json work but json bad db
why ?
what is bad with it
it's not supposed to store data
but if that work where is the problems ?
^
Read this
i see
i gonna use db
someone has good tutorial for learn how to use db ?
like sql lite
SQLBolt provides a set of interactive lessons and exercises to help you learn SQL
that's for sql
how can i save a list in sql lite ?
i make something like that await cursor.execute("CREATE TABLE IF NOT EXISTS users (id INTEGER, argent INTEGER, prime INTEGER, elo INTEGER, pv INTEGER, fragmentCommun INTEGER, fragmentInhabituel INTEGER, fragmentRare INTEGER, fragmentMystique INTEGER, fragmentDivin INTEGER, personnages TEXT, equipements TEXT)") but i want store more than 1 personnage text value personnage = character in french
and i check and i cant save list
so how can i make ?
sqlite doesn't support arrays, but you could use something like json and store it as TEXT in your database
which db can support arrays ?
Help me pls
i think i gonna use replit db
my bot is host in replit so
@wanton current
bro?
code?
eg. postgres
for first say hello, say your problem, stop spam pinging everyone, and show your code
i have to give you code?
@slate swan
show your code please
run what ?
or malicious
just ask if you try running a script or something else xd
we need to see your code to help u
@slate swan
.py
this is always not the code but yeah
i dont want help that and you dont show the code so i cant xd
what you are trying to run is malicious.
what is pyaes
no one can assist you further :)
?
If you don't know then no one can assist you @slate swan
hes trying to compile a token stealer dont help him at all
went ahead and reported him as well
yes
enjoy making a new account
5. Do not provide or request help on projects that may violate terms of service, or that may be deemed inappropriate, malicious, or illegal.
you really correct me bro im french and have better english than you
you are truly so immature its embarrassing. take your malicious, broken, open source bullshit and hop out of here
damn thats crazy, almost like i couldnt tell
send you something @primal sail
19
you were attempting to, by running malicious code targeted towards stealing other peoples information and accounts
17
someone already use replit db ?
because im fear i dont have enough memory for store date of all my member
yo can i have a minute to solve something real quick
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Member' object has no attribute 'avatar_url'
so this is the error alright?
bought me and my girlfriend breakfast
!paste
If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.
avatar.url if you're on >=2.0
a local restaurant which im not naming
100$ for a breakfast is crazy wth
its super fancy and brand new
im in the keys so
everything is expensive
yep works now thanks alot mate !
nw
50 MiB is enough for store data (like maybe 50 per user) for like 1k member ?
in a db
string and int
Shouldn't take up that much
do sum bout it
i can pay 7$ per month for 2go so if i have problem i gonna try that (if my server projet earn me money xd)
you can get a full fledged VPS with 40GB of storage less than $5 a month
you do realize at certain points in america, the time is different? theres multiple timezones, just like everywhere else in the world.
its 5pm in france
i dont need so much
(i think)
Yeah but paying $7 for 2GB is a scam
^^
maybe but the db is easy to use and make for my IDE
Whatever floats your boat
i dont understand how can i store value for each member
https://youtu.be/Vx5Ci77K-ss
Here's how to use Replit DB with Python!
Anyone got any clue how to send a button to a webhook, every time I try I get a value error
maybe you can use Context Menus (i never use it so dont really know)
I was trying to send it through using webhook.send(etc, etc, etc, view=buttonone())
But it says it needs to have a associated state
You send a View like that, not a Button
Ah you're trying to use a stateless webhook. If you made the Webhook via url and that Webhook has the token, you can use Webhook.fetch to gain the necessary state:
I forgot to brain
!d g discord.Webhook.fetch
await fetch(*, prefer_auth=True)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Fetches the current webhook.
This could be used to get a full webhook from a partial webhook.
New in version 2.0.
Note
When fetching with an unauthenticated webhook, i.e. [`is_authenticated()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Webhook.is_authenticated) returns `False`, then the returned webhook does not contain any user information.
So what do I change in my code then? What do I have to do
The webhook you're calling .send on is not a "full" webhook, it's Partial as the docs above touch on
You can call Webhook.fetch() to update it in place with a Full webhook... which can send Views
What is button
import discord
from discord import ui
class ButtonSendCode(ui.View):
def __init__(self):
super().__init__(timeout=None)
@discord.ui.button(label="Send Code", style=discord.ButtonStyle.green, custom_id="persistent:button_one")
async def button_one(self, interaction: discord.Interaction, button: discord.ui.Button):
await interaction.response.send_message("hi")
that is button
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 Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.
mhm what am i meant to do then
when i use the command it doesnt show what its suppose to but just random numbers
Nothing, you send an instance of this ButtonSendCode view with the view= kwarg
elaborate? what do you want it to show, and more importantly, what does it actually show?
how does one do that?
Like uh... this?
ValueError: Webhook views require an associated state with the webhook
the line i used was await webhook.send(view= ButtonSendCode)
Did you fetch it before (the webhook)?
yea im using webhook= Wbhook.from_url
You need to fetch that webhook
webhook = Webhook.from_url(...)
webhook = await webhook.fetch()
await webhook.send(...)
ahhhh
so
await.webhook.fetch()
await webhook.send(view= ButtonSendCode)
also what do i need to import
for the fetch
await.webhook.fetch()
^
SyntaxError: invalid syntax
cause i just get left with that
Where did you get await.webhook from?
does it need to be fetched? as far as i can tell, fetch() passes through the connection state to the new webhook anyway
https://github.com/Rapptz/discord.py/blob/v2.3.2/discord/webhook/async_.py#L1390
discord/webhook/async_.py line 1390
state=self._state,```
^
Yes it needs to be fetched
Webhook.from_url has no state at all
sending a View requires state
.fetch() returns a new webhook tho, good catch, i thought it just mutated self
Read it again, I have not done await.webhook anywhere in that codeblock
oh yea
still same issue
ValueError: Webhook views require an associated state with the webhook
I just edited the codeblock, sorry, read it again for the new change
ValueError: Webhook views require an associated state with the webhook
webhook2 = await webhook.fetch()
await webhook2.send(view= ButtonSendCode)
still exact same issue
works fine for me when client= is given
thats why i mentioned fetch() passing through _state, if the partial webhook is missing it then fetch() won't return it either
so
what should i do from ```
webhook2 = await webhook.fetch()
await webhook2.send(view= ButtonSendCode)
what do i need to do
Oh now I see what you meant, yeah, you're right
wait so in this case the webhook would be described as both "partial" and "stateful", right?
soooo what do i do?
webhook = Webhook.from_url("...", client=<your bot>)
await webhook.send(...)
client, not session
how do i obtain tat
it is your bot or client object
That bot object is what you use, yes
Don7t edit that line at all, that's just the bot i meant
so i just say client = bot
i wont dw
๐๏ธ๐๏ธ** **
already have one 
Server info
YES, but what numbers are incorrect?
guys, can anyone help me in my doubt of task.loop in python-help channel?
It's almost half an hour and after 1 hr of inactivity it closes so asking it here
Thanks in advanc!!
pass in the embed to the ModuleButton's init
which embed
callback embed?
yea ig
you can use an attribute as a reference
I am confused on what you want exactly
do you want to get the embed this function correct?
async def callback(self, interaction: Interaction) -> Any:
self.embed = discord.Embed(...)
return await interaction.edit_original_response(
embed=self.embed, view=self.view
)```
I want the self.embed = discord.Embed(...) of ModuleButton
yeah this embed
class ModuleButton(discord.ui.Button):
def __init__(...):
super().__init__(...)
self.embed = None # HERE
async def callback(self, interaction: Interaction) -> Any:
self.embed = discord.Embed(...)
return await interaction.edit_original_response(
embed=self.embed, view=self.view
)
class HelpPanel(discord.ui.View):
def __init__(self, ...):
super().__init__(...)
@discord.ui.button(...)
async def ...(self, interaction: discord.Interaction, _):
view = discord.ui.View(timeout=120)
for cog in self.bot.help_cogs['main']: # List of cogs
# Here
buttton = ModuleButton(...)
view.add_item(button)
view.children[0].disabled = True
return await interaction.response.send_message(
embed=button.embed,
view=view,
ephemeral=True
)
basically, When the user clicks the button of HelpPanel, it will send an ephemeral embed with a View
But isn't self.embed is None until it is clicked?
cause I want the first button to be already clicked
then predefine the embed there
class ModuleButton(discord.ui.Button):
def __init__(...):
super().__init__(...)
self.embed = Embed(...)
how will I get interaction there
what do you mean? Explain what you want to achieve
this on clicking the Main button
I mean, do you want to click on the button and have the embed message appear? ๐ค
here, main button is the button in HelpPanel
when i click on the button of HelpPanel I want it to show the first child's embed
Then use the reference I gave you in my example. You just need to access the button attribute and then submit it.
But I cant get access to interaction.user and client there
or is it the best to make the embed manually in HelpPanel's button
I have a question why do you have another view?
view = discord.ui.View(timeout=120)
use current view
I want.
why current
My goal is to have the first child's embed on clicking main button
Leave, I'll not provide the embed there
it will be None.
It's so simple you just have to add a reference. If you just want to send the embed message just use the attribute.
what is the 'reference'
And how?
.
You can save interactions in another attribute ๐ค
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 Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.
heres the code and here's the error discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Guild' object has no attribute 'member'
but if button is not clicked interaction is still None
it is member_count
kk
you use discord.py?
is member_count
ty! it works
thank you too
You already confused me, you said you just wanted the buried message.
๐
I want the embed but the embed requires the interaction.user and interaction.client
Does the embed have to show interaction information? Like the author, etc.? Correct?
Why did you delete your messages? I can't help you that way.
has anyone had any issues when inviting a discord bot to a server? when i try and click to save unsaved changes to generate a URL it wont save it
iYes
Yes*
created basic giveaway system! i ask for advice or improvements, thank you!
how to make a slash command only appear for the owner of the bot
Add that you can Chose How many People are going to win and that in the Embed is shown How many enterd the giveaway
i dont think you can hide it, only limit it
The short answer is you can't. Slash commands are deliberately made to be discoverable
good idea, thanks
You Can set command permissions in server but i'm not sure if you Can make it not show up for users
i dont think so, but you can set permissions
you can hide it from users that dont have certain permissions
- Dont use json as database
- You could make it only allow certain roles to join giveaway when specified on creation
- Show how many users are already in in the embed
- A bit harder but could make some multipliers for specified roles
So how could I send a modal using a regular command?
thank you, which database system should I use?
interactions from message components (views) can respond with modals, so thats your best option
modals only interact with interactions logic, dont they?
If you know SQL use some SQL database if you dont use mongodb but best is to learn sql
For example postgres but if you dont want to set it up and stuff you Can use sqlite for example which just requires a file like database.db
you can ask in #databases if you have related questions
https://paste.pythondiscord.com/2LRQ
I always get the error: 'Bot' object has no attribute 'select' any tips?
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.
i see
https://paste.pythondiscord.com/2LRQ#1L21-L21
on this line what is this?
from where did you get bot.select
thanks!
How do I get my bot to send a message on a voice channel?
you mean, let your bot speak?
How could I make the strings in regular commands, Allow spaces.
for example like string1= Hello there string2= hi there
no, let my bot send a message in a voice channel, like the voicemanster or astro bot do
FFmpeg
by default dpy will parse quoted strings, so given a command like: py @bot.command() async def cmd(ctx, arg1: str, arg2: str): ... you can pass both argumesnts as !cmd "Hello there" "hi there"
ohh, do you mean the text channel that every voice channel has? Or what exactly do you mean?
yes, the text channel that each voice channel has
thanks
if you want one argument to take the entire string without needing quotes, you can make it a keyword-only argument with a leading star: py @bot.command() async def cmd(ctx, arg1: str, *, arg2: str): ... !cmd "Hello there" hi there would then be equivalent to the first example
just get the ID from the voice channel. lemme check docs
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) object. To upload multiple files, the `files` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list) of [`File`](https://discordpy.readthedocs.io/en/latest/api.html#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) object. To upload multiple embeds, the `embeds` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list) of [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed) objects. **Specifying both parameters will lead to an exception**.
@slim bloom should work
voice_channel_id = 1245797706589278280 ###PUT HERE THE VOICECHANNEL ID
voice_channel = ctx.guild.get_channel(voice_channel_id)
await voice_channel.send("Test")
i just tried it, it works!
i would try this template if you are not familiar with Python.
if isinstance(channel, discord.VoiceChannel):
ctx.guild.get_channel(channel)
await channel.send(content='You have been added to the voice channel, welcome')```
alrr
This doesnโt work and idk why :(
message = ' '.join(map(str, args))
channel = bot.get_channel(modmail_channel)
if channel:
embed = nextcord.Embed(
title="**Mod Mail**",
description=message,
color=nextcord.Color.purple()
)
bot.loop.create_task(channel.send(embed=embed))
@bot.event
async def on_message(message):
if message.guild is None:
member = target_guild.get_member(message.author.id)
if member:
log(f"DM from **<@{message.author.id}>**: \n\n{message.content}") ```
It worked like 2 hours ago but now it doesnโt work and I didnโt change anything
hmm, try it first
no errors?
No
Just doesnโt work
I have a log thing which has the def as the EXACT same but different name and channel
I tried to print after
@bot.event
async def on_message(message):
And it didnโt work
hm
I also tried to log it as the exact same thing but โLogโ instead of โMod Mailโ and it didnโt work
And log works normally
add a error handling/prints
So smth to do with this part of the code:
async def on_message(message):
if message.guild is None:
member = target_guild.get_member(message.author.id)
if member:
modmail(f"DM from **<@{message.author.id}>**: \n\n{message.content}") ```
Wait ima try smth
@vocal magnet can I have permission to screen share?
Also the โlogโ is where I was testing it, it usually would be modmail
Found the issue, I had 2 on_message events

How do I cool down the server? prefix command
yep that could do it
!d discord.ext.commands.cooldown
@discord.ext.commands.cooldown(rate, per, type=discord.ext.commands.BucketType.default)```
A decorator that adds a cooldown to a [`Command`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Command)
A cooldown allows a command to only be used a specific amount of times in a specific time frame. These cooldowns can be based either on a per-guild, per-channel, per-user, per-role or global basis. Denoted by the third argument of `type` which must be of enum type [`BucketType`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.BucketType).
If a cooldown is triggered, then [`CommandOnCooldown`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CommandOnCooldown) is triggered in [`on_command_error()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.discord.ext.commands.on_command_error) and the local error handler.
A command can only have a single cooldown.
@slim bloom
Why does this only work with bot.event and not with bot.listen()
@bot.listen()
async def on_message_2(message):
if message.author.bot:
return
if message.channel.id == 1245101494689333340:
try:
await asyncio.sleep(1)
await message.add_reaction('โญ')
await asyncio.sleep(1)
await message.add_reaction('โ ๏ธ')
except Exception as e:
print(f'Error adding reaction: {e}')```
does on_message_2 have something to do with it
There is no such event called on_message_2
How can i have several events?
on_message events
@bot.listen("on_message")
Yah, just read the docs
very stupid of me ๐
thanks for your help
Just ask, it's wasting everyone's time asking to ask
!paste
If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.
so here's the code and here's the error
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: Embed.__init__() got an unexpected keyword argument 'Timestamp'
!d discord.Embed
class discord.Embed(*, colour=None, color=None, title=None, type='rich', url=None, description=None, timestamp=None)```
Represents a Discord embed.
len(x) Returns the total size of the embed. Useful for checking if itโs within the 6000 character limit.
bool(b) Returns whether the embed has any data set.
New in version 2.0.
x == y Checks if two embeds are equal.
New in version 2.0...
timestamp, not Timestamp
It's like, "I know this is a help channel but can someone help me?" ๐ญ
Don't beat up on them, it's just politeness. It's fine to assume in help dedicated spaces that folks are there to help
a simple and practical ticket system, does anyone have suggestions or ideas for improvement? thanks!
I strongly suggest you don't make channels for tickets. There's a ton of limitations and this is what discord made threads for basically
ok thank you, i will try to take this over
Otherwise looks pretty smooth
!paste
If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.
thank you, it took me almost a day. i didnt know exactly how to create the transcript system. i put the channel history in embed. but embeds have restrictions when it comes to words. i will use this to convert blocks.
The nice thing about threads is you really don't need a transcript. You just archive it
Incredibly smooth ux, just add people to the thread if you want it private then archive it when it's done
You're missing a closing )
i will remember that, thank you
huh, i checked my test bot's ratelimits and it showed 2000/1d for channel creates (shared bucket between guilds), and 1000/0.01s for deletes - thought the create limit would be much lower, but i guess you have max guild channel caps too
iirc that's one that they actually tend to vary between bots. The bot level rate limit tends to come into play less than the per guild max usually with these systems though
oh wait i think i misunderstood the bucket key, the ratelimits are still localized by top-level resources
looks like thread creates is 50/300s for me
and thats what, 1000 active threads max per guild vs 250 text channels?
!paste
If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.
hello, I have been using modals on my bot on a host but i keep getting this error
https://paste.pythondiscord.com/WVIQ
When I run it on vscode it works fine
the error?
oh you pasted
missing package (means that the requested resource set could not be found) ig contact the host support
Unknown webhook happens when you try to followup before responding
Are you doing something before sending the modal?
could you send the source?
i have blood in there and should i share it like this? pay me something for it 
ok
10$ 
How do I do a Button with a link?
A hands-on guide to Discord.py
Wow, that's great!
basically you set url
https://github.com/Rapptz/discord.py/blob/master/examples/views/link.py
here is the example but looks rather complicated xd
Nah, it's fine, I just had a bad time defining the bttn. I didn't know that link ones cannot be made with the decorator, ty
yea since you cant do anything when clicked cause it opens that link
ill show you the code
!paste
If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.
https://paste.pythondiscord.com/4WKA @naive briar
the thing is it works on vscode
but it doesnt work on on my host
or my other host
yes
can you do .send_modal when you already sent a message to .response?
wdym?
like this
await interaction.response.send_modal(VerificationModal())
class VerificationModal(discord.ui.Modal):
def __init__(self):
super().__init__(title="Enter Verification Code")
self.add_item(discord.ui.TextInput(label="Verification Code"))
async def on_submit(self, interaction: discord.Interaction):
user_code = self.children[0].value
if int(user_code) == bot.user_codes[interaction.user.id]:
await interaction.response.send_message("Email verified successfully! | Your email will be used to send you updates and statuses etc of zagzag. To remove it use /email-remove", ephemeral=True)
await bot.redis.set(key, email)
# Implement logic to mark the email as verified
else:
await interaction.response.send_message("Invalid verification code. Please try again.", ephemeral=True)
```

does anyone know how i can connect my discord bot to a website? like most famous bots where you can change the settings and setups on the website. i know you need HTML but what else? and do you have any good DOCS to start with?
There aren't really any "docs" for making a Discord bot web dashboard, but you'd have to be familiar with web development, as well with databases probably, and also finding a way to communicate things between your bot and your web dashboard. As well as things like OAuth2, and the list goes on.
It's definitely not an easy task.
@slate swan, Like this?
no text has been sent
Is there a built in function for grabbing a users name?
i would like to have it printed in the logs when someone does a command
@bot.event
async def on_app_command_completion(interaction: discord.Interaction, command: discord.app_commands.Command):
guild = bot.get_guild(your-guild-id)
channel = guild.get_channel(the-channel-id-you-want-the-logs-in)
await channel.send(f'{command.name} command used by {interaction.user}({interaction.user.id}) in ``{interaction.guild.name}``')
print(f'{command.name} command used by {interaction.user}({interaction.user.id}) in ``{interaction.guild.name}``')
```
Got a template for you
oh you want it printed
wait one sec
i mean
just in the terminal
so if i can get it to a variable its good
@bot.event
async def on_app_command_completion(interaction: discord.Interaction, command: discord.app_commands.Command):
print(f'{command.name} command used by {interaction.user}({interaction.user.id}) in ``{interaction.guild.name}``')
like that
and i just put on_app_command_completion() at the end of my commands?
no
oh wait its an event
its an event
yeah
Guys, can anyone tell me how to transfer money via a slash command for an economic discord bot, I am writing a bot in python but disnake.py
so what about this... im running the bot using a .service file. Something i just learned about the other day. So i cant directly see the logs
what do i have to do to have a terminal that monitors the logs and can recieve print commands?
do you have a database?
i assume it would just be some fancy SQL then, no?
SQlite3
so you dont have a terminal?
i do have a terminal
but what i dont have is one that actively monitors the bot
it just runs in the background
.
I need to figure out how to make a command using a slash
to transfer currency on the server, I need a code
The thing is how is it working on vscode and not on my host
also no, you cant
to do what?
I need to figure out how to make a command using a slash
to transfer currency on the server, I need a code
What you tried so far?
I donโt know how to write in code the transfer of money to the user in an economic bot using a slash command
Then learn how to, nobody is going to write code for you here
I'm asking if someone can explain to me how to write it correctly?
I tried to rewrite it many times, look at the forums and didnโt find anything.
You just said you dont know how to code
Also I tried to defer it and
discord.app_commands.errors.CommandInvokeError: Command 'verify-email' raised an exception: InteractionResponded: This interaction has already been responded to before
If you defer you cant send a modal
you wont find anyone here who will make you codes, unless there is a private payment for helping outside the server (i dont know if that violates rule nr 9) you have to learn to code yourself like everyone else here. we can help you correct your mistakes but we cant make them for you! @lost root
I know how to program, I just donโt know how to write a transfer of money to a user using a slash command
are you using cogs?
What do cogs have to do here ๐
yea
what else can i do?
Its just confusing that it is working on vscode, but not my host
Then maybe show some code, how you store the data, what you tried etc
Idk its weird
You Can Ask on dpy discord
if he uses cogs i recommend using app_commands or hybrid, otherwise in main.py, bot.tree would be sufficient https://fallendeity.github.io/discord.py-masterclass/slash-commands/
A hands-on guide to Discord.py
whats that?
I dont see how that affects this
But sure
@lost root
what exactly is your problem/error?
i advised you sum hrs bevor, to contact your host, often it is due to missing packages
what packages is missing
that is a guess. as i said, contact your hoster
ok
is it safe to hardcode API keys into my discord bot?
idk if someone is able to yoink them or not
someone gave me the solution
๐
the smtplib is blocking
yeah, but it's generally not recommended
Is anyone good at making a discord bot? Dm me
best to just have a config for em
Anyone wanna make a anime bot
Why is the title not showing up in the modal?
did I do something stupid or is it just broken lmao
I fixed it
Ok
im trying to make a new / command called graph. I have @bot.tree.command(name="graph", description="Create a graph!") above my async def graph, but discord doesnt see it as a command. I even do /graph and my terminal says /graph doesnt exist
anyone know any ways to fix it?
did you sync?
!paste
If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.
thats error
!paste
https://paste.pythondiscord.com/ZNKQ
thats the code i know its not optimal but idk what to do
wait nevermind im stupid i dont have role createdff
I need to have a function occur and finish before another function occurs, is there any wait like function for this?
isnt that a normal function at that point ๐ค
lmao yeah didn't read it properly
do you guys have any tutorials/websites i should visit to get started with discord bot development?
best one you'll find -> https://fallendeity.github.io/discord.py-masterclass/creating-a-bot/
A hands-on guide to Discord.py
tysm
!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.
ye but where do i put it how do i do it?\
for the client
ive done this now what do i put in the brackets?
or whatever its called
discord.Client(intents=...)
its wrong
did u even read the contents of the embed
i dont know shit about python its from a tutorial
then i would recommend learning some python before attempting discord bots, discord bots arent exactly a beginner friendly project
is there a good tutorial atleast?
.
discord.Intents
!d discord.Intents
class discord.Intents(value=0, **kwargs)```
Wraps up a Discord gateway intent flag.
Similar to [`Permissions`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions), the properties provided are two way. You can set and retrieve individual bits using the properties as if they were regular bools.
To construct an object you can pass keyword arguments denoting the flags to enable or disable.
This is used to disable certain gateway features that are unnecessary to run your bot. To make use of this, it is passed to the `intents` keyword argument of [`Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client).
New in version 1.5.
bot = commands.bot(command_prefix=".",ย ย ย ย ย ย ย ย ย ย ย intents=discord.Intents.all())
The output just says
AttributeError: module 'discord.ext.commands' has no attribute 'bot'
it used to work but now it doesnt
commands.Bot
Says the same thing
nvm it works. i just uninstalled discord.py and installed it back
should i switch from discord.py to pycord?
what library is easier or better?
discord.py has everything py-cord does
py-cord was created when Danny, the mantainer of discord.py, announced that discord.py's development stopped
but it also, Danny, resumed the development of discord.py
Now, both libraries are great, but none of them are easy.
And I also guess that discord.py would be a better choice ๐คท
that is a subjective opinion.
I tried both libraries, pycord is easier to use on some things. How to create forward slash commands. And your Guide is better documented for beginners.
Use whatever you like
Yes, it is subjective, for me it is easier pycord but for others it is discord.py.
alright
ModuleNotFoundError: No module named 'discord_slash'```
was trying to add slash commands and got this error
discord-py-slash-command is a couple years outdated and had published a massive rewrite before it stopped receiving updates, hence why that module can't be imported
so i can't add slash commands?
i suggest using discord.py's built-in slash commands instead, or a fork like disnake
if you really want to stick with the same maintainer of discord-py-slash-command, interactions.py is their new package
and where exactly do i find that
ergh, unfortunately the dpy docs dont have a first-party guide to it so you'll have to look to third party guides and the examples on the repository
https://about.abstractumbra.dev/discord.py/2023/01/30/app-command-basics.html
https://fallendeity.github.io/discord.py-masterclass/slash-commands/
https://github.com/Rapptz/discord.py/blob/v2.3.2/examples/app_commands/basic.py
*there's a guide in the works
the interactions api reference is still good though
https://discordpy.readthedocs.io/en/stable/interactions/api.html#decorators
referring to Rapptz/discord.py#7654?
ok, the thing is im on replit ..
because its much more easier for me
i dont wanna download too many files
you already had discord.py installed in order to use discord-py-slash-command
if its v2.0 or above, that means you have native slash command support already
yea
you mean the discord_slash error? because of my first message, discord-py-slash-command published a massive rewrite and then stopped being maintained
don't use it if you have d.py 2.0+, disnake, etc.
^ check out these guides/examples of using discord.py's slash commands
kk
oh use pycord which has the slash commands already built in and no additional installations.
discord.py does too
I didn't know, when I used it I had to use external packages and it was difficult.
ill try to stick with discord.py
thing is gonna have to write the whole code from scratch ๐
just to add slash commands
but i believe its worth it
2.0 came out a couple years ago with its own slash command implementation, so you might want to re-look into it
yes, thanks for the information
some devs find the new commandtree stuff complicated, but imo i like how the implementation is separated into its own subpackage
yeah it's a lot more clean and easier to manage
unrelated question, i'm trying to figure out which active threads in a channel have a specific user in them to limit the number of threads a user can request, is there any detailed documentation on how thread members are cached by discord.py? or i guess how thread events work in general? i'm messing with it right now and it seems extremely finicky, just to name a few quirks:
- on startup,
thread.membersis empty until new members join the thread - when creating a thread, the owner isn't included in
thread.members - when joining a thread,
thread.membersis wiped and doesn't get re-populated, only updating for new members joining - when leaving a private thread, the thread isn't evicted from cache unless the bot has manage threads perm
official api docs don't seem to cover this, and i'd rather not spam.fetch_members()on a channel's active threads
Hy someone here, I am looking for a discord bot dev to work with me as partner
so im testing the slash commands and i got a few bugs/errors ill show one of them for now and the rest later on
discord.app_commands.errors.TransformerError: Failed to convert giannakis.og to Member```
!paste
If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.
if the member's been banned from the guild, you won't be able to get a member object for them
though that particular error would suggest you didn't sync your command, which would have made the option show a member list and prevent you from inputting an invalid member
gotten alot of errors from almost commands ive made so far
since i tried making them slash commands
would you like me to send the whole code of the test bot for you to see what i should fix up?
!paste
If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.
- embed() since your
colorargument is a string,if color == 0x8300FF:will never be true- you can pass a string to discord.Color.from_str() to convert strings into a color object that Embed can handle
- clear()
channel.purge()can take a few seconds to return and might exceed the 3s timeout for interaction responses, making your command appear to fail- i suggest you use interaction.response.defer() before purging to avoid the timeout, and then
interaction.followup.send()after purging is done
- i suggest you use interaction.response.defer() before purging to avoid the timeout, and then
- kick() should have a permissions check of some form, like
@app_commands.default_permissions(kick_members=True), to prevent abuse - ban() same as above
- unban()
: discord.usershould be: discord.User, but discord only shows users in the current guild anyway so this won't be useful- the best you can do is accept a string and loop through guild.bans() to find a name or user ID that matches their input, then use guild.unban()
- mute()
member.mute()isn't a valid method, you're looking for member.timeout() - unmute() same as above
- help() commands usually aren't needed for slash commands since users can already see all slash commands at once
- feedback()
channel.send_message()isn't a valid method, should be.send()
what exactly do i replace in unban with what you told me
because i didnt quite understand
Alternatively on unban you can do await guild.unban(discord.Object(user_id))
alr
if u wanna unban by username though, you'd have to loop through the bans like in the message above
What doesn't work specifically?
my whois command
^
Yes, but what in it?
one sec
You need to do url=member.avatar.url insetad instead of member.avatar
should i just import the rest of the commands i have and then send the code to check whats wrong one by one?
looking at source, set_thumbnail() casts the Asset to str() which returns the url, so other than it potentially being None it should work
may be
async def jjk_fight():
payload["content"] = "jjk fight"
requests.post(url, payload, headers=header)
time.sleep(10)
asyncio.run(jjk_fight())
I want to execute this every 10s, why its showing me
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
full traceback?
also what's the point of having an async function if you're not doing anything async inside of it
is name= "..." not name "..."
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 Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.
I really suggest not making commands that are thin wrappers over simple operations that are already available in the client. You're effectively degrading the security and auditing of them
so i should keep a simple prefix?
@hushed galleon ?
sorry for the ping btw
wili maybe?
@wanton current
Permissions and logging
ill add permissions later on
trying to see why most of the commands wont do as they are tol
told*
Which ones?
Well i ahve sent the link and i would recommend check them all because there might be mistakes i might have not noticed
well er, a few of them call methods that don't exist like channel.create(), role.create(), and interaction.send_message()
if you're able to, you should try out an IDE with type checking support since they can tell you about non-existent methods or improper usage of parameters without having to test your code manually
vscode's pylance extension has an optional type checking setting you can turn on:
The problem is that, some functions i call right after the function that i need to be waited on, have some information that is required from the previous function leading to a critical error because thie first function starts then the second function starts
The Verify command that is in the rework has the arguments of:
channel
log_channel
role
role2
remove_role
You can see in the screenshot which each one does, should I keep the max of 2 roles? Or do you think other servers would have a verification system that might need more than 2 roles needed for a person..?
Make it more configurable, perhaps make it summon a view instead?
Also, the following is valid and would reduce bloat:-
@app_commands.describe(
arg1=...,
arg2=...,
etc...
)
I knew you could do it that way, but I just never changed it lol
Yeah its a bad practice ik xD
Well yeah
I guess I could refactor all my commands to do it that way
Would be "better" in a sense lol. But what type of view are you thinking?
docstrings >>>>
You can't use docstrings to describe an argument...?
You can
You can??
Didn't know that, mb lol
I use docstrings to describe the commands only n show usage n examples.
You need a valid docstring format
Dpy supports uhhhhh
checks source
๐ญ
you need to be more specific here, there are a lot of way to do what you're trying to do
Is there a channel where I can get ideas for my bot?
i am using image embeds on all embeds, in the configuration command for my bot the set_icon function is called first before all other functions which are using image embeds, the set icon function is called using await set_icon(ctx) and i have some functions beneath it but before the icon can be set the functions below it are called (and since the icon is stored as a variable which is currently None) is returning an error
@client.event
async def on_message(message):
if "discord.gg" in message.content:
anti = db.find_one({"_id": message.guild.id})["antiraid"]
if anti is True:
white = db.find_one({"_id": message.guild.id})["whitelisted"]
logs = db.find_one({"_id": message.guild.id})["logschannel"]
if message.author.id not in white:
await message.delete()
await message.channel.send(f"{message.author.mention} You are not allowed to send links here.")
embed = discord.Embed(title="Anti-Raid", description=f"**{message.author}** has sent a link in {message.channel.mention}\n{message.content}", color=embedc)
c = await client.fetch_channel(logs)
await c.send(embed=embed)
else:
pass```
**im making an anti-link and the anti-link itself is working but i literally cannot use any commands while this code is in my workspace. may someone help me**
the logs are also working. just that none of my commands or events will work besides this event. please ping or dm me if you can help.
https://discordpy.readthedocs.io/en/stable/faq.html#why-does-on-message-make-my-commands-stop-working
@client.event will override any on_message event that comes before it and requires you to call await client.process_commands(message) for it to handle commands normally
i would go with the @client.listen("on_message") decorator instead cause it doesn't have those same gotchas
i spent a couple days writing up a bot to try out these thread-style tickets, setting it up is a bit janky but i think overall it looks neat
https://github.com/thegamecracks/theticketbot
this literally fixed it. i appreciate it so much.
it was such a struggle to get ts to work.
yo anyone here?
Look all the messages above..
can i ask sth?
Don't know, can you?
Just ask bro
TypeError: 'timeout_members' is not a valid permission name
got this error for adding the command to timeout members
!paste
If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.
here's the code: https://paste.pythondiscord.com/YJDQ
the error says it all?
well yeah but whats the correct permission?
mute_members?
because neither did that work
!d discord.Permissions
class discord.Permissions(permissions=0, **kwargs)```
Wraps up the Discord permission value.
The properties provided are two way. You can set and retrieve individual bits using the properties as if they were regular bools. This allows you to edit permissions.
Changed in version 1.3: You can now use keyword arguments to initialize [`Permissions`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions) similar to [`update()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.update).
Go through them
Then see if one is related to timing out (the description, not necessarily the attribute name itself)
:incoming_envelope: :ok_hand: applied timeout to @daring citrus until <t:1717492421:f> (10 minutes) (reason: duplicates spam - sent 4 duplicate messages).
The <@&831776746206265384> have been alerted for review.
can somebody explain how to use cogs?
await bot.load_extension("cogs.super_cog")
what does this do?
loads a cog
"cogs.super_cog" this is its position in a folder right?
cogs is the name of the folder and super_cog is the name of the python file?
That does not load a cog. That loads an extension. That's literally the method name
These are two entirely separate concepts
load_extension will load an extension based on module name. This is distinct from path or file name
ah okay, bold of me to assume their extension file had a cog
It's important to call out this distinction so people don't use the terms interchangeably, since they're not
thanks for the tip :)
why do I get this error when I call discord.ui.Button?
@discord.ui.Button(label="Test", style=discord.ButtonStyle.green)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: 'Button' object is not callable
it's button
yea fixed, now only 1 buttons is shoing up
import discord
from typing import Callable, Optional
class Pagination(discord.ui.View):
def __init__(self, pages):
super().__init__()
self.page = 0
self.pages = pages
# self.add_item(discord.ui.Button(label='<', style=discord.ButtonStyle.green, custom_id="prev"))
# self.add_item(discord.ui.Button(label='>', style=discord.ButtonStyle.green, custom_id="next"))
@discord.ui.button(label="<", style=discord.ButtonStyle.green)
async def prev_button(self, interaction: discord.Interaction, button: discord.ui.Button):
if self.page > 0:
self.page -= 1
await interaction.response.edit_message(content=self.pages[self.page])
@discord.ui.button(label=">", style=discord.ButtonStyle.green)
async def prev_button(self, interaction: discord.Interaction, button: discord.ui.Button):
if self.page < len(self.pages) - 1:
self.page += 1
await interaction.response.edit_message(content=self.pages[self.page])```
anyone know why only the next page button works
because you're overwriting the first function with the second one by naming them the same thing
oh I forgot to change the name ๐คฆ
oh also, I currently have 1 database for storing information on guild currency and shop stuff, if I want to make an inventory system, it is advices to start a new database, or to just make a new table?
table
alr bet
whats the right name for this error? raise TypeError(f'{key!r} is not a valid permission name.') TypeError: 'manage_server' is not a valid permission name.
manage_guild
alr thanks
how is this even possible? ``` @app.commands.default_permissions(manage_channels=True)
NameError: name 'app' is not defined
it works perfectly in other commands
app_commands instead of app.commands
shoot
lol
think ive got more errors coming soon
dw
these slash commands are a great feature but a pain in my ....
here's another errordiscord.app_commands.errors.CommandInvokeError: Command 'addrole' raised an exception: AttributeError: 'Interaction' object has no attribute 'send_message'
discord.app_commands.errors.CommandInvokeError: Command 'clear' raised an exception: NotFound: 404 Not Found (error code: 10015): Unknown Webhook```
discord.app_commands.errors.CommandInvokeError: Command 'createcategory' raised an exception: AttributeError: 'CategoryChannel' object has no attribute 'create'
actually should i just send the whole code to see what other issues there are instead of sending one by on?
https://paste.pythondiscord.com/X2IQ @wanton current here
interation.response.send_message
followup before responding
no such thing
so no command for creating category?
would you mind checking the code i send? maybe find some other errors
@client.tree.command(name="lockall", description="Lock all channels")
@app_commands.default_permissions(manage_channels=True)
async def lockall(interaction):
await interaction.channel.set_permissions(interaction.guild.default_role, send_messages=False)
await interaction.send_message(f"Locked all channels")
@client.tree.command(name="unlockall", description="Unlock all channels")
@app_commands.default_permissions(manage_channels=True)
async def unlockall(interaction):
await interaction.channel.set_permissions(interaction.guild.default_role, send_messages=True)
await interaction.send_message(f"Unlocked all channels")
``` i dont see how you expect this to affect all channels
yea it will only "lock" the channel that the command was sent in not all of the channels
i hope you are aware of this
not so hard to see that lock is the same as lockall and unlock is the same as unlockall
just the messages sent differ
yeah nvm it doesnt work for all channels ๐ yeah you have a point
my bad i thought it actually worked.
after the developer portal update i cant find out how to add my bot to my server. when i try and select a guild install it wont let me save changes and keeps saying Private application cannot have a default authorisation link
i did try and generate a ont time auth url but when i put the link in my browser i get the error installation type not supported for this application
when i try to unban a user it gave me this error discord.app_commands.errors.CommandInvokeError: Command 'unban' raised an exception: NameError: name 'guild' is not defined
tbh i just went on discord dev portal
and its my first time seeing this installation so
but the oauth2 tab looks unchanged
do you have to do something in installation tho
it is a good feature though instead of just typing the command to invite, you go to it's profile to do so
wasnt that a thing before?
i dont have a clue ive been trying all types of stuff but nothing works
i had the invite button in bio for a year now in my bot
try the link i sent
well i discovered it a week ago
its different to the dev portal now
๐
like i said oauth2 tab looks the same
anyone?
you generate the url paste it in the browser and select guild where to add to
i tried that but it says installation type not supported for this application
how does your installation tab look like
you dont define guild?
thanks that worked
!e ```py
guild.some_method()
:x: Your 3.12 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "/home/main.py", line 1, in <module>
003 | guild.some_method()
004 | ^^^^^
005 | NameError: name 'guild' is not defined
how is it supposed to know what guild is you never told it
same with the user_id ?
you never defined this
so what exactly do i type to define them
k
let me see
nice it worked!
heya got another issue
async def avatar(interaction: discord.Interaction, member: discord.Member):
embed = discord.Embed(title=f"{member.name}'s Avatar", color=0x8300FF)
embed.set_image(url=member.avatar)
await interaction.response.send_message(embed=embed)```
so its not sending the image and its sending only the embed
discord.app_commands.errors.CommandInvokeError: Command 'avatar' raised an exception: AttributeError: 'Interaction' object has no attribute 'send_message'
And what's the traceback? It should have your own code in it
try member.display_avatar, that one worked for me
also, anyone know how to format an embed in columns of 2
add_field has an inline kwarg
You can mess with that
If you can still add an empty field by setting the name and value to \u200b
ik but, when I make it so that odd numbers are inline=True, and even are inline=False, it just gives me a straight line
if number % 4 == 0 and number != 0:
pages.append(new_page)
new_page = discord.Embed(title=name, description=description)
new_page.add_field(name=f"{item_dict['item_name']}: ${item_dict['item_price']}",
value=f"{item_dict['item_description']} (Stock: {item_dict['item_quantity']})")
elif number % 2 != 0:
new_page.add_field(name=f"{item_dict['item_name']}: ${item_dict['item_price']}",
value=f"{item_dict['item_description']} (Stock: {item_dict['item_quantity']})", inline=True)
else:
new_page.add_field(name=f"{item_dict['item_name']}: ${item_dict['item_price']}",
value=f"{item_dict['item_description']} (Stock: {item_dict['item_quantity']})", inline=False)```
I get something like this
what do i replace
mine just looks like this
@tree.command(name="avatar", description="Get a user's avatar")
@app_commands.describe(member='member')
async def avatar(interaction: discord.Interaction, member: discord.Member = None):
if member:
await interaction.response.send_message(member.display_avatar)
return
await interaction.response.send_message(interaction.user.display_avatar)```
member = member or interaction.user
await interaction.response.send_message(member.display_avatar.url)
works too
that's why I said #discord-bots message
# first line
add_field(), add_field()
# fake third field for first row
add_field(name="\u200b", value="\u200b", inline=True)
# second line
add_field(), add_field()
iirc
thing is i want it to be an embed
this error message doesn't seem to match your code, can you post the full traceback?
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 Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.
i've been trying to make this code work without any errors since yesterday till midnight and havent even finished it, always been having different errors. so tired
can you send the traceback too?
starting from Traceback (most recent call last): or something like that
Yeah, your code doesn't match your error
Can I share my own work here?
?
I made a discord bot based on a multimodal language model
But I'm not doing very well yet
as long as it doesn't fall under advertising or another rule, that should be fine
Is posting a github link here considered advertising?
just posting a github link?
ya
nothing else?
Then ask for advice
imo i would think it's advertising if it's sent without context or trying to promote the usage of some project
think that's fine
ok
Is there any way other than changing the IP so that the discord robot can play YouTube music normally?
I currently use lavalink
!ytdl cant help with that here sorry
Per Python Discord's Rule 5, we are unable to assist with questions related to youtube-dl, pytube, or other YouTube video downloaders, as their usage violates YouTube's Terms of Service.
For reference, this usage is covered by the following clauses in YouTube's TOS, as of 2021-03-17:
The following restrictions apply to your use of the Service. You are not allowed to:
1. access, reproduce, download, distribute, transmit, broadcast, display, sell, license, alter, modify or otherwise use any part of the Service or any Content except: (a) as specifically permitted by the Service; (b) with prior written permission from YouTube and, if applicable, the respective rights holders; or (c) as permitted by applicable law;
3. access the Service using any automated means (such as robots, botnets or scrapers) except: (a) in the case of public search engines, in accordance with YouTubeโs robots.txt file; (b) with YouTubeโs prior written permission; or (c) as permitted by applicable law;
9. use the Service to view or listen to Content other than for personal, non-commercial use (for example, you may not publicly screen videos or stream music from the Service)
yo guys, im making an inventory system where people can buy stuff. I currenly have a database for currency handling and shop info, it is better to create a seperate database, or make a new table to store inventory info?
One database, many tables. That's how it should be
#databases might be better fit for this however
bet bet, was a lil too worried if my database might get overloaded or something
Nah
If you're at a point where your database is getting overloaded you have bigger problems
bruh, how am I being rate limited ๐ญ
can you make certain users immune to @commands.cooldown(commands_per_cooldown, cooldown_seconds, commands.BucketType.user)
if you're using discord.py, you'll need a dynamic cooldown instead
!d discord.ext.commands.dynamic_cooldown
@discord.ext.commands.dynamic_cooldown(cooldown, type)```
A decorator that adds a dynamic cooldown to a [`Command`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Command)
This differs from [`cooldown()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.cooldown) in that it takes a function that accepts a single parameter of type [`Context`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Context) and must return a [`Cooldown`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.Cooldown) or `None`. If `None` is returned then that cooldown is effectively bypassed.
A cooldown allows a command to only be used a specific amount of times in a specific time frame. These cooldowns can be based either on a per-guild, per-channel, per-user, per-role or global basis. Denoted by the third argument of `type` which must be of enum type [`BucketType`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.BucketType).
If a cooldown is triggered, then [`CommandOnCooldown`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CommandOnCooldown) is triggered in [`on_command_error()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.discord.ext.commands.on_command_error) and the local error handler.
A command can only have a single cooldown.
New in version 2.0.
ah, dpy forks have the same deco too
hii i need help for discord dev portal
what do you need help with?
how can i get the url of my app bot?
to invite?
yeah
Go to the OAuth2 tab and scroll down to the "OAuth2 URL Generator", and then click the "bot" checkbox (and "application.commands" if your bot uses slash commands), and then select the permissions the new box that comes up when you select "bot".
and then the generated url is at the bottom
Turn off this in your Bot settings
ok and i can't turn it on???
It's probably not needed for what you're trying to do
hehe, tysm
nw
yo guys, whats a good way to log what discord commands were used? Im currently using a discord webhook but im not sure if thats a good way
why are you logging them
currently only me and a few people are testing the bot rn before we start seriously testing it, I wanna use it to see if commands used match up with data changed in the database, helped me catch some bugs quite a few times
i'd recommend a db and a command that paginates through them rather than a webhook, that way you can see them wherever (in dms, another server, etc) and then just store the relevant info in a table made for ran commands
ooh thats a good way prolly, ty
what does an anime bot do
Anime
Is there any way to handle all errors instead of using Forbidden or HTTPException?
I want to use try-except for async for msg in message.channel.history(limit=1, before=message):
Exception?
Though be careful with that one, it quite literally catches all errors
There's also DiscordException, which is for all exceptions of the library
What is the different between Exception and discord.DiscordException?
The former is any exception in python and the latter is a base exception for the disord.py (or fork) lib
What else exception could there be?
I get that
see the hierarchy at the bottom
Is it necessary to use pass to execute remaining code after the exception?
Or will it just raise the error and execute the rest of the code?
code?
try:
async for msg in message.channel.history(limit=1, before=message):
except discord.Forbidden:
print(
f"Missing permissions to fetch message history.")
except discord.HTTPException as e:
print(f"HTTP error while fetching message history.")
print("I want to execute this code after the try-except.")```
yeah, as long as you don't raise or return inside the except, it will continue running
Why have I seen people use pass after each exception then?
Just a habit?
since
except:
print("hi")
```Is invalid in python
if u wanna do nothing in case of an exception
you need something in the clause
No no, they still print an error message and pass
there's no reason to pass then
it's the equivalent of:
.catch({})
// or
try {
// abc
} catch {
// doing nothing
}
in js
Is there any way to retry the try-except in case an exception was raised?
wdym?
:incoming_envelope: :ok_hand: applied timeout to @tawny hull until <t:1717538183:f> (10 minutes) (reason: duplicates spam - sent 4 duplicate messages).
The <@&831776746206265384> have been alerted for review.
Let's say we try to fetch the message with async for msg in message.channel.history(limit=1, before=message): and we get a discord.HTTPException error. How can we retry fetching the message again after 10 seconds?
like
async def fetch_msg(..., message: discord.Message) -> Optional[discord.Message]:
msg = [i async for i in message.channel.history(limit=1, before=message)]
return msg[0]
async def f():
msg = None
while not msg: # should probably set some timeout so it stops eventually, after x retries, or x seconds
try:
msg = await fetch_msg(...)
except discord.HTTPException:
pass
probably something like this im not sure
Feels like there should be an easier way
for i in range(0, 10):
try:
async for msg in message.channel.history(limit=1, before=message):
break
except discord.Forbidden:
print(f"Missing permissions to fetch message history. Sleeping for 60 secs before next try.")
await asyncio.sleep(60)
continue
except discord.HTTPException as e:
print(f"HTTP error while fetching message history. Sleeping for 60 secs before next try.")
await asyncio.sleep(60)
continue
My bad
Better now?
this would break on the first iteration
you'd probably want to break inside the try: clause
There we go
you didn't hide your token correctly and posting the code is better then a screenshot
show your imports and code
!paste
If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.


