#General Help

1 messages Ā· Page 27 of 1

frigid lark
#

that is the wrong one

slender lintel
#

Run pip list

#

It will tell you

ashen kelp
slender lintel
#

Nevermind ima not use replit

frigid lark
#

oh

slender lintel
#

i cannot import commands.Bot

slender lintel
#

Use commands.Bot

slender lintel
slender lintel
slender lintel
frigid lark
slender lintel
slender lintel
frigid lark
#

do you have something else installed?

slender lintel
frigid lark
slender lintel
#

Make sure discord py isnt installed as said above, pycord wont work with it.

slender lintel
slender lintel
slender lintel
slender lintel
#

... clue in the name? 'improper token been passed,
If your using a env to store your token have it like this
bot.run(os.getenv("TOKEN"))
or without env
bot.run('TOKENGOESHERE')

slender lintel
#

What were you using before?

slender lintel
#

Btw, You should use an env for your token its much safer for, github and if your sharing your code in this case. saves you delting the token

hollow trail
#

I was seeing guide for prefix through command.ext but the example code never reacted on using prefix commands

slow dome
#

?Tag message-content

hearty rainBOT
#

As of Pycord Beta 5, Discord API v10 requires message content intent to receive message content. This affects the traditional commands. Not enabling this intent will result in the messages' content, embeds, and components being empty.

You will need to enable the intent on the developer portal, as well as in your code:

intents = discord.Intents.default()
intents.message_content = True
bot = discord.Bot(intents=intents)

Docs: https://docs.pycord.dev/en/master/api.html#discord.Intents.message_content

hollow trail
#

For your valuable time and information

slow dome
#

np, so it worked?

hollow trail
#

Let me check I've closed my laptop give me a second

hollow trail
slender lintel
#

Anyone able to help? I deleted my old repo and created a new one to try fix something (wasnt the issue anyways, lol) and i have this error after doing the instructions given after making the repo,

#

I deleted the old repo already so cant git pull

eager moss
#

The "on_message" event does not detect messages from bots

slow dome
eager moss
dreamy herald
#

hi, when connecting to a channel how can i check if the bot actually joined the channel and it didn't fail due to permissions?

slow dome
dreamy herald
#
        if not ctx.interaction.guild.voice_client:
            vc:wavelink.Player = await ctx.interaction.user.voice.channel.connect(cls = wavelink.Player, timeout = 10, reconnect = True)

            await ctx.interaction.guild.change_voice_state(channel = ctx.interaction.user.voice.channel, self_deaf = True)
#

i am trying to add a check here, any ideas on it?

slender lintel
slow dome
slow dome
dusky plinth
#

Hey, I want to make a /item use command for a bot with an inventory handler. I want the command to have an item option where the choices are only the items the user that started the command has in his inventory. Can somebody tell me how to do that ?

slow dome
supple ravineBOT
#

Here's the slash autocomplete example.

slender lintel
slow dome
slender lintel
#

o lol

dusky plinth
#

Yeah I already looked at that example, but I don't really understand how I can get the id of the invoker

slow dome
slender lintel
slender lintel
#

I meant autocomplete for python lol

eager moss
dusky plinth
#

Oh ok thx

slow dome
#

Is it just the bot itself or all bots?

dusky plinth
#

The ac limits the user to the option(s) we give him right ?

eager moss
slow dome
#

they can still type whatever they want and send it

#

but you can just check it

#

and throw an error back

dusky plinth
#

Yeah I was hoping not to do that but ok then

slow dome
slender lintel
slow dome
#

click fetch origin

#

and then click open visual studio code

#

and after you are done with vsc, go back to this page and click commit

#

after typing a summary

graceful robin
#

my bot responds twice to commands (slash commands are the only exception)

slender lintel
graceful robin
#

i dont

#

it happened before

slender lintel
slender lintel
slow dome
#

just drag everything over

slender lintel
#

alr. will i need to re install stuff

graceful robin
slow dome
#

regenerate token then do it @graceful robin

slender lintel
eager moss
slow dome
eager moss
slow dome
#

Interesting. I get the messages fine from other bots when I do it. Are you sure it's not a permissions thing

slow dome
steep verge
#

huh? I have children added py File "/home/container/main.py", line 117, in bug modal = BugReport() File "/home/container/main.py", line 100, in __init__ self.add_item(discord.ui.InputText(label="Bug Description", required=True, placeholder="Explain the bug you've found...")) File "/home/container/.local/lib/python3.9/site-packages/discord/ui/modal.py", line 135, in add_item if len(self._children) > 5: AttributeError: 'BugReport' object has no attribute '_children' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/home/container/.local/lib/python3.9/site-packages/discord/bot.py", line 993, in invoke_application_command await ctx.command.invoke(ctx) File "/home/container/.local/lib/python3.9/site-packages/discord/commands/core.py", line 357, in invoke await injected(ctx) File "/home/container/.local/lib/python3.9/site-packages/discord/commands/core.py", line 134, in wrapped raise ApplicationCommandInvokeError(exc) from exc discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: AttributeError: 'BugReport' object has no attribute '_children'

eager moss
graceful robin
slender lintel
slender lintel
graceful robin
#

the bot wouldnt start

slow dome
slow dome
slender lintel
#

alr

slender lintel
graceful robin
#

I dont think that thats the problem

slow dome
steep verge
slow dome
slow dome
#

although there are other people online

#

a lot of other people

slender lintel
#

I normaly help but im busy tryna sort this lol

#

if i see smth i can help with, i will

steep verge
#
class BugReport(discord.ui.Modal):
  def __init__(self):
    self.response = None
    self.add_item(discord.ui.InputText(label="Bug Description", required=True, placeholder="Explain the bug you've found..."))
    # other items
  async def callback(self, interaction: discord.Interaction):
    bug_description = self.children[0].value
    reproduction_steps = self.children[1].value
    expected_results = self.children[2].value
    actual_results = self.children[3].value
    self.response = {'bug_description': bug_description, 'reproduction_steps': reproduction_steps, 'expected_results': expected_results, 'actual_results': actual_results}
    self.stop()
    return```
#

and its saying there are no items/children

graceful robin
slow dome
#

and then send that

steep verge
#

on rc1

graceful robin
slow dome
#

and hide your token too

steep verge
graceful robin
slow dome
#

Actually you are missing super().__init__()

steep verge
#

oh right

#

oops

slender lintel
#

... some gone

#

F my main file gone

#

:((

slow dome
slender lintel
slow dome
#

you can rewrite it to be more efficient

slender lintel
#

Ok i agree ima make this bot so much better

#

im happy

ashen kelp
slow dome
balmy sparrow
#

Hello, does anyone know why when using

if codeRegex.search(ctx.content):

does not detect the message sent to bot

ashen kelp
#

slash commands doesnt work

#

normal commands either

wraith shell
#

just by isinstance(context, BridgeExtContext)?

slender lintel
#

Bruh, i am re writing my bot this ie the same as before and it works fine..??

import discord
from discord.ext.commands import slash_command
from discord.ext import commands
from discord.ext.commands import Cog``` why is discord.ext.commands could not be resolved
slender lintel
slender lintel
slender lintel
#

slash_command doesnt come from .ext.commands

#

it comes from discord.commands

#

Its worked fine in my other bot.? but ill fix that

slender lintel
#

maybe try and reinstall pycord

#

alr

slender lintel
#

ye

slender lintel
#

I had discord.ext first, tried it after

slow dome
slender lintel
#

alr

solar berry
#

is there a way to make the bot only do something on the first ready, bcz ive had instances of the bot randomly rebooting while running and that starts a 2nd loop on things like checking time for reminders

wraith shell
#
@client.event
async def on_ready():
    # here
slender lintel
#

Hey since I updated pycord to newest version my bot throws a error and does not start anymore. I already asked for help this afternoon and someone said that I should add self as parameter . I did this my bot started again but then when i used a command another error came.

Error before I added self:

    next(params)
