#discord-bots
1 messages · Page 564 of 1
@slate swan do u know ??
ah ok
i'll check docs in a second for you
tnxxx
!d discord.Member.guild_permissions
property guild_permissions: discord.permissions.Permissions```
Returns the member’s guild permissions.
This only takes into consideration the guild permissions and not most of the implied permissions or any of the channel permission overwrites. For 100% accurate permission calculation, please use [`abc.GuildChannel.permissions_for()`](https://discordpy.readthedocs.io/en/master/api.html#discord.abc.GuildChannel.permissions_for "discord.abc.GuildChannel.permissions_for").
This does take into consideration guild ownership and the administrator implication.
@slim whale ok so i found a way, if you do ctx.author.guild_permissions.adminstrator it will return true or false, if its true then just send Adminstrator as the text
if its false then ig dont?
perm_string = ', '.join([str(p[0]).replace("_", " ").title() for p in user.guild_permissions if p[1]])
embed.add_field(name="Guild permissions", value=f"{perm_string}", inline=False)```i found this code, how i can change it to make it send only the highest value?
wow that’s bad code
wyf
yeah
<Permissions value=8589934591> i did user.guild_permissions and the bot send this
why
going to check this
just do this
yes but i dont want only admin u know?
Whats with all the join string stuff
You can just cast permission to dict then use .keys()
didnt you want the highest perm tho?
didnt you say you wanted the highest permission?
ok, do user.top_role.mention, and then make a role info command, idk bro
yes but i want that the bot checks ur permissions and send the highest one u have
okey
bruh
xd
so random
how to fix pls
@commands.command(name="profile2")
async def _profile(self,ctx,member: discord.Member=None):
if not member:
member = ctx.author
pfp = member.avatar_url
membermention = ctx.author.mention
ages = ['15', '16']
memberroles = [role.name for role in member.guild.roles]
age = [i for i in ages if i in memberroles] # contains all "age" roles
if not age: # if they dont have any age roles
text = 'No role'
elif age[0] == '15':
text = '15 years underage'
elif age[0] == '16':
text = '16'
embed=discord.Embed(title=f"**Roleplay Finder**", description=f"**Discord User**: {membermention} | {member} ", color=0xffffff)
embed.set_thumbnail(url=(pfp))
embed.add_field(name="Verification", value="Verified", inline=True)
embed.add_field(name="Age", value=text, inline=True)
embed.add_field(name="Literacy", value="Semi-Lit", inline=True)
with open('blacklist.json', 'r') as file:
file = json.load(file)
if str(member.id) in file:
embed.add_field(name="__BLACKLISTED__", value="This user is blacklisted.", inline=False)
await ctx.send(embed=embed)
doesn't change the text in the embed no matter if i have no roles, the 15 role or the 16 role
it always just sends the first possible value e.g 15, then if i edit 15 to a random number like 99 it'll send 16, then if i edit both to random numbers it says
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: IndexError: list index out of range
Any way to make a shut down command?
return await getattr(self._user, x)(*args, **kwargs)
AttributeError: 'ClientUser' object has no attribute 'create_dm'```
@client.event
async def on_member_join(member):
global hasloo
haslo = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
haslo2 = 5
hasloo = "".join(random.sample(haslo,haslo2))
id_channel = int(828011225292079124)
await client.get_channel(id_channel).send(f"**{member.name}, użyj komendy** `!verify (kod)`\n**Twój kod weryfikacyjny to** \n`{hasloo}`")```
@bot.command()
async def badges(ctx, user: discord.Member = None):
if user.premium == True:
await ctx.send("si")
else:
await ctx.send("no")```i want to check if the user has nitro, it doesnt detect premium, im using this docs https://discordpy.readthedocs.io/en/latest/api.html?highlight=profile#discord.Profile
what does it return
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'NoneType' object has no attribute 'premium'
do i need any import or something?
@kindred epoch 🤷♂️
fetch the user, define it and then send me.mention
how?
!d discord.ext.commands.Bot.get_user
get_user(id, /)```
Returns a user with the given ID.
thanks
return await getattr(self._user, x)(*args, **kwargs)
AttributeError: 'ClientUser' object has no attribute 'create_dm'``````py
@client.event
async def on_member_join(member):
global hasloo
haslo = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
haslo2 = 5
hasloo = "".join(random.sample(haslo,haslo2))
id_channel = int(828011225292079124)
await client.get_channel(id_channel).send(f"**{member.name}, użyj komendy** `!verify (kod)`\n**Twój kod weryfikacyjny to** \n`{hasloo}`")```
yes
i need to ping myself?
no
whats , / ?
nothing, ignore that
ok
wait
Hello. I have an error there. But, this thing is working on my first bot but not on my second one... 🙂
from discord.utils import get
async def on_message(message):
server = bot.get_guild(885811553474072576)
category = get(server.categories, name = "DM") # get the support category```
```category = get(server.categories, name = "DM") # get the support category
AttributeError: 'NoneType' object has no attribute 'categories'```
really need help with detecting a users roles and placing it in an embed in #help-popcorn if possible
code i have doesn't seem to work
how to fix pls
@commands.command(name="profile2")
async def _profile(self,ctx,member: discord.Member=None):
if not member:
member = ctx.author
pfp = member.avatar_url
membermention = ctx.author.mention
ages = ['15', '16']
memberroles = [role.name for role in member.guild.roles]
age = [i for i in ages if i in memberroles] # contains all "age" roles
if not age: # if they dont have any age roles
text = 'No role'
elif age[0] == '15':
text = '15 years underage'
elif age[0] == '16':
text = '16'
embed=discord.Embed(title=f"**Roleplay Finder**", description=f"**Discord User**: {membermention} | {member} ", color=0xffffff)
embed.set_thumbnail(url=(pfp))
embed.add_field(name="Verification", value="Verified", inline=True)
embed.add_field(name="Age", value=text, inline=True)
embed.add_field(name="Literacy", value="Semi-Lit", inline=True)
with open('blacklist.json', 'r') as file:
file = json.load(file)
if str(member.id) in file:
embed.add_field(name="__BLACKLISTED__", value="This user is blacklisted.", inline=False)
await ctx.send(embed=embed)
doesn't change the text in the embed no matter if i have no roles, the 15 role or the 16 role
it always just sends the first possible value e.g 15, then if i edit 15 to a random number like 99 it'll send 16, then if i edit both to random numbers it says
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: IndexError: list index out of range
get_guild is returning None
double check the ID
I figured lol
Why doesn't it see him?
because you're defining emb1 when condition A is met, but only sending it when condition B is met, so it's catch-22
define emb1 after the else:
or before both conditions
seems they're only sending it in the else though ;P
thanks you so much
making an embed is not sending it
I agree!
server is none
ages = ['15','16']
memberroles = [role.name for role in member.guild.roles]
age = [i for i in ages if i in memberroles] # contains all "age" roles
if not age: # if they dont have any age roles
text = 'No role'
elif age[0] == '15':
text = '15 years underage'
elif age[0] == '16':
text = '16'
how do i make this so memberroles is checking the users assigned roles instead of roles that exist on the server
@client.event
async def on_message(message):
if client.user.mentioned_in(message):
embed = discord.Embed(description="command prefix: `,`\nfor help, use: `,help`\ninvite alone: `,invite`", color=color)
await message.channel.send(embed=embed)
else:
await client.process_commands(message)```
How could I make this not send the embed if @ here or @finite fableveryone is in the message
Check if the message.content is equal to the client.user.mention instead.
how could i do that lmfao
2 steps.
1 - use your brain to process what I said.
2 - use the same exact brain you used in step 1 to think of doing step 1.
class discord.FFmpegPCMAudio(source, *, executable='ffmpeg', pipe=False, stderr=None, before_options=None, options=None)```
An audio source from FFmpeg (or AVConv).
This launches a sub-process to a specific input file given.
Warning
You must have the ffmpeg or avconv executable in your path environment variable in order for this to work.
How to make a condition that if the author of the message is a bot, then do nothing
Bravo!
!d discord.Member.bot
property bot```
Equivalent to [`User.bot`](https://discordpy.readthedocs.io/en/master/api.html#discord.User.bot "discord.User.bot")
so?
What does message.author return? What object does it return?
author message
What?
he returns the author of the post
!d discord.Message.author
is there a way to make invites for all te servers the bot is in?
I just need a condition that if the author of the message is a bot, then do nothing
I have two separate cooldown messages so how do I make one cooldown message only for that specific command
Well message.author returns discord.Member object.
!d discord.Member.bot
property bot```
Equivalent to [`User.bot`](https://discordpy.readthedocs.io/en/master/api.html#discord.User.bot "discord.User.bot")
embed.set_thumbnail(self.bot.user.avatar.url)
TypeError: set_thumbnail() takes 1 positional argument but 2 were given
Ok so, this is in a cog and i checked in the debug, it is a string D_D
send code
set_thumbnail(*, url)```
Sets the thumbnail for the embed content.
This function returns the class instance to allow for fluent-style chaining.
Changed in version 1.4: Passing [`Empty`](https://discordpy.readthedocs.io/en/master/api.html#discord.Embed.Empty "discord.Embed.Empty") removes the thumbnail.
url = self.bot.user.avatar.url
yes
I do not understand how I can make this condition, sorry
it returns a bot object if the user is a bot
user.bot just returns true or false if the user is a bot account or not
name = "SEIF WESSAM"
name returns a str object. A str object has a method called lower(). So, if you do
print(name.lower())
It will print seif wessam.
Now you have here something similar. message.author returns discord.Member, and discord.Member has an attribute called bot. Now if you do
print(message.author.bot)
It will either print True or False depending on if the user is a bot or not.
That is, the condition should be like this?
No bro
Have you studied python before getting into discord.py?
message.author.bot returns a Bot object. In python every value that is equal to None returns false in an if statement, this is applied to class objects too
So if the author is a bot and you type if message.author.bot this statement returns true, else, if the author is not a bot, it returns false
!e
value = ""
print (True if value else False)
@placid skiff :white_check_mark: Your eval job has completed with return code 0.
False
I gotta agree not knowing the basics of python and jumping in to discord.py isnt the best thing
As you can see this returns false cuz value is an empty string, and empty strings are None object. In if condition None object return False
Please learn more python, at this point you've been explicitly told how it's supposed to work but you obviously lack the very basics of python
are you sure message.author.bot returns a bot object?
It doesn't return a Bot object
how would I get a bot to send a random with a keyword?
So someone uses a command to input a term and a gif is sent relating to it
I was referencing to this
Btw it is even easier lol
Use a gif api
yea, it still doesnt return a bot object
why would it
Although idk why you'd need it since there's already /giphy
Isn't discordpy being discontinued?
It is
That's sad
Yes
Still works tho
Somewhat, until discord does breaking changes or adds too many new stuff
Yep. You can use pycord i mean its basically the same thing-
There are maintained forks of discord.py, btw discord.py still works but it isn't updated
Especially using only slash commands for bots
Disnake is the best and most mature out of every fork out there, I recommend that one
so it will still work in the future? just no updates right?
Ehhhhh all of them are great but yes there are more forks.
Depends on discords updates
In the future? Definitely not, discord will do some breaking change and cause dpy to lose its functionality
It will still work for now, and then it will be out of date.
and it will stop working
I was just recommending the most mature one that's all
I'm using nextcord and dislash. I prefer the nextcord documentation, is a lot clear
With disnake i had a lot of throuble and i can't pass my days asking things in discord servers
hey guys
Wsp
¯\_(ツ)_/¯
im trying to add a leveling feature to my discord bot and i already did so but my role stuff is pretty trash
The docs are really easy to understand, so don't blame them, just saying
Its all personal preference
im thinking about deleting all the code for adding and removing level roles but i'd like some help so i can make it better
Im out im going to learn about dbs and disnake for the future later boys and girls have a good day or night
I don't blame anyone, i just can't find a sort of order in disnake xD
Ok any specific database you are using?
Order?
i was going to use sqlite but then i have a limit to how many roles a server could add
Actually yeah ig you may have some problems with finding stuff in the docs, that's why I always use my rtfm or docs command
well use sqlite just make the level roles harder to get?
json (ik it's bad) actually had the advantage of allowing ♾️ roles
this isn't a personal bot
Hmmmm, I would recrommend sqlite since its not personal
yeah but let me show you the issue i have
@commands.command(name="profile")
async def _profile(self,ctx,member: discord.Member=None):
if not member:
member = ctx.author
pfp = member.avatar_url
membermention = ctx.author.mention
userName = ""
userAge = ""
questions = [
"Please input your name/nickname:",
"Please input your age:"
]
dmChannel = await ctx.author.send(
"Yo will be receiving two questions. One involving your name and the other your age.")
def check(message):
return message.author == ctx.author and message.channel == dmChannel.channel
@client.event
async def askQuestion(question):
await ctx.author.send(question)
print("Waiting for reply...")
userReply = await client.wait_for('message', check=check)
print("User replied")
return userReply.content
userName = await askQuestion(questions[0])
userAge = await askQuestion(questions[1])
gives
Discord Version: 1.5.1
loading Bot, Please Wait
loaded cogs.Commands
loaded cogs.Currency
Ignoring exception in command profile:
Traceback (most recent call last):
File "C:\Users\coolb\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "C:\Users\coolb\OneDrive\Documents\mootbot\cogs\Commands.py", line 233, in _profile
@client.event
NameError: name 'client' is not defined
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\coolb\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\ext\commands\bot.py", line 903, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\coolb\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\ext\commands\core.py", line 859, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\coolb\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\ext\commands\core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: NameError: name 'client' is not defined
How did it limit you, never used sqlite but I'm pretty sure you can store a pretty long list inside a row
what am i doing wrong?
^^^^^ yep you can
erm thats a cog correct?
if its a cog , you cant yous @client.event.....
That looks like a complete mess
json be like
"xxxxxxxx(guild id)" {
"5": 901614930879455252,
"10": 901626195379109928,
"15": 100000000000000000,
"10000": 1000000000000000
}
}
yes
with sqlite
its copied code so idk lol
You can store a dict inside sqlite
you cant use @client.event, you have to use at @commands.Cog.listener i think
That's why you do not copy code you don't understand
he said that was json-
i could make a make a table that has 10000 columns but that isn't very practical
well then id have nothing if i didnt learn from copying and editing
dont ever copy code, you would never understand it unless you are proe 🆒
Wait bro what are you tryin to save in your database?
Go watch a tutorial on discord bots and then learn it.
You'd learn more if you'd do the code yourself
Leveling command
i always copy code then i learn what it means when i need to take bits and pieces from it and put it else were 🧠
I don't see how what you just sent is a "learning experience"
You clearly have 0 knowledge of python
In fact 😂
Because that's a python problem not dpy nor lib related problem
And your error doesn't even involve the database at all
@lunar helm Personally i like this tutorial for a leveling command with sqlite3 i recommend checking it out: https://www.youtube.com/watch?v=Bf2O-X4QQjU
My discord server ► https://discord.gg/BN6WaDs
(If you have any questions or just want to have a chat with us)
(Some Cool Stuff)
Nertivia ► https://nertivia.supertiger.tk/
My server in Nertivia ► https://nertivia.supertiger.tk/invites/B4tMwO
Install discord.py ► pip install discord.py or py -3 pip install discord.py
Discord.py documentation ►...
no tutorials for what i wanna do sadly
why not?
idk nobody has made one
as someone that can't stand school copy and pasting code is helpful but i recommend you dont copy and paste a full bot only copy and paste each little part of something that way you at least learn a little bit
Yeah there are, python tutorials, you need more python knowledge not more lib knowledge, if you'd have the pypi knowledge you wouldn't even need to copy paste code
check out this playlist https://www.youtube.com/watch?v=gPNQnrtcH-Y&list=PL34V7zCC1yuM3_r9TTG49Ez8Rm0znyIiI
My discord server ► https://discord.gg/BN6WaDs
(If you have any questions or just want to have a chat with us)
(Some Cool Stuff)
Nertivia ► https://nertivia.supertiger.tk/
My server in Nertivia ► https://nertivia.supertiger.tk/invites/B4tMwO
Install discord.py ► pip install discord.py or py -3 pip install discord.py
Discord.py documentation ►...
You have to know the basic of discord.py before creating a bot, you can't just code it without any knowledge
^^^^^^^^^^^^^^^^^^^^^^^
that playlist has got me to where im at but there is no tutorial for what i want to do now
Not of dpy, but of python
And you can't even copy others code
What do you want to do ?
Well that is like the essential xD
Without it you can't even start using packages
have a user respond to a question in dm then use their answer in an embed in a server
Tell that to people who copy paste code like the guy right now 😂
aka just capture their answer, i can do the rest
That is pretty easy but if you watch a lot of advanced tutorials
if you dont wanna watch someone else make a bot you will never use then learn how to make a bot that says hello when you say !hi
then look up how to do the other code and then put it inside the empty bot
i know how to make a bot jesus i just dont know this
Just use wait_for, no need for more
!d discord.ext.commands.Bot.wait_for
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**...
i forgor how to do a mod mail but yea you can use wait_for
You are tryin to find something that is already done for you
It doesn't work in this way.
Essentially your idea is very easy to do, but you don't have the knowledge necessary to do it
You have to learn, and you can't learn directly from what you want to do because is impossible to find tutorials that does specific thing
Tutorials meaning is to show you in general how something work, same goes for developing a bot
A tutorial can show you how you can make a bot that take parameters, then is your job to work with that parameters and do something with them
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: module 'discord.ext.commands' has no attribute 'wait_for'
?
nvm i got it working
i guess copy and pasting does work 😄
how could i get the total guild count a bot is in
@bot.command(name='membercount')
async def membercount(ctx):
await ctx.send(ctx.guild.member_count)
i said guild count
@client.command()
async def servers(ctx):
await ctx.send(f"{len(client.guilds)}")
AttributeError: 'Bot' object has no attribute 'guild'
How do I run 2 bots in the same file? (Ik I shouldn't, but I want to)
!d discord.PCMVolumeTransformer
class discord.PCMVolumeTransformer(original, volume=1.0)```
Transforms a previous [`AudioSource`](https://discordpy.readthedocs.io/en/master/api.html#discord.AudioSource "discord.AudioSource") to have volume controls.
This does not work on audio sources that have [`AudioSource.is_opus()`](https://discordpy.readthedocs.io/en/master/api.html#discord.AudioSource.is_opus "discord.AudioSource.is_opus") set to `True`.
how would i put a users message in a link inside an embed?
so other users can jump to that message?
await ctx.message.jump_url
!d discord.Message.jump_url
property jump_url: str```
Returns a URL that allows the client to jump to this message.
Is there a way I can make my bot react to messages like this for example?
those aren't reactions 🤔
those are buttons
Yes
uh its sending the most recent one when i picked another one
How do I make my bot click buttons?
discord_components
There's examples on their github
Oh
like for example, im trying to get it to jump from a message in a different channel and its showing the message i did the for the command
do you know what ctx is?
yea
then what do you expect
i have it ._.
@commands.command(aliases=['qu'])
async def quote(self, ctx, message_id:int):
msg = await ctx.channel.fetch_message(message_id)
embed = discord.Embed(
description=f"{ctx.message.jump_url} \n>>> {msg.content}"
)
embed.set_author(name=f"{ctx.message.author}", icon_url=ctx.author.avatar_url)
embed.set_footer(text=f"Message quoted by: {ctx.author}")
await ctx.send(embed=embed)
Replace ctx.message.jump_url with msg.jump_url
You clearly don't
no need to be rude about it
That was far from rude lmao
sometimes the truth can hurt.
i said discord.Message.jump_url, and you had the instance you needed, but you used ctx. That's on you.
idek
😂
client.users
!d discord.Guild.members guild.members where guild is an instance of discord.Guild. guild can be gotten by ctx.guild or bot.get_ or await bot.fetch_
property members: List[discord.member.Member]```
A list of members that belong to this guild.
oh in all guilds
!d discord.ext.commands.Bot.users
property users: List[discord.user.User]```
Returns a list of all the users the bot can see.
i know, i just need it in my status and i dont wanna do alot of work to get it
you can do filter(lambda m: not m.bot, bot.users)
i dont care about bots
Is this discord.partial_emoji?
that is a button.
No, it's a button, you've already been answered too
i've been getting fucking
AttributeError: 'Bot' object has no attribute 'guild' from {len(client.guild.members)}
its client.users
as we said
OH MY FUCKING GOD IM SO DUMB
agreed.
This
i can't even agree with you
The way you asked didn't point that out at all, but yeah, the emoji kwarg is what you're looking for
Ok
how come
variable_list = [ '903068179755069450','903068198935605318','903068209920495657']
channel = self.bot.get_channel({random.choice(variable_list)})
await channel.send(embed=embed)
doesn't work? it doesn't spit out any errors either. the goal is to have the message sent in 1 of 3 channels randomly chosen
You have a list of strings, get_channel takes an integer
And you have two stray brackets you don't need
as andy said, int the variable_list choice, and remove the {}
how do i int the variable_list
get_channel(int(random.choice(variable_list))), or you can just remov the ' from the indexes in the list.
thanks
if i have a funtion nested in a function how would i return on both of them
can you show code and expected output?
Hello, I have a function that gets the top 10 cryptocurrencies by market cap
import os
import json
from requests import Session
def get_top10():
CMC_API_KEY=os.environ.get('CMC')
parameters={
'start':1,
'limit':5000
}
headers={
'Accepts':'application/json',
'X-CMC_PRO_API_KEY':CMC_API_KEY
}
session=Session()
session.headers.update(headers)
url='https://pro-api.coinmarketcap.com/v1/cryptocurrency/map'
response=session.get(url,params=parameters)
json_file=json.loads(response.text)['data']
top10_rank_to_slug = {d['rank']: d['slug'] for d in json_file}
top_10 = sorted(top10_rank_to_slug.items())[:10]
for rank,name in top_10:
print(rank,name)```
but in order to pass it to my discord bot the function has to return a value not print it how can I do that (I want the bot to loop through the list then return the items one by one I dont want the bot to just return the list )
```python
@client.command()
@commands.check(check_channel)
async def top10(ctx):
await ctx.send(get_top10())
client.run(token)
how do you suggest I do that
yes
is there a fetch function in python like javascript and am I supposed to use nextcord to make a discord bot bc I heard discord py was discontinued
Requests is blocking use aiohttp instead
I am using disnake
Discord.py is still fine. You'll eventually have to make the switch but not now
ok what's disnake
what does the fetch function do in javascript
it returns a JSON as a string
https://api.github.com/ is a json and fetch() returns a string of it... then I can use JSON.parse() to convert it to an object and stuff
ok, you have any idea how to fix my problem?
I think I can do that with the json module in python
its a fork of discord.py
with buttons and slash and other things supported
guys its just another module
it doesnt really matter if your using nextcord, disnake or discord.py
can you help me with my question please?
that's why I want to use it... repl.it didn't update node so 😭
and I can't install npm
does it require the latest version of python or anything that repl.it doesn't have?
Same version as discord.py
Also let's keep this topic on python.
how do i use categories in the default help command
I keep trying to @ my alt acc but it only works for me can someone help
@commands.command(aliases=['ava'])
async def avatar(self, ctx, *, member: discord.Member = None):
if member is None:
member = ctx.author
embed = discord.Embed(
title=f"{member}'s Avatar",
color=0x000100,
timestamp=datetime.utcnow()
)
embed.set_image(url=member.avatar_url)
await ctx.send(embed=embed)
```
what
Are you putting in multiple mentions?
why do u need the self thing? https://andysimagehost.xyz/9Le8qp.png
No
i have an avatar command ill see what ur doing wrong
I’m just doing the command and @ my alt acc but it doesn’t work
You need to indent it right.
No...
At embed = discord.Embed(

Do you uderstand?
thats why it only works for u
Yeah
I also recommend using the or operator.
@commands.command(aliases=['ava'])
async def avatar(self, ctx, *, member: discord.Member = None):
if member is None:
member = ctx.author
embed = discord.Embed(
title=f"{member}'s Avatar",
color=0x000100,
timestamp=datetime.utcnow()
)
embed.set_image(url=member.avatar_url)
await ctx.send(embed=embed)
```that should fix it im pretty sure
if i removed the right ammount
Looks good to me.
if member is None:
member = ctx.author
``` is the same as ```py
member = member or ctx.author
How to check if a message was a DM??
!d discord.DMChannel , use isinstance to check message.channel
class discord.DMChannel```
Represents a Discord direct message channel.
x == y Checks if two channels are equal.
x != y Checks if two channels are not equal.
hash(x) Returns the channel’s hash.
str(x) Returns a string representation of the channel
if isinstance(ctx.channel, discord.channel.DMChannel):```??
yes sure
ty
i made a ban command but it can ban people higher then the executer, how could i make it so it cant
if ctx.author.guild_permissions.ban_members:```
yeah i have @commands.has_permissions but it bans even if the person who executes it is lower with ban_members
you need to set it to true as well
did you?
well yeah
what im saying is,
user is role below person he's trying to ban, it bans him
what I want:
if user is lower, it sends a message saying that they can't ban them
@client.command(aliases=['b'])
@commands.has_permissions(ban_members = True)
async def ban(ctx, member : discord.Member, *, reason = None):
if reason == None:
await member.ban(reason = reason)
await ctx.send(f"**{member}** has been banned :thumbsup: ")
else:
await member.ban(reason = reason)
await ctx.send(f"**{member}** has been banned for **{reason}** :thumbsup: ")```
there's that if u need that
!d discord.Role.position , compare the top role position
The position of the role. This number is usually positive. The bottom role has a position of 0.
Warning
Multiple roles can have the same position number. As a consequence of this, comparing via role position is prone to subtle bugs if checking for role hierarchy. The recommended and correct way to compare for roles in the hierarchy is using the comparison operators on the role objects themselves.
you can get top role of member by member.top_role
i have never used role.position, how would i check?
this and an operator
so isnt it possible to compare role hierarchy with numbers?
it is
someone help
!d discord.Member.top_role
property top_role: Role```
Returns the member’s highest role.
This is useful for figuring where a member stands in the role hierarchy chain.
!d discord.Role.position
The position of the role. This number is usually positive. The bottom role has a position of 0.
Warning
Multiple roles can have the same position number. As a consequence of this, comparing via role position is prone to subtle bugs if checking for role hierarchy. The recommended and correct way to compare for roles in the hierarchy is using the comparison operators on the role objects themselves.
i tried using this but i dont even know how to use it
Well you can compare the users' top role with the member he's trying to ban
like
if ... < ...:
return
the dots are the member objects

I dont think he understood
Is there anyway to use slash commands with nextcord?
I dont think they have it you can check their discord/github though
guys
what
a broblerm
what is ti
import discord
from discord.ext import commands
TOKEN = open('token.txt', 'r').read()
bot = commands.Bot(command_prefix="lk!")
class commandsbot():
@bot.command(name="hello")
async def embedm(ctx: commands.Context):
embed = discord.Embed(color=0x00ff00)
embed.title = "Hello!"
embed.description = f'{ctx.author.mention},Ok! Maybe Boy or girl!'
await ctx.send(embed=embed)
class botevents():
@bot.event
async def on_message(message):
if message.content == "hello":
await message.channel.send(f"Hey Man! Whats up?{message.author.mention}")
await message.author.create_dm()
await message.author.dm_channel.send(f'Hi {message.author.name}, Hope you are Fine!, Isnt? {message.author.mention}!')
@bot.event
async def on_ready():
print('Loki In Charge as @{0.user}'.format(bot))
bot.run(TOKEN)
this is code
eroor is
only hello is working
lk!hello isnt working
import discord
from discord.ext import commands
TOKEN = open('token.txt', 'r').read()
bot = commands.Bot(command_prefix="lk!")
class commandsbot():
@bot.command(name="hello")
async def embedm(ctx: commands.Context):
embed = discord.Embed(color=0x00ff00)
embed.title = "Hello!"
embed.description = f'{ctx.author.mention},Ok! Maybe Boy or girl!'
await ctx.send(embed=embed)
class botevents():
@bot.event
async def on_message(message):
if message.content == "hello":
await message.channel.send(f"Hey Man! Whats up?{message.author.mention}")
await message.author.create_dm()
await message.author.dm_channel.send(f'Hi {message.author.name}, Hope you are Fine!, Isnt? {message.author.mention}!')
@bot.event
async def on_ready():
print('Loki In Charge as @{0.user}'.format(bot))
bot.run(TOKEN)
!e
import discord
from discord.ext import commands
TOKEN = open('token.txt', 'r').read()
bot = commands.Bot(command_prefix="lk!")
class commandsbot():
@bot.command(name="hello")
async def embedm(ctx: commands.Context):
embed = discord.Embed(color=0x00ff00)
embed.title = "Hello!"
embed.description = f'{ctx.author.mention},Ok! Maybe Boy or girl!'
await ctx.send(embed=embed)
class botevents():
@bot.event
async def on_message(message):
if message.content == "hello":
await message.channel.send(f"Hey Man! Whats up?{message.author.mention}")
await message.author.create_dm()
await message.author.dm_channel.send(f'Hi {message.author.name}, Hope you are Fine!, Isnt? {message.author.mention}!')
@bot.event
async def on_ready():
print('Loki In Charge as @{0.user}'.format(bot))
bot.run(TOKEN)
@slate swan :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 1, in <module>
003 | ModuleNotFoundError: No module named 'discord'
Which helo
in commands
on_message(message):
if message.content == "hello":
this is one
this is onother
@boreal ravine got it?
oh boy !
Why are they in classes lol?
first no classes
They shouldn't be, unless you mean to make them cogs
Yea well, we can help with that
thanks bro
Get rid of your class's then you need to add this to your on_message. Actually read what Im linking to and youll see
btw my bot name is loki-laufeyson
ok?
await bot.process_commands(message)
ok
@valid perch
You meant like this?
@bot.event
async def on_message(message):
if message.content == "hello":
await message.channel.send(f"Hey Man! Whats up?{message.author.mention}")
await message.author.create_dm()
await message.author.dm_channel.send(f'Hi {message.author.name}, Hope you are Fine!, Isnt? {message.author.mention}!')
await bot.process_commands(message)
Outside of the if generally, but otherwise yea
Indent it out of your if statement
okthanks
just with pair to async def??
Otherwise it will execute commands only if the message is heloo
of pair with if?
No, same level as the if statement
ok
That's basically Python knowledge
ok
im a fool
and how do we make our bot to responds to dms?
check the type of the message channel using isinstance()
elif isinstance(message.channel, discord.channel.DMChannel) and message.author != bot.user:
like itthen
how to respongd to specific message?
@kayle
@boreal ravine
@boreal ravine last help that im gonna ask you please
@boreal ravine
@boreal ravine
Spamming will just make people mad and ignore you
ok
You won't get more attention by spamming
...??
it sends to random people
!d discord.on_member_update
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...
hm
Hey I was wondering if there’s a way to optimize an embed message edit, by modifying a single field.
Do I have no choices but to create a brand new embed despite using the same title and descriptions?
As far as I know you'd need to make a brand new embed object
Yeah, I thought so. So there’s no other way then?
this

how to respond to dms
You can grab the embed from the message and just modify that and send it back
Although this sounds like the smallest micro optimization thats likely un-needed. If you want speed, profile your code rather then making assumptions
for a specific message please?
pleaseeeeeeeeeeeeeeeeeeeeeeee
@slate swan help
im so concerned
Okii!
Thanks
with
!d discord.Embed.set_field_at
set_field_at(index, *, name, value, inline=True)```
Modifies a field to the embed object.
The index must point to a valid pre-existing field.
This function returns the class instance to allow for fluent-style chaining.
elif isinstance(message.channel, discord.channel.DMChannel) and message.author != bot.user:
how to respond to specific message?
@slate swan
this
how could we check if a user reacted with a particular emoji in a message?
wait_for a raw_reaction_add event
or an on_raw_reaction_add as a @bot.event
!d discord.ext.commands.Bot.wait_for
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**...
discord.Client.wait_for works the same
Whats status supposed to be
yeah.... if statement makes absolutely no sense lol
the if statement will always return true
Well
you're gonna get TypeError: argument of type 'CustomActivity' is not iterable
yeh then idk lol
does after refer to member?
well I rtd and before, after refers to the member object being BEFORE and AFTER they changed something
try activity.name and put that before checking if something is in it
wait @slate swan you're supposed to be using on_presence_update
!d discord.on_presence_update
discord.on_presence_update(before, after)```
Called when a [`Member`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member "discord.Member") updates their presence.
This is called when one or more of the following things change:
• status
• activity
This requires [`Intents.presences`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.presences "discord.Intents.presences") and [`Intents.members`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.members "discord.Intents.members") to be enabled...
if status in after.activity:
put activity before status and change after.activity to after.activity.name
Also maybe use the equality operator
https://www.w3schools.com/python/python_operators.asp please learn more python 🙂
!resources
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
if status in after.activity.name:```
Shouldn't start by making a Discord bot if you don't even know what an equality operator is
ok
Opposite, if item in list
So if ...name in status
TypeError: argument of type 'CustomActivity' is not iterable I suggested you use == to check if its a certain something
Thank you so much
What the
i want help
Because thats gonna help
Indeed spamming will make people help ya
please help!!!!!!!
What do you want help with?
Just tell the problem?
Heh, thats the funny part. No
how to make qa bot respond with dms
elif isinstance(message.channel, discord.channel.DMChannel) and message.author != bot.user:
done this then?
We can't help without knowing that what you need help with, no matter what
or any other
Ah nvm
if not message.guild:
# This message is in dms
# Do what you want
elif isinstance(message.channel, discord.channel.DMChannel) and message.author != bot.user:```
if not message.guild:
# This message is in dms
# Do what you want
Continue what, what do you want to do?
isinstance
Why isinstance?
okhang on
Why do you need it?
Am I supposed to answer this 🤔
classmethod red()```
A factory method that returns a [`Colour`](https://discordpy.readthedocs.io/en/master/api.html#discord.Colour "discord.Colour") with a value of `0xe74c3c`.
no
Help
@worthy wagon this
with
appreciate you
👍
so im trying to make a league football bot wanna see the codes i have so far?
sure
ok
import os
import discord
import asyncio
from datetime import datetime, timedelta
from discord.ext import commands
intents = discord.Intents.all()
#in the line below replace all of the prefixes with their emojis for each team (DONT REMOVE THE + PREFIX)
bot = commands.Bot(command_prefix=["+"], intents=intents, case_insensitive = True)
bottomimage = "https://media.discordapp.net/attachments/898576566299262987/902595014314557460/rainbow-border.gif"
bot.remove_command('help')
demands = 883837534919065604 #demands cannel
transactions = 883837534919065603
commandschannel = 883837534747103285
offers = 883837534919065602
clocktime = 1800 #Dont Change this
clocktimetwo = "30 minutes" #Dont Change this
maxroster = 12
```league = "YFA" #Their league name
threedemands = "3 Demands"
```twodemands = "2 Demands"
```onedemand = "1 Demand"
```blacklistrole = "No Demands"
```waitlist = "📙 Waitlist"
```suspendedrole = "⚠️ Suspended"
lol
well whats wrong?
is this a good code for the league bot
@client.event
async def on_reaction_add(self, reaction):
if str(reaction.emoji) == '😀':
await reaction.add("😀")
this isnt woring
only the 2.0 stuff (views, buttons)
i was trying to do if a person reacts with 😀 then bot also reacts with 😀
Whats reaction supposed to be on await reaction.add("😀")
to react to a message ig
why is there self
your function isn't in a class
!d discord.on_reaction_add takes 2 parameters
discord.on_reaction_add(reaction, user)```
Called when a message has a reaction added to it. Similar to [`on_message_edit()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_message_edit "discord.on_message_edit"), if the message is not found in the internal message cache, then this event will not be called. Consider using [`on_raw_reaction_add()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_raw_reaction_add "discord.on_raw_reaction_add") instead.
Note
To get the [`Message`](https://discordpy.readthedocs.io/en/master/api.html#discord.Message "discord.Message") being reacted, access it via [`Reaction.message`](https://discordpy.readthedocs.io/en/master/api.html#discord.Reaction.message "discord.Reaction.message").
This requires [`Intents.reactions`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.reactions "discord.Intents.reactions") to be enabled.
Note
This doesn’t require [`Intents.members`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.members "discord.Intents.members") within a guild context, but due to Discord not providing updated user information in a direct message it’s required for direct messages to receive this event. Consider using [`on_raw_reaction_add()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_raw_reaction_add "discord.on_raw_reaction_add") if you need this and do not otherwise want to enable the members intent.
Getting error client not defined using this
commands.when_mentioned_or("sbs!")(client, message)
Any suggestions
I am using cogs
wtf show full code
it says 'reaction' object has no attribute 'add'
async def get_prefix(client, message): ##first we define get_prefix
try:
pref = await fetch_prefix(message.guild.id)
print(pref)
return commands.when_mentioned_or(*prefixes)(client, message)
except:
return
commands.when_mentioned_or("sbs!")(client, message)
```@boreal ravine
because what you're trying to do isn't possible
If its in a class use self
What do you think await reaction.add("😀") does?
It is not In any class
you said it was in a cog though
it reacts to the message which the emoji was reacted first
do any of u guys know how to.. make an application bot for dms...(pythn)
Nope it doesn't work like that
Hey @slate swan!
It looks like you tried to attach a Python file - please use a code-pasting service such as https://paste.pythondiscord.com
Well you can use .message.add_reaction(":emoji:") to add a reaction to where it was reacted to
!d discord.Message.add_reaction
await add_reaction(emoji)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Add a reaction to the message.
The emoji may be a unicode emoji or a custom guild [`Emoji`](https://discordpy.readthedocs.io/en/master/api.html#discord.Emoji "discord.Emoji").
You must have the [`read_message_history`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.read_message_history "discord.Permissions.read_message_history") permission to use this. If nobody else has reacted to the message using this emoji, the [`add_reactions`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.add_reactions "discord.Permissions.add_reactions") permission is required.
Application bot?
@boreal ravine check full code
oh
hm
return await getattr(self._user, x)(*args, **kwargs)
AttributeError: 'ClientUser' object has no attribute 'create_dm'``````py
@client.event
async def on_member_join(member):
global hasloo
haslo = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
haslo2 = 5
hasloo = "".join(random.sample(haslo,haslo2))
id_channel = int(828011225292079124)
await client.get_channel(id_channel).send(f"**{member.name}, użyj komendy** `!verify (kod)`\n**Twój kod weryfikacyjny to** \n`{hasloo}`")```
NameError: name add_reaction is not defined
Well I don't know how you would define client outside a class without defining it using discord.Client/commands.Bot
use reaction.message before .add_reaction
k
do you understand though
What to do it works perfectly till now but now it stopped working any idea how to correct it
you saying "K" means you don't understand what to do from experience 🤷♂️
how did it work before?
so how does reaction.message helps with in that thing?
@slate swan wait your code isn't inside the function
Well to add a reaction to a message object you must first get the message (in this case it's reaction.message)
so its like fetching the message first to add reaction?
!d discord.Message.add_reaction
await add_reaction(emoji)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Add a reaction to the message.
The emoji may be a unicode emoji or a custom guild [`Emoji`](https://discordpy.readthedocs.io/en/master/api.html#discord.Emoji "discord.Emoji").
You must have the [`read_message_history`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.read_message_history "discord.Permissions.read_message_history") permission to use this. If nobody else has reacted to the message using this emoji, the [`add_reactions`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.add_reactions "discord.Permissions.add_reactions") permission is required.
sure
is this a mistake or not
Unclosed client session
client_session: <aiohttp.client.ClientSession object at 0x000001FB809E7A60>
understood now tysm
your calling a function/class so it returns that
my code
@commands.command(name= "мемчик")
async def meme(self, ctx):
des = random.choice(["Я пришёл разнести вас по личным причинам.", "Неправильный не я… Неправильный весь этот мир.", "Я просто подвигами маюсь.", "Выбор – это всегда только компромисс или эгоистичный ход в своих интересах. Только так.", "В конце концов, весь мир вращается вокруг меня!", "Терпеть не могу пороховой огонь, \n он понятия не имеет о хороших манерах.", "Если вам нечего делать, \n то не надо делать это здесь!", "Дураки любят высокие места.", "Сейчас мы покажем, на что способны… БЕЖИМ!!!", "Мы дойдем до самого конца! А потом еще куда-нибудь…", "Враньё – это путь к популярности."])
embed = discord.Embed(
title="Цитата:" ,
description=f"{des}",
colour = 0x694c5f
)
reddit = asyncpraw.Reddit(
client_id='client_id',
client_secret='client_secret',
user_agent='user_agent'
)
subreddit = await reddit.subreddit("animemes")
post_to_pick = random.randint(1, 100)
async for submission in subreddit.hot(limit=post_to_pick):
pass
embed.set_image(url=submission.url)
await ctx.reply(embed = embed)
hm
nope, its a warning
it is?
I have a question am I allowed to "hack" my own bot bc I used javascript to initially make it, but my node is old || and I can't update it for a lot of reasons || which means I can't use discord js v13 so I decided to login to my bot with python as well...
and disnake python has v13 features right?
hopefully?
Iterating over range(len(...)) is a common approach to accessing each item in an ordered collection.
for i in range(len(my_list)):
do_something(my_list[i])
The pythonic syntax is much simpler, and is guaranteed to produce elements in the same order:
for item in my_list:
do_something(item)
Python has other solutions for cases when the index itself might be needed. To get the element at the same index from two or more lists, use zip. To get both the index and the element at that index, use enumerate.
Remove ctx
!d discord.on_member_join only takes one parameter
discord.on_member_join(member)``````py
discord.on_member_remove(member)```
Called when a [`Member`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member "discord.Member") leaves or joins a [`Guild`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild "discord.Guild").
This requires [`Intents.members`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.members "discord.Intents.members") to be enabled.
Yes, it does have discord.js's v13 features
How would you check if a channel name already exist and if it doesnt exist the bot will create a channel with that name?
I made this bcz I thought this was how it was supposed to be made, but it doesnt work. It gives me an error and says get reference doesnt exist in channel = get(guild.text_channels, name='bot-chat'). I was sure that was a thing
@bot.command()
async def setup(ctx):
guild = ctx.guild
channel = get(guild.text_channels, name='bot-chat')
q_channel = get(guild.text_channels, name='quotes')
if channel is None:
await guild.create_text_channel('bot-chat')
channel = discord.utils.get(ctx.guild.channels, name="bot-chat")
channel_id = channel.id
print(channel_id)
else:
await ctx.send("there is already a channel in this server with the name 'bot-chat'")
if q_channel is None:
await guild.create_text_channel('quotes')
channel = discord.utils.get(ctx.guild.channels, name="quotes")
channel_id = channel.id
print(channel_id)
else:
await ctx.send("there is already a channel in this server with the name 'quotes'")
variable_list = [ 903068179755069450,903068198935605318,903068209920495657 ]
channel = self.bot.get_channel(random.choice(variable_list))
dmChannel = await ctx.author.send(
"Your request was sent in channel {channel}")
await channel.send(embed=embed)
how can i get {channel} to show as the chosen channel inside the text?
by making a slash command/view
!f-strigns
Creating a Python string with your variables using the + operator can be difficult to write and read. F-strings (format-strings) make it easy to insert values into a string. If you put an f in front of the first quote, you can then put Python expressions between curly braces in the string.
>>> snake = "pythons"
>>> number = 21
>>> f"There are {number * 2} {snake} on the plane."
"There are 42 pythons on the plane."
Note that even when you include an expression that isn't a string, like number * 2, Python will convert it to a string for you.
thanks
do you know how to integrate buttons though or could you lead me to the docs
I'm using disnake
well heres the examples page https://github.com/EQUENOS/disnake/tree/master/examples/views
https://disnake.readthedocs.io/en/latest/api.html#disnake.ui.View heres the documentation
thank you
Can somebody help me with this :
@bot.command()
async def help(ctx):
emb=discord.Embed(title="Help commands :PikaPika:", description="Mod commands : ")
emb.add_field(name=":text: Mute", value="[example](https://cdn.discordapp.com/attachments/893126341422104646/903204835531321345/2021-10-28_115132.png)")
bc when i click to the example it gives me this error on the site
https://cdn.discordapp.com/attachments/893126341422104646/903208186650177536/unknown.png
https://cdn.discordapp.com/attachments/903058192756518943/903207462000263168/unknown.png
pls someone
try making a new image
👍
How can I get the users who clicked the button?
inter.author
Breh
Not documented. Nvm
Hi i have this reaction that wont give the role to the user when they react to it
here is my code
Hello how to get all the perms from ctx.guild.me.guild_permissions?
I am expecting this output-
View Channels - True
Read Message History - True
Move Members - False
.....
you can do it manuallypy perms = ctx.guild.me.guild_permissions view_channels = perms.view_channels read_message_history = perms.read_message_history move_members = perms.move_memmbers or iter throughpy for k in perms: print(k)
How i can convert discord's message string into int?
Like messages return "1" but i want it to be 1
Ahem
if msg.content.is_digit():
#code here
I don't want it to check if it is int or not
Then?
The question is how can i convert "1" string to 1 int
int()
Alright
just print perms
Ummm ok
returns ```py
[('create_instant_invite', True), ('kick_members', True), ('ban_members', True), ('administrator', True), ('manage_channels', True), ('manage_guild', True), ('add_reactions', True), ('view_audit_log', True), ('priority_speaker', True), ('stream', True), ('read_messages', True), ('send_messages', True), ('send_tts_messages', True), ('manage_messages', True), ('embed_links', True), ('attach_files', True), ('read_message_history', True), ('mention_everyone', True), ('external_emojis', True), ('view_guild_insights', True), ('connect', True), ('speak', True), ('mute_members', True), ('deafen_members', True), ('move_members', True), ('use_voice_activation', True), ('change_nickname', True), ('manage_nicknames', True), ('manage_roles', True), ('manage_webhooks', True), ('manage_emojis', True), ('use_slash_commands', True), ('request_to_speak', True)]
that is [k for k in ctx.me.guild_permissions]
['DEFAULT_VALUE', 'VALID_FLAGS', '__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__slots__', '__str__', '__subclasshook__', '_from_value', '_has_flag', '_set_flag', 'add_reactions', 'administrator', 'advanced', 'all', 'all_channel', 'attach_files', 'ban_members', 'change_nickname', 'connect', 'create_instant_invite', 'deafen_members', 'embed_links', 'external_emojis', 'general', 'handle_overwrite', 'is_strict_subset', 'is_strict_superset', 'is_subset', 'is_superset', 'kick_members', 'manage_channels', 'manage_emojis', 'manage_guild', 'manage_messages', 'manage_nicknames', 'manage_permissions', 'manage_roles', 'manage_webhooks', 'membership', 'mention_everyone', 'move_members', 'mute_members', 'none', 'priority_speaker', 'read_message_history', 'read_messages', 'request_to_speak', 'send_messages', 'send_tts_messages', 'speak', 'stage', 'stage_moderator', 'stream', 'text', 'update', 'use_external_emojis', 'use_slash_commands', 'use_voice_activation', 'value', 'view_audit_log', 'view_channel', 'view_guild_insights', 'voice']
``` this is the output to `dir()`
This one!
basic python
!e
a = "5"
print(type(int(a)))
@boreal ravine :white_check_mark: Your eval job has completed with return code 0.
<class 'int'>
Lol
Already got the answer no need to answer again ig
I wasn't I was just scrolling up
@vale narwhal are you new to py?
Nah i just tired to search up on google and read 
Ok
What
I learn python by self learning 
Lol
how do you forget nvm
@vale narwhal me too
ahem
Self-learned
My grammar is cringe ignore it
@name.error
async def name_error(ctx, error):
if isinstance(error, ???)
#extra stuff
how i can handle this error?
ValueError: invalid literal for int() with base 10: 's'
for
@commands.listener
async def on_member_join(member):
```can I use```py
f"{member.id}"
```and
```py
f"{member.name}"
yes
ok cool
bot = commands.Bot(command_prefix="pls", intents=intents)
replace the pls with what you want it to be
bruh, then u cant use spae after pls
No..
i want use space
There is strip_after_prefix kwarg for that
pls
oh yes
no need for the space after pls
i didnt understand actually
which defaults to False
!d discord.ext.commands.Bot.strip_after_prefix
Whether to strip whitespace characters after encountering the command prefix. This allows for ! hello and !hello to both work if the command_prefix is set to !. Defaults to False.
New in version 1.7.
ty guys
yes you do, otherwise it won't work the way he wants it to
but when I use a regular prefix like "-" it works without putting a space after
why is pls any different
what
he wants it to be able to put a space after wtf
did you even read what they asked
oh wait yeah
🤦♂️
my bad
guys, how to turn on this functions
¯_(ツ)_/¯
i didnt understand actually
amogus
abobus
classic
rtd first
what function???
For my bot, I have it like this you can do the same and replace the "#" with "pls "
client = Bot(command_prefix="$", intents=discord.Intents.all(), strip_after_prefix=True)
how to get a users top role ?
good?
yes
thats right
thank you!
!d discord.Member.top_role
property top_role: Role```
Returns the member’s highest role.
This is useful for figuring where a member stands in the role hierarchy chain.
Maybe ctx.guild.top_role
thats the guild not member
Oh sorry lol
ok ty
👍
thts not wrking
show me what u did
wait 1sec
ok
👍
likes = likesc.get(str(ctx.author.id),0)
embed = discord.Embed(description=f" **Balance** : {wallet_amt} \n **Bank** : {bank_amt} \n **Level**: \n :mw_like: **Likes** : {likes}\n**Badges : **{badges} \n **Top Role**: {author.top_role}" ,color=0xFFDF00)
embed.set_author(name=f"{ctx.author.name}'s Profile")
#embed.set_thumbnail(url=ctx.author.avatar.url)
embed.set_footer(text=f'Requested By {ctx.author.name}')
await ctx.send(embed=embed)
ctx.author
ok
i want ask last question, how to make 2 prefixs, i mean like Dank Member too, it has 2 prefixs Pls and pls
lists ["!","?"]
prefixs = ["Pls", "pls"]
yes
?
yes
okey, ty bro!
👍
How to make the correct condition? What if the author of the message is a bot then do nothing?
make a helper funciton
In cogs for an event is it
@commands.listener()
```or```py
@commands.event()
```?
still not wrking bro
Right side is bot.user
@commands.Cog.listener iirc
ok thankyou
still not wrking bro
Without mesage
thanks you so much
?
how to get a users top role
if message.author.bot
!d discord.Member.top_role
property top_role: Role```
Returns the member’s highest role.
This is useful for figuring where a member stands in the role hierarchy chain.
!d discord.User.bot
Specifies if the user is a bot account.
there is no error shown
Can I see some code?
userdata = badgedta.get(str(ctx.author.id),[])
for i in userdata:
badges+= bademoji.get(i,'')+" "
wallet_amt = bank[str(ctx.author.id)]["wallet"]
bank_amt = bank[str(ctx.author.id)]["bank"]
likes = likesc.get(str(ctx.author.id),0)
embed = discord.Embed(description=f" **Balance** : {wallet_amt} \n **Bank** : {bank_amt} \n **Level**: \n :mw_like: **Likes** : {likes}\n**Badges : **{badges} \n **Top Role**: {ctx.author.top_role}" ,color=0xFFDF00)
embed.set_author(name=f"{ctx.author.name}'s Profile")
#embed.set_thumbnail(url=ctx.author.avatar.url)
embed.set_footer(text=f'Requested By {ctx.author.name}')
await ctx.send(embed=embed)
it should be shown in profile
thanks
And what does it show?
wait lemme get a pic
how to make pagination with buttons (not emoji) ??
tht should be shown below badges
Is a error handler try:?or something on that road
this right ?
Ah
yes it has yes it has
That's a try-except statement
!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.
it has
@bot.command()
async def badges(ctx, user: discord.Member = None):
if user.nitro == True:
await ctx.send("si")
else:
await ctx.send("no")```i want the bot to say if u have nitro
i sent wrong one
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Member' object has no attribute 'nitro'
You cant check if the user has nitro
Isnt except used to handle a error to
you can only check how long the user has nitro for
badges
There isn't one?
Shouldn't this work with bots too?
When I invite a bot nothing is being printed.
@commands.Cog.listener()
async def on_member_join(member):
print(f"{member.name} joined.")
No, thats if the code had an exception
so.. how to fix it ?
it's supposed to
since bots are member objects too
Then what is a error handler
yeah but nothing happens
I don't know then
!d discord.Profile
No documentation found for the requested symbol.
bro its litteraly what i send XD
Hmm, lemme see
@boreal ravine could it be something to do with my cogs
try it then
ig idk
does it work for members
Haven't tried yet
ik but it sends this error
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Member' object has no attribute 'nitro'```
I doubt it
do i need any import or something?
Thats weird the api still sends data about nitro tho
do you have member intents
whn i remove tht top role the cmnd works
Yeah
!d discord.Member.profile @slim whale
No documentation found for the requested symbol.
Wait lemme show
profile
See this
is decapretated
It's depreciated, also can be used only by non bot accounts
guys, how to make pagination with buttons (not emoji) ??
if u can help, i will say big Thanks
so how u can check if he has nitro for a user info? to check badges
Yups
!d discord.ui.View
class discord.ui.View(*, timeout=180.0)```
Represents a UI view.
This object must be inherited to create a UI within Discord.
New in version 2.0.
U gotta subclass that
why? so how people make userinfo with badges
Add buttons, increment/decrement buttons
!d discord.Member.public_flags
property public_flags```
Equivalent to [`User.public_flags`](https://discordpy.readthedocs.io/en/master/api.html#discord.User.public_flags "discord.User.public_flags")
^
thanks
Oh bruh
👍
Knew it already but now i know what the terms mean so thanks ig

wht is my bot working only in shash cmnds
till sm time back it was proper
are the prefix thing removed now itself
?
sure
does a return statement in a task restart the task after the cooldown?
hi guys, please tell me how to make an unban user
return will exit the task and wait for the next interval
!d discord.Member.unban
await unban(*, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Unbans this member. Equivalent to [`Guild.unban()`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild.unban "discord.Guild.unban").
ok thats perfect
!D discord.Member.ban
await ban(*, delete_message_days=1, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Bans this member. Equivalent to [`Guild.ban()`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild.ban "discord.Guild.ban").
Hallo kann mir jemand bei PyCharm CE helfen?
what
Oh sry
I speak english now
->> Hello can someone help me with PyCharm CE?
how can i make it so my bot sends a message telling a user that their message has too many characters instead of just going silent and putting this in console
In embed.fields.3.value: Must be 1024 or fewer in length.
What's the error btw
the bot does not start. i'm doing the same thing as the guy on youtube. it does not work. it constantly shows errors. I need help.
wait….
!traceback pls
Please provide the full traceback for your exception in order to help us identify your issue.
A full traceback could look like:
Traceback (most recent call last):
File "tiny", line 3, in
do_something()
File "tiny", line 2, in do_something
a = 6 / b
ZeroDivisionError: division by zero
The best way to read your traceback is bottom to top.
• Identify the exception raised (in this case ZeroDivisionError)
• Make note of the line number (in this case 2), and navigate there in your program.
• Try to understand why the error occurred (in this case because b is 0).
To read more about exceptions and errors, please refer to the PyDis Wiki or the official Python tutorial.
Show error
- Don't follow a guy on yt

Yes 😂 I have now also noticed that this is wrong
discord.py has 3.5* python requirement
like wht can it be ??
This section of the tutorial will show you how to create a new bot and add it to your server.
Follow this one
there is no error shown in console
Please provide the full traceback for your exception in order to help us identify your issue.
A full traceback could look like:
Traceback (most recent call last):
File "tiny", line 3, in
do_something()
File "tiny", line 2, in do_something
a = 6 / b
ZeroDivisionError: division by zero
The best way to read your traceback is bottom to top.
• Identify the exception raised (in this case ZeroDivisionError)
• Make note of the line number (in this case 2), and navigate there in your program.
• Try to understand why the error occurred (in this case because b is 0).
To read more about exceptions and errors, please refer to the PyDis Wiki or the official Python tutorial.
File "C:\Users\coolb\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\ext\commands\bot.py", line 903, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\coolb\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\ext\commands\core.py", line 859, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\coolb\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\ext\commands\core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In embed.fields.3.value: Must be 1024 or fewer in length.```
wht is my bot working only in shash cmnds
till sm time back it was proper
are the prefix thing removed now itself
anyone knows how to fix ?
can be xD
I‘m a german potato 😂
Hello guys and girls!i am new to a coding and to a python.I have a probly a noob questions.Wel here it go.I am trying to code a discord bot,basic bot with some commands like,if you type this command you get a link,daily joke and etc.My question is...do i need use some sort of database if i wish to store inputs from people,for example if a mod wana create new command via discord directly?
are u using Vs ??
or replit ?
Visual studio for now,since i have server at home so it would be self hosted bot
yes you need to use a database
if you are trying to say something with those images,i have no idea what are you trying to say
Catch the error in your error handler and send the error message
!d discord.HTTPException.text
The text of the error. Could be an empty string.
I have a command in a cog, let the command be <command_name>
When I use the default !help <command_name> on my bot, it first says No command <command_name> found then it successfully shows the command's documentation.
What do I do to prevent it from saying no command found?
yea that was message for a other guy but post got removed @boreal ravine,what database do you recommend mysql or mssql?i have experiance with mssql
