#discord-bots
1 messages · Page 307 of 1
Am I being dumb?
Specifies if the user is a bot account.
it does give me the role but it dont work with old messages like after restarting bot old messages dont give role
Ah so it'd be if user.bot == True or false
Yea I'm just dumb today I guess lol
it was like that but it didnt work but the one you gave work
lol
but it dont work on messages after starting the bot
like i setup reaction role on a message after restartnig the bot the message will no longer work with bot
I think the messages have to be cached or you have to fetch the message. Not 100% sure on that tbh
nvm ur not even in it
It is saved on a db
The message ID prob is
If you actually read the docs I shared you would know the message would have to be cached
!d discord.on_raw_reaction_add
discord.on_raw_reaction_add(payload)```
Called when a message has a reaction added. Unlike [`on_reaction_add()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_reaction_add), this is called regardless of the state of the internal message cache.
This requires [`Intents.reactions`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.reactions) to be enabled.
So I just have to use raw instead of normal
I'll do it after the power is back on cause it's off right now
hi oauth2 question, what are all the endpoints that accept an access_token (bearer token)? i thought they were all the enpoints with a @me but that's not true
this is a chill server
i belive it depends on what scopes you enable https://discord.com/developers/docs/topics/oauth2#shared-resources-oauth2-scopes
so, for some reason some commands work and some don't. I've marked with red the commands that don't work. What did I do wrong?
one sec
from nextcord.ext import commands
class basic(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.command()
async def test(self, ctx):
await ctx.send("This is a test!")
class basic(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.command()
async def help(self, ctx):
await ctx.send("If you need help with the bot, please contact cpt_w0lf on Discord, thank you! ")
class basic(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.command()
async def wiki(self, ctx):
await ctx.send("Here is the main page of the Stellaris Paradox Wiki site: https://stellaris.paradoxwikis.com/Stellaris_Wiki ")
class basic(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.command()
async def patch(self, ctx):
await ctx.send("Stellaris is currently running on patch 3.9.2 on PC!") ```
this is the entire code I've written for the commands
It is most likely because you're overriding the previous classes
so I have to write them in a different class?
no just add them to one class
You can have multiple commands in the same cog
so, how do I solve this?
cause the first and last command work, but those in the middle don't

aight
Here is a short example of how to use discord.py's slash commands as well as general information on them:
https://gist.github.com/AbstractUmbra/a9c188797ae194e592efe05fa129c57f
This currently covers free commands and groups at the Bot level, as well as within Cog classes.
It also includes information and gotchas relating to syncing and whatnot.
discord.py 2.0+ slash command info and examples. GitHub Gist: instantly share code, notes, and snippets.
can i get a TL;DR?
no
fair enough
it is already pretty small imo
but i cant find a single reference to slash commands in that forum
are cogs necessary for slash commands?
its all about slash commands?
no you can use bot.tree.command() decorator
tfym lol
Nothing to do with slash commands huh
class constructor
tfym?
the f you mean
the fuck you mean
make sense

Class constructor. If you add args into the __init__ they'll be required when constructing the class
idk why it does an error
i suck at this bro 😭
You completely ignored what I said

Nice
you def need to learn python before doing a discord bot
I DID 😭
Yes, and I told you to do it in setup_hook or create a command for it 💀
tree() isn't a thing
uhhh
It's an event
isnt tree an attribute from bot?
!d discord.ext.commands.Bot.tree
Attr, yes
property tree```
The command tree responsible for handling the application commands in this bot.
New in version 2.0.
Not a function/method
he prolly has tree = app_commands.CommandTree(...)
I don't think he did anything tbh
i copied everything from stack overflow yall 😭
Do you have to subclass your Bot instance to overwrite setup_hook or would a normal event decorator suffice
what are these gigantic words bro
can you do something like
@bot.event
async def setup_hook():
pass
``` ?
That's what I'm asking
that's why it is recommended to learn python before using discordpy
please tell me what that does 😭
Wasn't a question for you. The guide gives you a sync command to use
it literally does nothing
Actually read the guide, then ask questions
You're asking quesions before reading the guide, and it shows
okay okay
If you don't know what a cog is focus on this example
https://gist.github.com/AbstractUmbra/a9c188797ae194e592efe05fa129c57f#file-08-free_function_commands-py
discord.py 2.0+ slash command info and examples. GitHub Gist: instantly share code, notes, and snippets.
Isn't that what you just sent me 33 minutes ago
34 now
I need to give this a good read
AHA
CommandTree.sync
Is that what I'm supposed to look for 😭
It's an example inside the guide
?
I linked you a specific example on how to create slash commands outside of cogs
They're very similar to prefixed commands
THEN WHY ARENT THEY AS SIMILAR 😭 😭
why do i have to sync them in on_ready 😭
:0
i think i struck gold
is this what i need?
Did u just copy and paste code?
Please consider reading the examples given below
Here is a short example of how to use discord.py's slash commands as well as general information on them:
https://gist.github.com/AbstractUmbra/a9c188797ae194e592efe05fa129c57f
This currently covers free commands and groups at the Bot level, as well as within Cog classes.
It also includes information and gotchas relating to syncing and whatnot.
NOTE: This will be migrating to https://about.abstractumbra.dev/ as soon as I can be bothered to finish it.
My site for random things and stuff. Including a custom pip index and walkthroughs, both for discord.py!
Did u read the examples that I gave you?
this?
discord.py 2.0+ slash command info and examples. GitHub Gist: instantly share code, notes, and snippets.
That one above
Ok take your time
so
there is no reading involved
and i have the coding power of a potato
so i need to talk about my findings
here
You don't, and nobody said you should
Ok. And also don't auto sync and the way u are doing it is not the proper way
It specifically tells you to not sync your commands in on_ready, so I'm not sure where you're getting the idea that you should
copy_global_to only copies the global commands to your guild. It doesn't sync it for you
why do i need all that for slash commands
Slash commands are sent to discord
arent normal commands sent to discord too
No
Prefixed commands are not
Prefixed is handled internally by dpy. Slash commands are handled by Discord directly
why arent slash commands handled by dpy
Because they're integrated in the UI
OHHHHHHHHHHHHHH
How would they appear in Discord's UI if Discord isn't aware they exist
im gonna be busy for the whole entire day but later today i can code review it
!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.
ty dear, i'm cooking the best oauth2 extension out here
let him cook 🗣️

@discord.ui.button(label="Claim Ticket", style=discord.ButtonStyle.primary, custom_id="claim")
async def claim(self, interaction: discord.Interaction, button: discord.ui.Button):
user_name = interaction.user.name
if interaction.channel.name == f"{interaction.user.name}-ticket":
embed = discord.Embed(title=f"You can't claim the ticket, <@{interaction.user.id}>", color=0x7289da)
await interaction.response.send_message(embed=embed)
else:
await interaction.message.edit(view=ClaimButtonTwo())
embed = discord.Embed(title=f"The ticket claimed by {interaction.user.name}",color=0x7289da)
await interaction.response.send_message(embed=embed)
await interaction.channel.edit(topic=f"Claimed by {interaction.user.name}")
why the the channel name is come_-ticket and this is equal to {interaction.user.name}-ticket and this isnt work?
ok
can someone send me the code for copying someone elses messages like if they say “wsg” then ur account copies it and sends it too more like mocking
no, we dont code for you
well how do i figure it out
Do you want to do it in a command?
So a user will do something like !mock you're so dumb, and the bot replies with you're so dumb?
yes exactly!
but i want to choose like who to mock and let the process do it swlf
like for example, i do !mock @slate swan And my account starts sending the same messages as him
Would it just be 1 message or would it continually mock their messages?
It would be great if you could help me bro i wasted so much code
i have been trying for like 3 hours:(
and im kinda new so i dont know
i have tried so many stuff and it just wont work
it would he appreciated if you could help
How long are you looking at? Just a couple of minutes or hours/days
like 2 minutes
Okay, that makes it easier
What code do you have so far?
I deleted all of it:(
i gave up like 10 minutes ago
after continuous trying man
i can send you one i saved tho
If you want
okay come dms if you want
Do you know how to create them?
What the command?
Yes
Yeah i know that
Alright, write one real quick and send the code
Send it in here
ok
There’s no point in using DMs
import discord
from discord.ext import commands
bot = commands.Bot(command_prefix='!')
@bot.event
async def on_ready():
print(f'Logged in as {bot.user.name}')
@bot.event
async def on_message(message):
if message.author == bot.user:
return
if message.author.id == YOUR_USER_ID:
channel = bot.get_channel(YOUR_CHANNEL_ID)
await channel.send(message.content)
await bot.process_commands(message)
bot.run('YOUR_BOT_TOKEN')
I dont want it on a bot account tho
because i cant really add it into other servers
Idk if the code is right
Well unfortunately we don’t help people create self bots :/
Not your current code, but we can get it working
Would be appreciated mane
Do you know about the commands extension?
No what is that
It’s the proper way to create prefixed commands with discord.py. Creating them in on_message has a lot of downsides
Let me find you the docs and some examples real quick
Okay man thank you
I gotta leave so I can't help but here's a docs
Here’s a structure I would recommend
Create a bot variable with the list of people you want to be mocking
The command will add a person to that list
In your on message you check if they’re in your list, and if they are you send the message
Can someone explain cogs to me?
?tag cogs
Cogs are a pretty nifty way to organize your bot's commands and stuff. cogs derive from the commands.Cog class found in the commands ext and are usually placed in separate files and loaded as extensions (see ?tag cogs vs ext)
Cog docs > https://discordpy.readthedocs.io/en/latest/ext/commands/cogs.html
Cog example > https://gist.github.com/pinheaded/ac880263084a65b8d2f769c1fa46a3d7
?tag cogs vs ext
Difference between cogs and extensions
Extensions are files that are loaded, think of them as modules that the discord.py library imports when you call load_extension. After the import happens, a setup function is called, and is passed the Bot instance that it was loaded into....essentially module.setup(bot). That is it, there is no more to extensions...typically this setup function calls add_cog which will be described next, however there is no requirement that they do so.
A Cog is a class that inherits from commands.Cog and is added to the bot's list of cogs through add_cog, these classes typically house commands and act as a "category" for these commands. It can also house listeners for events such as on_message or on_member_join, etc.
tl;dr Extensions are imported modules, cogs are classes
hmm
so what would you rather?
Cogs ftw
hey, looks like that my discord bot is only seeing themselves in a guild? they have the intent set to see members, but it's being funky
figured it out -- turns out i had to specify discord member intents in the file's intents, strange that it was working yesterday but didn't today
Feel like ext.commands is what you would want so you don't have to shove it in on_message events
this is in DMs only, just for me, and i don't think bots are capable of integrating commands in DM channels beyond on_message events
Prefixed commands work in dms

Yea as long the bot created the dm, it will listen to messages passed in within dms
Slash commands is a different story that I never tested, but I've tested prefixed commands and know it works
noted
nah
forgot to remove my token LMAO
Traceback (most recent call last):
File "C:\Users\brian\PycharmProjects\NoteWizard\main.py", line 16, in <module>
@bot.event()
^^^^^^^^^^^
TypeError: Client.event() missing 2 required positional arguments: 'self' and 'coro'
import colorama
from colorama import Fore, Style
import discord
from discord.ext import commands
TOKEN = ""
bot = commands.Bot
class NoteWizard(commands.Bot):
def __init__(self):
super().__init__(
intents=discord.Intents.all()
)
@bot.event()
async def on_ready():
print(f"{Fore.GREEN}Note Wizard ONLINE{Style.RESET_ALL}")
game = discord.Game("Playing Music")
await bot.change_presence(status=discord.Status.online, activity=game)
async def setup_hook(self):
await self.load_extension("cog_ext")
NoteWizard().run(TOKEN)
First, if you're subclassing commands.Bot() you'll need to create cogs
bot = commands.Bot makes literally 0 sense
I know you did that because when you tried to create the event you got an undefined/attribute error
but
You'll also want to put setup_hook inside your NoteWizard class as outside of the class it won't be called
but, like @bot.event()
?
The error doesn't matter
To fix your other issues the event will be removed anyway
Furthermore, you shouldn't be changing your presence in on_ready for a couple of reasons, just do it in setup_hook or better yet, do it in your Bot() constructor
And, unless you do need every single intent you shouldn't be using all()
@final iron stop making my life hard
OMG WHAT IS THAT CODE, if im being honest, it looks like someone who knows nothing about python made it cuz like bot = commands.Bot???
also the error u were looking for was that bot.event() calls it even tho its meant to be bot.event
It won't ever be called anyway
Stop making me feel like im stupid
I WASNT TALKING TO YOU
its just easier tbh
asuming you did bot = commands.Bot() or whatever u named the subclass
if u want help from someone only then dont ask here?
Im jokimg
He didn't construct the class
import colorama
from colorama import Fore, Style
import discord
from discord.ext import commands
TOKEN = ""
class NoteWizard(commands.Bot):
def __init__(self):
super().__init__(
intents=discord.Intents.all()
)
async def setup_hook(self):
await self.load_extension("cog_ext")
NoteWizard().run(TOKEN)
@final iron Look better?
ye
looks way better
Sure
What else do I need to change
Where would I put the on_startup event?
Nothing
the one that prints that its online?
Doesn't exist
It doesn't exist though
It's not a thing
You cannot add it
Doesn't exist
what I just had?
if a on_startup event in ur meaning means when the bot starts up on, then you are talking about setup hook
@bot.event()
async def on_ready():
print(f"{Fore.GREEN}Note Wizard ONLINE{Style.RESET_ALL}")
setup hook only runs once and then is when the bot starts up
This
on_ready is different from on_startup
that is an on_ready and can be fired mutliple times
Anyway, you would have it in a cog
!d discord.on_ready
discord.on_ready()```
Called when the client is done preparing the data received from Discord. Usually after login is successful and the [`Client.guilds`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.guilds) and co. are filled up.
Warning
This function is not guaranteed to be the first event called. Likewise, this function is **not** guaranteed to only be called once. This library implements reconnection logic and thus will end up calling this event whenever a RESUME request fails.
read the bottom part
No, you just shouldn't be doing anything in it aside from printing the bot is online really
Yeah
so if ur putting smth that u only want to happen once, then you should prob put in setup_hook
what? and what class
class NoteWizard(commands.Bot):
def init(self):
super().init(
intents=discord.Intents.all()
)
so what are you going to put in it?
I meant under it
same thing
But the on_ready event.
ok sure thats fine just dont put the decorator
but if you want, you can put it in a cog as a listener
which is more effiecent?
main file would be better
ok sure
In my opion since it'll be a little more organized.
i disagree but if thats what u wanna do then sure
and the decorator is the @bot.event?
yes
how come?
Again like you said I'm just a clueless person that has no idea how to use Python.
no no its just my opion that wont change the outcome of the bot
but if u wanted to hear what i would do, i would create a file in the cogs folder called events.py and put all my events in there that way its easier but thats just how i would do it
Wow, your a genious
But since im not that smart
that'll just drive me insain
ty?
if u want i can help u set it up
The only thing is that for future endevors
Eh what the fuck, alright help me with it
Yeah
and a file inside of it called events.py?
oh mb i meant cogs folder
haha 😅
so create a cogs folder and inside of that create a file called events.py or whatever u wanna call it
?
no no u want a folder called cogs
and inside of that folder u want that events.py file
?
yes
alr
ok show me ur main.py file code (also u can delete cog.py)
thats used for all client sided events such as on_start and such wise?
class WizardCog(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.Cog.listener()
async def on_message(self, message):
if message.guild and message.guild.me.guild_permissions.ban_members:
await message.author.ban(reason="no speek") # very good reason
# doing something when the cog gets loaded
async def cog_load(self):
print(f"{self.__class__.__name__} loaded!")
# doing something when the cog gets unloaded
async def cog_unload(self):
print(f"{self.__class__.__name__} unloaded!")
async def setup(bot):
await bot.add_cog()
But what about all this in my cog.py file?\
This is my main.py
import colorama
from colorama import Fore, Style
import discord
from discord.ext import commands
TOKEN = ""
class NoteWizard(commands.Bot):
def __init__(self):
super().__init__(
command_prefix="w.",
intents=discord.Intents.all()
)
async def on_ready(self):
print(f"{Fore.GREEN}Note Wizard ONLINE{Style.RESET_ALL}")
async def setup_hook(self):
await self.load_extension("Cog.ext")
NoteWizard().run(TOKEN)
hmm
okay done
now u wanna add ur on_ready as a listener as u did with ur on_message
and with ur setjup func in ur events.py file, make sure u do await bot.add_cog(WizardCog(bot))
you want the load and unload thing also?
wym
# doing something when the cog gets loaded
async def cog_load(self):
print(f"{self.__class__.__name__} loaded!")
# doing something when the cog gets unloaded
async def cog_unload(self):
print(f"{self.__class__.__name__} unloaded!")
^ that
import colorama
from colorama import Fore, Style
import discord
from discord.ext import commands
class WizardCog(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.Cog.listener()
async def on_start(self):
print(f"{Fore.GREEN}Note Wizard ONLINE{Style.RESET_ALL}")
async def cog_load(self):
print(f"{self.__class__.__name__} loaded!")
async def cog_unload(self):
print(f"{self.__class__.__name__} unloaded!")
async def setup(bot):
await bot.add_cog(WizardCog(bot))
looks all good with you?
wonderful
in the brackets of the listener put in "on_ready" that way it knows that ur talking about on_ready and not on_startup
@commands.Cog.listener(on_ready)
async def on_ready(self):
print(f"{Fore.GREEN}Note Wizard ONLINE{Style.RESET_ALL}")
like that? I dont think thats what you meant
@commands.Cog.listener("on_ready")
async def on_startup(self):
cuz on_startup doesnt exist like told before
hm
so when u put in the event in the brackets, then discord knows what event ur talking about
wow, how the fuck am I going to manage to make a bot
wait where would I be putting all my commands?
More like discord.py 🥱
Why are the cog_load and cog_unload defined in an event, anyway?
I was using a github example tbh
Im a dumbass see and not smart.
thats for an event not command
yeh
why I asked
u want slash or prefixed?
slashed
then u would create app_commands
Any
u can create a new file just for app commands
would it be too complex to add a new file
not rlly
It would be the same for every extension file
later on it would be easier to find the app commands
Under cogs or under the project directory
Anywhere you want it to be
if ur gonna create a new file then just do it under cogs
Mb, this sticker may trigger some epileptic person 😔
mhm, made sense
so would I do the decorative?
huh?
u would use @app_commands.command()
!d discord.app_commands.command
@discord.app_commands.command(*, name=..., description=..., nsfw=False, auto_locale_strings=True, extras=...)```
Creates an application command from a regular function.
instead of bot.tree.command
!d interactions
Do you mind explaining the whole
async def ping(interaction: nextcord.Interaction):
in this interaction example I found via tge discord.py api
@bot.slash_command(guild_ids=[TESTING_GUILD_ID])
async def ping(interaction: nextcord.Interaction):
"""Simple command that responds with Pong!"""
await interaction.response.send_message("Pong!")
That doesn't look like discord.py
uhh, yeah
This is not discord.py's interaction implementation, by the way
Isn’t discord.py
Nextcord has a different implementation
whatever this bitch told me
Ignore it. It’s a different library
!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.
@dire mason
come the fuck on
?
I don't appreciate this kind of language very much
what
oh sorry frick
how come you find it soo easily, and it becomes sooo hard for me
its pretty easy when u use it
cuz i normally typehint interaction : discord.Interaction
so its very easy to find
Im finding soo many features that I want to use, but I'm making a music bot so I cant use them because theyre not used for it.
ok..
i keep getting a timeout error here and i dont know why
@bot.command()
async def wordbomb(ctx):
await ctx.send("Do you want to play Word Bomb? React with 👍 to join!")
def check(reaction, user):
return user != bot.user and str(reaction.emoji) == '👍' and reaction.message.id == ctx.message.id
try:
reaction, user = await bot.wait_for('reaction_add', timeout=15.0, check=check)
except TimeoutError:
await ctx.send('No one joined the game. The game has ended.')
else:
players[user] = 1
await ctx.send(f"{user.mention} has joined the game!")``` (this isn't the full code btw)
Are you trying to wait for a reaction to be reacted to the bot's or the command author's message?
the bots message.
def check(reaction, user):
return user != bot.user and str(reaction.emoji) == '👍' and reaction.message.id == ctx.message.id
You're checking for it in the command message (ctx.message.id)
ohhhhh
Hey i have one more question, how would i make it so more then 1 person could join in the 15s?
nvm i got it
Use external lib for music bot simple 
yeah like wavelink or lavalink
Mhm
And?
How would you check if the user already has a interaction with you? I want to see if they do and if they do I want to update the previous reply.
In the context of music bots, you need to be aware that streaming from YT, Spotify, or any other popular streaming sites prohibits streaming content from their sites. This also violated Discord TOS, so Discord has been lately taking aggressive action to take down bots who offer these services. (Case study: See why Groovy got shut down)
So what, how the hell do you host music then?
You don't
!ytdl for YouTube
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)
So they hate discords use of theyre music
These streaming services are the juggernauts in this field, and they have the ability to file lawsuits and DMCA strikes and copyright strikes. So unless you want to hire a lawyer and attempt to win a losing battle, it's just best not to even bother with it
Copyright....
THIS IS NOT LEGAL ADVICE
If you're making a "music bot", you should probably consider the implications on the terms of service you have agreed to.
- Redistributing copyrighted material (such as music) without the permission of the copyright holder violates international copyright law.
- Essentially all popular streaming services (YouTube, Spotify) explicitly forbid in their TOS any redistribution of the content they host without their permission.
- Discord developer TOS (which you have agreed to) forbid you using your bot to violate law or break the terms of service of other platforms, which applies to points 1 and 2 above.
- Discord has been taking increased action against bots violating these terms and has said this is not allowed in no unspecific wording.
Do with this information what you will, but consider the fact that organizations with far more money and power will put mounting pressure on discord if people continue to use bots to violate their copyrights.
that's copyright breach, artists don't get paid for what they do this way
Yeah
My biggest tip for bot devs is if you want to make a good bot, make something original that solves an issue or aids with something. Ask around in communities and develop features that help aid or solve that problem. Just like a good essay, you need to know your audience before you make the feature
A good example is Gnome's TTS Bot. The problem being that muted users were getting ignored in no-voice-channels, and users were also getting ignored in the text channels within voice channels. Now with TTS Bot, all you need to do is let that bot into your server, join a vc and run the command to join that server, and then speak in the text channels within the voice channels. Although robotic sounding, now others can listen to your ideas or what you have to say
Similarly, I developed a simple module aimed towards larger servers just like this one that aims to fix an issue that I had to deal with for over an year
paragraph pro
!d discord.ext.commands.Bot.setup_hook
await setup_hook()```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
A coroutine to be called to setup the bot, by default this is blank.
To perform asynchronous setup after the bot is logged in but before it has connected to the Websocket, overwrite this coroutine.
This is only called once, in [`login()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.login), and will be called before any events are dispatched, making it a better solution than doing such setup in the [`on_ready()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_ready) event.
Warning
Since this is called *before* the websocket connection is made therefore anything that waits for the websocket will deadlock, this includes things like [`wait_for()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.wait_for) and [`wait_until_ready()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.wait_until_ready)...
That applies to any business
Pretty much. It boils down to Mircoeconomics in essence
@bot.command()
async def set_avatar(ctx, url):
if ctx.author.id in owners:
await bot.user.edit(avatar=url)
await ctx.message.add_reaction("✅")
else:
await ctx.message.add_reaction("🔒")
why this command not working?
that's a very vague response. Short answer is probably that your bot doesn't have the perms to add reactions
its administartor + Im setting a correct avatar link in command also no errors
So what part isn't working
the avatar not changing
So is your author id within the owners list? Also you can just use @commands.is_owner to allow for the owner of the bot only to execute the command
yes
!d discord.ClientUser.edit it doesn't say that you are allowed to use just url
await edit(*, username=..., avatar=...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Edits the current profile of the client.
Note
To upload an avatar, a [bytes-like object](https://docs.python.org/3/glossary.html#term-bytes-like-object) must be passed in that represents the image being uploaded. If this is done through a file then the file must be opened via `open('some_filename', 'rb')` and the [bytes-like object](https://docs.python.org/3/glossary.html#term-bytes-like-object) is given through the use of `fp.read()`.
The only image formats supported for uploading is JPEG and PNG.
Changed in version 2.0: The edit is no longer in-place, instead the newly edited client user is returned...
though weird that you didn't get ValueError for wrong format then
Might have an eh
I used the command in another project and its showed this error
[2023-09-29 02:03:37] [ERROR ] discord.ext.commands.bot: Ignoring exception in command set_avatar
Traceback (most recent call last):
File "C:\Users\Hadi\PycharmProjects\test something\venv\Lib\site-packages\discord\ext\commands\core.py", line 235, in wrapped
ret = await coro(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Hadi\PycharmProjects\test something\main.py", line 123, in set_avatar
await bot.user.edit(avatar=url)
File "C:\Users\Hadi\PycharmProjects\test something\venv\Lib\site-packages\discord\user.py", line 423, in edit
payload['avatar'] = _bytes_to_base64_data(avatar)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Hadi\PycharmProjects\test something\venv\Lib\site-packages\discord\utils.py", line 627, in _bytes_to_base64_data
mime = _get_mime_type_for_image(data)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Hadi\PycharmProjects\test something\venv\Lib\site-packages\discord\utils.py", line 613, in _get_mime_type_for_image
if data.startswith(b'\x89\x50\x4E\x47\x0D\x0A\x1A\x0A'):
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: startswith first arg must be str or a tuple of str, not bytes
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\Hadi\PycharmProjects\test something\venv\Lib\site-packages\discord\ext\commands\bot.py", line 1350, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\Hadi\PycharmProjects\test something\venv\Lib\site-packages\discord\ext\commands\core.py", line 1029, in invoke
await injected(*ctx.args, **ctx.kwargs) # type: ignore
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Hadi\PycharmProjects\test something\venv\Lib\site-packages\discord\ext\commands\core.py", line 244, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: startswith first arg must be str or a tuple of str, not bytes
IDK why in the main project didnot showed
You have an error handler in the main one maybe
can you give me example of correct way to use it?
no
with open('some_filename', 'rb') as fp:
data = fp.read()
edit(avatar=data)
and for using an url, just get the content from there
Don't even need to do that + blocking call
Don't even need to do that
?
I want to provide the new avatar in command
Download content from url and use it for avatar
In this case, just take the url of the avatar (ofc validate it first), and request using aiohttp, read into bytes and then edit
There is probably a cleaner impl using discord.Asset and discord.File instead
can you give example for this?
I just gave it
Also instead of pointing to an url, I would suggest type hinting the arg using discord.Attachment instead. Then all you would need to do is just send the new pfp as an file
how I can check if the command have an attachment or if its an image?
The actual command or the message that invoked the command?
dont use requests lib in discord bot
Might as well recommend using aiohttp which is a dependency of discord.py
why?
Imagine that you're coding a Discord bot and every time somebody uses a command, you need to get some information from a database. But there's a catch: the database servers are acting up today and take a whole 10 seconds to respond. If you do not use asynchronous methods, your whole bot will stop running until it gets a response from the database. How do you fix this? Asynchronous programming.
What is asynchronous programming?
An asynchronous program utilises the async and await keywords. An asynchronous program pauses what it's doing and does something else whilst it waits for some third-party service to complete whatever it's supposed to do. Any code within an async context manager or function marked with the await keyword indicates to Python, that whilst this operation is being completed, it can do something else. For example:
import discord
# Bunch of bot code
async def ping(ctx):
await ctx.send("Pong!")
What does the term "blocking" mean?
A blocking operation is wherever you do something without awaiting it. This tells Python that this step must be completed before it can do anything else. Common examples of blocking operations, as simple as they may seem, include: outputting text, adding two numbers and appending an item onto a list. Most common Python libraries have an asynchronous version available to use in asynchronous contexts.
async libraries
The standard async library - asyncio
Asynchronous web requests - aiohttp
Talking to PostgreSQL asynchronously - asyncpg
MongoDB interactions asynchronously - motor
Check out this list for even more!
Hi, I was wondering if someone knows what the rate limit/frame rate you can achieve by editing a message over and over with a bot?
Should be listed somewhere in the discord API docs
its mostly based on number of requests rather than over an endpoint global limit per second is 50 requests iirc
https://discord.com/developers/docs/topics/rate-limits#:~:text=global"%3A%20true%20%7D-,Global%20Rate%20Limit,per%20second%20to%20our%20API.
5 edits / 5 seconds from what I observe
Rat robot
!d discord.on_message_delete
How can I make the event ignore some function or temporarily disable it?
Ignore what function and what's the event?
New here, have just a general question.
I've gone through most of the basic concepts in Python, and am looking to get started in working on a bot project;
what's the general roadmap that new self-learners take while trying to make something on their own?
I've looked at youtube but there's mostly just out of date stuff that's like older than 1.50 so it's missing info about intents etc.
The documentation and examples are great resources
But discord.py is more of an advanced library so it's generally expected that you know your way around Python pretty well and you know how to read documentation efficiently
I see. So what would be advised for some projects to work on then before a discord bot in your opinion?
I already have a bot connected to discord and all that and the only resource i have is theDocs which is why I came here because yeah I realized it's all just very technical (spending just hours long loops of googling and not actually even touching code)
!projects has a list of many project ideas you can try
The Kindling projects page on Ned Batchelder's website contains a list of projects and ideas programmers can tackle to build their skills and knowledge.
Don't take this to mean I'm telling you not to write Discord bots, though. I'm merely pointing out what's typically expected
Plenty of people make discord bots as beginners
I'm sure, I realized today though I am just definitely not one of those people lol
thank you for the response, appreciate it
Personally I learned Python by writing Discord bots. They weren't that great the start, and I had a fair bit of trouble but I did get the hang of it eventually
In the early stages of learning it helps to have a goal or something to keep you motivated. If you're learning just for the sake of learning, you'll probably end up getting burnt out quite fast
the projects thing you listed is good for me for sure.
I want to learn to work with python more whether it's making discord bots or pausing on that for the moment to learn and do something else.
As long as I feel I'm progressing and not wasting my time. just reading for hours on google about issues in bots for 4+ hrs out of my day without touching my code editor makes me wanna give up which is why I came to this Discord for extra advice on it.
What do you mean by
just reading for hours on google about issues in bots
?
The best way to learn a language is practice
Yeah. Pretty much anything you do will get you closer to that goal
I get an unexpected outcome in my bot > I google / look in thedocs to check individual parts of my strings to try and figure it out > google / thedocs uses language I don't understand > google each word I don't understand > endless cycle
Yeah. That seems like a lack of experience with the language itself
and ultimately i learn nothing if i dont apply it
So then how did you learn through starting with discord bots?
assuming by starting, you mean at the same level i am now which is very minimal
Pretty much what you did, but I stuck with it for long enough for stuff to start clicking. Learning is exponential, the more you already know, the easier it is to pick up new things
Though I honestly would not recommend that way of learning
No, it took about a year or so
It's a much slower process and also has room to learn bad habits and practices
before you could make anything work?
It’s much easier learn about individual topics like functions, async programming, OOP and just the basics overall
Especially with discord bots, basically every single tutorial either uses bad practices or outdated code
Well, I could make things work by googling the parts that weren't working, but I wouldn't really understand why or how it worked. That's really the intuition that needs to be developed before you can start building things fully on your own, and fixing things without having to google it
yeah i realized this which is why im stuck and came here to ask for different types of advice from people. Thanks for the previous reply too, that makes more sense to me. I've gone through Harvard CS50's 15+hr intro to Python vid and I've also gone through freecodecamp's intro vid and they go over every concept you mentioned
15 hours tutorials 
in total almost 20 hrs of videos that just kind of feel like lectures on just the basic concepts
that's my definition of pain
Tbh you’ll gain more knowledge if you’re actually doing mini projects, instead of watching lectures
I was also writing along with them
if i was just staring at the screen without doing anything else i'd forget it the next day
don't most people do that when learning? take notes to reinforce or also write the code using said concepts yourself?
Not everyone nope
Some people watch some 24 hours tutorials named "PYTHON FULL COURSE IN 24 HOURS 2023" and hope that at the end of the video they know everything
I gues you're insinuating that's what I am.
Alright anyways, thanks for the responses yall take care
you reinforce a lot of what you have learned while coding
Nope, if you're taking notes etc. it's amazing
Meant some people that come in this channel asking help, and they did exactly that
alright, so i'm working on a discord bot that streams a certain application, but it looks like in discord.py that isn't supported, unless i'm missing something in the docs, can anyone confirm?
bots can't stream videos, that's the discord api itself
YT streaming? don't bother with it
shit
meaning streaming something from the screen
oh bots can't do that
shit.
also it's pretty useless since there's the YouTube Activity
yeah but i wouldn’t be streaming youtube videos, it’d be my screen
i’ll just stream it myself for now and just have people send inputs while watching my stream instead of the bot’s stream
kinda still useless imo since twitch exists for that

My cog isn't responding it was working before but not anymore neither i made any changes
My cog
class anti(commands.Cog):
def __init__(self, client: MyBot):
self.client = client
async def on_ready(self):
print('Anti is loaded')
@commands.command()
async def Hello(self, ctx):
await ctx.send('done done')
My __init__ file
from .commands.anti import anti
from core import MyBot
async def setup(bot: MyBot):
await bot.add_cog(anti(bot))
MyBot() is my bot's subclass
what's your file structure?
do you use bot.load_extensions on the folder where the init.py is located?
the setup function is usually supposed to be in the extension file itself
It was working before but suddenly stopped working
- um do you have proper intents in the bot? (Message Content intent is the required one here)
- Does the "Anti is loaded" part get stdout-ed
I'm using discord.Intents.all()
And no it is not printing Anti is loaded
i would guess it might be getting ratelimited like usual for replit, but you cant tell because client.start() doesn't setup logging
Same issue in VSC
load_extension("cogs") - didn't u have to pass the file path seperated with .
No
cogs here is acting as a module itself since it has a setup function in the init
hmm, can you add discord.utils.setup_logging() just before starting the client?
just scrolled
are u allowed to have a command with capital letters? iirc u cant in slash i forgot for normal ones
you can in normal commands
^ though it's case sensitive by default unless you use case_insensitive=True
I'll try
case_insensitive = True yes ✓
case_insensitive is for prefixed commands
🙏 i see
I have both type of commands
weird but ok 👀
it would only work for prefixed but not work for slash
You don't have to type anything for slash commands they're just like choose and use
Makes sense
the reason why is you are supposed to have the setup coro at the end of your cog. Might want to see this example on cogs
there is one in the init of cogs module
they're loading the cogs package directly, so it should be reading the setup() from cogs/__init__.py
ah
I added logging.basicConfig(filename="bot.log", level=logging.INFO, filemode="a")
What next?
Or should I change my setup() location based on this?
run your bot as usual, tell us if your command works, and show the log output
oh yeah didn't notice it the first time but your on_ready() won't print without a @commands.Cog.listener() decorator
Ohh my bad
I got it confused with bot subclass
Command worked just by adding logging to bot 😭
How
i would still guess discord ratelimited your bot, you just didn't have a way to tell if it was happening
i can't recall how writing to files work in replit so i suggest using discord.utils.setup_logging(), or at least don't specify a filename in basicConfig()
I've been facing this issue since yesterday and maybe no resson for rate limit because it's just temporary testing bot
Oh i see
I never used logging before
Is there a way i can print it? Like if i want to make it log on console instead of file?
that's what setup_logging and basicConfig does by default
!d discord.utils.setup_logging
discord.utils.setup_logging(*, handler=..., formatter=..., level=..., root=True)```
A helper function to setup logging.
This is superficially similar to [`logging.basicConfig()`](https://docs.python.org/3/library/logging.html#logging.basicConfig) but uses different defaults and a colour formatter if the stream can display colour.
This is used by the [`Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client) to set up logging if `log_handler` is not `None`.
New in version 2.0.
any free recommended places to host a bot?
i know
Please make sure you read this fully
When you look for hosting your bot, you might be tempted to use free services or providers that claim to support hosting discord bots (eg PebbleHost and others). Do not use them. Why? Let me explain.
Free hosts and tiers always have drawbacks - The point of a free tier or a host is to get the user to use their product, and upgrade for all of the good features. Hosts such as replit use shared cpus, oftentimes will run into ratelimits, and have "gotchas" that make you tempted to upgrade to their paid tiers. They also literally remove all control out of how you run your bot. Think about it: Hosts need to make money somehow in order to either break even or gain profit. So naturally they will tempt you into upgrading in order to do that. This is basic economics and quite literally how businesses run.
If you are still looking for a host after reading this, then you have some options. And here are them:
-
Pay up - Pay up and use a VPS provider. My pick is Heznter, but see
?tag vpsfor the full list (if you are on the Python discord server, then see!hostingfor your options). More than likely if you are not an eligible HS or college student, this is your option. -
Self Host - If you are able to self host your own server, then go for it. This is really the only "free" way if you already pay for your electricity bill and have the equipment to do so. Raspberry Pis oftentimes are great for this.
-
GitHub Student Developer Pack - IF you are a enrolled student in an HS or college (you will need to either provide an valid student ID or proof of education of your HS or college), then you may apply for this deal. More info about this can be found here. The deal offers $200 free credits on DigitalOcean for 1 year, so if you are a student and need to host your bot, go for it.
@kindred epoch read the message above
lol alr ty
np lol
How would you make your discord bot send a message with this kind of format? Like with the line on the side, and the darker shaded background? (OWO bot for reference)
This is just a normal embed
How would I go about that, good sir?
Also nice PFP
!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...
Note the colour kwarg
Hmm, I've never used one of those before. Have any examples of how I would apply that to a message?
What do you mean, "apply it to a message"?
Idk, I'm just trying to make my discord bot send a message in that format. Say I wanted to send:
Hello!
I am a bot!
I do bot things!
but as an embed
inline=False for embed fields
by default it is enabled
assuming you're using discord.py, you would construct an Embed object with whatever attributes/parameters you want it to show, and then use the embed= parameter for whatever send() method you're calling
Can you edit embeds?
you would have to replace the embed with a new one
well, embeds can be modified in-place but you still need to edit the message for your changes to take effect
true
for example: ```py
embed = discord.Embed(description="Hello world!")
message = await channel.send(embed=embed)
embed.description = "foobar2000"
await message.edit(embed=embed)```
so I have an issue with making an activity for my bot
this is the code i use
intents = discord.Intents.all()
bot = commands.Bot(command_prefix="_", intents=intents)
client = discord.Client(intents=intents)
async def load():
await bot.load_extension(f"cogs.<COG-NAME>")
async def main():
activity = discord.Activity(type=discord.ActivityType.competing, name="working again!")
await bot.change_presence(status=discord.Status.online, activity=activity)
await load()
await bot.start("<TOKEN>")
asyncio.run(main())
the console returns me the following error AttributeError: 'NoneType' object has no attribute 'change_presence', implying that the bot object is non-existent which doesnt make sense as the cog I load works flawlessly, which uses the botobject.
you know.... you can set the activity directly instead
and also you dont need line 3
You shouldn't have 2 bot instances
Your intents variable is also useless as you could just pass discord.Intents.all() as your intents
how do I do that?
thanks for pointing that out
!d discord.ext.commands.Bot
class discord.ext.commands.Bot(command_prefix, *, help_command=<default-help-command>, tree_cls=<class 'discord.app_commands.tree.CommandTree'>, description=None, intents, **options)```
Represents a Discord bot.
This class is a subclass of [`discord.Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client) and as a result anything that you can do with a [`discord.Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client) you can do with this bot.
This class also subclasses [`GroupMixin`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.GroupMixin) to provide the functionality to manage commands.
Unlike [`discord.Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client), this class does not require manually setting a [`CommandTree`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CommandTree) and is automatically set upon instantiating the class.
async with x Asynchronously initialises the bot and automatically cleans up.
New in version 2.0.
activity and status kwargs
thanks
async def on_timeout(self):
print("timeout")
embed= discord.Embed(
title = "❗ | 시간초과",
description = f"답장이 너무 오래걸려 프로세스가 종료되었습니다.",
color = discord.Color.from_rgb(255, 0, 0)
)
embed.set_footer(text=f"{Ftmsg}")
await interaction.response.edit_message(embed=embed,view=None)
return
How do I fix it to work?
fix what to work
like fix the canbus to allow the cancoders to work?. Point is i dont know what you want that should get fixed and idk the error as well
I'm trying to modify the existing embed at timeout in discord.ui.View, but there is no interaction in on_timeout, so I can't modify the embed by the way I know it.
u cant (found a way)
actually nvm found a way
i want to test something on my bot can anyone help me test
what you would need to do is to edit the message itself, not the interaction. refer to the link (https://discordpy.readthedocs.io/en/stable/faq.html#how-can-i-disable-all-items-on-timeout) for more info
Test yourself
Create a second account, etc.
Does it work on discord.py 2.0 as well?
The documentation is for 2.x so take guess 
That document doesn't solve it
I looked at that document and tried it for 40 minutes
But I couldn't find an answer.
the docs doesn't give you answer explicitly. it guides you torwards it
i already know of a way to pretty much do what you want, but i want to let you figure out your own implementation of it
😢
view.message = await interaction.response.send_message(embed=embed,view=view)
Is it correct to use this code?
Continuously self.message value is shown as None
send_message returns None, so you will probably want to modify it to take in an InteractionMessage instead. Note that all interactions can only be responded to once unless you make a followup request
await interaction.response.send_message(embed=embed,view=view)
view.message = await interaction.original_response()
I understand up to here
But I'm not sure how to use self.message
The value of self.message is <InteractionMessage id=123 channel=<TextChannel id=123 name='channelname' position=0 nsfw=False news=False category_id=None> type=<MessageType.chat_input_command: 20> author=<Member id=123 name='bot name' global_name=None bot=True nick=None guild=<Guild id=123 name='server name' shard_id=0 chunked=False member_count=123>> flags =<MessageFlags value=0>>
These value were obtained using print()
Like any other message objects
That is the representation string of the object
!d discord.InteractionMessage
class discord.InteractionMessage```
Represents the original interaction response message.
This allows you to edit or delete the message associated with the interaction response. To retrieve this object see [`Interaction.original_response()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Interaction.original_response).
This inherits from [`discord.Message`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Message) with changes to [`edit()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.InteractionMessage.edit) and [`delete()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.InteractionMessage.delete) to work.
New in version 2.0.
Np
Hi, i have a little issue with the reaction listener. So when I generate a new region message and i react to it everything works fine adding me the roles i selected. The issue starts when i reload my bot, it's like it ignores the reactions from that message or idk.
!d discord.on_reaction_add
discord.on_reaction_add(reaction, user)```
Called when a message has a reaction added to it. Similar to [`on_message_edit()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_message_edit), if the message is not found in the internal message cache, then this event will not be called. Consider using [`on_raw_reaction_add()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_raw_reaction_add) instead.
Note
To get the [`Message`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Message) being reacted, access it via [`Reaction.message`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Reaction.message).
This requires [`Intents.reactions`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.reactions) to be enabled.
Note
This doesn’t require [`Intents.members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.members) within a guild context, but due to Discord not providing updated user information in a direct message it’s required for direct messages to receive this event. Consider using [`on_raw_reaction_add()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_raw_reaction_add) if you need this and do not otherwise want to enable the members intent.
And the code is?
Modals cannot contain user selects
Modals can only contain text inputs
!d discord.ui.TextInput
class discord.ui.TextInput(*, label, style=<TextStyle.short: 1>, custom_id=..., placeholder=None, default=None, required=True, min_length=None, max_length=None, row=None)```
Represents a UI text input.
str(x) Returns the value of the text input or an empty string if the value is `None`.
New in version 2.0.
Anyone else getting [Errno 111] Connection refused with mongodb?
Can you change the button style inside on_timeout? I gave it a try and it didn't work, just wondering if there's some workaround
ok so i have a proplem with
@client.command()
async def pack(ctx):
packs = {
"Bronze": 10000,
"Silver": 15000,
"Gold": 25000,
"Special": 50000
}
pack_list = ', '.join([f"{pack}({price})" for pack, price in packs.items()])
await ctx.send(f"Available packs: {pack_list}\nPlease reply with the pack name.")
def check(m):
return m.author == ctx.author and m.channel == ctx.channel
try:
reply = await bot.wait_for('message', check=check, timeout=30)
except asyncio.TimeoutError:
await ctx.send("You took too long to reply.")
return
selected_pack = reply.content.capitalize()
if selected_pack not in packs:
await ctx.send("Invalid pack name.")
return
cost = packs[selected_pack]
# Check if the user has enough money
user_id = str(ctx.author.id)
db = sqlite3.connect("data.db")
cursor = db.cursor()
cursor.execute("SELECT money FROM info WHERE id=?", (user_id,))
user_money = cursor.fetchone()[0]
if user_money < cost:
await ctx.send(f"You don't have enough money. You currently have {user_money}.")
cursor.close()
db.close()
return
selected_card = random.choice(cards_in_pack)
embedVar = discord.Embed(title=f"Unpacking a card from {selected_pack} pack",
color=0xff00ff)
embedVar.add_field(name=f"Card Name", value=selected_card[0], inline=False)
embedVar.add_field(name=f"Score", value=selected_card[1], inline=True)
embedVar.add_field(name=f"Position", value=selected_card[2].upper(), inline=True)
embedVar.add_field(name=f"Price", value=f"${selected_card[3]}", inline=True)
embedVar.set_image(url=selected_card[4])
await ctx.send(embed=embedVar)
at the start as u see it should detect the reply
but it doesnt detect
how can i make it detect the reply?
!code
!d discord.Interaction.response
Returns an object responsible for handling responding to the interaction.
A response can only be done once. If secondary messages need to be sent, consider using followup instead.
iirc u could
Don't bots change the button style to disabled?
None of my buttons have changed on timeout
Code?
Nvm firewall issue
Not at my computer rn, daughters nap time so I need to get her to sleep. But it's nothing abnormal I set a view timeout to 5 sec with a green button for testing and on timeout the button is unchanged, but will error on press. But if I try to change self.children[0].style in the on_timeout it doesn't error and doesn't do it
I meant to say that u should just use a button callback which uses interaction response instead of bot.wait_for
user_identification_view = UserIdentificationView()
await interaction.channel.send(embed=identification_embed, view=user_identification_view)
await asyncio.sleep(20)
break
except asyncio.TimeoutError:
# Handle the case where the user did not respond within the specified timeout
await interaction.channel.send("Interaction timed out; go ahead and use this one.")
while True:
def amtcheck(message):
return (
message.channel == interaction.channel
and message.author == interaction.user
and message.content.strip().isdigit() # Ensure the response is a valid number
)
try:
amount_embed = discord.Embed(
title="Amount",```
these are two diff embeds and they r sending at the same time
Theoretically yes, on_timeouts are just a discord.py thing
but idk what u mean by wait for
Well I'll have to see some code because I remember changing the style to disabled when I used to code. I'll try finding some code which does the same but u sharing the code would be really helpful
Because of that, though, you're not provided with an interaction object
Why does it matter?
Let me slap something together rq on my phone lol
thought it was just a money grab but; are u talking 2 me or him
Him
because we are both dealing with interactions
Can i ask how to made self bot?
no!1!
Why?
tos!1!
What?
its against terms of service
Oh ok
also whats the point of selfbotting its just a waste of time
Srry
whatever u can do a bot can do way better
Tnx for helping
No problem
@bot.tree.command()
async def test(interaction:discord.Interaction):
await interaction.response.send_message(view = myview(timeout=5))
class myview(discord.ui.View):
@discord.ui.button(style = discord.ButtonStyle.green, row=1, label = 'testing')
async def mybutton(self, interaction:discord.Interaction, button:discord.ui.Button):
await interaction.response.send_message(content= "pushed the button", ephemeral= True)
async def on_timeout(self):
self.children[0].style = discord.ButtonStyle.grey
Button stays green on timeout
Oh I need to edit the response. Nvm.
Also you can do self.mybutton.style = discord.ButotnStyle.grey
yea.... u gotta tell Discord that u edited the style lol
Was finding the docs for that, kinda forgot where they were
Yea I tried both ways. Just realized I'm a big dumb and never edited the response lol
uh how will that help
Helps people read your code, instead of it looking like a bunch of text on a screen
ok wait
Also, have you tried putting in some prints to see what's getting triggered, if the bot is detecting a reply at all? And do you have message content intents?
i enabled all intents
intents = discord.Intents.all()
client = commands.Bot(command_prefix="-", intents=intents)
So you're getting the timeout message whether you reply or not?
hmm, command is decorated with client but you're accessing the wait_for method from bot...
those aren't two bot objects you're using, right?
Ooo good catch
uh im using client
not bot
so i should change it to client.
No error because it's in a try block
Yes
then it will detct the message?
Try and see?
ok
You still shouldn’t have 2 bot instances
And your commands.Bot instance shouldn’t be called client as discord.Client exists
what
what is this
What's some reasonable price to host a discord bot online?
For example a simple one that scrapes some data and shows them in discord (no databases etc).
I am using pythonanywhere with 6.5€/month but I'm not satisfied. The consoles keep crashing.
I'm new in hosting my bots. They are actually the first things I make myself that are useful to more people (not just me, running a script when I want to).
Henzter
Isn't it way too expensive for a simple bot? I'll check it's tiers. Thanks.
No their cheapest plans are 4 euros per month
Ok that will do it then. Thanks 👍
Np
Do they reset their consoles?
netcup is cheaper tough
Also questionable
No you pay for a vps and ssh into it
I want something that runs 24/7 without resetting its consoles like pythonanywhere (it only gives you the always on feature for just one app).
Henzter does that
Not really german servers are heavily subsidized.
Their servers run 24/7. All you need to do is to ssh into it, and set it up
I am sure it's a pain for a beginner, right? Pythonanywhere was really simple. But I think it's worth it.
You can use something like systemd to run your bot as a process and manage it via that way
I don't even know what ssh is lol. Will learn.
Remote terminal
You could get one that is a bit more expensive for a UI but honestly if you plan to do this more often I recommend learning it now.
ssh is wonderful

wasn't discord.py discontinued
oh so just no more updates
Updates are happening
Check the GitHub repo
That was 2 years ago
yeah lol i don't use discord much
In short terms dpy is maintained and has full support for stuff like slash commands and all of the other discord features
last commit was 24 minutes ago on the discord.py repo
Danny was being a little bitch (no diss) because of Discord changes so he quit
Then like 8 months later he came back
oh lol
I think it had to do with how he thought the other forks were shit
No I think.. he just had other responsibilities
He made it seem like the leave was permanent
<t:1630036800:d> https://gist.github.com/Rapptz/4a2f62751b9600a31a0d3c78100287f1
<t:1647921600:d> https://gist.github.com/Rapptz/c4324f17a80c94776832430007ad40e6
as per the newer gist:
... as time went on it became increasingly clear that the Python bot ecosystem has been too fragmented. I was hopeful that after half a year that there would be a clear alternative library that most users can transparently migrate to, but it seems that this never ended up materialising. In order to prevent more turbulence in the ecosystem, it made sense to try to remedy the current, unfortunate, situation.
My motivation to work on Discord has been dwindling over the past year, since the verification system was introduced. Persistent tone deafness, deadlines, lies, gaslighting, and rapid changes without proper consultation by the Discord employees make it hard to have the motivation necessary to work with the frequent changes and the limitations being placed on me.
tldr intents and just Discord staff being ass is what got him all worked up
arguably it might be a safer choice to use an alternative given that danny didn't have any major contributor of the library that was willing to take over development when he left, but i believe it still remains as the most popular library for python discord bots, hence why most of the help here involves it
How can I stop my discord bot getting rate limited in the future when it grows? I have on_message events
- don't use replit
- don't make too many requests in a short time frame
- shard your bot, look into discord.AutoShardedClient/ discord.ext.commands.AutoShardedBot
whats this screenshot of? a modal?
is this some figma design?
its been rate limited for 2 hours now
and i cant put it back online
hi, "Application Role Connection Object" these are linked roles of third party apps right?
yeah prolly tho not 100% sure
when does the rate limit go?
nothing u can do
its been 2 hours
it depends on discord
bots are ratelimited by application id and tokens
so u can just wait it out
I dont have 2000+ guilds
only 160
were u using replit?
so i cant shard
no
or do u have some task which makes a bunch of requests?
well i have on_message events and active servers can maybe rate limit my bot using them
might be that then why not work on optimisation of ur bots events aspects then
add some cool down bucket or limiter
idk what to add. What would count as a request?
anything that makes a request to the discord api
reading a message?
generally when ur awaiting and requesting something
if u have the message object already then no
getting the message content?
Anything???
so like awaiting something from a different api?
say await bot.fetch_channel() any data ur requesting from discord
thats fine
oh ok
if the something needs to be done by the message, My on_message event awaits 4 times only
i mean based on any active server say 2-3 messages per second thats like 12 requests
and thats 160 servers
so u might log the requests a bit
you know delete_after=Int
would that be an request?
Ok ill delete that
reqs*
i dont really need it
ty honey
well you asked for when it grows so I answered likewise
make sure you're not making too many reqs
Sometimes your host can also be the problem if they use shared IPs
we have shared IPs but tbe port is different
@shrewd apex is getting a user id or user permission a request?
if message.author.id == self.bot.user.id or message.author == message.author.bot:
return
```
how many requests per second?
a verified bot can have?
no
if message.author.guild_permissions.ban_members:
return
i said when ur awaiting right here u already have the object ur just accessing properties
The same amount as not verified
50?
ye
50 is the global rate limit. the rate limits are dynamic iirc
then what hosts are you using
diva hosting
wtf is that one. it sounds like some sus host
Free and good don't exist together :p
nah i looked it up. shit host compared to DO
theres a paid plan
you are better off moving to a proper vps provider instead
And you are using it?
bro my websocket ping is like 22 all the time
with them
no
it's hosted in nj lol
anyways, see your options here
Need to run your bot 24/7? Get a cheap VPS.
https://www.scaleway.com/ EU https://www.time4vps.eu/ Lithuania.
https://www.digitalocean.com/ US https://www.vultr.com/ US
https://www.ovh.co.uk/ EU/Canada https://www.hetzner.com/ Germany/US
Self-hosting: Free hosting: Kinda free:
Any computer. Heroku dead 🦀 GCP, AWS have one year free micros.
well theres no free ones
that's the point. Do i have to draw the ATC, AVC, and MC graphs for that market?
disagree
you ain't convincing me btw
i got 2.5 GIB disk
Please make sure you read this fully
When you look for hosting your bot, you might be tempted to use free services or providers that claim to support hosting discord bots (eg PebbleHost and others). Do not use them. Why? Let me explain.
Free hosts and tiers always have drawbacks - The point of a free tier or a host is to get the user to use their product, and upgrade for all of the good features. Hosts such as replit (see ?tag replit for more info) use shared cpus, oftentimes will run into ratelimits, and have "gotchas" that make you tempted to upgrade to their paid tiers. They also literally remove all control out of how you run your bot. Think about it: Hosts need to make money somehow in order to either break even or gain profit. So naturally they will tempt you into upgrading in order to do that. This is basic economics and quite literally how businesses run.
If you are still looking for a host after reading this, then you have some options. And here are them:
-
Pay up - Pay up and use a VPS provider. My pick is Heznter, but see
?tag vpsfor the full list (if you are on the Python discord server, then see!hostingfor your options). More than likely if you are not an eligible HS or college student, this is your option. -
Self Host - If you are able to self host your own server, then go for it. This is really the only "free" way if you already pay for your electricity bill and have the equipment to do so. Raspberry Pis oftentimes are great for this.
-
GitHub Student Developer Pack - IF you are a enrolled student in an HS or college (you will need to either provide an valid student ID or proof of education of your HS or college), then you may apply for this deal. More info about this can be found here. The deal offers $200 free credits on DigitalOcean for 1 year, so if you are a student and need to host your bot, go for it.
The paid plan just has more storage
and ram
thats the difference
i can mount 50GB for $2 on Henzter
I only pay like $7 in total
for a VPS provider that actually knows what they are doing. Triple RAID replication, GDPR complaint, etc
you can buy extra server without paid plan
can you stop shilling that shitty host?
I'm telling you its good
because the next time you ask for help, don't expect it from me anymore
the went bankrupt because everyone was using the free plan and only 6 people were using paid
thats how good the free plan is
proves how jackshit it is
1,000 using free plan
you have 6 people using your paid plan, you make no profit
again, can you stop
Yeah i know
they had to use their own computer
can you stop about shilling that host. i'm being serious. i dont give two shits about your fucking shitty promotions
Ok
but im not changing
Me when #code-of-conduct 😔
Sorry...
port doesn't matter tho
huh, ty
🤔
the software you host are bounded to a port, that's where you access your application, it certainly does matter
ports are things only in the local computer so it doesn't matter, ratelimits are shared across same IP addresses
it has nothing to do with the ratelimits of an API, IP is all that matters
atleast for the discord API
oh, that i cannot speak for, apologies
the first part of that sentence is absurd, ports are a "thing" on every machine with a NIC
i mean ports are under that same IP address
ports would matter if ur using third party webhooks and such which requires either domain or ip and port an example is topgg
Probably gonna stop helping people on this channel
