#discord-bots

1 messages ยท Page 203 of 1

tribal shell
#

Link what?

minor totem
#

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

minor totem
tribal shell
#

Let me set one up.

minor totem
tribal shell
slate swan
tribal shell
minor totem
# tribal shell No download, no tutorial. It was just made a long while ago.

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

minor totem
left dew
smoky sinew
#

๐Ÿ˜

tribal shell
#

I think Python 2.7

smoky sinew
#

that's not a very helpful response for a staff member

smoky sinew
tribal shell
#

Oh okay.

tribal shell
smoky sinew
#

it's definitely fixable, but you do have a lot of catching up to do

smoky sinew
#

i'm not sure what versions of python discord.py supports today

tribal shell
smoky sinew
#

not to a 7 year old python version

minor totem
# tribal shell About 7 years ago. Haha

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

smoky sinew
minor totem
smoky sinew
minor totem
smoky sinew
#

it's not that outdated, neither is the python syntax really

minor totem
#

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

smoky sinew
#

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

minor totem
#

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

smoky sinew
#

the quickstart example isn't great since it uses message parsing

minor totem
#

That's why it fits so nicely with this, because it also uses the message event!

smoky sinew
hushed galleon
#

you assume they need to apply at all

young pendant
#

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

minor totem
tribal shell
#

@minor totem can you check DMs?

smoky sinew
minor totem
smoky sinew
#

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

clear elm
#

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

clear elm
#

there is no timeout, do i stil need to set it to none?

smoky sinew
#

there is a timeout by default

clear elm
#

oh

smoky sinew
#
class MyView(discord.ui.View):
    def __init__(self):
        super().__init__(timeout=None)
hushed galleon
hushed galleon
smoky sinew
#

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

clear elm
smoky sinew
#

180 seconds

#

but you should do what thegamecracks said as well

#

assuming your bot restarts, the view will break eventually

vital glacier
#

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)

vital glacier
#

But it keeps defaulting to None instead of N/A

hushed galleon
slate swan
hushed galleon
clear elm
#

!paste

unkempt canyonBOT
#

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.

clear elm
hushed galleon
#

why are the classes named like that? you probably meant to call add_view() inside the init method of your Bot class

young pendant
#

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

hushed galleon
# vital glacier But it keeps defaulting to None instead of N/A

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: ...

clear elm
#

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'```
slate swan
#
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
clear elm
slate swan
#

Hey I needed some help, does anyone know how I can get the content from an embed with the message id?

young pendant
vital glacier
#

thank anyway ๐Ÿ‘

graceful ermine
#

hey what am I doing wrong? I'm trying to make a permission handler

smoky sinew
smoky sinew
graceful ermine
smoky sinew
unkempt canyonBOT
#

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.

smoky sinew
#

also, it's pointless to do min_values = 1

graceful ermine
smoky sinew
graceful ermine
#

so how could I fix my permissions

#

??

clear elm
hushed galleon
graceful ermine
#

my permission handler does not work for some reason what am I doing wrong?

young pendant
smoky sinew
#

there are docs for select menus, you can look at them but i can't link it right now

smoky sinew
#

what do you mean by "does not work"

graceful ermine
clear elm
clear elm
#

thanks

smoky sinew
#

there are good examples on the docs

#

check that before asking

hushed galleon
young pendant
clear elm
smoky sinew
#

in the docs

hushed galleon
clear elm
#

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}')
young pendant
#
        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)```
hushed galleon
#

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

young pendant
#

yep

clear elm
#

what about it

young pendant
#

and I want it to be the way, that on member update checks if the member has more than just one role

smoky sinew
clear elm
#

do i have to do it like that or can i keep it the way i have?

hushed galleon
#

id rewrite your on_member_update to check if they have any of the associated roles, if no then you'd remove it

young pendant
#

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 Sadge

hushed galleon
#

rip raspberry

young pendant
#

yep

hushed galleon
#

it destroyed your SD card too?

young pendant
#

usb boot stick

vital glacier
#
    @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

young pendant
#

get this 7 times green led flash @hushed galleon

hushed galleon
vital glacier
#

Ooh

young pendant
hushed galleon
#

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```
clear elm
#

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'```
slate swan
#
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
smoky sinew
#

placeholder is an attribute of select, not view

