#Basic Pycord Help (Quick Questions Only)

1 messages · Page 55 of 1

fallen cove
#

The event on_message() how would I make a task do the same so I can start and stop it easily

proud pagoda
#

on_message isn't a task tho it's just a function that runs every time a message is sent

#

So you can't rlly even stop on_message

fallen cove
proud pagoda
fallen cove
#

Yup

proud pagoda
#

Also, is this smthn that's on a per-server basis you want or on a global basis?

fallen cove
proud pagoda
#

And if you have multiple servers, use a dict that has each server's ID in it and a true or false to determine whether to parse messages for that server

proud pagoda
#

You're welcome

tired goblet
#

can my bot see who joined a voice channel?

gleaming falcon
#

Confused by this. I normally send an empty response (it's hacky, but works), but unless I misunderstood something, Discord doesn't like this because you're not sending a response

class MyView(discord.ui.View):
    ...

    @discord.ui.button(label='Add Notes', style=discord.ButtonStyle.primary, emoji='📝', row=2)
    async def notes(self, button: discord.ui.Button, interaction: discord.Interaction):
        modal = NoteModal(view=self)
        await interaction.response.send_modal(modal)
        await modal.wait()

class NoteModal(discord.ui.Modal):
    ...

    async def callback(self, interaction: Interaction):
        ...
        await self._view.message.edit(embeds=self._view.message.embeds, view=self._view)

        self.stop()
        # This is what I normally do:
        # with contextlib.suppress(discord.HTTPException):
        #     await interaction.response.send_message()
proud mason
winter condorBOT
proud mason
silver moat
#

bump

tired goblet
bold notch
#

If i have a

async def on_message(message):

How could I find if the message is replying to a message and then what that message content is?

full basin
#

.rtfm Message.reference

silver moat
#

.rtfm fetch_message

proud mason
bold notch
#

How should I add scheduled tasks to be run at certain times to a commands bot?

proud mason
undone mulch
#
Error:
02.02 09:59:14 [Bot] Ignoring exception in command announce:
02.02 09:59:14 [Bot] Traceback (most recent call last):
02.02 09:59:14 [Bot] File "/.local/lib/python3.9/site-packages/discord/ext/commands/core.py", line 181, in wrapped
02.02 09:59:14 [Bot] ret = await coro(*args, **kwargs)
02.02 09:59:14 [Bot] File "/cogs/miner_only.py", line 137, in announce
02.02 09:59:14 [Bot] db["lastID"] = ctx.channel.id
02.02 09:59:14 [Bot] AttributeError: 'Owner_Only' object has no attribute 'channel'
02.02 09:59:14 [Bot] The above exception was the direct cause of the following exception:
02.02 09:59:14 [Bot] Traceback (most recent call last):
02.02 09:59:14 [Bot] File "/.local/lib/python3.9/site-packages/discord/ext/commands/bot.py", line 360, in invoke
02.02 09:59:14 [Bot] await ctx.command.invoke(ctx)
02.02 09:59:14 [Bot] File "/.local/lib/python3.9/site-packages/discord/ext/commands/core.py", line 927, in invoke
02.02 09:59:14 [Bot] await injected(*ctx.args, **ctx.kwargs)
02.02 09:59:14 [Bot] File "/.local/lib/python3.9/site-packages/discord/ext/commands/core.py", line 190, in wrapped
02.02 09:59:14 [Bot] raise CommandInvokeError(exc) from exc
02.02 09:59:14 [Bot] discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Owner_Only' object has no attribute 'channel'```

```py
Code:
    @commands.command(aliases=["notify"])
    @commands.is_owner()
    async def announce(ctx, ping, *, content):
      db["lastID"] = ctx.channel.id
      db["ancping"] = ping;db["ancContent"] = content
      embed = discord.Embed(title=mpupdates,description=content,color=p84clr)
      embed.add_field(name=mpfq,value=mpfqv,inline=False)
      sent_message = await ctx.reply(f"{mppreview} {mppreview2}",embed=embed)
      db["lastAnnouncement"] = sent_message.id```

Did the object change for normal cmds?
young bone
green hinge
#

Why is the role not removed from the user?
In role there is the role ID?

await interaction.user.remove_roles(role)```
chrome skiff
#

is there any working ipc for pycord?

proud mason
fervent cradle
#

How to get the channel where the command was run?

proud mason
proud mason
fervent cradle
#

okay, so not ctx.message.channel?

proud mason
#

See the guide

#

.guide

winter condorBOT
proud mason
fervent cradle
# proud mason It's the same

yeah, but im getting a error while trying to put the channel in a var
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: AttributeError: 'NoneType' object has no attribute 'channel'

#

c = ctx.message.channel

proud mason
#

So use ctx.channel

proud mason
fervent cradle
#

oh

#

it worked, thanks om!

chrome skiff
proud mason
green hinge
full basin
still helm
#

What does channel.edit need for a Code if i want to write : and , ?

#

normal code like this does not work and give me
await channel.edit(name=f"Paypal:{totalamount} € / {total}")

full basin
#

Because channel names don't support that.

#

Use voice channels.

still helm
#

ahhh thanks !

proud mason
#

.rtfm guild.edit

proud mason
copper magnet
#

Nope. Its dont working

#

Ignoring exception in command close:
Traceback (most recent call last):
File "other_folders_here/core.py", line 178, in wrapped
ret = await coro(*args, **kwargs)
File other_folders_here/ScpBotDeg3teR\Main.py", line 247, in close
await ctx.channel.move(category=get(ctx.guild.categories, id=1070410818262417419))
File "other_folders_here/discord\abc.py", line 1149, in move
raise InvalidArgument("Could not resolve appropriate move position")
discord.errors.InvalidArgument: Could not resolve appropriate move position

full basin
#

You're still using utils.get

copper magnet
#

Should I?🥹

full basin
#

Oh, no, totally don't follow instructions you're given.

proud mason
#

btw you can just pass discord.Object(id) instead of passing the category

copper magnet
proud mason
#

also, i think you would need to set either of beginning, end, before, after

#

.rtfm channel.move

proud mason
copper magnet
#

this doesn't work either

proud mason
copper magnet
#

oookayyy

proud mason
#

try setting end=True

copper magnet
#

okay thx

proud mason
#

this is why you should rtfm. Although ill spare you a bit because docs arent very clear on that

chrome skiff
# proud mason Gosh it was long ago 💀 But it should work. I think you need to install with no ...

Does pycord have a setup_hook to do like this?

class Bot(commands.Bot):
    def __init__(self):
        super().__init__(command_prefix=commands.when_mentioned_or(botinformations().prefix), case_insensitive=True, intents=intents)
        self.persistent_views_added = False

        self.ipc = ipc.Server(self, secret_key=secrets['APP_SECRET_KEY'])

    async def on_ready(self):
        if not self.persistent_views_added:
            self.persistent_views_added = True
        
        self.loop.create_task(status_task())
        print(f"▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬ \nErfolgreich eingeloggt als {bot.user}\nID: {bot.user.id}")
        print(f"Python: {sys.version[0:3]} pycord: {discord.__version__}")
        print('▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬')

    async def setup_hook(self) -> None:
        await self.ipc.start()
proud mason
proud mason
chrome skiff
#

so like

asyncio.create_task(bot.ipc)
bot.run("123")
green hinge
#

Does anyone know why my time is still displayed offset by 1 hour despite converting to the "Europe/Berlin" time zone?

            start_time_utc = datetime.datetime.strptime(notification['started_at'], "%Y-%m-%dT%H:%M:%SZ")
            start_time_de = start_time_utc.astimezone(pytz.timezone("Europe/Berlin"))
            start_time = start_time_de.strftime("%H:%M")```
proud mason
chrome skiff
#
class CarlitoEmailBot(commands.Bot):
    def __init__(self):
        super().__init__(command_prefix=commands.when_mentioned_or(botinformations().prefix), case_insensitive=True, intents=intents)
        self.persistent_views_added = False

        self.ipc = ipc.Server(self, secret_key=secrets['APP_SECRET_KEY'])

        asyncio.create_task(self.ipc.start)

    async def on_ready(self):
        if not self.persistent_views_added:
            self.persistent_views_added = True
        
        self.loop.create_task(status_task())
        print(f"▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬ \nErfolgreich eingeloggt als {bot.user}\nID: {bot.user.id}")
        print(f"Python: {sys.version[0:3]} pycord: {discord.__version__}")
        print('▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬')
proud mason
chrome skiff
#

not working i am getting a runtime error:
RuntimeError: no running event loop

proud mason
#

im not sure if it is asyncio.create_task(self.ipc.start) or self.loop.create_task(self.ipc.start)

chrome skiff
proud mason
#

not really iirc

chrome skiff
#

TypeError: a coroutine was expected, got <bound method Server.start of <Server endpoints=0 started=False standard_port=1025 multicast_port=20000 do_multicast=True>>

proud mason
#

add ()

#

my bad

chrome skiff
#

starting now

proud mason
#

so it works?

chrome skiff
#

yes

proud mason
#

cool

chrome skiff
# proud mason so it works?

works fine but do you know why it takes so long for the redirect?`

@app.route("/verified/")
@async_action
@requires_authorization
async def verified():
    user = discord.fetch_user()

    print(user.email)

    data = {
        "UserID": int(user.id),
        "UserEmail": user.email
    }

    await ipc.request("new_verify", data=data)
    
    return redirect("https://discord.com/channels/899448915206746134/1069410863078981643/", code=302)

is the redirect only starting when the new_verify route in the bot is done?

proud mason
chrome skiff
#

flask

proud mason
#

hmm. nope. no idea

chrome skiff
#

okay

fervent cradle
#

discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: AttributeError: 'NoneType' object has no attribute 'invoke'

any idea why this is happening

I'm taking an input, adding 2 numbers from the input and trynna output the 2 commands using slash commands

green hinge
#

Can I somehow call the get_fish function to load the fish from the database?
When I try to do this I always get "Function never awaited".

async def get_fish(gewaesser):
        fische = await dab.get_fisch_in_water(gewaesser)
        return [fische]

class Fisch(discord.ui.Select):
    def __init__(self, bot: discord.Bot, selected_letter, gewaesser):
        self.bot = bot
        self.gewaesser = gewaesser
        fische = get_fish(gewaesser)
        options = [discord.SelectOption(label=fish) for fish in fische if fish.startswith(selected_letter)]
        super().__init__(
            placeholder="Wähle deinen Fisch aus",
            min_values=1,
            max_values=1,
            options=options,
        )
        
    async def callback(self, interaction: discord.Interaction):```
full basin
#

You either make the function sync

#

Or make the init async

green hinge
full basin
#

Your db looks async

#

So

full basin
green hinge
fervent cradle
#
math  = discord.SlashCommandGroup("math", "Academia's math functions")
@math.command(name="add",description="adds numbers")
async def add(ctx,num1,num2):
  x = num1 + num2
  await ctx.respond(x)
fervent cradle
#

yeah, by the way you're asking looks like I made a mistake

fervent cradle
#

indentation?

silver moat
#

and logic

#

is this in a cog?

fervent cradle
#

no

#

I was looking at the get started guide and came across this in the slash commands page

silver moat
#

did you add the command group to the bot?

fervent cradle
#

yeah

#

bot.add_application_command(math)
this line write?

#

right*

silver moat
#

yes

fervent cradle
#

I did

silver moat
fervent cradle
#

`Ignoring exception in command math:
Traceback (most recent call last):
File "/home/cyber/.local/lib/python3.10/site-packages/discord/commands/core.py", line 124, in wrapped
ret = await coro(arg)
File "/home/cyber/.local/lib/python3.10/site-packages/discord/commands/core.py", line 1310, in _invoke
await command.invoke(ctx)
AttributeError: 'NoneType' object has no attribute 'invoke'

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
File "/home/cyber/.local/lib/python3.10/site-packages/discord/bot.py", line 1114, in invoke_application_command
await ctx.command.invoke(ctx)
File "/home/cyber/.local/lib/python3.10/site-packages/discord/commands/core.py", line 375, in invoke
await injected(ctx)
File "/home/cyber/.local/lib/python3.10/site-packages/discord/commands/core.py", line 132, in wrapped
raise ApplicationCommandInvokeError(exc) from exc
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: AttributeError: 'NoneType' object has no attribute 'invoke'`

#

i dont get what is being returned as nonetype

#

nonetype object has no attribute invoke

silver moat
fervent cradle
#

before the bot.run(token) line

silver moat
#

could you try using bot.create_group instead?

fervent cradle
#

does that mean I have to change the first command

#

wait, my bad

#

the error remains

silver moat
#

the same code you provided works on my end. Could you type pip list and show output?

hushed ledge
#

One message removed from a suspended account.

fervent cradle
#

it is a very long list, but if you're wondering if I have discord.py or some other lib installed, I do not have anything else, this is my first time making a discord bot on a fresh install of linux

green hinge
# full basin Or make the init async

What am I doing wrong?

async def get_fish(gewaesser):
        fische = []
        fische = await dab.get_fisch_in_water(gewaesser)
        return fische

class Fisch(discord.ui.Select):
    async def __init__(self, bot: discord.Bot, selected_letter, gewaesser):
        self.bot = bot
        self.gewaesser = gewaesser
        fische = await get_fish(gewaesser)
        options = [discord.SelectOption(label=fish) for fish in fische if fish.startswith(selected_letter)]
        await super().__init__(
            placeholder="Wähle deinen Fisch aus",
            min_values=1,
            max_values=1,
            options=options,
        )```
fervent cradle
#

if you could perhaps tell me what the error means, I could further try resolve it myself

#

checked, not there

silver moat
fervent cradle
#

i see, also previously you said I made a logical mistake, could you tell me what the mistake was

silver moat
#

num1 and num2 are strings

#

they should be casted to an int.

fervent cradle
#

should've specified num1:int

#

👍

silver moat
#

but again, that is unrelated to your error.

hushed ledge
silver moat
#

at least, not from what I can see

winter condorBOT
green hinge
# full basin .idw
  File "c:\Users\User\Documents\Coding\OnlyFrames\cogs\spot.py", line 70, in callback
    self.attached_message = await interaction.response.send_message(view=FischView(self.bot, selected_letter, self.gewaesser))
  File "c:\Users\User\Documents\Coding\OnlyFrames\cogs\spot.py", line 25, in __init__
    super().__init__(Fisch(self.bot, self.selected_letter, gewaesser))
TypeError: __init__() should return None, not 'coroutine'```
silver moat
green hinge
# silver moat you can make an async init with something like this: ```py class AsyncInit: ...

Is that how it works then?

class Fisch(discord.ui.Select):
    async def __init__(self, bot: discord.Bot, selected_letter, gewaesser):
        self.bot = bot
        self.gewaesser = gewaesser
        fische = await get_fish(gewaesser)
        options = [discord.SelectOption(label=fish) for fish in fische if fish.startswith(selected_letter)]
        obj = super().__init__(self)
        await obj.__init__(
            placeholder="Wähle deinen Fisch aus",
            min_values=1,
            max_values=1,
            options=options,            
        )
        return obj```
green hinge
#

Can anyone help me? I do not understand it so completely and find on the Internet also no Doku or explanation 😬

echo egret
#

what is the difference between fetch_message() and get_message() ?

limber urchin
#

fetch_message makes an API call, get_message uses the bot's internal cache

strange beacon
limber urchin
#

get_message only uses the cache, fetch_message only makes an API call. Nothing is tried "first"

#

.rtfm get_or_fetch

limber urchin
#

that's your best option ^

silver moat
#

there is no get_or_fetch_message afaik

echo egret
#

why can I get but not fetch from a Bot object?

limber urchin
#

because get uses the bot's internal cache

#

an API call requires a channel specified as well

echo egret
#

ok thanks for the help 👍

limber urchin
#

so basically, you should always try get first since it's faster and doesn't make any calls to Discord's API. If get returns None, use fetch

grizzled sentinel
#

If fetch returns none it does not exist

green hinge
# silver moat you can make an async init with something like this: ```py class AsyncInit: ...

This does not work, can you explain this to me or do you have a link where I can read this in more detail? 🙂

class Fisch(discord.ui.Select):
    async def __init__(self, bot: discord.Bot, selected_letter, gewaesser):
        self.bot = bot
        self.gewaesser = gewaesser
        fische = await get_fish(gewaesser)
        options = [discord.SelectOption(label=fish) for fish in fische if fish.startswith(selected_letter)]
        obj = super().__init__(self)
        await obj.__init__(
            placeholder="Wähle deinen Fisch aus",
            min_values=1,
            max_values=1,
            options=options,            
        )
        return obj```
silver moat
proud mason
proud mason
green hinge
# proud mason just add this to your class ```py async def __new__(cls, *args, **kwds): ...

Like this?

class Fisch(discord.ui.Select):
    async def __new__(cls,  bot: discord.Bot, selected_letter, gewaesser):
        cls.bot = bot
        cls.gewaesser = gewaesser
        obj = super().__new__(cls)
        fische =
        options = [discord.SelectOption(label=fish) for fish in bot.fish if fish.startswith(selected_letter)]
        await obj.__new__(
            placeholder="Wähle deinen Fisch aus",
            min_values=1,
            max_values=1,
            options=options,
        )
        return obj

    async def __init__(self, gewaesser):
        self.fische = await dab.get_fisch_in_water(self.gewaesser) ```
proud mason
proud mason
#

Although remove the await from super init

green hinge
# proud mason Although remove the await from super init

Like this?

class Fisch(discord.ui.Select):
    async def __new__(cls, *args, **kwds):
        obj = super().__new__(cls)
        await obj.__init__(*args, **kwargs)
        return obj

    async def __init__(self, bot: discord.Bot, selected_letter, gewaesser):
        self.bot = bot
        self.gewaesser = gewaesser
        fische = await get_fish(gewaesser)
        options = [discord.SelectOption(label=fish) for fish in fische if fish.startswith(selected_letter)]
        super().__init__(
            placeholder="Wähle deinen Fisch aus",
            min_values=1,
            max_values=1,
            options=options,
        ) ```
proud mason
#

you can now do smth = await Fisch(...)

green hinge
proud mason
green hinge
proud mason
green hinge
# proud mason oops. rename `kwds` to `kwargs` in the `__new__` functions

Error 😄

    raise TypeError(f"expected Item not {item.__class__!r}")
TypeError: expected Item not <class 'coroutine'>
C:\Users\User\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ui\view.py:416: RuntimeWarning: coroutine 'Fisch.__new__' was never awaited
  return await self.on_error(e, item, interaction)
RuntimeWarning: Enable tracemalloc to get the object allocation traceback```
proud mason
proud mason
#

also, possible to get full traceback?

green hinge
# proud mason did you await while creating the object?

My Code:

async def get_fish(gewaesser):
        print(gewaesser)
        fische = []
        fische = await dab.get_fisch_in_water(gewaesser)
        return fische

class Fisch(discord.ui.Select):
    async def __new__(cls, *args, **kwargs):
        obj = super().__new__(cls)
        await obj.__init__(*args, **kwargs)
        return obj

    async def __init__(self, bot: discord.Bot, selected_letter, gewaesser):
        self.bot = bot
        self.gewaesser = gewaesser
        fische = await get_fish(gewaesser)
        options = [discord.SelectOption(label=fish) for fish in fische if fish.startswith(selected_letter)]
        super().__init__(
            placeholder="Wähle deinen Fisch aus",
            min_values=1,
            max_values=1,
            options=options,
        ) ```
proud mason
#

like show where you use it

green hinge
#

The Error:

description=None emoji=None default=False>, <SelectOption label='S' value='S' description=None emoji=None default=False>, <SelectOption label='T' value='T' description=None emoji=None default=False>, <SelectOption label='U' value='U' description=None emoji=None default=False>, <SelectOption label='V' value='V' description=None emoji=None default=False>, <SelectOption label='W' value='W' description=None emoji=None 
default=False>, <SelectOption label='Z' value='Z' description=None emoji=None default=False>] channel_types=[] disabled=False>:
Traceback (most recent call last):
  File "C:\Users\User\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ui\view.py", line 414, in _scheduled_task
    await item.callback(interaction)
  File "c:\Users\User\Documents\Coding\Bot\cogs\spot.py", line 70, in callback
    self.attached_message = await interaction.response.send_message(view=FischView(self.bot, selected_letter, self.gewaesser))
  File "c:\Users\User\Documents\Coding\Bot\cogs\spot.py", line 25, in __init__
    super().__init__(Fisch(self.bot, self.selected_letter, gewaesser))
  File "C:\Users\User\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ui\view.py", line 181, in __init__
    self.add_item(item)
  File "C:\Users\User\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ui\view.py", line 287, in add_item
    raise TypeError(f"expected Item not {item.__class__!r}")
