#discord-bots

1 messages Β· Page 37 of 1

vocal snow
#

make sure you know basic python first πŸ‘

silk fulcrum
#

noo disnake and pycord(

paper sluice
#

yea? it wouldn't help very much though, try print the label or something of the button which will help you locate the problem

digital field
#

any tips on how can I get the grip of hikari

slate swan
slate swan
digital field
#

what is REST API?

dull terrace
#

Not a great place to ask such a broad question, would take too long to explain

#

Best way to start is legitimately to Google "how to make a discord bot"

vocal snow
#

I disagree that would bring up lucas tutorials

dull terrace
#

I started with bad tutorials, gotta start somewhere

vocal snow
#

starting with bad tutorials makes things harder in the long run

#

better to start with python fundamentals and then the documentation

dull terrace
#

Where are the good starter tutorials though

#

The problem with starting with python fundamentals is that it saps your motivation, I would debate that it's better to jump in and actually see that you can make something badly

vocal snow
#

For python basics, Automate the Boring Stuff, PY4E are great

#

being stuck on an issue for weeks because you don't have the prerequisite knowledge to solve it is even more demotivating

slate swan
# digital field what is REST API?

its like a Client Server data exchange medium, the client makes request to a server using GET, POST and PATCH etc methods and the Server processes it

#

await view.on_timeout() then?

#

Or is it

   . . .
#

you need to override on_timeout method of view class if you wanna do something when the view timeouts

#

mhm

robust fulcrum
#

My connection is good not bad

slate swan
#
class Myview(View):
    async def on_timeout(self):
       # stuff
vale wing
robust fulcrum
vocal snow
#

A good processor for fast opus encoding

vale wing
#

Get a VPS

slate swan
robust fulcrum
vale wing
#

Amazon AWS free 1 year

#

Oracle free tier

#

Azure free tier

silk fulcrum
#
            print(self.bombs)
            print(self.pos)
            print(self.is_bomb)
            print(self.bombs_around)
            self.label = str(self.bombs_around)
            print(self.label)``` now im confused even more... @paper sluice
vale wing
#

All those are blocked in Russia tho screw them

silk fulcrum
robust fulcrum
#

Or Google

#

Idk how to host bot

vale wing
#

I have samovar server

vocal snow
vale wing
slate swan
#

you need a credit card for any free vps you want to use

robust fulcrum
vale wing
digital field
#

@slate swan

vale wing
# robust fulcrum Or Google

Google doesn't support individuals in some countries and they work similar to digital ocean although I don't know certainly

robust fulcrum
vale wing
robust fulcrum
vale wing
slate swan
#

Possible to respond to an interaction which was sent and then bot turned off, then the bot would still respond to it

#

For now
If we send buttons with a message and turn off the bot and then turn it back on again it won’t respond to that interaction

silk fulcrum
unkempt canyonBOT
#

add_view(view, *, message_id=None)```
Registers a [`View`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.ui.View "discord.ui.View") for persistent listening.

This method should be used for when a view is comprised of components that last longer than the lifecycle of the program.

New in version 2.0.
slate swan
#

So if I just do

view.add_item(something)
await ctx.send(content=β€œsomething”, view=view)

The bot will respond to that button even when it is turned on and off?

loud phoenix
#

Have someone tried to automate TikTok uploading? I see some already done Python bots on that, but they require that you login manually, which destroys 90% of the purpose of automatic upload.

vocal snow
slate swan
#

Is there any on_button_click or on_interaction event?

vocal snow
slate swan
#

I’m trying to respond to a button which was sent before the bot turned off

vocal snow
#

You can just make a persistent view

slate swan
#

just for example
If you turn the bot off after sending a button
And then turn it back on it won’t send the response to that button sent last time

#

how?

vocal snow
cold sonnet
#

samandra you grinding for a day on vsc?

#

how much of that was coding?

slate swan
#

21 πŸ’€

slate swan
slate swan
still swan
#

Hello, its showing for me that there is /ping slash command but actually thats not true, its also showing in the menu when i type /, how i can disable that? may someone help me please?

sick birch
#

Make sure you’re use add_view for persistent buttons

hot prawn
#

Psst off

robust fulcrum
#

Guys anyone give any command idea for my bot

maiden fable
cold sonnet
#

command to change commands

robust fulcrum
cold sonnet
#

how is my idea not useful😭

robust fulcrum
cold sonnet
#

me

#

I'm gonna go home in 2 weeks and make that command

cerulean shale
#

Is it better to move on to nextcord from discord.py?

robust fulcrum
cold sonnet
#

practice

cold sonnet
#

absolutely no reason to

robust fulcrum
#

Dpy better

cerulean shale
cold sonnet
#

still no reason to

cerulean shale
robust fulcrum
#

No

cold sonnet
#

it isn't

cerulean shale
#

Well ok ig

cerulean shale
robust fulcrum
#

Bruh

#

Go and see their server

cerulean shale
cold sonnet
#

it's been being improved again

cerulean shale
cold sonnet
#

for more than half a year

robust fulcrum
#

Is ghost making 2.0 version then

cerulean shale
#

Ok then

cold sonnet
#

man you're late, missed much

cerulean shale
#

πŸ’€

#

Haven't been doing this stuff for almost a year, came back last week and saw his message

cold sonnet
#

pip<python version> install -U git+https://github.com/Rapptz/discord.py

#

python version part optional

#

just put it there for people who can't put the right pip on path

cerulean shale
#

Oh

#

I saw this like two days ago

robust fulcrum
#

How can I make a comand that can run js in discord.py?

cerulean shale
vocal snow
slender hamlet
surreal walrus
#

Can somone help /

cerulean shale
#

In ()

surreal walrus
#

new to this and and confused

rotund leaf
cerulean shale
cerulean shale
slate swan
#

Imagine not spending money for hosting and buying AirPods Pro πŸ’€

slate swan
#

I assume you mean global ban from gban

cerulean shale
surreal walrus
#

got it

surreal walrus
slender hamlet
#

Did you check application_commands when adding the bot to the server?

slate swan
#

define it then

slender hamlet
#

from discord import app_commands

slate swan
#

why syncing in on_ready, that's so horrible

shrewd apex
#

make a command for syncing πŸ‘€

slate swan
shrewd apex
shrewd apex
#

wait a sec

slate swan
#

waiting

shrewd apex
#

i swear i got it lemme try to replicate

slate swan
#

I don't see issues

#

install dpy 2.0

slender hamlet
#

I didn't know about setup_hook before, a guy suggested it once, but since my code worked I was to lazy to change it, thanks for the advice tho, gonna keep the link ready just incase

livid jacinth
#

Hey, i try to create an command for a todo list. I have a txt file with some words. When I enter the command and a word the discord bot should delete the word from the txt file. ```py
@bot.command()
async def v(ctx, arg):
words= open("user.txt", "r")
if arg in words:
print("Check")
for line in words:
if arg in line:
line = line.replace(arg,"")
words.write(line)
words.close()


the txt file:

```txt
test

123

ping

But the bot dont delete the word

slate swan
livid jacinth
#

Like that?

unkempt canyonBOT
#

json.load(fp, *, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, **kw)```
Deserialize *fp* (a `.read()`-supporting [text file](https://docs.python.org/3/glossary.html#term-text-file) or [binary file](https://docs.python.org/3/glossary.html#term-binary-file) containing a JSON document) to a Python object using this [conversion table](https://docs.python.org/3/library/json.html#json-to-py-table).

*object\_hook* is an optional function that will be called with the result of any object literal decoded (a [`dict`](https://docs.python.org/3/library/stdtypes.html#dict "dict")). The return value of *object\_hook* will be used instead of the [`dict`](https://docs.python.org/3/library/stdtypes.html#dict "dict"). This feature can be used to implement custom decoders (e.g. [JSON-RPC](https://www.jsonrpc.org) class hinting).

*object\_pairs\_hook* is an optional function that will be called with the result of any object literal decoded with an ordered list of pairs. The return value of *object\_pairs\_hook* will be used instead of the [`dict`](https://docs.python.org/3/library/stdtypes.html#dict "dict"). This feature can be used to implement custom decoders. If *object\_hook* is also defined, the *object\_pairs\_hook* takes priority.
slate swan
#

smh read the docs

livid jacinth
slate swan
#

nice

shrewd apex
# slate swan nice
raise Missing applicationID

discord.app_commands, errors. MissingApplicationid: Client does not have an application id set. Either the function was called before on ready was called or application id was not passed to the Client constructor.
maiden fable
#

2.0 publishing soonℒ️

shrewd apex
#

nice

livid jacinth
shrewd apex
maiden fable
#

Never really had time to get into programming since a few months now

#

I am missing out all the new stuff that's been happening

shrewd apex
#

mean embed object cannot be used as dict key and added in a set

cerulean shale
#
@bot.listen()
async def on_member_join(member):

  channel = get_channel(bot.get_all_channels(), 'π‘†π‘π‘Žπ‘π‘’π‘ β„Žπ‘–π‘')

  background = Editor("bg.jpg")
  profile_image = await load_image_async(str(member.avatar_url))

  profile= Editor(profile_image).resize((150, 150)).circle_image()
  lol = Font.poppins(size=50, variant="bold")

  hit = Font.poppins(size=20, variant="light")

  background.paste(profile, (325, 90))
  background.ellipse((325,90),150, 150, outline="white",stroke_width=5)

  background.text((400, 260), "Welcome to Nebula", color="white", font=lol, align="center")
  background.text((400, 325), f"{member.name}#{member.discriminator}", color="white", font=hit, align="center")

  file = File(fp=background.image_bytes, filename="welcome.jpg")
  await channel.send(f"**Hello** {member.mention}! **Welcome to Nebula**. **Pls check out** #πΆπ‘œπ‘šπ‘π‘Žπ‘ π‘  **for guidance. Get some fancy roles from** #𝑆𝑒𝑙𝑓-π‘…π‘œπ‘™π‘’π‘ . **Introduce yourself in** #πΌπ‘›π‘‘π‘Ÿπ‘œπ‘‘π‘’π‘π‘‘π‘–π‘œπ‘›π‘  **and have fun.**")
  await channel.send(file=file)```
shrewd apex
#

bummer i was doing it for paginator

livid jacinth
#

Hey, i try to create an command for a todo list. I have a json file with some words. When I enter the command and a word the discord bot should delete the word from the json file. ```py
@bot.command()
async def v(ctx, arg):
with open("user.json", "r") as f:
read = json.load(f)
if arg in read:
read.pop(arg)

cerulean shale
#

i changed the bg.jpg and i am getting this error

shrewd apex
#

and instead of the they added __eq__

cerulean shale
#

pls help

maiden fable
#

Why u even wanna compare embeds

shrewd apex
maiden fable
shrewd apex
#

what u gonna compare to embeds for in first place i have no idea

shrewd apex
maiden fable
#

Lemme see the code and check what they even comparing

cerulean shale
#

bruh ;-;

cerulean shale
maiden fable
#

Its probably in a folder

#

U r searching the root directory

cerulean shale
shrewd apex
maiden fable
#

Nice

cerulean shale
maiden fable
#

os.listdir()
Print this

livid jacinth
#

Hey, i try to create an command for a todo list. I have a json file with some words. When I enter the command and a word the discord bot should delete the word from the json file. ```py
@bot.command()
async def v(ctx, arg):
with open("user.json", "r") as f:
read = json.load(f)
if arg in read:
read.pop(arg)

But i get this error ```discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: 'str' object cannot be interpreted as an integer ```

Json file:```json
[
    "test"
]
cerulean shale
maiden fable
#

Wait, @shrewd apex if they made it unhashable, that means u won't be able to use it as a list element anymore, right?

maiden fable
#

Hm, I am mistaken then

shrewd apex
#

from which lib is this?

maiden fable
#

Nice __eq__

cerulean shale
shrewd apex
#

yeah they made dunder for == as i said

cerulean shale
shrewd apex
maiden fable
#

Lmao

shrewd apex
#

any benefits?

cerulean shale
maiden fable
#

Lucas?

cerulean shale
#

and it has been working for a while now

cerulean shale
maiden fable
#

Nvm

shrewd apex
#

ok pil gonna go major updates soon u might want to switch as well

maiden fable
#

What updates?

cerulean shale
mossy jacinth
#

I'm now completely confused because, I added letters to every field possible but it still says the same error

shrewd apex
#

idk if this easy pil gonna keep

shrewd apex
# maiden fable What updates?

quite a few along with 3.11 they deprecating prev Image filters gonna add something like Resampling next year around

maiden fable
#

O

cerulean shale
#

nvm it works now πŸ’€

#

anyways i will try pil, thx for the info

cerulean shale
shrewd apex
maiden fable
#

iirc pillow is a continued fork of pil

shrewd apex
#

pil now deprecated

cerulean shale
shrewd apex
#

it's pillow now

shrewd apex
limber bison
#

how can i add author in embed = discord.Embed
not vai embed.add_author\

junior verge
#

How do I fix this?

maiden fable
#

u forgot to await it

#

await client.load....

junior verge
#

I get that yeah

junior verge
# maiden fable await client.load....
@client.command()
async def load(ctx, extension):
    client.load_extension(f'cogs.{extension}')

@client.command()
async def unload(ctx, extension):
    client.unload_extension(f'cogs.{extension}')

for filename in os.listdir('./cogs'):
    if filename.endswith('.py'):
        client.load_extension(f'cogs.{filename[:-3]}')
``` for all 3?
maiden fable
#

mhm

#

why, are you not able to share an error?

#

interaction.user

mossy jacinth
junior verge
# maiden fable mhm
@client.command()
async def load(ctx, extension):
    await client.load_extension(f'cogs.{extension}')

@client.command()
async def unload(ctx, extension):
    await client.unload_extension(f'cogs.{extension}')

    for filename in os.listdir('./cogs'):
        if filename.endswith('.py'):
            await client.load_extension(f'cogs.{filename[:-3]}')
``` my bot doesn't respond to anything lol or am I doing something wrong
maiden fable
#

U never send anything

junior verge
#

wym?

#

getting no errors nothing

maiden fable
#

u never do await ctx.send() or smth, so u never get a response

junior verge
#

just the things in my cogs etc

#

It just doesn't respond to my cogs

#

Nor my main file

maiden fable
#

wym doesn't respond bro

junior verge
#

I just do do the command .ping for example but the bot gives no response nor error in the console

maiden fable
#

Can u print bot.commands?

#

and see if all the commands are there

#

also show yr error handler

glad cradle
#

as it is now your cogs will only be loaded by running the command unload

junior verge
mossy jacinth
#

how can i check if a user has at least one role?
Like if the member has at least one or more roles DM him but; if the member has No roles send a message into the chat?

glad cradle
mossy jacinth
#

if ctx.author is ctx.guild.owner:

i think

maiden fable
junior verge
#

I use 2.0 yes

glad cradle
junior verge
#

Why not?

maiden fable
shrewd apex
slate swan
shrewd apex
#

πŸ’€

slate swan
#

rip i cannot even type properly cuz knew keyboarddd

junior verge
#

But do I need to await it or not?

maiden fable
shrewd apex
slate swan
junior verge
#

so ignore this?

slate swan
#

otherwise it wont work

#

no?

maiden fable
slate swan
#

that code wont even run without a non-zero status code so

slate swan
junior verge
maiden fable
junior verge
#

im confused sorry

maiden fable
#

Its a command, why tf do u not have an async command function

slate swan
#

it's a command?

slate swan
#

if it was dpy would have raised ajn error

maiden fable
#

At the top lol

junior verge
#

just trying to load cogs in dpy 2.0

maiden fable
junior verge
#

It has it?

maiden fable
#

Yr error says otherwise

junior verge
#

@client.command()
async def load(ctx, extension):
    await client.load_extension(f'cogs.{extension}')

@client.command()
async def unload(ctx, extension):
    await client.unload_extension(f'cogs.{extension}')

for filename in os.listdir('./cogs'):
    if filename.endswith('.py'):
        await client.load_extension(f'cogs.{filename[:-3]}')
``` this is just what I got
maiden fable
#

Indent goes brrrrrrrrrr

junior verge
maiden fable
#

Indent was the same, be it old or new

junior verge
#

How does it need to be then lol

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

junior verge
#

I know what indent is yes

slate swan
#

anyone know how i could check if i had any dms with a user when they dm the bot
like if the bot said anything

maiden fable
#

!d discord.DMChannel

unkempt canyonBOT
#

class discord.DMChannel```
Represents a Discord direct message channel.

x == y Checks if two channels are equal.

x != y Checks if two channels are not equal.

hash(x) Returns the channel’s hash.

str(x) Returns a string representation of the channel
maiden fable
#

isinstance(msg.channel, discord.DMChannel)

shrewd apex
#

.channel

maiden fable
slate swan
#

anyone know how i could check if the bot had any dms with a user when they dm the bot

livid jacinth
#

Hey, i try to create an command for a todo list. I have a json file with some words. When I enter the command and a word the discord bot should delete the word from the json file. ```py
@bot.command()
async def v(ctx, arg):
with open("user.json", "r") as f:
read = json.load(f)
if arg in read:
read.pop(arg)

But i get this error ```discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: 'str' object cannot be interpreted as an integer ```

Json file:```json
[
    "test"
]
shrewd apex
slate swan
shrewd apex
#

how the bot gonna know they talk with u or not u talk in a bot monitored channel?

unkempt canyonBOT
#

async for ... in history(*, limit=100, before=None, after=None, around=None, oldest_first=None)```
Returns an [asynchronous iterator](https://docs.python.org/3/glossary.html#term-asynchronous-iterator "(in Python v3.10)") that enables receiving the destination’s message history.

You must have [`read_message_history`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.read_message_history "discord.Permissions.read_message_history") permissions to use this.

Examples

Usage...
junior verge
#
class Bot(commands.Bot):
    def __init__(self):
        super().__init__()
    
    async def on_ready(self):
        for filename in os.listdir("./cogs"):
            if filename.endswith(".py"):
                try:
                    await client.load_extension(f"cogs.{filename[:-3]}")
                    print(f"Loaded {filename}")
                except Exception as e:
                    print(f"Failed to load {filename}")
                    print(f"[ERROR] {e}")
``` shouldn't this work too?
shrewd apex
sick birch
shrewd apex
#

first of all add prefix intents in init

livid jacinth
#

Hey, i try to create an command for a todo list. I have a json file with some words. When I enter the command and a word the discord bot should delete the word from the json file. ```py
@bot.command()
async def v(ctx, arg):
with open("user.json", "r") as f:
read = json.load(f)
if arg in read:
read.pop(arg)

But i get this error ```discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: 'str' object cannot be interpreted as an integer ```

Json file:```json
[
    "test"
]

Can anyone help me pls?

shrewd apex
#

bot won't start otherwise

#

then use the setup hook as Robin said

junior verge
hazy needle
#

hey, any1 can help me? im using replit to this rn, but this dont run

sick birch
#

If you want to remove by string, use remove

shrewd apex
junior verge
sick birch
#

Okay, well use setup hook

shrewd apex
#
class Bot(commands.Bot):
    def __init__(self):
        super().__init__(command_prefix="!",  intents=discord.Intents.all())
    
    async def load_cogs(self):
        for filename in os.listdir("./cogs"):
            if filename.endswith(".py"):
                try:
                    await client.load_extension(f"cogs.{filename[:-3]}")
                    print(f"Loaded {filename}")
                except Exception as e:
                    print(f"Failed to load {filename}")
                    print(f"[ERROR] {e}")β€Š
 shouldn't this work too?
     async def setup_hook(self):
          await self.load_cogs()
#

the indents

#

fucked up

junior verge
#

yeah but I got my prefix and intents here if you get me

slate swan
hazy needle
shrewd apex
#

eh i can't do indents on phone

sick birch
shrewd apex
hazy needle
#

later of this dont run

slate swan
junior verge
sick birch
slate swan
hazy needle
shrewd apex
sick birch
unkempt canyonBOT
#

filter(function, iterable)```
Construct an iterator from those elements of *iterable* for which *function* returns true. *iterable* may be either a sequence, a container which supports iteration, or an iterator. If *function* is `None`, the identity function is assumed, that is, all elements of *iterable* that are false are removed.

Note that `filter(function, iterable)` is equivalent to the generator expression `(item for item in iterable if function(item))` if function is not `None` and `(item for item in iterable if item)` if function is `None`.

See [`itertools.filterfalse()`](https://docs.python.org/3/library/itertools.html#itertools.filterfalse "itertools.filterfalse") for the complementary function that returns elements of *iterable* for which *function* returns false.
shrewd apex
#

do this instead of bot.run

silk fulcrum
#

b-b-bump

slate swan
shrewd apex
hazy needle
silk fulcrum
shrewd apex
#

wait lemme see

silk fulcrum
#

he actually will?

#

😳

shrewd apex
#

recursion depth is 996 iirc so if u exceed that rip

#

wait reading

quaint epoch
#

!d sys.setrecursionlimit

unkempt canyonBOT
#

sys.setrecursionlimit(limit)```
Set the maximum depth of the Python interpreter stack to *limit*. This limit prevents infinite recursion from causing an overflow of the C stack and crashing Python.

The highest possible limit is platform-dependent. A user may need to set the limit higher when they have a program that requires deep recursion and a platform that supports a higher limit. This should be done with care, because a too-high limit can lead to a crash.

If the new limit is too low at the current recursion depth, a [`RecursionError`](https://docs.python.org/3/library/exceptions.html#RecursionError "RecursionError") exception is raised.

Changed in version 3.5.1: A [`RecursionError`](https://docs.python.org/3/library/exceptions.html#RecursionError "RecursionError") exception is now raised if the new limit is too low at the current recursion depth.
shrewd apex
#

when one lining some kata

hazy needle
golden tapir
#

how can i make my discoed bot move a channel to a catagory on a message

shrewd apex
hazy needle
shrewd apex
#

wait wtf are u actually trying to just run poketwos bot after cloning it?

#

u know poketwos resources are scattered all over the place also u can't just randomly clone a repo and expect it to work

hazy needle
shrewd apex
#

so u coded those cogs so that all have same name as poketwoπŸ—Ώ

#

u prolly urself don't know what are even tokens needed to run all those cogs like mongo creds redis creds etc

#

the resources for the db the images emojis

#

half them are not even on that repo

#

they are scattered in different repos

golden tapir
#

how can i make my discod bot move a channel to a different catorgaory on a message

unkempt canyonBOT
#

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

Edits the channel.

You must have the [`manage_channels`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_channels "discord.Permissions.manage_channels") permission to use this.

Changed in version 1.3: The `overwrites` keyword-only parameter was added.

Changed in version 1.4: The `type` keyword-only parameter was added.

Changed in version 2.0: Edits are no longer in-place, the newly edited channel is returned instead...
golden tapir
#

i read it

#

how would i use it

slate swan
golden tapir
#
      await channel.edit(category=1008790693327675463)
slate swan
golden tapir
#

would that work

shrewd apex
golden tapir
vocal snow
#

what types does that kwarg accept?

golden tapir
#

let me see

vocal snow
#

CategoryChannel

shrewd apex
#

no one saw anything πŸ‘€

vocal snow
#

it accepts Snowflake though

golden tapir
#

i am confused

#

the code i wrote doesnt work

#
      await channel.edit(category=1008790693327675463)
sick birch
#

Most API methods accept a snowflake because on a lower level that’s what’s sent over the API

#

I’m willing to bet you can send a message with just an object, but discord.py prevents you from doing so because the type of a snowflake is unknown

vocal snow
golden tapir
#

discord object

#

?

#

like a variable?

vocal snow
#

hmm?

#

!d discord.Object

unkempt canyonBOT
#

class discord.Object(id, *, type=...)```
Represents a generic Discord object.

The purpose of this class is to allow you to create β€˜miniature’ versions of data classes if you want to pass in just an ID. Most functions that take in a specific data class with an ID can also take in this class as a substitute instead. Note that even though this is the case, not all objects (if any) actually inherit from this class.

There are also some cases where some websocket events are received in [strange order](https://github.com/Rapptz/discord.py/issues/21) and when such events happened you would receive this class rather than the actual data class. These cases are extremely rare.

x == y Checks if two objects are equal.

x != y Checks if two objects are not equal.

hash(x) Returns the object’s hash.
vocal snow
#

makes sense to have some parts in rust for efficiency!!

shrewd apex
slate swan
#

I mean I understand the idea why using different languages but all that for a discord bot

golden tapir
#

a discord class

golden tapir
#

i am not good at classes

vocal snow
#

discord.Object(918291892819219219)

golden tapir
#

so

slate swan
shrewd apex
slate swan
shrewd apex
#

u thought correct

#

great minds think alike

golden tapir
#

ok

#

can u send me the links in dms

#

@vocal snow can u send me th links in dms

slate swan
hazy needle
#

who here know make bots about pokemon, i need help in a commands, well i need the command for spawn Dog_Sus

shrewd apex
vocal snow
#

and what isn't working

shrewd apex
golden tapir
#

why error

#
@bot.listen()
async def on_message(message):
  channel = str(message.channel.name)
  user_message = str(message.content)
  if channel == "juan-request":
    if user_message != "":
      new_name = "test"
      await channel.edit(name=new_name)
vocal snow
#

channel = str(message.channel.name)

#

channel is a string, not a TextChannel

silk fulcrum
vocal snow
#

oh nums_around is not a method

#

but you get what im saying

silk fulcrum
#

wdym remove current button from nums_around

vocal snow
#

self.view.children[n] is self for some iteration

silk fulcrum
#

what? how?

#

but nums around dont containt number it self

#

for 0 its 1, 5, 6

#

no 0 in there

vocal snow
#

assert self.view.children[n] is not selfand see

silk fulcrum
#

is not works here?

vocal snow
#

why not

silk fulcrum
#

ok

#

Um, actually nothing changed ig

vocal snow
#

make sure you assert before calling open()

silk fulcrum
#

still same error, still interaction error

vocal snow
#

wasnt it a recursionerror

silk fulcrum
#

it was

vocal snow
#

can you send the stuff again i lost it

silk fulcrum
vocal snow
#

it will call open() for pos 23

#

which will call pos 24

#

and so on

silk fulcrum
#

if they're both zero's right?

vocal snow
#

if self.bombs_around is 0 for both yes

slate swan
#

hello, i need help with this issue,

im using rapptz discord.py for my discord bot and it keeps saying

"Member" has no attribute to "avatar_url"

please help.

@bot.command(aliases=["s"])
async def snipe(ctx, member:discord.Member=None):
    if member == None:
    	member1 = ctx.author
    	memberxd = ctx.author.avatar_url
    	member = ctx.author.mention
    	channel = ctx.channel

    	try:
    		view = discord.ui.View()
    		button = discord.ui.Button(label="", style=discord.ButtonStyle.secondary, emoji="◀️")
    		button2 = discord.ui.Button(label="", style=discord.ButtonStyle.secondary, emoji="▢️")
    		view.add_item(button)
    		view.add_item(button2)
    		await ctx.reply(mention_author=False, embed=discord.Embed(
    	description = snipe_message_content[channel.id],
    	color = color,).set_footer(
    	text = f"{member1} β€’ deleted a few seconds ago").set_author(
    	name = snipe_message_author[channel.id],
    	icon_url=memberxd), view=view)
    	except KeyError:
    	   await ctx.reply(mention_author=False, embed=discord.Embed(
        description = f"ℹ️ {member}: no **recently** deleted msgs",
        color = 0xfaa61a))```
slate swan
#
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'NoneType' object has no attribute 'url'```
heavy swift
#

You're using 2.0.0a right?

slate swan
#

im not sure, how do i check?

heavy swift
#

if you're not sure then it's most likely a no but you can check by printing discord.__version__

#

if it's 1.7.3 you can upgrade by pasting pip install -U git+https://github.com/Rapptz/discord.py into the terminal

slate swan
#

yes im using 2.0.0

heavy swift
#

I'm reviewing ur code again, but in the meantime, I assume u have the members intent

vocal snow
#

you should use display_avatar attribute

slate swan
#

ctx.author.display_avatar.url

slate swan
vocal snow
#

ye

slate swan
#

alr thanks

gloomy field
#

are people still generally using discord.py after they resumed development? or are there other forks or libraries that people seem to prefer? i have a few bots i've been developing using discord.py and wondering if there's any good reason to switch now that development is continuing?

sick birch
# gloomy field are people still generally using discord.py after they resumed development? or a...

Discordpy going out of business gave the other forks and libraries a standing chance. Before they were practically unheard of and nobody used them. Now we actually have choices. A good reason you would use something other than discord.py is you don’t trust the longevity of it anymore. Going out and coming back in made a lot of people lose trust that will take work to earn back. Some people prefer the implementation details, or just for a change. I suggest try them out and see what you like, but there are a lot more resources for dpy and people helping (myself included, I primarily help with dpy)

gloomy field
sick birch
#

But personally, I don’t see any reason to switch

gloomy field
livid jacinth
#

Hey, i try to create an command for a todo list. I have a json file with some words. When I enter the command and a word the discord bot should delete the word from the json file. ```py
@bot.command()
async def v(ctx, arg):
with open("user.json", "r") as f:
read = json.load(f)
if arg in read:
read.remove(arg)
print("123")



Json file:```json
[
    "test"
]

But the bot dont delete the word. Can anyone help me pls?

vocal snow
#

!d json.dump

unkempt canyonBOT
#

json.dump(obj, fp, *, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, default=None, sort_keys=False, **kw)```
Serialize *obj* as a JSON formatted stream to *fp* (a `.write()`-supporting [file-like object](https://docs.python.org/3/glossary.html#term-file-like-object)) using this [conversion table](https://docs.python.org/3/library/json.html#py-to-json-table).

If *skipkeys* is true (default: `False`), then dict keys that are not of a basic type ([`str`](https://docs.python.org/3/library/stdtypes.html#str "str"), [`int`](https://docs.python.org/3/library/functions.html#int "int"), [`float`](https://docs.python.org/3/library/functions.html#float "float"), [`bool`](https://docs.python.org/3/library/functions.html#bool "bool"), `None`) will be skipped instead of raising a [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError "TypeError").

The [`json`](https://docs.python.org/3/library/json.html#module-json "json: Encode and decode the JSON format.") module always produces [`str`](https://docs.python.org/3/library/stdtypes.html#str "str") objects, not [`bytes`](https://docs.python.org/3/library/stdtypes.html#bytes "bytes") objects. Therefore, `fp.write()` must support [`str`](https://docs.python.org/3/library/stdtypes.html#str "str") input.

If *ensure\_ascii* is true (the default), the output is guaranteed to have all incoming non-ASCII characters escaped. If *ensure\_ascii* is false, these characters will be output as-is.
livid jacinth
#

Okay but i dont know how i have to use json.dump

vocal snow
#

obj is the dict, fp is the file object (which you can get with open())

livid jacinth
#

So?

@bot.command()
async def v(ctx, arg):
    with open("user.json", "r") as f:
        read = json.load(f)
        if arg in read:
            read.remove(arg)
            print("123")
            json.dump(read, f)
#

But i get now this error discord.ext.commands.errors.CommandInvokeError: Command raised an exception: UnsupportedOperation: not writable

vocal snow
#

because you're opening in read mode

#

you need to open in a writable mode

left idol
#
class MenuTest(discord.ui.View):

    def __init__(self, ctx, difficulty):
        self.context = ctx
        super().__init__(timeout=0)


        if difficulty == 1:
            self.boss_choices = [
                discord.SelectOption(label="Hawk", emoji=":one_star:", description="Hawk"),
                discord.SelectOption(label="Bear", emoji=":one_star:", description="Bear"),
                discord.SelectOption(label="Wolf", emoji=":one_star:", description="Wolf")
                ]

        elif difficulty == 5:
            self.boss_choices = [
                discord.SelectOption(label="Seraph", emoji=":one_star:", description="Seraph"),
                discord.SelectOption(label="Azazel", emoji=":one_star:", description="Azazel"),
                discord.SelectOption(label="Gilgamesh", emoji=":one_star:", description="Gilgamesh")
                ]


    @discord.ui.select(placeholder = "Choose a boss", options = self.boss_choices)
    async def select_callback(self, select, interaction): # the function called when the user is done selecting options
        if select.values[0] == 'Hawk':
            await interaction.response.send_message('You picked boss 1 :one_star:', ephemeral=True)
        elif select.values[0] == 'Bear':
            await interaction.response.send_message('You picked boss 2 :one_star:', ephemeral=True)
        elif select.values[0] == 'Wolf':
            await interaction.response.send_message('You picked boss 3 :one_star:', ephemeral=True)

is it possible to pass self to @discord.ui.select's options?

livid jacinth
#

So? py with open("user.json", "w+") as f:

sick birch
#

Should be under β€œviews” and is called β€œdropdown.py”

slate swan
#

can some one make me a discord bot or help

vocal snow
livid jacinth
# vocal snow because you're opening in read mode

My Bot delete now every word :c ```py
@bot.command()
async def v(ctx, arg):
with open("user.json", "w+") as f:
read = json.load(f)
if arg in read:
read.remove(arg)
print("123")
json.dump(read, f)

slate swan
#

write deletes everything in the file and passes what you provided

livid jacinth
#

Ah okay

#

Now the bot delete nothing

slate swan
#

yes?

livid jacinth
#

Yes

#

I dont know why

#

Thats weird ig

vocal snow
#

use r+, seek and truncate

vocal snow
slate swan
#

yeah

#

i checked stack and the methods to remove a line in a file are quite interesting

livid jacinth
vocal snow
#

seek to 0 and truncate after loading

#

or just open twice

livid jacinth
#

I dont know what do you mean. could you show me it please

#

?

vocal snow
#
with open("user.json", "r+") as f:
    data = json.load(f) # moves pointer to end
    f.seek(0)   # move to beginning
    f.truncate()   # remove everything

    # mutate data

    json.dump(data, f)  # dump new data
livid jacinth
#
 f.truncate()
``` but i dont want remove everything
vocal snow
#

yes you do

#

so that you can dump the new data

#

after editing it

#

otherwise you will have old data and new data in json file

livid jacinth
#

Ahhh thank you this work < 3

slate swan
#

How can I make it so that only a specific role can use a command?

#

!d discord.ext.commands.has_role

unkempt canyonBOT
#

@discord.ext.commands.has_role(item)```
A [`check()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") that is added that checks if the member invoking the command has the role specified via the name or ID specified.

If a string is specified, you must give the exact name of the role, including caps and spelling.

If an integer is specified, you must give the exact snowflake ID of the role.

If the message is invoked in a private message context then the check will return `False`.

This check raises one of two special exceptions, [`MissingRole`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.MissingRole "discord.ext.commands.MissingRole") if the user is missing a role, or [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.NoPrivateMessage "discord.ext.commands.NoPrivateMessage") if it is used in a private message. Both inherit from [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure").

Changed in version 1.1: Raise [`MissingRole`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.MissingRole "discord.ext.commands.MissingRole") or [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.NoPrivateMessage "discord.ext.commands.NoPrivateMessage") instead of generic [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure")...
left idol
#
class Dropdown(discord.ui.Select):
    def __init__(self, difficulty):
        if difficulty == 1:
            options = [
                discord.SelectOption(label='Red', description='Your favourite colour is red'),
                discord.SelectOption(label='Green', description='Your favourite colour is green'),
                discord.SelectOption(label='Blue', description='Your favourite colour is blue')
            ]

        elif difficulty == 2:
            options = [
                discord.SelectOption(label='One', description='Your favorite number is one'),
                discord.SelectOption(label='Two', description='Your favorite number is two'),
                discord.SelectOption(label='Three', description='Your favorite number is three')
            ]

        super().__init__(placeholder='Choose your favourite colour...', options=options)

    async def callback(self, select, interaction):
        await interaction.response.send_message(f'Your favourite colour is {self.values[0]}')

class DropdownView(discord.ui.View):
    def __init__(self, difficulty):
        super().__init__()
        self.add_item(Dropdown(difficulty))

so after subclassing my select menu, im getting that options is referenced before assignment so did i not handle it correctly?

#

i define options based on the difficulty i have inputted

#

i tried with my code but it didn't work so i'm working off of the example

sick birch
#

Or is it with your own code?

left idol
#

i tried to make the select menu dynamic following your example but i'm getting an error with super().__init__(placeholder='Choose your favourite colour...', options=options)

#

i think in my code it was the same problem

sick birch
#

Maybe the difficulty is not 1 or 2

left idol
#

i also tried having an else statement that also changes it but it gave the same error

#

oops not same error

#

it just went to the else statement

sick birch
#

What other error do you get if the else statement also defines the options?

left idol
#

correction, i didn't get an error it just ignored my first if statement

#

so its giving me the numbers option always

sick birch
#

So it works as expected with an else?

left idol
#

no matter what i input it with an else statement, it always gives me the option that is in response to the else statement

#

even with 1 as my difficulty it will skip to the else statement

#

idk if that makes sense what i just said

sick birch
#

It does, how are you defining difficulty?

#

I have a hunch on what the issue might be

#

But I can't be sure without more information

left idol
#

uh what do you mean, in my slash command difficulty is just a command argument and for the views i just have it defined in init

#

so in my View class self.add_item(Dropdown(difficulty))

#

and in my command its view = DropdownView(difficulty)

#

should i be referring to it as self.difficulty

sick birch
#

I see how you're passing it down up from your command down to your dropdown, but I'm concerned with it's datatype at the top level slash command handler

left idol
#

uhh do you mean what type difficulty is? its an integer

@bot.slash_command(description = 'aaaa')
async def whatthe(ctx, difficulty: int):
    view = DropdownView(difficulty)
    await ctx.send('aaaahhhhh', view=view)
sick birch
#

with type(difficulty)

#

!e

def my_function(int_arg: int):
  print(f"{type(int_arg)=}")
my_function("it's not an integer lol")
left idol
#

in my slash command or in the select view? im using pycord

unkempt canyonBOT
#

@sick birch :white_check_mark: Your 3.11 eval job has completed with return code 0.

type(int_arg)=<class 'str'>
sick birch
echo cobalt
#

bots

left idol
golden tapir
#

how can i hit the copy buttion to copy th url on mobile

sick birch
left idol
#

is there any reason why it would be None though?

sick birch
#

Can you send a picture of you invoking your slash command?

left idol
#

1 second, im trying again with optionchoice

golden tapir
#

is there anotjer way to add a bot on mobilr

#

mobile

slate swan
golden tapir
#

yeah

#

on mobile

sick birch
# left idol

Hmm okay. Seems like a bit of a pycord issue honestly, you'll need to figure out how to get it to return your arguments as integers

vocal snow
# left idol

shouldn't it show the description parameter there

hushed galleon
#

yeah that kind of looks like the command isnt registered with any parameters at all

vocal snow
slate swan
#

is there a way to check if a dictionary's keys is in the message's content, like $check keyname

left idol
#
@bot.slash_command(description = 'aaaa')
async def whatthe(ctx, difficulty: int):
    print(type(difficulty))
    view = DropdownView(difficulty)
    await ctx.send('aaaahhhhh', view=view)

is there any reason it shouldn't show up in this command?

#

i was just ignoring that because i didn't know if it was something wrong with my command

vocal snow
#

I think that's what pycord uses

whole sparrow
#

how do i check whether a channel exists in a server

#

right now my idea is to try except bot.get_channel

vocal snow
#

based on what, name, id

whole sparrow
#

id

sick birch
vocal snow
golden tapir
#

how can i invite discord bots on mobile

vocal snow
#

just use the invite link and should be fine πŸ€”

whole sparrow
#

also, how do I catch the exception? Do I catch disnake.ext.commands.errors.CommandInvokeError or AttribiuteError

#

or is there a better way

golden tapir
vocal snow
whole sparrow
#

ooo yeah ur right

whole sparrow
vocal snow
#

I wonder if they have parameters optional by default

left idol
#

async def whatthe(ctx, difficulty: Option(int, 'Pick a number')):

still isn't giving me the argument parameter

golden tapir
#

how can i invite my bot with out the url generator

vocal snow
#

you can't, the authorization part is important

slate swan
#

hi

#

i slep

golden tapir
slate swan
#

bue!!!!!!!!

vocal snow
slate swan
#

burps

vocal snow
#

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

left idol
#
class Dropdown(discord.ui.Select):
    def __init__(self, difficulty):
        if difficulty == 1:
            options = [
                discord.SelectOption(label='Red', description='Your favourite colour is red'),
                discord.SelectOption(label='Green', description='Your favourite colour is green'),
                discord.SelectOption(label='Blue', description='Your favourite colour is blue')
            ]

        else:
            options = [
                discord.SelectOption(label='One', description='Your favorite number is one'),
                discord.SelectOption(label='Two', description='Your favorite number is two'),
                discord.SelectOption(label='Three', description='Your favorite number is three')
            ]

        super().__init__(placeholder='Choose your favourite colour...', options=options)

    async def callback(self, select, interaction):
        await interaction.response.send_message(f'Your favourite colour is {self.values[0]}')

class DropdownView(discord.ui.View):
    def __init__(self, difficulty):
        super().__init__()
        self.add_item(Dropdown(difficulty))


@bot.slash_command(description = 'aaaa')
async def whatthe(ctx, difficulty: Option(int, 'Pick a number')):
    print(type(difficulty))
    view = DropdownView(difficulty)
    await ctx.send('aaaahhhhh', view=view)
#

this is what im trying to workout right now

vocal snow
#

are you creating more than one instance of discord.Bot or whatever

left idol
#

what do you mean?
bot = discord.Bot(debug_guilds=[os.getenv("GUILD")], intents=intents)

vocal snow
#

and that's the only one which you're running right

left idol
#

yea

hushed galleon
#

i dont think getenv can return an integer

vocal snow
#

oh you're right

hushed galleon
#

id figure its something to do with command synchronization

#

try adding int() around your getenv call and restart your bot, maybe pycord's not syncing correctly because of the mismatched type

left idol
#

i tried manually inputting my guildid and still isn't showing up

vocal snow
#

maybe remove the debug guilds altogether, they sync instantly anyways

left idol
#

but that seems weird that it didn't work with the debug guild?

vocal snow
#

yes, very weird

hushed galleon
#

can you check your integrations tab in server settings to see if there's two duplicate commands?

left idol
#

no just 1 of that command

hushed galleon
#

huh

vocal snow
hushed galleon
#

i guess you've been looking at the global slash command the entire time

left idol
#

yeah it was an int

hushed galleon
#

guild id is correct yeah?

left idol
#

yeah it worked with different commands

#

its just this one that wasn't working

vocal snow
#

probably py-cord has some weird syncing mechanism

#

i much prefer syncing manually for this reason

left idol
#

wym manually syncing

whole sparrow
#

How am i able to do this?

vocal snow
#

in py-cord, you create a command with the decorator and it's automatically updated in discord for you

sick birch
whole sparrow
#

Oo cool ill look into it

sick birch
left idol
#

oh really, thats neat

vocal snow
#

more like, the decorators add the commands to a pool and then they are synced with bot.run or whatever

sick birch
#

That would explain it

vocal snow
#

which is convenient sometimes but also really inconvenient

sick birch
#

I sure hope they aren’t actually syncing in the decorator

#

That’s not very pythonic

#

But knowing pycord they’re probably doing some weird hacky way

vocal snow
#

yep

left idol
#

would you mind sending the doc regarding the decorator?

left idol
#

thank you !

whole sparrow
#
    @commands.group(invoke_without_command=True)
    async def parent_command(self, ctx):
        await ctx.send("Parent command!")
    
    @commands.has_role("mod-role")
    @parent_command.slash_command(description="Make a voice channel that is privated")
    async def create(self, inter:disnake.CommandInteraction, channel_name:str):

Trying to make subcommands for slash commands, but getting this error

#

Anyone got example code on how to make subcommands?

sick birch
vocal snow
#

as they should, yeah

#

if they synced in the decorator it would be a lot of api calls 😳

whole sparrow
#

ur a legend tysm, how did i not find that

vocal snow
#

when in doubt, always check the docs πŸ˜„

whole sparrow
#

yeah fr

#

thanks again it helps out alot

vocal snow
#

πŸ‘

limber bison
#

how can i join 2 strings ?

#

hello

vocal snow
#

S1 + S2

limber bison
#

world

#

oh ok

#

any other way ?

vocal snow
#

fstring

limber bison
vocal snow
#

That's invalid syntax

#

!fstring

unkempt canyonBOT
#

Creating a Python string with your variables using the + operator can be difficult to write and read. F-strings (format-strings) make it easy to insert values into a string. If you put an f in front of the first quote, you can then put Python expressions between curly braces in the string.

>>> snake = "pythons"
>>> number = 21
>>> f"There are {number * 2} {snake} on the plane."
"There are 42 pythons on the plane."

Note that even when you include an expression that isn't a string, like number * 2, Python will convert it to a string for you.

limber bison
vocal snow
#

So use fstring

#

What's the issue

limber bison
#

!e
x= "hello"
y = "world"
print(x+y)
print(f"{x}\n + {y}")

vocal snow
#

Do you hate fstrings

unkempt canyonBOT
#

@limber bison :white_check_mark: Your 3.11 eval job has completed with return code 0.

helloworld
vocal snow
#

Did they bully you

limber bison
#

!e
x= "hello"
y = "world"
print(x+y)
print(f"{x}\n{y}")

unkempt canyonBOT
#

@limber bison :white_check_mark: Your 3.11 eval job has completed with return code 0.

001 | helloworld
002 | hello
003 | world
versed marlin
#

Hello I know like beginner level python and am new to making discord bots, can you make a discord bot do something in accordance to a user's rich presence?

#

like if someone was playing a game and the game's rich presence said like "fighting this boss" the bot would say something only when that rich presence is happening to a user

#

or something like that basically

limber bison
#

list index out of range why this error ?

limber bison
full lily
unkempt canyonBOT
#

@full lily :x: Your 3.11 eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 2, in <module>
003 | IndexError: list index out of range
full lily
limber bison
# full lily can you send a traceback
Traceback (most recent call last):
  File "D:\ph\lib\site-packages\discord\ext\commands\core.py", line 195, in wrapped
    ret = await coro(*args, **kwargs)
  File "c:\Users\Kamal kishore\Desktop\Project 0\commands\economy\store.py", line 41, in ad
    z = f"{x[i]}\n"
IndexError: list index out of range

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

    await injected(*ctx.args, **ctx.kwargs)  # type: ignore
  File "D:\ph\lib\site-packages\discord\ext\commands\core.py", line 204, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: IndexError: list index out of range```
full lily
#

I think you would want to start with i=0

limber bison
#

πŸ€”

#

but i dont want x[0] in my final result

full lily
#
        info = "ok\n"
        for y in x[1:]:
            info = info + f"{z}\n"

you could do this

#

orrrr

#

i think you just want

#

is this a list of strings?

limber bison
#

yes

full lily
#
    @commands.command()
    async def ad(self , ctx,*, name_and_dis):
        x = name_and_dis.splitlines()
        await ctx.send(f"ok\n{"\n".join(x[1:])}")
#

try this

limber bison
#

[1:] mean ?

full lily
#

means everything starting from index 1

limber bison
full lily
#

so it will skip index 0

#

which is what you wanted

limber bison
vocal snow
#

You can't have double quotes inside double quotes

#

You also can't have a newline inside the placeholder part of fstring

vocal snow
limber bison
limber bison
vocal snow
limber bison
celest sparrow
#

how would I restart my entire bot with a command? this is what i currently have

await self.bot.close()
self.bot.loop = asyncio.new_event_loop()
token = config['token']
self.bot.start(token)

but it says that RuntimeError: Event loop is closed

#

the exception is on the close() function

vocal snow
#

How would you define a restart

#

Do you want to logout and login

#

Or restart the script

burnt relic
#

SyntaxError: 'await' outside function in this

#

@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 == 'lol':
if user_message.lower() == 'is le dead':
await message.channel.send(f'lol lod')
return
elif user_message.lower() == '!game':
response = 'what game do you want to play? we have random number, '

client.run(TOKEN)

#

this chunk is broken

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.

burnt relic
#

i hate my keyobard

celest sparrow
# burnt relic @client.event async def on_message(message): username = str(message.author)....
@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 == 'lol':
    if user_message.lower() == 'is le dead':
        await message.channel.send(f'lol lod')
        return
    elif user_message.lower() == '!game':
        response = 'what game do you want to play? we have random number, '

client.run(TOKEN)
#

i did it for u :)

burnt relic
#

thx

vocal snow
#

Ty. Can see the indentation now

#

The second if statement isn't inside the event

#

Is that a formatting error or

celest sparrow
#
if message.channel.name == 'lol':
    if user_message.lower() == 'is le dead':
        await message.channel.send(f'lol lod')
        return
    elif user_message.lower() == '!game':
        response = 'what game do you want to play? we have random number, '

if the indentation on discord is correct, you need to tab forward this entire section, as the first if statement isn't in the on_message function

sick birch
vocal snow
#

I think they were just formatting it, not solving it

sick birch
#

Well it was an indentation problem so formatting and solving are synonymous in this case

drifting arrow
#

How do I make a popup window?

vocal snow
vocal snow
drifting arrow
vocal snow
#

!d discord.ui.Modal

unkempt canyonBOT
#

class discord.ui.Modal(*, title=..., timeout=None, custom_id=...)```
Represents a UI modal.

This object must be inherited to create a modal popup window within discord.

New in version 2.0.

Examples...
drifting arrow
#

ty

vocal snow
drifting arrow
#

Oh no, can't call it a promptwindow or a popup or something common.

#

Have to call it a 'modal'

sick birch
#

Well to be fair "popup" has a negative connotation, and a prompt window is usually associated with the OS/DE

drifting arrow
#

inputmenu

sick birch
sick birch
#

Looks like Danny moved it from it's original position under examples so now it looks like he made it instead of me 😭

#

Heck I don't even know if this is the one I made lol, my memory is terrible

drifting arrow
#

Β―_(ツ)_/Β―

#

if it works it works

#

Oh okay

#

I see. So it's sorta like an embed (sorta I said.)
where if you want a new input field, you create a new variable with all the things

#

Before someone jumps down my throat. I said sorta.

sick birch
#

I'm gonna have to say no on that one, but I get your point about sorta πŸ˜‚

drifting arrow
#

where an embed is: embed.add_field(blah blah) this is mynewvariable = inputthingy(blah blah)

sick birch
#

More or less, yeah

drifting arrow
#

and if I wanted a new field, I'd add:

newfield = discord.ui.TextInput(label='newfield', placeholder='New field placeholder',)

between the feedback and name.

#

not too much different to an embed in this regards

#

How many input fields can I have on 1 thing? or is it based on character limits?

hidden haven
#

Is it possible to send an ephemeral message when a user joins your server?

drifting arrow
#

Whats the documentation for ephemeral messages?

drifting arrow
sick birch
sick birch
drifting arrow
#

Really? D: dang

hidden haven
#

Ah, that's unfortunate

sick birch
#

Yeah most of discord's new features are very limited (take modals for instance, they only support the text inputs)

drifting arrow
#

Le-Sigh. I was gonna ask if they did dropdown.

#

Are modals a new thing?

sick birch
inner dawn
#

Hey, is it possible to get a users about me section using discord.py?

drifting arrow
sick birch
drifting arrow
#

How do I check my discordpy version?

sick birch
#

discord.__version__ anywhere in your code

drifting arrow
#

I did pip freeze, remembered that was a thing after I asked.

sick birch
#

Preferably in an on_ready or something similar:

@bot.even
async def on_ready():
  print(f"Using discord.py version {discord.__version__}")
drifting arrow
sick birch
#

Venvs would solve that problem, of course. You should always be using a venv when working with python

drifting arrow
#

Using discord.py version 2.0.0a

#

\o/

sick birch
#

Looks like you're good then

drifting arrow
#

Good coz I really didn't want to have to update all my bots again

inner dawn
#

Hey, I needed to ask, is it possible to get a users about me section using discord.py?

sick birch
unkempt canyonBOT
#

property activity```
Returns the primary activity the user is currently doing. Could be `None` if no activity is being done.

Note

Due to a Discord API limitation, this may be `None` if the user is listening to a song on Spotify with a title longer than 128 characters. See [GH-1738](https://github.com/Rapptz/discord.py/issues/1738) for more information.

Note

A user may have multiple activities, these can be accessed under [`activities`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member.activities "discord.Member.activities").
inner dawn
#

I'm not talking about the activity, I'm talking about a user's about me section in their profile.

sick birch
#

I know, but I believe that's what it's under

slate swan
#

how do you get the ID of emotes in discord? trying to have my bot check for a reaction of a certain emote

#

e.g ⭐

sick birch
#

You can just compare them like so:

emoji: discord.Emoji = # pretend this is the emoji that the user reacted with
if emoji == '⭐':
  ...
slate swan
#

Gotcha, how do you get these though? i can't copy them.

#

CTRL + C

⭐
#

i know that dude, it's just that when i try to paste it in pycharm, it pastes as * instead.

slate swan
#

I'm not? emotions are not conveyed well over text.

#

you could try pasting it directly into the file

drifting arrow
#

Try using vscode

slate swan
#

or use vscode, it's better

#

Or you could try opening the emoji keyboard shortcut

drifting arrow
#

Oh!

#

windows + .

slate swan
#

Windows key + >

#

same thing

#

Pycharm gives potential errors though, i don't know if vscode does that

slate swan
drifting arrow
#

oh neat

slate swan
drifting arrow
#

windows + < is neat. I started pressing all the keys

slate swan
#

😭

drifting arrow
#

I dont recommend doing the letters

#

although.. windows + L

slate swan
#

the star is U+2B50

#

iirc

#

\U0002B50

slate swan
drifting arrow
#

What do I need to add to the end of a function to remain PPEP8 compliant? async def makenote(orgid: int, note: str, shared: bool, bmid: int): is what I have atm. I know you are suppose to add something but idk what

slate swan
drifting arrow
#

How?

slate swan
#
async def some_command(ctx: discord.Context) -> None:
drifting arrow
#

oh

slate swan
drifting arrow
#
async def makenote(orgid: int, note: str, shared: bool, bmid: int) -> dict:
```?
slate swan
#

I'm 99% sure it's always gonna be None for discord.py commands

drifting arrow
#

Also what's the difference between:

""" Whatever this is suppose to be. """
and
# Commented out
#

I've always used # to make comments, but I often see the triple quotes as well

#

so idk the difference..

slate swan
#

triple quotes are docstrings

#

technically they're not comments though

drifting arrow
#

Is there any benefit to using them over #?

slate swan
#

it's still read by the interpreter

drifting arrow
#

Or is it like a preference thing?

slate swan
#

comments are ignored, triple quotes are read

#

by the interpreter at least

#

that's as much I know

drifting arrow
#

So, until we're told otherwise, it's a preference thing

#

wait!

#

@slate swan

#

That's what it does πŸ˜„

#

Oh fuck yeah.

#

Always wondered how to edit that stuff.

limber bison
#

how can i give role to command user ?

#

also how can i take it too

drifting arrow
#

Heyyy @sick birch

Traceback (most recent call last):
  File "C:\Users\Declan\Desktop\discordbots\notesbot\testbot.py", line 54, in <module>
    async def feedback(interaction: discord.Interaction):
  File "C:\Users\Declan\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\app_commands\tree.py", line 834, in decorator
    self.add_command(command, guild=guild, guilds=guilds)
  File "C:\Users\Declan\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\app_commands\tree.py", line 271, in add_command
    guild_ids = _retrieve_guild_ids(command, guild, guilds)
  File "C:\Users\Declan\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\app_commands\tree.py", line 106, in _retrieve_guild_ids
    return {guild.id}
AttributeError: 'int' object has no attribute 'id'
``` I tried running your code and like. wot.
#

is it coz my discord thingy isnt up to spec?

drifting arrow
#

I copied your code and just set TEST_GUILD to my guild id

smoky cedar
#

All of a sudden I'm getting Interaction object has no attribute 'edit_original_message'?

#

It only happens in production on my actual server, despite the code being exactly the same as my testing bot where it doesn't happen

drifting arrow
drifting arrow
#

Alright I did that. Now I get another error lol

#

I just want to see how it works. ;-; is this slash commands?

cerulean shale
#

Then you gotta make your bot give role to the user whenever they use the command

golden tapir
#

can i invite a bot via client id

sick birch
smoky cedar
smoky cedar
#

gahhhh

sick birch
#

Usually your dev version will be a few versions ahead

golden tapir
#

can i invite a bot via client id

sick birch
#

No

slate swan
#

Need help with setting up boost bot

smoky cedar
drifting arrow
#

oh @sick birch I dont think I can do slash commands 😦

limber bison
#

await ctx.author.add_roles([item["role"]])

error :
'list' object has no attribute 'id'

#

😳

#

dead ?

slate swan
#

yo how easy is it to set up a bot?

#

not coding part, setting up one to take the code?

#
import discord, os, json
from discord.ext import commands

with open('config.json', 'r') as f:
    config = json.load(f)

TOKEN = config.get('TOKEN')
Prefix = config.get('PREFIX')
Invite = config.get('Invite')

intents = discord.Intents.all()

client = discord.Client(command_prefix=Prefix, intents=intents)




@client.event
async def on_ready():
    print('Bot Online')

@client.command()
async def invite(ctx):
    await ctx.send(f"Add the bot here:"+ Invite)

client.run(TOKEN)```

ERROR:

Traceback (most recent call last):
  File "c:\Users\Clicks\Desktop\Stuff\test.py", line 22, in <module>
    @client.command()
AttributeError: 'Client' object has no attribute 'command'
slate swan
cerulean shale
limber bison
#

id have role id in my db

cerulean shale
#

Import get from discord.utils tho

slate swan
# slate swan Fairly simple

could you dm me a straightforward video on only setting it up, and how to add the code you make from vs code or something like that into the bot?

cerulean shale
cerulean shale
gleaming anvil
limber bison
gleaming anvil
slate swan
gleaming anvil
slate swan
#

yes thats what i need to know, create the bot

limber bison
#

await ctx.author.add_roles(item["role"])

'Int64' object has no attribute 'id' ?

gleaming anvil
cerulean shale
drifting arrow
#

WOOO!! Progress! πŸ˜„ https://www.youtube.com/watch?v=U0Us5NHG-nY <- gave me a lot of help

drifting arrow
#

MODALS!!

limber bison
sick birch
drifting arrow
#

Now for the fun part.

#

Hooking it all up in 1 go and finding all the bugs I made πŸ™‚

limber bison
drifting arrow
#

What could go wrong by pasting in a heap of code without testing it as I go?

sick birch
#

You can get it to show on a user's screen by responding to an interaction (slash command, button press, etc)

#

It's actually not too new of a feature, not sure how many people haven't heard of it yet

drifting arrow
#

Probably because it's rarely used.

#

I only found out about it because my friend used it on his server

#

and I was like 'Wow. That's gonna be a pain to use.' and here I am, 2 months later.

#

suffering that pain

sick birch
shrewd apex
#

oh modals

shrewd apex
drifting arrow
#

Quick question.

def myfunction(value1, value2, value3):
  pass

Do I have to do them in order? Or can I do:
myfunction(value3=1, value1=2, value2=3)?

sick birch
drifting arrow
#

😏 I pretty much got it all working. It's now hooked up to my new notes bot.

#

Ty @sick birch for your help.

sick birch
#

Awesome! Glad to hear

drifting arrow
#

I just hope nobody asks me to convert all my bots to slash commands lol

sick birch
#

Unfortunately for you discord does

#

If you're planning on going "commercial" that is

drifting arrow
#

All my bots are contained into 1 discord.

sick birch
#

What do you mean?

drifting arrow
#

1 guild*

celest sparrow
#

how would I restart my bot from a command? this is what I have currently

await self.bot.close()
self.bot.loop = asyncio.new_event_loop()
token = config['token']
self.bot.start(token)

but it gives me a RuntimeError: Event loop is closed error

drifting arrow
#

1 server*

sick birch
#

Ah yeah, that's not a problem

sick birch
celest sparrow
drifting arrow
drifting arrow
#

@celest sparrow Im using interactions, there is no ctx.

sick birch
unkempt canyonBOT
#

await close()```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Closes the connection to Discord.
celest sparrow
sick birch
#

Right. There's no need to mess with the event loop though, just use the .close() coro

celest sparrow
sick birch
#

Which is?

#

Oh the event loop is closed

celest sparrow
#

yea

sick birch
#

Get rid of the asyncio.new_event_loop() stuff it's messing with the event loop

celest sparrow
#

just did

#

same error

sick birch
#

Could you paste the full traceback?

celest sparrow
#
Traceback (most recent call last):
  File "C:\Users\vovan\AppData\Local\Programs\Python\Python310\lib\runpy.py", line 196, in _run_module_as_main
    return _run_code(code, main_globals, None,
  File "C:\Users\vovan\AppData\Local\Programs\Python\Python310\lib\runpy.py", line 86, in _run_code
    exec(code, run_globals)
  File "c:\Users\vovan\.vscode\extensions\ms-python.python-2022.12.0\pythonFiles\lib\python\debugpy\__main__.py", line 39, in <module>
    cli.main()
  File "c:\Users\vovan\.vscode\extensions\ms-python.python-2022.12.0\pythonFiles\lib\python\debugpy/..\debugpy\server\cli.py", line 430, in main
    run()
  File "c:\Users\vovan\.vscode\extensions\ms-python.python-2022.12.0\pythonFiles\lib\python\debugpy/..\debugpy\server\cli.py", line 284, in run_file
    runpy.run_path(target, run_name="__main__")
  File "c:\Users\vovan\.vscode\extensions\ms-python.python-2022.12.0\pythonFiles\lib\python\debugpy\_vendored\pydevd\_pydevd_bundle\pydevd_runpy.py", line 321, in run_path
    return _run_module_code(code, init_globals, run_name,
  File "c:\Users\vovan\.vscode\extensions\ms-python.python-2022.12.0\pythonFiles\lib\python\debugpy\_vendored\pydevd\_pydevd_bundle\pydevd_runpy.py", line 135, in _run_module_code
    _run_code(code, mod_globals, init_globals,
  File "c:\Users\vovan\.vscode\extensions\ms-python.python-2022.12.0\pythonFiles\lib\python\debugpy\_vendored\pydevd\_pydevd_bundle\pydevd_runpy.py", line 124, in _run_code
    exec(code, run_globals)
  File "c:\Users\vovan\OneDrive\Desktop\projects\Kaid\main.py", line 100, in <module>
    bot.run(token)
  File "c:\Users\vovan\OneDrive\Desktop\projects\Kaid\env\lib\site-packages\nextcord\client.py", line 793, in run
    future = asyncio.ensure_future(runner(), loop=loop)
  File "C:\Users\vovan\AppData\Local\Programs\Python\Python310\lib\asyncio\tasks.py", line 615, in ensure_future
    return _ensure_future(coro_or_future, loop=loop)
  File "C:\Users\vovan\AppData\Local\Programs\Python\Python310\lib\asyncio\tasks.py", line 636, in _ensure_future
    return loop.create_task(coro_or_future)
  File "C:\Users\vovan\AppData\Local\Programs\Python\Python310\lib\asyncio\base_events.py", line 436, in create_task
    self._check_closed()
  File "C:\Users\vovan\AppData\Local\Programs\Python\Python310\lib\asyncio\base_events.py", line 515, in _check_closed
    raise RuntimeError('Event loop is closed')
RuntimeError: Event loop is closed
sick birch
#

And full code?

#

Could I see that as well?

celest sparrow
#
    @commands.has_permissions(administrator=True)
    @commands.command()
    async def restart(self, ctx:commands.Context, module):
        if 'bot' in module:
            try:
                config = openConfig()
                await self.bot.close()
                #self.bot.loop = asyncio.new_event_loop()
                token = config['token']
                self.bot.start(token)
                embed = nextcord.Embed(title="Reload", description=f"Reloaded {module} successfully!", color=0xec0a96)
                await ctx.send(embed=embed)
            except Exception as e:
                print(e)
                await ctx.author.send(f"Restarting bot failed! | **Error :** `{e}`")
        else:
            try:
                self.bot.reload_extension(f"cogs.{module}")
                embed = nextcord.Embed(title="Reload", description=f"Reloaded {module} successfully!", color=0xec0a96)
                await ctx.send(embed=embed)
            except Exception as e:
                print(e)
                await ctx.author.send(f"Reloading extension failed! | Error : `{e}`")
sick birch
#

Yeah looks like you're trying to do API operations after your bot is closed

celest sparrow
#

wdym?

sick birch
#

e.g await ctx.send(...)
after

await self.bot.close()
gleaming anvil
#

whats the point of restarting the bot? you can just reload your cogs whenever you want to

celest sparrow
#

the exception occurs on the close function

#

and it should start the bot after

gleaming anvil
#

bot.close() closes the connection from gateway and closes the passes the bot.run() line as well, so you cannot restart the bot that way

limber bison
#

Any funfact about python ?

#

Which I dont know

sick birch
slate swan
#
with open("blacklist.json") as file:
    blacklist = json.load(file)

BlacklistedUsers = blacklist.get('ids')



@client.group()
async def ablacklist(ctx):
    text=f"There are {len(blacklist['ids'])} users in the blacklist"
    await ctx.send(text)

@ablacklist.command()
async def add(ctx, member: discord.Member = None):
    user_id = member.id
    if user_id in BlacklistedUsers:
        await ctx.send("User Already Blacklisted")
        return
    add_user_to_blacklist(user_id)
    embed=discord.Embed(title="User __Blacklisted__", description=f"**{member.name}** has been successfully added to the blacklist", color=0xff0000)
    embed.set_footer(
        text=f"There are now {len(blacklist['ids'])} users in the blacklist"
    )
    await ctx.send(embed=embed)```

It sends *both* `text=f"There are {len(blacklist['ids'])} users in the blacklist" await ctx.send(text)` & `embed=discord.Embed(title="User __Blacklisted__", description=f"**{member.name}** has been successfully added to the blacklist", color=0xff0000) embed.set_footer(text=f"There are now {len(blacklist['ids'])} users in the blacklist"`
limber bison
sick birch
#

i like snaek

limber bison
#

Is python use c in background ?