#discord-bots
1 messages Β· Page 460 of 1
oh okay
so what's not working?
I'm the owner
you cant change your nickname with a bot
it would raise forbidden
sad
yoo guys anyone know how to make a bot collect data from a database? like more specifically images and texts?
Yeah because the bot doesn't have a role/permission
Do you know how discord roles work...?
Check if the role has the required permissions
^
:)
Just said bro. We are chill
if you are just going to use a variable value only, you don't need f strings. For example, x = 10, print(x) and x = 10, print(f"{x}") will both work, so you don't need to put f strings. F strings are used to concatenate strings.
WE ARE CHILL!
thanks
Whatever the case, bots will never be able to edit the server owner's nickname
yeah
guys is it possible to make a bot collect specific images or text from a database and send it in a text channel?
putting a variable inside an fstring casts it into a str iirc
@client.command()
async def join(ctx):
channel = ctx.author.voice.channel
await channel.connect()
@client.command()
async def leave(ctx):
await ctx.voice_client.disconnect()
Why isn't this working?!
for objects, if a __str__ is not defined, it returns its __repr__
@slate swan :white_check_mark: Your eval job has completed with return code 0.
001 | <class 'int'>
002 | <class 'str'>
!e ```py
class obj:
def str(self):
return '1'
foo = obj()
print(f'{foo}')
@hasty iron :white_check_mark: Your eval job has completed with return code 0.
1
!e
x = 10
print(x)
@slate swan :white_check_mark: Your eval job has completed with return code 0.
10
Who would've thought
anyone can help on #help-cheese
srry did not want to reply to you
Same. I need help
where
Oh wait..., can @unkempt canyon play my guesser game?
#help-carrot anyone?
i have made a censor command that purges the words in that list i want the owner and mods to be the exception how do i do that?
using on_ready
!e
import random
number = random.randint(1, 1000)
player_name = input("Hello, What's your name?")
number_of_guesses = 0
print('okay! '+ player_name+ ' I am Guessing a number between 1 and 1000:')
while number_of_guesses < 100:
guess = int(input())
number_of_guesses += 1
if guess < number:
print('Your guess is too low')
if guess > number:
print('Your guess is too high')
if guess == number:
break
if guess == number:
print('You guessed the number in ' + str(number_of_guesses) + ' tries!')
else:
print('You did not guess the number, The number was ' + str(number))
lol
you could have an on_ready event load a message list but that isn't adviced since it triggers multiple times, How evr yoou can use an on_message event checking if the person who said the word has the permissions exclusive to the mod role
I need to create a "Muted" role, how to I set the perms?
@blazing beacon yea i can do a on_message yea
Exceptions i have to learn how to create
can anyone tell me when the api of discord will stop for python?
if message.author.has_role i think
Oh wait that'll work actually thanks a lot !!!!
@bot.command()
async def trade(ctx, *args):
output = ''
embed = discord.Embed(
title=" Trade Deal",
description=output,
color=0xff0000
)
embed.add_field(name="**Item**", value=f"{args[0]}")
embed.add_field(name="**Quantity**:", value=f"{args[1]}", inline = "False")
embed.add_field(name="**Contact Through**:", value=f"{args[2]}", inline = "False")
await ctx.send(embed=embed)
await ctx.message.delete()
``` right now the bot takes a word after sapce as a new arg but i want to add a symbol for starting a new arg
have something like
async def trade(ctx, *, arg):
args = arg.split(your_symbol)
# do stuff
alr thanks! its working
how to make the role on top of the list? I know I can't make it up bot's role, but if I put it on top, how to?
or "{}".format()
I know.
I was using F strings because it was used up by another user.
ok.
Of course, there are many ways to concatenate strings
help?
!d discord.Role.edit
await edit(*, reason=None, **fields)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Edits the role.
You must have the [`manage_roles`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Permissions.manage_roles "discord.Permissions.manage_roles") permission to use this.
All fields are optional.
Changed in version 1.4: Can now pass `int` to `colour` keyword-only parameter.
hm
ok but
Also
role = await guild.create_role(name="Muted", colour=discord.Colour(0xff0000))
await role.edit(position="")```
position?
0?
1?
Why don't you try it and see!
Also
role = discord.utils.get(ctx.guild.roles, name="Muted")
if role
#code if the role is there
if not role:
#code if the role isn't there
Sorry, you can't do that here!
I forgor π
how do i store message object in a file or database
You cant store python objects in databases
files? is there any other way?
But you can store an objects attributes
but suppose i want a to call a particular message
at any point even after i re run my bot
how do i do that
is there any way i can track how many times a command was used and make it the footer of an embed that sends as result of a command?
make a global variable and then keep on incrementing ?
Is ratelimiting an API not a good way if I need to see the ratelimit headers and can't find in docs? π
U gotta count it urself
damn
Make a botvar and += 1 on every time command is used
And with every use
i dont know how id do that, never used db before
That will reset when u restart the bot
database
U could use json for ur case, but u shouldnβt use json to store members and stuff
He dk how to use db
Rate limit headers should always be available in the response headers, so there is no reason to ratelimit on purpose
Ah, lemme check headers then. Thanks
hi, I want my discord bot to respond when you ping it but I am not able to understand how do i do it, I searched google too but didn't find anything.
!d discord.ext.commands.Bot.user
user```
Represents the connected client. `None` if not logged in.
!d discord.Member.mentioned_in
mentioned_in(message)```
Checks if the member is mentioned in the specified message.
if bot.user.mentioned_in(message) in an on_message event
@client.command()
@has_permissions(manage_roles=True, view_audit_log=True)
async def muterole(ctx):
try:
guild = ctx.guild
role = await guild.create_role(name="Muted", colour=discord.Colour(0xff0000))
all_roles = await guild.fetch_roles()
num_roles = len(all_roles)
await role.edit(position=(num_roles - 2))
embed = discord.Embed(color=0x000000)
embed.add_field(name="\u2705 Success!",
value=f"Successfully created <@&{role.id}> role.", inline=False)
await ctx.reply(embed=embed, mention_author=False)
except:
embed = discord.Embed(color=0x000000)
embed.add_field(
name="\u26d4 Error!", value="An error occurred.", inline=False)
await ctx.send(embed=embed)```
This works well as long as bot's role is on the top of the list. How to fix? I want it to create the role 1 position below the bot everytime, whatever bot's position is.
i want to check if the bot is mentioned in a message
hi i have a snipe feature in my bot, but it takes a really long time to show the result in some cases.
if i run it on my local machine it happens instantaneously
but when i run it on my raspi it takes a really long time but all the other bot features work fine
pycord
same as dpy but with slash commands and new features
thanks
no worries
is it an official module or a third party one like dpy?
third party
i see
i dont think there is any official module?
like, a python wrapper for discord API
that'd be made by discord
no
they like making it hell for devs why would they bother making a wrapper 
@client.event
async def on_message(message):
if client.user.mentioned_in(message):
await message.channel.send("https://c.tenor.com/fQ-R2Nw4OQMAAAAS/minecraft-who.gif")```
mhm
time consuming tho
but introducing questionable features isnt
i don't like the verified dev program at all its just pointless and makes it harder for new devs
exactly
please do help
yea and their eliminating bot prefixes in april 2022
i tried that, it didn't work
what bot prefix?
how did u run the bot
only slash commands
yea but ! isn't really a prefix command
from command line
That will be removed soon sadly
how
client = commands.Bot(command_prefix=">")
client or bot?
yea discord is making that a verified intent
bot
yea but that's just abstraction from discord.py or whatever
the API doesn't require any prefix
it listens to everything
and you will only be able to use slash commands from april 2022 onwards unless you get message content intents
@bot.event
async def on_message(message):
if bot.user.mentioned_in(message):
await message.channel.send("https://c.tenor.com/fQ-R2Nw4OQMAAAAS/minecraft-who.gif")```
async def on_message(message):
if client.user.mention in message:
await message.channel.send("hello there")```
in discord.NET for example by default you don't have a prefix, and you just do something like .StartsWith, prefix, if you want prefix
ye i wrote exactly that it didn't work
otherwise any text can be valid command
why is someone named mention
ohk, np thanks for the help :)
i want a to call a particular message
at any point even after i re run my bot
how do i do that
@ocean pasture try this
... make a command?
how to add a tag command which we can create our own tag for eg.
?tag
bot: Please Tell name of the tag
me- python
bot: Please tell the description of the tag
me- a language
bot: done!
?python
bot: a language
lol
wut
it works fine for me I'm sorry that didn't help
How
you need databases
read carefully :
how to make it
i did i didnt understand that grammar
i am sorry ! i dont know much english
nvm i did
look at sqlite3 or any database system you wanna use tutorial
then you wanna make a table with following columns (GuildID, tag, tag_description)
i recommend a database
So I have this purge command but it seems to be unable to not use the optional channel arg. when I give it a channel to purge it works fine but as soon as I don't input a channel (so that I can use the ctx.channel) it starts giving me errors that it can't purge a nonetype object```py
@commands.command(description = "Lets moderators remove mass amounts of msessages.", alaises = ["purge"], usage = "clear [members] [channel] <messages>")
@commands.bot_has_permissions(manage_messages = True)
@commands.has_permissions(manage_messages = True)
async def clear(self, ctx, targets: commands.Greedy[discord.Member], channel: Optional[discord.TextChannel], limit: int = 1):
channel if channel != None else ctx.channel
with ctx.channel.typing():
def _check(message):
return not len(targets) or message.author in targets
if 0 < limit <= 100:
await ctx.message.delete()
deleted = await channel.purge(limit = limit, after = datetime.utcnow()-timedelta(days = 14), check = _check)
await ctx.send(f"Deleted **{len(deleted)}** messages.", delete_after = 5)
await ctx.author.send(f"You just deleted **{len(deleted)}** messages in {channel.mention}.")
else:
await ctx.send("The limit provided is not within acceptable bounds.")```
i got this
class MySource(menus.ListPageSource):
async def format_page(self, menu, entries):
return entries
class MyMenu(menus.MenuPages,inherit_buttons = False):
async def finalize(self,timed_out):
try:
await self.ctx.message.add_reaction(":check:")
except:
pass
@menus.button(emoji=':first:')
async def go_to_first_page(self, payload):
await self.show_page(0)
@menus.button(emoji=':pre:')
async def go_to_previous_page(self,payload):
await self.show_checked_page(self.current_page - 1)
@menus.button(emoji=':stop:')
async def stop_pages(self, payload):
await self.ctx.message.add_reaction(":check:")
self.stop()
@menus.button(emoji=':nex:')
async def go_to_next_page(self, payload):
await self.show_checked_page(self.current_page + 1)
@menus.button(emoji=':last:')
async def go_to_last_page(self, payload):
await self.show_page(self._source.get_max_pages() - 1)
but when the author react it wont remove the authors reaction after going to that page
make channel purges happen if not channel is None
@solar kelp how do i make a command to store a particular message and call it when needed
Can you try channel = channel or ctx.channel instead?
using databases
yeah already tried that and got the same error
database can't store objects though
how do i fetch a message using id
oops
i'll need text channel too
!d discord.TextChannel.fetch_message
await fetch_message(id)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Retrieves a single [`Message`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Message "discord.Message") from the destination.
This can only be used by bot accounts.
for that
then store both
hmm okay
how about check if the channel is not None if it is none channel = ctx.channel?
so like this, I think if I'm understanding you correctly py if channel != None: await channel.purge(xyz) else: await ctx.channel.purge
or just
if channel:
channel_ = channel
if not channel:
channel_ = ctx.channel
channel = channel or ctx.channel?
he tried that
yeah still not sure why that didn't work. not sure if it's something to do with the fact that the channel is the second arg or somehting
do that line and after it print channel
how to make bot work in thread
it have all perms but dont work
ur using 2.0?
i got this
class MySource(menus.ListPageSource):
async def format_page(self, menu, entries):
return entries
class MyMenu(menus.MenuPages,inherit_buttons = False):
async def finalize(self,timed_out):
try:
await self.ctx.message.add_reaction(":check:")
except:
pass
@menus.button(emoji=':first:')
async def go_to_first_page(self, payload):
await self.show_page(0)
@menus.button(emoji=':pre:')
async def go_to_previous_page(self,payload):
await self.show_checked_page(self.current_page - 1)
@menus.button(emoji=':stop:')
async def stop_pages(self, payload):
await self.ctx.message.add_reaction(":check:")
self.stop()
@menus.button(emoji=':nex:')
async def go_to_next_page(self, payload):
await self.show_checked_page(self.current_page + 1)
@menus.button(emoji=':last:')
async def go_to_last_page(self, payload):
await self.show_page(self._source.get_max_pages() - 1)
but when the author react it wont remove the authors reaction after going to that page
tried that same thing, do I need to be type hinting channel as optional?channel: Optional[discord.TextChannel]or could I get away with removing optional?
what's the full traceback?
Aren't default emojis supposed to be unicode
if you remove optional, since you have a limit arg after, it'll mess things up if you put channel: discord.TextChannel = None. unless you make it the last arguement though
A paginator i see
i'll try that
it should work
yeah that didn't work, i'll try it a few other ways again
i really don't know, it's really odd
tb?
Is there any error
i got it to print ctx.channel
if no channel is provided
well yeah but it's coming from another cog with a on_message event. the last error from this cog ispy ERROR:cogs.error_handler:AttributeError: 'NoneType' object has no attribute 'purge' (In clear) Traceback: File "/home/snowyjaguar/.local/lib/python3.8/site-packages/discord/ext/commands/core.py", line 85, in wrapped ret = await coro(*args, **kwargs) File "/home/modmail/cogs/moderation.py", line 177, in clear deleted = await channel.purge(limit = limit, after = datetime.utcnow()-timedelta(days = 14), check = _check)
https://trolled.cc/βββββββββββββββββββββββββββββββ first one is context channel and 2nd one is when i put a channel
I'm confused, that shouldn't be happening...

what's the current code?
So you are using commands greedy for member as well right?
i think i'll try to diagnose the other cogs error to see if maybe it's having a knock on effect
yep
@flat solstice https://trolled.cc/ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ is this what are you trying to achieve
no errors
yeah i want it to clear msgs with no errors. it works fine for the most part, it accepts multiple members (β ), it accepts the number of msgs to clear (β ) and it acepets the channel arg (β ). it also works if I don't provide any members (β ) or if i don't provide a number of msgs (β ) but it just won't work without me inputting a channel(β)
alr ill send u the new code and try it
@commands.command(description = "Lets moderators remove mass amounts of msessages.", alaises = ["purge"], usage = "clear [members] [channel] <messages>")
@commands.bot_has_permissions(manage_messages = True)
@commands.has_permissions(manage_messages = True)
async def clear(self, ctx, targets: commands.Greedy[discord.Member], channel: Optional[discord.TextChannel], limit: int = 1):
if channel is None:
channel = ctx.channel
else:
channel = channel
with ctx.channel.typing():
def _check(message):
return not len(targets) or message.author in targets
if 0 < limit <= 100:
await ctx.message.delete()
deleted = await channel.purge(limit = limit, after = datetime.utcnow()-timedelta(days = 14), check = _check)
await ctx.send(f"Deleted **{len(deleted)}** messages.", delete_after = 5)
await ctx.author.send(f"You just deleted **{len(deleted)}** messages in {channel.mention}.")
else:
await ctx.send("The limit provided is not within acceptable bounds.")```
i'm currently troubleshooting a different issue to see if it's having a knock on effect
I think this is an okay section? I was wondering if anyone had thoughts on a typical per hour rate for a bot dev? I have done some work in the past, but I had someone lately what my per hour rate is and I don't know what is fair/average. Any thoughts?