hushed galleon
# clear elm https://paste.pythondiscord.com/utagevusim ```Traceback (most recent call last)...

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

smoky sinew
#

i didn't realize that

clear elm
#

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:')
        ]```
hushed galleon
#

just write the exact same list

clear elm
#

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

hushed galleon
#

i thought you were going to write your select menu using approach 2?

clear elm
#

oh

#

im super confused

#

!paste

unkempt canyonBOT
#

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.

clear elm
#

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:```
smoky sinew
#

use method #2 to write your view

#

also you shouldn't use replit to run your bot

clear elm
#

is the custom id like the value?

hushed galleon
#

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

clear elm
#
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:')
                                                                    ])```
slate swan
#

Hey I needed some help, does anyone know how I can get the content from an embed with the message id?

hushed field
#

how could i take an image as an argument and then turn that File object into an image

hushed field
golden portal
slate swan
#

that would work for a message

hushed field
#

yes from Message get .embeds

#

index list and get content

hushed field
#

or would i have to use bytes

golden portal
#

it will be in discord.Attachment

#

!d discord.Attachment, just see the methods, it has .save, .read and .to_file whichever suits your needs

unkempt canyonBOT
#

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.
clear elm
smoky sinew
#

what's the difference between File and Attachment?

#

i know Asset represents an asset from the CDN

smoky sinew
clear elm
#

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!")```
golden portal
hushed galleon
clear elm
#

yeah lmfao sorry about that

#

!paste

unkempt canyonBOT
#

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.

clear elm
#

it doesn't send the select menu @hushed galleon

hushed galleon
#

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

clear elm
#

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!")```
smoky sinew
smoky sinew
#

you need to set the timeout in the __init__ method of PersistentView

clear elm
#

ohh

golden portal
clear elm
smoky sinew
#

do that in setup_hook

smoky sinew
clear elm
#

!paste

unkempt canyonBOT
#

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.

clear elm
#

it says interaction view when the bot is restarted @smoky sinew

smoky sinew
#

use self

burnt imp
#

Is there a way to see where your bot is sending a message say if it's in dms who the recipient is?

smoky sinew
clear elm
#

i had self before anyways and it didnt work

#

ill try again

#

yeah, even if it's self

#

it still says interaction failed

burnt imp
smoky sinew
#

where are you setting timeout=None @clear elm ?

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)```
hushed galleon
# smoky sinew what's the point in making the distinction

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

smoky sinew
clear elm
#
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?

smoky sinew
#

no, timeout is an argument of view not select

#
class PersistentView(discord.ui.View):
    def __init__(self):
        super().__init__(timeout=None)
    ...
hushed galleon
smoky sinew
#

that's not possible

#

the error still happens when i just pass in "archive"

#

this is the cog code

clear elm
#
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!")```
hushed galleon
#

your setup method is what's invoking load_extension() incorrectly

smoky sinew
#

how so?

#

oh wait i get it

#

nevermind thanks

smoky sinew
#

what

clear elm
#

is that right?

smoky sinew
#

i think so, yes

clear elm
#

i just tried it, it idnd't work :\

smoky sinew
#

show your code

clear elm
#

!paste

unkempt canyonBOT
#

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.

clear elm
#

when i press an option, i do get an error but it still works

smoky sinew
#

what error

clear elm
#

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'```
smoky sinew
#

you would do select.values not self.values

#

views and select menus are separate, all the items are grouped in a view though

quick gust
#

what are the disadvantages of having a seperate file (and therefore a seperate cog) for each command?

smoky sinew
#

and it depends on what kind of commands you are making

quick gust
#

Yep I know that it is bad because well it just seems wrong but i dont know what are the disadvantages

quick gust
smoky sinew
#

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

quick gust
#

reminders, moderations, economy commands

smoky sinew
#

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

quick gust
#

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

smoky sinew
#

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

quick gust
#

Right thanks!

pliant gulch
clear elm
#

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
smoky sinew
#

you can't respond to an interaction twice

quick gust
#

yep its like

commands/
    moderation/
        ban.py
        kick.py
        ... 
     economy/
         balance.py
         give.py
... ```
smoky sinew
#

discord.js uses that

pliant gulch
#

Yea that's def gonna be a big disadvantage

#

Having a large codebase only for that reason is just stupid

quick gust
#

Mm true

clear elm
# smoky sinew you can't respond to an interaction twice

      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)```