TypeError: expected Item not <class 'coroutine'>
C:\Users\User\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ui\view.py:416: RuntimeWarning: coroutine 'Fisch.__new__' was never awaited
  return await self.on_error(e, item, interaction)
RuntimeWarning: Enable tracemalloc to get the object allocation traceback```
green hinge
proud mason
livid monolith
#
    async def reload(ctx):
        for extension in initial_extensions:
            bot.reload_extension(extension)
            await ctx.send("All cogs have been reloaded.")```

NameError: name 'bot' is not defined
proud mason
#

you need the async def __new__ code, you need to define __init__ as async, and await Fisch(...) in the super init

#

you also need to change this line

    self.attached_message = await interaction.response.send_message(view=FischView(self.bot, selected_letter, self.gewaesser))

to

    self.attached_message = await interaction.response.send_message(view=await FischView(self.bot, selected_letter, self.gewaesser))
green hinge
# proud mason you need the `async def __new__` code, you need to define `__init__` as async, a...

Ok like this?

class FischView(discord.ui.View):
    async def __new__(cls, *args, **kwargs):
        obj = super().__new__(cls)
        await obj.__init__(*args, **kwargs)
        return obj

    async def __init__(self, bot: discord.Bot, selected_letter: str, gewaesser):
        self.bot = bot
        self.gewaesser = gewaesser
        self.selected_letter = selected_letter
        super().__init__(await Fisch(self.bot, self.selected_letter, gewaesser))```
proud mason
#

now you are getting it prayadge

livid monolith
real frost
#

Hello, how to change the label of another button?

green hinge
real frost
#

oh, i got it

green hinge
proud mason
#

anyways i gtg sleep

green hinge
# proud mason sorry i didn’t understand

I have a dropdown menu.
When I select something in this dropdown menu a new second dropdown menu is created.
If I select something there again, a third dropdown menu is created.
If I select something in the third dropdown menu a button is created. When I press the button I want to write the three selected contents from the dropdown menus into the database.
Can I then somehow access the contents in the callback of the button without always having to pass the values of the dropdown menus self.values as a variable into the next view of the next dropdown?
Because then I have later in the view of the third dropdown menu 2 variables that were passed where the values from the previous Drin stand and must then pass 3 variables to the button.
Is that somehow easier that I can access the values directly in the button? 🙂

versed fern
#

Ig I'm not the only one here rewriting their code in order to migrate to v3. I created a v3 branch and use pycharm to switch back and forth. Unfortunately both branches use the same virtual environment, thus I can't install pycord v2 in one and v3 in the other. Is it possible to have different venvs/interpreters on different branches or do I have to create a seperat project?

limber urchin
#

Tbh migrating to v3 is not a very good idea unless you're doing it for test purposes

nova garnet
#

Hello! I have a question

Why don't slash commands appear for my bot on my sever? I tested several servers and edited the code in different ways, but there is no result
Initially, there were slash commands some time, but after some test now they simply do not appear (Could this be a discord rate limit?)

import discord
from config import settings

SubBot = discord.Bot(intents=discord.Intents.all())

print(f"::: Bot starts!")

@SubBot.event
async def on_connect():
    print(f"::: {SubBot.user} connected to Discord!")

@SubBot.event
async def on_ready():
    print(f"::: {SubBot.user} started successfully!!")

@SubBot.slash_command()
async def test(ctx):
    await ctx.respond(f"{ctx.user}")

SubBot.run(settings['TOKEN'])
versed fern
full basin
#

.rtfm on_connect

full basin
#

Read the docs. 1st item.

nova garnet
#

Oh! Thank you! I've been struggling with this for 2 hours now and I've already lost all the time

#

Can you explain why it doesn't call Bot.sync_commands()?

full basin
#

Because you're overriding the method that calls it

#

And You're not calling it by yourself

gleaming falcon
#

Generic python question -- is there a way to have a master class that loads and returns an instance of a child class automatically?

Like I want to be able to load an instance of Fruit (contrived) but have subclasses,, e.g. Apple and Banana be returned based on some thing I pass into the Fruit constructor.

What's the best way of doing that? Or is that not something recommended? I need to abstract out some API calls but don't want my cog to have to care which class I'm actually interacting with, assuming they have the same methods

strange beacon
mild sigil
#

Question about bot capabilities.

I am working on a bot to track some game statistics as well as achievement completions. Only issue is that with players self-reporting I want a means of verifying the data. Is it possible to have the bot wait for a specific reaction like a thumbs up or green check mark from a specific player/group before it runs the rest of the code? And how long can I have it waiting for each instance? If 10 players were to submit within an hour, does the bot have the capacity to remember each instance separately and wait for the requested reaction? I don't currently want code on this, merely to know if the API and python would be able to accomplish this.

#

My assumption is something along the lines of a intents.reaction with on_raw_reaction_add tied to true/false statement to see if user.id equals someone with higher admin role/perms?

full basin
#

Yes. The event is the best approach.

full basin
#

Isn't wait_for individual

#

Like it can't wait for multiple people to react

limber urchin
#

Oh, I thought they only wanted one person to react

#

I guess you could tie it into a loop and wait for a specific number of reactions. But in that case it's probably just better to use the event

mild sigil
#

Generally, I would like it to either accept with one reaction from an admin or from 3-5 reactions from unique players

#

whichever occurs first

limber urchin
#

You could do something like

while number_of_reactions < 5 and number_of_admin_reactions < 1:
    # wait for another reaction
# Do your stuff here

But the event listener might be cleaner

mild sigil
#

lol, noticed the edit and was about to comment on that

#

but yeah, that should probably work. I have a single command with 8 buttons for the options that each run their own code depending on which is pressed. Will play with this and see if I can get it to work properly

#

Thanks for the suggestions/help

winter dagger
#

Basic python question because I haven't ran into this yet:

What does the ellipses in this mean?
some_function(view: View = ...)

#

I'm used to the default being None. Wasn't sure if this acted the same way.

full basin
#

And makes the argument non-required

winter dagger
#

Hmmm, interesting. So this is essentially the same as None?

full basin
#

If you do = None, then it'll be None when you don't pass an argument

winter dagger
#

Ah, I see. It allows the argument to not exist. Thanks!

full basin
#

You can probably Google it and get a better explanation.

red geyser
#

I have an add faq command that store the faq in a separate file, however the faq isnt being written to the file. So when ever i restart the bot, it says the faq isnt there.

import dictionary

@commands.command()#addfaq command
@commands.has_permissions(administrator=True)
    async def addfaq(self, ctx, question, *, answer):
        dictionary.faq_dict[question.replace("'", "")] = answer.replace("'", "")
        await ctx.send(f"FAQ added: {question} - {answer}")
full basin
#

Use an actual database

red geyser
#

no

#

im not looking at using an "actual database"

nova garnet
#

If i have an description of command, how can i get it as string to send somewhere?

#

Something like {bot.command.user.description}

#

😭

mild sigil
#

The embed = embed seems redundant, you already have it called.
Probably:

``await ctx.respond(str(embed))

#

or embed[1]

nova garnet
#

Thanks but i dont think thats what i want

mild sigil
#

could always just return embed.description if you want it somewhere else

full basin
#

That will return a Command object, which has a description attribute. If this is what you're trying to ask lol

nova garnet
#

But i think i did all wrong

#

Ill try to fix it

mild sigil
#

willing to be proven wrong, thats how you learn

full basin
nova garnet
#

For start, this is the main file for now.

bot = discord.Bot(intents=discord.Intents.all())

user = bot.create_group(name="user", ...

@user.command(name="info",
              description="some description", ...
async def command(ctx):
   ...
#

Nice i did it
bot.get_application_command("user info").description

full basin
#

That's great.

hushed ledge
#

One message removed from a suspended account.

#

One message removed from a suspended account.

silver moat
hushed ledge
full basin
#

Where is the function?..

hushed ledge
full basin
#

Where's the get_pages function

silver moat
#

please show more of your code.

hushed ledge
#

One message removed from a suspended account.

silver moat
#

while the example is correct, yours may not be.

hushed ledge
#

One message removed from a suspended account.

silver moat
#

ok, but your commands?

hushed ledge
nova garnet
#

Hi
I cant understand why command options does not work
Ive tried to put option = [...] in @user.command
Put option into async def command
and tried to add @discord.command.option
And all does not works

bot = discord.Bot(intents=discord.Intents.all())

user = bot.create_group(name="user")

@user.command(name="info")
async def command(ctx: discord.ApplicationContext, test: discord.commands.Option(discord.Member, "Test")):
    await ctx.respond("test")
full basin
#

It's discord.Option

nova garnet
full basin
#

Yes

silver moat
nova garnet
#

Why discord.Option(discord.SlashCommandOptionType.user)) shows only all who writed something in chat? How can i select from all members of server?

silver moat
hushed ledge
#

One message removed from a suspended account.

errant craneBOT
#

Here's the paginator example.

hushed ledge
#

One message removed from a suspended account.

nova garnet
#

Why when im using more parameters in discord.Option members does not appears?

#

But when im using this all works fine

young bone
nova garnet
#

Like this? 🤨

young bone
#

discord.Member, name=""

nova garnet
#

Nice, thats works

#

But i think there is must be keyword? Or it does not exists?

silver moat
silver moat
hushed ledge
nova garnet
#

How to set default parameter to member that executed command?
This code is sends nothing good 😔

#

Ive tried discord.ApplicationContext.author but it sends <discord.utils._cached_property object at 0x0000022B92A9C410>

silver moat
#

you would usually set default to None and handle the logic in the callback itself

nova garnet
#

This? Nice

#

Thanks

proud mason
#

If they are in different messages, you have to pass the values around

proud mason
#

So you don't need an if condition

fervent cradle
#

why does this keep happening?

#

I have

        if not self.get_member_count.is_running():
            self.get_member_count.start()
fervent cradle
proven ferry
#

How should I fix it?

#
import os
import json
from discord.ext import commands

with open('config/config.json') as config:
    data = json.load(config)

class deva(commands.Bot):
    def __init__(self, *args, **kwargs):
        self.token = data["token"]
        super().__init__(command_prefix=data["prefix"], *args, **kwargs)

bot = deva(owner_id=901500429618274304, case_insensitive=True)

@bot.event
async def on_ready():
    print(f'{bot.user} is Ready')

if __name__ == "__main__":
    for file in os.listdir('./cogs'):
        if file.endswith('.py'):
            bot.load_extension(f'cogs.{file[:-3]}')

    bot.run(bot.token)```