i don't why it would as it's a on_message event in a completely different cog
What should be done? I did not understand
!d discord.VoiceClient.loop
The event loop that the voice client is running on.
its an event loop, not a song loop
anyone know the cause? i typed "mesg" ```message, user = await client.wait_for("message", timeout=60.0)
TypeError: cannot unpack non-iterable Message object
guys does anyone khnow how to make a command that only a user can use like i put his id in a code and if someone else try to use it it will say sorry you are not allowed
Hey there,
my bot sometimes crashes after some hours of work, what might be the reason?
This is the error which comes with the crash:
Traceback (most recent call last):
File "main.py", line 587, in <module>
client.run(TOKEN)
File "/home/rsam/.local/lib/python3.8/site-packages/discord/client.py", line 723, in run
return future.result()
File "/home/rsam/.local/lib/python3.8/site-packages/discord/client.py", line 702, in runner
await self.start(*args, **kwargs)
File "/home/rsam/.local/lib/python3.8/site-packages/discord/client.py", line 666, in start
await self.connect(reconnect=reconnect)
File "/home/rsam/.local/lib/python3.8/site-packages/discord/shard.py", line 445, in connect
raise item.error
File "/home/rsam/.local/lib/python3.8/site-packages/discord/shard.py", line 151, in worker
await self.ws.poll_event()
File "/home/rsam/.local/lib/python3.8/site-packages/discord/gateway.py", line 555, in poll_event
msg = await self.socket.receive(timeout=self._max_heartbeat_timeout)
File "/home/rsam/.local/lib/python3.8/site-packages/aiohttp/client_ws.py", line 216, in receive
raise RuntimeError("Concurrent call to receive() is not allowed")
RuntimeError: Concurrent call to receive() is not allowed
Unclosed client session
client_session: <aiohttp.client.ClientSession object at 0x7fcefde838b0>
with dpy being archived now, what's the new go-to? Should i keep developing with dpy alongside a discord commands library?
I'll look into it. What's the whole deal with slash commands? I understand that I should be changing to those instead of how we did it before?
ah,
danny did a good job explaining it https://gist.github.com/Rapptz/4a2f62751b9600a31a0d3c78100287f1
well it was an example in here so i thought
https://discordpy.readthedocs.io/en/stable/api.html#discord.Client.wait_for
but thanks
will i be able to use pycord in my existing discord.py code without any changes?
Please tell me how to fix it?
yeah thats for reactions (reaction, user==..)
how to add embeds and buttons in one command
I think so, but it'll show an error on start-up if commands.scope is not in the bot
i want to add just the button in vote i dont want any message
Guys, is there a way to record the number of warns of each user in a CSV file?
wdym by commands.scope
What's the command to get the python bot to convert emojis to unicode
Has anyone created a bot with a timer?
!charinfo
like?
wdym
Like it times you
Someone has
times what
I'm going to make a discord bot that tests you on your typing speed so im wondering of someone has made a bot with a timer built in
use asyncio
Also using another bot with your bot can be hectic
since you cant really trigger another bot with your bot
Make sure to send the test in an embed so they can't copy it
Just some advice
make the sentence a button?
Oh no I wont I was just wondering if it was possibl
u can use asyncio
u cant copy in an embed?
I dont think so
Depends what element u use
I can copy the whole info of the weather
maybe
Can you copy description
Oh well good to know then
is there a way to record the number of warns of each user in a CSV file?
hello, i'm making a bot in which i need to get who all is mentioned in an embed sent by the bot so that when he reacts on that messsage, it is deleted . any suggestions?
can i change the placeholder in on_timeout ?
use the on_reaction event
and to keep things simple use a purge
hi anyone help me to create a chat bot api pls
for discord or help me find how to do
Hello, I have a script that allows me to retrieve the roles of a channel, only, there is a problem when there is a user who has rights separately from a role, how to do it ?
where am i going wrong with adding these roles to the msg author? I don't seem to be receiving any errors in discord or in my logs fiepy for role in data[17]: mistakes_roles = self.bot.get(message.guild.roles, id = role) await message.author.add_roles(mistakes_roles, reason = f"{message.author} got the number wrong in {message.channel.name} and so has temporarily been given this role.")
My error :
TypeError: '<' not supported between instances of 'Member' and 'Role'
How is member lower than role
idk
This is directly the case when a member is inserted in the permissions of a channel
how can i check if message is str?
message.content == str```
thx
uhm thats not work
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.
if server_req.content == str:
await ctx.reply(':x_~1: The Message Content must be an integer.')
return``` and its not returning
You forgot type().
type(content) == str

@dapper cobalt do you know what i've done wrong here?
where are you getting server_req from?
A message's content is always string tho.
server_req = await self.bot.wait_for('message', check=check, timeout=60.0)
ah okay
if type(server_req.content) == str and server_req.isdigit() == False
okay
.isdigit() checks if the input given is an integer even if it's inside strings.
My bad, server_req**.content**
.content is missing ig
Yes.
what libraries is everyone using at the moment?
i'm still using d.py 1.7 but i think i'll be moving to hiriki when stable drops in november or december
helpppp
will it work
Soo
I have this lil project in mind
I wanna re-write dpy from scratch
Like use my own classes and shit
But I don't have the knowledge about discord API
And I don't wanna copy paste dpy's code either
Anyone got a suggestion for what I should do?
u can learn py
and also u dont need to edit whole code just make a some which need to get eddited
guys i need to make bot which is playing audio files but i don't know how to use ffmpeg, I was trying to do this: ```python
@client.command(pass_context = True)
async def clip(ctx):
play = create_ffmpeg_player("one.wav")
play.start()
Hello i would like to add in my command a code that makes only a user can use the command
guys will it work
whhy this is not working
it is editing the loop edits :/
but not editing the last edit :/
Hello i would like to add in my command a code that makes only a user can use the command
(i need a code pls if someone khnows)
pls
this edit is not working
pls help me
other edits are working :/
I meant the discord API stuff ofc
I have a decent knowledge of Python
@tawdry perch good
just what api u use to
@tawdry perch where are you from
help mee same code but error
most objects are just going to require you to look at the retruned json
for methods it should be pretty simple
Cause:
- The code is a little hard to read
- Most people who are forking it suck ass at doing it, which makes me who plans to not half-ass it not be recognised
Please anyone help me the line marked is not working other edits are working
@tawdry perch it's for me
I mean there's only one API that allows you to write a wrapper for bot coding
ohk
anyoneeeeeee
pls
use dpy as a reference
How I can go to group message
i did that the first time i made my own wrapper
no one ?
Hello i would like to add in my command a code that makes only a user can use the command
can someone help me ^^
Appreciate the help
anyone know how the bots do this now?
I didnt understand...
Slash commands and buttons
hey can someone explain to me the difference between role raw reaction and normal reaction
normal reaction gets called only when the message containing the reaction is cached
@commands.command()
async def roll(self, ctx, value = 10 , * , useless = None):
await ctx.send(random.randint(0, value))
ty
like I have this code I want to change it like only a user can do it
@bot.command()
async def setactivity(ctx, user_id : int, *reason, name):
await bot.change_presence(activity=discord.Game(name=name))
embed=discord.Embed(title="Activity", description="L'activitΓ© du bot a bien Γ©tΓ© changΓ© ! " , color=0xf50000)
await ctx.send(embed=embed)
raw reaction gets called everytime regardless
how do i make the command work when user inputs $roll text
this
a normal on_reaction event depends upon bot cache and on_raw_reaction doesn't. So when you react on an on_reaction event , it may not triggered because the cache wasn't properly or role was not present in the cache, but raw reaction event will get called everytime
what's cached, sorry if im asking stupid qs
in the bot's internal storage or something like that
the code is working actually but i just need to add the thing that i said i didnt khnow how to dit
When ever you run your code, bot has its own internal cache and data like roles guilds members are loaded in the cache when the bot starts
Tho I wonder, how that embed was possible
I have never seen fields like that
image manipulation
ah makes, sense why it doesn't detect reactions added on msgs after the bot is run
Or maybe a description
and the image field
That's an image?
yeah i see, but how can i do it like in the #do smth i put my code ?
probably
Damn
Yeah you are right
That's what I thought, how was embed fields possible like, turns out it's an image
Or you can make a command check for this
Yeah that happens
!checks
!d discord.ext.commands.check
discord.ext.commands.check(predicate)```
A decorator that adds a check to the [`Command`](https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command") or its subclasses. These checks could be accessed via [`Command.checks`](https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.Command.checks "discord.ext.commands.Command.checks").
These checks should be predicates that take in a single parameter taking a [`Context`](https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.Context "discord.ext.commands.Context"). If the check returns a `False`-like value then during invocation a [`CheckFailure`](https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure") exception is raised and sent to the [`on_command_error()`](https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.on_command_error "discord.on_command_error") event.
If an exception should be thrown in the predicate then it should be a subclass of [`CommandError`](https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.CommandError "discord.ext.commands.CommandError"). Any exception not subclassed from it will be propagated while those subclassed will be sent to [`on_command_error()`](https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.on_command_error "discord.on_command_error").
Read this, asta, if you want multiple commands like that
Wait that's your ID?
And you are the owner of the bot?
871460961230422046
Comparison don't work like that.. You can use checks
!d discord.ext.commands.is_owner
discord.ext.commands.is_owner()```
A [`check()`](https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") that checks if the person invoking this command is the owner of the bot.
This is powered by [`Bot.is_owner()`](https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.Bot.is_owner "discord.ext.commands.Bot.is_owner").
This check raises a special exception, [`NotOwner`](https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.NotOwner "discord.ext.commands.NotOwner") that is derived from [`CheckFailure`](https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure").
yeah
Yeah use that check
871460961230422046
I guessed that's your ID
how x) i'm a beginner i dont khnow actuelly how to use it lol
Its much better to use this than a bunch if statements
Its a decorator
oh okay, what actually need to do add an another person besides me to use the command
me the owner of the bot, and another person
how to make a bot remove a raw reaction
remove a reaction?
how
the raw one not cached
!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/stable/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/stable/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/stable/api.html#discord.abc.Snowflake "discord.abc.Snowflake") abc.
Set owner_ids is Bot constructor, like you added command_prefix and intents, do the same with owner_ids, and pass a list of ids
^
bot = commands.Bot(command_prefix="?", owner_ids = [])```
@slate swan
You need to pass a list of ids
As Akshu said
I'm a bit annoying, i did understand this thanks but i need it only in one command x)
Its basically a kwarg that you pass a list of user ids that you want them to be bot owners
@commands.Cog.listener()
async def on_raw_reaction_add(self,payload):
emoji=payload.emoji
member=payload.member
await remove_reaction(emoji,member)
will this work?
a few commands not all the commands but few ones
Yes you can set owner_ids in Bot decorator, and then wherever you;ll use @commands.is_owner deco, it'll use those ids
oh
It would be payload.member_id
If you don't use this deco, it'll work same as normal commands
Thx guys !
Can someone tell me where I'm going wrong with this?py roles = [] for role in data[17]: # <---- a list of roles in my db mistakes_roles = message.guild.get_role(role) roles.append(mistakes_roles) await message.author.add_roles(roles, reason = f"{message.author} got the number wrong in {message.channel.name} and so has temporarily been given this role.", atomic = True)it keeps returning this errorpy Traceback (most recent call last): File "/home/snowyjaguar/.local/lib/python3.8/site-packages/discord/client.py", line 343, in _run_event await coro(*args, **kwargs) File "/home/modmail/cogs/miscellaneous.py", line 57, in on_message await message.author.add_roles(roles, reason = f"{message.author} got the number wrong in {message.channel.name} and so has temporarily been given this role.", atomic = True) File "/home/snowyjaguar/.local/lib/python3.8/site-packages/discord/member.py", line 777, in add_roles await req(guild_id, user_id, role.id, reason=reason) AttributeError: 'list' object has no attribute 'id'the add_roles needs role objects right? I can't just pass in a load of role ID's striaght from my db?
add_roles don't take a list iirc, just pass them as args
unwrap your list using asterick *
Add_roles take a role object and it doesn't take a list
payload has attribute member
okay so i'll need to make them role objects from the ID's, is this the correct way? py mistakes_roles = message.guild.get_role(role)
Eh
is there a way to remove only on the particular message
!d discord.RawReactionActionEvent
class discord.RawReactionActionEvent```
Represents the payload for a [`on_raw_reaction_add()`](https://discordpy.readthedocs.io/en/stable/api.html#discord.on_raw_reaction_add "discord.on_raw_reaction_add") or [`on_raw_reaction_remove()`](https://discordpy.readthedocs.io/en/stable/api.html#discord.on_raw_reaction_remove "discord.on_raw_reaction_remove") event.
Yeah it has member
But optional
You need to get the message ID
Only if it's cached
And then remove the roles
yeah then will it work?
You need to get message object through the message ID
yeah
!d discord.TextChannel.fetch_message
await fetch_message(id)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Retrieves a single [`Message`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Message "discord.Message") from the destination.
This can only be used by bot accounts.
ill need channel id too
you need to get the message object and then add and remove roles
You can make config system
what's that
For what you need message object?
Basically make a config file that stores your channel and message ID
to remove the reaction
Like a simple json file
oh
Yeah you can do this too
Wait, i'm blank, what's partial message
Although an API call would be more precise and has a higher chance of success
oh
Another question if i want it to send a message if the user is not owner what do i do ?
It will raise an error
You are not the owner of the bot
so basically i'm making a reaction roles event
and i want to reset the reaction counter back to 1 so i want to remove the reaction of the user
You can make an error handler
That catches that error
It would be commands.NotOwner
Exception
!d discord.ext.commands.NotOwner
exception discord.ext.commands.NotOwner(message=None, *args)```
Exception raised when the message author is not the owner of the bot.
This inherits from [`CheckFailure`](https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure")
@slate swan
this?py for role in data[17]: mistakes_roles = message.guild.get_role(role) await message.author.add_roles(*mistakes_roles, reason = f"{message.author} got the number wrong in {message.channel.name} and so has temporarily been given this role.", atomic = True)or am I still doing it wrong?
Actually discord.Object won't work, since it's a method of message 
Tias
!d discord.PartialMessage
class discord.PartialMessage(*, channel, id)```
Represents a partial message to aid with working messages when only a message and channel ID are present.
There are two ways to construct this class. The first one is through the constructor itself, and the second is via [`TextChannel.get_partial_message()`](https://discordpy.readthedocs.io/en/stable/api.html#discord.TextChannel.get_partial_message "discord.TextChannel.get_partial_message") or [`DMChannel.get_partial_message()`](https://discordpy.readthedocs.io/en/stable/api.html#discord.DMChannel.get_partial_message "discord.DMChannel.get_partial_message").
Note that this class is trimmed down and has no rich attributes.
New in version 1.6...
ah okay okay another question can i make a command like +owner that automaticly adds owners with this command
!d discord.TextChannel.get_partial_message
get_partial_message(message_id)```
Creates a [`PartialMessage`](https://discordpy.readthedocs.io/en/stable/api.html#discord.PartialMessage "discord.PartialMessage") from the message ID.
This is useful if you want to work with a message and only have its ID without doing an unnecessary API call.
New in version 1.6.
like +owner add name#12354
# This decorator is the one used for error handling a specific command.
# It consists of 2 parts: the command name, and the attribute "error".
# Do keep in mind that you do not use the command name, but the function name that defined that command.
@kick.error
# This is the function that will trigger if the command specified on the decorator panics.
# It must be named commandname_error, and it takes 2 parameters: Context and Error.
# Unlike the decorator, this uses the actual command name.
async def kick_error(ctx, error):
# isinstance() is a builtin function to check for type equality between a value and a type
# In this case, we are using it to check if the error is the one specified on the second parameter.
if isinstance(error, commands.MissingPermissions):
# This is the code that will execute if the error that happened on the command matched our expectation.
# In this case we notify the user that they lack the permission to use this command.
await ctx.send(f'{ctx.author.mention} is missing the "Kick Members" permission.')
# If the error doesn't match our expectations, we raise it, that way we can see the traceback and debug the code accordingly.
else:
raise(error)β
for global error handling you can do:
# client being the var you asigned the bot to
@client.event
async def on_command_error(ctx, error):
...β
in the main file```
Then you would need a custom check for that
And a database
That stores the user IDS
I don't think owner_ids can be changed at runtime, you can save them in some file and access them on other run
Yeah it can't
well, it won't be really complicated
No, just make a decorator returning commands.check's return value
But it would a bit hard if you don't know what databases are
yeah i didnt touch to a database in my life
You could use a json file (which is a not a database)
And don't load the json on every check, instead cache it. Or learn databases, they will be so helpful
Waw i'm really confused right khnow how can i make a custom check like code it and put the json file waw idk x)
!d discord.ext.commands.check
discord.ext.commands.check(predicate)```
A decorator that adds a check to the [`Command`](https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command") or its subclasses. These checks could be accessed via [`Command.checks`](https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.Command.checks "discord.ext.commands.Command.checks").
These checks should be predicates that take in a single parameter taking a [`Context`](https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.Context "discord.ext.commands.Context"). If the check returns a `False`-like value then during invocation a [`CheckFailure`](https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure") exception is raised and sent to the [`on_command_error()`](https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.on_command_error "discord.on_command_error") event.
If an exception should be thrown in the predicate then it should be a subclass of [`CommandError`](https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.CommandError "discord.ext.commands.CommandError"). Any exception not subclassed from it will be propagated while those subclassed will be sent to [`on_command_error()`](https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.on_command_error "discord.on_command_error").
do you mean yes? or somehting else
Tias means Try it and see
Try it and see
ahn
like where do i put it
and how do i put this in a command
and make a json that stores idk what x)
You need open your json file and create a dict and then dump it into the json file
In this Python Programming Tutorial, we will be learning how to work with JSON data. We will learn how to load JSON into Python objects from strings and how to convert Python objects into JSON strings. We will also see how to load JSON from a file and save those Python objects back to files. Let's get started...
The code from this video can be ...
thx
If you don't know what that is, then you should really learn basic pythons first properly
yeah i will try
Discord.py is a very advanced library
yeah i see
You won't be able to go much further if you don't know python basics properly
so no?py Traceback (most recent call last): File "/home/snowyjaguar/.local/lib/python3.8/site-packages/discord/client.py", line 343, in _run_event await coro(*args, **kwargs) File "/home/modmail/cogs/miscellaneous.py", line 55, in on_message await message.author.add_roles(*mistakes_roles, reason = f"{message.author} got the number wrong in {message.channel.name} and so has temporarily been given this role.", atomic = True) TypeError: add_roles() argument after * must be an iterable, not Rolebeen at this for 2 or so hours now and I'm just not sure what needs to be changed for it to work
mistakes_roles is a single role object, you need to append it to some list and use that
some could just use *data[17]? which is the list it pulls from the db
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/stable/api.html#discord.Role "discord.Role")s.
You must have the [`manage_roles`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Permissions.manage_roles "discord.Permissions.manage_roles") permission to use this, and the added [`Role`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Role "discord.Role")s must appear lower in the list of roles than the highest role of the member.
Yeah I think you can do that
Or if not, make discord.Object for each id from the ids, and append them and use
i take this means not.py Ignoring exception in on_message Traceback (most recent call last): File "/home/snowyjaguar/.local/lib/python3.8/site-packages/discord/client.py", line 343, in _run_event await coro(*args, **kwargs) File "/home/modmail/cogs/miscellaneous.py", line 55, in on_message await message.author.add_roles(*data[17], reason = f"{message.author} got the number wrong in {message.channel.name} and so has temporarily been given this role.", atomic = True) File "/home/snowyjaguar/.local/lib/python3.8/site-packages/discord/member.py", line 777, in add_roles await req(guild_id, user_id, role.id, reason=reason) AttributeError: 'int' object has no attribute 'id'
and how would I make a role obj? I tried that earlier and didn't get anywhere
why any member.status return me offline?
are you getting the member and presence intents?
intents = discord.Intents.default()
intents.members = True
you might also need the presence intent
wdym?
intnets.presences = True
data = [123, 456] # soem list with ids you got from your db
tmp = [] # some temp list to append objects in
for id in data:
tmp.append(discord.Object(id)) # we make discord.Object here with ids and append it to the list
await ... # now add roles by unpacking tmp
thank you very much, it's working now
how do i check whats in the message in the check parameter of client.wait_for('message')
This is not true?
Its not a beginner library for sure, but it's definitely not very advanced either
does anyone have a code for an antispam pls
!custom-cooldown
Cooldowns in discord.py
Cooldowns can be used in discord.py to rate-limit. In this example, we're using it in an on_message.
from discord.ext import commands
message_cooldown = commands.CooldownMapping.from_cooldown(1.0, 60.0, commands.BucketType.user)
@bot.event
async def on_message(message):
bucket = message_cooldown.get_bucket(message)
retry_after = bucket.update_rate_limit()
if retry_after:
await message.channel.send(f"Slow down! Try again in {retry_after} seconds.")
else:
await message.channel.send("Not ratelimited!")
from_cooldown takes the amount of update_rate_limit()s needed to trigger the cooldown, the time in which the cooldown is triggered, and a BucketType.
thx !
like if i have a quiz, i want to check of the message is the correct answer and wanted to use the check parameter of the function
do you khnow how to make a command that activate and disable the antispam ?
Maybe make it with a bot var
how can i do it
I am from my phone so I can't make an example sorry
You can use a database to save states, and on startup, fetch and cache them. Check if it's enabled or not, and do the action
Botvar is fine, but it resets on every run.. so
If you need botvar ```py
bot = commands.Bot(...)
bot.is_antispam_enabled = True
in event, check if it is true or false
why is that better than a global var
Because you an also access it in cogs
oh nice
so like in different cogs
Globals are evil
I prefer not using them, also what NIR said
!bot-var
Python allows you to set custom attributes to most objects, like your bot! By storing things as attributes of the bot object, you can access them anywhere you access your bot. In the discord.py library, these custom attributes are commonly known as "bot variables" and can be a lifesaver if your bot is divided into many different files. An example on how to use custom attributes on your bot is shown below:
bot = commands.Bot(command_prefix="!")
# Set an attribute on our bot
bot.test = "I am accessible everywhere!"
@bot.command()
async def get(ctx: commands.Context):
"""A command to get the current value of `test`."""
# Send what the test attribute is currently set to
await ctx.send(ctx.bot.test)
@bot.command()
async def setval(ctx: commands.Context, *, new_text: str):
"""A command to set a new value of `test`."""
# Here we change the attribute to what was specified in new_text
bot.test = new_text
This all applies to cogs as well! You can set attributes to self as you wish.
Be sure not to overwrite attributes discord.py uses, like cogs or users. Name your attributes carefully!
Oh nice, I actually need to learn c# for school for the next 3 years
Me who compiles python to c and generate massive c files 

I'm lazy to learn a new lang, maybe next kotlin

c# is basically just betterjava

What IDE you using? @slate swan
kotlin is just easyjava 
VSC
How can you crate a project of c# using VSC?
You on windows
You need a compiler installed and something.. I forgot tbh
I made a cpp file and a compiled it using mingw
since nobody is asking anything, maybe we can talk about this lmao
ye
So I navigate to some parent dir, and than I need to type in terminal?
yeah
when you've installed .net core
does anyone know how to change the names of all channels at once?
iterate through guild.channels with a for loop
then use channel.edit()
Changing channel names have some strict rate limit iirc, stil wanna do? Loop th- ^^
π thank you
for fast help guys
How to make a slash command if you are using cogs?
How can I see if it's downloaded?
VSC isn't great for C#, but Visual studio exists and its very much meant for C# development
if dotnet works it's downloaded
I need an IDE which is good for html css and js(web development) and c#
School π
Unity
await message.add_reaction(u"\u2705")
await message.add_reaction(u"\U0001F6AB")
try:
reaction, user = await bot.wait_for("reaction_add", check=lambda reaction, user: user == ctx.guild.default_role and reaction.emoji in [u"\u2705", u"\U0001F6AB"], timeout=80000.0)
except asyncio.TimeoutError:
await channel.send("De request is niet snel genoeg beantwoord. De persoon is ingelicht.")
await ctx.send(f"{ctx.author.mention} uw verzoek is helaas verlopen, gelieve een opnieuw te sturen.")
else:
if reaction.emoji == u"\u2705":
channel=bot.get_channel(885597230273286154)
await channel.send("Goedgekeurd!")
else:
channel=bot.get_channel(885597230273286154)
await channel.send("Ouch, afgekeurd")```
I dont get an error or output, but I want everyone to be able to add reactions and then it would reacht
Discord made the code really weird
async def setupserverstats(self, ctx):
guild = str(ctx.guild.id)
try:
channels_dict = self.serverstats[guild]
except KeyError:
channels_dict = {}
permrole = discord.utils.get(ctx.guild.roles, name="@everyone")
date_format = "%d %b %Y"
est = discord.utils.get(guild.voice_channels, name=f"Est: {guild.created_at.strftime(date_format)}", category=None)```
error : str obj has no atrr voice_channels
To get the @everyone role you can do ctx.guild.default_role
And your guild is assigned to str(ctx.guild.id) so doing guild.voice_channels is doing p.e. '267624335836053506'.voice_channels. You need a discord.Guild instance, such as ctx.guild
But voice_channels is an attribute of discord.Guild
So you have to do it on ctx.guild in this case
@client.command()
Not only
You need to use the commands extension
And not discord.Client
!d discord.ext.commands.Bot https://vcokltfre.dev/
A tutorial on how to use discord.py to create your own Discord bot in Python, written to fix the flaws of many other popular tutorials.
class discord.ext.commands.Bot(command_prefix, help_command=<default-help-command>, description=None, **options)```
Represents a discord bot.
This class is a subclass of [`discord.Client`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Client "discord.Client") and as a result anything that you can do with a [`discord.Client`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Client "discord.Client") you can do with this bot.
This class also subclasses [`GroupMixin`](https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.GroupMixin "discord.ext.commands.GroupMixin") to provide the functionality to manage commands.
Hi all, So I'm trying to make a starboard with a raw_reaction_add event. I want my db to log the id of the original msg, the amount of stars a msg has and the id of the msg the bot posts to the starboard. I have it in a state where the bot is sending the msg to the channel but it is not tracking the count of the stars (i.e the amount of each star_reactions on the msg. This means that the bot just keeps sending the same post msg over and over again without the footer.
This is not the behaviour I want, what I want to happen is that each time the bot posts a new msg then it adds the id of the og msg to the db and adds the footer with the number of the 'stars` the msg has received. if the id of the og msg already exists in the db then i want the bot to update the footer to reflect the new count of the 'star' reactions. Can someone point out where i'm going wrong? https://sourceb.in/BZHz1WjPhZ
hey how can i make it so when a specific discord ID says something specific it runs a function
how can i loop this command?
Use tasks loops
suggestion:
use aioshttp
Hello world
on_message(message):
Can anybody tell me why this linepy await post.edit(embed = embed.set_footer(text = f"Stars: {str(star_count)}))is giving me a py SyntaxError: f-string: invalid syntaxThis is my code: https://sourceb.in/bV0QuimQ96
try removing the f string
nvm that won't work
yeah that just gave me a py SyntaxError: EOL while scanning string literal
asked elsehere, i was missing a " at the end of the str
hey
client = commands.Bot(command_prefix='.')
async def on_ready():
print ('Bot Is ready')
@client.event
async def on_message(ctx):
if ctx.author.id==208282482171314176:
await ctx.send("you're cute")
why doesn't this work
what does that mean
@quaint axle.event
oh
before on_ready
oh thats neat
whoever's name is client, I'm not sorry
yeah now it says the bot is ready in console
but it's still not doing what i want it to do
error?
line 16, in on_message
await ctx.send("you're cute")
AttributeError: 'Message' object has no attribute 'send'
Try ctx.channel.send
ty
How do I correctly count reactions on a msg? I am currently doingpy star_reactions = ["β", ":questionable_star:", ":star_struck:", ":star2:", ":StarPiece:", ":purple_star:"] for star in star_reactions: if payload.emoji.name == star: stared_message = await self.bot.get_channel(payload.channel_id).fetch_message(payload.message_id) if stared_message.id != stars[0]: reaction_count += stared_message.reactions.count # Adding the count of the star reactions to the count embed.set_footer(text = f"Stars: {str(reaction_count)}") post = await starboard.send(embed = embed) # Sending the embed to the starboard async with self.bot.pool.acquire() as conn: await conn.execute("UPDATE starboard SET stars=$1 WHERE id=$2", reaction_count, payload.message_id) await conn.execute("UPDATE starboard SET post=$1 WHERE id=$2", post.id, payload.message_id) else: star_count = stars[1] + 1 post = await self.bot.get_channel(starboard.id).fetch_message(stars[2]) # Getting the the post msg as a message object await post.edit(embed = embed.set_footer(text = f"Stars: {str(star_count)}")) async with self.bot.pool.acquire() as conn: await conn.execute("UPDATE starboard SET stars=$1 WHERE id=$2", star_count, payload.message_id)
but I don't think that is right as I keep getting this errorpy Ignoring exception in on_raw_reaction_add Traceback (most recent call last): File "/home/snowyjaguar/.local/lib/python3.8/site-packages/discord/client.py", line 343, in _run_event await coro(*args, **kwargs) File "/home/modmail/cogs/events.py", line 322, in on_raw_reaction_add post = await self.bot.get_channel(starboard.id).fetch_message(stars[2]) # Getting the the post msg as a message object File "/home/snowyjaguar/.local/lib/python3.8/site-packages/discord/abc.py", line 1132, in fetch_message data = await self._state.http.get_message(channel.id, id) File "/home/snowyjaguar/.local/lib/python3.8/site-packages/discord/http.py", line 254, in request raise HTTPException(r, data) discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body In message_id: Value "None" is not snowflake.which is caused by the post id not being in the db (I think) and it's not in the dm bc it can't send it bc it isn't counting correctly
@tasks.loop(minutes = 10)
async def counter(self):
if path.exists("./botFiles/stats.json"):
with open("./botFiles/stats.json", "r") as f:
channels_dict = json.load(f)
for key in self.serverstats.keys():
guild = key
guild = str(guild)
try:
statschannels = self.serverstats[guild]["statschannels"]
except KeyError:
statschannels = {}
category = discord.utils.get(guild.categories, name="STATS")```
str obj has not att categories
message.channel
Yes
!d discord.on_message
discord.on_message(message)```
Called when a [`Message`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Message "discord.Message") is created and sent.
This requires [`Intents.messages`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Intents.messages "discord.Intents.messages") to be enabled.
Warning
Your botβs own messages and private messages are sent through this event. This can lead cases of βrecursionβ depending on how your bot was programmed. If you want the bot to not reply to itself, consider checking the user IDs. Note that [`Bot`](https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.Bot "discord.ext.commands.Bot") does not have this problem.
how do u print the bots token using an eval cmd
why?
because I want to use it on my bot when I want to get my bots token faster
@kindred epoch ^^
bot.http.token
ah thanks ill give it a try
Thanks it worked
pls beg
it's okay, I'm not sorry, either. It's been my name for years. I'm used to it at this point
!d discord.Guild
class discord.Guild```
Represents a Discord guild.
This is referred to as a βserverβ in the official Discord UI.
`x == y` Checks if two guilds are equal.
`x != y` Checks if two guilds are not equal.
`hash(x)` Returns the guildβs hash.
`str(x)` Returns the guildβs name.
How would I get a commands default cooldown length from the command object? With discord.py
yeah I dont know the class location
however the class would be the first place to check for a cooldown attribute
Ok
hello i need help with my code
Don't ask to ask.
im trying to display an image from an api an im getting this error:
Command raised an exception: HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body In embeds.0.thumbnail.url: Scheme "['https" is not supported. Scheme must be one of ('http', 'https').
code:
@wickenz.command()
async def weather(self, ctx, *,city):
response = requests.get(f'http://api.weatherstack.com/current?access_key={weather_token}&query={city}')
weatherinfo = response.json()
location_name = weatherinfo['request']['query']
latitude = weatherinfo['location']['lat']
longitude = weatherinfo['location']['lon']
weather_icon = weatherinfo['current']['weather_icons']
googlemaps_link = f"https://maps.google.com/?q={latitude},{longitude}"
embed_weather = discord.Embed(title=f"Weather for {location_name}")
embed_weather.set_thumbnail(url="" + str(weather_icon))
await ctx.reply(embed=embed_weather, mention_author=False)```
hello
# bot.py
import os
import discord
from dotenv import load_dotenv
load_dotenv()
TOKEN = os.getenv('DISCORD_TOKEN')
GUILD = os.getenv('DISCORD_GUILD')
client = discord.Client()
@client.event
async def on_ready():
for guild in client.guilds:
if guild.name == GUILD:
break
print(
f'{client.user} is connected to the following guild:\n'
f'{guild.name}(id: {guild.id})\n'
)
members = '\n - '.join([member.name for member in guild.members])
print(f'Guild Members:\n - {members}')
client.run(TOKEN)```
Why is this not returning any members besides the bot?
member intents must be enabled
in the developer portal and inside your commands.Bot instance
.
!intents
Using intents in discord.py
Intents are a feature of Discord that tells the gateway exactly which events to send your bot. By default, discord.py has all intents enabled, except for the Members and Presences intents, which are needed for events such as on_member and to get members' statuses.
To enable one of these intents, you need to first go to the Discord developer portal, then to the bot page of your bot's application. Scroll down to the Privileged Gateway Intents section, then enable the intents that you need.
Next, in your bot you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:
from discord import Intents
from discord.ext import commands
intents = Intents.default()
intents.members = True
bot = commands.Bot(command_prefix="!", intents=intents)
For more info about using intents, see the discord.py docs on intents, and for general information about them, see the Discord developer documentation on intents.
@dull stirrup
alright thanks
i still only got the bot
# bot.py
import os
import discord
from dotenv import load_dotenv
from discord import Intents
from discord.ext import commands
intents = Intents.default()
intents.members = True
bot = commands.Bot(command_prefix="!", intents=intents)
load_dotenv()
TOKEN = os.getenv('DISCORD_TOKEN')
GUILD = os.getenv('DISCORD_GUILD')
client = discord.Client()
@client.event
async def on_ready():
for guild in client.guilds:
if guild.name == GUILD:
break
print(
f'{client.user} is connected to the following guild:\n'
f'{guild.name}(id: {guild.id})\n'
)
members = '\n - '.join([member.name for member in guild.members])
print(f'Guild Members:\n - {members}')
f= open("members.txt","w+")
f.write(members)
f.close
client.run(TOKEN)```
this is what it looks like now
wait just realized rn
you are using 2 instances
commands.bot and discord.Client
use only commads.Bot @vague prism
and change each variable to bot
ok
since commands.Bot has both events and commands
is there a way to check if a role is above another
!d discord.Role.position
The position of the role. This number is usually positive. The bottom role has a position of 0.
Compare the roles position, which is a number
@vague prism are you copying code
i am using part of a guide on realpython
ok

so if i type something like !halp it would respond
how would i do that
and any service i should use to make it
scratch that
how do i even get it in the server
how do I grab a display name using a given id?
I need embed help in croissant
id2 = client.get_id(userid)
await ctx.send(id2.user.name)
I THINK IM RUSTY IN PY SO IF IT AINT RIGHT SORRY
I don't think that's it.
use get_member then call the display_name attribute
call?
um
member.display_name() is calling it, you want member.display_name where you access display_name via dotnotation
yea idk the word
yeah I know how to get the display name. I just don't know how to grab a member using an id
The bot does not have a get_member method
guild.get_member(123)
That's a method of a guild
ah, thanks i'll try that
uhh;.. I broke it
@commands.command()
async def baltop(self, ctx):
self.addnet()
cursor = collection.find().sort('net', pymongo.DESCENDING)
docs = await cursor.to_list(length = 10)
for doc in docs:
name = ctx.guild.get_member(doc['_id'])
await ctx.send(f"{name} {doc['net']}")
print(doc['name'] + " " + str(doc['net']))```
as for my print.
you need to process commands
@boreal osprey
in your on_message event, add await bot.process_commands(message)
!d discord.ext.commands.Bot.process_commands
await process_commands(message)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
This function processes the commands that have been registered to the bot and other groups. Without this coroutine, none of the commands will be triggered.
By default, this coroutine is called inside the [`on_message()`](https://discordpy.readthedocs.io/en/stable/api.html#discord.on_message "discord.on_message") event. If you choose to override the [`on_message()`](https://discordpy.readthedocs.io/en/stable/api.html#discord.on_message "discord.on_message") event, then you should invoke this coroutine as well.
This is built using other low level tools, and is equivalent to a call to [`get_context()`](https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.Bot.get_context "discord.ext.commands.Bot.get_context") followed by a call to [`invoke()`](https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.Bot.invoke "discord.ext.commands.Bot.invoke").
This also checks if the messageβs author is a bot and doesnβt call [`get_context()`](https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.Bot.get_context "discord.ext.commands.Bot.get_context") or [`invoke()`](https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.Bot.invoke "discord.ext.commands.Bot.invoke") if so.
i'm talking about about my commands
i know, your commands arent working because you havent processed commands in your on_message event mate.
all of the commands?
yep
this will fix it
is this some update i am just not familiar about
nope, not an update
also
if you use an event listener for on_message you dont have to do this, but if you dont use a listener, you must process commands
the function "message" isn't used in all my commands
it doesnt matter
read the doc here
"This function processes the commands that have been registered to the bot and other groups. Without this coroutine, none of the commands will be triggered.:
wait it says something about get context
should that work to?
wait never mind that question
opinions ?
i think buttons would be better
tried
ah
using that for now till i completely understand
i was using selects but i couldn't get the embed to send so
@patent lark what should the await bot.process_commands(message) be placed in the command
it should be placed in your on_message event
at the top or bottom, just not inside any if conditions
my message event works without this though which is my bottom @bot.event
ive told you, adding this would fix your issue entirely. your commands are not working cause you have not processed commands in your on_message event
as the doc said:
This function processes the commands that have been registered to the bot and other groups. Without this coroutine, none of the commands will be triggered.
and i meant at the top or bottom of the event itself
your on message event:
@bot.event
async def on_message(message):
if "deez nuts" in message.content:
message = message.channel
await message.send("https://cdn.discordapp.com/emojis/855104399676407848.gif?v=1")```
WRONG^
```py
@bot.event
async def on_message(message):
await bot.process_commands(message)
if "deez nuts" in message.content:
message = message.channel
await message.send("https://cdn.discordapp.com/emojis/855104399676407848.gif?v=1")```
CORRECT^
you're welcome
no lol
but thanks though, i am still fairly new to discord.py
you're welcome, and thats okay.
!docs discord
In order to work with the library and the Discord API in general, we must first create a Discord Bot account.
Creating a Bot account is a pretty straightforward process.
!d discord.Role.position
The position of the role. This number is usually positive. The bottom role has a position of 0.
so i managed to do py if ctx.invoked_subcommand is None: await ctx.reply("no subcommand found") but then, i also have ```py
invoke_without_command=True
ughhh idk how to use any of this
brb lemme test itout
its simple
i'm trying to get the spot the authors role is vs the member there trying to bans is
once i see how to do it once i can jeep doing it
or do we not need to int it is it already an int by itself
discord.Role.position it an int, starting at 0, 0 is the bottom role, 1 is above it, etc.
ctx.author.role.position.
thats wrong
ctx.author.top_role.position
to get there highest role is top_role right
yep
you can use top_role, or iterate through the roles and target one.
snow
if you're checking if its higher than the members role, you'd do
if ctx.author.top_role.position > member.top_role.position
or you can check the position itself with an according integer,
if ctx.author.role == 5
etc
yes?
uhh
.
@patent lark
im not all that familiar with subcommands
okay then
Iβm trying to make a modmail system but itβs giving me this error and idk why, can someone help?
@client.event()
async def on_message(message):
empty_array = []
modmail_channel = discord.utils.get(client.get_all_channels(), name="modmail")
if message.author == client.user:
return
if str(message.channel.type) == "private":
if message.attachments != empty_array:
files = message.attachments
await modmail_channel.send("[" + message.author.display_name + "]")
for file in files:
await modmail_channel.send(file.url)
else:
await modmail_channel.send("[" + message.author.display_name + "] " + message.content)
elif str(message.channel) == "modmail" and message.content.startswith("<"):
member_object = message.mentions[0]
if message.attachments != empty_array:
files = message.attachments
await member_object.send("[" + message.author.display_name + "]")
for file in files:
await member_object.send(file.url)
else:
index = message.content.index(" ")
string = message.content
mod_message = string[index:]
await member_object.send("[" + message.author.display_name + "]" + mod_message)
This is the current code
you don't need bracket in @client.event()
I donβt?
I thought you need it
Yup Iβm stupid
you dont need it
also i dont recommend copying code from youtube, you dont learn anything
Send your code
mm
@bot.command()
async def text(ctx, *, text = "No text entered"):
img = Image.open("1hzypv.jpg")
draw = ImageDraw.Draw(img)
font = ImageFont.truetype("arial.ttf", 24)
draw.text((0,150), text, (0, 0, 0), font=font)
img.save("1hzypv.jpg")
await ctx.send(file = discord.File("1hzypv.jpg"))
this is code
Do u have a file named arial.ttf?
Indeed
PIL is not asynchronous so these methods are blocking
!d asyncio.loop.run_in_executor
awaitable loop.run_in_executor(executor, func, *args)```
Arrange for *func* to be called in the specified executor.
The *executor* argument should be an [`concurrent.futures.Executor`](https://docs.python.org/3.10/library/concurrent.futures.html#concurrent.futures.Executor "concurrent.futures.Executor") instance. The default executor is used if *executor* is `None`.
Example:
You don't have the font file
Yups
That's why its raising OS error
!d discord.Embed.set_author
set_author(*, name, url=Embed.Empty, icon_url=Embed.Empty)```
Sets the author for the embed content.
This function returns the class instance to allow for fluent-style chaining.
ok thanks
icon_url

Someone plz help me
How do I test code here.
like this
a=3
while (a>=0):
b=3
while(b>=0):
print(5,end=' ')
b=b-1
print()
a=a-1
!e print('a')
@dusk pumice :white_check_mark: Your eval job has completed with return code 0.
a
!e a=3
while (a>=0):
b=3
while(b>=0):
print(5,end=' ')
b=b-1
print()
a=a-1
@forest anchor :white_check_mark: Your eval job has completed with return code 0.
001 | 5 5 5 5
002 | 5 5 5 5
003 | 5 5 5 5
004 | 5 5 5 5
right
!e thx
@forest anchor :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 1, in <module>
003 | NameError: name 'thx' is not defined
Thnx
@hoary gust with
@slate swan I mean I am trying to make my bot send one of my file from one channel to another but how
I will send a file and then my bot will send it to another
!d discord.abc.Messageable.send
await send(content=None, *, tts=False, embed=None, file=None, files=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, mention_author=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Sends a message to the destination with the content given.
The content must be a type that can convert to a string through `str(content)`. If the content is set to `None` (the default), then the `embed` parameter must be provided.
To upload a single file, the `file` parameter should be used with a single [`File`](https://discordpy.readthedocs.io/en/stable/api.html#discord.File "discord.File") object. To upload multiple files, the `files` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.9)") of [`File`](https://discordpy.readthedocs.io/en/stable/api.html#discord.File "discord.File") objects. **Specifying both parameters will lead to an exception**.
If the `embed` parameter is provided, it must be of type [`Embed`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Embed "discord.Embed") and it must be a rich embed type.
@slate swan but how will it know that is there any file or not and even if there is a file how will it know it's name
!e a=3
while a>=0:
b=1
while b<=a:
print(b,end=β β)
b=b+1
print()
a=a-1
@forest anchor :x: Your eval job has completed with return code 1.
001 | File "<string>", line 2
002 | while a>=0:
003 | IndentationError: unexpected indent
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.
!d discord.Message.attachments
A list of attachments given to a message.