smoky sinew
#

?

#

what about it

clear elm
#

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

smoky sinew
#
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

clear elm
#
      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)```
smoky sinew
#

?

#

this is the code that will run if the channel already exists

clear elm
# smoky sinew this is the code that will run if the channel already exists

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?
smoky sinew
#

yes, but the bottom code runs either way

clear elm
#

no it doesnt

smoky sinew
#

yes it does

clear elm
#

i just tested, it doesnt

smoky sinew
#

ok

clear elm
#

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

smoky sinew
#

i thought you said it worked

clear elm
dull terrace
#

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.

dull terrace
#

or not 7739monkathink

smoky sinew
#

rip lol

dull terrace
#

i sent you a dm

clear elm
#

ok

#

@hushed galleon you've been typing for like 10 minutes ๐Ÿ˜ญ

hushed galleon
#

im a slow typer ok

hushed galleon
# quick gust what are the disadvantages of having a seperate file (and therefore a seperate c...

in general, isolating things into cogs+extensions makes it more difficult to reuse code defined in them since:

  1. it becomes bad practice to import your 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
  2. 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
  3. 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
smoky sinew
hushed galleon
#

!d discord.ext.commands.Bot.reload_extension

unkempt canyonBOT
#

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.
smoky sinew
#

oh that

hushed galleon
clear elm
#

@smoky sinew btw the selectmenu doesnt work if the bot is restarted

dull terrace
#

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 7739monkathink

quick gust
smoky sinew
#

would a discord snowflake be int32 or int64?

#

nvm i'm stupid

smoky sinew
clear elm
#

@hushed galleon do you know?

smoky sinew
#

how powerful is app command localization?

hushed galleon
smoky sinew
#

can it localize everything within a message, or just app command information?

clear elm
#

!paste

unkempt canyonBOT
#

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.

hushed galleon
clear elm
#

whats the custom_id for?

hushed galleon
smoky sinew
#

i meant if i can translate whole messages using the automatic translation

clear elm
smoky sinew
#

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

hushed galleon
clear elm
#

so how would i incorporate the custom_id?

hushed galleon
smoky sinew
#

should i even bother at all with the auto localization then

#

seems like a pain in the ass to use both systems

hushed galleon
#

the custom_id can be whatever you string you want ||up to 100 characters||

clear elm
#

ok

#

i added one

#

is there anything that i need to do now?

hushed galleon
unkempt canyonBOT
#

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.
hushed galleon
hushed galleon
#

i meant like use your command so it sends a new message with the updated view

clear elm
#

ohh

#

didnt work

hushed galleon
hushed galleon
clear elm
hushed galleon
clear elm
#

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!")```
restive mirage
#

This is allowed?

hushed galleon
smoky sinew
#

i just use something like commands.sync.success

#

though it is pretty verbose

hushed galleon
#

yeah that was an example of a different localization library

smoky sinew
#
await ctx.send(translate("example.key", ctx))

i currently use something like this

hushed galleon
#

if anything thats less verbose because you have a clear identifier for your string

smoky sinew
clear elm
hushed galleon
clear elm
#

i did, it didnt print

#

when is it supposed to print

hushed galleon
clear elm
#

!paste

unkempt canyonBOT
#

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.

clear elm
hushed galleon
#

well that explains it, you defined your PersistentViewBot but never actually used it

smoky sinew
#

also, assuming you own the bot why not just use @commands.is_owner() on the sync command?

clear elm
hushed galleon
#

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

smoky sinew
#

what's the point of removing a command named "h" when you don't have one

#

strange

clear elm
smoky sinew
#

replace commands.Bot with PersistentViewBot

#

and change your super().__init__(...) to use the arguments you were using before with commands.Bot

clear elm
smoky sinew
#

no

clear elm
#

oh

smoky sinew
#
class PersistentViewBot(commands.Bot):
#

and then use bot = PersistentViewBot()

clear elm
#

ok

smoky sinew
#

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

