#discord-bots
1 messages · Page 320 of 1
Is the slash command hidden in the integrations Ui?
sorry idk what you mean by that my english isnt the best-
https://paste.pythondiscord.com/NEHQ
my main and cog files
its probably a super stupid problem but i am getting really tired-
Doesn’t seem like you’re loading your cog
Cog you’re loading doesn’t match the class name
async def setup_hook():
await client.load_extension("commands.db")``` its this, the file is called db.py
should i rename it?
Do any of y’all know how to keep a bot online
Using discord.py or the raw gateway?
Check which commands are getting synced
!d discord.app_commands.CommandTree.sync
await sync(*, guild=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Syncs the application commands to Discord.
This also runs the translator to get the translated strings necessary for feeding back into Discord.
This must be called for the application commands to show up.
Look at the return type
and how should i use it? sorry- i am really better with like, an example that applies to my situation-
Loop through the list and print the name attribute
!d discord.app_commands.AppCommand.name
The application command’s name.
so something like, for command in app_commands (or smth like that)
print(name)?
i still dont understand ;;;;
sorry;;;;
async def setup_hook():
await client.load_extension("commands.test")
for command in client.app_commands:
print(command.name)``` like this?;;;
i just need to know where i should loop and how, its really hard for me to understand things like that without doing it successfully first
I don’t think you understand. I’m order to keep a bot online it needs some sort of cloud host to keep the code constantly working
So I’m asking if there’s any like trusted cloud hosting providers or is there another way to keep it online
AWS, GCP, hetzner
just look use the command !hosting
!hosting
Using free hosting options like repl.it or Heroku for continuous 24/7 bot hosting is strongly discouraged.
Instead, opt for a virtual private server (VPS) or use your own spare hardware if you'd rather not pay for hosting.
See our Discord Bot Hosting Guide on our website that compares many hosting providers, both free and paid.
You may also use #965291480992321536 to discuss different discord bot hosting options.
Wait you have this but also #discord-bots message?
Ah no i was just dumb and moved it
async def sync(ctx):
await client.tree.sync()
print('[Bot] Commands synced successfully')
for command in client.commands:
print(command.name)```
thats how it looks now (i had the app_commands but i got an error saying "discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Bot' object has no attribute 'app_commands")
Hello.
Could someone give me an example of how i would use discord.CategoryChannel.edit() whilst specifying overwrites parameter?
Im a bit confused on how it works
@sick birch?
Like I said, look at the return type of sync
it returns a list of AppCommands
AH I THINK I GOT IT
``` should i be getting this?
it says that mejora IS getting synced-
but in the list it isnt there?
@final iron (forgot to reply)
Right click on your server, clicked integrations
click manage on your bot
then click on the command and show a screenshot
It could just be taking a second to sync
If you actually type in the command in the chat does it come up? Instead of clicking on the bot
Also check if it shows in direct messages
and yes it does? im so confused-
yeah
i ctrl+s every like every 5 seconds
i been just closing VSC every once in a while
and i make sure its the right one-
No clue then
I'd post in the discord.py server as you'll most likely be able to fix it
i... closed and opened discord and now its there...
4 hours for this
thanks for the help anyways, and sorry for being so dumb about it
cute dog
enable auto save 💀
nah I like saving manually, it feels like I'm in control
hmm ok ig upto personal preference
Don't ever go to that cursed place
Lol
!paste
can i choose from my buttons class which buttons i wanna use?
or only create new class
You can add buttons to instance of class
can u show me docs to understand
or example of instance
@vale wing
I wanted to start building a discord bot on replit but when I test run it, it errored out. I think Discord blocks replit. Is there another cloud hosted editor that I can quickly touch code and run? Not something I want running 24/7. Just an on/off kinda development.
Instance is OOP term you should be familiar with
Just run it on local machine
Y do you even need cloud
In that case this is question for #editors-ides
try using github codespaces
Hmm yeah I guess I could try that. Thanks
can i find message in channel by embeds?
How should I access owner id?
owner of what? the guild?
owner should be user who created channel
There is no way to tell who created a text channel except using the audit log
So how can I give access to the command only to the person who created the channel?
do you know who created the channel?
if your bot created the channel for example
otherwise you might just have to listen for channel creates and record those
hello guys, i've started trying to learn how to code Discord Bot and recently when i'm running it, it just doesn't execute any of my command
I haven't touched anything and the last time i used it it was working, the events are still working and when i'm looking at the logs in my console there's nothing and I was wondering if you guys could help ? 
show code
yessir
import discord
import config
from discord import Member
from discord.ext.commands import has_permissions, MissingPermissions
from discord.ext import commands
from discord import FFmpegPCMAudio
intents = discord.Intents.all()
client = client = commands.Bot(command_prefix="!", intents = intents)
@client.event
async def on_ready():
print("*****************************************")
print('{0.user} est opérationelle'.format(client))
print("*****************************************")
@client.event
async def on_member_join(member):
channel = client.get_channel(1067144368839983226)
await channel.send("Bienvenue !")
print("new member")
@client.command()
async def hello(ctx):
await ctx.send("Hello I'm {0.user}".format(client))
print("message send")
async def join(ctx):
if ctx.author.voice:
channel = ctx.message.author.voice.channel
await channel.connect()
else:
await ctx.send("you aren't in a voice channel")
@client.command(pass_context = True)
async def leave(ctx):
if ctx.voice_client:
await ctx.guild.voice_client.disconnect()
await ctx.send("Bye Bye ! :wave:")
else :
await ctx.send("i'm not currently in a voice chat")
@client.event
async def on_message(message):
if message.content == "feur":
await message.delete()
await message.channel.send("do not send that")
print(message)
@client.command()
@has_permissions(kick_members=True)
async def kick(ctx, member: discord.Member,reason=None):
await member.kick(reason=reason)
await ctx.send(f'{member} has been kicked \nReason : {reason}')
@kick.error
async def kick_error(ctx, error):
if isinstance(error, commands.MissingPermissions):
await ctx.send("You don't have the permissions")
@client.command()
@has_permissions(ban_members=True)
async def ban(ctx, member: discord.Member,reason=None):
await member.kick(reason=reason)
await ctx.send(f'{member} has been banned \nReason : {reason}')
@ban.error
async def ban_error(ctx, error):
if isinstance(error, commands.MissingPermissions):
await ctx.send("You don't have the permissions")
client.run(config.TOKEN)
should've pasted it in a pastebin service but it's fine
yeah sorry 

