#discord-bots
1 messages · Page 1117 of 1
why (?
why do you have ( after the embed object?
thats not how it works.
!d discord.Embed.add_field
add_field(*, name, value, inline=True)```
Adds a field to the embed object.
This function returns the class instance to allow for fluent-style chaining. Can only be up to 25 fields.
ohh
btw i love your pfp
thx
Hello, I am trying to figure out how to sync my python discord bot commands to the built in command tree on discord that displays your command options when you type in the prefix. Can someone please help me?
okay so how would i make it so 2 get displayed on one line? the problem is if i change any to false they all seperate if they are all true then they are all inline
is that a capybara too?
yes
set it to False to make them appear in different lines
CAPYBARAS are the best animal
cats supermacy.
i set them to false and they all appeared in seperate lines
like even if i alternated false and true
a cat cant compare to a god?
factual
dpy doesnt create default slash help does it?
you can't compare gods*
thats right i cant compare to a capybara
it doesn't, not everthing's lightbulb lmao
well discord embed fields are really hard to understand, you can just try and see the results
alright ill try a few things
oki you ever worked with image manipulation?
never
#media-processing @slate swan
best place 😔
I know 😔 just confirming daddy
ayo?
all the fields have to be inline=True
if you want all the fields to be on the same line
but then update will be on the line with whois and usage
is updates inline True?
in this one its false
its supposed to go below whois
then it will go in line 😭
yeah and how would you like it?
Whois Usage
Update Usage
ah well set update to false
even tho
are you trying to do something like that?
no
and you want the usage to be next to update?
exactly like this
X y
W v
yes
ah
is that even possible 😭
well i dont think so because it would just go the the first row if its inline
so what should i do? add a third useless embed?
like a filler one?
yep
u want the fields in that fashion?
yeah
try these configs for iniline, False, True, False, True @eager bluff
i did
what did u get?
thats this
its because there is something above it
which is not inline
oh
yeaht thats what im doing rn
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: Forbidden: 403 Forbidden (error code: 50013): Missing Permissions
why do i get this error when other commands that need the same permissions works?
show permissions for both
just give admin
not a good idea
no bot should have admin perms its pretty dangerous
Does anyone know how to sync bot commands to the built in commands in discord? 😅
not my server, cant give admin
???
i mean if its your bot
@commands.command(aliases = ["123", "321"])
async def command_Forge_image(self, ctx, member: discord.Member = None):
if ctx.author.id == 567107484850847744:
img = requests.get(i_background, stream = True)
img = Image.open(io.BytesIO(img.content))
img = img.convert('RGBA')
img1 = requests.get(i_frame, stream = True)
img1 = Image.open(io.BytesIO(img1.content))
img1= img1.convert('RGBA')
img1M = requests.get(i_frameM, stream = True)
img1M = Image.open(io.BytesIO(img1M.content))
img1M= img.convert('L')
img.paste(img1M, (0,0))
img.save('./ImageS/kik.png') # сохранил картинку
embed = discord.Embed(
title = "123",
color= 0xff0000
)
file1 = discord.File("./ImageS/kik.png")
embed.set_image(url='attachment://kik.png')
await ctx.send(file=file1, embed=embed)
os.remove("./ImageS/kik.png")
dear please tell me what is the problem
wdym sync commands with builtin commands?
heres the roles it has for that channel and the bot role permissions
it was able to send embed for another command but i guess its not able to now?
it works in a different channel tho
If you type slash “/“ right now inside of the chat, it will display options of the commands available. I would like that for my bot @paper sluice
which library do u use?
are you missing the application commands scope?
no i had it ticked
I’m assuming you mean import discord from discord.ext import commands? @paper sluice
create em eperately
so you're using discord.py?
Yes I am @slate swan
hm
then why subclass?
if its discord.py you do bot.tree.sync
!d discord.app_commands.CommandTree.sync
await sync(*, guild=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Syncs the application commands to Discord.
This must be called for the application commands to show up.
button1 = discord.ui.Button(label=..., ...)
button2 = discord.ui.Button(label=..., ...)
like that?
I’ve seen that but I can’t import app_commands. I manually put the folders in aside from regular installation and it still doesn’t take.
how to send dm to a specific uset
with a if
id
!d discord.User.send
await send(content=None, *, tts=False, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=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/latest/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.10)") of [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File "discord.File") objects. **Specifying both parameters will lead to an exception**.
To upload a single embed, the `embed` parameter should be used with a single [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed "discord.Embed") object. To upload multiple embeds, the `embeds` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.10)") of [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed "discord.Embed") objects. **Specifying both parameters will lead to an exception**.
fetch the user
ni
i'm afraid that I might be clueless about that
!d discord.ext.commands.Bot.fetch_user
await fetch_user(user_id, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Retrieves a [`User`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User "discord.User") based on their ID. You do not have to share any guilds with the user to get this information, however many operations do require that you do.
Note
This method is an API call. If you have [`discord.Intents.members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.members "discord.Intents.members") and member cache enabled, consider [`get_user()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.get_user "discord.ext.commands.Bot.get_user") instead.
Changed in version 2.0: `user_id` parameter is now positional-only.
no just do bot.tree.sync it calls the commandtree for u
poor ryuga 😔
no i want message to only send in 716707479005823036 dms [my id]
well then just use the id attr
The user’s unique ID.
get brad to pin it
imagine getting pinned by a god
I already think that there are max pins to the channel
@commands.command(aliases = ["123", "321"])
async def command_Forge_image(self, ctx, member: discord.Member = None):
if ctx.author.id == 567107484850847744:
img = requests.get(i_background, stream = True)
img = Image.open(io.BytesIO(img.content))
img = img.convert('RGBA')
img1 = requests.get(i_frame, stream = True)
img1 = Image.open(io.BytesIO(img1.content))
img1= img1.convert('RGBA')
img1M = requests.get(i_frameM, stream = True)
img1M = Image.open(io.BytesIO(img1M.content))
img1M= img.convert('L')
img.paste(img1M, (0,0))
img.save('./ImageS/kik.png') # сохранил картинку
embed = discord.Embed(
title = "123",
color= 0xff0000
)
file1 = discord.File("./ImageS/kik.png")
embed.set_image(url='attachment://kik.png')
await ctx.send(file=file1, embed=embed)
os.remove("./ImageS/kik.png")
dear please tell me what is the problem
sadge
#discord-bots message they can unpin this
:))
hey brad, could this get pinned by any chance? @velvet compass
i mean they can clean up some outdated stuff, there is a pinned guide from 2018
🙏
ah
hes on a mission in some planet, no hes back les go
how? can u show me an exaple
Uhhh maybe? I'll bring it up internally 👍
oki
lmao
please im struggi=ling]
#discord-bots message and maybe you can unpin this if the pin channel limit is max
plead=se
there are multiple outdated pinned tutorials which u guys can clean up
>> user = bot.get_user(_id) or await bot.fetch_user(_id) #user must be an instance of a User object
>> user.id
>> 1234567890987654321
If the only way to send modals through interaction how would I send a modal from adding a reacting to a message
fake py repl
i want it to be my own iddddddddddddddd
then just hardcode the id
i want to send message to mhse
how
copy your id
and???
my_id = 716707479005823036 ( i copied ur id, so u can use it )
i tried it
!d discord.ext.commands.Bot.owner_id 😳
The user ID that owns the bot. If this is not set and is then queried via is_owner() then it is fetched automatically using application_info().
and?
because you need a User object
that too
howoww
so fetch it or get it from cache
get object from the id as ashely showed
oooay
dont ignore poor ash
🗿
okimii said the truth for the first time
I'm poor 😭
🗿
huh 
😔
yey my fav watchdog
i dont even have a dollar in my wallet, in debt😔
i dont have a wallet 😳
bro🤨
I only have like 30 pounds in mine 😔
mine has dust
and allot of it
you fill it with sand or what 😔
i wish
😳
ur acting like sparky
im not sparky
# If reacted with 'No'
elif str(reaction.emoji) == '':
class rejection_modal(ui.Modal, title="Suggestion Rejected"):
reason = ui.TextInput(
label=f'Suggestion:\n{self.answer_one}',
style=discord.TextStyle.long,
placeholder='Input the reason for rejection',
required=True,
max_length=500)
answer_one = self.answer_one
async def on_submit(self, interaction: discord.Interaction):
suggestion_embed = discord.Embed(
title='Suggestion Rejected',
description=f'**{self.answer_one.label}**\n{self.answer_one}\n\n**Reason**\n{self.reason}',
timestamp=datetime.now(),
color=0xef484a) # Red
# Updating suggestion in staff channel
suggestion_embed.set_author(name=interaction.user, icon_url=interaction.user.avatar)
suggestion_embed.set_footer(text=f'Rejected by {user}')
await suggestion_message.edit(embed=suggestion_embed)
# Alerting user of rejected suggestion
await interaction.user.send(embed=suggestion_embed)
await interaction.response.send_modal(rejection_modal()) # ERROR HERE
Can someone explain his error to me?
oh thats a lot
rip chat
cute check
now i have to use mouse
and the class being inside an if statement pfffttt
im sti;ll confused
how do i do it
I made it smaller 😬
god damn
😏
i sometimes struggle to see text at 100, i need to get glasses ff
dunno, even I gotta get colourblind glasses at some point
how would i make it so coolo becomes the next value? e.g if it find that you're in between 80 and 100000 instead of becoming 80 it becomes 100000
oop
accidentally replied
myid = 243434553465453
@bot.command
async def send():
myid.send("message")
uel;-'
help
get the object from the id (#discord-bots message)
i want it to send it to myself onlyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy
oeijrhbsu
thats not how oop works
you would need to get the object by placing your id in the method. hence making a user object and then making able to send a message.
buddy, myid right now is a python int, u cannot send messages to a python int, you have to convert it to a discord.Member/User object to send a message
this is why learning OOP is recommended b4 jumping into discord bots
why does coolo not become the next index number? it says index list out of range
because ur going of index on cutoffs, thats like trying to do [1][1]
ok [1][1] is a little confusing, how about a = [1] then a[1]
ah alright so what would i have to do instead
umm idk, stop b4 going out of index?
Indentation
Indentation is leading whitespace (spaces and tabs) at the beginning of a line of code. In the case of Python, they are used to determine the grouping of statements.
Spaces should be preferred over tabs. To be clear, this is in reference to the character itself, not the keys on a keyboard. Your editor/IDE should be configured to insert spaces when the TAB key is pressed. The amount of spaces should be a multiple of 4, except optionally in the case of continuation lines.
Example
def foo():
bar = 'baz' # indented one level
if bar == 'baz':
print('ham') # indented two levels
return bar # indented one level
The first line is not indented. The next two lines are indented to be inside of the function definition. They will only run when the function is called. The fourth line is indented to be inside the if statement, and will only run if the if statement evaluates to True. The fifth and last line is like the 2nd and 3rd and will always run when the function is called. It effectively closes the if statement above as no more lines can be inside the if statement below that line.
Indentation is used after:
1. Compound statements (eg. if, while, for, try, with, def, class, and their counterparts)
2. Continuation lines
More Info
1. Indentation style guide
2. Tabs or Spaces?
3. Official docs on indentation
Yes I’m on my phone lmao
elif message.content.lower() == 'optimization':
await message.channel.send(
'alright, please redirect yourself too https://tweakersempire.org/ and make a appointment' + (
message.author.mention))
spell and grammar mistake 😔
ive noticed, a lot of ppl code on their phones
?
Just doing it because I’m at school lmao
just steal school computer, thats what i did 😎
pay attention
redirect yourself to https://uwufy.uwu and make an appointment
bro
same pinch
Well. If you are in a agriculture class it’s a diff story
Not a important class
agriculture is the best class no cap
what
It’s so bad
then learn how to create an instance of a crop
are you scared of grass🙀
agriculture is so fun
Planting shi, is fun LMAO
one time i was riding a pig through the school
🙏
I’m in Canada stuff is so different
tf
How is that relevant to discord bots?
its relevant
i made a discord bot out of that idea😳
i made my discord bot attend school for me
pay attention on planting crops /jk
💀
Yeah well this channel is for the discord bot library, not riding pigs thru schools.
if anyone wants a professional website made for thier bot, hmu,ill make it for free, im full stack web dev looking for projects
Just saying
cool
youre just mad you werent hog rider for a day😔
I’ll pay attention In class once my indent issue is fixed
but, what about my bot which gradated high school 😔
I created an app for joining google meets at specific times everyday, kinda lost my mind when my laptop died for good
😔
Definitely the wrong channel mate
my bot because me
elif message.content.lower() == 'optimization':
await message.channel.send(
'alright, please redirect yourself too https://tweakersempire.org/ and make a appointment' + (
message.author.mention))
its related to discord bots
Fix for idents
lol
But not to coding discord bots.
ppl so uptight
^
Sten trying to keep this channel together, where us rebels are tearing it apart
anyways, lets help him out
i legit clicked on his profile to check
love this guy already
me too me too
!ot
Off-topic channel: #ot2-never-nester’s-nightmare
Please read our off-topic etiquette before participating in conversations.
😤
Can someone help me man please lmao
hun bun....I'm sure Hunter wont like you saying that name here in the server
he wont mind
mhm
.topic
Suggest more topics here!
self destruct
an actual cache class
when u call library.self_desctruct it should runos.system('pip uninstall library')
💀
life would be soo much simpler
you wont have to worry about that stupid bot you were making anymore
this should be a mandatory feature imo
import pip
@bot.command()
async def self_destruct(ctx):
for guild in ctx.bot.guilds:
await guild.me.ban()
pip.main(["uninstall", "discord.py"])
uwu
lets make a discord.py to hikari convertor
same thought but who cares
lolllll
hikari, I LOVE hikari, but that aint possible, hikari is complex
how old does a discord account need to be to remove the wumpus message? trying to write a simple func to autoban potential alts
nothing is impossible
well...it isnt
wumpus message?
this
some guy is skidding my friend's business and profiting off of it
and made a bunch of alts to join the server to mass dm
cool, this isnt the correct channel
just thought since it was under "discord" i could get some help here xd
Lol
https://discord.gg/discord-developers try asking here
appreciated man
an env file
should i create a separate file for it and then get it from it?
you put it in a diff file and read from it
^
yes, you should
should i only name it .env?
how do i get my bot to enter a voice channel and if he disconnects he enters again when someone speaks in chat (any people)
I tried use on_message
you cant have voice receiving
you mean text?
Yee
what code do you have by far?
thanks @slate swan and @paper sluice 🙂
Huh?
Ryuga's smort, thanking him alone is good enough
Check it message.channel is same as channel object
2nd @client.event
do you want people to write in a specific channel only?
All channels
then....why would it want to join a specific channel always
Músic bot
It stays on voice channel
I tried use If but i dont know what do i put
havent used this emoji for some time
Eh ashley disappeared
how can the bot delete its message?
a specific message
like a warning or smth
anyone? 🙂
fetch the message and delete it
wdym by fetch?
!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/latest/api.html#discord.Message "discord.Message") from the destination.
I'd use an http method myself at this point, since fetch_message makes an api call
bot.http.delete_message(channel_id, message_id)
lmao
channel = bot.get_channel(...) or await bot.fetch_channel(...)
message = await channel.fetch_message(...)
await message.delete()
while http methods be -> await bot.http.delete_message(channel_id, message_id)
oooof
from discord.ext import commands, discord
So this?
wait
thanks
discord.InvalidArgument should work weird
do you know how to press enter as \n or \t etc.?
press enter...?
yes
oh \n
no not a new line
\t is for a tabbed space
yeah ik
then?
Sooo?
is there one for enter?
no?
alr then
i need to get a channel name
like when the bot sends a message with the name of the channel like this: #python-discussion
oof
!d discord.TextChannel.mention
property mention```
The string that allows you to mention the channel.
it works then
wdym?
anyways
how to extract a ping from a message, for example:
if i ping @slate swan, i want the bot to get the ashley user ping
is there a way to do this?
!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.
There finally
How to get entered information via custom_id ?
thanks, but idk how to have it implemented, im not so familiar with discord api
any tips?
hey, someone knows how can i sort it?
async def StartGame(interaction: Interaction, winners:int = SlashOption(name="Winners", description="How many winners will there be?", required=True)):
this says that int object is not iterable (an error)
according to documentation it is ok
how can I fix it?
its the winners:int = part I think
make a list instead and do player_ids.sort()
guys where should i store my token if it isn't in a variable if ima need to upload bot on repl.it?
Just dont use replit
Your reaction button class cant fetch a "max_reactions" variable, cause its not given
free hosting options?
Can someome help?
azure is free?
alrightie thank you
I know how to use gcp but it's not free
you have to link a credit card
.
oh ok
for Repl.it users: where do you store your Token?
EDIT: solved thank you :)
view = add_reactions(reactions=..., max_reactions=...)
You can pass it down again from your view to your button
class AddReactionsView(discord.ui.View):
def __init__(self, max_reactions: int):
super().__init__(...) # regular view initialisation
self.add_button(ReactionButton(max_reactions)) # notice how we're passing it down to the button?
...
class ReactionButton(discord.ui.Button):
def __init__(self, max_reactions: int):
self.max_reactions = max_reactions
super().__init__(...) # regular button initialisation
...
async def callback(self, interaction: discord.Interaction):
print(self.max_reactions) # you have access to max_reactions here
...
How can I make reaction roles?
Use the secret thing.
how do i get my bot to enter a voice channel and if he disconnects he enters again when someone speaks in text channel (any people)
I tried but dont work
Try, ```py
@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()
oh thank you !
Try, not spoonfeeding. 👌
I know it works, but I want the bot to stay on the voice channel forever and if it disconnects it comes back if anyone sends a message
Like
async def on_message(message):
channel = ctx.author.voice.channel
await channel.connect()```?
You might wanna put in a check because not everyone that sends a message is going to be in a voice channel
no yellow color robin 😳
can someone give me tips on how i would make a bot repeat exactly what i say in a diferent channel
so i can talk as the bot kinda
and it would go to another channel
just make an on message and fetch the channel once and then for each message it gets redirected to the channel you just fetched
How to get the first message in a channel?
!d discord.TextChannel.history
async for ... in history(*, limit=100, before=None, after=None, around=None, oldest_first=None)```
Returns an [asynchronous iterator](https://docs.python.org/3/glossary.html#term-asynchronous-iterator "(in Python v3.10)") that enables receiving the destination’s message history.
You must have [`read_message_history`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.read_message_history "discord.Permissions.read_message_history") permissions to use this.
Examples
Usage...
thanks
bluish greenish Robin
Robin keep defending the best letter in the alphabet aka R🙏
you got it boss
🙏
getting an error for inconsistent use of tabs and spaces in indentation in all the red areas, not sure what I need to change because it looks right to me
@client.command()
@commands.has_role('Staff')
async def reason(ctx, msgID: int, *, arg):
msg = await client.get_channel(876688282552008734).fetch_message(msgID)
embeds = msg.embeds
if embeds:
textcontent = msg.content
newembed = embeds[0].copy()
newembed.description =str("📄 **Reason:**\n" + arg)
await msg.edit(content = textcontent, embed = newembed)
else:
await ctx.send("Message has no embed.")
await ctx.message.delete()
@reason.error # <- name of the command + .error
async def reason_error(ctx, error):
if isinstance(error, commands.MissingRole):
await ctx.send("You do not have the required permissions to use this command: `Staff`")
hia
how can i delete messages from specific user?
for example
!delete @devout iris 20
Would that delete the last 20 messages by that user?
exactly
!d discord.TextChannel.purge
await purge(*, limit=100, check=..., before=None, after=None, around=None, oldest_first=None, bulk=True, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Purges a list of messages that meet the criteria given by the predicate `check`. If a `check` is not provided then all messages are deleted without discrimination.
You must have the [`manage_messages`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_messages "discord.Permissions.manage_messages") permission to delete messages even if they are your own. The [`read_message_history`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.read_message_history "discord.Permissions.read_message_history") permission is also needed to retrieve message history.
Changed in version 2.0: The `reason` keyword-only parameter was added.
Examples
Deleting bot’s messages...
It has a check parameter, use that to filter out the specific user
It could be a lambda that takes one arg, eg user then check if that user is the same one as the one given when invoking the command
check has to be a function
So what i do?
my bot with 1051 servers is ranked #1823
how many bots have more than 30k servers then
oh, 532 bots have 10k+ servers
Just to help.
that doesnt help anyone really. It doesnt really help them learn or understand anything.
I know, but they can look at it and look at there code and figure whats wrong.
most of the time they copy it without thinking
what do you expect will happen when you send a snippet of code without explaining anything
@sick birch congrats on project leads role!
wasn't he already project lead
I'm having a weird issue that I think is discord library related
I have a bot, follows artists on spotify, and pings new releases
Task loops to check for new releases every 10 minutes. Before I would occasionally receive a JsonDecodeError, which upon being raised, caused my loop to start working indefinitely
So I went ahead and used tasks.loop(minutes=10, reconnect=True), I added the reconnect parameter since from what I understand, should restart the loop despite exceptions
However, now I'm seeing a new issue that occurred hours into the bot being online. I got
TypeError: sleep() got an unexpected keyword argument 'loop'
Once this happens, program is awol on making more spotify requests. But responds to other slash commands that don't require spotify calls
Thank you! 😊
No, I was a just a helper before
occurred hours into the bot being online
sounds like something's happening after the loop tries to resume after your bot disconnects
Also makes sense that happened after you set reconnect=True as that's what that kwarg does
Basically, whenever a spotify call throws an exception (for unknown reason), loop never resumes
But I thought using that reconnect parameter would make the task resume from scratch
Proper error handling would fix that most likely
Damn, Am I just misunderstanding reconnect then?
do you have the full traceback of that error?
Sort of, as it's meant more for picking up after your bot disconnects from discord's server, not for errors/crashes
Yes, honestly it might be related to the spotify library, since it happens inside of a method in it, but I suspect that there's more to it than that, sending now.
asyncio.sleep's loop kwarg was removed in python 3.10 so your version of spotify might be incompatible with 3.10
that is assuming sleep() refers to asyncio.sleep()
Sorry, gonna send img since I can't seem to copy over my ssh terminal
Yes, it does, your theory seems likely since it is an outdated library
Hmm. Potential solutions that don't involve forking and pushing my own updates 
Well, I can avoid calling retry in the first place somehow...?
But is it the reconnect that's causing that to happen or is that totally unrelated?
reconnect= affects how dpy will handle your function when a connection error occurs, i.e. exponential backoff
Kk, so unrelated
Just weird that I never saw this issue prior to implementing it
I suppose I may just have to catch the exception and return None
looking at spotify's source you happened to have been ratelimited in your case
Thanks
According to the traceback, the error seems to originate as a result of passing of self.loop as loop parameter in asyncio.sleep, which is removed. So he will either have to monkey patch the lib or make a PR, no?
,yes I did
!d discord.Role.mention
property mention```
Returns a string that allows you to mention a role.
I mean, u get the role and use the mention property to mention the role...
Having a strange issue
class BanLogs(commands.Cog):
def __init__(self, client):
self.client = client
guild = client.get_guild(507364684924452896)
@commands.command()
@commands.has_role('Staff')
async def reason(self, ctx, msgID: int, *, arg):
msg = await client.get_channel(876688282552008734).fetch_message(msgID)
embeds = msg.embeds
if embeds:
textcontent = msg.content
newembed = embeds[0].copy()
newembed.description =str("📄 **Reason:**\n" + arg)
await msg.edit(content = textcontent, embed = newembed)
else:
await ctx.send("Message has no embed.")
await ctx.message.delete()
@reason.error
async def reason_error(self, ctx, error):
if isinstance(error, commands.MissingRole):
await ctx.send("You do not have the required permissions to use this command: `Staff`")
def setup(client):
client.add_cog(BanLogs(client))
``` when I have the commands decorator inline with `self.client = client`, none of my commands can be found (i.e.
`Ignoring exception in command None: discord.ext.commands.errors.CommandNotFound: Command "reason" is not found`, and when it's inline with `def __init__` , it comes back with `"client" is not defined`
I'm just not sure what I oughta do to fix that, and I was wondering if anyone could give some insight on it, any help is greatly appreciated
role mentions are formatted as <&ID>, however im not aware if github allows you to customize the message sent with it
dpy's Cog system works by using a metaclass to go through the different methods you define in your class and looking for the ones with the command decorator, which happens during the definition of your class
by defining your methods inside init, dpy wont see them when that happens, so your commands end up as just functions that get discarded afterwards
@sick birch what are the projects youre leading anyways?
havent seen you in a while. how is it going ?🙂
doing alright, had some fun writing an async lib for battleye rcon
I see, so I should define client above init
mhm thats nice and good to hear
well, cogs arent meant to have the client defined anywhere but in init or in an instance of the cog, otherwise you wont be able to write your cogs in another script
you should be just storing the id instead of Context itself, because context becomes invalid after some time, like a update in message, message getting deleted etc...
Hmm
you should reference client in your command using ctx.bot or self.client as you have defined in init
So should I remove ctx from await set_dono(interaction.guild)?
where did you get the ctx from at the first place?
if you want to acess ctx in a view, ill recommend passing it in the view's init dunder and making it an attribute of the view instead of making it an attribute of bot
class BanLogs(commands.Cog):
def __init__(self, client):
self.client = client
deltarune = client.get_guild(507364684924452896)
@commands.command()
@commands.has_role('Staff')
async def reason(self, ctx, msgID: int, *, arg):
msg = await self.client.get_channel(876688282552008734).fetch_message(msgID)
embeds = msg.embeds
if embeds:
textcontent = msg.content
newembed = embeds[0].copy()
newembed.description =str("📄 **Reason:**\n" + arg)
await msg.edit(content = textcontent, embed = newembed)
else:
await ctx.send("Message has no embed.")
await ctx.message.delete()
@reason.error # <- name of the command + .error
async def reason_error(self, ctx, error):
if isinstance(error, commands.MissingRole):
await ctx.send("You do not have the required permissions to use this command: `Staff`")
```hmm, if this is what you were meaning, it worked, but it's not responding to anything aside from the message edit, I.e. no ctx.send or ctx.message.delete
Traceback (most recent call last):
File "/Users/grayson/Documents/6Mans/cas_v9.py", line 1, in <module>
import discord
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/discord/__init__.py", line 20, in <module>
from .client import Client, AppInfo, ChannelPermissions
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/discord/client.py", line 38, in <module>
from .state import ConnectionState
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/discord/state.py", line 36, in <module>
from . import utils, compat
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/discord/compat.py", line 32
create_task = asyncio.async
^
SyntaxError: invalid syntax
Process finished with exit code 1
Any ideas?
Possible to do it without ctx?
This is discord.py before the rewrite, update your discord.py to either v1.7.3 or the master branch.
what IDE are you using?
pycharm
where do you want to send the message, like is that channel fixed? or something defined by the user
or the interaction channel itself
You are probably not using the right venv
It’s a fixed channel
imagine asking for help in here and dpy server simultaneously 😔
Ye ye ik
totally not checking which guild is better
probably dpy since they got contributors to the library helping mostly and they know their stuff
if i want to load a @bot.command to run code in a seperate file instead on continuing on below, how would i go about redirecting the code? i think thats the kinda thing a cog is used for tho i have no experience with them
but their toxicity-
is there any other way apart from a cog?
least you could do is make a Command in one and add it to the bot in another
I’ve asked most of my errors here
add/reference it how tho
as far as i was aware u cant import a 'command'
you still should use a cog, so I wont help you with that solution as it aint a good practice
and dirty, and could be broken
ah
there arent any ways unless you write logic functions and import them from other files and call them under your command passing in required arguments, that's even more messier
cogs are 100% authentic to use
isnt too much to learn how to use em is there
you can just inter.client.get_channel( that channel 's id).fetch_message then
ive had a brief google but need to look into it more i spose
nope, you just need to see basic structure, they have that in the docs
iirc
alr
you can but should not
as ash said, just use cogs
in case you're interested in "how"
hi, gm sarth 👋
gm Sparky
interaction.client.get_channel(e).fetch_message(my_msg.id)
``` sarth ^
yep and make sure to await it
k
class BanLogs(commands.Cog):
def __init__(self, client):
self.client = client
@commands.command()
@commands.has_role('Staff')
async def reason(self, ctx, msgID: int, *, arg):
await ctx.message.delete()
msg = await self.client.get_channel(876688282552008734).fetch_message(msgID)
embeds = msg.embeds
if embeds:
textcontent = msg.content
newembed = embeds[0].copy()
newembed.description =str("📄 **Reason:**\n" + arg)
await msg.edit(content = textcontent, embed = newembed)
else:
await ctx.send("Message has no embed.")
``` everything seems to working as intended here except for the ctx.send
Any idea why that might be?
no errors? that means the message msg has embeds
Hmm
’NoneType’ object has no attribute ‘fetch_message’
I tried it on a message sent by myself in the channel
Not one by the bot, so that's why I'm confused
whats the e variable?
make sure its
- an integer
- a valid channel id
it is a valied channel id + integer
Like, running it on a message with embeds works fine and edits it, but running it on one without doesn't send back the "Message has no embed."
Sarth ^
oh, thats wierd, you have access to your bot variable right? try using bot.get_channel
if that doesn't work you will need to fetch the channel
❔
show code
it wont just send Message has no embed
yk the e variable?
In my code,
It gets the channel
And the channel1 variable in it gets the channel’s id
oh so e is a channel itself?
yah
channel1 = dono[str(interaction.guild.id)]["channel"]
e = client.get_channel(channel1)
Nextcord dev?
oh so you would do e.fetch_message
Tysm it works
And yah
It is a “host” button in giveaway donation
So it is easier to host the giveaway
oh, thats noice
ryuga
ya?
uwu
💀
How to set a presence to your bot!
The gist linked below is an in depth tutorial on how to set a presence to your bot!
https://gist.github.com/Okimii/0b6e5dcfcfb895ef613ac59a4ecc096a
ignore the message!
😔 it sends the PRESENCE payload to the gateway not "gateway event to the gateway"
can you be a little bit more specific please?😅
the text is poorly punctuated 😔
in where you're warning about not changing presence in on_ready
but i passed it to a grammar checker 😦
its better worded so ill accept that recommendation
use grammarly
lmao not grammar, there's missing periods but im weird so ehhh
totally my gist moment
let me use another website
grammarly?
no
or maybe I could make a pull req
at this point just pay a person with an english degree to fix it
ask andy he'll use esoteric language which noone will understand but it will sound fancy
zeffo delete your message 😔
hi ashley
Anyone remember how to fix the certification error
that's not very nice
Hi and dont give weird ideas to andy 😔
:D
on Mac?
yeah
Getting [SSL: CERTIFICATE_VERIFY_FAILED] on Python 3 on OS X?
Navigate to your Applications/Python 3.X/ folder and double click the Install Certificates.command to fix this.
Happy coding!
andy's gist would probably be the most readable one
ty
who's andy lol
our deity
their name sounds hot 😍
Off-topic channel: #ot2-never-nester’s-nightmare
Please read our off-topic etiquette before participating in conversations.
👋
i still wonder if that emoji is a slapping one....
👏👏👏👏
"These are not the droids you're looking for"
^
smh i was just saying 'hello'
lmao
I wonder when Pydis admins are going to rename this channel to #ot3-discord-bots
special non-changing ot
no surprise why this is the 2nd most active channel
just okimii's flirting area
😍
ofc ryuga applies routine revives for keeping it alive
Okifynvwwami
^
I had an intercourse with okingfrmi
Your mum
bro
okimii that gist could be written in a better way ngl
too wordy and confusing and repeating
so could this sentence
"could be return"
eh
lmao
im down
just !d discord.Activity the users who ask how to set status 😩
lmao
!d discord.Activity
class discord.Activity(**kwargs)```
Represents an activity in Discord.
This could be an activity such as streaming, playing, listening or watching.
For memory optimisation purposes, some activities are offered in slimmed down versions:
• [`Game`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Game "discord.Game")
• [`Streaming`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Streaming "discord.Streaming")
they won't understand shit from this !
and watch them change it inside of on_ready
🗿
i actually do that too oh yes
bro
😭
I don't mind if my bot makes request to change status multiple times
don't mind when the bot gets ratelimited too
isnt it fine to make a task loop for that? or just put it in commands.Bot
assert dominance, set status in on_message
or have i been doing it wrong till date
That's the preferred way yes
ic
how?
it sends a gateway event not a request to be exact
reconnects can happen multiple times within the cooldown period bor
also can someone write PR to make better help cmd 😩
https://github.com/szskill/poll-bot/
bot = commands.Bot(...)
bot.presence_changed = False
@bot.listen("on_ready")
async def uwu():
if not presence_changed:
await bot.change_presence(...)
bot.presence_changed = True
easy
okay but who the fuck uses bot.listen
me
all my homies use bot.event
all my homies make an event system
i use listen so I can name all my functions uwu or smth
i forgor to tell im using hikari and that event gets triggered only once.
uwu
uwu
uwu
:tomstaring:
oh yeah
nova should be banned
broke the streak👀
I should be unalive but no one has managed to make it happen
!ot
Off-topic channel: #ot2-never-nester’s-nightmare
Please read our off-topic etiquette before participating in conversations.
😔 imagine wtf'ing uwu
Didn't ask but ok
ok
oki ^~^
wdym change_presence is a gateway event and not a request?
That means presence payloads are sent and received from the gateway!!
🥵
I forgor if that's true tho, what okavtrremi said
😳
okavtrremi
it's kind Sir "Okimii" III Jr.
disnake/gateway.py line 748
async def change_presence(```
it uses DiscordWebsocket.send which sends a str to the gateway
how does that still matter, the websocket is already ready.
disnake/gateway.py lines 726 to 728
async def send(self, data: str, /) -> None:
await self._rate_limiter.block()
await self.socket.send_str(data)```
on_ready gets fired only after the websocket is ready and connected to discord
maybe there are times when websocket needs to reconnect to discord 
yeah thats why the on_ready may get triggered multiple times
but there's no way that on_ready is getting triggerd and the bot is not connected with gateway
discord/state.py lines 585 to 586
self.dispatch('connect')
self._ready_task = asyncio.create_task(self._delay_ready())```
@slate swan I got questions
yeah that's true
the only reasons i see not doing stuff in on ready is that it gets triggered multiple times, cache issues and some limitations
i think they meant if it reconnects then there will be multiple reqs send for on_ready?
which you can prevent using wait_until_ready
pardon?
about?
and no i can't use the activity kwargs in bot because i need to get something from cache
why do you got disnake examples in the gist, like it's just the name of the lib that has changed, makes the gist look a bit more cluttered
it sends a gateway event not a request to be exact
the client is connected to the gateway?
the client would send a event payload to the gateway so ofc it would be connected.
thats the point, its already exchanging events... so whats the issue with sending one?
the ratelimits
20 times in 5 seconds
and yeah ratelimit is the thing i totally agree with, but I dont understand the getting disconnected from gateway yet.
well some libs have different implementations and i kinda wanted to be clear about the examples over saying "in disnake its all the same just different name spaces"
I think I read somewhere what can cause disconnection, I think it's in rd*nny
why did you censor it
yes
what
hm, I see
well theres nothing really wrong with it but its unnecessary and the only real issue is ratelimits and if they send a request with a method that calls the api but thats not really related to the convo
mhm
but its a tiny detail i kinda wanted to point out as well
@client.command()
@commands.has_role('Staff')
async def reason(ctx, msgID: int, *, arg):
msg = await client.get_channel(876688282552008734).fetch_message(msgID)
embeds = msg.embeds
if embeds:
textcontent = msg.content
newembed = embeds[0].copy()
newembed.description =str("📄 **Reason:**\n" + arg)
await msg.edit(content = textcontent, embed = newembed)
else:
await ctx.send("Message has no embed.")
await ctx.message.delete()``` Sorry Im late wah
this screams attribute error
? the get_channel part works, as well as the msg.edit
!d discord.Client.get_channel
get_channel(id, /)```
Returns a channel or thread with the given ID.
Changed in version 2.0: `id` parameter is now positional-only.
The part that isn't working is the ctx.send, even when the message has no embeds it won't send anything
that was my mistake i forgot the method was their
print embeds and check
it always returns a list iirc
if its empty the list would be empty and would have a falsy value making the else get triggered
yeah and if there's no embed it should trigger the else part
yup
and its not message_content intent as he probably invoked the command itself lol
they are using fetch_message so that won't matter anyways
yup
well idk im going to sleep😴
wait whats with the indentation
is it like that in ur file too
Ah shit wait that's from the old one where I accidentally used client
I deeply apologize
class BanLogs(commands.Cog):
def __init__(self, client):
self.client = client
@commands.command()
@commands.has_role('Staff')
async def reason(self, ctx, msgID: int, *, arg):
await ctx.message.delete()
msg = await self.client.get_channel(876688282552008734).fetch_message(msgID)
embeds = msg.embeds
if embeds:
textcontent = msg.content
newembed = embeds[0].copy()
newembed.description =str("📄 **Reason:**\n" + arg)
await msg.edit(content = textcontent, embed = newembed)
else:
await ctx.send("Message has no embed.")
@reason.error # <- name of the command + .error
async def reason_error(self, ctx, error):
if isinstance(error, commands.MissingRole):
await self.ctx.send("You do not have the required permissions to use this command: `Staff`")
Hope that explains the wonky indentation
async def StartGame(interaction: Interaction, winners: int = SlashOption(name="Winners", description="How many winners will there be?", required=True)):
Traceback (most recent call last):
File "c:\Users\Harshit\Desktop\raffle bot\main.py", line 29, in <module>
async def StartGame(interaction: Interaction, winners: int = SlashOption(name="Winners", description="How many winners will there be?", required=True)):
File "C:\Users\Harshit\AppData\Local\Programs\Python\Python39\lib\site-packages\nextcord\client.py", line 2043, in decorator
result = slash_command(name=name, description=description, guild_ids=guild_ids,
File "C:\Users\Harshit\AppData\Local\Programs\Python\Python39\lib\site-packages\nextcord\application_command.py", line 1245, in decorator
app_cmd = ApplicationCommand(
File "C:\Users\Harshit\AppData\Local\Programs\Python\Python39\lib\site-packages\nextcord\application_command.py", line 773, in __init__
self._guild_ids_to_rollout: Set[int] = set(guild_ids) if guild_ids else set()
TypeError: 'int' object is not iterable
according to the documentation I did nothing wrong
Also, this is a bit disconnected from my last question, but is there a way to query the audit logs for a specific user's unban reason in on_member_unban?
!d discord.Guild.audit_logs
async for ... in audit_logs(*, limit=100, before=..., after=..., oldest_first=..., user=..., action=...)```
Returns an [asynchronous iterator](https://docs.python.org/3/glossary.html#term-asynchronous-iterator "(in Python v3.10)") that enables receiving the guild’s audit logs.
You must have the [`view_audit_log`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.view_audit_log "discord.Permissions.view_audit_log") permission to use this.
Examples
Getting the first 100 entries:
```py
async for entry in guild.audit_logs(limit=100):
print(f'{entry.user} did {entry.action} to {entry.target}')
```...
why delete the message?
Ah, pretty much just so it goes away immediately after being ran
Mhm
gotcha
Hmm, I see how to get the user, target, action, and total entries, but would getting the reason be as simple as
async for entry in guild.audit_logs(limit=1, action=discord.AuditLogAction.unban):
reason = (f"{entry.reason}")
Or is that just an oversimplification
should
And then I'm not sure how that'd fit into something like this
# unban logs
@commands.Cog.listener()
async def on_member_unban(self, guild, user):
username = str(user)
userid = str(user.id)
textcontent = str(f"{userid}")
async for entry in guild.audit_logs(user=user, limit=1, action=discord.AuditLogAction.unban):
reason = (f"{entry.reason}")
unbanembed = discord.Embed(
title=f"{username} was unbanned",
description=f"📄 {reason}",
color=0x2ecc71)
unbanembed.timestamp = datetime.datetime.utcnow()
unbanembed.set_author(name="Action: Unban", icon_url="https://cdn.discordapp.com/attachments/881835799547609109/959135738379784192/900265836210696212.gif")
unbanembed.set_footer(text="$reason [MessageID] New Reason")
modlog = self.client.get_channel(876688282552008734)
await modlog.send(content = textcontent, embed = unbanembed)
what's the issue?
dpy is so effing weird
Ignoring exception in on_guild_available
Traceback (most recent call last):
File "C:\Users\Harshit\AppData\Local\Programs\Python\Python39\lib\site-packages\nextcord\client.py", line 415, in _run_event
await coro(*args, **kwargs)
File "C:\Users\Harshit\AppData\Local\Programs\Python\Python39\lib\site-packages\nextcord\client.py", line 1907, in on_guild_available
if (await guild.rollout_application_commands(
File "C:\Users\Harshit\AppData\Local\Programs\Python\Python39\lib\site-packages\nextcord\guild.py", line 3230, in rollout_application_commands
await self.register_new_application_commands(data=guild_payload)
File "C:\Users\Harshit\AppData\Local\Programs\Python\Python39\lib\site-packages\nextcord\guild.py", line 3244, in register_new_application_commands
await self._state.register_new_application_commands(data=data, guild_id=self.id)
File "C:\Users\Harshit\AppData\Local\Programs\Python\Python39\lib\site-packages\nextcord\state.py", line 736, in register_new_application_commands
await self.register_application_command(app_cmd, guild_id)
File "C:\Users\Harshit\AppData\Local\Programs\Python\Python39\lib\site-packages\nextcord\state.py", line 752, in register_application_command
raw_response = await self.http.upsert_guild_command(self.application_id, guild_id, payload)
File "C:\Users\Harshit\AppData\Local\Programs\Python\Python39\lib\site-packages\nextcord\http.py", line 337, in request
raise HTTPException(response, data)
nextcord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In options.0.name: Command name is invalid
Absolutely no clue what is causing this (nextcord slash commands)
the command names are the same as the function names
and my code is correct according to documentation
might as well want to show your command names
hi guys !
do u know how to get someone's bio with a bot? i need this person to be on same server
you can't
@bot.slash_command(name="startgtb", guild_ids=[guild_id], description="Starts the game of guessing the balance")
async def startgtb(interaction: Interaction, winners: int = SlashOption(name="Winners", description="How many winners will there be?", required=True)):
there's a server that gives u a custom role if you put their vanity link in bio :o
startgtb
stopgtb
guess
you can't access bio with a bot :)
okie thanks Ashley 
that's weird
why does the error say options.0.name
its manual
@commands.Cog.listener()
async def on_member_unban(self, deltarune, user):
async for entry in deltarune.audit_logs(user=user, limit=1, action=discord.AuditLogAction.unban):
reason = (f"{entry.reason}")
username = str(user)
userid = str(user.id)
textcontent = str(f"{userid}")
unbanembed = discord.Embed(title=f"{username} was unbanned", description=f"📄 **Reason:**\n{reason}", color=0x2ecc71,)
unbanembed.timestamp = datetime.datetime.utcnow()
unbanembed.set_author(name="Action: Unban", icon_url="https://cdn.discordapp.com/attachments/881835799547609109/959135738379784192/900265836210696212.gif")
unbanembed.set_footer(text="$reason [MessageID] New Reason")
modlog = self.client.get_channel(876688282552008734)
await modlog.send(content = textcontent, embed = unbanembed)
``` alright, I put it in like this, but it says unexpected indent at line 52 (`unbanembed = discord.Embed[...]`)
yeah I have been stuck on this since last night, nothing works and there is nothing on google
okie
welcome
could you paste whole of the code in a pasting service? and send the link here
use any of those
<> moment ehe
too much to do, so I though that i'd remove em when they'll embed lmao

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.
but yeah, I don't understand why it's saying there's an issue with indentation, unless I'm overlooking something
whole of the code smh
show a screenshot of your code
at line 52
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.
from discord docs it seems like Winners needs to be winners
there is a extra ,
If there is a lowercase variant of any letters used, you must use those
remove the ,
I'm thinking it may have to do with the async for... part, but I'm not sure where I'd move that to
the comma after color=
that shouldn't matter
^ and without it, same error
the options have to be lowercase, that fixes your issue ig
Any idea why it's an indentation error? Or did I hit the nail on the head with the async for part being the issue
Could you send your full code?
Sure
import discord
from discord.ext import commands
import re, datetime, json
from requests import get
class BanLogs(commands.Cog):
def __init__(self, client):
self.client = client
deltarune = client.get_guild(507364684924452896)
@commands.command()
@commands.has_role('Staff')
async def reason(self, ctx, msgID: int, *, arg):
await ctx.message.delete()
msg = await self.client.get_channel(876688282552008734).fetch_message(msgID)
embeds = msg.embeds
if embeds:
textcontent = msg.content
newembed = embeds[0].copy()
newembed.description =str("?? **Reason:**\n" + arg)
await msg.edit(content = textcontent, embed = newembed)
else:
await ctx.send("Invalid Message.")
@reason.error # <- name of the command + .error
async def reason_error(self, ctx, error):
if isinstance(error, commands.MissingRole):
await self.ctx.send("You do not have the required permissions to use this command: `Staff`")
@commands.command()
@commands.has_role('Staff')
async def censor(self, ctx, msgID: int):
await ctx.message.delete()
msg = await self.client.get_channel(876688282552008734).fetch_message(msgID)
embeds = msg.embeds
if embeds:
textcontent = msg.content
newembed = embeds[0].copy()
newembed.title =str("[CENSORED NAME] was banned")
await msg.edit(content = textcontent, embed = newembed)
else:
await ctx.send("Invalid Message.")
# unban logs
@commands.Cog.listener()
async def on_member_unban(self, deltarune, user):
async for entry in deltarune.audit_logs(user=user, limit=1, action=discord.AuditLogAction.unban):
reason = (f"{entry.reason}")
username = str(user)
userid = str(user.id)
textcontent = str(f"{userid}")
unbanembed = discord.Embed(title=f"{username} was unbanned", description=f"📄 **Reason:**\n{reason}", color=0x2ecc71,)
unbanembed.timestamp = datetime.datetime.utcnow()
unbanembed.set_author(name="Action: Unban", icon_url="https://cdn.discordapp.com/attachments/881835799547609109/959135738379784192/900265836210696212.gif")
unbanembed.set_footer(text="$reason [MessageID] New Reason")
modlog = self.client.get_channel(876688282552008734)
await modlog.send(content = textcontent, embed = unbanembed)
# ban logs
@commands.Cog.listener()
async def on_member_ban(self, deltarune, user):
username = str(user)
userid = str(user.id)
textcontent = str(f"{userid}")
banreason = await deltarune.fetch_ban(user)
newreason = re.sub('(?i)(.*#\d{4}):\s*', '', banreason.reason)
banembed = discord.Embed(title=f"{username} was banned", description=f"📄 **Reason:**\n{newreason}", color=0xe74c3c)
banembed.timestamp = datetime.datetime.utcnow()
banembed.set_author(name="Action: Ban", icon_url="https://cdn.discordapp.com/attachments/881835799547609109/959135500386574367/510502447895281685.png")
banembed.set_footer(text="$reason [MessageID] New Reason")
#banembed.add_field(name="?? User ID:", value=f"{userid}", inline=True)
modlog = self.client.get_channel(876688282552008734)
await modlog.send(content = textcontent, embed = banembed)
def setup(client):
client.add_cog(BanLogs(client))
could you show the error code too?
you need to indent the code after the async for
you did it in the screen shot but not here
Of course
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: ExtensionFailed: Extension 'cogs.BanLogs' raised an error: IndentationError: unexpected indent (BanLogs.py, line 52)
❔
on_member_unban
no, the error you send is a Command Invoke Error
do you have a command that loads the extension?
Hmm
I do, that's what's showing that error
Since it won't let me reload it if there's an error in the code
do you have any code that modifies the file in any way?
Nope, not at all
clan
kai !!!
wow
ikr, sometimes that happens to me, removing the line and repasting it works
sounds like something nova would do ngl

have u done it?
new to discord.py, not entirely sure how to handle this error
discord.ext.commands.errors.CommandNotFound:
don't handle it, ignore it
okay i guess
can your bot see the audit logs, is the channel ure trying to get correct? Also
userid = str(user.id)
textcontent = str(f"{userid}")```
Can just be
```py
textcontent = f"{user.id}"```
Oh yeah, didn't notice that part lmao
Bot has admin and yes
on_command_error..thanks
you can eliminate the textcontent variable entirely
True, I wrote that on mobile back when I used replit
Try to print the entry to see what u get
casting a string to a string 💀
and casting that string to a string
ded
Is it possible to store something a user sent like:
@bot.command
async def store(ctx,*,message):
await set_msg(ctx.author,ctx)
user = await get_message(ctx.author,ctx)
user[str(ctx.author.id)][“message”] = message
await ctx.send(“Done 👍”)
class BasicView(discord.ui.View):
def __init__(self, ctx: commands.Context, timeout: optional[int] = None):
super().__init__(timeout=timeout)
self.ctx = ctx
cogs.fun' raised an error: NameError: name 'optional' is not defined
its Optional u need to import it from the typing library
you can also do int | None if ur on python3.10
ohk ty
This code is half
How do we know what is in the set_msg function and the rest
I’m asking about if it’s possible to store a message in json file
Yeah can
does somebody knows I want to get the server-id in a different function which does ctx, like ctx.guild.id but I want it without ctx
@slate swan Please don't try to ping @everyone or @here. Your message has been removed. If you believe this was a mistake, please let staff know!
db? or maybe a temporary var?
I cant create a temporary var idk why it still prints None
I tried this:
@bot.command()
async def set_id(ctx):
async with ctx.typing():
server_id= ctx.guild.id
id_psss = server_id```
and then I tried to access it in other functions but it was returning None
it will print None because of scope
you have to create a botvar
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!
how
^
ok
will this work:
@bot.command()
async def set_id(ctx):
async with ctx.typing():
server_id= ctx.guild.id
bot.id_psss = server_id```
and then I can access it by bot.id_psss
yes. but it will overwrite the id if the same command is run from another guild
np, I want it
@slate swan IT WORKED , TYSM
welcome
Guys how can use slash comamnd in discord.py 2.0
I mean, there's a lot of ways of using it.
from discord.commands import slash_command
I use discord.ext
not everyone uses pycord
Yes
Maintainer of dpy is back so me use it
@commands.Cog.listener(name="on_member_remove")
@commands.guild_only()
async def fm(member):
await member.ban(reason="User left while freeloader mode was on.")
``` this should ban the member who leaves right?
you're missing self, and yes
mhm k
How can we get discord channel in input?
arg: discord.TextChannel
How to get sticker url by the bot
!d discord.Client.fetch_sticker
await fetch_sticker(sticker_id, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Retrieves a [`Sticker`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Sticker "discord.Sticker") with the specified ID.
New in version 2.0.
!d discord.Sticker.url
The URL for the sticker’s image.
Sticker Id how to get that?
The id of the sticker.
I wanna steal the sticker using that
But what if the bot isn't there
(test)
oh, then you can't
all you can do is get it bytes using the cdn maybe
sarth,yk how to store a message in json file if possible
capy=[
"https://cdn.pixabay.com/photo/2018/03/12/10/39/mammal-3219344__480.jpg",
"https://upload.wikimedia.org/wikipedia/commons/a/a2/Hydrochaeris_hydrochaeris.jpg"
]
capyfact=["A kapibarák a világ legnagyobb rágcsálói.","A fogaik soha nem hagyják abba a növekedést.","Csoportban élnek.","Egyedi vokalizációjuk van.","Növényevők.","Saját kakijukat is megeszik.","Remek ülőhelyek kisebb állatoknak.","Nagyon jó úszók.","Képesek aludni a vizen.","35 km/h-val képes futni.","A capybarákat a többi állat ülőhelynek használja.","Nagyon szociális állatok."]
@commands.guild_only()
@client.command(name="capy",aliases=["Capybara","Capy"])
async def capy(ctx):
embed=discord.Embed(description=f"{random.choice(capyfact)}")
embed.set_image(f"{random.choice(capy)}")
await ctx.send(embed=embed)
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: object of type 'Command' has no len()
await create_sticker(*, name, description, emoji, file, reason=None):```