limber urchin
proven ferry
limber urchin
#

🤷‍♂️

#

Show your actual code, or show the actual error

proven ferry
sinful laurel
#

its not doing the funny

#

I basically did everything in ?tag replit but pycord just wont install

limber urchin
#

Then use something other than replit, it's trash

#

?tag norepl

obtuse juncoBOT
#

Why NOT to use Repl as a hosting platform

You should not use Repl.it to host your bot.
It may be a nice option as its "free" but you should use something else considering the major flaws.

  • The machines are super underpowered.
    • This means your bot will lag a lot as it gets bigger.
  • You'll need a web server alongside your bot to prevent it from being shut off.
    • This isn't a trivial task, and eats more of the machines power.
  • Repl.it uses an ephemeral file system.
    • This means any file you saved via your bot will be overwritten when you next launch.

IMPORTATNT

  • They use a shared IP for everything running on the service.
    This one is important - if someone is running a user bot on their service and gets banned, everyone on that IP will be banned. Including you.

Please avoid using repl.it to host your bot. It's not worth the trouble.

If you're looking for free options, consider using AWS/Google Cloud Platform/Azure and its respective free tiers or just pay for an actual VPS.

sinful laurel
#

im using it so i can work on it whereever

#

i have multiple computers

limber urchin
#

