#discord-bots
1 messages · Page 781 of 1
Get all the bot member objects and iterate through the perms, append the True condition to a list
so basically
hey i am having another problem cant make number of admin roles in a guild in serverinfo
[b for b in member.bot if b.guild_permissions.administrator]
but here how does it know which guild or something
Why not get all bot member objects first, it will be increase readability
Otherwise if you wanna shorthen, best of luck
how can i make my bot create new channel and add that channel to my channel_id = 'here'
Store the channel create method in a variable, and use the id property on the TextChannel object
guild = ctx.message.guild
r = [r for r in guild.roles if r.role_permissions.administrator]
await ctx.send(f'{len(r)}')
what is the prob in it
@tender estuary
ctx.author.guild first of all
then?
are you trying to get number of admin roles?
just a sec
ok
guild = ctx.author.guild
await ctx.send(len[r for r in guild.roles if r.role_permissions.administrator]))
Btw what error do you get?
multiple cooldowns for single command like if a user is not donator his cooldown is 10s and if he is then set the cooldown to 5s
You can remove cooldowns and stuff from commands, I just forgt how
but how?
!d discord.ext.commands.Command.reset_cooldown
reset_cooldown(ctx)```
Resets the cooldown on this command.
@true moon ^^
what's IPC
also you shared the wrong imports, the ones you shared are different than what it shows in the error
My bot gets admin by default, but still the error code is that you don't have the right to ban. Why is that?
hiearchy possibly
who did you try to ban? the owner?
nope, im the owner and i try ban my test acc
but nothing
Since I put an error system in it, it hasn't been good.
try giving the bot a role with admin permissions
so go but this bot is not a servereb you have
translate shit
now i delet the error system and works
BROO token
It's not a nuker?
@quick gust this is not any nuker
Oo
Imagine using replit on a mobile phone
lol, just a heads up if you are new to this, replit is not a good way to host your bots
Just telling, sorry if I'm wrong
@slate swan then where should I host
you aren't wrong
A virtual private server which you gotta buy ;-;
An actual server, or a vps
He’s doing this for fun he shouldn’t buy hosting
Ik lol, but some people start arguing
There we go
@slate swan reptl is enough I don't have money🥲
F.U.N
Hmm
never knew discord bots were F.U.N ¯\_(ツ)_/¯

what's the point of that?
They were making a nuker earlier
Goes against the rule 5
The nuker is already working but don't know to add more cmmds for kicking admins
Pls not asking doubt just saying
Ok
Helper or anybody?
That looks so F.U.N
Kooool
Imagine using a part of your life for making a nuker
F.U.N
First of all stop pinging
#pingreact
@commands.Cog.listener()
async def on_message(self,message):
prfx = await db.fetchrow('''SELECT prefix FROM setup WHERE guild = $1''', message.guild.id)
prefix = prfx["prefix"]
db.close()
mention = f'<@{self.bot.user.id}>'
if (mention == message.content):
await message.channel.send(f'My prefix here is ``{prefix}``')
pcmention = f'<@!{self.bot.user.id}>'
if (pcmention == message.content):
await message.channel.send(f'My prefix here is ``{prefix}``')```ping react stopped working
Stop pinging, I was in a class smhh ¯_(ツ)_/¯
@slate swan srry 🙏🙏
alright then
There's a few issues with this code.
1)on_message takes a "message" parameter.
- author.content doesn't exist. I think you mean message.content
So how it works:
when a message is dispatched it is printed to the console, then when a message is deleted, it is printed in the console, along with the content and the author name
uhm
the on_message event requires a message parameter typehinted as discord.Message
No need now I accidentally deleted the file😫
syntax is odd, but it's probably because of ^
!d disnake.ext.commands.when_mentioned_or
disnake.ext.commands.when_mentioned_or(*prefixes)```
A callable that implements when mentioned or other prefixes provided.
These are meant to be passed into the [`Bot.command_prefix`](https://docs.disnake.dev/en/latest/ext/commands/api.html#disnake.ext.commands.Bot.command_prefix "disnake.ext.commands.Bot.command_prefix") attribute.
Example
```py
bot = commands.Bot(command_prefix=commands.when_mentioned_or('!'))
```...
here, use this
Any one know how to make cmmd for kick and ban of members
@slate swan nop I also have that doubt
they are Python keywords that are used to define coroutines
Coroutines means
how in the hell are you programming discord bots when you don't even know what a coroutine is? lol
Why should I talk, plus no one listens to me assuming I'm too dumb for this shit 
async is a keyword not an attribute or a method smh
@placid skiff I just search for some cods and combine them
I would strongly recommend you to learn asynchronous programming
my god
anyways, I have class, dont ping, bye
That'ssss.. slightly worrying
there is pycord which is just a fork of dpy which is still maintained
@rose gyro I want to add kick/ban members for my bot can you help me
neither discord.py lol... what is that?
from what I understand from the docs, it's just a set of libs regarding networking
like, asyncio, socket etc
Lol but first of all, how you want to use something that you don't even know what it is
and second, i have used a lot of fork and never heard of this "ipc"
Make a command, get the member mentioned, and call the kick coroutine
can you link it?
i have some free time from my work cuz i'm waiting a client to response my mail xD
You have to study, you can't start developing a discord bot without knowing those thing and it's useless for you asking us, we can't tell you everything. Study python, study d.py and then start developing
https://discordpy.readthedocs.io/en/stable/ext/commands/commands.html there are examples here
How to study
it's useless to give him examples xD, he can't understand them
so uh what happens if i select and what happens if i dont
Are you familiar with virtual envs?
found the link? you can send it to me in pm or it will be consider as spam
From were
can I learn python
yes, I want to check it
google, youtube, courses, everywhere
docs, too. helped me a lot personally
well you can use docs when you understand what are classes, parameters, methods, coroutines and a lot of other things are lol
learn the basics, then start applying them to various projects. even a simple program means a lot
correct.
docs can be used along with tutorials since they go more in depth into the language concepts
YouTube are full of English viedos and I'm a mallu 🙃
and oop*
nvm its under classes
lol
almost everything related to programming is english
@placid skiff yss
you can't start programming without knowing english
even python is half english words ¯_(ツ)_/¯
@slate swan ya
python is meant to be a lot like english language lol
Should I laugh?
yes of course hahaha
I'll laugh to save you further humiliation then 🫂
I know English but don't understand some words they say
How does this not work?
@commands.command(name='Warnings',aliases=["warns"])
@commands.has_permissions(manage_messages=True)
async def warnings(self, ctx, user:discord.Member=None):
the decorator command name rules out the function name
https://wiki.python.org/moin/BeginnersGuide/NonProgrammers if you are new to programming, otherwise https://www.python.org/about/gettingstarted/
and the decorator command name has a capital W
commands can't have capitals, but i think you can use the name attribute to give a different name to your command, it should work
no
they can have a capital?
So how do I fix it
probably
lower the command name in the decorator
okay
eh? weird
You can set a case sensitive attribute for the bot
Does it?
Thanks it works
Which?
performance loss as said
Full of exceptions? 
And also got 1 question I got a @commands.has_permissions but how do I make it when soemone without that permissions tries the command that is just await.ctx something
Ohh, makes sense
What is parameters
!d discord.ext.commands.MissingPermissions
exception discord.ext.commands.MissingPermissions(missing_permissions, *args)```
Exception raised when the command invoker lacks permissions to run a command.
This inherits from [`CheckFailure`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure")
Error handling
uhhh... what?
use it with the on_command_error event
oh he meant that
Yeah
Mhm
Wht is parameters
or a different error handler for the command is easy
For?
For god sake, study D_D
How do I do that?
this is not the appropriate channel pls
oh god
Read about error handling in docs
huwunter
It's a bot event which takes in two args, the ctx which represents the context and the error which is the error that was raised. U can use isinstance to control how the bot should parse/act when a specific error comes
Can anyone tell me wht is variables
How do I define client here
ctx.bot
Ah that
Yeah
self, ctx, error
Got a idea?
Also u can do @commands.Cog.listener()
I already did
class Warn(commands.Cog):
def __init__(self, client):
self.client = client
@commands.command()
@commands.has_permissions(manage_messages=True)
async def warn(self, ctx, user:discord.Member=None, *, reason=None):
id= user.id
if collection.count_documents({"memberid":id}) == 0:
collection.insert_one({"memberid":id,"warns": 0})
if reason==None:
return await ctx.send("Please mention a reason")
elif user==None:
return await ctx.send("Please mention a user!")
warn_count = collection.find_one({"memberid":id})
count = warn_count["warns"]
new_count = count + 1
collection.update_one({"memberid":id},{"$set":{"warns": new_count}})
await ctx.send(f"Warned {user.name} for **{reason}** in **{ctx.guild}** | They now have **{new_count}** warnings!")
@commands.Cog.listener()
async def on_command_error(ctx,error):
if isinstance(error,commands.MissingPermissions):
await ctx.send("You can't do that")
await ctx.message.delete
def setup(client):
client.add_cog(Warn(client))
That is my code
I told ya
on_connand_error(self, ctx, error):
Also add an else statement like
else:
raise error
Mm
Where?
In the command error event
can someone link me a tutorial i could follow to setup a bot
Which bot
nvm
Ok
why do you send randomized messages every time lmao
Ok
Ok
¯_(ツ)_/¯
so i'm not very familiar with writing these (functions?) so i'm not sure if I'm doing it right. This is taking place inside of a on_member_join, What I want to check is that the member who joined is the same person who reacted with the emoji and if they are then it deletes the msg but if the person who adds a reaction is not the person who joined then it just ignores the reaction
This is my errorpy Ignoring exception in on_member_join Traceback (most recent call last): File "/usr/local/lib/python3.8/dist-packages/discord/client.py", line 343, in _run_event await coro(*args, **kwargs) File "/home/modmail/cogs/events.py", line 322, in on_member_join reaction, user = await self.bot.wait_for('raw_reaction_add', check = check) File "/usr/lib/python3.8/asyncio/tasks.py", line 455, in wait_for return await fut File "/usr/local/lib/python3.8/dist-packages/discord/client.py", line 370, in dispatch result = condition(*args) TypeError: check() missing 1 required positional argument: 'user'and this is my code```py
await error_message.add_reaction("
")
def check(reaction, user):
return user == member and str(reaction.emoji) == '
'
reaction, user = await self.bot.wait_for('raw_reaction_add', check = check)
await error_message.delete()```
have you checked the arguments of on_raw_reaction_add in the docs?
Hint: it's not reaction and user
How to make it so that if the bot joins a new server, it sends a message
use an empty char
\u200b
use the on_guild_join event for this
thx
oh yeah, it's just payload isn't it, so i'd need payload.emoji and payload.member, so somehting more like this?```py
await error_message.add_reaction("
")
def check(payload):
return payload.member == member and str(payload.emoji) == '
'
payload = await self.bot.wait_for('raw_reaction_add', check = check)
await error_message.delete()```
check the docs, then ask 😉 / try and see
why does the event not work
because you have to use it correctly
because you have to use a decorator on top of the event 🧠
well i had tried it and it didn't appear to error, but it's also probs mot the best quality of code
i want someone to helpme with mongo
well, appears to work, right?
no one respondig there ;-;
can be 2 options;
- vague question
- no one is active there
don't ask if you can ask a question, we're not in school
just ask straight away
lmao, why would asynchronous functions be made using keywords if asyncio was a third party lib
im... newbie
plus, who imports modules at line 27 
asyncio is preinstalled with discordpy python, no need to worry about that
edited
lol
it doesn't look right tho
ss
it's the right option tho
unless you want free errors
I see
free?
how do i do that
hello
Hello ¯_(ツ)_/¯
H
@bot.event if your bot's variable name is bot ofc
easy
ok
how do I do random.randrange 3 different times?
it is named as client.event tho
do I do it by using a for loop?
my bot is client
nothing to do with dpy tho xd, can be asked in a simple help channel
then edit accordingly
no one's answering
bot, client = Bot() lmfao
well thts what i put it as
give it some time
anyone?
whats the issue, band?
or use google for quicker answers
I want random.randrange to be done 3 different times
do I use a for loop for that?
use a for loop, easy
you also have built-in functions / methods which create random lists for you...
#❓|how-to-get-help
not here
huh?
his question isn't related to discord bots
it will help my discord bot
yeah lol
try and see, don't ask first lol
I did
what have you tried googling?
yes
what have you googled?
yes
Well but it isn't related to discord bots. It's about your question and not what you're building tbh. If you're making a web application and need to know how to print first, you'd ask in a general help channel and not in some specialized server meant for web applications specifically
^^
how do use random.randrange 3 different times
oh okay
lmao, that's wayyy too detailed, ofc you won't find an answer on google for that
i did tho
code?
BuT iTs ReLaTeD tO mY wEbSiTe 
she did though
tf
Go to #python-discussion
what did I say 
get yo anime looking bonified genderfluid headass outta here
get out
Lmao
That should be enough ¯_(ツ)_/¯
ok, done yet?
who's posting server invites 💀💀
not me
xGrx, remove the server invite from your code
some average server advertiser
or just
Pasting large amounts of code
If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
done yet? head ass
what if they're above average though
??
no comments then
what
@brisk brook Can I screenshot?
say one more thing, I'm pinging a mod
Your pfp hits hard
ok
bet bro
thanks bro
If they were, they should have known that there must have been an invite blocking system in a server like this one
Lol
Someone was going to study
cof cof
I am studying since an hour continuously
hunter your about me is missing a curly brace
How do I send a POST request of a message with one image attachment, using synchronous requests.post? I keep getting this response: b'{"message": "Cannot send an empty message", "code": 50006}'. I am printing the body of my request and my message is there, with payload_json and content seemingly in the right place (Content-Disposition: form-data; name="payload_json"\r\nContent-Type: application/json\r\n\r\n{"content": "My great message"}\r\n--1041de0a2d52d6e387c3fc61182138c9\r\nContent-Disposition: form-data; name="file[0]")
It's just discord being discord
Hunter new to js objects 
help?
@bot.event
async def on_ready():
Channel = bot.get_channel('919761341277949965')
Text= "**support team**/n hai there! looking to help out <@&932598948663812146>?/n react with :writing_hand: if you are,/n- always available to answer member’s questions/n- always alert and ready to take action/n- can always fix problems maturely/n receiving the support team role means you **strictly** need to follow the rules above. any disrespect or ignorance will have your role removed. thank you."
Moji = await bot.send_message(Channel, Text)
await bot.add_reaction(Moji, emoji=':writing_hand:')
@bot.event
async def on_reaction_add(reaction, user):
Channel = bot.get_channel('919761341277949965')
if reaction.message.channel.id != Channel
return
if reaction.emoji == ":writing_hand:":
Role = discord.utils.get(user.server.roles, name="Trial Mod")
await bot.add_roles(user, Role) ```error
``` File "main.py", line 167
if reaction.message.channel.id != Channel
^
SyntaxError: invalid syntax```
no :
missing a colon
oh-
Old syntax
if reaction.message.channel.id != Channel:
the channel id should be an integer
and indent the return inside that block'
this ain't related to discord bots, and are you sure the attachment is valid and it isn't None?
bot.add_reaction and bot.send_message isn't a thing anymore
That's the syntax from pre v1 discord.py module
very old code 😬
probably copy pasted 🥶
proceeds to install discord.py 0.001
U can now just do Channel.send()
lmao
no, it was from a while ago.
The API version it uses doesn't work anymore (if u talking about Alpha Version)
thats what im saying 💀
okay, discord sucks then
^
"a while"
imagine imagining that "a while"
lol
The latest version is 9 and iirc, the version it used was pre v7 or smth
okay?
discord uwu
no?
why is the default version deprecated
i didnt do anything. and i didnt copy and paste, i had an argument with you last month. im just trying to get help from a simple old code, what do you want from me? leave me alone.
Cz it provides the most basic syntax of the current implementation of send messages and stuff, like it doesn't has action rows and stuff, but got stuff like Channel.send or smth? I don't really know, sorry
It's far too easy to get made fun of in a programming server.
For compat
can't say without knowing what vars is
isn't the Channel.send thing something done by the wrapper?
You shouldn't use v6 anymore, you should manually specify the v9 in the url
who even remembers a month old F.U.N.
Yea
why nonone help me
ask
That isn't just old, but VERY old code. The API version it uses is most probably dead, and doesn't work anymore.
how old would you think it is, hunter
it was like 3 years ago, most likely more.
I don't really know, it's only been 1 year since I have been into discord bot deving scene
it's just a dictionary from my eval command
heres the code that got errored https://paste.disnake.dev/?id=1643286839908639&language=python
Most probably that, yea. But there are A LOT OF new changes since then, so u should just switch, since the API version it uses is pretty much dead now
can u both just ignore that and move on
Or take it to DMs
never forget the past
Actually u should
don't forget what they took from you
Anyways, if u still don't wanna forget it, then just try remembering it in DMs
their dms gonna be spicy 🥵
¯_(ツ)_/¯
At least ASK
I keep my dms closed lmfao
@client.event
async def on_guild_join():
print("hello")
what the hell how does this not even work
u r missing an arg guild
elaborate on "doesn't work"
discord.on_guild_join(guild)```
Called when a [`Guild`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild "discord.Guild") is either created by the [`Client`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client "discord.Client") or when the [`Client`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client "discord.Client") joins a guild.
This requires [`Intents.guilds`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.guilds "discord.Intents.guilds") to be enabled.
hunter pro
It is a Discord bot sending this request 🙂
I trimmed the request body, but in the full print I get I do see lots of non-printable bytes which I assume are the contents of the image.
https://github.com/Rapptz/discord.py/blob/master/discord/gateway.py#L372-L387 are you sure about that? i couldn't find anything related to v9 in d.py
gateway isn't the same as API
gateway is the websocket where u get the events, http is the API which is used to send messages
See the file http.py
Since components are a part of API v9
o
hey i needed some help 😅
why am i getting invalid string format in this line
if i use %S instead of $s it does not gives error but locks on to a date jan 1 1970
let's go over this together, ok?
oke
if you see in the docs under member.created_at, what does it return?
the member acc create date
I want to hear the datatype
||datetime.datetime||
spoiler
u were talking abt this right ?
yeah, you know what datatype that is? xd
no 😅
it's right under the text
got it
there you go
oof i had been looking api refernce a diff website it is not written there
bruh
ok, so to show a timestamp, you need to CONVERT your datetime to a timestamp
google can help you with those simple questions
hm oke let mee see
which one looks nicer?
2nd
2nd imo
I don't see any differences besides the 2 dropdowns
I don't like 2 drop downs
i think thats the only difference
depends on what they're for
2nd just looks cleaner, if 2 dropdowns are not needed then go with 2nd
first dropdown is for my bots cogs, second dropdown is for the commands in the cogs
isn't there a better selection menu?
cogs is understandable to use a dropdown, but the commands can be long
hm
I'd use buttons for the commands which turn green / red if enabled/disabled
and an embed on top to explain their use
So, I cannot tell what the Python code for my Discord bot is doing wrong. I am trying to send a POST request which contains a message with an attached image. I cannot see where what I am sending differs from https://discord.com/developers/docs/resources/channel#create-message and https://discord.com/developers/docs/reference#uploading-files.
This integrates with an existing application, so I must use synchronous requests. Thus, I cannot use disnake's methods to send the message; I am using requests.post instead. When passed a files argument, that method sets the request's Content-Type to multipart/form-data, as required by the docs. I print out the request and I see my image, represented as bytes. I also send a JSON payload containing the message text and an attachments list, referencing the file I am sending. That JSON has a Content-Type of application/json, as required by the docs. I can paste here the POST request, trimmed of the gibberish image bytes, if it would help you to help me.
What am I doing wrong?
Integrate your service with Discord — whether it's a bot or a game or whatever your wildest imagination can come up with.
Integrate your service with Discord — whether it's a bot or a game or whatever your wildest imagination can come up with.
uh
@client.event
async def on_guild_join(guild):
print("hello")
still doesnt work):
you do realize that this only prints if the bot joins a new guild right? not some random member
i kicked the bot and invited it
!paste
Pasting large amounts of code
If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
put your code here, don't leak the token
!d discord.Intents.guilds
Whether guild related events are enabled.
This corresponds to the following events...
U got these?
the whole code?
that's my suspicion, his intents
no
can you add this to your bot constructor:
is your client a commands.Bot or a discord.Client?
hmm so i went and saw some but did not really understood :(
anyways, just add intents = discord.Intents.default() in that method
commands.bot
commands.Bot, I hope
?
how long does rate limit last?
just add what I typed above in the Bot()
after him if u can help me out..
no idea what you tried
u were telling me ?
it is the discord module not me
it is something wrong whit the module, not my code
look
it still doesnt work
sigh why is my bot broken

I haven't seen any code from you
@client.event
async def on_guild_join(guild):
print("hello")
it's just
commands.Bot(whatever, intents = discord.Intents.default())
intents = disnake.Intents.default()
intents.members = True
intents.guilds = True
client = commands.Bot(command_prefix=prefix, intents=intents, case_insenstivive = True)
client.remove_command('help')
intents.guilds is default True, remove that line
also, case_insensitive
ok
it doesnt work even if its not there
why my bot bully me

I 'm guessing you have some client = ... somewhere else too
can i send u the code
full
done
wait what how doees this not worek
it's just on_guild_join(guild) as stated in the DOCS
unless you're in a class, then you have to add self as first parameter
it not in a clas
code?
class link(disnake.ui.View):
def __init__(self):
super().__init__()
self.add_item(disnake.ui.Button(label=':white_check_mark: Support Server', style=disnake.ButtonStyle.blurple,
url='e'))
self.add_item(disnake.ui.Button(label=':globe_with_meridians: Website', style=disnake.ButtonStyle.blurple,
url='e'))
@client.event
async def on_guild_join(guild):
joinchannel = guild.system_channel
embed=disnake.Embed(color=0x8400a8, title="Thank You For Adding PexiBot To Your Server!", description="Here are the basics to get you started.\n\n**Commands**:\n`/help` and `!info`\n\n**Support Server:**\nBot Support\n[PexiBot Support]e)\n\n**Vote/Review PexiBot:**\n[top.gg/PexiBot](e)\n\n**Issues?**\nMake sure the bot has administrator permissions.\nJoin the [support server](https://e) if there is any other issues.")
await joinchannel.send(embed=embed, view=link())
client.warnings[guild.id] = {}
her
ctrl+f on on_guild_join in your code
I highly suspect you have another one somewhere
and also, a traceback is there for a reason
it has an error AND tells you WHERE to error is
now a full error traceback
not the last 3 lines
Hikari question: How do I send a message? I am not using lightbulb or any sort of command library.
how can I access this variable
@client.event
async def on_ready():
global start_time
start_time = datetime.now()
In a cog like this
class uptime(commands.Cog):
def __init__(self, client):
self.client = client
@commands.command()
async def uptime(self, ctx):
delta_uptime = datetime.now() - start_time
Need to keep track of a variable between functions? No problem!
⚠️ Careful what you name it though, else you might overwrite something ⚠️
Just add it to your commands.Bot or discord.Client instance like so:
bot = commands.Bot(...)
bot.my_variable = 0
async def foo():
bot.my_variable += 1
# In a cog
@commands.command()
async def counter(self,ctx):
await ctx.send("Current Counter is at {}".format(ctx.bot.my_variable))
This also allows you to access this from other cogs/extensions/functions. Anywhere you have access to the bot instance
check your other files too
other files?
just these
try and rerun the bot I'd say
ok
!botvar exist
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!
works
nice to know commands on another server
(:
bruh, turning it off and on again is like the first thing you'd do
hello
most of us turn stuff on and off, when the plug behaves like shit I turn it off and on again
the plug?
that was before I realized that it was broken and had to get a new one
desktop pc be like
it was for charging my computer
random bullshit go
guys?
what did you do with your code? It needs something to happen for it to raise the error, else it happens to everybody
show your startup settings
if [[ -d .git ]] && [[ 0 == "1" ]]; then git pull; fi; if [[ ! -z ${PY_PACKAGES} ]]; then pip install -U --target /home/container/ ${PY_PACKAGES}; fi; if [[ -f /home/container/requirements.txt ]]; then pip install -U --target /home/container/ -r requirements.txt; fi; /usr/local/bin/python /home/container/main.py
not that , the python version, requirements TXT , additional package etc
now it is nothing
because i dont want the packages to be installed a few time
is there a way to count how many messages a user has sent on a server, ik i can use history to search a channels history but is there a way to search the entire servers history rather than a channel or would I need to search through every channel and then combine each channel's history to one counter
it was like
discord-componentes==3-4-3
and stuff like that
And the python docker image version?
try changing it to 3.8+ ...
choose 3.9 or 10
the 2nd option, loop thru all channels and count the messages
you removed the requirements file
so discord is no longer there
ohh thats why
let me try
let me try
and we are back to this error
thanks, thought i'd have to do that but it seemed a bit taxing on the bot
@slate swan
rushed this command, am i suppose to use it like "?slowmode {channel} {seconds}"?
@bot.command()
async def slowmode(ctx, seconds: int):
await ctx.channel.edit(slowmode_delay=seconds)
em1=discord.Embed(description="the `slowmode` has been **set** to {seconds} seconds", colour=discord.Colour.green())
await ctx.send(embed=em1)```
if I'm only adding one role to someone do I need the top 2 lines of this code? py tmp = [] tmp.append(discord.Object(797166495993692160)) await after.add_roles(*tmp, reason = f"{after} received the {tmp} role as they meet all of the criteria.", atomic = True)
No
So could I swap *tmp out for just the role ID or would it need to be *role-ID, or would I need to do tmp = self.bot.get_role(ID = role-ID then do add_role(tmp, reason)
u either need discord.Object or a discord.Role object
so using self.bot.ctx.guild.get_role(role-ID) would give me a discord.Role object right?
Yea
hello guys, can you tell me the event name to control nick changng?
nick changing*
discord.on_member_update(before, after)```
Called when a [`Member`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member "discord.Member") updates their profile.
This is called when one or more of the following things change:
• nickname
• roles
• pending...
@minor panther ^
coming back into this lib after 1 year any thing to note?
yea
so its come to an end?
I think, self.ctx.channel.send(delete_after=3.0) should be ok
but your message doesn't take any content btw
won't it send the message
cog
wait cog?
yup
like i will be using this context manager in a cog
does that has to do something with it
i don't think so ?
not actually
why do i get this error?
perhaps it will give empty message error
oh i'm dumb should be async tho
i would pass args in that function + turn into async
yeah but its a context manager so i would be using it something like this
and i want to remove that delete_after=3.0 part
async def funcname(self, content, dl):
await self.ctx.channel.send(content, delete_after=dl)
right
I would write smth like this
@scarlet snow no.. actually its pain to write it again and again
i have like so many commands like this
so it would be pain to write it in all of em

how do i add the discord developer portal custom games things with discord.py?
can someone send me docs on on_ready?
!d discord.ext.commands.Bot.on_ready
No documentation found for the requested symbol.
!d discord.on_ready
discord.on_ready()```
Called when the client is done preparing the data received from Discord. Usually after login is successful and the [`Client.guilds`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client.guilds "discord.Client.guilds") and co. are filled up.
Warning
This function is not guaranteed to be the first event called. Likewise, this function is **not** guaranteed to only be called once. This library implements reconnection logic and thus will end up calling this event whenever a RESUME request fails.
Are allowed mentions for send only for that specific message?
guys?
so a lot of my friends asked me to make a discord bot for our class, which keeps track of the timetable and reminds them what class it is, by pinging a role. For this, i want to trigger events only when it is a certain day and time, in IST. is there any way i can do that?
thanks
@tasks.loop(seconds = 600)
async def member():
name1 = (f"Member Count : {member.guild.member_count}")
chan = member.guild.get_channel(877784914668437508)
await chan.edit(name=name1)``` why wont this work im sure im missing an attribute not sure what it would be tho
how did mmeber.guild come?
member is the function name, not a member object
also you need
member.start() of course
whats member.start?
how do I get the channel a user sends a message in
??
ctx.channel
message.channel
ahokay
@tasks.loop(seconds = 600)
async def member(ctx):
member.start()
name1 = (f"Member Count : {ctx.guild.member_count}")
chan = ctx.guild.get_channel(877784914668437508)
await chan.edit(name=name1)```
makes sence?
this is a risky function name
why?
member can be used as a variable name
also, you don't start a loop in the loop itself
right
also, your task shouldn't have the ctx parameter
never used this function sorry
Are allowed mentions for send only for that specific message?
"oh, but how do I get the guild and channel then?"
get_guild, get_channel
oh i see
I'd say yes, seems to be quite logical
can you give an example?
the docs do
i see
@tasks.loop(seconds = 600)
async def member():
name1 = (f"Member Count : {get_guild.member_count}")
chan = get_guild.get_channel(877784914668437508)
await chan.edit(name=name1)```
this?
@commands.Cog.listener()
async def on_message(self, message):
if message.author == bot:
return
print(message.author)
if content_list_complied.search(message.content) is not None:
await message.channel.send(message.content)
else:
print("hellos")
``` why doesn't this not ignore the bot
!dno, get_guild is a method of bot / client
it needs an id as argument
oh i see
bot.user
better option:
if message.author.bot: return
=> ignores ALL bots
what's bot? Is bot your instance of commands.Bot or something?
If it is, then yeah, bot.user will do if you want to ignore your bot.
@tasks.loop(seconds = 600)
async def member():
name1 = (f"Member Count : {bot.get_guild.member_count}")
chan = bot.get_guild.get_channel(877784914668437508)
await chan.edit(name=name1)
get_guild is a method, not an attribute
can i have the docs lol
guys why when i run my code in my hosting i get that error? on my pc it works just fine
You need to provide get_guild a guild ID
oh i see
!d discord.ext.commands.Bot.get_guild
get_guild(id, /)```
Returns a guild with the given ID.
google your errors first
you can do bot.get_guild(guild_id).get_channel(channel_id) i think
why not just get_channel?
yep, i figured they wanted to do it in one line or something
good point lol
works too, but it'll check all guilds then
if you specify a guild, I'd think it'll go a bit faster
mhm makes sense
but , it gets the guild first , and then the channel ... so it may take kinda same time
yeah, but you can set it for all messages you send in bot constructor if i remember
so i have this command
@bot.command()
@commands.has_role("Bot Developer")
async def speak(self, ctx, channel_id, *, message):
channel_used = int(channel_id)
await channel_used.send(message)
but for some reason, whenever i try to run it, it just says "this command cannot be used in private messages."
i do have an on_command_error event and that's what it said
guild_id gives id or is it for mt referne?
because you have to unwrap the error, it's throwing an CommandInvoke error
english pls
id yes
guild_id gives id or is it for my reference?
1 thing, why do you have @bot.command with self as the first argument in your function
he means "is guild_id placeholder or actual id ?"
@tasks.loop(seconds = 600)
async def member():
name1 = (f"Member Count : {bot.get_guild(guild_id).member_count}")
chan = bot.get_guild(guild_id).get_channel(877784914668437508)
await chan.edit(name=name1)```
So are you in a cog or not?
this?
ah, its placeholder ye, you change that with actual id
the actual guild_id, not a variable xd
i asked that lol
you can hardcode it in there
nvm your right but idk if that causes the error
what if i wanted the guild id tho
also, not a good idea to get the guild twice
just
guild = bot.get_guild(..)
use the guild object later
wdym, you can get it however you want, by db or anything
the bot is only in 1 server tho
Can you remove that part of your error handler and send the full traceback?
ok
oh i see
Infinity lounge
Ignoring exception in command speak:
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/disnake/ext/commands/bot_base.py", line 560, in invoke
await ctx.command.invoke(ctx)
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/disnake/ext/commands/core.py", line 921, in invoke
await self.prepare(ctx)
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/disnake/ext/commands/core.py", line 842, in prepare
if not await self.can_run(ctx):
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/disnake/ext/commands/core.py", line 1168, in can_run
return await disnake.utils.async_all(predicate(ctx) for predicate in predicates) # type: ignore
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/disnake/utils.py", line 547, in async_all
for elem in gen:
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/disnake/ext/commands/core.py", line 1168, in <genexpr>
return await disnake.utils.async_all(predicate(ctx) for predicate in predicates) # type: ignore
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/disnake/ext/commands/core.py", line 1901, in predicate
raise NoPrivateMessage()
disnake.ext.commands.errors.NoPriva
i dont see my code
Traceback (most recent call last):
File "C:\Users\Nitin\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\tasks\__init__.py", line 101, in _loop
await self.coro(*args, **kwargs)
File "C:\Users\Nitin\OneDrive\Desktop\New bot\main.py", line 52, in member
name1 = (f"Member Count : {guild.member_count}")
AttributeError: 'NoneType' object has no attribute 'member_count'``` this is not a method for it?
oh yeah and the bottom part is
raise NoPrivateMessage()
disnake.ext.commands.errors.NoPrivateMessage: This command cannot be used in private messages.
@tasks.loop(seconds = 600)
async def member():
guild = bot.get_guild(877784914668437504)
name1 = (f"Member Count : {guild.member_count}")
chan = guild.get_channel(877784914668437508)
await chan.edit(name=name1)
member.start()```
Is the guild in cache?
as in non exsistance?
@final iron
perfect
you dont need to edit it everytime 600 sec goes
events exist for that
i do get an error tho 🤔
which event?
this one idk if its a method
i dont remember but i think on_member_join
they'd likely be referring to on_member_join
which executes when yk... someone joins
guys this has a disnake.ext.commands.errors.NoPrivateMessage: This command cannot be used in private messages.
guild is none, bot isn't in that server check to sniper's answer below
oh i could use that didnt think of that
2 options
- you passed an incorrect guild ID
1.1 bot isn't in the guild you specified - your guild isn't in cache yet (you have to await bot.wait_until_ready()
i see
you'd also need on_member_remove
yes i could do that as well
async def member():
await bot.wait_until_ready()
guild = bot.get_guild(877784914668437504)
name1 = (f"Member Count : {guild.member_count}")
chan = guild.get_channel(877784914668437508)
await chan.edit(name=name1)
member.start()```
Test it now
ill check
you don't need the () in name1
actually i dont but it wont give an error else ways
btw works now thanks! also sorry since I'm coming back to this lib after 2 years
No worries
now gotta try it with member join
you don't want to update whenever a member joins / leaves
why not?
I think that might get you ratelimited if you have a popular server where people keep joining and leaving
^^
anyone will help???
https://github.com/Rapptz/discord.py/blob/master/discord/ext/commands/bot.py#L507
ppl can just do this if their instance is commands.Bot```py
@bot.listen("on_member_join")
@bot.listen("on_member_remove")
async def on_member_count_change(member):
do len() and stuff here
discord/ext/commands/bot.py line 507
return func```
show me the on_command_error handler
i removed it and got this traceback
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/disnake/ext/commands/bot_base.py", line 560, in invoke
await ctx.command.invoke(ctx)
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/disnake/ext/commands/core.py", line 921, in invoke
await self.prepare(ctx)
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/disnake/ext/commands/core.py", line 842, in prepare
if not await self.can_run(ctx):
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/disnake/ext/commands/core.py", line 1168, in can_run
return await disnake.utils.async_all(predicate(ctx) for predicate in predicates) # type: ignore
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/disnake/utils.py", line 547, in async_all
for elem in gen:
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/disnake/ext/commands/core.py", line 1168, in <genexpr>
return await disnake.utils.async_all(predicate(ctx) for predicate in predicates) # type: ignore
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/disnake/ext/commands/core.py", line 1901, in predicate
raise NoPrivateMessage()
disnake.ext.commands.errors.NoPrivateMessage: This command cannot be used in private messages.
oh wow
i dont see my code in there
so what i am doing rn is fine?
in the traceback
yes
error says it all, no?
it wont
yea thanks
but i am not using @commands.guild_only() tho, i dont get why the error is coming
ye...
i dont understand why the error came
async def suggest_error(ctx, error):
if isinstance(error, commands.CommandOnCooldown):
await ctx.send(f"Hey! you need to wait {(int(error.retry_after/60))} mins before using it again!")``` this will work for cogs as well?
or i need a new one for cogs?
you do realize your channel_id is just an int right, not a channel object?
an integer doesn't have a .send() method 🧠
oh
yeah (just dont forget to add self if that is ever gonna stay in class)
wait you are right
watch out with error handlers
you want to handle other errors too
else
ofc I am 😎
wait so is that the only error you noticed
oh so @suggest.error async def suggest_error(self ,ctx, error): if isinstance(error, commands.CommandOnCooldown): await ctx.send(f"Hey! you need to wait {(int(error.retry_after/60))} mins before using it again!")
? i dont think so
seems right for me
just like any parameters of a function, yes.
@potent spear
Ignoring exception in command speak:
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/disnake/ext/commands/bot_base.py", line 560, in invoke
await ctx.command.invoke(ctx)
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/disnake/ext/commands/core.py", line 921, in invoke
await self.prepare(ctx)
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/disnake/ext/commands/core.py", line 842, in prepare
if not await self.can_run(ctx):
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/disnake/ext/commands/core.py", line 1168, in can_run
return await disnake.utils.async_all(predicate(ctx) for predicate in predicates) # type: ignore
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/disnake/utils.py", line 547, in async_all
for elem in gen:
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/disnake/ext/commands/core.py", line 1168, in <genexpr>
return await disnake.utils.async_all(predicate(ctx) for predicate in predicates) # type: ignore
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/disnake/ext/commands/core.py", line 1901, in predicate
raise NoPrivateMessage()
disnake.ext.commands.errors.NoPrivateMessage: This command cannot be used in private messages.
same traceback, i removed that useless variable for converting the channel_id into an int and used the channel_id param instead
so wont it get mixed with what were they called quargs i think
i mean, its fine to call ctx anything you want, discord.py passes it without doing keyword
this is what's wrong with your command:
you have a has_role decorator on a command
obviously in DM's people don't have ROLES, so this won't work either
ohh
kwargs, you do know what they are right?
yea i do
tell me
arent they what come after ctx
not necessarily
kwargs are
keyword arguments
yea
there's a difference between positional and keyword arguments, you should check that out sometime
**kwargs
* is for tuple and shit
i mean, let me just write example
def a(*args):
print(args)
a(1,2,3) # (1, 2, 3)
def b(**kwargs):
print(kwargs)
b(a = 1, b = 2) # {"a" : 1, "b" : 2}
yea btw did the dev add the embed option thing below them
wdym
great example 🏅
oh! btw what if i did b(1,2,3)?
error.
oh
an error would happen, since b doesn't expect any positionals
TypeError to be specific
its in python aswell
ye
i see thank : )
just realised i searched if discord.py is discontined and google had a result with the lib your working on lol
nice
error pycordIgnoring exception in on_member_join Traceback (most recent call last): File "C:\Users\hp\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\client.py", line 352, in _run_event await coro(*args, **kwargs) File ".\main.py", line 28, in on_member_join asset = member.display_avatar().with_size(128) TypeError: 'Asset' object is not callable
code
Does anyone know how I can do a perms check with the database, I have a command to add a person in the premium category and I would like her to use only those commands. I use mongodb
@commands.Cog.listener()
async def on_message(self, message):
if message.author.bot:
return
if "@everyone" in message.content:
channel1 = bot.fetch_channel(915552800350535750)
await message.channel.purge(limit=1)
at = discord.Embed(title="Moderation LOG", description="Messaged deleted")
at.add_field(name="Message deleted", value="``"+str(message.content)+"``")
at.add_field(name="Infracting user", value=str(message.author.mention))
at.add_field(name="Channel", value=str(message.channel.mention))
at.set_footer(text=f'Cosmic Overground')
at.timestamp = datetime.datetime.utcnow()
message.channel1.send(embed=at)``` yo I get this message ``TypeError: coroutine.send() takes no keyword arguments`` anyone got an idea as to why
you have to await it
also, you can just check if
message.guild.default_role in message.role_mentions:
idk if you like clean looks
oh my god
same goes for fetch_channel, this has to be awaited too
you can perfectly use get_channel tho (which doesn't need to be awaited since it's not an API call)
lastly, the str() is redundant, since they're all strings anyways
also your footer doesn't need the f as in f string
and removing a message is as simple as
await message.delete() you don't need the purge shit
If you store all premium users in the db, then when someone uses a command just check if their ID is stored in the db. If it is then the command runs and if not then it doesn't
and how can I do this? The database saves them this way.
so im building a anti scam link bot and my take on this was to parse the url to search for typical scam link embeds "og" meta tags, do you guys think its a good way to do it?
The easiest way to understand is to have an if statement at the start of the commands you want to be premium only, where it says something like
current_user_id = ...
list_of_user_ids = ...
if current_user_id not in list_of_user_ids:
send("sorry you're not premium")
else:
the rest of the command here
There are loads of nicer ways to do it but that's the simplest way to think about it without using decorators and checks which I'm not sure if you've used before
This is the code to add and remove premium: https://paste.pythondiscord.com/jogovaxaxu.less
But i don't know how can i check now
I think your code adds them to the database every single time since lines 21:24 aren't in an if statement, unless this isn't indented properly?
How it looks now is it will do some checks and send the error but it adds them anyway
regex is the best for those types of things
^
im using regex to scan if its a url
I have no problem with the code when I add someone or remove someone from the premium. My problem is not so how to check if the user is in the database in order to use the commands
then good just search for keywords like descord dicsord and other misspelled urls
not misspelled but fake
On a Levelup command that works fine but for some it doesnt How can i fix it?
thats what i did first but its not precise enough, im trying to go onto these websites and check if they have some nitro stuff in their emebed
wdym go onto
error says it all
currently using a module that scrapes meta tags with bs4
I need only the code to check a user if is premium or not
premium?
try to put your bot on top of other roles
added to a database for that server specifically, not like Nitro premium
from world import Person
okimii = Person(name="Okimii")``` it should be this @slate swan
huh
its just a nick name in this server only
so i wont update it
lol
The class
Sorry I gotta head out, if you haven't fixed it send me a message later and I can look when I'm home
Someone here could probably help sooner though
that wouldnt raise a 429
lmfao
it was 403 tho, and they stated that it worked for some users and didnt for others
Ok thank you
oh yeah a 429 is rate limitation
still wouldnt raise anything
oh ok
the role hierarchy has nothing to do with your bot
so it wont raise a http code because of roles
it just wont do the action
i got that once
it wouldnt ban users with a higher role even tho it had the perms
thats just how discord works
yes
you cant ban someone with higher power
ik, but i had a similar error saying it had no permission, thats why i thought it might be because of that
only way is if you did it via a bot that has a higher role than the user you're trying to ban
^
can someone help me #help-pear
[discord.py 2.0 doubt]
I was curious if there's a reason discord.ui.View doesn't have a message attribute:
https://github.com/Rapptz/discord.py/blob/master/discord/abc.py#L1437
Can't it be set after this?
how to drop a command if it gets called again?
Yea it doesn't , but you can define it yourself , I'll send an example in a moment
Check this out , it's Disnake but all it used in that example was discord.py 2.0 so it doesn't matter
dr...op?
Yes
so like you do !help and there's buttons for that command, if you do !help again, the old message's buttons wont work/disappear
is there a channel bucket?
variable with boolean ig
bucket?
if it's False, all button deactivate, then after that, send another help command after it becomes True maybe
yes, there is a buckettype
for channels right
you mean channel cooldowns?
can discord bots join a vc and unmute?
yes a bucket for channels
I want to avoid having to do the
view.message = await ctx.send("These buttons will be disabled or removed", view=view)
part every time, so was wondering if there is any issue if I attach it in the send call itself
yeah, according to dpy docs there is
??
Sure
avoid doing what
wait unmute itself?
okimii 
well, i read somewhere it could send 20 ms of sound data
!d discord.ext.commands.BucketType.channel
The channel bucket operates on a per-channel basis.
thx
Python bot be like
!d discord.VoiceClient.play
play(source, *, after=None)```
Plays an [`AudioSource`](https://discordpy.readthedocs.io/en/master/api.html#discord.AudioSource "discord.AudioSource").
The finalizer, `after` is called after the source has been exhausted or an error occurred.
If an error happens while the audio player is running, the exception is caught and the audio player is then stopped. If no after callback is passed, any caught exception will be displayed as if it were raised.
what errors does it give if an error occurrs?
See the docs
I should add a doc searcher thing for my personal assistant
!src d
Look up documentation for Python symbols.
that can help still
well since that button click has no attribute you may use to get the message , that's the only way to do that afaik
i guess
👁️ 👁️
what do u wanna do
Wait what
Ah wait nvm, u r doing it the correct way
Thought view.message was a thing, sorry



