#discord-bots

1 messages ยท Page 291 of 1

buoyant quail
#

Button callback is a new interaction

obsidian fable
#

other buttons works with followup tho

buoyant quail
#

Show one

obsidian fable
#
    class CanvasButton(ui.Button):
        async def callback(self, interaction: discord.Interaction):
            await interaction.response.send_message(f"[Spotify Canvas]({canvasurl})")
#

wait no not this one

#
    class PlayButton(ui.Button):
        async def callback(self, interaction: discord.Interaction):
            await interaction.response.defer(thinking=True)
            songlink = f"https://open.spotify.com/track/{spotify_id}"
            file_bytes = download(songlink)
            custom_path = "./files/ogg/"
            if not os.path.exists(custom_path):
                os.makedirs(custom_path)
            with open(f"{custom_path}{name}.ogg", "wb") as f:
                f.write(file_bytes)
            with open(f"{custom_path}{name}.ogg", "rb") as f:
                await interaction.followup.send(f"`{name} by {artists}` | Quality: `VERY_HIGH`", file=File(f, filename=f"{name}.ogg"))
            shutil.rmtree(custom_path)```
buoyant quail
#

Defer is a response too

obsidian fable
#

oh

#

thank you

#

it works now

final iron
#

Just another thing, if songs_query is a function or anything, it's blocking

obsidian fable
final iron
#

Just a matter of time

obsidian fable
#

do i make it coroutine

final iron
#

You'd want it to be async, yes

obsidian fable
#


def songs_query(query):
    base_url = "https://api.music.apple.com/v1/catalog/us/search"
    params = {'term': query, 'types': 'songs'}
    response = requests.get(base_url, headers=HEADERS, params=params)
    data = response.json()
    return data['results']['songs']['data'][0]
#

this is the current function but idk how to do async

#

do i just add async or

final iron
#

Yes

obsidian fable
#

and await right

final iron
#

You'd also need to use aiohttp or a similar library as requests is blocking

#

!d aiohttp

unkempt canyonBOT
#

Common data structures used by aiohttp internally...

obsidian fable
#

ooh i have to switch to aiohttp too

final iron
#

!d aiohttp.ClientSession.request

unkempt canyonBOT
#
coroutine async-with request(method, url, *, params=None, data=None, json=None, cookies=None, headers=None, skip_auto_headers=None, auth=None, allow_redirects=True, ...)```
Performs an asynchronous HTTP request. Returns a response object.
obsidian fable
#

is that the reason why I am getting those heartbeat errors while executing something

final iron
#

lmao

#

most likely

obsidian fable
#

๐Ÿ˜ญ thank you for the heads up

zealous lance
#

does anyone know why it wont send the embed? (get erroro on last line)

@bot.hybrid_command()
async def purge(ctx, messages: int):
    if messages > 100:
        return await ctx.send("You cannot delete more than 100 messages.")
    else:
        await ctx.channel.purge(limit=messages)
        embed = discord.Embed(title="**Messages removed!**", color=0x2a7412)
        embed.add_field(name="** **", value=f"{ctx.author.mention} successfully purged `{messages}` messages!", inline=False)
        await ctx.send(embed=embed)
slate swan
zealous lance
#

it has all perms

slate swan
#

You maybe missing permissions to run that command

zealous lance
#

it just cant send the embed for some reason

zealous lance
slate swan
zealous lance
#

tf

slate swan
zealous lance
#

Hybrid command raised an error: Command 'purge' raised an exception: NotFound: 404 Not Found (error code: 10062): Unknown interaction

slate swan
#

just try @bot.command

zealous lance
slate swan
zealous lance
slate swan
#

do you have a slash command handler?

zealous lance
#

ye

slate swan
#

hm, idk

zealous lance
#

but everything works fine

slate swan
#

I need to figure out how to use the cog thing, so I can seperate my command files

#

I have all my commands in 1 file lnao

#

lmao*

zealous lance
#

it says: ERROR discord.ext.commands.bot Ignoring exception in command purge

zealous lance
final iron
zealous lance
wicked ether
#

can anyone tell my a python bot tutorial

proud wolf
#

Could someone explain to me how to create a bot in discord.py with cogs and slash commands?

slate swan
#

@quartz rune

quartz rune
#
import discord
from discord.ext import commands

# create a new instance of a bot with a command prefix.
bot = commands.Bot(command_prefix='!')

@bot.event
async def on_ready():
    print(f'Logged in as {bot.user.name} ({bot.user.id})')

# Replace 'YOUR_BOT_TOKEN' with your actual bot token.
bot.run('dddddddddd')
```py
#

ignore the ddddddd

quartz rune
buoyant quail
#

sure

quartz rune
#

im trying to get my bot up and running

#

like just bare minimum but it just doesnt

buoyant quail
#

!intents

unkempt canyonBOT
#
Using intents in discord.py

Intents are a feature of Discord that tells the gateway exactly which events to send your bot. Various features of discord.py rely on having particular intents enabled, further detailed in its documentation. Since discord.py v2.0.0, it has become mandatory for developers to explicitly define the values of these intents in their code.

There are standard and privileged intents. To use privileged intents like Presences, Server Members, and Message Content, you have to first enable them in the Discord Developer Portal. In there, go to the Bot page of your application, scroll down to the Privileged Gateway Intents section, and enable the privileged intents that you need. Standard intents can be used without any changes in the developer portal.

Afterwards in your code, you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:

from discord import Intents
from discord.ext import commands

# Enable all standard intents and message content
# (prefix commands generally require message content)
intents = Intents.default()
intents.message_content = True

bot = commands.Bot(command_prefix="!", intents=intents)

For more info about using intents, see discord.py's related guide, and for general information about them, see the Discord developer documentation on intents.

quartz rune
#

i do not understand why its giving me erros

buoyant quail
#

You are copying from some old guides

quartz rune
#

could i get help setting it up

#

in a vc or anything

buoyant quail
buoyant quail
quartz rune
#

File "C:\Users\thisa\AppData\Roaming\Python\Python311\site-packages\discord\client.py", line 849, in runner
await self.start(token, reconnect=reconnect)
File "C:\Users\thisa\AppData\Roaming\Python\Python311\site-packages\discord\client.py", line 778, in start
await self.connect(reconnect=reconnect)
File "C:\Users\thisa\AppData\Roaming\Python\Python311\site-packages\discord\client.py", line 704, in connect
raise PrivilegedIntentsRequired(exc.shard_id) from None
discord.errors.PrivilegedIntentsRequired: Shard ID None is requesting privileged intents that have not been explicitly enabled in the developer portal. It is recommended to go to https://discord.com/developers/applications/ and explicitly enable the privileged intents within your application's page. If this is not possible, then consider disabling the privileged intents instead.
PS C:\Users\thisa\OneDrive\Desktop\l>

Discord Developer Portal

Integrate your service with Discord โ€” whether it's a bot or a game or whatever your wildest imagination can come up with.

buoyant quail
#

Just do what it says ยฏ_(ใƒ„)_/ยฏ

#

It is recommended to go to https://discord.com/developers/applications/ and explicitly enable the privileged intents within your application's page. If this is not possible, then consider disabling the privileged intents instead.

quartz rune
#

im on there

#

i enabled it

#

nothing

buoyant quail
#

show screenshot

quartz rune
#

i think i did it

final iron
buoyant quail
#

I guess "I did it" means that everything is running fine

final iron
quartz rune
#

i mean i wanna

#

vc with someone because like i still need help smh

quartz rune
final iron
quartz rune
#

i just cant add my bot to my server

#

cause i went to the oauth thing like i see in videos and its asking for a uri

final iron
#

Only select Bot

quartz rune
#

still nothin

slate swan
#

Disable "Require code grant" in your bot's settings

finite sage
finite sage
#

why it says this? All intent are correct and the token is correct too

tranquil pasture
#

Is it possible to create interaction and text command with a single function

buoyant quail
#

Check hybrid_commands

buoyant quail
finite sage
#

I don't know why it say that, it worked perfectly back then.

buoyant quail
#

Show the code ig

#

And did you try to generate a new token?

finite sage
#

if bot:
headers = {
"Authorization":
f"Bot {token}"
}
else:
headers = {
"Authorization":
token
}

rex = commands.Bot(
command_prefix=prefix,
intents=discord.Intents.all(),
help_command=None
)

finite sage
buoyant quail
#

That's surely not the place where you get that output

#

!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 Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.

finite sage
buoyant quail
#

But you are doing it after some condition or something i guess

finite sage
#
if __name__ == "__main__":
    clear()
    #print("\033[38;5;92m" + license)
    #sleep(3)
    clear()
    print(f"\033[38;5;89m[\033[38;5;92m{ftime}\033[38;5;89m] \033[0mLoading client.")
    try:
      rex.run(
        token, 
        bot=bot
      )
    except Exception:
      print(f"\033[38;5;89m[\033[38;5;92m{ftime}\033[38;5;89m] \033[0mSpecified a wrong token or a bot token without all intents.")```