Why not just use git?

sinful laurel
#

i have one personal computer, another is a chromebook

limber urchin
#

Why not just use git?

sinful laurel
#

how would I run it on a school chromebook lmao

limber urchin
#

Why wouldn't you?

sinful laurel
#

wdym

limber urchin
#

What's stopping you from using git on a chromebook?

silver moat
#

just use gitpod for chromebooks

silver moat
limber urchin
#

It does though

#

Enable Linux environment on it

sinful laurel
#

cant

sinful laurel
silver moat
limber urchin
#

There's definitely a workaround

sinful laurel
#

nope

limber urchin
#

NPCMechanicShrug alright, good luck then

#

have fun with repl

silver moat
#

literally online vscode

sinful laurel
#

wait

limber urchin
#

No one is going to download your bot and read it. Send your code or ask your question properly

sinful laurel
silver moat
sinful laurel
#

vscode

proven ferry
# limber urchin No one is going to download your bot and read it. Send your code or ask your que...
import os
import json
from discord.ext import commands

with open('config/config.json') as config:
    data = json.load(config)

class deva(commands.Bot):
    def __init__(self, *args, **kwargs):
        self.token = data["token"]
        super().__init__(command_prefix=data["prefix"], *args, **kwargs)

bot = deva(owner_id=901500429618274304, case_insensitive=True)

@bot.event
async def on_ready():
    print(f'{bot.user} is Ready')

if __name__ == "__main__":
    for file in os.listdir('./cogs'):
        if file.endswith('.py'):
            bot.load_extension(f'cogs.{file[:-3]}')

    bot.run(bot.token)```
sinful laurel
#

but on chromebook

proven ferry
#

here

sinful laurel
#

or was that someoen else

silver moat
limber urchin
limber urchin
#

You're the one sending the wrong code

bold notch
#

My bot currently want to look though reply chains. But I assume I will always be rate limited when trying to find the reply message to a reply and so on?

proven ferry
limber urchin
silver moat
limber urchin
#

That is literally a different error than you sent before

silver moat
#

if you have message content intents you can increase your message cache and not deal with ratelimits

limber urchin
bold notch
silver moat
silver moat
sinful laurel
fervent cradle
#

How do I set a listening-to status?

#

nevermind i've figured it out

tired goblet
#

how can i accept inputs along with a slash command?

real frost
#

You can set an argument by using discord.Option

tired goblet
#
async def img(ctx):
  generateCard()
  #await ctx.respond(file = discord.File('newcard.png'))
  print(ctx.message)```
#

why does it print a None?

#

shouldn't ctx.message be a Message object?

real frost
#

cause slash command didnt send any message

proud mason
zenith crystal
#

Idk what too do?

green hinge
# proud mason Then you dont have a better way than passing it around

The system works like this, that a user presses a start button, then a new text channel is created only for the user. There he clicks then gradually through the dropdown menus and at the end the data should be written into the DB. The whole thing can of course be done by several users at the same time.
Should I then perhaps create a Dict at the first dropdown and then always pass only the Dict and add the values there so that I do not have to pass so many variables through later or will that not work?

young bone
zenith crystal
#

yeah wait

#

idk why its so much xD

young bone
#

why 2 times?

#

its the same everytime

zenith crystal
#

idk

#

ik

young bone
#

which py-cord version is that?

#

also uninstall this and py-cord and reinstall py-cord

#

restart vscode after that

nova garnet
#

How to display this user.created_at timestamp in <t:1675415220:D> style?

zenith crystal
#

Same error

nova garnet
#
_description = f"> {user.created_at}\n" +\
                   f"> {user.joined_at}\n" +\
                   f"> {user.joined_at}"
nova garnet
#

Ive found it
discord.utils.format_dt(user.created_at, 'R')

young bone
#

why should it not support it?

green hinge
#

How can I send a response without sending a message?
What options do I have there?

        if self.attached_message:
            await self.attached_message.edit_original_response(view=await FischView(self.bot, selected_letter, self.gewaesser))
            await interaction.response.```
young bone
#

there are no docs for it

green hinge
young bone
#

than edit the message with the response

proud mason
#

Use that

#

To edit

proud mason
green hinge
# proud mason interaction.response.edit_message

Do you mean like this?

    async def callback(self, interaction: discord.Interaction):
        selected_letter = self.values[0]
        if self.attached_message:
            await self.attached_message.interaction.response.edit_message(view=await FischView(self.bot, selected_letter, self.gewaesser))
        else:
            self.attached_message = await interaction.response.send_message(view=await FischView(self.bot, selected_letter, self.gewaesser))```
proud mason
#

Depends on what you want

#

Not self.attached_message.interaction....

Just interaction.response.send_message

#

Use interaction you receive in the callback

green hinge
green hinge
# proud mason Use interaction you receive in the callback

I want my dropdown menu "Fish" to be updated (edited) when I select another letter. The message should not be deleted and posted again but at the point where it is simply edited because otherwise the sequence is no longer correct