alright thank you i'll try to fix it
welcome
How can I check the discord.py version?
I think discord.__version__
or pip show discord.py
i am getting some wierd commandinvokeerror on my code
i dont know what i should do or what its suppose to mean
the code of the command
it dont work on app commands and it gives error in the prefix command
i have a problem i want to add message.content.includes or startswith but the problem it says py 'str' object has no attribute 'content'
this is my code
import discord
import responses
async def send_message(message, user_message, is_private):
try:
response = responses.handle_response(user_message)
await message.author.send(response) if is_private else await message.channel.send(response)
except Exception as e:
print(e)
def run_discord_bot():
TOKEN = 'removed for discord purposes'
intents = discord.Intents.default()
intents.message_content = True
client = discord.Client(intents=intents)
@client.event
async def on_ready():
print(f'{client.user} is now running!')
@client.event
async def on_message(message):
if message.author == client.user:
return
username = str(message.author)
user_message = str(message.content)
channel = str(message.channel)
print(f'{username} said; {user_message}" {channel}')
if user_message[0] == '!':
user_message = user_message[1:]
await send_message(message, user_message, is_private=True)
else:
await send_message(message , user_message, is_private=False)
client.run(TOKEN)
import random
import time
def handle_response(message) -> str:
clock = time.time
p_message = message.lower()
if p_message == 'اهلا':
return 'هلا يالطيب!'
if p_message == 'عشوائي':
return str(random.randint(1,6))
if p_message == "help":
return "مرحبًا، لقد دخلت إلى قسم المساعدة، يرجى انتضار فريق المساعدة للوصول اليك، حظًا سعيدًا"
if p_message == "كيف الحال":
return "الحمد لله طيب"
if p_message == "كيف حالك":
return "الحمد لله طيب"
if p_message == "كيف حالك؟":
return "الحمد لله طيب"
if p_message == "حسراتن لمايس":
return "Chatteru من عبالله RUBY / LEXIAN/ SKERCRO/ RUBIAN و خالد Nag3ah/ Oklonz"
if message.content.startswith('!') & p_message == 'time':
return 'the time is'```
second one is the responses code
look at the last code, .content.startswith('!') and content.includes all dont work
please help ive had this problem since yesterday and i wasnt able to fix it
can someone help
What's the question? 
.
!traceback
Please provide the full traceback for your exception in order to help us identify your issue.
While the last line of the error message tells us what kind of error you got,
the full traceback will tell us which line, and other critical information to solve your problem.
Please avoid screenshots so we can copy and paste parts of the message.
A full traceback could look like:
Traceback (most recent call last):
File "my_file.py", line 5, in <module>
add_three("6")
File "my_file.py", line 2, in add_three
a = num + 3
~~~~^~~
TypeError: can only concatenate str (not "int") to str
If the traceback is long, use our pastebin.
theres no trace back
litteraly just says str object has no attribute 'content'
Chaterru#5501 is now running!
lexarubian said; d" كوماند-بوت
'str' object has no attribute 'content'```
this is everything in my console
/terminal
Then it'd be difficult to find where the error occurred 🫠
if message.content.startswith('!') & p_message == 'time':
return 'the time is'```
Do you have any error handler that's just printing out the error?
here i type message.content.startswith('!') when i remove that everything works it does say 'str' object has no attribute 'content'
its in that line and im 100% sure it is
This is why we type hint things 
what?
It looks like you're passing a string into the user_message argument of the function send_message, which in turn, is passing the string to the message argument of the handle_response function
look im a begginer i dont really fully undertsand what you just said, but i just want to know what can i modify to make it work
Which part did you not understand?
just use commands instead of this
it looks like you're passing a string into the user_message i dont understand how on earth can you pass a string on a user message and what can i do to modify that nonsense
@bot.commands
async def time(ctx):
ctx.reply(time)
wdym commands , as i said im a begginer so sorry if you didnt understnad
the thing you are doing is inefficient async def commands are the thing you should do
okay so how do i put that in exactly?

# ...
username = str(message.author)
user_message = str(message.content) # <-- the "user_message" is a string
channel = str(message.channel)
print(f'{username} said; {user_message}" {channel}')
if user_message[0] == '!':
user_message = user_message[1:]
await send_message(message, user_message, is_private=True) # <-- pass the "user_message" string into the function
ok so the guy that i was following on youtube is a idiot when it comes to doing anything else with the code, so how should i edit it?
first do
bot = discord.ext.commands.Bot()
bot.intents = discord.Intents.all()
bot.command_prefix = "!"
okay wait
Don't
why?
are you gonna say to setup app commadns?
intents argument of the commands.Bot is required, you're not passing any into it in that codeblock
command_prefix also
ok guys im confused as hell
Then where did it come from?
bot = discord.ext.commands.Bot(intents = discord.Intents.all(),command_prefix = "!")
here you go
happy?
No, you'd get
AttributeError: module 'discord' has no attribute 'ext'
From that thing
from discord.ext import commands
bot = commands.Bot(intents = discord.Intents.all(),command_prefix = "!")
happy now?
Good
should i add this?
i havent made normal commands in months i am sticking to the hybrid commands
yes
okay wait
It shouldn't be any different
and now instead of my message.content.startswith i should put this
If you're using a sane library like discord.py, anyway
but how does it know which command i want to use
i have !help !errors !time so how will it knoiw
it is a little cause i am working with classes
@naive briar i also dont know this did a have any error in this
It parses the users' messages and search for a command that you registered to it from the messages
how do i even register it?
I'll send the official example
@bot.command()
async def roll(ctx, dice: str):
"""Rolls a dice in NdN format."""
try:
rolls, limit = map(int, dice.split('d'))
except Exception:
await ctx.send('Format has to be in NdN!')
return
result = ', '.join(str(random.randint(1, limit)) for r in range(rolls))
await ctx.send(result)
``` @daring ravine
its a bit complicated lemme send you a simple one
@bot.command(description='For when you wanna settle the score some other way')
async def choose(ctx, *choices: str):
"""Chooses between multiple choices."""
await ctx.send(random.choice(choices))```
!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.
okay guys what... i just want , i just want to be able to use content.include i dont want all this stuff can i please just get what should i do and edit to be able to use content thats all i dont want any "better" ways i just want content to be useable, im a begginer, really small beginner so everything your typing is gibbresh to me if i ever want to edit it i cant because its way too complicated for me , if yall can just say how i can use content or just stop helping me because i WILL waste your time because i wouldnt understand a thing and i will just waste you're time asking and asking and over and over again, please i just need that or you dont have to help me i dont want to waste anyones time
This doesn’t make sense. Can you tell me what you’re trying to do?
import random
import time
def handle_response(message) -> str:
clock = time.time
p_message = message.lower()
if p_message == 'اهلا':
return 'هلا يالطيب!'
if p_message == 'عشوائي':
return str(random.randint(1,6))
if p_message == "help":
return "مرحبًا، لقد دخلت إلى قسم المساعدة، يرجى انتضار فريق المساعدة للوصول اليك، حظًا سعيدًا"
if p_message == "كيف الحال":
return "الحمد لله طيب"
if p_message == "كيف حالك":
return "الحمد لله طيب"
if p_message == "كيف حالك؟":
return "الحمد لله طيب"
if p_message == "حسراتن لمايس":
return "Chatteru من عبالله RUBY / LEXIAN/ SKERCRO/ RUBIAN و خالد Nag3ah/ Oklonz"
if message.content.startswith('!') & p_message == 'time':
return 'the time is'```
this is my respone code
see the last two lines
they dont work i get a error saying
'str' object does not have a attribute 'content'```
yes
import discord
import responses
from discord.ext import commands
bot = commands.Bot(intents = discord.Intents.all(),command_prefix = "!")
async def send_message(message, user_message, is_private):
try:
response = responses.handle_response(user_message)
await message.author.send(response) if is_private else await message.channel.send(response)
except Exception as e:
print(e)
def run_discord_bot():
TOKEN = 'safteyreasons'
intents = discord.Intents.default()
intents.message_content = True
client = discord.Client(intents=intents)
@client.event
async def on_ready():
print(f'{client.user} is now running!')
@client.event
async def on_message(message):
if message.author == client.user:
return
username = str(message.author)
user_message = str(message.content)
channel = str(message.channel)
print(f'{username} said; {user_message}" {channel}')
if user_message[0] == '!':
user_message = user_message[1:]
await send_message(message, user_message, is_private=True)
else:
await send_message(message , user_message, is_private=False)
client.run(TOKEN)
because message is a string in this case
this is my bot code
so message is not returning a discord.Message
okay so how do i make it return a discord.Message
if you want to use the .content() attribute, you must be sure this main class has this attribute
Don't make it into a string 
So typing message to discord.Message
how do i do that bro im a begginer
typehint **
does this work
import discord
import random
import time
def handle_response(message) -> str:
clock = time.time
p_message = discord.Message.lower()
if p_message == 'اهلا':
return 'هلا يالطيب!'
if p_message == 'عشوائي':
return str(random.randint(1,6))
if p_message == "help":
return "مرحبًا، لقد دخلت إلى قسم المساعدة، يرجى انتضار فريق المساعدة للوصول اليك، حظًا سعيدًا"
if p_message == "كيف الحال":
return "الحمد لله طيب"
if p_message == "كيف حالك":
return "الحمد لله طيب"
if p_message == "كيف حالك؟":
return "الحمد لله طيب"
if p_message == "حسراتن لمايس":
return "Chatteru من عبالله RUBY / LEXIAN/ SKERCRO/ RUBIAN و خالد Nag3ah/ Oklonz"
if message.content.startswith('!') & p_message == 'time':
return 'the time is'```
message: discord.Message
I’m on mobile so this looks confusing, let me hop on my computer
okay
Just remove the .content from the message.content.startswith
okay can i also use that with content.include?
No
What
The actual contents of the message. If Intents.message_content is not enabled this will always be an empty string unless the bot is mentioned or the message is a direct message.
i removed .content and now it says
unsupported operand type(s) for &: 'bool' and 'str'
yeah you can either do this OR in your function definition, typehint message. like this; message: discord.Message
Use and instead
Because message is a string in your case
& doesn't do the thing you might think it does
how ,on earth do i make it not a strinng please
!d and
6.11. Boolean operations
or_test ::= and_test | or_test "or" and_test
and_test ::= not_test | and_test "and" not_test
not_test ::= comparison | "not" not_test
``` In the context of Boolean operations, and also when expressions are used by control flow statements, the following values are interpreted as false: `False`, `None`, numeric zero of all types, and empty strings and containers (including strings, tuples, lists, dictionaries, sets and frozensets). All other values are interpreted as true. User-defined objects can customize their truth value by providing a [`__bool__()`](https://docs.python.org/3/reference/datamodel.html#object.__bool__) method.
The operator [`not`](https://docs.python.org/3/reference/expressions.html#not) yields `True` if its argument is false, `False` otherwise.
ohh
well i used to code c# and it used &&
heh
i removed and
now i ahve this code
if p_message.startswith('!'):
return 'the time is'```
its not working
i said !hi but it didnt work
i don’t understand a lot of this
no, change that back and in your function definition, please typehint 'message' parameter as discord.Message
like i’ve been saying lol
yeah ik lol
i dont understand
where do you even call handle_response
message: discord.Message
Of course, since it's this
p_message = discord.Message.lower()
def handle_response(message: discord.Message):
Please note that you need some OOP knowledge to use discord.py comfortably
Good, I suppose
And what's the current problem?
wait let me google typehint real quick
Type hints will not make any difference
@daring ravine your answer is literally this
How?
oh ok but where do i put it?
Bro.
What does it supposed to help?
Are you being serious?
i swear to god im not a troll im just a beginner okay
It's just there to tell the viewers what type an argument is, or occasionally, for the library to parse it for its process
People can have different experiences
sometimes typehinting it genuinely will fix issues like what he's having
Yes
What kind of issue?
it interpreting it as a string
Yes ^^^
That's because they're passing a string
He’s trying to use .content
But a normal string doesn’t have .content attr
no he's passing the message from on_message event
so he needs to typehint his message parameter to discord.Message
I just explained it all here
Oh?
guys i dont want it to be a string if its not what i should use then idont want it to be a string, how the hell do i not make it a string ive asked like 3 times and didnt get a single clear answer
I’ve given you your answer multiple times
???
They're casting it into a string before passing it to the function
oh i didn't see that i thought we were talking about the first argument
what's the question
rn only text info
but if you require attachments from your users then you can do that in an app_command type hinting a parameter with discord.Attachment
hi guys...
!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.
hol on
Please use the paste service to not flood the chat.
anyone knows whats goin on ? i pasted everythin i already tried.
my goal is it that the bot detects the key and the bpm of audios for people on my music server
So from my understanding you send the command -> User sends message with attachment -> If file name ends with .mp3 or .wav send info else ...
i had problems with my commands who weren't working and didn't print anything so thanks to the doc someone sent me i guess i had to use the sync() function but i didn't really understand how to use it, can someone please explain to me ?
here is the code : https://paste.pythondiscord.com/WA2Q
does anyone know why this doesnt work?
import nextcord
from nextcord import Permissions
from nextcord.ext import commands
import sqlite3
import re
class BoostNotify(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.Cog.listener()
async def on_member_update(self, before, after):
if not before.premium_since and after.premium_since:
# User has started boosting the server
print(f"{after.display_name} has boosted the server! Yer")
def setup(bot):
bot.add_cog(BoostNotify(bot))```
Yeah
Looks like the code is outdated
In the newer versions, your setup and extension loading must be asynchronous
Oh this is nextcord
This channel is for discord.py help.
nah
For questions and discussions ... Discord.py and other relevant Python libraries.
do you have an error to share with us?
👍
nah it doesnt give an error
its like it just ignores it but i verified the cog loads with a print statement
in the if
idk i just assumed thats bes way to do it but it doesnt owrk.
I want it to check if a user boosts the server it will send a print statement
wait how are you testing that?
With just print statements.
im checking it by literally boosting the server
ive got 4 accounts all with nitro so i have another 6 boosts
add a print outside the if to check if the event is dispatched at all for that change on the member object
the on_member_update event prints because i have another cog doing it just for nicknames
for debugging purposes
but this, i literally cannot get to function at all
ok, then try to change the if to check if the before premium since is different than the after premium since
dont work
Do you have the members intent enabled?
Yeah
i just got it chuck an error
Traceback (most recent call last):
File "C:\Program Files\Python311\Lib\site-packages\nextcord\client.py", line 490, in _run_event
await coro(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^
TypeError: BoostNotify.on_message() takes 1 positional argument but 2 were given
Ignoring exception in on_message
Traceback (most recent call last):
File "C:\Program Files\Python311\Lib\site-packages\nextcord\client.py", line 490, in _run_event
await coro(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^
TypeError: BoostNotify.on_message() takes 1 positional argument but 2 were given```
```py
@commands.Cog.listener()
async def on_message(message):
if message.type == nextcord.MessageType.premium_guild_subscription:
print("test")```
nvm got it to work
the o member update or the on message
btw what i was wondering here was if the discord api dispatch that event at all when someone boost
i got it to work on this py @commands.Cog.listener() async def on_message(self, message): if message.type == nextcord.MessageType.premium_guild_subscription: pass
😭 nextcord
nextcord only for
s
it's been a couple of month (years maybe) i haven't coding with discordpy... So discordpy isn't dead??
No
Of course its not dead lmao
I doubt discord.py will die.
For a very long time at least.
well when danny left in 2021 due to his frustrations with discord's decisions, they didnt have a maintainer willing to continue developing discord.py so it stayed in limbo for six months, only until danny came back to try consolidating the python discord bot community
Yes i know.
That was a sad time
I contributed to pycord for a while.
Im glad d.py came back.
has he appointed someone to take over the repository if he has to leave again? or will it "live on" in the form of more unofficial forks?
I really havent kept up to date with their ideas exactly. I would assume that someone stepped up and offered their skills to keep the lib alive incase this happens again. Although i couldnt tell you dannys decisions
Has discord implemented a dropdown menu inside modals already?
afaik it used to be in preview like a few years ago last year #discord-bots message , but then they never added it back
as sent last month by someone in the discord developers server (allegedly):
it's been suggested ever since they were added, they said it was coming, half built it for the pc version but stopped development due to mobile issues, then they abandoned it from the looks of it and right now it's still a suggestion
Docs for Banners.
to get a users banner.
@commands.hybrid_command(name="avatar")
@commands.guild_only()
async def avatar(self, ctx, member: discord.Member = None, type: AvatarChoices = AvatarChoices.display):
"""Shows your avatar or the mentioned member's avatar!"""
if not member:
member = ctx.author
if type == AvatarChoices.display:
avatar_url = member.display_avatar.url if member.display_avatar else member.default_avatar.url
else:
avatar_url = member.avatar.url
embed = discord.Embed(
title=f"{member.display_name}'s Avatar",
color=main_color
)
embed.set_image(url=avatar_url)
await ctx.send(embed=embed)```
This is for avatar, but wanna do one for banners, i just need the docs.
!d discord.User.banner
property banner```
Returns the user’s banner asset, if available.
New in version 2.0.
Note
This information is only available via [`Client.fetch_user()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.fetch_user).
i didnt realize the discord api provided banners, thought it'd be locked from bots like the about me
I got it, thank you tho :)
why do i get this error and how do i fixt it
File "c:\Users\trace\Desktop\chicken chicken\chicken wing\ticket.py", line 155, in setup
await client.add_view(TicketView(client))
TypeError: object NoneType can't be used in 'await' expression```
```py
class TicketView(discord.ui.View):
def __init__(self, client:commands.Bot):
super().__init__(timeout=None)
self.client = client
@button(label="Close Ticket", style=discord.ButtonStyle.primary,custom_id="close_ticket")
async def close_ticket(self, button: discord.ui.Button, interaction: discord.Interaction):
await interaction.response.send_message(view=confirm())
async def setup(client:commands.Bot):
await client.add_view(TicketView(client))```
you dont need to await add_view()
adding a view only has to tell pycord what functions it should call when it receives a component interaction, which internally is done by adding a few dictionary keys, so it doesn't need to make any API calls or whatnot
im not using pycord but i see what u mean thanks
oh i assumed pycord given the discord import and (button, interaction) parameter order
where can i host a personal bot for free?
Um. Free is the issue.
Depends on how efficient you want it to be.
A free hoster won't likely be a good option it terms of effiency.
not much
Oracle is the only one without major drawbacks, but you need a credit card
does it support postgres?
Oracle is the only one without major drawbacks
Wasn't there some scandal with Oracle a while back? I think they have a bad rep now when it comes to data security
I dunno maybe
Haven’t really looked into it
If Oracle is a no go then Digital Ocean with GitHub credits ig
Discord.py version is latest version, python is latest version
Whats the output of pip show?
I ran that and it showed everything fine.
I fixed it now, had to forcereinstall
DO has free temp credits system which you can abuse ☺️
def check_dependencies():
assert pycord_version == "2.5.4", (
"you don't have necessary version of Pycord."
" Please install the version specified in requirements.txt"
)
flags = subprocess.CREATE_NO_WINDOW if sys.platform == "win64" else 0
ffmpeg_output = None
try:
ffmpeg_output = check_output(
("ffmpeg", "-version"), text=True, creationflags=flags
).strip()
except (FileNotFoundError, CalledProcessError) as e:
if sys.platform == "win64":
print("Downloading FFmpeg...")
download_ffmpeg()
else:
raise RuntimeError("ffmpeg was not found") from e
if sys.platform == "win64" and ffmpeg_output:
ffmpeg_timestamp = extract_ffmpeg_timestamp(ffmpeg_output)
if ffmpeg_output == OLD_FFMPEG_CONF or (
ffmpeg_timestamp and ffmpeg_timestamp < NEWEST_FFMPEG_TIMESTAMP
):
print("Updating FFmpeg...")
download_ffmpeg()
try:
opus.Encoder.get_opus_version()
except opus.OpusNotLoaded as e:
raise RuntimeError("opus was not found") from e
``` Keeps raising ``RuntimeError("ffmpeg was not found")``
``pip show`` will show output, running ``python -m ffmpeg --version`` returns`` "No module named ffmpeg.__main__; 'ffmpeg' is a package and cannot be directly executed"`` i force reinstalled ffmpeg twice, not sure what to do.
i didn't know it was possible to install ffmpeg with pip, in my pc i installed it separately, maybe you can try this
Alright.
Thats why using ffmpeg sucks
broo
that's not true btw
never had issues with it
Downloading it via python sucks
If you use docker you can just install it via dockerfile
Hi, im trying to get data from sqlite3 and counting how many rows the table has. how do I do this?
Example:
data in table "stocks":
a
b
c
d
I want it to count the number of rows it has, for example on top, there's 4 rows
Here me with 2 gb ram☠️ cant convince me
Yeah as long as you know what you are doing, but you can use a lavalink server :3
Because raptor said he dont want to work on discordpy anymore
SELECT COUNT(*) FROM table?
Old news 
Me when #databases 
So my Database looks like this, I want to count the rows of "stock" how do I do this?
@burnt vale execute that and use cursor.fetchone to get it
ended up doing this
But my table name is shop and column is stock
I want to count the lines in stock
uwu i know what I'm doing
sup
Hi
023-11-09 09:47:41 ERROR discord.client Ignoring exception in on_command_error
Traceback (most recent call last):
File "/home/container/.local/lib/python3.11/site-packages/discord/client.py", line 441, in _run_event
await coro(*args, **kwargs)
File "/home/container/main.py", line 288, in on_command_error
await ctx.reply(
File "/home/container/.local/lib/python3.11/site-packages/discord/ext/commands/context.py", line 741, in reply
return await self.send(content, reference=self.message, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/container/.local/lib/python3.11/site-packages/discord/ext/commands/context.py", line 1024, in send
return await super().send(
^^^^^^^^^^^^^^^^^^^
File "/home/container/.local/lib/python3.11/site-packages/discord/abc.py", line 1561, in send
data = await state.http.send_message(channel.id, params=params)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/container/.local/lib/python3.11/site-packages/discord/http.py", line 681, in request
raise HTTPException(response, data)
discord.errors.HTTPException: 429 Too Many Requests (error code: 0): You are being blocked from accessing our API temporarily due to exceeding our rate limits frequently. Please read our docs at https://discord.com/developers/docs/topics/rate-limits to prevent this moving forward.
idk how i am exeding in rate limit my bot is litrelly idle
Is it replit?
solarhosting is in my opinion the best free hosting
Its just maybe solarhosting uses shared ip like replit too?
maybe cause i have seen it blocked many times
it should be rate limit per bot not per ip
Hm 
Well technically yes, but you sometime get blocked by cloudfare
And will be unable to use the API
my hosting is blocked by cloudfare multiple times
Then no luck 💀
but this is the only best fre hosting with no coins and shit and 1gb ram and 80% cpu there is no better
Check if solarhosting has kill 1 cmd like replit xd
nope did nothing
well i am tired ill go each lunch bye
\ isn't the same as /
uwu

Alright
Yummy free role
Me only uwu guy here
what's the type of connection discord bots and discord use? sockets?
i have no idea what to search on google
Yes
Discord's API is based around two core layers, a HTTPS/REST API for general operations, and persistent secure WebSocket based connection for sending and subscribing to real-time events.
thanks
Can we subscribe to discord downtimes? 🐸
uwu scrape it on intervals
😔
Or just
Get webhook notifications whenever Discord creates an incident, updates an incident, resolves an incident or changes a component status.
Whos going to trigger the webhook to send notification 
Need to scrape manually anyway 
uwu there's a subscribe button at https://discordstatus.com/history#
hit the <> where you can put a webhook URL
Discord's Incident and Scheduled Maintenance History
didn't knew about this until 1 min ago
When I get InteractionTimedOut error notification in bobux I know discord is tripping
most likely it's our host
400ms
Host is in austria with 1gbps speed
did you transfer it?
No cause I got old price which is cheaper
still i don't face 270ms with my local instance
If they ever decide to update price I will transfer to USA
uwu
!hosting
Using free hosting options like repl.it or Heroku for continuous 24/7 bot hosting is strongly discouraged.
Instead, opt for a virtual private server (VPS) or use your own spare hardware if you'd rather not pay for hosting.
See our Discord Bot Hosting Guide on our website that compares many hosting providers, both free and paid.
You may also use #965291480992321536 to discuss different discord bot hosting options.
I thought it sends stuff in email 💀
Me 400-500 ms lmao
I was making a leaderboard fuction for my minigame bot
It worked pretty well
But i want let it have pages
So i edit the code to this
@client.hybrid_command(description='Show score leaderboard')
async def leaderboard(ctx):
leaderboard = db.score.find().sort("score", pymongo.DESCENDING)
paginator = commands.Paginator()
for user in leaderboard:
paginator.add_line(f'{user["user"]} - {user["score"]} points')
for page in paginator.pages:
embed = discord.Embed(title='Tableturf top players ', description=page, color=0x2B32E4)
await ctx.send(embed=embed)```
Why result is this?
What result do you expect
What do u think?
I dont think this is how commands.Paginator works ig, meh not sure never used this class 💀 better to create own
I think your leaderboard has 3 users only
!d discord.ext.commands.Paginator
class discord.ext.commands.Paginator(prefix='```', suffix='```', max_size=2000, linesep='\n')```
A class that aids in paginating code blocks for Discord messages.
len(x) Returns the total number of characters in the paginator.
Are you sure add_line creates a page everytime?
Can you do pip show?
He mean to Run it in terminal
how do i make my bot perform a task every day
like i want a function to be active once every day
!d discord.ext.tasks.loop
@discord.ext.tasks.loop(*, seconds=..., minutes=..., hours=..., time=..., count=None, reconnect=True, name=None)```
A decorator that schedules a task in the background for you with optional reconnect logic. The decorator returns a [`Loop`](https://discordpy.readthedocs.io/en/latest/ext/tasks/index.html#discord.ext.tasks.Loop).
pass a datetime obj or something forgor in time=...
Can I use pygame and turtle with dpy ?
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!
but if you find a way to run them without Block the event loop then sure ig
this is a nice spot
You could with threading, but it’s entirely useless
import discord
from discord.ext import commands
client = commands.Bot(command_prefix = '!', intents=intents)
intents = discord.Intents.all()
@client.event
async def on_ready():
print("Bot is ready!")
print("-------------")
@client.command()
async def on_message():
if message.author == client.user:
return
if message.content.startswith('hi'):
await message.channel.send('Hello!')
client.run('')```
"NameError: name 'Intents' is not defined" what does it mean and how to fix
You defined intents after you used them
This is basic Python
ooohhhhhhhhhh
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
I’d probably start with the fundamentals, then move over to intermediate libraries
Show your current code
hi, discord is buggy actualy?
i have no idea why my contextual menu is not loaded in discord app...
i dont have any error, and the debug command return all cog loaded
import discord
from discord.ext import commands
client = commands.Bot(command_prefix='!', intents=discord.Intents.all())
@client.event
async def on_ready():
print("Bot is ready")
@client.command()
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('hi'):
await message.channel.send('Hello')
client.run('')```
It isn't lol
Unless you’re using it for self botting it is
You’re using a command decorator on an event
What library are you using
What library version, and python version
Were they working before and just stopped, or did you just add them
Your original message infers that they just randomly broke
@final iron no it doesn't work since I coded these features from the beginning
How do i make slash commands? I can’t seem to figure it out.
Help is much appreciated.

The gist doesn’t work, invalid link.
discord.py 2.0+ slash command info and examples. GitHub Gist: instantly share code, notes, and snippets.
thank you.
@final iron how do i print a message?!!?!?
In what context
none
What
Is it an application command, event, prefixed command
I’m going to need more information than that
Also what do you mean by “a message”? The message content?
print (aaaa)
I know what print is
???
what does this code do
import asyncio
class UppercaseMeta(type):
def __new__(cls, name, bases, dct):
uppercase_dct = {key.upper(): value for key, value in dct.items() if callable(value)}
return super(UppercaseMeta, cls).__new__(cls, name, bases, uppercase_dct)
class MyClass(metaclass=UppercaseMeta):
async def async_method(self):
await asyncio.sleep(1)
print("Async Method")
obj = MyClass()
def log_execution_time(func):
async def wrapper(*args, **kwargs):
import time
start_time = time.time()
result = await func(*args, **kwargs)
end_time = time.time()
print(f"Execution time: {end_time - start_time} seconds")
return result
return wrapper
obj.async_method = log_execution_time(obj.async_method)
async def main():
await obj.async_method()
# Run the event loop
asyncio.run(main())```
I mean the function name is very telling. It’s for logging execution time
So why are you asking
Because someone sent me it
Timeout commands so difficult 😭😭💀💀
Why? It should just be like, one line
me when await member.timeout(datetime.timedelta(days=1))
exactly
Saves you from the hassle of worrying about un-timeing out on time, handling disconnects, bot going complete offline, etc
no prob. are you using the built in timeout feature?
no.
ah, might be why

when i do " pip install discord.py" or install disnake it gives me the error
Could not build wheels for aiohttp, frozenlist, multidict, yarl, which is required to install pyproject.toml-based projects
then it tells me to install Microsoft Visual C++ 14.0 or greater which I already have but it still doesnt work.
yarl (a dependency of aiohttp (a dependency of discord.py)) doesn't support Python 3.12 yet
Yes
thanks
also is discord.py discontinued so will i have to use some fork of it or no?
nvm
Its like old news 🙂 dpy alive again, the same person started maintaining the lib in 2021 xd
oh ok thanks
can someone help me with bot? pls
i need to write bot that will disconnect a specific user from voice channel on server
Send your current code and we can help you.
import discord
from discord.ext import commands
Создаем экземпляр бота
bot = commands.Bot(command_prefix='!')
Указываем ID мембера, которого хотим отключать
member_id = 123456789
Функция, которая проверяет все голосовые каналы на сервере
async def check_voice_channels():
# Получаем список всех голосовых каналов на сервере
voice_channels = bot.get_guild(987654321).voice_channels
# Перебираем все каналы
for channel in voice_channels:
# Получаем список всех мемберов в канале
members = channel.members
# Перебираем всех мемберов
for member in members:
# Если мембер совпадает с указанным ID
if member.id == member_id:
# Отключаем его от канала
await member.move_to(None)
# Выводим сообщение в консоль
print(f'Отключил {member.name} от {channel.name}')
Команда, которая запускает проверку голосовых каналов
@bot.command()
async def check(ctx):
# Вызываем функцию проверки
await check_voice_channels()
# Отправляем сообщение в чат
await ctx.send('Проверил все голосовые каналы.')
Запускаем бота с токеном
bot.run('TOKEN')
#here description on russian but you will understand
wtf with code
member.move_to(None) should disconnect the user
yeah
Can you show me your error.
Then why are you asking for help.
Um. There are some parts of the code that are unnecessary.
But i guess it should work.
k, thx
Hi, I have a question about discord messages scrapper
Is it possible to create this without using discord API?
I think it's against the terms of service to gather server/user information without their consent, and at that point just use a client, but it will probably not be a good scraper
technically, no. But Im not allowed to help toy with this.
Can someone help me please?
I'm trying to bring as a default input the variable that has been received from the building function but I keep getting this annoying limit.
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In data.components: Must be between 1 and 5 in length.
This is my code:
class EditEmbed(ui.Modal):
def __init__(self, embed_title):
super().__init__(title="Edit Embed", timeout=None, custom_id="edit embed")
self.embed_title = embed_title
self.embed_title_input = ui.TextInput(label="Title", style=discord.TextStyle.short, placeholder="Insert Title", required=True, max_length=100, custom_id="title", default=embed_title)
You didn't set any text inputs to the modal 
See this example for how to correctly create modals
An API wrapper for Discord written in Python. Contribute to Rapptz/discord.py development by creating an account on GitHub.
I'm aware how to create modals, the issue is that I'm trying to take the embed_title with its value, and when I'm doing it outside of the constructor, I don't have the ability to use it, as it's not defined.
If you did it the same way as the example do, you can just access it from self since they are class variables
!e
class A:
var = 0
def something(self):
print(var)
A().something()
@naive briar :x: Your 3.12 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "/home/main.py", line 6, in <module>
003 | A().something()
004 | File "/home/main.py", line 4, in something
005 | print(var)
006 | ^^^
007 | NameError: name 'var' is not defined. Did you mean: 'self.var'?
Good explanation
Yep, but you're doing it with a function
So you're basically saying I need to create a function that will include all the inputs?
No?
So..?
So what?
I'm incapable of using the self
I don't understand what that means
You gave me an example here of how can I call the variable, while you used a function.
I'm not using a function, that's why I can't call the self.[variable]
And you told me to not create a function.
Thus I don't understand how to solve this
What do you mean you're not using a function?
I'm not using a function when adding text inputs
Like here

That example isn't using any function to create any either
It's setting the name and feedback text inputs as the class variables
Or am I misunderstanding something
Yes? But they're also being set as class variables, that's how discord.py get them
Just set your text inputs as class variables, instead of setting them as just attributes that discord.py won't recognise
What’s the point of doing this instead of just in the init
Because it gives me
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In data.components: Must be between 1 and 5 in length
Are you adding them?
Show what
!d discord.ui.Modal.add_item
add_item(item)```
Adds an item to the view.
This function returns the class instance to allow for fluent-style chaining.
If you’re doing it in the init you need to add them with this
If you don't need to set TextInputs dynamically, you're just making life harder for nothing this way
Thanks I figured it out
guys can discord.py be used with python 3.12?
One of its dependencies has a beta release for 3.12
aiohttp?
Ye
will other deps work?
I haven't encountered errors from other dependencies for 3.12
👍
can you make hybrid commands with cogs?
i tried but it giving error
File "d:\Projects\Python\FedxD PlayPal\main.py", line 27, in <module>
import handlers
File "d:\Projects\Python\FedxD PlayPal\handlers\__init__.py", line 2, in <module>
from handlers import setup
File "d:\Projects\Python\FedxD PlayPal\handlers\setup.py", line 32, in <module>
class Setup(Cog):
File "d:\Projects\Python\FedxD PlayPal\handlers\setup.py", line 35, in Setup
@commands.hybrid_command(name="setup", description="Setup The Bot")
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\abbas\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ext\commands\hybrid.py", line 893, in decorator
return HybridCommand(func, name=name, with_app_command=with_app_command, **attrs) # type: ignore # ???
File "C:\Users\abbas\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ext\commands\hybrid.py", line 503, in __init__
super().__init__(func, **kwargs)
File "C:\Users\abbas\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ext\commands\core.py", line 406, in __init__
self.callback = func
^^^^^^^^^^^^^
File "C:\Users\abbas\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ext\commands\core.py", line 513, in callback
self.params: Dict[str, Parameter] = get_signature_parameters(function, globalns)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\abbas\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ext\commands\core.py", line 130, in get_signature_parameters
raise TypeError(f'Command signature requires at least {required_params - 1} parameter(s)')
TypeError: Command signature requires at least 1 parameter(s)```
the error
i got this issue resolved but my hybrid commands wont work it just dont show on the app command but it works on the prefix commands
have you synced your command tree?
yes
do i have to do it in all cogs?
or just the main file
i have it on my main file
?
you have to load your cogs/extensions first, then sync your tree once
async def setup_hook(self):
await self.tree.sync()
print(f"Synced slash commands for {self.user}.")
await self.add_cog(handlers.setup.Setup(self))
await self.add_cog(handlers.lvlhandler.LevelHandler(self))
await self.add_cog(handlers.money.Money(self))
await self.add_cog(handlers.profile.Profile(self))
print(f"Loaded Cogs for {self.user}.")```
this good?
so yeah, put the sync at the end
does
@tasks.loop()
work in Cogs?
@discord.ext.tasks.lopp()
err basically yeah
i dont think so they do
its what ive done for my reminders system in my old bot
https://github.com/thegamecracks/thegamebot/blob/v2/bot/cogs/reminders.py#L494-L495
bot/cogs/reminders.py lines 494 to 495
@tasks.loop(minutes=10)
async def send_reminders(self):```
oh yeah i forgot it was documented
what wasn't documented was the fact that it works across multiple instances of one class
pretty convenient for refreshing my server statuses
@tasks.loop(minutes=1)
async def interest():
db.execute("SELECT * FROM tasks WHERE name = ?", ("interest",))
task = db.fetchone()
servers = []
if task is None:
db.execute("INSERT INTO tasks VALUES (?, ?)", ("interest", 0))
else:
if task[1] == 2:
db.execute("UPDATE tasks SET minutes = ? WHERE name = ?", (0, "interest"))
db.execute("SELECT * FROM guilds")
guilds = db.fetchall()
for guild in guilds:
serverdb = sql.connect(f"servers/{guild[0]}.db")
server = serverdb.cursor()
server.execute("SELECT * FROM profiles")
profiles = server.fetchall()
servers.append(serverdb)
for profile in profiles:
bank = profile[2]
interest = profile[3]
interest = interest / 100
interest = interest * bank
bank += interest
server.execute(
"UPDATE profiles SET bank = ? WHERE user_id = ?",
(bank, profile[0]),
)
for server in servers:
server.commit()
server.close()
print("Bank Interest Updated")
else:
db.execute(
"UPDATE tasks SET minutes = ? WHERE name = ?", (task[1] + 1, "interest")
)
main_db.commit()
i dont think this have worked ever
cause else it would create a thing
a row in a db
Debug
it didnt even made a db thing idk what is wrong twith this
As said, debug
ok i guess
Put some logs and check where it's failing or where it's not acting the way you want
if its in a class you need the self parameter, same way you fixed your hybrid command
oh
i guess that should fix the thing
the maindb still dont have the thing entered
so i guess its not working
what do i do
its something off with the loop command else is sorted
it would atleast print something when it runs which it is not doing
where did you start the loop?
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.
!paste
you uh messed up the indentation, but regardless the loop hadnt been started anywhere
it the paste thingy fking the indentation wait lemme fix it
i usually just use __init__ to start the loop
https://github.com/thegamecracks/thegamebot/blob/v2/bot/cogs/reminders.py#L156
bot/cogs/reminders.py line 156
self.send_reminders.start()```
well if your loop was already running you wouldn't really need to start it again
you need to call .start() somewhere outside of it
so i just need to call it once
oh
i can make owner commands to start and stop the loop
see also documentation
https://discordpy.readthedocs.io/en/stable/ext/tasks/index.html
oh
guys can we load an extension from an absolute path?
If you can import it as a module, sure
can i pass the load_extension an absolute path?
No
hmm, thats a issue
well it is working now thanks
Demn
i have path issues in relative paths, is there any way i can pass it absolute path?
glob
i get this if i use relative path
ModuleNotFoundError: No module named 'extensions'
Its looking for a module
Try adding init.py
Not sure what are you trying to do but since catty knows the context he may help u better
if it is skill issue, how can i do that easily in js,
i making a extension watcher
Its not like python is "bad at paths" its just you not knowing how to do in python but in js
It's just how they design import stuff 
ye i guess i am wrong
Oh file watcher?
I would use disnake tbh 💀
You can reload extensions using bot.reload_extension with a prefix command, maybe 
but why i get such error?
even my file exists
How and where are you running the bot?

i runnign using
python -m src
Python might be taking the current working directory when you run python stuff.py
i tried doing src.extensions.test.ext
(I don't really know though
)
it not worked
Sec
i am confused with what i doing
you shouldn't have to specify src
Usually I have a src/bot/exts so I can do from bot imports exts or similar
i fixed it
somehow
i changed it to
await self.load_extension(".extensions.test.ext")
i added "." in front
Lol wtf i was about to tell it but then catty came in so i just didnt send the message 💀💀💀

only if you use python -m path.to.main, for python path/to/main.py it adds the script directory to the import path instead of CWD
(see also https://docs.python.org/3/library/sys.html#sys.path)
relative imports are usually not recommended
favor absolute imports if possible
i again got error
discord.ext.commands.errors.ExtensionNotFound: Extension '.extensions.test.ext' could not be loaded.
Huh more sus
this is my file struct
eh i only recommend against them if it requires a .. parent import, which i used to do until i realized it was quite confusing to read from ...foo.bar import baz
come to think of it ive never named a python script with more than one period, but it looks like python refuses to import it if you do that
i suggest naming it test_ext.py instead so it can be imported via .extensions.test_ext
You can use pathlib ig
What is the problem?
@shrewd fjord
Did you install discord.py?
Do you have a virtual environment activated?
Is the VSCode interpreter version the same as what pip refers to?
!dashmpip
When trying to install a package via pip, it's recommended to invoke pip as a module: python -m pip install your_package.
Why would we use python -m pip instead of pip?
Invoking pip as a module ensures you know which pip you're using. This is helpful if you have multiple Python versions. You always know which Python version you're installing packages to.
Note
The exact python command you invoke can vary. It may be python3 or py, ensure it's correct for your system.
your_package is supposed to be the name of your package. Try py -3 -m pip install discord.py
Now try running your script - py -3 <bot-file>.py
Replace <bot-file>.py with whereever your main bot is
@kind roost
No, in your terminal, when you run the command, run your main bot file by specifying it's path
;-; from where
Um ok ig, lets not talk about this stuff here, its off-topic xd
interaction object changed author attribute to user?
!d discord.Interaction.user
The user or member that sent the interaction.
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\avira\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\discord\app_commands\tree.py", line 1248, in _call
await command._invoke_with_namespace(interaction, namespace)
File "C:\Users\avira\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\discord\app_commands\commands.py", line 853, in _invoke_with_namespace
return await self._do_call(interaction, transformed_values)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\avira\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\discord\app_commands\commands.py", line 846, in _do_call
raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'update' raised an exception: AttributeError: 'Interaction' object has no attribute 'author'
see
This .user will return Member obj if its in guild, and will return User if dm channel
.
does this mean interaction.author never existed?


You should reset your token
create .env for you token, quick 📸📸📸
DATABASE is updated but showing error on terminal and discord
Hi guys, I had a question please. I'm a beginner to python(still learning) and my first project would be a discord bot that would display live match results(for exemple). I wanted to know if it was possible to retrieve this data from a website to display it with the bot ? Thanks in advance 🙂 !
yes. find a website that has an api or websocket, retrieve the information using the appropriate http request, then display the information as you wish through your bot
that sounds like a lot but its not difficult once you learn what an api/websocket is
More or less 10 lines of code
For a simple implementation
Look into aiohttp, discord.py and http requests in general
thank you very much guys, I'll look into this
!d discord.User
class discord.User```
Represents a Discord user.
x == y Checks if two users are equal.
x != y Checks if two users are not equal.
hash(x) Return the user’s hash.
str(x) Returns the user’s handle (e.g. `name` or `name#discriminator`).
!d discord.Member
class discord.Member```
Represents a Discord member to a [`Guild`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild).
This implements a lot of the functionality of [`User`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User).
x == y Checks if two members are equal. Note that this works with [`User`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User) instances too.
x != y Checks if two members are not equal. Note that this works with [`User`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User) instances too.
hash(x) Returns the member’s hash.
str(x) Returns the member’s handle (e.g. `name` or `name#discriminator`).
The user’s unique ID.
property id```
Equivalent to [`User.id`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User.id)
@bot.tree.command(name="getuser", description="get user description")
@app_commands.describe(userid = "discord id of user")
async def getuser(interaction: discord.interactions, userid: discord.Member.id):
c.execute('SELECT * FROM userdata WHERE user_id = ?', (userid,))
user_data = c.fetchone()
if user_data:
userid, username, birth_year, biodrop = user_data
embed = discord.Embed(title=f"{username}", description=f"Used ID: `{userid}`\nBirth Year: `{birth_year}`, Biodrop: {biodrop}", color=0xff0000)
await interaction.response.send_message(embed=embed, ephemeral=True)
else:
await interaction.response.send_message("no info found in database", ephemeral=True)
ERROR:
Exception has occurred: TypeError
unsupported type annotation <property object at 0x00000203AE09CC70>
File "D:\Projects\Python\D4\memberInfoBot\bot.py", line 94, in <module>
@bot.tree.command(name="getuser", description="get user description")
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: unsupported type annotation <property object at 0x00000203AE09CC70>
how suppose i do the command only check able by the user who used command?
like this
!d discord.MessageFlags.ephemeral
Returns True if the source message is ephemeral.
New in version 2.0.
@commands.hybrid_command(name="banner")
@commands.guild_only()
async def banner(self, ctx, member: discord.Member):
"""Shows the banner of the mentioned member in the server."""
user_id = member.id
try:
user = await self.bot.fetch_user(user_id)
except discord.NotFound:
embed = discord.Embed(
title=f"Error",
description="User not found.",
color=error_color
)
await ctx.send(embed=embed)
return
try:
banner_url = user.banner.url
embed = discord.Embed(
title=f"{user.display_name}'s Banner",
color=main_color
)
embed.set_image(url=banner_url)
await ctx.send(embed=embed)
except AttributeError:
embed = discord.Embed(
title=f"{user.display_name}'s Banner",
description="This user is poor and can't afford NITRO.",
color=main_color
)
await ctx.send(embed=embed)
How to get a banner from a user for that GUILD
Kinda like a display pfp/avatar but display banner..?
!d discord.Member.banner
property banner```
Equivalent to [`User.banner`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User.banner)
It should return the current guild banner if member is used. If user is used then it would be a global banner.
How can i send a Webhook message like i have a Webhook link, and i want to send something to that webhooks
!d discord.Webhook.from_url
classmethod from_url(url, *, session=..., client=..., bot_token=None)```
Creates a partial [`Webhook`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Webhook) from a webhook URL.
Changed in version 2.0: This function will now raise [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError) instead of `InvalidArgument`.
!d discord.Webhook.send
await send(content=..., *, username=..., avatar_url=..., tts=False, ephemeral=False, file=..., files=..., embed=..., embeds=..., allowed_mentions=..., view=..., thread=..., ...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Sends a message using the webhook.
The content must be a type that can convert to a string through `str(content)`.
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.
If the `embed` parameter is provided, it must be of type [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed) and it must be a rich embed type. You cannot mix the `embed` parameter with the `embeds` parameter, which must be a [`list`](https://docs.python.org/3/library/stdtypes.html#list) of [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed) objects to send.
Changed in version 2.0: This function will now raise [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError) instead of `InvalidArgument`.
You cannot typehint an argument as discord.Member.id
https://discord.com/developers/docs/interactions/application-commands#application-command-object-application-command-option-type
These types can be translated to Python or discord.py types and used as typehints for slash commands.
STRING ->
- str
- app_commands.Range[str, min_length, max_length]
INTEGER -> does not support IDs
- int
- app_commands.Range[int, min_value, max_value]
BOOLEAN -> bool
USER -> in a guild, you will receive a member regardless of typehint, but it will not have presence data
- discord.User
- discord.Member
- Union[discord.Member, discord.User]
CHANNEL -> Union containing any number of these types is supported
- discord.Thread
- discord.abc.GuildChannel - all below
- discord.CategoryChannel
- discord.ForumChannel
- discord.StageChannel
- discord.VoiceChannel
- discord.TextChannel - text, news
ROLE -> discord.Role
MENTIONABLE -> Union with any combination of USER and ROLE
NUMBER ->
- float
- app_commands.Range[float, min_value, max_value]
ATTACHMENT -> discord.Attachment
Notes:
Rangebounds may beNoneto remain default.
Minimum and maximum values can be found in the option structure above the list of types.Transformercan be used for any types not listed above.
https://discordpy.readthedocs.io/en/stable/interactions/api.html#discord.app_commands.Transformer- Parameters can be made optional by giving them a default value or typehinting as
typing.Optional[X]orX | None
if I am using discord.User what data type will be stored?
discord.Member if it's sent in a guild, discord.User if not
discord.User is a int type or str type?
class discord.User```
Represents a Discord user.
x == y Checks if two users are equal.
x != y Checks if two users are not equal.
hash(x) Return the user’s hash.
str(x) Returns the user’s handle (e.g. `name` or `name#discriminator`).
okkkk
thumbnail
i did but it not worked
guys why my bot is not coming online and not working?
from rich import print
from pathlib import Path
from discord import Intents
from discord.ext import commands
from .utils.watcher import ExtsWatcher
class MyBot(commands.Bot):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
async def setup_hook(self) -> None:
print("[bold green]Bot is ready![/bold green]")
print(
"[bold green]Logged in as[/bold green]: [bold blue]"
+ str(self.user)
+ "[/bold blue]",
)
await self.load_extension(".extensions.test_ext", package=__package__)
watcher = ExtsWatcher(self, Path(__file__).parent / "extensions")
await watcher.start()
bot = MyBot(command_prefix=".", intents=Intents().all())
(.venv) ╭─ pwsh dbot ≢ 17s 765ms⠀ .venv 3.11.3 11,11:23
╰─ python -m src
2023-11-11 11:23:55 INFO discord.client logging in using static token
Bot is ready!
Logged in as: honey singh#4433
You’re not running it
You need to use start
!d discord.Client.start
await start(token, *, reconnect=True)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
A shorthand coroutine for [`login()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.login) + [`connect()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.connect).
i doing
__main__.py
from .bot import bot
from .constants import Constants
if __name__ == "__main__":
bot.run(Constants.TOKEN, reconnect=True)
Why are you importing a variable
i guess something is blocking my code
looks like th watcher is blocking
my bot worked when i remove that
thats not issue
Sure, but answer the question
What benefits does importing your bot object have over just running it directly in the file
so that i can run it ussing python -m src , i have run code in main.py , so i keep my code clean and green
but my this is blocking, idk how to fix it
class ExtsWatcher:
def __init__(self, bot: Bot, exts_path: Path) -> None:
self.bot = bot
self.exts_path = exts_path
async def start(self) -> None:
while self.exts_path.exists():
try:
async for changes in awatch(self.exts_path):
if not self.exts_path.exists():
raise FileNotFoundError
for change in sorted(changes, reverse=True):
change_type = change[0]
change_path = change[1]
ext_path = Path(change_path)
if (ext_path.suffix == ".py") & (
ext_path.stem.split(".")[-1] == "ext"
):
if change_type == Change.deleted:
if "extensions." + str(ext_path.stem):
print("deleted")
except FileNotFoundError:
continue
async def setup_hook(self) -> None:
print("[bold green]Bot is ready![/bold green]")
print(
"[bold green]Logged in as[/bold green]: [bold blue]"
+ str(self.user)
+ "[/bold blue]",
)
await self.load_extension(".extensions.test_ext", package=__package__)
watcher = ExtsWatcher(self, Path(__file__).parent / "extensions")
await watcher.start()
Start the watcher in a thread or smth
Run it parallel,,
i use threading module for that right?
Yeah
You can use create_task from asyncio too maybe
Uh wait Thread target do not accept async functions i think
!d asyncio.to_thread
coroutine asyncio.to_thread(func, /, *args, **kwargs)```
Asynchronously run function *func* in a separate thread.
Any \*args and \*\*kwargs supplied for this function are directly passed to *func*. Also, the current [`contextvars.Context`](https://docs.python.org/3/library/contextvars.html#contextvars.Context) is propagated, allowing context variables from the event loop thread to be accessed in the separate thread.
Return a coroutine that can be awaited to get the eventual result of *func*.
This coroutine function is primarily intended to be used for executing IO-bound functions/methods that would otherwise block the event loop if they were run in the main thread. For example:
!e
from threading import Thread
async def f():
...
Thread(target=f).start()
@shrewd fjord :white_check_mark: Your 3.12 eval job has completed with return code 0.
001 | /lang/python/default/lib/python3.12/threading.py:989: RuntimeWarning: coroutine 'f' was never awaited
002 | self._target(*self._args, **self._kwargs)
003 | RuntimeWarning: Enable tracemalloc to get the object allocation traceback
Huh just a runtime error
@robust fulcrum
not worked
C:\Users\dell\AppData\Local\Programs\Python\Python311\Lib\asyncio\base_events.py:1923: RuntimeWarning: coroutine 'ExtsWatcher.start' was never awaited
handle = None # Needed to break cycles when an exception occurs.
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
async def setup_hook(self) -> None:
print("[bold green]Bot is ready![/bold green]")
print(
"[bold green]Logged in as[/bold green]: [bold blue]"
+ str(self.user)
+ "[/bold blue]",
)
await self.load_extension(".extensions.test_ext", package=__package__)
watcher = ExtsWatcher(self, Path(__file__).parent / "extensions")
await to_thread(watcher.start)
You don’t call it
wdym?
Is this the current code
what do i don't call?

The function you’re passing
i get error then
Which is…?
2 mins
thats an async func, it not works if i pass it watcher.start()
Yeah, like the documentation and I said, you need to pass a function object
It’s clear you haven’t checked the documentation as it literally shows an example
bro it doesn't mean i haven't checked
the func is sync in docs
i guess to_thread is for sync functions
you mean i put await in fornt of func
No
You’re not awaiting any coros so it doesn’t need to be asynchronous in this situation
oh you mean i make the start func sync
but i can't do
cause i have to load cogs in that
and some async stuff
You’re not loading any cogs in it in the code sample you showed
i will in future
i wana make it work atleast now
What’s wrong with loading your cogs in setup_hook as you are now
is there any other way than to_thread?
i making a cogs watcher
Probably some convoluted method
whats convoluted?
i fixed it
asyncio.get_event_loop().create_task(
ExtsWatcher(self, Path(__file__).parent / "extensions").start()
)
thank you all though
Was telling you can use create_task from asyncio lol
how can i make captcha slover?
ty for that, sry if i ignored that
What captcha?
💀💀Nah i aint helping in illegal activities xd
But if its not, just let me tell you,. If you like ever created a captcha solver somehow, you wont be able to keep up the amount of captchas are now here these days, every morning every new captcha, But yeah you can create one with manually collecting vast amount of datas
Hey
I have a problem with a ping logger my code is not detecting here and everyone as a role
Does anyone know how to fix this
Because they technically are not a role
how can i detect it
wait no
everyone pings are literally just @everyone
!d discord.Message.mention_everyone
Specifies if the message mentions everyone.
Note
This does not check if the @everyone or the @here text is in the message itself. Rather this boolean indicates if either the @everyone or the @here text is in the message and it did end up mentioning.
^
uwu
worked
possible to split it between here and everyone
cause mention_everyone returns only true and not the role name
Use compound if condition
if message.mention_everyone and "@everyone" in message.content```
Like that
the content is empty
Enable message content intent
okay thx
if i reply to a message with a command is it possible to get the id of the message i replied to
Yes
!d discord.ext.commands.Context.author
Union[User, Member]: Returns the author associated with this context’s command. Shorthand for Message.author
no not this, for example if i reply to ur message with a command i want the bot to be able to get your id
!d discord.Message.reference
The message that this message references. This is only applicable to messages of type MessageType.pins_add, crossposted messages created by a followed channel integration, or message replies.
New in version 1.5.
ty
word = random.choice(get_words())
display_word = ""
for letter in word:
if letter in guessed_letters:
display_word += letter
else:
display_word += "_"
why this now working with discord
does forloop dont go well with discord bots?
For loops work fine
Define “not working”
this what came up for word riddle
it just not processing words it keep gliching out words as you play
it just really messes up i have to go or ill show you the live example
Well yeah, that’s what happens when the letter isn’t in guessed_letters
else it should display _
but it only give 2 for the word riddle with is 6 long
when i guess correct words it goes crazy as hell
@final iron come in dm ill show u
You can show me here just fine
i cant show like every responce here with ease you can jsut join the test server and can leave later