clear elm
#
super().__init__(command_prefix = '>', intents=intents)```
#

?

smoky sinew
#

sure

#

and replace bot = commands.Bot(...) with bot = PersistentViewBot()

clear elm
#

ok

#

is that it?

smoky sinew
#

i guess

clear elm
#

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

smoky sinew
#

show your code

clear elm
#

!paste

unkempt canyonBOT
#

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.

clear elm
smoky sinew
#

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

clear elm
#
  File "main.py", line 11, in <module>
    bot = PersistentViewBot()
NameError: name 'PersistentViewBot' is not defined
smoky sinew
#

you have to put your bot class before you use it

#

python reads everything in the order you put it

clear elm
#

but then bot wouldn't be defined

smoky sinew
#

it would be,

#
class MyClass:
    pass

my_class = MyClass()
clear elm
#

wait where do i put the calss

smoky sinew
#

before you use it

clear elm
#

do i put it below or above tis

smoky sinew
#

i mean that's using it

#

so above

clear elm
#
  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```
smoky sinew
#

put it before that too

slate swan
#

have you copied code?

smoky sinew
#

that's why i said "before you use it"

clear elm
clear elm
smoky sinew
#

whenever you type in bot, you are using it

slate swan
smoky sinew
#

!e ```py
x = 5
print(x)

print("\nversus\n")

print(y)
y = 5

unkempt canyonBOT
#

@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
smoky sinew
#

@clear elm

slate swan
clear elm
slate swan
#

yes

smoky sinew
#

yes

#

"the bot" is creating an instance of the PersistentViewBot class

clear elm
#

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)```
slate swan
#

yeah fine

clear elm
#

its above the command already

slate swan
#

show

clear elm
#

the whole code?

slate swan
#

sure

clear elm
#

!paste

unkempt canyonBOT
#

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.

clear elm
slate swan
#

a sec

smoky sinew
#

no it's not

#

the help command is above bot = PersistentViewBot()

clear elm
#

ohhh

#

u want me to put that above the command

smoky sinew
#

yes

clear elm
#

ok

hushed galleon
#

technically their initial statement was right, the class definition was above the command...

smoky sinew
#

that's why i said above the command lol

hushed galleon
#

class PersistentViewBot which was the misunderstanding

clear elm
#

uh the close command is broken, im getting an error

smoky sinew
#

their class definition was at the very bottom of their code before

clear elm
#
  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'```
smoky sinew
#

the channel does not have a topic

#

@clear elm you shouldn't use replit for hosting your bot

clear elm
#

i know, its just for now

hushed galleon
smoky sinew
#

when was that

clear elm
hushed galleon
smoky sinew
#

also, that's only for the help command, not any other commands

hushed galleon
clear elm
#

so why shouldn't it work

hushed galleon
smoky sinew
#

they sent that code after i sent mine though

hushed galleon
#

you said "no its not" right after they showed the paste

slate swan
#

guys stop , its fine

hushed galleon
#

yeah its just a technicality

hushed galleon
clear elm
#

mhm

#

it closes but it sends the error message even though there shouldn't be any rerors?

smoky sinew
clear elm
#

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'
smoky sinew
#

member is none

smoky sinew
#

you removed your members intent by the way @clear elm

clear elm
#

oh-

#

is that why?

slate swan
#

yeah ig

hushed galleon
#

wonder why dpy hasnt introduced try_* methods of their own

slate swan
#

yeah that would have been helpful

smoky sinew
#

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

hushed galleon
#

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

clear elm
smoky sinew
#

someone get danny's opinions on it and i will PR

#

i can't ask myself

smoky sinew
clear elm
#

should i add it on top?

#

like where the bot is defined?

smoky sinew
#

just define it inside __init__

clear elm
#

what do i put?

smoky sinew
#

?

clear elm
#

nvm

#
        super().__init__(command_prefix=commands.when_mentioned_or('>'), intents=intents, intents = discord.Intents.all(), intents.members=True)```
clear elm
#

what do i add?

smoky sinew
#

i'm going to bed

#

sorry, but you should define it separately

clear elm
naive briar
clear elm
#
  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)```
smoky sinew
clear elm
#

but why is it none

clear elm
smoky sinew
#

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

clear elm
#

can you help me fix it?

smoky sinew
#

your intents are probably messed up like i said

clear elm
#

how are they messed up? i have intents = discord.Intents.all()

smoky sinew
#

show the code

#

you can replace get_member with fetch_member but it'll be slower

clear elm
smoky sinew
#

sure

clear elm
#

!paste

unkempt canyonBOT
#

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.