class BuchstabeFisch(discord.ui.Select):
    async def __new__(cls, *args, **kwargs):
        obj = super().__new__(cls)
        await obj.__init__(*args, **kwargs)
        return obj

    async def __init__(self, bot: discord.Bot, gewaesser):
        self.bot = bot
        self.gewaesser = gewaesser
        self.attached_message = None
        fische = await get_fish(gewaesser)
        buchstaben = set()
        for fisch in fische:
            buchstaben.add(fisch[0])
        buchstaben_sortiert = sorted(list(buchstaben))
        options = [discord.SelectOption(label=letter) for letter in buchstaben_sortiert]
        super().__init__(
            placeholder="Anfangsbuchstabe Fisch",
            min_values=1,
            max_values=1,
            options=options,
        )
        
    async def callback(self, interaction: discord.Interaction):
        selected_letter = self.values[0]
        if self.attached_message:
            await self.attached_message.interaction.response.edit_message(view=await FischView(self.bot, selected_letter, self.gewaesser))
        else:
            self.attached_message = await interaction.response.send_message(view=await FischView(self.bot, selected_letter, self.gewaesser))```
nova garnet
#

I cant understand whats wrong, there is TypeError: 'in <string>' requires string as left operand, not int in if id not in user_first_join:
Ive tried to str(id) and then another TypeError: 'str' object does not support item assignment in user_first_join[id]
Then ive added int(id) and there is still this error sadcatthumbsup

user_first_join = {}
f = open("user_first_join.txt", "r")
user_first_join = f.read()
f.close()

def save_user_first_join(id):
    if id not in user_first_join:
        user_first_join[id] = bot.get_guild(1069357003362807848).get_member(id).joined_at
        f = open("user_first_join.txt", "w")
        f.write(f"{user_first_join}")
        f.close()

@bot.event
async def on_member_join(user):
    save_user_first_join(user.id)
young bone
#

oh pls use "with open("")

#

also use async def and await

nova garnet
#
user_first_join = {}
with open("user_first_join.txt", "r") as f:
    user_first_join = f.read()

async def save_user_first_join(id):
    if str(id) not in user_first_join:
        user_first_join[id] = bot.get_guild(1069357003362807848).get_member(id).joined_at
        with open("user_first_join.txt", "w") as f:
            f.write(f"{user_first_join}")

@bot.event
async def on_member_join(user):
    await save_user_first_join(user.id)

I hope this is it

proud mason
#

Also, good idea to not name your variables as id. It's a built in python function too

proud mason
#

Don't use text files or json as database

nova garnet
#

Is it fraught with performance?
I need to write a simple code for my server for 50 people as soon as possible, I don't think it's worth turning to SQLITE for this

#

Or it is?

proud mason
#

You could use python pickling but i feel you might as well use sqlite

young bone
#

Can you store emojis and long text in a db?

proud mason
#

Heck you can even store the bytes of the emoji in sql

green hinge
young bone
green hinge
# young bone you use this if the response takes longer

Can I just use that or is that messy?

        if self.attached_message:
            await self.attached_message.edit_original_response(view=await FischView(self.bot, selected_letter, self.gewaesser))
            await interaction.response.defer()
        else:
            self.attached_message = await interaction.response.send_message(view=await FischView(self.bot, selected_letter, self.gewaesser))```
young bone
#

you still have to send a message or you will get an error

proud mason
proud mason
proud mason
green hinge
proud mason
#

Can you show what happens? Like a video if possible

green hinge
green hinge
young bone
#

mkv? oof

green hinge
#

OBS Format 😄

#

Code:

class BuchstabeFisch(discord.ui.Select):
    async def __new__(cls, *args, **kwargs):
        obj = super().__new__(cls)
        await obj.__init__(*args, **kwargs)
        return obj

    async def __init__(self, bot: discord.Bot, gewaesser):
        self.bot = bot
        self.gewaesser = gewaesser
        self.attached_message = None
        fische = await get_fish(gewaesser)
        buchstaben = set()
        for fisch in fische:
            buchstaben.add(fisch[0])
        buchstaben_sortiert = sorted(list(buchstaben))
        options = [discord.SelectOption(label=letter) for letter in buchstaben_sortiert]
        super().__init__(
            placeholder="Anfangsbuchstabe Fisch",
            min_values=1,
            max_values=1,
            options=options,
        )
        
    async def callback(self, interaction: discord.Interaction):
        selected_letter = self.values[0]
        if self.attached_message:
            await interaction.response.edit_message(view=await FischView(self.bot, selected_letter, self.gewaesser))
        else:
            self.attached_message = await interaction.response.send_message(view=await FischView(self.bot, selected_letter, self.gewaesser))```
#

So the selections are dependent on each other.
Depending on which water I choose, I get other letters and depending on the letter other fish.
And I would like to do it now so that if I select a body of water and then a letter, I then but notice the body of water was wrong, that the dropdown menus of the letter is adjusted and then that of the fish of course also 🤔

young bone
nova garnet
#

How to get id of server on what i have used command?

nova garnet
#

Thanks
But how to get it from this event?

@bot.event
async def on_member_join(user):
 ...
young bone
#

same way but with user

#

if you use user: discord.Member it will show it

green hinge
#

How can I "save" the attached_message so that my intention works?

Because if I change the water then the dropdown menu for the letters is created again and thus the attached_message again to None so that I can then no longer edit the fish dropdown menu but a new create 🤔

proud mason
proud mason
#

.itworks

winter condorBOT
green hinge
green hinge
young bone
proud mason
#

Wait that doesn't make sense

sinful pivot
#

Hello. how would I be able to create a dropdown based on a list of arguments?

#

The list basically contains dataclasses.

green hinge
errant craneBOT
#

Here's the slash options example.

proud mason
#

Good idea for you to create a post in #969574202413838426 because this is getting big

rose turtle
#

Hello,
Is there away to set permissions in a private channel?
For example like this:

for channel in interaction.guild.channels:
            await channel.set_permissions(muted, speak=False, send_messages=False, read_message_history=True, read_messages=True)
proud mason
#

.rtfm channel.set

rose turtle
proud mason
green hinge
rose turtle
proud mason
rose turtle
#

How do I do that?

nova garnet
#

Why permissions dont works?

from discord import default_permissions

bot = discord.Bot(intents=discord.Intents.all())

dump = bot.create_group(name="dump")

@dump.command(name="first_join")
@default_permissions(administrator=True)
async def command(ctx: discord.ApplicationContext):
  ...

Everyone still can use this command

proud mason
#

.rtfm channel.perm

proud mason
#

Use permissions.for

rose turtle
#

Could please provide an example

proud mason
nova garnet
#

Discord bots cant set this permissions by default?

proud mason
proud mason
rose turtle
#

Why is mutedrole=discord.utils.get(ctx.guild.roles, id=int(role_id)) not working?

green hinge
grizzled sentinel
proud mason
#

Didn't know that lol

proud mason
rose turtle
rose turtle
nova garnet
proud mason
rose turtle
green hinge
#

Does anyone know a solution to my problem "Regenerate the following dropdown menus" ? That would be infinitely helpful.

proud mason
hushed ledge
#

One message removed from a suspended account.

full basin
hushed ledge
full basin
#

"Missing 1 required positional argument"

verbal marten
#

How would I create a cooldown for a modal? At the moment I have it on the button to open the modal, but I need it to only set the cooldown if its submitted.

proud mason
#

instead of updating time in button callback, update it in modal callback

#

you can also use self.stop in the modal and modal.wait in the button callback to keep updating the time in the button callback

verbal marten
#

I tried just placing that in the modal callback, but it doesn't function

proud mason
#

Rather than bucket.update_rate_limit, use bucket.get_retry_after
then pass the bucket to the modal. and at the end of the modal, use bucket.update_rate_limit

cooldown stuff is undocumented. so bear with me if my solutions are not working.

verbal marten
proud mason
verbal marten
verbal marten
# proud mason can you show the updated code
async def callback(self, interaction: discord.Interaction):
        new_message = interaction.message
        new_message.author = interaction.user
        bucket = self.cd_mapping.get_bucket(new_message)
        retry_after = bucket.get_retry_after()
        if retry_after:
            await interaction.response.send_message(f'cooldown')

        #modal stuff
        bucket.update_rate_limit()
        await channel.send(embed=embed, delete_after=18000)
cunning furnace
#

Is it possible to implement a system where when pressing a button, it sends a message asking you a question and then once you've answered it, it sends an embed with your answer to a specific person

limber urchin
#

yes

wooden spindle
#

I'm sure I'm being fuckin stupid

For some reason this listener isn't working

custom_commands is a dict and is not empty

    @commands.Cog.listener()
    async def on_message(self, message):

        for command, response in self.custom_comamnds.items():
            if message.content.startswith(">" + command):
                await message.channel.send(response)
#

i'm fucking special

#

commands != comamnds

peak rose
#

anyone has an idea why button might not get disabled

#
      for child in self.children:
            child.disabled = True
       
      await interaction.response.edit_message(view=self)```
grizzled sentinel
#

.rtfm disable_all

grizzled sentinel
full basin
#

It essentially does the same

grizzled sentinel
#

Otherwise we will need more code

fervent cradle
#

Is it okay? As a backup method, what if I'll post the .SQL file in a private Discord server channel?? As a backup of postgresql? In every 1minutes

grizzled sentinel
#

There is no way you need a backup ever 1 min. Also discord only saves attachments for about a month iirc. And there are file size limits on discord.
So no not really a good option.

fervent cradle
#

Is there any good way to do it ??

grizzled sentinel
#

Databases save to a file if you can still access your files you will have your data.

limber urchin
#

If you don't have access to a way to store your files, you won't be able to store backups either. Simple as that

fervent cradle
limber urchin
#

Then find another service or another place to store your files. This has nothing to do with pycord or python at all for that matter

grizzled sentinel
#

My guess if they stop the service they will not delete the files

fervent cradle
grizzled sentinel
#

Would be my guess, if you are super worried about it contact AWS support I'm sure they would be able to answer the question.

olive orbit
#

.rtfm cooldown

proud mason
proud mason
verbal marten
cunning furnace
young bone
cunning furnace
# young bone button and wait_for?