finite sage
#

yes

buoyant quail
#

Remove the try-except and show the actual error

slate swan
#

traceback.print_exc()

finite sage
#

that looks bad

slate swan
#

add that under except Exception

#

and import traceback lib

finite sage
#

i do already

#

it is very slow replit

#

I know

#

"bot is not recognized"

#

i just remove that "bot=bot"

lethal drift
#

I keep getting this error when turning case_insensitive to true

    return super().__contains__(k.casefold())
TypeError: unbound method str.casefold() needs an argument

but when it's false, it works just fine

slate swan
#

full traceback?

lethal drift
#
File "C:\Users\Jade\PycharmProjects\CharmCords\CharmCord\Classes\Commands.py", line 16, in command
    async def go(ctx, *args, Code=Code):
  File "C:\Users\Jade\PycharmProjects\CharmCord\venv\lib\site-packages\discord\ext\commands\core.py", line 1521, in decorator
    self.add_command(result)
  File "C:\Users\Jade\PycharmProjects\CharmCord\venv\lib\site-packages\discord\ext\commands\bot.py", line 246, in add_command
    super().add_command(command)
  File "C:\Users\Jade\PycharmProjects\CharmCord\venv\lib\site-packages\discord\ext\commands\core.py", line 1360, in add_command
    if alias in self.all_commands:
  File "C:\Users\Jade\PycharmProjects\CharmCord\venv\lib\site-packages\discord\ext\commands\core.py", line 257, in __contains__
    return super().__contains__(k.casefold())
TypeError: unbound method str.casefold() needs an argument
slate swan
#

what is function go

lethal drift
zealous lance
slate swan
finite sage
#

no argument

lethal drift
slate swan
#

whats Name and whats Aliases

finite sage
#

this is error return super().contains(k.casefold())

lethal drift
slate swan
#

so what are the values of those

unkempt canyonBOT
#

@naive briar :x: Your 3.11 eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "/home/main.py", line 1, in <module>
003 |     str.casefold()
004 | TypeError: unbound method str.casefold() needs an argument
lethal drift
naive briar
#

That's not how you define variables in Python

finite sage
#

k is not define

lethal drift
lethal drift
naive briar
#

If it's discord.py, I doubt if it will make this kind of mistake

slate swan
#

it comes from discord.py so it must have been provided to it somehow from outside

finite sage
#

return super().contains(str(k).casefold())

surreal grove
#

Hello, I know a little development but not the python language. lately I wanted to set up my own music bot that fetches music on youtube via !play link or title of the video by asking chatgpt to code it for me (not working). I wanted to know if anyone has published a code that works? Thanks in advance !

unkempt canyonBOT
#
Our youtube-dl, or equivalents, policy

Per Python Discord's Rule 5, we are unable to assist with questions related to youtube-dl, pytube, or other YouTube video downloaders, as their usage violates YouTube's Terms of Service.

For reference, this usage is covered by the following clauses in YouTube's TOS, as of 2021-03-17:

The following restrictions apply to your use of the Service. You are not allowed to:

1. access, reproduce, download, distribute, transmit, broadcast, display, sell, license, alter, modify or otherwise use any part of the Service or any Content except: (a) as specifically permitted by the Service;  (b) with prior written permission from YouTube and, if applicable, the respective rights holders; or (c) as permitted by applicable law;

3. access the Service using any automated means (such as robots, botnets or scrapers) except: (a) in the case of public search engines, in accordance with YouTubeโ€™s robots.txt file; (b) with YouTubeโ€™s prior written permission; or (c) as permitted by applicable law;

9. use the Service to view or listen to Content other than for personal, non-commercial use (for example, you may not publicly screen videos or stream music from the Service)
surreal grove
#

It s just for my Friend server

#

How sorry okay

slate swan
slate swan
buoyant quail
zealous lance
#

Tf

#

๐Ÿ’€

lethal drift
#

It worked many times before

#

So I'm a bit confused now

slate swan
#

hard to tell without seeing the core of it

#

at least CharmClient class

lethal drift
#

All it does is provide it to d.py

slate swan
#

lots of repeating code btw

lethal drift
#

Yea, Ik, I was refactoring before I ran into this error ๐Ÿ˜…

slate swan
finite sage
#

i now

#

get new version of discord.ext.commands

lethal drift
finite sage
#

put return super().__contains__(str(k).casefold())

naive briar
naive briar
#

!e

print(str(str))
unkempt canyonBOT
#

@naive briar :white_check_mark: Your 3.11 eval job has completed with return code 0.

<class 'str'>
slate swan
#

not running into that issue with this version

finite sage
#

it is bug with his version

slate swan
#

!paste @lethal drift how about more code

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 Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.

finite sage
#

and casefold() is instance

naive briar
#

It's a method of str

#

!d str.casefold

unkempt canyonBOT
#

str.casefold()```
Return a casefolded copy of the string. Casefolded strings may be used for caseless matching.

Casefolding is similar to lowercasing but more aggressive because it is intended to remove all case distinctions in a string. For example, the German lowercase letter `'รŸ'` is equivalent to `"ss"`. Since it is already lowercase, [`lower()`](https://docs.python.org/3/library/stdtypes.html#str.lower) would do nothing to `'รŸ'`; [`casefold()`](https://docs.python.org/3/library/stdtypes.html#str.casefold) converts it to `"ss"`.

The casefolding algorithm is described in section 3.13 of the Unicode Standard.

New in version 3.3.
slate swan
finite sage
lethal drift
buoyant quail
#

lol

buoyant quail
#

Why you have all imports inside the functions :/

naive briar
#

That looks even more confusing than discord.py ๐Ÿ˜ตโ€๐Ÿ’ซ

lethal drift
#

so I kinda drifted to other things in the project xD

slate swan
#

isnt that caused by the fact you are giving default value to a list

#

which will cause errors further

#

!e ```py
def f(value=[]):
print(value)
value.append(1)

f()
f()

unkempt canyonBOT
#

@slate swan :white_check_mark: Your 3.11 eval job has completed with return code 0.

001 | []
002 | [1]
lethal drift
#

OMG YOU JUST FIXED IT-

#

Because I had str as a default

#

even when nothing was given

slate swan
#

see

#

but you still shouldnt give an argument default value of list

finite sage
#

