#General Help

1 messages · Page 6 of 1

jolly charm
#
import discord
from discord.ext import commands

intents = discord.Intents()
intents.message_content = True 
bot = commands.Bot(command_prefix='!',intents=intents)

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

@bot.command()
async def hello(ctx):
    await ctx.reply("Hey!")


from config import TOKEN
bot.run(TOKEN)
#

still not working ;-;

gilded widget
#

you still need intents.messages lmao

#

you need both of them

jolly charm
jolly charm
jolly charm
gilded widget
#

anybody know how to keep spaces in an embed?

#

kinda annoyed that discord just chops off extra spacing 😐

#

all the solutions that google spouts out don't work either lmao

wooden coyote
#

'401: Unauthorised'

#

does it mean I dont have sufficent permissions?

jolly charm
#

i can get all those spaces in a normal message

gilded widget
#

yes, I've solved the issue i had now though

#

discord's embed chops off all unnecessary spaces

#

so any space beyond just one will be removed

jolly charm
jolly charm
#

ok

#

what should i do after importing all the class data baronkobama?

gilded widget
#

used \u1CBC to do it

#

theres examples for paginators

jolly charm
#

OH MY GOD !! thanks

jolly charm
terse plinth
#

Code -

    @commands.command()
    async def rr(self, ctx:commands.Context, message_id, emoji, role):
        await ctx.reply(f'{message_id}, {emoji}, {role}')

    
        message = self.client.get_message(message_id)

        await message.add_reaction(emoji)
#

Error -

Ignoring exception in command rr:
Traceback (most recent call last):
  File "C:\Python\lib\site-packages\discord\ext\commands\core.py", line 181, in wrapped
    ret = await coro(*args, **kwargs)
  File "e:\Python\Evelynn Workspace\Evelynn4.0 RE\cogs\reactroles_cog.py", line 49, in rr
    message = self.client.get_message(message_id)
AttributeError: 'Bot' object has no attribute 'get_message'

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

Traceback (most recent call last):
  File "C:\Python\lib\site-packages\discord\ext\commands\bot.py", line 360, in invoke
    await ctx.command.invoke(ctx)
  File "C:\Python\lib\site-packages\discord\ext\commands\core.py", line 927, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "C:\Python\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: AttributeError: 'Bot' object has no attribute 'get_message'
#

idk whats the issue

red tendon
terse plinth
#

how do i get a TextChannel object?

vague rune
#

Hi, every single bot I used pycord on, just suddenly stopped working.....like, the bot goes online but doesn't respond to any prefix commands....tho,slash commands do work....

I've been trying to fix this for a while now and haven't found why suddenly all bots just became an empty shell...any help would really be appreciated....

vague rune
#

I am also getting this error, my guess is that this is somehow connected to what's happening....

#

If so, how to solve it?

vague rune
silver arrow
#

pls if anyone can give attachment option in slash commands docs>

#

?

silver arrow
jolly charm
#

@stable tiger pls can you?

slender lintel
#

I HAVE FIXED!

Hey how i can say time in Modal? i have tried so: time=self.children[0].value (in async def callback(self, interaction: discord.Interaction, time=self.children[0].value):).

crimson gale
slender lintel
crimson gale
#

what do you mean?

#

also this self.children[0].value wouldnt work in a function def as a parameter

slender lintel
crimson gale
#

so the time is inputted into the first field of the modal?

slender lintel
#

Yes

#

do you want me to send you the code?

crimson gale
#

simply access self.children[0].value in the function then

slender lintel
crimson gale
#

in the function

#

not in the parameter section

#

in the function where you have all the code

slender lintel
#

Yeah wait

slender lintel
# crimson gale simply access `self.children[0].value` in the function then
class Giveaway_Basic(discord.ui.Modal):
    def __init__(self, *args, **kwargs) -> None:
        super().__init__(*args, **kwargs)

        self.add_item(discord.ui.InputText(label="⏰ Wann soll das Gewinnspiel enden?",
                                           placeholder="Beispiel: 5d", required=True, min_length=2))
        self.add_item(discord.ui.InputText(label="🎁 Was gibt es zu gewinnen?",
                                           placeholder="Beispiel: Discord Nitro", required=True))

    async def callback(self, interaction: discord.Interaction, time=None):
        time_give = {"d": 86400, "h": 3600, "m": 60, "s": 1}
        hmm = time.split(" ")
        mydate = self.children[0].value
        for i in hmm:
            mydate += int(i[:-1]) * time_give[i[-1]]
        timestamp = (datetime.datetime.now() + datetime.timedelta(seconds=mydate)).timestamp()
        timestamps = int(round(timestamp))
        await interaction.response.send_message(f"{self.children[1].value}")
        await asyncio.sleep(mydate)
        await interaction.response.send_message(f"yay")

So? i have this self.children[0].value to the mydate = self.children[0].value made.

crimson gale
#

that works

#

also you cant call interaction.response twice for an interaction

#

if you need to send a follow up use interaction.followup

slender lintel
# crimson gale that works
Ignoring exception in modal <extensions.Giveaway.Giveaway_Basic object at 0x000002004FD9FF10>:
Traceback (most recent call last):
  File "C:\Users\zReaxrYT\PycharmProjects\Discord\venv\lib\site-packages\discord\ui\modal.py", line 217, in dispatch
    await value.callback(interaction)
  File "C:\Users\zReaxrYT\PycharmProjects\Discord\extensions\Giveaway.py", line 24, in callback
    hmm = time.split(" ")
AttributeError: 'NoneType' object has no attribute 'split'
crimson gale
#

why do you still have that parameter in there?

slender lintel
#

how is a parameter ?

crimson gale
#

time=None this is useless

slender lintel
#

so then is time.split(" ") not working

crimson gale
#

you want to call it on mydate

slender lintel
crimson gale
#

that has nothing to do with that parameter

slender lintel
#
Ignoring exception in modal <extensions.Giveaway.Giveaway_Basic object at 0x00000250CDE8FEB0>:
Traceback (most recent call last):
  File "C:\Users\zReaxrYT\PycharmProjects\Discord\venv\lib\site-packages\discord\ui\modal.py", line 217, in dispatch
    await value.callback(interaction)
  File "C:\Users\zReaxrYT\PycharmProjects\Discord\extensions\Giveaway.py", line 24, in callback
    time_give = {"d": 86400, "h": 3600, "m": 60, "s": 1}
NameError: name 'time' is not defined
crimson gale
#

hmm

#

i wonder why that is

#

because that shouldnt be happening at all

slender lintel
#

