#discord-bots
1 messages · Page 810 of 1
yea
can someone help me with that?
your downloads and imports?
never mind guys
yes i didnt see you have to import something else from the package
The error was in this:
emb.add_field(name="**Канал:**", value=f"**<#{message.channel.id}>**", inline=False)
this code is fine unless message.chanel.id doesn't work
and I dont think it will
How to find out in which channel the user was kicked and find out the channel id?
So I have this commandpy @commands.command(description="Clone emojis!", usage = "<emoji>") @commands.has_permissions(manage_emojis=True) @commands.bot_has_permissions(manage_emojis=True) async def clone(self, ctx, emoji: Union[discord.PartialEmoji, discord.Emoji]= None): message = await ctx.reply(f"Cloning please wait... {emoji}['loading']") if isinstance(emoji, discord.PartialEmoji): emo = await ctx.guild.create_custom_emoji(name=emoji.name, image=await emoji.read(), reason=f"{ctx.command.name} command used by {ctx.author} ({ctx.author.id})") await message.edit(content=f"Emoji <:{emo.name}:{emo.id}> was added!") that lets me clone emoji's but I'm getting this errorpy ERROR:cogs.error_handler:AttributeError: 'PartialEmoji' object has no attribute 'read' (In clone) Traceback: File "/usr/local/lib/python3.8/dist-packages/discord/ext/commands/core.py", line 85, in wrapped ret = await coro(*args, **kwargs) File "/home/modmail/cogs/info.py", line 476, in clone emo = await ctx.guild.create_custom_emoji(name=emoji.name, image=await emoji.read(), reason=f"{ctx.command.name} command used by {ctx.author} ({ctx.author.id})")how should I go about fixing it?
Yo anyone know how to get a channels current permissions
🤔
Helpp
!d discord.GuildChannel.overwrites
No documentation found for the requested symbol.
property overwrites: Dict[Union[Role, Member], PermissionOverwrite]```
Returns all of the channel’s overwrites.
This is returned as a dictionary where the key contains the target which can be either a [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role") or a [`Member`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member "discord.Member") and the value is the overwrite as a [`PermissionOverwrite`](https://discordpy.readthedocs.io/en/master/api.html#discord.PermissionOverwrite "discord.PermissionOverwrite").
Wdym by "in which channel"? Users don't need any channel to kick or get kicked
Find out in which channel the user was kicked
!d discord.PartialEmoji.read If it's 1.7.3, do emoji.url.read()
await read()```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Retrieves the content of this asset as a [`bytes`](https://docs.python.org/3/library/stdtypes.html#bytes "(in Python v3.9)") object.
Users don't need any channel to kick or get kicked
so what would be the syntax to print the overwrites of the current channel
🤔
It returns a dict like json { <Role/Member 1>: <PermissionOverwrite 1>, <Role/Member 2>: <PermissionOverwrite 2>, ..., }
Parse it and you get the overwrites for each role set
That is, it is impossible to find out in which channel the user was kicked?
yes whats the syntax to make it return
I mean, it is impossible if it makes any sense, but it don't. User is not kicked from any channel
Okay
Not sure, havent use dpy for long. Just looked at the docs and can only conclude this much
!d discord.PermissionOverwrite check this out
class discord.PermissionOverwrite(**kwargs)```
A type that is used to represent a channel specific permission.
Unlike a regular [`Permissions`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions "discord.Permissions"), the default value of a permission is equivalent to `None` and not `False`. Setting a value to `False` is **explicitly** denying that permission, while setting a value to `True` is **explicitly** allowing that permission.
The values supported by this are the same as [`Permissions`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions "discord.Permissions") with the added possibility of it being set to `None`.
x == y Checks if two overwrites are equal.
x != y Checks if two overwrites are not equal.
iter(x) Returns an iterator of `(perm, value)` pairs. This allows it to be, for example, constructed as a dict or a list of pairs. Note that aliases are not shown.
Anybody knows why does this custom exec eat all the errors https://pastebin.com/BXtzvn6B
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
hi guys
!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.
Use this
What's the difference bro
Pastebin fucks with formatting
how to read message from discord using python ?
use Hikari
Depends how you want to read it
!d discord.Message.content
The actual contents of the message.
Ok seems like nobody knows how to fix that cring
Can someone make me a very basic discord bot please
Then it's time to use the power of help channels 
This place is for helping others with creating something by themselves, not making something for them
i wasn’t asking you specifically, you didn’t have to reply
nobody will do that
You probably need to search for somebody on freelance platform, this is the wrong place to ask
we're all rule respecting people 
it’s against the rules to do things for others?
As for paid work yes
!rule 9
I’m asking for free :>
paid work of 0mone
you can’t pay someone 0
bet
Spoonfeeding is generally discouraged here
That's only for paid work
Well once again, this is the wrong place to ask. This server is for code help, not for code making for someone
We can only provide you resources to learn how to make one by yourself
we've had several mod situations going on here, they all declined free work being allowed
wth
WTF
Help me
my eyes
ive never seen something more cursed in my life
LOL
This is discord.js, so wrong server to ask
and it's not even python broo
We only help with python bots
ever more cursed
can I have that font tho
OH
bro?
i have no clue
If you don't wanna code yourself, just take permission (or follow license?) and use a repo from github. There are plenty available as open source
seems challenging
seems dumb
I mean, ctrl+c and ctrl+v works I guess
that's my name
What about minecraft enchantment table font
also hi okimii ❤️
hi ❤️🔥
!ot
that’s sort of stealing
😳
yall dont run that font?
it's made to be
That's not, if you follow the license.
As long as its license allows its usage, it's totally not
we don't do work for people, maybe ask infernum, I heard he's making discord bots for hire 😏 (iirc)
its my first year of studying software engineering and i barely know shite about coding
what an L
Mostly bots have the MIT or don't even have one
LMFAO, I can just imagine the code
must be hell
*shit
hi i have a question . I have a embed with a reaction and when i react i want it to change de embed ( switching pages in help command) thats what i ve got
@commands.command()
async def help(self, ctx):
embed = discord.Embed(title="Commands for this bot!", description="**Prefixul acestui bot este ´.´ **", color=discord.Colour.random())
embed.set_thumbnail(url="https://media.discordapp.net/attachments/612746705406001213/612990390907305990/avatar.png")
embed.add_field(name="kick", value="Foloseste .kick pentru a dat kick unui membru.", inline=True)
embed.add_field(name="ban", value="Foloseste .ban pentru a dat ban unui membru", inline=True)
embed.add_field(name="unban", value="Foloseste .unban pentru a dat unban unui membru bannat.", inline=True)
embed.add_field(name="clear", value="Foloseste .clear + suma pentru a sterge mesaje de pe chat.", inline=True)
embed.add_field(name="mute", value="Foloseste .mute pentru a dat mute unui membru.", inline=True)
embed.add_field(name="unmute", value="Foloseste .unmute pentru a dat unmute unui membru.", inline=True)
embed.add_field(name="reload", value="Foloseste .reload pentru a debloca botul.", inline=True)
embed.add_field(name="ping", value="Foloseste .ping pentru a vedea latency-ul la bot.", inline=True)
embed.add_field(name="avatar", value="Foloseste .avatar + membru pentru a vedea avatarul unui membru.", inline=True)
embed.add_field(name="color", value="Foloseste .color pentru a genera o culoare random.", inline=True)
embed.add_field(name="poll", value="Foloseste .poll pentru a face un sondaj.", inline=True)
embed.set_footer(text="La Plesneala")
msg = await ctx.reply(embed=embed)
await msg.add_reaction(":white_check_mark:")
i know its not stealing but it feels like it
!d discord.exi.commands.Bot.wait_for || if you're waiting for an reaction
No documentation found for the requested symbol.
you even learn more from it than having someone do it for you
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 created a bot like a yr ago, you can use it. But the code is too shitty lol if you don't mind 🛐
ty
At least designers can actually create something good looking (I can't)
event should be "reaction" if you want to wait for a reaction
wtf is my spelling today
maybe i don’t have time to learn something new
right now
why not?
busy
you can always find time for coding 😏 10:00pm be like
with other things
Then wait until you are not busy
I code from 9-11, go to sleep, wake up at 6:30, code to 7, get ready for school
1 hour 10 mins of coding per day except tuesdays and mondays
As a "trying to do frontend for school project" guy, designing is so much pain too 💀
woohoo
I so fucking agree
for a tech fair I'm doing the frontend
I gave up so I'm using webflow
sorry but i dont understand it
I don't understand how can you make a nice looking thing
lemme pull up the docs
For my school project, I literally made a whole website, and later realised all this was just for 3 marks 😢
No spatial mind or smth
@client.event
async def on_message(message):
if message.content.startswith('$thumb'):
channel = message.channel
await channel.send('Send me that 👍 reaction, mate')
def check(reaction, user):
return user == message.author and str(reaction.emoji) == '👍'
try:
reaction, user = await client.wait_for('reaction_add', timeout=60.0, check=check)
except asyncio.TimeoutError:
await channel.send('👎')
else:
await channel.send('👍')
taken from here https://discordpy.readthedocs.io/en/master/api.html#discord.Client.wait_for
you code from 9-11 i code for 9/11 we're not the same
basically, wait_for waits for a event (obviously) and asyncio.TimeoutError is when the timeout reaches to 0
it's an error handler
you can use lambda for check
unlucky
I mean you can just do
def check(reaction):
if str(reaction.emoji) == "..."
if you just want to check for the reaction
But made some cool stuff I hope will help me to be put in some resume in future 🛐
wait hold it
I just had a fucking bruh moment
I don't think I understood you correctlypy INFO:cogs.events:POST https://discord.com/api/v7/channels/501004576866959391/messages took 1.7 seconds ERROR:cogs.error_handler:AttributeError: type object 'PartialEmoji' has no attribute 'read' (In clone) Traceback: File "/usr/local/lib/python3.8/dist-packages/discord/ext/commands/core.py", line 85, in wrapped ret = await coro(*args, **kwargs) File "/home/modmail/cogs/info.py", line 482, in clone emo = await ctx.guild.create_custom_emoji(name=emoji.name, image=await discord.PartialEmoji.read(), reason=f"{ctx.command.name} command used by {ctx.author} ({ctx.author.id})")I thought you meant I had to put in discord.PartialEmoji.read(), After reading your msg for the 4th time I think you were saying that instaed of emoji.read i needed emoji.url.read?
yippee
my resume's gonna be like
None
xD
i hope you don't get it
Exactly
nah its easy
enchantments font? If I make a typo idk where I go wrong
Ok anybody knows why does this exec command eat all the errors https://paste.pythondiscord.com/edubosazox.rust
does krypt0n have a skill issue or what https://krypt0n.co.uk/2022/01/30/How-I-protected-my-Minecraft-cheating-client/
Literally 2 try-excepts and it still eats the error to somewhere
lmaooo
int string = -1;
if (letter == letter.A) {
string = 1;
} else if (letter == letter.B) {
string = 2;
} else if (letter == letter.C) {
string = 3;
} else if (letter == letter.D) {
string = 4;
} else if (letter == letter.E) {
string = 5;
} else if (letter == letter.F) {
string = 6;
} else if (letter == letter.G) {
string = 7;
} else if (letter == letter.H) {
string = 8;
} else if (letter == letter.I) {
string = 9;
} else if (letter == letter.J) {
string = 10;
} else if (letter == letter.K) {
string = 11;
} else if (letter == letter.L) {
string = 12;
} else if (letter == letter.M) {
string = 13;
} else if (letter == letter.N) {
string = 14;
} else if (letter == letter.O) {
string = 15;
} else if (letter == letter.P) {
string = 16;
} else if (letter == letter.Q) {
string = 17;
mhm, nice
What lang is this
Why not use switch 

java
yeah it does
⎓𝙹∷ ╎ ╎リ ∷ᔑリ⊣ᒷ(10):
!¡∷╎リℸ ̣ ('nᒷ⍊ᒷ∷ ⊣𝙹リリᔑ ⊣╎⍊ᒷ ||𝙹⚍ ⚍!¡')```
I beg you to stop
APL mixed with enchanting table text
I beg you...
Can I have sharpness V
how do i make it so that if my bot pings someone, it responds with text
Sure
passed the vibe check
@bot.command()
async def (mention)(ctx):
await ctx.send("(text)")```
I can already see a stalker mod ruining it
😳 wut
what lang is this?
i want to make it so that if someone does ! and then mentions someone, it replies with something
Just use on_message event
how do i do that
!d discord.on_message
discord.on_message(message)```
Called when a [`Message`](https://discordpy.readthedocs.io/en/master/api.html#discord.Message "discord.Message") is created and sent.
This requires [`Intents.messages`](https://discordpy.readthedocs.io/en/master/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/master/ext/commands/api.html#discord.ext.commands.Bot "discord.ext.commands.Bot") does not have this problem.
how do i make it so that message is a mention
!d discord.Message.mentions
A list of Member that were mentioned. If the message is in a private message then the list will be of User instead. For messages that are not of type MessageType.default, this array can be used to aid in system messages. For more information, see system_content.
Warning
The order of the mentions list is not in any particular order so you should not rely on it. This is a Discord limitation, not one with the library.
fire aspect || only take it or leave it
Hello. In my bot I have on_message event and when I type command, the on_message event triggers, how can I stop that?
Code:
`@bot.event
async def on_message(message):
if message.author.id == bot.user.id:
returnif message.channel.id == 927347556860702793: await message.channel.send('Send') else: await message.channel.send("Wrong channel") await bot.process_commands(message)`
I want to make **on_message ** to ignore @bot.command events.
can I get a Looting VIII
I forgot the enchantment minecraft command sorry 😦
You may check if the message content starts with your prefix
Also it's better to use a listener to get rid of process_commands
When the database has random UNIQUE constraint
Oh okay, thanks!
/enchant
You put it into a decorator lol
its probably not in the class
Self is only given in the bound methods of the class. At the point where the decorator runs self is not defined
hi andy
It should be the first arg of the method
yes my mistake
hi i have this code and this error any help
page1 = discord.Embed(title="Bot Help 1", description="Use the buttons below to navigate between help pages.", colour=discord.Colour.orange())
page2 = discord.Embed(title="Bot Help 2", description="Page 2", colour=discord.Colour.orange())
page3 = discord.Embed(title="Bot Help 3", description="Page 3", colour=discord.Colour.orange())
client.help_pages = [page1, page2, page3]
@commands.command()
async def help(self, ctx):
buttons = [u"\u23EA", u"\u2B05", u"\u27A1", u"\u23E9"] # skip to start, left, right, skip to end
current = 0
msg = await ctx.send(embed=client.help_pages[current])
for button in buttons:
await msg.add_reaction(button)
while True:
try:
reaction, user = await client.wait_for("reaction_add", check=lambda reaction, user: user == ctx.author and reaction.emoji in buttons, timeout=60.0)
except asyncio.TimeoutError:
return print("test")
else:
previous_page = current
if reaction.emoji == u"\u23EA":
current = 0
elif reaction.emoji == u"\u2B05":
if current > 0:
current -= 1
elif reaction.emoji == u"\u27A1":
if current < len(client.help_pages)-1:
current += 1
elif reaction.emoji == u"\u23E9":
current = len(client.help_pages)-1
for button in buttons:
await msg.remove_reaction(button, ctx.author)
if current != previous_page:
await msg.edit(embed=client.help_pages[current])
``` error
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'slashes' object has no attribute 'song_queue', I'm exporting to / commands, this code works for normal prefix, but not for slash. https://mystb.in/SkiingAgeDublin.python
did u load ur cog?
help is already built in
yh that too
client.remove_command('help')
iirc that's not a cog
what error does it show?
self? @commands.command()?
i tried with another name too and dosent work
should have commands.Cog
nvm just a class
I have a question. Will the bot handle on_message event if there's about 100 messages/min ?
iirc
ur bot can handle pretty much everything
iirc yes
discord.ext.commands.errors.CommandNotFound: Command "help" is not found
Thanks!
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'slashes' object has no attribute 'song_queue', I'm exporting to / commands, this code works for normal prefix, but not for slash. https://mystb.in/SkiingAgeDublin.python
so do you guys know or i just drop it
instead of client.remove_command() try doing help_command=None in your commands.Bot()
!d discord.ext.commands.Bot || theres a help_command kwarg
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/master/api.html#discord.Client "discord.Client") and as a result anything that you can do with a [`discord.Client`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client "discord.Client") you can do with this bot.
This class also subclasses [`GroupMixin`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.GroupMixin "discord.ext.commands.GroupMixin") to provide the functionality to manage commands.
how do I get the permissions of a channel from a channel
client = commands.Bot(command_prefix=".", intents=intents, help_command=None)
!d discord.TextChannel.overwrites
property overwrites: Dict[Union[Role, Member], PermissionOverwrite]```
Returns all of the channel’s overwrites.
This is returned as a dictionary where the key contains the target which can be either a [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role") or a [`Member`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member "discord.Member") and the value is the overwrite as a [`PermissionOverwrite`](https://discordpy.readthedocs.io/en/master/api.html#discord.PermissionOverwrite "discord.PermissionOverwrite").
like that?
whats the syntax
Yeah
I can't figure it out
Depends on your case
If you are fetching it with a command, just ctx.channel.overwrites
still the same error
oh
ok duck it
thats so easythank you bro
hurrr
hmm i got another error on another command
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Context' object has no attribute 'voice_client', I dont even use this in the command it gives erorr
I think it's clearly understandable, isn't it
this, and plus that isn't really a dpy question
anyone?
code here: https://mystb.in/SkiingAgeDublin.python
show us the full error please
but here is the catch it is a buy this the user is the person who ran the command
this is all
Error occured in command play
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Context' object has no attribute 'voice_client'
no
it should have something more
u think I can't read tho?...
well, I guess
I'm experienced in py
Raise it
so I sure know how to send an error
okay how would I add new overwrites but keep the current ones?
for x in overwrites:
something
You sent a str representation and we need the traceback
weird, does it not send the line of the error?
well how do I get the traceback
like line 88?
no, doesnt since I use slash commands cog
You can fetch the dict and use update method of it
mk
list.to_dict()
right
try:
...
except Exception as e:
raise ErrorName(e)
I see
@rocky trench in the latest versions of many dpy forks the ctx.voice_client was removed and there's no alternative to it
oh
I use ctx.guild.voice_client
And the guild.voice_client has a wrong type
Bare exception bad
and it works for my other non slash commands
ik
Pretty sure it is VoiceProtocol and you need VoiceClient
it depends on what error it is
Idk which error it should throw so I'm shooting blind
!d discord.Guild.voice_client
property voice_client: Optional[VoiceProtocol]```
Returns the [`VoiceProtocol`](https://discordpy.readthedocs.io/en/master/api.html#discord.VoiceProtocol "discord.VoiceProtocol") associated with this guild, if any.
oof
I mean it's useless why not the VoiceClient
When I faced this issue, I just stored the clients in cog variable
You could do the same ig
Maybe there's a better method, but I don't know one and nobody could suggest me one when I asked
@slash_util.slash_command(description = 'Joins the voice channel')
async def join(self, ctx):
if ctx.author.voice is None:
return await ctx.send("You are not connected to a voice channel, please connect to the channel you want the bot to join.")
if ctx.guild.voice_client:
return await ctx.send("I am already connected to a voicechannel.")
await ctx.author.voice.channel.connect()
await ctx.guild.change_voice_state(channel = ctx.author.voice.channel,self_deaf=True)
await ctx.send('I joined the voice channel!', ephemeral = True)```
why did this work tho?
the if ctx.guild.voice_client:
Later in code you tried to access is_playing, in this code you are not accessing any attributes of the protocol
The ctx.guild.voice_client itself is valid, but ctx.guild.voice_client.is_playing() is not, as VoiceProtocol instances don't have that method
ah I see
Not really
overwrites = ctx.channel.overwrites.copy() # copy may be unnecessary
overwrites[ctx.guild.default_role] = discord.PermissionOverwrite(send_messages=False)
await ctx.channel.edit(overwrites=overwrites)```
A quick example that would change the permission for everyone role to send messages in the channel the command was used in
Note that this will **overwrite** the permission for a certain role and not modify it
So I know this is a very weird question, but, I have this ticket bot, and I want to return on the reaction when the payload.user_id is the ones of the bots, which I do like this:
if payload.user_id == 930853710811246602:
return```
Although, for some reason, this only keeps working on some servers, which I do not know why. Anyone knows solution to the issue?
You may get the user object and check if it is a bot if that's what you need
if bot.get_user(payload.user_id).bot:
return```
Recommended to fetch user if the bot is on large amount of guilds
why do i keep getting "This Interaction failed" from my dropdown
jolly good question sir
What would be the best way to grab the message history of a user in a server? ctx.author.history() doesnt seem to pull it.
thanks
you'd need to do that, flatten it, and filter() it
though it could take a while and be intensive
can you show us the code?
The only issue is that seems to only pull the history from the dm between the bot and the user
you would have to loop through each channel and get every message
Just the dms? I assume you're doing like member.history() which would get the history from the DMs
You probably thought that would get all the user's messages
Unfortunately it gets the dms messages
Ya
To get all the messages from a user, you'd have to loop through every single channel, get every single message in all of those channels, and filter them so it's only from the users. It would be very time costly and intensive on the mission
Aight
There is just no good way to get a specific users entire message history
I'm sure the endpoint is heavily ratelimited, and it would be 100 messages per API call or under 100 messages for 1
Ok, next question. We can work with just pulling from 1 channel but we want to pull all the channel ids from the server to randomly select or not select from a specific channel
For overall project context it takes 2 random messages from a persons history and splices them together. Currently based on the channel the command is sent in but causes issues when something like a bot spam channel is only full of bot commands and not actual messages
Hey guys, im migrating from Discord.PY, to Disnake atm. Everything is working well but for some reason, i can't pull the users profile pictures.
embed.set_thumbnail(url=member.avatar_url)```
member.avatar.url
Same error
disnake.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Member' object has no attribute 'avatar_url'
async def info(self, ctx, member: disnake.Member):
member is indeed passed
forgot to relaunch it because it didn’t recognize the change
-_-
It’s picking it up as “avatar_url” still which means it was not changed
lol
i had a print statement didn't see.
Thank you guys 🙂
lol
im back
in another place im now getting
eme.set_author(name=str(member), icon_url=member.avatar.url)
AttributeError: 'NoneType' object has no attribute 'url'```
eme.set_author(name=str(member), icon_url=member.avatar.url)
So I'm getting this errorpy ExtensionFailed - Extension 'cogs.info' raised an error: TypeError: Aliases of a command must be a list or a tuple of strings.but I can't see where it's coming from https://sourceb.in/vxMjyepBli
What line is it in
Aliases = [" "]
it's not telling me which is the annoying thing,
It’s the first command group decorator
thanks
And why are you adding extra commas after the last argument in the decorator
it's just my weird style of coding
Just don't
I feel like that will eventually cause an issue for you down the road
^^
@neat tartan any idea?
Aside from just what the error message says not really. I can’t think of the correct terms and I’m not too familiar with disnake
its disnake.
Oh
in the documentation there is no mention
of member.avatar.url
only avatar_url which is odd, because i had the same issue somewhere else
and doing .url fixed it
Also name = str(member) is unneeded. Just use name = member
fixed 🙂
also can I make command group sub commands guild only https://discordpy.readthedocs.io/en/master/ext/commands/api.html?highlight=guild_only#discord.ext.commands.guild_only (so i don't put @commands.guild_only() on the main command but on the sub commands instead, if they need it)
you know by any chance?
Its the same, just shorter 😊
should be able to
The documentation exists, it's on the master branch of the docs
yes i know
yes i know, just saying in the documentation there is no mention that you have to use . not _
!d discord.Member.avatar
property avatar```
Equivalent to [`User.avatar`](https://discordpy.readthedocs.io/en/master/api.html#discord.User.avatar "discord.User.avatar")
Wdym? It does
Ignoring exception in on_guild_join
Traceback (most recent call last):
File "C:\Users\PC\AppData\Local\Programs\Python\Python39\lib\site-packages\nextcord\client.py", line 415, in _run_event
await coro(*args, **kwargs)
TypeError: on_guild_join() takes 1 positional argument but 2 were given
i have only one argument ```py
@commands.Cog.listener()
async def on_guild_join(guild):
i think you need to pass self
It seems like it's just member.avatar
as the first argument
oh
forgot
Polar
yes
So I tried ```py
@commands.group(name = "user", aliases = ["member"], invoke_without_command = True, case_insensitive = True,)
async def user_group(self, ctx):
await ctx.reply("You used {ctx.command.name}")
await ctx.reply("{ctx.group.name} has {len(ctx.group.commands)}")
@user_group.guild_only()
@user_group.has_permissions(manage_guild = True)
@user_group.command(description = "Show a member's permission in a channel when specified.", usage = "[member] [channel]", aliases = ["perms"])
async def permissions(self, ctx, member: discord.Member = None, channel: Union[discord.TextChannel, discord.VoiceChannel, discord.StageChannel, discord.CategoryChannel] = None):```and got ```py
ExtensionFailed - Extension 'cogs.info' raised an error: AttributeError: 'Group' object has no attribute 'guild_only'```so do I put @commands.guild_only() decorator on the sub command instead
hello monkey
ahh ok
Seems like put it on the group then
I don't know how disnake works, just checking docs
mr tumble at it again
wtf
i got some bs now
disnake.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In embeds.0.author.icon_url: Scheme "none" is not supported. Scheme must be one of ('http', 'https').```
Ah yes
If the user doesn't have an avatar (basic one) it returns None
Use display_avatar instead
wait
are you trying to say, i can technically use that to check if the users pfp is default?
Display avatar is for example serverprofile avatar, or the one that's set
For me it would return the monkey thing
ah
🙂
@rocky trench seems like you are learning your stuff 👀
Oh its you binds!
mhmm
I didn't recognize you at first
yeah have a diff name here
The decorator command for commands.Group still returns a Command instance, just add the commands.guild_only decorator to the subcommand
Andy 🗿
🗿
I've rewritten Rin's slash commands implementation like 4 times already and I have no clue what design choice is best
lol
😔 this is gonna be even more painful when I have to do voice
I went from dpy to slash_utils
Ignore any potential formatting errors what is the correct way of listing this
I dont have an exact error message cause im asking on anothers behalf but channels is not picking up or doesnt exist within it
Which is pretty much the same
I need to probably transfer at some point but ive been holding off
For channel in ctx.guild.channels?
Think we tried that and it still had an issue but ill try it
This worked
👍
It was the first one we initially tried and didnt work. Might have had some sort of syntax error when we first were figuring it out. Thank you
You're welcome!
Ah I think for channel in guild.channels includes voice channels tho
It looked like the docs said it returns textchannels
Ah ok. The notation of all of this has been super fucky
The docs have been my bible for the past little bit. I was careful to try and follow it correctly but something was still going wrong so i asked in here. Its always stupid little things like that that get me
Yh I know the feeling
When you start helping, and you encounter a problem you won't forget it
Ya, ive been trying to help here where i canwhile ive been learning and it helps
hey so what's going on with discord py? I saw something saying that it's not going to be maintained anymore in February of 2022...?
slash commands
discord being annoying
so what's that mean, what's wrong
how can i use api link to post its result in embed
long story short, discord wants to re do the entire basis of how discord bots are made
dpy dev said, nah
Oof
and stopped
... whatttt
yeah
Dpy is no longer being developed. Discord will be making a breaking change to the api which will require bots to be reformated to function
you are kidding meeeeeee
So I'm trying to get my bot to send a list of the commands inside of a group but I can't seem to get right. py AttributeError: 'NoneType' object has no attribute 'commands'with thispy group_commands = [] for command in ctx.command.parent.commands(): group_commands.append(command) #await ctx.reply(f"You used {ctx.command.name}") #await ctx.reply(f"{ctx.command.group} has {len(ctx.command.group.commands)}") await ctx.reply(" ".join(group_commands))but I tried a different variation on the if statement and got this errorpy ERROR:cogs.error_handler:AttributeError: 'Context' object has no attribute 'group' (In emoji) Traceback: File "/usr/local/lib/python3.8/dist-packages/discord/ext/commands/core.py", line 85, in wrapped ret = await coro(*args, **kwargs) File "/home/modmail/cogs/info.py", line 160, in emoji_group await self.ungroup(ctx) File "/home/modmail/cogs/info.py", line 23, in ungroup for command in ctx.group.commands:
this is only for verified bots tho
We have to use extern library's now
so if youre only developing for yourself, its okay
4 of the biggest python discord bot libs got hit with 1k+ member raids :I
wait so, why is it only for verified bots?
privacy reasons
What only for verified bots?
the slash command
message intent
what he said ^
Will they eventually get to the point where they'll end support for the now old-school discord bots?
well you cant just end support
if your bots not verified and you dont plan on verifying it then you should be fine
like the api endpoints will exist, now with dpy you dont get to access to new endpoints
ugh
like i just finished converting from dpy to disnake
almost the exact same syntax
everything is almost the same
if you do plan on verifying it, then i suggest switching over to slash commands or apply for the intent
but it is modern
^^
I'm planning on verifying mine
this is going to be a giant fucking pain, considering I'm well through developing a bot for a friend
well this only applys to you if the bot is going to be in 75+ servers
soo, if its just for your friend, youre fine
you too C:
Does anyone know if its possible that a message isnt being passed to on_message because its not found as a command for the bot?
Is on_error in another file?
16 after 3 days

the limit is 16 servers now??
Didn't even fully release yet
No, my bot
ahh
Did you import it?
okay haha, what does your bot do ?
anyone work with the disnake Discord User Public flags
Unlikely, if the correct intents are being used the bot will be dispatch MESSAGE_CREATE (on_message for discor.dpy) regardless if the message represents a command for the bot, that is if this is a chat command, not a slash one
I can't tell where its erroring
if the intents are incorrect, all messages would fail, correct?
Correct, if you don't have GUILD_MESSAGES or for DM's DIRECT_MESSAGES No MESSAGE_CREATE will be dispatched
This as of now speaking are unprivileged intents though ^
we dont have code line numbers
Alright, that doesnt seem to be the issue then
It's not
This is what you have:
await on_error(
ctx,
"Invalid Option Specified",
f"Option {val1} needs to be one of {sconf(ctx.guild.id).colors.keys()}.",
["!conf colors", f"!conf colors {sconf(ctx.guild.id).colors.keys()[0]} 0xe67e22"])
This is what the error is showing:
await on_error(ctx, "error")
Unless I'm being really dumb
I just did some testing and it appears the on_message isnt being fired for commands that should be a command (like, beginning with the prefix)
Are regular messages dispatching?
yes
Do you have some implementation for on_message anywhere other than the default implementation provided by the wrapper?
What would an example of that be, sorry?
Do you have an on_message event anywhere you coded, not the one provided by the wrapper by default
I was not replying to you
burn 🔥
No, I dont use on_message for anything else other then on_message events, if thats what you mean
🤣
I'm asking if you HAVE one, seems like you do? It would be helpful to show it, so more information can be gathered
Oh sorry, yes I have multiple
@commands.Cog.listener()
async def on_message(self, message):
print(message)
For normal messages, it gets the message info.
For messages beginning with ! (prefix), it doesnt
Is this the only one?
Nope. However, I think i just fixed it
I added an error handler for commands not found (this is like a dev bot), and it worked (passing on error for command not found)
Odd, regardless of the error handler it should have dispatched a MESSAGE_CREATE event regardless if the message started with the prefix
async def ungroup(self, ctx):
group_commands = []
for command in ctx.command.parent.commands():
group_commands.append(command)
#await ctx.reply(f"{ctx.command.group} has {len(ctx.command.group.commands)}")
await ctx.reply(embed = discord.Embed(title = "Commands in `{ctx.command.name}`", description = "`{}`, ".join(group_commands)))```I think something's up with my for statement here since I'm getting `AttributeError: 'NoneType' object has no attribute 'commands'`, what I want this statement to do is go through each subcommand inside a command and add that command to a list which i then format into my embeds description, the bit I'm stuck on is how to retrieve the context commands sub commands
If you mean the check its cause its a verified bot
I mean the huge add to server button
Oh, all public bots have that by default
Is the ungroup command part of the command group?
It would be toggled in the discord dev portal
Otherwise parent would be None
Iirc i think I saw someone say it's on the dev portal
i call the ungroup function all of my parent commandspy @commands.group(name = "user", aliases = ["member"], invoke_without_command = True, case_insensitive = True,) async def user_group(self, ctx): await self.ungroup(ctx)
really it ought to be no_group
Your ctx here is under user_group, which in-itself is a Group
Thus, of course as to be expected it has no parent, it is the parent
Since it's a group, you'd go through the groups commands attribute
there would be all the subcommands
Nope.
Where abouts?
O.o
so more like for command in ctx.group.commands(): bc that spits outpy ERROR:cogs.error_handler:AttributeError: 'Context' object has no attribute 'group' (In channel) Traceback: File "/usr/local/lib/python3.8/dist-packages/discord/ext/commands/core.py", line 85, in wrapped ret = await coro(*args, **kwargs) File "/home/modmail/cogs/info.py", line 112, in channel_group await self.ungroup(ctx) File "/home/modmail/cogs/info.py", line 23, in ungroup for command in ctx.group.commands():
No, ctx.command is the Group, that has the commands attribute
It's also not callable as it's a set of commands
So don't call it
woo, it works. only isses is its put the around the comma, how do I make it wrap it around the command(s) insteadpy description = "`, `".join(group_commands))
Im pretty sure it would require an f string with backticks before and after everything else so that it essentially inverses whats there
Well this failedpy ERROR:cogs.error_handler:TypeError: join() takes no keyword arguments (In channel) Traceback: File "/usr/local/lib/python3.8/dist-packages/discord/ext/commands/core.py", line 85, in wrapped ret = await coro(*args, **kwargs) File "/home/modmail/cogs/info.py", line 112, in channel_group await self.ungroup(ctx) File "/home/modmail/cogs/info.py", line 26, in ungroup await ctx.reply(embed = discord.Embed(title = f"Commands in `{ctx.command.name}`", description = "`{command}`, ".join(command = group_commands)))
Whats the code look like? (as a screensot cause mobile doesnt format if possible)
Title was fine before
yeah title's fine, it's the join on the description that;s the pain
Description is where the issue was, i think it should be
description = f"`{", ".join(group_commands)}`"
I think this should work or at least this is the idea
nvm i got around it by doing py for command in ctx.command.commands: command_string = f"`{ctx.prefix + command.name}`" group_commands.append(command_string)which puts around each command, it's probs not the best way to do it but it gets the right end result
Same dif
for some reason this command```py
@user_group.command(description = "Show some information about yourself or the member specified.", usage = "[member]", aliases = ["whois", "ui"])
async def info(self, ctx, *, member: discord.Member = None):
member = ctx.author if member is None else member
roles = [f"<@&{role}>" for role in member._roles]
key_perms = ["administrator", "manage_guild", "manage_roles", "manage_channels", "manage_messages", "manage_webhooks", "manage_nicknames", "manage_emojis", "kick_members", "mention_everyone"]
has_key = [perm for perm in key_perms if getattr(member.guild_permissions, perm)]
if len(has_key) == 0:
has_key.append('No permissions')
member_status = "No status" if member.activity is None else member.activity.name
if len(roles) == 0:
roles.append("No roles")
embed = discord.Embed(title = f"{member.name}#{member.discriminator}", description = f"Status: **{member.status}**\n*{member_status}*", colour = member.colour)
embed.set_author(name = f"{member.id}", icon_url = member.avatar_url)
embed.set_thumbnail(url = member.avatar_url)
embed.add_field(name = "Joined Server:", value = f"<t:{int(member.joined_at.timestamp())}:R>", inline = True)
embed.add_field(name = "Avatar", value = f"[PNG]({member.avatar_url_as(static_format='png')})", inline = True)
embed.add_field(name = "Joined Discord:", value = f"<t:{int(member.created_at.timestamp())}:R>", inline = True)
embed.add_field(name = f"Roles: {len(roles)}",value = f"{len(roles)} roles" if len(" ".join(roles)) > 1000 else " ".join(roles), inline = False)
embed.add_field(name =f'Key permissions', value = ", ".join(has_key).replace("_"," ").title(), inline = False)
await ctx.reply(embed = embed)```keeps giving me this error```py
ERROR:cogs.error_handler:AttributeError: 'str' object has no attribute 'author' (In info)
Traceback:
File "/usr/local/lib/python3.8/dist-packages/discord/ext/commands/core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "/home/modmail/cogs/info.py", line 48, in info
member = ctx.author if member is None else memberwhich I find odd bcpy
@user_group.command(description = "Show a users avatar.", usage = "[member]", aliases = ["av"])
async def avatar(self, ctx, *, member: discord.Member = None):
member = ctx.author if member is None else member
embed = discord.Embed(title = f"{member.name}#{member.discriminator}'s Avatar", colour = member.colour)
embed.add_field(name = "PNG", value = f"Link", inline = True)
embed.add_field(name = "JPG", value = f"Link", inline = True)
embed.add_field(name = "WebP", value = f"Link", inline = True)
embed.set_image(url = member.avatar_url)
await ctx.reply(embed = embed)```works without issues
Took me a moment to realize those are 2 seperate sets of code
same LMFAO
lol
I hate debugging on mobile so much
ik
Can i get those codes in screenshot format?
this the 'second' command, the one that works
Ok, and the one that doesnt?
had to do it in 2 parts
Aightthats fine. Gimme a moment to read through it
👍
Why does discord.member have to be none?
In case the member is not specified
bc if member is not given i want it to send the info for author
Also, @flat solstice you're expecting the user to only send the user, correct?
Ahh
It's a good idea to remove the * in that case
yeah, i'll remove the * then
Next, you get the member's roles via member.roles, not member._roles
well both was working for me
Plus, doing "<@&{role}>" is incorrect - you're putting the discord.Role object into the string, not the role ID which is received via {role.id}
!pep3102 talks about the use of *, arg @flat solstice
PEP 8 is the official style guide for Python. It includes comprehensive guidelines for code formatting, variable naming, and making your code easy to read. Professional Python developers are usually required to follow the guidelines, and will often use code-linters like flake8 to verify that the code they're writing complies with the style guide.
More information:
• PEP 8 document
• Our PEP 8 song! :notes:
Yeah it shouldn't matter, but sticking to the method the docs mention will be better
!pep 3102
trying to time a user out,
In communication_disabled_until: Invalid communication disabled timestamp
ryan = guild.get_member(ryanId)
await ryan.timeout(duration=99999999, reason="timeout test")
any reason this isn't working?
are you trying to use the new timeouit feature?
and if so, what lib is this in
discord.py doesn't have the new timeout feature
disnake
Try printing ryan, to see if it's getting the user?
!d disnake.Member.timeout
await timeout(*, duration=..., until=..., reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Times out the member from the guild; until then, the member will not be able to interact with the guild.
Exactly one of `duration` or `until` must be provided. To remove a timeout, set one of the parameters to `None`.
You must have the [`Permissions.moderate_members`](https://docs.disnake.dev/en/latest/api.html#disnake.Permissions.moderate_members "disnake.Permissions.moderate_members") permission to do this.
New in version 2.3.
You can't even timeout a user for 99999999 seconds, the API only supports 28 days max
I copy and pasted the max # it allowed
and removed two 9s
user was found
my timeout command to remove a timeout works
Oh yea, this is totally the max allowed
await user.timeout(duration=None)
this works
user = guild.get_member(nicholasAlt2)
That is used to remove a timeout
The error you received is clear - the duration you've specified is longer than 28 days
ah I see
Way over 28 days 👀
uhm, is it in minutes?
As andy mentioned 
5 years infact
It's in seconds
You could also specify a datetime object, under until
But yeah, you're currently trying to mute the user for half a decade
Yea, if you want a max mute you'd do timedelta + datetime.now()
timdelta(days=28) + datetime.now() etc
Easier then calculating the seconds
okay so I made those changes but it still doesn't seem to be workingpy ERROR:cogs.error_handler:AttributeError: 'str' object has no attribute 'author' (In info) Traceback: File "/usr/local/lib/python3.8/dist-packages/discord/ext/commands/core.py", line 85, in wrapped ret = await coro(*args, **kwargs) File "/home/modmail/cogs/info.py", line 48, in info member = ctx.author if member is None else memberso i think something's either wrong with the type hint or something else
Is it possible to do something like this using hikari?
@client.event
async def on_message(message):
if cond == True:
await client.process_commands(message)
else:
return
you probably reassigned context somewhere to a string.
well it's only happening in this command```py
@user_group.command(description = "Show some information about yourself or the member specified.", usage = "[member]", aliases = ["whois", "ui"])
async def info(self, ctx, member: discord.Member = None):
member = ctx.author if member is None else member
roles = [f"<@&{role.id}>" for role in member.roles]
key_perms = ["administrator", "manage_guild", "manage_roles", "manage_channels", "manage_messages", "manage_webhooks", "manage_nicknames", "manage_emojis", "kick_members", "mention_everyone"]
has_key = [perm for perm in key_perms if getattr(member.guild_permissions, perm)]
if len(has_key) == 0:
has_key.append('No permissions')
member_status = "No status" if member.activity is None else member.activity.name
if len(roles) == 0:
roles.append("No roles")
embed = discord.Embed(title = f"{member.name}#{member.discriminator}", description = f"Status: **{member.status}**\n*{member_status}*", colour = member.colour)
embed.set_author(name = f"{member.id}", icon_url = member.avatar_url)
embed.set_thumbnail(url = member.avatar_url)
embed.add_field(name = "Joined Server:", value = f"<t:{int(member.joined_at.timestamp())}:R>", inline = True)
embed.add_field(name = "Avatar", value = f"[PNG]({member.avatar_url_as(static_format='png')})", inline = True)
embed.add_field(name = "Joined Discord:", value = f"<t:{int(member.created_at.timestamp())}:R>", inline = True)
embed.add_field(name = f"Roles: {len(roles)}",value = f"{len(roles)} roles" if len(" ".join(roles)) > 1000 else " ".join(roles), inline = False)
embed.add_field(name =f'Key permissions', value = ", ".join(has_key).replace("_"," ").title(), inline = False)
await ctx.reply(embed = embed)```and there;s other commands which use the same decorators and inputs which work without errors, this for example```py
@user_group.command(description = "Show when yourself or the member specified joined the {ctx.guild.name} and Discord.", usage = "[member]", aliases = ["dates", "created", "j"])
async def joined(self, ctx, member: discord.Member = None):
member = ctx.author if member is None else member
embed = discord.Embed(title = f"{member}", colour = member.colour)
embed.set_author(name = f"{member.id}", icon_url = member.avatar_url)
embed.set_thumbnail(url = member.avatar_url)
embed.add_field(name = "Joined Server:", value = f"<t:{int(member.joined_at.timestamp())}:R>", inline = True)
embed.add_field(name = "Joined Discord:", value = f"<t:{int(member.created_at.timestamp())}:R>", inline = True)
await ctx.reply(embed = embed)```
Is this in a cog or not?
yeah it's in a cog
Then ctx should work 
yeah that's what I was thinking
the weird thing is I have exactly the same code in slash command and it's working fine
@commands.command()
async def register(self, ctx):
register_questions = ['What is your Epic Games username?', 'What platform do you play on?', 'What input do you play on?', 'What region do you play on?']
register_answers = []
EpicUser = str(register_answers[0])
Platform = str(register_answers[1])
Input = str(register_answers[2])
Region = str(register_answers[3])
# Checking to be sure the author is the one who answered and in which channel
def check(m):
return m.author == ctx.author and m.channel == ctx.channel
# Asks the questions from the register_questions list 1 by 1
# Times out if the user doesn't answer within 30 seconds
for question in register_questions:
await ctx.send(question)
try:
message = await self.client.wait_for('message', timeout= 30.0, check = check)
except asyncio.TimeoutError:
await ctx.send('You didn\'t answer in time. Please try again and be sure to send your answer within 30 seconds of the question.')
return
else:
register_answers.append(message.content)
with open("users.json", "w") as file:
json.dump(EpicUser, Platform, Input, Region, file)```
Everything works as intended (not done) but i get the error `EpicUser = str(register_answers[0]) IndexError: list index out of range` can someone help me fix this? I've tried a few things but nothing seems to work.
pretty new to discordpy and python in general
Register_answers is empty. There is nothing in the first spot
If you print register_answers to the console it will likely be an empty list which means whatver is supposed to be in it isnt getting into it
okay thank you
@sick birch do you know much about migrating to slash commands? Or know of any sources to help?
No dependencies to install or update /home/runner/SALRP/venv/lib/python3.8/site-packages/setuptools/command/install.py:34: SetuptoolsDeprecationWarning: setup.py install is deprecated. Use build and pip and other standards-based tools.
what does this mean
What were you trying to do?
@sick birch help this person
That's \n bru
wat
i dont think its supposed to look like this? so how do i put an extra blank line
!e
print("Hello\nWorld")
@slate swan :white_check_mark: Your eval job has completed with return code 0.
001 | Hello
002 | World
okay, thats very helpful. but how do i put a space on line 002 and "world" on line 003
you dont thats the output
bruh
\n creates a new line
!e
print("Hello\n\nWorld")
@final iron :white_check_mark: Your eval job has completed with return code 0.
001 | Hello
002 |
003 | World
thank you
@commands.command()
async def register(self, ctx):
register_questions = ['What is your Epic Games username?', 'What platform do you play on?', 'What input do you play on?', 'What region do you play on?']
register_answers = []
EpicUser = str(register_answers[0])
Platform = str(register_answers[1])
Input = str(register_answers[2])
Region = str(register_answers[3])
# Checking to be sure the author is the one who answered and in which channel
def check(m):
return m.author == ctx.author and m.channel == ctx.channel
# Asks the questions from the register_questions list 1 by 1
# Times out if the user doesn't answer within 30 seconds
for question in register_questions:
await ctx.send(question)
try:
message = await self.client.wait_for('message', timeout= 30.0, check = check)
except asyncio.TimeoutError:
await ctx.send('You didn\'t answer in time. Please try again and be sure to send your answer within 30 seconds of the question.')
return
else:
register_answers.append(message.content)
with open("users.json", "w") as file:
json.dump(EpicUser, Platform, Input, Region, file)```
Everything works as intended (not done) but i get the error `EpicUser = str(register_answers[0]) IndexError: list index out of range` can someone help me log the register answers properly. I've tried a few things but nothing seems to work. Im pretty new to python so dont be to harsh on me please.
wouldnt this be considered databases?
Nah, I haven't worked on discord bots in a while, stopped working a little bit after all the slash command fiasco, so never really got into it. I did make a bit of a prototype where I used a custom decorator and used on_interaction to pick up slash commands, pretty similar to what discord.ext.commands does. If you wanna know more about that I'll be glad to tell you everything I know
no
hes just storing stuff in a json file
and json isnt for storing data
a database is for storing data tho
JSON is a serialization format, not for storing data yes ^
i.e making a request to an api most apis format the data or response body in json
Slash commands are so painful 😔
how much rewrites?
Not even using them, just trying to figure out the cleanest way to create a frontend for them
Indeed, many APIs are built with javascript and obviously, javascript makes it easy to work with javascript object notation.
Still on the 4th slash commands rewrite
yup
bruh
I will start the 5th iteration of slash commands for Rin soon
pain
I have no clue what to do
By now If I found something I liked I could've been done already
😔
bozo
Ill take a reign check on that. It sounds super interesting and might be a road i try going down
guys, why is my error code eating my console error?
# @purge.error
# async def purge_error(self, ctx, error):
# if isinstance(error, commands.MissingPermissions):
# await ctx.send('**:x: | You do not have permission to use this command!**')```
If the error isn't an instance of commands.MissingPermissions, it's simply ignored
Add an else statement, that way you can handle all other errors
and why is everything a comment
idk
how do i add an else statement?
How you would normally add an if statement
idk
if(...):
# if block
else:
# the else statement
Just print out the error
idk how
So it doesn't get eaten
else:
await ctx.send(error)
for any other errors it will send them
Hmm I don't like that one
It doesn't print the traceback
error.__traceback__ does iirc
@commands.command()
async def register(self, ctx):
register_questions = ['What is your Epic Games username?', 'What platform do you play on?', 'What input do you play on?', 'What region do you play on?']
register_answers = []
# Checking to be sure the author is the one who answered and in which channel
def check(m):
return m.author == ctx.author and m.channel == ctx.channel
# Asks the questions from the register_questions list 1 by 1
# Times out if the user doesn't answer within 30 seconds
for question in register_questions:
await ctx.send(question)
user = {
'EpicUser' : str(register_answers[0]),
'Platform' : str(register_answers[1]),
'Input' : str(register_answers[2]),
'Region' : str(register_answers[3])}
try:
message = await self.client.wait_for('message', timeout= 30.0, check = check)
except asyncio.TimeoutError:
await ctx.send('You didn\'t answer in time. Please try again and be sure to send your answer within 30 seconds of the question.')
return
else:
register_answers.append(message.content)
print (f'{register_answers}')
await ctx.send(f'Username{user["EpicUser"]}, Platform{user["Platform"]}, Input{user["Input"]}, Region{user["Region"]}')
with open("users.json", "w") as file:
json.dump(user, file)```
How would I be able to log the answer to each question as an answer? Im very new to python and this is my first large project so sorry if the solution is really simple.
could you explain wym by "log" ?
sending the answer to question in some channel?
think they mean storing it
add it to the register_answers list
@slate swan :white_check_mark: Your eval job has completed with return code 0.
['a text']
like this^
i have answers.append but i get the error IndexError: list index out of range still
which line
File "/home/runner/Elo-Bot/cogs/register.py", line 31, in register
'EpicUser' : str(register_answers[0]),
IndexError: list index out of range
register_answers.append(message.content) shouldnt this be register_answers.append(ctx.message.content)?
register_answers = [] # Empty list
for question in register_questions:
await ctx.send(question) # sends the question in channel
user = {
'EpicUser' : str(register_answers[0]) # now you are asking for the register_answers[0] before appending to it```
user = {
'EpicUser' : str(register_answers[0]),
'Platform' : str(register_answers[1]),
'Input' : str(register_answers[2]),
'Region' : str(register_answers[3])} ``` you havent recorded any response yet
move it outseide the for loop
whats the best free host in which i can make my bot
check pins
^^
lots of messages
i tagged the message
oh so they all are free
thank you
no
then
read what it says below, there's no good free option for hosting
but i asked for the free one
isnt there any free except repl.it
google cloud and aws provide free trials
there's none
replit is not a host, stop calling it a host.
there is so much free servers....
repl.it is a worst thing to host
and there is no good free host
yea, webservers exist by some hosting services on discord
fine
i mean like is the free servers not strong enough? i don't get it
doesn't like every thing have free servers
1sec
they are, but they dont have a good privacy policy
they got your token and stuff
yeah every server going to have your token
some like hiroku i think thats the name can technically host one but is designed for webapps not bots and i think commonly runs into ratelimit issues
how else could it work
Need to run your bot 24/7? Get a cheap VPS.
https://www.scaleway.com/ EU https://www.linode.com/ US/EU/Asia
https://www.digitalocean.com/ US https://www.vultr.com/ US
https://www.ovh.co.uk/ EU/Canada https://www.hetzner.com/ Germany/US
https://www.time4vps.eu/ Lithuania.
Self-hosting: Free hosting: Kinda free:
Any computer. No. Not even heroku. GCP, AWS have one year free micros.
if you use a server, the panel admins have complete acess to it, whereas with a good "paid" vps, that wont be the issue
google cloud and aws are considerable
😂 it would be too much load! and how would they get the src
ability for discord to host a bot with nitro subscription would be pog af
dont u think so?
idk i'm new
sorry sorry
mine's take around 200 mbs memory
i dont think they take too much until its in hundreds-thousands of servers taking many requests per second
yea depends on the cache
is there an easy way to get how many servers your bots in?
len(bot.guilds)
fuck, fair enough
!d discord.user.ClientUser.guilds
No documentation found for the requested symbol.
Uh
its just Client.guilds
It’s just Client
It's just
There is a ClientUser though
Yeah
!d discord.user.ClientUser
class discord.ClientUser```
Represents your Discord user.
x == y Checks if two users are equal.
x != y Checks if two users are not equal.
hash(x) Return the user’s hash.
str(x) Returns the user’s name with discriminator.
But that doesn’t hold the guilds property
it means the user of the Bot, so you're doing like discord.User.guilds
no way, for those bots in 3m servers how do they even run
By having many resources
100TB memory? idk
they dont use a free host
bots like carl bot hold gigabytes of cache
im taking example of carl since it uses discord.py
that’s definitely not how that works
okie
depends on members and other cache
if you keep all the intents off ( a RESTClient ) its barely 50 mb
oof the rabbit hole goes really far
but it wont be able to interact with the gateway, only requests will be made
thanks
Could get even lower than that, the only thing a rest client needs is a auth token, and a request handler, usually I'd assume would be storing ratelimit buckets in-memory. Other than that no cache is needed, you can basically have a stateless bot
People also do this with slash commands, setting up an interactions redirect URI which sends to their running servers, validating the request then returning a json object representing the interaction response
I'm sure you could get even lower than 50mb with some setups
While still being effective
cool
not anymore
the developers are planning to use py-cord now
You can also combine the regular gateway with slash command handling on a separate process via the an http server
Splitting up the resources even more
No they are rewriting it in rust already, pycord is being used for a minimal time ( atleast that's what I was told)
Nvm rust rewrite is not being done
Yea that's helpful in making dashboard kind of stuff too
hikari or disnake
is it possible to use the stuff like slash commands in discord py?
Yep, although it only makes handling interactions somewhat easier? Actually depends on skill level I'd say. If your not experienced it will be difficult as you won't have as many syntactic sugars/library abstractions
The response is also limited, somewhat? Or at least hard to use in a powerful manner
At least from my expirences
both hikari and Disnake have slash commands,
Hikari has a bit hard ( or maybe not regular discord.py like) syntax
Disnake has easier way of doing things
ok i'll do disnake because i prefer some easy way
it doesn't cache things so most of the things would be done with api requests right? Like getting the user object of the interaction author and othe things
Models are mostly dependent on cache and gateway events
You'd need to do an http request to get, modify, etc
that was carl-groth the old owner of the bot i think
well if you talk about easy ways, just to let you know hikari's lightbulb command handler allows you to make slash command and prefix command all together
I just saw it in some to-do list for carl-bot, I have no idea why
That's what the new Devs chose , the original developer was Rewriting it in rust
examples/basic_slash_command_bot_example.py lines 22 to 28
@bot.command()
@lightbulb.command("ping", "Checks that the bot is alive")
@lightbulb.implements(lightbulb.SlashCommand)
async def ping(ctx: lightbulb.Context) -> None:
"""Checks that the bot is alive"""
await ctx.respond("Pong!")```
inb4 64 gigabytes of cache
yea ofcourse, thats how the 3rd party libs manage to do it
Was the bot bought or did the owners switch
Can you show the native implementation
I am down bad for implementations 😔
sure, lemme see if there are any examples
since i never used that in raw hikari
well this is the SlashCommand class
anyone how to make a command that gives a radom message every time using hikari
https://www.hikari-py.dev/hikari/impl/rest.html#hikari.impl.rest.RESTClientImpl.create_slash_command
its in the rest
Ah, creating the slash command is easy, I've rewritten rin's implementation 4 times. I just haven't found a good way of implementing a frontend for users
Which I'm mostly interested in finding stuff for
Hey how to boost ban speed
I couldnt increase ban spd even using api
Pls help
I want bans in 0.1 millisecond lmao
you use the API anyways?
Do you have internet that fast?
since banning users is a coroutine
0.1 milisecond 👁️
Your gonna need an ethernet connection directly to discord's servers
Replit
LOL
thats a joke right?
@commands.Cog.listener()
async def on_member_ban(self, guild, user):
start = datetime.datetime.now().timestamp()
reason = "R Anti-Nuke | Banning Members"
logs = await guild.audit_logs(limit=1, action=discord.AuditLogAction.ban).flatten()
logs = logs[0]
user = logs.user.id
async with aiohttp.ClientSession(headers = { 'Authorization': f'Bot {self.client.http.token}', 'Content-Type': 'application/json' }) as session:
async with session.put("https://discord.com/api/v9/guilds/%s/bans/%s" % (guild.id, user), json={"reason": reason}) as r:
took = round((datetime.datetime.now().timestamp() - start), 3)
if r.status in (200, 201, 204):
logging.info("Successfully banned %s" % (user))
c = self.client.get_channel(940208901528363028)
await c.send(f"Banned %s, took: {took}" % (user))
else:
logging.error(f"Could not ban %s" % (user)) ```
Here is my code how to do tgat
This ban in 0.4
Sec need 0.1 sec
Ban
If you want speed, python isn't the language for you
Which lang is for spd then
Low level languages like rust
is the current implementation pushed in the repo? id like to check it out
@vocal snow how to make threaded ban in this
How add httpx aio
Pls help
Need help in adding httpx
It is not
that's why I've rewritten it so many times
I haven't found anything good
For frontend use that is, everything backend is easy
@slate swan bro do u know how to use httpx
from __future__ import annotations
import asyncio
import logging
import os
import rin
logging.basicConfig(level=logging.DEBUG)
client = rin.GatewayClient(os.environ["DISCORD_TOKEN"])
@client.once(rin.Events.READY)
async def ready(user: rin.User) -> None:
print(f"Logged in as {user}")
async with rin.ChatCommandBuilder(client, 837516299461591060) as builder:
with builder.options() as options:
options("user", type=rin.Member)
builder.description("An example description.")
builder.guilds(907106240537169980)
builder.name("demo")
@builder()
async def callback(interaction: rin.Interaction, user: rin.Member) -> None:
await interaction.send(f"Hey {user.mention}")
asyncio.run(client.start())
``` Heres one of them
yea, interface of slash command must be clear and handy ( and thats the only hard job )
import discord
import os
'''
reading key value pairs from .env
file and set them as envir variables
'''
#preventing enviroment pollution
from dotenv import load_dotenv
load_dotenv()
TOKEN_KEY = os.getenv('DISCORD_KEY')
bot_client = discord.Client()
@bot_client.event
# changes how call will behave
# must list event loop to run this part of code
async def on_ready(): # event handler
print(f'{bot_client.user} is connected to discord!')
bot_client.run(TOKEN_KEY)
So i've been trying to get this dotenv to work for quite a bit and honestly don't know what is wrong I don't think I need to install anything extra? am I missing something?
First or second iteration, scrapped in place of a generic builder
Then I scrapped that one,
seems good, the user variable in ready is for the bot user right?
Does discord have servers that fast 🤔
class Ping(slash_commands.SlashCommand):
name = "ping"
description = "Bot's Heartbeat Latency"
async def callback(self , ctx : lightbulb.SlashCommandContext )->None:
...
bot.add_slash_command(Ping)
``` another implementation
this one is lowkey simple
The 4th iteration was close to this, but instead the slash commands inherited the already implemented rin.Event allowing for ChatCommand.wait(), ChatCommand.dispatch(...) and @ChatCommand.on() along with the other variants of listeners
ChatCommand here means the application command ill assume
I've considered many design choices like this, and It seems I will ultimately have to use this sort
Application command can mean three things
any errors?
There are different types
oh ya, there are user commands too
The slash command one would be of the CHAT INPUT one
https://pypi.org/project/python-dotenv/ you have to install it
just use os.getenv
i'm dumb
ah, you're using it to load
works now thank you very much
Thoughts on doing ```py
@Something
class Command(...):
...
😔 I hate it still though
Nevermind still errors
does it say NoneType has no attribute strip ?
"This would be on the same level as event listeners", E.g ```py
@GatewayClient.on(rin.Events.READY)
async def ready(user: rin.user) -> None:
...
@ChatCommand(...)
class Command(...):
...
ModuleNotFoundError
restart vsc
Alright
this one seems kinda cool, a decorator would be handy
still errors
what about the options? would you implement it in the decorator or as function arguments
'''
An account
an application - allows interaction with discord API
a bot
a guild
'''
#bot.py
import discord
import os
'''
reading key value pairs from .env
file and set them as envir variables
'''
#preventing enviroment pollution
from dotenv import load_dotenv
load_dotenv()
TOKEN_KEY = os.getenv('DISCORD_KEY')
bot_client = discord.Client()
@bot_client.event
# changes how call will behave
# must list event loop to run this part of code
async def on_ready(): # event handler
print(f'{bot_client.user} is connected to discord!')
bot_client.run(TOKEN_KEY)
os.getenv should work normally in most of the cases
remove the ```py
from dotenv import load_dotenv
load_dotenv()``` part
alright
and see if it still causes an problem
@GatewayClient.once(rin.Events.READY) # NOTE: `ONCE`
async def ready(user: rin.User) -> None:
print(f"LOGGED IN AS {user}")
@ChatCommand(...)
class Command(name="demo", ...):
... # set things here
# ^^^ Caches internally via decorator.
@AppCommands["demo"].on()
async def callback(...) -> None:
...
@AppCommands["demo"].once()
async def callback(...) -> None:
...
@AppCommands["demo"].collect(amount=5)
async def callback(...) -> None:
...
``` Thoughts
Options would be defined inside of the classes namespace
Setting in READY listener to register the command itself internally via rest
i like your collect implementation, and will the user be able implement more than 1 kind of decorator ( .on()/.collect()) at the same time? ig not
since that ends the point of having seperate decos
Yes, the current implementation of rin.Event allows for events that DON'T block other events at all, even with the collector
If slash commands inherit rin.Event they gain all the pros from rin.Event
There is a hierarchy between which gets called first though
ah, makes sense
First-Last Listeners + Temp Listeners -> Futures -> Collectors
import discord
from discord.ext.commands import Bot
from discord.ext import commands
import random
client = discord.Client()
bot = commands.Bot(command_prefix = '$')
@client.event
async def on_ready():
print('We have logged in as {0.user}'.format(client))
@bot.command()
async def whydidyoucry(message):
whyICried = ['1', '2', '3']
await message.channel.send(random.choice(whyICried))
client.run(token_goes_here)
started learning discord.py today
whats with @bot.command()
it wont work
You should only have one bot or client remove client and change client.event to bot.event and client.run to bot.run
Hello, could anyone tell me what I am doing wrong here? A bit new to discord.py and python in general. Looked around online a lot but can't seem to figure it out. I am getting error "member is a required argument that is missing"
@bot.command()
async def cleanup(ctx, member: discord.Member):
big_airut_speedrun_1_id = 826189814596108378
big_airut_speedrun_2_id = 762488902304006174
big_airut_speedrun_3_id = 757836549361762424
big_airut_speedrun_1 = ctx.guild.get_roles(big_airut_speedrun_1_id)
big_airut_speedrun_2 = ctx.guild.get_roles(big_airut_speedrun_2_id)
big_airut_speedrun_3 = ctx.guild.get_roles(big_airut_speedrun_3_id)
if member.has_roles(big_airut_speedrun_1):
await member.remove_roles(big_airut_speedrun_2, big_airut_speedrun_3)
elif member.has_roles(big_airut_speedrun_2):
await member.remove_roles(big_airut_speedrun_3)
else:
await ctx.channel.send('None found.')
you didn't mention a member while running the command
And member has no attribute has_role
not sure what you mean exactly? like, a specific user id?
i am trying to have it go through all users in the server
member.has_roles is not a thing
yea i gotcha there, will deal with that. but i think that would be a different error no? i think this is something wrong with the arguments line?
import discord
from discord.ext.commands import Bot
from discord.ext import commands
import random
client = discord.Client()
bot = commands.Bot(command_prefix = '$')
@bot.event
async def on_ready():
print('We have logged in as {0.user}'.format(bot))
@bot.command()
async def whydidyoucry(message):
whyICried = ['1', '2', '3']
await message.channel.send(random.choice(whyICried))
@bot.command()
async def spam(message):
text_to_spam = message.content.split(' ')
amount_to_spam = int(message.content.split()[2])
amount_spammed = 0
while amount_spammed > amount_to_spam:
await message.channel.send(text_to_spam)
bot.run('')
i get this error