I tried using a wait_for inside of a button which is inside of a view class but like it gives the error AttributeError: 'BuilderDecisionView' object has no attribute 'bot'

        def check(m):
            return m.author == interaction.user and m.channel == interaction.channel
        reason = await self.bot.wait_for("message", check=check)
        reason = reason.content```
young bone
#

you have to use interaction for it

#

not bot

cunning furnace
#

await interaction.wait_for(...)?

young bone
cunning furnace
#

you can use interaction.client inside of a cog?

#

i thought client and bot just always got replaced with self

#

Well thank you very much for the help rooAww

rose turtle
weary fractal
#

How do i solve this? (I am new to to pycord)

amber shale
#

quick question can discord bot send a file?

young bone
fervent cradle
#

how can i add prefix on the bot but slash commands can still work?

young bone
fervent cradle
young bone
#

with commands.Bot

#

?tag client

obtuse juncoBOT
#
discord.Client # just for events
discord.Bot # events + slash/user/msg commands
commands.Bot # above + prefixed commands
bridge.Bot # above + bridge commands (application commands and text commands in one)
fervent cradle
#

I'll add commands.Bot even if i have dsicord.Bot?

young bone
#

replace discord.Bot

fervent cradle
#

aight

rose turtle
#

How do you make context menu in cogs?

astral mist
#

can i have 2 bots running in the same file

#

like just have 2 instances

young bone
#

?tag nojson

obtuse juncoBOT
#

Why not to use json files for data storage
JSON files are commonly used to store data that is read by a program, however, they are unsuitable for storing dynamic data due to a number of reasons.
It is recommended to use a DBMS (Database Management System) as they come with optimized technologies for storing and retrieving information.

Advantages of using a database:
- Database tables can be related, making it easy to separate your information into multiple tables and only fetch what you need
- Databases allow you to use a query/data processing language to make complex data operations easier with less code
- One misplaced character will corrupt an entire file. A database very rarely experiences corruptions due to their automatic handling of data integrity
- Transactions in SQL databases allow you to revert unwanted changes and prevent data corruption in the case of an error
- Databases have support for indexes, allowing retrieval of some data to be extremely fast
- It is very easy to update existing data in a database, as opposed to re-writing a file
- Databases are reliable

Popular database management systems:

  • SQLite3 (File based, no need for a server setup, SQLite is the most used database engine in the world)
  • MongoDB (Stores data in documents a similar manner to JSON format, easy for beginners)
  • PostgreSQL (Very popular and robust SQL based database management system)
  • MySQL (Another popular SQL based system, good start for learning SQL)
rose turtle
proud mason
rose turtle
proud mason
proud mason
#

One sec

astral mist
errant craneBOT
#

Here's the button roles example.

young bone
proud mason
proud mason
# rose turtle In cogs

Yeah i use @discord.message_command in cogs and it works as intended. User cmds should work too

fallow oracle
#
import discord
from discord.ext import commands

intents = discord.Intents.all() 
intents.members = True

client = commands.Bot(intents)

@client.event
async def on_ready():
    print("hi")
    await discord.ForumChannel.create_thread("1071432837229719613", "post name!")

token = load(open('./token.json'))
client.run(token["Token"])

Hey, any clue why this throws with

Ignoring exception in on_ready
Traceback (most recent call last):
  File "C:\Users\Dek\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 377, in _run_event
    await coro(*args, **kwargs)
  File "D:\GitHub\CTT\post.py", line 17, in on_ready
    await discord.ForumChannel.create_thread("1071432837229719613", "woo")
  File "C:\Users\Dek\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\channel.py", line 1227, in create_thread
    state = self._state
AttributeError: 'str' object has no attribute '_state'
Ignoring exception in on_message
Traceback (most recent call last):
  File "C:\Users\Dek\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\bot.py", line 298, in get_context
    if message.content.startswith(tuple(prefix)):
TypeError: tuple for startswith must only contain str, not tuple

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\Dek\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 377, in _run_event
    await coro(*args, **kwargs)
  File "C:\Users\Dek\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\bot.py", line 387, in on_message
    await self.process_commands(message)
  File "C:\Users\Dek\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\bot.py", line 383, in process_commands
    ctx = await self.get_context(message)
  File "C:\Users\Dek\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\bot.py", line 313, in get_context
    raise TypeError(
TypeError: Iterable command_prefix or list returned from get_prefix must contain only strings, not tuple
fervent cradle
#

How to get bot launch time?

fallow oracle
errant craneBOT
#

src/main.py line 81

done = time.time()```
#

Here's the basic bot example.

young bone
#

@fallow oracle ^

fallow oracle
young bone
fallow oracle
#

is there a way I could get ctx (or an alternative) in my on_ready function (or anything else that could be triggered on it's own at startup)

I'd like my bot creating a forum channel with an embed on the original message in the post when I run it (I don't want to deal with any manual functions on Discord and prefer using this as a CLI tool)

fallow oracle
proud mason
#

you can use bot.get_guild if you want

#

that gives you the guild

fallow oracle
young bone
fallow oracle
young bone
#

you dont even define the bot right

#

also get the guild and create the forum

fallow oracle
proud mason
proud mason
#

.intents

winter condorBOT
#

https://docs.pycord.dev/en/master/intents.html
https://discord.com/developers/docs/topics/gateway#gateway-intents

import discord
from discord.ext import commands

# Get specific intents for fine control
intents = discord.Intents()
intents.emojis = True
intents.guilds = True
intents.messages = True  # Required for prefix commands!
...
# Get all non-priveliged intents; this excludes presences, members and message_content 
intents = discord.Intents.default()

# Set priveliged intents: these must be enabled on dev portal
intents.members = True
intents.presences = True
intents.message_content = True  # Required for prefix commands >= 2.0.0b5

# Get all intents; all intents must be enabled on dev portal.
intents = discord.Intents.all()

# Apply intents when creating your bot
bot = commands.bot(prefix="?", intents=intents)
fallow oracle
#

alright, set it up like so:


intents = discord.Intents.default()
intents.members = True
intents.message_content = True

bot = commands.Bot(
    command_prefix=commands.when_mentioned_or("$"),
    description="",
    intents=intents,
)
fallow oracle
#
    guild = bot.get_guild(1070184725580349440)
    forum = guild.get_channel(1071432837229719613)
    await forum.create_thread("1071432837229719613", "woo")
fallow oracle
#

worked 👍 now imma see if I can make an embed in that original post

proud mason
#

ohh nice

fallow oracle
#

so it seems there's no support to feed it an embeds.Embed object

#

maybe I could modify that message and edit it and potentially replace it with a message with features an embed?

lethal valve
#

How would I go about stripping the contents of an embed down into a format similar to that of an api response

limber urchin
#

.rtfm Embed.to_dict

winter condorBOT
lethal valve
#

Appreciated 🫶

fervent cradle
#

Something's wrong with ephermal, how is it used?

Whenever I try to use it in a response the bot simply does not respond to the command anymore

fervent cradle
full basin
#

"ephermal"

fervent cradle
#

Can you explain?

#

oh, the word needs to be in quotes?

young bone
atomic wolf
#

minor spelling mistake

full basin
#

It's ephemeral

#

Not ephermal

fervent cradle
#

I'm confused with the spelling

#

And it worked! Thanks @full basin and @atomic wolf

fervent cradle
#

How to make an option like this? (not just bool)

errant craneBOT
#

Here's the slash options example.

limber urchin
#

Look at line 15 in that example @fervent cradle

fervent cradle
#

👍

topaz rune
#

Hi, can a bot use multiple tasks.loop()?

silver moat
topaz rune
#

it seems that it dont execute more than one at the same time

#

like, my second tasks.loop is only

@tasks.loop(seconds = 10) 
    async def actual_embed(self):
        print("test")
