#discord-bots
1 messages · Page 910 of 1
I just tried it with test account and it let an account with no perms do it
!d discord.ext.commands.has_permissions
@discord.ext.commands.has_permissions(**perms)```
A [`check()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") that is added that checks if the member has all of the permissions necessary.
Note that this check operates on the current channel permissions, not the guild wide permissions.
The permissions passed in must be exactly like the properties shown under [`discord.Permissions`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions "discord.Permissions").
This check raises a special exception, [`MissingPermissions`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.MissingPermissions "discord.ext.commands.MissingPermissions") that is inherited from [`CheckFailure`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure").
Oh yeah sorry
Where would I add that?
below @bot.commands()
so ```py
@bot.commands()
@commands.has_permissions()
yes but we will silently judge you
because it's a bot
XD
It's a subclass of discord.Client, which means it has everything client can do and more
am I limiting myself by writing everything in client.command then?
no
he's talking about the variable name
still workeds :p
no one said it wouldn't
I mean I thought that checks permissions?
No, that's just a naming convention
your naming convention is just confusing
it does
haha no still can use commands the user has no permissions for
did you pass the required permissions?
or did you just
plop it in your code
Show code
which permissions does the command require?
you need to pass permissions inside the has_permissions decorator
yeah my bad I didnt
im guessing it's nick perms
why a duck
i am a monsterous duck
if you enlarge my avatar you can see a 7" tall man in the image
that's his size compared to mine
magic
ssl certificate verification failed
import discord
client = discord.Client()
@client.event
async def on_ready():
print(f'We have logged in as {client.user}')
@client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('$hello'):
await message.channel.send('Hello!')
client.run('mytoken')
Check the pins
what part
There is a pinned message about how to fix your issue iirc
i dont even have that folder
Are you on mac?
help?
@bot.command()
async def attach(ctx, url):
if str(ctx.channel.type) == "private":
guild = bot.get_guild(944561115302617118)
channels = await guild.fetch_channels()
channel = discord.utils.get(channels, name = "general")
em = discord.Embed()
em.set_image(url=url)
em.color = 0x2f3136
await channel.send(embed=em)
theres no error but it wont send in the channel
yea i am
You have the folder then
Do you have an error handler?
no
where do i get the folder
Are you actually running it in dms? Why don't you put some prints or use a debugger
!d discord.ChannelType
class discord.ChannelType```
Specifies the type of channel.
;-;
Don't think it supports str()
do u know where i find the folder
yes i am and alright ill try
ive been stuck on this for 2 days
@queen linden Try this
bruhhhhhhhh
oh alright thank u
🤷♂️ Believe there's about a thousand tutorials about this online, because this isn't just a problem with Discord bots
It's a problem with anything that interacts with a secured api, meaning youtube-dl or even scraping
Tried heroku again, and its giving me errors for lines that literally dont exist.
how should i fix it>
.
First part of the sentence
Hello...!
in finder/
Yes
is it possible to get a web server and host the code on replit or do you have to use github
it works gg
dont use replit pfff, and github is for websites only (static)
get a vps or get the free tier oracle vps
Traceback (most recent call last):
File "main.py", line 1, in <module>
from core.Floater import Floater
File "/workspace/core/Floater.py", line 76, in <module>
bot.loop.run_until_complete(Floater.create_db_pool())
File "/layers/paketo-buildpacks_pip-install/packages/lib/python3.8/site-packages/discord/client.py", line 111, in __getattr__
raise AttributeError(msg)
AttributeError: loop attribute cannot be accessed in non-async contexts. Consider using either an asynchronous main function and passing it to asyncio.run or using asynchronous initialisation hooks such as Client.setup_hook
sys:1: RuntimeWarning: coroutine 'Floater.create_db_pool' was never awaited
await
its written there
?
READ
@bot.event
async def on_reaction_add(reaction, user):
channel = reaction.message.channel
await channel.send(channel, '{} Answered {} to {}, format'(user.name, reaction.emoji, reaction.message.content))
@bot.event
async def on_reaction_remove(reaction, user):
channel = reaction.message.channel
await channel.send(channel, '{} removed answer {} from {}'.format(user.name, reaction.emoji, reaction.message.content ))
It says the error, right, fucking, there
Where?
No need for that, let's keep calm please
Line?
await asyncpg.create_db_pool
Please read the error really cloesly, it does tell you where to put it.
await Floater.create_db_pool or whatever it's called
!mute 894794517079793704 1d you've been warned for being rude before. if your behavior remains like this or does not drastically improve you'll be removed from the community. if in doubt read our #rules and #code-of-conduct
:incoming_envelope: :ok_hand: applied mute to @tacit storm until <t:1647577341:f> (23 hours and 59 minutes).

Nice pfp

Anyway, looks like it's on line 76
File "/workspace/core/Floater.py", line 76, in <module>
RuntimeWarning: coroutine 'Floater.create_db_pool' was never awaited
2 important bits
I just wrote the answer for them 😔
She ignored me 😂
Let's stay on topic please, that has nothing to do with the problem at hand
Someone send code for a bot cmnd
We can't spoonfeed. However, we can help you get there step by step
Sure, what've you got so far?
No Response 
I mean can I code on replit and use a vps since I'm kind of just used to coding on replit now
Like do I have to import the code to the vps or do I just code the vps into replit
vps (private server) is offered by an organization, you need to deploy your app to the vps, ps, your bot will get ratelimited sooner on replit, use a local ide for testing if you can
Yes, use something like vscode (native git integration for deploying to VPS) or pycharm
yeah, but, pycharm is a heavier IDE than VSC, since VSC is just a text editor and pycharm is a native python editor
💀
VS is an IDE.
VS or VSC?
VS
VSC
VS : IDE ( https://visualstudio.microsoft.com/)
VSC : code editor (https://code.visualstudio.com/)
My bad 
I wish VS was available for Linux too ( without wine/other external supports)
Hey guys, Im making a timer command and i wanted it to have a reaction and if a user reacts on it, and when the timer ends, it will tell the users that the timer has ended
stuck here again? 😔
it worked but now its showing that
users =await susi.reactions.users.flatten()
AttributeError: 'list' object has no attribute 'users'
well, ofc it will 
wait
!d discord.Reaction.users
async for ... in users(*, limit=None, after=None)```
Returns an [asynchronous iterator](https://docs.python.org/3/glossary.html#term-asynchronous-iterator "(in Python v3.10)") representing the users that have reacted to the message.
The `after` parameter must represent a member and meet the [`abc.Snowflake`](https://discordpy.readthedocs.io/en/master/api.html#discord.abc.Snowflake "discord.abc.Snowflake") abc.
Changed in version 2.0: `limit` and `after` parameters are now keyword-only.
Examples
Usage...
you need to iterate through the list
It's already a list
mentions = [reaction.user.mention for reaction in susi.reactions]
await ctx.send(f"{', '.join(mentions)} | The Timer has ended")
this should work ig
correct me
reaction.user.mention?
oh wait, I'm high
no?
its a list of Reaction objects
of the Message object
Nvm
so is this correct?
Wait this won't work
U gotta put in yr CC
?
Credit Card
soooo
soooo
why are you spoonfeeding code?
It's wrong anyways
We are just doing paid work for free
I don't care if it's wrong, spoonfeeding code is still bad
Indeed
yes i do agree, but at some instances we have to do what we gotta do...
sometimes i also spoonfeed
Okay then I'm just too tired to think, correct it
so what should i do?
flatten isnt a thing anymore in dpy 2
Users is a method
Oh hmm
is it possible to use a proxy in dpy? 
That explains the error
https://discordpy.readthedocs.io/en/master/migrating.html#moving-away-from-custom-asynciterator
AsyncIterators have changed in 2.0.
- If you are looking to flatten:
# before 2.0
users = await reaction.users().flatten()
# now:
users = [user async for user in reaction.users()]
Ouh
Hm
users_mention = [member.mention for reaction in reactions async for user in reaction.users() if isinstance(user, discord.Member)]
Since reactions doesn't have .users() since reactions is a list of reactions we first have to for loop that. Then re iterate for the reaction.users()
Also if the user has left the guild the reaction will return a user object so hence the check.
what would happen if I define commands.bot twice like the first one has > as its prefix but after a certain amount of time it becomes !?
soo @maiden fable will this work?
ofc that will
hmm
will that also work for owners etc?
XD
But if you are going to change a lot i do recommend making a properly structured class for it to save time.
i want to write code to welcome new members thrug my bot but cant finfd the channeel id
Code?
do you want it so that where the discord welcome message comes the bot should welcome there?
i want it like when new ppl join the bot welcome in the main chat
by main chat you mean general or the place where discord sends these messages
NameError: name 'reaction' is not defined
should i remove
users = [user async for user in reaction.users()]
No clue what you are doing
yessir
Show the whole command
yes here i want my bot to wlcome with the message i will write
How do I get my bot to identify if the user is a bot
embed = discord.Embed(title="Welcome!", description="susi bakka welcome")
welcome=member.guild.system_channel
await welcome.send(f"Hey {member.mention}",embed=embed)
customize the embed
hmm i always wanted to know that
xD
!d discord.User.bot
Specifies if the user is a bot account.
oYHHHHHHHHHHHHHHHHHHH
SIUUUUUUUUUUUUUU
XDDD
Giving up for a coder is common
yea
Real coders bite through and never give up
I even took it this far that I fixed a library myself
If message.author.bot:
stackoverflow
like me trying to find to way to make reaction ping
lol
Wdym reaction ping?
Nope, If member = bot
If member.bot does the job also
Okay.
@rocky trench this
Check for reactions. If there is a reaction on your message, add it to a list. Then you can take the member out later and send him the message
Doesnt work
Send code
!d discord.Message.reactions
Reactions to a message. Reactions can be either custom emoji or standard unicode emoji.
embed=nextcord.Embed(
title="Timer 2.0",
description=f"{numberint}",
colour=nextcord.Colour.random())
embed.set_footer(text=":good stuff smh", icon_url="https://cdn.discordapp.com/avatars/839171088079519776/12cdb639fe5c26dccf39bf2e5678b8fc.webp?size=1024")
susi = await ctx.reply(embed = embed)
await susi.add_reaction("⏰")
users_mention = [member.mention for reaction in reactions async for user in reaction.users() if isinstance(user, discord.Member)]
users.pop(users.index(bot.user))
while number != 0:
number -= 1
embed=nextcord.Embed(
title="Timer 2.0",
description=f"{number}",
colour=nextcord.Colour.random())
embed.set_footer(text=":cool stuff smh", icon_url="https://cdn.discordapp.com/avatars/839171088079519776/12cdb639fe5c26dccf39bf2e5678b8fc.webp?size=1024")
await susi.edit(embed=embed)
hmmm = users
await asyncio.sleep(1)
await susi.edit(content='Ended!')
await ctx.send(f"{ctx.author.mention}and {hmmm}! The Timer has ended!")
What line is ur error on
the longest line
oh ok where though
susi.reactions
??
embed=nextcord.Embed(
title="Timer 2.0",
description=f"{numberint}",
colour=nextcord.Colour.random())
embed.set_footer(text=":good stuff smh", icon_url="https://cdn.discordapp.com/avatars/839171088079519776/12cdb639fe5c26dccf39bf2e5678b8fc.webp?size=1024")
susi = await ctx.reply(embed = embed)
await susi.add_reaction("⏰")
users_mention = [member.mention for reaction in susi.reactions async for user in reaction.users() if isinstance(user, discord.Member)]
users.pop(users.index(bot.user))
while number != 0:
number -= 1
embed=nextcord.Embed(
title="Timer 2.0",
description=f"{number}",
colour=nextcord.Colour.random())
embed.set_footer(text=":cool stuff smh", icon_url="https://cdn.discordapp.com/avatars/839171088079519776/12cdb639fe5c26dccf39bf2e5678b8fc.webp?size=1024")
await susi.edit(embed=embed)
hmmm = users
await asyncio.sleep(1)
await susi.edit(content='Ended!')
await ctx.send(f"{ctx.author.mention}and {hmmm}! The Timer has ended!")
hmm
what's the problem here now
I'm on phone. Hard to inspect the code
He wants to make a command which sends a message with reaction on it, then send a message to everybody who reacts
NameError: name 'users' is not defined
What is reaction.users?
!d discord.Reaction.users
Susi.reactions.flatten
async for ... in users(*, limit=None, after=None)```
Returns an [asynchronous iterator](https://docs.python.org/3/glossary.html#term-asynchronous-iterator "(in Python v3.10)") representing the users that have reacted to the message.
The `after` parameter must represent a member and meet the [`abc.Snowflake`](https://discordpy.readthedocs.io/en/master/api.html#discord.abc.Snowflake "discord.abc.Snowflake") abc.
Changed in version 2.0: `limit` and `after` parameters are now keyword-only.
Examples
Usage...
ayo what
Flatten doesn't work anymore
yea
no it does
i used it for giveaway command
I'm bad at path
It works for some, but dpy 2.0 changed
XD im on nextcord
Ah
hm
What program do you use for coding
you mean IDE?
Yeah
vscode
no
hm
are you talking about the vertical lines?
it shows when a word isn't defined
xjkdjdisjsm
XD
sed
@gaunt ice
Im sure there is a way to download it as file
hm
vscode with monokai pro theme
so blue....
hmm
Purple*
@gaunt ice
Nvm blue
no it's blue
wait
what cmd is this first of all
powershell?
what command is this
not the powershell
like the name of the command
async def what
This command isn’t working
damn
Error?
No
I found the mistake nvm
No errors
It's ctx.author.name
Ok
Oh
No
Not required
Description is not compulsry mate
it is required
Nope
ok
lmfao replit user
Still not working
i told u
👋🏼
Hmm
show code
I'm sry lol gimme a min
Show full code, I think you did what I did
Did add any error thing?
line 47 ctx.author
What I said first but he only did it on the other line LOL
yeah
It works thanks
also as the command is mainly to be used to view avatar, instead of setting it as thumbnail, set it as the image of the embed
Np
no
!d discord.Embed.set_image
set_image(*, url)```
Sets the image for the embed content.
This function returns the class instance to allow for fluent-style chaining.
ok
Also, I think you have a function which consumes errors can I see the full code?
i used it without several times
Like the error thing
class discord.Embed(*, colour=None, color=None, title=None, type='rich', url=None, description=None, timestamp=None)```
Represents a Discord embed.
len(x) Returns the total size of the embed. Useful for checking if it’s within the 6000 character limit.
bool(b) Returns whether the embed has any data set.
New in version 2.0.
For ease of use, all parameters that expect a [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)") are implicitly casted to [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)") for you.
Changed in version 2.0: `Embed.Empty` has been removed in favour of `None`.
Full code?
same
7. Keep discussions relevant to the channel topic. Each channel's description tells you the topic.
are you handling errors?
No the error handling
I made the code consume all my errors, That's what is shown on YT
Gotcha
What?
oooooooo
yeah yt tutorials suck
not all of them
What?
put
if ---:
...
else:
raise error```
Use this code instead
@client.event
async def on_command_error(ctx, error):
if isinstance(error, commands.CommandOnCooldown):
await ctx.reply("Slow down")
else:
raise error```
most of them suck and the ones that dont, stay unrecognized forever
What’s wrong with my error handling?
no else condition
What your code is doing is getting all the errors and just sending a message
you get no errors except for the cooldown one
It is consuming all your errors
Ok..
@client.event
async def on_command_error(ctx, error):
if isinstance(error, commands.CommandOnCooldown):
await ctx.reply("Slow down")
else:
raise error
Yes, Indents are wrong btw
you may just add the last two lines of that code snippet to your existing code as well
mhm
Show the error
Hmm
you're missing the format method
You don't need to make a f string
I don’t?
can i edit 50 channels at once without await ?
Youtube tutorials-
No.
But what about {:.2f}
That's not related with f
I think no
Oh I didn’t know
{ctx.retry_after:.2f}
No-
His code is totally fine
I dont rly use f while making the cooldown command
Oh, Use f
@formal basin put that inside f string
Sorry---
Yeah make a f string and instead of {:.2f}s use {ctx.retry_after:.2f}s
umm i dont think u will help
mb, error.retry_after
so did that work?
No
show code
i told you to put error.retry_after
!d discord.ext.commands.CommandOnCooldown.retry_after
The amount of seconds to wait before you can retry again.
also its already in seconds then why even bother formatting it to two decimal point?
nvm, it returns float
Working but instead of seconds I want to do hours minutes and seconds
How do I do it
then do basic math?
Wdym
hrs of cooldown
Yeah
I want to add it into my code
you can divide x seconds by 60 to get minutes
your code, you have that freedom I believe
Ok
@rocky trench ???
which way?
Do what I said then
@sullen shoal can you help
NameError: name 'users' is not defined
whats the problem with it
!e py from datetime import timedelta print(timedelta(seconds=600))
@slate swan :white_check_mark: Your eval job has completed with return code 0.
0:10:00
https://paste.pythondiscord.com/bucakafifa i keep getting this error on startup, im using the latest version of discord.py 2.0
its 600 lines long, what specifically needs to be seen
the part where you called asyncio.run there
NameError: name 'users' is not defined
oh i didnt see this message
search run
click on any line of code and do ctrl + f
show entire traceback
Traceback (most recent call last):
File "C:\Users\Admin\AppData\Local\Programs\Python\Python39\lib\site-packages\nextcord\ext\commands\bot.py", line 1052, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\Admin\AppData\Local\Programs\Python\Python39\lib\site-packages\nextcord\ext\commands\core.py", line 933, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\Admin\AppData\Local\Programs\Python\Python39\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: NameError: name 'users' is not defined
what did you import from index ?
from index import (
EMBED_COLOUR,
config,
cursor_n,
delay,
emojis,
mydb_n,
)```
it should be longer than that
@sullen shoal code
embed=nextcord.Embed(
title="Timer 2.0",
description=f"{numberint}",
colour=nextcord.Colour.random())
embed.set_footer(text=":good stuff smh", icon_url="https://cdn.discordapp.com/avatars/839171088079519776/12cdb639fe5c26dccf39bf2e5678b8fc.webp?size=1024")
susi = await ctx.reply(embed = embed)
await susi.add_reaction("⏰")
users_mention = [member.mention for reaction in susi.reactions async for user in reaction.users() if isinstance(user, discord.Member)]
users.pop(users.index(bot.user))
while number != 0:
number -= 1
embed=nextcord.Embed(
title="Timer 2.0",
description=f"{number}",
colour=nextcord.Colour.random())
embed.set_footer(text=":cool stuff smh", icon_url="https://cdn.discordapp.com/avatars/839171088079519776/12cdb639fe5c26dccf39bf2e5678b8fc.webp?size=1024")
await susi.edit(embed=embed)
hmmm = users
await asyncio.sleep(1)
await susi.edit(content='Ended!')
await ctx.send(f"{ctx.author.mention}and {hmmm}! The Timer has ended!")
Traceback (most recent call last):
File "C:\Users\Admin\AppData\Local\Programs\Python\Python39\lib\site-packages\nextcord\ext\commands\core.py", line 168, in wrapped
ret = await coro(*args, **kwargs)
File "c:\Users\Admin\Downloads\Palisade\main.py", line 879, in count
users.pop(users.index(bot.user))
NameError: name 'users' is not defined
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\Admin\AppData\Local\Programs\Python\Python39\lib\site-packages\nextcord\ext\commands\bot.py", line 1052, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\Admin\AppData\Local\Programs\Python\Python39\lib\site-packages\nextcord\ext\commands\core.py", line 933, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\Admin\AppData\Local\Programs\Python\Python39\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: NameError: name 'users' is not defined
theres more but this is where the code went wrong
The problem is clearly visible
looks like you want to use users_mention not users
hmm
do you need to see whats in index
now its coming as value error for my timer code
?
my timer code
@bot.command()
async def count(ctx, number:int):
try:
numberint = int(number)
if numberint < 0:
await ctx.reply(embed=nextcord.Embed(title="Timer", description="number can't be a negative",colour=nextcord.Colour.random()))
return
if numberint > 300:
await ctx.reply(embed=nextcord.Embed(title="Timer", description="number must be under 300", colour=nextcord.Colour.random()))
else:
embed=nextcord.Embed(
title="Timer 2.0",
description=f"{numberint}",
colour=nextcord.Colour.random())
embed.set_footer(text=":good stuff smh", icon_url="https://cdn.discordapp.com/avatars/839171088079519776/12cdb639fe5c26dccf39bf2e5678b8fc.webp?size=1024")
susi = await ctx.reply(embed = embed)
await susi.add_reaction("⏰")
users = [member.mention for reaction in susi.reactions async for user in reaction.users() if isinstance(user, discord.Member)]
users.pop(users.index(bot.user))
while number != 0:
number -= 1
embed=nextcord.Embed(
title="Timer 2.0",
description=f"{number}",
colour=nextcord.Colour.random())
embed.set_footer(text=":cool stuff smh", icon_url="https://cdn.discordapp.com/avatars/839171088079519776/12cdb639fe5c26dccf39bf2e5678b8fc.webp?size=1024")
await susi.edit(embed=embed)
hmmm = users
await asyncio.sleep(1)
await susi.edit(content='Ended!')
await ctx.send(f"{ctx.author.mention}and {hmmm}! The Timer has ended!")
except ValueError:
await ctx.send('time was not a number')
member.mention is str while bot.user is discord.User
remove the mention method
users = [member.mention for reaction in susi.reactions async for user in reaction.users() if isinstance(user, discord.Member)]
users.pop(users.index(bot.user))
and use ctx.guild.me
this?
yes there in the comprehension
well bot.user is discord.User
Extension 'Cogs.admin' raised an error: AttributeError: type object 'Embed' has no attribute 'Empty'```im now getting this error, theres no embeds in `admin` that are empty or empty strings
but your list is discord.Member
ctx.guild.me will return the Member obj of your bot
property me```
Similar to [`Client.user`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client.user "discord.Client.user") except an instance of [`Member`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member "discord.Member"). This is essentially used to get the member version of yourself.
is that all you got? or there's more of the error?
thats it
so
users = [guild.me for reaction in susi.reactions async for user in reaction.users() if isinstance(user, discord.Member)]
users.pop(users.index(bot.user))
??
ok
are you catching the errors and printing them yourself that are being raised from cogs?
@sullen shoal ill tell the whole story
did you copy paste that thing and now have no idea what you are doing there
Hey guys, Im making a timer command and i wanted it to have a reaction and if a user reacts on it, and when the timer ends, it will tell the users that the timer has ended
try:
bot.run(config.token)
except Exception as e:
print(f"Error when logging in: {e}")``` this is all im doing
yes
let it raise, it will provide more info
Alright
https://paste.pythondiscord.com/tuzesapose this is what i get
actually i have done something similar to that, i can link the source code if you want
are you loading the cogs yourself or its being done by some algorithm
import os
from utils import permissions
from discord.ext.commands import AutoShardedBot
class Bot(AutoShardedBot):
def __init__(self, *args, prefix=None, **kwargs):
super().__init__(*args, **kwargs)
self.prefix = prefix
async def setup_hook(self):
for file in os.listdir("Cogs"):
if file.endswith(".py"):
name = file[:-3]
await self.load_extension(f"Cogs.{name}")
async def on_message(self, msg):
if not self.is_ready() or msg.author.bot or not permissions.can_handle(
msg, "send_messages"):
return
await self.process_commands(msg)```
hmm thats a reminder but itll work ig
you may use continue for that
Why would info be raising any errors?
let me send the whole file
actually i think i found something that might cause issues
lemme see if that fixes anything
same thing
heres the whole file https://paste.pythondiscord.com/mecowahefu
should I add all of it or some of it because there is some useless stuff
i dislike that site, can you send http://paste.disnake.dev link
its the same thing
just understand the code
hmm i see
you will get better ideas of implementing your timer command
hmm i dont like cogs
its pretty hard for me
but really cool tbh
takes less space
each code has their own space
@sullen shoalnotice anything?
looks like these errors are because of new async stuff that discord.py has done
@sullen shoal should i remove the cogs as i dont need them
the thing that immediately sticks out to me is asyncio.get_event_loop(), but even though that needs to be changed in other files, info.py doesnt have anything like that
or is it part of code
if you find it hard, you probably are lacking some python skills, using OOP and use of decorators. Make personal projects with those skills and dont just try not to use cogs because you find it hard. thats not what a programmer should do
i was in the same stage, I stopped making bots and made several other projects except discord bots
i tried to understand the concept and experiment with it
this whole process took me around just 1/2 months
is your end goal being a discord bot developer or a software developer?
i just want to learn easily without my mind going crazy
none
technically yeah
Alright i guess im just not going to be using the new version of dpy because this makes absolutely no sense lmfao
but
ik thats why i switched to nextcord
yeah it sucks, i'd rather use disnake or hikari
but?
I dont understand why danny had to change how basic functions that were fine before worked
disnake is better than anything lel
its for a about of knowledege, like i would like to be a professional
Ill just fork dpy and fix it myself
and i know there is a long way for achieving that
XD
this is ridiculous
then your end goal shouldn't be to be just a discord bot developer that no one in the actual programming community has much respect for
no, my end goal is to learn python, html, java, javascript, all before 20
20 march?
learning multiple languages is not hard, once you understand the concept, you dont even need to learn anything for months, just keep reading the docs for the stuff you want
'the concept' is the hard part
XD
if you want to learn the languages you mentioned above you should have started with java, just a suggestion.
do you enjoy programming and getting stuck on something even after hours? if yes, it will be easy for you with the right resources
cause the others aint too hard, html has a completely different base
it doesn't really matter, all the mentioned programming languages there are object oriented programming languages
so it doesn't make a large difference
if you search, string methods x programming language, where x is any of those mentioned programming languages, you will end up with similar results
hmm
just be good at one then later on, when needed, you learn the others
currently you lack the understanding of the base concepts, you should try to learn them, look around yourself, try to seek for some resource that explains the use of OOP and it's benefits compared functional programming
We can say that a developer that knows all languages is a developer who knows how the three type of languages works: Those three types are procedural language, OOP language and interpreted language. Other than this three you should learn how those three type of language works: Machine language, low level language and high level language. A good thing to know when you start studying programming is how algorithms works. Once you learned how algorithms works, how to read an algorithm and create one you are good to go
Essentially with this base knowledge, when you switch to a language from another, the only thing that change is the syntax
yeah imma look at OOP
this library is also asynchronous, so do have a look at https://docs.python.org/3/library/asyncio-task.html after your understanding is clear with OOP
and then learn the uses of decorators
ok
do you now there is a sep parameter in print? do you know that we have abs function that returns the absolute number of a given number? if you dont, after all this is clear to you or at least the OOP part, don't forget to read the official documentation of Python
yes sir
Hi. I’m Austin Cepalia with realpython.com, and I welcome you to our series on object-oriented programming in Python 3. This is one of the biggest and most important subjects in all of programming and as you can see, we have a lot to cover. This…
im watching rn
not just for those two things, there are alot more stuff to it
i see
text articles are great, that will help you learn at your speed, not slow, not fast
yea but my normal preference is speaking/ voice
well you could try text articles along the line, you might enjoy the copy pasting of code snippets and jumping to certain topics without seeking some seconds forward or backward for minutes
yeah thats a benefit
as you read more, you will start to read faster than before and cover more topics faster
get_command(name)```
Get a [`Command`](https://docs.disnake.dev/en/latest/ext/commands/api.html#disnake.ext.commands.Command "disnake.ext.commands.Command") from the internal list of commands.
This could also be used as a way to get aliases.
The name could be fully qualified (e.g. `'foo bar'`) will get the subcommand `bar` of the group command `foo`. If a subcommand is not found then `None` is returned just as usual.
Apples
He meant before he is 20 so 5 years from now
@queen linden the message was auto-deleted because it had an invite link in it
pls help
@bot.event
async def on_member_update(before, after):
channel = bot.get_channel(950810468778410075)
if after.bot == True:
return
if before.activities == after.activities:
return
required_activity = "vanity url here"
userHasActivity = False
for activity in after.activities:
if isinstance(activity, discord.CustomActivity):
if str(activity).startswith(required_activity):
userHasActivity = True
if str(activity).endswith(required_activity):
userHasActivity = True
if userHasActivity:
emb = discord.Embed()
emb.description = f"""
thanks for the vanity i guess
"""
emb.color = 0x2f3136
emb.set_footer(text="to get this role, you must put vanity here in your status.")
emb.set_image(url="image link")
await channel.send(f"<@{after.id}>", embed=emb)
await after.add_roles(discord.utils.get(after.guild.roles, id=951202119434792960))
else:
await after.remove_roles(discord.utils.get(after.guild.roles, id=951202119434792960))
it keeps spamming the embed idk why
so sorry for the inv link
it keeps sending the embed like a few seconds or minutes after it sends one with the same user
How would I fix this https://pastebin.com/P1GXsYMc basically iv got custom prefixes in every guild and whenever my bot joins a guild it adds the guild id to prefixes.json however when I use the code that’s in the pastebin it fully breaks my code and it stops adding the guild ids to prefixes.json how would I fix it
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.
by stop using json as a data storage method
Yes
Use complex conditions for god's sake it's terrible to see all these ifs
aside from that wheres the problem
it keeps spamming the embed because members update all the time
also, just for "clean" purposes
using discord_utils is great for names and other attributes, but when you're getting an object by id, you can simply use get_x
so for your role, it's
guild.get_role(<your_id>)
is there another way then? 😭
depends on what you're ACTUALLY checking for in that event
whenever a member puts like the vanity url of my server it sends an embed and gives a role
also
for activity in after.activities:
if isinstance(activity, discord.CustomActivity):
if str(activity).startswith(required_activity):
userHasActivity = True
if str(activity).endswith(required_activity):
userHasActivity = True```
you don't have to keep on looping through the activities once the userHasActivity is set to True, you can break once that's done
puts where?
what you actually "forgot" to do in your event is if the ACTUAL update was the vanity url in activities
now, since every user has member updates all the time, it'll just keep on saying True because he has that url
what you ACTUALLY want to check for is if he DIDN't have that vanity url in activities before, but now does
oh icic
in the status
oh icic
im so sorry to ask but im confused on how to do that
if the before activities is not equal to the after activities, ....
why not use the on_presence_update event 
if he has v2+ or whatever, yes pls
I mean, 1.7.3 will just stop working as soon as discord stops the api version support
sad and true
oh
i havent heard of that
you can only use it if you are using a dpy fork or on dpy 2
hi i made this command trying to sort values in my sqlite database but it doesnt work. this is my code: py @client.command(name="lb") async def top10(ctx): db = client.database_connection cursor = await db.cursor() await cursor.execute(f"SELECT user_id, balance from money_data WHERE user_id = {ctx.guild.id} ORDER BY balance DESC LIMIT 3 ") result = await cursor.fetchall() embed = discord.Embed(title="Leaderboards", colour=discord.Colour(0x6790a7)) for i, x in enumerate(result, 1): embed.add_field(name=f"#{i}", value=f"<@{str(x[0])}> on Level {str(x[1])} with {str(x[2])} Total XP", inline=False) await ctx.send(embed=embed) print(result)
pls help me thank u
Anyone know how I make the user with the most coins be the top?
What's your code?
with open("users.json", "r") as f:
users = json.load(f)
data = []
index = 1
for item in users:
if index > 10:
break
member_name = f"<@{item}>"
member_amt = users[item]["coins"]
if index == 1:
msg1 = f"**[🥇] {member_name} - `{member_amt}` Coins**"
data.append(msg1)
if index == 2:
msg2 = f"**[🥈] {member_name} - `{member_amt}` Coins**"
data.append(msg2)
if index == 3:
msg3 = f"**[🥉] {member_name} - `{member_amt}` Coins**\n"
data.append(msg3)
if index >= 4:
members = f"**[{index}] {member_name} - `{member_amt}` Coins**"
data.append(members)
index += 1
msg = "\n".join(data)
em = discord.Embed(
title=f"Top 10 Coins",
description=f"{msg}",
color=discord.Color(0x00ff00),
timestamp=datetime.datetime.utcnow()
)
em.set_footer(text=f"{ctx.guild.name}")
await ctx.send(embed=em)```
Don't use json as a database
It does not matter at the moment, but how do you make the richest man be the top?
you have a dict of user, sort them by coins and then send the message
how?
!e
my_dict = {"tom": 231, "joe": 300, "tim": 400}
for i in sorted(my_dict.keys()):
print(i, end="\n")
@placid skiff :white_check_mark: Your eval job has completed with return code 0.
001 | joe
002 | tim
003 | tom
uhm strange
Maybe the bot is wrong? I will try anyway
whaa
no whait
!e
my_dict = {"tom": 231, "joe": 300, "tim": 400}
for i in sorted(my_dict.items()):
print(i, end="\n")
@placid skiff :white_check_mark: Your eval job has completed with return code 0.
001 | ('joe', 300)
002 | ('tim', 400)
003 | ('tom', 231)
How do I get my bot to identify if a user is another bot
!d discord.User.bot
Specifies if the user is a bot account.
so we have to check every member with this user.bot? for getting total membercount
?
!e
my_dict = {"tom": 231, "joe": 300, "tim": 400}
sorted_dict = sorted(my_dict.items(), key=lambda kv:(kv[1], kv[0]))
print(sorted_dict)
alr gtg
Camon
You're trying really hard for this.
Hahaha yeah
@candid orbit I read the documentation but IDK what to do
why in the hell it doesn't reverse
!e
my_dict = {"tom": 231, "joe": 300, "tim": 400}
print(sorted(my_dict.items(), key=lambda x: x[1]))
Enjoy
it needs to be reversed xD
Help...?
You literally just grab the user object and use the bot attr on it and it will give you your bill signifying if they are a bot or not
!rule 7, Not related to discord bots sorry if it is
The rules and guidelines that apply to this community can be found on our rules page. We expect all members of the community to have read and understood these.
is related to this
hahahaha
Ohk
You're Indian-
nope, Italian
Ou
Indians use "hahahahah"
@sage otter This is stupid... Give me code
!e
my_dict = {"tom": 231, "joe": 300, "tim": 400}
sorted_dict = sorted(my_dict.items(), key=lambda kv:(kv[1], kv[0]))
print(reversed(list(sorted_dict.items())))
@placid skiff :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 3, in <module>
003 | AttributeError: 'list' object has no attribute 'items'
How to make my bot identify if a user is bot
then why slicing doesn't work lol
!d discord.User.bot
Specifies if the user is a bot account.
!e
my_dict = {"tom": 231, "joe": 300, "tim": 400}
sorted_dict = sorted(my_dict.items(), key=lambda kv:(kv[1], kv[0]))
print(sorted_dict[::-1])
@placid skiff :white_check_mark: Your eval job has completed with return code 0.
[('tim', 400), ('joe', 300), ('tom', 231)]
Oh there it is
Wot
it returns True if the user you are checking is a bot else False
C...O...D...E
...
@bot.command()
async def am_i_bot(ctx: Context):
print(ctx.author.bot)
Wa-
.-.
no return type annotations 😔
YEY OKIMII
sup btw
bruh it's a print
Now help me :)
@client.command()
@commands.has_permissions(manage_messages=True)
async def warn(ctx, member: discord.Member, *, reason=None):
if member == member.bot:
await ctx.reply("You cannot warn a bot")
else:
print(f"Warn requested by {ctx.author}.")
await member.send(f"You have been warned in {ctx.guild.name} for {reason}")
await ctx.reply(f"{member} has been warned..")
print("Command successfully executed.")```
Doesn't work
yeah but atleast just set it to None
if member.bot == True?
you are comparing if a member object is equals to a bool object .-.
ok
or return a message obj
I am just doing if the member is a bot
ik but no harm in typehinting it yk
how do you check if bools are true or false usually?
.
why gifs..
Idk
yerlikayas way is better hes not comparing bools but hes saying if True or if not True
lol
same
i wanna just go full time coding and live in us
i did full time coding in summer now i dont do it much
ohh
how does dank memer support custom cmds for servers
like we can disable steal
ik its made in javascript but still
Stop, exams are fun
):
!d discord.ext.commands.Command.enabled
A boolean that indicates if the command is currently enabled. If the command is invoked while it is disabled, then DisabledCommand is raised to the on_command_error() event. Defaults to True.
hm

!ot
Off-topic channel: #ot2-never-nester’s-nightmare
Please read our off-topic etiquette before participating in conversations.

(Let's take this to an OT if u wanna continue)
i would like to debate in this topic
no i gtg to school 
Go to school then
ok
Who tf annotates commands
Umm I just learned abt embeding so like how can I get that rounded black box in which text is there inside embed?
That’s just so much work for little to no reason
It’s not like you're gonna be calling the coroutine anywhere else
i do
i still annotate it as it can return a different value than None
hello there
Me, if you always annotate things you get into the habit of doing it so you don't need to think about it
And what's the use of returning something in a command....?
Also pylance gets mad when I dont
hey there << just like that?
Cz PyLance gets a stroke easily
yes try
Aha sure
T-T
how to position set_image() to top of embed?
I can see that ig. Not really tho. That’s just a lack of discipline
wdym
like without a title ?
[image here]
title text here
fields here
no usage i just like to over do it
You don’t
image in different position in embed have different name, look at this screen
That’s a discord limitation
Thanks again man!!
oh ok what a bummer
Mind if I add you?
sure
fr plus its not a bad habit to over do it its like typehinting context yk
Thanks
Sometimes you have to.
Either way, annotations is still just for docs and intellisense just like type hints
And you won’t be calling the coroutine anywhere else so you don’t need it.
how dles dank memer have image generators
and its usefull for devs as well
Ok but you still don’t need it
do they use PIL?
You don’t need to see that every command returns Optional[Message]
you don't need annotations overall but its still used
how?
You use them during development
its annotations
You don’t use commands in development because you're not supposed to call them.

everyone has nitro.....
no man even i don't
that infers something else
🫂
i use built in union 
yes ot
there is something called logging and is very usefull for debugging, even for projects already in production
That’s called a pipe
bro what
|
.
Are pipes
yes the built in unions
That’s a whole different matter
No, it's not a lack of discipline it's sensible. The less you need to think about something the more you can focus on other things, if you have to focus on making typehints to ensure the validity of your code you're wasting time you could be thinking about application logic
theyre refered as the new built in union in python lol
Yes and that’s a pipe. That’s literally what it’s called in every language that’s used that operator for OR
well python doesnt refer to it as a pipe
¯\_(ツ)_/¯
but sure you can call it that
Omg okimii you're literally giving me a headache.
That’s literally what the operator is called
is it realted to 10th grade physics?
This has no relation to discord bots
No one says "You can use that built in union type there". Contrary to that, "You can use a pipe there for multiple types"
where in the pep
Anyone know why my commands not working?
maybe because you are not calling the commands
The CPython grammar file defines pipe as VBAR which is a little odd lol
It makes sense but also why
Maybe you‘re joking, of course I called them
It doesn’t need to be acknowledged in the pep to be considered what it is. In general that’s what that key on your keyboard is called
It’s not called "straight line" it’s called a pipe
a pipe can bend😳
then i guess, you are not calling in a right way. Bot doesn't have enough permission to do what it is supposed to do. The code isn't correct
um wait im sry i have series and parallel connection for electricity im sry
Then just don’t do it then
I’m literally arguing to not annotate commands
It’s a waste of time lack you said
@sage otter whats a pipe used for in other lans?
what is annotate..... command
Yesterday I changed from discord.Client to bot.Commands to make commands, but idk why the command is not working. When I add the code from the commands to an bot event it‘s working
The same thing it’s used for in python
typehints and all that are annotations
Aforementioned OR
ah yeah a bitwise of or
this is because your code is written to work with events, not to work with commands
You mean commands.Bot, right?
oof
thats commands.Bot.....
Guys i am new at this server because i wanna learn pythons to code my bot so can anyone tell me from where should i begin
docs
scoopy
dpy docs
Ayyy!
No no, I watched some docs and they did this with bot.command
Where?
I boosted from here, my mouse stopped working from there.
hyd
I'm doing great! Been a long time not checking up on here.
Yeah, I have but it‘s also not working
yup :rooyay:
It's a punishment
sed

with OOP, difference between method, function and parameters, asynchronous programming, decorators, inheritance, how to read documentation, basic python knowledge (builtin functions and methods)
Guys is pythons accept on visual studio node.js
What
I have a app on my laptop called visual studio
yes you can use vsc as an editor
How to do commands with events
import discord
bot = discord.Client()
@bot.event
async def on_message(msg):
if msg.startswith("!hi"):
await msg.reply("Lie")
How to make commands with discord.ext.commands
from discord.ext import commands
bot = commands.Bot(command_prefix="!")
@bot.command()
async def hi(ctx):
await ctx.reply("Cry")```
Okay
yes visual works
the command will never work because the event will "eat" your command
sir node.js isn't an ide
Don't forget to import discord
i have shown two different ways, they won't use both in one file
lmfao
Oh, I used '' for prefix instead of ""
we don't need discord in the code i sent
doesn't actually matter
no difference
single quotes and double quotes in python doesn't matter
^
even if you write the command in a separate file the on_message event will be triggered whenever is sent a message, so the commands will not be called
But then idk, because my code is the same
yeah yeah, so await bot.process_commands(msg)
no dif
show your code : )
more common, use the listen decorator
just use listen
!d discord.ext.commands.Bot.listen
@listen(name=None)```
A decorator that registers another function as an external event listener. Basically this allows you to listen to multiple events from different places e.g. such as [`on_ready()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_ready "discord.on_ready")
The functions being listened to must be a [coroutine](https://docs.python.org/3/library/asyncio-task.html#coroutine "(in Python v3.10)").
Example...
yeah yeah
Nitro expired? 
i am just showing him because he is familiar with events
no
lol
i am just showing him the difference we make in events and commands
cursor.execute('INSERT INTO banwords VALUES(%s, %s)', (message.author.id,1))2022-03-17T11:31:55.477270+00:00 app[worker.1]: psycopg2.errors.NumericValueOutOfRange: integer out of range
postgresql
async def jo(ctx):
await ctx.send('joooo')```
i literally know what happened
but use appropriate channel
#databases would be the best place to ask.
notice the s?
okay
ofc if your commands.Bot variable name is not sbot
But it doesn‘t matter because I used sbot=commands.Bot
Then what should i use in visual studio
Which file should I download
dude node.js is a javascript runtime which executes javascript codes in local machine
Uh
kden show full code
you should download the python ext and a interpreter
download python first
vsc needs an ext fyi
after that follw my steps
Okay
@slate swan go school
import os
import random
from discord import Intents
from discord.ext import commands
from witzliste import randomWitze
intents = Intents.default()
intents.members = True
sbot = commands.Bot(command_prefix='~',intents=intents)
@sbot.event
async def on_ready():
print('Ich habe mich nun eingeloggt als {0.user} '.format(sbot))
print('Jetzt geht es ab :D')
await sbot.change_presence(activity=discord.Game(name="mit Justin's Nerven"))
@sbot.command()
async def jo(ctx):
await ctx.send('joooo')```
im in school
Go study
screams in py2
umm sbot.run()?
u have it?
im free so no need
Of course. The bot is working only the commands not
the bot has perms to send msg right?
and you don't have any errors on the terminal
He has admin permissions
then idk
Yeah, that‘s the problem
Maybe it‘s because of replit.com?
@narrow grailu dont import command you imported commands nvrm
?
But isn‘t it right?
you on discord.py 2.0?
Idk
Why does my bot doesn't respond to commands in v2.0? / Why is message.content not there.
Discord.py v2.0 has migrated to api v10, and with this has come the introduction of Intents.message_content, which is disabled by default.
This means that you will need to __explicitly enable it in code and in the panel, at https://discord.com/developers/applications.__
intents = discord.Intents.default() # All but the THREE privileged ones
intents.message_content = True # Subscribe to the Message Content intent
bot = commands.Bot(command_prefix='-', intents=intents) # Pass the intents into your commands.Bot or discord.Client
``` NOTE: Still not responding to commands? see `?faq on_message` in [#559455534965850142](/guild/267624335836053506/channel/559455534965850142/)
try this