clear elm
smoky sinew
#

you're using default intents though

clear elm
#

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.```
naive briar
#

The error literally just told you

smoky sinew
#

content

#

actually, any text together i think

#

including embed descriptions names fields

clear elm
#

how can i do something like this?

#

like a text file

naive briar
#

Just send the file

hasty rain
#

Yesterday I again found a group of Russian programmers, but they donโ€™t have what I need =(

smoky sinew
#

thereโ€™s a discord.File class

#

ั ั€ัƒััะบะธะน

hasty rain
clear elm
hasty rain
#

ะฃั€ั‹๐Ÿฅณ๐Ÿฅณ๐Ÿฅณ

smoky sinew
clear elm
smoky sinew
#

so whatโ€™s wrong

clear elm
#

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()```
smoky sinew
#

there are docs on discord.pyโ€™s website for discord.File please look at those first

naive briar
#

!d discord.File

unkempt canyonBOT
#

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.
smoky sinew
#

thank you catgal

#

wait you changed your name

naive briar
#

It's fine, I don't really care

slate swan
#

is there anyway to get the users connections data? like their twitter, twitch, reddit names?

slate swan
smoky sinew
#

but what you linked is something different

#

the thing you linked is only for selfbots and was removed

slate swan
#

webscraping or something?

smoky sinew
#

set up a flask webserver

surreal current
#

What is the best way to get a dashboard up and running?

smoky sinew
surreal current
smoky sinew
#

set up a website for your dashboard

#

and use IPC to communicate between that and your bot

smoky sinew
surreal current
#

true but I already know about ipc

smoky sinew
#

then what are you asking about

surreal current
surreal current
smoky sinew
#

ok??

vital glacier
#
    @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='![back](https://cdn.discordapp.com/emojis/1077829978240077896.webp?size=128 "back")')
        pag.add_button('goto', emoji='![enter](https://cdn.discordapp.com/emojis/1077859606681899009.webp?size=128 "enter")')
        pag.add_button('next', emoji='![next](https://cdn.discordapp.com/emojis/1077830055159414816.webp?size=128 "next")')
        pag.add_button('delete', emoji='![stop](https://cdn.discordapp.com/emojis/1077830212982677604.webp?size=128 "stop")')
        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

left dew
#

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

left dew
#

okay thanks

smoky sinew
#

typing has helpful stuff for annotations

left dew
#

yes

smoky sinew
#

Union just means you can pass in either User or Member

vital glacier
smoky sinew
#

in commands at least

vital glacier
#

huh

#

how so

#

so like user: discord.Member = None

#

but like for instance, in an unban command

smoky sinew
#

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")
vital glacier
#

oh i see

smoky sinew
#

i'd assume discord.User would work in an unban command, i'm not sure

vital glacier
#

and what ab in an unban command, dont u gotta manually convert that?

#

hm

#

alright then

vital glacier
smoky sinew
#

i'm not sure

#

what's wrong with it??

vital glacier
#

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

smoky sinew
#

you shouldn't define entry before it

vital glacier
#

Huh

smoky sinew
vital glacier
#

It isn't tho

#

There is a ban in ctx.guild.bans, but it isnt getting it

smoky sinew
#

have you tried putting a print(entry)?

#

inside the loop

vital glacier
#

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()

smoky sinew
#

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)
vital glacier
#

yeah but would that work with a custom embed?

smoky sinew
#

it should

vital glacier
#

hm

#

time to figure that one out

vital glacier
#

It's harder then I thought mate

smoky sinew
#

what's wrong?

vital glacier
#

yeah idk, i just cant seem to properly figure it out

smoky sinew
#

the code doesn't work?

vital glacier
#

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='![back](https://cdn.discordapp.com/emojis/1077829978240077896.webp?size=128 "back")')
        pag.add_button('goto', emoji='![enter](https://cdn.discordapp.com/emojis/1077859606681899009.webp?size=128 "enter")')
        pag.add_button('next', emoji='![next](https://cdn.discordapp.com/emojis/1077830055159414816.webp?size=128 "next")')
        pag.add_button('delete', emoji='![stop](https://cdn.discordapp.com/emojis/1077830212982677604.webp?size=128 "stop")')
        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

smoky sinew
#

i guess turn the entries into a string first for as_chunks

#

i've never had to use that function

vital glacier
#

