#discord-bots
1 messages ยท Page 899 of 1
@commands.Cog.listener()
async def on_command_error(self,ctx,error):
if isinstance(error,commands.MissingPermissions):
await ctx.send("You can't do that")
await ctx.message.delete()
right here
That's eating up all your errors
What's wrong?
no like when the bot prints smth in the console
Then run a function or coro once you print something
You only have a single if statement, so if the error isn't of instance commands.MissingPermissions, its ignored
print("somethin")?
So what should I do to get it fixed?
print("something")
on_print()
Make sure you print the error regardless of if its an instance or not
STOP COPYING ME 
Or consider using cog only errors
How do I make it delete the command message? I did ctx.delete() but keep getting this error
@bot.command()
async def verify(ctx):
verified_role = get(ctx.guild.roles,name="Verified")
guild = ctx.guild
if ctx.channel.id == 945078080194621490:
await ctx.author.add_roles(verified_role)
embed1 = nextcord.Embed(title='Verified!', description = f"You have been verified successfully in {guild}!", color=nextcord.Color.green())
await ctx.author.send(embed=embed1)
await ctx.delete()
return
else:
return
on_command_error is global and it picks up every single error which sometimes can't be ideal (like now)
ctx.message.delete()
ctx.message.delete()
Ah, so what should I change it to.
on_print is the event right? so then what goes after it to detect what was printed?
something like:
async def on_command_error(...)
if isinstance(...):
# do something here
print(error) # very important
print("something")
on_print("something")
@commands.Cog.listener()
async def on_command_error(self,ctx,error):
if isinstance(error,commands.MissingPermissions):
await ctx.send("You can't do that")
await ctx.message.delete()
print(error)
``` Just like that
Though it really feels like an XY problem to me
!e on_print("s")
i've never seen this
https://xyproblem.info/, i feel like what you're asking is what you think is a solution to another bigger problem
Me?
Make sure you unindent the print
So it always runs, instead of conditionally
ah okay
Alternatively
async def on_command_error(...):
if isintance(...):
# do something
else:
print(error) # very important
@commands.Cog.listener()
async def on_command_error(self,ctx,error):
if isinstance(error,commands.MissingPermissions):
await ctx.send("You can't do that")
await ctx.message.delete()
else:
print(error)
But printing the error won't really be all that descriptive, use the traceback library to print the entire traceback
Uh okay, will this fix my problem though?
import traceback
traceback.print_tb(error.__traceback__)
Yes, you should start getting errors again
Hope so
Give it a whirl and see what happens
yo no comprendo
never defined error uh
I'm really thinking this is an XY problem. I'm assuming having an "on print" event is what you think is a solution to a different problem. What is the bigger problem you're trying to solve?
Well, at least you're getting errors now
Yeah lmao
Well from here on our you get all the errors and the problem is with other parts of your code
@commands.Cog.listener()
async def on_command_error(self,ctx,error):
if isinstance(error,commands.MissingPermissions):
await ctx.send("You can't do that")
await ctx.message.delete()
else:
print(error)
``` How should I define error.
You already have error provided to you in the error handler
im trying to make it so whenever i have an error, i can have it print smth and if that's printed then an event will send me a message in discord so i dont have to keep switching tabs and searching through the console
I mean that's what the error says, doesn't it?
True, let's see
i gtg
Aha, there you go. Use an error handler for that, not an on print event
Knew that was an XY
oh right i forgot that was a thing
cool
What was above it?
Looks like you chopped off the error
Yep xD
Hmmm
Should I do OSError?
No don't do that
oki
That's odd it should be defined
I guess remove the else and move print(error) to the function scope?
Maybe like
@commands.Cog.listener()
async def on_command_error(self,ctx,error):
if isinstance(error,commands.MissingPermissions):
await ctx.send("You can't do that")
await ctx.message.delete()
print(error)
That is very strange indeed
Search print(error) in your files
You might have it somewhere else not in the error handler
There is none somewhere else
Ok
I just did
@junior verge instead of on_command_error try cog_command_error
so I'm not sure what's going on but my cog/group doesn't seem to be registering andI'm not getting any errors that would suggest there's a problem. I'm starting my bot like this to load the extensionspy async def start_bot(self): COG_PATH = pathlib.Path("../cogs/") for extension in COG_PATH.glob("*.py"): if extension.name != "__init__.py": print(extension) try: self.load_extension(extension) except Exception: print(f"Failed to load extension {extension}.", file=sys.stderr) print(traceback.print_exc()) await self.start(token)I then actually start the bot herepy loop = asyncio.get_event_loop() if __name__ == '__main__': loop.run_until_complete(client.start_bot())and this is the cog/group I'm trying to add```py
import discord
#from utils.helpers import userinfo
from typing import Union
from discord import Member, User, Interaction, Embed
from discord.app_commands import Group, command, describe
class User(Group):
def init(self, client):
self.bot = client
@command()
@describe(user="The discord user to get information for.")
async def info(self, interaction: Interaction, member: Union[Member, User] = None):
await _userinfo_(interaction, member)
def setup(client):
client.add_cog(User(client))```
It's not an event, just you have to override it
Same error
class MyCog(commands.Cog):
...
async def cog_command_error(self, ctx: commands.Context, error: CommandError):
print(error)
You don't need the decorator just override it
yo guys, i am new to the python discord sever and python. Can you guys help me with a discord bot, i want to make one but i just dont know the ideas to
The entry point of your bot start_bot() should be started using asyncio.run()
You should try this to see what args are provided to there
@commands.Cog.listener()
async def on_command_error(*args):
print(args)```
@junior verge
that's a good idea
lets see
what's the difference? thanks for the advice but not really the root problem as the bot does run/start
YE SYES YES
If you are new to programming overall (no experience with other languages) I don't recommend starting with a discord bot
@sick birch Man I love you
@vale wing as well absolute ๐
Yessss
No clue tbh
Now we got another error, it'll be just simple I guess
import discord, datetime, time
from discord.ext import commands
class Uptime(commands.Cog):
def __init__(self, client):
self.client = client
@commands.command(pass_context=True)
async def uptime(self, ctx):
start_time = time.time()
current_time = time.time()
difference = int(round(current_time - start_time))
text = str(datetime.timedelta(seconds=difference))
embed = discord.Embed(colour=ctx.message.author.top_role.colour)
embed.add_field(name="Uptime", value=text)
embed.set_footer(text="Daxbot.com")
try:
await self.client.send(embed=embed)
except discord.HTTPException:
await self.client.send("Current uptime: " + text)
def setup(client):
client.add_cog(Uptime(client))
``` Uptime object has no attribute ctx
pass_context deprecated
Someone actually following pep8 
What should it be?
Just remove it entirely
Remove that param at all
Could you show the full traceback
I don't have a full error now anymore
Because of the error handller all shows is this
And please show how is your client defined
Just comment it out temporarily
Cause I have a suspicion that it is discord.Client and not a commands.Bot
Ok this is a different error
Yeah
But seems like client is bot
is it dw
yes
then its await ctx.send?
That's just in case
The upper exception please
Use ctx.send
uh sure
Not self.client.send
yeah sorry
Okay so, my uptime command works, but just does not update lmao
import discord, datetime, time
from discord.ext import commands
class Uptime(commands.Cog):
def __init__(self, client):
self.client = client
@commands.command()
async def uptime(self, ctx):
start_time = time.time()
current_time = time.time()
difference = int(round(current_time - start_time))
text = str(datetime.timedelta(seconds=difference))
embed = discord.Embed(colour=ctx.message.author.top_role.colour)
embed.add_field(name="Uptime", value=text)
embed.set_footer(text="Daxbot.com")
try:
await ctx.send(embed=embed)
except discord.HTTPException:
await ctx.send("Current uptime: " + text)
def setup(client):
client.add_cog(Uptime(client))
``` code btw
Cause start_time and current_time are almost the same as you define them both inside of the command
Which one should be outside?
ok i still cant figure this out
You would want to make start_time a bot var
client = commands.Bot(...)
client.start_time = time.time()```
Uh, lemme check
Still does not update
import discord, datetime, time
from discord.ext import commands
start_time = time.time()
class Uptime(commands.Cog):
def __init__(self, client):
self.client = client
@commands.command()
async def uptime(self, ctx):
current_time = time.time()
difference = int(round(current_time - start_time))
text = str(datetime.timedelta(seconds=difference))
embed = discord.Embed(colour=ctx.message.author.top_role.colour)
embed.add_field(name="Uptime", value=text)
embed.set_footer(text="Daxbot.com")
try:
await ctx.send(embed=embed)
except discord.HTTPException:
await ctx.send("Current uptime: " + text)
def setup(client):
client.add_cog(Uptime(client))
``` How should I do it tho?
Well personally I would use bot var as I said
Define it where you define client and then you can access it like
self.client.start_time```
Why
I don't know
Could you show how you assigned it to your client
wym
This
Sry I gotta go maybe someone else will be able to help you cya
Can anyone help me please
import discord, datetime, time
from discord.ext import commands
class Uptime(commands.Cog):
def __init__(self, client):
self.client = client
client = commands.Bot()
client.start_time = time.time()
@commands.command()
async def uptime(self, ctx):
current_time = time.time()
difference = int(round(current_time - self.client.start_time))
text = str(datetime.timedelta(seconds=difference))
embed = discord.Embed(colour=ctx.message.author.top_role.colour)
embed.add_field(name="Uptime", value=text)
embed.set_footer(text="Daxbot.com")
try:
await ctx.send(embed=embed)
except discord.HTTPException:
await ctx.send("Current uptime: " + text)
def setup(client):
client.add_cog(Uptime(client))
``` My uptime command does not update
anyone mind taking a look, no need to comment on my use of start instead of run as I can't change it atm as there's a current loop that I don't seem to be able to close
#bot-commands
i can never find the channel so i tagged it for myself
Okay so I'm using dpy 2.0 and have this app_commands group https://paste.pythondiscord.com/uwopililig which doesn't seem to be loading (or at I don't think it's loading bc the commands not appearing).I'm loading my bot like this(yes I should use run not start) https://paste.pythondiscord.com/yixucebijo and this is my main.py file https://paste.pythondiscord.com/mozogupeva. I'm just not sure why the cog/group isn't working as I'm not getting any errors for it
import discord
from discord.ext import commands
class Mention(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.Cog.listener()
async def on_message(self, ctx, message):
if self.client.user.mentioned_in(message):
embed=discord.Embed(title="", url="https://www.linkpicture.com/q/daxbot.png", description="Hello, I am Daxbot! I am a discord bot created by ``Daxles#9999``", color=0x18c3fb), embed.set_author(name="Daxbot#0621", icon_url="https://www.linkpicture.com/q/daxbot.png")
await ctx.send(embed=embed)
def setup(bot):
bot.add_cog(Mention(bot))
``` Idea?
on_message wont receive ctx
oh
dpy only passes in a message object, but since you specified two parameters it believes the message parameter is missing
so what should I do
Remove the ctx
ya
and then the ctx here?
ctx.send is just a shortcut for writing message.channel.send
So change it to that
oui
No lmao
ctx.send is a shortcut for ctx.channel.send
obviously, but ctx is created from a message object so they essentially come from the same thing
Sure but again, it's not a shortcut
Send the code
import discord
from discord.ext import commands
class Mention(commands.Cog):
def __init__(self, client):
self.client = client
@commands.Cog.listener()
async def on_message(self, message):
if self.client.user.mentioned_in(message):
embed=discord.Embed(title="", url="https://www.linkpicture.com/q/daxbot.png", description="Hello, I am Daxbot! I am a discord bot created by ``Daxles#9999``", color=0x18c3fb), embed.set_author(name="Daxbot#0621", icon_url="https://www.linkpicture.com/q/daxbot.png")
await message.channel.send(embed=embed)
def setup(bot):
bot.add_cog(Mention(bot))
what i mean is that conceptually they are referencing the same channel, not that you could Ctrl+R replace all occurrences of ctx.send with message.channel.send
color).set_author(...)
You forgot a newline
^ you should either write embed.set_author on its own line, or chain the call by typing .set_author after the closing parenthesis: py embed = discord.Embed( title='is a good music player' ).set_author(name='foobar2000')
is there a smart person that uses hikari?
you're free to ask your question, someone will either know hikari or can read the docs and understand enough to help
ask in the hikari server if you want smart hikari users
smart advice from a smart person
is there a reason when im putting someones avatar inside an embed it is very small, about the same size when you click on their account. am i doing something wrong?
Image or thumbnail?
image
Can you attach a screenshot of the embed?
using set_image
sure
teeny tiny
i tried adding it with add_field but it would always just be a url
and now its just small
you tried pip install discord.ui yeah
show what url you are setting it to
https://cdn.discordapp.com/avatars/{user.id}/{user.avatar}
and i hope you use disnake not discord.py
me?
yes
wut
i mean code that generates the url
oh
dont tell me that was it
well yeah, anything else i use i get errors
what lib and what version of lib
discordpy
what version
God
Just use user.avatar.url
๐
?
ok bro
I don't think ur comment was needed
Dpy 2.0 user.avatar.url
dpy: user.avatar_url
Ofcourse i assume they use dpy
my bad im back
wdym of course ๐
cant, get hash errors
Its literally the main python lib of discord๐๐๐๐๐๐๐
ur funny, the lib is dead
What errors?
one sec
Literally got resumed 5 days ago๐๐๐
bro cant tell by the new slash implementation that its gonna be shit ๐
Its not dead then๐๐๐
okay I have this app_commands.Group
import discord
#from utils.helpers import _userinfo_
from typing import Union
from discord import Member, User, Interaction, Embed, app_commands
from discord.app_commands import Group, command, describe
class User(app_commands.Group):
def __init__(self, client):
self.bot = client
def _timestamps_(self, member, embed, avatar):
embed.add_field(name = "Joined Server:", value = f"<t:{int(member.joined_at.timestamp())}:R>", inline = True)
if avatar == True:
embed.add_field(name = "Avatar", value = f"[PNG]({member.avatar_url_as(static_format='png')})", inline = True)
embed.add_field(name = "Joined Discord:", value = f"<t:{int(member.created_at.timestamp())}:R>", inline = True)
async def _userinfo_(interaction, member):
member = interaction.user if member is None else member
member_status = "No status" if member.activity is None else member.activity.name
embed = Embed(title = f"{member}", description = f"Status: **{member.status}**\n*{member_status}*", colour = member.colour)
embed.set_author(name = f"{member.id}", icon_url = member.avatar.url)
embed.set_thumbnail(url = member.avatar.url)
await _timestamps_(member, embed, True)
if isinstance(member, discord.Member):
roles = [f"{role.mention}" for role in member.roles]
if len(roles) == 0: roles.append("No roles")
has_key = [perm for perm in self.bot.config.key_perms if getattr(member.guild_permissions, perm)]
if len(has_key) == 0: has_key.append('No permissions')
embed.add_field(name = f"Roles: {len(roles)}",value = f"{len(roles)} roles" if len(" ".join(roles)) > 1000 else " ".join(roles), inline = False)
embed.add_field(name =f'Key permissions', value = ", ".join(has_key).replace("_"," ").title(), inline = False)
interaction.response.send_message(embed=embed)
@app_commands.command()
@app_commands.describe(user="The discord user to get information for.")
async def info(self, interaction: Interaction, member: Union[Member, User] = None):
await _userinfo_(interaction, member)```which is throwing an error of```py
Traceback (most recent call last):
File "C:\Users\Teagan\Documents\Coding\Zupie\bot\main.py", line 4, in <module>
from cogs.user import User
File "C:\Users\Teagan\Documents\Coding\Zupie\bot\cogs\user.py", line 7, in <module>
class User(Group):
File "C:\Users\Teagan\Documents\Coding\Zupie\bot\cogs\user.py", line 36, in User
async def info(self, interaction: Interaction, member: Union[Member, User] = None):
File "C:\Users\Teagan\Documents\Coding\Zupie\env\lib\site-packages\discord\app_commands\commands.py", line 941, in decorator
return Command(
File "C:\Users\Teagan\Documents\Coding\Zupie\env\lib\site-packages\discord\app_commands\commands.py", line 376, in __init__
self._params: Dict[str, CommandParameter] = _extract_parameters_from_callback(callback, callback.__globals__)
File "C:\Users\Teagan\Documents\Coding\Zupie\env\lib\site-packages\discord\app_commands\commands.py", line 285, in _extract_parameters_from_callback
_populate_descriptions(result, descriptions)
File "C:\Users\Teagan\Documents\Coding\Zupie\env\lib\site-packages\discord\app_commands\commands.py", line 208, in _populate_descriptions
raise TypeError(f'unknown parameter given: {first}')
arameters_from_callback
_populate_descriptions(result, descriptions)
File "C:\Users\Teagan\Documents\Coding\Zupie\env\lib\site-packages\discord\app_commands\commands.py", line 208, in _populate_descriptions
raise TypeError(f'unknown parameter given: {first}')
TypeError: unknown parameter given: user```
bro he can use whatever he wants
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In embed.image.url: Scheme "6c9ff0d904002e1728a218e44247ea0b" is not supported. Scheme must be one of ('http', 'https').```
i never said u cant
its just stupid
but whatever
@compact crow what version of the library
this is why i have to use what i am, otherwise i get this
dpy 2,0 master uses api v10
1.7.3 uses v7 i think
thats what we have been trying to tell u
then its not going to work
ye 1.x is dead in april
@compact crowhttps://discordpy.readthedocs.io/en/stable/api.html#discord.User.avatar_url
one of my bots is running 1.7.3 but the one of working on now uses 2.0
2.0 isnt stable but yall love dpy so keep using it ๐
dont even think about better forks
what fork would you recommend other than dpy if i were to change
prob disnake
also ty
who wouldnt like dpy?
dpy has special place in our hearts
@compact crow 3 possible reasons the image is small to you:
- avatar is small
- try pass image size to the url
- embed's max image size somehow doesnt satisfy you
none of the forks seem particularly good to me, i considered using hikari but that was such a drastic change and bc that's still in dev land those no decent into guides or tutorials
got it sorted now thanks ๐
disnake is made by the creator of dislash, their 2.0 is stable for a very long time
it was just me being a complete tool in the end
hinari's docs seemed all over the place to me
try pincer
The package is currently within the Alpha phase
that's the issue with most of them, they are all in dev land (not saying that's generally bad) and discord is just steamrolling ahead with new features faster than the libs can be updated or if they can catch up they seem rather tacked on (pycord)
All libs are being developed on
who cares if itโs in Alpha?
i don't massively, apart from if breaking changes get added
anyway back to what brought me here, does someone mind taking a look at this
what did i do wrong
you donโt even tell us the error lmao
there is no error it just doesnt do anything
is it a cog?
which part does nothing? Does it not send the first message or the second
ah yeah you donโt pass ctx when invoking the command
oh so just await message.edit?
what thhat mean
when doing bot.edit_guild(name=xyz, icon=icon) you need to set the icon as bytes, ive tried some stuff but that didnt work. does anyone know how to convert a png file/url into bytes used for the icon
s.kill @stray scarab
oops didnt mean to ping
Is it possible to make like a extra thread for each server my bot is on? So its like every Server has its own independent bot?
I am so lost with async and coroutine's
Why would you do that?
About what?
def check(m: discord.Message): # m = discord.Message.
return m.author.id == interaction.user.id and m.channel.id == interaction.channel.id
# checking author and channel, you could add a line to check the content.
# and m.content == "xxx"
# the check won't become True until it detects (in the example case): xxx
# but that's not what we want here.
try:
# event = on_message without on_
msg = await self.bot.wait_for(event='message', check=check, timeout=60.0)
# msg = discord.Message
except asyncio.TimeoutError:
# at this point, the check didn't become True, let's handle it.
await interaction.edit_original_message(content=
f"**{interaction.user}**, you didn't send any message that meets the check in this channel for 60 seconds..")
return
else:
# at this point, the check has become True and the wait_for has done its work, now we can do ours.
# we could also do things based on the message content here, like so
# if msg.content == "this is cool":
# return await ctx.send("wait_for is indeed a cool method")
await interaction.edit_original_message(
content=f"**{interaction.user}**, you responded with {msg.content}")```
https://cdn.discordapp.com/attachments/381965515721146390/951988168406761513/unknown.png why is str.content none?
Because the Bot has to work like this to function correctly. And I asked questions before, I tried to understand async functions etc but I just dont get it. And if this is possible, this would be a very good way to achive my goals
About running multiple functions at the same time.
What do you mean โjust donโt get itโ?
It will literally do nothing to have a bot on a separate thread
The bot runs once. That means you would have tons of bots running
Your best option is to try harder to understand, because what youโre trying to do is much more difficult than using the library as itโs meant
^
I get this whenever on website when i run my bot
No WebSocket UPGRADE hdr: None
Can "Upgrade" only to "WebSocket". using discord.ext.ipc can someone help plz
I read the documentation (not completely) and some other websites, but still dont know what they tried to tell me.
I found a reddit post about like exactly my problem, but it seems, there is no way ๐
It isnโt a "problem".
plain and simple that you shouldnโt run the same bot instance on multiple threads
That is extra complication that wonโt do anything
Okay so maybe I dont mean Threads, then I am sorry.
I just want, that variables cant be changed across servers.
For example if I define a variable
Server1
num = 5
and on another Server
Server2
num = 10
Then both values should be saved, but I want to work with num = 5 on Server1 and with num = 10 on Server2. Like independent.
does that makes sense?
yeah thatโs a simple database
Is there a database based on python? I tried sql and sqlalchemy, but I really dont like it.
currently I am saving everything in simple files
With a record for each specific guild, with specific config
you need to use sqlโฆ (unless you use a NoSQL db)
You can use ORMs along with dbs to not have to write raw SQL
Like
Server1
num = [Server1, 5]
Server2
num =[Server2, 10] ?
thatโs not how a relational database works
That's not a database?
yeah I tried Sqlalchemy, its a ORM right?
guys, opinion on having an arg in the event decorator which is raw and it means you get passed raw event data instead of whatever class
yeah but Prisma Client for Python is better
What API?
yes... How would it look like with a database? Sorry guys ๐ ๐ฌ
itโs a table
?
Are you making an API wrapper?
yes
๐ฟ
Yea so, what API?
discord api? tf
Could be useful I guess
Yeah okay, but still more or less the same.
Okay lets say I learn it. What do I have to change in my code? Every variable? ๐ค
Minecraft api
It is not the same
all you have to do is make a schema for your db, connect to your db, sync your db with the schema and use the prisma functions
Docs will tell you how to do it
Okay I think thats my main problem, I dont understand the difference or what I have to do in general. I have a wrong unterstanding
Thats not the problem, but I cant imagine that this would work. I just dont understand how
Okay can I give you an example?
and uniqueness
I have a game and it should be only possible to play one at a time.
So I have a boolean called "running". If True, you cant start a new game.
And I have a lot of data which I store in lists.
I understand that a database would be great for my lists. That I should safe everything in a real database. But I still have (for example) this single var. which should be independently on each Server. (Because if Server A plays a game, Server B dan still start one).
So do I give "running" an entry in one of my tables in dependency of the Server ID? And do this basiclly with every var. I use during a game...
So I dont use any python variables and only Database entry's?
you can use the var to make a query
Sorry I dont understand what you mean.
Do you understand basic sql?
I think so, yes.
learn basic sql before doing database
You talking to me?
use database-xy;
Select * from mytable where...;
donโt think the useis needed if a database connection is established already
# Pretend the connection has already been established
my_var = connection.cursor().execute("SELECT is_running FROM your_table_name;")
I think this is right anyway
snake_case?
okay
If you had a column called is_running which stored whether the user can start a new game, then my_var would be your bool (True/False) (It would be returned in a tuple but you get the point)
๐ฅณ
That would be more for the scope of #python-discussion or #โ๏ฝhow-to-get-help
!pypi ConfigParser
Where is the trash can smh
@uncut zephyr This is directed at you btw
Yes, thats what I meant. So I have to save everything in my database.
But it should be like this
# Pretend the connection has already been established
my_var = connection.cursor().execute("SELECT is_running FROM your_table_name WHERE server = message.guild.id;")
right?
Haha yeah I was not sure at first, but then I had to think about it
You get the idea but something is wrong
You're just doing message.guild.id
You should be using placeholders
Yeah and I dont get whats wrong. I think if I knew whats wrong everything will make sense. Looking forward to this moment tbh
You would do
# Pretend the connection has already been established
my_var = connection.cursor().execute("SELECT is_running FROM your_table_name WHERE server = ?;", (message.guild.id, ))
Not 100% sure though
I've actually never used placeholders
I only learnt about sql injection after I quit making my discord bot
ahh yes, i tried it with
my_var = connection.cursor().execute("SELECT is_running FROM your_table_name WHERE server = " + str(message.guild.id)) //WRONG
and it worked
thats not sanitisation
it would be , (message.guild.id, )
and you dont need the () around the ?
Ahh okay thank you. But except this, it would be correct?
Changed it
you also dont need the ; lol
It's better practice
n
Technically no but I would like to make it a habit
Always employ good practice, even if you don't need to
looks bad but you do you
Doesn't matter to me ๐คทโโ๏ธ
you cant just pull 'good practice' out of your ass
I can
Guys what is the user mention argument in discord.py
that escalated quickly lol
Theres a difference between doing it in python and SQL
like this?
.send("{}".format(message.author.mention))
Argument
In python it's unpythonic, in sql, it's good practice
Just don't write sql ๐คฆ
there is no difference
discord.Member works
ok thx
It's is good practice to put a ; at the end of your statement in SQL queries. If you disagree, ask in #databases
To come back to the question, so I have to save my "running" var in my database, connected with a server_id.
And I have to do this with every variable that I am currently using right?
i dont particularly care
Why are you so aggressive
im not
You are
Guys tone it down a notch
What did I do lmao
You're gonna scare people off from asking for help
apologies
great let's move on then
You mean is_running?
ah yeah right, it's called "is_running"
Yeah, you would
So its basically the same as this, just with a nice database
Yeah, you would do num = fetching from database etc.
I have a lot of variables which I only have to use for a very short amount of time, I have to do a database entry for everything right?
No I dont. And also the "is_running" is reset to False after every restart. So does it mean I dont have to safe it in a db?
I thought I understand everything haha
When your bot restarts the database will not be affected unless you do it yourself
yes I know. And thats all good. But I want to know, what I have to do with my variables which are just there to do "short tasks"
If you want to have only 1 game per server, yes you would pair it with a server id. If you wanted to do it for a per user basis you would just pair it with a user id
If you don't want the data to save after the bot restarts then you just keep them as normal variables
Yeah I got this. But also in a DB then?
I try to by clear, lets say I have this
num = 0
for i in range(20+len(username)) #I know len(username) does not exists, but say it does for a moment
num = num + 5
print(num)
And this gets called once in a while. So num does not need to be saved, but if someone else on another server starts a game, this "num" will be overwritten by him. So what to do?
def check(m: discord.Message): # m = discord.Message.
return m.author.id == interaction.user.id and m.channel.id == interaction.channel.id
# checking author and channel, you could add a line to check the content.
# and m.content == "xxx"
# the check won't become True until it detects (in the example case): xxx
# but that's not what we want here.
try:
# event = on_message without on_
msg = await self.bot.wait_for(event='message', check=check, timeout=60.0)
# msg = discord.Message
except asyncio.TimeoutError:
# at this point, the check didn't become True, let's handle it.
await interaction.edit_original_message(content=
f"**{interaction.user}**, you didn't send any message that meets the check in this channel for 60 seconds..")
return
else:
# at this point, the check has become True and the wait_for has done its work, now we can do ours.
# we could also do things based on the message content here, like so
# if msg.content == "this is cool":
# return await ctx.send("wait_for is indeed a cool method")
await interaction.edit_original_message(
content=f"**{interaction.user}**, you responded with {msg.content}")``` https://cdn.discordapp.com/attachments/381965515721146390/951988168406761513/unknown.png why is welcomeMessage.content none?
Does that makes sense?
I would personally use a database
is your code indented inside the check?
so a database after all for everything even if it does not have to be saved permanently?
Because this would not work if a game on another Server can change the variables on your server
if num is located inside a command function, that shouldn't be a concern due to how async works
If you're not using num outside of the function then you don't need a database
It wont be overwritten
okay that makes sense. Let me clarify, a function is
def whatever():
print("yeah")
#and also something like
async def whatever2():
print("yeah")
#but on_message is of not a function?
but on_message should be a function too. So everything in my code is in a function. I am confused, give me a moment xD
nope
I feel kinda stupid right now. But I dont have code outside a function lol
Then you'll have no issues with variables being overwritten
That's how async programming works
so in both my examples I wouldn't had any problems?
Thats weird because I have problems ๐
I will try something
If you don't need persistence it would be ideal to make a dict here, key would be the author's ID, then the value would be num
Then when running the code you increment dict[id] by 5
Instead of doing num = num + 5 you can also just do num += 5
You mean like this? #discord-bots message
yeah true
hey andy
If you want num to be incremented by anyone in the server, yea you'd do that
Otherwise set the key as the author's ID to have user specific nums
yes but just on THIS server. But If someone does the same on another Server it shouldnt increment
Yea, you'd be accessing the dict through the guild's ID preferably, so you won't be editing other guild's num
okay like num = [server_id, 5]
!e ```py
mapping = {1: 0, 2: 0}
mapping[1] += 5
print(mapping[1], mapping[2])
@pliant gulch :white_check_mark: Your eval job has completed with return code 0.
5 0
Now I am again lost, pep8 just said, I dont have to care about it inside a function
See here, the first guild, example here
It's under 1, and it has it's own num value
ahh yeah
You access the value, increment
Since it's key-value specific you won't be incrementing other guilds
makes sense. thanks.
๐
I guess its not working for me because I use to much global variables... I guess my own fault
Btw @final iron Thank you very much for your time, I really appreciate it!
sorry for the ping lol

How would I store user input for later use in discord.py
Traceback (most recent call last):
File "C:\Users\Teagan\Documents\Coding\Zupie\env\lib\site-packages\discord\client.py", line 384, in _run_event
await coro(*args, **kwargs)
File "C:\Users\Teagan\Documents\Coding\Zupie\bot\main.py", line 50, in on_ready
await bot.tree.sync(guild=discord.Object(id=default_guild))
File "C:\Users\Teagan\Documents\Coding\Zupie\env\lib\site-packages\discord\app_commands\tree.py", line 659, in sync
data = await self._http.bulk_upsert_guild_commands(self.client.application_id, guild.id, payload=payload)
File "C:\Users\Teagan\Documents\Coding\Zupie\env\lib\site-packages\discord\http.py", line 501, in request
raise Forbidden(response, data)
discord.errors.Forbidden: 403 Forbidden (error code: 50001): Missing Access```is this saying it can't make application commands? bc I have given the bot that scope
you can save it in a file if you want
Ok thx
or what do you mean?
What do you mean
Like ask for user input on something then store that into a dictionary value
In discord.py
for a long time?
Yes
You could use a database
like even if you kill your bot and restart it?
Everyone is so obsessed with databases haha
They do?
oh how dare you, recommending a global var. haha
Replit doesnโt save things after the program stops running
then dont use replit...
I code on mobile
oh
Because that's supposed to happen?
It sounds like you want something 24/7
Btw can u give me a example of how I would do this? Would I have to dynamically create a var?
It doesnโt even save database stuff
im not saying you should but you could do global var var = user_input
I could also do globals() prob, but it never worked for me
anyone knows of any fun facts api
use
client.var
(or bot.var)
you could use reddit
Ok thx ima search that up
never worked with reddit before
with requests
if you use
client = commands.Bot(command_prefix="&", help_command=None)
"client" in this case, you just have to write
client.var = blabla
every time and its like a global var.
isnt requests blocking lol
idk lol
It is indeed blocking
!botvar
Python allows you to set custom attributes to most objects, like your bot! By storing things as attributes of the bot object, you can access them anywhere you access your bot. In the discord.py library, these custom attributes are commonly known as "bot variables" and can be a lifesaver if your bot is divided into many different files. An example on how to use custom attributes on your bot is shown below:
bot = commands.Bot(command_prefix="!")
# Set an attribute on our bot
bot.test = "I am accessible everywhere!"
@bot.command()
async def get(ctx: commands.Context):
"""A command to get the current value of `test`."""
# Send what the test attribute is currently set to
await ctx.send(ctx.bot.test)
@bot.command()
async def setval(ctx: commands.Context, *, new_text: str):
"""A command to set a new value of `test`."""
# Here we change the attribute to what was specified in new_text
bot.test = new_text
This all applies to cogs as well! You can set attributes to self as you wish.
Be sure not to overwrite attributes discord.py uses, like cogs or users. Name your attributes carefully!
yeah exactly and the same with "client."
Yes
Wait so like can I do
@bot.command() async def g(ctx): await ctx.send(โWhatโ) def check(msg): return msg.author == ctx.author and msg.channel == ctx.channel bot.var = msg
?
yeah I think so. Now you can use "bot.var" everywhere in your code. And it just gets deleted if you restart the bot or do something like "bot.var =0"
yes
g = 0 @bot.command() async def g(ctx): global g await ctx.send(โWhatโ) def check(msg): return msg.author == ctx.author and msg.channel == ctx.channel g += 1 globals()[fโbot.var{g}โ] = [msg]
#would this make it different for every user?
I hope these attributes are immutable, or else thatโd be cringe
@uncut zephyr
Mutable
I dont think "global g" will work.
And you are using g also before telling its global
Is there a way to make it different for every person?
Make your g a dict, then use key-value of user-id to values
# main.py
from cogs.users import user
async def add_commands():
bot.tree.add_command(user(bot))
@bot.event
async def on_ready():
print('------')
print(
f'Logged in as {bot.user} (ID: {bot.user.id})',
f'Connected to {len(bot.guilds)} guilds',
f'Running version {version}',
f'Running {len(bot.shards)} shards',
sep='\n'
)
await add_commands()
await bot.tree.sync(guild=discord.Object(id=default_guild))
print('Sucessfully synced applications commands')
print('------')
# cogs.users.py
import discord
#from utils.helpers import _userinfo_
from typing import Union
from discord import Member, User, Interaction, Embed, app_commands
class user(app_commands.Group):
def __init__(self, bot):
super().__init__()
self.bot = bot
def _timestamps_(self, member, embed, avatar):
if not isinstance(member, discord.Member):
embed.add_field(name = "Joined Server:", value = f"<t:{int(member.joined_at.timestamp())}:R>", inline = True)
if avatar == True:
embed.add_field(name = "Avatar", value = f"[PNG]({member.avatar_url_as(static_format='png')})", inline = True)
embed.add_field(name = "Joined Discord:", value = f"<t:{int(member.created_at.timestamp())}:R>", inline = True)
async def _userinfo_(interaction, member):
member = interaction.user if member is None else member
member_status = "No status" if member.activity is None else member.activity.name
embed = Embed(title = f"{member}", description = f"Status: **{member.status}**\n*{member_status}*", colour = member.colour)
embed.set_author(name = f"{member.id}", icon_url = member.avatar.url)
embed.set_thumbnail(url = member.avatar.url)
await _timestamps_(member, embed, True)
if isinstance(member, discord.Member):
roles = [f"{role.mention}" for role in member.roles]
if len(roles) == 0: roles.append("No roles")
has_key = [perm for perm in self.bot.config.key_perms if getattr(member.guild_permissions, perm)]
if len(has_key) == 0: has_key.append('No permissions')
embed.add_field(name = f"Roles: {len(roles)}",value = f"{len(roles)} roles" if len(" ".join(roles)) > 1000 else " ".join(roles), inline = False)
embed.add_field(name =f'Key permissions', value = ", ".join(has_key).replace("_"," ").title(), inline = False)
interaction.response.send_message(embed=embed)
@app_commands.command()
@app_commands.describe(user="The discord user to get information for.")
async def info(self, interaction: Interaction, user: Union[Member, User] = None):
await _userinfo_(interaction, user)
```this users command (my only command so far) doesn't seem to be registering on the guild (and i have re-invited the bot twice to make sure it has the correct scopes)
Aren't string immutable, unless that isn't what you are talking about
Could just use a module level variable at that point
Not at that point I mean, but instead of custom attributes
Yes I think you've got the Idea.
like
bot.var = {"user": "your stuff"}
But tbh I have kind of the same problem with my code, so I am not sure haha
Thx I will try it
Why would you use globals over object attributes?
Just seems like bad practice to use global here
At least, I am assuming you mean global, as you'd use it for module level attributes
Wait to access the items in bot.var do I just do
{bot.var[ctx.author.id]}
Or is that not how bot variables work
It should be { instead of [
bot.var works like a normal var
That code would give an syntax error
oh sorry, I'll change it
Better to subclass Bot
He means the variable
Yeah
What
The variable. He wanted to know if it was settable only once or...
Ah
Well, you can pretty much override anything N times in python, unless it is a reserved keyword
Unless otherwise, if your object implements a property with no setter
This code write only 1 member, why?
Your bot should have member intents, otherwise you won't be able to see any members, other than your bot
and i how to add intents?
!intents
Using intents in discord.py
Intents are a feature of Discord that tells the gateway exactly which events to send your bot. By default, discord.py has all intents enabled, except for the Members and Presences intents, which are needed for events such as on_member and to get members' statuses.
To enable one of these intents, you need to first go to the Discord developer portal, then to the bot page of your bot's application. Scroll down to the Privileged Gateway Intents section, then enable the intents that you need.
Next, in your bot you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:
from discord import Intents
from discord.ext import commands
intents = Intents.default()
intents.members = True
bot = commands.Bot(command_prefix="!", intents=intents)
For more info about using intents, see the discord.py docs on intents, and for general information about them, see the Discord developer documentation on intents.
Ok I tested it and it gives me some kinda text idk how to explain
RuntimeError: Event loop is closed```
Send the full traceback
Exception ignored in: <function _ProactorBasePipeTransport.__del__ at 0x0000028A5CCCFE20>
Traceback (most recent call last):
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.752.0_x64__qbz5n2kfra8p0\lib\asyncio\proactor_events.py", line 116, in __del__
self.close()
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.752.0_x64__qbz5n2kfra8p0\lib\asyncio\proactor_events.py", line 108, in close
self._loop.call_soon(self._call_connection_lost, None)
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.752.0_x64__qbz5n2kfra8p0\lib\asyncio\base_events.py", line 745, in call_soon
self._check_closed()
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.752.0_x64__qbz5n2kfra8p0\lib\asyncio\base_events.py", line 510, in _check_closed
raise RuntimeError('Event loop is closed')
RuntimeError: Event loop is closed
Try reading the error
You got to go onto the developer dashboard as this guide tells you to do
thanks
How do you change message id to the message
wdym
I donโt know if thereโs a way, but something like this
letโs say that the message id of Joe is 1
how would I convert 1 to Joe
you mean to his name?
he wants to get the message content by using the id
Ye
But what content? You can use message.content
๐ฎ
xD
Wait lemme try that
i thought u knew that lmao
Yo thx I can store user input now
If statements
you can google this one very easy. https://stackoverflow.com/questions/59340143/how-to-change-nickname-discord-py check this out
!d discord.Member.edit
await edit(*, nick=..., mute=..., deafen=..., suppress=..., roles=..., voice_channel=..., timed_out_until=..., reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Edits the memberโs data.
Depending on the parameter passed, this requires different permissions listed below...
Union[Member, ClientUser]: Similar to Guild.me except it may return the ClientUser in private message contexts.
yes ty
never knew .me ever existed
!d await ctx.me.edit()
6.4. Await expression
Suspend the execution of coroutine on an awaitable object. Can only be used inside a coroutine function.
await_expr ::= "await" primary
``` New in version 3.5.
Union[Member, ClientUser]: Similar to Guild.me except it may return the ClientUser in private message contexts.
why
bcuz The remote computer refused the network connection
why it refuse
๐ฅฒ
bcuz it refused to connect
:V
what error so it refuse
can i send codes??
bot.db = await asyncpg.create_pool(database="Prefix",user = "postgres", password = "mypass")
print("Db added successfully")
bot.loop.create_task(create_db_pool())```
||@sick birch @slate swan ||
๐
Does anybody know any way of getting the About Me of a certain user? The official Discord.py doesn't support it yet. So, is there some kind of third-party library that may help?
pro ppls
What
ConnectionRefusedError: [WinError 1225] The remote computer refused the network connection
That's a Windows issue
someone need help :V
what is message
@bot.command()
async def activity(ctx, message):
await ctx.send("Activity Check\n @everyone")
await message.delete()
await ctx.message.add_reaction(Check)```
message missing arg
wym
how would i make an eval command?
bruh what this message do after ctx
DM me
...
This is my main.py file https://paste.pythondiscord.com/exigeyerol
This is my cogs.users.py file https://paste.pythondiscord.com/oqunuxobul
This is my utils.services.py file https://paste.pythondiscord.com/ofuyehohul
I've gone over this code several times and as far as I can see it should work, it just isn't and it's not giving me any errors
im trying to make it where when i say s.activity it deletes my message and sends the await ctx.send("Activity Check\n @everyone") and reacts to his own message with โ
i got it but it doesnt delete nor does it react
it just sends
ok u got it
async def activity(ctx):
msg = await ctx.send("Activity Check\n @everyone")
await ctx.message.delete()
await msg.add_reaction(':white_check_mark:')```
๐
try
except Exception as e:
await ctx.send(f'{e}')
Bot broken
so it send error
ys ig
Can anyone explain the meaning of ctx in discord?
I read the docs but still a bit confusedโฆ
hmm
context
Can you specify further @slate swan
what thing need to specify
anyone mind taking a look at this?
async def on_command_error(ctx, error):
if isinstance(error, commands.CommandNotFound):
await ctx.send("**Invalid command. Try using** `help` **to figure out commands!**")
if isinstance(error, commands.MissingRequiredArgument):
await ctx.send('**Please pass in all requirements.**')
if isinstance(error, commands.MissingPermissions):
await ctx.send("**You dont have all the requirements or permissions for using this command :angry:**")```
but this not show what exact error in terminal
lmao i don't get it
ok bro
well i am noob lmao
๐
Wait are you trying to get logs of every command ran (successful and unsuccessful)? Or just the unsuccessful ones
@bot.command()
async def Ping(ctx):
bans = await ctx.guild.bans()
#print(bans)
for i in ban:
#print(i)
print(i["User id"])
y this not wronking?
So i am trying to see if someone pings more than 5 times and this error pops up
i know that it needs to be the same datetimes but hwo do I know which datetimes to use?py TypeError: can't subtract offset-naive and offset-aware datetimes
Code:
@bot.event
async def on_message(message):
def _check(m):
return (m.author == message.author
and len(m.mentions)
and (datetime.utcnow()-m.created_at).seconds < 60)
if not message.author.bot:
if len(list(filter(lambda m: _check(m), bot.cached_messages))) >=3:
await message.channel.send("Don't spam mention!!!")```
@bot.command()
async def Ping(ctx):
ban = await ctx.guild.bans()
#print(bans)
for i in ban:
#print(i)
print(i["User id"])
y this not working? i get this error:
ret = await coro(*args, **kwargs)
File "main.py", line 28, in Ping
print(i["User id"])
TypeError: tuple indices must be integers or slices, not str
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/runner/WealthyFrequentOrigin/venv/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "/home/runner/WealthyFrequentOrigin/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "/home/runner/WealthyFrequentOrigin/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: tuple indices must be integers or slices, not str
why not just print i?
i wanna pring the user id of the loop ban
Well you could make a on message event and check if the msg starts with a command (message.startswith(bot.command_prefix + command) or you could make a JSON file and I'm each command just write data to the JSON saying which command was used and when (which is contained in ctx)
just do
for i in ban:
print(i)
!eval
ban = ['a', 'b']
for i in ban:
print(i)
BanEntry(reason=None, user=<User id=217353461933670403 name='! EssaPrime' discriminator='0001' bot=False>)
BanEntry(reason=None, user=<User id=311909271904190466 name='Shut yo bubble gum dum dum' discriminator='6912' bot=False>)
BanEntry(reason=None, user=<User id=373518542122909706 name='Kuri' discriminator='1686' bot=False>)
BanEntry(reason=None, user=<User id=376652583202324481 name='TheTrain' discriminator='4373' bot=False>)
BanEntry(reason=None, user=<User id=451138906612564008 name='OfCommunity' discriminator='1502' bot=False>)
BanEntry(reason=None, user=<User id=591939896319672341 name='vmp' discriminator='8218' bot=False>)
BanEntry(reason=None, user=<User id=694595888420749442 name='Ex' discriminator='0512' bot=False>)
BanEntry(reason=None, user=<User id=714881781408727189 name='SUMER' discriminator='1188' bot=False>)
BanEntry(reason=None, user=<User id=714889517433356389 name='yoru' discriminator='7154' bot=False>)
BanEntry(reason=None, user=<User id=741544459103109170 name='valueof' discriminator='4777' bot=False>)
BanEntry(reason=None, user=<User id=747960344298651718 name='yldJoM6yOpMs0CWS2UyO' discriminator='8447' bot=False>)
BanEntry(reason=None, user=<User id=761325978831290419 name='Kiitty' discriminator='1544' bot=False>)
what do you want form it?
the user name?
i just want to print out the user id's of the banned users
try print(i[0])
tell me what the response is
can someone just real quick help me ty
it prints "None"
hm try print(i[2])
Well it's 4am for me so I'll probs bot be quick at responding.
Also if you go down the route of the second suggestion I gave you then consider writing a separate function for working with the JSON file, then execute the function within each command and pass in relevant params
errors
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/runner/WealthyFrequentOrigin/venv/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "/home/runner/WealthyFrequentOrigin/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "/home/runner/WealthyFrequentOrigin/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: IndexError: tuple index out of range
Pretty clear error
!e
my_tup = (1, 2, 3)
print(my_tup[3])
@final iron :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 2, in <module>
003 | IndexError: tuple index out of range
Why index the BanEntry
It's a namedtuple, a lot easier to use dotnotation to access the user
!d discord.BanEntry.user
So i am trying to see if someone pings more than 5 times and this error pops up
i know that it needs to be the same datetimes but hwo do I know which datetimes to use?py TypeError: can't subtract offset-naive and offset-aware datetimes
Code:
@bot.event
async def on_message(message):
def _check(m):
return (m.author == message.author
and len(m.mentions)
and (datetime.utcnow()-m.created_at).seconds < 60)
if not message.author.bot:
if len(list(filter(lambda m: _check(m), bot.cached_messages))) >=3:
await message.channel.send("Don't spam mention!!!")```
the loop is closed
try indenting
so open then close after the check
ask_prefix() ?
U forgot to call the function?
Why not use a Command?
Well, seems like an on_message
why not use get_prefix?
!d discord.ext.commands.Bot.get_prefix
await get_prefix(message)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Retrieves the prefix the bot is listening to with the message as a context.
bot.db = await asyncpg.create_pool(database="test",user = "postgres", password = "pass")
print("Db added successfully")
bot.loop.create_task(create_db_pool())```
@client.listen()
async def on_message(message):
if message.author != client.user:
await message.channel.send(f"{message.content} sent by {message.author}")
the first message from the bot was running this code on repl.it
the second message from the bot was running this code on my laptop in VSC
Why?
why it say ConnectionRefusedError: [WinError 1225] The remote computer refused the network connection
Perhaps you're missing message_content intents on your laptop
and how do i get those?
!intents
Using intents in discord.py
Intents are a feature of Discord that tells the gateway exactly which events to send your bot. By default, discord.py has all intents enabled, except for the Members and Presences intents, which are needed for events such as on_member and to get members' statuses.
To enable one of these intents, you need to first go to the Discord developer portal, then to the bot page of your bot's application. Scroll down to the Privileged Gateway Intents section, then enable the intents that you need.
Next, in your bot you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:
from discord import Intents
from discord.ext import commands
intents = Intents.default()
intents.members = True
bot = commands.Bot(command_prefix="!", intents=intents)
For more info about using intents, see the discord.py docs on intents, and for general information about them, see the Discord developer documentation on intents.
you need
intents.message_content = True
and make sure it's turned on in the discord developer portal as well
Without those the content of a message is not made available to you
ok so whats weird is both my repl and my local VSC instance are running identical code
my thoughts exactly
like i literally copy pasted the code from VSC into repl before this test and it worked in the repl and not in vsc
Unless discord is treating your replit's gateway connection differently for some reason
Can you post the full code in a pastebin if it's too long?
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Alrighty let me take a look
Also looks like part of your token might be leaked, might want to consider changing it just to be safe
Hmm yeah quite odd
Can you try to run like the most basic bot with just an on message on both replit and vsc?
ye sure
import discord
from discord.ext import commands
client = commands.Bot(...)
@client.listen()
async def on_message(message):
if message.author != client.user:
await message.channel.send(f"{message.content} sent by {message.author}")
client.run(token)
just that
Same thing it seems?
yeah
but its weird cause it is receiving the event, and receiving the author, and the channel
but not the content?
I mean only thing I can think of is replit gets the message_content intent but vsc doesn't
But I don't know why the gateway would treat it differently
are they possibly sent over different ports?
No both are websocket connections
Do you have the bot running in both the replit and vsc simultaneously?
no i specifically stop one instance before running the other
actully lemme try that rq
bruh moment
and its aways the repl replying forst
https://github.com/Rapptz/discord.py/issues/6820
this has a identical issue but is for self bots exclusively it seem?
Curious indeed
Bots hosted on replit usually have 40ms ping
@glacial echo and you're 100% sure you have your message_content intents set up properly?
Can you show your code?
if i didnt, both should be getting empty message.content
I suppose, but it's worth giving it a shot
It doesn't take ()
Just
@client.event
...
Also make sure to process_commands()
What was the error before
Alright
And also you're aware on_message only provides you with message?
well what do you expect client.command to be
That's a decorator, so not sure why you're trying to add it to a string
Are you just trying to print something when someone runs a command?
does this look right? or is this the wrong section
discord.py already does that for you
Wrong section
How is the exe file going to send commands to the bot?
@glacial echo
I see
There's a better way to do this, let me check the docs since I don't remember
and it's enabled in the code?
still no message.content
How does it look like in the code?
from discord import Intents
import discord
from discord.ext import commands
token = "token"
client = commands.Bot(command_prefix="b|", case_insensitive = True)
intents = Intents.default()
intents.members = True
@client.listen()
async def on_message(message):
if message.author != client.user:
await message.channel.send(f"{message.content} sent by {message.author}")
client.run(token)
Some like this
bot = commands.Bot(...)
@bot.before_invoke
async def before_invoke(ctx: commands.Context):
...
make sure you have intents.message_content = True
ah
That's exactly what you want. It runs a function before a command is called
of course, call a print inside the before invoke hook
Understood
yeah that works
Just do a print inside of it, nothing special
That coro will get called before any function runs
follow naming conventions 
Yes, if it gets called then it's a valid command
why
ctx.command
keep in mind it's a discord.ext.commands.Command object not a regular string
Well, if we're to take it literally, before_invoke means before your function is called.
So, this is a function that is called before your command's method is called.
Y'know, just to explain a bit more precisely what's going on.
Yes, I'd like to include there's also a @bot.after_invoke if that helps you understand it more
awesome
still nadda
this is so weird
In that case, looks like you found a bug. Consider filing a bug report under discord.py
Congrats, you've utterly stumped me ๐
Does discord.py function anymore?
yes
Why wouldn't it?
man finding bugs in discord.py is not how i wanted this school project to go
yes, it is, and its back into development assuring updates
So should I be starting with discord.py or use smth lik pycord or hikari?
I can't tell if it's a discord.py bug or a discord gateway bug. Let's hope that it's a discord.py bug rather than with the gateway
No reason to unless you don't trust discord.py to stay unarchived for long
use disco instead
pycord ๐
I'm trying to get my first boy built so which one would be recommended?
b-boy....?
Bot*
a wife
lmao
Lol
xD
and what would a gateway bug entail?
Uh fantastic question
@glacial echo did set up message intents, maybe not included in that link but we turned it on and had it in the code
At least I hope
yes i put intents in my code and triple checked i enabled them in my developer portal
Should've mentioned that in the issue so it didn't get closed
Might want to comment on it saying you didn't include it but yes you did include the intents and it's the same behaviour
master the is dev branch
You should've included the fact that you did actually have message_content intent enabled in both your code and the dev portal
mhm didnt think about mentioning that
Yes.
Add a comment saying that you did
i did
welp guess i wont be working on refactoring and optimizing my bot
there goes possibly all potential work over the spring break on this
Everyone's bot is their owner's boy. Change my mind โ
You might have an orphan crisis on your hands then
Lmaoo

b r u h m o m e n t
if message.author == bot.user:
return
for word in bs:
if word in message.content:
await message.delete()
await message.channel.send(f'{message.author.mention} message has been deleted\n**Reason: **Discord Server Invite')```
in here i made anti-invite for discord servers, but how do i make it deactivate this thing in partner channel?
if message.channel.id != id
I don't know why I didn't think of that
๐คฆโโ๏ธ
i think message.channel.id doesnt exist
uh does it work if i do
if message.channel == channel_partner```
hi, so I was making this thing where my bot sends msg in a particular channel
but I wanna make it send the msg after like specific time....for example after each 15 mins or 1 hour
smtg like that~ is that possible?
!d discord.ext.tasks.Loop
tasks.loop
class discord.ext.tasks.Loop```
A background task helper that abstracts the loop and reconnection logic for you.
The main interface to create this is through [`loop()`](https://discordpy.readthedocs.io/en/master/ext/tasks/index.html#discord.ext.tasks.loop "discord.ext.tasks.loop").
loop
no thanks i've been here for the past 4 hours
this ones on you
Please don't leave me 
hmhm
oh uh I see
I've never used loop
so imma start with it
tysm!
too bad deal with it
!d discord.ext.tasks.loop in case u need docs
discord.ext.tasks.loop(*, seconds=..., minutes=..., hours=..., time=..., count=None, reconnect=True, loop=...)```
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/master/ext/tasks/index.html#discord.ext.tasks.Loop "discord.ext.tasks.Loop").
i'm gonna watch your performance and rate you
Starts acting as if I'm the nicest person ever
tysm! ^^
Is cool
๐คก
@command_name.error
async def command_name_error(ctx, error):
if isinstance(error, commands.CommandOnCooldown):
em = discord.Embed(title=f"Slow it down bro!",description=f"Try again in {error.retry_after:.2f}s.", color=0x00ff00)
await ctx.send(embed=em)
why does this give me this error?
Traceback (most recent call last):
File "main.py", line 65, in <module>
@command_name.error
NameError: name 'command_name' is not defined
i cant find a solution anywere
What's the command u r adding the error handler for?
๐
@maiden fable me in disnake server
@bot.command()
@commands.cooldown(1, 3, commands.BucketType.user)
async def delall(ctx):
if ctx.author.id == 474677613886177281:
Info = {"Cmd": "Delall", "User": ctx.author.id}
LogCMD("Misc/CommandLogs.json", Info)
embed=discord.Embed(title="DELETING ALL KEYS!", description="", color=0xff0000)
await ctx.send(embed=embed)
for i in db.keys():
del db[i]
print("Deleted Key: " + i + "")
this command
Do @delall.error
actually i need to be careful since that would actually ban you
Ain't I cute and innocent and the nicest? ๐ฅบ
\but i wanna add a slowmode to all my commands
Use on_command_error then
why are you making custom errors for commands?
and if their command cooldown isnt over then it sends them this
a custom command cooldown i meant
so like this?
@Use on_command_error
async def command_name_error(ctx, error):
if isinstance(error, commands.CommandOnCooldown):
em = discord.Embed(title=f"Slow it down bro!",description=f"Try again in {error.retry_after:.2f}s.", color=0x00ff00)
await ctx.send(embed=em)
@maiden fable
Ah
Then use on_command_error
Change the decorator to @bot.listen("on_command_error")
@Use on_command_error
async def command_name_error(ctx, error):
if isinstance(error, commands.CommandOnCooldown):
em = discord.Embed(title=f"Slow it down bro!",description=f"Try again in {error.retry_after:.2f}s.", color=0x00ff00)
await ctx.send(embed=em)
this get a invalid syntax error niw
Uhhhh?
^^^ @frigid pendant
@client.event
async def on_command_error(ctx, error):
if isinstance(error, commands.CommandOnCooldown):
await ctx.reply("Wait homie")```
Now if that is cogs then Idk
You wanna be very careful with that
That will consume all of your errors
Hmm?
Wait, Really!?
Yes, and you won't get any errors
Hmm
Had someone earlier today with the same problem
Robin here, I'm out. Peace โ
So that is the reason my code doesn't wrk
It could be
So can you tell me what do I do?
else:
raise error
With the errors?
Add this at the end
Oh, Right
In the top level of the function scope you can either reraise it like hunter said or print it using the traceback library
also, how do I make the bot send the msg automatically instead of using cmd?
do u know how thas possible?
import traceback
traceback.print_tb(error.__traceback__)
tasks.loop
Here we go-
ouuu i see
Too much work :D
And also increases processing resources since it's importing a lib
I suppose
@sick birch Thank you so much, Finally got the error
I mean I really just use else: raise error
Great. That makes 2 of the same problems today
Yeah
@client.command()
@commands.has_role(950040612625842186)
async def add_money(ctx, user: discord.Member, amount=None):
if amount == None:
await ctx.reply("**__INVALID AMOUNT__**, Please use `ayo add_money [user] [amount]`")
return
else:
await ctx.reply(f"Successfully added {amount} to {user.name}'s wallet")
users = await get_bank_data()
users[str(user.id)]["wallet"] += amount
with open("mainbank.json",'w') as f:
json.dump(users,f)
Error : ```ret = await coro(*args, **kwargs)
File "c:\Users\HP\OneDrive\Desktop\Discord bot\main.py", line 27, in add_money
users[str(user.id)]["wallet"] += amount
TypeError: unsupported operand type(s) for +=: 'int' and 'str'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\HP\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\client.py", line 415, in _run_event await coro(*args, **kwargs)
File "c:\Users\HP\OneDrive\Desktop\Discord bot\main.py", line 15, in on_command_error
raise error
File "C:\Users\HP\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\ext\commands\bot.py", line 1055, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\HP\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\ext\commands\core.py", line 933, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\HP\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\ext\commands\core.py", line 177, in wrapped
raise CommandInvokeError(exc) from exc
nextcord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: unsupported operand type(s) for +=: 'int' and 'str'```
@sick birch
Says it right there, can't add a number and a string
int() the string to add a number to a number
I=
Don't use JSON.
^
God damn
Someone teach me SQLite
Don't copy code from swastick.
Why not
I wrote it
It's only a matter of time before you descent into "JSON hell I call it" where it's just massive lines of int(something[str(...)])
he makes bad tutorials
why lie
most of em do
What does he do
can a bot send a msg in a channel WITHOUT anyone using the cmd?
But unfortunately people insist on following them
Yes
Of course
make tutorials
bot.get_channel, and then you can send it in that returned channel ofc
I mean, whatโs wrong with them
bad practices
For context, Iโve never watched discord bot video tutorials because those are cringe, so yeah
true
yes, but I want it to send it repeatedly after particular time...like 15 mins?
lucas kinda descent
he's great and all but his economy tutorial uses JSON instead of a proper database
lucas is even worse
bruh

but its so clear and understandable for beginners
In this video, we learn how to create several different commands for our discord bot
Let me know in the comments what videos you want to see next.
HIKARI GITHUB: https://github.com/hikari-py/hikari/
HIKARI DOCUMENTATION: https://www.hikari-py.dev/
HIKARI LIGHTBULB GITHUB: https://github.com/tandemdude/hikari-lightbulb
HIKARI LIGHTBULB DOCUMENT...
Create a coroutine that sleeps for that time, sends and loops and asyncio.create_task() it in on_ready
this is the new hikari setup
he done 14 parts playlist
before this
oh no
people copy his code without knowing what it does most of the time so 
hmmm
I could have guessed that, but do you have any examples
You think it is, but in reality you're just copying down bad code
kinda tru
for that u need to learn python first and then start with dpy
I see-
uh ok
do u have an example? Im rly confused with loops and the "sleep" part
That's what you're supposed to do, discord.py is not a beginners library
hmhm
anyway i need help
ask away