#discord-bots
1 messages · Page 69 of 1
shouldn't i like say something
and make a break somewhere
if it the letter is correct
inside else like if count == 10: break
Yes but u need to break out of the loop for current guess
i don't think so if guess is incorrect it can be passed
but then they have to say the command to guess AGAIN
which will start A new game
Breaking the loop will make the loop stop entirely
Did you mean to use continue instead of breaking out of the loop?
THATS WHAT I SAID
I know I was responding to endysis
ok
It doesn't really make much sense to break
do a check and if they have guessed all the words then break but if they guess the letter then continye
Yea that sounds right
I DK i never play da hangman b4
I thinking that if guess correct then stop
otherwise tell da user that they is wrong and do loop again
Is it possible to insert an image in discord modals?
Sure you could start the loop over again after breaking... But that isn't really efficient
continuing is the better option
No not start loop after breaking!!! I think u not understand me
Using break after a guess is correct will just lead to repetitive and redundant code
will this wotk
guessed = []
while guess != 0:
msg = await client.wait_for('message',check=check)
if msg.content in word:
if msg.content in guessed:
await ctx.channel.send("You've already guessed this.")
else:
index = word.find(msg.content)
guessed.append(msg.content)
await ctx.channel.send("Correct! Letter (s) was found in letter",index+1)
continue
``` not done
i forgot the else
@pliant gulch this work?
Ehhh I mean you have a syntax error
Other than that you have an issue with the code I would say
but he will die
what?
That would occur when the word being guessed has more than one apperance of the letter
For an example if the word was apple and my guess was p
I think you can see the issue there?
This is mostly due to the word.find finding the first occurrence
But also the fact you check if the letter was previously guessed. Making it impossible to progress in words that have the same letter appearing twice
Let me write you a quick example okay?
occurences
k
!e ```py
word = list("apple") # Construct a list, so ['a', 'p', ...]
guess = "p" # Pretend this is the user inputted letter.
if guess in word:
word.pop(word.index(guess)) # Remove the character from the list
if len(word) == 0: # Once all characters are removed that means the word has been guessed correctly
print("All letters guessed")
@pliant gulch :warning: Your 3.11 eval job has completed with return code 0.
[No output]
Does this make any sense?
It's a different method to check if the word is correct, but this fixes the issue with "double letters"
ohhh
Yep it's pretty simple
something like this?
while guess != 0:
msg = await client.wait_for('message',check=check)
if msg.content in wordlist:
wordlist.pop(wordlist.index(msg.content))
also wordlist is
wordlist = list(word)
msg.content
So the loop stops when the word has been guessed
oh
Then outside of the loop you can send a message saying they guessed the word right
Does that make any sense?
while len(wordlist) != 0:
msg = await client.wait_for('message',check=check)
if msg.content in wordlist:
await ctx.channel.send(embed=discord.Embed(
title="You guessed correctly!",
description=f"{msg.content} was found in the word!"
))
wordlist.pop(wordlist.index(msg.content))
continue
yes
Mhm perfect, now just add an else statement to tell the user they guessed wrong. Then outside of the loop make it send a message saying they guessed it right
After that, it should be finished and ready to be played
it just so happened that i managed to get the meaning of the word using an api. should i display that when they get it wrong
As long as the methodology is the same the game should be functional, you can add whatever extra flavour you want
wordlist = list(word)
while len(wordlist) != 0:
msg = await client.wait_for('message',check=check)
if msg.content in wordlist:
await ctx.channel.send(embed=discord.Embed(
title="You guessed correctly!",
description=f"{msg.content} was found in the word!"
))
wordlist.pop(wordlist.index(msg.content))
continue
else:
await ctx.channel.send(embed=discord.Embed(
title="You guessed wrong :(",
description=f"Hint: The meaning of the word is {meaning}"
))
continue
```
@pliant gulch will this work?
like final product
Looks fine to me, but if the else statement is the last portion of the loop you don't need continue, other than that it would be final in my eyes
ok
Granted you have some sort of response outside of the loop?
Like ```py
while len(wordlist) != 0:
...
await ctx.send(...)
ok done
wordlist = list(word)
while len(wordlist) != 0:
msg = await client.wait_for('message',check=check)
if msg.content in wordlist:
await ctx.channel.send(embed=discord.Embed(
title="You guessed correctly!",
description=f"{msg.content} was found in the word!"
))
wordlist.pop(wordlist.index(msg.content))
continue
else:
await ctx.channel.send(embed=discord.Embed(
title="You guessed wrong :(",
description=f"Hint: The meaning of the word is {meaning}"
))
await ctx.channel.send(embed=discord.Embed(
title="GG You won the game!",
description="please try again"
))
what is word supposed to be? 
The indentation looks a bit weird, other than that it looks fine
👏
well i ran into some problems
first of all the moment i type in the command it says "you guessed wrong"
secondly
actually wait nvm ik how to fix that
if the code is exatcly this is because len(worldlist) is equals to 0
well it would be split apart because i said
wordlist = list(word)
so the length of list will be same as length of word
it depends on what word is tbh, and no
You don't send any embed in that while loop, so when that embed is sent you're already out of that while
Can you show your check?
Maybe the bot's message with the embed triggered the guessed wrong?
Or any other message detected
Just make sure that you check for ctx.author == message.user
that will answer the bot too
Yea that's the issue I'm gonna assume
!d discord.User.bot
Specifies if the user is a bot account.
Okay so just do ```py
return m.channel == ctx.channel and not m.user.bot
This'll ignore all messages from the bot
m.author, m is a message
alr done
How to make bot respond only when somebody replies to him with a keyword?
@pliant gulch now the embed does not even show up
if (respond2 in message.content.lower().split(' ')):
if message.author.bot:
return
await message.reply("Не продается", mention_author=False
!d discord.Message.reference
The message that this message references. This is only applicable to messages of type MessageType.pins_add, crossposted messages created by a followed channel integration, or message replies.
New in version 1.5.
Okay, I would recommend sending the full command here. Otherwise I will be leaving soon so I'll let someone else help you now okay?
then you should not use discord.py yet 
@client.command()
async def hangman(ctx):
r = RandomWords()
word = r.get_random_word(hasDictionaryDef="true")
length = len(word)
data = dictionarysearch(word)
print(word)
meaning = data[0]["meanings"][0]["definitions"][0]["definition"]
under = "-"*length
mbed = discord.Embed(
title=f"Length of Word: {length} Reply to guess",
description=f"{under}"
)
await ctx.channel.send(embed=mbed)
def check(m):
return m.channel == ctx.channel and not m.user.bot
wordlist = list(word)
while len(wordlist) != 0:
msg = await client.wait_for('message',check=check)
if msg.content in wordlist:
await ctx.channel.send(embed=discord.Embed(
title="You guessed correctly!",
description=f"{msg.content} was found in the word!"
))
wordlist.pop(wordlist.index(msg.content))
continue
else:
await ctx.channel.send(embed=discord.Embed(
title="You guessed wrong :(",
description=f"Hint: The meaning of the word is {meaning}"
))
await ctx.channel.send(embed=discord.Embed(
title="GG You won the game!",
description="please try again"
))
you can't use any user package if you don't know how to read the docs
because, as i said before, in that while loop you don't send any embed
you just set a title and a description
I sent you what you need 
I can't do it for you
await ctx.channel.send(embed=discord.Embed(
title="You guessed correctly!",
description=f"{msg.content} was found in the word!"
))
i kinda did in a weird way
that is outside the while
ctx.send
bruh in that code the ctx.send and the while are on the same indentation level
that means the send is outside
now it is inside
Screw it, just gonna use the keyword
the incorrect and correct guess is whats inside
the intro and end are outside
yup
so whats the problem
if r1 is not None: do stuff ?
or just if r1:
and do stuff then
that has no logic in it, it says "if r1 is None then use it`"
do if r1 instead
I don't know. What do you want it to do if r1 is None?
No idea. I'd probably return. I don't clearly understand what are you making, except that it is reaction role.
why are you returning in if too?
I think so?
what's wrong with that?
your query returns none, that means that there is no row with such information you are checking for
What do you mean fix?
If that is not what you wanted then either your query is wrong or your database doesn't have expected row
You can check that by getting all rows from that table if it is not too big and check if there is a row you are looking for
If there is then check if data in it is similar with data you are giving to look for it and find where is the difference
And if there is not, then either add a row or edit an existing one
how can I make ```py
def check(m):
return m.content == 'yes' and m.channel == echannel
msg = await self.bot.wait_for('message', check=check)
await echannel.send("Confirmed")``` work only on reply, not on message
like this
In the check function add checking if the message is replying to your message by message.reference and message.reference.message_id == your_message_id, and by the way if you do that you won't need a channel check
@silk fulcrum yo 👋
Master meets another Master 🙏
But two Hunters can never met
Yes! Because if two Hunters meet, others will only see one in a few min 😄
hmm
meet*
Hi, Can anyone help me choose the right discord package with python
I've always used discord.py for my discord bot development
but now, when I discovered new things I can do with discord
like
- Slash Commands
- Buttons
- Lists
I noticed that it is not available with the normal discord.py package
I learned about 2 other packages called PyCord Dinsnake
I want something that could be reliable in the log-run ... which one should I use ?
you can use discord.py 2.01, but if you want to change package disnake is more suggested
how do u ppl do ur research how come u don't know 6-8 months old news 
stop degrading people's knowledge for your own benefit, it's not healthy for the person asking for help, and yourself
its available on pypi so u can just do pip install discord.py
sure as u say
I know that discord.py has been discontinued then re-continued ((:
I heard that discord.py 2.0 is in the making but I didn't know it's available for use (:
but if u feel like not keeping up with current affairs with related to what u are doing is not important then i have nothing to say
what if that person was away, in hospital, on vacation?
np 👌 u can use discord.py or disnake hikari nextcord pycord all if these support interactions views slash commands etc
he asked a simple valid question, we give an answer, we don't go into why he did not known that
sure if the vacation was on mars or on a deserted island
you're not him
are u?
mars is a one way trip, he would not get back
you would know this if you were sMarT oN asTonOmy
I'll just pass the needless argument just saying its good to do a bit of research before jumping head on
the question only took 2 seconds to answer, you just say 2.0.1
that's it, no need to go full sherlock homes on his ass as to why he did not know that
what would go into "your_message_id" ?
?
nvm 
Hi there Ashley
huh? absolutely not
Tvrsier 
What is better to use to create buttons and select menus?
dunno the issue
yes ok lemme explain
refer to the message or explain
def check(m):
if message.reference and message.reference.message_id == message.id:
return m.content == 'yes' and m.channel == echannel
msg = await self.bot.wait_for('message', check=check)
await echannel.send("Confirmed")```
I want to check if the message replies to the bot
the library you use
I mean that should be working actm
u sure?
i think you want to get reference fromm not message
yes that
def check(m):
if m.reference and m.reference.message_id == m.id:
return m.content == 'yes' and m.channel == echannel
msg = await self.bot.wait_for('message', check=check)
await echannel.send("Confirmed")``` still doesn't work
def check(m):
if m.reference and m.reference.message_id == message.id:
return m.content == 'yes' and m.channel == echannel
msg = await self.bot.wait_for('message', check=check)
await echannel.send("Confirmed")``` so like this?
doesn't work @paper sluice
any errors?
where have you define message?
@commands.Cog.listener()
async def on_message(self, message):
list = []
channel = self.bot.get_channel(1003147215080013876)
if message.channel == channel:
if message.content in list:
echannel = self.bot.get_channel(1006625124046340147)
await echannel.send(f"``{message.author}`` wants to be promoted to ``{message.content}``")
def check(m):
if message.reference and m.reference.message_id == message.id:
return m.content == 'yes' and m.channel == echannel
msg = await self.bot.wait_for('message', check=check)
await echannel.send("Confirmed")```
your list is empty....
I cleared it
just tell me what's the problem bro
hey
if message.content in list:```
this
that condition is never true because your list is empty
astuffirlaah don't worry bout it

He is saying that he removed the list as he have something personal ig just like people remove tokens and send their code in here for help
Wassup
gud, wby?
Me too 😊
Have you done some debugging by adding prints/else statements to ensure the if statements are executing correctly?
don't worry I done it
ah lol
How can i link a github file with my bot? and what type of file does it need to be?
hello
What do you mean by "link a github file with my bot"?
Hello
like i have all my commands inside the github file and i just link it with my bot but i got no clue how to do that
how can I host my bot 24/7
there is no such thing called "github file"
well then a python file inside of a github repository
or does it need to be another file type?
thanks
filetype doesn't matter, its what you do inside the file.
you can make bots in js, c++ or any other language which can interact with an API
Why did you ask the same question in #965291480992321536, with the time you spent to do so, it doesn't seem you've read the message I sent you.
k but how do i like link the file in my discord bot so i can run the commands that are inside of the file
You can't use it without importing somehow, you either clone it to your PC somewhere or make a request to github an eval that code, but that is very bad.
you need to have that file available locally, you can import it or whatever else you want to do with it
why can't you just have that file in your directory?
ctx.author.id is possible
i run it on a raspi and it would be easier to do it remotely
AttributeError: 'Interaction' object has no attribute 'author'
The above exception was the direct cause of the following exception:
nextcord.errors.ApplicationInvokeError: Command raised an exception: AttributeError: 'Interaction' object has no attribute 'author'```
i make it with buttoms
"not work" is not a valid description of your problem, provide an exception if you get it or else say what you expected to happen and what happened instead
i know
use .user not author
If you are using Interaciton, it is interaction.user.id, you'd better name Interaction an interaction, that has more logic
The above exception was the direct cause of the following exception:
nextcord.errors.ApplicationInvokeError: Command raised an exception: NotFound: 404 Not Found (error code: 10062): Unknown interaction```
Ok but the command
command can't use Interaciton only ctx
Looks like you are trying to respond to an interaction twice
yes
4 times
hmm, you must have some sort of interface to add new files or something. I'm not sure if you can do it remotely.
That is not possible
await interaction.send("?")
await interaction.send(interaction.id)
await interaction.send(player)```
You can only respond to an interaction once
await interaction.response.send_message('Sub Please i hope This World', ephemeral=False)
await interaction.send("?")
await interaction.send(interaction.id)
await interaction.send(player)```
it working well
you might use a followup
it working
No it is not. You get an error because of it
!d nextcord.Interaction.send
await send(content=None, *, embed=..., embeds=..., file=..., files=..., view=..., tts=False, ephemeral=False, delete_after=None, allowed_mentions=...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
This is a shorthand function for helping in sending messages in response to an interaction. If the interaction has not been responded to, [`InteractionResponse.send_message()`](https://nextcord.readthedocs.io/en/latest/api.html#nextcord.InteractionResponse.send_message "nextcord.InteractionResponse.send_message") is used. If the response [`is_done()`](https://nextcord.readthedocs.io/en/latest/api.html#nextcord.InteractionResponse.is_done "nextcord.InteractionResponse.is_done") then the message is sent via [`Interaction.followup`](https://nextcord.readthedocs.io/en/latest/api.html#nextcord.Interaction.followup "nextcord.Interaction.followup") using [`Webhook.send`](https://nextcord.readthedocs.io/en/latest/api.html#nextcord.Webhook.send "nextcord.Webhook.send") instead.
That took a time
yes
That was for me, I am checking if .send exists and how it works
oh
I am not sure if you can respond 4 times even with followups, I only used followup for second response.
Hm, okay
any ideas
LOL WORK NVM
i just fix small thing
wait
why the frist one have other id???
What are you sending?
@silk fulcrum this should do what id message id or user await interaction.send(interaction.id, ephemeral=True)
This will return an ID of the interaction
I don't think you need it
anyone ogt a fix
A so how get player id
that clicked the buttom
interaction.user.id? I think you've just been told about that.
Keep the thumbnail in string
Looks weird, are you using a custom context? @slate rapids
F string, f'{ctx.author.avatar.url}'
Ok Thank You
You're welcome
If you are not using a custom context, and it doesn't look like you do, then try using .display_avatar.url instead of .avatar.url
.url method returns an str, why would you need that
Shouldn't it be in a string tho?
What do you mean?
Ok.
Seems like you are using discord.py 1.7.3
my code works on replit
how to get newer
pip install --upgrade discord.py
works ty
Does anyone know a free easy-to-use online database for python?
I don't know a non-free database, but the most beginner-friendly is sqlite
!pip aiosqlite
Is this online?
I don't want to host it my self
What do you mean?
I want to make changes using apis
python provides a free database called sqlite, you will just need a .db file and then connect to it
.
what? that is weird
aiosqlite is just the sqlite versione compatible with asyncio
Okay
I'm trying to make a chat app, But I need a database to store the chats
And I don't wanna host anything myself
Sorry but when iclick buttom it work but when i click again it send nextcord.errors.ApplicationInvokeError: Command raised an exception: NotFound: 404 Not Found (error code: 10062): Unknown interaction i need reload all bot for it work again @silk fulcrum
I want a website that is already hosted or smth like that
I think this is a channel with quite different topic
urgh
I need more details, at least provide a full traceback.
https://www.npoint.io/ I want something like this, The problem with this one, It's not editable using python...
Ignoring exception in command <nextcord.application_command.SlashApplicationCommand object at 0x0000017CCFFBE710>:
Traceback (most recent call last):
File "C:\Users\Ibrah\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\application_command.py", line 848, in invoke_callback_with_hooks
await self(interaction, *args, **kwargs)
File "c:\Users\Ibrah\Desktop\Discord Bot\Test.py", line 39, in sub
await ctx.send(f'Does This Worked!', view=view)
File "C:\Users\Ibrah\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\interactions.py", line 564, in send
return await self.response.send_message(
File "C:\Users\Ibrah\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\interactions.py", line 893, in send_message
await adapter.create_interaction_response(
File "C:\Users\Ibrah\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\webhook\async_.py", line 204, in request
raise NotFound(response, data)
nextcord.errors.NotFound: 404 Not Found (error code: 10062): Unknown interaction
The above exception was the direct cause of the following exception:
nextcord.errors.ApplicationInvokeError: Command raised an exception: NotFound: 404 Not Found (error code: 10062): Unknown interaction```
show code please
@nextcord.ui.button(label= 'Sub', style=nextcord.ButtonStyle.green, disabled= False)
async def sub(self, buttom: nextcord.ui.Button, interaction: nextcord.Interaction):
await interaction.response.send_message('Sub Please i hope This World')
await interaction.send("?")
if player == interaction.user.id:
await interaction.send("if You See this You good guy :)")
await interaction.send("*I think so*")```
I don't see "Does This Worked!" in this code
Dude it work D: why you don't trust me D:
I absolutely trust you that it works somewhere. But I see await ctx.send("Does This Worked!") in the error, but I don't see that in your code
Oh

async def sub(ctx):
global player
player = ctx.user.id
view = Sub()
await ctx.send(f'Does This Worked!', view=view)
await view.wait()
if view.value is None:
return
i will remove it
wait what is this py Task was destroyed but it is pending! task: <Task pending name='nextcord: on_interaction' coro=<Client._run_event() done, defined at C:\Users\Ibrah\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\client.py:491> wait_for=<Future pending cb=[Task.task_wakeup()]>> Task was destroyed but it is pending! task: <Task pending name='nextcord: on_interaction' coro=<Client._run_event() done, defined at C:\Users\Ibrah\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\client.py:491> wait_for=<Future pending cb=[Task.task_wakeup()]>>
@silk fulcrum
What did you do before it appeared?
remove await view.wait() if view.value is None: return
what's the best cheapest way to host a discord bot
bannaa host
Leave your pc on
banna host i use it and good and online 24/7
a
I mean it doesn't get cheaper.
ty
free hostes are cringe
Always limitations.
IT NOT
Can you help me D:
With what?
nvm]
Show code bruh
What a highlight 💀, how will you see the name of the function
and can you send your code not by a screenshot
i use notepad++ rn bcs pycharm keeps crashing and the name is "fact"
Yo, do you see any error in it? Idk whether I am blind or what 💀
Try vsc, anyways send code, not ss
something wrong with indentation
Ik that
replaced {} with ()
that is why I am asking for code as a raw text
@client.command()
@commands.cooldown(rate=1, per=5)
async def fact(ctx):
print('Random fact was used')
rndf = randfacts.get_fact()
embed = discord.Embed(title=f'(rndf)',
color=discord.Color.blue())
await ctx.send(embed=embed)```
those are ()
You are mixing tabs and spaces 
title=rndf
that's my point
oh that's what that error means
Oh in title
or just don't use f-strings for one string
I like to make my string represent france.
common France L
fr"Hello World!"
this worked
and the command also worked with the {} thanks for the help
👍
YOOO CAT
!ot
Off-topic channel: #ot2-never-nester’s-nightmare
Please read our off-topic etiquette before participating in conversations.
#ot3-discord-bots smh
Aren't they all discord ot channels..?
Um, acutally, they are
cats > pandas
Nah animals >>>>> humans
nah, lemon >>>> human
No.
tf is ur theme ???
material ig
Do u mind translating what that says?
@app_commands.command(name="help", description="Get my slash commands!")
async def help(self, interaction: Interaction) -> None:
await interaction.response.defer(ephemeral=True, thinking=True)
if self.tree.get_commands() is None:
return await interaction.edit_original_response(content="No Slash Commands yet!")
slash_help = SlashHelp(self)
await interaction.response.send_message(embed=slash_help.buttons.embeds[0], view=slash_help)
why doesn't this work 
Congrats on overwriting the built-in help command! Hope you enjoy your experience
nice
And what isn't working? Explain
I mean, u r using a slash command to check if there are any slash commands.......?
double response with the defer and send_message
And yea, that should be interaction.followup or smth
still the command wont get triggered, im high
Is the command not showing or what
So it doesn't show that ephemeral message?
Can u try syncing the command once?
but it is in the internal app command list, and yes I did that too
So discord shows interaction failed?
yep
Try changing the name/description of the command then sync the command. Check if they were synced correctly
So its syncing correctly but not triggering the callback? What in the fuck
That's weird
I want to mention the unbanned user. How can I do that?
Are you sure you are on 2.0.1?
welp thanks hunter
You were still on 2.0.0?
im stuck with 1.7.3
You have to do f"<@{user.id}>"
lemme see 💀 I literally uninstalled the github version to remain consistent with pypi
when did they
release a new update
Tho I don't think it has anything related to yr issue, tho no harm in trying
Update then?
nvm, doesn't work
Do u have an error handler? Slash error handler
Ahh, right. Clever. Lol. Thanks!
nop
so the command name is printed when u print the internal slash command list?
yep
currently my code will face many issues with the new update and I'm too lazy to edit what it's required to And I see no reason to update since all my needs work fine for the very moment
Cool, ig
Try reporting this in the discord.py server
Seems like a bleeding edge case
mhm I'll try asking then, thanks
Only those people will be able to see the proper mention, who are either friends with that person or have a mutual server with them. Others will just see @tribal templeuser
Like this: @dusky fox
Nvm discord changed ping formats, but u get the idea
ahh. right. That happens.
But this is what they will see
Thx again for the help 
All cool
Im coding a bot in vsc and I keep getting the error TypeError: expected token to be a str, received <class 'NoneType'> instead which is very confusing because the way I set it up should work just fine
Well either yr env file has no variable named TOKEN or u don't have an env file in yr cwd
i think you must specify the token as an str
Nah
oh wait
env files are another way to hide yr token
i got it wrong
Hm
Try printing os.getcwd() and check if the env file resides in the same folder as it prints
from os import environ
from dotenv import load_dotenv
load_dotenv()
token = environ["TOKEN"]
load_dotenv doesn't need the path but doing so does increase performance by a small margin.
yeah it does
KeyError: 'TOKEN'```
this is what I got
@frail gyro
Hello I'm here
how to use the / with discord.py 2.0.1 ?
!d discord.app_commands.AppCommand
class discord.app_commands.AppCommand```
Represents an application command.
In common parlance this is referred to as a “Slash Command” or a “Context Menu Command”.
New in version 2.0...
!d discord.app_commands.command
@discord.app_commands.command(*, name=..., description=..., nsfw=False, auto_locale_strings=True, extras=...)```
Creates an application command from a regular function.


I can't do it
What do you mean?
I can't integrate the slash commands in my code
Why?
Because I can't figure out what code to use to set the slash command
Isn't it clearly explained what to do in the gist I sent?
I have trouble understanding

Understanding what?
Don't cry Ashley, your gist is perfect, people just have troubles understanding 🫂
can't say perfect either but okay
It’s still up for review on GitHub isn’t it?
idk lmao
maybe it need a little rework (I mean add some better markdown)
I'm not free to make it look good
Can i make a pull request to a gist?
that ain't possible
😩
pull requests are limited only to repos
I would have helped you
nop, only forks
leave a comment with your fork's reference, I'll check it out
oke, it will take me a while

Hi! every few weeks i get a message like this, my bot is used very rarely and i only test it every few months as i dont use it very much, i first thought it was because it was being used too much (why i kicked it from most servers to see if it would fix the issue) however its still not fixed, can anyone help with this?
thats replit for you
other discord bots are running on the same datacenter which makes it easier to hit a 429 Too Many Requests
oh! well, i guess thats a good and bad thing for me haha, thank you very much! time to look for a different server or smth
See the pins in #965291480992321536 for some resources
do kill 1 in the shell
This is a temporary solution
I know
I wouldn’t rely on it
I know
hi, sorry for bothering, i'm losing my mind. is this correct?
async def load_cogs():
for filename in os.listdir('./cogs'):
if filename.endswith('.py'):
await bot.load_extension(f"cogs.{filename[:-3]}")
Run it and see
thank you! ill use it for now until i have time to research :D
The python interpreter is better and faster than any human one
i'm receiving ```Exception has occurred: TypeError
object list can't be used in 'await' expression
can someone help me?.how can i make the code so when i thank someone the point will go to him
send a full traceback
Guys what this mean
Hi can anyone help me I'm making a level system and I have this formula to calculate how much xp it takes to go up 1 level "5 * (get_user_level ^ 2) + (50 * get_user_level) + 100 - xp_from_user" but I know Not how I should do it, that you then really go up a level, so how the bot should recognize that, can anyone tell me what I should do there or how I should do it without having to do thousands of if statements or is there no other way ?
I mean, what do I need to change here in order to interact with the select menu, only the author of the command that called this menu could
he's asking for his problem, he's not helping you
and why would you put it somewhere?
I don't know how to do this kind of interaction yet
dunno but
if interaction.user != self.ctx.author:
return False
else:
return True
```is the same as
```py
return interaction.user == self.ctx.author
good. But I asked something else. I meant how to make it so that only the author of command can interact with the select menu
and the fact that I threw it off is responsible for me so that only the author of the command can press the buttons
@slate swan by the way , why can this method be used at all ?
is this what you need?
edit: hold on, i pip reinstall discord py and now magically working 🤣 im so dumb
is there a way to create an event for all reactions added to messages?
@client.event
async def on_reaction_add(reaction, user):
print("reaction")
is what i try to use, but it dosent work for messages sent while the bot is offline.
if i send a message then react to it while the bot is online, it prints reaction.
if i send a message while the bot is offline, start then bot, then when the bot is online react to that message it dosent print reaction
Just not possible to do what your asking for based on the gateway API. You could save a message ID somewhere, then every time the bot loads check the message again for an new reactions but that is quite cumbersome, and will not get ALL messages unless you add the ID or at least some way to persist the message across runs
how to use global check to check if author has role
i don't know if this helps, i'm still beginer, but i'm using this
if intr.user == ctx.author:
await intr.response.edit_message(view = None)```
Will this work for select menu ? Well, just select menu is a little different and it's not the same as the buttons
try it and tell me too, i want to know
okey
Programmers not known for their humour
I guarantee someone is going to bring out the “um actually”
can someone help with this i have intents enabled on dev page
okay thx sorry for slow response lol
How do I save them then
Same way you’d make a variable
? so what would i write
intents = discord.intents.all()
HAHAHAHA that was very well said 😂
yea just figured that out
i added it to both bot startup and in the on_message event so it checks per message for a bit more accuracy
try on raw reaction add
where is the problem
!d discord.on_raw_reaction_add
discord.on_raw_reaction_add(payload)```
Called when a message has a reaction added. Unlike [`on_reaction_add()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_reaction_add "discord.on_reaction_add"), this is called regardless of the state of the internal message cache.
This requires [`Intents.reactions`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.reactions "discord.Intents.reactions") to be enabled.
from http import client
from mimetypes import init
import discord
from discord.ext import commands
import os
from apikeys import *
intents = discord.Intents.default()
intents.members = True
client = commands.Bot(command_prefix="!", help_command=None, intents=intents)
@client.event
async def on_ready():
print("vital is ready")
print("--------------")
await client.change_presence(activity=discord.Activity(type=discord.ActivityType.watching, name="you.."))
initial_extentions = []
for filename in os.listdir('./cogs'):
if filename.endswith('.py'):
initial_extentions.append("cogs." + filename[:-3])
if __name__ == '__main__':
for extention in initial_extentions:
client.load_extension(extention)
client.run(BOTTOKEN)``` Can someone tell me why my `lock` and `unlock` command doesnt work ill send cog if needed (thats where the coding for commands is)
Whats the cmd name
oh thx
@peak salmon no working
Oh well if u want reactions added from when the bot was offline, this won’t do it
what kind of viruses are you writing ?
U should only send the cog 😂
Didn’t read the last part
I found that on insta
i can combine both the startup check and that for full reaction counting
Yep
from discord.ext import commands
class Moderation (commands.Cog):
def __init__(self, bot):
self.bot = bot
self._last_member = None
@commands.command()
@commands.has_permissions(manage_channels = True)
async def lock(self, ctx):
await ctx.channel.set_permissiona(ctx.guild.default_role, send_messages = False)
em = discord.Embed(colour = discord.Color.random(), description=f"{ctx.author.mention} is now locked")
await ctx.send(embed=em)
@lock.error
async def lock_error(ctx, error):
if isinstance(error, commands.MissingPermissions):
em = discord.Embed(colour=discord.Color.orange(), description=f":warn: {ctx.author.mention}: You're **missing** permission: ``manage_channels``")
await ctx.send(embed=em)
@commands.command()
@commands.has_permissions(manage_channels = True)
async def unlock(self, ctx):
await ctx.channel.set_permissiona(ctx.guild.default_role, send_messages = True)
em = discord.Embed(colour = discord.Color.random, description=f"{ctx.author.mention} is now unlocked")
await ctx.send(embed=em)
@unlock.error
async def unlock_error(ctx, error):
if isinstance(error, commands.MissingPermissions):
em = discord.Embed(colour=discord.Color.orange(), description=f":warn: {ctx.author.mention}: You're **missing** permission: ``manage_channels``")
await ctx.send(embed=em)
async def setup(client):
await client.add_cog(Moderation (client))``` Is the cog
how to make it so that only the author of the command can interact with the select menu ?
U should edit overwrites
valoshop
Send ss of cmd
? So what do I do bruh
I think there is an example in docs in how to make a channel private
Idk by heart
@lone lichen how to make it so that only the author of the command can interact with the select menu ?
Okay, but is my cog like not loading is that all good or is it the command?
!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.
!d discord.ui.View.interaction_check
await interaction_check(interaction, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
A callback that is called when an interaction happens within the view that checks whether the view should process item callbacks for the interaction.
This is useful to override if, for example, you want to ensure that the interaction author is a given user.
The default implementation of this returns `True`.
Note
If an exception occurs within the body then the check is considered a failure and [`on_error()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.ui.View.on_error "discord.ui.View.on_error") is called.
This @slate swan
ok i solved it
Idk check with some print statements
What was it?
async def interaction_check(self, interaction) -> bool:
if interaction.user != self.ctx.author:
return False
else:
return True```
it should look something like this ? @lone lichen
async def store(ctx:discord.Interaction, username: str, Password: str):
P in password
i hate myself
Ig, again idk by heart, usually when I need it I check the docs and I see
Ohh ofc it has to be lowercase 😂
WHAT ?
Check the docs and ull see how It’ s done
U basically overwrite the method
why not just return interaction.user == self.ctx.author?
!d discord.on_error
discord.on_error(event, *args, **kwargs)```
Usually when an event raises an uncaught exception, a traceback is logged to stderr and the exception is ignored. If you want to change this behaviour and handle the exception for whatever reason yourself, this event can be overridden. Which, when done, will suppress the default action of printing the traceback.
The information of the exception raised and the exception itself can be retrieved with a standard call to [`sys.exc_info()`](https://docs.python.org/3/library/sys.html#sys.exc_info "(in Python v3.10)").
Note
`on_error` will only be dispatched to [`Client.event()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.event "discord.Client.event").
It will not be received by [`Client.wait_for()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.wait_for "discord.Client.wait_for"), or, if used, [Bots](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#ext-commands-api-bot) listeners such as [`listen()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.listen "discord.ext.commands.Bot.listen") or [`listener()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Cog.listener "discord.ext.commands.Cog.listener").
Changed in version 2.0: The traceback is now logged rather than printed.
This?
no where you can paste in ur code
!pastebin
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.
!eval
code
!eval [python_version] <code, ...>
Can also use: e
*Run Python code and get the results.
This command supports multiple lines of code, including code wrapped inside a formatted code block. Code can be re-evaluated by editing the original message within 10 seconds and clicking the reaction that subsequently appears.
If multiple codeblocks are in a message, all of them will be joined and evaluated, ignoring the text outside of them.
By default your code is run on Python's 3.11 beta release, to assist with testing. If you run into issues related to this Python version, you can request the bot to use Python 3.10 by specifying the python_version arg and setting it to 3.10.
We've done our best to make this sandboxed, but do let us know if you manage to find an issue with it!*
not it but ill try it
!eval 2.0.0 import discord
from discord.ext import commands
class Moderation (commands.Cog):
def init(self, bot):
self.bot = bot
self._last_member = None
@commands.command()
@commands.has_permissions(manage_channels = True)
async def lock(self, ctx):
await ctx.channel.set_permissiona(ctx.guild.default_role, send_messages = False)
em = discord.Embed(colour = discord.Color.random(), description=f"{ctx.author.mention} is now locked")
await ctx.send(embed=em)
@lock.error
async def lock_error(ctx, error):
if isinstance(error, commands.MissingPermissions):
em = discord.Embed(colour=discord.Color.orange(), description=f":warn: {ctx.author.mention}: You're **missing** permission: ``manage_channels``")
await ctx.send(embed=em)
@commands.command()
@commands.has_permissions(manage_channels = True)
async def unlock(self, ctx):
await ctx.channel.set_permissiona(ctx.guild.default_role, send_messages = True)
em = discord.Embed(colour = discord.Color.random, description=f"{ctx.author.mention} is now unlocked")
await ctx.send(embed=em)
@unlock.error
async def unlock_error(ctx, error):
if isinstance(error, commands.MissingPermissions):
em = discord.Embed(colour=discord.Color.orange(), description=f":warn: {ctx.author.mention}: You're **missing** permission: ``manage_channels``")
await ctx.send(embed=em)
async def setup(client):
await client.add_cog(Moderation (client))
But usually ud use ur installed interpreter 😂
I have it on the buttons. I tried to transfer it to the select menu, nothing worked for me
U can run ur code locally and it will show u errors 😂
Send code of ur view
def __init__(self, ctx):
options = [
discord.SelectOption(label = "Основные", emoji= "🔷", description= "Основные команды сервера", value="1"),
discord.SelectOption(label = "Модерация", emoji= "🔷", description= "Команды для модерирования сервера", value="2"),
discord.SelectOption(label = "Взаимодействие", emoji= "🔷", description= "Команды взаимодействия между участниками", value="3"),
]
super().__init__(placeholder='Список команд сервера', min_values=0, max_values=3, options=options)
self.ctx = ctx
async def callback(self, interaction: discord.Interaction):
ckick = self.values[0]
if ckick == '1':
await interaction.response.send_message(
embed = discord.Embed(description= f'', colour=0xF1C40F),
delete_after=60
)
elif ckick == '2':
await interaction.response.send_message(
embed = discord.Embed(description= f'', colour=0xF1C40F),
delete_after=60
)
elif ckick == '3':
await interaction.response.send_message(
embed = discord.Embed(description= f'', colour=0xF1C40F),
delete_after=60
)
else:
await interaction.response.send_message(ckick)
async def interaction_check(self, interaction) -> bool:
if interaction.user == self.ctx.author:
return False
else:
return True
class SelectMenuHelpView(discord.ui.View):
def __init__(self):
super().__init__()
self.add_item(SelectMenuHelp())```
I mean you're referencing self.ctx but you haven't defined it
I would suggest taking in a member argument into the view
@sick birch
Traceback (most recent call last):
File "C:\Users\ToxicPenguin\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\commands\core.py", line 113, in wrapped
ret = await coro(arg)
File "C:\Users\ToxicPenguin\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\commands\core.py", line 762, in _invoke
await self.callback(self.cog, ctx, **kwargs)
File "c:\Users\ToxicPenguin\Desktop\проекты на Python\disocrd bot python\cogs\osnov.py", line 152, in __help__
view = SelectMenuHelpView()
File "c:\Users\ToxicPenguin\Desktop\проекты на Python\disocrd bot python\cogs\osnov.py", line 99, in __init__
self.add_item(SelectMenuHelp())
TypeError: __init__() missing 1 required positional argument: 'ctx'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\ToxicPenguin\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\bot.py", line 755, in process_application_commands
await ctx.command.invoke(ctx)
File "C:\Users\ToxicPenguin\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\commands\core.py", line 312, in invoke
await injected(ctx)
File "C:\Users\ToxicPenguin\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\commands\core.py", line 119, in wrapped
raise ApplicationCommandInvokeError(exc) from exc
discord.commands.errors.ApplicationCommandInvokeError: Application Command raised an exception: TypeError: __init__() missing 1 required positional argument: 'ctx'```
@sick birch edit code
You have to pass it in from your function
And pass it down throughout your "tree"
Command -> View -> Select
@sick birch
I don't know what kind of tree it is transmitted by. But nothing works
The tree is not real, I'm just saying you have to pass it from top (your command) to the bottom (your select)
@sick birch I need to use async def interaction_check(self, interaction) -> bool: or it can all be done through if
guys why it send this error ```py
Traceback (most recent call last):
File "C:\Users\Ibrah\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\application_command.py", line 848, in invoke_callback_with_hooks
await self(interaction, *args, **kwargs)
File "c:\Users\Ibrah\Desktop\Discord Bot\main.py", line 163, in count
for i in range(count):
TypeError: 'SlashApplicationCommand' object cannot be interpreted as an integer
The above exception was the direct cause of the following exception:
nextcord.errors.ApplicationInvokeError: Command raised an exception: TypeError: 'SlashApplicationCommand' object cannot be interpreted as an integer```
Why does the error say ( is not closed even tho it is?
Here's an example:
class MySelectMenu(discord.ui.Select):
def __init__(self, ...) -> None:
super().__init__(...)
async def callback(
self,
select: discord.ui.Select,
interaction: discord.ui.Interaction,
) -> None:
...
class MyView(discord.ui.View):
def __init__(self, *, author: discord.Member, ...) -> None:
super().__init__(...)
self.author = author
self.add_item(MySelectMenu(...))
async def interaction_check(self, interaction: discord.Interaction) -> bool:
return interaction.user == self.author
@bot.command()
async def my_command(ctx: commands.Context, ...) -> None:
view = MyView(author=ctx.message.author)
await ctx.send(view=view)
An example of passing down the invoking member down @slate swan
anyone
You probably meant discord.Color.random()
Oh that works
help
thanks man
Traceback (most recent call last):
File "C:\Users\ToxicPenguin\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\commands\core.py", line 113, in wrapped
ret = await coro(arg)
File "C:\Users\ToxicPenguin\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\commands\core.py", line 762, in _invoke
await self.callback(self.cog, ctx, **kwargs)
File "c:\Users\ToxicPenguin\Desktop\проекты на Python\disocrd bot python\cogs\osnov.py", line 149, in __help__
view = SelectMenuHelpView()
TypeError: __init__() missing 1 required keyword-only argument: 'author'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\ToxicPenguin\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\bot.py", line 755, in process_application_commands
await ctx.command.invoke(ctx)
File "C:\Users\ToxicPenguin\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\commands\core.py", line 312, in invoke
await injected(ctx)
File "C:\Users\ToxicPenguin\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\commands\core.py", line 119, in wrapped
raise ApplicationCommandInvokeError(exc) from exc
discord.commands.errors.ApplicationCommandInvokeError: Application Command raised an exception: TypeError: __init__() missing 1 required keyword-only argument: 'author'```
anyone know why there are errors did I miss input something?
from such a transfer, my error just appears
class MyView(discord.ui.View):
def __init__(self, *, author: discord.Member, ...) -> None:
super().__init__(...)
self.author = author
self.add_item(MySelectMenu(...))
async def interaction_check(self, interaction: discord.Interaction) -> bool:
return interaction.user == self.author```
I just did it already and it was still a mistake. you use author only in myView and don't pass it anywhere else
@sick birch Thanks, but I didn't understand anything from your explanation. I only realized when I looked at how I did the same thing in button
That's the point
You need to get author into your view so you can check for it in interaction_check
can someone tell me why these are errors
I've already done everything
im using a cog from another file and I did this setup on the main file, where do i run this func?
@sick birch I said thank you
Ive tried running it normally and it didnt work so thats why im asking
can someone PLEASE help me with this idk why its an error
Looks like a typo, did you mean isinstance?
oh yes, but error is still an error
it says "error" is not defined
You forgot a comma in function definition, between ctx and error
ohhh thanks
You're welcome
I don't understand. What do you want by putting the setup func in main file? It should be at the end of cog file.
from discord.ext import commands
import os
class Moderation (commands.Cog):
def __init__(self, bot):
self.bot = bot
self._last_member = None
@commands.command(pass_context = True)
@commands.has_permissions(manage_roles = True)
async def role(self, ctx, user : discord.Member, *, role: discord.Role):
if role in user.roles:
await ctx.send(f"{user.mention}: already has {role}")
else:
await user.add_roles(role)
em = discord.Embed(discord.Color.random(), description=f"Added {role} to {user.mention}")
await ctx.send(embed=em)
@role.error
async def role_error(self, ctx, error):
if isinstance(error, commands.MissingPermissions):
em = discord.Embed(discord.Color.orange(), description=f"{ctx.author}: You're **missing** permission: `manage_roles`")
await ctx.sen(embed=em)
@commands.command(pass_context = True)
@commands.has_permissions(manage_roles = True)
async def removerole(self, ctx, user : discord.Member, *, role: discord.Role):
if role in user.roles:
await ctx.send(f"{user.mention}: does not have {role}")
else:
await user.add_roles(role)
em = discord.Embed(discord.Color.random(), description=f"Removed {role} from {user.mention}")
await ctx.send(embed=em)
@removerole.error
async def role_error(self, ctx, error):
if isinstance(error, commands.MissingPermissions):
em = discord.Embed(discord.Color.orange(), description=f"{ctx.author}: You're **missing** permission: `manage_roles`")
await ctx.sen(embed=em)
async def setup(client):
await client.add_cog(Moderation (client))``` Do you know why the command doesnt work or is there like something wrong I don't understand the Bot does nothing when I do `,role {user}`
Is what the terminal said
this is not a problem with the cog
loading extensions is now async
meaning that you need to await your .load_extension
oh you don't even have it in an async function like setup_hook...
Read this ig https://gist.github.com/Master326486/6cf48c1ca0509b98e673451e356ba625#extension-and-cog-loading--unloading-is-now-asynchronous
Wait so what do I do I'm lost
wdym? What do you not understand?
Like what am I sopose to replace or add?
oh gosh I really gotta go, sorry.
@sick birch can u help them?
oof ok ill wait for robin
yeah I figured it out thanks tho
exception discord.Forbidden(response, message)```
Exception that’s raised for when status code 403 occurs.
Subclass of [`HTTPException`](https://discordpy.readthedocs.io/en/latest/api.html#discord.HTTPException "discord.HTTPException")
dont forget to check error.original
Yeah, I assume they know that or would ask if they had an issue
markdown updated https://gist.github.com/Snipy7374/e0d754812ae9008544583ab977d8bc3e (original creator @slate swan)
unindent setup
async def setup(client):
await client.add_cog(Moderation(client))
```should be outside of the cog
from folder import file
i don't think he have a __init__.py file
no
just folder
eg:
from folder import foo
command still doesnt work
@silk fulcrum what do you think
but you shouldn't import cogs
where do I put that line 27?
can you send a screenshot of your folder
you have written bot.load_extension(...) already
shouldn't he have an __init__.py file to do from folder import func?
it doesnt load for me smh
await it
why?
he's not making packages
__pycache__?
no I didnt
I don't have an __init__.py in my project
and it works?
yes
an init file probably would fix he's problem
who ever has it
import discord
from discord.ext import commands
import os
from apikeys import *
intents = discord.Intents.default()
intents.members = True
client = commands.Bot(command_prefix="!", help_command=None, intents=intents)
@client.event
async def on_ready():
print("vital is ready")
print("--------------")
await client.change_presence(activity=discord.Activity(type=discord.ActivityType.competing, name="ur mom"))
initial_extentions = []
for filename in os.listdir('./cogs'):
if filename.endswith('.py'):
initial_extentions.append("cogs." + filename[:-3])
if __name__ == '__main__':
for extention in initial_extentions:
client.load_extension(extention)
client.run(BOTTOKEN)``` is my main.py
@slate swan pls remove the server invite from your code block, or use a pastebin
oop you got it
probably Bot
yea I forgot to sorry
this part
from distutils import extension
import discord
from discord.ext import commands
import os
from apikeys import *
intents = discord.Intents.default()
intents.members = True
client = commands.Bot(command_prefix="!", help_command=None, intents=intents)
@client.event
async def on_ready():
print("vital is ready")
print("--------------")
await client.change_presence(activity=discord.Activity(type=discord.ActivityType.competing, name="ur mom"))
initial_extentions = []
for filename in os.listdir('./cogs'):
if filename.endswith('.py'):
initial_extentions.append("cogs." + filename[:-3])
if __name__ == '__main__':
for extention in initial_extentions:
client.load_extension(extension)
client.run(BOTTOKEN)```
😩
you have to put your
for extention in initial_extentions:
client.load_extension(extention)
```in an async context
like a setup_hook event
and await client.load_extension(extention) instead of client.load_extension(extention)
like
@bot.event
async def setup_hook():
for extention in initial_extentions:
await client.load_extension(extention)
this is just an example
!d discord.ext.commands.Bot.setup_hook what does this even take
nothing, ok
Bro i put await and it does this how many damn times do i have to say?????
@event 🤢 + you still didnt await it
I just explained it
thanks
so do I get rid of if __name__ == '__main__':
yes
put that code in a setup_hook event
I'm gonna check if that overwrites something important
async def setup_hook():
for extention in initial_extentions:
await client.load_extension(extention)```
yes
so that?
yes
imagine mocking event for overwriting this
my command still doesnt work
from discord.ext import commands
import os
class Moderation (commands.Cog):
def __init__(self, bot):
self.bot = bot
self._last_member = None
@commands.command(pass_context = True)
@commands.has_permissions(manage_roles = True)
async def role(self, ctx, user : discord.Member, *, role: discord.Role):
if role in user.roles:
await ctx.send(f"{user.mention}: already has {role}")
else:
await user.add_roles(role)
em = discord.Embed(discord.Color.random(), description=f"Added {role} to {user.mention}")
await ctx.send(embed=em)
@role.error
async def role_error(self, ctx, error):
if isinstance(error, commands.MissingPermissions):
em = discord.Embed(discord.Color.orange(), description=f"{ctx.author}: You're **missing** permission: `manage_roles`")
await ctx.sen(embed=em)
@commands.command(pass_context = True)
@commands.has_permissions(manage_roles = True)
async def removerole(self, ctx, user : discord.Member, *, role: discord.Role):
if role in user.roles:
await ctx.send(f"{user.mention}: does not have {role}")
else:
await user.add_roles(role)
em = discord.Embed(discord.Color.random(), description=f"Removed {role} from {user.mention}")
await ctx.send(embed=em)
@removerole.error
async def role_error(self, ctx, error):
if isinstance(error, commands.MissingPermissions):
em = discord.Embed(discord.Color.orange(), description=f"{ctx.author}: You're **missing** permission: `manage_roles`")
await ctx.sen(embed=em)
async def setup(client):
await client.add_cog(Moderation (client))``` (cog)
do you get an error
no
here there's something that explain setup hook
https://gist.github.com/Snipy7374/e0d754812ae9008544583ab977d8bc3e#fundamentals-for-this-gist
example?
@client.event
async def setup_hook():
for extention in initial_extentions:
await client.load_extension(extention)
print("loaded" + extention)
extension would be right but ok
loaded.Moderation
loaded.Utility
it said in terminal
yea?
first of all, make one global error handler
an on_command_error event in your main file
i mean i would if i new how..
and remove these repetitive things
so remove error handlers from cog file?
yes
done
@bot.event
async def on_command_error(ctx, error):
if isinstance(error, ...):
...
like?
Anyone good with python here?
I'm trying to work on some stuff todo with google sheets, And I'm not exactly the best at python xd
@bot.event
async def on_command_error(ctx, error):
if isinstance(error, commands.MissingPermissions):
em = discord.Embed(discord.Color.orange(), description=f"{ctx.author}: You're **missing** permission: `manage_roles`")
await ctx.send(embed=em)
else:
raise error
you always have to raise the error if it's none of the above
this is why you didn't get an error before
you had commands.MissingPermissions before
so do I put that in the brackets?
alr fairs
wait I have another question
im still writing
oh ok
async def on_command_error(ctx, error):
if isinstance(error, commands.MissingPermissions):
em = discord.Embed(discord.Color.orange(), description=f"{ctx.author.mention}: You're **missing** permission: ")
await ctx.send(embed=em)
else:```
what do I do for the permission:
!d discord.ext.commands.MissingPermissions
exception discord.ext.commands.MissingPermissions(missing_permissions, *args)```
Exception raised when the command invoker lacks permissions to run a command.
This inherits from [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure")
do I put in {}
yes
discord.ext.commands.bot Privileged message content intent is missing, commands may not work as expected.
intents = discord.Intents.default()
intents.members = True
intents.message_content = True
or you could just do
intents = discord.Intents.all()
@cold sonnet
your post is pretty much the same as magnet's was before
you have to do this
what can I do to fix? I'm really trying to start making command tonight
it's easier actually
I have
async def setup_hook():
for extention in initial_extentions:
await client.load_extension(extention)
print("loaded" + extention)```
@bot.event
async def setup_hook():
await client.load_extension("tickets")
yeah that's alright he just had the same issue
oh you wern't talking to me mb
im gonna open a help channel
async def setup_hook():
await client.load_extension("tickets")``` is what he said a few mins ago
Did it work?
Je ne saurais pas que je suis un peu nouveau dans le codage, vous pouvez créer un canal d'aide et quelqu'un vous répondra
Oh okay
didn't know
how do I delete a message from the select menu ?
await interaction.message.delete()
await interaction.delete_original_response()
how can i get a category by name?
!d discord.utils.get
discord.utils.get(iterable, /, **attrs)```
A helper that returns the first element in the iterable that meets all the traits passed in `attrs`. This is an alternative for [`find()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.utils.find "discord.utils.find").
When multiple attributes are specified, they are checked using logical AND, not logical OR. Meaning they have to meet every attribute passed in and not one of them.
To have a nested attribute search (i.e. search by `x.y`) then pass in `x__y` as the keyword argument.
If nothing is found that matches the attributes passed, then `None` is returned.
Changed in version 2.0: The `iterable` parameter is now positional-only.
Changed in version 2.0: The `iterable` parameter supports [asynchronous iterable](https://docs.python.org/3/glossary.html#term-asynchronous-iterable "(in Python v3.10)")s...
thanks
and how do i create one?
guild.create_category_channel?
!d discord.Guild.create_category_channel
await create_category_channel(name, *, overwrites=..., reason=None, position=...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Same as [`create_text_channel()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild.create_text_channel "discord.Guild.create_text_channel") except makes a [`CategoryChannel`](https://discordpy.readthedocs.io/en/latest/api.html#discord.CategoryChannel "discord.CategoryChannel") instead.
Note
The `category` parameter is not supported in this function since categories cannot have categories.
Changed in version 2.0: This function will now raise [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError "(in Python v3.10)") instead of `InvalidArgument`.
thanks
hi for the first time I'm trying to make a bot but I have an error that could explain to me?
!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 Members, Message Content, and Presences. These are needed for features such as on_member events, to get access to message content, 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.
bot = commands.Bot(command_prefix = "$", intents=discord.Intents.all())
copy and paste that
enabling all intents isn't the best practice. It's better just to request the intents that are required.
@slate swan take a read of this
and take note that the line of code they provided you with changed some stuff from what you had originally
can sum1 help
yah fixed ty
does anyone know i can make my bot loop send a embed in a channel every 2 hours
exts
breuh, alright then
b
yeah thanks
thank you his walk but how do I my a description? please
Description of what?
a discord description
Your bot's profile?
yes
That can be done through the dev portal, on your application's page
there is an option to describe profile it manages how many servers?
You can't dynamically change your description, no
Usually bot's like to display statistics like that in their status though
how to do in the status? please
You can do that using change_presence
https://discordpy.readthedocs.io/en/stable/ext/commands/api.html?highlight=change_#discord.ext.commands.Bot.change_presence
There's an example of this page of the docs 
yall know how to fix this its supposed to print a house
C:\Users\youse\Downloads>python seff.py
File "C:\Users\youse\Downloads\seff.py", line 1
print ("
^
SyntaxError: unterminated string literal (detected at line 1)
\ cancels out the thing that's next to it
you have to put 2 next to each other to see one
wait
hmmm
You're gonna want to use a codeblock when tyrping that eval command
!e print (" )
(
^ )
/ \ ---
/ | |
/ _ \ |
/ () |
/
/| __ __
| | | | |
| || || |
| __ _ |
| | | | | | *
| | 0| || | ***
| | | | *****
///////////// "
@strange carbon :x: Your 3.11 eval job has completed with return code 1.
001 | File "<string>", line 1
002 | print (" )
003 | ^
004 | SyntaxError: unterminated string literal (detected at line 1)
yes
!e print(" / \\")
@cold sonnet :white_check_mark: Your 3.11 eval job has completed with return code 0.
/ \
?
exactly like that
@cold sonnet
your homework sucks
@commands.command()
async def purge(ctx, amount=11):
amount = amount+1
if amount > 101:
em = discord.Embed(color=discord.Colour.random(), description="I can not delete more than 100 messages")
await ctx.send(embed=em)
else:
await ctx.channel.purge(limit=amount)
em2 = discord.Embed(color=discord.Color.random(), description="Seccefully cleared messages")
await ctx.send(embed=em2)``` Can someone help me fix this error
fr
forgot self
as an argument
yes
so how do i fix it
!e print(" \/\/\/\/")
@cold sonnet :white_check_mark: Your 3.11 eval job has completed with return code 0.
\/\/\/\/
should be good
put two \'s everywhere I suppose
not just there where it's yellow
pink
whatever
even though it works right
Because you have 2 on_ready events and the last one will always take precedence
?
its bot.change_presence
Do you have discord.py installed?
yes
I don't really know the problem robin will have to help
Oops
You need to import discord
Yeah, but you need to import discord in your code
put import discord in your code
why is my slash command not being shown? I waited long enough
or was it bot.slash_command
i forgor
global slash commands take a while to sync
anything between 10 minutes to an hour or so I think, unless they somehow got that to speed up
thank you