how'd i do that then

#

Cus all i need is the person that got banned, their id and the reason ig

smoky sinew
#

it depends on how you want the bans to be formatted

vital glacier
#

not the whole thing

#

or just the person that got banned and their id

smoky sinew
#
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

vital glacier
#

ok lets try that out

smoky sinew
#

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

vital glacier
#

true

#

i sometime make the codework before cleaning it up

#

purely for debugging stuff

#

especially with stuff like this, makes it easier for me

smoky sinew
smoky sinew
#

thank you

vital glacier
#

left a comment just for you mate ๐Ÿ‘

#

that's p clean code aswell, damn

smoky sinew
#

i found out it looks cleaner with typehints so i started using them everywhere

vital glacier
#

fair enough

smoky sinew
#

lol

vital glacier
#

anyway i cant figure the bans cmd out, its not working the way i want lmfao

smoky sinew
#

there's an example on how to use it below

vital glacier
#

im ab to give up but its a useful cmd to have

vital glacier
#

yeah just idk, i cant figure it out

shrewd fjord
vital glacier
#

Read back and you'll see what i mean

smoky sinew
#

wdym?

vital glacier
#

The error im getting rn is: discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: sequence item 0: expected str instance, list found

shrewd fjord
#

Did u tru printing entries?

smoky sinew
#

oh i'm stupid nevermind

shrewd fjord
#

Oh wait...

smoky sinew
vital glacier
shrewd fjord
smoky sinew
#

but it should work?

vital glacier
#
    @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='![back](https://cdn.discordapp.com/emojis/1077829978240077896.webp?size=128 "back")')
        pag.add_button('goto', emoji='![enter](https://cdn.discordapp.com/emojis/1077859606681899009.webp?size=128 "enter")')
        pag.add_button('next', emoji='![next](https://cdn.discordapp.com/emojis/1077830055159414816.webp?size=128 "next")')
        pag.add_button('delete', emoji='![stop](https://cdn.discordapp.com/emojis/1077830212982677604.webp?size=128 "stop")')
        return await pag.start()

shrewd fjord
vital glacier
#

that's the code for now, not sure how else to do it

shrewd fjord
vital glacier
#
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
shrewd fjord
#

Actually, i made a simple paginator with View class only

smoky sinew
shrewd fjord
smoky sinew
#

it's also pretty simple, currently rewriting it to use a modal instead of wait_for

vital glacier
naive briar
#

!d str.join

unkempt canyonBOT
#

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.
shrewd fjord
#

The page is a list

vital glacier
#

That's what I gotta do to make it work? lmfao

shrewd fjord
naive briar
shrewd fjord
#

Agreed ๐Ÿ’€

vital glacier
#

yeah but that wont work lmfao

shrewd fjord
#

p for p in page

#

Works too lol

naive briar
#

!e

n = list(range(10))
print("".join(n for n in n))
#

Don't just copy and paste also

shrewd fjord
#

My bad ๐Ÿ’€

naive briar
#

!e

n = list(range(10))
print("".join(str(n) for n in n))
unkempt canyonBOT
#

@naive briar :white_check_mark: Your 3.11 eval job has completed with return code 0.

0123456789
vital glacier
#

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

naive briar
#

What yert

#

Python is confusing

shrewd fjord
#

Fr

vital glacier
#

It really is sometimes

shrewd fjord
#

Sometimes tho

#

Yeah

shrewd fjord
smoky sinew
#

wdym?

shrewd fjord
#

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

vital glacier
#

let's not go there LOL

smoky sinew
#

it's dead simple to use

vital glacier
#

nice

smoky sinew
#

i reduced it by like 10 LOC by switching to a modal

shrewd fjord
#

Nice

shrewd fjord
vital glacier
#

Well, neither

smoky sinew
vital glacier
#

I'm getting there, just not what I want tbh

shrewd fjord
shrewd fjord
smoky sinew
#

@vital glacier where's your comment you said you left?

slate swan
#
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
vital glacier
#

They can't even fix their stuff or double check it because they're stupid smh

smoky sinew
#

my account gets flagged whenever i make an alt account

vital glacier
#

yeah

#

that's why mines flagged

smoky sinew
#

even though i have a perfectly legitimate reason for doing so

vital glacier
#

yeah wanna know what they're saying

