#discord-bots

1 messages · Page 721 of 1

slate swan
#

discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: 'str' object is not callable

#

I dont want to use that

sage otter
forest blade
#

!d discord.ext.commands.Bot.get_command

unkempt canyonBOT
#

get_command(name)```
Get a [`Command`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command") from the internal list of commands.

This could also be used as a way to get aliases.

The name could be fully qualified (e.g. `'foo bar'`) will get the subcommand `bar` of the group command `foo`. If a subcommand is not found then `None` is returned just as usual.
heavy folio
#

im trynna make the ban command's "days" argument optional, and it has to be an int, the thing is if someone skips the day arg and goes to the member arg (str), it'll raise ```py
discord.ext.commands.errors.BadArgument: Converting to "int" failed for parameter "days".

async def ban(self, ctx, member: discord.Member, days=1, *, reason: str="No reason provided")
```
slate swan
#

you cannot just skip it ...

#

you may like typehinting days with a union of int and str , and check if day is int or not

#
async def ban(self , ctx , member : discord.Member, days = Union[int , str], reason = "No reason"):
   if isinstance(days , int ): # day in numbers was provided
   else : # nah ```
#

Union here is typing.Union ^

#

and ill assume you are talking about the reason argument , not member , since its before the days arg

heavy folio
#

oh

maiden fable
#

@heavy folio u can also use commands.Greedy

#

!d discord.ext.commands.Greedy

unkempt canyonBOT
#

class discord.ext.commands.Greedy```
A special converter that greedily consumes arguments until it can’t. As a consequence of this behaviour, most input errors are silently discarded, since it is used as an indicator of when to stop parsing.

When a parser error is met the greedy converter stops converting, undoes the internal string parsing routine, and continues parsing regularly.

For example, in the following code:

```py
@commands.command()
async def test(ctx, numbers: Greedy[int], reason: str):
    await ctx.send("numbers: {}, reason: {}".format(numbers, reason))
```  An invocation of `[p]test 1 2 3 4 5 6 hello` would pass `numbers` with `[1, 2, 3, 4, 5, 6]` and `reason` with `hello`...
heavy folio
#

oh yeahh

#

im using the second method but ChannelNotFound keeps getting raised, the message id i used was in the context channel tho,
does this depend on cache or... because i just used a message id in channel a, and it doesnt work, i did it again and it worked, now when i use it in channel b, it doesnt work

heavy folio
#
async def mock(self, ctx, message: discord.Message):
``````discord.ext.commands.errors.ChannelNotFound: Channel "None" not found.```
#

the rest of the stuff in the function are just embeds and ctx.send

slate swan
heavy folio
#

wdym

#

no i typehinted it to be a discord.Message so idt there's a need to fetch it

slate swan
heavy folio
slate swan
heavy folio
#

i dont want it to be limited to the context channel only

slate swan
#

Hmm, well, you need the channel id the message wasnt sent in

soft lynx
#
      await ctx.send(",".join([ctx.guild.get_role(role_id).mention for role_id in role_ids if len(ctx.guild.get_role(role_id).members) == 0])or "no"))

how can i place the ",".join(...) inside of an embed?

slate swan
soft lynx
#

gotcha thanks

slate swan
soft lynx
#

lol

woven ingot
#

Ok im implementing a code similar to this but I want to turn off the first command. I only want commands with 2 words to work. What would be the best way to implement something like this

#
@client.group(invoke_without_command = True) # for this main command (.help)
async def help(ctx):
    await ctx.send("Help! Categories : Moderation, Utils, Fun")

@help.command()   #For this command (.help Moderation)
async def Moderation(ctx):
    await ctx.send("Moderation commands : kick, ban, mute, unban")```
#

So i want to make a comand group but I want only the comands with 2 words like .help Moderation to work

#

I don't want .help to trigger anything

#

I will have sevral bots using something simialar but they will all have diffrent words that will trigger the command the problem is they all share the same first word wich will be convert

#

So that's why I dont want the first comand to work because using !convert would trigger all the bots at once.

#

Can I have a command group but have the first function with only one word not trigger anything?

#

would implementing something like this resolve the issue?

#
client.remove_command("help")
#

Does this even work

#

Or will this turn off all the comand groups that use the workd help

slate swan
#

its better to subclass the help command tho

#

!d discord.ext.commands.HelpCommand

unkempt canyonBOT
#

class discord.ext.commands.HelpCommand(*args, **kwargs)```
The base implementation for help command formatting.

Note