StopIteration

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "c:\Users\kingl\Desktop\Programmierung\Discord Bots\Slash Commands\playground\main.py", line 2216, in <module>
    playground()
  File "c:\Users\kingl\Desktop\Programmierung\Discord Bots\Slash Commands\playground\main.py", line 418, in __init__
    async def help(ctx: discord.ApplicationContext):
  File "C:\Users\kingl\AppData\Local\Programs\Python\Python39-32\lib\site-packages\discord\bot.py", line 813, in decorator
    result = command(**kwargs)(func)
  File "C:\Users\kingl\AppData\Local\Programs\Python\Python39-32\lib\site-packages\discord\commands\core.py", line 1580, in decorator
    return cls(func, **attrs)
  File "C:\Users\kingl\AppData\Local\Programs\Python\Python39-32\lib\site-packages\discord\commands\core.py", line 644, in __init__
    self.options: List[Option] = self._parse_options(params)
  File "C:\Users\kingl\AppData\Local\Programs\Python\Python39-32\lib\site-packages\discord\commands\core.py", line 676, in _parse_options
    params = self._check_required_params(params)
  File "C:\Users\kingl\AppData\Local\Programs\Python\Python39-32\lib\site-packages\discord\commands\core.py", line 670, in _check_required_params
    raise ClientException(f'Callback for {self.name} command is missing "{p}" parameter.')
discord.errors.ClientException: Callback for help command is missing "context" parameter.
PS C:\Users\kingl\Desktop\Programmierung\Discord Bots\Slash Commands\playground> 
#

After I added self parameter:

Ignoring exception in on_application_command_error
Traceback (most recent call last):
  File "C:\Users\kingl\AppData\Local\Programs\Python\Python39-32\lib\site-packages\discord\commands\core.py", line 126, in wrapped
    ret = await coro(arg)
  File "C:\Users\kingl\AppData\Local\Programs\Python\Python39-32\lib\site-packages\discord\commands\core.py", line 856, in _invoke
    await self.callback(ctx, **kwargs)
TypeError: help() missing 1 required positional argument: 'ctx'

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

Traceback (most recent call last):
  File "C:\Users\kingl\AppData\Local\Programs\Python\Python39-32\lib\site-packages\discord\client.py", line 382, in _run_event
    await coro(*args, **kwargs)
  File "c:\Users\kingl\Desktop\Programmierung\Discord Bots\Slash Commands\playground\main.py", line 413, in on_application_command_error
    raise error
  File "C:\Users\kingl\AppData\Local\Programs\Python\Python39-32\lib\site-packages\discord\bot.py", line 993, in invoke_application_command
    await ctx.command.invoke(ctx)
  File "C:\Users\kingl\AppData\Local\Programs\Python\Python39-32\lib\site-packages\discord\commands\core.py", line 357, in invoke
    await injected(ctx)
  File "C:\Users\kingl\AppData\Local\Programs\Python\Python39-32\lib\site-packages\discord\commands\core.py", line 134, in wrapped
    raise ApplicationCommandInvokeError(exc) from exc
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: TypeError: help() missing 1 required positional argument: 'ctx'

wraith shell
#

can you send the help() command definition?

slender lintel
#
@bot.slash_command(name="help", description="Sends the help menu")
async def help(self, ctx: discord.ApplicationContext):
wraith shell
#

is this in a cog?

slender lintel
#

so my bot has a own class

wraith shell
#

does the class inherit from commands.Cog?

slender lintel
slow dome
#

then why are you using self

slender lintel
slender lintel
#

Why isnt

@slash_command(name='ban', description='Bans chosen member')
    async def ban(
    self,
    ctx: discord.ApplicationContext,
    user: discord.User,
    reason: discord.Option(str, "Enter the reason")):
     ban = discord.Embed(title=f'{user.name} was banned', description=f'{user.name} has been banned for {reason}', color=0x15B4E3)
     ban.timestamp = datetime.datetime.now()
     await user.ban()
     await ctx.defer(f'**{ctx.bot.mention} is thinking**')
     await ctx.respond(embed = ban)``` working, It returns user has no attrubite 'ban'
#

I had member.ban before but changed to user to try fix it

slender lintel
#

you type hinted it as discord.User

#

thats not the same as discord.Member

#

Yeah, discord.user is people in any server and discord.member has to be in the server

#

right

#

but whys it happening

#
@slash_command(name='ban', description='Bans chosen member')
    async def ban(
    self,
    ctx: discord.ApplicationContext,
    member: discord.Member,
    reason: discord.Option(str, "Enter the reason")):
     ban = discord.Embed(title=f'{member.name} was banned', description=f'{member.name} has been banned for {reason}', color=0x15B4E3)
     ban.timestamp = datetime.datetime.now()
     await member.ban()
     await ctx.defer(f'**{ctx.bot.mention} is thinking**')
     await ctx.respond(embed = ban)```
#

It dosent even respond

#

@slender lintel

slender lintel
#

b!rtfm pyc defer

slender lintel
#

hmm

#

not here

#

yeah, defo not right one xD

#

ty

slender lintel
slender lintel
#

you have to do

#

await ctx.defer()

#

no input

#

ah alr

#

so remove f'{ctx.bot.mention} is thinking'

#

I was trying to make it say the bot is thinking then respond with the embed

slender lintel
slender lintel
languid hollow
#

Is there a way to make sure when there's error for application commands, it focuses on the error that it's programmed to do. For example
this below v is for a command when activates a cooldown

async def on_application_command_error(ctx, error):
        if isinstance(error, commands.CommandOnCooldown):
            Flight_Embed = discord.Embed(
                title="Cooldown",
                color=discord.Color.red()
            )
            Flight_Embed.add_field(
                name="Command on cooldown",
                value=f"\n> {error}"
            )
            await ctx.send(f" {ctx.author.mention}",embed=Flight_Embed)

and there's another application command which only certain roles can use it and if it detects user that doesn't have a role it sends in this

    @bot.event
    async def on_application_command_error(ctx, error):
        if isinstance(error, commands.MissingRole):
            Embed = discord.Embed(
                title="Invalid User",
                color=discord.Color.brand_red()
            )
            Embed.add_field(
                name="User is not the chosen one",
                value=f"\n> User is not permitted to run this command"
            )
            await ctx.respond(embed=Embed) 

However for the cooldown error it sends the error message above ^ and I'm not sure how to separate it

slender lintel
#

because its just going to instantly send the message

slender lintel
#

or like 5

languid hollow
#
await asyncio.sleep(5)
#

make sure to import asyncio

slender lintel
#

So I'd put that right before my ctx respond

languid hollow
#

yeah

slender lintel
#

Alr thanks

sudden path
#

Why would you asyncio sleep?

languid hollow
#

That's what I found out online to use

sudden path
#

And what's the point of deferring and then instantly responding

slender lintel
#

thats what i said too lol

languid hollow
#