shrewd fjord
#

Dumb securi-

vital glacier
#

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

shrewd fjord
#

Spooky's acc has been flagged

vital glacier
#

even tho if they check their logs they can see that i only own egirl on github

smoky sinew
#

spooky leave a comment pls

shrewd fjord
#

Yeah sure

vital glacier
#

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='![back](https://cdn.discordapp.com/emojis/1077829978240077896.webp?size=128 "back")')
        pag.add_button('goto', emoji='![enter](https://cdn.discordapp.com/emojis/1077859606681899009.webp?size=128 "enter")')
        pag.add_button('next', emoji='![next](https://cdn.discordapp.com/emojis/1077830055159414816.webp?size=128 "next")')
        pag.add_button('delete', emoji='![stop](https://cdn.discordapp.com/emojis/1077830212982677604.webp?size=128 "stop")')
        return await pag.start()

This now sends this:

smoky sinew
vital glacier
#

yeah that didnt work for me tho

naive briar
#

Format the string ๐Ÿฅค

smoky sinew
#
formatted_entries = [f"{entry.user.name} ({entry.user.id}) - {entry.reason}" for entry in entries]
vital glacier
#

that was just sending me this:

smoky sinew
#

those buttons look clean though

vital glacier
#

thanks

shrewd fjord
vital glacier
#

my whole bot is focused on minimal look

shrewd fjord
#

As far as i know

#

Not entry.user

smoky sinew
vital glacier
#

It works for now for me

green barn
vital glacier
#

If u want u can check out the bot, it's still a massive wip

vital glacier
green barn
#

LIES BRO

vital glacier
#

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

vital glacier
#

Yeah same

smoky sinew
#

why would you append the formatted_entries to entries and append formatted_entries to itself lol

vital glacier
#

Or would it be, entries.append(entry) and then where it says (formatted_entries, 10)

#

No wait that wouldnt make sense

shrewd fjord
#

Commented

#

Left 2 suggestions

vital glacier
#

anyway which one would it be tho @smoky sinew

smoky sinew
#

or doing "\n".join(formatted_entries) in the embed description i mean

vital glacier
#

uh

#

let me check that out

#

No, it just sends an empty embed @smoky sinew

smoky sinew
#

what

#

show the code

#

that shouldn't be possible tho

vital glacier
#

1sec

#

its not getting the page, so it wont get the entries from it

vital glacier
# smoky sinew show the code
    @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='![back](https://cdn.discordapp.com/emojis/1077829978240077896.webp?size=128 "back")')
        pag.add_button('goto', emoji='![enter](https://cdn.discordapp.com/emojis/1077859606681899009.webp?size=128 "enter")')
        pag.add_button('next', emoji='![next](https://cdn.discordapp.com/emojis/1077830055159414816.webp?size=128 "next")')
        pag.add_button('delete', emoji='![stop](https://cdn.discordapp.com/emojis/1077830212982677604.webp?size=128 "stop")')
        return await pag.start()
naive briar
#

๐Ÿคจ

vital glacier
#

That's the list it's getting from the bans?

shrewd fjord
#

Bro..m

vital glacier
#

If I remove the formatted_entries line and revert it back ,it sends me this:

shrewd fjord
#

U r assigning
formatted_entries var than assignment entries first

#

Bruh

#

formatted_entries=.....
pages=...

#

Use formatted_entries var above pages var

vital glacier
#

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))
smoky sinew
vital glacier
#

let me test that then i guess

#

Ok that works, thanks

shrewd fjord
#

Nice

vital glacier
#

Love all of you joethumbsup

smoky sinew
#

but you still want to paginate it

vital glacier
#

It's already paginated

smoky sinew
#

ok

shrewd fjord
#

Love

#

Love

#

๐Ÿ’€

#

Hate

#

Nvm exit

young pendant
#

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?

slate swan
#
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
slate swan
#

Can u explain breafily

shrewd fjord
#

From code?

slate swan
#

hello does anyone here have knowledge in discord.js? if yes could you dm me and help me to make message embedder

vocal snow
slate swan
#

oh thanks

young pendant
#

and yes, I do have intents enabled