```but it dont even print test
silver moat
#

did you start it

topaz rune
#

hm

#

how to? I dont start my first one, and its still working apparently

#

oh

#

im dumb

#

effectively

silver moat
topaz rune
#

ty mate

proud mason
#

command checks

hollow veldt
#
class MyModal(discord.ui.Modal):
    def __init__(self, *args, **kwargs) -> None:
        super().__init__(
            discord.ui.InputText(
                label="Short Input",
                placeholder="Placeholder Test",
            ),
            discord.ui.InputText(
                label="Longer Input",
                value="Longer Value\nSuper Long Value",
                style=discord.InputTextStyle.long,
            ),
            *args,
            **kwargs,
        )

    async def callback(self, interaction: discord.Interaction):
        embed = discord.Embed(
            title="Your Modal Results",
            fields=[
                discord.EmbedField(
                    name="First Input", value=self.children[0].value, inline=False
                ),
                discord.EmbedField(
                    name="Second Input", value=self.children[1].value, inline=False
                ),
            ],
            color=discord.Color.random(),
        )
        await interaction.response.send_message(embeds=[embed])


@bot.slash_command(name="modaltest")
async def modal_slash(ctx: discord.ApplicationContext):
    """Shows an example of a modal dialog being invoked from a slash command."""
    modal = MyModal(title="Slash Command Modal")
    await ctx.send_modal(modal)

I'm using the example to create a modal I get an error.

#
class MyModal(discord.ui.modal):
AttributeError: module 'discord.ui' has no attribute 'modal'
silver moat
#

are you sure the m in modal is capitalized?

hollow veldt
#

yes

silver moat
#

what pycord version?

hollow veldt
#

py-cord==2.0.0b1

silver moat
#

pip list and send output

silver moat
hollow veldt
#

how

#

?tag install

obtuse juncoBOT
#
  1. Uninstall discord.py or any other forks of discord.py you might have with the namespace discord.
    python -m pip uninstall discord.py discord -y

2a. Install py-cord
python -m pip install py-cord

2b. Update py-cord
python pip install -U py-cord

Installing other builds:
Note: You need to have git installed. Use ?tag git to find out how to install git.

Updating the module to master branch (unstable):
pip install -U git+https://github.com/Pycord-Development/pycord

silver moat
#

?tag install

obtuse juncoBOT
#
  1. Uninstall discord.py or any other forks of discord.py you might have with the namespace discord.
    python -m pip uninstall discord.py discord -y

2a. Install py-cord
python -m pip install py-cord

2b. Update py-cord
python pip install -U py-cord

Installing other builds:
Note: You need to have git installed. Use ?tag git to find out how to install git.

Updating the module to master branch (unstable):
pip install -U git+https://github.com/Pycord-Development/pycord

lethal valve
#

how do i edit a response using interaction

proud mason
#

or interaction.response.edit_message

#

depends on what you are doing

lethal valve
#

TypeError: InteractionResponse.edit_message() takes 1 positional argument but 2 were given

#

wtf

proud mason
#

you have to pass content as a kwarg btw

#

content="hello there"

olive marsh
#

unable to run, main file ".replit" not found

#

Umm

silver moat
#

create one

olive marsh
#

First time that problem appeared

#

now Im getting no module named discord

#

oh I see what I did

#

I deleted the history yesterday

#

I'm dumb

#

Need the packages again

silver moat
#

ok

olive marsh
#

Can you send me what the nix file should include?

#

I screwd up..

#

My god...

limber urchin
#

why are you using replit anyways?

olive marsh
#

Because it usually works and I'm more familiar with it

limber urchin
#

?tag norepl

obtuse juncoBOT
#

Why NOT to use Repl as a hosting platform

You should not use Repl.it to host your bot.
It may be a nice option as its "free" but you should use something else considering the major flaws.

  • The machines are super underpowered.
    • This means your bot will lag a lot as it gets bigger.
  • You'll need a web server alongside your bot to prevent it from being shut off.
    • This isn't a trivial task, and eats more of the machines power.
  • Repl.it uses an ephemeral file system.
    • This means any file you saved via your bot will be overwritten when you next launch.

IMPORTATNT

  • They use a shared IP for everything running on the service.
    This one is important - if someone is running a user bot on their service and gets banned, everyone on that IP will be banned. Including you.

Please avoid using repl.it to host your bot. It's not worth the trouble.

If you're looking for free options, consider using AWS/Google Cloud Platform/Azure and its respective free tiers or just pay for an actual VPS.

olive marsh
#

...

#

All of those will require a lot of setup and configuration

limber urchin
#

How?

olive marsh
#

I tried AWS

#

?tag repl

obtuse juncoBOT
#

dynoError No tag repl found.

limber urchin
#

okay?

olive marsh
#

?tag replit

obtuse juncoBOT
limber urchin
#

I'm just saying, replit will not work in the long run. If you want to develop Discord bots you should also learn how to host them properly. Especially if you ever plan on your bot growing.

olive marsh
#

My bot doesn't do anything crazy anyway

#

Except that you can make announcements with ease while the bot just asks you for inputs

limber urchin
#

Well if you're doing it for practice, why not also practice how to set it up?

olive marsh
#

I created a new repl

#

Fixed

#

Ooof

versed fern
#

Dude

lime totem
#

Hello

#

¿How to make a modal and embed message in one interaction?

silver moat
sinful laurel
#

getenv no workie

#

it keeps on saying it doesn't exist

#

tried also adding dotenv_path = ".env" but it doesn't really help much

young bone
sinful laurel
limber urchin
#

Your env file isn't supposed to be in json format lmao

sinful laurel
#

still acts as it never exists

limber urchin
#

google how env files look

#

that's still completely wrong

sinful laurel
#

wait fuck i think i screwed up the syntax

#

its =

young bone
waxen whale
#

So. Sorry but had to

young bone
#

what?

waxen whale
#

To clear the chat here

young bone
#

ok

fair ledge
#

Hello there! 🙂
Can autocompletion only be used with slash_commands or can I change the prefix somehow. So for example if i type in "cmd." as my prefix that the available commands with "cmd." as prefix are shown and described?

fair ledge
#

ok, I thought so. Thanks 🙂

boreal abyss
#

can i know how to make this list to auto complete?

list = ["probablilty". "randomized", "history", "likelihood"]

@bot.slash_command()
async def method(ctx, discord.autocomplete(list)):

is that true?

fair ledge
boreal abyss
#

where is the command

#

why do we return and do a for loop

#

why do we have 2 lists

limber urchin
#

Autocomplete takes a function that returns a list

boreal abyss
limber urchin
#

If you think making a function is hard, you might need to learn a bit more Python before making a bot

boreal abyss
#

no its not hard kik

limber urchin
#

so what's the issue then?

boreal abyss
#

im still confused how to link them

young bone
limber urchin
#

It literally tells you in the example. Look at line 138

boreal abyss
#

@real compasstion("color", description="Pick a color!", autocomplete=get_colors)
@real compasstion("animal", description="Pick an animal!", autocomplete=get_animals)
?

fair ledge
obtuse juncoBOT
#

dynoError No tag codeblocks found.

young bone
#

?tag codeblock

obtuse juncoBOT
#

Please put your code in a code block:
```py
Here is your Code
```

That makes reading code in Discord a lot easier:

print("This is an example.")
boreal abyss
#

understood thanks

stable cradle
#

How can I make it so that I can remove all the nicknames in my server?

fair ledge
#

is the hybrid_command decorator not implemented for pycord or how can I use it? 😮

limber urchin
#

hybrid command?

fair ledge
#
import discord
from discord.ext import commands
from discord import app_commands

class Bot(commands.Bot):
    def __init__(self):
        intents = discord.Intents.default()
        intents.message_content = True
        super().__init__(command_prefix = "?", intents = intents)

    async def setup_hook(self):
        await self.tree.sync(guild = discord.Object(id = guild_id))
        print(f"Synced slash commands for {self.user}.")
    
    async def on_command_error(self, ctx, error):
        await ctx.reply(error, ephemeral = True)

bot = Bot()

@bot.hybrid_command(name = "test", with_app_command = True, description = "Testing")
@app_commands.guilds(discord.Object(id = guild_id))
@commands.has_permissions(administrator = True)
async def test(ctx: commands.Context):
    await ctx.defer(ephemeral = True)
    await ctx.reply("hi!")

bot.run('TOKEN')

I want to register a command as a slash command but also on other prefixes like "?"

limber urchin
fair ledge
#

yeah, i know. That's why i was wondering on how to implement that on pycord 😮

errant craneBOT
#

Here's the bridge commands example.

fair ledge
#

ah thanks a lot, 😄

long moat
#

Hey, I'm making a bot to read data from a discord game bot and the embeds it sends. When it sends them normally (i.e. not a deferred message) the data can be captured fine. Some of the commands, it "thinks" about what it's doing (these are text prefix commands) and then responds (with the words (edited) appearing above the embed).

I would appreciate some help or direction on how to make it read "deferred" messages / embeds?

astral mist
#

bot = discord.bot(intents=intents)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: 'module' object is not callable

#
import discord
from dhooks import Webhook
from Secrets import *


vike = Webhook(viking_status)
blox = Webhook(blox_status)


intents = discord.Intents.default()
intents.typing = True
intents.presences = True

intents = discord.Intents.default()


bot = discord.bot(intents=intents)

@bot.event
async def on_ready():
    print(f'We have logged in as {bot.user}')
    vike.send(status)
    blox.send(status)





@bot.command
async def test(ctx):
    await ctx.respond(desc)


bot.run(token)

#

oh

astral mist
#

oh

proud mason
#

also, pycord has webhooks built in. use those

#

@astral mist ^

astral mist
#

Bot = discord.bot(intents=intents)

proud mason
astral mist
#

like this

proud mason
#

dhooks is a blocking library

#

it will block the event loop

astral mist
#

i didnt tho

astral mist
proud mason
#

you didnt what?

astral mist
proud mason
astral mist
#

oh

proud mason
#

check out the guide if you are using the library for the first time

#

.guide

winter condorBOT
astral mist
proud mason
# astral mist block the event loop

well dhooks is not an async library. it doesnt use the event loop. thats why using its functions will block your bot from connecting to the discord gateway

#

damn thats some lag

astral mist
#

oh

proud mason
#

👍

astral mist
#

whats this

#

no

proud mason
#

@bot.slash_command

astral mist
#

nvm wait

proud mason
#

please read the guide

#

.guide

winter condorBOT
astral mist
#

@bot.command
^^^^^^^^^^^
TypeError: ApplicationCommandMixin.command() takes 1 positional argument but 2 were given

#

this alr i will read it

full basin
#

I'm sure they don't and refrain to read the docs too.

limber urchin
#

so the usual doggokek

long moat
#

in slash?

#
Option(str, "description", choices=["choice1", "choice2"], required=False)```

adapt as req
#

i.e. int not str

#

but then your choices=[] will need to be integers not strings so choices=[1,2,3]

true pewter
#

to make a list of users, it should be like this, shouldn't it?

        list_users = await ctx.guild.fetch_members(limit=None)
        print(list_users)
limber urchin
#

try it and see

#

the docs explain exactly how to use the method

long moat
silver moat
#

perhaps

waxen whale
#

seems more like the cache is making problems

proud mason
long moat
#

so the game has "guilds", theres a way for someone to prove they are the "leader" by using a certain command, so i'm making a bot that tracks how often they have to do guild commands, who does them, when they reset for the next cycle etc.

the "proof" command, it "thinks" (deferred message) and then sends the embed which contains the "id" of the leader in

#

other than that there is no "automatic" way of confirming the person trying to register the guild with the tracking bot is actually the leader

silver moat
#

you can still use bot.wait_for to wait for an edited message.

long moat
#

i tried that and it came up blank.

silver moat
#

or the on_message_edit event

#

you have messages + message_content intents?

proud mason
#

Followup to a defer isn't actually a message edit iirc

#

Not sure but it would be cool if someone tested that

silver moat
silver moat
nova garnet
#

Is there any examples of pages with buttons like this? If you know please show it to me i want to do same thing

errant craneBOT
#

Here's the paginator example.

nova garnet
#

Thanks!

true pewter
proud pagoda
true pewter
#

