#discord-bots
1 messages · Page 690 of 1
yep
i understood nothimg from this
I think you need to use global
ARE YOU KIDDING ME?
im not.
in both of the methods?
helo
it will list the slash commands your bot has wdym...
hey
!e ```py
b = 1
class Foo:
def bar():
return b + 1
print(Foo.bar())
@tawdry perch :white_check_mark: Your eval job has completed with return code 0.
2
Try it. Then you'll understand what I said
why not use the class for the variables? thats the advantage of using classes
hm
@heavy folio
firstly @faint monolith did u even load your cog where the slashes are in
no
Yes
next u on dpy?
i wanna use b in the button label but i cant use class attrs before self was defined
???
@disnake.ui.button(label=b)
async def c(self, bu, i):
# await i.response.defer()
global b
b += 1
self.edit()
``` @boreal ravine, is the error on the which line if it is here
subclass ui.Button and use View.add_item
???
Yes yes. Python
tf
ig
WDYM DUDE?
subclass it to? what do I change
in which line?
dpy = discord.py????
yeah??
so I want to make a discord bot to play any text I search "not URL!!"(well maybe later) to play music from YouTube can someone help .. I tried tuts on YT ( 😅 ) but they are very confusing methods ... I tried something tho
YES
now show your code
i didnt get one, the error came from view.on_error method
okay looks like theres a lot i have to explain here wait a moment let me get on my pc
hm
what
am I allowed to collect data like server owner names and server's names
With 100 of codes
!d discord.Guild use the owner and name atrribute
class discord.Guild```
Represents a Discord guild.
This is referred to as a “server” in the official Discord UI.
x == y Checks if two guilds are equal.
x != y Checks if two guilds are not equal.
hash(x) Returns the guild’s hash.
str(x) Returns the guild’s name.
guild.name (str), guild.owner (user obj)
!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.
in what way allowed? discord ToS might not have anything against it (not sure but I would guess so) but the server the bot is in might not want it to happen depending of the rules
and if you talk about user names, you can surely store them
oh the server must be in the guild yeah
uh what
you have to subclass, https://discordpy.readthedocs.io/en/master/api.html#discord.ui.Button
class MyButton(ui.Button):
def __init__(self, ...):
super().__init__(label=...)
then add the item to your view using View.add_item
I meant does ToS allow it, I remember there was something about "stalking", collecting data from users and servers
ah ok brb
well this server keeps track of every user id and collects some data (can be found from their website) and it's not against ToS afaik
hm
but myxi that isnt the problem, im ok with using a variable in the main scope the problem is that im getting a nameerror for no reason
namerror?
yes
show the traceback
check that makes sure user has manage message perms before running commands
dont tell me you dont have one because thats not how humans debug
@heavy folio
https://paste.pythondiscord.com/avildohistro.py
?
Dammit that is wrong...
interesting
i dont think thats how classes work though
also that can be easily be fixed by setting that an attr of the View subclass
Here you are @heavy folio
theres no point of using globals inside a method
!ytdl
Per Python Discord's Rule 5, we are unable to assist with questions related to youtube-dl, pytube, or other YouTube video downloaders, as their usage violates YouTube's Terms of Service.
For reference, this usage is covered by the following clauses in YouTube's TOS, as of 2021-03-17:
The following restrictions apply to your use of the Service. You are not allowed to:
1. access, reproduce, download, distribute, transmit, broadcast, display, sell, license, alter, modify or otherwise use any part of the Service or any Content except: (a) as specifically permitted by the Service; (b) with prior written permission from YouTube and, if applicable, the respective rights holders; or (c) as permitted by applicable law;
3. access the Service using any automated means (such as robots, botnets or scrapers) except: (a) in the case of public search engines, in accordance with YouTube’s robots.txt file; (b) with YouTube’s prior written permission; or (c) as permitted by applicable law;
9. use the Service to view or listen to Content other than for personal, non-commercial use (for example, you may not publicly screen videos or stream music from the Service)
actually globals are often times useless
we will not help with music bots
why isnt it working then
can't you just have self.b = 1 and edit it?
no
youre using jsk that might be the cause of it. because it runs the code inside a function so the variable you set is local not global.
global it before the first definition
hm
!e
def func():
hi = 1
class H():
def hi(self):
global hi
print(hi)
H().hi()
func()```
@sullen shoal :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 8, in <module>
003 | File "<string>", line 7, in func
004 | File "<string>", line 6, in hi
005 | NameError: name 'hi' is not defined
!e
def func():
global hi
hi = 1
class H():
def hi(self):
#global hi
print(hi)
H().hi()
func()```
@sullen shoal :white_check_mark: Your eval job has completed with return code 0.
1
hm
why is there a class inside a function? that looks weird for some reason
thats what kayle is doing
oh
as i said you gotta subclass ui.Button and use View.add_item
global is not the solution
hm
how to get all the servers that both the user and bot are in (mutual servers)
also if it is, you should never be proud of that code
that got removed in 1.7 iirc
kk
anyone?
you just asked that question, be patient
!d discord.User.mutual_guilds
property mutual_guilds: List[Guild]```
The guilds that the user shares with the client.
Note
This will only return mutual guilds within the client’s internal cache.
New in version 1.7.
sorry
how do i write it in my code?
try reading the docs first
also it seems to just return a list of guild that a user is in so maybe you just pass user obj + that mutual_guilds thing
in the cache
hm?
seems bad since it only gives cached guilds
Hi all
that'd work? it says guilds in the cache not the member
i dont think fetching guild will have every member's member object tho
does anyone have a ruby extention for visual studio code
!ot
Off-topic channels
There are three off-topic channels:
• #ot2-never-nester’s-nightmare
• #ot1-perplexing-regexing
• #ot0-psvm’s-eternal-disapproval
Their names change randomly every 24 hours, but you can always find them under the OFF-TOPIC/GENERAL category in the channel list.
Please read our off-topic etiquette before participating in conversations.
looks better suited for #editors-ides
hmm could be, just came up with ot because of ruby
how to check if a message was sent in dms (using if and on_message event)
@client.event
async def on_message(message):
if message.guild == None:
#some stuff
⬆️ doesnt work
if isinstance(message.channel , discord.DMChannel): ```
ty
how to check that the bot is not the one that sent the message (using if)
you can just compare message.author with client.user
kk ty
though, you can just ignore bots completely by checking if discord.Member.bot is True
return if its True
if message.guild:
return
makes the code return if the message was sent in guild
ohk ty!
oh I just noticed you had a answer alrd 😅, well gl!
print(message.author.mutual_guilds)
```sry i dont know how to do this 😭
oh
how to make these kinds of messages
ephernal iirc, works for slash commands
one only the author can see
works for interactions*
!d discord.abc.Messageable.send
hm not here
hmm
ephemeral
whats ephemeral
ephemeral messages, they work with any kind of interactions, here is the breakdown of "interactions"
views:
buttons
dropdowns
etc
application_commands:
slash_commands
user_commands
message_commands
the kind of messages which only a particular user can see, i.e.
mhm
you just add ephemeral=True to that interaction when you send it and it should work
have you tried using uptimerobot
hey guys. im trying to host my discord bot 24/7. whats the best way to do this? thanks :))
For the first time heroku would be fine
is it difficult to do?
Need help if my bot dont have presnece intent and i want to use this code
intents = discord.Intents.all()
intents.members = True
How to use this
channel.set_permissions(user, None) iirc
!d discord.TextChannel.set_permissions
await set_permissions(target, *, overwrite=see - below, reason=None, **permissions)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Sets the channel specific permission overwrites for a target in the channel.
The `target` parameter should either be a [`Member`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member "discord.Member") or a [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role") that belongs to guild.
The `overwrite` parameter, if given, must either be `None` or [`PermissionOverwrite`](https://discordpy.readthedocs.io/en/master/api.html#discord.PermissionOverwrite "discord.PermissionOverwrite"). For convenience, you can pass in keyword arguments denoting [`Permissions`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions "discord.Permissions") attributes. If this is done, then you cannot mix the keyword arguments with the `overwrite` parameter.
If the `overwrite` parameter is `None`, then the permission overwrites are deleted.
You must have the [`manage_roles`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.manage_roles "discord.Permissions.manage_roles") permission to use this...
Yups pass None to overwrites kwarg
@sullen shoal 👀
ill look into it
oh damn another guy getting ruined
thx
lmao
Need help if my bot dont have presnece intent and i want to use this code
intents = discord.Intents.all()
intents.members = True
How to use this
iv already made the bot in pycharm and it would be so long to get it all on repl properly
ohh yeah then idk
how do i host it on heroku?
put the code in github, use env variables of heroku for the token and os.getenv in code then just hit deploy
haha i think i need to do some research
wait a min i think ik smth that could help
-> step 1: make a git repo with all of your bot files
-> step 2: go to your heroku account, create a new app (located in US, will get your average bot latency to under 30ms 100% of the time)
-> step 3: go to settings and add python buildpack, then click "Reveal Config Vars" and add your bot token, along with whatever you have in your .env there
-> step 4: go to deploy, select Github, connect your github account, then select your bot's repo
-> step 5: make sure your bot has a `Procfile` which has "worker: python main.py" (or whatever the file that runs your bot is) and a requirements.txt where you have your requirements listed in newlines
-> step 6: go to overview, click Configure Dynos and then click that pencil icon and toggle the button then click Confirm
-> step 7: make sure you have 2 heroku accounts and switch between them at the end of each month (when you get an email from heroku saying that you're running out of dynos, they refresh at the start of each month)
-> step 8: done
thanks to @slate swan
.bm
tysm!
how do i make a discord bot make a channel
!d discord.Guild.create_text_channel
await create_text_channel(name, *, reason=None, category=None, position=..., topic=..., slowmode_delay=..., nsfw=..., overwrites=...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Creates a [`TextChannel`](https://discordpy.readthedocs.io/en/master/api.html#discord.TextChannel "discord.TextChannel") for the guild.
Note that you need the [`manage_channels`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.manage_channels "discord.Permissions.manage_channels") permission to create the channel.
The `overwrites` parameter can be used to create a ‘secret’ channel upon creation. This parameter expects a [`dict`](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.9)") of overwrites with the target (either a [`Member`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member "discord.Member") or a [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role")) as the key and a [`PermissionOverwrite`](https://discordpy.readthedocs.io/en/master/api.html#discord.PermissionOverwrite "discord.PermissionOverwrite") as the value.
Note
Creating a channel of a specified position will not update the position of other channels to follow suit. A follow-up call to [`edit()`](https://discordpy.readthedocs.io/en/master/api.html#discord.TextChannel.edit "discord.TextChannel.edit") will be required to update the position of the channel in the channel list...
can only 1 on_message be there?
u can also do guild.create_voice_channel and so on
nope
ty
str(len(guild.members)) gives only 1 member for some reason
only 1 is working
is anybody familiar with danny's asqlite?
u gotta use bot.listen and name the functions different
!intents
Using intents in discord.py
Intents are a feature of Discord that tells the gateway exactly which events to send your bot. By default, discord.py has all intents enabled, except for the Members and Presences intents, which are needed for events such as on_member and to get members' statuses.
To enable one of these intents, you need to first go to the Discord developer portal, then to the bot page of your bot's application. Scroll down to the Privileged Gateway Intents section, then enable the intents that you need.
Next, in your bot you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:
from discord import Intents
from discord.ext import commands
intents = Intents.default()
intents.members = True
bot = commands.Bot(command_prefix="!", intents=intents)
For more info about using intents, see the discord.py docs on intents, and for general information about them, see the Discord developer documentation on intents.
yea, to some extent
oh ok thanks
nice, I am a complete beginner to databases and i needed to know how to connect my bot to sqlite3
sqlite3.connect(database[, timeout, detect_types, isolation_level, check_same_thread, factory, cached_statements, uri])```
Opens a connection to the SQLite database file *database*. By default returns a [`Connection`](https://docs.python.org/3/library/sqlite3.html#sqlite3.Connection "sqlite3.Connection") object, unless a custom *factory* is given.
*database* is a [path-like object](https://docs.python.org/3/glossary.html#term-path-like-object) giving the pathname (absolute or relative to the current working directory) of the database file to be opened. You can use `":memory:"` to open a database connection to a database that resides in RAM instead of on disk.
When a database is accessed by multiple connections, and one of the processes modifies the database, the SQLite database is locked until that transaction is committed. The *timeout* parameter specifies how long the connection should wait for the lock to go away until raising an exception. The default for the timeout parameter is 5.0 (five seconds).
There
this is sqlite3 ig
asqlite is just await in front of sqlite3
isnt asqlite different from sqlite3 package?
oh-
what is overwrites ?
ic thanks
!d discord.PermissionOverwrite
class discord.PermissionOverwrite(**kwargs)```
A type that is used to represent a channel specific permission.
Unlike a regular [`Permissions`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions "discord.Permissions"), the default value of a permission is equivalent to `None` and not `False`. Setting a value to `False` is **explicitly** denying that permission, while setting a value to `True` is **explicitly** allowing that permission.
The values supported by this are the same as [`Permissions`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions "discord.Permissions") with the added possibility of it being set to `None`.
x == y Checks if two overwrites are equal.
x != y Checks if two overwrites are not equal.
iter(x) Returns an iterator of `(perm, value)` pairs. This allows it to be, for example, constructed as a dict or a list of pairs. Note that aliases are not shown.
db = await asqlite.connect(file-name)
for guild in client.guilds:
text_channel_list = []
for channel in guild.text_channels:
text_channel_list.append(channel)
file = open("guild"+str(guild.id), "w")
file.write("Name: "+str(guild)+"\nOwner: "+str(guild.owner)+"\nMembers: "+str(len(guild.members))+"\nChannels: "+str(text_channel_list))
would this be against the ToS? (collecting server info)
file name?
cz db and discord bot
Like its not even maintained well as aiosqlite
how do I get the server owner's name and tag not id?
cuz guild.owner_id gives
then use aiosqlite ezz
!pypi aiosqlite
ah
Yes
!d discord.Guild.owner
property owner: Optional[discord.member.Member]```
The member that owns the guild.
k
property name```
Equivalent to [`User.name`](https://discordpy.readthedocs.io/en/master/api.html#discord.User.name "discord.User.name")
there
Lmao well I don't really care whatever they are using since there ain't much changes in sqlite3 anyways
output is None
k
Better maintained
ok but how do i connect?
Check their docs
k
Should be in the pypi page
or just check this out if you're too lazy to read docs https://github.com/sarthak-py/disnake-template/blob/main/saving_data/sqlite3_usage.py
!hel[
Hmm
We all know what your doing
Even I do
Ignoring exception in on_message
Traceback (most recent call last):
File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "c:\Users\user\OneDrive\Υπολογιστής\Bots\main.py", line 224, in on_message
users = json.load(f)
File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\json\__init__.py", line 293, in load
return loads(fp.read(),
File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\json\__init__.py", line 346, in loads
return _default_decoder.decode(s)
File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\json\decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\json\decoder.py", line 355, in raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)``` this error code level up why
Anyways add {} in the file
json?
yea
}``` here ?
that is your JSON file?
yes
weird, the error says the file is empty
{
}``` users.json file this ?
wait
Ignoring exception in on_message
Traceback (most recent call last):
File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "c:\Users\user\OneDrive\Υπολογιστής\Bots\main.py", line 228, in on_message
await level_up(users, message.author, message.channl)
AttributeError: 'Message' object has no attribute 'channl'
Ignoring exception in on_message
Traceback (most recent call last):
File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "c:\Users\user\OneDrive\Υπολογιστής\Bots\main.py", line 228, in on_message
await level_up(users, message.author, message.channl)
AttributeError: 'Message' object has no attribute 'channl'``` new error
hey guys, i used github and heroku to host my bot but its still offline.. does anyone know any troubleshooting things i can try?
*channel
channel*
try seeing the console
where i put it?
any errors you get in the heroku console?
json ?
nope no errors
you have message.channl which should be message.channel
line 228 of your code
my only idea is that maybe my requirements are wrong? what exactly should i put in that file?
@slate swan u into web development?
{"728612647423180820": {"experience": 5, "level": 1}, "728612647423180820": {"experience": 5, "level": 1}} this prob for json
why ?
use discdb tho What is the problem
what
wat's the issue
ik basic html and css but havent started with anything yet
ah okay
hover over it and tell the problem
yes
the message IDs are the same, and that is happening twice
that isn't allowed in JSON
and now what do I do?
it will either error or make the bot online unless your code isn't actually running the bot
Can someone explain me how can I make one button to run bot.command on_click?
and now what do I do?
!d discord.ext.commands.Bot.get_command , get the command and use .invoke()
get_command(name)```
Get a [`Command`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Command "discord.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.
@slate swan mind helping?
manoloudios?
mhm
client.owner is not a thing in og discord.py , if you want the command to be usable only by you use @commands.is_owner() check
f , now noone other than you will be able to slap
for that atleast
hey

just compare the user.id with your id
¯_(ツ)_/¯
bruh
if user.id == 834811249622908988:
#dont slap me```
ive been on vsc for to long
jeez
lol
!d discord.ext.commands.Bot.owner_id
The user ID that owns the bot. If this is not set and is then queried via is_owner() then it is fetched automatically using application_info().
loll
!d discord.ext.commands.Bot.owner_ids
The user IDs that owns the bot. This is similar to owner_id. If this is not set and the application is team based, then it is fetched automatically using application_info(). For performance reasons it is recommended to use a set for the collection. You cannot set both owner_id and owner_ids.
New in version 1.3.
or just use
@is_owner decorator
cleaner
does the same thing without an if statement
they dont want to do that tho
another way would be,
if user.id == ctx.bot.owner_id:
#dont slap me ```
user and the bot owner
it makes the entire command only usable by the command
what they're trying to do is to see if the mentioned user is the owner
yea , cleaner and not hardcoded
why
🧍♂️
they dont want to get virtually slapped
they want to make something like , if the author mentions someone other than him , bot slaps them
if its him , bot doesnt
ah i see
ah i see thats funny lol
kindof
i think i would have done smth completely unnecessary to do that
using global checks and a list of commands where i dont want the first arg to be me and Context.args
you did what
the benefit is that i can have multiple commands like that without the if statement in every command where I want it
?
nvm
i mean yeah its good
or make a custom decorator
idk how that's gonna work
do u know for level up ?
avoid dumping data for same ids multiple times
also i think you should do some maths with experience to get the level
def decorator():
async def check(ctx):
if ctx.author.id == 1234567890:
return
else:
pass
idk would this work
im just doing it from my mind lol
thats not how decorators work
decorators are just some easy way to do smth like
decorator(func)
which is same as
@decorator
def func()```
another way is to do
def func()
decorator(func)```
yeah ik
isnt this a custom check
a command is just a function so thats gonna error
so it would be in the commands
@bot.command()
@decorator()
async def commmand():
....
what error?
however if you do,
def decorator():
async def check(ctx):
if ctx.author.id == 1234567890:
return
else:
pass
return check```
`ctx` will be the function
you cant get Context like that thats it
can anyone tell me why this code is not working ???
@bot.event
async def on_member_join(member):
mbed = discord.Embed(
title=f'**Welcome!**',
description=f'**{hello}**',
color=(c.light_grey())
)
await member.send(embed=mbed)
member.channel isnt a thing
whats the error
that's the problem... It's not giving any error... It's just not working
!intents
Using intents in discord.py
Intents are a feature of Discord that tells the gateway exactly which events to send your bot. By default, discord.py has all intents enabled, except for the Members and Presences intents, which are needed for events such as on_member and to get members' statuses.
To enable one of these intents, you need to first go to the Discord developer portal, then to the bot page of your bot's application. Scroll down to the Privileged Gateway Intents section, then enable the intents that you need.
Next, in your bot you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:
from discord import Intents
from discord.ext import commands
intents = Intents.default()
intents.members = True
bot = commands.Bot(command_prefix="!", intents=intents)
For more info about using intents, see the discord.py docs on intents, and for general information about them, see the Discord developer documentation on intents.
on_member_*
doesn't work without members intent
You are not allowed to use that command here. Please use the #bot-commands channel instead.
guys, how do I create such a rule, Who clicked on the reaction and he is not the author who called the return command
its on_member_join not on_member
okay listen.. I just want that... whenever a member joins my server... my bot will DM that user... Can anyone share me the code for that cuz mine is not working... 😭
no
^
whyy
@bot.event()
channel = channel id
async def on_member_join():
await channel.send(f"{member.mention} join the server!")```
no spoonfeed zone
do the shit in
#discord-bots message
and your code will work
lol nice code its not even right
be sure to enable them in the dev panel too
someone help?
whats the channel var for
lol
i don't wanna send the message in any server's channel.. I want my bot to DM that user
member.send
a pain to watch
Did u read what myxi told u to do 2 times?
yeah I've done that but its not working...
Tf is this
@bot.event()
async def on_member_join():
await member.send(f"{member.mention} join the server!")```
hurts doesnt it
If you’re gonna spoon feed at least give the right code lmao
forgot the member param
It's wrong lmao
poor dude
damn this hurts
It freaking does
watching this poor kid trying to spoonfeed but cant
this code is not working with my bot
i have home service but the cost is a fee
ok
No duh
oh my god, I'm out
Jesus
this is painful
It’s disgraceful
sad
im gonna go and do my shit
right with you
@bot.event(member)
async def on_member_join():
await member.send(f"{member.mention} join the server!")```
Try this
Does anyone know a simple bot code with a level system?
Bruh
no comment
What the hell is that lmao 😂
hes tried to spoonfeed like 3 times and has failed
that one freecodecamp kid
What is this
Are you trying to shitpost right now? Or like actually trying to help by spoonfeeding?
why are u still trying??
how do I create a check, Who clicked on the reaction to check if he is the author who called the command.????
this is a pain
yall way too mean to him
its just sad bro
Do not know
you should help when you yourself know what shit you did
on_reaction_add() takes two arguments. user and reaction just compare user with the ctx.author
Does anyone know a simple bot code with a level system?
i know, but i can't add ctx.
Aren’t you doing this in a command?
did you write to me?
yes
a database and on_message event some 2nd grade math is all you need
Aren’t you doing this in or for a command?
for on_reaction_add ```py
async def on_reaction_add(reaction, user):
Just make the bot wait for a reaction
If thats what your trying to do
Who can help me with the welcome message command?
Tell me your intentions.
I need to create a check, Who clicked on the reaction, then check if he is the author who called the command itself if he is not the author, then return. . .
wait_for(event, *, check=None, timeout=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Waits for a WebSocket event to be dispatched.
This could be used to wait for a user to reply to a message, or to react to a message, or to edit a message in a self-contained way.
The `timeout` parameter is passed onto [`asyncio.wait_for()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.wait_for "(in Python v3.9)"). By default, it does not timeout. Note that this does propagate the [`asyncio.TimeoutError`](https://docs.python.org/3/library/asyncio-exceptions.html#asyncio.TimeoutError "(in Python v3.9)") for you in case of timeout and is provided for ease of use.
In case the event returns multiple arguments, a [`tuple`](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.9)") containing those arguments is returned instead. Please check the [documentation](https://discordpy.readthedocs.io/en/master/api.html#discord-api-events) for a list of events and their parameters.
This function returns the **first event that meets the requirements**...
Utilize this.
how do i create a voice channel with custom permissions ?
And do what I said earlier with comparing the command author and the reaction user
@bot.event
async def on_member_join(member):
with open('users.json', 'r') as f:
users = json.load(f)
await update_data(users, member)
with open('users.json', 'w') as f:
json.dump(users, f)
@bot.event
async def on_message(message):
if message.author.bot == False:
with open('users.json', 'r') as f:
users = json.load(f)
await update_data(users, message.author)
await add_experience(users, message.author, 5)
await level_up(users, message.author, message)
with open('users.json', 'w') as f:
json.dump(users, f)
await bot.process_commands(message)
async def update_data(users, user):
if not f'{user.id}' in users:
users[f'{user.id}'] = {}
users[f'{user.id}']['experience'] = 0
users[f'{user.id}']['level'] = 1
async def add_experience(users, user, exp):
users[f'{user.id}']['experience'] += exp
async def level_up(users, user, message):
with open('levels.json', 'r') as g:
levels = json.load(g)
experience = users[f'{user.id}']['experience']
lvl_start = users[f'{user.id}']['level']
lvl_end = int(experience ** (1 / 4))
if lvl_start < lvl_end:
await message.channel.send(f'{user.mention} has leveled up to level {lvl_end}')
users[f'{user.id}']['level'] = lvl_end
@bot.command()
async def level(ctx, member: discord.Member = None):
if not member:
id = ctx.message.author.id
with open('users.json', 'r') as f:
users = json.load(f)
lvl = users[str(id)]['level']
await ctx.send(f'You are at level {lvl}!')
else:
id = member.id
with open('users.json', 'r') as f:
users = json.load(f)
lvl = users[str(id)]['level']
await ctx.send(f'{member} is at level {lvl}!')
it's a level system and it don't works
so I have this code:
for member_role in member.roles:
print(member_role)
and it prints this
@everyone
R
@everyone
C
C
@everyone
R
Role Bot
but now if I do
for member_role in member.roles:
if member_role == "R":
print("Has Role")
it does not print Has role
help. I imported a json and os. and it's don't work
But which part doesn’t work?
What are you trying to do?
why would you think a role object would be equivalent to a string? use the name attribute to compare it to a string.
so member.roles.names?
i mean it printed the name when i did the for loop
@tawdry perch search for a role if a user has it, print osmething
no
member.roles returns a list, lists have no "names" attribute
How to create a check for on_reaction_add, If the user clicked on the reaction, then check whether he is the author.
so why cant i do == if its a list
and use a for loop to loop through the list..
who said you cant??
you did
where
.
name attribute
asss
it's all don't working. For example it doesn't writing in json file
your looping through a members roles which returns a list of discord.Role objects, discord.Role has a name attribute, use that to compare roles with a string
why are you using json as a database lol
json as db 😔
Do what kayle said and it will work
how often can you use os.chdir
I think reaction.message.author == user
does response count as on_message?
response by bot
If it's a message or smth sent, then yes
Uh don't know, never tried
I have it so bot sends this on click ```py
await interaction.send(content=message.content+" | Suggestion accepted by "+str(interaction.author), ephemeral=False, delete_after=30)
and then on_message ```py
if "accepted" in message.content:
which the message does, then it send a message to another channel
cuz apperently you cant send a message on button click to another channel
ah its working now
t
next problem here::
if message.content in "accepted":
for guild in client.guilds:
for channel in guild.channels:
if str(channel) == "💡┃suggestion-results":
embed = discord.Embed(title="Suggestion Accepted", description=message.content, color=0xFF000)
await channel.send(content=None, embed=embed)
break
only send "Suggestion Accepted", doesn't send the description, which is message.content
huh
why not fetch the channel?
idk
I just like doing it like that, but thats not the problem
the problem is that it doesn't send the description=message.content
I even tried debugging with
print(message.content)
and it doesn't print anything
Hello! Any advice for a discord.py orphan?
Try get first
Then fetch it
huh
Wrong reply
how can I make a timeout after any function or command is used?
cooldown?
!d discord.ext.commands.cooldown
@discord.ext.commands.cooldown(rate, per, type=discord.ext.commands.BucketType.default)```
A decorator that adds a cooldown to a [`Command`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command")
A cooldown allows a command to only be used a specific amount of times in a specific time frame. These cooldowns can be based either on a per-guild, per-channel, per-user, per-role or global basis. Denoted by the third argument of `type` which must be of enum type [`BucketType`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.BucketType "discord.ext.commands.BucketType").
If a cooldown is triggered, then [`CommandOnCooldown`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CommandOnCooldown "discord.ext.commands.CommandOnCooldown") is triggered in [`on_command_error()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.discord.ext.commands.on_command_error "discord.discord.ext.commands.on_command_error") and the local error handler.
A command can only have a single cooldown.
thanks
np
does it have an announcement when given role?
Do you mean event?
Yeah it dispatches on_member_update
but how can i do it on a specified role?
@commands.command()
async def botinfo(self, ctx):
developers = "Keref"
embed = discord.Embed(title="Botinfo")
embed.add_field(name="Server Count", value = f"{self.bot.guilds}")
await ctx.send(embed = embed)
len() it
alright
but how can i do it on a specified role?
When a specific role is given?
yes
Just make logical checks.
thanks lol i forgot about len
Check if the role you want to check for is in after.roles
ty
hey, how can i make it so if someone has a "Beta Tester" role in my bots support server it will print their name under the "Beta tester" field.
!d discord.Role.members
property members: List[Member]```
Returns all the members with this role.
huh i would need a example of that please
Grab the role object and use that attribute?
print(discord.utils.get(SomeGuildObj.roles, name="Beta Tester").members)
Something like that.
how can I set a cooldown after a button has been pressed?
like i want this in my embed so do i do
embed.add_field(name="Beta Testers", value = len(discord.utils.get(SomeGuildObj.roles, name="Beta Tester").members)
```?
I thought you wanted their names?
Yes
alright
and instead of discord.utils it would just be utils.get
do i have to change the "SomeGuildObj" to my guild id?
No it’s supposed to be the actual object of your guild that has that role.
oh
so if it's discord.utils
why would he import it from discord.ext
Oh shit. Didn’t notice that 

How can I make a cooldown for a user after he has clicked a certain button
it’s just
from discord import utils then
yes lmao
No……
im confused af
It just means "the exact same" some people will use verbatim instead of "word for word" sometimes
can anyone tell me how to get the channel name
utils.get(Guild.roles, name="Beta Tester").members)
use the .name attr
would this work?
It’s a thing for Voice, Text, Category, Threads, etc
can you tell me the full code
it says discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: 'property' object is not iterable
Dude please.
for example a member messaged hello in general channel. then who to store the channel name in a variable through our bot
get(mesg.channel)
Is there any way to set a cooldown on a button?
will this work ?
pep8 is crying 💀
It’s an example. to show where his actual guild object is supposed to be.
PEP8 doesn’t care that much.
Are you able to rephrase your question in like proper English. I understood like a nice 2 percent of it.
You got it yet?
i have a question
how can i remove the normal $help and make my own
like remove that
because if i try making a normal $help its broken
In your bot constructor do
help_command=None
its python
????????????
why does this not work?
member = client.get_user(826965853156147230)
await member.edit(nick="test")
I get the error AttributeError: 'User' object has no attribute 'edit'
AttributeError: 'User' object has no attribute 'edit'
Member does
client.get_member
That’s not a thing
oh wait
!d discord.Guild.get_member
get_member(user_id, /)```
Returns a member with the given ID.
right
yeah i got an error
yeah it doesn't 😦
What did I say that made it sound like i wasn’t talking about python?
well this syntax is obviously java smh
Right.
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: Expected discord.Colour, int, or Embed.Empty but received method instead.
Show code.
code:
@commands.command()
async def help(self, ctx):
embed = discord.Embed(title="NeoBot Premium Commands", color=discord.Color.blurple)
embed.add_field(name="Admin", value="`ban`")
embed.add_field(name="Misc", value="`botinfo`")
await ctx.send(embed = embed)
discord.Color.blurple()
You need to call it, as it's a method
what's blurple
does it have an if changed role-id is ?
oh alright thanks
Blue and purple
Danny being Danny
use hex code for the color
Nah it’s a discord thing
not necessary
true
i wonder why its a method lol - it returns a a static hex
if changed_role_id == '890329488000209384'``` wheres the problem?
before, after
Because it's a classmethod
Just creates a new discord.Colour with the value of that colour
but what is it then?
you made 4 errors in 2 lines 
i'm learning python
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
but what is it then?
which you just took
pls help
well you iterate through the roles of this person
and check if that id is any of those roles' id
@bot.event
async def on_message(message):
with open('users.json', 'r') as f:
users = json.load(f)
await update_data(users, message.author)
await add_experience(users, message.author, 5)
await level_up(users, message.author, message.channel)
with open('users.json', 'w') as f:
json.dump(users, f)
async def update_data(users, user):
if not user.id in users:
users[user.id] = {}
users[user.id]['experience'] = 0
users[user.id]['level'] = 1``` code
prob json
Exception ignored in: <function ClientSession.del at 0x000001BAA3878550>
Traceback (most recent call last):
File "C:\Users\astro\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\aiohttp\client.py", line 326, in del
if not self.closed:
File "C:\Users\milky\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\aiohttp\client.py", line 963, in closed
return self._connector is None or self._connector.closed
AttributeError: 'ClientSession' object has no attribute '_connector'
Traceback (most recent call last):
File "c:\Users\milky\code\practice bot\bott.py", line 52, in <module>
response = aiohttp.ClientSession("GET", jokeurl, headers=headers)
TypeError: init() takes 1 positional argument but 3 positional arguments (and 1 keyword-only argument) were given
what do i do
response = aiohttp.ClientSession("GET", jokeurl, headers=headers)
Because that’s not how you use aiohttp.
get is a method of ClientSession which you can pass in all your arguments and what not into.
!d aiohttp.ClientSession.get
coroutine async-with get(url, *, allow_redirects=True, **kwargs)```
Perform a `GET` request.
In order to modify inner `request` parameters, provide kwargs.
How to make the time display as in (de_DE)?
What module are you using?
yea
Ok
Or…?
yea
OK
Please tell me how to insert this into the code?
My date is displayed like this
And it should be like this:
i keep getting this error
Traceback (most recent call last):
File "c:\Users\srtpc\OneDrive\Desktop\run dis up\spider.py", line 7, in <module>
client = commands.Bot(command_prefix = '+')
AttributeError: module 'discord.ext.commands' has no attribute 'Bot'```
Show code
reinstall dpy
pip install -U discord.py
me?
mhm
done
u ran this?
Thanks
Hello can someone help me with my discord bot, i cant figure out how to add roles to a member when someone has a specific text in their custom status this is my code so far:
@bot.event
async def on_ready():
await bot.change_presence(status=discord.Status.dnd, activity=discord.Game(name='erci'))
for guild in bot.guilds:
for user in guild.members:
for activity in user.activities:
if isinstance(activity, discord.CustomActivity):
print(activity)
if activity == "ercy":
picperms = discord.utils.get(user.guild.roles, name="pic")
await user.add_roles(picperms)
it doesnt give me any errors
but it doesnt give me the role
either
Dont do anything on ready
Make a task
client.command*
alr ill try it
is there any way to shorten this code?
string = "hello world"
print(string[::-1][:5][::-1])
i fixed it but when i press run the bot dosent run
error?
!d string.split
so no one want help me with a sentence
!d str.split
str.split(sep=None, maxsplit=- 1)```
Return a list of the words in the string, using *sep* as the delimiter string. If *maxsplit* is given, at most *maxsplit* splits are done (thus, the list will have at most `maxsplit+1` elements). If *maxsplit* is not specified or `-1`, then there is no limit on the number of splits (all possible splits are made).
If *sep* is given, consecutive delimiters are not grouped together and are deemed to delimit empty strings (for example, `'1,,2'.split(',')` returns `['1', '', '2']`). The *sep* argument may consist of multiple characters (for example, `'1<>2<>3'.split('<>')` returns `['1', '2', '3']`). Splitting an empty string with a specified separator returns `['']`.
For example:
Get a vps
c:; cd 'c:\Users\milky\code'; & 'C:\Users\milky\AppData\Local\Microsoft\WindowsApps\python3.9.exe' 'c:\Users\milky.vscode\extensions\ms-python.python-2021.12.1559732655\pythonFiles\lib\python\debugpy\launcher' '63436' '--' 'c:\Users\milky\code\penis.py'
thats what pops up
everyone wants that lol
U didn't add bot.run properly
i dont have a command line for bot.run i just do the run button
edited lib
In the code
yeah i dont have a line that says bot.run
run(*args, **kwargs)```
A blocking call that abstracts away the event loop initialisation from you.
If you want more control over the event loop then this function should not be used. Use [`start()`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client.start "discord.Client.start") coroutine or [`connect()`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client.connect "discord.Client.connect") + [`login()`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client.login "discord.Client.login").
Roughly Equivalent to...
Put it at the end
No
client.run(YOUR_TOKEN) and replace YOUR_TOKEN with the token u get from Discord Dev Portal
how to mention role on embed message?
!d discord.Role.mention
property mention: str```
Returns a string that allows you to mention a role.
fetch the role place into variable, then do variable.mention
Just like u mention in a simple message
await create_text_channel(name, test, reason=None, category=None, position=1, topic='Hi', slowmode_delay=0, nsfw=false, overwrites=...)
is this correct
topic='hi'
Maybe not related to channel topic I guess
now?
anything that is None, you dont need within the parameters
and nsfw has to be False, not false
ye i didnt know if it had to be caps or not so just left it not
await create_text_channel(name, test, reason=None, category=None, position=1, topic='Hi', slowmode_delay=0, nsfw=False, overwrites=...)
nono, you can leave the None out of speechmarks since it is using bool
Bools always start with capital lol
and an error will occur since you havent defined overwrites
ye i dont understand that part
you can leave it out intirely
pls idc
U need a guild object
ctx.guild, message.guild, both return one
oh wait yes
No such thing
You should get a help channel for your doubt, this isn't the right channel for it
@south thicket Could you please ask questions in the right channels? Just because you are making a Discord bot does not mean everything that you do with it id Discord related. We help with modules that speak to the actual Discord API.
I've asked you this yesterday as well.
this is the right chaaaaaaaaannel
its about discord hosts
why all will eat me
Host can host anything not only discord bots
Discord host != discord bots or discord API
If you ask here, you will not get any help
Well your wrong.
Okay long story short, @south thicket look into Railway platform, u can host your bot there and it's free, now everyone take a chill pill
Or self host like a chad
Railway isn't really good for bot hosting
._.
hi 🙂
Its similar to heroku
Which free hosting even is lmao
👋
i have big bug in heroku
I tried it once
No free host is good tbh
so cant use it
i cant
Heroku isn't even Python related 
bec my problem
Just take a help channel
about pafy youtube lib
How hard even is it
and this server cant help you
Heroku isnt even ment for discord bots
Indeed
If you scrape YouTube then yes
Pafy uses ytdl
No we don't condone breaking ToS, different story.
Its against the rule of this server
this is correct up to the guild part yes?
@bot.command(name="test")
async def ping(ctx: commands.Context):
await create_text_channel(name, test, reason=None, category=None, position=1, topic='Hi', slowmode_delay=0, nsfw=False)
!ytdl
Per Python Discord's Rule 5, we are unable to assist with questions related to youtube-dl, pytube, or other YouTube video downloaders, as their usage violates YouTube's Terms of Service.
For reference, this usage is covered by the following clauses in YouTube's TOS, as of 2021-03-17:
The following restrictions apply to your use of the Service. You are not allowed to:
1. access, reproduce, download, distribute, transmit, broadcast, display, sell, license, alter, modify or otherwise use any part of the Service or any Content except: (a) as specifically permitted by the Service; (b) with prior written permission from YouTube and, if applicable, the respective rights holders; or (c) as permitted by applicable law;
3. access the Service using any automated means (such as robots, botnets or scrapers) except: (a) in the case of public search engines, in accordance with YouTube’s robots.txt file; (b) with YouTube’s prior written permission; or (c) as permitted by applicable law;
9. use the Service to view or listen to Content other than for personal, non-commercial use (for example, you may not publicly screen videos or stream music from the Service)
idc about someone if help me or not i can found the solution with my self
i just love speak with others
love programming
Then why ask?
like me
Bruh why this channel always gets offtopic
Were just following rules
Mostly ends getting muted
Yeah
Look okay but this topic is Discord bots and not Heroku, i don't get why we are still having this debate.
Shitpost lol
!ot
Off-topic channel: #ot2-never-nester’s-nightmare
Please read our off-topic etiquette before participating in conversations.
id need help about heroku lmao
Heroku sucks
You won't get any help here
Use replit
true
You said what
@maiden fable
replit cant let my project private
i know
No
replit not for hosting
Shares ip machines are slow
No
Then go to a channel that is meant for that. #ot0-psvm’s-eternal-disapproval, #ot1-perplexing-regexing , #ot2-never-nester’s-nightmare , #❓|how-to-get-help
You need the guild object
ye ik
ctx.guild returns the guild object
i was saying is it correct up to that point
@ moderators
Python is slow compared to other languages like js and c languages
await ctx.guild.create_text_channel(...)
Node js is the best
Ot lol
Plus if you don’t want your repl.it public make the max username length and make your username with cuss words, slurs, and etc
The hell?
@bot.command(name="test")
async def ping(ctx: commands.Context):
await ctx.guild.create_text_channel(name, test, reason=None, category=None, position=1, topic='Hi', slowmode_delay=0, nsfw=False)
?
Yeah
I feel like getting ignored 
Exactly lol
What me get banned
agreed
Sorry
But make an inappropriate username for your repl username
just go to an ot channel or to a private channel
Code?
no code
And what you tryna do?
question
.
🙃
You need to search for that yourself
Yes you can set role icons, in disnake (fork) afaik
lesgo
but there are other forks too that probably support that
You need to look that for yourself
disnake probably has everything then
!warn 852448735296356392 Do not bring up inappropriate topics on this server.
:incoming_envelope: :ok_hand: applied warning to @slate swan.
everyone including hunter says it's better than dpy
Well technically it does
was it hunter? idk
panda for sure
Hehe 
I want to do Comedy ping (delay) but I type on dc !ping then nothing happens can you help me or give me some advice
https://cdn.discordapp.com/attachments/921843915781464104/921847633490894928/unknown.png
🙂
Ok agree
is says name is not defined
:<
name isn't defined
test too
wait do i put it in ' ' ?
Ok...?
you need to pass the name of the channel, in the name arg
name="foo"
and it will work ?
Try it and see,
you forgot @
so it would be
@bot.command()
Robin already mentioned
Cool
after what you said it doesn't work, what should I do? :((
@bot.command(name="hi")
async def ping(ctx: commands.Context):
await ctx.send("hi all")
await ctx.send("hi all")
await ctx.send("hi all")
await ctx.send("hi all")
await ctx.send("hi all")
await ctx.send("hi all")
await ctx.send("hi all")
await ctx.send("hi all")
ok this is an example but if i was making my bot send separate messages like this ^
why does it send 4 and then wait and then another 4?
is there a way to make it do it constantly ?
No, being ratelimited means that discord limits the amount of requests you can make
You can maybe add a short delay between all the messages so it's consistent
is there a way i can make a command loop ?
Yea it's being ratelimited
You can use tasks
for a time
fter what you said it doesn't work, what should I do? :((
discord.ext.tasks.loop(*, seconds=0, minutes=0, hours=0, count=None, reconnect=True, loop=None)
this ?
Read how to contract such a task in the docs
where would i put it in the code
It's not just some lines of code you put in
It's a task
You need to know how to make one
That's why I linked the docs
That's how tasks look:
@tasks.loop(minutes = 1)
async def my_task() :
code...
Here is an example
Yeah was trying to find one but didn't find, an example is much better
import disnake
from disnake.ext import tasks
do i need this
I told you it was an example don't use this.
ye ik
How do I make my bot dm a user that they have been muted once they have?
Send the muted person a message.
!d discord.Member.send