(oh mb you're talking to him)

sudden path
#

@slender lintel You do
await ctx.defer() at the start of your response, do your actions and then respond.

#

No idea why you're deferring such thing when it just sends an embed

languid hollow
#

anyone got an idea for above ^^?

slow dome
slender lintel
slow dome
#

and discord.User actually doesn't have anything to do with ban

#

I love it when my thoughts go faster than I can type

slender lintel
#

relatable

slow dome
#

like, maybe I should type it this way instead and it turns out I just mess up even more

slender lintel
slow dome
#

so why would you want to do that

slender lintel
slow dome
#

but why

#

what is the point of waiting

slender lintel
#

Making the bot slow on purpose is not a good idea

slender lintel
slender lintel
# slender lintel Rip alr

its not because it effects the bot or anything but as squid said it would waste the persons time if they used the command.

#

having it send immediately would be more beneficial and convient

#

Tru

slender lintel
sudden path
#

It's literally unnecessary coding

slender lintel
#

i read it then did something and came back and your words just reworded itself in my brain

slow dome
#

not that I disagree, but yeah

slender lintel
#

I wanted it like this

slow dome
#

why do you want it to think

sudden path
#

But that's actually because the bot needs to process a bunch of code

slow dome
#

oh I think you just want it to say something when it is processing it

#

but not actually increase run time

slender lintel
#

Yeah

#

Sorry I probably said it wrong

#

So howd I do that

slow dome
#
@slash_command(name='ban', description='Bans chosen member')
    async def ban(
    self,
    ctx: discord.ApplicationContext,
    member: discord.Member,
    reason: discord.Option(str, "Enter the reason")):
     await ctx.defer()
     ban = discord.Embed(title=f'{member.name} was banned', description=f'{member.name} has been banned for {reason}', color=0x15B4E3)
     ban.timestamp = datetime.datetime.now()
     await member.ban()
     await ctx.respond(embed = ban)
#

just put the defer at the beginning

slender lintel
#

Bur how would I choose what it says

#

@slow dome

slow dome
#

you can't

#

it is forced to bot is thinking

slender lintel
#

Oh, that's fine then

#

Ty

languid hollow
#

For the appliaction error event, is only one of the event required?

languid hollow
#

so I have one command that initiates the application error when on cooldown

#

and another if a user doesn't have the required role

#

lemme scroll up to find my message

sudden path
#

Check instances?

languid hollow
#

wait i forgot to update it

slow dome
#

yeah, you should only have one

#

if a specific command differs from the rest of the commands, you can handle that one with

@command_name.error
languid hollow
#

I have 2 commands that have different cooldown

#

that'd be very handy

languid hollow
slow dome
#

while @command_name.error only handles the same one

#

if you are going to have different error messages then @command_name.error

#

otherwise, it would be better for on_app_cmd_error

languid hollow
#

I used on_app_cmd_error but I needed different messages for those 2 cooldown commands

#

one is in 10 secs another in 30 mins and if I use maths to convert secs into mins

both of them can converted

slender lintel
#

hi guys

#

i am new to pycord

#

how to do a thing like this

#

it updates the discord user count and the online member count on the server banner

reef dove
#

does anyone have some SQL knowledge?

slender lintel
vivid nacelle
dreamy herald
#
        if not ctx.interaction.guild.voice_client:
            vc:wavelink.Player = await ctx.interaction.user.voice.channel.connect(cls = wavelink.Player, timeout = 10, reconnect = True)

            await ctx.interaction.guild.change_voice_state(channel = ctx.interaction.user.voice.channel, self_deaf = True)

So if the bot does not have enough perms , how can i add a check in this piece of code that the bot actually is joining the channel

#

and for some reasons, is_playing does not return None

#

rather, nothing is returned none

#

i am stuck here for 2 days, pls help me

#

basically, i just want to know which thing is returned as none if the bot can not join a vc due to permission error

vivid nacelle
#

maybe create a seperate help thread for that. could become complicated thinkCat

heavy flint
#

if i had a very long string s, how would i send it as a file

#

wait i think ik how to do it imma try it rq

#

nvmd my solution ended up very hacky of turning a stringio into a bytesio

slender lintel
#

hey

#

how can i ctx.respond a message

#

and then edit it

worthy basin
#

ctx.respond returns the message than you can edit it with message.edit()

heavy flint
slender lintel
#

i have message = ctx.respond()

#

and then message.edit

worthy basin
runic flare
#
          for color in ROLES.colors:
            for i in range(len(ROLES.colors[color])):
                print(int(list(ROLES.colors[color][i].keys())[0], 16))
                role = discord.utils.get(
                    ctx.guild.roles, name=ROLES.names[color], color=int(list(ROLES.colors[color][i].keys())[0], 16))
                print(role)
                if not role:
                    await ctx.guild.create_role(name=ROLES.names[color], color=int(list(ROLES.colors[color][i].keys())[0], 16))
                else:
                    pass
            for i, number in enumerate(ROLES.numbers):
                emote = discord.utils.get(
                    ctx.guild.emojis, name=ROLES.numbers_names[i])
                if not emote:
                    with open(number, errors="ignore") as f:
                        image = f.read()

                    await ctx.guild.create_custom_emoji(
                        name=ROLES.numbers_names[i], image=image)
                else:
                    pass

for reference

colors = {
        "white": [{"0xFFFFFF": "role"}, {"0xF5F5F5": "role"}, {"0xF0FFF0": "role"}, {"0xF0FFFF": "role"}, {"0xF8F8FF": "role"}, {"0xFFF5EE": "role"}, {"0xFFFAFA": "role"}],
        "black": [{"0x000000": "role"}, {"0x111111": "role"}, {"0x222222": "role"}, {"0x333333": "role"}, {"0x444444": "role"}, {"0x555555": "role"}, {"0x666666": "role"}, {"0x777777": "role"}, {"0x888888": "role"}],
        "red": [{"0xFF0000": "role"}, {"0xFFA500": "role"}, {"0xFF4500": "role"}, {"0xFF6347": "role"}, {"0xFF7F50": "role"}, {"0xFF8C00": "role"}, {"0xFFA07A": "role"}, {"0xFFB6C1": "role"}, {"0xFF0000": "role"}],
        "orange": [{"0xFFA500": "role"}, {"0xFF8C00": "role"}, {"0xFF7F50": "role"}, {"0xFF6347": "role"}, {"0xFF4500": "role"}, {"0xFFA07A": "role"}, {"0xFFB6C1": "role"}, {"0xFFA500": "role"}, {"0xFF8C00": "role"}],```
#

        "yellow": [{"0xFFFF00": "role"}, {"0xFFFF7F": "role"}, {"0xFFFF00": "role"}, {"0xFFFF7F": "role"}, {"0xFFFF00": "role"}, {"0xFFFF7F": "role"}, {"0xFFFF00": "role"}, {"0xFFFF7F": "role"}, {"0xFFFF00": "role"}],
        "green": [{"0x00FF00": "role"}, {"0x00FF7F": "role"}, {"0x00FF00": "role"}, {"0x00FF7F": "role"}, {"0x00FF00": "role"}, {"0x00FF7F": "role"}, {"0x00FF00": "role"}, {"0x00FF7F": "role"}, {"0x00FF00": "role"}],
        "blue": [{"0x0000FF": "role"}, {"0x0000FF": "role"}, {"0x0000FF": "role"}, {"0x0000FF": "role"}, {"0x0000FF": "role"}, {"0x0000FF": "role"}, {"0x0000FF": "role"}, {"0x0000FF": "role"}, {"0x0000FF": "role"}],
        "purple": [{"0x800080": "role"}, {"0x800080": "role"}, {"0x800080": "role"}, {"0x800080": "role"}, {"0x800080": "role"}, {"0x800080": "role"}, {"0x800080": "role"}, {"0x800080": "role"}, {"0x800080": "role"}],
    }

    names = {
        "white": "惁",
        "black": "惖",
        "red": "惬",
        "orange": "オ",
        "yellow": "悤",
        "green": "悰",
        "blue": "惖",
        "purple": "惗",
    }

    numbers_names = [
        "0",
        "1",
        "2",
        "3",
        "4",
        "5",
        "6",
        "7",
        "8",
    ]

    numbers = [
        "./core/assets/emoji/1.png",
        "./core/assets/emoji/2.png",
        "./core/assets/emoji/3.png",
        "./core/assets/emoji/4.png",
        "./core/assets/emoji/5.png",
        "./core/assets/emoji/6.png",
        "./core/assets/emoji/7.png",
        "./core/assets/emoji/8.png",
    ]
Traceback (most recent call last):
  File "D:\Documents\Coding\Discord\Eclipse\venv\lib\site-packages\discord\ext\commands\core.py", line 181, in wrapped
    ret = await coro(*args, **kwargs)
  File "D:\Documents\Coding\Discord\Eclipse\utils\cogs\colorRoles.py", line 24, in colorroles
    await self.init(ctx)
  File "D:\Documents\Coding\Discord\Eclipse\utils\cogs\colorRoles.py", line 60, in init```
#

    await ctx.guild.create_custom_emoji(
  File "D:\Documents\Coding\Discord\Eclipse\venv\lib\site-packages\discord\guild.py", line 2597, in create_custom_emoji
    img = utils._bytes_to_base64_data(image)
  File "D:\Documents\Coding\Discord\Eclipse\venv\lib\site-packages\discord\utils.py", line 523, in _bytes_to_base64_data
    mime = _get_mime_type_for_image(data)
  File "D:\Documents\Coding\Discord\Eclipse\venv\lib\site-packages\discord\utils.py", line 509, in _get_mime_type_for_image
    if data.startswith(b"\x89\x50\x4E\x47\x0D\x0A\x1A\x0A"):
TypeError: startswith first arg must be str or a tuple of str, not bytes

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

Traceback (most recent call last):
  File "D:\Documents\Coding\Discord\Eclipse\venv\lib\site-packages\discord\ext\commands\bot.py", line 344, in invoke
    await ctx.command.invoke(ctx)
  File "D:\Documents\Coding\Discord\Eclipse\venv\lib\site-packages\discord\ext\commands\core.py", line 927, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "D:\Documents\Coding\Discord\Eclipse\venv\lib\site-packages\discord\ext\commands\core.py", line 190, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: startswith first arg must be str or a tuple of str, not bytes
#

im assuming the error is because the image im passing into the create_custom_emoji function is a byte array and it's asking for a string though the documentation says it's supposed to take in bytes?

#

im a little confused

slender lintel
#

Does on_error get every discord.DiscordException error?

rigid lodge
#

Does anyone know why this doesn't work? The command only works when I have a small number as the timeout but not 3600 (An hour)

await bot.wait_for("message", timeout=3600)
...
errant verge
#

can i have a 2x2 of embed fields?

gilded widget
# errant verge can i have a 2x2 of embed fields?

this is about the best you can do as far as im concerned:

        embed = discord.Embed(
            fields=[
                discord.EmbedField(name="a", value="b", inline=True),
                discord.EmbedField(name="c", value="d", inline=True),
                discord.EmbedField(name="\u200b", value="\u200b", inline=False),  # \u200b should create an empty space character
                discord.EmbedField(name="e", value="f", inline=True),
                discord.EmbedField(name="g", value="h", inline=True),
            ]
        )
#

you can also just change it to be dashes or something kinda like a border

slender lintel
#

Wouldn't it be embed.addfield

gilded widget
#

you can do that too

#

but what i sent also works

slender lintel
#

Alr, so it won't make it break the way I said

gilded widget
#

nope

slender lintel
#

Alr

gilded widget
slender lintel
fair cradle
#

I have a question, is it posible, that custom emojis work in embeds responding to an interaction?

young parcel
#

I've noticed that jump_url has been added to User class recently, 6/25 to be specific.
is there a way to use the jump_url in the newest version, i.e. 2.0.0rc1?

young parcel
#

I've tried and got error saying that the attribute dose not exist.

#

yes

#

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

#

and this is the error msg i got

frigid elm
#
        em = discord.Embed(color=discord.Color.from_rgb(13, 99, 143),title="Boosters")
        em.add_field(name=f"A list of every person that has boosted **{ctx.guild}**",value=f"{booster.mention}")for booster in ctx.guild.premium_subscribers:
        em = discord.Embed(color=discord.Color.from_rgb(13, 99, 143),title="Boosters")
        em.add_field(name=f"A list of every person that has boosted **{ctx.guild}**",value=f"{booster.mention}")``` how do i make it so that the boosters are sorted with numbers
slender lintel
slender lintel
#
x = 1
for booster in ctx.guild.premium_subscribers:
        em = discord.Embed(color=discord.Color.from_rgb(13, 99, 143),title="Boosters")
        em.add_field(name=f"A list of every person that has boosted **{ctx.guild}**",value=f"{x}: {booster.mention}")
        x += 1
frigid elm
#

ty

crimson gale
frigid elm
slender lintel
frigid elm
#

oh alright

frigid elm
#

NotFound: 404 Not Found (error code: 10062): Unknown interaction

#

the command works but its not able to respond to the "Message"

frigid elm
#

i deleted it cuz i fixed it mb

slender lintel
#
@commands.command(name="purge")
    async def purge(self, ctx, limit=5):
        await ctx.channel.purge(limit=limit)

error:

raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'PartialMessageable' object has no attribute 'purge'

intents

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

(in cogs)
v2.0.0b7

frigid elm
#

i cant use normal commands,only slash commands work idk why

slow dome
#

?tag message-content

hearty rainBOT
#

As of Pycord Beta 5, Discord API v10 requires message content intent to receive message content. This affects the traditional commands. Not enabling this intent will result in the messages' content, embeds, and components being empty.

You will need to enable the intent on the developer portal, as well as in your code:

intents = discord.Intents.default()
intents.message_content = True
bot = discord.Bot(intents=intents)

Docs: https://docs.pycord.dev/en/master/api.html#discord.Intents.message_content

frigid elm
#

i have this on

#

intents=discord.Intents().all()

slow dome
#

it has an await bot.process_command(message) right?

frigid elm
#

wym

#

no

#

im sorry im jst new to pycord

slow dome
#

what is your current code

frigid elm
#

its 500 lines but slash commands work, the one with the normal command is this: @bot.command()
async def test(ctx):
print("yh")

#

ik it doesnt need ctx but i jst changed it to printt sumthing to look if it wld work

#

but nope

stable torrent
frigid elm
#

discord.Bot

stable torrent
#

it doesn't support old styled commands

frigid elm
#

oh

stable torrent
#

bot.command in this case will make slash command

frigid elm
#

oh ty

stable torrent
#

try changing to ext.commands.Bot and using bot.command for default commands and bot.slash_command for slash

slow dome
#

commands.Bot will create prefixed commands

frigid elm
#

so i just replace discord.Bot with discord.ext.commands.Bot with

slow dome
frigid elm
#

same

stable torrent
#

you can use bridge commands for that

slow dome
#

then, using discord.ext.Bridge.bot would be better

frigid elm
#

alrightt i was finna copy paste all the commandds ty

slow dome
#

Bridge creates slash and prefixed with a single function

stable torrent
#

but there is some breaking changes in behaviour (at least when i used it there was)

#

so check the docs

slow dome
#

and the guide

frigid elm
#

module 'discord.ext' has no attribute 'bridge'

stable torrent
frigid elm
#

imma see

stable torrent
#

you should update probably

frigid elm
#

yup works now tysm

stable torrent
#

šŸ‘šŸ»

languid hollow
#

I'm not sure if you're able to delete Link Buttons

#

but this is my code, and it doesn't work, is it possible to remove link buttons?

languid hollow
daring flint
#

Sanity check - can Role Images be displayed for inline use, maybe using emoji tags or something similar?

slow dome
daring flint
#

I see the icon asset, but wasn't sure if that could be printed alongside the role, since I would've assumed an asset would act as an attached file

#

Will play around with it, just wanted to see if it was worth spending the time. Thanks

slow dome
#

where it is a string

daring flint
#

Yeah but if you use a registered but custom emoji, it's then not unicode

languid hollow
#

it's in the class

daring flint
#

yepyep.

slow dome
languid hollow
#
class Flight_Button(View):
    def __init__(self,bot):
        super().__init__(timeout=None)
        self.bot = bot

        Private_Button = Button(
          label= "Private Server",
          style= discord.ButtonStyle.url,
          emoji=":link:",
          url= "ee"
        )
        
        self.add_item(Private_Button)

    @discord.ui.button(
        label="Flight Reviews",
        style=discord.ButtonStyle.green,
        emoji=":star:"
    )

    async def callback(self,button,interaction):
        Server = self.bot.get_guild(ee)
        User_ID = interaction.user
        Role_Review = Server.get_role(ee) # Needs to change this to Flight Reviewer

        await interaction.response.send_message(f"You have been given the {Role_Review.mention}",ephemeral=True)
        await User_ID.add_roles(Role_Review)

    @discord.ui.button(
      label="Flight Departed",
      style=discord.ButtonStyle.green
    )

    async def green_button_callback(self,button,interaction):
        if interaction.user.id == 481099018676600853:
          Private_Button = Button(
            label= "Private Server",
            style= discord.ButtonStyle.url,
            emoji=":link:",
            url= "EEE"
          )

          self.remove_item(Private_Button)

          for child in self.children:
            if child.label == "Flight Departed":
              child.style=discord.ButtonStyle.red
              child.disabled = True
            
            
            
          await interaction.response.edit_message(view=self)
        else: await interaction.response.send_message("Egg",view=self,ephemeral=True)
#

the whole code

slow dome
languid hollow
languid hollow
slender lintel
#

Hello, is it possible to save channels in html?

#

Like a transcript

slow dome
slender lintel
slow dome
#

with await channel.history(limit=xxx)

#

b!rtfm channel.history

open bearBOT
# slow dome b!rtfm channel.history

I couldn't find a documentation with the name channel.history! Maybe you used to command wrong? Correct Usage: <prefix>rtfm <docs> [<term>] (eg. b!rtfm py cool)
List of Documentations you can search:
python
pycord
discord.py
yarsaw
nextcord
disnake

slow dome
#

b!rtfm pyc channel.history

quartz snow
#
he conflict is caused by:
           The user requested py-cord==2.0.0rc1
           py-cord[speed] 1.7.3 depends on py-cord 1.7.3 (from https://files.pythonhosted.org/packages/04/16/808ad971642cdd66e719edb6107a0e065608dd383f05a9389a34dddf7bb4/py_cord-1.7.3-py3-none-any.whl#sha256=19cb49ee6cb830d71e8b5d9555249cef5c15c652c096176e69edce5ff993701b (from https://pypi.org/simple/py-cord/) (requires-python:>=3.5.3))
       
       To fix this you could try to:
       1. loosen the range of package versions you've specified
       2. remove package versions to allow pip attempt to solve the dependency conflict
       
       ERROR: ResolutionImpossible: for help visit https://pip.pypa.io/en/latest/topics/dependency-resolution/#dealing-with-dependency-conflicts
 !     Push rejected, failed to compile Python app.
 !     Push failed

is there pycord[speed] on 2.0.0rc1?

quartz snow
slow dome
#

py-cord[speed] == 2.0.0rc1

steep verge
#

!tag install

robust nebulaBOT
#

Install pycord:

pip uninstall discord.py
pip install py-cord

Install pycord beta:

pip uninstall discord.py
pip install py-cord==2.0.0b7

Install pycord alpha from git:

pip uninstall discord.py
pip install git+https://github.com/Pycord-Development/pycord
limpid breach
#
import discord
from discord.ext import commands

bot = commands.Bot(commands_prefix="f!")

@bot.event
async def on_ready():
    print(f"{bot.user} is ready!")

@bot.command()
async def hello(ctx):
    print("hi")
    await ctx.reply("Hello World!")

bot.run("")
#

I run this code and gives me the confirmation that its running

#

but the command doesn't give me an output

#

I've checked permissions and the bot has admin

slow dome
hearty rainBOT
#

As of Pycord Beta 5, Discord API v10 requires message content intent to receive message content. This affects the traditional commands. Not enabling this intent will result in the messages' content, embeds, and components being empty.

You will need to enable the intent on the developer portal, as well as in your code:

intents = discord.Intents.default()
intents.message_content = True
bot = discord.Bot(intents=intents)

Docs: https://docs.pycord.dev/en/master/api.html#discord.Intents.message_content

slender lintel
slow dome
lament nimbus
#

in what version is timeout inplimented?

slow dome
lament nimbus
#

users

#

because im getting a
Command raised an exception: AttributeError: 'Member' object has no attribute 'timeout_for'
error

slow dome
slender lintel
lament nimbus
slow dome
slow dome
lament nimbus
#

it has that

#

im assuming its because of the code i use for diffrent guilds have diffrent prefixes

limpid breach
lament nimbus
#

how do i check version again?

slow dome
slow dome
limpid breach
slow dome
#

traceback

lament nimbus
#

oh i have py-cord 1.7.3

slow dome
lament nimbus
#

oh

#

how do i get the b5 version?

limpid breach
#
  File "c:\Users\tanay\Documents\All_Python_Projects\Food Bot\test.py", line 13, in <module>
    bot.run("")
  File "C:\Users\tanay\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\client.py", line 715, in run
    return future.result()
  File "C:\Users\tanay\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\client.py", line 694, in runner
    await self.start(*args, **kwargs)
  File "C:\Users\tanay\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\client.py", line 658, in start
    await self.connect(reconnect=reconnect)
  File "C:\Users\tanay\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\client.py", line 599, in connect
    raise PrivilegedIntentsRequired(exc.shard_id) from None
discord.errors.PrivilegedIntentsRequired: Shard ID None is requesting privileged intents that have not been explicitly enabled in the developer portal. It is recommended to go to https://discord.com/developers/applications/ and explicitly enable the privileged intents within your application's page. If this is not possible, then consider disabling the privileged intents instead.
Exception ignored in: <function _ProactorBasePipeTransport.__del__ at 0x0000022E27E36320>
Traceback (most recent call last):
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.1520.0_x64__qbz5n2kfra8p0\lib\asyncio\proactor_events.py", line 116, in __del__
    self.close()
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.1520.0_x64__qbz5n2kfra8p0\lib\asyncio\proactor_events.py", line 108, in close
    self._loop.call_soon(self._call_connection_lost, None)
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.1520.0_x64__qbz5n2kfra8p0\lib\asyncio\base_events.py", line 750, in call_soon
    self._check_closed()
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.1520.0_x64__qbz5n2kfra8p0\lib\asyncio\base_events.py", line 515, in _check_closed
    raise RuntimeError('Event loop is closed')
RuntimeError: Event loop is closed
Exception ignored in: <function _ProactorBasePipeTransport.__del__ at 0x0000022E27E36320>
Traceback (most recent call last):
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.1520.0_x64__qbz5n2kfra8p0\lib\asyncio\proactor_events.py", line 116, in __del__
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.1520.0_x64__qbz5n2kfra8p0\lib\asyncio\proactor_events.py", line 108, in close
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.1520.0_x64__qbz5n2kfra8p0\lib\asyncio\base_events.py", line 750, in call_soon
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.1520.0_x64__qbz5n2kfra8p0\lib\asyncio\base_events.py", line 515, in _check_closed
RuntimeError: Event loop is closed```
lament nimbus
lament nimbus
queen nacelle
#

anyone know how to make a button for each result in a database?

limpid breach
#

I've enabled it here

#

If this isn't the right place, Idk where

slow dome
worthy basin
#

Do you want specifically beta 5 or the latest beta?

slow dome
limpid breach
#
intents = discord.Intents()
intents.message_content = True```
slow dome
limpid breach
#

Ohhhh ty

slender lintel
#

Hey, I have tried making a reason option unrequired because its a ban command, but it just adds an arg

import discord
from discord.commands import slash_command
from discord.ext import commands
import datetime
from discord.commands import Option
class Ban(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

    @slash_command(name='ban', description='Bans chosen member')
    async def ban(
    self,
    ctx: discord.ApplicationContext,
    member: discord.Member,
    reason: Option(str, "Enter the reason"), required=False):
     await ctx.defer()
     ban = discord.Embed(title=f'{member.name} was banned', description=f'{member.name} has been banned for {reason}', color=0x15B4E3)
     ban.timestamp = datetime.datetime.now()
     await member.ban()
     
     await ctx.respond(embed = ban)
       

def setup(bot):
    bot.add_cog(Ban(bot))```
#

How can i get text from embed fields?

limpid breach
#

How do you get a bot to join the same vc as the user?

slender lintel
#

put it inside Option()

#

Oh yeah, thanks.

#

Btw if you dont mind me asking, How would i also have a tempban command? So i can use member.ban fine but howd i have it use a time?

#

wdym?

#

like ban someone then unban them later?

#

Yeah basicly

#

after a certian amount of time

#

One way is using asyncio.sleep()

#

but that way is bad

#

so you should store the time the person should be unbanned in a database

#

then unban when it is time

#

I know how i can store my data, but im not sure how id specify any time?

slender lintel
slender lintel
#

then store that time in the database

slender lintel
slender lintel
slender lintel
#

My description for the embed uses {reason}, Could that be why

#

I don't think that should be a problem

slender lintel
#
    @slash_command(name='ban', description='Bans chosen member')
    async def ban(
        self, ctx: discord.ApplicationContext,
        member: discord.Member,
        reason: Option(
              str, "Enter the reason",  
              required=False
        ) = "No reason provided."
    ):
        await ctx.defer()
     
        ban = discord.Embed(
           title=f'{member.name} was banned',           
           description=f'{member.name} has been banned for {reason}', 
           color=0x15B4E3
        )
        ban.timestamp = datetime.datetime.now()

        await member.ban()
        await ctx.respond(embed = ban)
#

try this real quick

#

I gave reason a default value

slender lintel
#

Yeah, Ic now

slender lintel
# slender lintel Since you wouldnt have a value when you dont give it one, reason will be None
   @slash_command(name='unban', description='Unbans chosen member')
    async def ban(
    self,
    ctx: discord.ApplicationContext,
    user: discord.User,
    reason: Option(
              str, "Enter the reason",  
              required=False
) = "No Reason Given."):
     await ctx.defer()
     unban = discord.Embed(title=f'{user.name} was unbanned', description=f'{user.name} has been unbanned for {reason}', color=0x15B4E3)
     ban.timestamp = datetime.datetime.now()
     await user.unban()
     
     await ctx.respond(embed = unban)``` If i use this for my unban command, Does it allow User ID (as you obviously cant mention them)
slender lintel
# slender lintel probably

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

Nope, What can i use instead of user.unban?

slender lintel
#

ill try that

frigid lark
#

ctx.guild.unban(user, reason)

slender lintel
slender lintel
#

Whats causing it then?

#

ctx.guild.unban(user, reason=reason)

#

ah alr

slender lintel
slender lintel
#

bruh they are..? Its my alt

#

hmm

#

correct id?

#

Yes, Ill double check tho

#

Weird

#

b!rtfm pyc unban

slender lintel
#

hm

#

Works now? Must have been wrong ID

#

ĀÆ_(惄)_/ĀÆ

#

lol

limpid breach
#

how do you get the voice channel a user is connected to

lament nimbus
slender lintel
#
 await ctx.respond(f'Rickrolled {member.name}', ephemeral=True)``` Bruv why isnt it ephemeral
frigid elm
#
    for result in results:
        collectionafk.delete_one(result)
        await message.channel.send(f"You have been removed from AFK {message.author.mention}")
    if message.mentions:
     results = collection.find({"member": message.author.id}) 
     for result in results:
        collection.delete_one(result)
        if message.content == result:
            await message.channel.send(f"This person is currently AFK" ``` how do i check if the mentione user is inside the collection? the code above spams messages
past gate
#

no wonder it spams messages its in a for loop lol

slender lintel
frigid elm
#
    for mention in message.mentions:
        if mention.id in results:
            await message.channel.send("he afk")
    if message.author.id in results:
        await collectionafk.delete_one(results)
```thought this might work to remove tthe afk
slender lintel
#

yea

#

well

#

the defer needs to be ephemeral

#

alr

#
await ctx.defer(ephemeral=True)```
#

ty

ebon spruce
#

your missing await

#

if i'm not wrong

slender lintel
#

is there a way to ban someone from a certain server with guild ids

slow dome
slender lintel
#

how do i fetch the guild i did everything but i didn’t know that part

slow dome
#

b!rtfm pyc bot.fetch_guild

slender lintel
#

bet thanks

slow dome
#

gl

glass nova
#

i didnt know that

slender lintel
#

Yiu can't

#

I thought you could

slow dome
crimson gale
#

fyi proper usage of defer is to use it at the very first line of the command

slender lintel
#

Yeah

#

It's sorted now

#

Thanks btw

deep grail
#

Is it possible to have cogs auto reload when edits are made?

frigid lark
#

I already try to find

deep grail
#

wdym

#

@frigid lark

frigid lark
deep grail
#

No, I don't

frigid lark
#

you can run the bot with "nodemon" and the bot will autorestart after editing

deep grail
#

Oh

frigid lark
thorny void
#

Possibly dumb question but can you add bridge commands to subcommand groups?
Easy workaround if not but it'd make it neat

burnt quiver
#

is it possible to receive voice audio as a stream with pycord? i know you can use start_recording() + stop_recording(), but this doesn't provide an audio stream to use

rigid wave
#

How do I make the buttons work even after restarting the bot?

supple ravineBOT
#

Here's the persistent example.

sudden path
#

@rigid wave

rigid wave
sudden path
#

The same way?

dreamy herald
#

how to get a role from its initial 2 or 3 letters?

#

like we get in dyno or probot where ?role <user> mod and it will add moderator role

worthy basin
#

Try typing the argument to discord.Role this might convert it to the closest name.

solar berry
#

Is there a way to set a home guild for a bot
So that guild is always cached on start

solar berry
#

can you fetch it before the on_ready() call?

slow dome
solar berry
#

maybe yeah

#

I jus thought since chunking exists, if you could only chunk one guild lol

#

also, does fetching the guild cache all the channels too

solar berry
#

what's the difference between self.bot.fetch_channel() and Guild.fetch_channel()
how does the self.bot know what guild to fetch from

frigid elm
frigid elm
#

how do i get the id of a mentioned user?

sudden path
#

Depends on the context

still ingot
#

Hello so i wanna add new button so like a row.

#

in here in the view do i just put a ","

#

so like view=view1, view2

#

like that?

slender lintel
#

How can i make select menu work 1 time?

sudden path
still ingot
#

so how do i get multiple buttons

sudden path
#

You add them to a view

still ingot
#
    buttonfish.callback = button_callback
    view1 = View()
    view1.add_item(buttonfish, buttonhunt, buttonfarm)```so in here like this??
#

like that i just add ","?

#

@sudden path

sudden path
#

Read the docs.

#

b!rtfm pyc view.add_item

open bearBOT
still ingot
#

kk

sudden path
wide cloak
#

Is pycord filtering xss injections?

vivid nacelle
#

discord should filter that lol

wide cloak
vivid nacelle
wide cloak
#

That was the thing i wanted to know

vivid nacelle
#

ok perfect šŸ˜…

civic hawk
#

does anyone have a solution to accessing the cog inside an autocomplete option

spring wharf
#

Is there anyway I can use "bot" inside of a discord.ui.button?

civic hawk
spring wharf
#

Could you link me the callback please

#

Sorry I am just new to this library that's all

civic hawk
#

its in one of the examples on the github, lemme check

slender lintel
#

hwy

#

hey

#

after using await interaction.response.edit_message

#

how can i edit the message after that

civic hawk
#

inside the confirm view class theres 2 buttons with the callback function which set self.value to a value for the ask function to look at

spring wharf
#

thanks

#

I just want to be able to request info from a DB inside of the button

#

When someone presses it

slender lintel
civic hawk
#

just pass bot through in the arguments of the view and set it as self.db or something so it can be accessed in the buttons own function

#

noteason i think when you do send_message or whichever function you used to send the message it returns the message object so you could just keep that message object to run message.edit

slender lintel
spring wharf
#

Hmm alright ill try it rq

civic hawk
#

oh are you trying to edit the view?

slender lintel
#

basically

#

i will run a slash command, then it will show an embed with a dropdown view, after i click something on the dropdown view it edits the message once with interaction.response.edit_message, but then im wondering how to edit the message after that

wide cloak
#

So i dont have to filter any message from a user

spring wharf
#

discord.errors.ExtensionFailed: Extension 'cogs.suggest' raised an error: TypeError: metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases

#

I defined bot in my class

#
class SuggestionButtons(discord.ui.View, bot):```
#

and imported bot from main import bot

spring wharf
slender lintel
#

Would it be smart to use nodemon to reload cogs? Its slash commands though...

spring wharf
#
            self.bot.unload_extension(f'cogs.{extension}')
            self.bot.load_extension(f'cogs.{extension}')```
#

I just do that

#

Works fine for me

slender lintel
spring wharf
#

Oh slash commands...

#

Mb didn't read that bit

pure lake
#

can you guys recommend a good async sql libary to use with python pls

spring wharf
#

aiomysql

spring wharf
#

Is it possible for me to use the variable "bot" defined in main.py in my discord.ui.View?

crimson gale
#

pass the bot instance when instantiating an instance of your class

pure lake
spring wharf
#

I've got that ATM

crimson gale
#

you need to make an __init__ method

spring wharf
#
class SuggestionButtons(discord.ui.View, bot):
    def __init__(self, bot):```
#

?

crimson gale
#

yes but remove the bot from the class args

vivid nacelle
crimson gale
#

its not valid

spring wharf
#

what now?

crimson gale
#

now you set any attribute of the instance (bot is most common) to the passed object

spring wharf
#
class SuggestionButtons(discord.ui.View, bot):
    def __init__(self):
        super().__init__(timeout=None)

    @discord.ui.button(label="Upvote", emoji="⬆", style=discord.ButtonStyle.green, custom_id="persistent_view:upvote")
    async def upvote(self, button: discord.ui.Button, interaction: discord.Interaction):
        msg = await self.bot.db.select("suggestions", ["*"], checks=[["status", 0]], single=True)```
#

This is what I have I have bot.db defined in main.py

crimson gale
#

def __init__(self, bot):

#

and then you set the attribute

spring wharf
#

oh

#

self.bot = bot

#

?

crimson gale
#

yep

spring wharf
#

oh

crimson gale
#

and remove bot from the parenthesis for the class

spring wharf
#

Yeah i did

#

Now it's not working

#

No error or anything

#

It's not sending the original embed with the buttons

crimson gale
#

show related code?

spring wharf
#
class Suggest(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

    @commands.command()
    @commands.cooldown(1, 30, commands.BucketType.user)
    async def suggest(self, ctx, *, suggestion):
        embed = discord.Embed(title=f"Exod | Suggestions",
                              description=f"""
                              ā— **Suggestion**
                               `{suggestion}`
                              
                              ā— **Information**
                               `-` **From:** {ctx.author.mention}
                               `-` **Status:** :orange_circle:
                               `-` **Upvotes:** 0
                               `-` **Downvotes:** 0
                              """, colour=col)
        embed.set_image(
            url="dsds")
        channel = self.bot.get_channel(970645293886500914)
        msg = await channel.send(embed=embed, view=SuggestionButtons())
        await self.bot.db.insert("suggestions",
                                 [["message_id", msg.id], ["user_id", ctx.author.id], ["suggestion", suggestion]])```
crimson gale
#

oh btw if youre gonna have multiple instances of that view, youre gonna run into trouble with custom id conflicts

spring wharf
#

Yeah i was gonna remove the custom_id anyway

crimson gale
#

nothing seems to be wrong

spring wharf
#

Is it because it's in the same file as the COG?

#

like

#

I have 2 classes in the cog

#

commands.Cog

crimson gale
#

it shouldnt matter

spring wharf
#

That's what I thought

#

Can I DM you?

#

the whole thing

crimson gale
#

oh i can see that youre not passing the bot when youre instantiating the view object

spring wharf
#

wdym

crimson gale
#

3rd to last line

spring wharf
#

oh

#

view=SuggestionButtons(bot)

#

?

crimson gale
#

self.bot since its in a cog

spring wharf
#

Ok lemme try that rq

#

That worked

#

thanks

rigid wave
#

How do I remove/add a specific button using custom_id?

spring wharf
#

Can I edit a already sent message via ID?

slender lintel
#

yes

spring wharf
#

im using msg.edit

#

msg is the ID

#

Is there a different way?

slender lintel
#

m.edit should work

spring wharf
#

AttributeError: 'int' object has no attribute 'edit'

#

Is it because I've set msg to the ID?

#

Nevermind dw

spring wharf
#

Traceback (most recent call last):
File "/home/container/.local/lib/python3.8/site-packages/discord/ui/view.py", line 371, in _scheduled_task
await item.callback(interaction)
TypeError: upvote() missing 1 required positional argument: 'interaction'

#

Not seen this error yet...

spring wharf
#

    @discord.ui.button(label="Upvote", emoji="⬆", style=discord.ButtonStyle.green)
    async def upvote(self, ctx, button: discord.ui.Button, interaction: discord.Interaction):
 
#Embed stuff here


        m = ctx.fetch_message(msg[0])
        m.edit(embed=embed)
        await interaction.response.send_message("Upvote", ephemeral=True)```
slender lintel
#

hmm

terse plinth
#

have local error handlers for bridge commands been added?

slender lintel
#

#992444675816439838

#

(Bump)

spring wharf
#

Traceback (most recent call last):
File "/home/container/.local/lib/python3.8/site-packages/discord/ui/view.py", line 371, in _scheduled_task
await item.callback(interaction)
TypeError: upvote() missing 1 required positional argument: 'interaction'

#

Does anyone know how to fix this error?

slender lintel
#

šŸ’€

slow dome
terse plinth
#

which version is it on?

slow dome
#

master branch

terse plinth
#

so i dont have to update my pycord library? that doesnt seem right

slow dome
terse plinth
#

in other words, do i have to pip install anything to access this feature?

terse plinth
slow dome
#

?tag install

hearty rainBOT
#
  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

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

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

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

Updating to release candidate:
pip install py-cord==2.0.0rc1

slow dome
#

the alpha one

terse plinth
#

thanks

vagrant mortar
#

Anyone know wtf this suddenly is?

#

I don't even need or use the voiceclient stuff

#

it happens on literal bot startup.

slender lintel
#

Have you installed pycord?

vagrant mortar
#

Ofcourse...

#

Between yesterday and today, nothing changed in my dev environment

past gate
#

can you send your pip list output?

vagrant mortar
slender lintel
#

anybody know how to make pagination make a new page if the page before fields get full?

craggy rapids
#

does we have a input view for text ?

#

on alpha

icy sluice
#

many people can’t find the error to this code, does anyone know?

Code:

@bot.event
async def on_guild_join(guild):
    server = await bot.fetch_guild(guild.id)
    print(server.channels)
    hi = await server.channels[0].create_invite()
    channel = bot.get_channel(988031087424983090)
    stuff = guild.owner
    jem = discord.Embed(color=0x2f3136)
    jem.set_author(f"{bot.user} has joined a new server:",icon_url=bot.avatar.url)
    jem.set_description(f"Server owner ID: {guild.owner_id}\
                        Server owner tag: {stuff.tag}\
                        Server name: {guild.name}\
                        Server ID: {guild.id}\
                        Server member count: {guild.member_count}\
                        Server invite: {hi}")
    await channel.send(embed=jem)

Error (full trace back):

Ignoring exception in on_guild_join
Traceback (most recent call last):
  File "/home/container/.local/lib/python3.9/site-packages/discord/client.py", line 382, in _run_event
    await coro(*args, **kwargs)
  File "/home/container/main.py", line 37, in on_guild_join
    hi = await server.channels[0].create_invite()
IndexError: list index out of range
#

^ I have all intents enabled

past gate
#

what if the server has no channels

icy sluice
#

it does though

#

that’s what I’m confused about

icy sluice
past gate
#

šŸ¤”

toxic tiger
#

Is it possible to get the message to which a thread is "attached" to without parsing it from the jump_url?

crimson gale
#

access attribute thread

#

actually no

#

access attribute channel and check if its a Thread

toxic tiger
#

?

crimson gale
#

isinstance(msg.channel, discord.Thread)

toxic tiger
#

I know that it is a thread. I want to know the "normal" message to which the thread is attached

crimson gale
#

as in that the first message derives from a message that was sent to a text channel?

gilded widget
toxic tiger
#

example:
on_thread_update I get the thread and I want to know to which text channel message the thread belongs

gilded widget
#

should be what you're looking for if I'm understanding your question

crimson gale
#

Thread has the starting_message attribute that has a Message present if the first message was sent to a text channel from which the thread was created from

#

i reckon you could access the channel attribute of that

toxic tiger
#

just that it can be None if not in the cache, which happens quiet often in bigger bots blobsad

gilded widget
#

since the ID of the message is the same as the thread ID you can probably try and fetch the message if Thread.starting_message returns None

crimson gale
#

The ID for this message is the same as the thread ID.

#

you could use this to your knowledge

toxic tiger
#

omg you are right! Didn't recognise that šŸ˜…

#

thanks guys :D

#

that even saves me a database field :P

gilded widget
#

nice

lament nimbus
#

How do i attach a img to a embed?

#

like this?

slow dome
#

b!rtfm pyc embed.set_image

open bearBOT
lament nimbus
#

i think ive done that

#

ive got

embed.set_image(url=attachedurl)
slow dome
#

Not a valid image link, it seems like

lament nimbus
#

oh tf

#

odd

#

oh now it worked

halcyon cairn
lament nimbus
#

i had to post the img again

slow dome
halcyon cairn
#

interesting. I'd personally do a console output as to what the list is, so you can see what data it's trying to work with.

icy sluice
#

under where I store server as a variable, I do have print(server.channels), lol

slow dome
#

I think it's a caching issue.

icy sluice
#

any way I could resolve that?

slender lintel
#

after u do that once u cant again

slow dome
slender lintel
#

oh

#

last time i did it dint work

#

ill try again tho

frigid elm
#

@bot.event
async def on_command_error(ctx, error):
if isinstance(error, commands.CommandOnCooldown):
await ctx.send('This command is on cooldown, you can use it in {round(error.retry_after, 2)}')

#

it doesnt handle it

#

itt jst gives the error in terminal

lament nimbus
#

wait you can add cooldowns that easily?

slow dome
#

b!rtfm pyc on_application_command_error

lament nimbus
#

how do i use buckettypes?

#

but idk how to use them

#

for a cooldown

#
@commands.cooldown(2,5,"user")

is what i tried

slow dome
lament nimbus
#

im bad at explaining

slow dome
#

commands.BucketType.user for your example is how you want to use it

lament nimbus
#

oh thanks

mild hatch
#

Is there a way to add checks for cog listeners like in commands?

icy sluice
#

how do i get the bots avatar url?

crimson gale
#

bot.user.(display_)avatar.url

icy sluice
#

display?

crimson gale
#

text inside the brackets is optional but heavily encouraged as it will always result in an Asset object

slow dome
mild hatch
#

like it wouldn't listen if the event came from a certain server

icy sluice
crimson gale
#

yes

icy sluice
#

got it, ty

slow dome
mild hatch
#

yep i've been doing that, i was just wondering if there was another way to do so

icy sluice
#

what does this even mean šŸ¤”

halcyon cairn
icy sluice
#

i have icon_url=xxx?

halcyon cairn
#

I don’t think author field has ability to post pic

#

Not for author.

icy sluice
#

it can aha

halcyon cairn
#

I thought that was a diff field. Could be wrong though. I’m gonna look it up

icy sluice
#

one sec I’ll get a ss

sudden path
#

You haven't provided name=

#

b!rtfm pyc embed.set_author

open bearBOT
icy sluice
#

strange

#

I’d assume that’s only when I’m providing an icon?

#

it doesn’t get less confusing

#

ermm

#

slightly confused?

slow dome
#

b!rtfm pyc embed.descrip

open bearBOT
icy sluice
#

and jem is my embed definition

#

so I’m confused?

sudden path
#

set_description doesn't exist

#

Read the documentation

clever lava
#

help

#

cant install pycord

#

just downloaded python 3.10

#

but i still cant install pycord

sudden path
#

Can't read your mind mate. Provided errors / explain what's happening

clever lava
#
PS C:\Users\proje\OneDrive\Documentos\code> pip install py-cord==2.0.0rc1
pip : O termo 'pip' não é reconhecido como nome de cmdlet, função, arquivo de script ou programa operÔvel. Verifique a grafia do nome ou, se um 
caminho tiver sido incluĆ­do, veja se o caminho estĆ” correto e tente novamente.
No linha:1 caractere:1
+ pip install py-cord==2.0.0rc1
+ ~~~
    + CategoryInfo          : ObjectNotFound: (pip:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException
#

this is what it says

#

every single pip command dont work btw

#

help plase

crimson gale
#

try py -m pip

clever lava
#

k

#

ok now what]

crimson gale
#

well did it work?

clever lava
#

yes

crimson gale
#

then use it instead of pip

clever lava
#

hm

#

ok

#

it worked!

#

tysm

crimson gale
#

you may have botched something during the install process but the alternative is the exact same so it doesnt matter

icy sluice
#

i have stuff = guild.owner then {stuff.tag} but I get this error: AttributeError: 'Member' object has no attribute 'tag'

sudden path
#

b!rtfm pyc Member.tag

open bearBOT
sudden path
#

Tada

#

It doesn't exist

smoky path
#

is it possible to get with on_voice_state_update: Member server muted/deafed, member was MOVED into a channel?

icy sluice
#

got it now, dw

#

how do i make a new line though in a description?

half marsh
#

\n thonk

icy sluice
#

ty

#

I’ve been doing n\ 🄓

#

oh god

#

now a EOL while scanning string literal err

#

think I fixed it

sage robin
#

code

#
async def _8ball(self, question):
        
        embed = discord.Embed(title = question, description = random.choice(ball_responses))
        
        await ctx.respond(embed=embed)

ball_responses = [
     "Es cierto.",
     "Es decididamente asĆ­.",
     "Sin duda.",
     "SĆ­ definitivamente.",
     "Puedes confiar en ello.",
    "Como yo lo veo, sĆ­.",
    "M Ɣs probable.",
    "Perspectivas buena.",
    "SĆ­.",
    "Las seƱales apuntan a que sƭ.",
    "Respuesta confusa, intenta otra vez.",
    "Pregunta de nuevo mƔs tarde.",
    "Mejor no decirte ahora.",
    "No se puede predecir ahora.",
    "ConcƩntrate y pregunta otra vez.",
    "No cuentes con eso",
    "Mi respuesta es no.",
    "Mis huevos dicen que no.",
    "Outlook no es tan bueno",
    "Muy dudoso."
    ]```
sage robin
half marsh
#

on very top

clever lava
#

there is a way to implement auto help commands?

#

like if i add a command it join on a help command

sage robin
#

tenks

#

other error

icy sluice
#

how do i fetch a member using an api call while using a discord member converter?

solar berry
#

or pass : Member to your obj in the command params

mild hatch
#

I think my commands are just not syncing

#

auto sync commands is set to true

steep bluff
#

Is there a way to loop through all @tasks.loop() tasks of my discord bot/cog? I want to loop through them in cog_unload and cancel/stop them. Would be easier than manually writing a cancel for each one :)

craggy rapids
#

If this embed maked with title="** **"?

#

And just use set author?

solar berry
solar berry
craggy rapids
#

And like just use the embed.set_author?

solar berry
#

its hard to tell on mobile

craggy rapids
solar berry
#

xxx's blackjack game is the author
'you didnt respond in time' is either bold in description or title

steep bluff
craggy rapids
#

it is embed.add_author right?

#

to make that embed we need to make title="** **" right?

terse plinth
#
    @_change_prefix.error
    async def _change_prefix_error(self, ctx:bridge.BridgeContext, error):

        if isinstance(error, commands.MissingRequiredArgument):
            await ctx.respond(f'> **Error : Missing Required Argument - **`new_prefix`')

i get the error

Traceback (most recent call last):
  File "C:\Python\lib\site-packages\discord\cog.py", line 715, in _load_from_module_spec
Traceback (most recent call last):
  File "e:\Python\Evelynn Workspace\Evelynn7\main.py", line 28, in <module>
    client.load_extension(f'cogs.{filename[:-3]}')
  File "C:\Python\lib\site-packages\discord\cog.py", line 787, in load_extension
    self._load_from_module_spec(spec, name)
  File "C:\Python\lib\site-packages\discord\cog.py", line 717, in _load_from_module_spec
    del sys.modules[key]
KeyError: 'cogs.setup_cog'
#

_change_prefix -

@bridge.bridge_command(name = 'change_prefix', description = 'Change the prefix for your server')
    @commands.has_permissions(administrator = True)
    async def _change_prefix(self, ctx:bridge.BridgeContext, new_prefix:discord.Option(str, description = 'New prefix for your server')):

        mongo.guild_profiles.update_one({'_id' : ctx.guild.id}, {'$set' : {'prefix' : new_prefix}})

        await ctx.respond(f'Prefix for `{ctx.guild.name}` set to `{new_prefix}`')
solar berry
#

afaik loops don't stop when u unload them

#

and there's not a good way that i know of to start a loop thats in a cog that i know of, which can be enabled on cog load and disabled on cog unload

#

i could be wrong tho, take my words with a grain of salt

steep bluff
#
  def __init__(self, bot:commands.Bot):
        self.client:commands.Bot = bot
        if self.do_checks.is_running():
            self.do_checks.stop()
        self.do_checks.start()

    def cog_unload(self):
        # To avoid errors, stop all running loops 
        loop: tasks.Loop
        for loop in [self.do_checks]:
            if loop.is_running():
                try:
                    loop.stop()
                except Exception as e:
                    log.error(f"{loop.__name__} {e}")
#

Working fine, would just be better to have something else than a manual list of all loops

icy sluice
#

Code in main file:

@tasks.loop(seconds=10)
async def updateactivity():
        """Updates the bot's activity"""
        await bot.change_presence(activity=discord.Activity(type=discord.ActivityType.listening, name=f"!help in {len(bot.guilds)} servers for {members(bot)} users."))

@updateactivity.before_loop
async def wait_for_ready():
        """Waits until the bot is ready"""
        await bot.wait_until_ready()


@bot.event
async def on_ready():
    print(f"{bot.user} is ready and online!")

@bot.event
async def on_guild_join(guild):
    # some code

bot.run(os.getenv('TOKEN'))
updateactivity.start()```
**Error:** my bot doesn’t have a status, no error shown.
steep bluff
icy sluice
steep bluff
#

This is true, you can either do

if not updateactivity.is_running():
   updateactivity.start()
``` or just put your ``updateactivity.start()`` right before ``bot.run()``.  Not sure about this though, but ```py
@updateactivity.before_loop
async def wait_for_ready():
```  should handle this I think.
icy sluice
#

putting it before bot.run() worked for me, thank you :)

graceful robin
#

my bot responds 2 times to normal commands

#

everything else works

#

when I ping the bot it responds once

#

I noticed that a new command that I created recently works normally

solar berry
graceful robin
#

yes

#

i changed the token

#

i restarted my computer

#

this keeps happening for over 2 weeks now

solar berry
#

that is really odd

#

show code?

graceful robin
#

someone ran it on his computer

#

and everything was fine

#

i even created a different bot

#

and it still didnt work

solar berry
#

have you tried reinstalling the library

#

this issue is really odd

graceful robin
#

no

solar berry
#

I have a slight issue, where uploaded files are kept in memory after being uploaded, kinda like a memory leak, does anyone know how to fix if possible?

graceful robin
#

alright

#

lets try now

#

didnt work