And how is that done? @proud pagoda

proud pagoda
#

Make sure you enable it in the dev portal and in your code

green hinge
#

Maybe someone can help me further.
When I run my code on my PC everything works fine. But when I start the whole thing on my server and want to run my function I always get this error, maybe someone knows this and can tell me what the reason is?

Traceback (most recent call last):
  File "/usr/local/lib/python3.8/dist-packages/discord/ui/view.py", line 414, in _scheduled_task
    await item.callback(interaction)
  File "/home/Bot/Bot/cogs/spot.py", line 1537, in start_button
    await interaction.channel.send(view=GewaesserView(self.bot))
  File "/usr/local/lib/python3.8/dist-packages/discord/abc.py", line 1606, in send
    data = await state.http.send_message(
  File "/usr/local/lib/python3.8/dist-packages/discord/http.py", line 366, in request
    raise HTTPException(response, data)
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In components.0.components.0.options.12: The specified option value is already used
proud mason
#

can you show pip list

#

@green hinge

green hinge
#

I have not changed anything 🤔

proud mason
green hinge
#

I have also completely restarted the server and tried again

proud mason
#

can you uninstall and reinstall pycord. just to ensure no package goof ups

#

i havent seen that happen before lol

green hinge
#

Me neither 😄

I will reinstall pycord.

proud mason
#

can you also show the code for GewaesserView

#

i think you have a select menu with duplicate option

grizzled sentinel
#

You are not running them both with the same token at the same time are you?

umbral island
#

How can I properly move my bot to a different voice channel? I was following what seems to be an older tutorial that uses the method await self.vc.move_to() but this function does not seem to exist, or at least is not for pycord.

grizzled sentinel
errant craneBOT
#

Here's the basic voice example.

umbral island
proud mason
#

what even is self ? what class is this in?

limber urchin
#

How are you going to run a function on it if it's None?

umbral island
#

maybe i should have created a thread instead 💀

green hinge
grizzled sentinel
limber urchin
grizzled sentinel
umbral island
green hinge
# proud mason can you also show the code for `GewaesserView`

The funny thing is that it works on my PC locally and there are only problems on the server.

class GewaesserView(discord.ui.View):
    def __init__(self, bot: discord.Bot):
        self.bot = bot
        super().__init__(Gewaesser(self.bot))

class Gewaesser(discord.ui.Select):
    def __init__(self, bot: discord.Bot):
        self.bot = bot
        self.dictlist = []
        for item in self.dictlist:
            if 'messageid1' in item:
                self.attached_message = item['messageid1']
                break
        else:
            self.attached_message = None
        options = [discord.SelectOption(label=water) for water in bot.waters]
        super().__init__(
            placeholder="Wähle das Gewässer aus",
            min_values=1,
            max_values=1,
            options=options,
        )
        
    async def callback(self, interaction: discord.Interaction):
        user_id = interaction.user.id
        if self.attached_message:
            updated = False
            for item in self.dictlist:
                if 'gewaesser' in item:
                    item['gewaesser'] = self.values[0]
                    updated = True
                if 'buchstabefisch' in item:
                    del item['buchstabefisch']
                if 'fisch' in item:
                    del item['fisch']
            if not updated:
                for dict in self.dictlist:
                    if dict['user_id'] == interaction.user.id:
                        dict['gewaesser'] = self.values[0]
                        break
            await self.attached_message.edit(view=await BuchstabeFischView(self.bot, self.dictlist))
            await self.dictlist[1]['messageid2'].edit(view=await FischView(self.bot, self.dictlist))
            await interaction.response.defer()
        else:
            self.dictlist.append({'user_id': user_id, 
                             'gewaesser': self.values[0]})
            self.attached_message = await interaction.channel.send(view=await BuchstabeFischView(self.bot, self.dictlist))
            await interaction.response.defer()
            self.dictlist.append({'messageid1': self.attached_message})```
limber urchin
proud mason
green hinge
limber urchin
proud mason
#

dont name your variable dict

green hinge
limber urchin
#

What even is this piece of code???

#

it makes no sense

#

how is that even running

proud mason
green hinge
# proud mason can you show what bot.waters is? also print `options` before super.init and see ...

bot.waters:
['Achtuba', 'Alte Festung', 'Belaya', 'Bernstein See', 'Bärensee', 'Kuori', 'Ladoga Archipel', 'Ladogasee', 'Moskito See', 'Sewerskij Donez', 'Sura', 'The Cottage', 'Untere Tunguska', 'Windenbach', 'Wolchow', 'Yama River']
options:
[<SelectOption label='Achtuba' value='Achtuba' description=None emoji=None default=False>, <SelectOption label='Alte Festung' value='Alte Festung' description=None emoji=None default=False>, <SelectOption label='Belaya' value='Belaya' description=None emoji=None default=False>, <SelectOption label='Bernstein See' value='Bernstein See' description=None emoji=None default=False>, <SelectOption label='Bärensee' value='Bärensee' description=None emoji=None default=False>, <SelectOption label='Kuori' value='Kuori' description=None emoji=None default=False>, <SelectOption label='Ladoga Archipel' value='Ladoga Archipel' description=None emoji=None default=False>, <SelectOption label='Ladogasee' value='Ladogasee' description=None emoji=None default=False>, <SelectOption label='Moskito See' value='Moskito See' description=None emoji=None default=False>, <SelectOption label='Sewerskij Donez' value='Sewerskij Donez' description=None emoji=None default=False>, <SelectOption label='Sura' value='Sura' description=None emoji=None default=False>, <SelectOption label='The Cottage' value='The Cottage' description=None emoji=None default=False>, <SelectOption label='Untere Tunguska' value='Untere Tunguska' description=None emoji=None default=False>, <SelectOption label='Windenbach' value='Windenbach' description=None emoji=None default=False>, <SelectOption label='Wolchow' value='Wolchow' description=None emoji=None default=False>, <SelectOption label='Yama River' value='Yama River' description=None emoji=None default=False>]

mossy holly
#

Hey guys quick question: is there a way to reset a View when a button is clicked ? Thanks 😄

full basin
mossy holly
# full basin And what do you mean by reset view?

Sorry I wasn't clear just realised:
I have a few select, and one of them is disabled after the user made the choice (because next one depends on this first choice), I would like to provide a way to reset (i.e re-enable the first select) without having to retype the command

full basin
#

Create a new instance of the view, edit the message as response, pass such instance

mossy holly
#

The code in my button callback:

#
newView = TestView()
await interaction.response.edit_message(view=newView)
#

I've tried with enable_all_items() same error

gleaming falcon
#

Discord allegedly supports four images in an Embed if the URL is set.

I also do see that it appears to be based on separate embeds with the same destination URL. Does Pycord have any special way of handling this, or do I just create my own Embeds manually?

(Answer: Manually works fine)

sinful laurel
#

it's literally the rickroll url plus some jibberish

#

i know im very funny

#

it's so original

mossy holly
green hinge
# green hinge Maybe someone can help me further. When I run my code on my PC everything works ...

I have tested the whole thing several times now. With different bots, with the same bots, locally on my computer and on the server.
Locally on the computer everything works without problems. On the server not.
All my other bots also run without problems.
But the problem is also only with this one button. Other functions of the bot also work without problems. I really do not know what the whole thing should be 😬

waxen whale
harsh canyon
#
ctx.voice_client.play(discord.FFmpegPCMAudio(queue[0]), **ffmpeg_options, after=self.qhandler(self, ctx))
``` this code calls qhandler about 5 seconds after the media starts not when it ends
abstract otter
#
server = await bot.fetch_guild(server_id)
streamer_member = await server.fetch_member(streamer_member_id)

streamer_member.voice

streamer_member.voice is always None, despite the user being in a voice channel.

Thanks in advanced!

abstract otter
proud mason
green hinge
proud mason
mossy holly
tired goblet
#

How can I make a discord.Option mandatory at the time of submitting a slash command?

#

I already have required=True but it still lets the user submit without filling in all the values

proud mason
tired goblet
young bone
#

remove the =

proud mason
#

it should be :

limber urchin
#

You're supposed to type hint, not set the value

tired goblet
#

Oh should I use a colon

#

Oh okay

proud mason
#

yea

tired goblet
#

Worked, thanks all

green hinge
green hinge
young bone
green hinge
grizzled sentinel
# green hinge

Is this the pip list for the sever? If no can I see that.

green hinge
green hinge
rose turtle
#

How do I make a massban command?

young bone
rose turtle
young bone
limber urchin
#

You won't always find examples for everything. Sometimes you need to write your own code

rose turtle
grizzled sentinel
#

If you share that here we can help you find the bug

#

That is much better for helping you learn rather than us just giving you the code

limber urchin
solid agate
#

Anyone know if we can access the Sprout bool for Members? (if it even exists)

limber urchin
#

What is "the Sprout bool"?

solid agate
#

that thing

proud mason
#

Oh that's new member

solid agate
#

yeah, aka "sprout"

proud mason
#

I believe it appears if the member has joined in the last 1 week

limber urchin
#

You can just check the member's join date and compare to the current date

solid agate
#

I want to know if we can access that in code, or if we need to do some mental gymnastics with the joined_at parameter

#

the latter i see 😛

limber urchin
#

It's not really that complicated

#

Just one date - the other

proud mason
#

Mhm. It's a one liner

solid agate
#

everything with dates is complicated.

limber urchin
#

Not if you do it right

proud mason
#

Not if you always use timezone aware datetime

proud mason
solid agate
#

mental gymnastics it is! thanks for the answers 🙂

proud mason
grizzled sentinel
#

All time should be based on UTC no time zones just know that where you live day is not 6am to 6 pm but like 12am to 12pm or something