yeah.. :((

#

thank you despite it

plush lintel
#

If I want to put every member in my server into an embed, what should i do?

#
    for name in ctx.author.guild.members:
        members = name
#
        value=f"Member No: {ctx.author.guild.member_count}\nMembers: {members}",
#

plz help me thx

stray smelt
#
all_member = []
for name in ctx.author.guild.members:
  all_member.append(name)

embed = discord.Embed()
embed.add_field(name = "..." , value = f"Member No:{ctx.author.guild.member_count}\nMembers: {", ".join(all_member)}"
plush lintel
#

thxx

#
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'list' object has no attribute 'join'
#

what shall i change?

stray smelt
#

try this again

#

@plush lintel

plush lintel
#

ok

#

@stray smelt ```py
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: sequence item 0: expected str instance, Member found

stray smelt
#

Did u have member intents?

#

?tag intents

hearty rainBOT
#
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)
plush lintel
#

yeah

#
bot = commands.Bot(command_prefix="pls", intents = discord.Intents.all())
stray smelt
#

Can u try simple debug by print(ctx.author.guilds.members) ?

crimson gale
silver arrow
#

cant send empheral messages via ctx.respond?

#

await ctx.respond('❌ This command can be used By Teachers only !', ephemeral=True)

crimson gale
#

what issue are you running into?

silver arrow
crimson gale
#

then why are you asking for help?

#

youve done it right

silver arrow
crimson gale
#

are you deferring the interaction with ephemeral=True?

crimson gale
#

show me the entire command callback

silver arrow
crimson gale
#

the entire command

silver arrow
#

i mean normaly if i send it should work

crimson gale
#

does it take alot of time to process through that you have to defer the interaction?

crimson gale
#

then show me that part

silver arrow
#

it send it not an empheral image

crimson gale
#

show me the defer line

silver arrow
crimson gale
#

thats responding, not deferring

#

oh i see the defer line up there

#

add ephemeral=True into its args

#

@silver arrow

silver arrow
#

ok

jolly charm
#

Is there any way for me to get the current page input , the user is currently on?

#

or maybe user selects a page .. and i can get that somehow

slender lintel
#

Hey, how can I check if a datetime format is spelled correctly in an if statement? For example, if 10 was specified in a command, the command doesn't know what 10 means, days, hours, minutes, seconds, etc., how can I throw an error?
I don't know how to call the full format in the if query.

time_give = {"d": 86400, "h": 3600, "m": 60, "s": 1}
sour terrace
#

Check if it ends with d, h, m, s

slender lintel
sour terrace
#

Heh? Slash commands or normal ones

slender lintel
#

Slash Command and Modal

sour terrace
#

Can i see your command function

slender lintel
#

yeah

sour terrace
#

parameters

slender lintel
#
    async def callback(self, interaction: discord.Interaction):
        time = self.children[0].value
        time_give = {"d": 86400, "h": 3600, "m": 60, "s": 1}
        time_spilt = time.split(" ")
        mydate = 0
        for i in time_spilt:
            mydate += int(i[:-1]) * time_give[i[-1]]
        timestamp = (datetime.datetime.now() + datetime.timedelta(seconds=mydate)).timestamp()
        timestamps = int(round(timestamp))
        await interaction.response.send_message(f"{self.children[1].value} - <t:{timestamps}:R>")
sour terrace
#

so time is a string

slender lintel
#

what do you mean?

sour terrace
#

Are you getting time like this? 10h15d

slender lintel
#

for what?

sour terrace
#

How do you take input

royal stag
#

I tried checking the docs but is there a way to send a message to a specific channel(via using channel id)?

#

not sure if i looked enough

sour terrace
#

Yes

slender lintel
#

i want only a if query not more when a user a failed datetime format used then a just a error message

sour terrace
royal stag
#

as far as a i remember u get the guild via

#

ctx.guild

slender lintel
sour terrace
#

No i dont

slender lintel
#

😦

sour terrace
#

First how do you get time and in what format

slender lintel
#

i know how i can a if querry but i dont know how i can a datetime format define.

sour terrace
#

Idk what you are trying to do

slender lintel
jolly charm
sour terrace
#

There is something calles endswith in python google it@slender lintel

slender lintel
jolly charm
# sour terrace Lemme check docs of sec

I want to implement something like: user chooses a specific page, but for that i must know which page the user currently is in.
If i can get the input of user clicking the next button.. I can make a variable to get the current page

sour terrace
#

Usually the paginator starts with page 1

jolly charm
#

there is a attribute called current_page.. i tried printing that.. turns out to be 0 at beginning

wheat hedge
#

can i add reactions to a message that is invoked with slash commands?

jolly charm
#

but can i get the current_page whenever user clicks on next page?

sour terrace
hearty rainBOT
slender lintel
#

how do i make a command that replies to the original command?

wheat hedge
jolly charm
sour terrace
#

I have never used this but you can try and tell me too

sour terrace
wheat hedge
#

its not my code.. it was code sent by another person.. and in the docs i couldnt find add_reaction

sour terrace
#

when you send a response you can add reaction to that message

wheat hedge
slender lintel
sour terrace
#

Hmm

#

@wheat hedge Can you try and fetch the message by id then add reaction?

wheat hedge
#

i can suggest them to do so

sour terrace
#

Yep

supple plaza
#

whenever I run the code it tells me there is an error in "elif choice1 == '2' or choice == 'two':
could anyone help? (mention me if you can help ) thx

finite tiger
supple plaza
#

what do you mean?

finite tiger
#

the part after elif should be indented.. pretty basic stuff my friend.

supple plaza
#

I'm sorry english is not my native language

finite tiger
#

🙌 📔 🇬🇧

supple plaza
#

nope didn't work

sudden path
#

Why are you adding : after elif

finite tiger
#

😴

silver arrow
#

so i dont know
like it doesnt freeze the bot in d.py

ornate spade
#

update pycord

#

get the github version

vague rune
#

Still pops up

ornate spade
finite tiger
#

try to resync commands manually

ornate spade
#

just install from github

finite tiger
#

in server settings

vague rune
#

Ok

pallid flume
#

how do i check if somebody used a slash command?

#

i want to make a log command

clever lava
#

how to check how many members have in a role

sudden path
sudden path
pallid flume
clever lava
clever lava
#
@bot.slash_command(guild_ids=tbw)
async def check(ctx, role : discord.Role):

  await ctx.respond(role.members)

  if role.members < 10:
    await ctx.respond("< 10")
  else:
    await ctx.respond(">= 10")
#

yo

#

this does not work

#

i think its because if role.members < 10:

#

the "<" does not have its meaning in python

#

can someone help mee

clever lava
crimson gale
clever lava
#

oh

#

im comparing a list with a int

#

thats why

clever lava
crimson gale
#

len()

clever lava
#

wat

crimson gale
#

basic python

clever lava
#

can you give me a example

#

me noob

crimson gale
#

just toss it in that function

clever lava
#

len(role.members)

#

like this?

lunar maple
#

hi o/ what's the maximum amount of channels a discord server can have? is there a way to query it from a bot?

crimson gale
clever lava
#

i hate knowing pycord but not knowing basic python

clever lava
#

just explain me please

crimson gale
#

what does the list contain?

clever lava
#
  dcria = ctx.guild.get_role(975412724102234163)
  owner_dcria = ctx.guild.get_role(975412867044098139)

  embed=discord.Embed(title=None, description="Member added to your clan", color=discord.Color.green())

  if owner_dcria in ctx.author.roles:
    if len(dcria.members) < 9:
      await membro.add_roles(dcria)
      await ctx.respond(embed=embed)
    else:
      await ctx.respond("Your clan already have 8 members, no one can be added anymore", ephemeral=True)
  else:
    await ctx.respond("Your clan is not registered", ephemeral=True)
#

i've got the command workin

#

but it does not satisfact the if

crimson gale
#

swap it to be greater than max members here

clever lava
#

um

#
  dcria = ctx.guild.get_role(975412724102234163)
  owner_dcria = ctx.guild.get_role(975412867044098139)

  embed=discord.Embed(title=None, description="Member added to your clan", color=discord.Color.green())

  if owner_dcria in ctx.author.roles:
    if len(dcria.members) > 7:
      await ctx.respond("Your clan already have 8 members, no one can be added anymore", ephemeral=True)
    else:
      await membro.add_roles(dcria)
      await ctx.respond(embed=embed)
  else:
    await ctx.respond("Your clan is not registered", ephemeral=True)
clever lava
crimson gale
#

yes

clever lava
#

k

clever lava
#

it just ignores the if

#

i added 5 members to that role

#

even with a limit of 3 (just for testing)

crimson gale
#

it doesnt

#

if its going to the if statement then the condition is evaluated

#

have you tried inspecting the contents of the list yet?

keen oasis
#

Is it possible to check if a member's dms are open without trying to message them?

terse plinth
#

@keen oasis
user.dm_channel.can_send() returns a bool
replace user with a discord.Member object

#

nice name btw

slim coral
#
class SettingsManagerCog(commands.Cog):
    def __init__(
        self, bot: commands.bot, settings_manager: SettingsManager
    ) -> None:
        self.bot = bot
        self.settings_manager = settings_manager
        self.setting_names = list(
            self.settings_manager.defaults.__dataclass_fields__.keys()
        )

    @slash_command()
    async def update_settings(
        self,
        ctx,
        setting: discord.Option(
            str,
            description="Setting name to update",
            required=True,
            choices=list(self.setting_names)
        ),

is there a way to make this boilerplate work? i have a SettingsManager cog which the user provides a settings model to, then initializes this cog with the SettingsManager. I have a generic update_settings command but it needs access to a self property in the choices kwarg for discord.Option

vapid forge
#

I just randomly started getting discord.errors.HTTPException: 405 Method Not Allowed (error code: 0): 405: Method Not Allowed, how can I figure out what method is causing it?

#

Am already running b7*

stable tiger
#

upgrade to master for the fix but this exception is "feel free to ignore" in b7

idle wagon
#

Uploading messages from the database

I have a database. How do I load. Messages with buttons.And also how to delete this message?

blazing turret
#

Is there anyway that I can defer() an interaction as ephemeral, then followup the interaction with a non-ephemeral message?

blazing turret
#

L

blazing turret
#

How can I delete the defer() loading message

idle wagon
#

How to delete a message by id, or how to get message by id?

stable tiger
#

get_message if in cache fetch_message otherwise then message.delete()

idle wagon
#

How do I pass mes Id?

kind mesa
#

then the id would work too

alpine totem
#

does anyone know if you can select multiple items in a pycord dropdown menu?

sudden path
#

Yes you can.

slim coral
#

i'm having a problem getting server display names...i just re-added my bot as admin in case i was missing perms and all of name, display_name, and nick are showing up as my normal username and not my server name...

slender lintel
slim coral
#

i am pulling via message.author

slender lintel
#

Well only works with member

slim coral
#

doesn't work on member either

slender lintel
#

Huh can you send code?

slim coral
slender lintel
#

Guild intent?

#

Or member intent?

#

Other than that I have no idea then sorry

#

Code looks fine to me

midnight cedar
past torrent
#

i'm trying to dm a user a file. i have the file path, my main problem is i need the File object. how do i get this? open() gives me an IOBufferWrapper which doesnt work.

midnight cedar
#

pass the file path to the File object

#

and ittl open it for you

past torrent
midnight cedar
#

no

past torrent
#

cuz i got this instead

#

oh ok

midnight cedar
#

literally just give the filename as a string to discord.File

#

and then send it with the file kwarg

past torrent
#

just*

midnight cedar
#

yeah

inland acorn
#

hey there!!, i want to upload an image file to discord and get its image url, how to achieve that

limpid ginkgo
#

what are the styles for discord.utils.format_dt?

idle wagon
#

Hi what's wrong?

stray smelt
wooden coyote
#

is there an example of subclassing a bot?

stray smelt
#
class MyBot(commands.Bot):
    def __init__(self):
        super().__init__(command_prefix="prefix here",
        intents = discord.Intents())

bot = MyBot()
@bot.event
async def on_ready():
  print("test")
wooden coyote
#

I have tried doing it inside MyBot Class

#

slash command

#

doesnt show nor respond

stray smelt
#

you don't need to subclass bot for slash command

#
import discord

bot = discord.Bot()

@bot.slash_command()
async def hello(ctx, name: str = None):
    name = name or ctx.author.name
    await ctx.respond(f"Hello {name}!")


bot.run("token")
#

just do something like this then it should work

wooden coyote
#

aight

#

well I'm considering that im adding common features

#

so shoving the internal stuff would be more organised

limpid ginkgo
#

how do i get the local user time?

#

i tried using discord.utils.utcnow() but that isnt my time, but if i use that in a embed i get my local time

crimson gale
#

its not your local time for a reason

#

you should generally work with utc as a timezone without messing around with timezone conversions

past torrent
#

how do i run two discord bots at the same time? ive tried: sh python file1.py && python file2.py but that makes file2's contents after i control-c file1. ive also tried: ```sh
python file1.py &
python file2.py &

#

i need to be able to run both from one .sh file

crimson gale
#

why are you attempting to do such a thing?

#

just use pm2

#

if youre running it on a server that is

wooden coyote
#

what are the alternatives to "load_extension"?

past torrent
crimson gale
#

you can make it run anything, not just node.js stuff

wooden coyote
#

is load_extension broken?

crimson gale
#

it is not

#

why are you asking?

wooden coyote
#

whenever I load a cog using that method

#

for some reason commands are not appearing in application

#

I tried it using th example

crimson gale
#

show code?

wooden coyote
crimson gale
#

the cogs as well

wooden coyote
#

this is the cog I am attempting to load

#

"record"

#

I made a post here in forums and no1 respond

frigid lark
#

Intents?

crimson gale
wooden coyote
#

this the class it is subclassed within

crimson gale
#

this does not answer my question

wooden coyote
#

wym

crimson gale
#

are you subclassing discord.Bot or commands.Bot?

wooden coyote
#

commands.Bot

crimson gale
#

voilá, found the root issue

#

command = prefixed command, slash_command = application command

wooden coyote
#

did something have broken commands.Bot?

crimson gale
#

your cog contains prefixed commands

#

except that youre using groups so that doesnt make sense

#

shit

frigid lark
#

You can use commands.Bot for both

wooden coyote
#

let me see if I switch from commands.Bot to discord.Bot

#

see if it makes a difference

#

nope still the same issue

#

I checked if the commands exist

#

only the main commands I see

#

no subcommands

strange oxide
#

Hello guys,
I want to use a callback on my button so I can use it dynamically
I found that you have to use py-cord for that
So i try to see how ti work and it completely broke my bot the commands are not recognized anymore
Can some one tell me what I am doing wrong with this quick code who is not working please

crimson gale
#

both of those are required for prefixed commands to function with api v10

strange oxide
crimson gale
#

actually

#

?tag intents

hearty rainBOT
#
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)
crimson gale
#

there

strange oxide
#

Thanks !

feral smelt
#

how would I go about unregistering commands? I've removed some commands from my code and they've not unregistered on Discord.

woven bone
#

Hi, I have trouble with the commands like @client.command(). Python dosent see it

#

Import discord
from discord.ext import commands does nothing

#

But @client.event works

surreal nimbus
#

yes, cuz u probably did client = discord.Client()

woven bone
#

Yep

surreal nimbus
#

yeah...

woven bone
#

What should I write instead?

surreal nimbus
#

discord.Client() is used for events only

woven bone
#

Oh

surreal nimbus
#

if you want commands, you have to use commands.Bot, but please make the instance bot, instead of client

woven bone
#

Thanks!

surreal nimbus
#

np!

vague rune
#

Hello, the way my slash commands are written is giving an error....

class BotName(commands.Bot):
  def __init__(self):
    super().__init__(command_prefix=get_prefixes)


    @self.slash_command(guild_ids=dc_servers,description="Show's the bot's latency.... :robot:")
    async def ping(ctx):
      await ctx.respond(f":ping_pong:  **Pong !** `{round(self.latency * 1000)}` ms")
#

This is the error.....
discord.errors.ClientException: Callback for ping command is missing "context" parameter.

#

is there something wrong with it?

worthy basin
#

Because your ping command is in a class the first parameter should be self so ctx is being set to self and thus there is no. parameter for context. adding self to before ctx in the ping defenition would fix this

vague rune
worthy basin
#

your ping command looks like this?
async def ping(self, ctx):?

worthy basin
#

Does this happen if you don't put the command in your bot class?

slender lintel
#

Hi, i'd like to add my bot to the server to test it with more people but i don't know if one of its features from is allowed here

It has a feature that if you reply any messages from him, it answers you

It doesn't responds any messages that are not direct replies to its messages, only when clicking on them and pressing "reply"

and it also responds non-reply messages with its @
it's a chatbot like feature

is this allowed on the server? i'm confused because it's not a prefix but it's a way to call the bot like a prefix does ‍​​​​​​‌​​​‌‎‎‎‌​​​​​‌‎‎‎‎‎‎‌​​​‌‍

vague rune
worthy basin
#

I think a @ (mention) counts as a prefix. If you DM dorukyum he would tell you if you could.

worthy basin
vague rune
slender lintel
worthy basin
vague rune
worthy basin
#

Yes

woven bone
# surreal nimbus if you want commands, you have to use `commands.Bot`, but please make the instan...

Hi again, what should I write instead here? Sry im new to bot coding

import discord
from discord.ext import commands
from datetime import datetime
import random

intents = discord.Intents.default()
intents.messages=True

TOKEN = *nope*
client = discord.Client(intents = intents)

[...]

@client.command(aliases = ['!Бэбэй'])

async def on_message(message,question):
    rep = 412547573367308288
    Bebchoice = ["Да","Нет","Возможно","Пошёл"]

    await rep.send(f"Бэбэй говорит {random.choice(Bebchoice)}")
    




client.run(TOKEN)


I dont really understand what should I replace

strange oxide
#

Hello,
Quick question
I use call back on button
I display a Embed that i stock on a List[]
I would like to click on next and update my cursor "pos" every time i click on next or prev
so i can access the list elem of the pos
How can i make this code work please ?

surreal nimbus
woven bone
#

yes

surreal nimbus
#

what do you want to do - message prefixes or slash commands?

woven bone
#

prefix

surreal nimbus
#

what is ur bot gonna be?

#

like what type

#

because no point in making message prefix based commands if you don't get the message intent

woven bone
#

is a logging bot

#
  • some fun commands
#

Here is the full code

#
import discord
from discord.ext import commands
from datetime import datetime
import random

intents = discord.Intents.default()
intents.messages=True

TOKEN = nope
client = discord.Client(intents = intents)


@client.event
async def on_ready():
    print("Я Маления, клинок {0.user}".format(client))

@client.event
async def on_message(message):
    username = str(message.author).split("#")[0]
    user_message = str(message.content)
    channel = str(message.channel.name)
    beb = 0



    cha = client.get_channel(975441449560723556)
    if message.author == client.user:
        return
    else:
        embed = discord.Embed(title = f'Сообщение от : {message.author}\n', description = f'Содержание : {message.content}\n Автор : {message.author.mention}\n в канале {message.channel.mention}',timestamp = datetime.now(), color = discord.Colour.blue())
        await cha.send(embed = embed)
    print(f"от {username} в {channel} - {user_message}")

    if message.channel.name == ':speech_balloon:флудильня':
        if user_message.lower() == "Вызов Малении".lower():
            await message.channel.send(f"Я Маления, клинок Микеллы")
            return
    if message.channel.name == ':speech_balloon:флудильня':
        if user_message.lower() == "Вызов Бэбэя".lower():
            while beb != 100:
                beb = beb + 20
                await message.channel.send(f"*Подключение {beb}%*")
 
            if beb == 100 : 
                await message.channel.send(f"**Бэбэй на связи**")
                beb = 0
    if message.channel.name == ':speech_balloon:флудильня':
        if user_message.lower() == "Бот, кому ты служишь?".lower():
            await message.channel.send(f"Я служу Бекону")


#
@client.event
async def on_message_delete(message):
    chs = client.get_channel(975441449560723556)
    if message.author == client.user:
        return
    else:
        embed = discord.Embed(title = f'Удалено сообщение от : {message.author}\n', description = f'Содержание : {message.content}\n Автор : {message.author.mention}\n в канале {message.channel.mention}',timestamp = datetime.now(), color = discord.Colour.red())
        await chs.send(embed = embed)

@client.command(aliases = ['!Бэбэй'])

async def on_message(message,question):
    rep = 412547573367308288
    Bebchoice = ["Да","Нет","Возможно","Пошёл нахуй"]

    await rep.send(f"Бэбэй говорит {random.choice(Bebchoice)}")
    



client.run(TOKEN)```
hybrid flame
#

Hey guys!
I hope this is not a stupid question.
If my bot "discord.AutoShardedBot", are "@tasks.loop" executed multiple times?
I don't understand the shard system yet 🥸

woven bone
#

This is a multi func. bot

surreal nimbus
#

I mean if your bot will have message logging, then discord may give you the message intent, but still it will take a long time so I recommend using slash cmds

woven bone
#

Okay

#

so what sould I write for @bot?

#

@surreal nimbus

woven bone
#

Gives an error

#

Exception has occurred: TypeError
'module' object is not callable
File "C:\Users\ragna\DiscordLogBot.py", line 11, in <module>
bot = commands.bot(command_prefix = "-")

surreal nimbus
#

the first letter

woven bone
#

It works, now I need to change @client to @bot.event

#

I have another one

#

Exception has occurred: TypeError
Aliases of a command must be a list or a tuple of strings.
File "C:\Users\ragna\DiscordLogBot.py", line 65, in <module>
async def eigtball():

#

code :

l65 async def eigtball():
      rep = 412547573367308288
      Bebchoice = ["Да","Нет","Возможно","Пошёл нахуй"]

    await rep.send(f"Бэбэй говорит {random.choice(Bebchoice)}")
idle wagon
#

@worthy basin @steep lark get_message not work

midnight cedar
#

#help-rules 4, and the message probably isn't cached

idle wagon
stable tiger
#

You can try fetch_message as well ;

#

But overall maybe problem is in self.bot being None

#

I don’t think view has bot attribute, does it ? Then do you provide it for that subclass

#

Well anyway people would get bot/client instance from interaction.client

idle wagon
#

It works. But it is very strange that he could not find the message without channel

woven bone
#

Ok, so I fixed the @bot problem but my 8ball code dosent seem to work, bot just ignores it.

surreal nimbus
#

define the command function with something else, not an event name, that will be very confusing, name it something like "eightball"

#

also, you need ctx arg in the function

#

and in order to send a message, the rep needs to be a discord.Channel or discord.Member or discord.User object

inland acorn
#

hey there!!, i want to upload an image file to discord and get its image url, how to achieve that

surreal nimbus
#

it's a command

#

not an event

#

so it takes Context param

slender lintel
#

Ohh my bad

#

Didn't noticed that xD

surreal nimbus
#

xD

#

don't worry, every human makes mistakes

surreal nimbus
#

1 sec

surreal nimbus
#

well it doesn't really matter.

#

what you need to do is get the instance of the message, then get the message attachments (discord.Message.attachments) and you will get a list. Then you can use the url function on the attachment from the list and you will get the link

woven bone
#

still ignoring

surreal nimbus
inland acorn
#

so just send the mesage, obtain its id, fetch message and get attachment url?

surreal nimbus
woven bone
#

yes

surreal nimbus
surreal nimbus
# woven bone yes

then you don't need the discord.Channel = ..., you just do ctx.send(...)

surreal nimbus
# inland acorn eloborate more?

ok, let's say you send the message ctx.send(...), you can get the instance of that with msg = ctx.send(...) and msg will be the discord.Message so you don't need to make unnecessary API calls to get the message

#

and you won't need to fetch the msg

surreal nimbus
inland acorn
woven bone
#

the bot works

surreal nimbus
#

show the command code please

woven bone
# surreal nimbus show the command code please

prefix - bot = commands.Bot(command_prefix = "-")
command - ```@bot.command(aliases =['bebey','Bebey'])
async def bebeyball(ctx):

Bebchoice = ["Да","Нет","Возможно","Пошёл нахуй"]
await ctx.send(f"Бэбэй говорит {random.choice(Bebchoice)}")```
surreal nimbus
#

hm

#

could it be because of the discord update

#

wait

#

@crimson coral can you use message prefixed cmds if you don't have the msg intent and your bot isn't verified?

rigid lodge
#

What would I put in the isinstance() func for an error when the user doesn't have a specific role needed to use the command

#

idk the error type

slow dome
surreal nimbus
#

or commands.MissingRole

#

(for short ^)

rigid lodge
#

Thank you!

woven bone
surreal nimbus
#

👍

woven bone
#

Maybe / command?

little isle
#

Is it possible to have a "project-level" pip install? I have two projects with conflicting package requirements

crimson gale
#

virtual environments are your friends

#

if you need a quick and easy way to just get a venv with its own dependencies, consider looking into pipenv

#

note: this isnt necessary if you are using pycharm, it handles venvs for you already

little isle
#

ty

#

Now for something else ...

I just installed the current master, and I get TypeError: issubclass() arg 1 must be a class when loading my cogs.

Example:

class AdminCog(BaseCog):

Where BaseCog is a subclass of commands.Cog

strange oxide
#

Hello,
Quick question
I use call back on button
I display a Embed that i stock on a List[]
I would like to click on next and update my cursor "pos" every time i click on next or prev
so i can access the list elem of the pos
How can i make this code work please ?

woven bone
#

Quick question, how to check if somebody has a specific role?

#

like if message.author == (role):

broken wren
#

if role in message.author.roles

tropic fractal
#
Traceback (most recent call last):
  File "/home/nex/PycharmProjects/spanner-v2/venv/lib/python3.10/site-packages/discord/cog.py", line 715, in _load_from_module_spec
    spec.loader.exec_module(lib)  # type: ignore
  File "<frozen importlib._bootstrap_external>", line 883, in exec_module
  File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed
  File "/home/nex/PycharmProjects/spanner-v2/src/cogs/official/debug.py", line 24, in <module>
    class Debug(commands.Cog):
  File "/home/nex/PycharmProjects/spanner-v2/src/cogs/official/debug.py", line 80, in Debug
    async def clean_bot_message(self, ctx: discord.ApplicationContext, max_search: int = 1000):
  File "/home/nex/PycharmProjects/spanner-v2/venv/lib/python3.10/site-packages/discord/commands/core.py", line 1580, in decorator
    return cls(func, **attrs)
  File "/home/nex/PycharmProjects/spanner-v2/venv/lib/python3.10/site-packages/discord/commands/core.py", line 644, in __init__
    self.options: List[Option] = self._parse_options(params)
  File "/home/nex/PycharmProjects/spanner-v2/venv/lib/python3.10/site-packages/discord/commands/core.py", line 696, in _parse_options
    elif issubclass(p_obj.default, (DiscordEnum, Enum)):
TypeError: issubclass() arg 1 must be a class

Is this a me problem? I'm on the master branch, literally just updated

#

seems to error on any argument with a default value that isn't in a discord.Option

#
async def foo(..., x: discord.Option(int, default=100)):  # works

async def foo(..., x: int = 100):  # doesn't work
ornate spade
#

this is about to be fixed

tropic fractal
#

awesome

#

trust me to install a commit that's broken and think I broke something since its working in production 💀

ornate spade
#

@tropic fractal hey I just merged the fix so could you reinstall and check if it works now?

little isle
#

I can confirm it's working on my end

clever lava
woven bone
#

thankx

tropic fractal
ornate spade
#

great thanks

dusk gale
#

Hey all. Been fighting a TypeError error for a while now and I think I'm doing something simple wrong haha

The case;
I fetch a channel using sales_channel = sales_guild.get_channel(int('channel_id_here')) where sales_channel is fetched by running sales_guild = self.get_guild(int('guild_id_here')). In my variable explorer I see the right guild and right channel get fetched. Now whenever I run await sales_channel.send(embed) with a configured Embed, I run into the following error: TypeError: object TextChannel can't be used in 'await' expression. Though when removing await, it says sales_channel.send(embed) was never awaited. Any insights where I'm going wrong?

#

It seems to error out specifically at File "%AppData%\Local\Programs\Python\Python310\lib\site-packages\discord\abc.py", line 1428, in send channel = await self._get_channel().

surreal nimbus
#

you need to await the sales_channel instance's definition

slender lintel
#

Hey, I got a question. I think the Intents in my script isnt working. Is there anything wrong with that? In discord.py it works.

weak hearth
#

why do i get this error?

dusk gale
surreal nimbus
slender lintel
surreal nimbus
dusk gale
weak hearth
#

ahh

surreal nimbus
#

🥂

dusk gale
surreal nimbus
#

Hm

#

1 sec

#

Hm the get_channel doesn't need await, but the send one needs one

dusk gale
#

Right. That's how I have it set up, but it gives me the TypeError when I await channel.send but says it needs to be awaited (as I expected) when I leave out the await.

#

I'm thinking either my channel definition isn't correct or something's off 😄

surreal nimbus
#

Hm

#

I am so confused

dusk gale
#

Let me drop the entire traceback

slender lintel
#

maybe this works idk

surreal nimbus
#

@dusk gale isn't it self.bot.get_guild?

#

Because you wrote self.get_guild

dusk gale
#

I'm parsing the bot as the self, but let me check

#

Since I'm using cogs. Does that make sense or am I going wrong there?

#

It runs into the same issue.

#
Traceback (most recent call last):
  File "%AppData%\Local\Programs\Python\Python310\lib\site-packages\discord\ext\tasks\__init__.py", line 176, in _loop
    await self.coro(*args, **kwargs)
  File "d:\Tech\Avenged Sevenfold\discord\bot\bot.py", line 79, in on_ready
    await OpenSeaCog.update_sales.start(self._bot)
  File "%AppData%\Local\Programs\Python\Python310\lib\site-packages\discord\ext\tasks\__init__.py", line 205, in _loop
    raise exc
  File "%AppData%\Local\Programs\Python\Python310\lib\site-packages\discord\ext\tasks\__init__.py", line 176, in _loop
    await self.coro(*args, **kwargs)
  File "d:\Tech\Avenged Sevenfold\discord\bot\cogs\opensea.py", line 358, in update_sales
    await sales_channel.send(embed)
  File "%AppData%\Local\Programs\Python\Python310\lib\site-packages\discord\abc.py", line 1428, in send
    channel = await self._get_channel()
TypeError: object TextChannel can't be used in 'await' expression
#

That's the traceback

idle linden
#

Also embed=embed

surreal nimbus
dusk gale
#

To confirm, I do see the guild and channel get fetched properly. I'm just unable to send the embed.

surreal nimbus
#

Hm

dusk gale
#

Greatly appreciate your time and effort btw. Just wanted to get that out there.

surreal nimbus
#

Could you send the whole command code?

#

Or the whole function code

dusk gale
#

Yes, I shall

surreal nimbus
#

Ok

dusk gale
#
    @tasks.loop(seconds=request_interval)
    async def update_sales(self):
        init_timestamp = int(time.time())-7200
        last_timestamp = None
        
        sales_guild = self.get_guild(int('guild_id'))
        print(sales_guild) # < This populates without issue
        sales_channel = sales_guild.get_channel(int('channel_id'))
        print(sales_channel) # < This populates without issue

        event_timestamp = last_timestamp if not last_timestamp == None else init_timestamp
        url = f"https://api.opensea.io/api/v1/events?only_opensea={os_only}&asset_contract_address={asset_contract_address}&event_type=successful&occurred_after={event_timestamp}"
        last_timestamp = int(time.time())
        logging.info(f"Fetching data from URL: {url}")
        assets = requests.get(url, headers=headers).json()

        for asset in assets.get('asset_events', {}):
            sale_event = OpenSeaEvent(asset)
            embed = Embed(
                title= f"{sale_event.name} just sold for {sale_event.total_price} ETH",
                url= sale_event.permalink,
                timestamp= datetime.utcnow())
            embed.set_image(url=sale_event.image_url)
            embed.add_field(name="Name", value=sale_event.name, inline=True)
            buyer_value = f"[{sale_event.buyer_name}]({sale_event.buyer_address})" if sale_event.buyer_name != None else f"[{self.shorten_address(sale_event.buyer_address)}]({sale_event.buyer_address})"
            seller_value = f"[{sale_event.seller_name}]({sale_event.seller_address})" if sale_event.seller_name != None else f"[{self.shorten_address(sale_event.seller_address)}]({sale_event.seller_address})"
            embed.add_field(name="Buyer", value=buyer_value, inline=True)
            embed.add_field(name="Seller", value=seller_value, inline=True)
            logging.info("Sending embed to channel.")
            await sales_channel.send(embed=embed)
        await asyncio.sleep(request_interval - ((time.time() - init_timestamp) % request_interval))
surreal nimbus
#

Oh of course

#

Is this task inside a class?

dusk gale
#

Yes, it is.

surreal nimbus
#

Hm, try to send something else other than an embed, like a normal string

#

If it works, then we will know it's something wrong with the embed

dusk gale
#

Alright, I shall try. Thanks.

surreal nimbus
#

Happy to help!

dusk gale
#

Still the same issue unfortunately. Tried just sending a test message but no success.

surreal nimbus
#

Hm

#

How about trying to get the channel with self.get_channel(id)?

#

Instead of getting the guild and then channel

dusk gale
#

One sec.

#

Still the same haha.

surreal nimbus
#

hm

#

What is your pycord version?

dusk gale
surreal nimbus
#

hm

#

Maybe they made a mistake

dusk gale
#

Should I try 2.0.0b7?

surreal nimbus
#

Give it a try ig

lunar maple
#

hey friends. is it possible to get an interaction after sending a view with ctx.followup.send?

crimson coral
dusk gale
crimson coral
#

ideally you're using the callbacks to handle them

lunar maple
crimson coral
#

uhhh

#

followup.send returns a WebhookMessage if im not mistaken, so you should build around that

lunar maple
crimson coral
#

hold on

crimson coral
# lunar maple could you elaborate or point me to a reading source to better understand? 🙏

So as per https://docs.pycord.dev/en/master/api.html#discord.Interaction.followup, interaction.followup is Webhook object, and https://docs.pycord.dev/en/master/api.html#discord.Webhook.send Webhook.send returns WebhookMessage. For most cases, you can assume WebhookMessage is more or less identical to Message, and you can read about its own methods at https://docs.pycord.dev/en/master/api.html#discord.WebhookMessage

lunar maple
#

oh hold on, if it's a webhook message can't I just edit it directly after modifying the components?

crimson coral
#

yeah pretty much

lunar maple
crimson coral
#

all good

dusk gale
slender lintel
#

why dont coming a error?

time_regex = re.compile(r"(?:(\d{1,5})(h|s|m|d))+?")
time_dict = {"h": 3600, "s": 1, "m": 60, "d": 86400}

def convert(argument):
    args = argument.lower()
    matches = re.findall(time_regex, args)
    time = 0
    for key, value in matches:
        try:
            time += time_dict[value] * float(key)
        except KeyError:
            raise commands.BadArgument(
                f"{value} ist eine falsche Zeitangabe! Nutze: `h|m|s|d`"
            )
        except ValueError:
            raise commands.BadArgument(f"{key} ist keine Zahl!!")
    return round(time)
pallid flume
#

how do i make a button just clickable to a certain person?

#

and send a message just for a person who is not the author of the command

tribal vapor
#

hey for slash command options, what's it called to have a menu where I can select a user? something like /blah <menu to select a user>

#

found it, it was discord.User

pallid flume
#

how do i make that one message "the bot is thinking"?

ancient crest
#

can someone help me with my python discord bot it wont respond to me when use the prefixed command

#

pls

south ermine
south ermine
south ermine
ancient crest
#

what is that im new as heck

south ermine
#

?tag intents

#

idk why Dyno is ignoring me

#

#883236900171816970 message

pallid flume
#

why is this happening?

south ermine
sudden path
pallid flume
vivid nacelle
#

@hearty rain

wild spire
#

Hello, I am trying to import from discord.ext bridge using pycord, but it keeps telling me that it cant access it. I installed pycord, and am using vscode

stable tiger
#

Install latest beta version or just from git master ;

wild spire
#

I did a py -3 -m install -U py-cord install

solar berry
#

Can you have multiple prefixes?

surreal nimbus
solar berry
#

How o.o

south ermine
#

!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
south ermine
#

you need beta or alpha

surreal nimbus
fervent lance
#

hey what's a simple way to take another input from a user after the user clicks a button?

#
class MyButton(Button):
    def __init__(self,label):
        super().__init__(label=label, style=discord.ButtonStyle.primary)
    async def callback(self, interaction):
        await interaction.response.edit_message(content="**Anime selected!**" , view=None)
        episode_fun(self.label)
        await interaction.followup.send("**_Select_ Episode _from:_ 1-"+ str(total_ep)+'**')

class MyView(View):
    def __init__(self,n):
        super().__init__()
        for i in range(1,(n+1)):
            button = MyButton(str(i))
            self.add_item(button)

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

@bot.command()
async def weeb(ctx):
    anime_fun(ctx.message.content)
    pages = []
    for i in range(len(anime_posters)):
        pages.append(discord.Embed(title=anime_titles[i],description=anime_desc[i]))
        pages[i].set_image(url=anime_posters[i])
        paginator = Paginator(pages=pages,timeout=180.0, author_check=True, disable_on_timeout=True)   
    await paginator.send(ctx=ctx)

    view = MyView(len(anime_posters))
    await ctx.send("Select Anime: ",view=view)
#

so after the callback, ie. followup.send(), I want a user input

slender lintel
#

why is role.edit just not working? await role.edit(name='new name') just blocks the code and does not show any error?

#

I am sure im not suppressing any errors and that role is valid

#

Im also sure it isnt a permission issue

slender lintel
#
@role_group.command(guild_ids=[961950658595020850])
async def edit(self, ctx: discord.ApplicationContext, name: Option(str, 'The name for your role.')) -> None:
    role = ctx.author.roles[-1]
    print(role) # outputs the role so it is valid
    await role.edit(name=name)
    await ctx.respond('Role updated.')
#

it just blocks on role.edit

slender lintel
#

the name of the role

red tendon
slender lintel
#

but if i put type(role) it says discord.Role

slender lintel
#

1 sec

#

<class 'discord.role.Role'>

red tendon
slender lintel
#

the bot has admin and has the highest role

red tendon
slender lintel
#

if I remember correctly I had this issue before and it magically fixed itself but now it has returned

slender lintel
red tendon
#

try removing this and try doing this:

try:
  #edit the role
except:
  raise```
slender lintel
#

yeah it never progresses from the try and except block

#

its stuck on role.edit

red tendon
#

yeah try it and remove -> None

slender lintel
#

alright

#

still nothing

red tendon
slender lintel
#

nope

red tendon
#

weird

slender lintel
#

yeah im properly confused

crimson gale
#

have you perhaps considered the fact that the role could have the exact same name its being edited to?

slender lintel
#

I remember I was last time but then it suddenly started working again

slender lintel
red tendon
slender lintel
#

master

red tendon
slender lintel
#

I removed it already

red tendon
#

you have on_command_error / on_error in your code in whereever place?

slender lintel
#

also

try:
    await role.edit(name=ename)
    print('yay')
except:
    raise

it never prints yay

red tendon
#

very weird....

slender lintel
#

yeah

#

could it be im missing any intents?

#

i have default with members enabled

red tendon
slender lintel
#

could i be i need presence intent

#

idk in which way that would make sense

#

lets try

red tendon
#

make your life easier :)

slender lintel
#

true

#

still nothing 😦

#

i changed the code to this

#
@slash_command(guild_ids=[961950658595020850])
async def test(self, ctx: discord.ApplicationContext):
    await ctx.author.roles[-1].edit(name='test')
    await ctx.respond('Success')
red tendon
#

any*

slender lintel
#

yeah

red tendon
slender lintel
#

two

red tendon
#

ok

slender lintel
#

the lowest one is far below the bot

red tendon
#

dont do [0] cuz is @ everyone role

slender lintel
#

still nothing

red tendon
#

b!rtfm Guild.get_role

open bearBOT
# red tendon b!rtfm Guild.get_role

I couldn't find a documentation with the name guild.get_role! 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

red tendon
#

b!rtfm pyc guild.get_role

open bearBOT
slender lintel
#

yeah thats how i initially got the role

red tendon
#

and update pycord

slender lintel
#

i just reinstalled pycord

red tendon
#

and try again

slender lintel
#

still nothing

#

i am so confused

#

I bet its a bit flip in my pc

red tendon
#

maybe...

#

try opening an issue in github

slender lintel
#

alright

#

ive never opened an issue before lol

#

oh there is actually an issue about it

#

25 days ago

#

and he also said it magically started working again just like it did with me

#

could be an issue on discords side?

#

oh i almost forgot i have exams in an hour

#

ill check back later if it works

#

thanks a ton for the help btw

wild spire
# south ermine well, that's not right

Thats what worked on my system using powershell 🙂 The issue was that I had discord.py installed, and didnt know I had to uninstall that before starting with pycord. I went through and looked at the docs and found the solution

tall fossil
#

is there in Pycord sth like interaction.deferResponse? I want to tell my command users they have to wait a bit

stable tiger
#

It’s just ctx.defer()

tall fossil
#

but can I sent a custom Message? Like "MyBot is thinking"?

stable tiger
#

ctx.defer() trigger this but you can send stuff yourself with channel send or something before responding to interaction

frank moon
#

do i just use @commands.cooldown(1, 10, commands.BucketType.user) for slash commands cooldowns?

red tendon
#

i am not sure tho

frank moon
red tendon
#

cuz it had been a long time i look at pycord's slash commands

frank moon
supple ravineBOT
#

examples/cooldown.py line 7

# an application command with cooldown```
red tendon
#

there you are right

#

is still discord.ext.commands.cooldown

#

mb

red tendon
frank moon
#

alright

frank moon
frank moon
#

ah so the user needs all the permission stated?

#

wow the option for slash commands changed it wasn't like this before lol

frank moon
#

how do i check if a user is currently timed out?

humble sigil
#

how i can install the version from github

red tendon
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
frank moon
#

or is there no way to do so? :((

red tendon
open bearBOT
red tendon
#

hmm

#

i remember there is one

#

one sec

frank moon
#

cant find it in docs..

red tendon
open bearBOT
red tendon
#

ugh

#

b!rtfm pyc Member.timed_out

open bearBOT
red tendon
#

there ya go

frank moon
red tendon
#

np

humble sigil
# red tendon !install

I've already done but I always get this message
class Ticketclose(discord.ui.Button):
AttributeError: module 'discord' has no attribute 'ui'

red tendon
#

you using replit?

humble sigil
#

still does not work

red tendon
#

pip uninstall py-cord -y
pip install -U git+https://blablabla.iamlazytotype

humble sigil
#

wait

#

still does not work

red tendon
#

restart ur terminal first

humble sigil
#

Package Version


aiohttp 3.8.1
aiosignal 1.2.0
async-timeout 4.0.2
attrs 21.4.0
charset-normalizer 2.0.12
frozenlist 1.3.0
idna 3.3
multidict 6.0.2
pip 22.1
py-cord 2.0.0b7
setuptools 58.1.0
yarl 1.7.2

red tendon
#

gtg

humble sigil
#

still does not work

#

@red tendon

fervent lance
#

How I can use ctx with an edit statement to edit the last message

fervent lance
#

Hey, I've made a bot. thing is, if two ppl concurrently use the bot.. it messes up the results for the first user and shows the results for the latter

#

any solutions guys?
will it be fixed with multithreading?'

vague rune
#

Hello, I have made a bot using commands.Bot with pycord......
For some reason, only slash commands are working....when prefix commands are typed, no response from bot and no error on terminal too.....

#

cogs get loaded (which has the prefix commands) , but no response

midnight cedar
little tapir
#

how to install a git branch through requirements.txt

#
git+https://github.com/Pycord-Development/pycord
pymongo
motor
asyncio``` i hope this is right
novel cave
#

code

@bot.slash_command(guild_ids = [925595902956171285, 963260514379657286],description= "Shows the avatar of the mentioned user")
async def avatar(ctx, user:Option(discord.Member)):
    embed = discord.Embed(title=f"Avatar of {user.mention}", color = discord.User.color())
    embed.set_thumbnail(url = discord.User.avatar_url)
    embed.set_footer(text=f"Requested by {ctx.author}", icon_url=ctx.author.avatar_url)
    await ctx.respond(embed = embed)

error

Application Command raised an exception: TypeError: 'property' object is not callable
little tapir
#

full traceback show the line where the error is being raised

novel cave
# little tapir full traceback show the line where the error is being raised
File "C:\Users\%USER%\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 128, in wrapped
    raise ApplicationCommandInvokeError(exc) from exc
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: TypeError: 'property' object is not callable
little tapir
novel cave
# little tapir send it like this , this one shows the line where the error is popped up
Traceback (most recent call last):
  File "C:\Users\%USER%\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\bot.py", line 1098, in invoke_application_command
    await ctx.command.invoke(ctx)
  File "C:\Users\%USER%\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 331, in invoke
    await injected(ctx)
  File "C:\Users\%USER%\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 128, in wrapped
    raise ApplicationCommandInvokeError(exc) from exc
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: TypeError: 'property' object is not callable
little tapir
#

uff u didnt get me ig

surreal nimbus
#

Send the full traceback

#

BRUH

#

Do you know the difference between a class and an instance?

#

In other words, you should use user instead of discord.User

surreal nimbus
#

dude...

novel cave
surreal nimbus
#

Learn the difference between an instance and a class

south ermine
surreal nimbus
#

Then you will know where the problem is

#

I won't spoonfeed

novel cave
surreal nimbus
#

Learn the difference first

#

You will know the problem

little tapir
#

yh

novel cave
placid falcon
#

discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: TypeError: 'tuple' object is not callable
Anyone getting the same error when using slash commands with discord.TextChannel option?

gilded widget
gilded widget
placid falcon
vocal crane
#

What is this error all about?

#

raise HTTPException(response, data)
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In _errors: [{'code': 'APPLICATION_COMMAND_TOO_LARGE', 'message': 'Command exceeds maximum size (4000)'}]

obsidian zephyr
#

Is there a way to track/get a list of users who clicked a button? then use it to get a random user like a giveaway command

vocal crane
#

i think u can check the people that reacted make a list or just pick their names and use random to choose one

inland acorn
obsidian zephyr
#

kk

echo sluice
#

Is it possible to edit an embed and keep the reactions that were initially on it?

inland acorn
#

i want any admin panel for my bot, any api alr present for this? like accessing command usage per guild; its chart, bot stats, in a website

echo sluice
# surreal nimbus I think so

any idea how to do that? unsure if im doing something wrong but when i use edit on the embed it gets rid of all the reactions that were there.

surreal nimbus
#

But why reactions?

#

Buttons exist

echo sluice
#

they do. working on a giveaway bot and reactions seem to work easier for that but if im missing something im alright with switching

surreal nimbus
#

Idk, it shouldn't remove the reactions when editing

echo sluice
#

hmm alright ill have to take a look again, thought that was my issue

#

ahh yes youre right thanks.. dumb move but had small error

surreal nimbus
#

What type of error? You accidentally cleared the reactions again?

echo sluice
#

no, was just being stupid, still had the code in for deleting and sending a new embed after editing it..

wild spire
tough quarry
#

Hi! Does anyone have any idea why this event isn't being called? All the other events work but not this one

@bot.event
async def on_thread_create(thread):
  print("Thread Created")
slender lintel
pale depot
#

How do I make my slash commands only appear in specific channels?

dusky epoch
#

how do i get the voice channel version of pycord?

tough quarry
weak hearth
#

how can i display an avatar even if the user doesn't have one?

idle linden
idle linden
raw tulip
#

hey

#

is there a limit on how many pages a paginator can have

jovial tusk
#

I keep getting this error when i start my bot

#

How do I solve this??

#

I dont think theres any issue tbh, this just feels like a warning, my bot is working fine, and it gets updated normally(the slash commands get synced)

#

but how do I get rid of that msg??

#

thanks in advance :D

#

And yes, i invited the bot with applications.commands

#

im on 2.0.0b7

#

version

raw tulip
#

the hell is this

stable tiger
thorn ocean
#

I have a function in a cog file, that i need to call with data from another file thats not apart of the bot.
Problem is, it has self. And using @staticmethod doesnt work as in the function in the bot file i need to use client.
How can I call the function without self?

vocal crane
thin trellis
#

The default_permissions will only apply when the bot gets added to the guild right?

#

So basically it will not mess up current configured permissions that are already set
by administrators?

surreal nimbus
hazy loom
#

I'm using slash command and was wondering if there's a way to change interaction failed message to something else in SlashCommands

surreal nimbus
hazy loom
#

Instead of this

#

I want it to fail but instead of telling everyone it'll reply as something else

#

Instead of The app did not respond to something like bot failed to join

surreal nimbus
#

Oh, then use ctx.respond()

#

And pass the message in the ()

hazy loom
#

Yeah but will only the person who sent the command see this?

surreal nimbus
#

As a string ofc

surreal nimbus
hazy loom
#

Okay, i'll check thanks!

#

So in the check I have to always return true?

surreal nimbus
hazy loom
#

Like this custom check I made

surreal nimbus
#

What?

#

No

hazy loom
#

So it can still be false?

#

NVM i'll just check it myself sry for bothering xDDD

surreal nimbus
#

You do await ctx.respond("msg", ephemeral = True)

hazy loom
#

works

#

That's cool af ngl xDDDD

surreal nimbus
#

;D

hazy loom
#

I'm in love with pycord

#

The bridge commands are the best

surreal nimbus
#

Yeah I agree

#

It's so simple to use

#

I am not switching back to dpy because Pycord is being updated and it's easier to use

hazy loom
#

I need to update my bot now to pycord

#

Since I discovered it i'm learning a lot of easier ways to improve

hazy loom
glossy thicket
#

Hello,Could someone give me an example to make a persistent button in a cog? Thank you

surreal nimbus
glossy thicket
hazy loom
#

Is there a way to check in bridge if the bot has been called by prefix or slash command?

surreal nimbus
#

idk

#

Let me check

#

Didn't find anything

stable tiger
#

Yes, actually there is example right in docs

hazy loom
#

Detects a type error of the keyword and just responded to that

hazy loom
#

oh lol

#

tnx xDDD

frigid lark
#

Can I use discord.option is a modal?

hazy loom
#

Another little question, is there a way to check if bot is connected to a channel?

inner iris
#

Can someone please explain me how this works?

@bot.command(name="test")
async def test(ctx: commands.Context, channel: discord.TextChannel):
  print(channel.name)

INSTEAD OF:
@bot.command(name="test")
async def test(ctx: commands.Context, channel_id: str):
  channel = bot.fetch_channel(channel_id)
  print(channel.name)

So it basically creates the TextChannel object just with the channel id or mention. How does that work? Is there a method that gets called or how does it know to create the TextChannel object? Can I also use this in my code like channel = discord.TextChannel(channel_id) or something like that?

south ermine
slender lintel
south ermine
inner iris
#

ok thx

south ermine
stable tiger
hazy loom
ornate fog
# inner iris Can someone please explain me how this works? ```py @bot.command(name="test") as...

Pycord/discord.py is able to look at the type annotations that you give (using the inspect module)
Normal this would only be type hints and do nothing at the runtime lvl.
However since pycord checks at runtime what typehints you provided it is possible for the lib to call a converter that is able to convert the name/channel_id that is provided and retrieve a object of target type (your annotation) from the cache and pass it in as the method parameter instead of the true value the user provided.

This is not magic so it does not work with every object someone needs to write a converter for it you can also write a converter for your custom objects in pycord.

(To give a moire detailed answer)

inner iris
#

It's more a general python question but is there any difference in performance between type(a) is b and isinstance(a, b)? Both ways should always give the same output right? I find the first option actually more readable, so there is the question of the "performance". I know, both of these ways of checking the type are probably nearly equivalent in speed but there has to be a ever so slight difference. So what do you think (or know) is the faster one?

gilded widget
#

pretty sure performance wise there is not much of a difference. however, checking type(a) is b doesn't account for inheritance things while isinstance(a, b) does

inner iris
#

so isinstance checks if b is somewhere in a's inherites types?

gilded widget
inner iris
#

thx

dusty flame
#

Is it possible to use Subcommand groups in cogs, and if so, how?

gilded widget
dusty flame
#

Thanks

dusty flame
#

I'm getting this error with this piece of code await context.respond(f"Playing: {video['title']}")

discord.commands.errors.ApplicationCommandInvokeError: Application Command raised an exception: NotFound: 404 Not Found (error code: 10062): Unknown interaction
#

Could someone please tell me why I'm getting this error?

dusty flame
#

Code:

#search
def search(query):
    with YoutubeDL({'format': 'bestaudio', 'noplaylist': 'True'}) as ydl:
        try:
            requests.get(query)
        except:
            info = ydl.extract_info(f"ytsearch:{query}", download=False)['entries'][0]
        else:
            info = ydl.extract_info(query, download=False)
    return info
#command
...
    @music.command(name="play",description="Plays a song")
    async def play(self, context,*,query):
        member_voice = context.author.voice
        if member_voice and member_voice.channel:
            if context.voice_client:
                pass
            else:
                await member_voice.channel.connect()
            if self.query != []:
                video = search(query)
                emb = discord.Embed(title=f"✅ Queued {video['title']}", color=0xff2700)
                self.query.append(video)
                await context.respond(embed=emb)
            if self.query == []:
                client_voice = context.voice_client
                self.voice_client = context.voice_client
                self.voice_context = context 
                await context.trigger_typing()
                video = search(query)
                source = video['formats'][0]['url']
                emb = discord.Embed(title="Now playing", description=f"[{video['title']}]({video['webpage_url']})\n**Uploader:** {video['uploader']}", color=0xff2700)
                emb.set_thumbnail(url=video['thumbnail'])
                client_voice.play(FFmpegPCMAudio(source,**FFMPEG_OPTIONS,executable=exe))
                self.np = video["title"]
                self.query.append(video)
                await context.send(embed=emb)
                await context.respond("Playing requested song.")
                await gettime(self)
                await nextque(self)
...

The piece of code causing the error is video = search(query). Does anyone know why this is happening?

unique glacier
#

Hello, I just switched to the new update and I was wonderinf if theres a way to use is_owner as a decorator

@bot.slash_command(description="Kill the bot")
@bot.is_owner()
async def kill(self, ctx):
    print("BYE!!! (Killed through command)")
    quit()

Though bot.is_owner seems to be a check that required a user to check against and not a decorator, anyway I could use this as a decorator?

dusty flame
#

While you're finding this out you can just use an if statement to check the user ids

unique glacier
earnest sapphire
#

Is the help team?

#

I need help

sudden path
idle linden
#

!ask

daring flint
#

Er. Am I doing something wrong here?

Trying to use guild.get_channel() or even just trying to browse guild.channels results in the following

AttributeError: 'TextChannel' object has no attribute 'news'
daring flint
# midnight cedar Full traceback?
 Traceback (most recent call last):
[pycharm/ipython stuff]
  File "[python]/site-packages/discord/channel.py", line 190, in __repr__
    attrs = [(val, getattr(self, val)) for val in self._repr_attrs]
  File "[python]/site-packages/discord/channel.py", line 190, in <listcomp>
    attrs = [(val, getattr(self, val)) for val in self._repr_attrs]
AttributeError: 'TextChannel' object has no attribute 'news'

using rc1

midnight cedar
#

I see what's happened

supple ravineBOT
#

discord/channel.py line 711

return super()._repr_attrs + ("news",)```
midnight cedar
#

that shouldn't be there

daring flint
#

git blame

midnight cedar
#

blame bob

dusty flame
#

I'm getting an odd error from my code, could someone please help me?
Code:

@music.command(name="play",description="Plays a song")
    async def play(self, context,*,query):
        member_voice = context.author.voice
        if member_voice and member_voice.channel:
            if context.voice_client:
                pass
            else:
                await member_voice.channel.connect()
            if self.query != []:
                video = search(query)
                emb = discord.Embed(title=f"✅ Queued {video['title']}", color=0xff2700)
                self.query.append(video)
                await context.respond(embed=emb)
            if self.query == []:
                client_voice = context.voice_client
                self.voice_client = context.voice_client
                self.voice_context = context 
                await context.trigger_typing()
                video = search(query)
                source = video['formats'][0]['url']
                emb = discord.Embed(title="Now playing", description=f"[{video['title']}]({video['webpage_url']})\n**Uploader:** {video['uploader']}", color=0xff2700)
                emb.set_thumbnail(url=video['thumbnail'])
                client_voice.play(FFmpegPCMAudio(source,**FFMPEG_OPTIONS,executable=exe))
                self.np = video["title"]
                self.query.append(video)
                await context.send(embed=emb)
                await context.respond("Playing requested song.")
                await gettime(self)
                await nextque(self)

The piece of code that is giving me errors is video = search(query) the code for that is:

def search(query):
    with YoutubeDL({'format': 'bestaudio', 'noplaylist': 'True'}) as ydl:
        try:
            requests.get(query)
        except:
            info = ydl.extract_info(f"ytsearch:{query}", download=False)['entries'][0]
        else:
            info = ydl.extract_info(query, download=False)
    return info
static edge
#

not sure if i'm somehow missing something in the documentation, but is the message returned from wait_for when waiting for the message event NOT supposed to have content? it gives me effectively everything except the content. it's also not an issue of perms, because if i do a fetch with the ID it retrieves the content perfectly fine. small sample of code here:

            msg: discord.Message = await bot.wait_for("message", check=check, timeout=5)
            print("Content", msg.content)
            other_ctx = ctx.channel.get_partial_message(msg.id)
            print("Other content", (await other_ctx.fetch()).content)

For reference i'm not getting the standard msg.content on both whatever build i was previously on as well as rc1

crimson gale
static edge
crimson gale
#

¯_(ツ)_/¯

static edge
#

i'm pretty sure it's a bug but i'd like a second opinion if someone is willing to see if they have the same issue

hollow moth
#

How can I set the default member permissions for a slash command group?

glass nova
#

I use windows and if i try to send audio packets, something happens like this (no idea what missingsentinel is):

  File "C:\Users\hhh\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\voice_client.py", line 905, in send_audio_packet
    encoded_data = self.encoder.encode(data, self.encoder.SAMPLES_PER_FRAME)
AttributeError: '_MissingSentinel' object has no attribute 'encode'
shell tide
#

Im using the new Version of pycord and now the Bot dont create Slashcommands. The bot can create Slashcommands and has Admin Permissions

#

Both commands dont show up

hollow moth
#

If you don't specify commands to be guild specific they're global so take much longer to sync

shell tide
#

i had a command before only for the guild but that didnt worked

#

Even with debug_guilds its not working. iirc It should take a maximum of one hour

low knot
#

how do I set slash commands to only work for the bot owner?

shell tide
crimson gale
#

because outside of a cog you have to use the decorator from the bot object

#

e.g. @bot.slash_command()

#

@shell tide

stable anvil
#

when i click on button it successfully executes the block of code in button_callback but for some reason im getting "This interaction failed" at the end. No errors though.

stable anvil
# stable anvil when i click on button it successfully executes the block of code in button_call...
import discord

class WarPostView(discord.ui.View):
    def __init__(self, bot : discord.Bot) -> None:
        super().__init__(timeout=None)
        self.bot = bot

    @discord.ui.button(emoji="🔴", custom_id="stream", style=discord.ButtonStyle.gray)
    async def stream(self, button : discord.Button, interaction : discord.Interaction) -> None:
        user = interaction.user
        message = interaction.message
        emb : discord.Embed
        for emb in message.embeds:
            for i in emb.fields:
                if(i.name != ":red_circle: Stream") : continue

                if(i.value == "-") : 
                    i.value = user.mention
                    break

                if(user.mention in i.value):
                    i.value = i.value.replace(f"<@{user.id}>","")
                    if(i.value == ""):
                        i.value = "-"
                else: i.value = f"{i.value}\n{user.mention}"
        
        await message.edit(embed=emb,view=self)
crimson gale
#

change the edit line to be await interaction.response.edit_message instead

stable anvil
#

i see let me try that

opal storm
#

whoops accidently replied to u

#

#976366303176716339 ive been waiting for like a whole day noone responded, (this is a re post because I lost the old post and it got archived

fair cradle
opal storm
#

prob a sharex filter

shell tide
kind mesa
#

Is there a new Method to check if a User has a certain Role for a Command?
@discord.has_role() is no longer available

warm tundra
#

how do i send norm text and embed in a single message

opal storm
#

provide both params

warm tundra
#

thanks

opal storm
#

your welcome :D

keen prawn
#

Hey guys I got a question, are cooldowns working for you? Cause mine are not working on latest GitHub Version

hazy loom
#

Hey, I was wondering if there's a way to get the guild out of a VoiceProtocol? I can get the guild thats why i'm asking

keen prawn
#

No, I don't think so

hazy loom
#

Is there a way to get all connected voice clients?

#

I need a way to check if the bot is connected to a channel

#

Like any channel is a guild