slate swan
slate swan
slate swan
slate swan
# slate swan hello, so I am trying to make this command which shows user's inventory, but I h...

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.message as None so you should probably assign your actual message object instead
  • button and interaction parameters in your button callbacks are in reverse order (and consider deferring the interaction response so you don't get interaction failed)
young dagger
#
    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)```
young dagger
# naive briar 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

slate swan
#

then do your sending embed stuff seperately

naive briar
#

Isn't that set

slate swan
#

yep i realised that :p

#

though that would work too

slate swan
slate swan
unkempt mauve
#
  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'```
slate swan
#

reinstall dpy

naive briar
slate swan
slate swan
maiden fable
#

He was probably expecting the guild name, not the guild object <Guild ... >

slate swan
#

Whers server

modern ore
#

CPython: Core Developer

shadow wraith
#

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

maiden fable
#

!d discord.Message.reactions

unkempt canyonBOT
maiden fable
#

!d discord.Reaction.emoji

unkempt canyonBOT
shadow wraith
#

interesting i'll have a look

shadow wraith
#

actually

#

how would i check the reactions of a user in an entire channel

#

not just a message

maiden fable
shadow wraith
#

the channel only has 2 messages

#

will that get me rate limited

maiden fable
#

nah

slate swan
#

!d discord.ui.View

unkempt canyonBOT
#

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.
sick birch
#

Answered in pygen after crosspost

slate swan
#

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

slate swan
# slate swan 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 sad

#

Try use edit_original_response to edit an interaction response

#

alright i will try it

#

still an error

tired pollen
#

defer it first then use edit_original_response

zealous yarrow
#

i ll show u may code

smoky sinew
#

ok

#

check what library you are using though

#

it's sometimes different

zealous yarrow
#
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)
    ```
smoky sinew
#

that's not how you handle errors

#

errors are raised outside of your code, you need an on_command_error to catch command errors

zealous yarrow
#

ph

#

oh*

smoky sinew
#
@bot.event
async def on_command_error(ctx, error):
    if isinstance(error, commands.MissingRequiredArgument):
        await ctx.send("an error occured")
zealous yarrow
#

oh

tired pollen
#

or user
@commandname.error
Decorator
For specific command

smoky sinew
zealous yarrow
#

@tired pollen can u like suggest me some resource so that i can learn all this

smoky sinew
zealous yarrow
smoky sinew
zealous yarrow
#

ok

tired pollen
#

Discord py github / doc

slate swan
#

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

unkempt canyonBOT
#

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).
slate swan
#

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

slate swan
slate swan
#

On discord

smoky sinew
#

if you find something on discord it will probably be sketchy

slate swan
#

i used discloud

#

Its legit and popular

#

25k members

smoky sinew
#

sure

smoky sinew
steep wedge
smoky sinew
#

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

sick birch
#

You could make a sub-slash-command for each setting

#

At the very least it would be properly typed

smoky sinew
#

i don't even think you can have more than 100 global commands

#

that's why i want to reuse it

sick birch
#

rip

#

i mean could you do the same thing with prefix commands though?

slate swan
#

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"]]
sick birch
#

Using typing.Union[] for 20 different type just seems eh

smoky sinew
#

100 global CHAT_INPUT commands
5 global USER commands
5 global MESSAGE commands

smoky sinew
#

oh

#

i didn't see your message above

#

well yeah, but at least it's possible with message commands

sick birch
smoky sinew
#

yes i'm pretty sure

sick birch
#

time to make a web dashboard

smoky sinew
#

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

slate swan
#

I don't know where am i wrong, it's my first time working in json

smoky sinew
#

what are you using the json for

slate swan
#

Adding guilds for purge command

smoky sinew
smoky sinew
#

you can't do [] in json

#

i'm pretty sure the first character needs to be {

slate swan
#

Kk ill make this in json

naive briar
smoky sinew
#

and then do if ctx.guild.id in guild["guilds"]:

smoky sinew
naive briar
#

!e

import json

print(json.loads('[["cat"], ["meow"]]'))
unkempt canyonBOT
#

@naive briar :white_check_mark: Your 3.11 eval job has completed with return code 0.

[['cat'], ['meow']]
smoky sinew
#

interesting

slate swan
smoky sinew
#

does Guild.members include the bot?

slate swan
#

is anyone here good with discord bots? I created a ticket bot but I keep getting this error on discord saying "this interaction failed"

sick birch
#

Can you provide the full traceback and your code

sick birch
#

Traceback?