i say that

finite sage
slate swan
finite sage
#

no

lethal drift
glad cradle
#

btw

#

!pep 8

unkempt canyonBOT
buoyant quail
#

just seeing with your eyes that code looks not good >>

glad cradle
lethal drift
buoyant quail
buoyant quail
lethal drift
#

Cause I was about to ask about this...

#

like wtf-

slate swan
#

this is only intro to new python era

buoyant quail
#

Python 4

slate swan
#

unimport and sync keywords

ember mango
#

There are several types

slate swan
slow hollow
slate swan
# slow hollow

Remember to:
โ€ข Ask your Python question, not if you can ask or if there's an expert who can help.
โ€ข Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
โ€ข Explain what you expect to happen and what actually happens.

#

thats not even a screenshot but yeah photo applies

glad cradle
slow hollow
#

the welcome message is not being sent

glad cradle
slow hollow
#
async def on_member_join(member):
    general_channel: discord.TextChannel = client.get_channel(1143525494973804648)
    await general_channel.send(content=f"Bienvenue sur le serveur {member.display_name} !")```
slate swan
#

this will ensure that you will get channel object

slow hollow
#

where should i put this code?

slate swan
#

when you get TextChannel object from id

slow hollow
#

don't general_channel: disord.TextChannel ?

#

just channel ?

#
async def on_member_join(member):
    general_channel: discord.TextChannel = client.get_channel(1143525494973804648)
    await general_channel.send(content=f"Bienvenue sur le serveur {member.display_name} !")
or await client.fetch_channel(1143525494973804648)```
naive briar
#

No

slow hollow
finite sage
slow hollow
finite sage
#

what

slow hollow
slow hollow
naive briar
finite sage
#

this work

finite sage
#
async def on_member_join(member):
    channel = await client.fetch_channel(1143525494973804648)
    await channel.send(content=f"Bienvenue sur le serveur {member.display_name} !")```
naive briar
glad cradle
#

shame

slow hollow
#

Like that

meager rock
#

!d discord.Client.get_partial_messageable no need to get or fetch the channel just to create a message

unkempt canyonBOT
#

get_partial_messageable(id, *, guild_id=None, type=None)```
Returns a partial messageable with the given channel ID.

This is useful if you have a channel\_id but donโ€™t want to do an API call to send messages to it.

New in version 2.0.
slow hollow
finite sage
#

it does

slate swan
finite sage
#

you are just do it wrong KID i just test it

slow hollow
slate swan
# slow hollow

You have other on_member_join event defined in other place

#

?

slate swan
#

put print statement inside to ensure its invoking

naive briar
#

The event requires the members intent

#

Make sure that it's enabled

slow hollow
#

default_intents = discord.Intents.default()
default_intents.members = True

client = discord.Client(intents=default_intents)

@client.event
async def on_ready():
    print("Le bot est prรชt.")

@client.event
async def on_member_join(member):
    channel = await client.fetch_channel(1143525494973804648)
    await channel.send(content=f"Bienvenue sur le serveur {member.display_name} !")

@client.event
async def on_message(message):
    if message.content.lower() == "ping":
       await message.channel.send("pong", delete_after=5)

    if message.content.startswith('$hello'):
        await message.channel.send('Hello!')

client.run('`token')``` full code
slow hollow
cloud dawn
slate swan
#

Can you do what i ask for

slate swan
slow hollow
turbid condor
#

Guess that's the next part

slow hollow
cloud dawn
slate swan
naive briar
#

The English language ๐Ÿ˜”

finite sage
#

put intent

slate swan
#

Let me rephrase it

Print something inside this event to make sure its called

slate swan
#

print("something")?

cloud dawn
#

Ah yes printing, beware any printer connected will print this on an A4

slow hollow
ember mango
slate swan
cloud dawn
slate swan
slow hollow
#
async def on_member_join(member):
    channel = await client.fetch_channel(1143525494973804648)
    await channel.send(content=f"Bienvenue sur le serveur {member.display_name} !")
Print("something")````
ember mango
#

Now i want create 12

slate swan
#

๐Ÿ˜

turbid condor
#

Small p in Print

cloud dawn
slate swan
#

Is that inside the event?

#

I dont think so

slow hollow
cloud dawn
#

Phone coding confirmed

ember mango
slate swan
cloud dawn
slate swan
#

No only the on_member_join function body is the event

slow hollow
#
Print("something")
async def on_member_join(member):
    channel = await client.fetch_channel(1143525494973804648)
    await channel.send(content=f"Bienvenue sur le serveur {member.display_name} !")
slate swan
#

still no.

slow hollow
#

I'm drunk I'll be back I'm going to eat

cloud dawn
#

Drunk coding is good vibe ngl

ember mango
#
    raise CommandInvokeError(exc) from exc
disnake.ext.commands.errors.CommandInvokeError: Command raised an exception: JSONDecodeError: Expecting value: line 1 column 1 (char 0)```
```@bot.slash_command()
async def predict(ctx):
    games = scraper.get("https://rest-bf.blox.land/games/crash").json()```
#

scraper = cloudscraper.create_scraper()

#

Anyone can help me?

#

@slate swan ๐Ÿ—ฟ

slate swan
#

nope since its breaking rule 5

#

!rule 5

unkempt canyonBOT
#

5. Do not provide or request help on projects that may violate terms of service, or that may be deemed inappropriate, malicious, or illegal.

ember mango
slate swan
slow hollow
#

hey

lofty kindle
#

what is the error

slow hollow
slow hollow
lofty kindle
#

did you check the intents

slow hollow
lofty kindle
#

ok

slow hollow
#

in api

lofty kindle
#

@client.event
async def on_member_join(member):
print(f"Member joined: {member.display_name}")
channel = await client.fetch_channel(1143525494973804648)
await channel.send(content=f"Bienvenue sur le serveur {member.display_name} !")

can you try this

slow hollow
lofty kindle
#

ok

slow hollow
#

