#discord-bots
1 messages ยท Page 203 of 1
Right, so when it is loaded that will be parsed as a guild ID and guild is now an int. You should put [1042533707464060979] in the JSON file instead
The repository to the code ๐
I don't have one yet.
Let me set one up.
Where did you download this code? If you're just following a tutorial, can you link the tutorial?
No download, no tutorial. It was just made a long while ago.
now it didnt have error but bot didnt send kurac in chat
Do you have a date of when it was written (I just want to know if it was years, or months ago)? We could fix this by downgrading the version of discord.py you use, if you just want it working.
I'm afraid that I don't really want to help you with migrating a whole project, so it may be best you do so at a later point when you have this working again and get a bit better at coding. Up to you though, as I'm sure there might be others who have a bit more experience from migrating several of their own bots
Can you print guild and make sure it is the same ID as the one in the JSON file?
About 7 years ago. Haha
๐
I think Python 2.7
that's not a very helpful response for a staff member
it's at least python 3.5 because it has async def syntax which didn't exist before that
Oh okay.
How do I downgrade my Python on VSC?
it's definitely fixable, but you do have a lot of catching up to do
you shouldn't, stick to python 3.10
i'm not sure what versions of python discord.py supports today
Bluenix said I should.
That would explain the @asyncio.coroutine from Python 3.4, and at that point presumably using either the async discord.py a la 0.16 or even earlier ๐ซฃ. These versions of discord.py no longer work with the current Discord API I'm afraid.
I assumed this was a year back and we could downgrade to say version 1.0, since 2.0 was recently released. I would probably recommend you rewrite it since otherwise you would need to migrate it 3 - 4 times, but looking at the repository it is not a lot of code so that may not be a lot of work
Mind helping me?
why are you so insistent on rewriting it? you can just migrate the code
Oh? I am sorry, I don't see what you mean. Can you DM me? It was not my intention to be rude or unhelpful
@tribal shell
read both of these:
https://discordpy.readthedocs.io/en/latest/migrating_to_v1.html#migrating-1-0
https://discordpy.readthedocs.io/en/latest/migrating.html
use python 3.10 and the latest version of discord.py, if you get any issues i can definitely help migrate it
Because the code is 7 years old and needs to catch up on 7 versions of Python, and 3 - 4 major rewrite migrations of discord.py
it's not that outdated, neither is the python syntax really
What I mean by rewriting in this case, is starting from a quickstart base from the current discord.py version and writing in the actual functionality of the bot while looking at the old code.
This, as opposed to going through each and every point of several migration guides, and then running the code until you no longer get an error - which to me, sounds like more work
the code barely interacts with the discord api really, other than reading and parsing latex from messages
other than logging in with email and password, manually parsing commands and not using stateful models
Yes looking at the code it was a surprisingly small amount of discord.py usage. I think what we both have in mind for migrating this involves somewhat the same thing. Personally I would just start from a recent discord.py quickstart example and copy in the methods then replace the main.py file with that
the quickstart example isn't great since it uses message parsing
That's why it fits so nicely with this, because it also uses the message event!
yeah, good luck with applying to get the message intent lol
you assume they need to apply at all
Hey guys
I have wrote a discord bot
What does the bot do?
Category roles
What is my issue?
With the command /change_team_role I can set the team role ( role X )
With the command add_role I can set roles, that will be in the team roles ( roles Y )
If a member has the role Y1 the member will automatically get the role X from the bot
If I give a member the roles Y1 and Y2 the bot gives the user also the role X how it is supposed to
But when I remove one of the Y roles, the bot removes the role X and then assigns it back after realising that the member still has a Y role
Can you help me fix that? https://paste.pythondiscord.com/zuwucukego
Okay so your suggestion is that this person rewrites their bot to use slash commands?
@minor totem can you check DMs?
you tell me, you're the one insistent on them using the quick start example ยฏ_(ใ)_/ยฏ
Yes I've seen it, I am about to send my message ๐
why would you want to parse messages to get the command
it gets complicated quickly, which is solved with the commands extension but even that is not great because you can easily port it over to slash commands with a few extra lines of code
how do i make it so if i use a select menu, i can use it again infinitely and so anyone can use it infinitely too
set the timeout to None
there is no timeout, do i stil need to set it to none?
there is a timeout by default
oh
class MyView(discord.ui.View):
def __init__(self):
super().__init__(timeout=None)
im not saying if its better to do a simple 1-1 rewrite or learn the new practices for discord bots, just that message content as an argument conditionally applies if their bot is popular
you want to make the view persistent, which requires said timeout=None but also custom ids for your components and calling add_view() when your bot starts up
theres an example of persistent views in the repository:
https://github.com/Rapptz/discord.py/blob/master/examples/views/persistent.py
i think it's always better to code things that are extensible and scalable in the future, if at any point a lot of people decide to invite it to their server the bot will suddenly break
whats the default amount?
180 seconds
but you should do what thegamecracks said as well
assuming your bot restarts, the view will break eventually
(which is a weird design flaw of discord.py)
can someone help me?
Anyone that can help me?
I'm trying to make it so that if a guild doesn't have a vanity it'll say Vanity: N/A instead of None, and if they have a vanity I want it to have the vanity name and then make it a hyperlink (like I have in the first embed)
This is the code for this: https://paste.pythondiscord.com/ridamagenu
But it keeps defaulting to None instead of N/A
depends, at some point the scope is small enough that the author will find it more cost-effective to do a barebones design without the worry of technical debt
yep i fixed it but i have another question can u come dm please? if u have time
i would consider this flexibility - persisting a view requires storing it somewhere, whether by hardcoding it or putting into a database, and d.py makes it your choice how you want to restore the views into memory
!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.
https://paste.pythondiscord.com/ilelafigug @hushed galleon is this right?
why are the classes named like that? you probably meant to call add_view() inside the init method of your Bot class
Hey guys
I wrote a bot
when I assign the role twitch mod to a user, the bot will assign the role team to the user automatically
when I assign the role discord mod to a user, the bot will assign the role team to the user automatically
when a user has both roles, and I remove the role Twitch mod from the user the bot removes the role Team and assigns it again after realising that the user still has the role Discord mod
when a user has both roles, and I remove the role Discord mod from the user the bot removes the role Team and assigns it again after realising that the user still has the role twitch mod
What do you think is the issue here?
code: https://paste.pythondiscord.com/zuwucukego
you're always assigning invite to a string so that specific variable can never be None - you would probably want to write it like this instead, comparing the actual vanity url before you format it into a string: py invite = "N/A" if guild.vanity_url is not None: ...
https://paste.pythondiscord.com/utagevusim
File "/home/runner/corpotics/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 862, in _do_call
return await self._callback(interaction, **params) # type: ignore
File "main.py", line 204, in help
await interaction.response.send_message(embed=helpEmbed, view=PersistentView())
File "main.py", line 105, in __init__
super().__init__(placeholder='Open a ticket!', min_values=1, max_values=1, options=options)
TypeError: View.__init__() got an unexpected keyword argument 'placeholder'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/runner/corpotics/venv/lib/python3.10/site-packages/discord/app_commands/tree.py", line 1242, in _call
await command._invoke_with_namespace(interaction, namespace)
File "/home/runner/corpotics/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 887, in _invoke_with_namespace
return await self._do_call(interaction, transformed_values)
File "/home/runner/corpotics/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 876, in _do_call
raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'tickets' raised an exception: TypeError: View.__init__() got an unexpected keyword argument 'placeholder'```
Thank you :thums
๐
async def clear(ctx, limit: int = None):
with open("kurac.json", 'r') as f:
guild = json.loads(f.read())
if ctx.guild.id not in guild['servers']:
if limit == None:
await ctx.channel.purge(limit=30)
await ctx.send("[ **SUCCESSFULLY** ] - *deleted messages*")
else:
if limit > 30:
await ctx.send("[**ERROR**] Your max limit is 30.")
else:
await ctx.channel.purge(limit=limit)
await ctx.send("[ **SUCCESSFULLY** ] - *deleted messages*")
elif ctx.guild.id in guild['servers']:
if limit == None:
await ctx.channel.purge(limit=10000)
await ctx.send("[ **SUCCESSFULLY** ] - *deleted messages*")
else:
await ctx.channel.purge(limit=limit)
await ctx.send("[ **SUCCESSFULLY** ] - *deleted messages*")```
why it didnt read servers: in json
@hushed galleon i cahgned the code up a bit
?
Hey I needed some help, does anyone know how I can get the content from an embed with the message id?
Hey, can someone help me please ๐ข
^
vanity = vanity or "N/A"
hey what am I doing wrong? I'm trying to make a permission handler
why? wouldn't the discord gateway dispatch that a button on the view has been clicked and then discord.py will call the view that holds that button?
why are you using globals anyway
I think they are better
^
!globals
When adding functions or classes to a program, it can be tempting to reference inaccessible variables by declaring them as global. Doing this can result in code that is harder to read, debug and test. Instead of using globals, pass variables or objects as parameters and receive return values.
Instead of writing
def update_score():
global score, roll
score = score + roll
update_score()
do this instead
def update_score(score, roll):
return score + roll
score = update_score(score, roll)
For in-depth explanations on why global variables are bad news in a variety of situations, see this Stack Overflow answer.
that's an argument of select, but you're using it in a view
also, it's pointless to do min_values = 1
plus that I am using it for a different event too
see what it said though
so what do i need to do?
ok
Please help about json?
only if the said view was added, but it wouldnt be feasible for dpy to implicitly add every view subclass to the client
my permission handler does not work for some reason what am I doing wrong?
Hey, can you help me real quick?^^
use the select decorator
there are docs for select menus, you can look at them but i can't link it right now
^^^^
you don't need to repost your question 3 minutes after you know
what do you mean by "does not work"
when I am in my alt account the slash command still works even though I do not have administrator
can you help me with that
thanks
im struggling to understand your code, but in check_roles() it appears you are incorrectly checking if an integer is in a list of Role objects
So, I can tell you what the code does
if you have discord mod, twitch mod and the role team
When a user is given twitch mod, he gets team role
When a user is given discord mod, he gets team role
what do i need to do to make it function properly?
did you look at the code example
in the docs
that doesnt really make it easier to understand, but have you looked into the issue i pointed out?
this?
class View(discord.ui.View):
@discord.ui.select(cls=ChannelSelect, channel_types=[discord.ChannelType.text])
async def select_channels(self, interaction: discord.Interaction, select: ChannelSelect):
return await interaction.response.send_message(f'You selected {select.values[0].mention}')
yes, the issue is in on member update but I cant find it
if before.roles != after.roles:
if after.guild.id in self.team_roles.keys():
await self.check_roles(after)
for role in before.roles:
team_role = discord.utils.get(before.guild.roles, id=self.team_roles[before.guild.id])
if role.id in self.roles_of_team[before.guild.id] \
and role not in after.roles \
and team_role in after.roles:
# if user has a role that belongs to team and role got removed and user has teamrole after
# changes
await after.remove_roles(team_role)```
oh i see now, the role that got removed triggers it to also remove the team role which triggers on_member_update a second time, then check_roles() notices the other team role and adds it back
yep
yes
what about it
and I want it to be the way, that on member update checks if the member has more than just one role
i mean that's how you create a select menu
do i have to do it like that or can i keep it the way i have?
id rewrite your on_member_update to check if they have any of the associated roles, if no then you'd remove it
A friend of mine fixed that issue but we had a power outage today and all of my files from my raspberry pi are gone because it literally got fried 
rip raspberry
yep
it destroyed your SD card too?
usb boot stick
@commands.command(
name='bans',
aliases=['banlist'],
usage='bans',
description='View banned users in the guild'
)
@commands.bot_has_permissions(ban_members=True)
async def bans(self, ctx, guild: discord.Guild = None):
"""View banned users in the guild"""
await ctx.typing()
embeds = []
ret = []
num = 0
pagenum = 1
guild = ctx.guild if guild is None else guild
bans = await guild.bans()
for entry in bans:
num+=1
ret.append(f'**{num}.** {entry.user.name} ({entry.user.id}) - {entry.reason}')
pages = [p for p in discord.utils.as_chunks(ret, 10)]
for page in pages:
pagenum += 1
embeds.append(discord.Embed(
title=f'Bans in {guild.name}',
color=color,
description="\n".join(page))
)
pag = Paginator(self.bot, embeds, ctx, invoker=ctx.author.id)
pag.add_button('prev', emoji=':back:')
pag.add_button('next', emoji=':next:')
pag.add_button('goto', emoji=':enter:')
pag.add_button('delete', emoji=':stop:')
return await pag.start()
Anyone that can help me? I'm trying to make a ban list command and for some reason this isn't working. The error jsk is giving me is this: https://paste.pythondiscord.com/cexixesuka
But I looked it up and await guild.bans() should work in this case
get this 7 times green led flash @hushed galleon
https://discordpy.readthedocs.io/en/stable/migrating.html#change-in-guild-bans-endpoint
await guild.bans() is outdated since the discord api changed how ban fetching works, now discord.py gives you an async generator which happens to be compatible with as_chunks(), e.g. py async for bans in discord.utils.as_chunks(guild.bans(), 10): # bans being a list of Ban objects
Ooh
the issue is, that I've been trying to figure out what the issue is since 2 hours or more, can you help me with that?
I'm new to all the discord.py stuff
right now your code removes the team role as soon as it sees that an assigned role was removed, but what you actually want your code to do is remove the team role if they no longer have any assigned roles
if they don't have the team role:
do nothing
for each of the member's roles:
if role is assigned to their team:
do nothing
if we're here, we know the team role is un-needed
therefore, remove the team role```
https://paste.pythondiscord.com/utagevusim
File "/home/runner/corpotics/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 862, in _do_call
return await self._callback(interaction, **params) # type: ignore
File "main.py", line 204, in help
await interaction.response.send_message(embed=helpEmbed, view=PersistentView())
File "main.py", line 105, in __init__
super().__init__(placeholder='Open a ticket!', min_values=1, max_values=1, options=options)
TypeError: View.__init__() got an unexpected keyword argument 'placeholder'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/runner/corpotics/venv/lib/python3.10/site-packages/discord/app_commands/tree.py", line 1242, in _call
await command._invoke_with_namespace(interaction, namespace)
File "/home/runner/corpotics/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 887, in _invoke_with_namespace
return await self._do_call(interaction, transformed_values)
File "/home/runner/corpotics/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 876, in _do_call
raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'tickets' raised an exception: TypeError: View.__init__() got an unexpected keyword argument 'placeholder'```
async def clear(ctx, limit: int = None):
with open("kurac.json", 'r') as f:
guild = json.loads(f.read())
if ctx.guild.id not in guild['servers']:
if limit == None:
await ctx.channel.purge(limit=30)
await ctx.send("[ **SUCCESSFULLY** ] - *deleted messages*")
else:
if limit > 30:
await ctx.send("[**ERROR**] Your max limit is 30.")
else:
await ctx.channel.purge(limit=limit)
await ctx.send("[ **SUCCESSFULLY** ] - *deleted messages*")
elif ctx.guild.id in guild['servers']:
if limit == None:
await ctx.channel.purge(limit=10000)
await ctx.send("[ **SUCCESSFULLY** ] - *deleted messages*")
else:
await ctx.channel.purge(limit=limit)
await ctx.send("[ **SUCCESSFULLY** ] - *deleted messages*")```
why it didnt read servers: in json
did you not see the example
placeholder is an attribute of select, not view
there are two ways to write a view with a select menu:
class MySelect(discord.ui.Select):
def init(self):
super().init(placeholder=..., options=...)
async def callback(self, interaction):
print("Hello world!")
class MyView(discord.ui.View):
def init(self):
super().init()
self.add_item(MySelect())or 2.py
class MyView(discord.ui.View):
@discord.ui.select(placeholder=..., options=...)
async def my_select(self, interaction, select):
print("Hello world!")``` see how they're different? mudkip is telling you to use the second approach, but your code is currently a mishmash of 1 and 2 - you can't declare a subclass of view but then invoke __init__(placeholder=...) in that view subclass because thats only a thing for Select subclasses
i didn't realize that
what would i put in options? currently this is in my code for options:
options = [
discord.SelectOption(label='General Support', value="1", description='Opens a general support ticket.', emoji=':support:'),
discord.SelectOption(label='Bug Reports', value="2", description='Opens a bug report ticket.', emoji=':bug:'),
discord.SelectOption(label='Reports', value="3", description='Opens a report ticket.', emoji=':report:')
]```
just write the exact same list
ohh ok
would it be like this?
super().__init__(placeholder='Open a ticket!', options = [
discord.SelectOption(label='General Support', value="1", description='Opens a general support ticket.', emoji=':support:'),
discord.SelectOption(label='Bug Reports', value="2", description='Opens a bug report ticket.', emoji=':bug:'),
discord.SelectOption(label='Reports', value="3", description='Opens a report ticket.', emoji=':report:'),
], max_values=1, timeout=None)```
@hushed galleon
i thought you were going to write your select menu using approach 2?
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.
https://paste.pythondiscord.com/ufitovopif
File "/home/runner/corpotics/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 862, in _do_call
return await self._callback(interaction, **params) # type: ignore
File "main.py", line 203, in help
await interaction.response.send_message(embed=helpEmbed, view=PersistentView())
File "main.py", line 186, in __init__
self.add_item(PersistentSelect())
File "main.py", line 97, in __init__
super().__init__(placeholder='Open a ticket!', max_values=1, timeout=None, options = [
TypeError: View.__init__() got an unexpected keyword argument 'placeholder'
The above exception was the direct cause of the following exception:```
look at what thegamecracks said
use method #2 to write your view
also you shouldn't use replit to run your bot
is the custom id like the value?
its just a unique id for a message component, its sent to discord and when someone uses the button/select menu, that same custom id is sent to discord.py so it knows which component was used
options= [
discord.SelectOption(label='General Support', value="1", description='Opens a general support ticket.', emoji=':support:'),
discord.SelectOption(label='Bug Reports', value="2", description='Opens a bug report ticket.', emoji=':bug:'),
discord.SelectOption(label='Reports', value="3", description='Opens a report ticket.', emoji=':report:')
])```
Hey I needed some help, does anyone know how I can get the content from an embed with the message id?
how could i take an image as an argument and then turn that File object into an image
get_message/fetch_message depending on if in cache
typehint your argument as discord.Attachment
well no it's an embed
that would work for a message
done, will it be an Image now?
or would i have to use bytes
it will be in discord.Attachment
!d discord.Attachment, just see the methods, it has .save, .read and .to_file whichever suits your needs
class discord.Attachment```
Represents an attachment from Discord.
str(x) Returns the URL of the attachment.
x == y Checks if the attachment is equal to another attachment.
x != y Checks if the attachment is not equal to another attachment.
hash(x) Returns the hash of the attachment.
Changed in version 1.7: Attachment can now be casted to [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)") and is hashable.
@hushed galleon
what's the difference between File and Attachment?
i know Asset represents an asset from the CDN
?
is that right?
class MyView(discord.ui.View):
@discord.ui.select(placeholder="Open a ticket below!", options= [
discord.SelectOption(label='General Support', value="1", description='Opens a general support ticket.', emoji=':support:'),
discord.SelectOption(label='Bug Reports', value="2", description='Opens a bug report ticket.', emoji=':bug:'),
discord.SelectOption(label='Reports', value="3", description='Opens a report ticket.', emoji=':report:')
])
async def my_select(self, interaction, select):
print("Hello world!")```
File is user created, Attachment is given by discord, similar to discord.ui.Button and discord.Button
besides the horrendous formatting yeah that looks fine
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.
you have two classes defined, PersistentView and MyView, and only MyView has the select menu, but in your command you're using PersistentView() which is the class that has nothing inside it
OH
File "main.py", line 95, in <module>
class PersistentView(discord.ui.View):
File "main.py", line 96, in PersistentView
@discord.ui.select(placeholder="Open a ticket below!", timeout=None, max_values=1, options= [
TypeError: select() got an unexpected keyword argument 'timeout'```
class PersistentView(discord.ui.View):
@discord.ui.select(placeholder="Open a ticket below!", timeout=None, max_values=1, options= [
discord.SelectOption(label='General Support', value="1", description='Opens a general support ticket.', emoji=':support:'),
discord.SelectOption(label='Bug Reports', value="2", description='Opens a bug report ticket.', emoji=':bug:'),
discord.SelectOption(label='Reports', value="3", description='Opens a report ticket.', emoji=':report:')
])
async def my_select(self, interaction, select):
print("Hello world!")```
what's the point in making the distinction
you don't set a timeout for select menus, timeouts are for views
you need to set the timeout in the __init__ method of PersistentView
ohh
its standard to have a difference between library generated, and user generated data models, plus, usually user generated has a few more options
how come if the bot restarts, the select menu doesnt continue to work?
did you add the view using Bot.add_view?
do that in setup_hook
i think the error might be in the cog itself
!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.
not Bot.add_view, Bot would be the bot object
use self
Is there a way to see where your bot is sending a message say if it's in dms who the recipient is?
i can't predict what your variable name is sorry
i had self before anyways and it didnt work
ill try again
yeah, even if it's self
it still says interaction failed
This happens to me as well, I figured it's just because when the bot stops it has no way of knowing what was sent before unless you save it some how.
where are you setting timeout=None @clear elm ?
class PersistentViewBot(commands.Bot):
def __init__(self, timeout=None):
intents = discord.Intents.default()
intents.message_content = True
super().__init__(command_prefix=commands.when_mentioned_or('c!'), intents=intents)```
they're ultimately different in the discord API - attachment objects are given by discord and have various attributes like url, size, etc., but when uploading a file they only ask you to provide the filename and data in a multipart request
that makes sense
no, you need to set timeout=None in PersistentView, not PersistentViewBot, also that would be the arguments that the bot takes in
anyone know why this happens?
class PersistentView(discord.ui.View):
@discord.ui.select(placeholder="Open a ticket below!", max_values=1, options= [
discord.SelectOption(label='General Support', value="1", description='Opens a general support ticket.', emoji=':support:'),
discord.SelectOption(label='Bug Reports', value="2", description='Opens a bug report ticket.', emoji=':bug:'),
discord.SelectOption(label='Reports', value="3", description='Opens a report ticket.', emoji=':report:')
])
async def my_select(self, interaction, select, timeout=None):
print("Hello world!")```
is that right?
no, timeout is an argument of view not select
class PersistentView(discord.ui.View):
def __init__(self):
super().__init__(timeout=None)
...
you used load_extension() which expects a string representing a module to be imported by discord.py, but you gave it a Cog object instead
that's not possible
the error still happens when i just pass in "archive"
this is the cog code
class PersistentView(discord.ui.View):
def __init__(self):
super().__init__(timeout=None)
@discord.ui.select(placeholder="Open a ticket below!", max_values=1, options= [
discord.SelectOption(label='General Support', value="1", description='Opens a general support ticket.', emoji=':support:'),
discord.SelectOption(label='Bug Reports', value="2", description='Opens a bug report ticket.', emoji=':bug:'),
discord.SelectOption(label='Reports', value="3", description='Opens a report ticket.', emoji=':report:')
])
async def my_select(self, interaction, select):
print("Hello world!")```
your setup method is what's invoking load_extension() incorrectly
^ @smoky sinew
what
is that right?
i think so, yes
i just tried it, it idnd't work :\
show your code
!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.
what error
this is the error when i press one of the options
File "/home/runner/corpotics/venv/lib/python3.10/site-packages/discord/ui/view.py", line 425, in _scheduled_task
await item.callback(interaction)
File "main.py", line 130, in my_select
if self.values[0]=="1":
AttributeError: 'PersistentView' object has no attribute 'values'```
you would do select.values not self.values
views and select menus are separate, all the items are grouped in a view though
what are the disadvantages of having a seperate file (and therefore a seperate cog) for each command?
the question you should be asking is "what are the advantages?"
and it depends on what kind of commands you are making
Yep I know that it is bad because well it just seems wrong but i dont know what are the disadvantages
Just normal commands
like what?
also files, extensions, and cogs are all separate from each other
you can have multiple cogs in one file
and a file without any extensions
reminders, moderations, economy commands
Yep I'm aware
it would be good to group them into those then, i would only make a separate extension if the command serves a very specific purpose and fits into a very specific category that none of the other commands fit in
I see
could you tell me the disadvantages though? It's not my bot and I'll need to give valid points to convince the owner
oh i get it
well, it's extra work to write and maintain, harder to read, also harder to parse such as in your help command which by default lists all cogs separately
Right thanks!
ohh
50 commands = 50 different files (granted you said and therefor a separate cog for each command)
im getting another errorafter i did that
File "/home/runner/corpotics/venv/lib/python3.10/site-packages/discord/ui/view.py", line 425, in _scheduled_task
await item.callback(interaction)
File "main.py", line 140, in my_select
await interaction.response.send_message(f'You already have an open ticket! {channel.mention}', ephemeral=True)
File "/home/runner/corpotics/venv/lib/python3.10/site-packages/discord/interactions.py", line 743, in send_message
raise InteractionResponded(self._parent)
discord.errors.InteractionResponded: This interaction has already been responded to before
you can't respond to an interaction twice
yep its like
commands/
moderation/
ban.py
kick.py
...
economy/
balance.py
give.py
... ```
discord.js uses that
Yea that's def gonna be a big disadvantage
Having a large codebase only for that reason is just stupid
Mm true
guild = interaction.guild
category = bot.get_channel(1078823637609631765)
if category is None:
await guild.create_category_channel(name="Tickets")
channel = discord.utils.get(category.channels, topic=str(interaction.user.id))
if channel:
await interaction.response.send_message(f'You already have an open ticket! {channel.mention}', ephemeral=True)
else:
overwrites = {
guild.default_role: discord.PermissionOverwrite(view_channel=False),
interaction.user: discord.PermissionOverwrite(view_channel=True, send_messages=True, read_messages=True),
guild.get_role(1078464006433542154): discord.PermissionOverwrite(view_channel=True, send_messages=True, read_messages=True)
}
channel = await guild.create_text_channel(name=f'ticket-{interaction.user.name}', topic=str(interaction.user.id), category=category, overwrites=overwrites)
await interaction.response.send_message(f'Your ticket has been created. {channel.mention}', ephemeral=True)
orderEmbed=discord.Embed(title="New ticket!", color=0x23B425)
orderEmbed.add_field(name="", value=f'Thanks for creating a ticket {interaction.user.mention}, please wait for one of our staff members to assist you!', inline=False)
orderEmbed.set_footer(text="Corpotics")
await channel.send("<@&1078464006433542154>", embed=orderEmbed)
if select.values[0]=="3":
await interaction.response.send_message("Opened a reports ticket for you!", ephemeral=True)```
its responding to the interaction only if they have an open ticket by saying "You already have an open ticket!" but nothing else and if they dont it sends "Opened a reports ticket for you!" so how is that responding to the interaction twice if it only responds to one of them
await interaction.response.send_message(f'Your ticket has been created. {channel.mention}', ephemeral=True)
also you're not returning if they already have an open ticket, so the code will just continue and create it anyways
if channel:
await interaction.response.send_message(f'You already have an open ticket! {channel.mention}', ephemeral=True)
else:
overwrites = {
guild.default_role: discord.PermissionOverwrite(view_channel=False),
interaction.user: discord.PermissionOverwrite(view_channel=True, send_messages=True, read_messages=True),
guild.get_role(1078464006433542154): discord.PermissionOverwrite(view_channel=True, send_messages=True, read_messages=True)
}
channel = await guild.create_text_channel(name=f'ticket-{interaction.user.name}', topic=str(interaction.user.id), category=category, overwrites=overwrites)```
yes and then if it doesnt ```py
else:
overwrites = {
guild.default_role: discord.PermissionOverwrite(view_channel=False),
interaction.user: discord.PermissionOverwrite(view_channel=True, send_messages=True, read_messages=True),
guild.get_role(1078464006433542154): discord.PermissionOverwrite(view_channel=True, send_messages=True, read_messages=True)
}
channel = await guild.create_text_channel(name=f'ticket-{interaction.user.name}', topic=str(interaction.user.id), category=category, overwrites=overwrites)``` should run, right?
yes, but the bottom code runs either way
no it doesnt
yes it does
i just tested, it doesnt
ok
anyways, im trying to make it work even if the bot is restarted
but it doesnt continue to work
you have to run the command again
@smoky sinew
i thought you said it worked
i mean this part worked ^
Does anyone want to test a discord bot game I made and give some brutal feedback? All i hear is positive things but the growth has been terrible lately, almost at 500 servers but the past couple weeks i haven't gained a single one.
sure i guess
or not 
rip lol
i sent you a dm
im a slow typer ok
in general, isolating things into cogs+extensions makes it more difficult to reuse code defined in them since:
- it becomes bad practice to
importyour extension as it bypasses d.py's hot-reloading mechanism entirely, meaning the only viable option would be accessing whatever things are added to your bot by the setup() function, usually your cog - if you are adding a cog to the bot, you would need to maintain a public interface (aka defining methods and attributes) to be used by other cogs
- if you have custom objects defined by your extension, you wouldn't want to keep strong references to those objects outside your extension because:
a. if you reloaded your extension afterwards, you'd run into memory leakage or obscure bugs related to multiple versions of the same extension being loaded at the same time
b. if you avoid reloading the extension, you'd defeat the purpose of hot-reloading and might as well write a regular module
discord.py has hot reloading?
!d discord.ext.commands.Bot.reload_extension
await reload_extension(name, *, package=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Atomically reloads an extension.
This replaces the extension with the same extension, only refreshed. This is equivalent to a [`unload_extension()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.unload_extension "discord.ext.commands.Bot.unload_extension") followed by a [`load_extension()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.load_extension "discord.ext.commands.Bot.load_extension") except done in an atomic way. That is, if an operation fails mid-reload then the bot will roll-back to the prior working state.
oh that
though if you literally meant one command per cog, that's just extremely verbose
(but from the few discord.js bots ive seen, i think it might be common practice there to separate individual commands by file)
@smoky sinew btw the selectmenu doesnt work if the bot is restarted
anyone else up for giving some feedback on a game bot, still need some brutal feedback or some ideas on how to make it better 
mmm that makes sense, would've never thought of that. I appreciate you!
I see I see
sure
@smoky sinew
i don't know
@hushed galleon do you know?
how powerful is app command localization?
whats your current code?
can it localize everything within a message, or just app command information?
!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.
it doesnt look like you provided any custom_id, you should be seeing an error from setup_hook
whats the custom_id for?
i think the automatic translation is only available for certain attributes/arguments, most of them in app_commands but some supported in ext.commands, but given that you have a Translator subclass, you could still manually localize strings using it
^
there's a translator subclass?
i meant if i can translate whole messages using the automatic translation
isnt it the exact same as values?
currently, i have a simple translate helper function that takes in a messageable and a translation key
and it gets the language for the messageable and translates it based off that
conceptually kind of, but values are associated with select options while custom ids are part of the button/select itself
so how would i incorporate the custom_id?
if by messages you mean the content you're sending, nope
should i even bother at all with the auto localization then
seems like a pain in the ass to use both systems
how do you set it in discord.py anyway?
the custom_id can be whatever you string you want ||up to 100 characters||
!d discord.app_commands.CommandTree.set_translator
await set_translator(translator)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Sets the translator to use for translating commands.
If a translator was previously set, it will be unloaded using its [`Translator.unload()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.Translator.unload "discord.app_commands.Translator.unload") method.
When a translator is set, it will be loaded using its [`Translator.load()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.Translator.load "discord.app_commands.Translator.load") method.
send your view again so it has the new custom id, and then restart your bot and test it
send the code?
i meant like use your command so it sends a new message with the updated view
of the few examples ive seen there's always some inconvenience with it, typically being that you're always calling the localization function in your code
any error message in your terminal? what did you change about the decorator?
no errors, i only added a custom id
inconvenience with what
restarted your code, used your command to get the new view, and restarted again right? can you put a print statement in your setup_hook to make sure it shows up?
mhm
let me be sure, is the custom_id in the right spot?
class PersistentView(discord.ui.View):
def __init__(self):
super().__init__(timeout=None)
@discord.ui.select(placeholder="Open a ticket below!", max_values=1, custom_id='persistent_view:tickets', options= [
discord.SelectOption(label='General Support', value="1", description='Opens a general support ticket.', emoji=':support:'),
discord.SelectOption(label='Bug Reports', value="2", description='Opens a bug report ticket.', emoji=':bug:'),
discord.SelectOption(label='Reports', value="3", description='Opens a report ticket.', emoji=':report:')
])
async def my_select(self, interaction, select):
print("Hello world!")```
This is allowed?
what i described, explicitly calling a function whenever you want to localize something like _("this is a translatable string")
is that the gettext method of localization?
i just use something like commands.sync.success
though it is pretty verbose
yeah that was an example of a different localization library
await ctx.send(translate("example.key", ctx))
i currently use something like this
if anything thats less verbose because you have a clear identifier for your string
@hushed galleon
seems to be
why would you need that
do you want all of my code?
did you try adding the print statement inside setup_hook to see if it actually prints?
when your bot starts up... guess the full code would be helpful
!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.
there seems to be conflicting information on whether bots are allowed to edit the vanity url, but discord developers suggests it was never a public API to begin with so this probably wouldnt be allowed, not to mention it could be heavily ratelimited to prevent abuse
well that explains it, you defined your PersistentViewBot but never actually used it
using intents.members = True on Intents.all??
also, assuming you own the bot why not just use @commands.is_owner() on the sync command?
yeah, can i not do that or smth?
you see this line? py bot = commands.Bot(command_prefix = '>', intents=intents) you're using an instance of commands.Bot
now look below: py class PersistentViewBot(commands.Bot): ... this means you defined a subclass of commands.Bot, but above you're still using a regular commands.Bot to connect to discord
why would you
what's the point of removing a command named "h" when you don't have one
strange
someone told me that h is also help ๐
what do i need to do to fix it?
replace commands.Bot with PersistentViewBot
and change your super().__init__(...) to use the arguments you were using before with commands.Bot
class PersistentViewBot(PersistentViewBot):?
no
oh
ok
wdym
you are using this right now:
bot = commands.Bot(command_prefix = '>', intents=intents)
but in your PersistentViewBot class, you are using this:
super().__init__(command_prefix=commands.when_mentioned_or('c!'), intents=intents)
do you see the problem
also inside PersistentViewBot you are only using the message content intent, while outside that you are using all intents
what do i need to do then?
super().__init__(command_prefix = '>', intents=intents)```
?
i guess
ok i think it works
let me test
now my close command doesnt work
File "/home/runner/corpotics/venv/lib/python3.10/site-packages/discord/app_commands/tree.py", line 1091, in wrapper
await self._call(interaction)
File "/home/runner/corpotics/venv/lib/python3.10/site-packages/discord/app_commands/tree.py", line 1221, in _call
command, options = self._get_app_command_options(data)
File "/home/runner/corpotics/venv/lib/python3.10/site-packages/discord/app_commands/tree.py", line 1127, in _get_app_command_options
raise CommandNotFound(name, parents)
discord.app_commands.errors.CommandNotFound: Application command 'close' not found
it says that its not found but there is a command called close
only the tickets comamnd works
show your code
!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.
you're not even using PersistentViewBot
you have to replace it on line 11
you are basically creating two bot instances, and the second one is overwriting everything
File "main.py", line 11, in <module>
bot = PersistentViewBot()
NameError: name 'PersistentViewBot' is not defined
you have to put your bot class before you use it
python reads everything in the order you put it
but then bot wouldn't be defined
wait where do i put the calss
before you use it
do i put it below or above tis
File "main.py", line 117, in <module>
@bot.tree.command(name="tickets", description="Provides you with the tickets menu.")
NameError: name 'bot' is not defined```
put it before that too
have you copied code?
that's why i said "before you use it"
dont remove the bot
i didnt
wdym use it
whenever you type in bot, you are using it
like ur using
print(x)
before defining what is x
!e ```py
x = 5
print(x)
print("\nversus\n")
print(y)
y = 5
@smoky sinew :x: Your 3.11 eval job has completed with return code 1.
001 | 5
002 |
003 | versus
004 |
005 | Traceback (most recent call last):
006 | File "<string>", line 6, in <module>
007 | NameError: name 'y' is not defined
@clear elm

but they said to put the class above the bot
yes
yeah but its saying bot isnt defined even though this is here:
class PersistentViewBot(commands.Bot):
def __init__(self):
intents = discord.Intents.default()
intents.message_content = True
super().__init__(command_prefix=commands.when_mentioned_or('>'), intents=intents)```
yeah fine
put it above
its above the command already
show
the whole code?
sure
!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.
a sec
yes
ok
technically their initial statement was right, the class definition was above the command...
that's why i said above the command lol
where?
class PersistentViewBot which was the misunderstanding
uh the close command is broken, im getting an error
their class definition was at the very bottom of their code before
File "/home/runner/corpotics/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 862, in _do_call
return await self._callback(interaction, **params) # type: ignore
File "main.py", line 191, in close
member=guild.get_member(int(channel.topic))
TypeError: int() argument must be a string, a bytes-like object or a real number, not 'NoneType'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/runner/corpotics/venv/lib/python3.10/site-packages/discord/app_commands/tree.py", line 1242, in _call
await command._invoke_with_namespace(interaction, namespace)
File "/home/runner/corpotics/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 887, in _invoke_with_namespace
return await self._do_call(interaction, transformed_values)
File "/home/runner/corpotics/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 876, in _do_call
raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'close' raised an exception: TypeError: int() argument must be a string, a bytes-like object or a real number, not 'NoneType'```
the channel does not have a topic
@clear elm you shouldn't use replit for hosting your bot
i know, its just for now
justin showed a snippet of class PersistentViewBot, you said to "put it above", they said it was already above the command and given the context it was a correct statement
when was that
isnt the topic the description?
this convo 8 minutes ago?
also, that's only for the help command, not any other commands
the code was here: https://paste.pythondiscord.com/dakajifina.py
yeah when you go to edit a channel, it shows it as "channel topic"
so why shouldn't it work
oh well i thought you saw the new paste they sent right above your message
<#discord-bots message>
they sent that code after i sent mine though
you said "no its not" right after they showed the paste
guys stop , its fine
yeah its just a technicality
did the channel you used the command in definitely has a channel topic? i dont see any reason it should be none otherwise
mhm
it closes but it sends the error message even though there shouldn't be any rerors?
but i mean it wasn't in that paste also
here's the error in the console
File "/home/runner/corpotics/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 862, in _do_call
return await self._callback(interaction, **params) # type: ignore
File "main.py", line 200, in close
ticketlogEmbed.add_field(name="Opened by:", value=f'{member.mention}', inline=True)
AttributeError: 'NoneType' object has no attribute 'mention'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/runner/corpotics/venv/lib/python3.10/site-packages/discord/app_commands/tree.py", line 1242, in _call
await command._invoke_with_namespace(interaction, namespace)
File "/home/runner/corpotics/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 887, in _invoke_with_namespace
return await self._do_call(interaction, transformed_values)
File "/home/runner/corpotics/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 880, in _do_call
raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'close' raised an exception: AttributeError: 'NoneType' object has no attribute 'mention'
member is none
use fetch with get
you removed your members intent by the way @clear elm
yeah ig
wonder why dpy hasnt introduced try_* methods of their own
yeah that would have been helpful
i used to use enhanced-discord.py back when discord.py didn't support replies and was slow to implement anything
that had try_object methods and i kind of miss it
someone here should make a PR
maybe me but danny is very particular about things
it has been [1 year, 3 weeks, 1 day] since i migrated from enhanced-discord.py, but it appears the fork's been archived now
i guess its not that hard to write your own try_* functions and throw it in some utils module
where did i remove it?
not remove, but you're not using it in the bot class
oh
should i add it on top?
like where the bot is defined?
just define it inside __init__
what do i put?
?
nvm
super().__init__(command_prefix=commands.when_mentioned_or('>'), intents=intents, intents = discord.Intents.all(), intents.members=True)```
what no
what do i add?
^
Intents.all already enable all intents
File "/home/runner/corpotics/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 862, in _do_call
return await self._callback(interaction, **params) # type: ignore
File "main.py", line 199, in close
ticketlogEmbed.add_field(name="Opened by:", value=f'{member.mention}', inline=True)
AttributeError: 'NoneType' object has no attribute 'mention'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/runner/corpotics/venv/lib/python3.10/site-packages/discord/app_commands/tree.py", line 1242, in _call
await command._invoke_with_namespace(interaction, namespace)
File "/home/runner/corpotics/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 887, in _invoke_with_namespace
return await self._do_call(interaction, transformed_values)
File "/home/runner/corpotics/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 880, in _do_call
raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'close' raised an exception: AttributeError: 'NoneType' object has no attribute 'mention'```
my close command is broken
@bot.tree.command(name="close", description="Closes the ticket!")
async def close(interaction, reason:str):
guild = interaction.guild
log_channel=guild.get_channel(1078949152735641650)
if not interaction.channel.name.startswith('ticket-'):
await interaction.response.send_message('This is not a ticket channel.', ephemeral=True)
return
channel=interaction.channel
message=""
async for messages in channel.history(oldest_first=True, limit=5000):
message+=f"{messages.author.name}: {messages.content}\n"
member=guild.get_member(int(channel.topic))
try:
await member.send(f'Your ticket was closed by {interaction.user.mention} for {reason} ```{message}```')
except Exception as e:
await interaction.response.send_message("I couldn't DM the transcript for unkown reasons!")
await asyncio.sleep(10)
await interaction.channel.delete()
ticketlogEmbed=discord.Embed(title="Ticket Closed", color=0xFF5349)
ticketlogEmbed.add_field(name="Opened by:", value=f'{member.mention}', inline=True)
ticketlogEmbed.add_field(name="Closed by:", value=f'{interaction.user.mention}', inline=True)
ticketlogEmbed.add_field(name="Reason:", value=f'{reason}', inline=True)
ticketlogEmbed.set_footer(text="Made by justin;#6868")
ticketlogEmbed.set_author(name=f'{interaction.user}', icon_url = f'{interaction.user.display_avatar}')
await log_channel.send(f'```{message}```', embed=ticketlogEmbed)```
member is none, so you don't have the member in your cache
but why is it none
it closes the ticket but sends that it couldn't send the transcript in dms and it doesn't send it to the logging channel
because it's not in your cache
get_member gets the member from your bot's cache
caching is when your bot saves the result of an API call so it doesn't have to do the call again
can you help me fix it?
your intents are probably messed up like i said
how are they messed up? i have intents = discord.Intents.all()
whole code?
sure
!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.
oh that was so easy, thanks
what has to be 4000 or fewer in length?
File "/home/runner/kaiso-assistant/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 862, in _do_call
return await self._callback(interaction, **params) # type: ignore
File "main.py", line 184, in close
await log_channel.send(f'```{message}```', embed=ticketlogEmbed)
File "/home/runner/kaiso-assistant/venv/lib/python3.10/site-packages/discord/abc.py", line 1538, in send
data = await state.http.send_message(channel.id, params=params)
File "/home/runner/kaiso-assistant/venv/lib/python3.10/site-packages/discord/http.py", line 744, in request
raise HTTPException(response, data)
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In content: Must be 4000 or fewer in length.
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/runner/kaiso-assistant/venv/lib/python3.10/site-packages/discord/app_commands/tree.py", line 1242, in _call
await command._invoke_with_namespace(interaction, namespace)
File "/home/runner/kaiso-assistant/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 887, in _invoke_with_namespace
return await self._do_call(interaction, transformed_values)
File "/home/runner/kaiso-assistant/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 880, in _do_call
raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'close' raised an exception: HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In content: Must be 4000 or fewer in length.```
The error literally just told you
content
actually, any text together i think
including embed descriptions names fields
Just send the file
Yesterday I again found a group of Russian programmers, but they donโt have what I need =(
it is one
thereโs a discord.File class
ั ััััะบะธะน
ะัะธะณะตัั
thats not my bot, the one i currently have for my trnascript isnt a text fiel
ะฃัั๐ฅณ๐ฅณ๐ฅณ
i know, but the bot you showed sent a text file
i know, i got it online as an example
so whatโs wrong
i want to make my transcripts. a text file too, i can show you the current code
channel=interaction.channel
message=""
async for messages in channel.history(oldest_first=True, limit=5000):
message+=f"{messages.author.name}: {messages.content}\n"
member=guild.get_member(int(channel.topic))
try:
await member.send(f'Your ticket was closed by {interaction.user.mention} for {reason} ```{message}```')
except Exception as e:
await interaction.response.send_message("I couldn't DM the transcript for unkown reasons!")
await asyncio.sleep(10)
await interaction.channel.delete()```
there are docs on discord.pyโs website for discord.File please look at those first
!d discord.File
class discord.File(fp, filename=None, *, spoiler=..., description=None)```
A parameter object used for [`abc.Messageable.send()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Messageable.send "discord.abc.Messageable.send") for sending file objects.
Note
File objects are single use and are not meant to be reused in multiple [`abc.Messageable.send()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Messageable.send "discord.abc.Messageable.send")s.
It's fine, I don't really care
is there anyway to get the users connections data? like their twitter, twitch, reddit names?
oauth2
i saw this, but i'm not finding the params or anything for it in the docs. got a link? https://github.com/Rapptz/discord.py/discussions/7332
How to get connections from user profile? I try use ctx.author.profile(), but in discord.py documentation written that : Deprecated since version 1.7. This can only be used by non-bot accounts.
oauth2 isnโt supported in discord.py
but what you linked is something different
the thing you linked is only for selfbots and was removed
ohhh. So what do i need to learn next to grab this data if it's not discord.py?
webscraping or something?
oauth2
set up a flask webserver
What is the best way to get a dashboard up and running?
๐ A discord.py extension for inter-process communication. - GitHub - Ext-Creators/discord-ext-ipc: ๐ A discord.py extension for inter-process communication.
... that doesn't help much
set up a website for your dashboard
and use IPC to communicate between that and your bot
i mean you asked a very broad question
true but I already know about ipc
then what are you asking about
hehe was already looking at that
yk just forget it i'll figure it out lol ty for ur time
ok??
@commands.command(
name='bans',
aliases=['banlist']
)
@commands.has_permissions(ban_members=True)
async def bans(self, ctx):
await ctx.typing()
embeds=[]
ret=[]
pagenum=0
async for entry in ctx.guild.bans():
ret.append(f'')
if ret is None:
return await ctx.success(f"This guild doesn\'t have any bans")
pages = [p for p in discord.utils.as_chunks(ret, 10)]
for page in pages:
pagenum += 1
embeds.append(discord.Embed(
color=color,
title=f'Bans in {ctx.guild.name}',
description="\n".join(page))
.set_author(name=ctx.author.display_name, icon_url=ctx.author.display_avatar)
.set_footer(text=f'Page {pagenum}/{len(pages)}'))
pag = Paginator(self.bot, embeds, ctx, invoker=ctx.author.id)
pag.add_button('prev', emoji='')
pag.add_button('goto', emoji='')
pag.add_button('next', emoji='')
pag.add_button('delete', emoji='')
return await pag.start()
This is the code I'm using, but it's not getting the entry from ctx.guild.bans(), its sending the paginated embed though, anyone that can help me?
I assume it's because I don't have entry defined, but I don't know what's the smartest way to define the entry
async def whois(ctx, user: Union[discord.Member, discord.User]=None):
what do i import to make Union defined? at the moment it is undefined
from typing import Union
okay thanks
typing has helpful stuff for annotations
yes
Union just means you can pass in either User or Member
Would that also work for like ID & username?
huh
how so
so like user: discord.Member = None
but like for instance, in an unban command
if you annotate discord.Member for an argument:
@bot.command()
async def slap(ctx, member: discord.Member):
# you can pass in either the id, a ping, or username
await ctx.send(f"{member.mention} was slapped")
oh i see
i'd assume discord.User would work in an unban command, i'm not sure
and what ab in an unban command, dont u gotta manually convert that?
hm
alright then
also @smoky sinew, any chance u can look at this?
Well, it's not getting entry from ctx.guild.bans()
and i assume it's because entry is defined before it
because it sends the paginated embed but it doesnt get the bans from the guild
but ive got no idea how to get the entry from it otherwise icl
you shouldn't define entry before it
Huh
what do you mean?? ctx.guild.bans is empty??
let me check
yeah it does get it from the bans
BanEntry(reason='x ๏ฟฝ#6899 (323118319144271872) | yeet', user=<User id=384905496819138561 name='px' discriminator='9070' bot=False>)
That's what it gets from the entry, which is correct.
But I assume it isn't working because entry isnt getting called after i defined it in async for entry in ctx.guild.bans()
why are you using ret.append(f"")?
you are appending nothing and then sending that as a paginated message lol
shouldn't you make a list of entries and then use as_chunks on it?
probably a better way to do this but,
entries = []
async for entry in ctx.guild.bans():
entries.append(entry)
pages = discord.utils.as_chunks(entries, 10)
yeah but would that work with a custom embed?
it should
yeah for some reason I can't seem to figure it out haha
It's harder then I thought mate
what's wrong?
yeah idk, i just cant seem to properly figure it out
the code doesn't work?
Because rn I did this right:
@commands.command(
name='bans',
aliases=['banlist']
)
@commands.has_permissions(ban_members=True)
async def bans(self, ctx):
await ctx.typing()
embeds=[]
entries = []
pagenum=0
num = 0
async for entry in ctx.guild.bans():
entries.append(entry)
if entry is None:
return await ctx.success(f"This guild doesn\'t have any bans")
pages = discord.utils.as_chunks(entries, 10)
for page in pages:
pagenum += 1
embeds.append(discord.Embed(
color=color,
title=f'Bans in {ctx.guild.name}',
description="\n".join(page))
.set_author(name=ctx.author.display_name, icon_url=ctx.author.display_avatar)
.set_footer(text=f'Page {pagenum}/{len(pages)}'))
pag = Paginator(self.bot, embeds, ctx, invoker=ctx.author.id)
pag.add_button('prev', emoji='')
pag.add_button('goto', emoji='')
pag.add_button('next', emoji='')
pag.add_button('delete', emoji='')
return await pag.start()```
which i most def assume it wouldnt work, but the error its giving me is: `discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: sequence item 0: expected str instance, BanEntry found`
I changed stuff up but I assume it's still wrong lmfao
i guess turn the entries into a string first for as_chunks
i've never had to use that function
how'd i do that then
Cus all i need is the person that got banned, their id and the reason ig
it depends on how you want the bans to be formatted
formatted_entries = [f"{entry.user.name} ({entry.user.id}) - {entry.reason}" for entry in entries]
try something like this and then pass formatted_entries to as_chunks instead
ok lets try that out
also, you wouldn't do if entry is None but if not entries instead
if entries will be True if the list isn't empty
true
i sometime make the codework before cleaning it up
purely for debugging stuff
especially with stuff like this, makes it easier for me
https://gist.github.com/mudkipdev/4b0ce96a2d9bd6205e16c52798546571
somebody comment on my paginator pls lol
its actually pretty good ngl
thank you
i found out it looks cleaner with typehints so i started using them everywhere
fair enough
lol
anyway i cant figure the bans cmd out, its not working the way i want lmfao
there's an example on how to use it below
im ab to give up but its a useful cmd to have
?
yeah just idk, i cant figure it out
Just tell your problems
Read back and you'll see what i mean
wdym?
The error im getting rn is: discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: sequence item 0: expected str instance, list found
Did u tru printing entries?
oh i'm stupid nevermind
Oh wait...
list of BanEntry
already did that, we've been over that
I mean if working or not
but it should work?
Which line?
@commands.command(
name='bans',
aliases=['banlist']
)
@commands.has_permissions(ban_members=True)
async def bans(self, ctx):
await ctx.typing()
embeds=[]
entries = []
pagenum=0
num = 0
async for entry in ctx.guild.bans():
formatted_entries = [f"{entry.user.name} ({entry.user.id}) - {entry.reason}" for entry in entries]
entries.append(formatted_entries)
if entry is None:
return await ctx.success(f"This guild doesn\'t have any bans")
pages = discord.utils.as_chunks(entries, 10)
for page in pages:
pagenum += 1
embeds.append(discord.Embed(
color=color,
title=f'Bans in {ctx.guild.name}',
description="\n".join(page))
.set_author(name=ctx.author.display_name, icon_url=ctx.author.display_avatar)
.set_footer(text=f'Page {pagenum}/{len(pages)}'))
pag = Paginator(self.bot, embeds, ctx, invoker=ctx.author.id)
pag.add_button('prev', emoji='')
pag.add_button('goto', emoji='')
pag.add_button('next', emoji='')
pag.add_button('delete', emoji='')
return await pag.start()
Yeah it should
that's the code for now, not sure how else to do it
Give full traceback fr
Traceback (most recent call last):
File "/usr/local/lib/python3.8/dist-packages/discord/ext/commands/core.py", line 229, in wrapped
ret = await coro(*args, **kwargs)
File "/home/void/cogs/Moderation.py", line 372, in bans
description="\n".join(page))
TypeError: sequence item 0: expected str instance, list found
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/usr/local/lib/python3.8/dist-packages/jishaku/features/invocation.py", line 168, in jsk_debug
await alt_ctx.command.invoke(alt_ctx)
File "/usr/local/lib/python3.8/dist-packages/discord/ext/commands/core.py", line 1023, in invoke
await injected(*ctx.args, **ctx.kwargs) # type: ignore
File "/usr/local/lib/python3.8/dist-packages/discord/ext/commands/core.py", line 238, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: sequence item 0: expected str instance, list found
Actually, i made a simple paginator with View class only
mine is a view
.join(page for page in page)
it's also pretty simple, currently rewriting it to use a modal instead of wait_for
what
!d str.join
str.join(iterable)```
Return a string which is the concatenation of the strings in *iterable*. A [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError "TypeError") will be raised if there are any non-string values in *iterable*, including [`bytes`](https://docs.python.org/3/library/stdtypes.html#bytes "bytes") objects. The separator between elements is the string providing this method.
description+="\n".join(page for page in page)
The page is a list
That's what I gotta do to make it work? lmfao
Yeah bro
You're overriding the var
yeah but that wont work lmfao
My bad ๐
!e
n = list(range(10))
print("".join(str(n) for n in n))
@naive briar :white_check_mark: Your 3.11 eval job has completed with return code 0.
0123456789
i know, i havent tested it that page for page in page, i was just wondering if that wouldve worked, and then i saw it was going to override it lmfao
Fr
It really is sometimes
Rewrite it for all in one package ๐
wdym?
Like, the current code u using, is only for discord.py
Make it so like, we can use it with any packages ๐
Tho u need use your 90% of braincells
let's not go there LOL
it's dead simple to use
nice
i reduced it by like 10 LOC by switching to a modal
Nice
So, you gave up? Or ended up fixing it ๐
Well, neither
ok i updated the gist to use modals
https://gist.github.com/mudkipdev/4b0ce96a2d9bd6205e16c52798546571
I'm getting there, just not what I want tbh

Sed
@vital glacier where's your comment you said you left?
async def clear(ctx, limit: int = None):
with open("kurac.json", 'r') as f:
guild = json.loads(f.read())
if ctx.guild.id not in guild['servers']:
if limit == None:
await ctx.channel.purge(limit=30)
await ctx.send("[ **SUCCESSFULLY** ] - *deleted messages*")
else:
if limit > 30:
await ctx.send("[**ERROR**] Your max limit is 30.")
else:
await ctx.channel.purge(limit=limit)
await ctx.send("[ **SUCCESSFULLY** ] - *deleted messages*")
elif ctx.guild.id in guild['servers']:
if limit == None:
await ctx.channel.purge(limit=10000)
await ctx.send("[ **SUCCESSFULLY** ] - *deleted messages*")
else:
await ctx.channel.purge(limit=limit)
await ctx.send("[ **SUCCESSFULLY** ] - *deleted messages*")```
why it didnt read servers: in json
It's probably not showing up because i forgot my account is flagged for some dumb reason by github and their support it useless
They can't even fix their stuff or double check it because they're stupid smh
my account gets flagged whenever i make an alt account
even though i have a perfectly legitimate reason for doing so
yeah wanna know what they're saying
Dumb securi-
that i own 5 or so other accounts even tho they're my friends, he logged into my github with his ip to connect it to his discord acc
Spooky's acc has been flagged
even tho if they check their logs they can see that i only own egirl on github
spooky leave a comment pls
Yeah sure
ok so back to this problem:
@commands.command(
name='bans',
aliases=['banlist']
)
@commands.has_permissions(ban_members=True)
async def bans(self, ctx):
await ctx.typing()
embeds=[]
entries=[]
pagenum=0
num = 0
async for entry in ctx.guild.bans():
num += 1
entries.append(entry)
if entry is None:
return await ctx.success(f"This guild doesn\'t have any bans")
pages = discord.utils.as_chunks(entries, 10)
for page in pages:
pagenum += 1
embeds.append(discord.Embed(
color=color,
title=f'Bans in {ctx.guild.name}',
description="\n".join(str(page) for page in page))
.set_author(name=ctx.author.display_name, icon_url=ctx.author.display_avatar))
pag = Paginator(self.bot, embeds, ctx, invoker=ctx.author.id)
pag.add_button('prev', emoji='')
pag.add_button('goto', emoji='')
pag.add_button('next', emoji='')
pag.add_button('delete', emoji='')
return await pag.start()
This now sends this:
that's why i said to use the list comprehension thing
yeah that didnt work for me tho
Format the string ๐ฅค
formatted_entries = [f"{entry.user.name} ({entry.user.id}) - {entry.reason}" for entry in entries]
that was just sending me this:
those buttons look clean though
thanks
my whole bot is focused on minimal look
i love that look but whenever i try to make my bot look like something it never works lol
It works for now for me
creds 2 me
If u want u can check out the bot, it's still a massive wip
that's the only thing u did smjh
LIES BRO
ok so if i string the entries, right
how would i do it with the entries.append(entry)
would it be
entries.append(formatted_entries)
formatted_entries.append(formatted_entries)
formatted_entries.append(entry)
cus idek atp
No.
i'm confused
Yeah same
lol what
why would you append the formatted_entries to entries and append formatted_entries to itself lol
Or would it be, entries.append(entry) and then where it says (formatted_entries, 10)
No wait that wouldnt make sense
anyway which one would it be tho @smoky sinew
does just doing this and then sending formatted_entries in the embed work?
or doing "\n".join(formatted_entries) in the embed description i mean
@commands.command(
name='bans',
aliases=['banlist']
)
@commands.has_permissions(ban_members=True)
async def bans(self, ctx):
await ctx.typing()
embeds=[]
entries=[]
pagenum=0
num = 0
formatted_entries = [f"{entry.user.name} ({entry.user.id}) - {entry.reason}" for entry in entries]
async for entry in ctx.guild.bans():
num += 1
entries.append(entry)
if entry is None:
return await ctx.success(f"This guild doesn\'t have any bans")
pages = discord.utils.as_chunks(entries, 10)
for page in pages:
pagenum += 1
embeds.append(discord.Embed(
color=color,
title=f'Bans in {ctx.guild.name}',
description="\n".join(formatted_entries))
.set_author(name=ctx.author.display_name, icon_url=ctx.author.display_avatar))
pag = Paginator(self.bot, embeds, ctx, invoker=ctx.author.id)
pag.add_button('prev', emoji='')
pag.add_button('goto', emoji='')
pag.add_button('next', emoji='')
pag.add_button('delete', emoji='')
return await pag.start()
Your entries var is empty
๐คจ
That's the list it's getting from the bans?
Bro..m
If I remove the formatted_entries line and revert it back ,it sends me this:
U r assigning
formatted_entries var than assignment entries first
Bruh
formatted_entries=.....
pages=...
Use formatted_entries var above pages var
So it should be like this then?
if entry is None:
return await ctx.success(f"This guild doesn\'t have any bans")
formatted_entries = [f"{entry.user.name} ({entry.user.id}) - {entry.reason}" for entry in entries]
pages = discord.utils.as_chunks(entries, 10)
for page in pages:
pagenum += 1
embeds.append(discord.Embed(
color=color,
title=f'Bans in {ctx.guild.name}',
description="\n".join(formatted_entries))
.set_author(name=ctx.author.display_name, icon_url=ctx.author.display_avatar))
put formatted_entries after the loop
Nice
Love all of you 
but you still want to paginate it
It's already paginated
ok
Someone here who can help me?
Hey guys
I wrote a bot
when I assign the role twitch mod to a user, the bot will assign the role team to the user automatically
when I assign the role discord mod to a user, the bot will assign the role team to the user automatically
when a user has both roles, and I remove the role Twitch mod from the user the bot removes the role Team and assigns it again after realising that the user still has the role Discord mod
when a user has both roles, and I remove the role Discord mod from the user the bot removes the role Team and assigns it again after realising that the user still has the role twitch mod
What do you think is the issue here?
code: https://paste.pythondiscord.com/zuwucukego
The Issue is that on_member_update does not check, when I remove discord mod, if a member still has twitch mod as a role, how can I do that?
async def clear(ctx, limit: int = None):
with open("kurac.json", 'r') as f:
guild = json.loads(f.read())
if ctx.guild.id not in guild['servers']:
if limit == None:
await ctx.channel.purge(limit=30)
await ctx.send("[ **SUCCESSFULLY** ] - *deleted messages*")
else:
if limit > 30:
await ctx.send("[**ERROR**] Your max limit is 30.")
else:
await ctx.channel.purge(limit=limit)
await ctx.send("[ **SUCCESSFULLY** ] - *deleted messages*")
elif ctx.guild.id in guild['servers']:
if limit == None:
await ctx.channel.purge(limit=10000)
await ctx.send("[ **SUCCESSFULLY** ] - *deleted messages*")
else:
await ctx.channel.purge(limit=limit)
await ctx.send("[ **SUCCESSFULLY** ] - *deleted messages*")```
why it didnt read servers: in json
Can u explain breafily
Do you have intents enabled?
From code?
hello does anyone here have knowledge in discord.js? if yes could you dm me and help me to make message embedder
you could also ask in the discord.js server
oh thanks
hello, so I am trying to make this command which shows user's inventory, but I have a problem with the buttons that its not editing
The intents aren't the issue
on_member_update is
and yes, I do have intents enabled
It didnt read json file
{"Server": [[id server]]
Idk why
Can u try printing guild
Idk, i think problem is in read json idk why
In your button callbacks you're editing self.message and passing in self.current_page +- 1 which is just an integer. Also:
- You assigned
self.messageasNoneso you should probably assign your actual message object instead buttonandinteractionparameters in your button callbacks are in reverse order (and consider deferring the interaction response so you don't getinteraction failed)
member = ctx.author
summoner = await collection.find_one({"discord_id": member.id})
if summoner:
summoner_name = summoner.get("summoner_name")
tier_and_rank = summoner.get("tier_and_rank")
elo = summoner.get("elo_rating")
users.append(
{"member": member, "summoner_name": summoner_name, "tier_and_rank": tier_and_rank, "elo_rating": elo})
async def remove_from_users():
await asyncio.sleep(4 * 60 * 60)
for user in users:
if user['member'] == member:
users.remove(user)
embed = discord.Embed(title=f'',
description=f'{ctx.author.mention} has been in queue for 4 hours, and been removed due to inactivity.',
timestamp=datetime.datetime.now(), color=discord.Color.red())
await ctx.send(embed=embed)
asyncio.create_task(remove_from_users())```
Is there any way to simplify?
for user in users:
if user['member'] == member:
users.remove(user)```
thank you very much ๐
Simplify what
I don't really know tbh. I wish I could just simply use if member in users: and then users.remove(member) but for some reason that is not working
a list comprehension ```py
users = [user for user in users if user["member"] != member]
then do your sending embed stuff seperately
Isn't that set
Thatโs a why im telling to print
Can i send u code in dm and u can try to fix?
File "c:\Users\Mosiur\OneDrive\Desktop\Siam's Files\Test Bot\main.py", line 2, in <module>
from discord import app_commands
File "C:\Users\Mosiur\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\app_commands\__init__.py", line 12, in <module>
from .commands import *
File "C:\Users\Mosiur\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\app_commands\commands.py", line 51, in <module>
from ..enums import AppCommandOptionType, AppCommandType, ChannelType, Locale
ModuleNotFoundError: No module named 'discord.enums'```
reinstall dpy
if i understood u right, is this a better one?
https://paste.pythondiscord.com/uyujokunoh
Use dicts instead of those if-elif wall
thank you
But what's the issue in printing "guild" ?
He was probably expecting the guild name, not the guild object <Guild ... >
U dont understand me ....
It didnt read file i added bot command add guild
And clear now didnt read the json file
Whers server
CPython: Core Developer
how would i go about making a command that checks the reaction made by a user of a specific message and sending the emoji of the reaction
!d discord.Message.reactions
Reactions to a message. Reactions can be either custom emoji or standard unicode emoji.
!d discord.Reaction.emoji
The reaction emoji. May be a custom emoji, or a unicode emoji.
interesting i'll have a look
actually
how would i check the reactions of a user in an entire channel
not just a message
You will have to iterate through text_channel.history() but there is a high chance u will be ratelimited
nah
!d discord.ui.View
class discord.ui.View(*, timeout=180.0)```
Represents a UI view.
This object must be inherited to create a UI within Discord.
New in version 2.0.
Answered in pygen after crosspost
heyy, I am having this problem, when I changed from normal commands to app_commands, i dont really know what I am doing wrong with my buttons anymore https://paste.pythondiscord.com/oconicadeg I tried changing many things but still nothing worked
Any errors in the console
File "C:\Users\Kynhogat\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\app_commands\commands.py", line 861, in _do_call
return await self._callback(self.binding, interaction, **params) # type: ignore
File "C:\Users\Kynhogat\Desktop\again_OP\cogs\inventory.py", line 80, in inventory
await view.start(interaction)
File "C:\Users\Kynhogat\Desktop\again_OP\cogs\inventory.py", line 110, in start
self.message = await ctx.send(embed=self.pages[self.current_page], view=self)
AttributeError: 'Interaction' object has no attribute 'send'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\Kynhogat\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\app_commands\tree.py", line 1242, in _call
await command._invoke_with_namespace(interaction, namespace)
File "C:\Users\Kynhogat\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\app_commands\commands.py", line 887, in _invoke_with_namespace
return await self._do_call(interaction, transformed_values)
File "C:\Users\Kynhogat\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\app_commands\commands.py", line 880, in _do_call
raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'inventory' raised an exception: AttributeError: 'Interaction' object has no attribute 'send'
Well there's your issue
You're calling await view.start(...) and passing in an Interaction object, which doesn't have a send method
You're probably after interaction.response.send_message(...)
I tried that too
I got another error then
File "C:\Users\Kynhogat\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\ui\view.py", line 425, in _scheduled_task
await item.callback(interaction)
File "C:\Users\Kynhogat\Desktop\again_OP\cogs\inventory.py", line 106, in on_next_page
await self.show_page(self.current_page + 1)
File "C:\Users\Kynhogat\Desktop\again_OP\cogs\inventory.py", line 95, in show_page
await self.message.edit(embed=self.pages[self.current_page], view=self)
AttributeError: 'NoneType' object has no attribute 'edit'
that happens when i click on a button
Because send_message doesn't return the response I don't think
So self.message is just None
after running the command i got an response but when i click on its buttons nothing happens and i get that error 
Try use edit_original_response to edit an interaction response
alright i will try it
still an error
defer it first then use edit_original_response
i ll show u may code
import discord
from discord.ext import commands
# Intents
var_prefix = ";"
var_intent = discord.Intents.default()
var_intent.messages = True
var_intent.message_content = True
bot = commands.Bot(intents = var_intent ,command_prefix=var_prefix)
#------------------------------------
@bot.command()
async def say(ctx,arg):
try :
await ctx.message.delete()
await ctx.send(arg)
except:
temp_embed=discord.Embed(title="Missing Argument",
url="si=d95ecd56be0a459a",
description="Syntax: {var_prefix}say 'your text'",
color=0xFF5733)
await ctx.send(embed=temp_embed)
```
that's not how you handle errors
errors are raised outside of your code, you need an on_command_error to catch command errors
@bot.event
async def on_command_error(ctx, error):
if isinstance(error, commands.MissingRequiredArgument):
await ctx.send("an error occured")
oh
or user
@commandname.error
Decorator
For specific command
also, your argument will only be one word in your command
@tired pollen can u like suggest me some resource so that i can learn all this
the discord.py docs
yes i am learning
ok
Discord py github / doc
anyone knows a 24/7 bot hoster that is free?
Self-hosting
how do i check for file size?
example if a file is over 35 kilobytes
it will print hello 1
if a file is under 35 kilobytes
it will print hello 2
!d os.path.getsize
os.path.getsize(path)```
Return the size, in bytes, of *path*. Raise [`OSError`](https://docs.python.org/3/library/exceptions.html#OSError "OSError") if the file does not exist or is inaccessible.
Changed in version 3.6: Accepts a [path-like object](https://docs.python.org/3/glossary.html#term-path-like-object).
this doesnt help
for example if i send a screenshot it contains a file size
so if its over 35 kb it will just do the thing that i just siad
if you mean a discord.Attachment just read the bytes using .read() method and use len on it
just use a popular one
if you find something on discord it will probably be sketchy
sure

?
Why not just pay $1 per month for something more reliable
slash commands are so useless
if i want to make a /settings command that takes in a key and a value
let's say i have a "language" setting, and the user can set it to english or spanish
i'll just set the type of the value to str
but i want to make a "starboard" setting, and i need the user to type in a channel for the starboard, i can't annotate it as textchannel because i already set it to str
... what's the limit on subcommands ๐ค
You could make a sub-slash-command for each setting
At the very least it would be properly typed
i don't even think you can have more than 100 global commands
that's why i want to reuse it
Any who can help
async def add(ctx, *text):
with open('kurac.json', 'r') as f:
lines = json.loads(f.read())
for ctx.guild.id in text:
lines.append(text)
with open('kurac.json', 'w') as f:
f.write(json.dumps(lines))
@client.command()
async def clear(ctx, limit: int = None):
with open("kurac.json", 'r') as f:
guild = json.loads(f.read())
if ctx.guild.id not in guild:
if limit == None:
await ctx.channel.purge(limit=30)
await ctx.send("[ **SUCCESSFULLY** ] - *deleted messages*")
else:
if limit > 30:
await ctx.send("[**ERROR**] Your max limit is 30.")
else:
await ctx.channel.purge(limit=limit)
await ctx.send("[ **SUCCESSFULLY** ] - *deleted messages*")
elif ctx.guild.id in guild:
if limit == None:
await ctx.channel.purge(limit=10000)
await ctx.send("[ **SUCCESSFULLY** ] - *deleted messages*")
else:
await ctx.channel.purge(limit=limit)
await ctx.send("[ **SUCCESSFULLY** ] - *deleted messages*")```
I dont know why it spam ur max limit is 30 but i added ctx guild in json
[["Id"]]
Using typing.Union[] for 20 different type just seems eh
100 global CHAT_INPUT commands
5 global USER commands
5 global MESSAGE commands
i don't even think you can do that for slash commands
oh
i didn't see your message above
well yeah, but at least it's possible with message commands
do subcommands count towards that?
yes i'm pretty sure
discord wants me to purposefully restrict my bot
and what's even the point of a command limit
surely discord servers won't crash at like 500 commands per bot
Any who can help me?
what's wrong
It didnt work it spam Your max limit is 30 but i have json and id in json
Like
[["Id of server"]]
I don't know where am i wrong, it's my first time working in json
what are you using the json for
Adding guilds for purge command
shouldn't it be ```json
{
"guilds": [
guild_id
]
}
Kk ill make this in json
Not true
and then do if ctx.guild.id in guild["guilds"]:
what is it then?
!e
import json
print(json.loads('[["cat"], ["meow"]]'))
@naive briar :white_check_mark: Your 3.11 eval job has completed with return code 0.
[['cat'], ['meow']]
interesting
Can u help me?
?
does Guild.members include the bot?
is anyone here good with discord bots? I created a ticket bot but I keep getting this error on discord saying "this interaction failed"
Can you provide the full traceback and your code
Traceback?