Internally instances of this class are deep copied every time the command itself is invoked to prevent a race condition mentioned in [GH-2123](https://github.com/Rapptz/discord.py/issues/2123).

This means that relying on the state of this class to be the same between command invocations would not work as expected.
woven ingot
slate swan
#

!d pass

unkempt canyonBOT
#

7.4. The pass statement


pass_stmt ::=  "pass"
``` [`pass`](https://docs.python.org/3/reference/simple_stmts.html#pass) is a null operation — when it is executed, nothing happens. It is useful as a placeholder when a statement is required syntactically, but no code needs to be executed, for example:

```py
def f(arg): pass    # a function that does nothing (yet)

class C: pass       # a class with no methods (yet)
woven ingot
#

Oh ok awesome

#
@client.group(invoke_without_command = True) # for this main command (.help)
async def help(ctx):
    pass_stmt ::=  "pass"
@help.command()   #For this command (.help Moderation)
async def Moderation(ctx):
    await ctx.send("Moderation commands : kick, ban, mute, unban")```
woven ingot
woven ingot
#

Or can i just use pass

#
@client.group(invoke_without_command = True) # for this main command (.help)
async def help(ctx):
    pass
@help.command()   #For this command (.help Moderation)
async def Moderation(ctx):
    await ctx.send("Moderation commands : kick, ban, mute, unban")```
#

??

small igloo
#

vote system?

slate swan
crude crater
crude crater
slate swan
soft lynx
#

how do i utilize args for slash cmds?

@Slash.slash(...
options=[
           create_option(
                 name="continent",
                 description="Choose your continent.",
                 required=True,
                 option_type=3,
                 choices=[
                   create_choice(
                     name="North America",
                     value="hi"
                   ), ...

could i then do smthing like

async def view(ctx: SlashContext, continent: str=None):
if value == "hi":

or, is there another way to use args

crude crater
slate swan
sage otter
slate swan
#

i thought they got something to say

sage otter
#

They definitely don’t and never will 👌

#

Certified troller

slate swan
#

lol ic

woven ingot
#

I was also waiting for an answer. Kinda wack to troll on a channel where people are looking for help

woven ingot
crude crater
slate swan
#

erm why is it not running

gloomy cloud
slate swan
boreal ravine
#
    @commands.Cog.listener()
    async def on_message(self, message: disnake.Message):

        prefix = await self.database.find_one({'_id': message.guild.id})

        if message.content == f'<@{self.bot.user.id}>' or message.content == f'<@{self.bot.user.id}>':
            await message.reply(
                f'Hey! My prefix for this server is `{prefix["prefix"]}`.',
                mention_author=False
            )
``` tryna make my bot to reply when it gets pinged, isnt working for some reason, no errors.
boreal ravine
gloomy cloud
lament mesa
boreal ravine
#

is that wrong?

lament mesa
#

its not wrong, pings can be <@{id}> or <@!{id}>

boreal ravine
#

o

#

brb

#

@lament mesa thanks the bot had a nickname

lament mesa
#

👍

shadow wraith
#

give me command ideas

slate swan
boreal ravine
#

no

#

your bot token

#

using your own token is against ToS

shadow wraith
#

🤦‍♂️ bro did you copy code why'd you write token there

#

your meant to put your token in a variable, env, or as a string

slate swan
shadow wraith
#

ye

#

you copied it now x]

#

now remove that TOKEN from client.run

#

and add '<copy_paste_here>' as the string for client.run()

#

istg if you know how to make embeds you should probably know how to make the bot run

slate swan
#

nvm i will change my token later

boreal ravine
slate swan
#

"

#

like tat? erm

boreal ravine
boreal ravine
#

?

boreal ravine
slate swan
#

oh sry i saw wrongly

verbal cairn
#

anyone know how to make it so u can ping a specific role

slate swan
#

wait ah

boreal ravine
slate swan
boreal ravine
boreal ravine
#

now run your bot ig

slate swan
#

still not working

shadow wraith
#

show your client variable

#

@slate swan show your client variable

slate swan
#
import random
import discord.ext


client = discord.Client()

@client.event
async def on_ready():
  print('hi {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)
  print(f'{username}: {user_message} ({channel})')

  if message.author  == client.user:
    return

  if message.channel.name == 'my_channel':
    if user_message.lower() == 'hello':
      await message.channel.send(f'hello mdfk {username}')
      return
    elif user_message.lower() == '!random':
      response = f'ur random num: {random.randrange(100)}'
      await message.channel.send(response)
      return

  

  elif user_message.lower() == 'random':
      response = f'ur random num: {random.randrange(100)}'
      await message.channel.send(response)
      return





  if message.content.startswith('$invite'):
    await message.author.send('https://discord.com/oauth2/authorize?client_id=920313284920488017&permissions=534723950662&scope=bot')
    return



@client.command()
async def embed(ctx):
  embed = discord.Embed(title="how to make an discord embed", url="https://www.youtube.com/watch?v=UoROS78Vtr4", description="this is tutorial", color=0x8ceb34)
  await ctx.send(embed=embed)

client.run("i will change my token later")```
#

@shadow wraith

shadow wraith
#

bro why you have elif statement but using if after

torn sail
#

You can’t make commands with discord.Client

shadow wraith
#

^

#

that's why i asked, a uppercased C in a client means something is wrong, that's why i asked

slate swan
#

erm so i need to do wat

flint jetty
#

Hello, I have a question.
Is there a way to disable the select(dropdown) of a message when the interaction timesout in discord.ui.Select using on_timeout?
(this question applies to discord.py 2.0, nextcord and pycord)

loud junco
#

can anyone help me with my bot?
dm me i send u the source link

flint jetty
loud junco
#

idk how to tell

#

idk why my pc cant screenshot also

#

can i dm u?

flint jetty
knotty gazelle
flint jetty
#

yes, but on doing that, it just makes it so it will say "interaction failed", it dosent "disable" the dropdown

knotty gazelle
#

Wait ill look into my code

flint jetty
#

this is what i mean from "disabled" dropdown, timeout dosent do this

knotty gazelle
#

Oh

#

Do you use nextcord

flint jetty
#

i use pycord, but dropdowns are same in both pycord and nextcord since both are a fork of discord.py 2.0

slate swan
#

this remains same for all forks^

knotty gazelle
#

Try: {className}.disabled = True

loud junco
#

can someone help me? dm me
i send u the link(not free nitro :/)

knotty gazelle
#

Why in dms?

slate swan
#

!d discord.ui.View.children , you need to use this kavoya , and .disabled=True

unkempt canyonBOT
loud junco
loud junco
#

window shift s not working

slate swan
#

use snipping tool , or copy paste code

loud junco
#

and the error is HUGEEEE

slate swan
#

!paste

unkempt canyonBOT
#

Pasting large amounts of code

If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pythondiscord.com/

After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.

loud junco
#

i mean

knotty gazelle
#

Do this

loud junco
#

!paste

#

ok

knotty gazelle
#
import discord
from discord.ext import commands
loud junco
knotty gazelle
unkempt canyonBOT
#

Pasting large amounts of code

If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pythondiscord.com/

After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.

loud junco
knotty gazelle
#

??

loud junco
#

LOL

#

local variable 'emote' defined in enclosing scope on line 8 referenced before assignment

#

it shouldnt be error

#

=.=

slate swan
#

is emote a folder ,or a python file?

loud junco
#

python file

slate swan
#

and emote is some function / class inside it?

knotty gazelle
#

can you put it in github so we can see it

loud junco
slate swan
loud junco
slate swan
loud junco
#

oo ok

#

emoji also cant

slate swan
#

local variable 'emote' defined in enclosing scope on line 8 referenced before assignment
is the error yoy get right?

loud junco
#

what else can i put =.=

#

ya

slate swan
#

my_emojis probably

loud junco
#

ok

slate swan
#

or anything u want

loud junco
#

my_emote can right?

slate swan
#

yea ig

loud junco
#

still the same

#

local variable 'my_emote' defined in enclosing scope on line 8 referenced before assignment

slate swan
#

show the function

loud junco
#

i just changed the name

slate swan
#

thats not how global variables work

loud junco
#

:/

#

then what should i change

shadow wraith
#

thank you bot, very helpful

#

this is my code:

@bot.command(aliases=["8ball"])
@commands.guild_only()
@commands.cooldown(1, 3, BucketType.default)
async def eightball(ctx, *, question):
    async with aiohttp.ClientSession as session:
        request = await session.get("https://8ball.delegator.com/magic/JSON/e")
        request1 = await request.json()
    randomAnswer = random.choice(request1.get("magic").get("answer"))
    embed = disnake.Embed(
        title=question + "?",
        description=randomAnswer + ".",
        color=disnake.Colour.random(),
    )
    await ctx.send(embed=embed)  # gentle 8ball command.
#

anyone wonder why this aenter issue is coming?

boreal ravine
#

that error usually raises with context managers

unkempt canyonBOT
#
class aiohttp.ClientSession(base_url=None, *, connector=None, cookies=None, headers=None, skip_auto_headers=None, auth=None, json_serialize=json.dumps, ...)```
The class for creating client sessions and making requests.
boreal ravine
#

It's a method

#

Not a property

shadow wraith
#

i eventually figured that out

boreal ravine
#

Nice

shadow wraith
#

but now apparently the embed is sent super slow, and like, the answer which is showing is blank or just u

hoary crest
#

Is it possible to use 1 @bot.command() code block and have multiple names and respective command_alias with the same block

boreal ravine
hoary crest
#

No.

Multiple commands names

#

Like i want to use the same code block but different names.

#

name="barrows1", command_alias=["barrow1","bro1"],

name="barrows2", command_alias=["barrow2","bro2"],

name="barrows3", command_alias=["barrow3","bro3"]

)```
#

something like this?

boreal ravine
#

that wont work

#

command_alias isn't a thing

hoary crest
#

ok

slate swan
#

how do I use aiohttp and send data to a site and then the send the output of the site in the discord bot's output?

loud junco
#

;-;

slate swan
loud junco
#

!paste

unkempt canyonBOT
#

Pasting large amounts of code

If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pythondiscord.com/

After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.

loud junco
#

local variable 'my_emote' defined in enclosing scope on line 8 referenced before assignment

#

help

slate swan
#

I can't find the error here

@bot.command(aliases=['clean', 'purge'])
async def clear(ctx, n=0):
  if n <= 0:
    await ctx.send("Please add the amount of messages to delete")
  else:
    await ctx.channel.purge(limit=int(n))
    cembed = discord.Embed(title='Done!')
    cembed.add_field(name='Deleted Messages:', value=f'{n}', inline=False)
  cembed.set_author(name=ctx.author.display_name, icon_url=ctx.author.avatar_url)
cembed.timestamp = datetime.datetime.utcnow()
    await ctx.send(embed=cembed)
maiden fable
#

Mind telling the error?

slate swan
#

Wait

#

Unexpected indent

maiden fable
#

!indent

unkempt canyonBOT
#

Indentation

Indentation is leading whitespace (spaces and tabs) at the beginning of a line of code. In the case of Python, they are used to determine the grouping of statements.

Spaces should be preferred over tabs. To be clear, this is in reference to the character itself, not the keys on a keyboard. Your editor/IDE should be configured to insert spaces when the TAB key is pressed. The amount of spaces should be a multiple of 4, except optionally in the case of continuation lines.

Example

def foo():
    bar = 'baz'  # indented one level
    if bar == 'baz':
        print('ham')  # indented two levels
    return bar  # indented one level

The first line is not indented. The next two lines are indented to be inside of the function definition. They will only run when the function is called. The fourth line is indented to be inside the if statement, and will only run if the if statement evaluates to True. The fifth and last line is like the 2nd and 3rd and will always run when the function is called. It effectively closes the if statement above as no more lines can be inside the if statement below that line.

Indentation is used after:
1. Compound statements (eg. if, while, for, try, with, def, class, and their counterparts)
2. Continuation lines

More Info
1. Indentation style guide
2. Tabs or Spaces?
3. Official docs on indentation

slate swan
#

Aham

#

I can't find where should the await be placed

vale wing
#

Does View raise any exceptions on timeout?

#

I mean like how to handle timeout outside of on_timeout

slate swan
#

how do i make it so it can be multiple channels that get the welcome messages

#

etc for multiple servers

vale wing
#

Store welcome channels ids somewhere and access them

tawdry perch
#

to make OAuth2 url, does it need to be authorised?

#

I mean, it seems like I can't use local host http://127.0.0.1:5001/

sacred lodge
#

🤔

#

Was there a pingerino?

slate swan
#

looking for someone with same name as u

sacred lodge
#

Oh

loud junco
slate swan
#

What are people using to build a discord bot in python now that discord.py is archived?

serene lynx
#

how to solve this?

serene lynx
# serene lynx how to solve this?
2021-12-31T10:51:47.234622+00:00 app[worker.1]: discord.errors.HTTPException: 429 Too Many Requests (error code: 0): You are being blocked from accessing our API temporarily due to exceeding our rate limits frequently. Please read our docs at https://discord.com/developers/docs/topics/rate-limits to prevent this moving forward.
loud junco
#

its rate limit, not an error

#

u just gotta wait for some time

loud junco
#

try not to leave an error before letting it run itself for few hours

#

cuz it will restart non stop for that time

#

and thats how u get rate limited i guess

serene lynx
loud junco
#

then im not sure

#

btw

shadow wraith
serene lynx
loud junco
#

i doesnt mean this one

slate swan
#

How can I fix that???

loud junco
#

embed not hembed

#

:/

dapper cobalt
slate swan
#

With this? '

loud junco
#

@slate swan

slate swan
dapper cobalt
slate swan
dapper cobalt
#

Both ' and " are strings.

slate swan
#

This isn't error

#

I fixed it

dapper cobalt
#

url="https://..."

slate swan
#

Ty

serene lynx
slate swan
#

why isnt this working ;-;

    for filename in os.listdir('./cogs'):
        if filename.endswith('.py'):
            client.load_extension(f"cogs.{filename[:-3]}")    
shadow wraith
shadow wraith
slate swan
#
class Add_data(commands.Cog):
    def __init__(self, client):
        self.client = client

def setup(client):
    client.add_cog(Add_data(client))

and my filename is add.py

manic wing
#

@dapper cobalt

#

wanna join a project we’re in?

velvet tinsel
#

bro

#

i thought you said "DM"

dapper cobalt
manic wing
#

10 or so

dapper cobalt
#

Send me a friend request.

honest vessel
#

@slate swan client dosnt have cogs

slate swan
#

how can i add a code block in a field?

shadow wraith
#

!code

unkempt canyonBOT
#

Here's how to format Python code on Discord:

```py
print('Hello world!')
```

These are backticks, not quotes. Check this out if you can't find the backtick key.

tawdry perch
#

can someone explain where did this come from?

shadow wraith
#

anyways why can't others react, only the author of the command can react and change it, how can i make it so anyone can react?

@bot.command()
@commands.guild_only()
@commands.cooldown(1, 3, BucketType.default)
async def rhyme(ctx, *, word):
    try:

        def check(r: disnake.Reaction, u: Union[disnake.Member, disnake.User]):
            return u.id == ctx.author.id and r.message.channel.id == ctx.channel.id

        async with aiohttp.ClientSession() as session:
            newword = quote_plus(word)
            Api = await session.get(f"https://api.datamuse.com/words?rel_rhy={newword}")
            API = await Api.json()

            randomWord = random.choice(API).get("word")
            __what_rhymes__ = await ctx.reply(
                f"Word: {word}\nWhat rhymes: {randomWord}"
            )
            await __what_rhymes__.add_reaction("🔄")
            while 1:
                try:
                    event = await bot.wait_for(
                        "reaction_add", check=check, timeout=30.0
                    )
                except asyncio.TimeoutError:
                    break
                except IndexError:
                    await ctx.reply("No more rhyming words can be found. :(")
                else:
                    newWord = random.choice(API).get("word")
                    if str(event[0].emoji) == "🔄" and not event[1].bot:
                        await __what_rhymes__.edit(
                            content=f"Word: {word}\nWhat rhymes: {newWord}"
                        )
                    else:
                        pass

    except IndexError as ie:
        await ctx.reply(f"There are no words rhyming with {word} :(")
shadow wraith
tawdry perch
#

what?

shadow wraith
#

you hovered over a module's name

tawdry perch
#

that's the place where the error comes from

shadow wraith
#

i don't see the error

slate swan
#

Will I get banned if I try to change role colors every 10 mins? (ping me)

shadow wraith
#

wait i see it now

slate swan
slate swan
slate swan
shadow wraith
#

how do i check if a file is uploaded to a command use for exaxmple uploading an image and having the text above it be like >rotate <degrees>, i know how to rotate the img just wondering how i can get the image

craggy cloak
#
    @commands.command(aliases=['av'])
    async def avatar(self,ctx, member: discord.Member = None):
      if member == None:
        member = ctx.author

      embed = discord.Embed(title=f"Avatar for {member.name}",description=f"**Link as**\n[png]({member.avatar.url.as(format='png', size=1024)}) | [jpg]({member.avatar.url.as(format='jpg', size=1024)}) | [webp]({member.avatar.url.as(format='webp', size=1024)})", colour=discord.Color.blurple())
      embed.set_image(url=member.avatar.url)
      await ctx.send(embed=embed)

#

No error? But the bot don't send the embed?

slate swan
craggy cloak
#

discord color?

#

There is something rong with this

#
member.avatar_url_as

#

member.avatar.url.as

slate swan
craggy cloak
#

2.00

slate swan
#

look in the docs about formatting tbh, i've got no clue

cobalt slate
#

salut

#

s'il vous plait qui maîtrise le langage Golang ici ??

#

hi here
please who is fluent in golang language here ??

vocal plover
oak warren
#

hey i am making something related to leveling and i have this in a cog

 else:
                xp = stats["xp"] + random.randint(30, 50)
                collection_name.update_one(
                    {"id": message.author.id}, {"$set": {"xp": xp}})

                lvl = math.floor(0.1 * math.sqrt(xp))
                nlvl = lvl + 1
                xpnxtlevl = (100 * nlvl * nlvl) - (100 * lvl * lvl)
                if (xp - (100 * lvl * lvl)) >= xpnxtlevl:
                    embed = discord.Embed(title="🏆 LEVEL UP! 🎉",
                                        description=f"Congratulations **{message.author}**!\nYou've leveled up to level **{nlvl}** 🎉",
                                        color=discord.Color.red())
```but when i level up it doesnt send the message
untold token
#

Because you aren't sending the message.....?

#

you need to send the embed

shadow wraith
#

how do you send a file

#

in discord bot

#

because i have this image manipulator command which uses PIL for it but i got stuck on how to send a file, this is my code:

@bot.command()
@commands.guild_only()
@commands.cooldown(1, 3, BucketType.default)
async def rotate(
    ctx: commands.Context, degrees: int = 90, image: disnake.File = "amongus"
):
    os.chdir("/Users/sadancooler/Documents/Code/Python/bots/infinity/images/")
    with open(f"{image}.png", "w"):
        if image == "amongus":
            __image__ = Image.open("amongus.png")
            __image__.convert(degrees).save("amongus.png")
maiden fable
#

Just use discord.File

#

!d discord.File

unkempt canyonBOT
#

class discord.File(fp, filename=None, *, spoiler=False)```
A parameter object used for [`abc.Messageable.send()`](https://discordpy.readthedocs.io/en/master/api.html#discord.abc.Messageable.send "discord.abc.Messageable.send") for sending file objects.

Note

File objects are single use and are not meant to be reused in multiple [`abc.Messageable.send()`](https://discordpy.readthedocs.io/en/master/api.html#discord.abc.Messageable.send "discord.abc.Messageable.send")s.
oak warren
gentle rose
#

How to copy ID of the animated emoji in discord? If i don't have discord nitro kekw

visual island
#

On desktop:

  1. Open emojis tab
  2. Press cntrl + shift + i
  3. Press select element (the thing in the upper left corner)
  4. Click the emoji you want using the select element
  5. It will redirect you to a html code
  6. Right click and select edit HTML
  7. you will see the id there
rancid stump
#

Is there anyone who have made a discord bot that accept usdt or trx as crypto ???
Can you tell me how you do it ???

gentle rose
#

merry4 is the name of emoji

#

after : - ID of the emoji

untold token
#

Ye

untold token
#

Also
<"emoji_name": emoji_id>

#

What does this show?

gentle rose
untold token
#

Ah guessed so

#

hmm maybe try putting the id in quotes too

#

Dunno if that matters but try it

gentle rose
#

oh

#

i figured out

untold token
#

Ah nice

gentle rose
#

I forgot a before emoji name

untold token
#

oh

gentle rose
#

solution - <a : merry4:924255066649669652>

untold token
#

Ah ye

gentle rose
#

without spaces after a and before merry4

stark fog
#

Hello

#

I keep running into a few errors with my code

#

It's for a levelling bot

#

lemme get the code real quick

#

Here are the errors:

shadow wraith
#

it's urllib i think

slate swan
#

Yeah
read as url-lib

stark fog
#

yeah

#

but that also brings up some errors

#

Also, I dont understand why it brings up an error for import levelsys

#

also, I haven't used the word 'lifetime' anywhere

grand shell
#

hey, im trying to find the guild object from an ID in a cog. I wrote this but self.adminGuild = None

    def __init__(self, client: commands.Bot):
        self.client = client

        self.adsSent = 0
        self.embedInd = 0

        self.embeds = [self.get_adEmbed(), self.get_servEmbed()]

        self.adminGuild = self.client.get_guild(int(925459999856136263))
        print(self.adminGuild)
        self.errorChan = self.adminGuild.get_channel(int(926482390132596736))
        self.adsLogChan = self.adminGuild.get_channel(int(926483060411756614))

does anyone know what Im doing wrong?

#

ah i worked it out!

#

the bot needs to be ready so the server is in the cache or something i think

#

so i moved that to a on_ready event

#

is that the best way to fix it?

slate swan
#

Is galaxy gate trust worthy

#

To host my bot

stark fog
#

imo using an rpi is the best

hollow plover
#

hello im making a commadnd for rps (rock paper scissors) game and want to use discord.ui.button this is what i have but not sure how to get exactly what button label/ choice of rock paper scissors they chose . How do you do this?

#

pls help im stressed

ebon island
#

What is the best solution to having as close a blank name field in an embed?

hollow plover
#

\u200b

hollow plover
ebon island
#

I'm going to try it 🙂

#

The other ones I have tried so far haven't worked just yet

#

Awesome! That worked, thanks Krafty

#

Is there a way to make an embed message use more horizontal space?

hollow plover
#

ur embed looks something like this right?

embed.add_field(name="something", value="content") right?

ebon island
#

so this is the output right now

#

and yes

hollow plover
#

so they are all name elements right

ebon island
#

I want it to look cleaner/more uniform

#

No they are values

#

the name value is the alt code you gave above

hollow plover
#

i dont actually know that much about embeds but a dumb way to do this would probably be try using diferent amounts of spaces

#

if that doesnt work then use name instaead of value

ebon island
#

that isn't a possible solution since the words change

hollow plover
#

oh right

ebon island
#

I'll try using name instead of value

hollow plover
#

yea cos my help command for my bot is relatively well aligned without uing spacs and that

ebon island
#

looks maybe a little better like this but still not perfect

hollow plover
#

hmmm

#

idk really the problem is just with the "visit" part tbh

#

im sorry i couldnt help on that one :(

ebon island
#

Is there a header field?

#

or similar? If so perhaps it could push the words down and maybe they would align better

potent spear
# ebon island

add values to the fields, maybe they'll align themselves,don't worry just yet

ebon island
#

I have values as \u200b character

hollow plover
#

u can have a look at discord.Embed in docs

#

!d discord.Embed

unkempt canyonBOT
#

class discord.Embed(*, colour=Embed.Empty, color=Embed.Empty, title=Embed.Empty, type='rich', url=Embed.Empty, description=Embed.Empty, timestamp=None)```
Represents a Discord embed.

len(x) Returns the total size of the embed. Useful for checking if it’s within the 6000 character limit.

bool(b) Returns whether the embed has any data set.

New in version 2.0.

Certain properties return an `EmbedProxy`, a type that acts similar to a regular [`dict`](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.9)") except using dotted access, e.g. `embed.author.icon_url`. If the attribute is invalid or empty, then a special sentinel value is returned, [`Embed.Empty`](https://discordpy.readthedocs.io/en/master/api.html#discord.Embed.Empty "discord.Embed.Empty").

For ease of use, all parameters that expect a [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)") are implicitly casted to [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)") for you.
ebon island
#

I'm looking there already haha

#

I'm going to try all the different options

heavy folio
#

is there a way to set the default invite url for the bot (so i can always access it)

ebon island
#

If I want to do something like image or set_image what is the syntax to use them?

hollow plover
#

embed.set_image i think

ebon island
#

and what about calling it? It has two separate methods

hollow plover
#

wdym calling it

#

just set_image then await ctx.send(embed=embed)

#

embed being ur discord.Embed thing name

#

i gtg now srry i couldnt help tht much

shadow wraith
#

how do i get the clicker of the button

hollow plover
#

bruh thanks python

#

its something like that

#

i gtg bye

heavy folio
unkempt canyonBOT
hollow plover
#

there we go

ebon island
#

Hmm this is odd -

self.client.embed_widener = 'https://cdn.discordapp.com/attachments/544302254694465547/926497254611759135/unknown.png'
embed.set_image(self.client.embed_widener)

set_image method takes one arg, url, but when I try to run the code as above I get:

Embed.set_image() takes 1 positional argument but 2 were given
shadow wraith
#

so discord.Interaction.author is the one that like uhh

#

@heavy folio what's the difference between discord.Interaction.author and discord.Interaction.user

heavy folio
#

it doesnt exist?

#

interaction.user is the "author"

shadow wraith
#

ohh wait that's disnake lmfao

#

!d disnake.Interaction.author exists lmfao

unkempt canyonBOT
shadow wraith
heavy folio
shadow wraith
#

ok but how pass ctx as an argument. self.ctx = commands.Context?

heavy folio
#

instance of ctx, not the class object

#

figure it out, pass ctx as an arg in __init__ and self.ctx = <instance of ctx>

shadow wraith
#

ohh, fuck i get it now

#

oh fuck i got an error now

wild tangle
#

how was the command to encode

#

I forgot it

ebon island
#

is it possible to do an in line if statement for the values of a tuple?

#

here's my attempt lol

('Burst Count:', server.burst_count if server.cypher_mode == 'burst' else 'Word Count:', server.word_count)
boreal ravine
wild tangle
#

the code ig?

#

what should i encode my life?

glacial kernel
#

Does anyone know what code is needed for my bot to assign posts by reaction?

slate swan
#

!d discord.on_reaction_add

#

nvm

unkempt canyonBOT
#

discord.on_reaction_add(reaction, user)```
Called when a message has a reaction added to it. Similar to [`on_message_edit()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_message_edit "discord.on_message_edit"), if the message is not found in the internal message cache, then this event will not be called. Consider using [`on_raw_reaction_add()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_raw_reaction_add "discord.on_raw_reaction_add") instead.

Note

To get the [`Message`](https://discordpy.readthedocs.io/en/master/api.html#discord.Message "discord.Message") being reacted, access it via [`Reaction.message`](https://discordpy.readthedocs.io/en/master/api.html#discord.Reaction.message "discord.Reaction.message").

This requires [`Intents.reactions`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.reactions "discord.Intents.reactions") to be enabled.

Note

This doesn’t require [`Intents.members`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.members "discord.Intents.members") within a guild context, but due to Discord not providing updated user information in a direct message it’s required for direct messages to receive this event. Consider using [`on_raw_reaction_add()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_raw_reaction_add "discord.on_raw_reaction_add") if you need this and do not otherwise want to enable the members intent.
ebon island
#

How do I get the list of commands available to my discord.py?

glacial bridge
#

What version are you using? You can check the docs

glacial kernel
#

its not working

#

can you type it into this code pls

slate swan
#

use the add_role method

#

on the user parameter

vale wing
#

why

await ctx.send(str(bot.http.__session.headers))
AttributeError: 'HTTPClient' object has no attribute '__session'```
ebon island
#

it was Bot.commands

glacial kernel
agile goblet
slate swan
slate swan
#

most people use disnake so...

slate swan
glacial kernel
#

My problem is to put this in the code so it works

grand shell
#

hey! iv hosted my bot with heroku and github. In the bot, different json files are edited. How does this work? it doesnt change the github repo so does it just change it temporarily until its redeployed?

glacial kernel
agile goblet
#

cheers

glacial kernel
glacial kernel
#

Does anyone know what code is needed for my bot to assign posts by reaction?

#

this is my problem

#

and I dont know how to fix it

slate swan
slate swan
glacial kernel
#

I just want to know whats wrong with my code

slate swan
#

you use the add_roles method for that

#

!d discord.Member.add_roles

unkempt canyonBOT
#

await add_roles(*roles, reason=None, atomic=True)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Gives the member a number of [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role")s.

You must have the [`manage_roles`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.manage_roles "discord.Permissions.manage_roles") permission to use this, and the added [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role")s must appear lower in the list of roles than the highest role of the member.
glacial kernel
#

ok I will try it one sec

#

but I just want to give the role if someone reacts to the message

glacial kernel
slate swan
#

@glacial kernel

slate swan
wraith torrent
slate swan
#

replit shows all the html content

glacial bridge
wraith torrent
#

dude didn’t even run a single command lol

slate swan
glacial bridge
#

It’s not a dpy issue, it’s a replit issue

wraith torrent
#

I see

glacial bridge
#

Here’s from official dpy server

slate swan
glacial kernel
# slate swan <@!691789249913159722>
@bot.event
async def on_reaction_add(reaction, user):
    guild = ctx.guild
    postrole = discord.utils.get(guild.roles, id=925783050984505385) 
    if reaction.emoji == ":unlock:":
        await add_roles(postrole, reason=None, atomic=True)

It says ctx is not defined

wraith torrent
#

Add ctx into the parameters

glacial kernel
#

ok

slate swan
slate swan
glacial kernel
# slate swan reaction.guild*, and user.add_roles
@bot.event
async def on_reaction_add(reaction, user, ctx):
    guild = reaction.guild
    postrole = discord.utils.get(guild.roles, id=925783050984505385) 
    if reaction.emoji == "🔓":
        await user.add_roles(postrole, reason=None, atomic=True)
#

It says on_reaction_add() missing 1 required positional argument: 'ctx'

rotund nova
#

ale ze ashley

maiden fable
glacial kernel
#
@bot.event
async def on_reaction_add(reaction, user):
    guild = reaction.guild
    postrole = discord.utils.get(guild.roles, id=925783050984505385) 
    if reaction.emoji == "🔓":
        await user.add_roles(postrole, reason=None, atomic=True)
#

like this?

maiden fable
#

Yups

soft lynx
#

is there a has role attribute for slash cmds?

maiden fable
soft lynx
maiden fable
#

U can do if <role> in interaction.author.roles replacing the role with the actual role object

soft lynx
#

alright, thanks

maiden fable
#

Or u can also use utils.get, but that's sometimes slow

glacial kernel
soft lynx
maiden fable
glacial kernel
maiden fable
maiden fable
glacial kernel
#

ok

glacial kernel
maiden fable
#

(:

glacial kernel
#

by now you know what command is needed to alert the outputs

maiden fable
#

???

glacial kernel
#

on_member_join

#

this is the command to alert when someone enters which command to alert when someone exits

maiden fable
#

!d discord.on_member_remove

unkempt canyonBOT
#

discord.on_member_join(member)``````py

discord.on_member_remove(member)```
Called when a [`Member`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member "discord.Member") leaves or joins a [`Guild`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild "discord.Guild").

This requires [`Intents.members`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.members "discord.Intents.members") to be enabled.
glacial kernel
#

thank you

maiden fable
#

(:

soft lynx
#

how do i make a slash command where the argument is a role?

#

i know how to make a slash command, i just dont know how to create role choices under an option

lyric tusk
#

how can i fix xD
my code:

@client.event
async def on_member_join(member):
    with open('welcome.json', 'r', encoding='utf-8') as f:
        welcome_dict = json.load(f)
    for channel in member.guild.channels:
        welcome_dict(member.channel.guild.id)
        embed = discord.Embed(color=0x4a3d9a)
        embed.add_field(name="Welcome", value=f"{member.name} has joined {member.guild.name}", inline=False)
        embed.set_image(url="https://media.giphy.com/media/f4V2mqvv0wT9m/giphy.gif")
        await channel.send(embed=embed)


@client.command(name='setwelcomechannel')
async def setwelcomechannel(ctx, channel: discord.TextChannel):
    with open('welcome.json', 'r', encoding='utf-8') as f:
        welcome_dict = json.load(f)

    welcome_dict[str(ctx.guild.id)] = str(channel.id)
    with open('welcome.json', 'w', encoding='utf-8') as f:
        json.dump(welcome_dict, f, indent=4, ensure_ascii=False)
    
    await ctx.send(f'Sent welcome channel for {ctx.message.guild.name} to {channel.name}')

@client.event
async def on_guild_remove(guild):
    with open('welcome.json', 'r', encoding='utf-8') as f:
        welcome_dict = json.load(f)

    welcome_dict.pop(guild.id)
    with open('welcome.json', 'w', encoding='utf-8') as f:
        json.dump(welcome_dict, f, indent=4, ensure_ascii=False)

my error:

Ignoring exception in on_member_join
Traceback (most recent call last):
  File "C:\Users\wedaa\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\client.py", line 343, in _run_event
    await coro(*args, **kwargs)
  File "c:\Users\wedaa\Desktop\discordbot\me code.py", line 62, in on_member_join
    for channel in member.guild.channel:
AttributeError: 'Guild' object has no attribute 'channel'
slate swan
#

u didnt save the file before running

lyric tusk
#

i did save

slate swan
#

well your error says you have py for channel in member.guild.channel: but u actually have py for channel in member.guild.channels: in the code

lyric tusk
#

i just save the file and it is the same

sage otter
#

Did you restart the bot?

jaunty wraith
#

Does anyone know how to get the bot to mention the mentioned user
Like ctx.author.mention but for the mentioned user

lyric tusk
vale wing
#

Is there a way to get an image attached to a slash command?

#

Would like

image: disnake.Attachment```
typehint work
cold sonnet
#

idk how slash commands work

#

can you get a message object from it?

#

you probably can

#

image = message_object.attachments[0]

#

damn everybody went to celebrate the new year

placid skiff
# cold sonnet can you get a message object from it?

Depends which package you are using.
In diskane, after you sent the message in response to a command, you can use ApplicationCommandInteraction.original_message to get that message object, usefull if you want to edit it or delete it
This will take the first response you sent to a command trough Application, which means that this will not work for other message you could send

vale wing
#

How to get VoiceClient from guild? I only get VoiceProtocol but that's not what I need I think

cold sonnet
#

!d discord.Guild.voice_client

unkempt canyonBOT
#

property voice_client: Optional[VoiceProtocol]```
Returns the [`VoiceProtocol`](https://discordpy.readthedocs.io/en/master/api.html#discord.VoiceProtocol "discord.VoiceProtocol") associated with this guild, if any.
cold sonnet
#

oh

vale wing
#

Yeah

cold sonnet
#

what do you need it for?

vale wing
#

For is_playing

cold sonnet
#

music bot?

vale wing
#

Kind of

cold sonnet
vale wing
#

So how to get that stupid voice client

cold sonnet
#

I can only think of ctx

vale wing
#

The only way I see is to create a variable and place the state on connection to there

#

!d discord.ext.commands.Context.voice_client

cold sonnet
#

you need the full path

unkempt canyonBOT
#

property voice_client: Optional[VoiceProtocol]```
A shortcut to [`Guild.voice_client`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild.voice_client "discord.Guild.voice_client"), if applicable.
vale wing
#

Still protocol

cold sonnet
#

nah

#

you mean like
vclient = await voice.connect()
?

vale wing
#

Yes

#

Create a variable in cog and then do everything to it, I will see if it's possible

cold sonnet
#

!d discord.VoiceChannel.connect

unkempt canyonBOT
#

await connect(*, timeout=60.0, reconnect=True, cls=<class 'discord.voice_client.VoiceClient'>)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Connects to voice and creates a [`VoiceClient`](https://discordpy.readthedocs.io/en/master/api.html#discord.VoiceClient "discord.VoiceClient") to establish your connection to the voice server.

This requires [`Intents.voice_states`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.voice_states "discord.Intents.voice_states").
slate swan
#

does anyone know why this won't add the color?

self.add_item(discord.ui.Button(label='Invite Me', style=discord.ButtonStyle.green, url=url))
cold sonnet
#

seems good

vale wing
#

That's the only way we can get the VoiceClient from it turns out

cold sonnet
#

!d discord.ButtonStyle

unkempt canyonBOT
#

class discord.ButtonStyle```
Represents the style of the button component.

New in version 2.0.
vale wing
slate swan
#

ahh okay thanks

soft lynx
#

How do i accept a role as a slash command argument and then assign that role to the user who invoked the command

ebon island
#

What's the proper way to catch CommandNotFound error?

cloud dawn
unkempt canyonBOT
#

disnake.ext.commands.on_command_error(ctx, error)```
An error handler that is called when an error is raised inside a command either through user input error, check failure, or an error in your own code.

A default one is provided ([`Bot.on_command_error()`](https://docs.disnake.dev/en/latest/ext/commands/api.html#disnake.ext.commands.Bot.on_command_error "disnake.ext.commands.Bot.on_command_error")).
ebon island
#

So I just overwrite that method within a class inheriting client and it will work?

#

Why do I keep seeing disnake?

#

is this a new version or something?

edgy lion
#
    @commands.command()
    async def daily(self, ctx):
        async with self.db.execute(
                f"SELECT time from 'economycooldown' where guild_id = {ctx.guild.id} and user_id = {ctx.author.id} and type = {str('daily')}",
        ) as cursor:
            coolDownTime = await cursor.fetchone()``` why does the bot return this error? https://cdn.discordapp.com/attachments/784465822180704340/926553300122370068/unknown.png
slate swan
#

the error is pretty-much self explainatory

edgy lion
boreal ravine
#

did you restart/save your bot?

edgy lion
cold sonnet
#

that's not a column

#

that's the other thingy

slate swan
#

your code seems correct though

cold sonnet
#

row

#

that's a row

edgy lion
slate swan
#

yeah , daily is a row

cold sonnet
edgy lion
cold sonnet
#

uh

#

maybe the query style

#

wait

slate swan
#

ill guess its because of f strings...

edgy lion
cold sonnet
ebon island
#

How do I listen for a CommandNotFound error in a cog? What decorator do I use?

cold sonnet
#

damnit

lyric tusk
#

help xD
my error

File "c:\Users\wedaa\Desktop\discordbot\bot.py", line 53, in on_member_join
    for channel in member.guild.channel:
AttributeError: 'Guild' object has no attribute 'channel'

my code:

@client.event
async def on_member_join(member):
    with open('welcome.json', 'r', encoding='utf-8') as f:
        welcome_dict = json.load(f)
    for channel in member.guild.channel:
        welcome_dict(member.channel.guild.id)
        embed = discord.Embed(color=0x4a3d9a)
        embed.add_field(name="Welcome", value=f"{member.name} has joined {member.guild.name}", inline=False)
        embed.set_image(url="https://media.giphy.com/media/f4V2mqvv0wT9m/giphy.gif")
        await channel.send(embed=embed)


@client.command(name='setwelcomechannel')
async def setwelcomechannel(ctx, channel: discord.TextChannel):
    with open('welcome.json', 'r', encoding='utf-8') as f:
        welcome_dict = json.load(f)

    welcome_dict[str(ctx.guild.id)] = str(channel.id)
    with open('welcome.json', 'w', encoding='utf-8') as f:
        json.dump(welcome_dict, f, indent=4, ensure_ascii=False)
    
    await ctx.send(f'Sent welcome channel for {ctx.message.guild.name} to {channel.name}')

@client.event
async def on_guild_remove(guild):
    with open('welcome.json', 'r', encoding='utf-8') as f:
        welcome_dict = json.load(f)

    welcome_dict.pop(guild.id)
    with open('welcome.json', 'w', encoding='utf-8') as f:
        json.dump(welcome_dict, f, indent=4, ensure_ascii=False)
slate swan
#
execute(
"""
SELECT time FROM economycooldown
WHERE guild_id = ? and user_id = ? and type = daily
""" , 
(ctx.guild.id , ctx.author.id)
)```
cold sonnet
#

what

slate swan
cold sonnet
#

you don't do that in a cog

ebon island
#

I'm having difficulty getting it to work

#

why not?

cold sonnet
#

you do that in the main file

#

had that problem with another guy before

ebon island
#

I want to have an error handling cog if possible for neatness/cleanliness of code

slate swan
#

its possible in any file you want , just in case of cogs you'd be using an listener

ebon island
#

What decorator do I use to establish a listener?

cold sonnet
#

well try

#

@commands.Cog.listener()

slate swan
cold sonnet
#

if imported

slate swan
#

indeed

ebon island
#

what args do I pass into the decorator if any?

#

says the type is str name

#

name of what I don't know

slate swan
#

its optional , you can either pass the event name in it , or name the function ```py
@Cog.listener('on_command_error')
async def call_it_whatever(self , ctx , error):
....

@Cog.listener()
async def on_command_error(self , ctx , error):```

lyric tusk
cold sonnet
#

a member doesn't have a channel

boreal ravine
#

its member.guild? whats member.channel supposed to mean

ebon island
#

I had this for testing -

@commands.Cog.listener()
    async def on_command_error(self, ctx, error):
        print('we hit this')
        if isinstance(error, discord.ext.commands.CommandNotFound):
            print('yeah we got one!')

print statements to see if it even enters the blocks, it doesn't even print 'we hit this' which should print if every it enters the block

cold sonnet
#

hah

#

told u

boreal ravine
#

Is the function inside the cog?

slate swan
#

and yea , what kayle said

ebon island
#

that was it haha, I had just added the cog, it works 🙂

cold sonnet
#

oof

boreal ravine
#

ok

ebon island
#

I set it up but didn't list it in main to load the cog

#

now it works and hit both print statements 🙂

cold sonnet
#

you don't have to give full path to the error

#

start with commands bruhkitty

slate swan
#

yea even commands.CommandNotFound

#

or if you want to do something weird like me

ebon island
#

Ah, I just saw that in the traceback so I went with it since it couldn't be wrong haha

cold sonnet
ebon island
#

What is the deal with disnake? I have been seeing it everywhere, am I completely oblivious and have been using an old version until now?

slate swan
placid skiff
ebon island
slate swan
ebon island
#

ooh

slate swan
#

*of

ebon island
#

nice, what do I need to know about converting my project into disnakke?

slate swan
#

which is regularly updated and maintained

slate swan
ebon island
#

How involved is updating to be compatible from latest dpy?

#

ooh, so I just change all my imports to disnake and it should work out of the box?

cold sonnet
#

yes

ebon island
#

ooh cool, I will have to do that then

cold sonnet
#

it's the same

ebon island
#

thank you 🙂

cold sonnet
#

the only difference is that it's still developed

#

meaning new things will get into disnake but not dpy

slate swan
cold sonnet
ebon island
#

haha ooh, that's smart

#

and it won't have any conflicts overwriting if I do it that way? Or should I first uninstall dpy to be safe?

slate swan
blissful bridge
#
    @commands.command()
    async def tmp(self, ctx, role: discord.Role):
        for m in ctx.author.guild.members:
            temp = False
            for role in ctx.author.roles:
                if role.id == 898641586622197801:
                    temp = True
            if not temp:
                try:
                    await m.add_roles(role)
                    print("success")
                except Exception as e:
                    print(e)
                await asyncio.sleep(5)

I have an administrator role on the bot and it is higher than the role i am specifying and yet every single member results in a permissions error. It doesn't make any sense...

ebon island
#

Thank you 🙂

slate swan
#

hello, i need to do a database (.json) thtat save guilds id, can someone help me ?

cold sonnet
#

json no database

slate swan
#

.-., i need to do a file that save guilds id to do a variable per guild

cold sonnet
#

I recommend a database bruhkitty

reef shell
#

Use an actual database

#

I recommend psql

cold sonnet
#

yes

reef shell
#

PostgreSQL

cold sonnet
#

best one

reef shell
#

Indeed

vale wing
#
datetime.now()-inter.created_at```
Gives error
```py
TypeError: can't subtract offset-naive and offset-aware datetimes```
How to substract them
velvet tinsel
#

@reef shell

#

Want to join a project?

#

Discord bot?

reef shell
#

I don’t develop bot that much nowadays, btw is the project ongoing?

velvet tinsel
#

Yes

#

We got Caeden

#

And most developers

#

Wait I shouldn’t be inviting I wasn’t tasked with that yert

reef shell
#

Last commit

velvet tinsel
#

?

#

this is a new project

reef shell
#

Ik

cold sonnet
patent lark
velvet tinsel
velvet tinsel
cold sonnet
#

wt

patent lark
#

there are only 21 working on the bot i thought?

cold sonnet
#

that's a lot

patent lark
#

yeah

#

its fun, i enjoy working on this project

cold sonnet
#

I can't imagine

patent lark
#

currently coding an AI algorithm

velvet tinsel
#

Currently being useless in web development 💀

cold sonnet
#

how everyone would understand every shit 20 other people wrote

velvet tinsel
#

But I’m working on the ide 💀

patent lark
velvet tinsel
#

Me too

#

I’m fixing the embed 💀

patent lark
#

we are getting off topic for this channel, perhaps we talk about this in the actual server and steer this channel back to topic.

velvet tinsel
#

yeah but it is discord bots

patent lark
wicked atlas
velvet tinsel
#

tbh I don’t understand shit in ide.py so I’ll work on features

cold sonnet
#

main subject is discord bot development

lime trench
#

hey, i have a question on how member.created_at.timestamp() is measured in, does it count how many seconds ago a account was created? Dumb question as ive proven it wrong but i may be crazy. Is the a way to see say how many hours ago an account was created?

cold sonnet
wicked atlas
#

It's the number of seconds since 00:00:00 UTC Thursday, 1 January 1970

lime trench
#

oh ok

wicked atlas
#

I believe that created_at is a datetime object, so you should be able to subtract that from a now() object, and get the number of hours

patent lark
cold sonnet
#

break it down to
relating to Discord bot development

patent lark
#

with what library

cold sonnet
#

any python

patent lark
#

oh okay, i thought the topic said "with discord.py"

#

i must be wrong

cold sonnet
#

AND

#

other relevant Python libraries

patent lark
#

right

#

and either way, we were off topic lol

cold sonnet
#

but

#

bru

#

okay

patent lark
#

👍

cold sonnet
#

:thumbsup_tone5:

pliant gulch
#

🤔

patent lark
slate swan
#

ctx.author.metion does it still work?

humble fog
#

need help with showing latency

#

i have the message.content.startswith instead of ctx.send

ebon island
#

How do I handle command on cooldown in a cog?

I was looking at docs but wasn't entirely clear on it, I assume it will be a listener but what method do I use? command_on_cooldown?

#

message.content.startswith is not equivalent or serving the same purpose as ctx.send

slate swan
#

import discord

client = discord.client()


@client.event
async def on_ready():
  print('online and logged in as {client.user}')


 @client.event
  async def on_message(message):
    if message.author == client.user:
      return

      if message.content == 'quit':
        await message.channel.send('hello {ctx.author.mention})```
#

File "main.py", line 11
@client.event
^
IndentationError: unindent does not match any outer indentation level

ebon island
#

Nevermind figured it out above 🙂

slate swan
#

i think im blind

ebon island
#

use code blocks

slate swan
#

i cant find error

ebon island
#

it is horrible looking at code like that

slate swan
#

k

#

whats the code block symbol again

ebon island
#

`

cold sonnet
#

!resources @slate swan

unkempt canyonBOT
#
Resources

The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.

ebon island
#

return is going to break out of your code

#

so it won't read anything after the break

#

return is something that goes on the end of functions

cold sonnet
#

indents are his only problem

#

he has to deindent the second if

ebon island
#

I assumed the indentation was intentional

cold sonnet
#

it's not

ebon island
#

as the conditionals have two different intents

cold sonnet
#

even the error is about indentation

ebon island
#

I didn't even see the error :p

cold sonnet
#

and idk how client works

#

discord.Client() should it be
with a capital C

slate swan
#

o

lyric tusk
#

help
my error

Ignoring exception in on_member_join
Traceback (most recent call last):
  File "C:\Users\wedaa\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\client.py", line 343, in _run_event
    await coro(*args, **kwargs)
  File "c:\Users\wedaa\Desktop\discordbot\main.py", line 54, in on_member_join
    welcome_dict(member.channel.guild.id)
AttributeError: 'Member' object has no attribute 'channel

my code:

@client.event
async def on_member_join(member):
    with open('welcome.json', 'r', encoding='utf-8') as f:
        welcome_dict = json.load(f)
    for channel in member.guild.channels:
        welcome_dict(member.channel.guild.id)
        embed = discord.Embed(color=0x4a3d9a)
        embed.add_field(name="Welcome", value=f"{member.name} has joined {member.guild.name}", inline=False)
        embed.set_image(url="https://media.giphy.com/media/f4V2mqvv0wT9m/giphy.gif")
        await channel.send(embed=embed)


@client.command(name='setwelcomechannel')
async def setwelcomechannel(ctx, channel: discord.TextChannel):
    with open('welcome.json', 'r', encoding='utf-8') as f:
        welcome_dict = json.load(f)

    welcome_dict[str(ctx.guild.id)] = str(channel.id)
    with open('welcome.json', 'w', encoding='utf-8') as f:
        json.dump(welcome_dict, f, indent=4, ensure_ascii=False)
    
    await ctx.send(f'Sent welcome channel for {ctx.message.guild.name} to {channel.name}')

@client.event
async def on_guild_remove(guild):
    with open('welcome.json', 'r', encoding='utf-8') as f:
        welcome_dict = json.load(f)

    welcome_dict.pop(guild.id)
    with open('welcome.json', 'w', encoding='utf-8') as f:
        json.dump(welcome_dict, f, indent=4, ensure_ascii=False)
cold sonnet
lyric tusk
#

i dint see that xD

cold sonnet
#

np

lyric tusk
#

ty

delicate salmon
#

help
my error
Ignoring exception in on_member_join
Traceback (most recent call last):
File "C:\Users\wedaa\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "c:\Users\wedaa\Desktop\discordbot\main.py", line 54, in on_member_join
welcome_dict(member.channel.guild.id)
AttributeError: 'Member' object has no attribute 'channel

my code:
@client.event
async def on_member_join(member):
with open('welcome.json', 'r', encoding='utf-8') as f:
welcome_dict = json.load(f)
for channel in member.guild.channels:
welcome_dict(member.channel.guild.id)
embed = discord.Embed(color=0x4a3d9a)
embed.add_field(name="Welcome", value=f"{member.name} has joined {member.guild.name}", inline=False)
embed.set_image(url="https://media.giphy.com/media/f4V2mqvv0wT9m/giphy.gif")
await channel.send(embed=embed)

@client.command(name='setwelcomechannel')
async def setwelcomechannel(ctx, channel: discord.TextChannel):
with open('welcome.json', 'r', encoding='utf-8') as f:
welcome_dict = json.load(f)

welcome_dict[str(ctx.guild.id)] = str(channel.id)
with open('welcome.json', 'w', encoding='utf-8') as f:
    json.dump(welcome_dict, f, indent=4, ensure_ascii=False)

await ctx.send(f'Sent welcome channel for {ctx.message.guild.name} to {channel.name}')

@client.event
async def on_guild_remove(guild):
with open('welcome.json', 'r', encoding='utf-8') as f:
welcome_dict = json.load(f)

welcome_dict.pop(guild.id)
with open('welcome.json', 'w', encoding='utf-8') as f:
    json.dump(welcome_dict, f, indent=4, ensure_ascii=False)
slate swan
#

how can i make system that can add points to users checks theirs points and rank promotes can promote sameone to highter rank or domote to lower rank i mean when samone reach like 100/100 points admin or some of staff members can promote sameone or when they dont get point the staff members can demote by using command
and the adding points by usuing command like +addpt @nick number of points

#

?

#

pls

patent lark
patent lark
cold sonnet
#

you copied the whole thing and came back to the same place with the same error

#

outstanding move

cedar stream
#

You just need to have a db set up, from there It’ s basically just simple crud operations

cold sonnet
#

straight up

lyric tusk
#

xD

cold sonnet
#

the AUDACITY

lyric tusk
#

😂

cold sonnet
#

don't think u should worry

#

the guy probably doesn't know how to even set up your json file

lyric tusk
#

oh yeah xD

solid falcon
#

the id should be what you need

magic ore
#

!d discord.Guild.get_role

unkempt canyonBOT
magic ore
#

if you're using 2.0 you can use this instead to check if the member has a role:

#

!d discord.Member.get_role

unkempt canyonBOT
#

get_role(role_id, /)```
Returns a role with the given ID from roles which the member has.

New in version 2.0.
quaint epoch
#

what is this? what am i looking at?

slate swan
magic ore
#

all arguments before / in a function definition indicate that they are positional only

#

i.e. they can't be passed like role_id=1

slate swan
#

i mean made i mean started making

#

cuz im asking how can i make it and how should the code look like or something

cold sonnet
quaint epoch
cold sonnet
#

!d disnake.Client.getch_user

unkempt canyonBOT
#

await getch_user(user_id, *, strict=False)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Tries to get the user from the cache. If fails, it tries to fetch the user from the API.
quaint epoch
cold sonnet
quaint epoch
#

and you edited it

cold sonnet
#

yes

#

I couldn't click the emoji first try

#

missed it

quaint epoch
cold sonnet
#

it's the same thing

#

but you have to do error handling in the middle

quaint epoch
cold sonnet
#

getch seems like the lazier way

cold sonnet
#

that doesn't make any sense

quaint epoch
#

and why tf can't you fetch a role? you can only get it

cold sonnet
#

probably cuz get will always succeed

#

stay away from API calls whenever it's possible

#

why are you using the main class

#

and indeed, a member doesn't have get_role

#

discord.Member is the main class

quaint epoch
cold sonnet
#

you need an instance of discord.Member there

#

then it does

#

but use an instance

cold sonnet
#

tho this isn't python syntax wtf

#

discord.Member

#

replace that

quaint epoch
#

get role from guild

cold sonnet
#

a member instance

#

ctx.author

#

roles is not a function

#

ctx.guild.get_role(id)

quaint epoch
#
discord.utils.get(ctx.guild.roles, id=(role_id))```
cold sonnet
slate swan
#

how can i make system that can add points to users checks theirs points and rank promotes can promote sameone to highter rank or domote to lower rank i mean when samone reach like 100/100 points admin or some of staff members can promote sameone or when they dont get point the staff members can demote by using command
and the adding points by usuing command like +addpt @nick number of points how the would like etc

cold sonnet
#

use a database

#

make database calls all the time

#

nothing

#

it's okay without brackets

cold sonnet
quaint epoch
#

nothing

#
id=role_id```do the same thing
cold sonnet
#

you saved a role as an int didn't u

quaint epoch
#

lol

#

you DO that?

magic ore
#

no

heavy folio
#

!d discord.ext.commands.Bot.load_extension no, that wont work

unkempt canyonBOT
#

load_extension(name, *, package=None)```
Loads an extension.

An extension is a python module that contains commands, cogs, or listeners.

An extension must have a global function, `setup` defined as the entry point on what to do when the extension is loaded. This entry point must have a single argument, the `bot`.
heavy folio
#

you can have a list, then iterate through it and load the extensions

#
EXTENSIONS = ['cogs.xxx', 'cogs.yyy', 'cogs,zzz']
#

mhm

silent portal
#

Hi, I upgraded to 2.0 and now my button event isn't working.

fading kettle
#

.help

sick birch
#

Many people prefer to have it dynamic, looping through every file in a certain folder and adding it as an extension

#

That way when you add a new extension, you don't have to also add it's name in the list, you just need to make the extension and it automatically loads it for you

#

Nah just in your main bot file

#

It should be one of the first thing the bot does

heavy folio
sick birch
#

There are interactions, but those are for other things as well such as slash commands and select menus

silent portal
#

And it worked, but as soon as I installed 2.0 it doesn't seem to work anymore

maiden fable
#

!d discord.on_interaction is what u looking for @silent portal

unkempt canyonBOT
#

discord.on_interaction(interaction)```
Called when an interaction happened.

This currently happens due to slash command invocations or components being used.

Warning

This is a low level function that is not generally meant to be used. If you are working with components, consider using the callbacks associated with the [`View`](https://discordpy.readthedocs.io/en/master/api.html#discord.ui.View "discord.ui.View") instead as it provides a nicer user experience.

New in version 2.0.
heavy folio
#

why are you using on_interaction tho..

maiden fable
final iron
#

Store your cogs in a folder and loop through the folder loading the cogs

#

No hardcoding needed

maiden fable
#

!d os.listdir

unkempt canyonBOT
#

os.listdir(path='.')```
Return a list containing the names of the entries in the directory given by *path*. The list is in arbitrary order, and does not include the special entries `'.'` and `'..'` even if they are present in the directory. If a file is removed from or added to the directory during the call of this function, whether a name for that file be included is unspecified.

*path* may be a [path-like object](https://docs.python.org/3/glossary.html#term-path-like-object). If *path* is of type `bytes` (directly or indirectly through the [`PathLike`](https://docs.python.org/3/library/os.html#os.PathLike "os.PathLike") interface), the filenames returned will also be of type `bytes`; in all other circumstances, they will be of type `str`.

This function can also support [specifying a file descriptor](https://docs.python.org/3/library/os.html#path-fd); the file descriptor must refer to a directory.

Raises an [auditing event](https://docs.python.org/3/library/sys.html#auditing) `os.listdir` with argument `path`.
slate swan
#

hey why when i put one more id the channel whitelist dont work

#

bot.command() # Stock command
async def stock(ctx):
if ctx.channel.id == 926669256270176346 or 926669246128349195:

fading knot
#

Try to loop like

unkempt canyonBOT
#

When checking if something is equal to one thing or another, you might think that this is possible:

if favorite_fruit == 'grapefruit' or 'lemon':
    print("That's a weird favorite fruit to have.")

While this makes sense in English, it may not behave the way you would expect. In Python, you should have complete instructions on both sides of the logical operator.

So, if you want to check if something is equal to one thing or another, there are two common ways:

# Like this...
if favorite_fruit == 'grapefruit' or favorite_fruit == 'lemon':
    print("That's a weird favorite fruit to have.")

# ...or like this.
if favorite_fruit in ('grapefruit', 'lemon'):
    print("That's a weird favorite fruit to have.")
fading knot
#
Ch = [channels list]
for channel in Ch:
  If ctx.channel.id == channel```
#

@slate swan

fading knot
#

Yes

#

Is there anyone feeling aiohttp error

upbeat otter
boreal ravine
fading knot
#

Aiphttp upgraded to new version so old version of discord. Py not working

boreal ravine
delicate salmon
#

Happy new year

#

Let go

boreal ravine
delicate salmon
#

2022 is ?

slate swan
slate swan
upbeat otter
#

Lol

delicate salmon
#

2022 is bruh

upbeat otter
unkempt canyonBOT
slate swan
#

how can i make system that can add points to users checks theirs points and rank promotes can promote sameone to highter rank or domote to lower rank i mean when samone reach like 100/100 points admin or some of staff members can promote sameone or when they dont get point the staff members can demote by using command
and the adding points by usuing command like +addpt @nick number of points
? i only need how to make this system cuz me dont know how to make this system

upbeat otter
slate swan
#

but i dont know how to make exacly this command bursh

frosty jolt
#

what are some reasons for your bot to get rate limited?

boreal ravine
maiden fable
frosty jolt
#

o im using repl lol

boreal ravine
#

or that

frosty jolt
#

how do i fix it? and how long will i be blocked from makig requests for

boreal ravine
#

1 hour usually, or less

frosty jolt
#

ok ty

#

do you know any other ides or wahtever and thing si can use to host it

final iron
#

An old laptop

#

Pay for a VPS

slate swan
#

me dont know but i know where u can host your bot

final iron
slate swan
#

not heroku

frosty jolt
#

ok ill try some alternatives later

slate swan
#

u can use danbot host

frosty jolt
#

how often will this happen?

slate swan
frosty jolt
#

ok ill use that for hosting

slate swan
#

ok

#

and in the dan bot hosting u can write in python too so u dont need to upload x timex the same file of bot with more futures to bot

maiden fable
slate swan
#

heh

full lily
slate swan
#

i dont think so

full lily
#

Are you sure this wasn't down to the client's negligence?

slate swan
#

cuz people use this hosting and their bot tokens dosent got leaked

heavy folio
#

is there a way to get the thread's parent channel

valid galleon
#

so i have a list of dictionaries, like:
cases = [{'Case Number': 1, 'Date': date}, {'Case Number': 2, 'Date': date}]
I want to iterate through it, and add fields to an embed, so that it looks something like this:

Case Number 1
Date: date

Case Number 2
Date: date```
#

any idea how i can do this?

heavy folio
#

hmm

#

what i'd do is ```py
for i in range(len(cases)):

#

then do stuff, the name of the embed can be something like ```py
f"Case Number {i}"

#

not sure if that works tho

valid galleon
#

thanks, i'll try that

slate swan
#

ok

sage otter
#

Proceeds to get
Case Number: {'Case Number': 1}