:((

#

I don't understand, there are no error messages

lofty kindle
#

im not the best with coding so i just thought that may have worked

#

sorry

slow hollow
#

np ty

vocal laurel
#

Do u still need help?

slow hollow
vocal laurel
#

Hmm Iโ€™m not familiar with the pythons tags system

#

!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 Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.

vocal laurel
#

There

slow hollow
#

infact I have no error messages but the bot does not send anything when a member joins the server

vocal laurel
#

What intents do u have

slow hollow
#

I checked everything in the api

vocal laurel
#

Check what intent it says there

vocal laurel
slow hollow
#
async def on_member_join(member):
    general_channel: discord.TextChannel = client.get_channel(1143525494973804648)
    await general_channel.send(content=f"Bienvenue sur le serveur {member.display_name} !")```
vocal laurel
#

No no

#

Intent

slow hollow
#

default_intents = discord.Intents.default()
default_intents.members = True

client = discord.Client(intents=default_intents)

vocal laurel
#

Oh wait u have member intents

#

Do u have it enabled in the dev portal?

slow hollow
#

i dont have : OAuth2

vocal laurel
#

Itโ€™s ok

#

Ok so put a print statement inside the event

#

So where the code isnโ€™t working out a print statement

slow hollow
#

what should I change?

vocal laurel
#

The very first thing everyone learns

slow hollow
vocal laurel
vocal laurel
#

Where u did print

#

Put it inside event

slow hollow
vocal laurel
slow hollow
vocal laurel
#

I meant put it inside the event

slow hollow
vocal laurel
slow hollow
#

but it's not already inside?

vocal laurel
slow hollow
#

?

slate swan
#

what does this shard thing mean? Is it beneficial

slow hollow
#

I have to copy my code?

vocal laurel
vocal laurel
slate swan
vocal laurel
slate swan
#

Does it make the bot better at all, does it make a difference?

slow hollow
vocal laurel
#

Basically when ur bot gets in a lot of servers (1k+) then the bot needs sharding that way the bot doesnโ€™t slow down

slate swan
#

huh

vocal laurel
finite sage
slow hollow
vocal laurel
vocal laurel
slow hollow
#

the tab key?

vocal laurel
slow hollow
#

like that ?

vocal laurel
#

Yea

slow hollow
#

and ?

vocal laurel
#

Does it print anything when a member joins?

slow hollow
#

no

#

no message

#

@vocal laurel

vocal laurel
#

No print?

slow hollow
#

no

vocal laurel
slow hollow
vocal laurel
#

Well idk then donโ€™t think I can help

slow hollow
vocal laurel
#

!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 Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.

vocal laurel
#

Ok paste ur code there and I will see if I can see the error

vocal laurel
#

Does ur on message work?

slow hollow
naive briar
#

Is there even someone joining to trigger the event

vocal laurel
#

Did not work

slow hollow
vocal laurel
slow hollow
#

would it be a question of right in the server or connection? (he is admin)

#

?

slow hollow
#

Itโ€™s impossible

#

?

tall temple
#

i'm actually using pycord and i get the following error (appearing in the ss)

here is all the script imports :

from discord.ext import commands
import discord
from discord import default_permissions
from colorama import Fore, Back, Style, init
import json
import os
import pathlib```
buoyant quail
#

Reinstall it i guess

tall temple
sick birch
#

pycord has a tendency to shuffle around import locations from discordpy

#

I don't use pycord so I can't tell for sure but they may have just moved commands somewhere else

buoyant quail
#

From their docs it looks they didn't

sick birch
#

hmm

#

@tall temple can you show us all your files?

tall temple
#

i don't think that it can be benefic

sick birch
#

humour me

tall temple
#

hm ?

visual island
#

database is the correct choice

buoyant quail
#

what's the difference between dictionary and json format in python? pithink

visual island
#

sure

sick birch
#

Sure if you're just using a local SQLite db

#

I usually use postgres though

crude sparrow
#
  File "C:\Users\Administrator\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\lightbulb\app.py", line 1162, in invoke_application_command
    await context.invoke()
  File "C:\Users\Administrator\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\lightbulb\context\base.py", line 334, in invoke
    await self.command.invoke(self)
  File "C:\Users\Administrator\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\lightbulb\commands\base.py", line 798, in invoke
    await self(context, **kwargs)
  File "C:\Users\Administrator\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\lightbulb\commands\base.py", line 712, in __call__
    return await self.callback(context, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "c:\Users\Administrator\Desktop\teddy\ext\fun.py", line 92, in translate_text
    translated_text = data["data"]["translations"][0]["translatedText"]
                      ~~~~^^^^^^^^
KeyError: 'data'

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

Traceback (most recent call last):
  File "C:\Users\Administrator\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\lightbulb\app.py", line 1203, in handle_interaction_create_for_application_commands
    await self.invoke_application_command(context)
  File "C:\Users\Administrator\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\lightbulb\app.py", line 1180, in invoke_application_command
    raise new_exc
lightbulb.errors.CommandInvocationError: An error occurred during command 'translate' invocation```
velvet tinsel
#

how would you get all fields of a slash command in discord.py? So far I've got

for i in bot.tree.walk_commands():
  command = i if i.name == command_name else False

if command:
  if isinstance(command, commands.slash_command):
    description = command.description

And I'm kinda stumped.

crude sparrow
#

I know the problem is with the JSON but don't know how to fix that

velvet tinsel
#

might wanna double check your json file

crude sparrow
crude sparrow
velvet tinsel
#

checks the docs then

crude sparrow
#

that's docs page

velvet tinsel
#

[][data] probably?

visual island
thin raft
#

@misty pier

#

Open it again, I was typing

misty pier
#

Okay.

crude sparrow
meager rock
#

saves you from writing extra code

final iron
#

uh

slate swan
#

unfortunately we cant help with that due to rule 5

obsidian fable
#

alr

#

deleted

zealous lance
#

hi im trying to get a free game notifier but my code doesnt seem to work can anyone help me?

session = requests.Session()
session.headers.update({'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'})

@tasks.loop(seconds=5)
async def free_epic():
    channel_id = 1144298794641526874
    channel = bot.get_channel(channel_id)
    
    epic_url = 'https://www.epicgames.com/store/en-US/free-games' 
    try:
        epic_response = session.get(epic_url)
        epic_response.raise_for_status()
        epic_soup = BeautifulSoup(epic_response.text, 'html.parser')

        epic_free = []

        for game in epic_soup.find_all('div', class_='css-w6ymp8'):
            title = game.find('span', class_='css-1162pv2').text.strip()
            epic_free.append(title)

        if epic_free:
            embed = discord.Embed(title="Free Games Alert!", description="Here are the latest free games:", color=0x00ff00)
            epic_list = "\n".join([f"โ€ข {game}" for game in epic_free])
            embed.add_field(name="Epic Games", value=epic_list, inline=False)
            expiration_time = datetime.utcnow() + timedelta(days=7)
            embed.set_footer(text=f"Expires on {expiration_time.strftime('%Y-%m-%d %H:%M:%S')} UTC")
            await channel.send(embed=embed)
    
    except requests.RequestException as e:
        print("An error occurred:", e)
#

error: An error occurred: 403 Client Error: Forbidden for url: https://store.epicgames.com/en-US/free-games

final iron
#

Read the error

zealous lance
#

it says forbidden but it shouldnt be

final iron
#

Have you thought that a multi billion dollar company wouldn't want bots spamming it's webpage?

zealous lance
final iron
#

It could be Nasa's computers, a bot is a bot

#

Doesn't matter where it's coming from

zealous lance
#

but can i let it act like a computer? there are many people who have a working one

obsidian fable
#

captcha exists

#

cf exists

final iron
slate swan
#

On a side-note you should use aiohttp to make HTTP requests in an async application

zealous lance
obsidian fable
#

๐Ÿ”ฅ

final iron
#

Okay, then find that one for bots

#

You're not using that now, therefore breaking TOS

obsidian fable
#

find an official api that provides storefront

final iron
#

If you have to impersonate a computer they don't want bots visiting that website

#

You've already tried and you've been blocked, therefore it's disallowed

obsidian fable
#

I think private apis is againest the rules here cant help you with that

#

refer to their official docs

slate swan
zealous lance
final iron
#

What are you looking for

zealous lance
# final iron What are you looking for

for how to get the info so i contacted epic support and they told me there was no problem with it and it should work so now i have to ask discord ๐Ÿ’€

final iron
quick nebula
#

What service do you use to host a discord bot? I can host one on my own computer, but what else do people use?

final iron
slate swan
#

I've been using digital ocean for around 6 months, their pricing is decent imo and i've never really had any issues with their service

sick birch
#

DO k8s is nice

quick brook
#

also DO bc i have free credits to spend

final iron
#

I'm just going to use my raspberry pi and see how it goes

dusk dagger
final iron
#

Ethernet so

#

I'll see how it goes for like a day

#

I have no clue how much RAM I bought

#

Hopefully 4GB

dusk dagger
#

vps is the best imo

#

DO, hetzner, vultr are all great

final iron
#

I already have a PI so

#

If it doesn't turn out good or if I need an upgrade I'll prob go with do or hetnzer

#

Only downside for Hetnzer is no Canadian servers

#

But most people using the bot are gonna be in the USA or elsewhere so ๐Ÿคทโ€โ™‚๏ธ

cloud dawn
zealous lance
buoyant quail
#
await bot.tree.sync()
slate swan
#

pycord autosyncs doesnt it ?

cloud dawn
#

Ironic py-cord move

tall temple
#

can someone help me with this import error please ? ...

#
ImportError: cannot import name 'commands' from 'discord.ext' (unknown location)
naive briar
#

What library are you using?

tall temple
#

thanks

#

@slate swan but i'm using pycord ..

slate swan
#

Then there are two cases:

  1. You are using discord.py:
    Then you are ready to go should be working
  2. You are not using discord.py:
    Then you need to run this too:
    pip uninstall discord.py
    pip install -U YOUR_LIB
slate swan
tall temple
#

ok

#

i run the script and reinstall my package ?

slate swan
#

And replace YOUR_LIB with py-cord

tall temple
#

same problem occurs

    from discord.ext import commands
ImportError: cannot import name 'commands' from 'discord.ext' (unknown location)
slate swan
#

can you run this script:
print(__import__("discord").__version__)

cloud dawn
#

py-cord doesn't have ext. You are most likely using discord.py code.

slate swan
#

Doesnt it?

cloud dawn
#

How come that py-cord is getting so popular??

slate swan
#

!pypi py-cord

unkempt canyonBOT
cloud dawn
#

Damn tutorials.

tall temple
cloud dawn
buoyant quail
slate swan
cloud dawn
#

๐Ÿ’€

tall temple
#

i always use that code for pycord but it's not working for packages importing shit and i always forget what should i do

buoyant quail
#

Though it's a second such question here. There was someone with the same problem in pycord yesterday

unkempt canyonBOT
#

discord/ext/commands/bot.py line 390

class Bot(BotBase, discord.Bot):```
slate swan
#

It should give error when ran

tall temple
slate swan
#

how about __title__ instead of __version__

cloud dawn
#

yes

tall temple
slate swan
#

Whatever it is its not pycord

unkempt canyonBOT
#

discord/__init__.py line 11

__title__ = "pycord"```
slate swan
#

Pycord Has such attribute

buoyant quail
#

Pycord has ext.commands too ยฏ_(ใƒ„)_/ยฏ

#

I'd just jump into the import discord (ctrl + click in pycharm, idk about another ide) and look what's there

slate swan
#

Yeah

#

Or just print out dir(discord)

#

Obviously after importing discord

tall temple
#
------------------ ---------
aiohttp            3.8.5
aiosignal          1.3.1
anyio              3.7.1
async-timeout      4.0.3
attrs              23.1.0
certifi            2023.7.22
charset-normalizer 3.2.0
colorama           0.4.6
discord-protos     0.0.2
exceptiongroup     1.1.3
fernet             1.0.1
ffmpeg-python      0.2.0
frozenlist         1.4.0
future             0.18.3
h11                0.14.0
httpcore           0.17.3
httpx              0.24.1
idna               3.4
imageio-ffmpeg     0.4.8
multidict          6.0.4
numpy              1.25.2
pip                23.2.1
protobuf           4.24.1
py-cord            2.4.1
pyaes              1.6.1
pycord             0.1.1
requests           2.31.0
setuptools         57.4.0
sniffio            1.3.0
typing_extensions  4.7.1
urllib3            2.0.4
yarl               1.9.2
meager chasm
tall temple
slate swan
tall temple
slate swan
#

Also uninstall pycord

tall temple
#

ok ok

slate swan
#

py-cord is the correct one

tall temple
#

ik

cloud dawn
slate swan
#

Nah its most likely caused by pycord lib

cloud dawn
#

Work with venv's and only install packages globally what you use when playing around/ running random code.

slate swan
#

!pip pycord

unkempt canyonBOT
slate swan
#

Or maybe no aware

tall temple
#

hmm

cloud dawn
#

~/Downloads (0.957s)
pip list
Package Version
numpy 1.25.2
pip 23.2.1
psutil 5.9.5
setuptools 65.5.0

this all of my packages lol

tall temple
cloud dawn
#

@slate swan have you ever heard of warp?

cloud dawn
slate swan
#

what is it for

cloud dawn
#

It's just a fancy command prompt, but it has some cool features.

slate swan
waxen shore
#

Dm me if you have slah command code

oak falcon
#

Can someone tell me how can I set the new custom status in discord.py?

buoyant quail
#

!d discord.ext.commands.Bot you can pass activity to the bot

unkempt canyonBOT
#

class discord.ext.commands.Bot(command_prefix, *, help_command=<default-help-command>, tree_cls=<class 'discord.app_commands.tree.CommandTree'>, description=None, intents, **options)```
Represents a Discord bot.

This class is a subclass of [`discord.Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client) and as a result anything that you can do with a [`discord.Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client) you can do with this bot.

This class also subclasses [`GroupMixin`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.GroupMixin) to provide the functionality to manage commands.

Unlike [`discord.Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client), this class does not require manually setting a [`CommandTree`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CommandTree) and is automatically set upon instantiating the class.

async with x Asynchronously initialises the bot and automatically cleans up.

New in version 2.0.
buoyant quail
#

!d discord.ext.commands.Bot.change_presence or just this

unkempt canyonBOT
#

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

Changes the clientโ€™s presence.

Example

```py
game = discord.Game("with the API")
await client.change_presence(status=discord.Status.idle, activity=game)
```   Changed in version 2.0: Removed the `afk` keyword-only parameter...
mighty pilot
naive briar
#

That's what the method is for

mighty pilot
#

Yea I see it now

naive briar
#

Or is this what you meant

buoyant quail
#

Is that different?

The following types currently count as user-settable:

  • Activity
  • Game
  • Streaming
  • CustomActivity
#

there is CustomActivity

slate swan
#

!d discord.CustomActivity

unkempt canyonBOT
#

class discord.CustomActivity(name, *, emoji=None, **extra)```
Represents a custom activity from Discord.

x == y Checks if two activities are equal.

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

hash(x) Returns the activityโ€™s hash.

str(x) Returns the custom status text.

New in version 1.3.
slate swan
#

its that one with emoji

oak falcon
#

class discord.CustomActivity(name, *, emoji=None, **extra)

#

this one looks like the one i need

#

pithink does it still work why is the bot reacting with trash

naive briar
#

What still work?

oak falcon
naive briar
#

And the trashcan emoji is for the user to delete the embed

oak falcon
#

i noticed it a few days ago

oak falcon
slate swan
#

yeah we know

#

discord told us

oak falcon
buoyant quail
#

Waiting for hi, i am old emoji

oak falcon
#

๐Ÿ’€ lol

slate swan
#

I'm trying to get users from a database. How can I skip the user's selection if he is leaved the server?

slate swan
buoyant quail
#

That try-except should work fine. Weird that you still get the error
Maybe it's from some other place or the file is not saved

visual island
#

It might be that it's wrapped inside HTTPException

young dagger
#

How can I get the post count for a user?

modest nexus
#

bro wth

young dagger
#

What method?

slate swan
#

how many messages they sent?

slate swan
young dagger
slate swan
#

you cant really do that unless you store this data yourself

buoyant quail
slate swan
unkempt canyonBOT
#

bot/exts/info/information.py line 433

user_activity = await self.bot.api_client.get(f"bot/users/{user.id}/metricity_data")```
slate swan
buoyant quail
#

There are not so much keywords :/

slate swan
#

continue just goes to next iteration in loop

#

!d continue

unkempt canyonBOT
#

7.10. The continue statement


continue_stmt ::=  "continue"
``` [`continue`](https://docs.python.org/3/reference/simple_stmts.html#continue) may only occur syntactically nested in a [`for`](https://docs.python.org/3/reference/compound_stmts.html#for) or [`while`](https://docs.python.org/3/reference/compound_stmts.html#while) loop, but not nested in a function or class definition within that loop. It continues with the next cycle of the nearest enclosing loop.

When [`continue`](https://docs.python.org/3/reference/simple_stmts.html#continue) passes control out of a [`try`](https://docs.python.org/3/reference/compound_stmts.html#try) statement with a [`finally`](https://docs.python.org/3/reference/compound_stmts.html#finally) clause, that `finally` clause is executed before really starting the next loop cycle.
young dagger
young dagger
#

That is strange

#

It's just a number

slate swan
#

i doubt you can loop over each message in each channel and check ids but you will mostlikely be ratelimited so easily

visual island
slate swan
#

bruh, it seems that there is no way to do without deleting
1 3 5 6 ...

buoyant quail
#

Just change the number only if the member is found

#

But if you want to get exactly 10 users, then yeah, that can become very inefficient

#

Also use get_member and fetch_member together to decrease api calls count

#

!d discord.Guild.get_member

unkempt canyonBOT
#

get_member(user_id, /)```
Returns a member with the given ID.

Changed in version 2.0: `user_id` parameter is now positional-only.
mighty pilot
#

It sounds like you're assigning the placement in a for loop, why not do a for loop to add them to a list, that way you can sort out whether they're a member or not inside the for loop, and after you're done use the list of members to assign placement

severe sonnet
#

i have the id

#

but i don't know how to ping it

naive briar
#

<@id>

severe sonnet
#

like this then:
f"character of <@{ctx.author.id}>"

severe sonnet
#

or am i wrong?

naive briar
#

!d discord.User.mention or just this if you have a user/member object

unkempt canyonBOT
slate swan
severe sonnet
#

@severe sonnet

#

oh i see, it's not a variable thing but a string thing

#

okay soo i'm still confuse on how webhooks works

#

i got this structure:

{
  "username": "Webhook",
  "avatar_url": "https://i.imgur.com/4M34hi2.png",
  "content": "Text message. Up to 2000 characters.",
  "embeds": [
    {
      "author": {
        "name": "Birdieโ™ซ",
        "url": "https://www.reddit.com/r/cats/",
        "icon_url": "https://i.imgur.com/R66g1Pe.jpg"
      },
      "title": "Title",
      "url": "https://google.com/",
      "description": "Text message. You can use Markdown here. *Italic* **bold** __underline__ ~~strikeout~~ [hyperlink](https://google.com) `code`",
      "color": 15258703,
      "fields": [
        {
          "name": "Text",
          "value": "More text",
          "inline": true
        },
        {
          "name": "Even more text",
          "value": "Yup",
          "inline": true
        },
        {
          "name": "Use `\"inline\": true` parameter, if you want to display fields in the same line.",
          "value": "okay..."
        },
        {
          "name": "Thanks!",
          "value": "You're welcome :wink:"
        }
      ],
      "thumbnail": {
        "url": "https://upload.wikimedia.org/wikipedia/commons/3/38/4-Nature-Wallpapers-2014-1_ukaavUI.jpg"
      },
      "image": {
        "url": "https://upload.wikimedia.org/wikipedia/commons/5/5a/A_picture_from_China_every_day_108.jpg"
      },
      "footer": {
        "text": "Woah! So cool! :smirk:",
        "icon_url": "https://i.imgur.com/fKL31aD.jpg"
      }
    }
  ]
}
#

but i hacve no idea how they works

#

do i just send it as a dictionary or...?

slate swan
#

tias

#

Reading docs can help as well

severe sonnet
#

and i read the docs

#

i'm trying this:

#

but i still have no idea what to do

#

using this dict

harsh orbit
#

Why when I make an account send command with requests the command doesn't work

#

Its not even called

slate swan
harsh orbit
#

It's command with prefix + all intents is enabled+ when I type command it work

#

Only when send it with requests not working

naive briar
harsh orbit
#

Do you know requests library?

naive briar
#

Yes?

harsh orbit
#

I'm using it to send command with an acc

naive briar
#

Send what command

harsh orbit
#

Bro

#

requests.post

#

And the message is a command

buoyant quail
#

Show it

#

The only problem with requests is blocking

#

But it seems it's something else by you

slate swan
#

!blocking

unkempt canyonBOT
#
Asynchronous programming

Imagine that you're coding a Discord bot and every time somebody uses a command, you need to get some information from a database. But there's a catch: the database servers are acting up today and take a whole 10 seconds to respond. If you do not use asynchronous methods, your whole bot will stop running until it gets a response from the database. How do you fix this? Asynchronous programming.

What is asynchronous programming?
An asynchronous program utilises the async and await keywords. An asynchronous program pauses what it's doing and does something else whilst it waits for some third-party service to complete whatever it's supposed to do. Any code within an async context manager or function marked with the await keyword indicates to Python, that whilst this operation is being completed, it can do something else. For example:

import discord

# Bunch of bot code

async def ping(ctx):
    await ctx.send("Pong!")

What does the term "blocking" mean?
A blocking operation is wherever you do something without awaiting it. This tells Python that this step must be completed before it can do anything else. Common examples of blocking operations, as simple as they may seem, include: outputting text, adding two numbers and appending an item onto a list. Most common Python libraries have an asynchronous version available to use in asynchronous contexts.

async libraries
The standard async library - asyncio
Asynchronous web requests - aiohttp
Talking to PostgreSQL asynchronously - asyncpg
MongoDB interactions asynchronously - motor
Check out this list for even more!

slate swan
#

use aiohttp instead

mighty pilot
#

Any ideas why I couldn't display an animated emoji in an embed title? Works when I swap to a regular one.

slate swan
#

shouldnt it be lowercase a?

mighty pilot
#

Oh you know what, it's formatted as a title

slate swan
#

Custom Emoji (Animated) <a:NAME:ID> :b1nzy:

#

its lowercase here dont know if it changes anything for discord

mighty pilot
#

Yea that's probably what it is. When I'm putting together the embed I'm formatting the text as title

obsidian fable
#

can a bot read replies like this?

naive briar
unkempt canyonBOT
#

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

A shortcut method to [`abc.Messageable.send()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Messageable.send) to reply to the [`Message`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Message).

New in version 1.6.

Changed in version 2.0: This function will now raise [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError) or [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError) instead of `InvalidArgument`.
obsidian fable
buoyant quail
#

!d discord.Message.reference

unkempt canyonBOT
#

The message that this message references. This is only applicable to messages of type MessageType.pins_add, crossposted messages created by a followed channel integration, or message replies.

New in version 1.5.

obsidian fable
#

oh thats why its not working

obsidian fable
naive briar
final iron
ember mango
#

Hello anyone know how to hide member Offline on server discord?

#

@buoyant quail Sorry but you know?

buoyant quail
#

What does that mean

#

Hide where

ember mango
buoyant quail
#

Are you sure that's possible?

ember mango
#

yes like here look member offline

#

you cant see on member list

ember mango
buoyant quail
#

Is there an example of small server with that
Because here it's causing so much lags to my discord that i am not sure that all people are loaded

ember mango
#

Like this hide this

buoyant quail
#

Yes i understood. I mean a small server where it surely is so

#

Because here i feel more like discord just is not going to destroy my pc by showing all the 200k people

ember mango
#

I mean how to hide

#

That is, no one should see it

buoyant quail
#

And i mean i still don't believe that it's possible

ember mango
#

anyone can help me?

buoyant quail
#
#

1000 members and you won't see them

ember mango
buoyant quail
#

ye

ember mango
slate swan
#

!d discord.CustomActivity

unkempt canyonBOT
#

class discord.CustomActivity(name, *, emoji=None, **extra)```
Represents a custom activity from Discord.

x == y Checks if two activities are equal.

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

hash(x) Returns the activityโ€™s hash.

str(x) Returns the custom status text.

New in version 1.3.
slate swan
#

what did you try?

#

are you using raw discord api?

#

thats how its parsed here

harsh orbit
buoyant quail
#

code

buoyant quail
harsh orbit
#
payload = {
         "content" : f"-join {self.server_id.value} {self.count.value}"
       }
        headers = {"authorization" : "the token of the acc"} 
        r = requests.post("https://discord.com/api/v8/channels/1100879507541459034/messages", data=payload, headers=headers)
naive briar
#

Are you self-botting?

slate swan
#

๐Ÿง

harsh orbit
#

No

#

It's a regular bot

slate swan
#

lies

naive briar
#

So what's the token of the acc means

harsh orbit
#

But only there is this part using an acc in it

harsh orbit
naive briar
#

Account of what

harsh orbit
#

Discord maybe?

slate swan
#

isnt that definition of self botting?

naive briar
#

If it's an user account, that's self-botting

harsh orbit
#

So?

slate swan
#

so we wont help you

naive briar
#

!rule 5

unkempt canyonBOT
#

5. Do not provide or request help on projects that may violate terms of service, or that may be deemed inappropriate, malicious, or illegal.

harsh orbit
#

Nvm

velvet compass
#

Self botting is enforced by discord as well

#

We would ban, they would obliterate the account

harsh orbit
#

Why you didn't tell me when I send the first message?

velvet compass
#

I don't read every message in the server ยฏ_(ใƒ„)_/ยฏ

harsh orbit
#

I mean them

slate swan
#

didnt we?

velvet compass
#

Well it seems like they were trying to understand what you were asking about

terse hawk
#

How do i make a Slash command? can someone give me code?

slate swan
terse hawk
#

for me?

slate swan
#

yes!

terse hawk
#

can i dm?

slate swan
#

why would you need to dm me

terse hawk
#

i want to show you my code and what to paste in im VERY new

slate swan
#

well thats not how it works

#

we dont give you code to copy paste

terse hawk
#

?

terse hawk
slate swan
#

show them here then

terse hawk
#

from discord.ext import commands is that the same as from discord import app_commands

slate swan
#

no

terse hawk
#

ok thans

slate swan
#

commands is for prefixed commands while app_commands is for slash commands

terse hawk
slate swan
#

you can use prefixed commands with slash

terse hawk
#

but i want the / command that shows up when u type in /

slate swan
#

they do not bother each other

terse hawk
#

bot = commands.Bot(command_prefix="/", intents=discord.Intents.all ()) can i delete that?

slate swan
slate swan
slate swan
terse hawk
#

so do i delete that

slate swan
terse hawk
#

wich line?

slate swan
#

every

terse hawk
#

ok lemme read throught

slate swan
#

the example purpose is to run it yourself check how the commands work, then try to understand why and how it works then change some stuff in the code and see what it changes on discord. Basically thats how you learn

terse hawk
#

so it says something about tree can u explain im very new

#

Thanks Down

#

what is a CommandTree?

slate swan
#

a command tree just stores your commands you dont need to bother how it works, just how to use it

terse hawk
#

ok so i need to use?

slate swan
terse hawk
#

ok

#

@client.tree.command()
async def hello(interaction: discord.Interaction):
"""Says hello!"""
await interaction.response.send_message(f'Hi, {interaction.user.mention}')
that is not working?

slate swan
terse hawk
#

its not reacting

#

if i type Hello or ping the bot he doesnt respond

#

no errors

slate swan
#

its a slash command as you wanted

#

you invoke it by /hello

terse hawk
#

ERROR discord.ext.commands.bot Ignoring exception in command None
discord.ext.commands.errors.CommandNotFound: Command "hello" is not found

slate swan
#

remove the / as prefix

terse hawk
#

ok

obsidian fable
#

can bots see bio?

slate swan
obsidian fable
#

i see

terse hawk
#

It now does not react when I type /hello

quick brook
quick brook
slate swan
#

when you try

terse hawk
slate swan
#

you need to choose this command from list that pops up

#

for example type / here and see what commands you have got to choose from

quick brook
#

Does it show up on the command list

terse hawk
quick brook
#

Just type in / and see if your /hello command appears

#

If it doesn't, then it's time to sync your command tree

slate swan
#

also show your code

terse hawk
#

await self.tree.sync(guild=MY_GUILD) i did not include that because it was an eroor

slate swan
#

removing the line of code cause it has error doesnt solve the error

#

what was the error?

terse hawk
# slate swan also show your code

mport discord
from discord.ext import commands
client=discord.client
bot = commands.Bot(command_prefix="!", intents=discord.Intents.all ())
from discord import app_commands

MY_GUILD = discord.Object(id=1066713764356964372)

class MyClient(discord.Client):
def init(self, *, intents: discord.Intents):
super().init(intents=intents)

    self.tree = app_commands.CommandTree(self)

    async def setup_hook(self):
        
        self.tree.copy_global_to(guild=MY_GUILD)

intents = discord.Intents.default()
client = MyClient(intents=intents)
client.event

async def on_ready():
print(f'Logged in as {client.user} (ID: {client.user.id})')
print('------')

@client.tree.command()
async def hello(interaction: discord.Interaction):
"""Says hello!"""
await interaction.response.send_message(f'Hi, {interaction.user.mention}')

bot.run(TOKEN)

i did the token but discord says its dangerous to chat it

slate swan
#

!code

unkempt canyonBOT
#
Formatting code on discord

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.

For long code samples, you can use our pastebin.

slate swan
#

format it please

quick brook
#

Oh boy auto syncing

slate swan
#

why you create both Bot and Client instance?

terse hawk
#
import discord
from discord.ext import commands
client=discord.client
bot = commands.Bot(command_prefix="!", intents=discord.Intents.all ())
from discord import app_commands

MY_GUILD = discord.Object(id=1066713764356964372)

class MyClient(discord.Client):
    def __init__(self, *, intents: discord.Intents):
        super().__init__(intents=intents)

        self.tree = app_commands.CommandTree(self)

        async def setup_hook(self):
            
            self.tree.copy_global_to(guild=MY_GUILD)
          
        
intents = discord.Intents.default()
client = MyClient(intents=intents)
client.event

async def on_ready():
    print(f'Logged in as {client.user} (ID: {client.user.id})')
    print('------')


@client.tree.command()
async def hello(interaction: discord.Interaction):
    """Says hello!"""
    await interaction.response.send_message(f'Hi, {interaction.user.mention}')






bot.run ("The tokn i should not Share")
slate swan
#

you add your commands to client

#

but you start the bot

terse hawk
#

huh? whats that

quick brook
#

Should be client.run

gloomy fox
#

Im trying to create a Discord bot. Do you have any recomendations of Youtube videos or places where I can reserach more?

slate swan
#

replace all your code with the example

quick brook
unkempt canyonBOT
slow hollow
#

please what is the code for "intents

terse hawk
#

ok

gloomy fox
slate swan
slate swan
#

!d discord.Intents

unkempt canyonBOT
#

class discord.Intents(value=0, **kwargs)```
Wraps up a Discord gateway intent flag.

Similar to [`Permissions`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions), the properties provided are two way. You can set and retrieve individual bits using the properties as if they were regular bools.

To construct an object you can pass keyword arguments denoting the flags to enable or disable.

This is used to disable certain gateway features that are unnecessary to run your bot. To make use of this, it is passed to the `intents` keyword argument of [`Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client).

New in version 1.5.
slate swan
quick brook
#

That guide has some stuff missing ngl

slow hollow
#

TypeError: BotBase.__init__() missing 1 required keyword-only argument: 'intents'

slate swan
unkempt canyonBOT
#
Using intents in discord.py

Intents are a feature of Discord that tells the gateway exactly which events to send your bot. Various features of discord.py rely on having particular intents enabled, further detailed in its documentation. Since discord.py v2.0.0, it has become mandatory for developers to explicitly define the values of these intents in their code.

There are standard and privileged intents. To use privileged intents like Presences, Server Members, and Message Content, you have to first enable them in the Discord Developer Portal. In there, go to the Bot page of your application, scroll down to the Privileged Gateway Intents section, and enable the privileged intents that you need. Standard intents can be used without any changes in the developer portal.

Afterwards in your code, you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:

from discord import Intents
from discord.ext import commands

# Enable all standard intents and message content
# (prefix commands generally require message content)
intents = Intents.default()
intents.message_content = True

bot = commands.Bot(command_prefix="!", intents=intents)

For more info about using intents, see discord.py's related guide, and for general information about them, see the Discord developer documentation on intents.

quick brook
slow hollow
terse hawk
# slate swan yes, to see how it works

Exception has occurred: NameError
name 'Optional' is not defined
File "C:\Users\Phil\Desktop\discordbot.py", line 70, in <module>
async def joined(interaction: discord.Interaction, member: Optional[discord.Member] = None):
^^^^^^^^
NameError: name 'Optional' is not defined

unkempt canyonBOT
#

examples/app_commands/basic.py line 1

from typing import Optional```
terse hawk
slow hollow
#
Traceback (most recent call last):
  File "C:\Users\david\PycharmProjects\pythonProject\bot discord\venv\Lib\site-packages\discord\ext\commands\core.py", line 235, in wrapped
    ret = await coro(*args, **kwargs)
          ^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\david\PycharmProjects\pythonProject\bot discord\main bot discord.py", line 18, in delete
    messages = await ctx.channel.history(limit=number_of_message + 1).flatten()
                     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AttributeError: 'async_generator' object has no attribute 'flatten'

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

Traceback (most recent call last):
  File "C:\Users\david\PycharmProjects\pythonProject\bot discord\venv\Lib\site-packages\discord\ext\commands\bot.py", line 1350, in invoke
    await ctx.command.invoke(ctx)
  File "C:\Users\david\PycharmProjects\pythonProject\bot discord\venv\Lib\site-packages\discord\ext\commands\core.py", line 1029, in invoke
    await injected(*ctx.args, **ctx.kwargs)  # type: ignore
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\david\PycharmProjects\pythonProject\bot discord\venv\Lib\site-packages\discord\ext\commands\core.py", line 244, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'async_generator' object has no attribute 'flatten'```
slate swan
slate swan
terse hawk
#

403 Forbidden (error code: 50001): Missing Access
File "C:\Users\Phil\Desktop\discordbot.py", line 28, in setup_hook
await self.tree.sync(guild=MY_GUILD)
File "C:\Users\Phil\Desktop\discordbot.py", line 116, in <module>
client.run('TOKEN')
discord.errors.Forbidden: 403 Forbidden (error code: 50001): Missing Access

slate swan
slow hollow
slate swan
slow hollow
#

i test and you tell me if it's good

terse hawk
#

403 Forbidden (error code: 50001): Missing Access
File "C:\Users\Phil\Desktop\discordbot.py", line 28, in setup_hook
await self.tree.sync(guild=MY_GUILD)
File "C:\Users\Phil\Desktop\discordbot.py", line 116, in <module>
client.run('TOKEN')
discord.errors.Forbidden: 403 Forbidden (error code: 50001): Missing Access

terse hawk
slate swan
#

!traceback

unkempt canyonBOT
#
Traceback

Please provide the full traceback for your exception in order to help us identify your issue.
While the last line of the error message tells us what kind of error you got,
the full traceback will tell us which line, and other critical information to solve your problem.
Please avoid screenshots so we can copy and paste parts of the message.

A full traceback could look like:

Traceback (most recent call last):
  File "my_file.py", line 5, in <module>
    add_three("6")
  File "my_file.py", line 2, in add_three
    a = num + 3
        ~~~~^~~
TypeError: can only concatenate str (not "int") to str

If the traceback is long, use our pastebin.

terse hawk
#

In this basic example, we just synchronize the app commands to one guild.

# Instead of specifying a guild to every command, we copy over our global commands instead.
# By doing so, we don't have to wait up to an hour until they are shown to the end-user.
async def setup_hook(self):
    # This copies the global commands over to your guild.
    self.tree.copy_global_to(guild=MY_GUILD)
    await self.tree.sync(guild=MY_GUILD)

xception has occurred: Forbidden
403 Forbidden (error code: 50001): Missing Access
File "C:\Users\Phil\Desktop\discordbot.py", line 28, in setup_hook
await self.tree.sync(guild=MY_GUILD)
File "C:\Users\Phil\Desktop\discordbot.py", line 116, in <module>
client.run('TOKEN')
discord.errors.Forbidden: 403 Forbidden (error code: 50001): Missing Access

gloomy fox
#

@slate swan There are no options here?

terse hawk
gloomy fox
#

At the bottom

slate swan
gloomy fox
#

No url

slate swan
#

cause you selected some scopes that require redirect url

terse hawk
#

at the top u need to select

slate swan
#

which you prolly dont want

gloomy fox
#

ok

slate swan
#

select only bot and application.commands

gloomy fox
harsh orbit
#

So if the self bot is illegal
Can I make another bot send a message in the same project?

surreal grove
#

Hi ! Im new in dev discord bot with python and my bot not respond to any command. No error in console ..

slate swan
slow hollow
#

messages = [user async for user in ctx.channel.history(limit=number_of_message + 1)]

terse hawk
slow hollow
slate swan
gloomy fox
slate swan
gloomy fox
#

Thanks

slow hollow
terse hawk
slate swan
surreal grove
#

bot do nothing

slate swan
slate swan
slate swan
terse hawk
slate swan
slate swan
#

..

surreal grove
slow hollow
slate swan
terse hawk
#

n-2023.14.0\pythonFiles\lib\python\debugpy\adapter/../..\debugpy\launcher' '60554' '--' 'C:\Users\Phil\Desktop\discordbot.py'
2023-08-25 21:33:44 INFO discord.client logging in using static token
PS C:\Users\Phil\Desktop>

slate swan
terse hawk
#

im in terminal

slate swan
#

i want the traceback you provided earlier just not full

slow hollow
#

the varibale : each message ?

slate swan
#

why you still have .flatten

gloomy fox
#

@slate swan Its not allowing me to save?

terse hawk
# slate swan i want the traceback you provided earlier just not full

Thats all there is standing
Exception has occurred: Forbidden
403 Forbidden (error code: 50001): Missing Access
File "C:\Users\Phil\Desktop\discordbot.py", line 28, in setup_hook
await self.tree.sync(guild=MY_GUILD)
File "C:\Users\Phil\Desktop\discordbot.py", line 116, in <module>
client.run('TOKEN')
discord.errors.Forbidden: 403 Forbidden (error code: 50001): Missing Access

slate swan
gloomy fox
#

should i just chane it to none?

slate swan
slow hollow
terse hawk
slate swan
slow hollow
slate swan
slate swan
#

dont run it in debug mode unless you know how to use it

slow hollow
terse hawk
#

i just pressed f5

#

My friend told me

slate swan
slate swan
#

ther is run button

terse hawk
slate swan