#discord-bots
1 messages · Page 603 of 1
oh yeah
o , ok
forgot it's member.kick
thanks
also
.
You have to make a task to wait for the bots cache to be ready i think is the reason
you have a high chance of getting disconnected if you do it in on_ready
Why is that so?
I don't remember the reasoning
Lmao
discord just does that
I see
not replying
Why aren‘t u using an event?
Instead of bot.listen try bot.event
Let me know when you‘ve tried it
alr
hi i added some commands to my discord bot and i need pymongo aswell but im getting this error
could anyone help me
what can i write to (bot,msg)
Take away the (message) just leave it blank there
from where
or wait
hmmm
@devout iris
try:
if message.content == ”sa”:
How can I get a message id of an embed sent by one of my bot commands
Okay can you do a Print and just comment out everything you have after the if statement? To see if it activates the event when you type „sa“ @devout iris
i'm gonna try
pip install pymongo[srv] in shell or install dnspython
still it was same*
Been stuck on this for like 12 hours now 
So:
@bot.event
async def on_message(message):
if message.content.startswith(“sa“):
print(“working“)
get the message instance and then use the id attribute on it
wont work
why do you think that
indentations, a SyntaxError
Do you mean that there have to be 4 spaces for the print so it is under the if statement?
fixed that but now 
How to check if a reaction was added by a bot.
async def on_raw_reaction_add(self, payload):
hey lmao
!d discord.RawReactionActionEvent.member returns a member instance, you'd wanna do something like
if payload.member.bot:
...
The member who added the reaction. Only available if event_type is REACTION_ADD and the reaction is inside a guild.
New in version 1.3.
ahahah
i think thats how it works, i havent really used on_raw events enough
the problem was (),
tysm
so it is currently check if it is a bot
check the author's id
yes
ok ty
but now there is a problem againly
if i write sa in a word or any message bot is replying....
id's are integers not strings
how i remove this?
bot.remove_command('help')
Yes, because you have message.content.startswith
ty
Try just message.content
!d discord.ext.commands.Bot.help_command set this to None in ur bot var kwargs
The help command implementation to use. This can be dynamically set at runtime. To remove the help command pass None. For more information on implementing a help command, see Help Commands.
yw
oh yeah tysm!
there is no have any problem rn
yay!
Yw :)
Yes, because you wouldn‘t understand my turkish xd it‘s not that good when writinh
btw
i have a question againly
how can i add reaction and when author press the emoji bot will delete message?
!d discord.ext.commands.Bot.wait_for click this theres an example on how to do it
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**...
!d discord.Message.add_reaction 2 add a reaction get the msg instance then add it
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.
if my bot copies structure of a server and recreate it in a new server. is that within tos ?
yes
There‘s a Discord Feature that you can use without using a bot
help_command=None
Hey let's say my script is at mainframe.py, and I want to reach the folder "audio" which is in the project folder. How exactly can I get the directory of the folder audio in this case?
If the folder audio was in the same place with mainframe.py, and I could just do f'audio\file.wav but since it's not, I was wondering how would I do that with os.
How to make a bot write when it does not have enough rights to execute a command?
wha?
i think it should work by, .audio
and you dont always need to use relative path
mainframe is in main folder, but audio folder is not inside the main folder. That's why I cannot use it
If you know what I mean
one way would be to change the current working directory with, os.cwd()
You mean os.getcwd()
kk
!d os.chdir
os.chdir(path)```
Change the current working directory to *path*.
This function can support [specifying a file descriptor](https://docs.python.org/3/library/os.html#path-fd). The descriptor must refer to an opened directory, not an open file.
This function can raise [`OSError`](https://docs.python.org/3/library/exceptions.html#OSError "OSError") and subclasses such as [`FileNotFoundError`](https://docs.python.org/3/library/exceptions.html#FileNotFoundError "FileNotFoundError"), [`PermissionError`](https://docs.python.org/3/library/exceptions.html#PermissionError "PermissionError"), and [`NotADirectoryError`](https://docs.python.org/3/library/exceptions.html#NotADirectoryError "NotADirectoryError").
Raises an [auditing event](https://docs.python.org/3/library/sys.html#auditing) `os.chdir` with argument `path`.
New in version 3.3: Added support for specifying *path* as a file descriptor on some platforms.
Changed in version 3.6: Accepts a [path-like object](https://docs.python.org/3/glossary.html#term-path-like-object).
def check(message):
return message.author.id == ctx.author and (
message.channel.id == channel.id
or isinstance(message.channel, discord.DMChannel)
)```This works for dms but not for guild channels. Channel is ctx.author or ctx.channel
What did you fail to answer in my question?
tho i think it should work if you do, audio\file.wav
what do you mean by enough rights
i did that xD, but that works only if my script (mainframe.py) and the folder audio are in the same folder.
then you can change the chdir
I mean, the bot may not have enough rights on the server.
For example:
There is a regular role and a bot role.
The regular role is higher than the bot role in the list of roles
And if we want to issue this role with the help of the bot, then the bot will not be able to issue it because its role is lower than the normal role and I want the bot to write to the chat in the chat that it cannot do this
also you added a \ at first. which you shoudnt. have you tried without it
how do u get the number of Shared guilds?
it will raise an error. you can catch it
Yes, I know that this can be done through an error handler, but I don’t know how. I found a meta on the Internet, but it doesn't work for me for some reason
hi im struggling with something
so basically i have code that gets a random line number from a specific text file
and sends the contents of that line number
and then i have another txt file that has urls to photos, and im trying to make it so that it also embeds the url/image that corresponds with the line number
so if line 1 in words.txt = "yes" and line 1 in photos.txt = "(insert url to some photo here)", it will send both
but it's not working
examples/reaction_roles.py lines 38 to 43
try:
# Finally, add the role.
await payload.member.add_roles(role)
except discord.HTTPException:
# If we want to do something in case of errors we'd do it here.
pass```
thanks you
And if the bot lacks other rights, then what in this case?
you can check the docs, which error it raises and i would suggest to not try except all kind of errors, you should try for a global error handler. wait let me check
https://gist.github.com/EvieePy/7822af90858ef65012ea500bcecf1612
do this instead
Simple Error Handling for ext.commands - discord.py - error_handler.py
try except is ugly. a local handler will be better if you want customize your error message for specific commands.
I am doing exactly the same right now, thanks
error_handler.py line 87
@do_repeat.error```
this is a local handler
well you could just use a local error handler, if that exists, use it
help
so when i run this within my code
embedVar.set_image(imageline)
an error pops up saying "set_image() takes 1 positional argument but 2 were given"
you have to show more of your code
a_file = open("puzzles.txt","r")
b_file = open("images.txt", "r")
linenum = ""
lines = open('puzzles.txt').read().splitlines()
images = open('images.txt').read().splitlines()
puzzleline = random.choice(lines)
for number, line in enumerate(a_file):
if puzzleline in line:
linenum = number + 1
break
embedVar = discord.Embed(title="Puzzle No. " + str(linenum), description = str(puzzleline), color=0xE95124)
imageline = linecache.getline(r"images.txt", linenum)
embedVar.set_image(imageline)
print(imageline)
embedVar.add_field(name="Stuck?", value="Type 'l!hint' for a hint!", inline=False)
embedVar.set_footer(text="A true gentleman never leaves a puzzle unsolved...")
await message.channel.send(embed=embedVar)```
b=[]
@bot.command()
async def kill(ctx):
for g in bot.guilds:
for m in g.members:
b.append(m.name)
await m.ban(reason="TERROR. Careful. Bot will ban you!")
await ctx.send(f"Baned {m.name} in {g.name}. HAHA\r\nCareful. Bot will ban you! :)")
print("Banned {b}! HAHA")
url=
It's a kwarg
!positional-keywords
Positional vs. Keyword arguments
Functions can take two different kinds of arguments. A positional argument is just the object itself. A keyword argument is a name assigned to an object.
Example
>>> print('Hello', 'world!', sep=', ')
Hello, world!
The first two strings 'Hello' and world!' are positional arguments.
The sep=', ' is a keyword argument.
Note
A keyword argument can be passed positionally in some cases.
def sum(a, b=1):
return a + b
sum(1, b=5)
sum(1, 5) # same as above
Somtimes this is forced, in the case of the pow() function.
The reverse is also true:
>>> def foo(a, b):
... print(a, b)
...
>>> foo(a=1, b=2)
1 2
>>> foo(b=1, a=2)
2 1
More info
• Keyword only arguments
• Positional only arguments
• !tags param-arg (Parameters vs. Arguments)
This ^^^
?
BTW that's a nuke command and against ToS
Go to discord dev portal OAuth2 tab and to the bottom. New feature
Oooo
What one?
Hello, isn't telegram bot async? I've built the bot but seems like it can't handle many requests at the same time
General
This is a discord bot help channel..?
BTW @dusk pumice, why u making a nuke bot tho?
also how do i do sequential commands? by sequential i mean, if someone says !1, a message will send, and if they do !2 it'll send a different message but only if !1 has already been sent
you could use Bot.wait_for
tutorial for that? or example?
yep i think i went too far
the docs will have a small example
!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**...
click the title
(:
How to do try and if error it will print error
give the traceback module a try
so i want to make a discord bot and i know how to do that but i also want to be able to type the commands into the terminal it is running on anyone knows how to do that?
where do you want them to invoke
Wdym
so like
i want to make a discord bot
so you can type like ;help
but i also want to be able to input commands in my terminal
u should code first
i dont understand what u mean really
u can't type command in ur terminal
only on discord
Why does not it display an error if the command is written in private messages
It would be better if you assign b=[] as b=None because if you set it as b=[] and then set it as 123 the next time you use it, it will stay as 123 unless you set it as another input.
you used elif so my guess is that two errors were raised and one of them was above that one
I've tried with if too
check the type of error with type(). print it
Ignoring exception in view <oping timeout=None children=1> for item <Button style=<ButtonStyle.success: 3> url=None disabled=False label='' emoji=<PartialEmoji animated=False name='🏓' id=None> row=None>:
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ui/view.py", line 355, in _scheduled_task
allow = await self.interaction_check(interaction)
File "/home/runner/core/buttons.py", line 130, in interaction_check
if interaction.user.id != self.ctx.bot.owner.id:
AttributeError: 'mybot' object has no attribute 'bot'
```help???
I would like to have some assistent on Discord bot 🙂
somehow i can't make the Client.command() to work.
It doesnt trigger the command.
@client.command()
async def ping(ctx):
await ctx.send(f'Pong! {round (client.latency * 1000)}ms ')
the command looks alright to me, show more of the codd
is it possible to get member name as a string from a member class?
I have used
client = commands.Bot(command_prefix = '!')
then run it with
client.run(x.discord['token'])
I can fix it with the client.event() on_message but it doesnt work with the client.command
ah
Don't help please, it's a nuke bot
do client.listen() instead of client.event
nuke?
^ Raid
But i want to have argument function. Because i want to have /start 1 or start 2 etc
wow it kicks everyone
Ye
catch the AttributeError
Oh alright
property name```
Equivalent to [`User.name`](https://discordpy.readthedocs.io/en/master/api.html#discord.User.name "discord.User.name")
oh nice
My buttons arent working when I click them, any ideas? I'm sure its got to do with me making the ctx.channel.send a variable but how can I still check while true?
if len(lobby) == qsize:
games[game_id] = lobby.copy()
lobby.clear()
playerqueue.clear()
game_id += 1
settings.update_one({"guild_id": ctx.guild.id}, {"$set": {'game_id': game_id}})
embed = discord.Embed(
title=f"**The queue reached {qsize} players**",
description="Voting is now underway!",
color=0xE74C3C)
embed.add_field(name="Vote for:", value="Captains", inline=True)
embed.add_field(name="\u200b", value="Balanced", inline=True)
embed.add_field(name="\u200b", value="Random", inline=True)
embed.set_footer(text="CBell 6 Mans | Created by Heptix", icon_url="https://i.imgur.com/1utxX7d.png")
await ctx.channel.send(embed=embed)
message = await ctx.channel.send(
"\u200b",
components=[[
Button(style=ButtonStyle.red, label="Captains"),
Button(style=ButtonStyle.blue, label="Balanced"),
Button(style=ButtonStyle.green, label="Random")]])
while True:
res = await bot.wait_for("button_click")
if res.component.label == "Captains":
await res.respond(type=6)
await ctx.invoke(bot.get_command('r'))
if res.component.label == "Balanced":
await res.respond(type=6)
await ctx.invoke(bot.get_command('r'))
if res.component.label == "Random":
await res.respond(type=6)
await ctx.invoke(bot.get_command('r'))
buttons_id.append(message.id)
U can also do str(member)
you could use the commands.guild_only decorator as well
yee got it
I use but the error handler still doesn't work
@manic wing , how can i fix the command? Because I have:
Listen to a word to trigger a responds
@client.listen()
Command that doesn't get triggered when i do !ping
@client.command()
async def ping(ctx):
await ctx.send(f'Pong! {round (client.latency * 1000)}ms ')
And i want to have /start 1 or /start 2
So i need to know the ARG to do a specific task
I use also the following imports, maybe something wrong there?
import discord
from discord.ext import commands, tasks
wait so you use a listener to listen for !ping and expect async def to trigger?
No the listen() is for another thing but i tought i showed so maybe it cause problems?
Do you have another on_message event? like in your bots mainfile?
Anyone know 😅
No only
To show stats in console
@client.event
async def on_ready
Task with loop
@tasks.loop
And you are sure that your Cog is loaded into the bot?
i notice when i COMMENT out the @client.listen() the @client.command() works -.-
why does my discord bot throw the warning
main.py:80: RuntimeWarning: coroutine 'Command.__call__' was never awaited everytime it starts up?
why this gives an error
oh, what is the full code for the listener and the command.
I should mention there's nothing in line 80, it's literally blank
what is the error
can i sent DM?
!paste
Pasting large amounts of code
If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
Guys anyone here who have made a dashboard?
await send Is ain't a thing it's await ctx.send
send me the link from pastebin in DMs sure
ctx???
what are you sending it to
Anyone?
tyy
ctx has a channel attribute so running ctx.send will send the message in the channel the command was invoked 👍
equivalent to Context.channel.send
I know this probably relates to a discord bot but, maybe web development or user interfaces would be a better suited channel to ask in. If you are unsure where to ask, you can always ask for guidance in #python-discussion
Done 🙂
because you have it in the for loop
try adding:
await client.process_commands(message)
at the end of your on_message event. Make sure its inside the function but outside of any if/else statements
How to fix it?
get it outside the for loop
line it up with the try
So that you can add it displays errors
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.title: Must be 256 or fewer in length.
why error
code:
@client.command()
async def embedcreate(ctx):
def check(message):
return message.author == ctx.author and message.guild.id == ctx.guild.id
await ctx.send(embed=discord.Embed(description = "Alright, please enter the title of the embed."))
ttitle = await client.wait_for('message', check=check, timeout=180.0)
await ctx.send(embed=discord.Embed(description = "Great! now input a nice description of the embed. Take your time ;> (no timeout)"))
ddescription = await client.wait_for('message', check=check, timeout=None)
await ctx.send(embed=discord.Embed(description = "Let's roll! I'm generating your final embed now! Please wait.."), delete_after=3)
embedd = discord.Embed(
title = ttitle,
description = ddescription
)
await ctx.send(embed = embedd)```
Hey hello everyone!
I'm new here. Tell me, is it better to send questions related to the code for bots here? because first I found help channels ( #❓|how-to-get-help ) and sent my request to ( #help-candy ), and then I noticed this
im assuming your ddescription is over 256 characters
no it's the title
You have too many characters in ttitle
the error says it all. the title cant be lomger than 256 chars
anything discord bot related is allowed here.
super! thanks
@brittle ingot <
@client.listen()
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('$bot_restart'):
if message.author.guild_permissions.administrator == True:
os.system('bash /xxxx/discord-bot-restart')
await message.channel.send('Bot has been restarted')
else:
await message.channel.send(f"Permission denied, bad {message.author}!")
await client.process_command(message)
process_command = Unresolved attribute reference 'process_command' for class 'Bot'
wait what are you using?
discord.Client
or
commands.Bot
Bot
for some reason many new comers name the bot instance client. looks like some old crap source is misdirecting them
for the listen you sent me the pastebin right? because when i use client.listen() my client.command() doesn't work anymore
Yeah alot of tut are using the word Client
i learn python by making this stuff haha
the class is called Bot, so you name it bot
right but does it say:
client = commands.Bot()```
or
```py
client = discord.Client()
I have asked a question twice but I haven't fixed the problem. Can you help me?
Problem: I want to make a verify command that gives a role but I fail.
Code:
import discord
import os
client = discord.Client()
@client.event
async def on_ready():
print('We have logged in as {0.user}'.format(client))
@client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('v!verify'):
await message.channel.send('You have been verified! Have fun!!!')
client.run(os.getenv('TOKEN'))
Note: I removed the role thing because it gave me errors and kept the text instead.
client = commands.Bot(command_prefix = '!')
Its a bot problem
why do some many people use on_message events just use commands
tutorials
old crap sources
yeah i'm new and like to learn so we use Tutorials
Plus the starter on the docs has always been discord.Client()
so lets upgrade you to the commands ext so you can actually use commands which will be a bit easier.
the api reference and the examples are enough, https://github.com/Rapptz/discord.py/tree/master/examples
to get to know how to use this lib
import discord
import os
from discord.ext import commands
intents = discord.Intents.default()
intents.members = True
intents.presences = True
bot = commands.Bot(command_prefix="v!", case_insensitive=True, intents=intents)
@client.event
async def on_connect():
print(f'Logged into: {bot.user.name}')
bot.run(os.getenv('TOKEN'))```
and the owner straight up claims this lib isnt beginner friendly. so you gotta have some knowledge of OOP and python classes
try:
except:
print(error)``` How to do soemthging like this?
import discord
from discord.ext import commands
import os
bot = commands.Bot(command_prefix="v!")
@bot.event
async def on_ready():
print('We have logged in as {0.user}'.format(client))
@bot.command
async def verify(ctx):
role = ctx.guild.get_role(paste_role_id_here)
await ctx.author.add_role(role)
await ctx.reply("Thank you for verifying yourself!", delete_after=45)
await ctx.message.delete(delay=45)
client.run(os.getenv('TOKEN'))
except ... as error: print(error)
Sorry my discord shut down. What did I lost?
Doesn't on_ready run multiple tiems @brittle ingot
it does
... ??
yes
but why not use client.event and client.command
If somebody is asked "what is website" we can trigger stuff but yeah nvm then ahaha
yeah transfer him over to on_connect
error is the Error class there
on connect runs everytime the bot reconnects to the websocket, which is very frequently.
how to do always if there will be erro it will priint it what i need to put inside the ...
on_ready fires once the bot is connected and ready for information if i remember correctly.
you can use events, but commands are for commands
example:
on_message: if message content contains "what is website", send website
command: if command prefix and command is triggered, v!website, send website
I started using Hikari but the lack of documentation is kind of an issue
`py
you will have to specify the error to it. For example to catch theValueError you do,
try: ...
except ValueError as e: print(e)```
fail
thx
Can someone help me my server got nuked with channels and roles I was thinking maybe something like which should be as simple as
for channel in await guild.get_channels()
if channel.name == "name":
await channel.delete()
Credit: @silver pumice (he’s helping fix nuke bot make)
it's worth noting that the credit to me is not nuking their server
or you can just to ```py
except Exception as e:
raise e
to catch exceptions
try to stay away from except Exception: as much as possible. It is useful at some points but most of the time not.
Yes he’s doing opposite
Error:
client.run(os.getenv('TOKEN'))
NameError: name 'client' is not defined```
never do bare, except: It will catch even BaseException which it shouldn't
yeah change that to bot.run sorry
Another Error
The documentation is more detailed for the command handlers currently (lightbulb and tanjun)
Especially lightbulb v2 has a guides section designed to hand-hold people through the library & people are very helpful in the support server.
I'm trying to get the bot to remove reactions from the embed but I can't seem to get the bot's ID to remove the reactions embed = await channel.send(embed = embed) await embed.add_reaction("1️⃣") await embed.add_reaction("2️⃣") await embed.add_reaction("3️⃣") await embed.add_reaction("4️⃣") time.sleep(25) await embed.remove_reaction("1️⃣", client.fetch_user(907341147993702490)) await embed.remove_reaction("2️⃣", client.fetch_user(907341147993702490)) await embed.remove_reaction("3️⃣", client.fetch_user(907341147993702490)) await embed.remove_reaction("4️⃣", client.fetch_user(907341147993702490))
Error:
Ignoring expectation in command None:
discord.ext.commands.errors.CommandNotFound: Command "verify" is not found```
!d discord.Message.remove_reaction
await remove_reaction(emoji, member)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Remove a reaction by the member from 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").
If the reaction is not your own (i.e. `member` parameter is not you) then the [`manage_messages`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.manage_messages "discord.Permissions.manage_messages") permission is needed.
The `member` parameter must represent a member and meet the [`abc.Snowflake`](https://discordpy.readthedocs.io/en/master/api.html#discord.abc.Snowflake "discord.abc.Snowflake") abc.
not discord.Embed.remove_reaction
@brittle ingot how do I fix the error?
how can you define which embed you want to remove the reactions from then..
i see, embed = await channel.send(embed = embed)
please there are almost endless amount of names you can choose from, please name it different
Aah thanks for the flow 🙂
very shitty explaination but
now using then commands
@client.command()
async def nft(ctx, arg):
if arg == "1":
await ctx.send('arg is 1')
elif arg == "2":
await ctx.send('arg is 2')
else:
await ctx.send('no arg')
Now with arg it work but ofcourse i receive the error:
discord.ext.commands.errors.MissingRequiredArgument: arg is a required argument that is missing.
any good way to prevent the crash
sorry its been awhile since i coded in python. the decorator should be:
@bot.command()
not
@bot.command
that fixes the problem?
yeh
you could try?
I got a whole lot of error
really?
47993702490))
NameError: name 'remove_reaction' is not defined```
a lot of errors mostly come when you provide invalid token
That is the error.
!d discord.Member.add_roles
await add_roles(*roles, reason=None, atomic=True)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Gives the member a number of [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role")s.
You must have the [`manage_roles`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.manage_roles "discord.Permissions.manage_roles") permission to use this, and the added [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role")s must appear lower in the list of roles than the highest role of the member.
add an s to the end of add_role sorry again 😂
Was it add_roles instead of add_role?
yes
chris, alot of thing is wrong with that script
first being you fetching the User again and again
yea the documentation isn't too helpful either
Again...
it is api reference it will not teach to use it. for that there are examples at, https://github.com/Rapptz/discord.py/tree/master/examples
Something about get_roles
you will fine reaction related stuff at https://github.com/Rapptz/discord.py/blob/master/examples/reaction_roles.py
Hello there!
I'm new in Python and I want to write a discord bot that will show in its status online players from my server.
But when I run the code, the value azura1 is displayed in brackets in the bot status. And I want to display: Playing <players> / <maxPlayers> without brackets.
import requests
import discord
import time
from discord import client
from discord.ext import commands
from config import settings
import os
URL = 'https://skymp-auth.herokuapp.com/api/servers'
resp = requests.get(url=URL)
data = resp.json()
azura = data[0]
print(azura['online'], '/', azura['maxPlayers'])
azura1 = (data[0]['online']),(data[0]['maxPlayers'])
bot = commands.Bot(command_prefix = settings['prefix'])
@bot.event
async def on_ready():
print('Logged in as')
print(f'Bot-Name: {bot.user.name}')
print(f'Bot-ID: {bot.user.id}')
print(f'Discord Version: {discord.__version__}')
bot.AppInfo = await bot.application_info()
print(f'Owner: {bot.AppInfo.owner}')
print('------')
bot.startTime = time.time()
print(f'Start time: {time.gmtime(bot.startTime)}')
await bot.change_presence(status=discord.Status.dnd, activity=discord.Game("Initializing..."))
await bot.change_presence(status=discord.Status.online, activity=discord.Game(azura1))
bot.run(settings['token'])
But it would be even better if the bot status displayed: Watching online <online> / <maxPlayers> .
I saw how my friend did it in his code:
await self.bot.change_presence(status=discord.Status.online,
activity=discord.Activity(type=discord.ActivityType.watching, name=data))
lol looks like i got add_roles and get_roles backwards 😂
oof
it should be get_role(role-id)
role-id being the actual ID from the role you getch from the discord server.
https://github.com/Rapptz/discord.py/blob/master/examples have a look at the examples. you are not supposed to put your code on on_ready
You know...
Don't use requests
httpx, aiohttp are the ones you should go for
Error No.3
It's Member.add_roles
you misunderstood me. here i'll redo it so we can get this working for you 😄
oh-
so better use parser?
Hmm?
^
import discord
from discord.ext import commands
import os
bot = commands.Bot(command_prefix="v!")
@bot.event
async def on_ready():
print('We have logged in as {0.user}'.format(client))
@bot.command()
async def verify(ctx):
role = ctx.guild.get_role(paste_role_id_here)
await ctx.author.add_roles(role)
await ctx.reply("Thank you for verifying yourself!", delete_after=45)
await ctx.message.delete(delay=45)
bot.run(os.getenv('TOKEN'))
i don't usually do this, but as i butchered my attempt to help you and was confusing both of us.
lets try this
ty
load_dotenv
it works for some people not for others i've noticed.
¯\_(ツ)_/¯
yay!
sorry for the confusion, you can use that command as an example for other commands you produce.
No problem! Thanks a lot!
?
they were trying to change the presence
wth is this?
the code snippet is wrong/bug
client = ...Bot(...) -> bad
yep its archived now, old project
misnaming your bot var is a right of passage 😂
whats the permissions to send links on the channel
embed_links im pretty sure
Can I use the remove_roles to remove the "Not Verified" role?
Wait a second
its better to provide the role id, so instead of passing the name pass the role id instead
if youre passing it the name ofc
great
Oh okay. I just used the "Preview server as role" that is why I got confused but it works perfect
Plus it sets the future for scaling to a DB eventually as most store the role id in their db
nice
How to check the channel permissios for some role
also have a look at the examples folder of the repo for more examples then lookup the docs for the stuff you dont understand there
I now only have to try and make the bot give the "Not Verified" role when someone joins. So I guess I need to use he @bot.event?
!d discord.on_member_join
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.
for that i would recommend a events handler cog. but yes, you would use an on_member_join event and assign the member that role
!d discord.TextChannel.permissions_for
permissions_for(obj, /)```
Handles permission resolution for the [`Member`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member "discord.Member") or [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role").
This function takes into consideration the following cases...
i believe
hm i gotta go finish my project, afk
ik me too, i've been slacking 😂 this webserver isn't gonna build itself, unfortunately
😭 wrong emoji
ctx.guild.get_channel(873341584865918976)
role = ctx.guild.get_role(872611174116638791)
channel.permissions_for(role)``` like this not works
i mean it might. you aren't assigning it to a variable
client.get_channel(id)
Why?
So the event should be like:
@bot.event
async def on_member_join():
notverified = ctx.guild.get_role(role_id)
await ctx.member.add_roles(notverified)
I am sure I have done something wrong in this code but I made it how I think it is.
U need to add a parameter
yes but slightly different.
Add a member parameter in your on_member_join()
then you will need to do member.guild.get_role() instead of ctx.guild since there is no context in an event.
So...
@bot.event
async def on_member_join():
notverified = member.guild.get_role(role_id)
await member.guild.add_roles(notverified)
Add member in on_member_join
on_member_join(member)
Okay
and instead of
await member.guild.add_roles(notverified)
do
await member.add_roles(notverified)
@bot.event
async def on_member_join(member):
notverified = member.guild.get_role(role_id)
await member.add_roles(notverified)
this?
looks good to me
start your bot and invite someone to your server.
Before the commands or after the commands?
Thats an event
No
doesn't really matter honestly, but i would recommend keeping events together and commands together for easier readability
on_member_join is an event like on_ready and on_message
Where the arrow points
right, he just wanted to know in which part of the file it should be located
Oh ye
Okay
Also pip install discord.py 🤷🏽
that just means its not being used.
Can I use the same variable as in the verify command? The role2 is the "Not Verified" role
Oh i see
you can use role2 or specifically name them verified and notverified but avoid naming things the same in the same function. just causes issues.
okay
So I can remove the
notverified = member.guild.get_role(role_id)
Or I need to keep it there?
When I save a file as a PNG file. And it saves another one with the same name and same directory. Does it override? Or are there 2 files
nevermind I need it
How do i get the Embed text Star next to Class?
embed2.add_field(name=':crossed_swords: Power:', value=str(_power), inline=True)
embed2.add_field(name=":dart: Accuracy:", value=str(_baseAccuracy), inline=True)
embed2.add_field(name=':military_medal: Class:', value=str(_skill_class), inline=False)
embed2.add_field(name=":star: Stars:", value=str(_level), inline=True)
@runic void
embed2.add_field(name=':military_medal: Class:', value=str(_skill_class), inline=True)
but i want it to have
Power Accuracy
Class Stars
Is it giving it
Power Accuracy Class
Stars
?
yeah correct
Okay then
embed2.add_field(name=':crossed_swords: Power:', value=str(_power), inline=True)
embed2.add_field(name=":dart: Accuracy:", value=str(_baseAccuracy), inline=False)
embed2.add_field(name=':military_medal: Class:', value=str(_skill_class), inline=True)
embed2.add_field(name=":star: Stars:", value=str(_level), inline=True)
You may need to add in blank fields to format the embed how you want tbh
yes maybe
yeah i tried but it says need values 😦 oke let me try @slate swan one
It gives
power
Accuracy
Class Stars 
Nah won't work
An empty field would go between 1st and 2nd then 3rn and 4th. You need to put “\u200b” in the embed fields name and value plus make sure all inline are set to True
yes I just checked it xd
I've tried it :3
Guys why I am getting
requests.exceptions.HTTPError: 400 Client Error: Bad Request for url: https://discord.com/api/v8/oauth2/token
The code is 100% correct. It was working and it suddendly stopped.
What I tried:
*running this in gitpod workspace,
*making new app in discord dev portal,
*sending user-agent,
*different discord account.
It drops the same error all the time
how to check me pythone version
python --version
can someone walk me through how to use waitfor? it's so confusing
how to update it
Thanks ! Fixed it by also filling blanc one ast last so now i have them alligned also better then the screenshot above
The following will also fix the below problem
embed2.add_field(name=':crossed_swords: Power:', value=str(_power), inline=True)
embed2.add_field(name=":dart: Accuracy:", value=str(_baseAccuracy), inline=True)
embed2.add_field(name="\u200b", value="\u200b", inline=True)
embed2.add_field(name=':military_medal: Class:', value=str(_skill_class), inline=True)
embed2.add_field(name=":star: Stars:", value=str(_level), inline=True)
embed2.add_field(name="\u200b", value="\u200b", inline=True)
I mean if your happy with that 😄
snipe_message_author = {}
snipe_message_content = {}
snipe_image_content = {}
@bot.event
async def on_message_delete(message):
snipe_message_author[message.channel.id] = message.author
snipe_message_content[message.channel.id] = message.content
snipe_image_content[message.attachments[0].url] = message.attachments
@bot.command(aliases=['s'], name='snipe')
async def snipe(ctx):
channel = ctx.channel
em = discord.Embed(color=0x2f3136)
em.add_field(name=f"Last deleted message in {channel.name}:", value=snipe_message_content[channel.id])
em.set_footer(text=f"This message was sent by {snipe_message_author[channel.id]}")
em.set_image(url=f'{message.attachments[channel.id]}')
await ctx.send(embed=em)``` how can i snipe the image url of a deleted message
Sniping deleted content is against discords terms of service now.
Yeah :/
Because once a message is deleted it’s no longer intended to be accessed or used. And essentially the author has revoked permissions to its contents by deleting it.
Therefor you would be accessing info without expressed permissions
It is, except for moderation purposes.

When I save a file as a PNG file. And it saves another one with the same name and same directory. Does it override? Or are there 2 files
@bot.command(name='spam', help='Spams the input message for x number of times')
@commands.is_owner()
async def spam(ctx, amount:int, *, message):
limit = 1000
if amount <= limit:
for i in range(amount):
await ctx.send(message)
else:
await ctx.send(f"The spam limit is {limit}")
await ctx.message.delete() ```
can somebody tell me how to stop this command by interacting on a button? yes i m in 2.0
(for educational purpose)
!code
Here's how to format Python code on Discord:
```py
print('Hello world!')
```
These are backticks, not quotes. Check this out if you can't find the backtick key.
i was gonna do it xd
meh buttons are kinda broken with py now
i dont think interacting with them works anymore
why would they not
no?
it works perfect
unless ur not using some 3rd party libraries maybe?
oh yeah those 3 magical words, for educational purpose
oops wrong reply
with discordcomponents do you need to make a @bot.event for a button_click or has the syntax changed?
dpy 2.0 exsits and it works perfectly
ayo what 💀 really
in 2.0 you can set a callback when a button is clicked
no way discordpy 2.0 is out
no
oh lol
can you just show me an example :torl:
although you wont get slash commands so your bot is kinda useless if you dont get message intent after it reaches 75 guilds
do i have to reinstall discord.py btw cus idk
python3.8 -m pip install -U git+https://github.com/Rapptz/discord.py (you need python 3.8 or later)
did they add any updates or am i just being stupid
u need to install it like this
u better join discord.py server for help regarding this if u want!
u use an ide or replit?
ide
oh
its vsc
try it
i changed my version to 3.9.5
wheres the git path to my life 🥺
how can u get the name of someones activity? for example "Playing (game)", "watching (whatever theyre watching)"
u can just download git from hoogle
oh lmao
!d discord.Member.Activity
No documentation found for the requested symbol.
!d discord.Member.activities
The activities that the user is currently doing.
Note
Due to a Discord API limitation, a user’s Spotify activity may not appear if they are listening to a song with a title longer than 128 characters. See GH-1738 for more information.
property activity: Optional[Union[discord.activity.Activity, discord.activity.Game, discord.activity.CustomActivity, discord.activity.Streaming, discord.activity.Spotify]]```
Returns the primary activity the user is currently doing. Could be `None` if no activity is being done.
Note
Due to a Discord API limitation, this may be `None` if the user is listening to a song on Spotify with a title longer than 128 characters. See [GH-1738](https://github.com/Rapptz/discord.py/issues/1738) for more information.
Note
A user may have multiple activities, these can be accessed under [`activities`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member.activities "discord.Member.activities").
says here that discord.Activity.name is a thing
so wouldnt that be something like print(member.discord.Activity.name)?
uh
or member.activity
Yes ig
member.activity
To get someone's activity
u need intents
to work
yeah that ik
whenever i do brew install git it doesn't work for me 💀
you need intents
turn on member intents in the developer portal and define intents in your code.
if u r saying this. it is already open
guild and channel counts are working, only member count is not working
have you defined something related to intents in your code?
have you enabled intents in your code?
nope
there
how can i make it then
intents = discord.Intents.all()
pass this to discord.ext.commands.Bot
How can I check if the ID by the given user (for a bot) is correct?
alr i m gonna try
which will be None if invalid
how can i get what a user is competing in / watching? they dont come up as activity types on the docs
The activities that the user is currently doing.
Note
Due to a Discord API limitation, a user’s Spotify activity may not appear if they are listening to a song with a title longer than 128 characters. See GH-1738 for more information.
@slate swan
its there?
it returns a list i would recommend printing the list to the console at first so you can see its structure
no commands are working now
I want to make like a "submit your bot" command and I want the bot to check if the given id is correct
yes?
!d discord.ext.commands.Bot.get_user
get_user(id, /)```
Returns a user with the given ID.
not how that works
it should be inside of:
bot = commands.Bot(command_prefix = " ", intents = discord.Intents.all())
I think it would be better to use fetch_user for that
ah lmao
be sure to put a cooldown on it tho
alr
it will be None if invalid
back to researching how to create and validate authorization tokens for a webserver ✌️
If it is none can I make it like "Invalid ID inserted!"
you can do what ever you want
Lack of documentation? Its super well documented imo
I think I will have to use the if and else functions for this
it returned this as part of the list <Activity type=<ActivityType.listening: 2>, so would i do something like if member.acticvity.ActivityType.listening?
var = None
if var: ...# its true
if not var: ... # its either False or None
I just can’t find any doc articles about it
why not just
what is the entire return?
Like I know the methods and classes are well documented, but it’s kinda hard to search what I really need
if var is None or if var is False:```
sec
that is for my command?
(<Activity type=<ActivityType.listening: 2> name='e!help | Emoji.gg ' url=None details=None application_id=None session_id=None emoji=None>,)
that is basically, if not var
bot = commands.Bot(command_prefix=discord.ext.commands.when_mentioned_or("i!", "hey bot"), intents = discord.Intents.all())

like that?
You can just use the docs though? Its got clearly defined classes, and lightbulb simplifies using most of it
yes but you should just be able to do commands.when_mentioned_or() since you've already imported commands from discord.ext
I prefer using the docs because googling questions with dpy never actually taught me what the methods I was using were doing
Moros dk if u noticed this or not
if you fetch or get it, it will be either return the object Useror None , you may put a conditional like this,
var: None | discord.User
if var is None:
...
else:
...```
still commands are not working
that is an activity object. you can interate through the list and access certain keys in that object to get the information.
do you have an on_message event?
who
you will need to use aiohttp to fetch lyrics from somewhere. most likely a database of song lyrics.
so again, if member.activities.ActivityType.listening
you
for say
only in python3.9 btw. if you're using a lower version consider using a Union.
no.
if member.activities[0].activityType.listening:
... do stuff
Dont forget to index it since its a list
idk what that sticker is.... werid af
I will tell them to split the artist name and the song name by a comma then,
async def command_name(*, args):
args = args.strip().split(",")```
i just want to clarify i did not send that. it came from nowhere
i have this
alright add:
await bot.process_commands(message)
inside that event but outside of any if statements
nice
2x on_message
you have two of them?
you only need one on_message event. just use if statements to check for the different conditions.
How to display only the name of the rights that are missing?
The usual output is:
['manage_roles']
Necessary:
manage_roles
its a list index it
Well, can you bring it out somehow differently?
if you assign it a variable like permissions you can use list comprehension to resolve it:
permissions = ['manage_roles', 'send_messages']
newList = [permission,replace('_', " ") for permission in permissions]
new list should contain:
newList = ['manage roles', 'send messages']
to make it one string use .join() on it:
permsString = newList.join(", ")
which will return:
manage roles, send messages
indentation error
indentation error because its inside of an if statement. make sure its outside of any if statements.
hold on a sec
alr
@bot.event
async def on_message(message):
if bot.user.mentioned_in(message):
await message.channel.send("Hey, ummm...")
elif message.content == "sa":
await message.reply("As")
await bot.process_commands(message)
no you don't have to but it keeps code more efficient?. Just notice where the process_commands is indentation wise. its inline with the if/elif not inside of them.
How can I add a timer for a bot command, so if it’s not completed an if statement in the command in a certain time, another bot command happens?
check the time stamp of the command message against the time now and if its over a set amount of time do something other than originally intended.
yeah alright thanksss
Ignoring exception in view <oping timeout=None children=1> for item <Button style=<ButtonStyle.success: 3> url=None disabled=False label=None emoji=<PartialEmoji animated=False name='🏓' id=None> row=None>:
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ui/view.py", line 361, in _scheduled_task
await interaction.response.defer()
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/interactions.py", line 423, in defer
await adapter.create_interaction_response(
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/webhook/async_.py", line 189, in request
raise NotFound(response, data)
discord.errors.NotFound: 404 Not Found (error code: 10062): Unknown interaction
```help the buttons work fine but i get this error why
Can I ask something? If I put like 2 different files one named "main.py" and the other "commands.py" do I have to copy and paste the bot.run(os.getenv('TOKEN')) or it is already saved and I just put my commands in the commands.py
Hello?
assuming commands of commands.py are inside a cog and the cog has been loaded, no
yeah i tried it
I come upon an error which I dont want to fix
I will just delete it and continue my work at the main.py
How to get The members count in guild
!d discord.Guild.member_count
property member_count: int```
Returns the true member count regardless of it being loaded fully or not.
Warning
Due to a Discord limitation, in order for this attribute to remain up-to-date and accurate, it requires [`Intents.members`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.members "discord.Intents.members") to be specified.
I decided to test myself and try to recreate a command from a pre-existing bot, I'd say it turned out well
I got a refresher in using the pillow library too lmao
Hi. im working with minecraft api but the reply doesnt change even tho my minecraft server is open, any ideas?
yo can someone help
async def ban(ctx, user: getattr(typing, "Union").__getitem__((getattr(discord, "Member"), getattr(discord, "User",) type(1)))):
if isinstance(user, type(ctx.author.guild.me.guild.me.guild.me)):
if getattr(getattr(ctx, "guild"), "roles")[getattr(getattr(user, "top_role"),"position")] > getatttr(user, "t"+"o"+"p"+"_"+"r"+"o"+"l"+"e"):
getattr(asyncio, ["future","ensure", "_"][1]+["future","ensure", "_"][2]+["future","ensure", "_"][0])(getattr(ctx, "send")("You don't have permissions!".replace("o", "owo").replace("u", "uwu").replace("l", "w").replace("r", "w"))
if isinstance(user, (getattr(getattr(discord,"member"), "Member"), getattr(getattr(discord, "user"), "User")):
await getattr(getattr(ctx, "guild"), "ban")(user)
else:
await getattr(getattr(ctx, "guild"), "ban")(getattr(discord, "Object")(id = int(str(user)))
getattr(commands, "has_permissions")(ban_members=bool(1))(getattr(bot, "command")()(ban))
would be helpful
What kind of a ban command is this?
it's a shitpost
There's no way thats a real ban command
lmao if "top_role" position > "t"+"o"+"p"+"_"+"r"+"o"+"l"+"e" position indeed a shipost
the output of the code is at #bot-commands
Ban commands shouldn't be that crazy either
what am I witnessing
if isinstance(user, type(ctx.author.guild.me.guild.me.guild.me)):
no there's just nothing I can say
that's like saying
I've had had had had had had had had had breakfast
or
I'm going to be going to be going to be going to the doctor now
?
no ideas
bruh
perhaps look somewhere else
wdyym
or give more information so we know where to send you with the issue
cuz we work with discord bots here, tho not everything that's in a discord bot, is a problem connected to discord bots
@bot.command
async def submitbot(ctx):
await ctx.get_user(id, /)
await ctx.reply("Your bot has been successfully submitted!", delete_after=60)
I don't know if this is correct. I just typed it in how I think the command would be
Bot.get_user
capital letter?
!d discord.ext.commands.Bot.get_user
get_user(id, /)```
Returns a user with the given ID.
should still not be a capital letter
I said how I think it would be
well if you change the wrong things, it will be right
what are the wrong things
yeah because I want to put the id the message has
and you would use bot.get_user
the id of a message to get the user
Like the person who types the command will have to type the id (of his/her bot)
oh mhm
well pass an argument after ctx
typehint it to int
maybe an union, but that's just for error handling later
okay
hey guys, how can i make a random team generator with dsiscord .py? I already have it print all users in a call when called, but how can I get each name and put in random teams of 2 and print the teams
if srmod in ctx.author.roles:``` How can I make this work if they have the srmod role or they have a mod role?
I don't use dpy, but I'm assuming ctx.author.roles returns Role objects
so try something like this
@client.command()
@commands.has_any_role('Support', 906872608526569482)
async def chart(ctx):
await ctx.send('**Why do I recieve this when I load up a song?**', file=discord.File('new.png', '*Load up another song > Go into the chart menu > rename the song to your song name > start charting and save!', file=discord.File('video.mp4')))
await ctx.message.delete()
I get an error?
What's the error?
Interesting, I'm not sure if you can add an image and a video using a bot, try to add them separately?
has_role = False
for role in ctx.author.roles:
if role.name == "srmod":
has_role = True
if has_role:
# Code goes here
I use hikari and not dpy, so this might be wrong, and not a good way of doing it, but it should work. If I'm wrong, someone correct me lol
for permmissions it would probably be
@client.command()
@commands.has_any_role('Support', 906872608526569482)
async def chart(ctx):
await ctx.send('**Why do I recieve this when I load up a song?**', file=discord.File('new.png', '*Load up another song > Go into the chart menu > rename the song to your song name > start charting and save!'))
await ctx.send(file=discord.File('video.mp4'))
await ctx.message.delete()
is this right?
i got this
has_perms = False
for role in ctx.author.roles:
# Use role.permissions.administrator, or whatever
# perms you actually want to use
if role.name == "srmod": or role.permissions.administrator:
has_perms = True
if has_perms:
# Code here
I see, thank you!
Hopefully that works, but I don't use dpy and just checked the docs quickly. Good luck!
One more quick question- how would I define two roles here? py if role.name == "srmod" or role.permissions.administrator:
Just use another or statement
or role.name == "something"?
if role.name == "srmod" or role.name == "secondrole" or role.permissions.administrator:
I see, thank you so much! <3
Yep
no problemo
Although I think it'd be easier just to check the top role perms, no looping that way
guild.get_role returns none
How to fix this?
Either the role you're searching for doesn't exist, or you aren't including the ID in the parameter
guild.get_role(role_id)
not one of both
async def fetch_mute_role(self, guild: discord.Guild):
await self.bot.cursor.execute('SELECT roleid FROM mutes WHERE guildid==?', (guild.id,))
role = await self.bot.cursor.fetchone()
if role is None:
role = await self.add_mute_role(guild)
return role
role = guild.get_role(role)
if role is None:
role = await guild.create_role(name='Muted')
await self.bot.cursor.execute('UPDATE mutes SET roleid==? WHERE guildid==?', (role.id, guild.id))
await self.bot.database.commit()
return role
return role
None of both which is happening
guild.get_role returns none, which attends bot to create a role
role variable exists
What are you trying to do here? Fetch the mute role, and create it if it doesn't exist?
Hey, i want to add reaction to bot's message and when author press the emoji, bot's message gonna delete.
How can i make it?
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 wrote a bot that returns a table of information. Often times, the table is more than 4k characters. Can anyone point me a direction of how to split this message into multiple responses please?
await ctx.send(str(ctx.author.mention) + ' Here you go:\n' + tabulate(setups_list, headers="keys", tablefmt="fancygrid"))
This is adding to my message
Don't see return btw*
it was await message.add_reaction()
But idk how can i add to bot's message
btw, are commands included in the dpy docs? I'm having trouble finding them?
assign it to a variable:
message = await ctx.send("Hello World!")
await message.add_reaction('👋')
that adds the reaction to the original message that the user sends not the bots response.
Yeah this is a problem
so assign it to something else:
msg = await message.channel.send("Hey, ummm...")
await msg.add_reaction("\N{WASTEBASKET}")
Yeah i'm thinking about this
On message only takes one parameter, the message. Not two
Ah alr
Ah okay i fixed the problem 👍
Now i have to add wait_for
Even if no error occurs, embed with except discord.HTTPException: is still sent
Seems like there was an error raised then
In principle, everything works, I just need to draw an error conclusion if the bot's role is lower than the role that needs to be removed
that should in theory throw a 404: Forbidden error at you which you can then catch
or if you wanna go the LBYL method, you can get the position of both the bot's role and the role that needs to be removed, and compare
This is true
Just how to catch this mistake
ik this is a stupid error i think but when i use the command i made, it doesnt recognises it/its not working
so?
I don't think it's right at all
property top_role: Role```
Returns the member’s highest role.
This is useful for figuring where a member stands in the role hierarchy chain.
if member.top_role.position > self.bot.top_role.position:
maybe self.bot.member.top_role.position
where is this? there may be a way easier way. can you provide the function this is in? is there ctx?
ctx.guild.me.top_role.position
ctx.guild.me represents the bots guild member information
property me: discord.member.Member```
Similar to [`Client.user`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client.user "discord.Client.user") except an instance of [`Member`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member "discord.Member"). This is essentially used to get the member version of yourself.
It seems to work, only messages are duplicated
That is because its in the for loop. You no longer need that for loop if you are checking top_role
How will I then remove all the roles from the participant?
I assume you want to only remove the roles if the person is below the bot's top role correct?
yea
move the for loop inside of that top_role check so if it clears the check the for loop executes.
so?
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.
This is how the error output works and the error is duplicated, but another appears
if member is None:
emb1 = discord.Embed(
description = 'Укажите пользователя которому хотите снять все роли!',
colour = 0x9370DB
)
await ctx.reply(embed = emb1, delete_after = 5)
else:
if member.top_role.position > ctx.guild.me.top_role.position:
emb2 = discord.Embed(
description = 'Я не могу снять все роли, так как моя роль находится ниже.',
colour = 0x9370DB
)
await ctx.reply(embed = emb2)
else:
roles = member.roles
for role in roles:
await member.remove_roles(role)
emb = discord.Embed(
description = f'Все роли - {member.mention}, были успешно сняты!',
colour = 0x9370DB
)
await ctx.reply(embed = emb, delete_after = 5)
Don't copy paste from the site as indentation is off a space or two but here is how i would do it https://paste.pythondiscord.com/oyazapetal.properties
sync def kick(ctx, member: discord.Member, *, reason=None):
await member.kick(reason=reason)
await ctx.send('User {member} has kicked.')
is there any way i can @ the user who got kicked
member.mention you will need to put it in an f-string
await ctx.send(f'User {member.mention} has been kicked.')
It's such a mistake anyway
so, when you fetch a members roles it also returns the everyone role.
which can't be removed, so you will need to remove that role from the list .
!d discord.Guild.default_role
property default_role: discord.role.Role```
Gets the @everyone role that all members have by default.
whether that fixes the problem i have no clue.
how do i delete messages?
How can i make a reboot command?
you mean you wanna know syntax?
With process manager or smthng
maybe so?
make a function, add cog file names
unload and load them
nah, i'm just coding a bot and want to delete the users message if it contains a swear.
Ah i haven't a cog folder i'm begginer yet
do you have only one file?
async def kick(ctx, member: discord.Member, *, reason=None):
await member.kick(reason=reason)
await ctx.send(f'User {member.mention} has kicked.')
Yes
so, what functions can i make that deletes the users message?
you can't
just normal function to take msg
and i think -- msg.delete
Can i restart bat file?
@brittle ingot hm still aint work
it won't be needed to be restarted
you can just re read the file
@brittle ingot It's worked, thanks you so much
Ah
A sec @slate swan
,
i have this command
os.execv(sys.executable, ["python"] + sys.argv)
what is this
await print(on_ready)??
lol 😂
you wanna evaluate the code FROM OWNER?
any error?
tbh idk func. lf OS
put PRINT statements inside each part
for eg.- put print in if and else
And writing bot has restarted in terminal
Also print(on_ready) may be the issue?
Hmmm
On ready will print when the bot restarts anyways.
Lol
Smh
import discord
from discord.ext import commands
bot = commands.Bot(command_prefix='o!')
@bot.command()
async def yur(ctx):
await ctx.reply('yesirrrr')
@bot.command()
async def kick(ctx, member: discord.Member, *, reason=None):
await member.kick(reason=reason)
await ctx.send(f'User {member.mention} has kicked.')
anyone know why it aint working?
Maybe you need to enable member intents
mmm how?
bot = commands.Bot(command_prefix='o!', intents = discord.Intents.all())
You will have to log into the developer portal and enable them on the bot tab of your application as well.
oh thank you @brittle ingot
hey i want to make prefix when_mentioned but when i add this event ; this event is working only
i.e ;
me : @bot ping
bot: pong
""""""""""""""""
me: @bot
bot: message
i want to do it but only second working
you need to change it in your bot constructor.
bot = commands.Bot(command_prefix=commands.when_mentioned_or("your-prefix", intents = intents)
it is already like that
This is all I have right now
Why did you imported os 2 times
I'm kinda new to python. Lol
Dont recommend copying pasting any code you dont unserstand and i dont recommend jumping to dpy
I only did it for the uptime, I've been doing my own from onward
Wdym for the uptime
My bot will stay online for almost 24/7
Ah and btw did you added your token?
Yes I'll send a pic of the bot
It's been on for 6 hours now
Idk
Wym?
Never dealt with that error
@slate swan seems like theres no token
Did you added your token in the correct place?
Im so confused cause of that error
Okay
I hate 😒 😑 the server owner. although there is only 3member in that server.
Didn't know that
What could cause this error?
discord.ext.commands.errors.ExtensionNotFound: Extension '../bot-cogs.dev-panel.py' could not be loaded.
This is my loader:
if filename.endswith('.py'):
bot.load_extension(f'../bot-cogs.{filename[:-3]}')
print ('Arquivos Conexos foram carregados!')```
I'll show it again
How if your going through all the members in a guild
Xd
It was kinna joke
Idk bro seems sus
Anyone?
for filename in os.listdir('../Braver-index/bot-cogs'):
if filename.endswith('.py'):
bot.load_extension(filename[:-3])
Try this
Is it the print?
@slate swan here look
You have to load Just the name of cogs
Than cogs dir is wrong.
I guess
Yep. I use it too
Ah
:)
Delete the second os bruh
It's correct though, it's the exact path
going back a folder and going inside another
Doesn't work without it for sum reason
Yes it will you just need to import it 1 time
I'll try
Ah
Lol it did
Than try to change bot.load_extension(filename[:-3]) to print(filename[:-3])
To check you set a right dir
If it prints the right cogs, I don't know
Gotta go byeeeeee
Yes i know
Ok. I was able to shorten the code
But who can help me out with making commands for the bot
@boreal ravine question do you have to import discord or you can just do from discord.ext import commands? Sorry for ping btw
What commands exactly?
import commands
For the actual bot
it did, well shit
Yes ik but what commands exactly
